qlogicagent 2.24.8 → 2.24.9
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 +10 -70
- package/dist/cli.js +7 -7
- package/dist/index.js +212 -272
- package/dist/orchestration.js +14 -14
- package/dist/types/agent/tool-loop/loop-helpers.d.ts +2 -34
- package/dist/types/agent/tool-loop.d.ts +7 -58
- package/dist/types/agent/types.d.ts +5 -17
- package/dist/types/cli/core-tools/agent-tool-service.d.ts +1 -2
- package/dist/types/cli/handlers/turn-handler.d.ts +1 -1
- package/dist/types/cli/mcp-bootstrap.d.ts +1 -1
- package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +1 -1
- package/dist/types/contracts/index.d.ts +1 -1
- package/dist/types/contracts/tool-execution-evidence.d.ts +0 -12
- package/dist/types/contracts/tool-name.d.ts +0 -5
- package/dist/types/contracts/turn-event.d.ts +7 -81
- package/dist/types/orchestration/tool-loop/tool-choice-policy.d.ts +0 -1
- package/dist/types/protocol/wire/notification-payloads.d.ts +2 -0
- package/dist/types/runtime/config/tunable-defaults.d.ts +0 -23
- package/dist/types/runtime/infra/agent-project-projection.d.ts +0 -1
- package/dist/types/runtime/infra/subagent-turn-snapshot.d.ts +0 -1
- package/dist/types/runtime/ports/agent-runtime-ports.d.ts +0 -1
- package/dist/types/runtime/prompt/system-prompt-sections.d.ts +1 -14
- package/dist/types/skills/tools/agent-tool.d.ts +0 -5
- package/dist/types/skills/tools/write-tool.d.ts +3 -11
- package/package.json +2 -3
- package/dist/types/agent/tool-loop/agent-argument-normalizer.d.ts +0 -12
- package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +0 -171
- package/dist/types/agent/tool-loop/budget-continuation-policy.d.ts +0 -26
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +0 -48
- package/dist/types/agent/tool-loop/completion-stop-policy.d.ts +0 -19
- package/dist/types/agent/tool-loop/direct-response-contract.d.ts +0 -12
- package/dist/types/agent/tool-loop/final-status-stream-suppressor.d.ts +0 -22
- package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +0 -50
- package/dist/types/agent/tool-loop/tool-result-classification.d.ts +0 -10
- package/dist/types/agent/tool-loop.test-harness.d.ts +0 -20
- package/dist/types/cli/test-support/fs-cleanup.d.ts +0 -19
- package/dist/types/cli/test-support/tool-catalog-fixture.d.ts +0 -3
- package/dist/types/contracts/structured-planner.d.ts +0 -2
- package/dist/types/runtime/infra/token-budget.d.ts +0 -92
- package/dist/types/runtime/prompt/prompt-policy.d.ts +0 -12
- package/dist/types/test-support/global-home-setup.d.ts +0 -2
- package/dist/types/test-support/project-store-fixture.d.ts +0 -11
package/dist/orchestration.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
function
|
|
2
|
-
${JSON.stringify(e)}`}}var
|
|
3
|
-
${l}`},...
|
|
1
|
+
function be(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function _e(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 Re=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={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]},xe=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ke=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ae=512,Se=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ee=new Set([500,502,503,504,521,522,523,524,529]),Me=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],ve=["upgrade your plan","upgrade plan","current plan","subscription"],we=["daily","weekly","monthly"],Ie=["try again","retry","temporary","cooldown"],Oe=["usage limit","rate limit","organization usage"],Le=["organization","workspace"],Pe=["billing period","exceeded","reached","exhausted"],Ne=/["']?(?: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,Fe=/^(?: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 De(e){return T(e,h.format)}function Z(e){return T(e,h.rateLimit)}function Be(e){return T(e,h.timeout)}function Ue(e){return Re.test(e)}function L(e){let t=e.toLowerCase();return t?e.length>Ae?ke.test(t):T(t,h.billing)?!0:xe.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Q(e){return T(e,h.authPermanent)}function je(e){return T(e,h.auth)}function ee(e){return T(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function $e(e){return y(e,Me)||y(e,ve)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ge(e){let t=y(e,we),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Le);return y(e,Ie)&&y(e,Oe)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Pe))}function ze(e){return e.trim().toLowerCase().replace(Fe,"").trim()}function te(e){let t=ze(e);return!t||$e(t)?"billing":Z(t)||Ge(t)?"rate_limit":"billing"}function qe(e){return Ne.test(e)?te(e):null}function ne(e){let t=e.match(Se);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function He(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ye(e){let t=e.trim();if(!t)return!1;let n=ne(t);return n?Ee.has(n.code):!1}function oe(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?te(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Q(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&ee(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&L(t)?"billing":"format":null}function We(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 Xe(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 re(e){if(Xe(e))return"session_expired";if(We(e))return"model_not_found";let t=qe(e);return t||(Ue(e)?L(e)?"billing":"rate_limit":Z(e)?"rate_limit":ee(e)?"overloaded":Ye(e)?ne(e.trim())?.code===529?"overloaded":"timeout":He(e)?"timeout":De(e)?"format":L(e)?"billing":Be(e)?"timeout":Q(e)?"auth_permanent":je(e)?"auth":null)}var Ke=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function se(e){return Ke.has(e)}var Ve={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 Je(e,t){let n=oe(e,t)??(t?re(t):null);return n?Ve[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function z(e){return typeof e.compressAsync=="function"}var E="[Context capsule v1]";function C(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(E)))try{let t=JSON.parse(e.content.slice(E.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function le(e,t,n,o){let r=e.map(c=>c.itemId).filter(c=>!!c),s={...o?.state.anchors??{}};for(let c of e)for(let u of c.contextAnchors??[]){let p=s[u.category]??[];s[u.category]=[...new Set([...p,C(u.value)])].slice(-50)}let i=[...o?.state.userRequests??[],...e.filter(c=>c.role==="user").map(c=>C(typeof c.content=="string"?c.content:JSON.stringify(c.content??"")))].slice(-50),l={summary:C(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((c,u)=>c+n(u),0)};return{receipt:{...a,digest:Ze(JSON.stringify({receipt:a,state:l}))},state:l}}function ce(e){return{role:"system",content:`${E}
|
|
2
|
+
${JSON.stringify(e)}`}}var ie=4;function ae(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var P=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(ae(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let l=[],a=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===i)continue;let m=this.estimateTokens(d);if(s-m<0&&a>=ie)break;if(s-m<0&&a<ie){l.unshift(d),a++;continue}s-=m,l.unshift(d),a++}let c=r.length-(l.length+(i&&!l.includes(i)?1:0)),u=[...o];return i&&!l.includes(i)&&u.push(i),c>0&&u.push(ae(c)),u.push(...l),{messages:u,droppedCount:c,strategy:"sliding-window"}}},N=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),l=this.summarize(s);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
3
|
+
${l}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},F=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:Qe(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Qe(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
|
-
`));if(
|
|
6
|
-
[...truncated: ${e.length-
|
|
5
|
+
`));if(s>t*.5)return n.slice(0,s+1)+`
|
|
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
|
|
10
|
-
`)}var
|
|
9
|
+
[...truncated: ${e.length-t} chars omitted]`}function et(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let l=i.compress(o,n);o=l.messages,r+=l.droppedCount,l.droppedCount>0&&s.push(l.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function tt(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let l=i.compress(o,n);o=l.messages,r+=l.droppedCount,l.droppedCount>0&&s.push(l.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,s=[],i=0,l=!1,a=!1;for(let c of e){let u=z(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&s.push(u.strategy),u.metrics&&(i+=u.metrics.latencyMs,l=l||u.metrics.usedLlm,a=a||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||l?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:l,cacheInvalidated:a}:void 0}}}}function q(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 l=C(typeof i.content=="string"?i.content:JSON.stringify(i.content??"")),a=i.role==="user"?l:l.length>2e3?l.slice(0,2e3)+"...":l;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 D=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=pe(t),i=r.findIndex(f=>k(f)!==void 0),l=k(i>=0?r[i]:void 0),a=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,c=t.reduce((f,O)=>f+this.config.estimateTokens(O),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let f=0;f<s.length&&(s[f].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));f++)u=f+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),m=Math.max(u,s.length-d);if(m<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let b=s.slice(0,u),_=s.slice(u,m),v=s.slice(m),w=q(_,{taskContext:[this.config.taskContext,l?`Prior verified capsule:
|
|
11
11
|
${JSON.stringify(l.state)}`:void 0].filter(Boolean).join(`
|
|
12
12
|
|
|
13
|
-
`)||void 0}),A=C(await this.config.summarize(_,w)),
|
|
13
|
+
`)||void 0}),A=C(await this.config.summarize(_,w)),I=ce(le(_,A,this.config.estimateTokens,l)),x=[...a,...b,I,...v],g=Date.now()-o,R=x.reduce((f,O)=>f+this.config.estimateTokens(O),0);return{messages:x,droppedCount:_.length,strategy:"head-tail-protected",metrics:{tokensBefore:c,tokensAfter:R,compressionRatio:c>0?R/c:1,latencyMs:g,usedLlm:!0,cacheInvalidated:!0}}}},B=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=pe(t),i=r.findIndex(g=>k(g)!==void 0),l=i>=0?r[i]:void 0,a=k(l),c=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,u=Math.max(0,s.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=t.reduce((g,R)=>g+this.config.estimateTokens(R),0);if(p<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=s.slice(0,u),m=s.slice(u),b=a?`Prior verified capsule state:
|
|
14
14
|
${JSON.stringify(a.state)}
|
|
15
15
|
|
|
16
|
-
Integrate only the new messages below:`:void 0,_=
|
|
17
|
-
`),
|
|
16
|
+
Integrate only the new messages below:`:void 0,_=q(d,{taskContext:b}),v=C(await this.config.summarize(d,_)),w=ce(le(d,v,this.config.estimateTokens,a)),A=[...c,w,...m],I=Date.now()-o,x=A.reduce((g,R)=>g+this.config.estimateTokens(R),0);return{messages:A,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:p,tokensAfter:x,compressionRatio:p>0?x/p:1,latencyMs:I,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config=t}compress(t,n){let o=S(t),r=this.config.inner.compress(t,n),s=S(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=S(t),r=z(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=S(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}}}},ue={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function nt(e={}){let t={...ue,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function ot(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var j=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 l of this.events)n+=l.tokensBefore>0?l.tokensAfter/l.tokensBefore:1,o+=l.latencyMs,r+=Math.max(0,l.tokensBefore-l.tokensAfter),l.usedLlm&&s++,l.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}},$=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 pe(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function S(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("|")}var rt=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]);function st(e){let t=e;for(let n=0;n<3;n+=1){if(!t||typeof t!="object"||Array.isArray(t))return;let o=t,r=o.outcome??o.status;if(r==="committed"||r==="not-applied"||r==="indeterminate")return r;t=o.structuredContent}}var G=class{constructor(t=20,n=M){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let a of t){let c=a.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((a,c)=>{if(c>=r||a.role!=="tool"||typeof a.content!="string")return a;let u=a.name??o.get(a.tool_call_id??""),p=st(a.structuredContent);if(!p&&(!u||!rt.has(u)))return a;let d=a.structuredContent?JSON.stringify(a.structuredContent).length:0;if(a.content.length<=200&&d<=200)return a;let m=this.estimateTokens(a);return i+=m,s++,{...a,content:`[result cleared \u2014 ${a.content.length+d} chars]`,...p?{structuredContent:{status:p,outcome:p}}:{}}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function it(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),l=i.path??i.filePath??i.file_path??i.file;l&&typeof l=="string"&&t.set(l,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function at(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=it(t);if(r.length===0)return e;let s=e.map(d=>typeof d.content=="string"?d.content:"").join(`
|
|
17
|
+
`),i=r.filter(d=>!s.includes(d));if(i.length===0)return e;let l=n.maxTokenBudget,a=[],c=0;for(let d of i){if(c>=n.maxFiles||l<=0)break;let m=await n.readFile(d);if(!m)continue;let b=o(m);b>l||(l-=b,c++,a.push({role:"system",content:`[Post-compact file recovery: ${d}]
|
|
18
18
|
|
|
19
|
-
${m}`}))}if(a.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...a),u}function ct(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let l of e){let a=l.tool_call_id??"";if(a&&t.has(a)){o+=n(l),r++,t.delete(a);continue}i.push(l)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function ut(){return{stages:[]}}function pt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(l=>l.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=mt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let l of s)t.stages.push(l);return i=me(e,t),{messages:i,stagedCount:s.length}}function dt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let l=Math.min(s,o.length),a={role:"system",content:r.summary};o.splice(i,l-i,a)}return o}function mt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(a=>`${a.range[0]}-${a.range[1]}`)),s=-1,l=0;for(let a=0;a<o;a++){let c=e[a];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=a),l++;else{if(l>=3){let p=`${s}-${s+l}`;i.has(p)||r.push({id:`collapse_${s}_${s+l}`,range:[s,s+l],summary:`[${l} tool results collapsed]`,committed:!1})}s=-1,l=0}}if(l>=3){let a=`${s}-${s+l}`;i.has(a)||r.push({id:`collapse_${s}_${s+l}`,range:[s,s+l],summary:`[${l} tool results collapsed]`,committed:!1})}return r}function ft(e){return[...new Set(e.map(v).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ge(e){let t=ft(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function gt(e){let t=[...new Set(e.map(v).filter(Boolean))].sort((s,l)=>s.localeCompare(l)),n=new Set(t),o=ge(e),r=n.has("exec"),i=["read","search","write","edit","patch"].some(s=>n.has(s));return!r||!i?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function v(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 yt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ht(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Tt(e){if(!e.eligibility?.length)return[...e.tools];let t=ht(e.eligibility);return e.tools.filter(n=>{let o=v(n);if(!o)return!1;let r=t.get(o);return!r||yt(r.status)})}function Ct(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 bt(e){let t=Ct({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Tt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ge(r)}:{},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",extraSystemPrompt:gt(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let l=r.filter(a=>v(a)===s);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:l,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var _t=["stop","aborted","timeout","cancelled","interrupted","error"],Rt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function xt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function kt(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 At(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 i=kt(r);if(i.size!==0)for(let s=o+1;s<e.length;s+=1){if(t.has(s))continue;let l=e[s];l?.role==="tool"&&typeof l.tool_call_id=="string"&&i.has(l.tool_call_id)&&(n.push(l),t.add(s))}}return n}function St(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 Et(e){return new Set((e??_t).map(t=>t.trim().toLowerCase()))}function he(e,t){return e?Et(t).has(e.trim().toLowerCase()):!1}function Mt(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 Y(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 c=a.tool_calls.filter(u=>St(u));return{...a,...c.length>0?{tool_calls:c}:{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 c of a.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.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 i=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let c=a.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=a;p.content!=null&&p.content!==""&&i.push(p);continue}if(c.length<a.tool_calls.length){i.push({...a,tool_calls:c});continue}}i.push(a)}let s=At(i),l=[];for(let a of s){let c=l.length>0?l[l.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){l[l.length-1]=xt(c,a);continue}l.push(a)}return l}function W(e,t){return he(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Rt)delete o[r];return o}):[...e]}function X(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function vt(e,t){let n=Y(e),o=W(n,t);return X(o,t)}function Te(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=he(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Mt(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let l=new Set,a=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;l.add(u)}a.push(c)}for(let[c]of s)l.has(c)||o||a.push({type:"function_call_output",call_id:c,output:n});return a}function It(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 wt(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 Ot(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 Lt(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 Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Pt(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 Nt(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 Ft(e){let t=[],n=Y(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=W(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=X(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:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:wt(r)}),recoveryActions:t}}function Dt(e){let t=Te(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:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ot(t),completedToolCallIds:Lt(t)}),recoveryActions:n}}var Bt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ut(e){return e?Bt.has(e):!0}function Gt(e){return e===429||e===529}function jt(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 In={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $t(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var On=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ln=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var V=4;var Pn=50*1024,Nn=500*1024,Fn=500*1024*1024,Dn=50*1024*1024;var J="<fork-child-context>",be="Fork started \u2014 processing in background";function zt(e){return JSON.stringify(e).includes(J)}function qt(e){return e<V}function Ht(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
19
|
+
${m}`}))}if(a.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...a),u}function lt(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let l of e){let a=l.tool_call_id??"";if(a&&t.has(a)){o+=n(l),r++,t.delete(a);continue}s.push(l)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function ct(){return{stages:[]}}function ut(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(l=>l.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=de(e,t),i=dt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let l of i)t.stages.push(l);return s=de(e,t),{messages:s,stagedCount:i.length}}function pt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:me(e,t),committed:n}}function de(e,t){return t.stages.filter(o=>o.committed).length===0?e:me(e,t)}function me(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let l=Math.min(i,o.length),a={role:"system",content:r.summary};o.splice(s,l-s,a)}return o}function dt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(a=>`${a.range[0]}-${a.range[1]}`)),i=-1,l=0;for(let a=0;a<o;a++){let c=e[a];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=a),l++;else{if(l>=3){let p=`${i}-${i+l}`;s.has(p)||r.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}i=-1,l=0}}if(l>=3){let a=`${i}-${i+l}`;s.has(a)||r.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}return r}function fe(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 mt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ft(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function gt(e){if(!e.eligibility?.length)return[...e.tools];let t=ft(e.eligibility);return e.tools.filter(n=>{let o=fe(n);if(!o)return!1;let r=t.get(o);return!r||mt(r.status)})}function yt(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 ht(e){let t=yt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=gt({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 l=r.filter(a=>fe(a)===i);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:l,normalizedToolChoice:{type:"function",function:{name:i}},warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Tt=["stop","aborted","timeout","cancelled","interrupted","error"],Ct=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ge(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function bt(e,t){return{...e,content:[...ge(e.content),...ge(t.content)]}}function _t(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 Rt(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=_t(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let l=e[i];l?.role==="tool"&&typeof l.tool_call_id=="string"&&s.has(l.tool_call_id)&&(n.push(l),t.add(i))}}return n}function xt(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 kt(e){return new Set((e??Tt).map(t=>t.trim().toLowerCase()))}function ye(e,t){return e?kt(t).has(e.trim().toLowerCase()):!1}function At(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 H(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 c=a.tool_calls.filter(u=>xt(u));return{...a,...c.length>0?{tool_calls:c}:{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 c of a.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.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 c=a.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=a;p.content!=null&&p.content!==""&&s.push(p);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=Rt(s),l=[];for(let a of i){let c=l.length>0?l[l.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){l[l.length-1]=bt(c,a);continue}l.push(a)}return l}function Y(e,t){return ye(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Ct)delete o[r];return o}):[...e]}function W(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 St(e,t){let n=H(e),o=Y(n,t);return W(o,t)}function he(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=ye(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=At(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(s.add(u),i.set(u,c))}let l=new Set,a=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!s.has(u))continue;l.add(u)}a.push(c)}for(let[c]of i)l.has(c)||o||a.push({type:"function_call_output",call_id:c,output:n});return a}function Et(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 Mt(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 vt(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 wt(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 Te(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function It(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 Ot(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 Lt(e){let t=[],n=H(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=Y(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=W(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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Et(r),completedToolCallIds:Mt(r)}),recoveryActions:t}}function Pt(e){let t=he(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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:vt(t),completedToolCallIds:wt(t)}),recoveryActions:n}}var Nt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ft(e){return e?Nt.has(e):!0}function Dt(e){return e===429||e===529}function Bt(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 En={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ut(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var X=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var vn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var K=4;var wn=50*1024,In=500*1024,On=500*1024*1024,Ln=50*1024*1024;var V="<fork-child-context>",Ce="Fork started \u2014 processing in background";function jt(e){return JSON.stringify(e).includes(V)}function $t(e){return e<K}function Gt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
20
20
|
|
|
21
21
|
Your working directory is: ${e.worktreePath}
|
|
22
|
-
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${
|
|
22
|
+
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${V}
|
|
23
23
|
|
|
24
24
|
You are the "${t.agent.name}" agent.${o}
|
|
25
25
|
|
|
26
|
-
${t.taskPrompt}`}]};return n.push(r),n}function
|
|
26
|
+
${t.taskPrompt}`}]};return n.push(r),n}function zt(e){return e.map(t=>({role:"tool",tool_call_id:t,content:Ce}))}function qt(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 Ht(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Yt={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."},Xt={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."},Kt={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."},Vt={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."},Jt={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."},J=[Yt,Wt,Xt,Kt,Vt,Jt];function Zt(){return[...J]}function Qt(e){return J.find(t=>t.name===e)}function en(e){return J.some(t=>t.name===e)}function tn(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 nn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function on(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 rn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function sn(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 an(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 ln(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function cn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function un(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
|
|
27
27
|
${n.join(`
|
|
28
28
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
29
29
|
Step ${e.activeSkillContext.step}:
|
|
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
34
34
|
|
|
35
35
|
${t.join(`
|
|
36
36
|
|
|
37
|
-
`)}`}function
|
|
37
|
+
`)}`}function pn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function dn(e){return!e.attemptedThisTurn}export{E as CONTEXT_CAPSULE_MARKER,U as CacheAwareCompressionStrategy,j as CompressionMetricsCollector,$ as ContextEngineRegistry,ue as DEFAULT_ADAPTIVE_BUDGET_CONFIG,Ce as FORK_PLACEHOLDER_RESULT,V as FORK_SENTINEL_TAG,X as FallbackTriggeredError,D as HeadTailProtectedStrategy,B as IncrementalCompactStrategy,K as MAX_FORK_DEPTH,G as MicroCompactStrategy,P as SlidingWindowStrategy,N as SummarizeOldStrategy,F as ToolResultTrimStrategy,It as advanceToolLoopState,ut as applyContextCollapsesIfNeeded,ht as applyToolChoicePolicy,be as buildAssistantToolCallMessage,zt as buildForkPlaceholderResults,Gt as buildForkedMessages,un as buildPostCompactRestorationMessage,q as buildStructuredSummaryPrompt,_e as buildToolResultMessage,sn as calculateTokenWarningState,$t as canForkAtDepth,Je as classifyError,tt as composeAsyncStrategies,et as composeStrategies,nt as computeAdaptiveBudget,Bt as computeRetryBackoff,ct as createCollapseStore,pn as createReactiveCompactState,nn as createTaskState,rn as createTurnLoopGuardState,Ht as generateForkChildAgentId,Qt as getBuiltInAgent,Zt as getBuiltInAgents,z as isAsyncCompressionStrategy,en as isBuiltInAgent,Ft as isForegroundSource,jt as isInForkChild,Ut as isPersistentRetryEnabled,se as isRetryableCategory,Dt as isTransientCapacityError,k as parseContextCapsule,at as postCompactFileRecovery,pt as recoverContextCollapseFromOverflow,Lt as recoverToolLoopStateFromChatConversation,Pt as recoverToolLoopStateFromResponsesItems,C as redactCompressionSecrets,St as repairOpenAiChatConversation,tn as resolveAgentToolSet,an as resolveApiErrorRecovery,qt as resolveForkChildTools,ln as resolveOutputTokenEscalation,on as resolvePromptContextTokens,ot as selectCompressionTier,Ot as settleToolLoopState,cn as shouldAbortTurn,dn as shouldAttemptReactiveCompact,lt as snipCompactIfNeeded};
|
|
@@ -1,40 +1,8 @@
|
|
|
1
|
-
import type { ChatMessage
|
|
2
|
-
export { isEmptyToolResult } from "./tool-result-classification.js";
|
|
3
|
-
export declare const OUTPUT_REQUEST_CONTEXT_PATTERN: RegExp;
|
|
4
|
-
export declare function findLastToolError(messages: unknown[], toolName: string, toolArguments?: string): string | undefined;
|
|
5
|
-
export declare function isCapabilityDenial(text: string): boolean;
|
|
1
|
+
import type { ChatMessage } from "../types.js";
|
|
6
2
|
export declare function resolveToolLoopBudget(requested?: number, messages?: readonly ChatMessage[]): number;
|
|
7
|
-
export declare function
|
|
8
|
-
export declare function resolvePerRoundToolCallBudget(requested?: number): number;
|
|
3
|
+
export declare function resolvePerRoundToolCallBudget(requested?: number): number | undefined;
|
|
9
4
|
export declare function filterWhitespaceOnlyAssistant<T extends {
|
|
10
5
|
role: string;
|
|
11
6
|
content?: unknown;
|
|
12
7
|
}>(messages: T[]): T[];
|
|
13
|
-
export declare function synthesizeFallbackContent(messages: ChatMessage[], log: {
|
|
14
|
-
info: (m: string) => void;
|
|
15
|
-
}): string;
|
|
16
|
-
/**
|
|
17
|
-
* Fail-loud stop message for the repeated-tool-failure early exit, used when the model produced no
|
|
18
|
-
* final text of its own. Without this the turn would end on a bare dump of the failing tool errors
|
|
19
|
-
* (synthesizeFallbackContent) — which reads as a silent/cryptic stop. Plain-language reason + the
|
|
20
|
-
* last real tool error, so the user always learns WHY the turn stopped. The model's own text, when
|
|
21
|
-
* present, is preferred over this by the caller.
|
|
22
|
-
*/
|
|
23
|
-
export declare function buildRepeatedToolFailureStopContent(messages: ChatMessage[], failedRounds: number): string;
|
|
24
|
-
/**
|
|
25
|
-
* Self-correction nudge for the repeated-tool-failure recovery. Instead of killing the turn after N
|
|
26
|
-
* consecutive all-failed rounds, surface the last command + error and tell the model to consult the
|
|
27
|
-
* tool's own help and stop repeating the failing command — the same Help-First habit the skills ask
|
|
28
|
-
* for. Many CLIs (e.g. OfficeCLI) print a "run <tool> help" hint the model can act on; it just needs
|
|
29
|
-
* the error put in front of it once. Returns null when there is no tool error to correct from.
|
|
30
|
-
*/
|
|
31
|
-
export declare function buildToolFailureCorrectionNudge(messages: ChatMessage[], failureKind?: ToolCallExecutionEvidence["failureKind"]): ChatMessage | null;
|
|
32
|
-
/**
|
|
33
|
-
* exec 命令的"族"标识:程序名 + 子命令/脚本名(最多两段),用于 churn/变体失败
|
|
34
|
-
* 计数。审计 CASE2:按精确命令串 keying 时,每轮换一个转换/安装命令即可永远绕过
|
|
35
|
-
* 阈值 —— 按族计数后 "pip install A" / "pip install B" 归并为同一目标。
|
|
36
|
-
*/
|
|
37
|
-
export declare function execCommandFamily(command: string): string;
|
|
38
|
-
export declare function isIterativeRunnerFamily(family: string): boolean;
|
|
39
|
-
export declare function isSetupOnlyExecCommand(command: string | null): boolean;
|
|
40
8
|
export declare function summarizeToolInput(rawArgs: string): string | undefined;
|
|
@@ -1,24 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Provider-driven tool loop.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* - Error Withholding: 413 / max_output_tokens / media errors are
|
|
8
|
-
* withheld from callers during recovery attempts
|
|
9
|
-
* - Context Collapse drain: staged collapses committed on 413
|
|
10
|
-
* BEFORE falling through to reactive compact
|
|
11
|
-
* - Media error recovery: image/media errors -> reactive compact retry
|
|
12
|
-
* - Hermes delta suppression preserved
|
|
13
|
-
* - StreamingToolExecutor preserved
|
|
14
|
-
* - Sub-agent fork depth preserved
|
|
15
|
-
* - Skill learning evaluation preserved
|
|
16
|
-
*
|
|
17
|
-
* CC reference: src/query.ts queryLoop()
|
|
4
|
+
* The provider chooses tools and receives their protocol results. The loop
|
|
5
|
+
* handles transport recovery, context limits, cancellation and explicit caller
|
|
6
|
+
* budgets, but does not rewrite tool arguments or steer semantic decisions.
|
|
18
7
|
*
|
|
19
8
|
* Zero imports from express/pg/ioredis/ws.
|
|
20
9
|
*/
|
|
21
|
-
import type { AgentLogger, ChatMessage, ToolDefinition, ToolInvoker, TurnEvent, HookRegistry, LLMTransport
|
|
10
|
+
import type { AgentLogger, ChatMessage, ToolDefinition, ToolInvoker, TurnEvent, HookRegistry, LLMTransport } from "./types.js";
|
|
22
11
|
import type { ToolLoopRuntimePorts } from "../runtime/ports/index.js";
|
|
23
12
|
export interface ToolLoopParams {
|
|
24
13
|
turnId: string;
|
|
@@ -46,12 +35,6 @@ export interface ToolLoopParams {
|
|
|
46
35
|
* tool_choice="required" forcing (judgment-over-mechanism: hint first, force only on the
|
|
47
36
|
* observed violation).
|
|
48
37
|
*/
|
|
49
|
-
freshEvidenceRequired?: boolean;
|
|
50
|
-
/**
|
|
51
|
-
* Build/test verification gate (lever ②). Default true. Set false to disable the
|
|
52
|
-
* "fix-and-rerun until the test/build passes" recovery — used for A/B measurement.
|
|
53
|
-
*/
|
|
54
|
-
buildVerificationGate?: boolean;
|
|
55
38
|
/** Parent fork depth (0 = top-level) */
|
|
56
39
|
parentDepth?: number;
|
|
57
40
|
/** Tool eligibility context for policy-based filtering */
|
|
@@ -64,8 +47,6 @@ export interface ToolLoopParams {
|
|
|
64
47
|
fallbackModel?: string;
|
|
65
48
|
/** Query source for foreground/background retry distinction (CC parity). */
|
|
66
49
|
querySource?: string;
|
|
67
|
-
/** Token budget for this turn (>0 enables budget continuation). */
|
|
68
|
-
tokenBudget?: number;
|
|
69
50
|
/**
|
|
70
51
|
* Refresh tools callback -called between turns (CC refreshTools parity).
|
|
71
52
|
* Returns updated tool definitions if tools have changed (e.g. MCP reconnect),
|
|
@@ -136,45 +117,13 @@ export interface ToolLoopParams {
|
|
|
136
117
|
runtimePorts: ToolLoopRuntimePorts;
|
|
137
118
|
signal?: AbortSignal;
|
|
138
119
|
}
|
|
139
|
-
/** Crossing this many consecutive failed/empty actions on the SAME target flags no progress. */
|
|
140
|
-
export declare const NO_PROGRESS_TARGET_THRESHOLD = 4;
|
|
141
|
-
/**
|
|
142
|
-
* [lever 3] Identify the "target" a tool call acts on, for churn counting: the file path
|
|
143
|
-
* for write/edit/patch, the command FAMILY (program + subcommand/script) for exec — with
|
|
144
|
-
* iterate-by-design runner families (test/build/lint/git) exempted, since repeatedly
|
|
145
|
-
* re-running those is a normal fix-verify cycle, not churn. The caller only increments
|
|
146
|
-
* this key for genuinely executed failures or empty results; a successful result resets
|
|
147
|
-
* the streak. Returns null for tools whose repetition isn't a stuck-signal (read, search,
|
|
148
|
-
* etc.). Exported for testing.
|
|
149
|
-
*/
|
|
150
|
-
export declare function noProgressTargetKey(toolName: string, rawArguments: string): string | null;
|
|
151
|
-
/**
|
|
152
|
-
* Remove presentation-only churn from an observation. Time passing, elapsed counters, and package
|
|
153
|
-
* manager lock markers do not prove that the observed task made progress.
|
|
154
|
-
*/
|
|
155
|
-
export declare function normalizeProgressObservation(content: string): string;
|
|
156
|
-
/** Stable identity for observation-style successes. null means the success itself proves progress. */
|
|
157
|
-
export declare function toolProgressIdentity(toolName: string, details: unknown, content: string): string | null;
|
|
158
|
-
export declare function buildLongHorizonStateMaintenanceInstruction(documents: ReadonlyMap<string, MaintainedDocumentIndex>, turn: number): string | null;
|
|
159
|
-
export declare function longHorizonStateMaintenanceWriteValidation(maintainedDocuments: ReadonlyMap<string, MaintainedDocumentIndex>, filePath: string, rawArguments: string): {
|
|
160
|
-
ok: true;
|
|
161
|
-
} | {
|
|
162
|
-
ok: false;
|
|
163
|
-
reason: string;
|
|
164
|
-
};
|
|
165
|
-
export declare function longHorizonStateHashIntegrityViolations(maintainedDocuments: ReadonlyMap<string, MaintainedDocumentIndex>): {
|
|
166
|
-
path: string;
|
|
167
|
-
reason: string;
|
|
168
|
-
}[];
|
|
169
120
|
/**
|
|
170
121
|
* Execute the tool loop -CC query.ts queryLoop() aligned.
|
|
171
122
|
*
|
|
172
123
|
* Yields TurnEvent stream. The caller (Agent class) wraps this with
|
|
173
124
|
* start/end lifecycle and error handling.
|
|
174
125
|
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
* drain ->reactive compact ->escalation ->recovery message pipeline
|
|
178
|
-
* before surfacing to callers.
|
|
126
|
+
* Provider output is preserved as typed events while transport and context
|
|
127
|
+
* recovery remain internal to the adapter.
|
|
179
128
|
*/
|
|
180
129
|
export declare function executeToolLoop(params: ToolLoopParams, transport: LLMTransport, toolInvoker: ToolInvoker, log: AgentLogger): AsyncGenerator<TurnEvent>;
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import type { HookRegistry } from "../contracts/hooks.js";
|
|
9
9
|
import type { AccumulatedToolCall, LLMChunk, LLMRequest, LLMTransport } from "../runtime/ports/index.js";
|
|
10
10
|
import type { ChatMessage as WireChatMessage, ChatMessageRole as WireChatMessageRole, ThinkingBlock as WireThinkingBlock, ToolCallMessage as WireToolCallMessage, ToolDefinition as WireToolDefinition, WireTokenUsage } from "../protocol/wire/index.js";
|
|
11
|
-
import type {
|
|
11
|
+
import type { ToolCallExecutionEvidence } from "../contracts/tool-execution-evidence.js";
|
|
12
12
|
export type ChatMessageRole = WireChatMessageRole;
|
|
13
13
|
export type ThinkingBlock = WireThinkingBlock;
|
|
14
14
|
export type ToolCallMessage = WireToolCallMessage;
|
|
@@ -29,12 +29,8 @@ export interface ToolDefinition extends WireToolDefinition {
|
|
|
29
29
|
* (inputTokens, outputTokens, reasoningTokens, cacheRead, cacheWrite).
|
|
30
30
|
*/
|
|
31
31
|
export type TokenUsage = WireTokenUsage;
|
|
32
|
-
export type {
|
|
33
|
-
/**
|
|
34
|
-
* Why the previous iteration continuedeach variant corresponds to one of
|
|
35
|
-
* the 7 `continue` sites in the main while(true) loop.
|
|
36
|
-
* Tests can assert recovery paths fired without inspecting message contents.
|
|
37
|
-
*/
|
|
32
|
+
export type { SkillCreateInstruction, SkillImproveInstruction, SkillInstruction, TurnEvent, } from "../contracts/turn-event.js";
|
|
33
|
+
/** Observable reason why the provider loop started another inference round. */
|
|
38
34
|
export type ToolLoopTransition = {
|
|
39
35
|
reason: "collapse_drain_retry";
|
|
40
36
|
committed: number;
|
|
@@ -45,10 +41,6 @@ export type ToolLoopTransition = {
|
|
|
45
41
|
} | {
|
|
46
42
|
reason: "max_output_tokens_recovery";
|
|
47
43
|
attempt: number;
|
|
48
|
-
} | {
|
|
49
|
-
reason: "stop_hook_blocking";
|
|
50
|
-
} | {
|
|
51
|
-
reason: "token_budget_continuation";
|
|
52
44
|
} | {
|
|
53
45
|
reason: "next_turn";
|
|
54
46
|
};
|
|
@@ -131,7 +123,7 @@ export interface TurnConfig {
|
|
|
131
123
|
apiKey?: string;
|
|
132
124
|
/** Optional base URL override */
|
|
133
125
|
baseUrl?: string;
|
|
134
|
-
/**
|
|
126
|
+
/** Explicit max tool-call rounds per turn. Undefined means unbounded. */
|
|
135
127
|
maxRounds?: number;
|
|
136
128
|
/** Temperature override */
|
|
137
129
|
temperature?: number;
|
|
@@ -143,12 +135,8 @@ export interface TurnConfig {
|
|
|
143
135
|
modelMaxOutputTokens?: number;
|
|
144
136
|
/** Tool choice strategy: "auto" (default), "none", "required" */
|
|
145
137
|
toolChoice?: "auto" | "none" | "required";
|
|
146
|
-
/** Turn demands fresh tool evidence — arms the loop's reactive one-shot forced retry. */
|
|
147
|
-
freshEvidenceRequired?: boolean;
|
|
148
138
|
/** Parent fork depth (0 = top-level, default 0). CC: depth tracking for fork recursion limit. */
|
|
149
139
|
parentDepth?: number;
|
|
150
|
-
/** Per-turn token budget (prompt + completion). 0 or undefined = unlimited. */
|
|
151
|
-
tokenBudget?: number;
|
|
152
140
|
/** Fallback model to switch to after repeated 529 errors (CC parity). */
|
|
153
141
|
fallbackModel?: string;
|
|
154
142
|
/** Max turns (tool loop iterations). 0 or undefined = use maxRounds. */
|
|
@@ -182,7 +170,7 @@ export interface TurnConfig {
|
|
|
182
170
|
/** MCP server configurations (stdio/sse/http). Passed from host to agent per-turn. */
|
|
183
171
|
mcpServers?: Record<string, unknown>;
|
|
184
172
|
}
|
|
185
|
-
export type {
|
|
173
|
+
export type { ToolCallExecutionEvidence };
|
|
186
174
|
/**
|
|
187
175
|
* ToolInvoker: request tool execution from the host process (Gateway).
|
|
188
176
|
* In CLI mode this sends a JSON-RPC notification over stdio and waits for result.
|
|
@@ -4,7 +4,7 @@ import type { ChatMessage } from "../../agent/types.js";
|
|
|
4
4
|
import { type ForkedAgentResult } from "../../runtime/execution/forked-agent.js";
|
|
5
5
|
import type { BackgroundTaskManager } from "../../runtime/infra/background-tasks.js";
|
|
6
6
|
import type { ToolCatalog } from "../../runtime/ports/index.js";
|
|
7
|
-
import type {
|
|
7
|
+
import type { AgentToolDeps } from "../../skills/tools/agent-tool.js";
|
|
8
8
|
import type { LLMTransport } from "../provider-core-facade.js";
|
|
9
9
|
export interface AgentToolServiceHost {
|
|
10
10
|
readonly agent: unknown | null;
|
|
@@ -49,5 +49,4 @@ export declare function extractForkLifecycleSummary(result: ForkedAgentResult):
|
|
|
49
49
|
totalTokens: number;
|
|
50
50
|
};
|
|
51
51
|
};
|
|
52
|
-
export declare function extractForkUiAcceptanceEvidence(result: ForkedAgentResult): NonNullable<AgentResult["uiAcceptanceEvidence"]>;
|
|
53
52
|
export declare function createAgentToolService({ host, hooks, log, toolCatalog, toolInvoker }: AgentToolServiceOptions): AgentToolDeps;
|
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
import { type ModelPurpose } from "../../runtime/infra/model-registry.js";
|
|
6
6
|
import { type InstructionFileInfo } from "../../runtime/prompt/instruction-loader.js";
|
|
7
7
|
import type { HookRegistry } from "../../contracts/hooks.js";
|
|
8
|
-
export { isStructuredPlannerSystemPrompt } from "../../contracts/structured-planner.js";
|
|
9
8
|
import type { PermissionMetadataResolver, ToolCatalog } from "../../runtime/ports/index.js";
|
|
10
9
|
import type { ChatMessage, TokenUsage, ToolDefinition, TurnConfig } from "../../agent/types.js";
|
|
11
10
|
type UnderstandMediaKind = "image" | "video" | "audio";
|
|
@@ -129,3 +128,4 @@ export interface TurnPipelineResult {
|
|
|
129
128
|
* Invoked with `.call(host, input)` by the standard-ACP `session/prompt` handler.
|
|
130
129
|
*/
|
|
131
130
|
export declare function runTurnPipeline(this: any, input: TurnPipelineInput): Promise<TurnPipelineResult>;
|
|
131
|
+
export {};
|
|
@@ -13,7 +13,7 @@ export interface McpBootstrapDeps {
|
|
|
13
13
|
setManager(manager: McpManager | null): void;
|
|
14
14
|
setReady(ready: Promise<void>): void;
|
|
15
15
|
setConfigKey?(configKey: string): void;
|
|
16
|
-
/**
|
|
16
|
+
/** Optional manager factory; defaults to the concrete mcporter-backed manager. */
|
|
17
17
|
createManager?(config: McpManagerConfig): McpManager;
|
|
18
18
|
}
|
|
19
19
|
export declare const mcpToolRegistrationModule: import("../runtime/ports/tool-contracts.js").ToolRegistrationModule<McpBootstrapDeps>;
|
|
@@ -18,6 +18,6 @@ export declare class StdioAcpProtocolCoordinator {
|
|
|
18
18
|
} | undefined;
|
|
19
19
|
dispose(_reason?: string): void;
|
|
20
20
|
private textState;
|
|
21
|
-
private
|
|
21
|
+
private flushCommittedAgentMessage;
|
|
22
22
|
emitUpdate<M extends NotificationMethod>(sessionId: string, method: M, params: NotificationMethodMap[M]): boolean;
|
|
23
23
|
}
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* Internal contracts — hooks.
|
|
3
3
|
*/
|
|
4
4
|
export * from "./hooks.js";
|
|
5
|
-
export type {
|
|
5
|
+
export type { SkillCreateInstruction, SkillImproveInstruction, SkillInstruction, TurnEvent, } from "./turn-event.js";
|
|
@@ -9,17 +9,6 @@ export interface ToolCallExecutionEvidence {
|
|
|
9
9
|
error?: string;
|
|
10
10
|
failureKind?: "policy_blocked" | "semantic_quality_failed" | "timeout" | "mcp_start_failed" | "mcp_unavailable" | "tool_execution_failed";
|
|
11
11
|
}
|
|
12
|
-
export interface FinalAnswerEvidence {
|
|
13
|
-
schemaVersion: 1;
|
|
14
|
-
requirement: "not-required" | "fresh-tool-evidence";
|
|
15
|
-
disposition: "not-required" | "grounded" | "blocked-no-tool-evidence" | "blocked-no-successful-evidence";
|
|
16
|
-
successfulCallIds: string[];
|
|
17
|
-
failedCallIds: string[];
|
|
18
|
-
blockedCallIds: string[];
|
|
19
|
-
reason: string;
|
|
20
|
-
}
|
|
21
|
-
export declare function isFreshEvidenceToolCall(call: Pick<ToolCallExecutionEvidence, "identity">): boolean;
|
|
22
|
-
export declare function hasSuccessfulFreshToolEvidence(toolCalls: readonly ToolCallExecutionEvidence[]): boolean;
|
|
23
12
|
export declare function classifyToolFailureKind(result: {
|
|
24
13
|
blocked?: boolean;
|
|
25
14
|
blockReason?: string;
|
|
@@ -33,4 +22,3 @@ export declare function summarizeToolExecutionOutcomes(toolCalls: readonly Pick<
|
|
|
33
22
|
failedTools: string[];
|
|
34
23
|
blockedTools: string[];
|
|
35
24
|
};
|
|
36
|
-
export declare function buildFinalAnswerEvidence(freshEvidenceRequired: boolean, toolCalls: readonly ToolCallExecutionEvidence[], requiredSuccessfulLogicalToolNames?: readonly string[]): FinalAnswerEvidence;
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
export declare function isAgentOwnedBuiltinTool(toolName: string, identity?: {
|
|
2
|
-
owner?: string;
|
|
3
|
-
family?: string;
|
|
4
|
-
}): boolean;
|
|
5
1
|
/**
|
|
6
2
|
* Return the provider-local name of a projected function.
|
|
7
3
|
*
|
|
@@ -11,4 +7,3 @@ export declare function isAgentOwnedBuiltinTool(toolName: string, identity?: {
|
|
|
11
7
|
export declare function toolLocalName(toolName: string): string;
|
|
12
8
|
export declare function toolNamespace(toolName: string): string | undefined;
|
|
13
9
|
export declare function isQualifiedToolName(toolName: string): boolean;
|
|
14
|
-
export declare function toolNameMatches(toolName: string, localName: string): boolean;
|