aegisone 1.0.38 → 1.0.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSING.md +186 -0
- package/README.md +2 -2
- package/bin/aegis.js +1 -1
- package/package.json +3 -2
- package/scripts/predist.mjs +1 -1
- package/src/child.js +1 -1
- package/src/permissions.js +1 -1
- package/vendor/cli/package.json +4 -2
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +3 -1
- package/vendor/cli/src/config.js +1 -1
- package/vendor/cli/src/engine.js +1 -1
- package/vendor/cli/src/history.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/src/overlays.js +1 -1
- package/vendor/cli/src/panels.js +1 -1
- package/vendor/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/cli/vendor/client/credits.js +45 -0
- package/vendor/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/cli/vendor/client/naming.js +1 -1
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/session-search.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/cli/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/cli/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +774 -37
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/cli/vendor/mcp/admission.js +3 -0
- package/vendor/cli/vendor/mcp/server.js +1 -1
- package/vendor/cli/vendor/one/src/child.js +1 -1
- package/vendor/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/bin/aegis.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/lib/sync/memory-store.js +3 -0
- package/vendor/desktop/main.js +774 -37
- package/vendor/desktop/package.json +20 -7
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +5 -1
- package/vendor/desktop/renderer/index.html +221 -5
- package/vendor/desktop/renderer/provider-mark.js +1 -1
- package/vendor/desktop/renderer/provider-toolbar.js +1 -1
- package/vendor/desktop/renderer/providers.js +1 -1
- package/vendor/desktop/renderer/style.css +223 -6
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/package.json +3 -2
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -1
- package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -2
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/sandbox/provenance.json +20 -0
- package/vendor/desktop/vendor/sandbox/x64-linux/bwrap +0 -0
- 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";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({"nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
|
|
3
|
+
"use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({nexus:"auto-routing id: aegis1 picks the tier and settles the charge","nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");function dataDir(e={}){if(e.dir)return e.dir;const r=e.env||process.env;if(r.AEGISCODE_HOME)return r.AEGISCODE_HOME;const n=e.home||(()=>{try{return os.homedir()}catch{return r.HOME||r.USERPROFILE||""}})();return path.join(n,".aegiscode")}function registryPath(e={}){return path.join(dataDir(e),"harnesses.json")}function harnessName(e){const r=e&&(e.name||e.title);return String(null==r?"":r).trim().toLowerCase().replace(/\s+/g,"-").replace(/_/g,"-").replace(/[^a-z0-9.-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function deniedHarnesses(e={}){const r=e.env||process.env;return String(r.AEGISCODE_HARNESS_DENY||"").split(/[\s,]+/).map((e=>e.trim().toLowerCase())).filter(Boolean)}function admit(e,r={}){const n=harnessName(e),s=deniedHarnesses(r);return s.includes(n)||s.includes("*")?{ok:!1,name:n,reason:`AEGIS: harness "${n}" is denied by AEGISCODE_HARNESS_DENY. Unset that variable (or remove this name from it) to admit it.`}:{ok:!0,name:n,reason:""}}function read(e={}){const r=registryPath(e);try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return e&&"object"==typeof e&&e&&"object"==typeof e.harnesses&&e.harnesses?e.harnesses:{}}catch{return{}}}function record(e,r={}){const n=harnessName(e),s=(new Date).toISOString();try{const t=read(r),a=t[n]||{},i=e&&e.version?String(e.version):a.version||null;t[n]={firstSeen:a.firstSeen||s,lastSeen:s,calls:(Number(a.calls)||0)+1,version:i};const o=registryPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const c=`${o}.${process.pid}.tmp`;return fs.writeFileSync(c,JSON.stringify({harnesses:t},null,2),{mode:384}),fs.renameSync(c,o),{ok:!0,name:n}}catch{return{ok:!1,name:n}}}module.exports={dataDir:dataDir,registryPath:registryPath,harnessName:harnessName,deniedHarnesses:deniedHarnesses,admit:admit,read:read,record:record};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
"use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:
|
|
4
|
+
"use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js"),admission=require("./admission.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let caller={ok:!0,name:"unknown",reason:""},pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:r}=e,o=null==t;try{switch(i){case"initialize":{const e=r&&r.clientInfo||null;return caller=admission.admit(e),caller.ok?admission.record(e):process.stderr.write(`${caller.reason}\n`),void reply(t,{protocolVersion:r&&r.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}})}case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(o||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{if(!caller.ok)return void reply(t,{content:[{type:"text",text:caller.reason}],isError:!0});const i=r&&r.name,o=TOOLS[i];if(!o)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${i}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await o.run(r&&r.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(o||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){o||replyError(t,-32603,e.message)}}let buffer="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally((()=>{pending--,maybeExit()}))}})),process.stdin.on("end",(()=>{stdinClosed=!0,maybeExit()}));
|
|
@@ -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 FLAGS=Object.freeze({headlessSkip:"--dangerously-skip-permissions",interactiveSkip:"--allow-dangerously-skip-permissions",permissionMode:"--permission-mode",allowedTools:"--allowedTools",disallowedTools:"--disallowedTools",print:"-p",outputFormat:"--output-format",model:"--model",sessionId:"--session-id",resume:"--resume",addDir:"--add-dir"});function addDirArgs(e){const s=[];for(const o of unique(e))s.push(`${FLAGS.addDir}=${o}`);return s}const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DEFAULT_OUTPUT_FORMAT="stream-json";function unique(e){const s=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const e=String(i).trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}function claudeArgv(e={}){const s=e.posture;if(!s||"object"!=typeof s)throw new Error("claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)");const o=s.childKind,i="interactive"!==o,{PERMISSION_MODES:r}=require("./permissions.js"),n=void 0!==e.permissionMode&&null!==e.permissionMode
|
|
3
|
+
"use strict";const FLAGS=Object.freeze({headlessSkip:"--dangerously-skip-permissions",interactiveSkip:"--allow-dangerously-skip-permissions",permissionMode:"--permission-mode",allowedTools:"--allowedTools",disallowedTools:"--disallowedTools",print:"-p",outputFormat:"--output-format",model:"--model",sessionId:"--session-id",resume:"--resume",inputFormat:"--input-format",permissionPromptTool:"--permission-prompt-tool",addDir:"--add-dir"});function addDirArgs(e){const s=[];for(const o of unique(e))s.push(`${FLAGS.addDir}=${o}`);return s}const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DEFAULT_OUTPUT_FORMAT="stream-json";function unique(e){const s=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const e=String(i).trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}function claudeArgv(e={}){const s=e.posture;if(!s||"object"!=typeof s)throw new Error("claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)");const o=s.childKind,i="interactive"!==o,{PERMISSION_MODES:r}=require("./permissions.js"),n=s.child&&"string"==typeof s.child.permissionMode?s.child.permissionMode:null,d=void 0!==e.permissionMode&&null!==e.permissionMode?String(e.permissionMode):null,t=null!==d||null!==n,l=null!==d?d:n;if(t&&!r.includes(l))throw new Error(`--permission-mode ${JSON.stringify(l)} is not one of ${r.join("|")} — refusing to pass (or to silently drop) a mode the child does not accept.`);const a=s.rules||{},p=unique(a.allow),u=unique(a.deny),c=unique(a.ask),m=e.resumeSessionId?String(e.resumeSessionId).trim():"",h=e.sessionId?String(e.sessionId).trim():"",g=m||null,f=!g&&h?h:null;for(const[e,s]of[["resumeSessionId",g],["sessionId",f]])if(s&&!UUID_RE.test(s))throw new Error(`${e} ${JSON.stringify(s)} is not a UUID — refusing to pass it to --resume/--session-id, which the child rejects after the spawn (turning a continuity bug into an opaque failed turn).`);const S=!0===e.askBridge&&!(s.child&&s.child.skip),A=[];i&&A.push(FLAGS.print,FLAGS.outputFormat,String(e.outputFormat||"stream-json")),e.model&&A.push(FLAGS.model,String(e.model));const F=addDirArgs(e.addDir);A.push(...F),p.length&&A.push(FLAGS.allowedTools,p.join(",")),u.length&&A.push(FLAGS.disallowedTools,u.join(",")),t&&A.push(FLAGS.permissionMode,l),s.child&&s.child.flag&&A.push(s.child.flag),S&&A.push(FLAGS.inputFormat,"stream-json",FLAGS.permissionPromptTool,"stdio"),g?A.push(FLAGS.resume,g):f&&A.push(FLAGS.sessionId,f),Array.isArray(e.extra)&&A.push(...e.extra.map(String)),S||void 0===e.prompt||null===e.prompt||A.push(String(e.prompt));const w=Object.freeze({kind:o,permissionMode:l,permissionModePassed:t,permissionModeSource:t?null!==d?"descriptor":"posture":null,permissionModeDropped:s&&s.permissionModeDropped||null,skip:Boolean(s.child&&s.child.skip),skipFlag:s.child&&s.child.flag||null,allowedTools:Object.freeze(p),disallowedTools:Object.freeze(u),unmappedAsk:Object.freeze(c),addDir:Object.freeze(F.map((e=>e.slice(FLAGS.addDir.length+1)))),resumeSessionId:g,sessionId:f,askBridge:S,argv:Object.freeze(A.slice())});return{argv:w.argv,record:w}}function childRecordLine(e){if(!e||"object"!=typeof e)return null;const s=e.permissionModePassed?`${FLAGS.permissionMode}=${e.permissionMode}`:e.permissionModeDropped?`no --permission-mode (asked for one, dropped: ${e.permissionModeDropped})`:"no --permission-mode (none was set)";return`aegis: claude child [${e.kind}] ${e.skipFlag||"no permission flag"} · ${s} · allowedTools=[${e.allowedTools.join(", ")}] disallowedTools=[${e.disallowedTools.join(", ")}]`+(e.unmappedAsk.length?` (ask rules recorded, unmapped: ${e.unmappedAsk.join(", ")})`:"")+(e.addDir&&e.addDir.length?` · addDir=[${e.addDir.join(", ")}]`:"")+(e.resumeSessionId?` · resumed session ${e.resumeSessionId}`:e.sessionId?` · new session ${e.sessionId}`:" · no session id (each turn is a new conversation)")+(e.askBridge?" · ask bridge (the child can raise approval cards)":" · no ask bridge (headless: unapproved tools auto-deny)")}module.exports={FLAGS:FLAGS,DEFAULT_OUTPUT_FORMAT:"stream-json",claudeArgv:claudeArgv,addDirArgs:addDirArgs,childRecordLine:childRecordLine};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const path=require("node:path"),CHILD_KINDS=Object.freeze({HEADLESS:"headless",INTERACTIVE:"interactive"}),CONFIGURABLE_CLASSES=Object.freeze(["exec","writeFile","editFile"]),SKIP_FLAG="--dangerously-skip-permissions",FROZEN_CLASSES=Object.freeze(["write","shell","network","offDevice"]),PERMISSION_MODES=Object.freeze(["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]);let cachedEvaluator=null,cachedConfig=null;function loadEvaluator(e){if(e)return e;if(cachedEvaluator)return cachedEvaluator;const o=[path.join(__dirname,"..","..","cli","src","permissions.js"),path.join(__dirname,"..","vendor","cli","src","permissions.js"),path.join(__dirname,"..","..","..","src","permissions.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.evalPermission&&"function"==typeof o.resolveSkip)return cachedEvaluator=o,o}catch{}throw new Error("aegis: the one rule evaluator (cli/src/permissions.js) is missing from this install — refusing to resolve a permission posture from a second, unshared rule engine.")}function loadConfigStore(e){if(e)return e;if(cachedConfig)return cachedConfig;const o=[path.join(__dirname,"..","..","cli","src","config.js"),path.join(__dirname,"..","vendor","cli","src","config.js"),path.join(__dirname,"..","..","..","src","config.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.confirmPosture)return cachedConfig=o,o}catch{}return null}function storedPermissionFacts(e={}){const o=loadConfigStore(e.config);if(!o)return{confirmationsOn:void 0,rules:void 0,source:"unavailable"};try{const e=o.confirmPosture();let
|
|
3
|
+
"use strict";const path=require("node:path"),CHILD_KINDS=Object.freeze({HEADLESS:"headless",INTERACTIVE:"interactive"}),CONFIGURABLE_CLASSES=Object.freeze(["exec","writeFile","editFile"]),SKIP_FLAG="--dangerously-skip-permissions",FROZEN_CLASSES=Object.freeze(["write","shell","network","offDevice"]),PERMISSION_MODES=Object.freeze(["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]);let cachedEvaluator=null,cachedConfig=null;function loadEvaluator(e){if(e)return e;if(cachedEvaluator)return cachedEvaluator;const o=[path.join(__dirname,"..","..","cli","src","permissions.js"),path.join(__dirname,"..","vendor","cli","src","permissions.js"),path.join(__dirname,"..","..","..","src","permissions.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.evalPermission&&"function"==typeof o.resolveSkip)return cachedEvaluator=o,o}catch{}throw new Error("aegis: the one rule evaluator (cli/src/permissions.js) is missing from this install — refusing to resolve a permission posture from a second, unshared rule engine.")}function loadConfigStore(e){if(e)return e;if(cachedConfig)return cachedConfig;const o=[path.join(__dirname,"..","..","cli","src","config.js"),path.join(__dirname,"..","vendor","cli","src","config.js"),path.join(__dirname,"..","..","..","src","config.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.confirmPosture)return cachedConfig=o,o}catch{}return null}function storedPermissionFacts(e={}){const o=loadConfigStore(e.config);if(!o)return{confirmationsOn:void 0,rules:void 0,permissionMode:null,source:"unavailable"};try{const e=o.confirmPosture();let s;try{s=o.loadPermissions()}catch{s=void 0}let i=null;try{if("function"==typeof o.permissionMode){const e=o.permissionMode();"string"==typeof e&&PERMISSION_MODES.includes(e)&&(i=e)}}catch{i=null}return{confirmationsOn:e&&"boolean"==typeof e.enabled?e.enabled:void 0,rules:s,permissionMode:i,source:e&&e.source||"unavailable"}}catch{return{confirmationsOn:void 0,rules:void 0,permissionMode:null,source:"unavailable"}}}function normalizeRules(e){const o=e&&"object"==typeof e?e:{},s=e=>Array.isArray(e)?e.map(String):[];return Object.freeze({defaultMode:"allow"===o.defaultMode||"deny"===o.defaultMode?o.defaultMode:"ask",allow:Object.freeze(s(o.allow)),deny:Object.freeze(s(o.deny)),ask:Object.freeze(s(o.ask)),explicitAsk:!0===o.explicitAsk||"ask"===o.defaultMode})}function resolvePosture(e={},o={}){const s=loadEvaluator(o.evaluator),i=normalizeRules(e.rules),n=!0===e.interactive,r=e.childKind===CHILD_KINDS.INTERACTIVE?CHILD_KINDS.INTERACTIVE:CHILD_KINDS.HEADLESS,t=s.resolveSkip({flag:!0===e.flag,env:e.env,interactive:n}),a=!1===e.gate,l=t.skip||a,c=t.skip?t.source:a?"posture":t.source,u="string"==typeof e.permissionMode?e.permissionMode:null,d=null!==u&&PERMISSION_MODES.includes(u),p=d&&!l?u:null,f=null!==u&&!p,S=r===CHILD_KINDS.INTERACTIVE;return Object.freeze({version:1,rules:i,interactive:n,childKind:r,skip:l,skipSource:c,skipFromFlag:t.skip,envVarSet:t.envSet,storedGate:void 0===e.gate||null===e.gate?null:Boolean(e.gate),permissionMode:p,permissionModeAsked:d?u:null,permissionModeDropped:f?l?"a skip is in effect (--dangerously-skip-permissions or the stored posture), and the child may not be given two permission policies":"not one of "+PERMISSION_MODES.join("|"):null,warned:t.warned,warning:t.warning||null,skipped:Object.freeze(l?CONFIGURABLE_CLASSES:[]),frozen:FROZEN_CLASSES,child:Object.freeze({kind:r,skip:l,permissionMode:p,flag:l?S?"--allow-dangerously-skip-permissions":"--dangerously-skip-permissions":null,why:l?S?"the interactive variant offers the bypass as an option (the child still asks; a human is there)":"the headless variant takes the bypass as a default, because no one can answer the child's prompt":"no skip was asked for, so no permission flag is passed to the child"})})}function gateFor(e,o,s,i={}){const n=loadEvaluator(i.evaluator),r=e&&e.rules?e.rules:normalizeRules({}),t=n.evalPermission(o,s,r);return"deny"===t?"deny":"allow"===t||e&&e.skip?"allow":"ask"}function skipReport(e){if(!e||!e.skip)return null;const o=e.child.flag?`; the ${e.child.kind} Claude child is passed ${e.child.flag}`:"";return`aegis: ${"posture"===e.skipSource?"automode (the stored confirmation posture both faces share)":"--dangerously-skip-permissions"} (via ${e.skipSource}) — skipping the configurable confirmation gates (${CONFIGURABLE_CLASSES.join(", ")})${o}. NOT skipped, and not reachable by any setting, flag or env var: the ÆGIS covenant pre-action assert and the ${FROZEN_CLASSES.join("|")} approvals (always 'ask'), plus any explicit deny rule.`}module.exports={CHILD_KINDS:CHILD_KINDS,CONFIGURABLE_CLASSES:CONFIGURABLE_CLASSES,FROZEN_CLASSES:FROZEN_CLASSES,PERMISSION_MODES:PERMISSION_MODES,SKIP_FLAG:SKIP_FLAG,loadEvaluator:loadEvaluator,loadConfigStore:loadConfigStore,storedPermissionFacts:storedPermissionFacts,normalizeRules:normalizeRules,resolvePosture:resolvePosture,gateFor:gateFor,skipReport:skipReport};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
"use strict";const path=require("node:path"),{spawn:spawn}=require("node:child_process"),appDir=path.join(__dirname,"..");(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(require(path.join(appDir,"package.json")).version),process.exit(0));
|
|
4
|
+
"use strict";const path=require("node:path"),{spawn:spawn}=require("node:child_process"),appDir=path.join(__dirname,"..");let electronPath;(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(require(path.join(appDir,"package.json")).version),process.exit(0));try{electronPath=require("electron")}catch(e){console.error("Failed to launch AEGIS Desktop: the electron runtime is not installed.\nIt ships as an optional dependency, so an install run with --omit=optional\n(or --no-optional, or a registry/proxy that skipped it) leaves it out.\nFix it with: npm i -g electron@^44 — or reinstall without that flag."),process.env.AEGIS_DEBUG&&console.error(e),process.exit(1)}const child=spawn(electronPath,[appDir,...process.argv.slice(2)],{stdio:"inherit"});child.on("error",(e=>{console.error("Failed to launch AEGIS Desktop:",e.message),process.exit(1)})),child.on("close",(e=>process.exit(null==e?0:e)));
|
|
@@ -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};
|
|
@@ -23,7 +23,16 @@
|
|
|
23
23
|
* sites, and the window that serves the renderer;
|
|
24
24
|
* - `lib/local/shell.js` the process that actually executes `exec`;
|
|
25
25
|
* - `lib/local/tools.js` the tool surface handed to the model;
|
|
26
|
-
* - `lib/local/exec-plan.js` the rule that decides what may run batched
|
|
26
|
+
* - `lib/local/exec-plan.js` the rule that decides what may run batched;
|
|
27
|
+
* - `lib/local/sandbox.js` the policy that decides what a batch can REACH.
|
|
28
|
+
*
|
|
29
|
+
* The last entry was added with ~/plan/agent-safety-plan.md §1b, and it earns its
|
|
30
|
+
* place differently from the other four: it is not a spawn site, it is what
|
|
31
|
+
* `shell.js` and `tools.js` each consult before spawning. Leaving it unpinned
|
|
32
|
+
* would have been the one hole the set could not see — replacing it with a
|
|
33
|
+
* stub that returns `{ ok: true, file: cmd, args }` disarms the outcome bound
|
|
34
|
+
* while every pinned byte stays byte-identical, so the interlock would report
|
|
35
|
+
* a clean tree. A unit that another unit trusts has to be a unit.
|
|
27
36
|
*
|
|
28
37
|
* A digest is taken over those files *as one closed set*, so changing any one
|
|
29
38
|
* changes the whole, and compared to a value sealed into this file. On a
|
|
@@ -87,6 +96,37 @@ const UNITS = Object.freeze([
|
|
|
87
96
|
{ id: 'd2', rel: Buffer.from('bGliL2xvY2FsL3NoZWxsLmpz', 'base64').toString('utf8') },
|
|
88
97
|
{ id: 'd3', rel: Buffer.from('bGliL2xvY2FsL3Rvb2xzLmpz', 'base64').toString('utf8') },
|
|
89
98
|
{ id: 'd4', rel: Buffer.from('bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==', 'base64').toString('utf8') },
|
|
99
|
+
{ id: 'd5', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3guanM=', 'base64').toString('utf8') },
|
|
100
|
+
// §2 of ~/plan/agent-safety-plan.md. Pinned for the same reason `sandbox.js`
|
|
101
|
+
// is: `main.js` requires it and it answers 'allow'/'deny' for the approval
|
|
102
|
+
// gate, so a stubbed copy that always returned `null` would leave the gate
|
|
103
|
+
// standing, but one that returned 'allow' would delete it — silently, and
|
|
104
|
+
// with the seal still green if this file were not itself a unit.
|
|
105
|
+
{ id: 'd6', rel: Buffer.from('bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=', 'base64').toString('utf8') },
|
|
106
|
+
// §3 of ~/plan/agent-safety-plan.md. The writer, and it earns the pin more
|
|
107
|
+
// sharply than the reader did: this module decides WHAT a durable allow is
|
|
108
|
+
// allowed to say. A stubbed copy that dropped the wildcard and blank-subject
|
|
109
|
+
// refusals would turn "Always allow this command" into "always allow every
|
|
110
|
+
// shell command" on the second click, while the gate, the reader and every
|
|
111
|
+
// other pinned byte stayed byte-identical and the seal reported a clean tree.
|
|
112
|
+
{ id: 'd7', rel: Buffer.from('bGliL2xvY2FsL3Blcm0td3JpdGUuanM=', 'base64').toString('utf8') },
|
|
113
|
+
// §4 of ~/plan/agent-safety-plan.md (the rules editor). Pinned because it is the
|
|
114
|
+
// WRITER of the rule list: a stubbed copy could add an allow for every tool
|
|
115
|
+
// the user did not ask for, or silently drop a `deny` while the card on screen
|
|
116
|
+
// still listed it. `perm-rules.js` (d6) only reads what this one stores, so
|
|
117
|
+
// pinning the reader and not the writer would seal the lock and leave the key
|
|
118
|
+
// in the door.
|
|
119
|
+
{ id: 'd8', rel: Buffer.from('bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=', 'base64').toString('utf8') },
|
|
120
|
+
// §1d/§1e of ~/plan/agent-safety-plan.md. The per-platform mechanisms behind
|
|
121
|
+
// `sandbox.js`. Pinned because `sandbox.js` is pinned: it now DELEGATES the
|
|
122
|
+
// argv construction and the availability answer to these files, so leaving
|
|
123
|
+
// them out of the set would move the trust rather than remove it. A stubbed
|
|
124
|
+
// `sandbox-seatbelt.js` returning `available: true` with `(allow default)` and
|
|
125
|
+
// no denies would report "sandbox: workspace-write via Seatbelt" while
|
|
126
|
+
// confining nothing — with every previously pinned byte identical.
|
|
127
|
+
{ id: 'd9', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=', 'base64').toString('utf8') },
|
|
128
|
+
{ id: 'd10', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz', 'base64').toString('utf8') },
|
|
129
|
+
{ id: 'd11', rel: Buffer.from('bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=', 'base64').toString('utf8') },
|
|
90
130
|
]);
|
|
91
131
|
|
|
92
132
|
/**
|
|
@@ -94,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
94
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
95
135
|
* after obfuscation), never by hand.
|
|
96
136
|
*/
|
|
97
|
-
const SEALED = '
|
|
137
|
+
const SEALED = '044aa104fa89c413b18393d8cca3c3574808a312b8d1195ac26bd367978ba237';
|
|
98
138
|
|
|
99
139
|
/**
|
|
100
140
|
* Ask the question. Never throws — a check that can break the program it is
|