qlogicagent 2.24.9 → 2.24.11
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/README.md +4 -0
- package/dist/agent.js +7 -11
- package/dist/cli.js +7 -7
- package/dist/embedded.js +11 -0
- package/dist/index.js +150 -163
- package/dist/orchestration.js +10 -16
- package/dist/skills/builtin/web-research/SKILL.md +8 -5
- package/dist/types/agent/tool-loop/compression-pipeline.d.ts +5 -11
- package/dist/types/agent/tool-loop/stream-error-recovery.d.ts +2 -7
- package/dist/types/agent/tool-loop.d.ts +3 -12
- package/dist/types/agent/types.d.ts +2 -7
- package/dist/types/cli/core-tools/fork-system-prompt.d.ts +13 -21
- package/dist/types/cli/handlers/turn-handler.d.ts +2 -2
- package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +1 -1
- package/dist/types/embedded/contracts.d.ts +244 -0
- package/dist/types/embedded/default-runtime-ports.d.ts +3 -0
- package/dist/types/embedded/embedded-tool-executor.d.ts +9 -0
- package/dist/types/embedded/index.d.ts +3 -0
- package/dist/types/orchestration/error-handling/retry-loop.d.ts +0 -9
- package/dist/types/orchestration/index.d.ts +2 -4
- package/dist/types/protocol/wire/acp-protocol.d.ts +6 -3
- package/dist/types/protocol/wire/index.d.ts +2 -2
- package/dist/types/protocol/wire/notification-payloads.d.ts +7 -0
- package/dist/types/runtime/config/tunable-defaults.d.ts +0 -3
- package/dist/types/runtime/context/context-compression-strategies.d.ts +0 -108
- package/dist/types/runtime/execution/tool-result-storage.d.ts +0 -11
- package/dist/types/runtime/hooks/context-compression.d.ts +9 -12
- package/dist/types/runtime/infra/file-watcher.d.ts +1 -3
- package/dist/types/runtime/ports/agent-runtime-ports.d.ts +0 -13
- package/dist/types/runtime/ports/model-transport-contracts.d.ts +15 -0
- package/dist/types/runtime/prompt/instruction-loader.d.ts +13 -13
- package/dist/types/runtime/prompt/system-prompt-sections.d.ts +9 -11
- package/package.json +10 -2
- package/dist/types/orchestration/context/context-collapse.d.ts +0 -58
package/dist/orchestration.js
CHANGED
|
@@ -1,29 +1,23 @@
|
|
|
1
|
-
function
|
|
2
|
-
${JSON.stringify(e)}`}}var
|
|
3
|
-
${
|
|
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 G(e){return T(e,y.rateLimit)}function ve(e){return T(e,y.timeout)}function Ie(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 j(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":G(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&&j(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||(Ie(e)?x(e)?"billing":"rate_limit":G(e)?"rate_limit":q(e)?"overloaded":De(e)?$(e.trim())?.code===529?"overloaded":"timeout":Fe(e)?"timeout":Me(e)?"format":x(e)?"billing":ve(e)?"timeout":j(e)?"auth_permanent":we(e)?"auth":null)}var Ge=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e){return Ge.has(e)}var je={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?je[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(a=>a.itemId).filter(a=>!!a),s={...o?.state.anchors??{}};for(let a of e)for(let u of a.contextAnchors??[]){let p=s[u.category]??[];s[u.category]=[...new Set([...p,h(u.value)])].slice(-50)}let i=[...o?.state.userRequests??[],...e.filter(a=>a.role==="user").map(a=>h(typeof a.content=="string"?a.content:JSON.stringify(a.content??"")))].slice(-50),c={summary:h(t),userRequests:i,anchors:s},l={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((a,u)=>a+n(u),0)};return{receipt:{...l,digest:ze(JSON.stringify({receipt:l,state:c}))},state:c}}function He(e){return{role:"system",content:`${_}
|
|
2
|
+
${JSON.stringify(e)}`}}var X=4;function K(e){return{role:"system",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=[],l=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&&l>=X)break;if(s-f<0&&l<X){c.unshift(d),l++;continue}s-=f,c.unshift(d),l++}let a=r.length-(c.length+(i&&!c.includes(i)?1:0)),u=[...o];return i&&!c.includes(i)&&u.push(i),a>0&&u.push(K(a)),u.push(...c),{messages:u,droppedCount:a,strategy:"sliding-window"}}},E=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.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:"system",content:`[Conversation summary]
|
|
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
|
|
10
|
-
`)}var
|
|
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??"")),l=i.role==="user"?c:c.length>2e3?c.slice(0,2e3)+"...":c;return`[${i.role}]: ${l}`}),"","## 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(),{system:r,nonSystem:s}=Ke(t),i=r.findIndex(m=>k(m)!==void 0),c=k(i>=0?r[i]:void 0),l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,a=t.reduce((m,R)=>m+this.config.estimateTokens(R),0);if(a<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let m=0;m<s.length&&(s[m].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));m++)u=m+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),f=Math.max(u,s.length-d);if(f<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let se=s.slice(0,u),C=s.slice(u,f),ie=s.slice(f),ae=J(C,{taskContext:[this.config.taskContext,c?`Prior verified capsule:
|
|
11
|
+
${JSON.stringify(c.state)}`:void 0].filter(Boolean).join(`
|
|
12
12
|
|
|
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
|
-
${JSON.stringify(a.state)}
|
|
15
|
-
|
|
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
|
-
|
|
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?`
|
|
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?`
|
|
20
14
|
|
|
21
15
|
Your working directory is: ${e.worktreePath}
|
|
22
|
-
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${
|
|
16
|
+
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${F}
|
|
23
17
|
|
|
24
18
|
You are the "${t.agent.name}" agent.${o}
|
|
25
19
|
|
|
26
|
-
${t.taskPrompt}`}]};return n.push(r),n}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 vt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var It={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=[It,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 Gt(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function jt(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,consecutiveTruncations:0,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,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 Yt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function Wt(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
21
|
${n.join(`
|
|
28
22
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
29
23
|
Step ${e.activeSkillContext.step}:
|
|
@@ -34,4 +28,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
34
28
|
|
|
35
29
|
${t.join(`
|
|
36
30
|
|
|
37
|
-
`)}`}function
|
|
31
|
+
`)}`}function Xt(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Kt(e){return!e.attemptedThisTurn}export{_ as CONTEXT_CAPSULE_MARKER,v as CacheAwareCompressionStrategy,I 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,Wt as buildPostCompactRestorationMessage,J as buildStructuredSummaryPrompt,de as buildToolResultMessage,zt as calculateTokenWarningState,At as canForkAtDepth,qe as classifyError,We as computeAdaptiveBudget,Rt as computeRetryBackoff,Xt as createReactiveCompactState,Gt as createTaskState,qt as createTurnLoopGuardState,vt 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,Ht as resolveOutputTokenEscalation,jt as resolvePromptContextTokens,Xe as selectCompressionTier,yt as settleToolLoopState,Yt as shouldAbortTurn,Kt as shouldAttemptReactiveCompact};
|
|
@@ -23,14 +23,17 @@ description: 需要联网查资料、搜索网页、抓取网页内容或做多
|
|
|
23
23
|
如果找不到工具或 Prompt:
|
|
24
24
|
|
|
25
25
|
1. 引导用户在桌面端“插件 → 连接器”安装并启用官方 **Astra Search**。
|
|
26
|
-
2. Xiaozhi Runtime 会在正常 llmrouter
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
2. Xiaozhi Runtime 会在正常 llmrouter 握手后自动取得仅供 `astra-search` 使用的独立
|
|
27
|
+
托管 Key,不应让用户选择认证模式或重复填写密钥;如果该 Key 尚不可用,引导用户
|
|
28
|
+
先完成桌面账号登录。
|
|
29
|
+
3. 第三方 Agent 所使用的 MCP 客户端支持标准 OAuth 授权时,使用浏览器 OAuth + PKCE
|
|
30
|
+
完成登录,不要求用户复制 Key。MCP 客户端不支持 OAuth 时才使用普通 LLMRouter
|
|
31
|
+
API Key 兼容入口:
|
|
29
32
|
- 未注册时打开或给出 <https://www.qlogicagent.com/signup>;
|
|
30
33
|
- 登录后打开或给出 <https://www.qlogicagent.com/keys> 创建或重置密钥;
|
|
31
|
-
- 让用户返回 Astra Search
|
|
34
|
+
- 让用户返回 Astra Search 设置,把密钥填入安全的 API Key 凭证框。
|
|
32
35
|
4. 当前 Host 能安全打开外部链接时可以导航到上述页面;否则提供可点击链接。
|
|
33
|
-
**不要把 API Key 发到聊天、写入项目文件、日志、记忆或 Skill。**
|
|
36
|
+
**不要把 API Key 或 OAuth Token 发到聊天、写入项目文件、日志、记忆或 Skill。**
|
|
34
37
|
|
|
35
38
|
完成安装、绑定、启用和连接测试后,重新发现 MCP 清单并读取 Prompt。不得改用旧
|
|
36
39
|
REST 搜索、本地 provider 或其它隐藏 fallback。
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Context compression pipeline
|
|
2
|
+
* Context compression pipeline for one provider round.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* → whitespace filter, returning the messages to send to the LLM. Each stage runs
|
|
8
|
-
* before the next; an earlier stage that brings us under threshold makes later
|
|
9
|
-
* stages no-ops.
|
|
4
|
+
* This transform has a side-channel of `recovery` events. It applies
|
|
5
|
+
* deterministic tool-result controls, then selects at most one context compaction
|
|
6
|
+
* transform before returning the model-visible history.
|
|
10
7
|
*
|
|
11
8
|
* Extracted from the main loop to cut its reading cost: this phase has no control-flow
|
|
12
9
|
* escape (never continues/returns the outer loop), so it is a clean `yield*` boundary.
|
|
@@ -15,13 +12,10 @@
|
|
|
15
12
|
*/
|
|
16
13
|
import type { AgentLogger, HookRegistry, TurnEvent } from "../types.js";
|
|
17
14
|
import type { ToolLoopRuntimePorts } from "../../runtime/ports/index.js";
|
|
18
|
-
import { type
|
|
15
|
+
import { type TurnLoopGuardConfig } from "../../orchestration/index.js";
|
|
19
16
|
export interface CompressionPipelineDeps {
|
|
20
17
|
messages: unknown[];
|
|
21
18
|
contentReplacementState: unknown;
|
|
22
|
-
snipRemovedIds: Set<string>;
|
|
23
|
-
collapseStore: CollapseStore;
|
|
24
|
-
guardState: TurnLoopGuardState;
|
|
25
19
|
guardConfig: TurnLoopGuardConfig;
|
|
26
20
|
runtimePorts: ToolLoopRuntimePorts;
|
|
27
21
|
hooks: HookRegistry | undefined;
|
|
@@ -11,22 +11,18 @@
|
|
|
11
11
|
* - { kind: "return" } → loop returns (a terminal error event was already yielded)
|
|
12
12
|
* - { kind: "streamError", … } → loop sets streamError and falls through to error withholding
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* whether we continue or fall through). Covered by tool-loop.states.test.ts:
|
|
17
|
-
* fallback / stale-connection / max-tokens-overflow / 429-retry.
|
|
14
|
+
* The retry stays on the selected model. Provider selection remains Host-owned;
|
|
15
|
+
* capacity errors never trigger an Agent-side model switch.
|
|
18
16
|
*/
|
|
19
17
|
import type { AgentLogger, TokenUsage, ToolLoopTransition, TurnEvent } from "../types.js";
|
|
20
18
|
/** Subset of the loop's State this phase reads / mutates in place. */
|
|
21
19
|
export interface StreamErrorState {
|
|
22
20
|
consecutive529Errors: number;
|
|
23
21
|
consecutiveApiRetries: number;
|
|
24
|
-
currentModel: string;
|
|
25
22
|
totalUsage: TokenUsage;
|
|
26
23
|
}
|
|
27
24
|
/** Fields the loop should merge into State before continuing. */
|
|
28
25
|
export interface StreamErrorPatch {
|
|
29
|
-
currentModel?: string;
|
|
30
26
|
consecutive529Errors?: number;
|
|
31
27
|
consecutiveApiRetries?: number;
|
|
32
28
|
maxOutputTokensOverride?: number;
|
|
@@ -49,7 +45,6 @@ export interface StreamErrorCtx {
|
|
|
49
45
|
guardState: {
|
|
50
46
|
currentMaxOutputTokens: number;
|
|
51
47
|
};
|
|
52
|
-
fallbackModel: string | undefined;
|
|
53
48
|
signal: AbortSignal | undefined;
|
|
54
49
|
querySource: string | undefined;
|
|
55
50
|
turnId: string;
|
|
@@ -28,13 +28,6 @@ export interface ToolLoopParams {
|
|
|
28
28
|
modelMaxOutputTokens?: number;
|
|
29
29
|
/** Tool choice strategy (default "auto") */
|
|
30
30
|
toolChoice?: "auto" | "none" | "required";
|
|
31
|
-
/**
|
|
32
|
-
* The turn's request demands fresh tool evidence (file read / command run / media generated).
|
|
33
|
-
* The prompt section instructs it; this flag arms the loop's REACTIVE one-shot forced retry
|
|
34
|
-
* when the model answers in prose with zero tool calls anyway. Replaces the retired upstream
|
|
35
|
-
* tool_choice="required" forcing (judgment-over-mechanism: hint first, force only on the
|
|
36
|
-
* observed violation).
|
|
37
|
-
*/
|
|
38
31
|
/** Parent fork depth (0 = top-level) */
|
|
39
32
|
parentDepth?: number;
|
|
40
33
|
/** Tool eligibility context for policy-based filtering */
|
|
@@ -43,12 +36,10 @@ export interface ToolLoopParams {
|
|
|
43
36
|
hooks?: HookRegistry;
|
|
44
37
|
/** Max turns (loop iterations). 0 = use maxRounds. */
|
|
45
38
|
maxTurns?: number;
|
|
46
|
-
/**
|
|
47
|
-
fallbackModel?: string;
|
|
48
|
-
/** Query source for foreground/background retry distinction (CC parity). */
|
|
39
|
+
/** Query source for foreground/background retry distinction. */
|
|
49
40
|
querySource?: string;
|
|
50
41
|
/**
|
|
51
|
-
* Refresh tools callback
|
|
42
|
+
* Refresh tools callback, called between turns.
|
|
52
43
|
* Returns updated tool definitions if tools have changed (e.g. MCP reconnect),
|
|
53
44
|
* or the same array reference if unchanged.
|
|
54
45
|
*/
|
|
@@ -118,7 +109,7 @@ export interface ToolLoopParams {
|
|
|
118
109
|
signal?: AbortSignal;
|
|
119
110
|
}
|
|
120
111
|
/**
|
|
121
|
-
* Execute the tool loop
|
|
112
|
+
* Execute the provider/tool event loop.
|
|
122
113
|
*
|
|
123
114
|
* Yields TurnEvent stream. The caller (Agent class) wraps this with
|
|
124
115
|
* start/end lifecycle and error handling.
|
|
@@ -32,9 +32,6 @@ export type TokenUsage = WireTokenUsage;
|
|
|
32
32
|
export type { SkillCreateInstruction, SkillImproveInstruction, SkillInstruction, TurnEvent, } from "../contracts/turn-event.js";
|
|
33
33
|
/** Observable reason why the provider loop started another inference round. */
|
|
34
34
|
export type ToolLoopTransition = {
|
|
35
|
-
reason: "collapse_drain_retry";
|
|
36
|
-
committed: number;
|
|
37
|
-
} | {
|
|
38
35
|
reason: "reactive_compact_retry";
|
|
39
36
|
} | {
|
|
40
37
|
reason: "max_output_tokens_escalate";
|
|
@@ -137,17 +134,15 @@ export interface TurnConfig {
|
|
|
137
134
|
toolChoice?: "auto" | "none" | "required";
|
|
138
135
|
/** Parent fork depth (0 = top-level, default 0). CC: depth tracking for fork recursion limit. */
|
|
139
136
|
parentDepth?: number;
|
|
140
|
-
/** Fallback model to switch to after repeated 529 errors (CC parity). */
|
|
141
|
-
fallbackModel?: string;
|
|
142
137
|
/** Max turns (tool loop iterations). 0 or undefined = use maxRounds. */
|
|
143
138
|
maxTurns?: number;
|
|
144
139
|
/** Max concurrent tool executions (0 = unlimited). */
|
|
145
140
|
maxConcurrentTools?: number;
|
|
146
|
-
/** Model requires
|
|
141
|
+
/** Model requires streaming; disable transport-level non-streaming fallback. */
|
|
147
142
|
streamRequired?: boolean;
|
|
148
143
|
/** Reasoning effort for models that support it (GPT-5.x, o-series). */
|
|
149
144
|
reasoning?: {
|
|
150
|
-
effort: "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
145
|
+
effort: "auto" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
151
146
|
includeEncryptedReasoning?: boolean;
|
|
152
147
|
};
|
|
153
148
|
/** Prompt cache bucketing key used instead of the provider-level `user` field. */
|
|
@@ -1,39 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Subagent
|
|
2
|
+
* Subagent persona and repository-context assembly.
|
|
3
3
|
*
|
|
4
4
|
* A forked subagent starts FRESH (no parent conversation by default), but it
|
|
5
|
-
* still needs
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* still needs a system persona and the same lower-authority repository context as
|
|
6
|
+
* the parent. These are returned separately so repository files never inherit the
|
|
7
|
+
* persona's system role.
|
|
8
8
|
*
|
|
9
9
|
* Without these the subagent produces off-convention work and ignores standing
|
|
10
|
-
* user/project context.
|
|
11
|
-
* message" model: the brief is the prompt, the standing context is injected here.
|
|
10
|
+
* user/project context. The direct delegated task remains the latest user message.
|
|
12
11
|
*/
|
|
13
12
|
import type { HookRegistry } from "../../contracts/hooks.js";
|
|
14
13
|
import type { AgentDefinition } from "../../orchestration/subagent/agent-registry.js";
|
|
15
|
-
export interface
|
|
14
|
+
export interface SubagentPromptContextInput {
|
|
16
15
|
/** Behavioral framing — who the subagent is and how it should act. */
|
|
17
16
|
persona: string;
|
|
18
|
-
/** Project root
|
|
17
|
+
/** Project root for loading repository instructions. */
|
|
19
18
|
cwd?: string;
|
|
20
19
|
/** Hook registry (instruction loader uses it). */
|
|
21
20
|
hooks?: HookRegistry;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
*/
|
|
27
|
-
includeRules?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface SubagentPromptContext {
|
|
23
|
+
systemPrompt?: string;
|
|
24
|
+
repositoryInstructionMessage?: string;
|
|
28
25
|
}
|
|
29
26
|
/** Build the persona section for a built-in fork agent (type + behavioral suffix). */
|
|
30
27
|
export declare function personaForAgentDefinition(agentDef: AgentDefinition): string;
|
|
31
28
|
/**
|
|
32
|
-
*
|
|
33
|
-
* and the subprocess team member, so their standing context is identical:
|
|
34
|
-
* 1. persona — who the subagent is / how it behaves (caller-supplied)
|
|
35
|
-
* 2. project rules / AGENTS — the same getInstructions the parent loads
|
|
36
|
-
*
|
|
37
|
-
* Returns undefined when there is genuinely nothing to inject.
|
|
29
|
+
* Return the system persona and repository user context as separate values.
|
|
38
30
|
*/
|
|
39
|
-
export declare function
|
|
31
|
+
export declare function buildSubagentPromptContext(input: SubagentPromptContextInput): Promise<SubagentPromptContext>;
|
|
@@ -24,13 +24,13 @@ export interface TurnControlHandlerHost {
|
|
|
24
24
|
*/
|
|
25
25
|
export declare function logTurnBackgroundFailure(context: string, err: unknown): void;
|
|
26
26
|
/**
|
|
27
|
-
* Load the INSTRUCTIONS.md / project-rules
|
|
27
|
+
* Load the INSTRUCTIONS.md / project-rules user message for a turn. A load failure means the WHOLE turn
|
|
28
28
|
* runs without the user's standing rules — the old inline catch called that "non-fatal" and left
|
|
29
29
|
* zero trace. Degrading is still the right call (the turn can proceed), but it must be visible
|
|
30
30
|
* in the adapter diagnostic log.
|
|
31
31
|
* `loadInstructions` is injectable so tests can force a failure; defaults to getInstructions.
|
|
32
32
|
*/
|
|
33
|
-
export declare function
|
|
33
|
+
export declare function loadRepositoryInstructionMessageForTurn(deps: {
|
|
34
34
|
cwd: string;
|
|
35
35
|
turnId: string;
|
|
36
36
|
hooks?: HookRegistry;
|
|
@@ -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 flushCommittedThought;
|
|
22
22
|
emitUpdate<M extends NotificationMethod>(sessionId: string, method: M, params: NotificationMethodMap[M]): boolean;
|
|
23
23
|
}
|