aws-runtime-bridge 1.9.172 → 1.9.175
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/CHANGELOG.md +126 -0
- package/dist/adapter/AcodeSdkAdapter.d.ts +5 -1
- package/dist/adapter/AcodeSdkAdapter.js +3 -3
- package/dist/adapter/types.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/routes/bridge-temp-files.d.ts +1 -0
- package/dist/routes/bridge-temp-files.js +2 -0
- package/dist/routes/dashboard.js +35 -5
- package/dist/routes/file-browser.d.ts +4 -10
- package/dist/routes/file-browser.js +1 -1
- package/dist/routes/git.d.ts +42 -0
- package/dist/routes/git.js +34 -34
- package/dist/routes/sessions.js +1 -1
- package/dist/routes/tech-stack.d.ts +2 -0
- package/dist/routes/tech-stack.js +2 -0
- package/dist/routes/terminal.js +19 -19
- package/dist/services/agent-pty-manager.d.ts +2 -0
- package/dist/services/agent-pty-manager.js +5 -4
- package/dist/services/agent-startup-memory.js +4 -4
- package/dist/services/bridge-temp-files.d.ts +36 -0
- package/dist/services/bridge-temp-files.js +2 -0
- package/dist/services/fileSnapshotStore.d.ts +9 -0
- package/dist/services/fileSnapshotStore.js +1 -1
- package/dist/services/gitignore.d.ts +12 -0
- package/dist/services/gitignore.js +2 -0
- package/dist/services/log-retention.js +1 -1
- package/dist/services/open-doc-events.d.ts +21 -0
- package/dist/services/open-doc-events.js +2 -0
- package/dist/services/open-doc-registry.d.ts +24 -0
- package/dist/services/open-doc-registry.js +2 -0
- package/dist/services/request-invalid-dump.js +1 -1
- package/dist/services/runtime-resources-snapshot.js +2 -2
- package/dist/services/snapshot-retention.d.ts +7 -0
- package/dist/services/snapshot-retention.js +2 -0
- package/dist/services/tech-stack-scanner.d.ts +31 -0
- package/dist/services/tech-stack-scanner.js +2 -0
- package/dist/services/tunnel-client.d.ts +42 -0
- package/dist/services/tunnel-client.js +1 -1
- package/dist/services/workspaceTaskChangeWatcher.js +2 -2
- package/package/acode/dist/__tests__/summary-request-helper.d.ts +2 -0
- package/package/acode/dist/__tests__/summary-request-helper.js +2 -0
- package/package/acode/dist/cache-control.d.ts +26 -0
- package/package/acode/dist/cache-control.js +2 -0
- package/package/acode/dist/compaction.d.ts +35 -5
- package/package/acode/dist/compaction.js +19 -17
- package/package/acode/dist/microcompact.d.ts +57 -0
- package/package/acode/dist/microcompact.js +2 -0
- package/package/acode/dist/runtime.d.ts +4 -0
- package/package/acode/dist/runtime.js +40 -33
- package/package/acode/dist/token-estimator.d.ts +15 -0
- package/package/acode/dist/token-estimator.js +2 -0
- package/package/acode/dist/types.d.ts +13 -0
- package/package/aws-client-agent-mcp/dist/ability-market-tools.js +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +15 -2
- package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +5 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.js +25 -23
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +7 -7
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +21 -2
- package/package/aws-client-agent-mcp/dist/memory-store.js +27 -2
- package/package/aws-client-agent-mcp/dist/memory-tools.js +13 -9
- package/package/aws-client-agent-mcp/dist/server-memory-store.d.ts +1 -1
- package/package/aws-client-agent-mcp/dist/server-memory-store.js +1 -1
- package/package/aws-client-agent-mcp/dist/types.d.ts +51 -0
- package/package.json +1 -1
|
@@ -1,21 +1,23 @@
|
|
|
1
|
-
const
|
|
2
|
-
`)
|
|
3
|
-
${
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function Vt(t,e,n,o=!0){const r=[];let s=[],i=0;for(let l=0;l<t.length;l++){const a=Q(t[l],l,e,o),h=k(a);s.length>0&&i+h>n&&(r.push(s.join(`
|
|
7
|
-
`)),s=[],i=0),s.push(a),i+=h}return s.length>0&&r.push(s.join(`
|
|
8
|
-
`)),r}function qt(t,e,n=!0){const o=Math.max(1,e.summaryInputBudget),r=["S1","S2","S3","S4"];for(let a=0;a<Y.length;a++){const h=Y[a],f=Jt(t,h,n);if(k(f)<=o)return{step:r[a]??"S4",cap:h,chunks:[f],singleShot:!0}}const s=Y[Y.length-1]??2e3,i=Vt(t,s,Math.floor(o*.9),n),l=i.length<=st?i:Qt(i,st);return{step:"S5",cap:s,chunks:l,singleShot:!1}}function Qt(t,e){const n=Math.max(1,Math.min(e,t.length)),o=[];for(let r=0;r<n;r++){const s=Math.floor(r*t.length/n),i=Math.floor((r+1)*t.length/n);o.push(t.slice(s,Math.max(s+1,i)).join(`
|
|
9
|
-
`))}return o}function te(t){return new Promise(e=>setTimeout(e,t))}function F(t){if(!(t instanceof Error))return!1;if(t.name==="AbortError")return!0;const e=t.message.toLowerCase();return e.includes("aborted by user")||e.includes("summarization aborted")}function ee(t){if(!(t instanceof Error))return!1;const e=t.message.toLowerCase();return/\b(408|429|5\d\d)\b/.test(e)||e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||e.includes("empty content")||e.includes("stream response has no body")}async function J(t,e){const n=Math.max(1,Math.floor(e?.maxAttempts??1)),o=e?.baseDelayMs??Dt,r=e?.maxDelayMs??Bt,s=e?.jitterMs??$t;let i=new Error("summarizer was never invoked");for(let l=1;l<=n;l++)try{const a=await t();if(typeof a!="string"||a.trim().length===0)throw new Error("summarizer returned empty content");return{summary:a,attempts:l}}catch(a){if(i=a instanceof Error?a:new Error(String(a)),a instanceof z||F(a))throw i;if(!ee(a)||l>=n)throw new U(l,i);const f=Math.min(r,o*Math.pow(2,l-1));await te(f+Math.random()*s)}throw new U(n,i)}async function ne(t){const{removed:e,budget:n,llmSummarizer:o,anchors:r,previousSummary:s,retryPolicy:i,includeReasoning:l=!0}=t,a=qt(e,n,l),h=lt(r)?void 0:r,f=n.summaryMaxTokens>0?n.summaryMaxTokens:void 0;let p=0;if(a.singleShot){const d=await J(()=>o({conversationText:a.chunks[0],messageCount:e.length,contextLimit:n.contextLimit,...s?{previousSummary:s}:{},...h?{anchors:h}:{},...f?{maxTokens:f}:{}}),i);return{summary:d.summary,step:a.step,chunks:1,attempts:d.attempts}}const m=new Array(a.chunks.length).fill(null);for(let d=0;d<a.chunks.length;d++){if(m[d]!==null)continue;const w=a.chunks[d],c=await J(()=>o({conversationText:w,messageCount:e.length,contextLimit:n.contextLimit,...h?{anchors:h}:{},...f?{maxTokens:f}:{}}),i);m[d]=c.summary,p+=c.attempts}let u=m,_=0;for(;u.length>1&&_<it;){const d=[],c=_===it-1?u.length:Math.max(2,Math.ceil(u.length/4));for(let g=0;g<u.length;g+=c){const b=u.slice(g,g+c),y=b.map((R,C)=>`### Part ${g+C+1}
|
|
10
|
-
${R}`).join(`
|
|
1
|
+
import{ESTIMATION_ASCII_CHARS_PER_TOKEN as ut,ESTIMATION_IMAGE_TOKENS as wt,ESTIMATION_TOOL_OVERHEAD as Ot,estimateTokens as b}from"./token-estimator.js";const Ct=2e4,Et=.55,bt=[[32e3,.7],[128e3,.75],[512e3,.8],[Number.POSITIVE_INFINITY,.85]];function H(t){if(t<=0)return Et;for(const[e,o]of bt)if(t<e)return o;return .85}const Rt=4e4,It=2e4,Pt=.5,Lt=.1,ft=new Set(["skill","todo_write","todo_read"]),Y={read_file:0,Read:0,grep:0,Grep:0,glob:0,Glob:0,"contextweaver_codebase-retrieval":0,Edit:1,edit:1,Write:1,write:1,write_file:1,webfetch:2,WebFetch:2,WebSearch:2,websearch_web_search_exa:2,bash:3,Bash:3,run_terminal_command:3,playwright_browser_:4},W=2;function mt(t){if(!t)return W;if(Y[t]!==void 0)return Y[t];const e=Object.keys(Y).filter(o=>t.startsWith(o)).sort((o,n)=>n.length-o.length);return e.length>0?Y[e[0]]:W}const G=128e3,U=8192,Nt=8,vt=6e3,Se=500,j="ACode context compaction summary:",zt="ACode runtime resources:",Ut="[Runtime Instructions]",we=["Please summarize the conversation above using the following structured format.","Keep each section concise but preserve all actionable details.","Omit any section that has no relevant content.","","## Goal","The user's primary objective in this conversation (1-2 sentences).","","## Known Facts","Key facts already established: decisions, findings, errors, constraints, and user-stated preferences.","","## Done","Tasks that have been completed (do not redo these).","","## In Progress","What is currently being worked on but not yet finished: which step it stopped at and any partial results.","","## Next Steps","The immediate next actions to take to continue the work.","","## Files","Files read, modified, or created with brief context.","","Output only the summary, no preamble."].join(`
|
|
2
|
+
`);import{ESTIMATION_CJK_CHARS_PER_TOKEN as Fe}from"./token-estimator.js";import{ESTIMATION_ASCII_CHARS_PER_TOKEN as De}from"./token-estimator.js";import{ESTIMATION_SAFE_PADDING as Ke}from"./token-estimator.js";import{ESTIMATION_IMAGE_TOKENS as Ye}from"./token-estimator.js";import{ESTIMATION_TOOL_OVERHEAD as Ge}from"./token-estimator.js";const jt=6e4,Ft=.45,Bt=.8,Dt=2e3,$t=.08,Kt=8192,X=[Number.POSITIVE_INFINITY,32e3,8e3,2e3],dt=8,ht=2,Ht=.75,Yt=!1,Wt=.6,F=800,Gt=100,pt=8e3,Xt=1e3,Jt=8e3,Zt=1e3,Vt=32e3;class B extends Error{constructor(e){super(`ACode summary input overflow: ${e}`),this.marker=e,this.kind="overflow",this.name="SummaryOverflowError"}}class D extends Error{constructor(e,o){super(`ACode summary unavailable after ${e} attempt(s): ${o.message}`),this.attempts=e,this.lastError=o,this.kind="unavailable",this.name="SummaryUnavailableError"}}function qt(t,e,o){const n=Math.floor(t*H(t)),r=o??t,s=Math.min(Ct,e),i=r-s;return Math.min(n,i)}function _t(t){const{contextLimit:e,maxOutput:o}=t,n=t.inputLimit&&t.inputLimit>0?t.inputLimit:e,r=Math.max(1,n-o),s=Math.max(0,Math.floor(t.toolsTokens??0)),i=t.threshold??qt(e,o,t.inputLimit),l=Math.max(0,Math.min(jt,Math.floor(r*Ft))),a=Math.max(Dt,Math.floor(r*Bt)-s),m=Math.max(0,Math.min(Kt,Math.floor(r*$t))),_=Math.max(0,Math.floor(i*Ht));return{contextLimit:e,maxOutput:o,...t.inputLimit&&t.inputLimit>0?{inputLimit:t.inputLimit}:{},usableTokens:r,toolsTokens:s,keepRecentTokens:l,summaryInputBudget:a,summaryMaxTokens:m,targetTokens:_}}function v(t,e){const o=R(t)+e.toolsTokens;return e.targetTokens<=0?!0:o<=e.targetTokens}function Oe(t,e){return R(t)+e.toolsTokens<=e.usableTokens}const Qt=[{key:"filePaths",pattern:/(?:[A-Za-z]:[\\/]|\.{1,2}[\\/]|\/)?(?:[\w.@-]{1,120}[\\/]){1,16}[\w.@-]{1,120}\.[A-Za-z0-9]{1,8}\b/g},{key:"commands",pattern:/\b(?:npm|npx|yarn|pnpm|git|docker|kubectl|mvn|gradle|python|python3|node|deno|bun|cargo|go|make|pytest|vitest|tsc)\s+[^\n"'`]{2,120}/g},{key:"errors",pattern:/\b(?:[A-Z][A-Za-z]*(?:Error|Exception)|E[A-Z]{3,})\b[^\n]{0,120}/g},{key:"identifiers",pattern:/\b(?:[A-Z][A-Z0-9_]{2,31}|[a-z][a-z0-9]{0,30}(?:_[a-z0-9]{1,20})+|[a-z][a-z0-9]{0,30}[A-Z][A-Za-z0-9]{0,30})\b/g},{key:"numbers",pattern:/\b\d{2,}(?:\.\d+){0,3}\b/g}],et=2e4,te={filePaths:5,commands:6,errors:8,identifiers:4,numbers:2};function ee(t){const e={filePaths:new Set,commands:new Set,errors:new Set,identifiers:new Set,numbers:new Set},o=[];for(const n of t)if(n.role!=="system"){if(typeof n.content=="string")o.push(n.content);else if(Array.isArray(n.content)){for(const r of n.content)if(typeof r=="string")o.push(r);else if(r&&typeof r=="object"){const s=r.text;typeof s=="string"&&o.push(s)}}if(n.tool_calls?.length)try{o.push(JSON.stringify(n.tool_calls))}catch{}}for(const n of o){const r=n.length<=et?n:`${n.slice(0,et/2)}
|
|
3
|
+
${n.slice(-et/2)}`;for(const{key:s,pattern:i}of Qt){i.lastIndex=0;let l;for(;(l=i.exec(r))!==null;){const a=l[0].trim();if(!(a.length<te[s])){if(e[s].size>=Gt)break;e[s].add(a)}}i.lastIndex=0}}return{filePaths:[...e.filePaths],commands:[...e.commands],errors:[...e.errors],identifiers:[...e.identifiers],numbers:[...e.numbers]}}function gt(t){return t.filePaths.length===0&&t.commands.length===0&&t.errors.length===0&&t.identifiers.length===0&&t.numbers.length===0}function Ce(t){const e=["The following facts MUST appear verbatim in your summary (exact spelling,","no paraphrasing, no rounding, no path shortening). Include each one that is","relevant to the conversation:"],o=[["File paths",t.filePaths],["Commands",t.commands],["Errors",t.errors],["Identifiers",t.identifiers],["Numbers",t.numbers]];for(const[n,r]of o)if(r.length!==0){e.push("",`${n}:`);for(const s of r)e.push(`- ${s}`)}return e.join(`
|
|
4
|
+
`)}function ne(t,e){const o={filePaths:[],commands:[],errors:[],identifiers:[],numbers:[]};for(const n of Object.keys(o))for(const r of e[n])t.includes(r)||o[n].push(r);return o}function oe(t,e){if(gt(e))return t;const o=[t.trimEnd(),"","## Verbatim Anchors","(Facts below were present in the raw conversation and are reproduced verbatim.)"],n=[["File paths",e.filePaths],["Commands",e.commands],["Errors",e.errors],["Identifiers",e.identifiers],["Numbers",e.numbers]];for(const[r,s]of n)if(s.length!==0){o.push("",`${r}:`);for(const i of s)o.push(`- ${i}`)}return o.join(`
|
|
5
|
+
`)}function yt(t,e){const o=[];for(const n of t){const r={role:n.role,content:re(n.content,e)};n.tool_call_id&&(r.tool_call_id=n.tool_call_id),n.tool_calls&&n.tool_calls.length>0&&(r.tool_calls=n.tool_calls),o.push(r)}return o}function re(t,e){return!Number.isFinite(e)||t===null?t:typeof t=="string"?t.length<=e?t:J(t,e):Array.isArray(t)?t.map(o=>{if(typeof o=="object"&&o!==null&&o.type==="text"&&typeof o.text=="string"){const n=o.text;return n.length<=e?o:{...o,text:J(n,e)}}return o}):t}function se(t){const e=[];for(const o of t){const n=o.reasoning;typeof n!="string"||n.length===0||e.push(n.slice(0,pt))}if(e.length!==0)return e.join(`
|
|
11
6
|
|
|
12
|
-
`),
|
|
13
|
-
|
|
7
|
+
`)}function ie(t,e,o){const n=[];let r=[],s=0;for(const i of t){const l=yt([i],e)[0],a=b(Mt(l));r.length>0&&s+a>o&&(n.push(r),r=[],s=0),r.push(l),s+=a}return r.length>0&&n.push(r),n}function Mt(t){let o=typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(n=>typeof n=="object"&&n!==null?JSON.stringify(n):String(n)).join(" "):"";return t.tool_calls&&t.tool_calls.length>0&&(o+=` ${JSON.stringify(t.tool_calls)}`),o}function Ee(t,e,o=!0){return t.map((n,r)=>st(n,r,e,o)).join(`
|
|
8
|
+
`)}function be(t,e,o,n=!0){const r=[];let s=[],i=0;for(let l=0;l<t.length;l++){const a=st(t[l],l,e,n),m=b(a);s.length>0&&i+m>o&&(r.push(s.join(`
|
|
9
|
+
`)),s=[],i=0),s.push(a),i+=m}return s.length>0&&r.push(s.join(`
|
|
10
|
+
`)),r}function le(t,e,o=!0,n=0){const r=Math.max(1,e.summaryInputBudget-n),s=["S1","S2","S3","S4"];for(let m=0;m<X.length;m++){const _=X[m],M=yt(t,_);if(xt(M)<=r)return{step:s[m]??"S4",cap:_,chunks:[M],singleShot:!0}}const i=X[X.length-1]??2e3,l=ie(t,i,Math.floor(r*.9)),a=l.length<=dt?l:ae(l,dt);return{step:"S5",cap:i,chunks:a,singleShot:!1}}function xt(t){let e=0;for(const o of t)e+=b(Mt(o));return e}function ae(t,e){const o=Math.max(1,Math.min(e,t.length)),n=[];for(let r=0;r<o;r++){const s=Math.floor(r*t.length/o),i=Math.floor((r+1)*t.length/o);n.push(t.slice(s,Math.max(s+1,i)).flat())}return n}function ce(t){return new Promise(e=>setTimeout(e,t))}function ue(t){const e=new Set;for(const o of t)if(!(o.role!=="assistant"||!o.tool_calls?.length))for(const n of o.tool_calls)typeof n=="object"&&n!==null&&typeof n.id=="string"&&e.add(n.id);return e}function fe(t){const e=new Set;for(const o of t){if(o.role!=="tool")continue;const n=typeof o.tool_call_id=="string"?o.tool_call_id.trim():"";n!==""&&e.add(n)}return e}function $(t){if(!(t instanceof Error))return!1;if(t.name==="AbortError")return!0;const e=t.message.toLowerCase();return e.includes("aborted by user")||e.includes("summarization aborted")}function me(t){if(!(t instanceof Error))return!1;const e=t.message.toLowerCase();return/\b(408|429|5\d\d)\b/.test(e)||e.includes("fetch failed")||e.includes("timed out")||e.includes("timeout")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("etimedout")||e.includes("enotfound")||e.includes("socket hang up")||e.includes("network error")||e.includes("empty content")||e.includes("stream response has no body")}async function nt(t,e){const o=Math.max(1,Math.floor(e?.maxAttempts??1)),n=e?.baseDelayMs??Xt,r=e?.maxDelayMs??Jt,s=e?.jitterMs??Zt;let i=new Error("summarizer was never invoked");for(let l=1;l<=o;l++)try{const a=await t();if(typeof a!="string"||a.trim().length===0)throw new Error("summarizer returned empty content");return{summary:a,attempts:l}}catch(a){if(i=a instanceof Error?a:new Error(String(a)),a instanceof B||$(a))throw i;if(!me(a)||l>=o)throw new D(l,i);const _=Math.min(r,n*Math.pow(2,l-1));await ce(_+Math.random()*s)}throw new D(o,i)}async function de(t){const{removed:e,budget:o,llmSummarizer:n,anchors:r,previousSummary:s,retryPolicy:i,includeReasoning:l=!0,prefixMessages:a}=t,m=a?xt(a):0,_=le(e,o,l,m),M=gt(r)?void 0:r,g=o.summaryMaxTokens>0?o.summaryMaxTokens:void 0;let d=0;const f=l?se(e):void 0,u=a?.length?{prefixMessages:a}:{};if(_.singleShot){const C=await nt(()=>n({messages:_.chunks[0],messageCount:e.length,contextLimit:o.contextLimit,...u,...f?{reasoningText:f}:{},...s?{previousSummary:s}:{},...M?{anchors:M}:{},...g?{maxTokens:g}:{}}),i);return{summary:C.summary,step:_.step,chunks:1,attempts:C.attempts}}const h=new Array(_.chunks.length).fill(null);for(let C=0;C<_.chunks.length;C++){if(h[C]!==null)continue;const c=_.chunks[C],p=await nt(()=>n({messages:c,messageCount:e.length,contextLimit:o.contextLimit,...u,...f?{reasoningText:f}:{},...M?{anchors:M}:{},...g?{maxTokens:g}:{}}),i);h[C]=p.summary,d+=p.attempts}let A=h,O=0;for(;A.length>1&&O<ht;){const C=[],p=O===ht-1?A.length:Math.max(2,Math.ceil(A.length/4));for(let T=0;T<A.length;T+=p){const y=A.slice(T,T+p),S=y.map((I,K)=>`### Part ${T+K+1}
|
|
11
|
+
${I}`).join(`
|
|
14
12
|
|
|
15
|
-
`),
|
|
13
|
+
`),L=await nt(()=>n({messages:[{role:"user",content:S}],messageCount:y.length,contextLimit:o.contextLimit,...s?{previousSummary:s}:{},...g?{maxTokens:g}:{}}),i);C.push(L.summary),d+=L.attempts}A=C,O+=1}return{summary:A.length===1?A[0]:A.map((C,c)=>`### Part ${c+1}
|
|
14
|
+
${C}`).join(`
|
|
15
|
+
|
|
16
|
+
`),step:_.step,chunks:_.chunks.length,attempts:d}}function J(t,e){if(!t||t.length<=e)return t;const o=Math.max(F,Math.floor(e));if(t.length<=o)return t;const n=Math.floor(o*Wt),r=Math.max(0,o-n),s=t.length-n-r;return t.slice(0,n)+`
|
|
16
17
|
\u2026[truncated ${s} chars]\u2026
|
|
17
|
-
`+(r>0?t.slice(-r):"")}function
|
|
18
|
-
`)});
|
|
19
|
-
`)
|
|
20
|
-
`)
|
|
18
|
+
`+(r>0?t.slice(-r):"")}function he(t){return t.role!=="tool"||typeof t.content!="string"||t.content==="[Old tool result content cleared]"?!1:t.content.length>F}function pe(t,e){let o=0,n=0;if(e<=0||t.length===0)return{downsampleCount:o,droppedMessages:n};let r=R(t);if(r<=e)return{downsampleCount:o,droppedMessages:n};for(;r>e;){let s=-1,i=0;for(let _=0;_<t.length;_++){const M=t[_];if(!he(M))continue;const g=M.content.length;g>i&&(i=g,s=_)}if(s<0)break;const l=t[s],a=b(l.content),m=Math.max(F,Math.floor(i/2));l.content=J(l.content,m),r-=a-b(l.content),o+=1}for(;r>e;){const s=_e(t);if(s<=0||t.length-s<1)break;const i=t.slice(0,s);r-=R(i),t.splice(0,s),n+=s}for(;r>e;){let s=-1,i=0;for(let _=0;_<t.length;_++){const M=t[_];typeof M.content=="string"&&(M.content.length<=F||M.content!=="[Old tool result content cleared]"&&M.content.length>i&&(i=M.content.length,s=_))}if(s<0)break;const l=t[s],a=b(l.content),m=Math.max(F,Math.floor(i/2));l.content=J(l.content,m),r-=a-b(l.content),o+=1}return{downsampleCount:o,droppedMessages:n}}function _e(t){if(t.length<=1)return 0;let e=0;for(;e<t.length&&t[e].role==="system";)e+=1;if(e>=t.length)return 0;for(let o=e+1;o<t.length;o++)if(t[o].role==="user")return o-e;return 0}function Re(t,e){const o=e&&e>0?e:t;return o>0?o:t}const Z={"claude-4":{contextLimit:2e5,maxOutput:8192},"claude-sonnet-4":{contextLimit:2e5,maxOutput:8192},"claude-3-5-sonnet":{contextLimit:2e5,maxOutput:8192},"claude-3-opus":{contextLimit:2e5,maxOutput:8192},"claude-3-haiku":{contextLimit:2e5,maxOutput:8192},"claude-2":{contextLimit:1e5,maxOutput:4096},"gpt-4o":{contextLimit:128e3,maxOutput:16384},"gpt-4-turbo":{contextLimit:128e3,maxOutput:4096},"gpt-4":{contextLimit:8192,maxOutput:4096},"gpt-3.5-turbo":{contextLimit:16384,maxOutput:4096},o1:{contextLimit:2e5,maxOutput:1e5},"o3-mini":{contextLimit:2e5,maxOutput:1e5},"gemini-2.0-flash":{contextLimit:1048576,maxOutput:8192},"gemini-2.5-pro":{contextLimit:1048576,maxOutput:8192},"gemini-1.5-pro":{contextLimit:2097152,maxOutput:8192},"gemini-1.5-flash":{contextLimit:1048576,maxOutput:8192},deepseek:{contextLimit:64e3,maxOutput:8192},"deepseek-chat":{contextLimit:64e3,maxOutput:8192},"deepseek-reasoner":{contextLimit:64e3,maxOutput:8192},"qwen-max":{contextLimit:32e3,maxOutput:8192},"qwen-plus":{contextLimit:128e3,maxOutput:8192},"qwen-turbo":{contextLimit:1e6,maxOutput:8192},"glm-4":{contextLimit:128e3,maxOutput:4096},"yi-":{contextLimit:2e5,maxOutput:4096},"llama-3":{contextLimit:8192,maxOutput:4096},"llama-2":{contextLimit:4096,maxOutput:4096},mistral:{contextLimit:32e3,maxOutput:4096},mixtral:{contextLimit:32e3,maxOutput:4096},codestral:{contextLimit:256e3,maxOutput:8192},grok:{contextLimit:131072,maxOutput:4096},"nova-":{contextLimit:2e5,maxOutput:8192}};function Ie(t,e){if(e?.contextLimit&&e.contextLimit>0)return{contextLimit:e.contextLimit,maxOutput:e.maxOutput??U};if(!t)return{contextLimit:G,maxOutput:U};const o=t.toLowerCase().trim();if(Z[o])return Z[o];const n=Object.keys(Z).filter(r=>o.startsWith(r)).sort((r,s)=>s.length-r.length);return n.length>0?Z[n[0]]:{contextLimit:G,maxOutput:U}}import{estimateTextTokens as Je,estimateTokens as Ze}from"./token-estimator.js";function ge(t){if(typeof t=="object"&&t!==null){const e=t;return e.type==="text"&&typeof e.text=="string"?b(e.text):e.type==="image_url"||e.type==="document"?wt:Math.ceil(JSON.stringify(t).length/ut)}return typeof t=="string"?b(t):0}function V(t){return Buffer.byteLength(t,"utf8")}function Tt(t){let e=16;if(typeof t.content=="string")e+=V(t.content);else if(Array.isArray(t.content))for(const o of t.content)typeof o=="object"&&o!==null&&(e+=V(JSON.stringify(o)));return t.tool_calls&&(e+=V(JSON.stringify(t.tool_calls))),t.tool_call_id&&(e+=V(t.tool_call_id)),e}function Pe(t){let e=0;for(const o of t)e+=Tt(o);return e}function R(t){let e=0;for(const o of t){if(typeof o.content=="string")e+=b(o.content);else if(Array.isArray(o.content))for(const n of o.content)e+=ge(n);o.tool_calls&&(e+=Ot+Math.ceil(JSON.stringify(o.tool_calls).length/ut))}return e}function ot(t,e=0){return R(t)+Math.max(0,Math.floor(e))}function q(t){let e=0;for(const o of t)e+=Tt(o);return Math.round(e/1024*10)/10}function Le(t,e,o){if(e<=0)return!1;const n=R(t),r=Math.floor(e*H(e));return n>=r}function Ne(t,e,o){if(o<=0)return!1;const n=t+e,r=Math.floor(o*H(o));return n>=r}function At(t){return t.role==="tool"}function ve(t,e,o){if(!(t.role!=="tool"||!t.tool_call_id))for(let n=o-1;n>=0;n--){const r=e[n];if(r&&r.role==="assistant"&&Array.isArray(r.tool_calls)){for(const s of r.tool_calls)if(typeof s=="object"&&s!==null&&"id"in s&&s.id===t.tool_call_id){const i=s.function;return i?String(i.name??""):void 0}}}}function kt(t,e=G,o){if(t.length===0)return{prunedCount:0,freedTokens:0};const n=Math.min(Rt,Math.floor(e*Pt)),r=Math.min(It,Math.floor(e*Lt)),s=o?.ignoreMinimumGain===!0,i=new Map;for(const d of t)if(!(d.role!=="assistant"||!Array.isArray(d.tool_calls)))for(const f of d.tool_calls){if(typeof f!="object"||f===null)continue;const u=f,h=u.id,A=u.function;if(typeof h!="string"||!h||typeof A!="object"||A===null)continue;const O=A.name;typeof O=="string"&&i.set(h,O)}let l=0;const a=[],m=[];let _=0;for(let d=t.length-1;d>=0;d--){const f=t[d];if(f.role==="user"&&_++,_<2||!At(f))continue;const u=f.tool_call_id?i.get(f.tool_call_id):void 0;if(u&&ft.has(u))continue;const h=typeof f.content=="string"?f.content:"";if(h==="[Old tool result content cleared]")continue;const A=b(h);if(l+=A,l>n){const O=u?mt(u):W,P={msg:f,tokens:A,name:u??""};O<=1?m.push(P):a.push(P)}}if(a.sort((d,f)=>f.tokens-d.tokens),m.sort((d,f)=>d.tokens-f.tokens),s){const d=new Set([...a.map(f=>f.msg),...m.map(f=>f.msg)]);for(let f=t.length-1;f>=0;f--){const u=t[f];if(!At(u)||d.has(u))continue;const h=u.tool_call_id?i.get(u.tool_call_id):void 0;if(h&&ft.has(h))continue;const A=typeof u.content=="string"?u.content:"";if(A==="[Old tool result content cleared]")continue;const O={msg:u,tokens:b(A),name:h??""};(h?mt(h):W)<=1?m.push(O):a.push(O)}m.sort((f,u)=>f.tokens-u.tokens)}const M=[];let g=0;for(const d of a){if(!s&&g>=r)break;g+=d.tokens,M.push(d.msg)}if(s||g<r){for(const d of m)if(g+=d.tokens,M.push(d.msg),!s&&g>=r)break}if(!s&&g<r)return{prunedCount:0,freedTokens:0};for(const d of M)d.content="[Old tool result content cleared]";return{prunedCount:M.length,freedTokens:g}}function rt(t){return t.role==="system"&&typeof t.content=="string"&&t.content.startsWith(j)}function ye(t){return t.role==="system"&&typeof t.content=="string"&&t.content.startsWith(zt)}function Me(t){return t.role==="system"&&typeof t.content=="string"&&t.content.startsWith(Ut)}function st(t,e,o=Number.POSITIVE_INFINITY,n=!0){const r=typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l)).join(" "):"",s=Number.isFinite(o)&&r.length>o?`${r.slice(0,o)}\u2026[truncated ${r.length-o} chars]`:r,i=[`${e+1}. ${t.role}`];if(t.tool_calls&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0){const l=t.tool_calls.map(a=>{if(typeof a=="object"&&a!==null){const m=a.function;return m?String(m.name??""):""}return""}).filter(Boolean).join(", ");l&&i.push(`tool_calls=${l}`)}if(t.tool_call_id&&i.push(`tool_call_id=${t.tool_call_id}`),n&&t.reasoning){const l=t.reasoning.slice(0,pt);i.push(`thinking=${l}`)}return s&&i.push(`content=${s}`),i.join(" | ")}async function St(t,e){const o=e?.includeReasoning!==!1,n=e?.budget??_t({contextLimit:e?.contextLimit??G,maxOutput:U}),r=t.filter(c=>c.role==="system"&&!rt(c)&&!ye(c)&&!Me(c)),s=t.filter(c=>c.role!=="system"||rt(c)),i=Math.max(0,s.length-Nt),l=s.slice(0,i);let a=s.slice(i);const m=ue(l),_=fe(l);for(const c of l){if(c.role!=="tool")continue;const p=typeof c.tool_call_id=="string"?c.tool_call_id.trim():"";if(p===""||m.has(p))continue;const T=typeof c.content=="string"?c.content:JSON.stringify(c.content??"");c.role="user",delete c.tool_call_id,c.content=`[\u5DE5\u5177\u6267\u884C\u7ED3\u679C] \u5176\u5BF9\u5E94\u7684\u5DE5\u5177\u8C03\u7528\u4E0D\u5728\u672C\u6B21\u6458\u8981\u8303\u56F4\u5185\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF1A
|
|
19
|
+
${T}`}for(const c of l){if(c.role!=="assistant"||!c.tool_calls?.length)continue;const p=c.tool_calls.filter(T=>{if(typeof T!="object"||T===null)return!1;const y=T.id;return typeof y!="string"?!1:_.has(y)});if(p.length!==c.tool_calls.length){if(p.length>0){c.tool_calls=p;continue}delete c.tool_calls,(typeof c.content!="string"||c.content.length===0)&&(c.content="[\u52A9\u624B\u66FE\u53D1\u8D77\u4E00\u6B21\u5DE5\u5177\u8C03\u7528\uFF0C\u5176\u7ED3\u679C\u4E0D\u5728\u672C\u6B21\u6458\u8981\u8303\u56F4\u5185\u3002]")}}const M=new Set;for(const c of a)if(c.role==="assistant"&&c.tool_calls?.length)for(const p of c.tool_calls)typeof p=="object"&&p!==null&&typeof p.id=="string"&&M.add(p.id);a=a.filter(c=>{if(c.role==="tool"){const p=typeof c.tool_call_id=="string"?c.tool_call_id.trim():"";return p!==""&&M.has(p)}return!0});let g=!0;for(;g;){g=!1;const c=new Set;for(const y of a)if(y.role==="assistant"&&y.tool_calls?.length)for(const S of y.tool_calls)typeof S=="object"&&S!==null&&typeof S.id=="string"&&c.add(S.id);const p=new Set;for(const y of a)y.role==="tool"&&y.tool_call_id&&p.add(y.tool_call_id);const T=a.filter(y=>{if(y.role==="tool"){const S=typeof y.tool_call_id=="string"?y.tool_call_id.trim():"";return S!==""&&c.has(S)}if(y.role==="assistant"&&y.tool_calls?.length){const S=new Set;for(const I of y.tool_calls)typeof I=="object"&&I!==null&&typeof I.id=="string"&&S.add(I.id);if(S.size===0)return!0;let L=!0;for(const I of S)if(!p.has(I)){L=!1;break}return L}return!0});T.length!==a.length&&(g=!0,a=T)}if(a.length===0)return 0;const d=i>0?n.keepRecentTokens:Math.min(n.keepRecentTokens,n.targetTokens),f=pe(a,d);if(e?.stats&&(e.stats.downsampleCount+=f.downsampleCount,e.stats.droppedMessages+=f.droppedMessages),i===0){if(!(f.downsampleCount>0||f.droppedMessages>0))return 0;const p=new Set(a),T=[];let y=0;for(const S of t)if(p.has(S)){const L=a[y++];L&&T.push(L)}else T.push(S);for(;y<a.length;y++)T.push(a[y]);return t.length=0,t.push(...T),0}const u=ee(l);let h=null,A,O,P=0;const C=e?.allowRuleFallback!==!1;if(e?.llmSummarizer)try{const c=await de({removed:l,budget:n,llmSummarizer:e.llmSummarizer,anchors:u,includeReasoning:o,...e.previousSummary?{previousSummary:e.previousSummary}:{},...e.retryPolicy?{retryPolicy:e.retryPolicy}:{},...e.prefixMessages?.length?{prefixMessages:e.prefixMessages}:{}}),p=ne(c.summary,u);h=oe(c.summary,p),A=c.step,O=c.chunks,P=c.attempts}catch(c){if(c instanceof B||$(c)||!C||!(c instanceof D))throw c;h=null}if(t.length=0,t.push(...r),h!==null)t.push({role:"system",content:[j,`${i} earlier conversation messages were summarized by LLM to free context space.`,"Preserve the user's goal, known facts, completed work, in-progress work, next steps, file paths, and errors from this summary.","Continue from where the work left off \u2014 do not redo completed tasks.","Recent messages below remain authoritative.","",h].join(`
|
|
20
|
+
`)});else{const p=l.map((T,y)=>st(T,y)).join(`
|
|
21
|
+
`).slice(0,vt);t.push({role:"system",content:[j,`${i} earlier conversation messages were summarized to free context space.`,"Preserve the user's goal, known facts, completed work, in-progress work, next steps, file paths, and errors from this summary.","Continue from where the work left off \u2014 do not redo completed tasks.","Recent messages below remain authoritative.","",p].join(`
|
|
22
|
+
`)})}return t.push(...a),i}function it(t){if(t.length<=1)return 0;let e=0;for(;e<t.length&&t[e].role==="system";)e++;if(e>=t.length)return 0;let o=t.length;for(let i=e+1;i<t.length;i++)if(t[i].role==="user"){o=i;break}if(o>=t.length)return 0;const n=new Set;for(let i=e;i<o;i++){const l=t[i];if(l.role==="assistant"&&Array.isArray(l.tool_calls))for(const a of l.tool_calls)typeof a=="object"&&a!==null&&typeof a.id=="string"&&n.add(a.id)}const r=o-e;t.splice(e,r);let s=0;for(let i=t.length-1;i>=e;i--){const l=t[i];if(l.role!=="tool")continue;const a=typeof l.tool_call_id=="string"?l.tool_call_id.trim():"";(a===""||n.has(a))&&(t.splice(i,1),s++)}return r+s}function xe(t){for(let e=t.length-1;e>=0;e--){const o=t[e];if(!rt(o))continue;const n=typeof o.content=="string"?o.content:"";return(n.startsWith(j)?n.slice(j.length).trim():n).slice(0,Vt)}}function Te(t){let e=0;for(const o of t){if(o.role!=="tool")continue;const n=typeof o.content=="string"?o.content:"";n&&(n.startsWith("[tool output omitted")||(o.content=`[tool output omitted: ${n.length} chars]`,e+=1))}return e}function Ae(t){let e=0;for(const o of t)o.reasoning&&(delete o.reasoning,e+=1);return e}async function ze(t,e,o=U,n){const r=q(t),s=t.length,i=R(t);let l="none",a=0,m=0,_=0,M=!1,g=1,d,f=!1;const u={downsampleCount:0,droppedMessages:0},h=n?.budget??_t({contextLimit:e,maxOutput:o,...n?.inputLimit?{inputLimit:n.inputLimit}:{},...n?.toolsTokens?{toolsTokens:n.toolsTokens}:{}}),A=Math.floor(e*H(e)),O=R(t),P=n?.actualUsedTokens?Math.max(O,n.actualUsedTokens):O;if(!(n?.force===!0||P>=A))return{strategy:"none",freedTokens:0,sizeBeforeKB:r,sizeAfterKB:r,tokensBefore:i,tokensAfter:i,contextTokensAfter:ot(t,h.toolsTokens),messageCountBefore:s,messageCountAfter:s,prunedToolMessages:0,summarizedMessages:0,level:1,downsampleCount:u.downsampleCount,droppedMessages:u.droppedMessages,noSummary:!0,reachedTarget:v(t,h)};if(n?.llmSummarizer){n?.onPhase&&n.onPhase({phase:"prune_start",messageCount:t.length});const x=kt(t,e);n?.onPhase&&n.onPhase({phase:"prune_end",prunedCount:x.prunedCount,freedTokens:x.freedTokens}),x.prunedCount>0&&(l="prune",a+=x.prunedCount)}if(!n?.llmSummarizer){n?.onPhase&&n.onPhase({phase:"prune_start",messageCount:t.length});const x=kt(t,e);n?.onPhase&&n.onPhase({phase:"prune_end",prunedCount:x.prunedCount,freedTokens:x.freedTokens});let E=0;(n?.force===!0||P>=A)&&(n?.onPhase&&n.onPhase({phase:"summarize_start",messageCount:t.length}),E=await St(t,{contextLimit:e,budget:h}),E===0&&(E=it(t)),n?.onPhase&&n.onPhase({phase:"summarize_end",summarizedCount:E,usedLLM:!1,level:2}));const w=R(t),k=q(t),N=v(t,h);return{strategy:x.prunedCount>0?E>0?"prune+summarize":"prune":E>0?"summarize":"none",freedTokens:Math.max(0,i-w),sizeBeforeKB:r,sizeAfterKB:k,tokensBefore:i,tokensAfter:w,contextTokensAfter:ot(t,h.toolsTokens),messageCountBefore:s,messageCountAfter:t.length,prunedToolMessages:x.prunedCount,summarizedMessages:E,level:2,downsampleCount:u.downsampleCount,droppedMessages:u.droppedMessages,noSummary:!0,reachedTarget:N}}const c=xe(t);let p;const T=async(x,E,w)=>{if(!n?.llmSummarizer)return"empty";n?.onPhase&&n.onPhase({phase:"summarize_start",messageCount:t.length});const k=await St(t,{llmSummarizer:n.llmSummarizer,contextLimit:e,budget:h,includeReasoning:w,allowRuleFallback:n.allowRuleFallback,...n.retryPolicy?{retryPolicy:n.retryPolicy}:{},...c?{previousSummary:c}:{},...n.prefixMessages?.length?{prefixMessages:n.prefixMessages}:{},stats:u});return k<=0?"empty":(g=x,d=E,l=a>0?"prune+summarize":"summarize",m+=k,M=!!t.find(z=>z.role==="system"&&typeof z.content=="string"&&z.content.includes("summarized by LLM")),n?.onPhase&&n.onPhase({phase:"summarize_end",summarizedCount:m,usedLLM:M,level:g}),"ok")};let y=!1,S=!1;try{await T(1,"LLM \u6458\u8981\uFF08\u9AD8\u4FDD\u771F\uFF09",!0)==="empty"&&(S=!0)}catch(x){if($(x)||!(x instanceof B))throw x;p=x,y=!0,n?.onPhase&&n.onPhase({phase:"degrade",level:2,reason:x instanceof Error?x.message:String(x)})}if(S){const x=R(t),E=Math.max(0,i-x);if(!(u.downsampleCount>0||u.droppedMessages>0)||E===0)return{strategy:"none",freedTokens:0,sizeBeforeKB:r,sizeAfterKB:r,tokensBefore:i,tokensAfter:i,messageCountBefore:s,messageCountAfter:s,prunedToolMessages:0,summarizedMessages:0,level:1,downsampleCount:u.downsampleCount,droppedMessages:u.droppedMessages,noSummary:!0,reachedTarget:v(t,h)};let k=0;for(;!v(t,h);){const tt=it(t);if(tt<=0)break;k+=tt}const N=R(t),z=Math.max(0,i-N),ct=q(t);return k>0&&(g=4,d="\u9010\u8F6E\u622A\u65AD\uFF08\u65E0\u65E9\u671F\u5BF9\u8BDD\u53EF\u6458\uFF09",m+=k),{strategy:k>0?"summarize":"prune",freedTokens:z,sizeBeforeKB:r,sizeAfterKB:ct,tokensBefore:i,tokensAfter:N,messageCountBefore:s,messageCountAfter:t.length,prunedToolMessages:0,summarizedMessages:k,level:g,...d?{levelLabel:d}:{},downsampleCount:u.downsampleCount,droppedMessages:u.droppedMessages,noSummary:!0,reachedTarget:v(t,h)}}if(y)if(Yt&&v(t,h))f=!0;else{const x=Te(t);x>0&&(a+=x,l=m>0?"prune+summarize":"prune");let E=!1;try{if(await T(2,"\u53BB\u9664\u5DE5\u5177\u8F93\u51FA\u540E\u6458\u8981",!0)!=="ok")throw new D(1,new Error("summarize produced nothing"))}catch(w){if($(w)||!(w instanceof B))throw w;p=w,E=!0,n?.onPhase&&n.onPhase({phase:"degrade",level:3,reason:w instanceof Error?w.message:String(w)})}if(E){Ae(t);let w=!1;try{if(await T(3,"\u4EC5\u660E\u9762\u6587\u672C\u6458\u8981",!1)!=="ok")throw new D(1,new Error("summarize produced nothing"))}catch(k){if($(k)||!(k instanceof B))throw k;p=k,w=!0,n?.onPhase&&n.onPhase({phase:"degrade",level:4,reason:k instanceof Error?k.message:String(k)})}if(w){let k=0;for(;!v(t,h);){const N=it(t);if(N<=0)break;k+=N}if(k>0)g=4,d="\u9010\u8F6E\u622A\u65AD\uFF08\u515C\u5E95\uFF09",l="summarize",m+=k,f=!0;else if(p&&m===0)throw p}}}const I=q(t),K=t.length,Q=R(t),lt=ot(t,h.toolsTokens);_=Math.max(_,Math.max(0,i-Q));const at=v(t,h);return l==="none"?{strategy:"none",freedTokens:0,sizeBeforeKB:r,sizeAfterKB:r,tokensBefore:i,tokensAfter:Q,contextTokensAfter:lt,messageCountBefore:s,messageCountAfter:K,prunedToolMessages:0,summarizedMessages:0,level:g,downsampleCount:u.downsampleCount,droppedMessages:u.droppedMessages,noSummary:!0,reachedTarget:at}:{strategy:l,freedTokens:_,sizeBeforeKB:r,sizeAfterKB:I,tokensBefore:i,tokensAfter:Q,contextTokensAfter:lt,messageCountBefore:s,messageCountAfter:K,prunedToolMessages:a,summarizedMessages:m,level:g,...d?{levelLabel:d}:{},downsampleCount:u.downsampleCount,droppedMessages:u.droppedMessages,noSummary:f,reachedTarget:at}}export{Ct as COMPACTION_BUFFER,we as COMPACTION_LLM_PROMPT_TEMPLATE,Et as COMPACTION_TRIGGER_RATIO,De as ESTIMATION_ASCII_CHARS_PER_TOKEN,Fe as ESTIMATION_CJK_CHARS_PER_TOKEN,Ye as ESTIMATION_IMAGE_TOKENS,Ke as ESTIMATION_SAFE_PADDING,Ge as ESTIMATION_TOOL_OVERHEAD,It as PRUNE_MINIMUM,Rt as PRUNE_PROTECT,Ut as RUNTIME_INSTRUCTIONS_PREFIX,zt as RUNTIME_RESOURCES_PREFIX,B as SummaryOverflowError,D as SummaryUnavailableError,oe as appendMissingAnchors,_t as calculateCompactionBudget,qt as calculateCompactionThreshold,Pe as conversationSizeBytes,q as conversationSizeKB,J as downsampleToolContent,ot as estimateContextTokens,R as estimateConversationTokens,Je as estimateTextTokens,Ze as estimateTokens,ee as extractFidelityAnchors,ne as findMissingAnchors,Oe as fitsHardWindow,H as getCompactionTriggerRatio,v as hasReachedTarget,rt as isCompactionSummaryMessage,gt as isEmptyAnchors,Le as isOverflow,Ne as isOverflowByActualUsage,Me as isRuntimeInstructionsMessage,ye as isRuntimeResourcesMessage,Ie as lookupModelLimits,ze as performCompaction,kt as pruneToolOutputs,Ce as renderAnchorsForPrompt,Re as resolveReplayWindow,pe as shrinkRetainedWindow,it as snipOldestMessageGroup,St as summarizeConversation};
|
|
21
23
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
export declare const MICROCOMPACT_CLEARED_TOOL_RESULT = "[Old tool result content cleared]";
|
|
4
|
+
|
|
5
|
+
export declare const MICROCOMPACT_KEEP_RECENT_TOOL_RESULTS = 5;
|
|
6
|
+
|
|
7
|
+
export declare const MICROCOMPACT_MIN_TOKEN_SAVINGS = 256;
|
|
8
|
+
|
|
9
|
+
export declare const MICROCOMPACT_THRESHOLD_RATIO = 0.9;
|
|
10
|
+
|
|
11
|
+
export declare const MICROCOMPACT_THRESHOLD_BUFFER_TOKENS = 2000;
|
|
12
|
+
|
|
13
|
+
export declare const MICROCOMPACT_COMPACTABLE_TOOLS: readonly string[];
|
|
14
|
+
|
|
15
|
+
export interface MicrocompactMessage {
|
|
16
|
+
role: string;
|
|
17
|
+
content: unknown;
|
|
18
|
+
tool_call_id?: string;
|
|
19
|
+
tool_calls?: unknown[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type MicrocompactReason = "disabled" | "not_triggered" | "no_candidates" | "nothing_to_clear" | "below_min_savings" | "applied";
|
|
23
|
+
|
|
24
|
+
export interface MicrocompactDecision {
|
|
25
|
+
reason: MicrocompactReason;
|
|
26
|
+
|
|
27
|
+
estimatedTokenCount: number;
|
|
28
|
+
|
|
29
|
+
thresholdTokens: number;
|
|
30
|
+
|
|
31
|
+
preTokenCount?: number;
|
|
32
|
+
|
|
33
|
+
postTokenCount?: number;
|
|
34
|
+
|
|
35
|
+
tokensSaved?: number;
|
|
36
|
+
|
|
37
|
+
clearedCount?: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface MicrocompactConfig {
|
|
41
|
+
|
|
42
|
+
enabled?: boolean;
|
|
43
|
+
|
|
44
|
+
thresholdTokens?: number;
|
|
45
|
+
|
|
46
|
+
keepRecentToolResults?: number;
|
|
47
|
+
|
|
48
|
+
minTokenSavings?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export declare function buildMicrocompactThreshold(autoCompactThreshold: number): number;
|
|
52
|
+
|
|
53
|
+
export declare function isClearedToolResult(content: unknown): boolean;
|
|
54
|
+
|
|
55
|
+
export declare function maybeMicrocompact(messages: MicrocompactMessage[], config: MicrocompactConfig | undefined, options: {
|
|
56
|
+
autoCompactThreshold: number;
|
|
57
|
+
}): MicrocompactDecision;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{estimateTokens as C}from"./token-estimator.js";const T="[Old tool result content cleared]",R=5,b=256,k=.9,x=2e3,N=["read_file","Read","bash","Bash","grep","Grep","glob","Glob","web_fetch","WebFetch","web_search","WebSearch","edit","Edit","write","Write","apply_patch","ApplyPatch"],A=new Set(["skill","todo_write","todo_read","task","exit_plan_mode"]);function S(e){const t=Math.floor(e*k),r=e-x;return Math.max(0,Math.min(t,r))}function g(e){const t=new Map;for(const r of e)if(!(r.role!=="assistant"||!Array.isArray(r.tool_calls)))for(const o of r.tool_calls){if(typeof o!="object"||o===null)continue;const n=o,l=n.id,s=n.function;if(typeof l!="string"||!l||typeof s!="object"||s===null)continue;const a=s.name;typeof a=="string"&&t.set(l,a)}return t}function E(e){return typeof e=="string"&&e===T}function I(e){return Array.isArray(e)?e.some(t=>{if(typeof t!="object"||t===null)return!1;const r=t.type;return r==="image_url"||r==="image"||r==="file"}):!1}function P(e,t){const r=[];let o;const n=()=>{o&&o.length>0&&r.push(o),o=void 0};for(let l=0;l<e.length;l+=1){const s=e[l];if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){n(),o=[];continue}if(s.role!=="tool")continue;const a=s.tool_call_id;if(typeof a!="string"||!a)continue;const i=t.get(a);if(i&&!A.has(i)&&!E(s.content)&&!I(s.content)){if(!o){r.push([{index:l,toolCallId:a}]);continue}o.push({index:l,toolCallId:a})}}return n(),r}function _(e){if(typeof e=="string")return C(e);if(e==null)return 0;try{return C(JSON.stringify(e))}catch{return 0}}function O(e){let t=0;for(const r of e)t+=_(r.content);return t}function v(e,t,r){const o=typeof t?.thresholdTokens=="number"&&t.thresholdTokens>0?Math.floor(t.thresholdTokens):S(r.autoCompactThreshold),n=O(e);if(t?.enabled===!1)return{reason:"disabled",estimatedTokenCount:n,thresholdTokens:o};if(t?.enabled!==!0)return{reason:"disabled",estimatedTokenCount:n,thresholdTokens:o};if(n<o)return{reason:"not_triggered",estimatedTokenCount:n,thresholdTokens:o};const l=g(e),s=P(e,l);if(s.length===0)return{reason:"no_candidates",estimatedTokenCount:n,thresholdTokens:o};const a=typeof t?.keepRecentToolResults=="number"&&t.keepRecentToolResults>0?Math.floor(t.keepRecentToolResults):R,i=Math.max(1,a),d=Math.max(0,s.length-i);if(d===0)return{reason:"nothing_to_clear",estimatedTokenCount:n,thresholdTokens:o};const f=s.slice(0,d).flat(),m=f.reduce((c,u)=>{const h=e[u.index];return h?c+_(h.content):c},0),M=typeof t?.minTokenSavings=="number"&&t.minTokenSavings>=0?Math.floor(t.minTokenSavings):b;if(m<M)return{reason:"below_min_savings",estimatedTokenCount:n,thresholdTokens:o,preTokenCount:n,postTokenCount:n,tokensSaved:0,clearedCount:0};for(const c of f){const u=e[c.index];u&&(u.content=T)}const p=O(e),y=Math.max(0,n-p);return{reason:"applied",estimatedTokenCount:n,thresholdTokens:o,preTokenCount:n,postTokenCount:p,tokensSaved:y,clearedCount:f.length}}export{T as MICROCOMPACT_CLEARED_TOOL_RESULT,N as MICROCOMPACT_COMPACTABLE_TOOLS,R as MICROCOMPACT_KEEP_RECENT_TOOL_RESULTS,b as MICROCOMPACT_MIN_TOKEN_SAVINGS,x as MICROCOMPACT_THRESHOLD_BUFFER_TOKENS,k as MICROCOMPACT_THRESHOLD_RATIO,S as buildMicrocompactThreshold,E as isClearedToolResult,v as maybeMicrocompact};
|
|
2
|
+
|
|
@@ -156,6 +156,8 @@ export declare class ACodeRuntime extends EventEmitter {
|
|
|
156
156
|
|
|
157
157
|
private handleCompactionPhase;
|
|
158
158
|
|
|
159
|
+
private runMicrocompactPass;
|
|
160
|
+
|
|
159
161
|
private runCompactionPass;
|
|
160
162
|
|
|
161
163
|
compactContext(): {
|
|
@@ -299,6 +301,8 @@ export declare class ACodeRuntime extends EventEmitter {
|
|
|
299
301
|
|
|
300
302
|
private prepareToolCall;
|
|
301
303
|
|
|
304
|
+
private emitCallToolEvent;
|
|
305
|
+
|
|
302
306
|
private resolveToolConcurrencyDeclaration;
|
|
303
307
|
|
|
304
308
|
private runBuiltInToolCall;
|