aegisone 1.0.35 → 1.0.37

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 (152) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/scripts/predist.mjs +1 -1
  5. package/src/iface/paths.js +3 -0
  6. package/src/iface/pty.js +3 -0
  7. package/src/iface/update.js +3 -0
  8. package/src/iface/window.js +3 -0
  9. package/src/protocol.js +3 -0
  10. package/src/selfhost.js +3 -0
  11. package/vendor/cli/package.json +1 -1
  12. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  13. package/vendor/cli/vendor/desktop/main.js +67 -1
  14. package/vendor/cli/vendor/one/src/selfhost.js +3 -0
  15. package/vendor/desktop/lib/local/integrity.js +1 -1
  16. package/vendor/desktop/main.js +67 -1
  17. package/vendor/desktop/package.json +1 -1
  18. package/vendor/desktop/vendor/faces/cli/LICENSE +661 -0
  19. package/vendor/desktop/vendor/faces/cli/README.md +784 -0
  20. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +20 -0
  21. package/vendor/desktop/vendor/faces/cli/package.json +44 -0
  22. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +4 -0
  23. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +4 -0
  24. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +4 -0
  25. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +4 -0
  26. package/vendor/desktop/vendor/faces/cli/scripts/seal-gate.mjs +3 -0
  27. package/vendor/desktop/vendor/faces/cli/src/agents.js +3 -0
  28. package/vendor/desktop/vendor/faces/cli/src/app.js +3 -0
  29. package/vendor/desktop/vendor/faces/cli/src/art.js +3 -0
  30. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +3 -0
  31. package/vendor/desktop/vendor/faces/cli/src/caps.js +3 -0
  32. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +3 -0
  33. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +3 -0
  34. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +3 -0
  35. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +3 -0
  36. package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -0
  37. package/vendor/desktop/vendor/faces/cli/src/config.js +3 -0
  38. package/vendor/desktop/vendor/faces/cli/src/connect.js +3 -0
  39. package/vendor/desktop/vendor/faces/cli/src/credentials.js +3 -0
  40. package/vendor/desktop/vendor/faces/cli/src/deps.js +3 -0
  41. package/vendor/desktop/vendor/faces/cli/src/devrun.js +3 -0
  42. package/vendor/desktop/vendor/faces/cli/src/diff.js +3 -0
  43. package/vendor/desktop/vendor/faces/cli/src/diffview.js +3 -0
  44. package/vendor/desktop/vendor/faces/cli/src/engine.js +3 -0
  45. package/vendor/desktop/vendor/faces/cli/src/entitlement.js +3 -0
  46. package/vendor/desktop/vendor/faces/cli/src/events.js +3 -0
  47. package/vendor/desktop/vendor/faces/cli/src/export.js +3 -0
  48. package/vendor/desktop/vendor/faces/cli/src/filepreview.js +3 -0
  49. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +3 -0
  50. package/vendor/desktop/vendor/faces/cli/src/format.js +3 -0
  51. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +3 -0
  52. package/vendor/desktop/vendor/faces/cli/src/gate.js +3 -0
  53. package/vendor/desktop/vendor/faces/cli/src/history.js +3 -0
  54. package/vendor/desktop/vendor/faces/cli/src/init.js +3 -0
  55. package/vendor/desktop/vendor/faces/cli/src/input.js +3 -0
  56. package/vendor/desktop/vendor/faces/cli/src/keys.js +3 -0
  57. package/vendor/desktop/vendor/faces/cli/src/limits.js +3 -0
  58. package/vendor/desktop/vendor/faces/cli/src/markdown.js +3 -0
  59. package/vendor/desktop/vendor/faces/cli/src/mcp.js +3 -0
  60. package/vendor/desktop/vendor/faces/cli/src/models.js +3 -0
  61. package/vendor/desktop/vendor/faces/cli/src/naming.js +3 -0
  62. package/vendor/desktop/vendor/faces/cli/src/overlays.js +3 -0
  63. package/vendor/desktop/vendor/faces/cli/src/panels.js +3 -0
  64. package/vendor/desktop/vendor/faces/cli/src/permissions.js +3 -0
  65. package/vendor/desktop/vendor/faces/cli/src/ping.js +3 -0
  66. package/vendor/desktop/vendor/faces/cli/src/presence.js +3 -0
  67. package/vendor/desktop/vendor/faces/cli/src/provenance.js +58 -0
  68. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +36 -0
  69. package/vendor/desktop/vendor/faces/cli/src/render.js +3 -0
  70. package/vendor/desktop/vendor/faces/cli/src/screen.js +3 -0
  71. package/vendor/desktop/vendor/faces/cli/src/screens.js +3 -0
  72. package/vendor/desktop/vendor/faces/cli/src/secret.js +3 -0
  73. package/vendor/desktop/vendor/faces/cli/src/securefs.js +3 -0
  74. package/vendor/desktop/vendor/faces/cli/src/settings.js +3 -0
  75. package/vendor/desktop/vendor/faces/cli/src/shared.js +3 -0
  76. package/vendor/desktop/vendor/faces/cli/src/sharedpaths.js +3 -0
  77. package/vendor/desktop/vendor/faces/cli/src/signup.js +3 -0
  78. package/vendor/desktop/vendor/faces/cli/src/summarize.js +3 -0
  79. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +3 -0
  80. package/vendor/desktop/vendor/faces/cli/src/system.js +3 -0
  81. package/vendor/desktop/vendor/faces/cli/src/theme.js +3 -0
  82. package/vendor/desktop/vendor/faces/cli/src/title.js +3 -0
  83. package/vendor/desktop/vendor/faces/cli/src/todos.js +3 -0
  84. package/vendor/desktop/vendor/faces/cli/src/tokens.js +3 -0
  85. package/vendor/desktop/vendor/faces/cli/src/topup.js +3 -0
  86. package/vendor/desktop/vendor/faces/cli/src/update.js +3 -0
  87. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +4 -0
  88. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +3 -0
  89. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +3 -0
  90. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +3 -0
  91. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +3 -0
  92. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +3 -0
  93. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +3 -0
  94. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +3 -0
  95. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +3 -0
  96. package/vendor/desktop/vendor/faces/cli/vendor/client/device-fingerprint.js +3 -0
  97. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +3 -0
  98. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-upload.js +3 -0
  99. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +3 -0
  100. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +3 -0
  101. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +3 -0
  102. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +3 -0
  103. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +3 -0
  104. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +3 -0
  105. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +3 -0
  106. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +3 -0
  107. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +3 -0
  108. package/vendor/desktop/vendor/faces/cli/vendor/client/presence-constants.js +3 -0
  109. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +3 -0
  110. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +105 -0
  111. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +3 -0
  112. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +3 -0
  113. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +3 -0
  114. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +3 -0
  115. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +3 -0
  116. package/vendor/desktop/vendor/faces/cli/vendor/covenant/README.md +21 -0
  117. package/vendor/desktop/vendor/faces/cli/vendor/covenant/aegis.seal +177 -0
  118. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/aegis-seal.mjs +241 -0
  119. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/agents.js +3 -0
  120. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +3 -0
  121. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +3 -0
  122. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +3 -0
  123. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +3 -0
  124. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/covenant.js +567 -0
  125. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +3 -0
  126. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +3 -0
  127. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
  128. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/git-scope.js +3 -0
  129. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +3 -0
  130. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +3 -0
  131. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +3 -0
  132. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +3 -0
  133. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +3 -0
  134. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +3 -0
  135. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +3 -0
  136. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +3 -0
  137. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +3 -0
  138. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +3 -0
  139. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +3 -0
  140. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -0
  141. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +3 -0
  142. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -0
  143. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +2 -0
  144. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -0
  145. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -0
  146. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +4 -0
  147. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +3 -0
  148. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +3 -0
  149. package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +3 -0
  150. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +3 -0
  151. package/vendor/desktop/vendor/faces/cli/vendor/tools/agent-gate.mjs +1203 -0
  152. package/vendor/desktop/vendor/selfhost.js +3 -0
