aegis-desktop 1.0.16 → 1.0.17
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/lib/auto.js +1 -1
- package/lib/google-connect.js +1 -1
- package/lib/local/attachments.js +3 -0
- package/lib/local/claude-pro.js +1 -1
- package/lib/local/context.js +1 -1
- package/lib/local/engine.js +1 -1
- package/lib/local/exec-plan.js +3 -0
- package/lib/local/local.js +1 -1
- package/lib/local/prompt.js +1 -1
- package/lib/local/session-rounds.js +1 -1
- package/lib/local/shell.js +1 -1
- package/lib/local/spill.js +3 -0
- package/lib/local/tools.js +1 -1
- package/main.js +2 -2
- package/package.json +3 -2
- package/preload.js +2 -2
- package/renderer/app.js +1 -1
- package/renderer/budget.js +1 -1
- package/renderer/fingerprint.js +2 -2
- package/renderer/index.html +44 -4
- package/renderer/quick.html +4 -1
- package/renderer/quick.js +1 -1
- package/renderer/stream-policy.js +1 -1
- package/renderer/style.css +124 -0
- package/vendor/aegis.js +1 -1
- package/vendor/attest.js +1 -1
- package/vendor/byok-catalog.js +1 -1
- package/vendor/catalog-client.js +3 -0
- package/vendor/conversation-export.js +3 -0
- package/vendor/drive-upload.js +1 -1
- package/vendor/session-store.js +1 -1
package/lib/auto.js
CHANGED
|
@@ -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 AUTO_MINT_QUIET_DEFAULT_MS=9e4,AUTO_MINT_QUIET_MIN_MS=1e4,AUTO_MINT_QUIET_MAX_MS=36e5;function errorText(e){return e&&e.message||String(e)}function createAutoDrain({proceed:e,settings:t,queue:r,env:n=process.env,log:o=(()=>{}),setIntervalFn:i=setInterval,clearIntervalFn:u=clearInterval}={}){if("function"!=typeof e)throw new Error("createAutoDrain: a proceed() entry point is required");if(!t||"function"!=typeof t.getAutoDrain)throw new Error("createAutoDrain: the settings store is required");let s=null,a=!1,l=0,c=0,p=null,d=null;const f=e=>(p=e,o(e),e);function y(){return{...t.autoDrainState(),armed:Boolean(s),busy:a,ticks:l,drains:c,last:p,lastSkip:d}}function M(){const e=t.getAutoDrain();return e.enabled?(s&&e.intervalMs===s.__intervalMs||(A(),s=i((()=>{_()}),e.intervalMs),s.__intervalMs=e.intervalMs,s&&"function"==typeof s.unref&&s.unref(),o({type:"auto-drain-armed",intervalMs:e.intervalMs})),y()):(A(),y())}function A(){return s?(u(s),s=null,o({type:"auto-drain-disarmed"}),y()):y()}async function _(){if(l+=1,!t.getAutoDrain().enabled)return f({type:"skip",reason:"disabled"});if(a)return f({type:"skip",reason:"busy"});if(!r||"function"!=typeof r.loadQueue)return f({type:"skip",reason:"no queue access"});let o;try{o=r.loadQueue(n)}catch(e){return f({type:"error",phase:"read",error:errorText(e)})}if(!r.pendingCount(o))return f({type:"skip",reason:"empty"});try{const e=r.lockHolder(n);if(e&&e.pid&&e.pid!==process.pid&&("function"!=typeof r.isAlive||r.isAlive(e.pid)))return f({type:"skip",reason:"locked",holder:e})}catch{}a=!0;try{const t=await e();return t&&t.locked?f({type:"skip",reason:"locked",holder:t.holder||null}):(c+=1,f({type:"drain",ok:!(t&&!1===t.ok),ran:t&&t.ran||[],reason:t&&t.reason||null}))}catch(e){return f({type:"error",phase:"drain",error:errorText(e)})}finally{a=!1}}return{state:y,start:M,arm:M,stop:A,tick:_,set:e=>(t.setAutoDrain(e||{}),M(),y()),_timer:()=>s}}function createAutoMint({mint:e,settings:t,log:r=(()=>{}),quietMs:n=9e4,setTimeoutFn:o=setTimeout,clearTimeoutFn:i=clearTimeout}={}){if("function"!=typeof e)throw new Error("createAutoMint: mint() is required");if(!t||"function"!=typeof t.getAutoMint)throw new Error("createAutoMint: the settings store is required");const u=(()=>{const e=Number(n);if(!Number.isFinite(e))return 9e4;const t=Math.round(e);return t<1e4||t>36e5?9e4:t})();let s=null,a=0,l=!1,
|
|
3
|
+
"use strict";const AUTO_MINT_QUIET_DEFAULT_MS=9e4,AUTO_MINT_QUIET_MIN_MS=1e4,AUTO_MINT_QUIET_MAX_MS=36e5;function errorText(e){return e&&e.message||String(e)}function createAutoDrain({proceed:e,settings:t,queue:r,env:n=process.env,log:o=(()=>{}),setIntervalFn:i=setInterval,clearIntervalFn:u=clearInterval}={}){if("function"!=typeof e)throw new Error("createAutoDrain: a proceed() entry point is required");if(!t||"function"!=typeof t.getAutoDrain)throw new Error("createAutoDrain: the settings store is required");let s=null,a=!1,l=0,c=0,p=null,d=null;const f=e=>(p=e,o(e),e);function y(){return{...t.autoDrainState(),armed:Boolean(s),busy:a,ticks:l,drains:c,last:p,lastSkip:d}}function M(){const e=t.getAutoDrain();return e.enabled?(s&&e.intervalMs===s.__intervalMs||(A(),s=i((()=>{_()}),e.intervalMs),s.__intervalMs=e.intervalMs,s&&"function"==typeof s.unref&&s.unref(),o({type:"auto-drain-armed",intervalMs:e.intervalMs})),y()):(A(),y())}function A(){return s?(u(s),s=null,o({type:"auto-drain-disarmed"}),y()):y()}async function _(){if(l+=1,!t.getAutoDrain().enabled)return f({type:"skip",reason:"disabled"});if(a)return f({type:"skip",reason:"busy"});if(!r||"function"!=typeof r.loadQueue)return f({type:"skip",reason:"no queue access"});let o;try{o=r.loadQueue(n)}catch(e){return f({type:"error",phase:"read",error:errorText(e)})}if(!r.pendingCount(o))return f({type:"skip",reason:"empty"});try{const e=r.lockHolder(n);if(e&&e.pid&&e.pid!==process.pid&&("function"!=typeof r.isAlive||r.isAlive(e.pid)))return f({type:"skip",reason:"locked",holder:e})}catch{}a=!0;try{const t=await e();return t&&t.locked?f({type:"skip",reason:"locked",holder:t.holder||null}):(c+=1,f({type:"drain",ok:!(t&&!1===t.ok),ran:t&&t.ran||[],reason:t&&t.reason||null}))}catch(e){return f({type:"error",phase:"drain",error:errorText(e)})}finally{a=!1}}return{state:y,start:M,arm:M,stop:A,tick:_,set:e=>(t.setAutoDrain(e||{}),M(),y()),_timer:()=>s}}function createAutoMint({mint:e,settings:t,log:r=(()=>{}),quietMs:n=9e4,setTimeoutFn:o=setTimeout,clearTimeoutFn:i=clearTimeout}={}){if("function"!=typeof e)throw new Error("createAutoMint: mint() is required");if(!t||"function"!=typeof t.getAutoMint)throw new Error("createAutoMint: the settings store is required");const u=(()=>{const e=Number(n);if(!Number.isFinite(e))return 9e4;const t=Math.round(e);return t<1e4||t>36e5?9e4:t})();let s=null,a=0,l=null,c=!1,p=0,d=0,f=null,y=null,M=null;function A(){return{...t.autoMintState(),armed:Boolean(s),quietMs:u,pendingTurns:a,model:l,busy:c,seals:p,failures:d,last:f,lastError:y,lastSeal:M}}function _(){s&&(i(s),s=null)}async function T(){const r=t.getAutoMint();if(!r.enabled)return{type:"skip",reason:"disabled"};if(c)return{type:"skip",reason:"busy"};if(!a)return{type:"skip",reason:"nothing new"};c=!0;const n=a;a=0;try{const t=await e({publish:!0===r.publish,aiModel:l||void 0});return t&&!1!==t.ok?(p+=1,y=null,l=null,M={at:Date.now(),id:t.record&&t.record.id||null,out:t.out||null,turns:n,vaultError:t.vaultError||null},f={type:"seal",...M}):(d+=1,y=t&&t.error||"the seal did not complete",f={type:"error",phase:"seal",error:y})}catch(e){return d+=1,y=errorText(e),f={type:"error",phase:"seal",error:y}}finally{c=!1}}return{state:A,note:function(e){const r=t.getAutoMint(),n=e&&"string"==typeof e.model?e.model.trim():"";return n&&(l=n),r.enabled?(a+=1,f={type:"turn",at:Date.now(),sessionId:e&&e.sessionId||null},_(),s=o((()=>{s=null,T()}),u),s&&"function"==typeof s.unref&&s.unref(),A()):(a+=1,A())},flush:T,reset:()=>(_(),a=0,l=null,A()),start:()=>(t.getAutoMint().enabled||_(),A()),stop:()=>(_(),A()),set:e=>(t.setAutoMint(e||{}),t.getAutoMint().enabled||_(),A()),_timer:()=>s}}module.exports={createAutoDrain:createAutoDrain,createAutoMint:createAutoMint,AUTO_MINT_QUIET_DEFAULT_MS:9e4,AUTO_MINT_QUIET_MIN_MS:1e4,AUTO_MINT_QUIET_MAX_MS:36e5};
|
package/lib/google-connect.js
CHANGED
|
@@ -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 createGoogleConnect({aegis:e,credentials:n,persistKey:t,openUrl:o,googleSignIn:r,driveConnect:i,driveUpload:a,onAccountChange:
|
|
3
|
+
"use strict";function createGoogleConnect({aegis:e,credentials:n,persistKey:t,openUrl:o,googleSignIn:r,driveConnect:i,driveUpload:a,conversationExport:s,getSession:c,getAuthor:l,onAccountChange:u}){let g=null,y=null,d=null,k=null,p=!1;function f(){try{const e="function"==typeof l?l():null;return{keyFingerprint:e&&e.keyFingerprint||null}}catch{return{keyFingerprint:null}}}function m(e){return s&&"function"==typeof s.authorLine?s.authorLine(e&&e.keyFingerprint):null}return{signInWithGoogle:function(){return g||(g=(async()=>{try{let i;try{i=await r.startGoogleSignIn({apiBase:e.apiBase})}catch(e){return{ok:!1,error:`could not start the local sign-in server — ${e&&e.message||e}`}}const a=Boolean(o(i.url));let s;try{s=await i.wait()}catch(e){return{ok:!1,opened:a,url:i.url,error:e&&e.message||String(e)}}if(e.setApiKey(s.apiKey),t(s.apiKey),s.memoryToken&&n&&"function"==typeof n.saveMemoryToken)try{n.saveMemoryToken(s.memoryToken)}catch{}return p=!0,"function"==typeof u&&u(),{ok:!0,opened:a,url:i.url,username:s.username||null}}finally{g=null}})()),g},connectDrive:async function(){return e.apiKey?(y||(y=(async()=>{try{let n=!0;try{const t=await i.driveStatus(e);n=!(t.googleLinkedKnown&&!t.googleLinked)}catch{}if(!n)return{ok:!1,error:"sign in with Google first — this account is not linked to a Google identity yet, and connecting Drive now would attach it to a different account"};const t=i.driveConnectUrl(e.apiBase),r=Boolean(o(t));try{const n=await i.waitForDriveConnected(e);return{ok:!0,opened:r,url:t,connected:n.connected,email:n.email}}catch(e){return{ok:!1,opened:r,url:t,error:e&&e.message||String(e)}}}finally{y=null}})()),y):{ok:!1,error:"sign in with Google first — this device has no AEGIS account key yet"}},status:async function(){if(!e.apiKey)return{signedIn:!1,googleLinked:!1,googleLinkedKnown:!0,connected:!1,email:null};const n=await i.driveStatus(e),t=!0===n.googleLinked||p;return{signedIn:t,...n,googleLinked:!0===n.googleLinked||t,googleLinkedKnown:n.googleLinkedKnown||t}},syncMemoryNow:async function(){try{const n=await e.driveToken();if(!n||!n.connected||!n.access_token)throw new Error("Google Drive is not connected yet");const t=await e.memoryPull(0),o=t&&t.entries||[],r=(new Date).toISOString(),i=JSON.stringify({exportedAt:r,entries:o},null,2),c=f(),l=s&&"function"==typeof s.memoryMarkdown?s.memoryMarkdown(i,{keyFingerprint:c.keyFingerprint,email:n.email||null,exportedAt:r,count:o.length}):i,u=await a.uploadMemoryBackup(n.access_token,l,{fileName:s?"aegis-memory-backup.md":void 0,mimeType:s?"text/markdown":void 0});return d=Date.now(),k=null,{ok:!0,count:o.length,fileId:u.fileId,webViewLink:u.webViewLink,updated:u.updated,author:m(c),lastSyncAt:d}}catch(e){return k=e&&e.message||String(e),{ok:!1,error:k,lastSyncAt:d}}},backupConversation:async function({sessionId:n}={}){try{if(!s||"function"!=typeof s.conversationMarkdown)return{ok:!1,error:"this build cannot export a conversation — the export module is missing"};const t=await e.driveToken();if(!t||!t.connected||!t.access_token)return{ok:!1,error:"connect Google Drive first — no Drive access token yet"};if(!n)return{ok:!1,error:"start a conversation first — there is nothing to save yet"};const o="function"==typeof c?c(n):null;if(!o)return{ok:!1,error:"that conversation is not in the session store yet — send one message, then save"};const r=o.messages||o.transcript||[];if(Array.isArray(r)&&0===r.length)return{ok:!1,error:"that conversation has no messages yet — nothing to save"};const i=(new Date).toISOString(),l=f(),u="function"==typeof s.toTranscript?s.toTranscript(o):o.markdown||"",g=s.conversationMarkdown(o,{transcript:u,keyFingerprint:l.keyFingerprint,email:t.email||null,exportedAt:i,count:Array.isArray(r)?r.length:null}),y=s.conversationFileName(o,i),d=await a.uploadConversation(t.access_token,{name:y,content:g});return{ok:!0,fileId:d.fileId,webViewLink:d.webViewLink,file:d.path||y,title:o.title||o.id||null,author:m(l)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},state:()=>({lastSyncAt:d,lastSyncError:k})}}module.exports={createGoogleConnect:createGoogleConnect};
|
|
@@ -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 MAX_FILE_BYTES=33554432,MAX_TEXT_BYTES=524288,MAX_IMAGE_BYTES=5242880,MAX_ATTACHMENTS=8,IMAGE_TOKEN_COST=850,PNG_SIG=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_SIG=Buffer.from([255,216,255]),GIF87=Buffer.from("GIF87a","ascii"),GIF89=Buffer.from("GIF89a","ascii"),PDF_SIG=Buffer.from("%PDF-","ascii"),BMP_SIG=Buffer.from("BM","ascii");function startsWith(t,e){return!(!Buffer.isBuffer(t)||t.length<e.length)&&0===t.compare(e,0,e.length,0,e.length)}function isWebp(t){return Buffer.isBuffer(t)&&t.length>=12&&"RIFF"===t.toString("ascii",0,4)&&"WEBP"===t.toString("ascii",8,12)}function looksLikeText(t,e=8192){if(!Buffer.isBuffer(t)||0===t.length)return!1;const i=t.subarray(0,Math.min(t.length,e));if(i.includes(0))return!1;const n=new TextDecoder("utf-8",{fatal:!0});try{n.decode(i)}catch{return!1}return!0}function sniff(t){return startsWith(t,PNG_SIG)?{kind:"image",mime:"image/png",ext:"png"}:startsWith(t,JPEG_SIG)?{kind:"image",mime:"image/jpeg",ext:"jpg"}:startsWith(t,GIF87)||startsWith(t,GIF89)?{kind:"image",mime:"image/gif",ext:"gif"}:isWebp(t)?{kind:"image",mime:"image/webp",ext:"webp"}:startsWith(t,PDF_SIG)?{kind:"pdf",mime:"application/pdf",ext:"pdf"}:startsWith(t,BMP_SIG)&&t.length>14?{kind:"image",mime:"image/bmp",ext:"bmp"}:looksLikeText(t)?{kind:"text",mime:"text/plain",ext:"txt"}:{kind:"binary",mime:"application/octet-stream",ext:""}}function isVisionMime(t){return"image/png"===t||"image/jpeg"===t||"image/webp"===t||"image/gif"===t}function toDataUrl(t,e){return Buffer.isBuffer(t)?`data:${e||"application/octet-stream"};base64,${t.toString("base64")}`:null}function imagePart(t,e){const i=toDataUrl(t,e);return i?{type:"image_url",image_url:{url:i}}:null}function flattenContent(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return String(t);const e=[];for(const i of t)i&&"object"==typeof i&&("string"==typeof i.text?e.push(i.text):"image_url"===i.type&&e.push("[image]"));return e.join("\n")}function imageCount(t){if(!Array.isArray(t))return 0;let e=0;for(const i of t)i&&"image_url"===i.type&&(e+=1);return e}function effectiveMime(t){if(t&&"string"==typeof t.mime&&t.mime)return t.mime;const e=t&&"string"==typeof t.dataUrl?t.dataUrl:"",i=/^data:([^;,]+)[;,]/.exec(e);return i?i[1].toLowerCase():""}function buildContent(t,e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return"string"==typeof t?t:"";const n=[],r="string"==typeof t?t:"";r.trim()&&n.push({type:"text",text:r});for(const t of i)if("image"===t.kind&&t.dataUrl&&isVisionMime(effectiveMime(t)))n.push({type:"image_url",image_url:{url:t.dataUrl}});else if("image"===t.kind){const e=effectiveMime(t)||"unknown image type",i=t.path?`[attached image, not inline (${e} is not a vision format): ${t.path}]\nThe file is not attached inline; use a tool to inspect it.`:`[attached image, not inline (${e} is not a vision format)]`;n.push({type:"text",text:i})}else"text"===t.kind&&"string"==typeof t.text?n.push({type:"text",text:`--- ${t.name} ---\n${t.text}`}):"pdf"===t.kind?n.push({type:"text",text:`[attached PDF: ${t.path}]\nUse a tool to read this file.`}):t.path&&n.push({type:"text",text:`[attached file: ${t.path}]`});return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:r}function pathLines(t){return(Array.isArray(t)?t:[]).map((t=>t&&t.path?/[\s"']/.test(t.path)?`"${t.path}"`:t.path:"")).filter(Boolean).join("\n")}function describe(t){return t&&"object"==typeof t?`${String(t.name||t.path||"file")} · ${humanBytes(Number(t.size)||0)}`:""}function humanBytes(t){const e=Number(t)||0;return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1048576).toFixed(1)} MB`}module.exports={MAX_FILE_BYTES:33554432,MAX_TEXT_BYTES:524288,MAX_IMAGE_BYTES:5242880,MAX_ATTACHMENTS:8,IMAGE_TOKEN_COST:850,sniff:sniff,looksLikeText:looksLikeText,isVisionMime:isVisionMime,toDataUrl:toDataUrl,imagePart:imagePart,flattenContent:flattenContent,imageCount:imageCount,buildContent:buildContent,pathLines:pathLines,describe:describe,humanBytes:humanBytes};
|
package/lib/local/claude-pro.js
CHANGED
|
@@ -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"},{id:"opus",label:"Opus",note:"alias the CLI resolves"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves"}]);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 k=()=>{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)};k();const b=createStreamParser({onText:e=>{k(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{k(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{k(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{k(),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=>{k(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&b.line(n)}})),u.stderr.on("data",(e=>{k(),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()&&b.line(g.trim()),_({choices:[{message:proMessage(b.text,b.thinking,b.thinkingTokens),finish_reason:"stop"}],usage:b.resultLine&&b.resultLine.usage||void 0,childRecord:a.record,error:b.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("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};
|
package/lib/local/context.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/CHARS_PER_TOKEN))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";return MESSAGE_OVERHEAD+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const E=Math.max(0,s-n),r=[],i=Math.max(0,Number(o)||0);let
|
|
3
|
+
"use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/CHARS_PER_TOKEN))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=MESSAGE_OVERHEAD;for(const s of t)s&&"object"==typeof s&&("string"==typeof s.text?e+=estimateTokens(s.text):("image_url"===s.type||s.image_url)&&(e+=IMAGE_COST));return e}return MESSAGE_OVERHEAD+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const E=Math.max(0,s-n),r=[],i=Math.max(0,Number(o)||0);let a=i;t&&(a+=MESSAGE_OVERHEAD+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const s=messageTokens(e[t]);if(a+s>E&&r.length>0)break;r.unshift(e[t]),a+=s}return{messages:r,system:t,dropped:e.length-r.length,estimatedTokens:a,fixedTokens:i}}module.exports={CHARS_PER_TOKEN:CHARS_PER_TOKEN,MESSAGE_OVERHEAD:MESSAGE_OVERHEAD,IMAGE_COST:IMAGE_COST,estimateTokens:estimateTokens,messageTokens:messageTokens,trimContext:trimContext};
|
package/lib/local/engine.js
CHANGED
|
@@ -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"),promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.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 i=r.homedir,a=r.cwd;try{i||(i=os.homedir()),a||(a=process.cwd())}catch{}let l=r.shell,d=r.shellKind;try{if(!l||!d){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,d=d||e.kind}}catch{}let c=r.desktopdir;try{!c&&platformLib&&(c=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",i),desktopdir:s("desktopdir",c),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",a),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(a)),shell:s("shell",l),shellKind:s("shellKind",d),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 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},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},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},{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?t:"high"]:void 0}function nativeEffort(e,o,t){const r=String(o||"");if(EFFORT_INERT_RE.test(r))return;const n="low"===t||"medium"===t?t:"high";for(const o of EFFORT_DIALECTS)if(o.provider===e&&o.re.test(r))return{field:o.field,level:o.map[n]}}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}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{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){if("string"==typeof e.prompt&&e.prompt.trim())return e.prompt;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&&"string"==typeof t.content&&t.content.trim())return t.content}return e.prompt}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;function emptyTurnError({cls:e,model:o,finishReason:t,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:i}){const a=Number(i)||0,l=Number(n)||0,d=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(a?`, and ${a} extra recovery call${1===a?"":"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 d.status=502,d}function createLocalEngine({aegis:e,settings:o,tools:t,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:i,localTransport:a=localTransport,fetchImpl:l,gitScope:d}){const c=new Map,u=t||toolsModule,f=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,p=require("./session-rounds.js"),m=()=>{if("function"==typeof i)return!1!==i();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 i=!1;const a=()=>l(!1),l=e=>{i||(i=!0,v.delete(s),t&&t.removeEventListener("abort",a),n(e))};t&&t.addEventListener("abort",a,{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 i=await u.executeTool(e,o,t);return n&&("writeFile"===e||"editFile"===e)&&i&&!1!==i.ok&&recordWrite(n,o&&o.file_path),i}async function T(e,{toolCtx:o,rootSessionId:t,rootOnDelta:r,signal:n}){const{name:s}=e,i=normalizeToolArgs(u,s,e.args,o||{});if(!i.ok)return{ok:!1,error:i.error};const a=i.args;if(!u.MUTATING_TOOLS.has(s))return w(s,a,o);if(!m())return w(s,a,o);if(function(e,o){const t=g.get(e);return Boolean(t&&t.has(o))}(t,s))return w(s,a,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,a,o||{}),!l.ok))return{ok:!1,error:l.error};const d=await function(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n("cancel");const s=randomUUID();let i=!1;const a=()=>l("cancel"),l=e=>{i||(i=!0,k.delete(s),t&&t.removeEventListener("abort",a),n(e))};t&&t.addEventListener("abort",a,{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:a,diff:l&&l.diff});if("deny"===d)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"!==d&&"once"!==d)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};if("session"===d&&function(e,o){g.has(e)||g.set(e,new Set),g.get(e).add(o)}(t,s),l){const e=u.applyChecked(s,a,l,o||{});return e&&!1!==e.ok&&o&&o.guard&&recordWrite(o.guard,a&&a.file_path),e}return w(s,a,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=nativeEffort(o,r,t.effort);try{return await e.byokChatCompletion({provider:o,model:r,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:n&&"effort"===n.field?n.level:void 0,reasoningEffort:n&&"reasoning_effort"===n.field?n.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||a.DEFAULT_BASE,o=o=>a.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=d;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 i?!i():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,i=reasoningBudget("byok"===n?splitByokModel(s).model:s,t&&t.maxTokens,t&&t.effort),l=statedCapOf(t),d="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;c.set(g,b);const w=b.signal,A=!(t&&!1===t.tools),N=A?u.toolsFor({includeSubagent:h<4}):[],O=t&&t.toolChoice||null,x=t&&t.system||f(_(t)),R=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let L=R.length,F=t&&t.prompt||"",D=null;const U=_(t),I=U.cwd,C={getShell:()=>D||(D=new ShellSession({cwd:_(t).cwd})),signal:w,cwd:I,desktopdir:U.desktopdir};try{const c="byok"===n?splitByokModel(s):null,f="byok"===n?o.get(byokNamespace(c.provider))||{}:"local"===n&&o.get("local")||{},b="byok"===n?o.rawKey(byokNamespace(c.provider)):null,_="byok"!==n?null:b||providerKeyFromEnv(c.provider);if(!("byok"!==n||c.provider&&c.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"===c.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(c.provider).rejected,t=new Error(o?`${o}. That is why this turn has no ${c.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 ${c.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 "${c.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${c.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=a.remoteRefusal(f.baseURL||a.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===c.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 D={cls:n,model:s,mode:t&&t.mode,maxTokens:i,statedMaxTokens:l,autonomous:d,sessionId:g,signal:w,onDelta:r,cfg:f,apiKey:_,toolChoice:O,cwd:I,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:d?9e5:void 0,stream:!t||!1!==t.stream};let U=!1,P=!1;const B=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),q=K||(d?40:24);let j=p.keyFor(t,R),$=p.take(j);if(!$){const e=p.adopt();e&&($=e.entry,j=e.key)}if($){const e=p.resumePreamble($);0===R.length?Array.isArray($.messages)&&$.messages.length&&R.push(...$.messages):Array.isArray($.added)&&$.added.length&&R.push(...$.added),F?F=`${e}\n\n${F}`:R.push({role:"user",content:e}),k&&k({delta:`\n\n[resuming work this session left unfinished at ${$.rounds} tool rounds`+($.interruptions>1?` (cut off ${$.interruptions}×)`:"")+"…]\n"})}let G=K||q+($?p.bonus(q):0),Y=0;const W=q,z=8;let H=0;const V={calls:0},X=["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"],J=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){V.calls+=1;for(const e of X)"number"==typeof o[e]&&Number.isFinite(o[e])&&(V[e]=(V[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&&(V.total_tokens=(V.total_tokens||0)+e)}}},Q=e=>e&&"object"==typeof e&&V.calls?{...e,usage:{...V}}:e,Z=()=>{if(""===F)return;const e=R[R.length-1];e&&"user"===e.role&&e.content===F||R.push({role:"user",content:F}),F=""};for(L=R.length;;){if(Y>=G){if(m&&H<z&&!w.aborted&&await E(y,k,w,{spent:G,extensions:H+1,max:z,size:W})){H+=1;const e=G;G+=W,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${W} 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 ${B} for a longer single turn`,o=`[stopped at ${G} tool rounds`+(V.total_tokens?`, ${V.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=p.record(j,{rounds:Y,tokens:V.total_tokens||0,note:o,chain:$?$.interruptions:0,messages:R,added:R.slice(L)});return k&&k({delta:`\n\n${o}`}),Q({model:D.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:j})}Y+=1;const e={...D,system:x,messages:R,prompt:F,tools:N,recallDeep:D.recallDeep&&1===Y};let o;if(o=await S(n,e),J(o),w.aborted)return Q(o);if(!U&&!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){U=!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}),J(o),w.aborted)return Q(o)}const i=N.length?extractToolCalls(o):[];if(!i.length){if(assistantText(o)||P||!A)return Q(o);P=!0,Z(),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,i=t.effort;if(J(o),w.aborted)return Q(o);if(!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){const e=reasonedButSilent(o);if(r=retryBudgetFor(t,e),i=e?"high":t.effort,o=await S(n,{...t,effort:i,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),J(o),w.aborted)return Q(o)}const a=(()=>{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&&(i="high"),r=a,o=await S(n,{...t,messages:R,effort:i,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),J(o),w.aborted)return Q(o)}if(!assistantText(o))throw emptyTurnError({cls:n,model:s,effort:i,recoveryRounds:l,finishReason:finishReasonOf(o),reasoningChars:reasoningTextOf(o).length,reasoningTokens:reasoningTokensOf(o)});return Q(o)}Z(),R.push({role:"assistant",content:assistantText(o),tool_calls:i.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});for(const e of i){r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:I,phase:"run"}});const o=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:C,rootSessionId:y,rootOnDelta:k,signal:w});o&&o.usage&&J({usage:o.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:o.ok,id:e.id,cwd:I,phase:"done"}}),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:u.toolResultText(o)})}}}catch(e){throw w.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{D&&D.dispose(),c.delete(g)}}async function M({description:e,subagent_type:o,prompt:t}={},{cls:r,model:n,statedMaxTokens:s,effort:i,mode:a,parentSignal:l,depth:d,rootSessionId:c,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=()=>N(g),l.addEventListener("abort",h,{once:!0})}try{const e=await A({class:r,model:n,mode:a,system:m,prompt:f,sessionId:g,depth:(d||0)+1,rootSessionId:c,rootOnDelta:u,statedMaxTokens:s,effort:i},(()=>{})),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 N(e){const o=c.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,i=null;try{const o=await e.byokProviders();r=withUserModels(withByokAdditions(o&&o.providers||[])),n=o&&o.fee||null}catch(e){r=[],s=!0,i=e&&e.message||String(e)}const a=[];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&&a.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:a,providers:r,needsProviderKey:a.length>0&&!a.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:i,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===t){const e=(o.get("local")||{}).baseURL||a.DEFAULT_BASE,r=await a.probe(e);if(!r.running)return{class:t,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await a.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:N,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 a.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"),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};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
const READ_VERBS=new Set(["cat","head","tail","less","more","wc","grep","egrep","fgrep","rg","sed","awk","cut","sort","uniq","tr","diff","comm","join","nl","ls","dir","tree","stat","file","du","df","pwd","which","type","basename","dirname","realpath","readlink","find","locate","echo","printf","date","uname","whoami","id","env","printenv","true","test"]),GIT_READ_SUBCOMMANDS=new Set(["diff","status","log","show","blame","grep","ls-files","rev-parse","describe","cat-file","shortlog","whatchanged","reflog","show-ref","ls-tree","diff-tree","diff-files","diff-index","merge-base"]),WRITE_PATTERNS=[/(^|[\s;&|(])rm(\s|$)/,/(^|[\s;&|(])rmdir(\s|$)/,/(^|[\s;&|(])mv(\s|$)/,/(^|[\s;&|(])cp(\s|$)/,/(^|[\s;&|(])ln(\s|$)/,/(^|[\s;&|(])mkdir(\s|$)/,/(^|[\s;&|(])touch(\s|$)/,/(^|[\s;&|(])chmod(\s|$)/,/(^|[\s;&|(])chown(\s|$)/,/(^|[\s;&|(])truncate(\s|$)/,/(^|[\s;&|(])dd(\s|$)/,/(^|[\s;&|(])tee(\s|$)/,/(^|[\s;&|(])install(\s|$)/,/(^|[\s;&|(])patch(\s|$)/,/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,/(^|[\s;&|(])sort\b[^|;]*--output=/,/(^|[\s;&|(])dd\b[^|;]*\bof=/,/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,/(?<![0-9&])>>?(?![&-])/,/\bexport\s+[A-Za-z_]/,/(^|[\s;&|(])source(\s|$)/],STATEFUL_PATTERNS=[/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,/(^|[\s;&|(])pushd(\s|$)/,/(^|[\s;&|(])popd(\s|$)/,/(^|[\s;&|(])nohup(\s|$)/,/(^|[\s;&|(])disown(\s|$)/,/<<-?\s*['"]?[A-Za-z_]/,/(^|[\s;&|(])\&$/,/(^|[\s;&|(])exec(\s|$)/,/(^|[\s;&|(])history(\s|$)/,/(^|[\s;&|(])jobs(\s|$)/];function effectiveVerb(e){let s=0;for(let t=0;t<4&&s<e.length;t++){const t=e[s];if("time"!==t&&"command"!==t)if("env"!==t)if("timeout"!==t){if("nice"!==t)break;s+=1,s<e.length&&"-n"===e[s]?s+=2:s<e.length&&/^-?\d+$/.test(e[s])&&(s+=1)}else{for(s+=1;s<e.length&&e[s].startsWith("-");)s+=1;s<e.length&&/^[0-9]+(\.[0-9]+)?[smhd]?$/.test(e[s])&&(s+=1)}else for(s+=1;s<e.length&&(e[s].startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[s]));)s+=1;else s+=1}return s<e.length?{verb:e[s],rest:e.slice(s)}:null}function segments(e){const s=[],t=/(\|\||&&|[;|])/g;let n,r=0;for(;n=t.exec(e);)s.push({sep:null,text:e.slice(r,n.index)}),s.push({sep:n[1]}),r=n.index+n[1].length;return s.push({sep:null,text:e.slice(r)}),s}function leadingCd(e){const s=/^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(e);if(!s)return{cwd:null,rest:e};const t=(s[1]||s[2]||s[3]||"").trim();return t.startsWith("/")?{cwd:t,rest:s[4]}:{cwd:null,rest:e}}function planExec(e,s={}){const t=s.baseCwd||null,n="string"==typeof e?e:"",r=e=>({oneShot:!1,cwd:null,reason:e});if(!n.trim())return r("empty command");if(n.includes("\n"))return r("multi-line command");for(const e of STATEFUL_PATTERNS)if(e.test(n))return r("depends on session state");for(const e of WRITE_PATTERNS)if(e.test(n))return r("contains a write");const{cwd:i,rest:o}=leadingCd(n),l=o.trim();if(!l)return r("nothing after the cd");const a=segments(l).filter((e=>!e.sep));if(!a.length)return r("no command");for(const e of a){const s=e.text.trim().replace(/^\(+\s*/,"").split(/\s+/).filter(Boolean);if(!s.length)continue;const t=effectiveVerb(s);if(!t)return r("empty command after wrappers");const n=t.verb;if("git"!==n){if(!READ_VERBS.has(n))return r(`${n} is not a known read verb`);if(("sed"===n||"awk"===n)&&/(^|\s)-[a-zA-Z]*w\s/.test(t.rest.join(" ")))return r(`${n} writes a file`)}else{const e=t.rest[1];if(!e||e.startsWith("-"))continue;if(!GIT_READ_SUBCOMMANDS.has(e))return r(`git ${e} is not read-only`)}}return{oneShot:!0,cwd:i||t,reason:"read-only"}}module.exports={planExec:planExec,READ_VERBS:READ_VERBS,GIT_READ_SUBCOMMANDS:GIT_READ_SUBCOMMANDS,WRITE_PATTERNS:WRITE_PATTERNS,STATEFUL_PATTERNS:STATEFUL_PATTERNS};
|
package/lib/local/local.js
CHANGED
|
@@ -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{estimateTokens:estimateTokens,trimContext:trimContext}=require("./context.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=SSE_IDLE_TIMEOUT_MS,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const i=n+1<t.length?t[n+1].at:e.length,l=e.slice(t[n].body,i),a=dsmlAttrs(t[n].attrs),c=a.name||a.function||a.tool||"",u={},_=[];let f;for(DSML_RE_DRIFT_PARAM.lastIndex=0;f=DSML_RE_DRIFT_PARAM.exec(l);)_.push({at:f.index,attrs:f[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<_.length;e++){const t=e+1<_.length?_[e+1].at:l.length,n=l.slice(_[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(_[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=i,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,i=o[0];if(i.includes(DSML_TAG_MARK)){n+=e.slice(s,r+i.length),s=r+i.length;continue}const l=e.slice(r+i.length),a=TEXT_TOOL_TAG_CLOSE_RE.exec(l);if(!a)break;const c=textCallsIn(l.slice(0,a.index));if(n+=e.slice(s,r),s=r+i.length+a.index+a[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let i;-1!==r&&e.length-r<=DSML_HOLD_MAX?(i=e.slice(0,r),e=e.slice(r)):(i=e,e="");const l=plainToolTagHoldAt(i);return-1!==l&&(e=i.slice(l)+e,i=i.slice(0,l)),n(i)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map((e=>String(e)))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every((e=>t.has(e.name)))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},i=e=>{n+="string"==typeof e?e:"";let i="",l=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(i+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){l=!0;break}i+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const a=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(a){i+=n.slice(0,a.index),n=n.slice(a.index);const e=n.slice(a[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){l=!0;break}const s=n.slice(0,a[0].length+t.index+t[0].length);i+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),_=n.slice(0,c.index);if(-1===u){i+=_,n=n.slice(c.index),l=!0;break}const f=textCallsIn(n.slice(c.index,u));if(i+=_,o(f))for(const e of f)s.push(e);else i+=n.slice(c.index,u);n=n.slice(u)}const a=l?0:trailingHeadFrom(n,Boolean(t));return-1===a?(i+=n,n=""):a>0&&(i+=n.slice(0,a),n=n.slice(a)),n.length>TEXT_TOOL_HOLD_MAX&&(i+=n,n=""),i};return i.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const i=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),i)},i.calls=()=>s.slice(),i}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some((e=>e>255)))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map((e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}}))).filter((e=>e.id))}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=FIRST_BYTE_TIMEOUT_MS,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(UNLOAD_TIMEOUT_MS)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=SSE_IDLE_TIMEOUT_MS}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",i=null,l=()=>{};const a=new Promise(((e,t)=>{l=t})),c=()=>{i&&clearTimeout(i),i=setTimeout((()=>{l(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))}),n)};c();try{for(;;){const e=await Promise.race([s.read(),a]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{i&&clearTimeout(i);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then((()=>{}),(()=>{}))),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch((()=>{})))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map((([e,t])=>unload(e,t))))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):DEFAULT_WARM_SECS}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const i=Math.round((r.until-o)/1e3);return i<=0?(residentMemo.delete(residentKey(e,t,n)),0):i}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout((()=>s.abort()),WINDOW_TIMEOUT_MS);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find((e=>sameModel(e&&(e.name||e.model),t))),i=r&&Number(r.context_length);return Number.isFinite(i)&&i>0?i:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const i=baseOf(e);if(!isLocalEndpoint(i))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const l=warmSecsFor({warmSecs:o}),a="string"==typeof n?n:"",c={warmSecs:l,prefixSource:a?"turn-system":"none",prefixChars:a.length};if(l<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,_=residentSecsLeft(i,t,a,{dialer:u});if(_>=Math.min(l,60)){const e=residentEntry(i,t,a,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:_,contextLength:e&&e.contextLength||null,...c}}const f=new AbortController,d=()=>f.abort();s&&(s.aborted?f.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",d,{once:!0}));const m=Number(r),E=Number.isFinite(m)&&m>0?Math.min(m,RESIDENT_TIMEOUT_MS):RESIDENT_TIMEOUT_MS;let T=!1,p=null;const S=setTimeout((()=>{T=!0,f.abort()}),E);S&&"function"==typeof S.unref&&S.unref();try{try{const e=await fetch(`${i}/api/ps`,{method:"GET",signal:f.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find((e=>sameModel(e&&(e.name||e.model),t)));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(p=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(l,60))return residentMemo.set(residentKey(i,t,a),{until:Date.now()+1e3*e,dialer:u,contextLength:p}),{ok:!0,already:!0,remainingSecs:e,contextLength:p,...c}}}}catch{}if(f.signal.aborted)return{ok:!1,aborted:!0,timeout:T,contextLength:p,...c};const e=a?[{role:"system",content:a},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${i}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:l,stream:!1,messages:e,options:{num_predict:1}}),signal:f.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch((()=>""));try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==p&&(p=await windowOf(i,t,{signal:f.signal})||null),residentMemo.set(residentKey(i,t,a),{until:Date.now()+1e3*l,dialer:u,contextLength:p}),swapWarmModel(i,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:p,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:T,contextLength:p,...c}}finally{clearTimeout(S),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",d)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o}){const r=Number(s);if(!Number.isFinite(r)||r<=0)return null;const i=(Array.isArray(e)?e:[]).filter((e=>e&&"system"!==e.role)),l=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,a=Number(o),c=Number.isFinite(a)&&a>0?a:Math.round(r/4),u=trimContext({messages:i,system:"string"==typeof t?t:"",budgetTokens:r,reserveTokens:c,fixedTokens:l});return{window:r,reserveTokens:c,toolTokens:l,dropped:u.dropped,messages:u.messages,over:u.estimatedTokens>Math.max(0,r-c),estimatedTokens:u.estimatedTokens}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:i,tools:l,toolChoice:a,signal:c,onDelta:u,firstByteTimeoutMs:_=FIRST_BYTE_TIMEOUT_MS,contextLength:f}={}){const d=baseOf(e),m=remoteRefusal(d);if(m)throw m;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const E=[];s&&E.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&E.push(t)}const T="string"==typeof o?o:"";if(T){const e=E[E.length-1];e&&"user"===e.role&&e.content===T||E.push({role:"user",content:T})}if(!E.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let p=null;if(null!=f){const e=E[0]&&"system"===E[0].role?E[0]:null;if(p=fitToWindowOf({rows:E,system:e&&e.content||s||"",tools:l,contextLength:f,maxTokens:r}),p){const t=p.messages;E.length=0,e&&E.push(e),E.push(...t)}}const S={model:String(t),messages:E,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=i?{temperature:i}:{},...l&&l.length?{tools:l}:{},...a?{tool_choice:a}:{}},g=new AbortController;let h=!1;const L=setTimeout((()=>{h=!0,g.abort()}),_);L&&"function"==typeof L.unref&&L.unref();const M=()=>g.abort();let y;c&&(c.aborted?g.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",M,{once:!0}));try{y=await fetch(`${d}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(S),signal:g.signal})}catch(e){if(h||isHeadersDeadline(e)){const e=h?`sent nothing in ${Math.round(_/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(HEADERS_DEADLINE_MS/1e3)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||g.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(L)}if(!y.ok){let e="";try{e=await y.text()}catch{}const t=new Error(`local: chat/completions ${y.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=y.status,t}let O="",A=null;const D=[],R=new Map,x=makeDeepSeekEnvelopeStripper(),b=makeTextToolCallStripper({toolNames:(Array.isArray(l)?l:[]).map((e=>e&&e.function&&e.function.name||e&&e.name||"")).filter(Boolean)});try{await readSSE(y,(e=>{e&&e.usage&&(A=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=b(x(n.content));e&&(O+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:D.length;let n=R.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},R.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}}),{idleTimeoutMs:SSE_IDLE_TIMEOUT_MS})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:O,usage:A});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",M)}const w=`${b(x.flush())||""}${b.flush()||""}`;w&&(O+=w,"function"==typeof u&&u({text:w}));for(const[e,t]of[...R.entries()].sort(((e,t)=>e[0]-t[0])))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),D.push(t));const k={role:"assistant",content:O};D.length&&(k.tool_calls=D);const N=x.calls(),I=b.calls(),C={id:"local",model:String(t),choices:[{index:0,message:k,finish_reason:D.length?"tool_calls":"stop"}],...A?{usage:A}:{}};return(D.length||N.length||I.length)&&(C.toolCalls=[...D.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...N.map((e=>({id:"",name:e.name,args:e.args||{}}))),...I.map((e=>({id:"",name:e.name,args:e.args||{}})))],(N.length||I.length)&&"tool_calls"!==C.choices[0].finish_reason&&(C.choices[0].finish_reason="tool_calls")),p&&(C.window={contextLength:p.window,dropped:p.dropped,toolTokens:p.toolTokens,estimatedTokens:p.estimatedTokens,reserveTokens:p.reserveTokens,over:p.over}),C}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,(async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})}));return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:DEFAULT_WARM_SECS,RESIDENT_TIMEOUT_MS:RESIDENT_TIMEOUT_MS,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,FIRST_BYTE_TIMEOUT_MS:FIRST_BYTE_TIMEOUT_MS,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:HEADERS_DEADLINE_MS,windowOf:windowOf,stoppedTurn:stoppedTurn};
|
|
3
|
+
"use strict";const{estimateTokens:estimateTokens,trimContext:trimContext}=require("./context.js"),attachmentsModule=require("./attachments.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=SSE_IDLE_TIMEOUT_MS,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,l=e.slice(t[n].body,a),i=dsmlAttrs(t[n].attrs),c=i.name||i.function||i.tool||"",u={},f=[];let _;for(DSML_RE_DRIFT_PARAM.lastIndex=0;_=DSML_RE_DRIFT_PARAM.exec(l);)f.push({at:_.index,attrs:_[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<f.length;e++){const t=e+1<f.length?f[e+1].at:l.length,n=l.slice(f[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(f[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=a,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,a=o[0];if(a.includes(DSML_TAG_MARK)){n+=e.slice(s,r+a.length),s=r+a.length;continue}const l=e.slice(r+a.length),i=TEXT_TOOL_TAG_CLOSE_RE.exec(l);if(!i)break;const c=textCallsIn(l.slice(0,i.index));if(n+=e.slice(s,r),s=r+a.length+i.index+i[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let a;-1!==r&&e.length-r<=DSML_HOLD_MAX?(a=e.slice(0,r),e=e.slice(r)):(a=e,e="");const l=plainToolTagHoldAt(a);return-1!==l&&(e=a.slice(l)+e,a=a.slice(0,l)),n(a)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map((e=>String(e)))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every((e=>t.has(e.name)))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},a=e=>{n+="string"==typeof e?e:"";let a="",l=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(a+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){l=!0;break}a+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const i=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(i){a+=n.slice(0,i.index),n=n.slice(i.index);const e=n.slice(i[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){l=!0;break}const s=n.slice(0,i[0].length+t.index+t[0].length);a+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),f=n.slice(0,c.index);if(-1===u){a+=f,n=n.slice(c.index),l=!0;break}const _=textCallsIn(n.slice(c.index,u));if(a+=f,o(_))for(const e of _)s.push(e);else a+=n.slice(c.index,u);n=n.slice(u)}const i=l?0:trailingHeadFrom(n,Boolean(t));return-1===i?(a+=n,n=""):i>0&&(a+=n.slice(0,i),n=n.slice(i)),n.length>TEXT_TOOL_HOLD_MAX&&(a+=n,n=""),a};return a.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const a=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),a)},a.calls=()=>s.slice(),a}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some((e=>e>255)))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map((e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}}))).filter((e=>e.id))}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=FIRST_BYTE_TIMEOUT_MS,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(UNLOAD_TIMEOUT_MS)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=SSE_IDLE_TIMEOUT_MS}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",a=null,l=()=>{};const i=new Promise(((e,t)=>{l=t})),c=()=>{a&&clearTimeout(a),a=setTimeout((()=>{l(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))}),n)};c();try{for(;;){const e=await Promise.race([s.read(),i]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{a&&clearTimeout(a);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then((()=>{}),(()=>{}))),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch((()=>{})))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map((([e,t])=>unload(e,t))))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):DEFAULT_WARM_SECS}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const a=Math.round((r.until-o)/1e3);return a<=0?(residentMemo.delete(residentKey(e,t,n)),0):a}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout((()=>s.abort()),WINDOW_TIMEOUT_MS);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find((e=>sameModel(e&&(e.name||e.model),t))),a=r&&Number(r.context_length);return Number.isFinite(a)&&a>0?a:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const a=baseOf(e);if(!isLocalEndpoint(a))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const l=warmSecsFor({warmSecs:o}),i="string"==typeof n?n:"",c={warmSecs:l,prefixSource:i?"turn-system":"none",prefixChars:i.length};if(l<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,f=residentSecsLeft(a,t,i,{dialer:u});if(f>=Math.min(l,60)){const e=residentEntry(a,t,i,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:f,contextLength:e&&e.contextLength||null,...c}}const _=new AbortController,d=()=>_.abort();s&&(s.aborted?_.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",d,{once:!0}));const m=Number(r),E=Number.isFinite(m)&&m>0?Math.min(m,RESIDENT_TIMEOUT_MS):RESIDENT_TIMEOUT_MS;let T=!1,p=null;const S=setTimeout((()=>{T=!0,_.abort()}),E);S&&"function"==typeof S.unref&&S.unref();try{try{const e=await fetch(`${a}/api/ps`,{method:"GET",signal:_.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find((e=>sameModel(e&&(e.name||e.model),t)));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(p=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(l,60))return residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*e,dialer:u,contextLength:p}),{ok:!0,already:!0,remainingSecs:e,contextLength:p,...c}}}}catch{}if(_.signal.aborted)return{ok:!1,aborted:!0,timeout:T,contextLength:p,...c};const e=i?[{role:"system",content:i},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${a}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:l,stream:!1,messages:e,options:{num_predict:1}}),signal:_.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch((()=>""));try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==p&&(p=await windowOf(a,t,{signal:_.signal})||null),residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*l,dialer:u,contextLength:p}),swapWarmModel(a,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:p,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:T,contextLength:p,...c}}finally{clearTimeout(S),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",d)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o}){const r=Number(s);if(!Number.isFinite(r)||r<=0)return null;const a=(Array.isArray(e)?e:[]).filter((e=>e&&"system"!==e.role)),l=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,i=Number(o),c=Number.isFinite(i)&&i>0?i:Math.round(r/4),u=trimContext({messages:a,system:"string"==typeof t?t:"",budgetTokens:r,reserveTokens:c,fixedTokens:l});return{window:r,reserveTokens:c,toolTokens:l,dropped:u.dropped,messages:u.messages,over:u.estimatedTokens>Math.max(0,r-c),estimatedTokens:u.estimatedTokens}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:a,tools:l,toolChoice:i,signal:c,onDelta:u,firstByteTimeoutMs:f=FIRST_BYTE_TIMEOUT_MS,contextLength:_}={}){const d=baseOf(e),m=remoteRefusal(d);if(m)throw m;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const E=[];s&&E.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&E.push(t)}const T="string"==typeof o||Array.isArray(o)?o:"";if(!(""===T||Array.isArray(T)&&0===T.length)){const e=E[E.length-1],t=attachmentsModule.flattenContent(T),n=e?attachmentsModule.flattenContent(e.content):null;e&&"user"===e.role&&n===t||E.push({role:"user",content:T})}if(!E.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let p=null;if(null!=_){const e=E[0]&&"system"===E[0].role?E[0]:null;if(p=fitToWindowOf({rows:E,system:e&&e.content||s||"",tools:l,contextLength:_,maxTokens:r}),p){const t=p.messages;E.length=0,e&&E.push(e),E.push(...t)}}const S={model:String(t),messages:E,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=a?{temperature:a}:{},...l&&l.length?{tools:l}:{},...i?{tool_choice:i}:{}},g=new AbortController;let h=!1;const L=setTimeout((()=>{h=!0,g.abort()}),f);L&&"function"==typeof L.unref&&L.unref();const M=()=>g.abort();let y;c&&(c.aborted?g.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",M,{once:!0}));try{y=await fetch(`${d}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(S),signal:g.signal})}catch(e){if(h||isHeadersDeadline(e)){const e=h?`sent nothing in ${Math.round(f/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(HEADERS_DEADLINE_MS/1e3)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||g.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(L)}if(!y.ok){let e="";try{e=await y.text()}catch{}const t=new Error(`local: chat/completions ${y.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=y.status,t}let O="",A=null;const D=[],R=new Map,x=makeDeepSeekEnvelopeStripper(),b=makeTextToolCallStripper({toolNames:(Array.isArray(l)?l:[]).map((e=>e&&e.function&&e.function.name||e&&e.name||"")).filter(Boolean)});try{await readSSE(y,(e=>{e&&e.usage&&(A=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=b(x(n.content));e&&(O+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:D.length;let n=R.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},R.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}}),{idleTimeoutMs:SSE_IDLE_TIMEOUT_MS})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:O,usage:A});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",M)}const w=`${b(x.flush())||""}${b.flush()||""}`;w&&(O+=w,"function"==typeof u&&u({text:w}));for(const[e,t]of[...R.entries()].sort(((e,t)=>e[0]-t[0])))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),D.push(t));const k={role:"assistant",content:O};D.length&&(k.tool_calls=D);const N=x.calls(),I=b.calls(),C={id:"local",model:String(t),choices:[{index:0,message:k,finish_reason:D.length?"tool_calls":"stop"}],...A?{usage:A}:{}};return(D.length||N.length||I.length)&&(C.toolCalls=[...D.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...N.map((e=>({id:"",name:e.name,args:e.args||{}}))),...I.map((e=>({id:"",name:e.name,args:e.args||{}})))],(N.length||I.length)&&"tool_calls"!==C.choices[0].finish_reason&&(C.choices[0].finish_reason="tool_calls")),p&&(C.window={contextLength:p.window,dropped:p.dropped,toolTokens:p.toolTokens,estimatedTokens:p.estimatedTokens,reserveTokens:p.reserveTokens,over:p.over}),C}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,(async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})}));return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:DEFAULT_WARM_SECS,RESIDENT_TIMEOUT_MS:RESIDENT_TIMEOUT_MS,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,FIRST_BYTE_TIMEOUT_MS:FIRST_BYTE_TIMEOUT_MS,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:HEADERS_DEADLINE_MS,windowOf:windowOf,stoppedTurn:stoppedTurn};
|
package/lib/local/prompt.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:s,dataDir:r,locale:a,localeName:i,languages:l,cwd:h,vcs:d,shell:u,shellKind:c,roots:m,appVersion:p,model:f}=e||{},
|
|
3
|
+
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:s,dataDir:r,locale:a,localeName:i,languages:l,cwd:h,vcs:d,shell:u,shellKind:c,roots:m,appVersion:p,model:f}=e||{},y=[];if(t&&y.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";y.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const g=(Array.isArray(l)?l:[]).map((e=>languageLine(e))).filter(Boolean);g.length&&y.push(`recorded language evidence from the user's own saved writing: ${g.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&y.push(`home directory: ${o}`),s&&y.push(`desktop directory: ${s} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),r&&y.push(`AEGIS data directory: ${r} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),h&&y.push(`working directory: ${h}`),"git"===d?y.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===d&&y.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),u&&y.push(`exec shell: ${u}${c?` (${c})`:""}`),f&&y.push(`model: ${f}`),p&&y.push(`AEGIS Desktop ${p}`);const w=Array.isArray(m)?m.filter(Boolean):[],v=[];y.length&&v.push(y.join("\n")),w.length&&v.push(`repo roots:\n${w.map((e=>` - ${e}`)).join("\n")}`);const b=commandDialectLine(t,c);return b&&v.push(b),v.length?`# Environment\n${v.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n=environmentPreamble(e);return n&&t.push(n),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,buildSystemPrompt:buildSystemPrompt};
|
|
@@ -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 TTL_MS=18e5,MAX_ENTRIES=64,entries=new Map,historyKeys=new WeakMap;let historyKeySeq=0;function prune(e=Date.now()){for(const[t,n]of entries)e-n.at>TTL_MS&&entries.delete(t);for(;entries.size>MAX_ENTRIES;){const e=entries.keys().next();if(e.done)break;entries.delete(e.value)}return entries.size}function keyFor(e,t){const n=e&&"object"==typeof e?e:{},r=n.sessionKey||n.sessionId||n.chatId||n.threadId||n.conversationId;if("string"==typeof r&&r.trim())return`s:${r.trim()}`;if("string"==typeof n.cwd&&n.cwd.trim())return`cwd:${n.cwd.trim()}`;if(t&&"object"==typeof t){let e=historyKeys.get(t);return e||(historyKeySeq+=1,e=`hist-${historyKeySeq}`,historyKeys.set(t,e)),e}return"default"}function bonus(e){const t=Number.isFinite(e)&&e>0?e:0;return Math.max(4,Math.ceil(t/4))}function peek(e,t=Date.now()){return prune(t),entries.get(e)||null}function take(e,t=Date.now()){prune(t);const n=entries.get(e);return n?(entries.delete(e),n):null}function adopt({now:e=Date.now(),maxAgeMs:t=6e5}={}){prune(e);let n=null,r=null;for(const[s,i]of entries)e-i.at>t||(!r||i.at>r.at)&&(r=i,n=s);return r?(entries.delete(n),{key:n,entry:r}):null}function record(e,{rounds:t,tokens:n,note:r,chain:s,messages:i,added:o}={},
|
|
3
|
+
"use strict";const TTL_MS=18e5,MAX_ENTRIES=64,entries=new Map,historyKeys=new WeakMap;let historyKeySeq=0;function prune(e=Date.now()){for(const[t,n]of entries)e-n.at>TTL_MS&&entries.delete(t);for(;entries.size>MAX_ENTRIES;){const e=entries.keys().next();if(e.done)break;entries.delete(e.value)}return entries.size}function keyFor(e,t){const n=e&&"object"==typeof e?e:{},r=n.sessionKey||n.sessionId||n.chatId||n.threadId||n.conversationId;if("string"==typeof r&&r.trim())return`s:${r.trim()}`;if("string"==typeof n.cwd&&n.cwd.trim())return`cwd:${n.cwd.trim()}`;if(t&&"object"==typeof t){let e=historyKeys.get(t);return e||(historyKeySeq+=1,e=`hist-${historyKeySeq}`,historyKeys.set(t,e)),e}return"default"}function isStatedKey(e){const t=e&&"object"==typeof e?e:{},n=t.sessionKey||t.sessionId||t.chatId||t.threadId||t.conversationId;return!("string"!=typeof n||!n.trim())||"string"==typeof t.cwd&&t.cwd.trim().length>0}function bonus(e){const t=Number.isFinite(e)&&e>0?e:0;return Math.max(4,Math.ceil(t/4))}function peek(e,t=Date.now()){return prune(t),entries.get(e)||null}function take(e,t=Date.now()){prune(t);const n=entries.get(e);return n?(entries.delete(e),n):null}function adopt({now:e=Date.now(),maxAgeMs:t=6e5}={}){prune(e);let n=null,r=null;for(const[s,i]of entries)e-i.at>t||(!r||i.at>r.at)&&(r=i,n=s);return r?(entries.delete(n),{key:n,entry:r}):null}function record(e,{rounds:t,tokens:n,note:r,chain:s,messages:i,added:o}={},a=Date.now()){prune(a);const u=entries.get(e),d={rounds:Number.isFinite(t)?t:0,tokens:Number.isFinite(n)?n:0,note:"string"==typeof r?r:"",at:a,interruptions:(Number.isFinite(s)?s:u&&u.interruptions)||0,messages:Array.isArray(i)?i.slice():[],added:Array.isArray(o)?o.slice():[]};return d.interruptions+=1,entries.delete(e),entries.set(e,d),prune(a),d}function resumePreamble(e){return`[session resume] The previous turn in this conversation was cut off at ${e&&e.rounds?e.rounds:"the previous turn's"} tool rounds${e&&e.tokens?` (${e.tokens.toLocaleString()} tokens)`:""} because it reached the round horizon, so the work it started is unfinished. Continue that work now: do not restart, do not re-do steps that already completed, and do not treat the interruption as a failure to report. Pick up the next unfinished step and finish with a written answer.`}function state(e=Date.now()){return prune(e),{size:entries.size,ttlMs:TTL_MS,maxEntries:MAX_ENTRIES,entries:[...entries].map((([e,t])=>({key:e,...t})))}}function reset(){return entries.clear(),entries.size}module.exports={TTL_MS:TTL_MS,MAX_ENTRIES:MAX_ENTRIES,keyFor:keyFor,isStatedKey:isStatedKey,bonus:bonus,peek:peek,take:take,adopt:adopt,record:record,resumePreamble:resumePreamble,state:state,reset:reset};
|