aegisone 1.0.39 → 1.0.41

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 (122) hide show
  1. package/LICENSING.md +186 -0
  2. package/README.md +2 -2
  3. package/bin/aegis.js +1 -1
  4. package/package.json +3 -2
  5. package/scripts/predist.mjs +1 -1
  6. package/src/child.js +1 -1
  7. package/src/permissions.js +1 -1
  8. package/vendor/cli/package.json +4 -2
  9. package/vendor/cli/src/app.js +1 -1
  10. package/vendor/cli/src/chatflow.js +1 -1
  11. package/vendor/cli/src/commands.js +3 -1
  12. package/vendor/cli/src/config.js +1 -1
  13. package/vendor/cli/src/diff.js +1 -1
  14. package/vendor/cli/src/diffview.js +1 -1
  15. package/vendor/cli/src/engine.js +1 -1
  16. package/vendor/cli/src/history.js +1 -1
  17. package/vendor/cli/src/models.js +1 -1
  18. package/vendor/cli/src/overlays.js +1 -1
  19. package/vendor/cli/src/panels.js +1 -1
  20. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  21. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  22. package/vendor/cli/vendor/client/credits.js +45 -0
  23. package/vendor/cli/vendor/client/foreign-sessions.js +3 -0
  24. package/vendor/cli/vendor/client/naming.js +1 -1
  25. package/vendor/cli/vendor/client/prefs.js +1 -1
  26. package/vendor/cli/vendor/client/session-search.js +3 -0
  27. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  28. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  29. package/vendor/cli/vendor/desktop/lib/local/integrity.js +42 -2
  30. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +206 -0
  31. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +298 -0
  32. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +199 -0
  33. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
  34. package/vendor/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
  35. package/vendor/cli/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
  36. package/vendor/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
  37. package/vendor/cli/vendor/desktop/lib/local/sandbox.js +493 -0
  38. package/vendor/cli/vendor/desktop/lib/local/shell.js +155 -20
  39. package/vendor/cli/vendor/desktop/lib/local/tools.js +29 -4
  40. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  41. package/vendor/cli/vendor/desktop/main.js +774 -37
  42. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  43. package/vendor/cli/vendor/mcp/admission.js +3 -0
  44. package/vendor/cli/vendor/mcp/server.js +1 -1
  45. package/vendor/cli/vendor/one/src/child.js +1 -1
  46. package/vendor/cli/vendor/one/src/permissions.js +1 -1
  47. package/vendor/desktop/bin/aegis.js +1 -1
  48. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  49. package/vendor/desktop/lib/local/engine.js +1 -1
  50. package/vendor/desktop/lib/local/integrity.js +42 -2
  51. package/vendor/desktop/lib/local/perm-rules.js +206 -0
  52. package/vendor/desktop/lib/local/perm-store.js +298 -0
  53. package/vendor/desktop/lib/local/perm-write.js +199 -0
  54. package/vendor/desktop/lib/local/pro-sessions.js +3 -0
  55. package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
  56. package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
  57. package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
  58. package/vendor/desktop/lib/local/sandbox.js +493 -0
  59. package/vendor/desktop/lib/local/shell.js +155 -20
  60. package/vendor/desktop/lib/local/tools.js +29 -4
  61. package/vendor/desktop/lib/settings.js +1 -1
  62. package/vendor/desktop/lib/sync/memory-store.js +3 -0
  63. package/vendor/desktop/main.js +774 -37
  64. package/vendor/desktop/package.json +19 -7
  65. package/vendor/desktop/preload.js +1 -1
  66. package/vendor/desktop/renderer/app.js +5 -1
  67. package/vendor/desktop/renderer/diff.js +1 -1
  68. package/vendor/desktop/renderer/diffview.js +1 -1
  69. package/vendor/desktop/renderer/index.html +221 -5
  70. package/vendor/desktop/renderer/provider-mark.js +1 -1
  71. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  72. package/vendor/desktop/renderer/providers.js +1 -1
  73. package/vendor/desktop/renderer/style.css +223 -6
  74. package/vendor/desktop/renderer/usage.js +1 -1
  75. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  76. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  77. package/vendor/desktop/vendor/credits.js +45 -0
  78. package/vendor/desktop/vendor/faces/cli/package.json +3 -2
  79. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  80. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  81. package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -1
  82. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  83. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  84. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  85. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  86. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  87. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  88. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  89. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  90. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  91. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  92. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +45 -0
  93. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
  94. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  95. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  96. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +3 -0
  97. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  98. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  99. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  100. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +3 -0
  101. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
  102. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
  103. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
  104. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
  105. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
  106. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
  107. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
  108. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  109. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  110. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  111. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -2
  112. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  113. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +3 -0
  114. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  115. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  116. package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
  117. package/vendor/desktop/vendor/foreign-sessions.js +3 -0
  118. package/vendor/desktop/vendor/naming.js +1 -1
  119. package/vendor/desktop/vendor/prefs.js +1 -1
  120. package/vendor/desktop/vendor/sandbox/provenance.json +20 -0
  121. package/vendor/desktop/vendor/sandbox/x64-linux/bwrap +0 -0
  122. package/vendor/desktop/vendor/session-search.js +3 -0
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l={...o,seeded:!(!r||r.named)},a=await refineTitle(s,n,l);if(a){try{e.setTitle(t,i,a,{named:!0})}catch{return null}return a}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
3
+ "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l=!(!r||r.named);if(l&&s&&!isGenericTitle(s)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...o,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),a=extractNonSecretHalf(readJson(s,{})),i=Object.keys(a).filter((e=>void 0===n[e]));if(!i.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(a).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of i)c[e]=a[e];return c.adopted={from:s,at:(new Date).toISOString(),names:i.slice().sort()},write({...n,...c},r),{adopted:!0,keys:i.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:LEGACY_MEMORY_PERSIST_NAMESPACE,prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),i=extractNonSecretHalf(readJson(s,{})),a=Object.keys(i).filter((e=>void 0===n[e]));if(!a.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(i).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of a)c[e]=i[e];return c.adopted={from:s,at:(new Date).toISOString(),names:a.slice().sort()},write({...n,...c},r),{adopted:!0,keys:a.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:LEGACY_MEMORY_PERSIST_NAMESPACE,prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
@@ -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 haystack(e){if(!e||"object"!=typeof e)return"";const t=[e.title,e.summary,e.cwd,e.id].filter((e=>"string"==typeof e&&e)),s=Array.isArray(e.messages)?e.messages:[];for(const e of s)if(e&&"user"===e.role&&"string"==typeof e.content&&e.content){t.push(e.content.slice(0,400));break}return t.join("\n")}function scoreSession(e,t){const s=String(e||"").trim().toLowerCase();if(!s)return{matched:!0,score:0,field:"all"};const r="string"==typeof(t&&t.title)?t.title.toLowerCase():"",n=haystack(t).toLowerCase();if(r&&r===s)return{matched:!0,score:1e3,field:"title"};if(r&&r.startsWith(s))return{matched:!0,score:900,field:"title"};const o=r?r.indexOf(s):-1;if(-1!==o)return{matched:!0,score:700-o,field:"title"};const i=n.indexOf(s);if(-1!==i)return{matched:!0,score:Math.max(1,400-i),field:"body"};if(r){let e=100,t=-2,n=-1,o=!0;for(const i of s){const s=r.indexOf(i,n+1);if(-1===s){o=!1;break}e+=s===t+1?15:5,0===s&&(e+=20),t=s,n=s}if(o)return{matched:!0,score:e,field:"title"}}return{matched:!1,score:0,field:null}}function rankSessions(e,t){const s=Array.isArray(t)?t:[],r=String(e||"").trim();if(!r)return s.slice();const n=[];for(let e=0;e<s.length;e+=1){const t=s[e],o=scoreSession(r,t);o.matched&&n.push({s:t,i:e,score:o.score})}return n.sort(((e,t)=>t.score-e.score||e.i-t.i)),n.map((e=>e.s))}function matchReason(e,t){const s=String(e||"").trim();if(!s)return null;const r=scoreSession(s,t);return r.matched?"title"===r.field?"title":"body"===r.field?"content":null:null}module.exports={haystack:haystack,scoreSession:scoreSession,rankSessions:rankSessions,matchReason:matchReason};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const o={...e||{}},s=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=o[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete o[e];const a=n.trim().length;a>0&&s.push({name:e,length:a,reason:t})}return n&&(o.CLAUDE_CODE_OAUTH_TOKEN=n),{env:o,dropped:s}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function shadowingValue(e,n){const t=e||{},o=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!o)return null;const s=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(o(n)?s&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,o=path.join(n.dir||claudeConfigDir(t),".credentials.json"),s={claude:n.claudeVersion||null,file:o,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(o,"utf8")),s.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(s.kind="oauth",s.subscription=r.subscriptionType||null,s.expiresAt=Number(r.refreshTokenExpiresAt)||0,s.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(s.kind="apikey",s.loggedIn=!0):claudeOAuthToken(t)&&(s.kind="env-token",s.loggedIn=!0),s.subscriptionPresent=s.loggedIn&&"apikey"!==s.kind,s.shadowed=shadowingValue(t,{hasSubscription:s.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:s.subscriptionPresent});return s.credentialPresent=s.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,s}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=a(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:o||l.result||"",error:l.is_error?l.result||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")];for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}function runClaudePro(e,n){const t=e||{},o=n||{},s=o.seam||loadSeam(o.dir),i=o.spawn||require("node:child_process").spawn,r=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,env:t.env||process.env}),a=s.child.claudeArgv({posture:r,prompt:t.prompt,model:t.model||void 0,permissionMode:t.permissionMode,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const l=childEnvPlan(n,s,{hasSubscription:r}),c=l.env,d=envDroppedLine(l.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(o.executable||"claude",a.argv,{cwd:t.cwd||process.cwd(),stdio:["ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...l.dropped.length?{envDropped:l.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,a.record)}catch{}let p=!1,h="",g="",f=null;const m=Number(t.idleTimeoutMs)||6e5,_=n=>{p||(p=!0,f&&clearTimeout(f),t.signal&&t.signal.removeEventListener("abort",v),e(l.dropped.length?{...n,envDropped:l.dropped}:n))},v=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",v,{once:!0});const b=()=>{f&&clearTimeout(f),f=setTimeout((()=>{v(),_({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(m/1e3)}s and was stopped`})}),m)};b();const k=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onDone:e=>{e.error?_({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):_({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:a.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&k.line(n)}})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{_({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&k.line(g.trim()),_({choices:[{message:proMessage(k.text,k.thinking,k.thinkingTokens),finish_reason:"stop"}],usage:k.resultLine&&k.resultLine.usage||void 0,childRecord:a.record,error:k.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,runClaudePro:runClaudePro};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const o={...e||{}},s=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=o[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete o[e];const a=n.trim().length;a>0&&s.push({name:e,length:a,reason:t})}return n&&(o.CLAUDE_CODE_OAUTH_TOKEN=n),{env:o,dropped:s}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function shadowingValue(e,n){const t=e||{},o=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!o)return null;const s=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(o(n)?s&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,o=path.join(n.dir||claudeConfigDir(t),".credentials.json"),s={claude:n.claudeVersion||null,file:o,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(o,"utf8")),s.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(s.kind="oauth",s.subscription=r.subscriptionType||null,s.expiresAt=Number(r.refreshTokenExpiresAt)||0,s.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(s.kind="apikey",s.loggedIn=!0):claudeOAuthToken(t)&&(s.kind="env-token",s.loggedIn=!0),s.subscriptionPresent=s.loggedIn&&"apikey"!==s.kind,s.shadowed=shadowingValue(t,{hasSubscription:s.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:s.subscriptionPresent});return s.credentialPresent=s.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,s}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=a(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:o||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find((e=>"string"==typeof e&&e.trim())):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")];for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}function runClaudePro(e,n){const t=e||{},o=n||{},s=o.seam||loadSeam(o.dir),i=o.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=s.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=s.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,s,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(o.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},A=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",k),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},k=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",k,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout((()=>{k(),A({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})}),f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then((()=>t.onAsk(e))).then((n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED")),(n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)})).catch((()=>{}))},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?A({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):A({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}})),_&&u.stdin&&u.stdin.on("error",(()=>{})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{A({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&S.line(g.trim()),A({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}function normalizeToolArgs(e,o,t,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(o,t,r):{ok:!0,args:t&&"object"==typeof t?t:{},error:null}}function detectVcs(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let r=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(r,".git")))return"git";const e=t.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},o={},t=null){const r=e||{},n=o||{},s=(e,o)=>null!=n[e]?n[e]:o;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",t&&t.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function providerKeyRecord(e){const o={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return o;try{const t=envFile.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,o,t){const r=Number(o);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function nativeEffort(e,o,t){const r=String(o||"");if(EFFORT_INERT_RE.test(r))return;if(null===t)return;const n="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of EFFORT_DIALECTS)if(o.provider===e&&o.re.test(r)){const e=Object.prototype.hasOwnProperty.call(o.map,n)?o.map[n]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,n)?o.extra[n]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:parseArgs(o.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const o=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const r=flattenContent(o.content);if(r.trim())return r}return o}function assistantText(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function finishReasonOf(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const o=finishReasonOf(e);return"length"===o||"max_tokens"===o}function reasoningTextOf(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",n=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,o){const t=doubledBudget(e.maxTokens);return o&&ladderRung(e.maxTokens)?Math.max(t,REASONING_RETRY_FLOOR):t}function ladderRung(e){const o=Number(e);return Number.isFinite(o)&&Object.values(EFFORT_TOKEN_BUDGET).includes(o)}function doubledBudget(e){const o=Number(e)||0;return o>0?2*o:8192}function statedCapOf(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,o,t){if(o)return!1;if(!(t>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:o,finishReason:t,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:o,tools:t,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,localTransport:i=localTransport,fetchImpl:l,gitScope:c}){const d=new Map,u=t||toolsModule,f=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,p=require("./session-rounds.js"),m=()=>{if("function"==typeof a)return!1!==a();if(o&&"function"==typeof o.getConfirmMode){const e=o.getConfirmMode();return void 0===e||Boolean(e)}return!0},g=new Map,h=new Map,y=new Map,k=new Map,v=new Map;function b(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function E(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,v.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),v.set(s,{resolve:l}),"function"==typeof o?o({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function w(e,o,t){const r=normalizeToolArgs(u,e,o,t||{});if(!r.ok)return{ok:!1,error:r.error};o=r.args;const n=t&&t.guard;if(n&&"exec"===e){const e=blocksDestructive(n,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=covenant.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=covenant.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await u.executeTool(e,o,t);return n&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&recordWrite(n,o&&o.file_path),a}async function T(e,{toolCtx:o,rootSessionId:t,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(u,s,e.args,o||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!u.MUTATING_TOOLS.has(s))return w(s,i,o);if(!m())return w(s,i,o);if(function(e,o){const t=g.get(e);return Boolean(t&&t.has(o))}(t,s))return w(s,i,o);if(function(e,o){const t=h.get(e);return Boolean(t&&t.has(o))}(t,s))return{ok:!1,error:b(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=u.previewMutation(s,i,o||{}),!l.ok))return{ok:!1,error:l.error};const c=await function(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,k.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),k.set(s,{resolve:l}),"function"==typeof o?o({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null}}):l("cancel")}))}(t,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return function(e,o){h.has(e)||h.set(e,new Set),h.get(e).add(o)}(t,s),{ok:!1,error:b(s)};if("session"!==c&&"once"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};if("session"===c&&function(e,o){g.has(e)||g.set(e,new Set),g.get(e).add(o)}(t,s),l){const e=u.applyChecked(s,i,l,o||{});return e&&!1!==e.ok&&o&&o.guard&&recordWrite(o.guard,i&&i.file_path),e}return w(s,i,o)}function _(e){return hostEnv(s||{},e&&e.env||{},e)}async function S(o,t){if("aegis"===o){const o=!t.singlePass&&(!!t.autonomous||void 0);return e.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===o?{}:{brain:o},...!1===o?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===o&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===o){const{provider:o,model:r}=splitByokModel(t.model),n=canonicalModelId(o,r),s=nativeEffort(o,n,t.effort);try{return await e.byokChatCompletion({provider:o,model:n,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===o){const e=t.cfg&&t.cfg.baseURL||i.DEFAULT_BASE,o=o=>i.chat({baseURL:e,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...o&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await o(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return o(!1);throw e}}if("pro"===o){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?y.get(e):null,r=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),r=t(e),n=e=>{const n=t(e);n&&n!==r&&!o.includes(n)&&o.push(n)};let s=c;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return o}(t.cwd),n=await claudePro.runClaudePro({prompt:proTurnPrompt(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:r,resumeSessionId:o||void 0,gate:"function"==typeof a?!a():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:claudePro.childLine(o)})}});return e&&n&&n.sessionId&&!n.error&&y.set(e,n.sessionId),n}throw new Error(`dispatch: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function A(t,r){const n=t&&t.class,s=t&&t.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,t&&t.maxTokens,t&&t.effort),l=statedCapOf(t),c="aegis"===n&&Boolean(t&&t.autonomous),m=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||randomUUID(),h=Number.isInteger(t&&t.depth)?t.depth:0,y=t&&t.rootSessionId||g,k=t&&t.rootOnDelta||r,v="function"==typeof r?e=>e&&r({reasoning:e}):void 0,b=new AbortController;d.set(g,b);const w=b.signal,A=!(t&&!1===t.tools),x=A?u.toolsFor({includeSubagent:h<4}):[],N=t&&t.toolChoice||null,O=t&&t.system||f(_(t)),R=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let U=R.length,F=t&&t.prompt||"";const D=String(F||""),L=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let I=L.length?attachmentsModule.buildContent(F,L):F,C=null;const P=_(t),B=P.cwd,q={getShell:()=>C||(C=new ShellSession({cwd:_(t).cwd})),signal:w,cwd:B,desktopdir:P.desktopdir};try{const d="byok"===n?splitByokModel(s):null,f="byok"===n?o.get(byokNamespace(d.provider))||{}:"local"===n&&o.get("local")||{},b="byok"===n?o.rawKey(byokNamespace(d.provider)):null,_="byok"!==n?null:b||providerKeyFromEnv(d.provider);if(!("byok"!==n||d.provider&&d.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!_){const e="anthropic"===d.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(d.provider).rejected,t=new Error(o?`${o}. That is why this turn has no ${d.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${d.provider} <key> to set one here.`:e&&e.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${e.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${d.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${d.provider} <key>.`);throw t.status=400,t}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=i.remoteRefusal(f.baseURL||i.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===d.provider&&!(f.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const C={cls:n,model:s,mode:t&&t.mode,maxTokens:a,statedMaxTokens:l,autonomous:c,sessionId:g,signal:w,onDelta:r,cfg:f,apiKey:_,toolChoice:N,cwd:B,rootSessionId:y,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:v,idleTimeoutMs:c?9e5:void 0,stream:!t||!1!==t.stream};let P=!1,j=!1;const K=c?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",$=(()=>{const e=Number.parseInt(process.env[K]||"",10);return Number.isFinite(e)&&e>0?e:0})(),G=$||(c?40:24);let Y=p.keyFor(t,R),W=p.take(Y);if(!W&&!p.isStatedKey(t)){const e=p.adopt();e&&(W=e.entry,Y=e.key)}if(W){const e=p.resumePreamble(W);0===R.length?Array.isArray(W.messages)&&W.messages.length&&R.push(...W.messages):Array.isArray(W.added)&&W.added.length&&R.push(...W.added),F?(F=`${e}\n\n${F}`,I=L.length?attachmentsModule.buildContent(F,L):F):(R.push({role:"user",content:e}),I=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=$||G+(W?p.bonus(G):0),H=0;const V=G,X=8;let J=0;const Q={calls:0},Z=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ee=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){Q.calls+=1;for(const e of Z)"number"==typeof o[e]&&Number.isFinite(o[e])&&(Q[e]=(Q[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(Q.total_tokens=(Q.total_tokens||0)+e)}}},oe=e=>e&&"object"==typeof e&&Q.calls?{...e,usage:{...Q}}:e,te=()=>{if(""===I)return;const e=R[R.length-1],o=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&o===flattenContent(I)||R.push({role:"user",content:I}),F="",I=""};U=R.length;const re=u&&u.MUTATING_TOOLS||new Set;let ne=0,se=0,ae=!1;for(;;){if(H>=z){if(m&&J<X&&!w.aborted&&await E(y,k,w,{spent:z,extensions:J+1,max:X,size:V})){J+=1;const e=z;z+=V,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${V} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=m?"":`, or raise ${K} for a longer single turn`,o=`[stopped at ${z} tool rounds`+(Q.total_tokens?`, ${Q.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=p.record(Y,{rounds:H,tokens:Q.total_tokens||0,note:o,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return k&&k({delta:`\n\n${o}`}),oe({model:C.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:Y})}H+=1;const e={...C,system:O,messages:R,prompt:I,tools:x,recallDeep:C.recallDeep&&1===H};let o;if(o=await S(n,e),ee(o),w.aborted)return oe(o);if(!P&&!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){P=!0;const t=reasonedButSilent(o);if(o=await S(n,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:retryBudgetFor(e,t),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const a=x.length?extractToolCalls(o):[];if(!a.length){if(assistantText(o)||j||!A){if(!ae&&A&&wantsMutation(D,se>0,ne)){ae=!0,te(),R.push({role:"assistant",content:assistantText(o)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return oe(o)}j=!0,te(),R.push({role:"user",content:reasonedButSilent(o)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const t={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};o=await S(n,t);let r=t.maxTokens,a=t.effort;if(ee(o),w.aborted)return oe(o);if(!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){const e=reasonedButSilent(o);if(r=retryBudgetFor(t,e),a=e?"high":t.effort,o=await S(n,{...t,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const o={maxTokens:r};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,retryBudgetFor(o,!0))})();let l=0;for(;!assistantText(o)&&l<2&&!w.aborted;){const e=reasonedButSilent(o);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,o=await S(n,{...t,messages:R,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}if(!assistantText(o))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(o),reasoningChars:reasoningTextOf(o).length,reasoningTokens:reasoningTokensOf(o)});return oe(o)}te(),R.push({role:"assistant",content:assistantText(o),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const o=planExec(e.args&&e.args.command,{baseCwd:B});return i.set(e,o),o},d=e=>{if(e.name===u.SUBAGENT_TOOL)return!1;if(!re.has(e.name))return!0;const o=c(e);return Boolean(o&&o.oneShot)},f=[];for(const e of a){const o=f[f.length-1];d(e)&&o&&o.parallel?o.calls.push(e):f.push({parallel:d(e),calls:[e]})}const g=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:B,phase:"run"}});const o=c(e),a=o&&o.oneShot?{...q,oneShotExec:!0,cwd:o.cwd||q.cwd}:q,i=e.name===u.SUBAGENT_TOOL?await M(e.args,{cls:n,model:s,statedMaxTokens:l,effort:t&&t.effort,mode:t&&t.mode,parentSignal:w,depth:h,rootSessionId:y,rootOnDelta:k}):await T(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:w});return i&&i.usage&&ee({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:B,phase:"done"}}),i};for(const e of f){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>g(e)))):[await g(e.calls[0])];e.calls.forEach(((e,t)=>{const r=o[t];re.has(e.name)&&(ne+=1,r&&r.ok&&(se+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:u.toolResultText(r)})}))}}}catch(e){throw w.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),d.delete(g)}}async function M({description:e,subagent_type:o,prompt:t}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(t||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=o&&"general"!==o?agentRoleLabel(o):"general",m=agentSystemPrompt(o),g=randomUUID();let h;if(l){if(l.aborted)return{ok:!1,error:"aborted"};h=()=>x(g),l.addEventListener("abort",h,{once:!0})}try{const e=await A({class:r,model:n,mode:i,system:m,prompt:f,sessionId:g,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),o=assistantText(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${p}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&h&&l.removeEventListener("abort",h)}}function x(e){const o=d.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((t=>{if("aegis"===t.class)return{...t,configured:Boolean(e.apiKey)};if("byok"===t.class){const e=(o.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...t,configured:e}}if("local"===t.class)return{...t,configured:!0};if("pro"===t.class){const e=claudePro.claudeProStatus({env:process.env}),o=claudePro.seamAvailable();return{...t,configured:e.loggedIn,status:e,seam:o}}return{...t,configured:!1}}))},listModels:async function(t){if("aegis"===t){if(!e.apiKey)return{class:t,models:[],needsKey:!0};const o=await e.listModels();return{class:t,models:offerableCatalog(normalizeCatalog(o&&o.models))}}if("byok"===t){let r=[],n=null,s=!1,a=null;try{const o=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(o&&o.providers||[]))),n=o&&o.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const t=o.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const o of s){const s="string"==typeof o?o:o&&o.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(t.configured||n),keyRejected:r.rejected||null})}}return{class:t,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===t){const e=(o.get("local")||{}).baseURL||i.DEFAULT_BASE,r=await i.probe(e);if(!r.running)return{class:t,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await i.listTags(e)}catch{s=!1}return{class:t,models:n,baseURL:r.baseURL,listed:s}}if("pro"===t){const e=claudePro.claudeProStatus({env:process.env});return{class:t,models:claudePro.PRO_MODELS.map((o=>({id:o.id,label:o.label,note:o.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:A,cancel:x,respondApproval:function(e,o){const t=k.get(e);return t?(k.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=v.get(e);return t?(v.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return g.delete(e),h.delete(e),y.delete(e),{ok:!0}},settings:o,unloadLocalModels:function(){return i.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,o)=>addUserModel(e,o),removeUserModel:(e,o)=>removeUserModel(e,o),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),r=function(e){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";try{if(o&&"function"==typeof o.rawKey){const e=o.rawKey(byokNamespace(t));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(t)}(t),n=await discoverVendorModels(t,{key:r,fetchImpl:l});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])s.push(o)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(t)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=addUserModel(e,o);r.file=t.file||r.file,t.added?r.added+=1:r.already.push(t.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=t.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(o),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
3
+ "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,n){const r=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return r?r(t,o,n):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let n=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(n,".git")))return"git";const e=o.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const n=e||{},r=t||{},s=(e,t)=>null!=r[e]?r[e]:t;let a=n.homedir,i=n.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=n.shell,c=n.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=n.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=n.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=n.locale,p=n.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",n.platform||process.platform),arch:s("arch",n.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",n.languages),cwd:s("cwd",i),vcs:s("vcs",null!=n.vcs?n.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",n.roots),appVersion:s("appVersion",n.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const n=Number(t);return Number.isFinite(n)&&n>0?n:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const n=String(t||"");if(EFFORT_INERT_RE.test(n))return;if(null===o)return;const r="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(n)){const e=Object.prototype.hasOwnProperty.call(t.map,r)?t.map[r]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,r)?t.extra[r]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const n=flattenContent(t.content);if(n.trim())return n}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",r=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,r.reasoning_tokens,r.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&MUTATION_INTENT_RE.test(n)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:n,reasoningTokens:r,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(r)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(n?`, hidden reasoning: ${n} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(n||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:n,recallProvider:r,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=n&&n.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:n.tool,args:n.args,diff:n.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:n.spent,extensions:n.extensions,max:n.max,size:n.size}}):l(!1)}))}async function $(e,t,o,n,r){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=covenant.preActionAssert({tool:e,args:t||{}});if(!i.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},i);return{ok:!1,error:`refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`,covenant:o}}const l="writeFile"===e||"editFile"===e,c=l?I(t&&t.file_path):null,d=await m.executeTool(e,t,o);if(a&&l&&d&&!1!==d.ok&&recordWrite(a,t&&t.file_path),l&&c&&d&&!1!==d.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(n,{id:r||randomUUID(),tool:e,path:t&&t.file_path,before:c,after:o,at:Date.now()})}return d}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function B(e,{toolCtx:t,rootSessionId:o,rootOnDelta:n,signal:r}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const n=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return n.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,n.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const n=_.get(e);return Boolean(n&&n.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let n;try{n=g(s,i)}catch(e){n={verdict:null,source:"error",error:e&&e.message||String(e)}}if(n&&"deny"===n.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:n.rule||null};if(n&&"allow"===n.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,n,r,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function q(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),n=o(e),r=e=>{const r=o(e);r&&r!==n&&!t.includes(r)&&t.push(r)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&r(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&r(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:n}=splitByokModel(o.model),r=canonicalModelId(t,n),s=nativeEffort(t,r,o.effort);try{return await e.byokChatCompletion({provider:t,model:r,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const n=K(o.cwd),r=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:n,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,n=o.rootOnDelta,r=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=r||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return n&&n({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(n&&n({delta:"",note:E(s,e.reason)}),"deny")}if(r&&m.MUTATING_TOOLS.has(s))return n&&n({delta:"",note:E(s)}),"deny";if(!r&&!PRO_PLAN_MODE_SAFE.has(s))return n&&n({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return n&&n({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return n&&n({delta:"",note:L(s)}),"deny";const l=await C(t,n,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await r(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await r(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,n){const r=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===r?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===r&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||n,b="function"==typeof n?e=>e&&n({reasoning:e}):void 0,w=new AbortController;p.set(f,w);const E=w.signal,_=!(o&&!1===o.tools),T=_?m.toolsFor({includeSubagent:g<4}):[],S=o&&o.toolChoice||null,x=o&&o.system||h(q(o)),A=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let M=A.length,O=o&&o.prompt||"";const N=String(O||""),F=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let R=F.length?attachmentsModule.buildContent(O,F):O,D=null;const U=q(o),I=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const n=require("./sandbox.js"),r=e&&e.cwd||process.cwd(),s=n.normalize(o,r);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=n.autoGrants(r,{home:e,addDirs:(()=>{try{return K(r)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||n.detect({appDir:l.appDir}),workspace:r,appDir:l.appDir,strict:!0===l.strict}})(U,r),L=U.cwd,C={getShell:()=>D||(D=new ShellSession({cwd:U.cwd,sandbox:I})),signal:E,cwd:L,desktopdir:U.desktopdir,sandbox:I};try{const l="byok"===r?splitByokModel(s):null;let p=null;const h="byok"===r?t.get(byokNamespace(l.provider))||{}:"local"===r&&t.get("local")||{},w="byok"===r?t.rawKey(byokNamespace(l.provider)):null,D="byok"!==r?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==r||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===r&&!D){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,n=nexusFallbackModel({provider:l.provider,providerKey:D,providerKeyRefused:o,aegisKey:D?"":e.apiKey});if(!n){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:n}}if("byok"===r&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===r){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===r&&"custom"===l.provider&&!(h.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const U=p?"aegis":r,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:E,onDelta:n,cfg:h,apiKey:D,toolChoice:S,pooledFrom:p?p.from:void 0,cwd:L,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let $=!1,j=!1;const q=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[q]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,A),H=v.take(z);if(!H&&!v.isStatedKey(o)){const e=v.adopt();e&&(H=e.entry,z=e.key)}if(H){const e=v.resumePreamble(H);0===A.length?Array.isArray(H.messages)&&H.messages.length&&A.push(...H.messages):Array.isArray(H.added)&&H.added.length&&A.push(...H.added),O?(O=`${e}\n\n${O}`,R=F.length?attachmentsModule.buildContent(O,F):O):(A.push({role:"user",content:e}),R=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${H.rounds} tool rounds`+(H.interruptions>1?` (cut off ${H.interruptions}×)`:"")+"…]\n"})}let V=K||Y+(H?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},ne=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},re=()=>{if(""===R)return;const e=A[A.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(R)||A.push({role:"user",content:R}),O="",R=""};M=A.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1;for(;;){if(X>=V){if(u&&Z<Q&&!E.aborted&&await P(y,k,E,{spent:V,extensions:Z+1,max:Q,size:J})){Z+=1;const e=V;V+=J,A.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=u?"":`, or raise ${q} for a longer single turn`,t=`[stopped at ${V} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:H?H.interruptions:0,messages:A,added:A.slice(M)});return k&&k({delta:`\n\n${t}`}),ne({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:x,messages:A,prompt:R,tools:T,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),E.aborted)return ne(t);if(!$&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){$=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const a=T.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!_){if(!le&&_&&wantsMutation(N,ie>0,ae)){le=!0,re(),A.push({role:"assistant",content:assistantText(t)}),A.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return ne(t)}j=!0,re(),A.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:A,prompt:"",tools:[]};t=await G(U,o);let n=o.maxTokens,a=o.effort;if(oe(t),E.aborted)return ne(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(n=retryBudgetFor(o,e),a=e?"high":o.effort,t=await G(U,{...o,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const i=(()=>{const e=Number(n)||0;if(!e)return n;const t={maxTokens:n};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!E.aborted;){const e=reasonedButSilent(t);if(l+=1,A.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),n=i,t=await G(U,{...o,messages:A,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}if(!assistantText(t))throw emptyTurnError({cls:r,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return ne(t)}re(),A.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:L});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{n&&n({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:L,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...C,oneShotExec:!0,cwd:t.cwd||C.cwd}:C,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:r,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:E,depth:g,rootSessionId:y,rootOnDelta:k}):await B(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:E});return l&&l.usage&&oe({usage:l.usage}),n&&n({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:L,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const n=t[o];se.has(e.name)&&(ae+=1,n&&n.ok&&(ie+=1)),A.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(n)})}))}}}catch(e){throw E.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{D&&D.dispose(),p.delete(f)}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:n,model:r,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:n,model:r,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let n=[],r=null,s=!1,a=null;try{const t=await e.byokProviders();n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),r=t&&t.fee||null}catch(e){n=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of n){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},n=providerKeyRecord(e.id),r=n.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||r),keyRejected:n.rejected||null})}}return{class:o,models:i,providers:n,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:r,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(n)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,n=await c.probe(e);if(!n.running)return{class:o,models:[],baseURL:n.baseURL,needsDaemon:!0};let r=[],s=!0;try{r=await c.listTags(e)}catch{s=!1}return{class:o,models:r,baseURL:n.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],n=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===n)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const r=o[n],s=I(r.path);if(!s||s.existed!==r.after.existed||s.content!==r.after.content)return{ok:!1,error:`${r.path} has changed since ${r.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{r.before.existed?fs.writeFileSync(r.path,r.before.content,"utf8"):fs.unlinkSync(r.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(n,1),{ok:!0,path:r.path,restored:r.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),n=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),r=await discoverVendorModels(o,{key:n,fetchImpl:d});if(!r||!r.ok)return r;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...r,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);n.file=o.file||n.file,o.added?n.added+=1:n.already.push(o.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=o.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(t),reason:r})}return n},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{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="a5a0606d175e3f9b7d5148cd19a631123edaec22c8d45c042bc7f9176ad7bfaa";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};
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 r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).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")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="3afb3af431c2949073c05cbd85752329fd5882cb1a184fd77dfa7cbbc0870f29";function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r="string"==typeof SEALED?SEALED.trim():"";return 64!==r.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(r)!==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
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ "use strict";const path=require("path");function candidates(r){const e=r||__dirname;return[path.join(e,"..","..","..","one","src"),path.join(e,"..","..","vendor","one","src"),path.join(e,"..","..","..","..","one","src"),path.join(e,"..","..","vendor","faces","cli","vendor","one","src")]}let cachedShared=null;function loadShared(r){if(null!==cachedShared&&void 0===r)return cachedShared;for(const e of candidates(r))try{const t=require(path.join(e,"permissions.js"));if(t&&"function"==typeof t.storedPermissionFacts&&"function"==typeof t.loadEvaluator){const e={permissions:t};return void 0===r&&(cachedShared=e),e}}catch{}return null}function rulesVerdict(r,e,t={}){const o=loadShared(t.dir);if(!o)return{verdict:null,source:"unavailable",error:"one/src/permissions.js not found"};const{permissions:n}=o;let c=t.facts;if(!c)try{c=n.storedPermissionFacts()}catch(r){return{verdict:null,source:"unavailable",error:r&&r.message||String(r)}}const s=c&&c.rules;if(!s||"object"!=typeof s)return{verdict:null,source:c&&c.source||"none"};let a;try{a=n.loadEvaluator()}catch(r){return{verdict:null,source:"unavailable",error:r&&r.message||String(r)}}const{matchRule:u,subjectFor:i}=a;if("function"!=typeof u||"function"!=typeof i)return{verdict:null,source:"unavailable",error:"rule evaluator is incomplete"};const l=i(r,e||{});for(const e of["deny","allow"]){const t=Array.isArray(s[e])?s[e]:[];for(const o of t){let t=!1;try{t=u(o,r,l)}catch{t=!1}if(t)return{verdict:"deny"===e?"deny":"allow",source:c.source||"store",rule:o}}}return{verdict:null,source:c.source||"store"}}function subjectFor(r,e){try{const t=loadShared();if(!t)return"";const o=t.permissions.loadEvaluator();return o&&"function"==typeof o.subjectFor?o.subjectFor(r,e||{}):""}catch{return""}}module.exports={rulesVerdict:rulesVerdict,loadShared:loadShared,candidates:candidates,subjectFor:subjectFor};
@@ -0,0 +1,3 @@
1
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ "use strict";const{loadShared:loadShared}=require("./perm-rules.js"),LISTS=Object.freeze(["deny","allow","ask"]);function resolveStore(e={}){if(e.config){const o=["loadPermissions","savePermissions","addPermissionRule","removePermissionRule"].find((o=>"function"!=typeof e.config[o]));return o?{ok:!1,reason:`the permissions store has no ${o}()`}:{ok:!0,config:e.config}}const o=loadShared(e.dir);if(!o)return{ok:!1,reason:"one/src/permissions.js not found"};let r;try{r=o.permissions.loadConfigStore()}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}if(!r)return{ok:!1,reason:"the permissions store is unavailable"};for(const e of["loadPermissions","savePermissions","addPermissionRule","removePermissionRule"])if("function"!=typeof r[e])return{ok:!1,reason:`the permissions store has no ${e}()`};return{ok:!0,config:r}}function listRules(e={}){const o=resolveStore(e);if(!o.ok)return{ok:!1,reason:o.reason};let r;try{r=o.config.loadPermissions()}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}const n=r&&"object"==typeof r?r:{},s=e=>Array.isArray(e)?e.map(String):[];return{ok:!0,source:"store",rules:{defaultMode:"allow"===n.defaultMode||"deny"===n.defaultMode?n.defaultMode:"ask",deny:s(n.deny),allow:s(n.allow),ask:s(n.ask)}}}function validateRule(e,o={}){const r=String(null==e?"":e).trim();if(!r)return{ok:!1,reason:"a rule cannot be empty"};if(/[\n\r]/.test(r))return{ok:!1,reason:"a rule must be a single line"};const n=loadShared(o.dir);if(!n)return{ok:!1,reason:"one/src/permissions.js not found"};let s;try{s=n.permissions.loadEvaluator()}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}const{matchRule:t,subjectFor:i,canonTool:a}=s;if("function"!=typeof t||"function"!=typeof i)return{ok:!1,reason:"the rule evaluator is incomplete"};const l=/^(\w+)(?:\((.*)\))?$/.exec(r);if(!l)return{ok:!1,reason:"a rule has the form tool(pattern), e.g. exec(npm test)"};const u=l[1];if("function"==typeof a&&!KNOWN_TOOLS.has(a(u)))return{ok:!1,reason:`"${u}" is not a tool this app calls — nothing would ever match it`};const c=l[2];if(void 0!==c&&""!==c){let e=!1;try{e=t(r,u,c)}catch{e=!1}if(!e)return{ok:!1,reason:"this pattern cannot match itself, so it would never fire"}}return void 0===c||""===c?{ok:!0,warning:`a bare ${u}() rule matches every ${u} call, including commands that change directory more than once`}:{ok:!0}}const KNOWN_TOOLS=new Set(["shell","read","write","edit","list","glob","grep","task"]);function toFileShape(e){const o=e&&"object"==typeof e?e:{},r=e=>Array.isArray(e)?e.map(String):[];return{defaultMode:"allow"===o.defaultMode||"deny"===o.defaultMode?o.defaultMode:"ask",deny:r(o.deny),allow:r(o.allow),ask:r(o.ask)}}function addRule(e,o,r={}){const n=String(e||"");if(!LISTS.includes(n))return{ok:!1,reason:`unknown list "${n}"`};const s=validateRule(o,r);if(!s.ok)return{ok:!1,reason:s.reason};const t=s.warning,i=resolveStore(r);if(!i.ok)return{ok:!1,reason:i.reason};const a=String(o).trim();try{const e=toFileShape(i.config.loadPermissions()),o=i.config.addPermissionRule(n,a,e),r=o&&o.rules?toFileShape(o.rules):e;return o&&!1===o.added?{ok:!0,added:!1,rules:r,...t?{warning:t}:{}}:(i.config.savePermissions(r),{ok:!0,added:!0,rules:r,...t?{warning:t}:{}})}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}}function removeRule(e,o,r={}){const n=String(e||"");if(!LISTS.includes(n))return{ok:!1,reason:`unknown list "${n}"`};const s=resolveStore(r);if(!s.ok)return{ok:!1,reason:s.reason};const t=String(null==o?"":o).trim();if(!t)return{ok:!1,reason:"no rule named"};try{const e=toFileShape(s.config.loadPermissions()),o=s.config.removePermissionRule(n,t,e),r=o&&o.rules?toFileShape(o.rules):e;return o&&!1===o.removed?{ok:!0,removed:!1,rules:r}:(s.config.savePermissions(r),{ok:!0,removed:!0,rules:r})}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}}module.exports={LISTS:LISTS,KNOWN_TOOLS:KNOWN_TOOLS,toFileShape:toFileShape,validateRule:validateRule,listRules:listRules,addRule:addRule,removeRule:removeRule};
@@ -0,0 +1,3 @@
1
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ "use strict";const{loadShared:loadShared}=require("./perm-rules.js"),INEXPRESSIBLE=/[*?\n\r]/;function composeRule(e,o,r={}){const s=String(e||"").trim();if(!s)return{ok:!1,reason:"no tool name"};const n=loadShared(r.dir);if(!n)return{ok:!1,reason:"one/src/permissions.js not found"};let t;try{t=n.permissions.loadEvaluator().subjectFor}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}if("function"!=typeof t)return{ok:!1,reason:"rule evaluator is incomplete"};const a=t(s,o||{});return a?INEXPRESSIBLE.test(a)?{ok:!1,reason:"this command contains a wildcard character, which the rule language cannot match literally"}:{ok:!0,rule:`${s}(${a})`,subject:a,tool:s}:{ok:!1,reason:"this call has no command or path to scope a rule to"}}function describeRule(e,o,r={}){const s=composeRule(e,o,r);return s.ok?s.rule:null}function persistAllow(e,o={}){if(!e||"string"!=typeof e)return{ok:!1,reason:"no rule to persist"};let r,s=o.config;if(!s){const e=loadShared(o.dir);if(!e)return{ok:!1,reason:"one/src/permissions.js not found"};try{s=e.permissions.loadConfigStore()}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}}if(!s||"function"!=typeof s.addPermissionRule||"function"!=typeof s.savePermissions)return{ok:!1,reason:"the permissions store is unavailable, so no rule was written"};try{r="function"==typeof s.loadPermissions?s.loadPermissions():{}}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}const{explicitAsk:n,...t}=r||{},a={defaultMode:"allow"===t.defaultMode||"deny"===t.defaultMode?t.defaultMode:"ask",allow:Array.isArray(t.allow)?t.allow:[],deny:Array.isArray(t.deny)?t.deny:[],ask:Array.isArray(t.ask)?t.ask:[]};let l;try{const o=s.addPermissionRule("allow",e,a);if(l=o&&o.rules?o.rules:a,o&&!1===o.added)return{ok:!0,added:!1,rules:l,source:"store"};s.savePermissions(l)}catch(e){return{ok:!1,reason:e&&e.message||String(e)}}return{ok:!0,added:!0,rules:l,source:"store"}}function alwaysAllow(e,o,r={}){const s=composeRule(e,o,r);if(!s.ok)return{ok:!1,reason:s.reason};const n=persistAllow(s.rule,r);return n.ok?{ok:!0,rule:s.rule,added:!1!==n.added}:{ok:!1,rule:s.rule,reason:n.reason}}module.exports={composeRule:composeRule,describeRule:describeRule,persistAllow:persistAllow,alwaysAllow:alwaysAllow};
@@ -0,0 +1,3 @@
1
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),MAX_ENTRIES=200;function storePath(e=process.env){const t=e||{},r=process.env||{},n=t.AEGIS_PRO_SESSIONS_FILE||r.AEGIS_PRO_SESSIONS_FILE;if(n)return n;const s=t.AEGISCODE_HOME||t.AEGIS_HOME||r.AEGISCODE_HOME||r.AEGIS_HOME;return path.join(s?path.resolve(String(s).trim()):path.join(os.homedir(),".aegiscode"),"pro-sessions.json")}function read(e=process.env){try{const t=fs.readFileSync(storePath(e),"utf8"),r=JSON.parse(t);if(!r||"object"!=typeof r||Array.isArray(r))return{};const n={};for(const[e,t]of Object.entries(r))t&&"object"==typeof t&&"string"==typeof t.id&&t.id&&(n[e]={id:t.id,at:Number(t.at)||0});return n}catch{return{}}}function prune(e){const t=Object.keys(e);if(t.length<=MAX_ENTRIES)return e;t.sort(((t,r)=>(e[r].at||0)-(e[t].at||0)));const r={};for(const n of t.slice(0,MAX_ENTRIES))r[n]=e[n];return r}function write(e,t=process.env){try{const r=storePath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const n=`${r}.${process.pid}.tmp`;return fs.writeFileSync(n,JSON.stringify(prune(e),null,2),{mode:384}),fs.renameSync(n,r),!0}catch{return!1}}function get(e,t=process.env){if(!e)return null;const r=read(t);return r[e]?r[e].id:null}function set(e,t,r=process.env){if(!e||"string"!=typeof t||!t)return!1;const n=read(r);return n[e]={id:t,at:Date.now()},write(n,r)}function del(e,t=process.env){if(!e)return!1;const r=read(t);return!r[e]||(delete r[e],write(r,t))}module.exports={storePath:storePath,read:read,write:write,get:get,set:set,del:del,MAX_ENTRIES:MAX_ENTRIES};
@@ -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"),VENDOR_REL=path.join("vendor","sandbox");function helperCandidates(e,n=process.env){const t=[];return n&&n.AEGIS_SANDBOX_HOST&&t.push(String(n.AEGIS_SANDBOX_HOST)),e&&(t.push(path.join(e,VENDOR_REL,`${process.arch}-win32`,"aegis-sandbox-host.exe")),t.push(path.join(e,VENDOR_REL,"win32","aegis-sandbox-host.exe"))),t}function findHelper(e,n){for(const t of helperCandidates(e,n))try{if(fs.statSync(t).isFile())return t}catch{}return null}function detect({appDir:e,env:n=process.env,platform:t=process.platform,probe:o}={}){if("win32"!==t)return{available:!1,path:null,reason:`no win32 mechanism on ${t}`,probed:!1};const a=findHelper(e,n);if(!a)return{available:!1,path:null,reason:"AppContainer has no command-line wrapper; a signed aegis-sandbox-host.exe is required and is not shipped",probed:!1};if("function"!=typeof o)return{available:!1,path:a,reason:"aegis-sandbox-host.exe present but unproven — no confinement probe is implemented",probed:!1};const r=o(a);return r&&r.ok?{available:!0,path:a,reason:null,probed:!0,mechanism:"appcontainer"}:{available:!1,path:a,reason:r&&r.reason||"aegis-sandbox-host probe failed",probed:!0}}function wrap(e,n,t={}){const{host:o,workspace:a,argv:r=[],cwd:s}=t;if(!o)return{ok:!1,reason:"no aegis-sandbox-host binary"};const i=e||{};if("off"===i.mode)return{ok:!1,reason:"sandbox disabled by policy"};const p=a?path.resolve(a):null,c=i.fileSystem&&Array.isArray(i.fileSystem.entries)?i.fileSystem.entries:[];for(const e of c){if(!e||"write"!==e.access)continue;const n=e.path;if(n&&"special"===n.type&&n.value&&"root"===n.value.kind)return{ok:!1,policyFault:!0,reason:"policy grants write to the filesystem root, which a sandbox cannot honour"}}const l=[];let d=!1;for(const e of c){if(!e||"write"!==e.access)continue;const n=e.path;n&&("special"!==n.type?"path"===n.type&&"string"==typeof n.path&&n.path&&l.push(path.resolve(n.path)):n.value&&"slash_tmp"===n.value.kind&&(d=!0))}p&&"workspace-write"===i.mode&&!l.includes(p)&&l.push(p);const u=[o];u.push("--mode",String(i.mode)),u.push("--network","open"===i.network?"open":"restricted"),d&&u.push("--grant-tmp");for(const e of l)u.push("--grant-write",e);s&&u.push("--cwd",String(s)),u.push("--");for(const e of r)u.push(String(e));return u.push(String(n)),{ok:!0,argv:u,guarantee:"capability",pending:!0}}function describe(e,n){return e&&e.available?`sandbox: ${n&&n.mode||"workspace-write"} via AppContainer — ${"open"===(n&&n.network)?"network open":"network restricted"}`:`sandbox: OFF — ${e&&e.reason||"unavailable"} (commands run with full user access)`}module.exports={name:"win32",mechanism:"appcontainer",guarantee:"capability",implemented:!1,VENDOR_REL:VENDOR_REL,helperCandidates:helperCandidates,findHelper:findHelper,detect:detect,wrap:wrap,describe:describe};
@@ -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{spawnSync:spawnSync}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),VENDOR_REL=path.join("vendor","sandbox");function candidates(e,n=process.env){const t=[];if(e){const n=/app\.asar[\\/]?$/.test(String(e))?String(e).replace(/app\.asar[\\/]?$/,"app.asar.unpacked"):String(e).replace(/app\.asar([\\/])/,"app.asar.unpacked$1");n!==e&&(t.push(path.join(n,VENDOR_REL,`${process.arch}-linux`,"bwrap")),t.push(path.join(n,VENDOR_REL,"linux","bwrap"))),t.push(path.join(e,VENDOR_REL,`${process.arch}-linux`,"bwrap")),t.push(path.join(e,VENDOR_REL,"linux","bwrap"))}return n&&n.AEGIS_SANDBOX_BWRAP&&t.push(String(n.AEGIS_SANDBOX_BWRAP)),t.push("/usr/bin/bwrap","/bin/bwrap","/usr/local/bin/bwrap"),t}function findBwrap(e,n){for(const t of candidates(e,n))try{if(fs.statSync(t).isFile())return fs.accessSync(t,fs.constants.X_OK),t}catch{}return null}function detect({appDir:e,env:n=process.env,platform:t=process.platform,probe:r}={}){if("linux"!==t)return{available:!1,path:null,reason:`no linux mechanism on ${t}`,probed:!1};const a=findBwrap(e,n);if(!a)return{available:!1,path:null,reason:"bwrap not found",probed:!1};const s=("function"==typeof r?r:defaultProbe)(a);return s&&s.ok?{available:!0,path:a,reason:null,probed:!0,mechanism:"bwrap"}:{available:!1,path:a,reason:s&&s.reason||"bwrap probe failed (unprivileged user namespaces unavailable?)",probed:!0}}function defaultProbe(e){try{const n=spawnSync(e,["--ro-bind","/","/","--dev","/dev","--","/bin/true"],{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"]});return n.error?{ok:!1,reason:`bwrap probe error: ${n.error.message}`}:0!==n.status?{ok:!1,reason:String(n.stderr||"").trim().split("\n")[0]||`bwrap probe exited ${n.status}`}:{ok:!0}}catch(e){return{ok:!1,reason:`bwrap probe threw: ${e.message}`}}}function isSpecial(e,n){const t=e&&e.path;return Boolean(t&&"special"===t.type&&t.value&&t.value.kind===n)}function entryPath(e){const n=e&&e.path;return n&&"path"===n.type&&"string"==typeof n.path&&n.path?n.path:null}function wrap(e,n,t={}){const{bwrap:r,workspace:a,argv:s=[],cwd:o}=t;if(!r)return{ok:!1,reason:"no bwrap binary"};const i=e||{};if("off"===i.mode)return{ok:!1,reason:"sandbox disabled by policy"};const p=a?path.resolve(a):null,c=[r,"--ro-bind","/","/","--dev","/dev","--proc","/proc"],u=i.fileSystem&&Array.isArray(i.fileSystem.entries)?i.fileSystem.entries:[];let l=!1;for(const e of u){if("write"!==e.access)continue;if(isSpecial(e,"root")){l=!0;continue}if(isSpecial(e,"slash_tmp")){c.push("--bind","/tmp","/tmp");continue}const n=entryPath(e);if(!n)continue;let t=!1;try{fs.statSync(n),t=!0}catch{t=!1}if(!t){if("skip"===e.missingPathBehavior)continue;return{ok:!1,policyFault:!0,reason:`sandbox path does not exist: ${n}`}}c.push("--bind",n,n)}if(l)return{ok:!1,policyFault:!0,reason:"policy grants write to the filesystem root, which a sandbox cannot honour"};if(p&&"workspace-write"===i.mode){let e=!1;for(const n of u){const t=entryPath(n);"write"===n.access&&t&&path.resolve(t)===p&&(e=!0)}e||c.push("--bind",p,p)}for(const e of u){if("read"!==e.access)continue;const n=entryPath(e);if(n){try{fs.statSync(n)}catch{if("skip"===e.missingPathBehavior)continue;return{ok:!1,policyFault:!0,reason:`sandbox path does not exist: ${n}`}}c.push("--ro-bind",n,n)}}const d=i.fileSystem&&Array.isArray(i.fileSystem.denies)?i.fileSystem.denies:[];for(const e of d){const n=e&&e.path;if(!n)continue;let t=null;try{t=fs.statSync(n)}catch{return{ok:!1,policyFault:!0,reason:`sandbox deny path does not exist: ${n}`}}if(!t.isDirectory())return{ok:!1,policyFault:!0,reason:`sandbox deny must name a directory, not a file: ${n}`};c.push("--tmpfs",n)}"restricted"===i.network&&c.push("--unshare-net"),c.push("--die-with-parent","--new-session"),o&&c.push("--chdir",o),c.push("--");for(const e of s)c.push(String(e));return c.push(String(n)),{ok:!0,argv:c,policy:i,guarantee:"capability"}}function describe(e,n){return e&&e.available?`sandbox: ${n&&n.mode||"workspace-write"} via bwrap — ${"open"===(n&&n.network)?"network open":"network restricted"}`:`sandbox: OFF — ${e&&e.reason||"unavailable"} (commands run with full user access)`}module.exports={name:"linux",mechanism:"bwrap",guarantee:"capability",implemented:!0,VENDOR_REL:VENDOR_REL,candidates:candidates,findBwrap:findBwrap,detect:detect,defaultProbe:defaultProbe,wrap:wrap,describe:describe,isSpecial:isSpecial,entryPath:entryPath};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path");function candidates(e=process.env){const t=[];return e&&e.AEGIS_SANDBOX_SEATBELT&&t.push(String(e.AEGIS_SANDBOX_SEATBELT)),t.push("/usr/bin/sandbox-exec"),t}function findSeatbelt(e){for(const t of candidates(e))try{if(fs.statSync(t).isFile())return fs.accessSync(t,fs.constants.X_OK),t}catch{}return null}function detect({env:e=process.env,platform:t=process.platform,probe:n}={}){if("darwin"!==t)return{available:!1,path:null,reason:`no darwin mechanism on ${t}`,probed:!1};const o=findSeatbelt(e);if(!o)return{available:!1,path:null,reason:"sandbox-exec not found",probed:!1};const r=("function"==typeof n?n:defaultProbe)(o);return r&&r.ok?{available:!0,path:o,reason:null,probed:!0,mechanism:"seatbelt"}:{available:!1,path:o,reason:r&&r.reason||"sandbox-exec probe failed",probed:!0}}function defaultProbe(e){const{spawnSync:t}=require("node:child_process");try{const n=t(e,["-p","(version 1)(allow default)","/usr/bin/true"],{timeout:5e3,encoding:"utf8",stdio:["ignore","pipe","pipe"]});return n.error?{ok:!1,reason:`sandbox-exec probe error: ${n.error.message}`}:0!==n.status?{ok:!1,reason:String(n.stderr||"").trim().split("\n")[0]||`sandbox-exec probe exited ${n.status}`}:{ok:!0}}catch(e){return{ok:!1,reason:`sandbox-exec probe threw: ${e.message}`}}}function quotePath(e){const t=String(e);return/["\\\n\r]/.test(t)?null:`(subpath "${t}")`}function quoteLiteral(e){const t=String(e);return/["\\\n\r]/.test(t)?null:`(literal "${t}")`}const SYSTEM_READONLY=Object.freeze(["/System","/usr","/Library","/private/etc","/bin","/sbin"]),DEVICE_WRITES=Object.freeze('(allow file-write* (literal "/dev/null") (literal "/dev/stdout") (literal "/dev/stderr") (literal "/dev/zero") (literal "/dev/dtracehelper"))');function ps(e,t){return e===t||e.startsWith(t.endsWith(path.sep)?t:t+path.sep)}function wrap(e,t,n={}){const{seatbelt:o,workspace:r,argv:a=[]}=n;if(!o)return{ok:!1,reason:"no sandbox-exec binary"};const s=e||{};if("off"===s.mode)return{ok:!1,reason:"sandbox disabled by policy"};const i=r?path.resolve(r):null,l=["(version 1)","(allow default)"];"restricted"===s.network&&l.push("(deny network*)");const c=s.fileSystem&&Array.isArray(s.fileSystem.entries)?s.fileSystem.entries:[];for(const e of c){if(!e||"write"!==e.access)continue;const t=e.path;if(t&&"special"===t.type&&t.value&&"root"===t.value.kind)return{ok:!1,policyFault:!0,reason:"policy grants write to the filesystem root, which a sandbox cannot honour"}}if("read-only"===s.mode)l.push("(deny file-write*)"),l.push(DEVICE_WRITES),l.push("(allow mach-lookup)");else{l.push("(deny file-write*)"),l.push(DEVICE_WRITES);const e=[];for(const t of c){if(!t||"write"!==t.access)continue;const n=t.path;if(!n)continue;if("special"===n.type){"slash_tmp"===(n.value&&n.value.kind)&&e.push("/tmp","/private/tmp");continue}if("path"!==n.type||"string"!=typeof n.path||!n.path)continue;const o=path.resolve(n.path);if("skip"===t.missingPathBehavior)try{fs.statSync(o)}catch{continue}const r=quotePath(o),a=quoteLiteral(o);if(!r||!a)return{ok:!1,policyFault:!0,reason:`sandbox path cannot be expressed in a profile: ${o}`};e.push(r,a)}if(e.length&&l.push(`(allow file-write* ${e.join(" ")})`),i){let e=!1;for(const t of c)t&&"write"===t.access&&t.path&&"path"===t.path.type&&path.resolve(t.path.path)===i&&(e=!0);if(!e){const e=quotePath(i),t=quoteLiteral(i);if(!e||!t)return{ok:!1,policyFault:!0,reason:`workspace path cannot be expressed in a profile: ${i}`};l.push(`(allow file-write* ${e} ${t})`)}}const t=process.env.HOME||"",n=t?path.resolve(t):"",o=Boolean(i&&n&&ps(i,n));if(n&&n!==i&&!o){const e=quotePath(path.resolve(t));e&&l.push(`(deny file-write* ${e})`)}for(const e of SYSTEM_READONLY){const t=quotePath(e);t&&l.push(`(deny file-write* ${t})`)}l.push("(allow mach-lookup)")}const p=l.join("\n"),u=[o,"-p",p];for(const e of a)u.push(String(e));return u.push(String(t)),{ok:!0,argv:u,profile:p,guarantee:"blacklist"}}function describe(e,t){return e&&e.available?`sandbox: ${t&&t.mode||"workspace-write"} via Seatbelt — ${"open"===(t&&t.network)?"network open":"network restricted"} (strong blacklist: system trees and $HOME outside the workspace are write-denied; not a capability grant)`:`sandbox: OFF — ${e&&e.reason||"unavailable"} (commands run with full user access)`}module.exports={name:"darwin",mechanism:"seatbelt",guarantee:"blacklist",candidates:candidates,findSeatbelt:findSeatbelt,detect:detect,wrap:wrap,describe:describe,quotePath:quotePath,quoteLiteral:quoteLiteral,SYSTEM_READONLY:SYSTEM_READONLY,DEVICE_WRITES:DEVICE_WRITES,ps:ps};
@@ -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"),MODES=Object.freeze(["off","read-only","workspace-write","managed"]),VENDOR_REL=path.join("vendor","sandbox");function mechanism(e){return"linux"===e?require("./sandbox-bwrap.js"):"darwin"===e?require("./sandbox-seatbelt.js"):"win32"===e?require("./sandbox-appcontainer.js"):null}function supported(e=process.platform){const t=mechanism(e);return Boolean(t&&!1!==t.implemented)}function detect({appDir:e,env:t=process.env,platform:a=process.platform,probe:n}={}){const r=mechanism(a);return r?r.detect({appDir:e,env:t,platform:a,probe:n}):{available:!1,path:null,reason:`no sandbox implementation for ${a} yet`,probed:!1}}const probeCache=new Map;function cacheKey(e,t){return`${t}\0${e?path.resolve(String(e)):""}`}function detectCached({appDir:e,env:t=process.env,platform:a=process.platform,probe:n}={}){if("function"==typeof n)return detect({appDir:e,env:t,platform:a,probe:n});const r=cacheKey(e,a),o=probeCache.get(r);if(o&&o.env===t){let e=!1;try{e=Boolean(o.path)&&fs.statSync(o.path).mtimeMs===o.mtimeMs}catch{e=!o.path}if(e)return{...o.state,cached:!0};probeCache.delete(r)}const s=detect({appDir:e,env:t,platform:a});let i=null;if(s.path)try{i=fs.statSync(s.path).mtimeMs}catch{i=null}return probeCache.set(r,{state:s,path:s.path,mtimeMs:i,env:t}),s}function invalidateProbe(e,t=process.platform){return void 0===e?probeCache.clear():probeCache.delete(cacheKey(e,t))}function defaultPolicy(e){const t=e?path.resolve(e):null,a=[{path:{type:"special",value:{kind:"root"}},access:"read"}];return t&&a.push({path:{type:"path",path:t},access:"write"}),a.push({path:{type:"special",value:{kind:"slash_tmp"}},access:"write"}),t&&a.push({path:{type:"path",path:path.join(t,".git")},access:"read",missingPathBehavior:"skip"}),{mode:"workspace-write",fileSystem:{entries:a,denies:[]},network:"restricted"}}function autoGrants(e,t={}){const a=[],n=new Set,r=(e,t)=>{if(!e)return;let r;try{r=path.resolve(String(e))}catch{return}if(r===path.parse(r).root)return;const o=`${t}:${r}`;n.has(o)||(n.add(o),a.push({path:{type:"path",path:r},access:t,missingPathBehavior:"skip"}))};r(e,"write"),r(t.gitRoot||e,"write");for(const e of Array.isArray(t.addDirs)?t.addDirs:[])r(e,"write");const o=t.home||null;return o&&(r(path.join(o,".aegiscode"),"read"),r(path.join(o,".ollama"),"read")),r("/tmp","write"),a}function entryPath(e){const t=e&&e.path;return t&&"path"===t.type&&"string"==typeof t.path&&t.path?t.path:null}function isSpecial(e,t){const a=e&&e.path;return Boolean(a&&"special"===a.type&&a.value&&a.value.kind===t)}function normalize(e,t){if(!e||"object"!=typeof e)return defaultPolicy(t);const a=MODES.includes(e.mode)?e.mode:"workspace-write";if("off"===a)return{mode:"off",fileSystem:{entries:[]},network:"open"};const n=e.fileSystem&&Array.isArray(e.fileSystem.entries)?e.fileSystem.entries:null,r=defaultPolicy(t),o="read-only"===a,s=[],i=[];for(const e of n||r.fileSystem.entries){if(o&&e&&"write"===e.access)continue;if(!e||"object"!=typeof e)continue;if("none"===e.access){const t=e.path;if(!t||"object"!=typeof t||"path"!==t.type)continue;if("string"!=typeof t.path||!t.path)continue;i.push({path:path.resolve(t.path)});continue}const t="write"===e.access?"write":"read"===e.access?"read":null;if(!t)continue;const a=e.path;if(!a||"object"!=typeof a)continue;if("path"!==a.type&&"special"!==a.type)continue;if("path"===a.type&&("string"!=typeof a.path||!a.path))continue;const n={path:a,access:t};"skip"===e.missingPathBehavior&&(n.missingPathBehavior="skip"),s.push(n)}return{mode:a,fileSystem:{entries:s,denies:i},network:"open"===e.network?"open":"restricted"}}function wrap(e,t,a={}){const n=a.platform||process.platform,r=mechanism(n);if(!r)return{ok:!1,reason:`no sandbox implementation for ${n}`};const o=normalize(e,a.workspace);if("off"===o.mode)return{ok:!1,reason:"sandbox disabled by policy"};const s=a.bwrap||a.seatbelt||a.host;return r.wrap(o,t,{...a,bwrap:s,seatbelt:s,host:s,policy:o})}function spawnPlan(e,t,a,n={}){const r=Boolean(e&&e.strict),o=e&&e.policy?e.policy:null;if(!e||!o||"off"===o.mode)return{ok:!0,file:t,args:a.slice(),degraded:null};const s=e.state||detect({appDir:e.appDir,env:e.env,platform:e.platform});if(!s.available)return r?{ok:!1,reason:describe(s,o)}:{ok:!0,file:t,args:a.slice(),degraded:describe(s,o)};const i=wrap(o,t,{bwrap:s.path||e.bwrap,workspace:e.workspace,cwd:n.cwd,platform:e.platform});if(!i.ok)return i.policyFault?{ok:!1,reason:`sandbox policy cannot be honoured: ${i.reason}`}:r?{ok:!1,reason:i.reason}:{ok:!0,file:t,args:a.slice(),degraded:`sandbox policy not enforceable: ${i.reason}`};const c=i.argv.slice(0,i.argv.length-1).concat([t],a);return{ok:!0,file:c[0],args:c.slice(1),degraded:null}}function describe(e,t,a=process.platform){const n=mechanism(a);return n&&"function"==typeof n.describe?n.describe(e,t):e&&e.available?`sandbox: ${t&&t.mode||"workspace-write"} — mechanism unknown`:`sandbox: OFF — ${e&&e.reason||"unavailable"} (commands run with full user access)`}module.exports={MODES:MODES,VENDOR_REL:VENDOR_REL,supported:supported,mechanism:mechanism,detect:detect,detectCached:detectCached,invalidateProbe:invalidateProbe,defaultPolicy:defaultPolicy,autoGrants:autoGrants,normalize:normalize,wrap:wrap,spawnPlan:spawnPlan,describe:describe,entryPath:entryPath,isSpecial:isSpecial};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{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};
3
+ "use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto"),integrity=require("./integrity.js"),sandbox=require("./sandbox.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 shellSandbox(e){const s=e&&"object"==typeof e?e:{},t=s.sandbox;return t&&"object"==typeof t?{policy:t.policy||null,state:t.state||null,strict:!0===t.strict,workspace:t.workspace,appDir:t.appDir,env:t.env||s.env,bwrap:t.bwrap}:null}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=sandbox.spawnPlan(shellSandbox(n),l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd()});if(!h.ok)return void i({content:`exec: ${h.reason}`,isError:!0});const a=spawn(h.file,h.args,{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let d="",c="";a.stdout.on("data",(e=>{d=appendBounded(d,e.toString())})),a.stderr.on("data",(e=>{c=appendBounded(c,e.toString())})),a.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),a.on("close",(e=>{const s=`${d}${c?`\n${c}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s,sandbox:t}={}){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.sandboxError=null,this.sandboxDegraded=null,this._sandboxNoted=!1,this.shellOptions=s&&"object"==typeof s?{...s}:{},t&&!this.shellOptions.sandbox&&(this.shellOptions.sandbox=t),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{const t="powershell"===this.shell.kind?["-NoLogo","-NoProfile","-NonInteractive","-Command","-"]:[],n=sandbox.spawnPlan(shellSandbox(this.shellOptions),this.shell.cmd,t,{cwd:e||process.cwd()});if(!n.ok)return this.sandboxError=n.reason,void(this.alive=!1);this.sandboxDegraded=n.degraded||null,this.child=spawn(n.file,n.args,{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});if(this.sandboxError)return Promise.resolve({content:`exec: ${this.sandboxError}`,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(this._noteSandboxDegraded(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 a;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} )`),a=`{ ${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 }";a=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,a+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(a)}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){let t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this.sandboxDegraded&&!this._sandboxNoted){this._sandboxNoted=!0;const e=`[sandbox_unavailable] ran UNCONFINED: ${this.sandboxDegraded}`;t={...t,content:`${e}\n${t.content||""}`}}if(!this._degradedNoted){this._degradedNoted=!0;const e=`[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`;t={...t,content:`${e}\n${t.content||""}`}}return t}_noteSandboxDegraded(e){const s=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(!this.sandboxDegraded||this._sandboxNoted)return s;this._sandboxNoted=!0;const t=`[sandbox_unavailable] ran UNCONFINED: ${this.sandboxDegraded}`;return{...s,content:`${t}\n${s.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};