@@ -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 FREE_MAX_WORKERS=1,PAID_PLANS=Object.freeze(["pro","unlimited"]),TIER_NAMES=Object.freeze({pro:"Pro",unlimited:"Unlimited"});function tierName(e){return TIER_NAMES[normalizePlan(e)]||null}const LEGACY_PLAN_ALIASES=Object.freeze({cloud:"pro",memory:"pro",s:"pro",heavy:"pro",team:"pro",starter:"free"}),PRO_VALUE="Pro puts the drain in the cloud, so the job keeps running after you close the laptop",FREE_HONESTY="Everything on your machine is free, permanently. The cloud drain is what you pay for.",BYOK_FEE_NOTE="Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider's own bill.";function ratePerMillion(e){return`$${(1e3*Number(e)).toFixed(2)}/M`}function byokFeeLine(e){const n=e&&"object"==typeof e?e:null;if(!n)return"";const r=Number(n.in_usd_per_1k),a=Number(n.out_usd_per_1k);if(!Number.isFinite(r)||!Number.isFinite(a))return"";if(!0===n.disabled)return"Bring your own key is relayed free on this deployment right now.";const o=`Bring your own key: relayed through AEGIS, handled at ${ratePerMillion(r)} in / ${ratePerMillion(a)} out, on top of your provider's bill — no fee at all on Unlimited, and no fee at all during the free 1-month Unlimited trial`;let l="";if(!0===n.require_account)l="and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed";else{const e=Number(n.anonymous_daily_calls);Number.isFinite(e)&&e>0&&(l=`with ${e} relayed turns/24h before an AEGIS account is required`)}return l?`${o} — ${l}.`:`${o}.`}const CAMPAIGN="queue_cap",UPGRADE_URL="https://aegiscloud.org/go/upgrade?s=desktop&c=queue_cap",BALANCE_CAMPAIGN="topup_bank",BALANCE_URL="https://aegiscloud.org/go/topup?s=desktop&c=topup_bank",SIGNUP_SOURCES=Object.freeze(["desktop","cli","mcp"]),DEFAULT_HOST="desktop";function goUrl(e,n,r){const a=String(null==r?"":r).trim().toLowerCase(),o=SIGNUP_SOURCES.includes(a)?a:DEFAULT_HOST;return`https://aegiscloud.org/go/${String(e).trim().toLowerCase()}?s=${o}&c=${n}`}function promptUrlFor(e){return{upgrade:goUrl("upgrade",CAMPAIGN,e),balance:goUrl("topup",BALANCE_CAMPAIGN,e)}}const DEFAULT_TTL_MS=6e4;function normalizePlan(e){const n=String(null==e?"":e).trim().toLowerCase();return n?PAID_PLANS.includes(n)?n:LEGACY_PLAN_ALIASES[n]||"free":"free"}const ASK_EXAMPLE="Do X autonomously";function isPaidPlan(e){return"free"!==normalizePlan(e)}function fanoutRefusal(){return`Fan-out needs Pro: ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: Pro, or any Token Bank balance. Free keeps the local drain on your own key — one worker per task, while this window is open.`}function balanceRefusal(){return`Your AEGIS balance is empty — ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: top up the Token Bank, or upgrade to Pro. Local drains stay free: one worker per task, on your own key, while this window is open.`}function balanceOf(e){if(!e||"object"!=typeof e)return{balanceKnown:!1,balanceMicros:null};let n=null;return null!=e.balance_micros?n=Number(e.balance_micros):null!=e.balance_eur&&(n=1e6*Number(e.balance_eur)),null!=n&&Number.isFinite(n)?{balanceKnown:!0,balanceMicros:Math.trunc(n)}:{balanceKnown:!1,balanceMicros:null}}function classifyProbe(e,n){if(n){const e=balanceOf(n&&n.data),r=n.status,a=n&&n.data||{},o=String(a.error||a.code||""),l=String(n&&n.message||"");return 400===r||401===r||/api_key required|invalid api key|unauthor/i.test(`${o} ${l}`)?{source:"no-key",plan:"free",degraded:!1,...e}:{source:"unreachable",plan:"free",degraded:!0,...e}}const r=e&&"object"==typeof e?e:{},a=balanceOf(r);if(!1===r.valid)return{source:"no-key",plan:"free",degraded:!1,...a};const o=null!=r.plan_effective&&String(r.plan_effective).trim()?r.plan_effective:r.plan,l=String(null==o?"":o).trim();return l?{source:"server-plan",plan:normalizePlan(l),degraded:!1,...a}:{source:"no-plan-field",plan:"free",degraded:!0,...a}}function createEntitlement({probe:e,now:n=Date.now,ttlMs:r=6e4,host:a=DEFAULT_HOST}={}){const o=promptUrlFor(a);let l=Object.freeze({pro:!1,entitled:!1,balanceKnown:!1,balanceMicros:null,balanceZero:!1,wall:"plan",plan:"free",tier:null,tierName:null,planRaw:null,maxWorkers:1,source:"unresolved",degraded:!0,checkedAt:null,campaign:CAMPAIGN,host:SIGNUP_SOURCES.includes(String(a).toLowerCase())?String(a).toLowerCase():DEFAULT_HOST,upgradeUrl:o.upgrade,refusal:null}),t=null;function i({source:e,plan:r,degraded:a,planRaw:l,balanceKnown:t=!1,balanceMicros:i=null}){const u=normalizePlan(r),c="free"!==u,s=t&&Number.isFinite(i)&&i>0,d=c||s,f=t&&!s,p=d?null:f?"balance":"plan";return Object.freeze({pro:c,entitled:d,balanceKnown:Boolean(t),balanceMicros:t?i:null,balanceZero:f,wall:p,plan:c?u:"free",tier:c?u:null,tierName:c&&TIER_NAMES[u]||null,planRaw:null==l?null:String(l),maxWorkers:d?null:1,source:e,degraded:Boolean(a),checkedAt:n(),campaign:"balance"===p?BALANCE_CAMPAIGN:CAMPAIGN,upgradeUrl:"balance"===p?o.balance:o.upgrade,refusal:d?null:"balance"===p?balanceRefusal():fanoutRefusal()})}return{refresh:async function({force:a=!1}={}){if(null!=l.checkedAt&&n()-l.checkedAt<r&&!a)return l;if(t)return t;t=(async()=>{if("function"!=typeof e)return l=i({source:"no-probe",plan:"free",degraded:!0}),l;try{const n=await e(),r=classifyProbe(n,null);l=i({...r,planRaw:n&&n.plan})}catch(e){const n=classifyProbe(null,e);l=i(n)}return l})();try{return await t}finally{t=null}},current:function(){return l},gateFanout:function({workers:e,fanout:n}={}){const r=Number.isInteger(e)?e:null;return!0===n||null!=r&&r>1?l.entitled?{ok:!0,workers:r,fanout:!0}:{ok:!1,code:"balance"===l.wall?"fanout_requires_balance":"fanout_requires_pro",reason:l.refusal||fanoutRefusal(),campaign:l.campaign,upgradeUrl:l.upgradeUrl,wall:l.wall,pro:!1,entitled:!1,maxWorkers:1,entitlement:l}:{ok:!0,workers:r,fanout:Boolean(n)}}}}module.exports={createEntitlement:createEntitlement,normalizePlan:normalizePlan,isPaidPlan:isPaidPlan,tierName:tierName,TIER_NAMES:TIER_NAMES,classifyProbe:classifyProbe,fanoutRefusal:fanoutRefusal,balanceRefusal:balanceRefusal,ASK_EXAMPLE:ASK_EXAMPLE,balanceOf:balanceOf,FREE_MAX_WORKERS:1,PAID_PLANS:PAID_PLANS,LEGACY_PLAN_ALIASES:LEGACY_PLAN_ALIASES,CAMPAIGN:CAMPAIGN,UPGRADE_URL:UPGRADE_URL,BALANCE_CAMPAIGN:BALANCE_CAMPAIGN,BALANCE_URL:BALANCE_URL,PRO_VALUE:PRO_VALUE,FREE_HONESTY:FREE_HONESTY,BYOK_FEE_NOTE:BYOK_FEE_NOTE,byokFeeLine:byokFeeLine,DEFAULT_TTL_MS:6e4,SIGNUP_SOURCES:SIGNUP_SOURCES,DEFAULT_HOST:DEFAULT_HOST,goUrl:goUrl,promptUrlFor:promptUrlFor};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ const READ_VERBS=new Set(["cat","head","tail","less","more","wc","grep","egrep","fgrep","rg","sed","awk","cut","sort","uniq","tr","diff","comm","join","nl","ls","dir","tree","stat","file","du","df","pwd","which","type","basename","dirname","realpath","readlink","find","locate","echo","printf","date","uname","whoami","id","env","printenv","true","test"]),GIT_READ_SUBCOMMANDS=new Set(["diff","status","log","show","blame","grep","ls-files","rev-parse","describe","cat-file","shortlog","whatchanged","reflog","show-ref","ls-tree","diff-tree","diff-files","diff-index","merge-base"]),WRITE_PATTERNS=[/(^|[\s;&|(])rm(\s|$)/,/(^|[\s;&|(])rmdir(\s|$)/,/(^|[\s;&|(])mv(\s|$)/,/(^|[\s;&|(])cp(\s|$)/,/(^|[\s;&|(])ln(\s|$)/,/(^|[\s;&|(])mkdir(\s|$)/,/(^|[\s;&|(])touch(\s|$)/,/(^|[\s;&|(])chmod(\s|$)/,/(^|[\s;&|(])chown(\s|$)/,/(^|[\s;&|(])truncate(\s|$)/,/(^|[\s;&|(])dd(\s|$)/,/(^|[\s;&|(])tee(\s|$)/,/(^|[\s;&|(])install(\s|$)/,/(^|[\s;&|(])patch(\s|$)/,/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,/(^|[\s;&|(])sort\b[^|;]*--output=/,/(^|[\s;&|(])dd\b[^|;]*\bof=/,/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,/(?<![0-9&])>>?(?![&-])/,/\bexport\s+[A-Za-z_]/,/(^|[\s;&|(])source(\s|$)/],STATEFUL_PATTERNS=[/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,/(^|[\s;&|(])pushd(\s|$)/,/(^|[\s;&|(])popd(\s|$)/,/(^|[\s;&|(])nohup(\s|$)/,/(^|[\s;&|(])disown(\s|$)/,/<<-?\s*['"]?[A-Za-z_]/,/(^|[\s;&|(])\&$/,/(^|[\s;&|(])exec(\s|$)/,/(^|[\s;&|(])history(\s|$)/,/(^|[\s;&|(])jobs(\s|$)/];function effectiveVerb(e){let s=0;for(let t=0;t<4&&s<e.length;t++){const t=e[s];if("time"!==t&&"command"!==t)if("env"!==t)if("timeout"!==t){if("nice"!==t)break;s+=1,s<e.length&&"-n"===e[s]?s+=2:s<e.length&&/^-?\d+$/.test(e[s])&&(s+=1)}else{for(s+=1;s<e.length&&e[s].startsWith("-");)s+=1;s<e.length&&/^[0-9]+(\.[0-9]+)?[smhd]?$/.test(e[s])&&(s+=1)}else for(s+=1;s<e.length&&(e[s].startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[s]));)s+=1;else s+=1}return s<e.length?{verb:e[s],rest:e.slice(s)}:null}function segments(e){const s=[],t=/(\|\||&&|[;|])/g;let n,r=0;for(;n=t.exec(e);)s.push({sep:null,text:e.slice(r,n.index)}),s.push({sep:n[1]}),r=n.index+n[1].length;return s.push({sep:null,text:e.slice(r)}),s}function leadingCd(e){const s=/^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(e);if(!s)return{cwd:null,rest:e};const t=(s[1]||s[2]||s[3]||"").trim();return t.startsWith("/")?{cwd:t,rest:s[4]}:{cwd:null,rest:e}}function planExec(e,s={}){const t=s.baseCwd||null,n="string"==typeof e?e:"",r=e=>({oneShot:!1,cwd:null,reason:e});if(!n.trim())return r("empty command");if(n.includes("\n"))return r("multi-line command");for(const e of STATEFUL_PATTERNS)if(e.test(n))return r("depends on session state");for(const e of WRITE_PATTERNS)if(e.test(n))return r("contains a write");const{cwd:i,rest:o}=leadingCd(n),l=o.trim();if(!l)return r("nothing after the cd");const a=segments(l).filter((e=>!e.sep));if(!a.length)return r("no command");for(const e of a){const s=e.text.trim().replace(/^\(+\s*/,"").split(/\s+/).filter(Boolean);if(!s.length)continue;const t=effectiveVerb(s);if(!t)return r("empty command after wrappers");const n=t.verb;if("git"!==n){if(!READ_VERBS.has(n))return r(`${n} is not a known read verb`);if(("sed"===n||"awk"===n)&&/(^|\s)-[a-zA-Z]*w\s/.test(t.rest.join(" ")))return r(`${n} writes a file`)}else{const e=t.rest[1];if(!e||e.startsWith("-"))continue;if(!GIT_READ_SUBCOMMANDS.has(e))return r(`git ${e} is not read-only`)}}return{oneShot:!0,cwd:i||t,reason:"read-only"}}module.exports={planExec:planExec,READ_VERBS:READ_VERBS,GIT_READ_SUBCOMMANDS:GIT_READ_SUBCOMMANDS,WRITE_PATTERNS:WRITE_PATTERNS,STATEFUL_PATTERNS:STATEFUL_PATTERNS};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),crypto=require("node:crypto"),{spawnSync:spawnSync}=require("node:child_process");function gitRoot(t){const e=spawnSync("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8"});return 0===e.status?e.stdout.trim():null}function contentHash(t,e){try{const n=fs.lstatSync(path.join(t,e));return n.isFile()?crypto.createHash("sha1").update(fs.readFileSync(path.join(t,e))).digest("hex"):n.isDirectory()?"nonfile:dir":"nonfile:other"}catch{return"absent"}}function gitStatusSnapshot(t){const e=gitRoot(t);if(!e)return null;const n=spawnSync("git",["status","--porcelain=v1","-z","--untracked-files=all","--no-renames"],{cwd:e,encoding:"utf8",maxBuffer:67108864});if(0!==n.status)return null;const o=new Map;for(const t of n.stdout.split("\0")){if(t.length<4)continue;const n=t.slice(3);o.set(n,contentHash(e,n))}return o}function foreignChanges(t,e){if(!e)return[];const n=gitStatusSnapshot(t);if(!n)return[];const o=[];for(const[t,s]of n)e.has(t)&&e.get(t)===s&&o.push(t);return o}function toRepoRelative(t,e,n){const o=String(null==n?"":n).trim();if(!o)return"";const s=path.isAbsolute(o)?o:path.resolve(e||t,o),r=path.relative(t,s);return!r||r.startsWith("..")||path.isAbsolute(r)?"":r.split(path.sep).join("/")}function writtenSet(t,e,n){const o=new Set;for(const s of n||[]){const n=toRepoRelative(t,e,s);n&&o.add(n)}return o}function attributedChanges(t,{before:e,written:n}={}){const o=gitRoot(t);if(!o)return null;const s=gitStatusSnapshot(t);if(!s)return null;const r=writtenSet(o,t,n),i=[],a=[];for(const[t,n]of s)e&&e.has(t)&&e.get(t)===n||!r.has(t)?a.push(t):i.push(t);return{root:o,ours:i,left:a,written:r}}function scopedCommit(t,{message:e,before:n,written:o}={}){if(!gitRoot(t))return{skipped:!0,reason:"not a git repo"};if(!n)return{ok:!1,error:"no pre-task snapshot; refusing to sweep the working tree"};const s=attributedChanges(t,{before:n,written:o});if(!s)return{skipped:!0,reason:"not a git repo"};const{root:r,ours:i,left:a}=s;if(!i.length)return{ok:!0,skipped:!0,foreign:a,identicalForeign:foreignChanges(t,n),reason:a.length?`no changes of our own (left ${a.length} change(s) this task did not write)`:"no changes"};const c=spawnSync("git",["add","-A","--pathspec-from-file=-","--pathspec-file-nul"],{cwd:r,encoding:"utf8",input:i.join("\0")});if(0!==c.status)return{ok:!1,error:c.stderr||"git add failed"};const u=spawnSync("git",["commit","-m",e],{cwd:r,encoding:"utf8"});return 0!==u.status?/nothing to commit|no changes added/i.test(u.stdout+u.stderr)?{ok:!0,skipped:!0,foreign:a,reason:"no changes"}:{ok:!1,error:u.stderr||u.stdout}:{ok:!0,message:e,foreign:a,paths:i,staged:i.length}}module.exports={gitRoot:gitRoot,contentHash:contentHash,gitStatusSnapshot:gitStatusSnapshot,foreignChanges:foreignChanges,toRepoRelative:toRepoRelative,writtenSet:writtenSet,attributedChanges:attributedChanges,scopedCommit:scopedCommit};
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,"..",".."),SALT="aegis-desktop-interlock-v1",PAD="aegis-desktop-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let n=0;n<e.length;n++){const r=parseInt(e[n],16),s=parseInt(PAD_HEX[n%PAD_HEX.length],16);if(Number.isNaN(r)||Number.isNaN(s))return null;t+=(r^s).toString(16)}return t}const UNITS=Object.freeze([{id:"d1",rel:Buffer.from("bWFpbi5qcw==","base64").toString("utf8")},{id:"d2",rel:Buffer.from("bGliL2xvY2FsL3NoZWxsLmpz","base64").toString("utf8")},{id:"d3",rel:Buffer.from("bGliL2xvY2FsL3Rvb2xzLmpz","base64").toString("utf8")},{id:"d4",rel:Buffer.from("bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==","base64").toString("utf8")}]),SEALED="48fc29f73f029cb1da82fb44f24bef085525eba53a2c2dc913fefb005e6f3ebf";function check(){const e=[];for(const t of UNITS){const n=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(n))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(n)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),n="string"==typeof SEALED?SEALED.trim():"";return 64!==n.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(n)!==t?{tripped:!0,code:"d3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegis-desktop: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"d2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function sealOf(e){const t=e.map((e=>sha256(readFileSync(e))));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,sealOf:sealOf,mask:unmask};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const{estimateTokens:estimateTokens,trimContext:trimContext}=require("./context.js"),attachmentsModule=require("./attachments.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=SSE_IDLE_TIMEOUT_MS,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,l=e.slice(t[n].body,a),i=dsmlAttrs(t[n].attrs),c=i.name||i.function||i.tool||"",u={},f=[];let _;for(DSML_RE_DRIFT_PARAM.lastIndex=0;_=DSML_RE_DRIFT_PARAM.exec(l);)f.push({at:_.index,attrs:_[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<f.length;e++){const t=e+1<f.length?f[e+1].at:l.length,n=l.slice(f[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(f[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=a,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,a=o[0];if(a.includes(DSML_TAG_MARK)){n+=e.slice(s,r+a.length),s=r+a.length;continue}const l=e.slice(r+a.length),i=TEXT_TOOL_TAG_CLOSE_RE.exec(l);if(!i)break;const c=textCallsIn(l.slice(0,i.index));if(n+=e.slice(s,r),s=r+a.length+i.index+i[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let a;-1!==r&&e.length-r<=DSML_HOLD_MAX?(a=e.slice(0,r),e=e.slice(r)):(a=e,e="");const l=plainToolTagHoldAt(a);return-1!==l&&(e=a.slice(l)+e,a=a.slice(0,l)),n(a)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map((e=>String(e)))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every((e=>t.has(e.name)))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},a=e=>{n+="string"==typeof e?e:"";let a="",l=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(a+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){l=!0;break}a+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const i=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(i){a+=n.slice(0,i.index),n=n.slice(i.index);const e=n.slice(i[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){l=!0;break}const s=n.slice(0,i[0].length+t.index+t[0].length);a+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),f=n.slice(0,c.index);if(-1===u){a+=f,n=n.slice(c.index),l=!0;break}const _=textCallsIn(n.slice(c.index,u));if(a+=f,o(_))for(const e of _)s.push(e);else a+=n.slice(c.index,u);n=n.slice(u)}const i=l?0:trailingHeadFrom(n,Boolean(t));return-1===i?(a+=n,n=""):i>0&&(a+=n.slice(0,i),n=n.slice(i)),n.length>TEXT_TOOL_HOLD_MAX&&(a+=n,n=""),a};return a.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const a=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),a)},a.calls=()=>s.slice(),a}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some((e=>e>255)))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map((e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}}))).filter((e=>e.id))}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=FIRST_BYTE_TIMEOUT_MS,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(UNLOAD_TIMEOUT_MS)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=SSE_IDLE_TIMEOUT_MS}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",a=null,l=()=>{};const i=new Promise(((e,t)=>{l=t})),c=()=>{a&&clearTimeout(a),a=setTimeout((()=>{l(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))}),n)};c();try{for(;;){const e=await Promise.race([s.read(),i]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{a&&clearTimeout(a);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then((()=>{}),(()=>{}))),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch((()=>{})))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map((([e,t])=>unload(e,t))))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):DEFAULT_WARM_SECS}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const a=Math.round((r.until-o)/1e3);return a<=0?(residentMemo.delete(residentKey(e,t,n)),0):a}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout((()=>s.abort()),WINDOW_TIMEOUT_MS);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find((e=>sameModel(e&&(e.name||e.model),t))),a=r&&Number(r.context_length);return Number.isFinite(a)&&a>0?a:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const a=baseOf(e);if(!isLocalEndpoint(a))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const l=warmSecsFor({warmSecs:o}),i="string"==typeof n?n:"",c={warmSecs:l,prefixSource:i?"turn-system":"none",prefixChars:i.length};if(l<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,f=residentSecsLeft(a,t,i,{dialer:u});if(f>=Math.min(l,60)){const e=residentEntry(a,t,i,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:f,contextLength:e&&e.contextLength||null,...c}}const _=new AbortController,d=()=>_.abort();s&&(s.aborted?_.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",d,{once:!0}));const m=Number(r),E=Number.isFinite(m)&&m>0?Math.min(m,RESIDENT_TIMEOUT_MS):RESIDENT_TIMEOUT_MS;let T=!1,p=null;const S=setTimeout((()=>{T=!0,_.abort()}),E);S&&"function"==typeof S.unref&&S.unref();try{try{const e=await fetch(`${a}/api/ps`,{method:"GET",signal:_.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find((e=>sameModel(e&&(e.name||e.model),t)));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(p=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(l,60))return residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*e,dialer:u,contextLength:p}),{ok:!0,already:!0,remainingSecs:e,contextLength:p,...c}}}}catch{}if(_.signal.aborted)return{ok:!1,aborted:!0,timeout:T,contextLength:p,...c};const e=i?[{role:"system",content:i},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${a}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:l,stream:!1,messages:e,options:{num_predict:1}}),signal:_.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch((()=>""));try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==p&&(p=await windowOf(a,t,{signal:_.signal})||null),residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*l,dialer:u,contextLength:p}),swapWarmModel(a,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:p,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:T,contextLength:p,...c}}finally{clearTimeout(S),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",d)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o}){const r=Number(s);if(!Number.isFinite(r)||r<=0)return null;const a=(Array.isArray(e)?e:[]).filter((e=>e&&"system"!==e.role)),l=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,i=Number(o),c=Number.isFinite(i)&&i>0?i:Math.round(r/4),u=trimContext({messages:a,system:"string"==typeof t?t:"",budgetTokens:r,reserveTokens:c,fixedTokens:l});return{window:r,reserveTokens:c,toolTokens:l,dropped:u.dropped,messages:u.messages,over:u.estimatedTokens>Math.max(0,r-c),estimatedTokens:u.estimatedTokens}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:a,tools:l,toolChoice:i,signal:c,onDelta:u,firstByteTimeoutMs:f=FIRST_BYTE_TIMEOUT_MS,contextLength:_}={}){const d=baseOf(e),m=remoteRefusal(d);if(m)throw m;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const E=[];s&&E.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&E.push(t)}const T="string"==typeof o||Array.isArray(o)?o:"";if(!(""===T||Array.isArray(T)&&0===T.length)){const e=E[E.length-1],t=attachmentsModule.flattenContent(T),n=e?attachmentsModule.flattenContent(e.content):null;e&&"user"===e.role&&n===t||E.push({role:"user",content:T})}if(!E.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let p=null;if(null!=_){const e=E[0]&&"system"===E[0].role?E[0]:null;if(p=fitToWindowOf({rows:E,system:e&&e.content||s||"",tools:l,contextLength:_,maxTokens:r}),p){const t=p.messages;E.length=0,e&&E.push(e),E.push(...t)}}const S={model:String(t),messages:E,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=a?{temperature:a}:{},...l&&l.length?{tools:l}:{},...i?{tool_choice:i}:{}},g=new AbortController;let h=!1;const L=setTimeout((()=>{h=!0,g.abort()}),f);L&&"function"==typeof L.unref&&L.unref();const M=()=>g.abort();let y;c&&(c.aborted?g.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",M,{once:!0}));try{y=await fetch(`${d}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(S),signal:g.signal})}catch(e){if(h||isHeadersDeadline(e)){const e=h?`sent nothing in ${Math.round(f/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(HEADERS_DEADLINE_MS/1e3)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||g.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(L)}if(!y.ok){let e="";try{e=await y.text()}catch{}const t=new Error(`local: chat/completions ${y.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=y.status,t}let O="",A=null;const D=[],R=new Map,x=makeDeepSeekEnvelopeStripper(),b=makeTextToolCallStripper({toolNames:(Array.isArray(l)?l:[]).map((e=>e&&e.function&&e.function.name||e&&e.name||"")).filter(Boolean)});try{await readSSE(y,(e=>{e&&e.usage&&(A=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=b(x(n.content));e&&(O+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:D.length;let n=R.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},R.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}}),{idleTimeoutMs:SSE_IDLE_TIMEOUT_MS})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:O,usage:A});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",M)}const w=`${b(x.flush())||""}${b.flush()||""}`;w&&(O+=w,"function"==typeof u&&u({text:w}));for(const[e,t]of[...R.entries()].sort(((e,t)=>e[0]-t[0])))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),D.push(t));const k={role:"assistant",content:O};D.length&&(k.tool_calls=D);const N=x.calls(),I=b.calls(),C={id:"local",model:String(t),choices:[{index:0,message:k,finish_reason:D.length?"tool_calls":"stop"}],...A?{usage:A}:{}};return(D.length||N.length||I.length)&&(C.toolCalls=[...D.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...N.map((e=>({id:"",name:e.name,args:e.args||{}}))),...I.map((e=>({id:"",name:e.name,args:e.args||{}})))],(N.length||I.length)&&"tool_calls"!==C.choices[0].finish_reason&&(C.choices[0].finish_reason="tool_calls")),p&&(C.window={contextLength:p.window,dropped:p.dropped,toolTokens:p.toolTokens,estimatedTokens:p.estimatedTokens,reserveTokens:p.reserveTokens,over:p.over}),C}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,(async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})}));return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:DEFAULT_WARM_SECS,RESIDENT_TIMEOUT_MS:RESIDENT_TIMEOUT_MS,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,FIRST_BYTE_TIMEOUT_MS:FIRST_BYTE_TIMEOUT_MS,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:HEADERS_DEADLINE_MS,windowOf:windowOf,stoppedTurn:stoppedTurn};
@@ -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 MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:s,dataDir:r,locale:a,localeName:i,languages:l,cwd:h,vcs:d,shell:u,shellKind:c,roots:m,appVersion:p,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 g=(Array.isArray(l)?l:[]).map((e=>languageLine(e))).filter(Boolean);g.length&&y.push(`recorded language evidence from the user's own saved writing: ${g.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}`),s&&y.push(`desktop directory: ${s} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),r&&y.push(`AEGIS data directory: ${r} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),h&&y.push(`working directory: ${h}`),"git"===d?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"):""===d&&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"),u&&y.push(`exec shell: ${u}${c?` (${c})`:""}`),f&&y.push(`model: ${f}`),p&&y.push(`AEGIS Desktop ${p}`);const w=Array.isArray(m)?m.filter(Boolean):[],v=[];y.length&&v.push(y.join("\n")),w.length&&v.push(`repo roots:\n${w.map((e=>` - ${e}`)).join("\n")}`);const b=commandDialectLine(t,c);return b&&v.push(b),v.length?`# Environment\n${v.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.":""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n=environmentPreamble(e);return n&&t.push(n),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,buildSystemPrompt:buildSystemPrompt};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),STATUSES=Object.freeze(["pending","running","done","error"]);function dataDir(e=process.env){const t=e||{},n=t.AEGISCODE_HOME||t.AEGIS_HOME;return n?path.resolve(n):path.join(os.homedir(),".aegiscode")}function queuePath(e=process.env){return e&&e.AEGIS_QUEUE_FILE||path.join(dataDir(e),"queue.jsonl")}function runsPath(e=process.env){return e&&e.AEGIS_RUNS_FILE||path.join(dataDir(e),"runs.jsonl")}function lockPath(e=process.env){return e&&e.AEGIS_QUEUE_LOCK||path.join(dataDir(e),"queue.lock")}function ensureDir(e){return fs.mkdirSync(e,{recursive:!0}),e}function readQueue(e){let t="";try{t=fs.readFileSync(e,"utf8")}catch{return[]}const n=[];for(const e of t.split("\n")){const t=e.trim();if(t)try{const e=JSON.parse(t);e&&"object"==typeof e&&null!=e.id&&n.push(e)}catch{}}return n}function writeQueue(e,t){ensureDir(path.dirname(e));const n=t.map((e=>JSON.stringify(e))).join("\n")+(t.length?"\n":""),r=`${e}.${process.pid}.tmp`;return fs.writeFileSync(r,n,{mode:384}),fs.renameSync(r,e),t}function loadQueue(e=process.env){return readQueue(queuePath(e))}function saveQueue(e,t){return writeQueue(queuePath(e),t)}function nextId(e){let t=0;for(const n of e){const e=Number(n&&n.id);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function upsert(e,t){const n=Array.isArray(e)?e:[],r=n.findIndex((e=>e&&e.id===t.id));return-1===r?n.push(t):n[r]={...n[r],...t},n}function addTask(e,t={}){const n=String(null==t.task?"":t.task).trim();if(!n)throw new Error("queue: a task needs text");const r=require("./autonomous.js"),s=r.normalizeClass(t.class),u=String(null==t.model?"":t.model).trim(),a=r.modelRefusal(u,s);if(a)throw new Error(`queue: ${a}`);const o=loadQueue(e),i=t.now||Date.now(),c={id:nextId(o),task:n,cwd:t.cwd||process.cwd(),class:s,model:u||null,effort:t.effort||null,workers:Number.isInteger(t.workers)?t.workers:null,singlePass:Boolean(t.singlePass),commit:Boolean(t.commit),maxRounds:Number.isInteger(t.maxRounds)?t.maxRounds:null,source:t.source||"manual",status:"pending",attempts:0,created:i,updated:i};return upsert(o,c),saveQueue(e,o),c}function findTask(e,t){const n=Number(t);return(e||[]).find((e=>Number(e&&e.id)===n))||null}function markRunning(e,t,n={}){const r=findTask(e,t);if(!r)return null;const s=n.now||Date.now();return r.status="running",r.pid=n.pid||process.pid,r.startedAt=s,r.updated=s,r.attempts=(Number(r.attempts)||0)+1,r}function settle(e,t,{status:n,result:r,error:s,now:u=Date.now()}={}){const a=findTask(e,t);return a?(a.status=STATUSES.includes(n)?n:"error",a.updated=u,a.finishedAt=u,delete a.pid,void 0!==r&&(a.result=r),s?a.error=String(s):delete a.error,a):null}function retryTask(e,t,n={}){const r=loadQueue(e),s=findTask(r,t);return s?(s.status="pending",s.updated=n.now||Date.now(),delete s.error,delete s.pid,delete s.roundStops,saveQueue(e,r),s):null}function clearQueue(e,{all:t=!1}={}){const n=loadQueue(e),r=t?[]:n.filter((e=>"pending"===e.status||"running"===e.status)),s=n.length-r.length;return saveQueue(e,r),{removed:s,kept:r.length}}function isAlive(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function recoverStale(e,{isAliveFn:t=isAlive,now:n=Date.now()}={}){const r=[];for(const s of e||[])s&&"running"===s.status&&(s.pid&&t(s.pid)||(s.status="pending",s.updated=n,s.recoveredAt=n,delete s.pid,r.push(s.id)));return r}function pendingCount(e){return(e||[]).filter((e=>e&&"pending"===e.status)).length}function pending(e){return(e||[]).filter((e=>e&&"pending"===e.status))}function lockHolder(e=process.env){try{return JSON.parse(fs.readFileSync(lockPath(e),"utf8"))}catch{return null}}function acquireLock(e=process.env,{pid:t=process.pid,now:n=Date.now(),isAliveFn:r=isAlive}={}){const s=lockPath(e),u=lockHolder(e);return u&&u.pid&&u.pid!==t&&r(u.pid)?{ok:!1,holder:u}:(ensureDir(path.dirname(s)),fs.writeFileSync(s,JSON.stringify({pid:t,host:os.hostname(),startedAt:n}),{mode:384}),{ok:!0,holder:{pid:t,startedAt:n}})}function releaseLock(e=process.env,{pid:t=process.pid}={}){const n=lockHolder(e);if(n&&n.pid&&n.pid!==t)return{ok:!1,holder:n};try{return fs.unlinkSync(lockPath(e)),{ok:!0}}catch{return{ok:!0,already:!0}}}function appendRun(e,t){const n=runsPath(e);return ensureDir(path.dirname(n)),fs.appendFileSync(n,JSON.stringify(t)+"\n",{mode:384}),t}function readRuns(e=process.env,{limit:t=20}={}){let n="";try{n=fs.readFileSync(runsPath(e),"utf8")}catch{return[]}const r=n.split("\n").filter((e=>e.trim())),s=t>0?r.slice(-t):r,u=[];for(const e of s)try{u.push(JSON.parse(e))}catch{}return u}function planPath(e){return path.join(e,"PLAN.md")}function parsePlanStatus(e){const t=new Map,n=new Set,r=new Set;let s=!1;for(const u of String(e||"").split("\n")){if(/^Status:/.test(u)){s=!0;continue}if(s){const e=u.match(/^- \[([ x])\] Phase (\d+)/);if(e){t.set(Number(e[2]),"x"===e[1]);continue}if(""===u.trim()||/^\s+\S/.test(u))continue;s=!1}const e=u.match(/^##\s*Phase\s+(\d+)\b/);if(e){const t=Number(e[1]);r.add(t),/✅/.test(u.slice(e[0].length))&&n.add(t)}}return{statusDone:t,headerDone:n,headerNums:r}}function extractPhaseTitle(e,t){const n=String(e||"").match(new RegExp(`^## Phase ${t}\\b(.*)$`,"m"));return n&&n[1].trim().replace(/^(✅|⚠️)\s*/,"").replace(/\s*(✅|⚠️)$/,"").replace(/^[—-]\s*/,"").trim()||`Phase ${t}`}function healPlanStatus(e,t){const n=[...t.headerDone].filter((e=>!t.statusDone.has(e))).sort(((e,t)=>e-t));if(!n.length)return{text:e,changed:!1,added:[]};const r=String(e||"").split("\n"),s=r.findIndex((e=>/^Status:/.test(e)));if(-1===s)return{text:e,changed:!1,added:[]};let u=-1;for(let e=s+1;e<r.length;e++)if(/^- \[[ x]\] Phase \d+/.test(r[e]))u=e;else if(""!==r[e].trim()&&!/^\s+\S/.test(r[e]))break;if(-1===u)return{text:e,changed:!1,added:[]};const a=n.map((t=>`- [x] Phase ${t} — ${extractPhaseTitle(e,t)}`));return r.splice(u+1,0,...a),{text:r.join("\n"),changed:!0,added:n}}function reconcilePlan(e,{write:t=!1}={}){let n;try{n=fs.readFileSync(planPath(e),"utf8")}catch{return{ok:!1,reason:`no PLAN.md in ${e}`,next:null}}const r=parsePlanStatus(n),s=healPlanStatus(n,r);s.changed&&t&&(fs.writeFileSync(planPath(e),s.text),n=s.text);const u=new Set(r.headerDone);for(const[e,t]of r.statusDone)t&&u.add(e);const a=[...r.headerNums].filter((e=>!u.has(e))).sort(((e,t)=>e-t))[0];return null==a?{ok:!0,text:n,parsed:r,healed:s,next:null,title:null}:{ok:!0,text:n,parsed:r,healed:s,next:a,title:extractPhaseTitle(n,a)}}module.exports={STATUSES:STATUSES,dataDir:dataDir,queuePath:queuePath,runsPath:runsPath,lockPath:lockPath,ensureDir:ensureDir,readQueue:readQueue,writeQueue:writeQueue,loadQueue:loadQueue,saveQueue:saveQueue,nextId:nextId,upsert:upsert,addTask:addTask,findTask:findTask,markRunning:markRunning,settle:settle,retryTask:retryTask,clearQueue:clearQueue,isAlive:isAlive,recoverStale:recoverStale,pendingCount:pendingCount,pending:pending,lockHolder:lockHolder,acquireLock:acquireLock,releaseLock:releaseLock,appendRun:appendRun,readRuns:readRuns,planPath:planPath,parsePlanStatus:parsePlanStatus,extractPhaseTitle:extractPhaseTitle,healPlanStatus:healPlanStatus,reconcilePlan:reconcilePlan};
@@ -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 TTL_MS=18e5,MAX_ENTRIES=64,entries=new Map,historyKeys=new WeakMap;let historyKeySeq=0;function prune(e=Date.now()){for(const[t,n]of entries)e-n.at>TTL_MS&&entries.delete(t);for(;entries.size>MAX_ENTRIES;){const e=entries.keys().next();if(e.done)break;entries.delete(e.value)}return entries.size}function keyFor(e,t){const n=e&&"object"==typeof e?e:{},r=n.sessionKey||n.sessionId||n.chatId||n.threadId||n.conversationId;if("string"==typeof r&&r.trim())return`s:${r.trim()}`;if("string"==typeof n.cwd&&n.cwd.trim())return`cwd:${n.cwd.trim()}`;if(t&&"object"==typeof t){let e=historyKeys.get(t);return e||(historyKeySeq+=1,e=`hist-${historyKeySeq}`,historyKeys.set(t,e)),e}return"default"}function isStatedKey(e){const t=e&&"object"==typeof e?e:{},n=t.sessionKey||t.sessionId||t.chatId||t.threadId||t.conversationId;return!("string"!=typeof n||!n.trim())||"string"==typeof t.cwd&&t.cwd.trim().length>0}function bonus(e){const t=Number.isFinite(e)&&e>0?e:0;return Math.max(4,Math.ceil(t/4))}function peek(e,t=Date.now()){return prune(t),entries.get(e)||null}function take(e,t=Date.now()){prune(t);const n=entries.get(e);return n?(entries.delete(e),n):null}function adopt({now:e=Date.now(),maxAgeMs:t=6e5}={}){prune(e);let n=null,r=null;for(const[s,i]of entries)e-i.at>t||(!r||i.at>r.at)&&(r=i,n=s);return r?(entries.delete(n),{key:n,entry:r}):null}function record(e,{rounds:t,tokens:n,note:r,chain:s,messages:i,added:o}={},a=Date.now()){prune(a);const u=entries.get(e),d={rounds:Number.isFinite(t)?t:0,tokens:Number.isFinite(n)?n:0,note:"string"==typeof r?r:"",at:a,interruptions:(Number.isFinite(s)?s:u&&u.interruptions)||0,messages:Array.isArray(i)?i.slice():[],added:Array.isArray(o)?o.slice():[]};return d.interruptions+=1,entries.delete(e),entries.set(e,d),prune(a),d}function resumePreamble(e){return`[session resume] The previous turn in this conversation was cut off at ${e&&e.rounds?e.rounds:"the previous turn's"} tool rounds${e&&e.tokens?` (${e.tokens.toLocaleString()} tokens)`:""} because it reached the round horizon, so the work it started is unfinished. Continue that work now: do not restart, do not re-do steps that already completed, and do not treat the interruption as a failure to report. Pick up the next unfinished step and finish with a written answer.`}function state(e=Date.now()){return prune(e),{size:entries.size,ttlMs:TTL_MS,maxEntries:MAX_ENTRIES,entries:[...entries].map((([e,t])=>({key:e,...t})))}}function reset(){return entries.clear(),entries.size}module.exports={TTL_MS:TTL_MS,MAX_ENTRIES:MAX_ENTRIES,keyFor:keyFor,isStatedKey:isStatedKey,bonus:bonus,peek:peek,take:take,adopt:adopt,record:record,resumePreamble:resumePreamble,state:state,reset:reset};
@@ -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{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto"),integrity=require("./integrity.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`shell.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const IS_WIN32=platform.IS_WIN32,OUTPUT_CAP=3e4,MAX_TIMEOUT=6e5,DEFAULT_TIMEOUT=12e4,POSIX_SHELL_NAMES=["bash","sh","dash","ksh","zsh"],POSIX_FALLBACK_NAMES=["bash","sh"],POSIX_PROBE="if [ 1 -eq 1 ]; then exit 0; fi",SHELL_PROBE_TIMEOUT=4e3;function shellName(e){return String(e||"").trim().split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/,"")}function isPosixShellName(e){return POSIX_SHELL_NAMES.includes(shellName(e))}function probePosixShell(e,{env:s,timeout:t=SHELL_PROBE_TIMEOUT}={}){try{const n=spawnSync(e,["-c",POSIX_PROBE],{env:s,encoding:"utf8",timeout:t,windowsHide:!0,stdio:"ignore"});return!n.error&&0===n.status}catch{return!1}}function shellSeams(e){const s=e&&"object"==typeof e?e:{};return{platform:"string"==typeof s.platform&&s.platform?s.platform:process.platform,env:s.env&&"object"==typeof s.env?s.env:process.env,exists:"function"==typeof s.exists?s.exists:void 0,probe:"function"==typeof s.probe?s.probe:void 0,injected:"function"==typeof s.probe||"function"==typeof s.exists}}function considerPosixCandidate(e,s,t,n){const i=String(s.cmd||"").trim();if(!i)return t.push({candidate:s.source||"(unset)",ok:!1,reason:"unset"}),null;if(!isPosixShellName(i))return t.push({candidate:i,ok:!1,reason:`${s.source||"candidate"} is not a POSIX shell — ${shellName(i)||i} is a different language (fish/csh/nu), so it was never executed and never sent POSIX syntax`}),null;const o=platform.resolveExecutable(i,{platform:e.platform,env:e.env,exists:e.exists});if(!o)return t.push({candidate:i,ok:!1,reason:/[\\/]/.test(i)?"not present":"not found on PATH"}),null;const r=e.probe?Boolean(e.probe(o,["-c",POSIX_PROBE])):probePosixShell(o,{env:e.env});return n.push(o),r?(t.push({candidate:o,ok:!0,reason:"verified: one `-c` POSIX script exited 0"}),{ok:!0,cmd:o,arg:"-c",kind:"posix-sh",source:s.source,verified:!0}):(t.push({candidate:o,ok:!1,reason:`failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`}),null)}function resolvePosixSessionShell(e){const s=[],t=[],n=String(e.env&&e.env.SHELL||"").trim(),i=[];n?i.push({cmd:n,source:"$SHELL"}):s.push({candidate:"$SHELL",ok:!1,reason:"$SHELL is unset"});for(const e of POSIX_FALLBACK_NAMES)i.push({cmd:e,source:`PATH:${e}`});let o=null;for(const n of i)if(o=considerPosixCandidate(e,n,s,t),o)break;const r=n&&!isPosixShellName(n)?n:null;return o?{...o,unsupported:r,caveat:r?`$SHELL is ${r}, which is not a POSIX shell — the session runs the POSIX dialect through ${o.cmd} instead, and ${r} is never sent brace groups, \`exec 2>&1\` or \`$?\``:null,error:null,executed:t,tried:s}:{ok:!1,cmd:null,arg:null,kind:null,source:"refused",verified:!1,unsupported:r,caveat:null,error:r?`exec: refusing to run — $SHELL is "${r}", which is not a POSIX shell (fish/csh/nushell are a different language), and no sh/bash could be verified on PATH to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.`:`exec: no POSIX shell available — $SHELL is ${n?`"${n}"`:"unset"} and no sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.`,executed:t,tried:s}}const SHELL_CACHE=new Map;function resolveSessionShell(e={}){const s=shellSeams(e);if("win32"===s.platform){const e=platform.shellSpec({platform:"win32",env:s.env}),t=platform.resolveExecutable("powershell",{platform:"win32",env:s.env,exists:s.exists})||"powershell.exe";return{ok:!0,cmd:t,arg:"-",kind:"powershell",source:"powershell.exe",verified:!0,unsupported:null,caveat:null,error:null,oneShot:{cmd:t,arg:"-Command",kind:"powershell",source:"powershell.exe"},executed:[],tried:[{candidate:t,ok:!0,reason:"the Windows default (PowerShell session AND one-shot)"},{candidate:e.cmd,ok:!1,reason:"cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches"}]}}const t=[s.platform,s.env&&s.env.SHELL,s.env&&s.env.PATH].join("\0");if(!s.injected&&SHELL_CACHE.has(t))return SHELL_CACHE.get(t);const n=resolvePosixSessionShell(s);return s.injected||SHELL_CACHE.set(t,n),n}const{cap:spillCap}=require("./spill.js");function cap(e){return spillCap(e,OUTPUT_CAP)}const TAIL_KEEP=65536,BUFFER_CEILING=OUTPUT_CAP+TAIL_KEEP,ELISION="\n… (earlier output elided — command produced more than the buffer ceiling)\n";function appendBounded(e,s){const t=e+s;return t.length<=BUFFER_CEILING?t:t.slice(0,OUTPUT_CAP)+ELISION+t.slice(-TAIL_KEEP)}function oneShotShellSpec(e={}){const s=resolveSessionShell(e);if(!s.ok)return{ok:!1,cmd:null,arg:null,kind:null,error:s.error,spec:s};if("powershell"===s.kind){const t=s.oneShot||platform.shellSpec({platform:"win32",env:shellSeams(e).env});return{ok:!0,cmd:t.cmd,arg:t.arg,kind:t.kind||"powershell",error:null,spec:s}}return{ok:!0,cmd:s.cmd,arg:s.arg,kind:"posix-sh",error:null,spec:s}}function oneShotShell({command:e,timeout:s=12e4,working_directory:t,shellOptions:n}={}){return new Promise((i=>{if(integrity.armed())return void i({content:"exec: unavailable in this build",isError:!0});const o=shellSeams(n),r=resolveSessionShell(n);if(!r||!r.ok)return void i({content:r&&r.error||"exec: no usable shell",isError:!0});const l="powershell"===r.kind?r.oneShot:r,h=spawn(l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let c="",d="";h.stdout.on("data",(e=>{c=appendBounded(c,e.toString())})),h.stderr.on("data",(e=>{d=appendBounded(d,e.toString())})),h.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),h.on("close",(e=>{const s=`${c}${d?`\n${d}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s}={}){this.sentinel=`__AEGIS_SH_${crypto.randomBytes(8).toString("hex")}__`,this.marker=`${this.sentinel}EXIT:`,this.buf="",this.alive=!1,this._pending=null,this.cwd=e||process.cwd(),this.disposed=!1,this._respawns=0,this._degradedNoted=!1,this.shellOptions=s||{},this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(e)}_start(e){if(!this.shell||!this.shell.ok)return void(this.alive=!1);const s=shellSeams(this.shellOptions).env;try{this.child="powershell"===this.shell.kind?spawn(this.shell.cmd,["-NoLogo","-NoProfile","-NonInteractive","-Command","-"],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]}):spawn(this.shell.cmd,[],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]})}catch{return void(this.alive=!1)}this.alive=!0;const t=e=>{this.buf=appendBounded(this.buf,e.toString()),this._pending&&this._pending()};if(this.child.stdout.on("data",t),this.child.stderr.on("data",t),this.child.on("exit",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),this.child.on("error",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),"posix-sh"===this.shell.kind)try{this.child.stdin.write("exec 2>&1\n")}catch{this.alive=!1}}run(e,{timeout:s=12e4,working_directory:t}={}){if(integrity.armed())return Promise.resolve({content:"exec: unavailable in this build",isError:!0});const n=this.shell&&"posix-sh"===this.shell.kind&&this.shell.verified;if(!this.alive||!this.child||this.shell&&"posix-sh"===this.shell.kind&&!n)return!this.alive&&this.shellError?Promise.resolve({content:this.shellError,isError:!0}):!this.alive&&!this.disposed&&this._respawns<1&&(this._respawns+=1,this.buf="",this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(this.cwd),this.alive)?this.run(e,{timeout:s,working_directory:t}):oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>this._noteDegraded(e,this.alive?"no usable session dialect":"the persistent session is not running")));let i=String(e||"");return new Promise((o=>{let r=!1;const l=e=>{r||(r=!0,clearTimeout(h),this._pending=null,o(e))},h=setTimeout((()=>{const e=cap(this.buf.trim());this.dispose(),l({content:`${e}${e?"\n":""}(timed out after ${s}ms)`,isError:!0})}),Math.min(Number(s)||12e4,6e5));let c;if(this._pending=e=>{if(e&&!this.buf.includes(this.marker))return void l({content:cap(this.buf.trim())||"(shell session ended)",isError:!0});const s=this.buf.indexOf(this.marker);if(-1===s)return;const t=this.buf.slice(s+this.marker.length),n=t.indexOf("\n");if(-1===n)return;const i=parseInt(t.slice(0,n),10),o=this.buf.slice(0,s).replace(/\n+$/,"");this.buf=t.slice(n+1),l({content:cap(o||`(exit ${i})`),isError:0!==i})},n)t&&(i=`( cd ${shq(t)} && ${i} )`),c=`{ ${i.trim()?i:":"}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;else{const e=i.trim()?i:"Write-Output $null",s="$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }";c=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,c+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(c)}catch{return this.alive=!1,void oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>l(this._noteDegraded(e,"the session stdin rejected the command"))))}this._pending&&this._pending()}))}_noteDegraded(e,s){const t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this._degradedNoted)return t;this._degradedNoted=!0;const n=`[shell_degraded] ran one-shot via ${this.shell&&this.shell.cmd?this.shell.cmd:"unknown shell"} (${s}); session dialect was ${this.shell&&this.shell.kind?this.shell.kind:"none"} — quoting contracts may differ`;return{...t,content:`${n}\n${t.content||""}`}}dispose(){if(this.disposed=!0,this.alive=!1,this.child){try{this.child.stdin.end()}catch{}try{this.child.kill("SIGKILL")}catch{}this.child=null}}}function shq(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function pshq(e){return`'${String(e).replace(/'/g,"''")}'`}module.exports={ShellSession:ShellSession,oneShotShell:oneShotShell,IS_WIN32:IS_WIN32,resolveSessionShell:resolveSessionShell,oneShotShellSpec:oneShotShellSpec,isPosixShellName:isPosixShellName,POSIX_SHELL_NAMES:POSIX_SHELL_NAMES,POSIX_PROBE:POSIX_PROBE,appendBounded:appendBounded,OUTPUT_CAP:OUTPUT_CAP,BUFFER_CEILING:BUFFER_CEILING,TAIL_KEEP:TAIL_KEEP};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),SPILL_MAX_FILES=40;let spillDir=null,spillCount=0;function spill(t){try{if(spillCount>=SPILL_MAX_FILES)return null;spillDir||(spillDir=fs.mkdtempSync(path.join(os.tmpdir(),"aegiscode-tool-"))),spillCount+=1;const l=path.join(spillDir,`output-${spillCount}.txt`);return fs.writeFileSync(l,String(t),"utf8"),l}catch{return null}}function cap(t,l){const n=String(null==t?"":t);if(n.length<=l)return n;const i=n.slice(0,l),r=spill(n);return r?`${i}\n… (truncated after ${l} of ${n.length} chars — full output: ${r} — grep or readFile that path)`:`${i}\n… (truncated)`}module.exports={spill:spill,cap:cap,SPILL_MAX_FILES:SPILL_MAX_FILES};
@@ -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{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),integrity=require("./integrity.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i}={}){return new Promise((o=>{const n=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void o(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void o(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),_=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",_),d.stderr&&d.stderr.on("data",_);const y=e=>{g||(g=!0,clearTimeout(m),o(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(integrity.armed())return fail("exec: unavailable in this build");if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
@@ -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{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex((t=>"git"===t||t.endsWith("/git")));if(-1===e)return null;let n=e+1;for(;n<t.length&&t[n].startsWith("-");)n+=GIT_FLAGS_WITH_ARG.has(t[n])?2:1;return n>=t.length?null:{sub:t[n],args:t.slice(n+1)}}function namedPaths(t){const e=t.indexOf("--");return-1!==e?t.slice(e+1).filter((t=>!t.startsWith("-"))):t.filter((t=>!t.startsWith("-")))}const isTreeMark=t=>"."===t||"./"===t||"*"===t||"./*"===t,hasForce=t=>t.some((t=>"-f"===t||"--force"===t||/^-[a-zA-Z]*f/.test(t)));function judge(t,e){const n=namedPaths(e),r=0===n.length||n.some(isTreeMark);switch(t){case"checkout":return e.includes("--")||hasForce(e)?{what:"checkout of uncommitted changes",scope:r?"tree":"paths",paths:n}:r&&n.length?{what:"checkout . (tree-wide restore)",scope:"tree",paths:n}:null;case"restore":return{what:"restore (discards uncommitted changes)",scope:r?"tree":"paths",paths:n};case"reset":return e.includes("--hard")?{what:"reset --hard",scope:"tree",paths:[]}:null;case"clean":return hasForce(e)?{what:"clean -f (deletes untracked files)",scope:"tree",paths:[]}:null;case"stash":{const t=e.find((t=>!t.startsWith("-")));return"list"===t||"show"===t?null:{what:`stash ${t||"push"} (uncommitted changes across the tree)`,scope:"tree",paths:[]}}case"worktree":{const t=e.find((t=>!t.startsWith("-")));return"remove"===t||"prune"===t?{what:`worktree ${t}`,scope:"tree",paths:[]}:null}default:return null}}function classifyDestructive(t){for(const e of tokenize(t)){const t=gitInvocation(e);if(!t)continue;const n=judge(t.sub,t.args);if(n)return{destructive:!0,...n}}return{destructive:!1}}function beginTurnGuard(t){const e=gitRoot(t),n=e?gitStatusSnapshot(t):null;return{root:e,cwd:t,before:n,startedAt:Date.now(),written:new Set,active:Boolean(e&&n)}}function toRel(t,e){let n=String(e||"");return n?(t.root&&n.startsWith(t.root)&&(n=n.slice(t.root.length).replace(/^[/\\]/,"")),n.split("\\").join("/")):null}function recordWrite(t,e){if(!t||!t.active)return;const n=toRel(t,e);n&&t.written.add(n)}function foreignSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r,s]of e)t.written.has(r)||t.before.has(r)&&t.before.get(r)===s&&n.push(r);return n.sort()}function concurrentSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r]of e)t.written.has(r)||t.before.has(r)||n.push(r);return n.sort()}function blocksDestructive(t,e){const n=classifyDestructive(e);if(!n.destructive)return{ok:!0};if(!t||!t.active)return{ok:!0};let r=foreignSince(t),s=concurrentSince(t).filter((t=>!r.includes(t))),o=[];if("tree"===n.scope)o=[...r,...s];else{const t=new Set(n.paths.map((t=>t.replace(/^\.\//,"")))),e=e=>e.filter((e=>t.has(e)||t.has("./"+e)));r=e(r),s=e(s),o=[...r,...s]}if(!o.length)return{ok:!0,what:n.what};const i=[];return r.length&&i.push(`${r.length} hold another agent's uncommitted work: `+r.slice(0,8).join(", ")+(r.length>8?` (+${r.length-8} more)`:"")),s.length&&i.push(`${s.length} changed since this turn began and were not written by this session: ${s.slice(0,8).join(", ")}`+(s.length>8?` (+${s.length-8} more)`:"")),{ok:!1,what:n.what,scope:n.scope,foreign:r,unattributed:s,reason:`refusing \`${n.what}\` in ${t.root}: `+("tree"===n.scope?"it is tree-scoped and would discard work it did not create — ":"it targets a path that is not yours to discard — ")+i.join("; ")+". Name only the paths you mean, or take the worktree lock first."}}module.exports={classifyDestructive:classifyDestructive,beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,foreignSince:foreignSince,concurrentSince:concurrentSince,blocksDestructive:blocksDestructive};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");function worktreeLockDir(){if(process.env.AEGISCODE_WORKTREE_LOCK_DIR)return process.env.AEGISCODE_WORKTREE_LOCK_DIR;if(process.env.AEGISCODEX_WORKTREE_LOCK_DIR)return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;const r=process.env.AEGISCODE_HOME||process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(r,"worktree-locks")}const DEFAULT_WORKTREE_WAIT_MS=66e4,NOOP_TOKEN="(no-worktree)";function canonical(r){if(!r)return null;const e=path.resolve(String(r));try{return fs.realpathSync(e)}catch{return e}}function worktreeLockPath(r){if(!r)return null;const e=crypto.createHash("sha1").update(canonical(r)).digest("hex").slice(0,16);return path.join(worktreeLockDir(),e+".lock")}function pidAlive(r){try{return process.kill(r,0),!0}catch{return!1}}function readHolder(r){try{return JSON.parse(fs.readFileSync(worktreeLockPath(r),"utf8"))}catch{return null}}function worktreeLockHolder(r){if(!r)return null;const e=readHolder(r);return e?{pid:e.pid,token:e.token,since:e.since,root:e.root||canonical(r),session:e.session||null}:null}function isWorktreeLocked(r){if(!r)return!1;const e=readHolder(r),o=Number(e&&e.pid);if(!Number.isInteger(o)||o<=0||!pidAlive(o)){try{fs.unlinkSync(worktreeLockPath(r))}catch{}return!1}return!0}function tryAcquire(r,e,o){try{fs.mkdirSync(worktreeLockDir(),{recursive:!0});const t=fs.openSync(worktreeLockPath(r),"wx");return fs.writeFileSync(t,JSON.stringify({pid:process.pid,token:e,since:Date.now(),root:canonical(r),session:o&&o.session||null})),fs.closeSync(t),!0}catch(r){return!r||"EEXIST"!==r.code}}function releaseWorktreeLock(r,e){if(!r||!e||e===NOOP_TOKEN)return;const o=readHolder(r);if(o&&o.token===e)try{fs.unlinkSync(worktreeLockPath(r))}catch{}}async function acquireWorktreeLock(r,{waitMs:e=DEFAULT_WORKTREE_WAIT_MS,pollMs:o=200,signal:t,session:n=null}={}){if(!r)return NOOP_TOKEN;const c=crypto.randomUUID(),i=Date.now()+e;for(;;){if(t&&t.aborted)return null;if(tryAcquire(r,c,{session:n}))return c;if(isWorktreeLocked(r)){if(Date.now()>=i)return null;await new Promise((r=>setTimeout(r,o)))}}}class WorktreeBusyError extends Error{constructor(r,e){super(`working tree ${r} is locked by pid ${e?e.pid:"?"}`),this.name="WorktreeBusyError",this.root=r,this.holder=e||null}}async function withWorktreeLock(r,e,o){const t=await acquireWorktreeLock(r,e);if(!t)throw new WorktreeBusyError(r,worktreeLockHolder(r));try{return await o()}finally{releaseWorktreeLock(r,t)}}module.exports={DEFAULT_WORKTREE_WAIT_MS:DEFAULT_WORKTREE_WAIT_MS,worktreeLockDir:worktreeLockDir,worktreeLockPath:worktreeLockPath,worktreeLockHolder:worktreeLockHolder,isWorktreeLocked:isWorktreeLocked,releaseWorktreeLock:releaseWorktreeLock,acquireWorktreeLock:acquireWorktreeLock,WorktreeBusyError:WorktreeBusyError,withWorktreeLock:withWorktreeLock};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{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 t=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!t)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${t}:(F)`],{stdio:"ignore"})}catch(t){console.error(`[settings] failed to restrict ACL on ${e}: ${t.message}`)}}else try{fs.chmodSync(e,384)}catch(t){console.error(`[settings] failed to chmod ${e} to 0600: ${t.message}`)}}function createSettingsStore({dir:e,safeStorage:t,prefsDir:n,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==n?"":String(n).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 t=a()[e];return void 0===t?null:t}const u=()=>Boolean(t&&"function"==typeof t.isEncryptionAvailable&&t.isEncryptionAvailable());function _(e){return null==e?null:u()?t.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const n=Buffer.from(String(e),"base64");return u()?t.decryptString(n):n.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function A(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const t=`${o}.tmp-${process.pid}`;fs.writeFileSync(t,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(t,o),restrictFile(o)}function f(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 t=d()[e]||{},n=l(t.key);return{provider:e,baseURL:t.baseURL||"",configured:Boolean(n),keyMask:maskKey(n)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},t="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:t}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function g(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const t=d().__confirmMode||{};return void 0===t.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(t.enabled),source:"config"}}function y(){return!0===(d().__telemetry||{}).enabled}function N(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const t=d().__memoryPersist||{};return void 0===t.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(t.enabled),source:"config"}}function p(){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 v(){const e=d().__avatar||{};return{...p(),source:void 0===e.enabled?"default":"config"}}function b(e){const t=Number(e);if(!Number.isFinite(t))return 6e4;const n=Math.round(t);return n<15e3||n>18e5?6e4:n}function T(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:b(e.intervalMs)}}function R(){const e=d().__autoDrain||{};return{...T(),source:void 0===e.enabled?"default":"config"}}function C(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function h(){const e=d().__autoMint||{};return{...C(),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,t){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]:t},{dir:i}),c(e)},get:E,set:function(e,{baseURL:t,key:n}={}){f(e);let r=t;if("local"===e&&t){const e=localTransport.remoteRefusal(t);if(e)throw e;r=localTransport.normalizeBase(t)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==n&&(i.key=n?_(n):null),o[e]=i,A(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){f(e);const t=d();return delete t[e],A(t),{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 t=d();return t.__aegis={...t.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},A(t),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const t=e.aegis||{},n=e.__aegis||{},r={...e};return t.key&&!n.key&&(r.__aegis={...n,key:t.key}),delete r.aegis,A(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:t}={}){const n=d();return n.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof t&&t.trim()?t.trim():"CmdOrCtrl+Shift+Space"},A(n),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const t=d();return t.__vaultBackend={backend:e},A(t),M()},getConfirmMode:function(){return g().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const t=d();return void 0!==t.__confirmMode&&(delete t.__confirmMode,A(t)),g().enabled},confirmModeState:g,getTelemetryOptIn:y,setTelemetryOptIn:function(e){const t=d();return t.__telemetry={enabled:Boolean(e)},A(t),y()},getMemoryPersist:function(){return N().enabled},memoryPersistState:N,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const t=d();return void 0!==t.__memoryPersist&&(delete t.__memoryPersist,A(t)),N()},getAvatar:p,avatarState:v,setAvatar:function(e={}){const t=p(),n=e&&"object"==typeof e?e:{},r={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),showLevel:void 0===n.showLevel?t.showLevel:Boolean(n.showLevel),motion:AVATAR_MOTION_MODES.includes(n.motion)?n.motion:t.motion},o=d();return o.__avatar=r,A(o),v()},getAutoDrain:T,autoDrainState:R,setAutoDrain:function(e={}){const t=T(),n=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),intervalMs:void 0===n.intervalMs?t.intervalMs:b(n.intervalMs)},A(r),R()},getAutoMint:C,autoMintState:h,setAutoMint:function(e={}){const t=C(),n=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),publish:void 0===n.publish?t.publish:Boolean(n.publish)},A(r),h()},clampAutoDrainInterval:b}}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};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
+ "use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL=`${IPC_PREFIX}chatDelta`,MENU_NEW_CHAT_CHANNEL=`${IPC_PREFIX}menuNewChat`,MENU_SEARCH_CHANNEL=`${IPC_PREFIX}menuSearch`,MENU_EXPORT_MARKDOWN_CHANNEL=`${IPC_PREFIX}menuExportMarkdown`,MENU_EXPORT_JSON_CHANNEL=`${IPC_PREFIX}menuExportJson`,MENU_FINGERPRINT_CHANNEL=`${IPC_PREFIX}menuFingerprint`,MENU_GOOGLE_DRIVE_CHANNEL=`${IPC_PREFIX}menuGoogleDrive`,DEEP_LINK_CHANNEL=`${IPC_PREFIX}deepLink`,QUICK_LAUNCHER_PUSH_CHANNEL=`${IPC_PREFIX}quickLauncherPush`,QUEUE_PROGRESS_CHANNEL=`${QUEUE_PREFIX}progress`,QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const n=t||{},r=n.intervalMs||TOPUP_POLL_MS,o=n.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,n.maxTries?{maxTries:n.maxTries}:void 0),a=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},i=async()=>{const e=await s.tick();"credited"===e.state?(a(),(e=>{if("function"!=typeof n.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(a(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(i,r),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:a,tick:i,get baseline(){return s.baseline}}}async function saveMemoryWithQueue(e,t,n,r){const o=avatarStore.normalizeMemoryEntry(n);try{const t=await e.memorySave(o);return r&&o&&"object"==typeof o&&r.awardSave(o,{session:o.session}),t}catch(e){const s=upgradeInfo(e);if(s)return{ok:!1,queued:0,saved:0,upgrade:s,reason:errorText(e)};if(!t||!n)throw e;return memoryQueue.enqueue(t,o),r&&o&&"object"==typeof o&&r.awardQueued(o,{session:o.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,n=quotaFromPayload(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}async function importForeignMemory(e,t,n,r){const o=n||{},s=foreignMemory.scan({sources:o.sources,limit:o.limit||1e3}),a=foreignMemory.describe(s),i=s.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),c={summary:a,totals:s.totals,sources:i};if(!o.confirm||!s.entries.length)return{...c,ok:!0,dryRun:!o.confirm,saved:0,queued:0};let u=0,l=0;const d=[];let p=null;for(const n of foreignMemory.chunk(s.entries,200))try{const t=await e.memorySaveBatch(n);if(u+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}}catch(e){if(p=upgradeInfo(e),!p&&t)for(const e of n)memoryQueue.enqueue(t,e),l+=1,r&&r.awardQueued(e,{session:e&&e.session});d.push(errorText(e));break}return{...c,ok:0===d.length,dryRun:!1,saved:u,queued:l,upgrade:p,reason:d[0]||null}}function resolveIconsDir(e,t,n){return e?path.join(t,"icons"):path.join(n,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function createIpcDispatch(e,t,n,r,o,s,a){let i=null;const c=new Proxy({},{get(e,n){i||(i=createFingerprintService({dir:t,getVaultBackend:a}));const r=i[n];return"function"==typeof r?r.bind(i):r},has:(e,n)=>(i||(i=createFingerprintService({dir:t,getVaultBackend:a})),n in i)}),u=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},l=r||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:u()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult((()=>e.billingCheckout())),tokenBankTopup:async t=>{const n=parseTopupAmount(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await startTopup(e,n.amount);return!0===r.ok&&r.url&&watchTopupCredit(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{}),fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:t=>normalizeMemoryRead(e.memorySearch(t&&t.query,t&&t.limit)),memorySave:n=>saveMemoryWithQueue(e,t,n&&n.entry,s),memoryList:t=>normalizeMemoryRead(e.memoryList(t&&t.limit)),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:t=>e.memoryPull(t&&t.since),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>importForeignMemory(e,t,n,s),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(l(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:errorText(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,n){return n?e.then((e=>(n(t,e),e))):e}function registerIpc(e,t,n,r,o,s,a,i){const c=createIpcDispatch(t,n,r,o,a,void 0,i);for(const[t,n]of Object.entries(c))"chatCompletion"!==t?e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${IPC_PREFIX}${t}`,((e,t)=>{const r={...t||{}};if(!r.stream)return withReplyNotify(n(r),e,s);const o=e&&e.sender;return withReplyNotify(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}}),e,s)}));return c}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function withAutoRoundsSwitch(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function registerConfirmModeIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function registerTelemetryIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,a=o&&"json"===o.format?"json":"markdown",i=s?e.getSession(t,s):null;if(!i)return{ok:!1,reason:"session not found"};const c="json"===a?e.toJson(i):e.toMarkdown(i),u="json"===a?"json":"md",l="json"===a?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${safeExportBasename(i)}.${u}`,filters:l});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,n,r,o){const s=createExportDispatch(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t)));return s}function createQuickLauncherDispatch(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t))):e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t,e)));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}try{const e=require("../one/src/iface/paths.js").plan({platform:process.platform,env:process.env});if(e&&e.ok)return e.state}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||resolveUserDataDir(t),a=createSettingsStore({dir:s,safeStorage:n});return a.migrateLegacyAegisKey(),{engine:createLocalEngine({aegis:e,settings:a}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:a}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",n=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!n||!path.isAbsolute(n))return null;const r=fs.realpathSync(n),o=fs.realpathSync(path.resolve(r,t)),s=path.relative(r,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(i,e,0,PREVIEW_READ_MAX_BYTES,0);let n=e.toString("utf8",0,t);const r=n.lastIndexOf("\n");return r>0&&(n=n.slice(0,r+1)),{text:n,truncated:!0}}finally{fs.closeSync(i)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),a=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,i="image/png"===t?a.toPNG():a.toJPEG(82);return i&&i.length?{buffer:i,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const n=e&&"string"==typeof e.path?e.path.trim():"";if(!n)return{ok:!1,reason:"no path"};if(!path.isAbsolute(n))return{ok:!1,reason:"not an absolute path"};let r,o,s;try{r=fs.realpathSync(n),o=fs.statSync(r)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(r)}catch{return{ok:!1,reason:"unreadable"}}const a=attachmentsModule.sniff(s),i={path:r,name:path.basename(r),size:o.size,mime:a.mime,kind:a.kind};if("image"===a.kind){let{mime:e}=a,n=s,r=!1;if(n.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<n.length&&(n=o.buffer,e=o.mime,r=!0)}const o=attachmentsModule.toDataUrl(n,e);return o?{ok:!0,attachment:{...i,kind:"image",mime:e,size:n.length,dataUrl:o,scaled:r,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===a.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...i,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...i,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===a.kind?{ok:!0,attachment:{...i,kind:"pdf"}}:{ok:!0,attachment:{...i,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=autoRoundsDefault(t),a=!1;const i=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let i;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();i=r(e&&e.enabled)}void 0===i&&t&&"function"==typeof t.getConfirmMode&&(i=r(t.getConfirmMode()))}catch{}return a||void 0===i||(void 0===o?o=i:i!==o&&(a=!0,s=!0)),!(!s||!t||void 0===i)&&!1===i},c={listClasses:async()=>(await e.listClasses()).filter((e=>DESKTOP_CLASSES.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,(n=>{if(n&&n.rounds&&n.rounds.id&&i()){const a=autoContinuePlan({on:!0,used:r.get(s)||0,limit:autoContinueLimit(t)});if(r.set(s,a.used),a.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${a.used}/${a.cap}, then it asks).`})}}}o(n)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&isReservedNamespace(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId)};return Object.defineProperties(c,{autoRoundsOn:{value:i,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),a=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,n,r,o){let s=null;function a(){return Boolean(n&&n.apiKey)}async function i(){const r=e.listPending(t);if(!a())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const o=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let t=0;t<e.length;t+=1)try{await n.memorySave(e[t]),o+=1}catch(n){const o=upgradeInfo(n);if(o){s=o,r.push(...e.slice(t));break}r.push(e[t])}return memoryQueue.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let i=0,c=null,u=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),i+=1}catch(e){if(c=e,u=describeSyncError(e),"quota"===u.kind||"auth"===u.kind)break}const l=e.listPending(t).length;i&&(s=Date.now());const d=(c?upgradeInfo(c):null)||o.upgrade;return 0===i&&c?{ok:!1,queued:l,reason:syncErrorReason(u),failed:u?[u]:[],kind:u?u.kind:"error",status:u?u.status:0,hint:u?u.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:l,pushed:i,failed:u?[u]:[],memoryFlushed:o.flushed,upgrade:d}}const c=persistGate.createAutoPush({push:i,dir:r||t});return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>({sessions:e.listSessions(t)}),open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),nameSession:async n=>{const r=n&&n.sessionId,s=n&&n.prompt;if(!r||!String(null==s?"":s).trim())return null;let a;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{a=require(e);break}catch{}if(!a)return null;const i=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:n&&n.class||"model",model:n&&n.model,prompt:e,system:t.system,maxTokens:64,sessionId:r,tools:!1}),a=s&&s.choices&&s.choices[0]||{};return a.message&&a.message.content||null}catch{return null}};try{return await a.nameSession(e,t,r,s,{callModel:i})}catch{return null}},push:i,pull:async function(){if(!a())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),o=e.mergeRemoteSessions(t,r&&r.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:a(),lastSyncAt:s})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;let s=0,a=0,i=null,c=!1;function u(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return i=e||"push failed",a=n()+t,{attempted:!0,ok:!1,error:i,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<a)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:a-t};if(c)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?u(t.reason||t.kind||"push failed"):(s=0,a=0,i=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return u(errorText(e))}finally{c=!1}},state:function(){const e=n();return{failures:s,lastError:i,retryInMs:s>0&&a>e?a-e:0}},recordFailure:e=>u(errorText(e))}}function registerModelIpc(e,t,n,r,o,s,a){const i=createModelDispatch(t),c=createSyncDispatch(sessionStore,n,r,a,i),u=createHeartbeatRetry((()=>c.push()),s);function l(){const e=u.run();e&&"function"==typeof e.catch&&e.catch((e=>u.recordFailure(e)))}for(const[t,n]of Object.entries(i))"chat"!==t?"listModels"!==t?e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(l(),n(t)))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const a="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=a;const i=e&&e.sender,c=r.class||"model",u=n({...r,onStream:e=>{i&&"function"==typeof i.send&&!i.isDestroyed()&&i.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}});return s?u.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return console.warn(`[model] background ${c} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}})):withReplyNotify(u,e,o).catch((e=>{if(!isAbortShapedError(e))throw e;return console.warn(`[model] ${c} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e)}))}));e.on(`${MODEL_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,n]of Object.entries(c))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>{l();const r=n(t);return r&&"object"==typeof r?{...r,retry:u.state()}:r}));return{modelDispatch:i,syncDispatch:c,heartbeat:u}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,(t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)}))}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function createQueueDispatch({engine:e,env:t=process.env,queue:n=queueModule,autonomous:r=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=(()=>{})}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let a=null,i=!1,c=!1;const u=r.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(a=e.taskId),e&&"finish"===e.type&&(a=null),s(e)},canFanOut:()=>o.current().entitled});function l(){const e=n.loadQueue(t);return{ok:!0,items:e,pending:n.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:i,defaultCwd:process.cwd(),defaultModel:r.resolveModel({env:t}),queueFile:n.queuePath(t),runs:n.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,QUEUE_MAX_WORKERS),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...l()};const{opts:a,error:i}=function(e){const t=e||{},n=String(null==t.task?"":t.task).trim();if(!n)return{error:"a queued task needs text"};if(n.length>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${n.length} > ${QUEUE_MAX_TASK_CHARS} chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=r.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim().slice(0,120)||null,i=r.modelRefusal(a,s);if(i)return{error:i};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:n,cwd:o,class:s,model:a,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...l()}:{ok:!0,item:n.addTask(t,a),...l()}},list:()=>l(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...l()}),clear:e=>({...n.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...l()}),retry:e=>{const r=e&&e.id,o=n.retryTask(t,r);return o?{ok:!0,item:o,...l()}:{ok:!1,reason:`no task #${r}`,...l()}},remove:e=>{const r=e&&e.id,o=n.loadQueue(t),s=n.findTask(o,r);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...l()}:(n.saveQueue(t,o.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...l()}):{ok:!1,reason:`no task #${r}`,...l()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};let e;c=!0,i=!1;try{const t=await u.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,a=null,{...e,...l()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};c=!0,i=!1;const e=[];let t;try{for(;;){const n=await u.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:d(e)};break}if(!n.ran.length){t={ok:!0,stopped:i,ran:d(e)};break}if(e.push(...n.ran),i){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(n){t={ok:!1,reason:errorText(n),ran:d(e)}}return c=!1,a=null,{...t,...l()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,n=null==t?null:u.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...l()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function registerQueueIpc(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:a}={}){let i=null;const c=createQueueDispatch({engine:t,env:n,queue:r,autonomous:o,entitlement:s||entitlementModule.createEntitlement({probe:a&&"function"==typeof a.verifyApiKey?async()=>{const e=await a.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof a.tokenBankBalance)try{const e=await a.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{i&&"function"==typeof i.send&&("function"==typeof i.isDestroyed&&i.isDestroyed()||i.send(QUEUE_PROGRESS_CHANNEL,e))}});for(const[t,n]of Object.entries(c))e.handle(`${QUEUE_PREFIX}${t}`,((e,t)=>(i=e&&e.sender||null,n(t))));return c}function registerAutoIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${AUTO_PREFIX}${n}`,((e,t)=>r(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}accountStatusChanged`,UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:n=(()=>Date.now()),fetchImpl:r,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i}={}){const c="aegis-desktop";let u="unknown";try{u=require("./package.json").version}catch{}let l={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const d=t=>(l={...l,...t},e&&e(l),l);let p=null;try{p=require("../client/update.js")}catch{try{p=require("./vendor/update.js")}catch{p=null}}let f=0,m=0,h=null,g=null,y=null,E=null;function k(){h&&s(h),h=null}async function _({announce:e=!1}={}){if(!p)return d({status:"disabled",error:"update checker unavailable"});if(g)return g;g=(async()=>{const s=l.status,a=l.version;let i;d({status:"checking",error:null,reason:null,transient:!1});try{i=await async function(){if(r)return r({pkg:c});if(p&&"function"==typeof p.checkPublished){const e=await p.checkPublished({current:u,pkg:c,now:n(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){i={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(i.ok){if(f=0,m=0,k(),!p.isNewer(i.latest,u))return d({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(E)return E;const e=p&&p.detectInstallMethod;if("function"!=typeof e)return E="npm",E;try{E=e({env:process.env,argv:process.argv,pkg:c,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{E="npm"}return E}(),n="function"==typeof p.updatePlan?p.updatePlan({current:u,latest:i.latest,behind:!0,channel:"npm",pkg:c,method:e}):null;return d({status:"available",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:n,method:e,command:t?`${i.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:n&&n.instruction||`npm i -g ${c}@latest`,commandIsSentence:t||Boolean(n&&!n.apply),canDownload:Boolean(n&&n.apply)&&!t})}f+=1;const g=i.error||describeRegistryFailure(i.reason,i.status,c);return y=i.reason,v=i.status,("function"==typeof p.isTransientReason?p.isTransientReason(y,v):"unknown"===y)?(function(){k();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(f-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];m=n()+e,h=o((()=>{h=null,_().catch((()=>{}))}),e),h&&h.unref&&h.unref(),d({retryInMs:e})}(),d(e?{status:"error",error:g,reason:i.reason,transient:!0,attempts:f}:{status:"available"===s?"available":"unavailable",version:a,error:g,reason:i.reason,transient:!0,attempts:f})):(k(),m=0,d({status:"error",error:g,reason:i.reason,transient:!1,attempts:f,retryInMs:0}));var y,v})();try{return await g}finally{g=null}}return{status:()=>l,check:_,download:async()=>{const e=!t&&l.plan&&l.plan.apply;if(!e)return d({status:"available"===l.status?"available":l.status,command:l.plan&&l.plan.instruction||l.command,canDownload:!1});d({status:"downloading",error:null,progress:0});const n=await function(e){const t=a||((e,t)=>new Promise((n=>{execFile(e,t,{timeout:18e4,windowsHide:!0},((e,t,r)=>{if(e)return n({ok:!1,output:String(r||t||e.message||e)});n({ok:!0,output:String(t||"")})}))}))),n=!a&&p&&"function"==typeof p.installSpawn?p.installSpawn(e,{env:process.env}):null,r=n?n.command:e.command,o=n?n.args:e.args;return Promise.resolve(t(r,o)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:errorText(e)})))}(e);return n.ok?d({status:"downloaded",version:l.version,error:null,progress:100,command:`npm i -g ${c}@latest`,canDownload:!1}):d({status:"error",transient:!1,error:n.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===l.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{_().catch((()=>{})),y=setInterval((()=>_().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),y.unref&&y.unref()},stop:()=>{k(),y&&clearInterval(y),y=null},retryState:()=>({attempts:f,retryAt:m,inFlight:!!g,hasTimer:!!h})}}function createUpdateManager({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const n=createUpdateDispatch(t);for(const[t,r]of Object.entries(n))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t)));return n}let resolveTargetWindow=null;function sendToAppWindow(e,t){const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null,r=n&&!n.isDestroyed()?n:e.getFocusedWindow()||e.getAllWindows()[0];r&&!r.isDestroyed()&&r.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send(DEEP_LINK_CHANNEL,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function buildAppMenu({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion()});const a={label:"Check for Updates…",click:()=>r.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(n,MENU_NEW_CHAT_CHANNEL)},c={label:"Search…",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(n,MENU_SEARCH_CHANNEL)},u={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(n,MENU_EXPORT_MARKDOWN_CHANNEL)},l={label:"Export Session…",click:()=>sendToAppWindow(n,MENU_EXPORT_JSON_CHANNEL)},d={label:"Authorship Panel…",click:()=>sendToAppWindow(n,MENU_FINGERPRINT_CHANNEL)},p={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(n,MENU_GOOGLE_DRIVE_CHANNEL)},f=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},u,l,{type:"separator"},...s?[]:[a,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[c,{type:"separator"},d,p,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},...s?[]:[{label:"Help",submenu:[{role:"about"}]}]];return t.buildFromTemplate(f)}function bootstrap(){let e=!1;try{e=require("./lib/local/integrity.js").armed()}catch{e=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(e){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:t,BrowserWindow:n,ipcMain:r,safeStorage:o,shell:s,Menu:a,Notification:i,screen:c,dialog:u,globalShortcut:l}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const n=e.plan({packaged:t.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(n){const r=e.spawnOptions(n,process.env),o=require("node:child_process").spawnSync(r.exec,r.args,{stdio:"inherit",env:r.env}),s="number"==typeof o.status?o.status:1;return void t.exit(s)}}catch(e){t.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(t.disableHardwareAcceleration(),t.commandLine.appendSwitch("disable-gpu"),t.commandLine.appendSwitch("disable-software-rasterizer"),t.commandLine.appendSwitch("disable-gpu-compositing"),t.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||t.commandLine.appendSwitch("log-level","3"),!t.requestSingleInstanceLock())return void t.quit();if(t.setName("AEGIS Desktop"),envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}t.setAsDefaultProtocolClient(deepLink.PROTOCOL);let d=deepLink.parseDeepLinkArgv(process.argv);t.on("open-url",((e,t)=>{e.preventDefault();const n=deepLink.parseDeepLinkUrl(t);if(!n)return;const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null;r&&!r.isDestroyed()?sendDeepLinkToWindow(r,n):d=n}));const p=createClient(credentials.clientOptions()),f=resolveUserDataDir(t),{engine:m,sessionsDir:h,settingsDir:g,settings:y}=createEngine(p,{app:t,safeStorage:o,dir:f}),E=createAccountKey({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>q(e)});let k=null;const _=createGoogleConnect({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(s.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(h,e),getAuthor:()=>{try{k||(k=createFingerprintService({dir:f,getVaultBackend:()=>y.vaultBackendConfig().backend}));const e=k.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>q(E.status())}),v=Boolean(p.apiKey),A=autoProvision.autoProvisionApiKey(p,credentials,{app:"desktop"}).then((e=>{if(E.recordStartup(e),!e.key&&!p.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(y,envFile,{onWarn:t}),m&&m.settings&&m.settings!==y&&e(m.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let b=null;const S=(e,t)=>{if(function(e){const t=e&&e.sender,r=t&&n.fromWebContents(t);if(!r||r.isDestroyed())return;if(r.isFocused()&&r.isVisible())return;if(!i||!i.isSupported())return;const o=new i({title:"AEGIS Desktop",body:"Reply ready"});o.on("click",(()=>{r.isDestroyed()||(r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus())})),o.show()}(e),b&&"function"==typeof b.note){const e=t&&(t.model||t.modelId)||void 0;b.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(r,p,f,(e=>{const t=y.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>s.openExternal(e)),S,(()=>providerRouteConfigured(m)),(()=>y.vaultBackendConfig().backend));const w=registerModelIpc(r,m,h,p,S,void 0,g);registerConfirmModeIpc(r,withAutoRoundsSwitch(createConfirmModeDispatch(y),w.modelDispatch)),registerConfirmModeIpc(r,createVaultBackendDispatch(y)),registerTelemetryIpc(r,createTelemetryDispatch(createTelemetry({dir:g,enabled:telemetryEnabled(process.env,y),appVersion:(()=>{try{return"function"==typeof t.getVersion?t.getVersion():""}catch{return""}})()}))),registerCovenantIpc(r,createCovenantDispatch(covenantModule));const I=registerQueueIpc(r,{engine:createQueueEngine(p,y),aegis:p}),C=createAutoDrain({proceed:()=>I.proceed(),settings:y,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let R=null;b=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:f,getVaultBackend:()=>y.vaultBackendConfig().backend})),R.mint(e||{})),settings:y}),registerAutoIpc(r,createAutoDispatch({autoDrain:C,autoMint:b})),C.start(),b.start();let P=null,M=null;function T(){return M&&!M.isDestroyed()||(M=new n({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),M.setMenuBarVisibility(!1),M.loadFile(path.join(__dirname,"renderer","quick.html")),M.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||M.isDestroyed()||M.hide()})),M.on("blur",(()=>{!M.isDestroyed()&&M.isVisible()&&M.hide()})),M.on("closed",(()=>{M=null}))),M}function D(){const e=T();e.isVisible()?e.hide():function(){const e=T(),t=c.getCursorScreenPoint(),n=c.getAllDisplays(),r=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(P&&!P.isDestroyed())return P;const e=n.getFocusedWindow();return e&&!e.isDestroyed()&&e!==M?e:n.getAllWindows().find((e=>e!==M))||null};const N=createQuickLauncherDispatch(y,{isPackaged:t.isPackaged,applyConfig:function(e){if(l.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:t.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!l.register(e.shortcut,D)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const n=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,t){const r=t&&t.sender&&n.fromWebContents(t.sender);r&&!r.isDestroyed()&&r.hide();const o=P&&!P.isDestroyed()?P:n.getAllWindows().find((e=>e!==r))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(r,N);let U=null;t.on("will-quit",(()=>{U&&"function"==typeof U.stop&&U.stop(),l.unregisterAll(),O&&"function"==typeof O.stop&&O.stop()}));let L=!1;t.on("before-quit",(e=>{!L&&m&&"function"==typeof m.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>m.unloadLocalModels())).catch((()=>{})).finally((()=>{L=!0,t.quit()})))}));const F=new Set;function q(e){for(const t of F)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);x()}function x(){a.setApplicationMenu(buildAppMenu({app:t,Menu:a,BrowserWindow:n,updateManager:O,loggedIn:Boolean(p.apiKey)}))}const O=createUpdateManager({isPackaged:t.isPackaged,onStatus:function(e){for(const t of F)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(r,O),r.handle(`${IPC_PREFIX}accountStatus`,(()=>E.status())),r.handle(`${IPC_PREFIX}registerAccount`,(()=>E.registerAccount())),r.handle(`${IPC_PREFIX}driveSignIn`,(()=>_.signInWithGoogle())),r.handle(`${IPC_PREFIX}driveConnect`,(()=>_.connectDrive())),r.handle(`${IPC_PREFIX}driveStatus`,(()=>_.status())),r.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>_.syncMemoryNow())),r.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>_.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(r,sessionStore,h,(e=>u.showSaveDialog(n.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),x();const B=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function j(){const e=windowState.load(f),r=windowState.clampToDisplay(e,c.getAllDisplays(),{width:1080,height:720}),o=resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),a=new n({...r,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:iconForPlatform(o,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&a.maximize(),a.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&s.openExternal(e),{action:"deny"}))),a.webContents.on("will-navigate",((e,t)=>{t!==B&&(e.preventDefault(),isSafeExternalUrl(t)&&s.openExternal(t))}));let i=null;function u(){if(a.isDestroyed())return;const e=a.isMaximized(),t=e?a.getNormalBounds():a.getBounds();windowState.save(f,{...t,isMaximized:e})}function l(){i&&clearTimeout(i),i=setTimeout(u,500)}return a.on("resize",l),a.on("move",l),a.on("close",(()=>{i&&clearTimeout(i),u()})),a.loadFile(path.join(__dirname,"renderer","index.html")),F.add(a),P=a,a.on("closed",(()=>{F.delete(a),P===a&&(P=null)})),a}t.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await A,t=startupKeyOverride({mintedKey:v?"":e.key,hostKey:credentials.normalizeApiKey(y.aegisRawKey())});if(t)credentials.saveApiKey(t),p.setApiKey(t);else{const e=credentials.preferNewest(y.aegisRawKey(),y.aegisKeySavedAt());e.key&&(p.setApiKey(e.key),"shared"===e.source&&y.setAegisKey(e.key))}}try{U&&"function"==typeof U.stop&&U.stop(),U=sharedPresence.createPresence({apiKey:p.apiKey,app:"desktop",version:t.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),U.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(y,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),m&&m.settings&&m.settings!==y&&e(m.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}N.setConfig(y.quickLauncherConfig());const e=j();O.start(),d&&sendDeepLinkToWindow(e,d)})),t.on("window-all-closed",(()=>{"darwin"!==process.platform&&t.quit()})),t.on("activate",(()=>{const e=n.getAllWindows();if(0===e.length)return void j();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),t.on("second-instance",((e,t)=>{const n=resolveTargetWindow(),r=deepLink.parseDeepLinkArgv(t);if(n)n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&sendDeepLinkToWindow(n,r);else{const e=j();r&&sendDeepLinkToWindow(e,r)}}))}electron&&electron.app&&bootstrap(),module.exports={createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
@@ -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";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({"nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
@@ -0,0 +1 @@
1
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex((e=>e&&e.id===r.id));-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some((e=>e&&"aegis-api-key"===e.id));if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter((e=>!(e&&"aegis-api-key"===e.id))):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((e=>JSON.parse('"'+e[1]+'"'))));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find((e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e)))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map((e=>getTarget(e))).filter(Boolean):TARGETS,o=[];for(const t of s)for(const s of t.scopes||["user"]){const i=t.path(s,r),a={id:t.id,label:t.label,scope:s,file:i,exists:!1,installed:!1,entry:null,error:null,docs:t.docs,verified:t.verified};let c;try{c=readText(i)}catch(e){a.error=e.message,o.push(a);continue}if(a.exists=c.exists,c.exists&&null!==c.text)if("mcp-toml"===t.kind)a.entry=parseTomlEntry(c.text,`${t.container}.${n.name}`),a.installed=Boolean(a.entry);else try{const e=parseJson(c.text,i);a.entry=getPath(e,`${t.container}.${n.name}`)||null,a.installed=Boolean(a.entry)}catch(e){a.error=e.message}a.installed&&(a.serverPath=entryServerPath(a.entry),a.serverUnverifiable=hasHostVar(a.serverPath),a.serverExists=a.serverPath&&!a.serverUnverifiable?isFile(a.serverPath):null),o.push(a)}return o}function detected(e={}){const t=e.ctx||hostCtx(),r=new Set;for(const e of TARGETS)for(const n of e.scopes||["user"])try{fs.accessSync(e.path(n,t)),r.add(e.id)}catch{}for(const[e,n]of[["Code","vscode"],["Code - Insiders","vscode-insiders"],["VSCodium","vscodium"],["Cursor","cursor"]])try{fs.accessSync(path.join(appConfig(t),e)),r.add(n)}catch{}for(const[e,n]of[[[".codeium"],"windsurf"],[[".gemini"],"gemini"],[[".codex"],"codex"],[[".continue"],"continue"],[[".junie"],"junie"],[[".cursor"],"cursor"]])try{fs.accessSync(path.join(t.home||t.env.HOME||t.env.USERPROFILE,...e)),r.add(n)}catch{}return r}module.exports={hostCtx:hostCtx,planTarget:planTarget,planRemove:planRemove,apply:apply,status:status,detected:detected,renderEntry:renderEntry,entryServerPath:entryServerPath,hasHostVar:hasHostVar,parseTomlEntry:parseTomlEntry,upsertTomlSection:upsertTomlSection,removeTomlSection:removeTomlSection,setPath:setPath,getPath:getPath,delPath:delPath,readText:readText,resolveServer:resolveServer};