qlogicagent 2.12.6 → 2.12.8
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 +6 -6
- package/dist/cli.js +294 -288
- package/dist/index.js +293 -287
- package/dist/orchestration.js +6 -6
- package/dist/types/cli/acp-session-host.d.ts +17 -4
- package/dist/types/cli/core-tool-coordinator.d.ts +2 -0
- package/dist/types/cli/core-tools/agent-tool-service.d.ts +4 -0
- package/dist/types/cli/core-tools/fork-system-prompt.d.ts +45 -0
- package/dist/types/cli/core-tools/team-tool-service.d.ts +14 -3
- package/dist/types/cli/stdio-server.d.ts +2 -0
- package/dist/types/orchestration/index.d.ts +1 -1
- package/dist/types/runtime/infra/agent-process.d.ts +12 -9
- package/dist/types/runtime/infra/background-tasks.d.ts +26 -0
- package/dist/types/runtime/tasks/task-types.d.ts +24 -19
- package/package.json +2 -2
package/dist/orchestration.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(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}:{}}}var Ee=/\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]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,
|
|
1
|
+
function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(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}:{}}}var Ee=/\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]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,we=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Oe=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],De=["daily","weekly","monthly"],Fe=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?: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,He=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $e(e){return h(e,y.format)}function W(e){return h(e,y.rateLimit)}function ze(e){return h(e,y.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,y.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function V(e){return h(e,y.authPermanent)}function Xe(e){return h(e,y.auth)}function J(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function Ke(e){return T(e,Pe)||T(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=T(e,De),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ue);return T(e,Fe)&&T(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,je))}function We(e){return e.trim().toLowerCase().replace(He,"").trim()}function Z(e){let t=We(e);return!t||Ke(t)?"billing":W(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Z(e):null}function Q(e){let t=e.match(we);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=Q(t);return n?Oe.has(n.code):!1}function ee(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&&V(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&J(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(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 et(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 te(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":W(e)?"rate_limit":J(e)?"overloaded":Ze(e)?Q(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":$e(e)?"format":E(e)?"billing":ze(e)?"timeout":V(e)?"auth_permanent":Xe(e)?"auth":null)}var tt={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"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=ee(e,t)??(t?te(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var ne=4,I=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let c of t)c.role==="system"?o.push(c):r.push(c);let i=n;for(let c of o)i-=this.estimateTokens(c);let a;for(let c of r)if(c.role==="user"){a=c;break}if(a&&(i-=this.estimateTokens(a)),i<=0)return{messages:a?[...o,a]:o,droppedCount:r.length-(a?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===a)continue;let p=this.estimateTokens(d);if(i-p<0&&l>=ne)break;if(i-p<0&&l<ne){s.unshift(d),l++;continue}i-=p,s.unshift(d),l++}let u=[...o];return a&&!s.includes(a)&&u.push(a),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(a&&!s.includes(a)?1:0)),strategy:"sliding-window"}}},v=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 i=r.slice(0,r.length-this.recentCount),a=r.slice(r.length-this.recentCount),s=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
2
2
|
${s}`},...a],droppedCount:i.length,strategy:"summarize-old"}}},L=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:st(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function st(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
3
3
|
`),n.lastIndexOf(`]
|
|
4
4
|
`));if(i>t*.5)return n.slice(0,i+1)+`
|
|
@@ -6,9 +6,9 @@ ${s}`},...a],droppedCount:i.length,strategy:"summarize-old"}}},L=class{construct
|
|
|
6
6
|
`);return r>t*.7?n.slice(0,r)+`
|
|
7
7
|
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
8
8
|
[...truncated: ${e.length-t} chars omitted]`}function it(...e){return{compress(t,n){let o=t,r=0,i=[];for(let a of e){let s=a.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function at(...e){return{compress(t,n){let o=t,r=0,i=[];for(let a of e){let s=a.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],a=0,s=!1,l=!1;for(let u of e){let c=B(u)?await u.compressAsync(o,n):u.compress(o,n);o=c.messages,r+=c.droppedCount,c.droppedCount>0&&i.push(c.strategy),c.metrics&&(a+=c.metrics.latencyMs,s=s||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:a>0||s?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:a,usedLlm:s,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(a=>a.role==="user"),o=e.filter(a=>a.tool_calls!=null),r=e.filter(a=>a.role==="tool"),i=["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","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact values, identifiers, keywords, or secrets the user mentioned or asked you to remember. 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&&i.push("","## Additional Context",t.taskContext),i.push("","## Conversation to Summarize","",...e.map(a=>{let s=typeof a.content=="string"?a.content:JSON.stringify(a.content??""),l=a.role==="user"?s:s.length>2e3?s.slice(0,2e3)+"...":s;return`[${a.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."),i.join(`
|
|
9
|
-
`)}var
|
|
9
|
+
`)}var w=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??S,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:i}=re(t),a=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(a<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let s=0,l=0;for(let m=0;m<i.length&&(i[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)s=m+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),c=Math.max(s,i.length-u);if(c<=s)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=i.slice(0,s),p=i.slice(s,c),f=i.slice(c),C=U(p,{taskContext:this.config.taskContext}),k=await this.config.summarize(p,C),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
10
10
|
|
|
11
|
-
${k}`},_=[...r,...d,A,...f],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:a,tokensAfter:b,compressionRatio:a>0?b/a:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},
|
|
11
|
+
${k}`},_=[...r,...d,A,...f],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:a,tokensAfter:b,compressionRatio:a>0?b/a:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},O=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??S}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=re(t),a=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),s=a>=0?r[a]:void 0,l=a>=0?[...r.slice(0,a),...r.slice(a+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let c=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),p=i.slice(u),f=s&&typeof s.content=="string"?`Previous summary:
|
|
12
12
|
${s.content}
|
|
13
13
|
|
|
14
14
|
New messages to integrate:`:void 0,C=U(d,{taskContext:f}),k=await this.config.summarize(d,C),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
@@ -17,14 +17,14 @@ ${k}`},_=[...l,A,...p],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTo
|
|
|
17
17
|
`),a=r.filter(p=>!i.includes(p));if(a.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of a){if(u>=n.maxFiles||s<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>s||(s-=C,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
18
18
|
|
|
19
19
|
${f}`}))}if(l.length===0)return e;let c=[...e],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function mt(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}i.push(s)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:a}}function ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=se(e,t),a=yt(i,t,o);if(a.length===0)return{messages:i,stagedCount:0};for(let s of a)t.stages.push(s);return i=se(e,t),{messages:i,stagedCount:a.length}}function Tt(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:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(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,a]=r.range;if(i>=o.length)continue;let s=Math.min(a,o.length),l={role:"system",content:r.summary};o.splice(i,s-i,l)}return o}function yt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),a=-1,s=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")a<0&&(a=l),s++;else{if(s>=3){let d=`${a}-${a+s}`;i.has(d)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}a=-1,s=0}}if(s>=3){let l=`${a}-${a+s}`;i.has(l)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as H,dirname as _t}from"node:path";var Nn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Dn=300*1e3,j=4;var Fn=3600*1e3;var Bn=50*1024,Un=500*1024,jn=500*1024*1024,Gn=50*1024*1024;var Hn=60*1024;var Te=0;var bt="skill-patterns.json";function ye(e){return H(e,".qlogicagent",bt)}function he(e){let t=ye(e);try{return JSON.parse(fe(t,"utf8"))}catch{return{version:1,patterns:{}}}}function me(e,t){let n=ye(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-de;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Ce(e,t){if(t.length===0)return!1;let n=x(t),o=he(e);Rt(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return me(e,o),!1;i.count++,i.lastSeen=r;let a=i.count>=pe;return a&&(i.promoted=!0),me(e,o),a}function St(e){let t=he(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=ge(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=H(t,r.name,"SKILL.md");try{let s=fe(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let l=s[1].split(`
|
|
20
|
-
`).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _e(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 It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function Ot(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 wt(e){let t=Ot({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({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",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>_e(l)===a);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(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 Bt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Bt(t).has(e.trim().toLowerCase()):!1}function Ut(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 $(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>Ft(u));return{...s,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&i.push(c);continue}if(l.length<s.tool_calls.length){i.push({...s,tool_calls:l});continue}}i.push(s)}let a=[];for(let s of i){let l=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){a[a.length-1]=Dt(l,s);continue}a.push(s)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(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 a of i.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function jt(e,t){let n=$(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Ut(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,a=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(i.add(c),a.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!i.has(c))continue;s.add(c)}l.push(u)}for(let[u]of a)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Gt(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 Ht(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 $t(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 zt(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 xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function qt(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 Xt(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 Kt(e){let t=[],n=$(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=z(n,e.options);o.some((i,a)=>i!==n[a])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gt(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Yt(e){let t=Se(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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:$t(t),completedToolCallIds:zt(t)}),recoveryActions:n}}var Wt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Vt(e){return e?Wt.has(e):!0}function Jt(e){return e===429||e===529}function Zt(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 Qn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){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 K="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(K)}function tn(e){return e<j}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
20
|
+
`).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _e(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 It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function wt(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 Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({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",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>_e(l)===a);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(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 Bt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Bt(t).has(e.trim().toLowerCase()):!1}function Ut(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 $(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>Ft(u));return{...s,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&i.push(c);continue}if(l.length<s.tool_calls.length){i.push({...s,tool_calls:l});continue}}i.push(s)}let a=[];for(let s of i){let l=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){a[a.length-1]=Dt(l,s);continue}a.push(s)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(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 a of i.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function jt(e,t){let n=$(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Ut(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,a=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(i.add(c),a.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!i.has(c))continue;s.add(c)}l.push(u)}for(let[u]of a)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Gt(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 Ht(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 $t(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 zt(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 xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function qt(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 Xt(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 Kt(e){let t=[],n=$(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=z(n,e.options);o.some((i,a)=>i!==n[a])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gt(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Yt(e){let t=Se(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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:$t(t),completedToolCallIds:zt(t)}),recoveryActions:n}}var Wt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Vt(e){return e?Wt.has(e):!0}function Jt(e){return e===429||e===529}function Zt(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 Qn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){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 K="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(K)}function tn(e){return e<j}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
21
21
|
|
|
22
22
|
Your working directory is: ${e.worktreePath}
|
|
23
23
|
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${K}
|
|
24
24
|
|
|
25
25
|
You are the "${t.agent.name}" agent.${o}
|
|
26
26
|
|
|
27
|
-
${t.taskPrompt}`}]};return n.push(r),n}function on(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function rn(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"&&n!=="team")}function sn(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var an={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},ln={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_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},cn={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_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},un={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0},pn={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_file","search","think","memory"],canFork:!1},dn={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read_file","search","think"],canFork:!1},Y=[an,ln,cn,un,pn,dn];function mn(){return[...Y]}function fn(e){return Y.find(t=>t.name===e)}function gn(e){return Y.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"&&n!=="team")}var yn=new Set(["agent_tool","team_create","fork_agent","send_message"]);function hn(e,t){switch(e){case"worker":return t.filter(n=>!yn.has(n));case"coordinator":return[...t];default:return[...t]}}function Cn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function _n(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function bn(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Rn(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 Sn(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 xn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var kn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function An(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
|
+
${t.taskPrompt}`}]};return n.push(r),n}function on(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function rn(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"&&n!=="team")}function sn(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var an={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},ln={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_file","search","web_search","web_fetch","think","memory","tool_search"],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."},cn={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_file","search","web_search","web_fetch","think","memory","task","tool_search"],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."},un={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."},pn={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_file","search","think","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."},dn={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read_file","search","think"],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."},Y=[an,ln,cn,un,pn,dn];function mn(){return[...Y]}function fn(e){return Y.find(t=>t.name===e)}function gn(e){return Y.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"&&n!=="team")}var yn=new Set(["agent_tool","team_create","fork_agent","send_message"]);function hn(e,t){switch(e){case"worker":return t.filter(n=>!yn.has(n));case"coordinator":return[...t];default:return[...t]}}function Cn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function _n(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function bn(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Rn(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 Sn(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 xn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var kn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function An(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
|
|
28
28
|
${n.join(`
|
|
29
29
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
30
30
|
Step ${e.activeSkillContext.step}:
|
|
@@ -35,4 +35,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
35
35
|
|
|
36
36
|
${t.join(`
|
|
37
37
|
|
|
38
|
-
`)}`}function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function En(e,t=kn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,K as FORK_SENTINEL_TAG,X as FallbackTriggeredError,
|
|
38
|
+
`)}`}function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function En(e,t=kn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,K as FORK_SENTINEL_TAG,X as FallbackTriggeredError,w as HeadTailProtectedStrategy,O as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,F as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,qt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,Ot as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,on as buildForkPlaceholderResults,nn as buildForkedMessages,An as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,bn as calculateTokenWarningState,tn as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,Zt as computeRetryBackoff,ft as createCollapseStore,Mn as createReactiveCompactState,Cn as createTaskState,_n as createTurnLoopGuardState,hn as filterToolsByRole,sn as generateForkChildAgentId,fn as getBuiltInAgent,mn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,gn as isBuiltInAgent,Vt as isForegroundSource,en as isInForkChild,Qt as isPersistentRetryEnabled,rt as isRetryableCategory,Jt as isTransientCapacityError,dt as postCompactFileRecovery,Ce as recordPatternAndCheckThreshold,Tt as recoverContextCollapseFromOverflow,Kt as recoverToolLoopStateFromChatConversation,Yt as recoverToolLoopStateFromResponsesItems,jt as repairOpenAiChatConversation,Tn as resolveAgentToolSet,Rn as resolveApiErrorRecovery,rn as resolveForkChildTools,Sn as resolveOutputTokenEscalation,ct as selectCompressionTier,Xt as settleToolLoopState,xn as shouldAbortTurn,En as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
|
|
@@ -2,14 +2,27 @@ import type { HookRegistry } from "../contracts/hooks.js";
|
|
|
2
2
|
import type { AcpSessionMeta } from "../protocol/wire/index.js";
|
|
3
3
|
import { createMemoryPrefetchState } from "../runtime/hooks/memory-hooks.js";
|
|
4
4
|
import type { SessionState } from "../runtime/session/session-state.js";
|
|
5
|
+
/**
|
|
6
|
+
* LLM config pinned on the session by the host (session/set_config_option /
|
|
7
|
+
* session/set_model / the /model command). This is host-supplied INPUT — distinct
|
|
8
|
+
* from the host's resolved-agent snapshot (stdio-server current*), which is
|
|
9
|
+
* derived state and gets invalidated on every ModelRegistry change. Pinned config
|
|
10
|
+
* must survive registry churn: a spawned team member is provisioned exactly this
|
|
11
|
+
* way, and a background catalog hydration firing between the pin and the first
|
|
12
|
+
* prompt must not wipe it (that wipe was the standalone NO_PROVIDER bug).
|
|
13
|
+
*/
|
|
14
|
+
export interface SessionLlmConfig {
|
|
15
|
+
provider?: string;
|
|
16
|
+
model?: string;
|
|
17
|
+
apiKey?: string;
|
|
18
|
+
baseUrl?: string;
|
|
19
|
+
}
|
|
5
20
|
export interface AcpSessionHost {
|
|
6
21
|
/** Gateway-supplied per-session context (_meta from session/new); inherited by every prompt. */
|
|
7
22
|
acpSessionMeta: AcpSessionMeta | null;
|
|
8
|
-
|
|
9
|
-
|
|
23
|
+
/** Host-pinned per-session LLM config; overlaid into every prompt's turn config. */
|
|
24
|
+
sessionLlmConfig: SessionLlmConfig;
|
|
10
25
|
currentHooks: HookRegistry | null;
|
|
11
|
-
currentModel: string;
|
|
12
|
-
currentProvider: string;
|
|
13
26
|
currentSessionId: string;
|
|
14
27
|
memoryPrefetchState: ReturnType<typeof createMemoryPrefetchState>;
|
|
15
28
|
sessionState: SessionState | null;
|
|
@@ -6,6 +6,7 @@ import type { LLMTransport } from "./provider-core-facade.js";
|
|
|
6
6
|
export interface CliCoreToolHostDeps {
|
|
7
7
|
getAgent(): unknown | null;
|
|
8
8
|
getCurrentTransport(): LLMTransport | null;
|
|
9
|
+
getCurrentProvider(): string;
|
|
9
10
|
getCurrentApiKey(): string;
|
|
10
11
|
getCurrentModel(): string;
|
|
11
12
|
getCurrentBaseUrl(): string;
|
|
@@ -15,6 +16,7 @@ export interface CliCoreToolHostDeps {
|
|
|
15
16
|
getBackgroundTasks(): BackgroundTaskManager | null;
|
|
16
17
|
getConversationHistory(): readonly ChatMessage[] | null;
|
|
17
18
|
isGroupContext(): boolean;
|
|
19
|
+
getMemoryIndex(): string | null;
|
|
18
20
|
sendNotification(method: string, params: Record<string, unknown>): void;
|
|
19
21
|
emitAgentStatus(agentId: string, state: string, extra?: {
|
|
20
22
|
missedBeats?: number;
|
|
@@ -21,6 +21,10 @@ export interface AgentToolServiceHost {
|
|
|
21
21
|
getConversationHistory(): readonly ChatMessage[] | null;
|
|
22
22
|
/** Whether the current turn is group-chat / untrusted (drives context redaction). */
|
|
23
23
|
isGroupContext(): boolean;
|
|
24
|
+
/** Active project root — for loading the subagent's project rules / AGENTS. */
|
|
25
|
+
getActiveProjectRoot(): string;
|
|
26
|
+
/** Lightweight memory INDEX block injected into the subagent system prompt. */
|
|
27
|
+
getMemoryIndex(): string | null;
|
|
24
28
|
}
|
|
25
29
|
export interface AgentToolServiceOptions {
|
|
26
30
|
host: AgentToolServiceHost;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent system-prompt assembly.
|
|
3
|
+
*
|
|
4
|
+
* A forked subagent starts FRESH (no parent conversation by default), but it
|
|
5
|
+
* still needs three things the parent has, injected by policy:
|
|
6
|
+
* 1. Persona — who it is and how it should behave (agent definition).
|
|
7
|
+
* 2. Project rules — the same .qlogicagent/rules + AGENTS.md the parent loads.
|
|
8
|
+
* 3. Memory — the lightweight memory INDEX (user preferences / project facts).
|
|
9
|
+
*
|
|
10
|
+
* Without these the subagent produces off-convention work and ignores standing
|
|
11
|
+
* user/project context. This mirrors Claude Code's "compose a delegation
|
|
12
|
+
* message" model: the brief is the prompt, the standing context is injected here.
|
|
13
|
+
*/
|
|
14
|
+
import type { HookRegistry } from "../../contracts/hooks.js";
|
|
15
|
+
import type { AgentDefinition } from "../../orchestration/subagent/agent-registry.js";
|
|
16
|
+
export interface SubagentSystemPromptInput {
|
|
17
|
+
/** Behavioral framing — who the subagent is and how it should act. */
|
|
18
|
+
persona: string;
|
|
19
|
+
/** Project root, for loading rules/AGENTS (only when includeRules). */
|
|
20
|
+
cwd?: string;
|
|
21
|
+
/** Hook registry (instruction loader uses it). */
|
|
22
|
+
hooks?: HookRegistry;
|
|
23
|
+
/** Lightweight memory INDEX block (memdir.getIndexForPrompt()), or null. */
|
|
24
|
+
memoryIndex: string | null;
|
|
25
|
+
/**
|
|
26
|
+
* Inject project rules / AGENTS. True for the in-process fork (it has no turn
|
|
27
|
+
* pipeline of its own). False for a subprocess team member, which assembles its
|
|
28
|
+
* own rules from its worktree — skip to avoid duplicating them.
|
|
29
|
+
*/
|
|
30
|
+
includeRules?: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** Build the persona section for a built-in fork agent (type + behavioral suffix). */
|
|
33
|
+
export declare function personaForAgentDefinition(agentDef: AgentDefinition): string;
|
|
34
|
+
/** Build the persona section for a team member (name + role + coordination note). */
|
|
35
|
+
export declare function personaForTeamMember(name: string, role: string): string;
|
|
36
|
+
/**
|
|
37
|
+
* Shared subagent context assembly — used by BOTH the in-process fork (agent tool)
|
|
38
|
+
* and the subprocess team member, so their standing context is identical:
|
|
39
|
+
* 1. persona — who the subagent is / how it behaves (caller-supplied)
|
|
40
|
+
* 2. project rules / AGENTS — the same getInstructions the parent loads
|
|
41
|
+
* 3. memory — the lightweight memdir INDEX (preferences / project facts)
|
|
42
|
+
*
|
|
43
|
+
* Returns undefined when there is genuinely nothing to inject.
|
|
44
|
+
*/
|
|
45
|
+
export declare function buildSubagentSystemPrompt(input: SubagentSystemPromptInput): Promise<string | undefined>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AgentLogger } from "../../agent/types.js";
|
|
2
|
+
import type { BackgroundTaskManager } from "../../runtime/infra/background-tasks.js";
|
|
2
3
|
import type { TeamToolDeps } from "../../skills/tools/team-tool.js";
|
|
3
4
|
import type { TeamRegistry } from "./team-registry.js";
|
|
4
5
|
export interface TeamToolService extends TeamToolDeps {
|
|
@@ -8,15 +9,25 @@ export interface TeamToolServiceHost {
|
|
|
8
9
|
readonly currentSessionId: string;
|
|
9
10
|
readonly verbose: boolean;
|
|
10
11
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
12
|
+
* The leader's resolved LLM config, pushed to each spawned member as standing
|
|
13
|
+
* session config (session/set_config_option). Without it a standalone member
|
|
14
|
+
* (no llmrouter directory to hydrate a catalog from) cannot provision a
|
|
15
|
+
* provider, and its first reply turn fails with NO_PROVIDER. Returns null
|
|
16
|
+
* when the leader has no resolved provider yet.
|
|
14
17
|
*/
|
|
15
18
|
getLlmConfig(): {
|
|
19
|
+
provider: string;
|
|
16
20
|
model: string;
|
|
17
21
|
apiKey: string;
|
|
18
22
|
baseUrl?: string;
|
|
19
23
|
} | null;
|
|
24
|
+
/** Lightweight memory INDEX injected into each member's system prompt (parent context). */
|
|
25
|
+
getMemoryIndex(): string | null;
|
|
26
|
+
/**
|
|
27
|
+
* Unified background-task registry. Team members register here as `team_member`
|
|
28
|
+
* tasks so the `task` tool's list/output/cancel reach them. Null when unbound.
|
|
29
|
+
*/
|
|
30
|
+
getBackgroundTasks(): BackgroundTaskManager | null;
|
|
20
31
|
sendNotification(method: string, params: Record<string, unknown>): void;
|
|
21
32
|
emitAgentStatus(agentId: string, state: string, extra?: {
|
|
22
33
|
missedBeats?: number;
|
|
@@ -38,6 +38,8 @@ export declare class StdioServer {
|
|
|
38
38
|
private currentModel;
|
|
39
39
|
private currentProvider;
|
|
40
40
|
private currentBaseUrl;
|
|
41
|
+
/** Host-pinned per-session LLM config (session/set_config_option · set_model · /model). */
|
|
42
|
+
private sessionLlmConfig;
|
|
41
43
|
private sessionState;
|
|
42
44
|
private currentMediaApiKeys;
|
|
43
45
|
private taskStore;
|
|
@@ -10,6 +10,6 @@ export { advanceToolLoopState, recoverToolLoopStateFromChatConversation, recover
|
|
|
10
10
|
export { isForegroundSource, isTransientCapacityError, computeRetryBackoff, isPersistentRetryEnabled, FallbackTriggeredError, type PersistentRetryConfig, } from "./error-handling/retry-loop.js";
|
|
11
11
|
export { canForkAtDepth, buildForkedMessages, buildForkPlaceholderResults, FORK_PLACEHOLDER_RESULT, FORK_SENTINEL_TAG, generateForkChildAgentId, isInForkChild, MAX_FORK_DEPTH, resolveForkChildTools, type ForkChildConfig, type ForkChildMessage, type ForkContext, type ForkResult, } from "./subagent/fork-subagent.js";
|
|
12
12
|
export { getBuiltInAgent, getBuiltInAgents, isBuiltInAgent, resolveAgentToolSet, type AgentDefinition, } from "./subagent/agent-registry.js";
|
|
13
|
-
export { createTaskState, filterToolsByRole, type IsolationMode, type PermissionRole, type TaskType, type TaskLifecycle, type TaskState, type TaskStateBase, type LocalBashTaskState, type LocalAgentTaskState, type RemoteAgentTaskState, type
|
|
13
|
+
export { createTaskState, filterToolsByRole, type IsolationMode, type PermissionRole, type TaskType, type TaskLifecycle, type TaskState, type TaskStateBase, type LocalBashTaskState, type LocalAgentTaskState, type RemoteAgentTaskState, type TeamMemberTaskState, type DreamTaskState, type DreamTurn, type DreamPhase, } from "./subagent/task-types.js";
|
|
14
14
|
export { calculateTokenWarningState, createTurnLoopGuardState, resolveApiErrorRecovery, resolveOutputTokenEscalation, shouldAbortTurn, type ApiErrorRecovery, type TokenWarningState, type TurnLoopGuardConfig, type TurnLoopGuardState, } from "./context/turn-loop-guard.js";
|
|
15
15
|
export { buildPostCompactRestorationMessage, createReactiveCompactState, shouldAttemptReactiveCompact, type ReactiveCompactConfig, type ReactiveCompactState, } from "./context/reactive-compact.js";
|
|
@@ -29,11 +29,20 @@ export interface AgentProcessConfig {
|
|
|
29
29
|
env?: Record<string, string>;
|
|
30
30
|
/** Agent type hint for the child (sets system prompt behavior). */
|
|
31
31
|
agentType?: string;
|
|
32
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Standing LLM config for an internal child. Pushed via session/set_config_option
|
|
34
|
+
* right after session/new so every turn (initial task, send_message replies)
|
|
35
|
+
* resolves provider/model/apiKey explicitly. A standalone child has no llmrouter
|
|
36
|
+
* directory to hydrate a model catalog from — without this push its first turn
|
|
37
|
+
* dies with NO_PROVIDER. provider+apiKey are what the child's turn resolution
|
|
38
|
+
* requires (resolveTextGenerationConfig); model rides along for determinism.
|
|
39
|
+
*/
|
|
40
|
+
provider?: string;
|
|
41
|
+
/** Model for the child's turns (see provider). */
|
|
33
42
|
model?: string;
|
|
34
|
-
/** API key (
|
|
43
|
+
/** API key for the child's turns (see provider). */
|
|
35
44
|
apiKey?: string;
|
|
36
|
-
/** Base URL for LLM API. */
|
|
45
|
+
/** Base URL for the child's LLM API (see provider). */
|
|
37
46
|
baseUrl?: string;
|
|
38
47
|
/** Enable verbose logging in child. */
|
|
39
48
|
verbose?: boolean;
|
|
@@ -159,9 +168,6 @@ export declare class AgentProcessManager {
|
|
|
159
168
|
* Returns the JSON-RPC result (content/usage carried on the response).
|
|
160
169
|
*/
|
|
161
170
|
sendTask(memberId: string, prompt: string, options?: {
|
|
162
|
-
model?: string;
|
|
163
|
-
apiKey?: string;
|
|
164
|
-
baseUrl?: string;
|
|
165
171
|
sessionId?: string;
|
|
166
172
|
timeout?: number;
|
|
167
173
|
}): Promise<unknown>;
|
|
@@ -181,9 +187,6 @@ export declare class AgentProcessManager {
|
|
|
181
187
|
* `pingTimeout`, the task is considered failed.
|
|
182
188
|
*/
|
|
183
189
|
sendTaskAsync(memberId: string, prompt: string, options?: {
|
|
184
|
-
model?: string;
|
|
185
|
-
apiKey?: string;
|
|
186
|
-
baseUrl?: string;
|
|
187
190
|
sessionId?: string;
|
|
188
191
|
/** Total timeout for the task (default: unlimited, 0 = no timeout) */
|
|
189
192
|
timeout?: number;
|
|
@@ -54,10 +54,23 @@ export interface TaskOutputSnapshot {
|
|
|
54
54
|
output: string;
|
|
55
55
|
running: boolean;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Control surface for a task whose EXECUTION lives outside this manager — e.g. a
|
|
59
|
+
* team-member subprocess owned by AgentProcessManager. The manager holds the task
|
|
60
|
+
* in the unified panel (list/output/cancel) and routes those three actions here;
|
|
61
|
+
* lifecycle settlement is driven by the owner via settleExternalTask().
|
|
62
|
+
*/
|
|
63
|
+
export interface ExternalTaskControl {
|
|
64
|
+
/** Kill / tear down the external executor (invoked by `task cancel`). */
|
|
65
|
+
cancel(): void;
|
|
66
|
+
/** Optional live status snapshot for `task output` while the task runs. */
|
|
67
|
+
readStatus?(): string;
|
|
68
|
+
}
|
|
57
69
|
export declare class BackgroundTaskManager {
|
|
58
70
|
private readonly store;
|
|
59
71
|
private readonly controllers;
|
|
60
72
|
private readonly bashHandles;
|
|
73
|
+
private readonly externalControls;
|
|
61
74
|
private readonly settledListeners;
|
|
62
75
|
constructor(store: TaskStore);
|
|
63
76
|
/** Subscribe to natural task settlement (completed/failed). Returns unregister fn. */
|
|
@@ -73,6 +86,19 @@ export declare class BackgroundTaskManager {
|
|
|
73
86
|
* promise settles the task; live output is readable from outputPath.
|
|
74
87
|
*/
|
|
75
88
|
registerBashTask(opts: RegisterBashTaskOptions): LocalBashTaskState;
|
|
89
|
+
/**
|
|
90
|
+
* Register a task whose executor lives OUTSIDE this manager (team-member
|
|
91
|
+
* subprocess). It joins the unified panel immediately; `task output` calls
|
|
92
|
+
* control.readStatus(), `task cancel` calls control.cancel(). The owner MUST
|
|
93
|
+
* drive settlement via settleExternalTask() when the executor exits.
|
|
94
|
+
*/
|
|
95
|
+
registerExternalTask(task: TaskState, control: ExternalTaskControl): void;
|
|
96
|
+
/**
|
|
97
|
+
* Settle an external task (owner observed exit / teardown). Idempotent: a task
|
|
98
|
+
* already terminal (e.g. cancelled by the user just before its process exited)
|
|
99
|
+
* is left untouched. Drops the control entry either way.
|
|
100
|
+
*/
|
|
101
|
+
settleExternalTask(taskId: string, lifecycle: "completed" | "failed" | "cancelled", output?: string): void;
|
|
76
102
|
private settle;
|
|
77
103
|
getTask(taskId: string): TaskState | undefined;
|
|
78
104
|
listTasks(): TaskState[];
|
|
@@ -9,25 +9,28 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Reference: claude-code src/tasks/types.ts
|
|
11
11
|
*/
|
|
12
|
-
import type { PermissionMode } from "../ports/permission-contracts.js";
|
|
13
12
|
/**
|
|
14
13
|
* Sub-agent task types.
|
|
15
14
|
*
|
|
16
15
|
* PRODUCED today (have a real registration site):
|
|
17
|
-
* - local_bash:
|
|
18
|
-
* - local_agent:
|
|
19
|
-
* -
|
|
16
|
+
* - local_bash: backgrounded shell command (BackgroundTaskManager.registerBashTask)
|
|
17
|
+
* - local_agent: backgrounded forked agent (BackgroundTaskManager.startAgentTask)
|
|
18
|
+
* - team_member: long-lived team subprocess (team-tool-service → registerExternalTask)
|
|
19
|
+
* - dream: memory consolidation (runDream → taskStore.registerTask)
|
|
20
20
|
*
|
|
21
21
|
* PLANNED — declared for the TASK_PREFIX taxonomy + UI/protocol contract, but NO
|
|
22
22
|
* producer exists yet. Do not assume these are created anywhere; wire a producer
|
|
23
23
|
* before relying on them:
|
|
24
|
-
* - remote_agent:
|
|
25
|
-
* -
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
24
|
+
* - remote_agent: cloud sandbox (polling-based)
|
|
25
|
+
* - local_workflow: DAG/pipeline execution
|
|
26
|
+
* - monitor_mcp: MCP server monitoring agent
|
|
27
|
+
*
|
|
28
|
+
* Naming note: we deliberately diverge from upstream CC's `in_process_teammate`.
|
|
29
|
+
* Our team members run as isolated SUBPROCESSES (AgentProcessManager) in their own
|
|
30
|
+
* git worktrees, not AsyncLocalStorage in-process agents — so the honest name is
|
|
31
|
+
* `team_member`. Keeps the `t` task-id prefix.
|
|
29
32
|
*/
|
|
30
|
-
export type TaskType = "local_bash" | "local_agent" | "remote_agent" | "
|
|
33
|
+
export type TaskType = "local_bash" | "local_agent" | "remote_agent" | "team_member" | "local_workflow" | "monitor_mcp" | "dream";
|
|
31
34
|
/**
|
|
32
35
|
* How a sub-agent is isolated from the parent execution.
|
|
33
36
|
*
|
|
@@ -107,16 +110,18 @@ export interface RemoteAgentTaskState extends TaskStateBase {
|
|
|
107
110
|
/** Polling endpoint for status checks. */
|
|
108
111
|
pollEndpoint?: string;
|
|
109
112
|
}
|
|
110
|
-
/**
|
|
111
|
-
export interface
|
|
112
|
-
type: "
|
|
113
|
+
/** Team member — long-lived collaborator subprocess in its own git worktree. */
|
|
114
|
+
export interface TeamMemberTaskState extends TaskStateBase {
|
|
115
|
+
type: "team_member";
|
|
116
|
+
/** Team this member belongs to. */
|
|
113
117
|
teamName: string;
|
|
118
|
+
/** Member's display name. */
|
|
114
119
|
agentName: string;
|
|
115
|
-
/**
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
|
|
119
|
-
/** Isolated git worktree path
|
|
120
|
+
/** Stable member id (`team-<team>-<name>`) — routes send_message / cancel. */
|
|
121
|
+
memberId: string;
|
|
122
|
+
/** Subprocess PID, once spawned. */
|
|
123
|
+
pid?: number;
|
|
124
|
+
/** Isolated git worktree path (when provisioned). */
|
|
120
125
|
worktreePath?: string;
|
|
121
126
|
/** Worktree branch name (for cleanup). */
|
|
122
127
|
worktreeBranch?: string;
|
|
@@ -148,7 +153,7 @@ export interface PlannedTaskState extends TaskStateBase {
|
|
|
148
153
|
type: "local_workflow" | "monitor_mcp";
|
|
149
154
|
}
|
|
150
155
|
/** Union of all concrete task states. */
|
|
151
|
-
export type TaskState = LocalBashTaskState | LocalAgentTaskState | RemoteAgentTaskState |
|
|
156
|
+
export type TaskState = LocalBashTaskState | LocalAgentTaskState | RemoteAgentTaskState | TeamMemberTaskState | DreamTaskState | PlannedTaskState;
|
|
152
157
|
/**
|
|
153
158
|
* Filter available tools by permission role.
|
|
154
159
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qlogicagent",
|
|
3
|
-
"version": "2.12.
|
|
3
|
+
"version": "2.12.8",
|
|
4
4
|
"description": "XiaozhiClaw Agent CLI — subprocess architecture (JSON-RPC over stdio)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"@agentclientprotocol/sdk": "^0.25.0",
|
|
90
90
|
"@napi-rs/canvas": "0.1.100",
|
|
91
91
|
"@xiaozhiclaw/pet-core": "0.1.1",
|
|
92
|
-
"@xiaozhiclaw/provider-core": "0.1.
|
|
92
|
+
"@xiaozhiclaw/provider-core": "0.1.8",
|
|
93
93
|
"better-sqlite3": "^12.10.0",
|
|
94
94
|
"dotenv": "^17.3.1",
|
|
95
95
|
"ioredis": "^5.11.1",
|