qlogicagent 2.24.12 → 2.24.14
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/dist/agent.js +8 -8
- package/dist/cli.js +7 -7
- package/dist/embedded.js +8 -8
- package/dist/index.js +129 -130
- package/dist/orchestration.js +8 -8
- package/dist/types/agent/tool-loop/stream-error-recovery.d.ts +0 -1
- package/dist/types/agent/types.d.ts +0 -5
- package/dist/types/orchestration/context/turn-loop-guard.d.ts +2 -16
- package/dist/types/orchestration/index.d.ts +1 -1
- package/dist/types/protocol/wire/acp-protocol.d.ts +1 -1
- package/dist/types/protocol/wire/index.d.ts +2 -2
- package/dist/types/protocol/wire/notification-payloads.d.ts +17 -5
- package/dist/types/runtime/config/tunable-defaults.d.ts +0 -6
- package/dist/types/runtime/ports/model-transport-contracts.d.ts +15 -13
- package/package.json +2 -4
package/dist/orchestration.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
function pe(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function de(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var fe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},me=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ye=512,Te=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var he=new Set([500,502,503,504,521,522,523,524,529]),Ce=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],be=["upgrade your plan","upgrade plan","current plan","subscription"],_e=["daily","weekly","monthly"],Re=["try again","retry","temporary","cooldown"],xe=["usage limit","rate limit","organization usage"],ke=["organization","workspace"],Ae=["billing period","exceeded","reached","exhausted"],Ee=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Se=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function T(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Me(e){return T(e,y.format)}function
|
|
2
|
-
${JSON.stringify(e)}`}}var X=4;function K(e){return{role:"
|
|
1
|
+
function pe(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function de(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var fe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},me=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ye=512,Te=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var he=new Set([500,502,503,504,521,522,523,524,529]),Ce=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],be=["upgrade your plan","upgrade plan","current plan","subscription"],_e=["daily","weekly","monthly"],Re=["try again","retry","temporary","cooldown"],xe=["usage limit","rate limit","organization usage"],ke=["organization","workspace"],Ae=["billing period","exceeded","reached","exhausted"],Ee=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Se=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function T(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Me(e){return T(e,y.format)}function j(e){return T(e,y.rateLimit)}function Ie(e){return T(e,y.timeout)}function ve(e){return fe.test(e)}function x(e){let t=e.toLowerCase();return t?e.length>ye?ge.test(t):T(t,y.billing)?!0:me.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function G(e){return T(e,y.authPermanent)}function we(e){return T(e,y.auth)}function q(e){return T(e,y.overloaded)}function g(e,t){return t.some(n=>e.includes(n))}function Oe(e){return g(e,Ce)||g(e,be)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Le(e){let t=g(e,_e),n=e.includes("spend limit")||e.includes("spending limit"),o=g(e,ke);return g(e,Re)&&g(e,xe)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||g(e,Ae))}function Pe(e){return e.trim().toLowerCase().replace(Se,"").trim()}function z(e){let t=Pe(e);return!t||Oe(t)?"billing":j(t)||Le(t)?"rate_limit":"billing"}function Ne(e){return Ee.test(e)?z(e):null}function $(e){let t=e.match(Te);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Fe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function De(e){let t=e.trim();if(!t)return!1;let n=$(t);return n?he.has(n.code):!1}function H(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?z(t):"billing":e===429?"rate_limit":e===401||e===403?t&&G(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&q(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&x(t)?"billing":"format":null}function Be(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ue(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Y(e){if(Ue(e))return"session_expired";if(Be(e))return"model_not_found";let t=Ne(e);return t||(ve(e)?x(e)?"billing":"rate_limit":j(e)?"rate_limit":q(e)?"overloaded":De(e)?$(e.trim())?.code===529?"overloaded":"timeout":Fe(e)?"timeout":Me(e)?"format":x(e)?"billing":Ie(e)?"timeout":G(e)?"auth_permanent":we(e)?"auth":null)}var je=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e){return je.has(e)}var Ge={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function qe(e,t){let n=H(e,t)??(t?Y(t):null);return n?Ge[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function V(e){return typeof e.compressAsync=="function"}var _="[Context capsule v1]";function h(e){return e.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*["']?[^\s"',;]+/giu,"$1=[REDACTED]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/gu,"[REDACTED_TOKEN]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/giu,"Bearer [REDACTED]")}function ze(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function k(e){if(!(!e||typeof e.content!="string"||!e.content.startsWith(_)))try{let t=JSON.parse(e.content.slice(_.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function $e(e,t,n,o){let r=e.map(l=>l.itemId).filter(l=>!!l),s={...o?.state.anchors??{}};for(let l of e)for(let u of l.contextAnchors??[]){let p=s[u.category]??[];s[u.category]=[...new Set([...p,h(u.value)])].slice(-50)}let i=[...o?.state.userRequests??[],...e.filter(l=>l.role==="user").map(l=>h(typeof l.content=="string"?l.content:JSON.stringify(l.content??"")))].slice(-50),c={summary:h(t),userRequests:i,anchors:s},a={version:1,sourceMessageCount:(o?.receipt.sourceMessageCount??0)+e.length,sourceItemIds:[...new Set([...o?.receipt.sourceItemIds??[],...r])].slice(-200),firstItemId:o?.receipt.firstItemId??r[0],lastItemId:r.at(-1)??o?.receipt.lastItemId,priorDigest:o?.receipt.digest,tokensBefore:(o?.receipt.tokensBefore??0)+e.reduce((l,u)=>l+n(u),0)};return{receipt:{...a,digest:ze(JSON.stringify({receipt:a,state:c}))},state:c}}function He(e){return{role:"user",content:`${_}
|
|
2
|
+
${JSON.stringify(e)}`}}var X=4;function K(e){return{role:"user",content:`[${e} earlier messages removed to fit the context budget]`}}var A=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let s=n;for(let p of o)s-=this.estimateTokens(p);let i;for(let p of r)if(p.role==="user"){i=p;break}if(i&&(s-=this.estimateTokens(i)),s<=0){let p=r.length-(i?1:0),d=i?[...o,i]:[...o];return p>0&&d.push(K(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let c=[],a=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===i)continue;let f=this.estimateTokens(d);if(s-f<0&&a>=X)break;if(s-f<0&&a<X){c.unshift(d),a++;continue}s-=f,c.unshift(d),a++}let l=r.length-(c.length+(i&&!c.includes(i)?1:0)),u=[...o];return i&&!c.includes(i)&&u.push(i),l>0&&u.push(K(l)),u.push(...c),{messages:u,droppedCount:l,strategy:"sliding-window"}}},E=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(a=>a.role==="system"),r=t.filter(a=>a.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let s=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),c=this.summarize(s);return{messages:[...o,{role:"user",content:`[Conversation summary]
|
|
3
3
|
${c}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},S=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:Ye(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ye(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let s=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
4
4
|
`),n.lastIndexOf(`]
|
|
5
5
|
`));if(s>t*.5)return n.slice(0,s+1)+`
|
|
6
6
|
[...truncated: ${e.length-s-1} chars omitted]`}let r=n.lastIndexOf(`
|
|
7
7
|
`);return r>t*.7?n.slice(0,r)+`
|
|
8
8
|
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
9
|
-
[...truncated: ${e.length-t} chars omitted]`}function J(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Preserve exact non-secret operational facts: file paths, URLs, port numbers, numeric values, version numbers, proper nouns, identifiers, and user-provided constraints. Never reproduce passwords, API keys, bearer tokens, cookies, or credentials; write [REDACTED] instead.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact non-secret values, identifiers, and keywords. Redact every secret even if the user asked to remember it. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let c=h(typeof i.content=="string"?i.content:JSON.stringify(i.content??"")),
|
|
10
|
-
`)}var M=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??Ve,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),
|
|
11
|
-
${JSON.stringify(
|
|
9
|
+
[...truncated: ${e.length-t} chars omitted]`}function J(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Preserve exact non-secret operational facts: file paths, URLs, port numbers, numeric values, version numbers, proper nouns, identifiers, and user-provided constraints. Never reproduce passwords, API keys, bearer tokens, cookies, or credentials; write [REDACTED] instead.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact non-secret values, identifiers, and keywords. Redact every secret even if the user asked to remember it. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let c=h(typeof i.content=="string"?i.content:JSON.stringify(i.content??"")),a=i.role==="user"?c:c.length>2e3?c.slice(0,2e3)+"...":c;return`[${i.role}]: ${a}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),s.join(`
|
|
10
|
+
`)}var M=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??Ve,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),r=t.findIndex(m=>k(m)!==void 0),s=k(r>=0?t[r]:void 0),i=r>=0?[...t.slice(0,r),...t.slice(r+1)]:t,{system:c,nonSystem:a}=Ke(i),l=t.reduce((m,R)=>m+this.config.estimateTokens(R),0);if(l<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let m=0;m<a.length&&(a[m].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));m++)u=m+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(a.length*.4)),f=Math.max(u,a.length-d);if(f<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let se=a.slice(0,u),C=a.slice(u,f),ie=a.slice(f),ae=J(C,{taskContext:[this.config.taskContext,s?`Prior verified capsule:
|
|
11
|
+
${JSON.stringify(s.state)}`:void 0].filter(Boolean).join(`
|
|
12
12
|
|
|
13
|
-
`)||void 0}),le=h(await this.config.summarize(C,ae)),ce=He($e(C,le,this.config.estimateTokens,c)),B=[...l,...se,ce,...ie],ue=Date.now()-o,U=B.reduce((m,R)=>m+this.config.estimateTokens(R),0);return{messages:B,droppedCount:C.length,strategy:"head-tail-protected",metrics:{tokensBefore:a,tokensAfter:U,compressionRatio:a>0?U/a:1,latencyMs:ue,usedLlm:!0,cacheInvalidated:!0}}}},v=class{config;constructor(t){this.config=t}compress(t,n){let o=b(t),r=this.config.inner.compress(t,n),s=b(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=b(t),r=V(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=b(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Z={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function We(e={}){let t={...Z,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function Xe(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var I=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,s=0,i=0;for(let c of this.events)n+=c.tokensBefore>0?c.tokensAfter/c.tokensBefore:1,o+=c.latencyMs,r+=Math.max(0,c.tokensBefore-c.tokensAfter),c.usedLlm&&s++,c.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},w=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function Ke(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function Ve(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function b(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}function Q(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Je(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Ze(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Qe(e){if(!e.eligibility?.length)return[...e.tools];let t=Ze(e.eligibility);return e.tools.filter(n=>{let o=Q(n);if(!o)return!1;let r=t.get(o);return!r||Je(r.status)})}function et(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function tt(e){let t=et({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Qe({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let c=r.filter(l=>Q(l)===i);if(c.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:c,normalizedToolChoice:{type:"function",function:{name:i}},warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var nt=["stop","aborted","timeout","cancelled","interrupted","error"],ot=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ee(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function rt(e,t){return{...e,...t,content:[...ee(e.content),...ee(t.content)]}}function st(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function it(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=st(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let c=e[i];c?.role==="tool"&&typeof c.tool_call_id=="string"&&s.has(c.tool_call_id)&&(n.push(c),t.add(i))}}return n}function at(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function lt(e){return new Set((e??nt).map(t=>t.trim().toLowerCase()))}function te(e,t){return e?lt(t).has(e.trim().toLowerCase()):!1}function ct(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function O(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let a=l.tool_calls.filter(u=>at(u));return{...l,...a.length>0?{tool_calls:a}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let a of l.tool_calls)typeof a.id=="string"&&a.id&&n.add(a.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let a=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(a.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&s.push(p);continue}if(a.length<l.tool_calls.length){s.push({...l,tool_calls:a});continue}}s.push(l)}let i=it(s),c=[];for(let l of i){let a=c.length>0?c[c.length-1]:void 0;if(l.role==="user"&&a?.role==="user"){c[c.length-1]=rt(a,l);continue}c.push(l)}return c}function L(e,t){return te(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ot)delete o[r];return o}):[...e]}function P(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function ut(e,t){let n=O(e),o=L(n,t);return P(o,t)}function ne(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=te(t?.stopReason,t?.forcedStopReasons),r=[];for(let a=0;a<e.length;a+=1){let u=e[a];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(a+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=ct(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let a of r){if(a.type!=="function_call")continue;let u=typeof a.call_id=="string"&&a.call_id?a.call_id:typeof a.id=="string"?a.id:void 0;u&&(s.add(u),i.set(u,a))}let c=new Set,l=[];for(let a of r)if(!(o&&a.type==="function_call")){if(a.type==="function_call_output"){let u=typeof a.call_id=="string"?a.call_id:"";if(!u||!s.has(u))continue;c.add(u)}l.push(a)}for(let[a]of i)c.has(a)||o||l.push({type:"function_call_output",call_id:a,output:n});return l}function pt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function dt(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function ft(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function mt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function oe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function gt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function yt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Tt(e){let t=[],n=O(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=L(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=P(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:oe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:pt(r),completedToolCallIds:dt(r)}),recoveryActions:t}}function ht(e){let t=ne(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:oe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:ft(t),completedToolCallIds:mt(t)}),recoveryActions:n}}var Ct=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function bt(e){return e?Ct.has(e):!0}function _t(e){return e===429||e===529}function Rt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var un={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function xt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var dn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var N=4;var fn=50*1024,mn=500*1024,gn=500*1024*1024,yn=50*1024*1024;var F="<fork-child-context>",re="Fork started \u2014 processing in background";function kt(e){return JSON.stringify(e).includes(F)}function At(e){return e<N}function Et(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
13
|
+
`)||void 0}),le=h(await this.config.summarize(C,ae)),ce=He($e(C,le,this.config.estimateTokens,s)),B=[...c,...se,ce,...ie],ue=Date.now()-o,U=B.reduce((m,R)=>m+this.config.estimateTokens(R),0);return{messages:B,droppedCount:C.length,strategy:"head-tail-protected",metrics:{tokensBefore:l,tokensAfter:U,compressionRatio:l>0?U/l:1,latencyMs:ue,usedLlm:!0,cacheInvalidated:!0}}}},I=class{config;constructor(t){this.config=t}compress(t,n){let o=b(t),r=this.config.inner.compress(t,n),s=b(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=b(t),r=V(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=b(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Z={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function We(e={}){let t={...Z,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function Xe(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var v=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,s=0,i=0;for(let c of this.events)n+=c.tokensBefore>0?c.tokensAfter/c.tokensBefore:1,o+=c.latencyMs,r+=Math.max(0,c.tokensBefore-c.tokensAfter),c.usedLlm&&s++,c.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},w=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function Ke(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function Ve(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function b(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}function Q(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Je(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Ze(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Qe(e){if(!e.eligibility?.length)return[...e.tools];let t=Ze(e.eligibility);return e.tools.filter(n=>{let o=Q(n);if(!o)return!1;let r=t.get(o);return!r||Je(r.status)})}function et(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function tt(e){let t=et({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Qe({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let c=r.filter(a=>Q(a)===i);if(c.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:c,normalizedToolChoice:{type:"function",function:{name:i}},warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var nt=["stop","aborted","timeout","cancelled","interrupted","error"],ot=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ee(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function rt(e,t){return{...e,...t,content:[...ee(e.content),...ee(t.content)]}}function st(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function it(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=st(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let c=e[i];c?.role==="tool"&&typeof c.tool_call_id=="string"&&s.has(c.tool_call_id)&&(n.push(c),t.add(i))}}return n}function at(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function lt(e){return new Set((e??nt).map(t=>t.trim().toLowerCase()))}function te(e,t){return e?lt(t).has(e.trim().toLowerCase()):!1}function ct(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function O(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(u=>at(u));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),n=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let l of a.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&n.has(a.tool_call_id))),r=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&r.add(a.tool_call_id);let s=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let l=a.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...p}=a;p.content!=null&&p.content!==""&&s.push(p);continue}if(l.length<a.tool_calls.length){s.push({...a,tool_calls:l});continue}}s.push(a)}let i=it(s),c=[];for(let a of i){let l=c.length>0?c[c.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){c[c.length-1]=rt(l,a);continue}c.push(a)}return c}function L(e,t){return te(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ot)delete o[r];return o}):[...e]}function P(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function ut(e,t){let n=O(e),o=L(n,t);return P(o,t)}function ne(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=te(t?.stopReason,t?.forcedStopReasons),r=[];for(let l=0;l<e.length;l+=1){let u=e[l];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(l+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=ct(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let l of r){if(l.type!=="function_call")continue;let u=typeof l.call_id=="string"&&l.call_id?l.call_id:typeof l.id=="string"?l.id:void 0;u&&(s.add(u),i.set(u,l))}let c=new Set,a=[];for(let l of r)if(!(o&&l.type==="function_call")){if(l.type==="function_call_output"){let u=typeof l.call_id=="string"?l.call_id:"";if(!u||!s.has(u))continue;c.add(u)}a.push(l)}for(let[l]of i)c.has(l)||o||a.push({type:"function_call_output",call_id:l,output:n});return a}function pt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function dt(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function ft(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function mt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function oe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function gt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function yt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Tt(e){let t=[],n=O(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=L(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=P(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:oe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:pt(r),completedToolCallIds:dt(r)}),recoveryActions:t}}function ht(e){let t=ne(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:oe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:ft(t),completedToolCallIds:mt(t)}),recoveryActions:n}}var Ct=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function bt(e){return e?Ct.has(e):!0}function _t(e){return e===429||e===529}function Rt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var cn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function xt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var pn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var N=4;var dn=50*1024,fn=500*1024,mn=500*1024*1024,gn=50*1024*1024;var F="<fork-child-context>",re="Fork started \u2014 processing in background";function kt(e){return JSON.stringify(e).includes(F)}function At(e){return e<N}function Et(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
14
14
|
|
|
15
15
|
Your working directory is: ${e.worktreePath}
|
|
16
16
|
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${F}
|
|
17
17
|
|
|
18
18
|
You are the "${t.agent.name}" agent.${o}
|
|
19
19
|
|
|
20
|
-
${t.taskPrompt}`}]};return n.push(r),n}function St(e){return e.map(t=>({role:"tool",tool_call_id:t,content:re}))}function Mt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function
|
|
20
|
+
${t.taskPrompt}`}]};return n.push(r),n}function St(e){return e.map(t=>({role:"tool",tool_call_id:t,content:re}))}function Mt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function It(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var vt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},wt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},Ot={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},Lt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},Pt={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},Nt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read","search","task"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},D=[vt,wt,Ot,Lt,Pt,Nt];function Ft(){return[...D]}function Dt(e){return D.find(t=>t.name===e)}function Bt(e){return D.some(t=>t.name===e)}function Ut(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function jt(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Gt(e){let t=Number.isFinite(e.totalPromptTokens)&&(e.totalPromptTokens??0)>0?Math.floor(e.totalPromptTokens):0,n=Number.isFinite(e.promptTokens)&&e.promptTokens>0?Math.floor(e.promptTokens):0,o=Number.isFinite(e.cacheReadTokens)&&(e.cacheReadTokens??0)>0?Math.floor(e.cacheReadTokens):0,r=Number.isFinite(e.cacheCreationTokens)&&(e.cacheCreationTokens??0)>0?Math.floor(e.cacheCreationTokens):0,s=o+r,i=s>n?n+s:n;return Math.max(t,i)}function qt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,aborted:e.abortSignal?.aborted??!1}}function zt(e,t){let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return o>=85?{level:"warning",usagePercent:o,remainingTokens:Math.max(0,n-e.promptTokens)}:{level:"ok"}}function $t(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Ht(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function Yt(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
|
|
21
21
|
${n.join(`
|
|
22
22
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
23
23
|
Step ${e.activeSkillContext.step}:
|
|
@@ -28,4 +28,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
28
28
|
|
|
29
29
|
${t.join(`
|
|
30
30
|
|
|
31
|
-
`)}`}function
|
|
31
|
+
`)}`}function Wt(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Xt(e){return!e.attemptedThisTurn}export{_ as CONTEXT_CAPSULE_MARKER,I as CacheAwareCompressionStrategy,v as CompressionMetricsCollector,w as ContextEngineRegistry,Z as DEFAULT_ADAPTIVE_BUDGET_CONFIG,re as FORK_PLACEHOLDER_RESULT,F as FORK_SENTINEL_TAG,M as HeadTailProtectedStrategy,N as MAX_FORK_DEPTH,A as SlidingWindowStrategy,E as SummarizeOldStrategy,S as ToolResultTrimStrategy,gt as advanceToolLoopState,tt as applyToolChoicePolicy,pe as buildAssistantToolCallMessage,St as buildForkPlaceholderResults,Et as buildForkedMessages,Yt as buildPostCompactRestorationMessage,J as buildStructuredSummaryPrompt,de as buildToolResultMessage,zt as calculateTokenWarningState,At as canForkAtDepth,qe as classifyError,We as computeAdaptiveBudget,Rt as computeRetryBackoff,Wt as createReactiveCompactState,jt as createTaskState,qt as createTurnLoopGuardState,It as generateForkChildAgentId,Dt as getBuiltInAgent,Ft as getBuiltInAgents,V as isAsyncCompressionStrategy,Bt as isBuiltInAgent,bt as isForegroundSource,kt as isInForkChild,xt as isPersistentRetryEnabled,W as isRetryableCategory,_t as isTransientCapacityError,k as parseContextCapsule,Tt as recoverToolLoopStateFromChatConversation,ht as recoverToolLoopStateFromResponsesItems,h as redactCompressionSecrets,ut as repairOpenAiChatConversation,Ut as resolveAgentToolSet,$t as resolveApiErrorRecovery,Mt as resolveForkChildTools,Gt as resolvePromptContextTokens,Xe as selectCompressionTier,yt as settleToolLoopState,Ht as shouldAbortTurn,Xt as shouldAttemptReactiveCompact};
|
|
@@ -25,7 +25,6 @@ export interface StreamErrorState {
|
|
|
25
25
|
export interface StreamErrorPatch {
|
|
26
26
|
consecutive529Errors?: number;
|
|
27
27
|
consecutiveApiRetries?: number;
|
|
28
|
-
maxOutputTokensOverride?: number;
|
|
29
28
|
transition?: ToolLoopTransition | undefined;
|
|
30
29
|
}
|
|
31
30
|
export type StreamErrorDecision = {
|
|
@@ -33,11 +33,6 @@ export type { SkillCreateInstruction, SkillImproveInstruction, SkillInstruction,
|
|
|
33
33
|
/** Observable reason why the provider loop started another inference round. */
|
|
34
34
|
export type ToolLoopTransition = {
|
|
35
35
|
reason: "reactive_compact_retry";
|
|
36
|
-
} | {
|
|
37
|
-
reason: "max_output_tokens_escalate";
|
|
38
|
-
} | {
|
|
39
|
-
reason: "max_output_tokens_recovery";
|
|
40
|
-
attempt: number;
|
|
41
36
|
} | {
|
|
42
37
|
reason: "next_turn";
|
|
43
38
|
};
|
|
@@ -4,8 +4,7 @@
|
|
|
4
4
|
* Aligned with Claude Code's multi-condition termination:
|
|
5
5
|
* 1. AbortSignal from user cancellation
|
|
6
6
|
* 2. Token usage warning (the provider remains authoritative for its context window)
|
|
7
|
-
* 3.
|
|
8
|
-
* 4. Prompt-too-long reactive compact trigger
|
|
7
|
+
* 3. Prompt-too-long reactive compact trigger
|
|
9
8
|
*/
|
|
10
9
|
export interface TurnLoopGuardConfig {
|
|
11
10
|
/** Context window size in tokens. */
|
|
@@ -18,8 +17,6 @@ export interface TurnLoopGuardConfig {
|
|
|
18
17
|
abortSignal?: AbortSignal;
|
|
19
18
|
/** Whether reactive compact is available. */
|
|
20
19
|
reactiveCompactEnabled: boolean;
|
|
21
|
-
/** Whether max_output_tokens escalation is allowed. */
|
|
22
|
-
outputEscalationEnabled: boolean;
|
|
23
20
|
}
|
|
24
21
|
export type TokenWarningState = {
|
|
25
22
|
level: "ok";
|
|
@@ -33,10 +30,8 @@ export interface TurnLoopGuardState {
|
|
|
33
30
|
promptTokens: number;
|
|
34
31
|
/** Whether reactive compact has already been attempted this turn. */
|
|
35
32
|
hasAttemptedReactiveCompact: boolean;
|
|
36
|
-
/** Current max_output_tokens
|
|
33
|
+
/** Current max_output_tokens. */
|
|
37
34
|
currentMaxOutputTokens: number;
|
|
38
|
-
/** Number of consecutive max_tokens truncations. */
|
|
39
|
-
consecutiveTruncations: number;
|
|
40
35
|
/** Whether the turn has been aborted. */
|
|
41
36
|
aborted: boolean;
|
|
42
37
|
}
|
|
@@ -83,15 +78,6 @@ export declare function resolveApiErrorRecovery(error: {
|
|
|
83
78
|
status?: number;
|
|
84
79
|
message?: string;
|
|
85
80
|
}, state: TurnLoopGuardState, config: TurnLoopGuardConfig): ApiErrorRecovery;
|
|
86
|
-
/**
|
|
87
|
-
* Handle finish_reason === "max_tokens" — escalate max_output_tokens.
|
|
88
|
-
*
|
|
89
|
-
* CC pattern: double the output token budget up to model max.
|
|
90
|
-
*/
|
|
91
|
-
export declare function resolveOutputTokenEscalation(state: TurnLoopGuardState, config: TurnLoopGuardConfig, modelMaxOutput: number): {
|
|
92
|
-
shouldEscalate: boolean;
|
|
93
|
-
newMax: number;
|
|
94
|
-
};
|
|
95
81
|
/**
|
|
96
82
|
* Check if the turn should be aborted (user cancellation).
|
|
97
83
|
*/
|
|
@@ -8,5 +8,5 @@ export { isForegroundSource, isTransientCapacityError, computeRetryBackoff, isPe
|
|
|
8
8
|
export { canForkAtDepth, buildForkedMessages, buildForkPlaceholderResults, FORK_PLACEHOLDER_RESULT, FORK_SENTINEL_TAG, generateForkChildAgentId, isInForkChild, MAX_FORK_DEPTH, resolveForkChildTools, type ForkChildConfig, type ForkChildMessage, type ForkContext, type ForkResult, } from "./subagent/fork-subagent.js";
|
|
9
9
|
export { getBuiltInAgent, getBuiltInAgents, isBuiltInAgent, resolveAgentToolSet, type AgentDefinition, } from "./subagent/agent-registry.js";
|
|
10
10
|
export { createTaskState, type IsolationMode, type PermissionRole, type TaskType, type TaskLifecycle, type TaskState, type TaskStateBase, type LocalBashTaskState, type LocalAgentTaskState, type RemoteAgentTaskState, } from "./subagent/task-types.js";
|
|
11
|
-
export { calculateTokenWarningState, createTurnLoopGuardState, resolvePromptContextTokens, resolveApiErrorRecovery,
|
|
11
|
+
export { calculateTokenWarningState, createTurnLoopGuardState, resolvePromptContextTokens, resolveApiErrorRecovery, shouldAbortTurn, type ApiErrorRecovery, type TokenWarningState, type TurnLoopGuardConfig, type TurnLoopGuardState, } from "./context/turn-loop-guard.js";
|
|
12
12
|
export { buildPostCompactRestorationMessage, createReactiveCompactState, shouldAttemptReactiveCompact, type ReactiveCompactConfig, type ReactiveCompactState, } from "./context/reactive-compact.js";
|
|
@@ -223,7 +223,7 @@ export interface AcpUsage {
|
|
|
223
223
|
cachedWriteTokens?: number;
|
|
224
224
|
_meta?: Record<string, unknown>;
|
|
225
225
|
}
|
|
226
|
-
export declare const
|
|
226
|
+
export declare const ACP_USAGE_RECORDS_META_KEY = "xiaozhiclaw/usageRecords";
|
|
227
227
|
export type AcpStopReason = "end_turn" | "max_tokens" | "max_turn_requests" | "refusal" | "cancelled";
|
|
228
228
|
export interface AcpJsonRpcRequest {
|
|
229
229
|
jsonrpc: "2.0";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { type ChatMessage, type ChatMessageRole, type ContextAnchor, type ContextAnchorCategory, type ContextEnvelope, type LocalizedToolText, type SemanticToolCapability, type ThinkingBlock, type ToolCapabilityCategory, type ToolCallMessage, type ToolDefinition, type ToolIdentity, } from "./chat-types.js";
|
|
2
|
-
export { type MediaResultType, type NotificationMethod, type NotificationMethodMap, type TurnDeltaNotification, type TurnEndNotification, type TurnMediaResultNotification, type TurnReasoningDeltaNotification, type TurnToolBlockedNotification, type TurnToolCallNotification, type TurnToolResultNotification, type
|
|
3
|
-
export { ACP_METHODS, ACP_PROTOCOL_VERSION, isAcpJsonRpcNotification, isAcpJsonRpcRequest, isAcpJsonRpcResponse, parseAcpMessage, type AcpAgentCapabilities, type AcpConfigOptionDescriptor, type AcpContentBlock, type AcpFsReadTextFileParams, type AcpFsReadTextFileResult, type AcpFsWriteTextFileParams, type AcpFsWriteTextFileResult, type AcpHostCapabilities, type AcpInitializeParams, type AcpInitializeResult, type AcpJsonRpcError, type AcpJsonRpcMessage, type AcpJsonRpcNotification, type AcpJsonRpcRequest, type AcpJsonRpcResponse, type AcpMode, type AcpPermissionOption, type AcpPermissionRequestParams, ACP_PERMISSION_PRESENTATION_META_KEY, type AcpPermissionPresentationMetaV1, type AcpPermissionRequestResult, type AcpSessionCancelParams, type AcpSessionCloseParams, type AcpSessionMeta, type AcpSessionLoadParams, type AcpSessionModeState, type AcpSessionNewParams, type AcpSessionNewResult, type AcpSessionPromptParams, type AcpSessionPromptResult,
|
|
2
|
+
export { type MediaResultType, type NotificationMethod, type NotificationMethodMap, type TurnDeltaNotification, type TurnEndNotification, type TurnMediaResultNotification, type TurnReasoningDeltaNotification, type TurnToolBlockedNotification, type TurnToolCallNotification, type TurnToolResultNotification, type WireUsageRecord, type WireUsageSource, type WireTokenUsage, } from "./notification-payloads.js";
|
|
3
|
+
export { ACP_METHODS, ACP_PROTOCOL_VERSION, isAcpJsonRpcNotification, isAcpJsonRpcRequest, isAcpJsonRpcResponse, parseAcpMessage, type AcpAgentCapabilities, type AcpConfigOptionDescriptor, type AcpContentBlock, type AcpFsReadTextFileParams, type AcpFsReadTextFileResult, type AcpFsWriteTextFileParams, type AcpFsWriteTextFileResult, type AcpHostCapabilities, type AcpInitializeParams, type AcpInitializeResult, type AcpJsonRpcError, type AcpJsonRpcMessage, type AcpJsonRpcNotification, type AcpJsonRpcRequest, type AcpJsonRpcResponse, type AcpMode, type AcpPermissionOption, type AcpPermissionRequestParams, ACP_PERMISSION_PRESENTATION_META_KEY, type AcpPermissionPresentationMetaV1, type AcpPermissionRequestResult, type AcpSessionCancelParams, type AcpSessionCloseParams, type AcpSessionMeta, type AcpSessionLoadParams, type AcpSessionModeState, type AcpSessionNewParams, type AcpSessionNewResult, type AcpSessionPromptParams, type AcpSessionPromptResult, ACP_USAGE_RECORDS_META_KEY, type AcpSessionSetConfigParams, type AcpSessionSetConfigResult, type AcpStandardMethod, type AcpStopReason, type AcpUsage, } from "./acp-protocol.js";
|
|
4
4
|
export { type ApprovalRequiredToolContract, type ModelSelectionReason, type PendingPromptContract, type RuntimeCapabilitySummaryContract, type RuntimeSessionContract, type SessionIdentityContract, } from "./session.js";
|
|
5
5
|
export { CAPABILITY_MANIFEST_DIFF_SECTIONS, cloneCapabilityManifestSnapshot, createCapabilityManifestDiffPayload, deriveCapabilityToolNamespaces, deriveCapabilityWorkspaceIds, mergeCapabilityManifestSnapshot, type CapabilityManifestApprovalMode, type CapabilityManifestApprovalPolicyContract, type CapabilityManifestDiffSection, type CapabilityMcpManifestContract, type CapabilityManifestSnapshotContract, type HostCapabilitySnapshotContract, type CapabilityPluginManifestContract, type RuntimeCapabilityViewContract, type RuntimeToolEligibilityContract, type CapabilitySkillManifestContract, type CapabilityToolManifestContract, type CapabilityWorkspaceSummaryContract, type ToolEligibilityResolvedSource, type ToolEligibilityReasonCode, type ToolEligibilityStatus, } from "./capability-manifest.js";
|
|
6
6
|
export { WEB_ACTION_SCOPE_VALUES, WEB_APPROVAL_DEFAULT_VALUES, WEB_CAPABILITY_FAMILY_VALUES, WEB_CAPABILITY_ID_VALUES, WEB_DEGRADATION_TARGET_VALUES, WEB_ESCALATION_REASON_VALUES, WEB_EXECUTION_MODE_VALUES, WEB_POLICY_RISK_CLASS_VALUES, WEB_RETRY_POLICY_VALUES, WEB_STATEFULNESS_VALUES, WEB_TASK_MODE_VALUES, type WebActionScope, type WebApprovalDefault, type WebCapabilityDescriptorContract, type WebCapabilityFamily, type WebCapabilityId, type WebDegradationTarget, type WebEscalationReason, type WebExecutionMode, type WebPolicyRiskClass, type WebRetryPolicy, type WebStatefulness, type WebTaskMode, type ToolRiskLevel, } from "./web-capability.js";
|
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
/** Token accounting returned by an Agent turn. */
|
|
2
|
-
export
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
export type WireUsageSource = "llmrouter.settlement" | "provider.reported" | "host.observed" | "estimated";
|
|
3
|
+
export interface WireUsageRecord {
|
|
4
|
+
schemaVersion: 1;
|
|
5
|
+
source: WireUsageSource;
|
|
6
6
|
requestIds: string[];
|
|
7
|
+
tokens: {
|
|
8
|
+
inputTokens?: number;
|
|
9
|
+
outputTokens?: number;
|
|
10
|
+
totalTokens?: number;
|
|
11
|
+
reasoningTokens?: number;
|
|
12
|
+
cacheReadTokens?: number;
|
|
13
|
+
cacheWriteTokens?: number;
|
|
14
|
+
};
|
|
15
|
+
cost?: {
|
|
16
|
+
currency: string;
|
|
17
|
+
amount: string;
|
|
18
|
+
};
|
|
7
19
|
}
|
|
8
20
|
export interface WireTokenUsage {
|
|
9
21
|
inputTokens: number;
|
|
@@ -11,7 +23,7 @@ export interface WireTokenUsage {
|
|
|
11
23
|
reasoningTokens?: number;
|
|
12
24
|
cacheRead?: number;
|
|
13
25
|
cacheWrite?: number;
|
|
14
|
-
|
|
26
|
+
records?: WireUsageRecord[];
|
|
15
27
|
}
|
|
16
28
|
/** Internal events that have a direct standard ACP projection. */
|
|
17
29
|
export interface TurnDeltaNotification {
|
|
@@ -25,10 +25,6 @@ export declare const RESPONSE_BUFFER_TOKENS = 13000;
|
|
|
25
25
|
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
26
26
|
/** Model's absolute max output tokens (escalation ceiling). */
|
|
27
27
|
export declare const DEFAULT_MODEL_MAX_OUTPUT_TOKENS = 65536;
|
|
28
|
-
/** Max max_output_tokens recovery attempts (CC: 3). */
|
|
29
|
-
export declare const MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3;
|
|
30
|
-
/** Escalated max output tokens during recovery (CC: 64k). */
|
|
31
|
-
export declare const ESCALATED_MAX_OUTPUT_TOKENS = 65536;
|
|
32
28
|
/** Per-tool result size threshold (chars) for disk persistence. */
|
|
33
29
|
export declare const DEFAULT_MAX_RESULT_SIZE_CHARS = 50000;
|
|
34
30
|
/** Per-message aggregate tool result budget (chars). */
|
|
@@ -99,8 +95,6 @@ export interface TunableDefaults {
|
|
|
99
95
|
responseBufferTokens: number;
|
|
100
96
|
defaultMaxOutputTokens: number;
|
|
101
97
|
defaultModelMaxOutputTokens: number;
|
|
102
|
-
maxOutputTokensRecoveryLimit: number;
|
|
103
|
-
escalatedMaxOutputTokens: number;
|
|
104
98
|
defaultMaxResultSizeChars: number;
|
|
105
99
|
maxToolResultsPerMessageChars: number;
|
|
106
100
|
toolResultPreviewBytes: number;
|
|
@@ -82,21 +82,23 @@ export type LLMChunk = {
|
|
|
82
82
|
reasoningTokens?: number;
|
|
83
83
|
cacheReadTokens?: number;
|
|
84
84
|
cacheCreationTokens?: number;
|
|
85
|
-
|
|
86
|
-
schemaVersion:
|
|
87
|
-
source:
|
|
88
|
-
|
|
89
|
-
currency: string;
|
|
90
|
-
cost: string;
|
|
85
|
+
records?: Array<{
|
|
86
|
+
schemaVersion: 1;
|
|
87
|
+
source: "llmrouter.settlement" | "provider.reported" | "host.observed" | "estimated";
|
|
88
|
+
requestIds: string[];
|
|
91
89
|
tokens: {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
totalTokens
|
|
95
|
-
reasoningTokens
|
|
96
|
-
cacheReadTokens
|
|
97
|
-
|
|
90
|
+
inputTokens?: number;
|
|
91
|
+
outputTokens?: number;
|
|
92
|
+
totalTokens?: number;
|
|
93
|
+
reasoningTokens?: number;
|
|
94
|
+
cacheReadTokens?: number;
|
|
95
|
+
cacheWriteTokens?: number;
|
|
98
96
|
};
|
|
99
|
-
|
|
97
|
+
cost?: {
|
|
98
|
+
currency: string;
|
|
99
|
+
amount: string;
|
|
100
|
+
};
|
|
101
|
+
}>;
|
|
100
102
|
} | {
|
|
101
103
|
type: "response_id";
|
|
102
104
|
id: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qlogicagent",
|
|
3
|
-
"version": "2.24.
|
|
3
|
+
"version": "2.24.14",
|
|
4
4
|
"packageManager": "pnpm@10.23.0",
|
|
5
5
|
"description": "XiaozhiClaw standard ACP Agent adapter",
|
|
6
6
|
"type": "module",
|
|
@@ -60,10 +60,8 @@
|
|
|
60
60
|
"test": "vitest run",
|
|
61
61
|
"test:slow": "vitest run --config vitest.release.config.ts",
|
|
62
62
|
"test:release": "pnpm test && pnpm run test:slow",
|
|
63
|
-
"benchmark:multi-session-real": "tsx benchmarks/multi-session-real/runner.ts",
|
|
64
63
|
"check": "node scripts/run-check.mjs",
|
|
65
64
|
"test:watch": "vitest",
|
|
66
|
-
"benchmark:hermes-superiority": "tsx benchmarks/hermes-superiority/runner.ts",
|
|
67
65
|
"lint": "oxlint .",
|
|
68
66
|
"check:encoding-corruption": "node scripts/check-encoding-corruption.mjs",
|
|
69
67
|
"check:mechanical-rules": "node scripts/check-mechanical-rules.mjs",
|
|
@@ -86,7 +84,7 @@
|
|
|
86
84
|
"@agentclientprotocol/sdk": "^0.25.0",
|
|
87
85
|
"@napi-rs/canvas": "0.1.100",
|
|
88
86
|
"@xiaozhiclaw/module-sdk": "0.4.5",
|
|
89
|
-
"@xiaozhiclaw/provider-core": "0.1.
|
|
87
|
+
"@xiaozhiclaw/provider-core": "0.1.46",
|
|
90
88
|
"ajv": "8.20.0",
|
|
91
89
|
"better-sqlite3": "^12.10.0",
|
|
92
90
|
"dotenv": "^17.3.1",
|