qlogicagent 2.16.5 → 2.16.6
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 +20 -20
- package/dist/cli.js +372 -366
- package/dist/index.js +371 -365
- package/dist/orchestration.js +10 -10
- package/dist/types/agent/tool-loop/loop-helpers.d.ts +1 -4
- package/dist/types/agent/tool-loop/pseudo-tool-output.d.ts +8 -0
- package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +0 -1
- package/dist/types/agent/tool-loop/tool-guardrails.d.ts +24 -0
- package/dist/types/agent/tool-loop/tool-result-classification.d.ts +10 -0
- package/dist/types/cli/acp-commands.d.ts +1 -2
- package/dist/types/cli/handlers/pinned-skill-context.d.ts +2 -0
- package/dist/types/cli/skill-invocation-service.d.ts +2 -0
- package/dist/types/runtime/execution/untrusted-tool-result.d.ts +2 -0
- package/dist/types/runtime/infra/skill-resolver.d.ts +8 -2
- package/dist/types/skills/mcp/mcp-manager.d.ts +20 -2
- package/dist/types/skills/skill-system/skill-bundles.d.ts +8 -0
- package/dist/types/skills/skill-system/skill-frontmatter.d.ts +1 -5
- package/dist/types/skills/skill-system/skill-lifecycle.d.ts +13 -1
- package/dist/types/skills/skill-system/skill-preprocessing.d.ts +11 -0
- package/dist/types/skills/skill-system/skill-types.d.ts +0 -75
- package/dist/types/skills/skill-system/skill-validation.d.ts +1 -0
- package/dist/types/skills/tools/skill-tool.d.ts +2 -1
- package/package.json +3 -2
- package/dist/types/skills/skill-system/skill-source.d.ts +0 -38
package/dist/orchestration.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
function
|
|
2
|
-
${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},
|
|
1
|
+
function Re(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function xe(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 Se=/\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]},ke=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ae=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Me=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ie=new Set([500,502,503,504,521,522,523,524,529]),ve=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],we=["upgrade your plan","upgrade plan","current plan","subscription"],Le=["daily","weekly","monthly"],Oe=["try again","retry","temporary","cooldown"],Pe=["usage limit","rate limit","organization usage"],Ne=["organization","workspace"],Fe=["billing period","exceeded","reached","exhausted"],De=/["']?(?: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,Be=/^(?: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 Ue(e){return h(e,y.format)}function X(e){return h(e,y.rateLimit)}function Ge(e){return h(e,y.timeout)}function je(e){return Se.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Me?Ae.test(t):h(t,y.billing)?!0:ke.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function K(e){return h(e,y.authPermanent)}function $e(e){return h(e,y.auth)}function W(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function He(e){return T(e,ve)||T(e,we)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=T(e,Le),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ne);return T(e,Oe)&&T(e,Pe)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,Fe))}function qe(e){return e.trim().toLowerCase().replace(Be,"").trim()}function V(e){let t=qe(e);return!t||He(t)?"billing":X(t)||ze(t)?"rate_limit":"billing"}function Ye(e){return De.test(e)?V(e):null}function J(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Xe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ke(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?Ie.has(n.code):!1}function Z(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?V(t):"billing":e===429?"rate_limit":e===401||e===403?t&&K(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function We(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ve(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 Q(e){if(Ve(e))return"session_expired";if(We(e))return"model_not_found";let t=Ye(e);return t||(je(e)?E(e)?"billing":"rate_limit":X(e)?"rate_limit":W(e)?"overloaded":Ke(e)?J(e.trim())?.code===529?"overloaded":"timeout":Xe(e)?"timeout":Ue(e)?"format":E(e)?"billing":Ge(e)?"timeout":K(e)?"auth_permanent":$e(e)?"auth":null)}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"},Ze=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Qe(e,t){let n=Z(e,t)??(t?Q(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function et(e){return Ze.has(e)}function B(e){return typeof e.compressAsync=="function"}var ee=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 s=n;for(let c of o)s-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=ee)break;if(s-p<0&&l<ee){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let u=[...o];return i&&!a.includes(i)&&u.push(i),u.push(...a),{messages:u,droppedCount:r.length-(a.length+(i&&!a.includes(i)?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 s=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),a=this.summarize(s);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
2
|
+
${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},w=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:tt(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function tt(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(`}
|
|
3
3
|
`),n.lastIndexOf(`]
|
|
4
4
|
`));if(s>t*.5)return n.slice(0,s+1)+`
|
|
5
5
|
[...truncated: ${e.length-s-1} chars omitted]`}let r=n.lastIndexOf(`
|
|
6
6
|
`);return r>t*.7?n.slice(0,r)+`
|
|
7
7
|
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
8
|
-
[...truncated: ${e.length-t} chars omitted]`}function
|
|
9
|
-
`)}var
|
|
8
|
+
[...truncated: ${e.length-t} chars omitted]`}function nt(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function ot(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,s=[],i=0,a=!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&&s.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,a=a||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:l}:void 0}}}}function U(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","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&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;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(`
|
|
9
|
+
`)}var L=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??x,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}=ne(t),i=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let m=0;m<s.length&&(s[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)a=m+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),c=Math.max(a,s.length-u);if(c<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=s.slice(0,a),p=s.slice(a,c),f=s.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
|
-
${
|
|
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:i,tokensAfter:b,compressionRatio:i>0?b/i:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},O=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??x}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=ne(t),i=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),a=i>=0?r[i]:void 0,l=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 c=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=s.slice(0,u),p=s.slice(u),f=a&&typeof a.content=="string"?`Previous summary:
|
|
12
12
|
${a.content}
|
|
13
13
|
|
|
14
|
-
New messages to integrate:`:void 0,C=
|
|
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]
|
|
15
15
|
|
|
16
|
-
${
|
|
16
|
+
${k}`},_=[...l,A,...p],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:b,compressionRatio:c>0?b/c:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),s=R(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=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=R(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}}}},te={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function rt(e={}){let t={...te,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function st(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=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 a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.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}},F=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 ne(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function x(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(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 it=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"]),D=class{constructor(t=20,n=x){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=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!it.has(a.name)||a.content.length<=200)return a;let u=this.estimateTokens(a);return s+=u,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function at(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),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&t.set(a,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 lt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=at(t);if(r.length===0)return e;let s=e.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
17
17
|
`),i=r.filter(p=>!s.includes(p));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=n.maxFiles||a<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>a||(a-=C,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
18
18
|
|
|
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 lt(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}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(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=oe(e,t),i=dt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=oe(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:re(e,t),committed:n}}function oe(e,t){return t.stages.filter(o=>o.committed).length===0?e:re(e,t)}function re(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 a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}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(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=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==="")i<0&&(i=l),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as mt,writeFileSync as ft,mkdirSync as gt}from"node:fs";import{join as yt,dirname as Tt}from"node:path";var wn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),On=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var se=3,ie=2,ae=300*1e3,le=3,ce=720*60*60*1e3,U=4;var Ln=3600*1e3;var Pn=50*1024,Nn=500*1024,Fn=500*1024*1024,Dn=50*1024*1024;var Bn=60*1024;var pe=0;var ht="skill-patterns.json";function de(e){return yt(e,".qlogicagent",ht)}function me(e){let t=de(e);try{return JSON.parse(mt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function ue(e,t){let n=de(e);gt(Tt(n),{recursive:!0}),ft(n,JSON.stringify(t,null,2),"utf8")}function Ct(e){let t=Date.now()-ce;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function fe(e,t){if(t.length===0)return!1;let n=ge(t),o=me(e);Ct(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return ue(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=le;return i&&(s.promoted=!0),ue(e,o),i}function _t(e){let t=me(e);return Object.values(t.patterns)}function ge(e){return[...e].sort().join("+")}function bt(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<se||e.distinctToolCount<ie||Date.now()-pe<ae||t?.projectRoot&&t.tools.length>0&&!fe(t.projectRoot,t.tools))}function Rt(e){return e.existingSkillName?e.feedback==="negative":!1}function xt(e,t){return Rt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:bt(e,t)?(pe=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 St(e){let t=new Set(e.map(G).filter(Boolean)),n=t.has("exec"),o=["read","search","write","edit","patch"].some(r=>t.has(r));return!n||!o?"You must call one of the available tools before responding.":'You must call one of the available tools before responding. Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function G(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 kt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function At(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Mt(e){if(!e.eligibility?.length)return[...e.tools];let t=At(e.eligibility);return e.tools.filter(n=>{let o=G(n);if(!o)return!1;let r=t.get(o);return!r||kt(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 It(e){let t=Et({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Mt({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:St(r),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 a=r.filter(l=>G(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var vt=["stop","aborted","timeout","cancelled","interrupted","error"],wt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ot(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function Lt(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 Pt(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=Lt(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Nt(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 Ft(e){return new Set((e??vt).map(t=>t.trim().toLowerCase()))}function Te(e,t){return e?Ft(t).has(e.trim().toLowerCase()):!1}function Dt(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 j(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 u=l.tool_calls.filter(c=>Nt(c));return{...l,...u.length>0?{tool_calls:u}:{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 u of l.tool_calls)typeof u.id=="string"&&u.id&&n.add(u.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 u=l.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(u.length===0){let{tool_calls:c,...d}=l;d.content!=null&&d.content!==""&&s.push(d);continue}if(u.length<l.tool_calls.length){s.push({...l,tool_calls:u});continue}}s.push(l)}let i=Pt(s),a=[];for(let l of i){let u=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&u?.role==="user"){a[a.length-1]=Ot(u,l);continue}a.push(l)}return a}function $(e,t){return Te(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of wt)delete o[r];return o}):[...e]}function H(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 Bt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function he(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 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=Dt(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let s=new Set,i=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&&(s.add(c),i.set(c,u))}let a=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||!s.has(c))continue;a.add(c)}l.push(u)}for(let[u]of i)a.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Ut(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 Gt(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 jt(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 $t(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ht(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 zt(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 qt(e){let t=[],n=j(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=$(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=H(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Ut(r),completedToolCallIds:Gt(r)}),recoveryActions:t}}function Yt(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:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:jt(t),completedToolCallIds:$t(t)}),recoveryActions:n}}var Xt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Kt(e){return e?Xt.has(e):!0}function Wt(e){return e===429||e===529}function Vt(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 Vn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Jt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",_e="Fork started \u2014 processing in background";function Zt(e){return JSON.stringify(e).includes(q)}function Qt(e){return e<U}function en(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
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 ct(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function ut(){return{stages:[]}}function pt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=oe(e,t),i=mt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=oe(e,t),{messages:s,stagedCount:i.length}}function dt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:re(e,t),committed:n}}function oe(e,t){return t.stages.filter(o=>o.committed).length===0?e:re(e,t)}function re(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 a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function mt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=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==="")i<0&&(i=l),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as ft,writeFileSync as gt,mkdirSync as Tt}from"node:fs";import{join as yt,dirname as ht}from"node:path";var On=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Pn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var se=3,ie=2,ae=300*1e3,le=3,ce=720*60*60*1e3,G=4;var Nn=3600*1e3;var Fn=50*1024,Dn=500*1024,Bn=500*1024*1024,Un=50*1024*1024;var Gn=60*1024;var pe=0;var Ct="skill-patterns.json";function de(e){return yt(e,".qlogicagent",Ct)}function me(e){let t=de(e);try{return JSON.parse(ft(t,"utf8"))}catch{return{version:1,patterns:{}}}}function ue(e,t){let n=de(e);Tt(ht(n),{recursive:!0}),gt(n,JSON.stringify(t,null,2),"utf8")}function _t(e){let t=Date.now()-ce;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function fe(e,t){if(t.length===0)return!1;let n=ge(t),o=me(e);_t(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return ue(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=le;return i&&(s.promoted=!0),ue(e,o),i}function bt(e){let t=me(e);return Object.values(t.patterns)}function ge(e){return[...e].sort().join("+")}function Rt(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<se||e.distinctToolCount<ie||Date.now()-pe<ae||t?.projectRoot&&t.tools.length>0&&!fe(t.projectRoot,t.tools))}function xt(e){return e.existingSkillName?e.feedback==="negative":!1}function St(e,t){return xt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Rt(e,t)?(pe=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 kt(e){return[...new Set(e.map(S).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Te(e){let t=kt(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not mention, invent, or attempt any tool that is not in this list.`}function At(e){let t=[...new Set(e.map(S).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Te(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function S(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 Et(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function It(e){if(!e.eligibility?.length)return[...e.tools];let t=Et(e.eligibility);return e.tools.filter(n=>{let o=S(n);if(!o)return!1;let r=t.get(o);return!r||Mt(r.status)})}function vt(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=vt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=It({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Te(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:At(r),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 a=r.filter(l=>S(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lt=["stop","aborted","timeout","cancelled","interrupted","error"],Ot=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Pt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function Nt(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 Ft(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=Nt(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Dt(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??Lt).map(t=>t.trim().toLowerCase()))}function he(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 j(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 u=l.tool_calls.filter(c=>Dt(c));return{...l,...u.length>0?{tool_calls:u}:{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 u of l.tool_calls)typeof u.id=="string"&&u.id&&n.add(u.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 u=l.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(u.length===0){let{tool_calls:c,...d}=l;d.content!=null&&d.content!==""&&s.push(d);continue}if(u.length<l.tool_calls.length){s.push({...l,tool_calls:u});continue}}s.push(l)}let i=Ft(s),a=[];for(let l of i){let u=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&u?.role==="user"){a[a.length-1]=Pt(u,l);continue}a.push(l)}return a}function $(e,t){return he(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 H(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 Gt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function Ce(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=he(t?.stopReason,t?.forcedStopReasons),r=[];for(let 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 s=new Set,i=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&&(s.add(c),i.set(c,u))}let a=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||!s.has(c))continue;a.add(c)}l.push(u)}for(let[u]of i)a.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function jt(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 $t(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 Ht(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 _e(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 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 Xt(e){let t=[],n=j(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=$(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=H(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:_e({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:jt(r),completedToolCallIds:$t(r)}),recoveryActions:t}}function Kt(e){let t=Ce(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:_e({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ht(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 Zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",be="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(q)}function tn(e){return e<G}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
20
20
|
|
|
21
21
|
Your working directory is: ${e.worktreePath}
|
|
22
22
|
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
|
|
23
23
|
|
|
24
24
|
You are the "${t.agent.name}" agent.${o}
|
|
25
25
|
|
|
26
|
-
${t.taskPrompt}`}]};return n.push(r),n}function
|
|
26
|
+
${t.taskPrompt}`}]};return n.push(r),n}function on(e){return e.map(t=>({role:"tool",tool_call_id:t,content:be}))}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")}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","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."},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","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."},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","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"],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")}function yn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function hn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Cn(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 _n(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 bn(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 Rn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var xn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Sn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
|
|
27
27
|
${n.join(`
|
|
28
28
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
29
29
|
Step ${e.activeSkillContext.step}:
|
|
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
34
34
|
|
|
35
35
|
${t.join(`
|
|
36
36
|
|
|
37
|
-
`)}`}function
|
|
37
|
+
`)}`}function kn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function An(e,t=xn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,F as ContextEngineRegistry,te as DEFAULT_ADAPTIVE_BUDGET_CONFIG,be as FORK_PLACEHOLDER_RESULT,q as FORK_SENTINEL_TAG,z as FallbackTriggeredError,L as HeadTailProtectedStrategy,O as IncrementalCompactStrategy,G as MAX_FORK_DEPTH,D as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,w as ToolResultTrimStrategy,qt as advanceToolLoopState,pt as applyContextCollapsesIfNeeded,wt as applyToolChoicePolicy,Re as buildAssistantToolCallMessage,on as buildForkPlaceholderResults,nn as buildForkedMessages,Sn as buildPostCompactRestorationMessage,St as buildSkillInstruction,U as buildStructuredSummaryPrompt,xe as buildToolResultMessage,ge as buildToolSignature,Cn as calculateTokenWarningState,tn as canForkAtDepth,Qe as classifyError,ot as composeAsyncStrategies,nt as composeStrategies,rt as computeAdaptiveBudget,Zt as computeRetryBackoff,ut as createCollapseStore,kn as createReactiveCompactState,yn as createTaskState,hn as createTurnLoopGuardState,sn as generateForkChildAgentId,fn as getBuiltInAgent,mn as getBuiltInAgents,bt as getPatternStats,B as isAsyncCompressionStrategy,gn as isBuiltInAgent,Vt as isForegroundSource,en as isInForkChild,Qt as isPersistentRetryEnabled,et as isRetryableCategory,Jt as isTransientCapacityError,lt as postCompactFileRecovery,fe as recordPatternAndCheckThreshold,dt as recoverContextCollapseFromOverflow,Xt as recoverToolLoopStateFromChatConversation,Kt as recoverToolLoopStateFromResponsesItems,Gt as repairOpenAiChatConversation,Tn as resolveAgentToolSet,_n as resolveApiErrorRecovery,rn as resolveForkChildTools,bn as resolveOutputTokenEscalation,st as selectCompressionTier,Yt as settleToolLoopState,Rn as shouldAbortTurn,An as shouldAttemptReactiveCompact,ct as snipCompactIfNeeded};
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import type { ChatMessage } from "../types.js";
|
|
2
|
-
export
|
|
3
|
-
toolName: string;
|
|
4
|
-
message: unknown;
|
|
5
|
-
}): boolean;
|
|
2
|
+
export { isEmptyToolResult } from "./tool-result-classification.js";
|
|
6
3
|
export declare function findLastToolError(messages: unknown[], _toolName: string): string | undefined;
|
|
7
4
|
export declare function looksLikeBuildRequest(messages?: readonly ChatMessage[]): boolean;
|
|
8
5
|
export declare function isBareIntentPreamble(text: string): boolean;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface PseudoToolOutputInput {
|
|
2
|
+
text: string;
|
|
3
|
+
enabledToolNames: readonly string[];
|
|
4
|
+
}
|
|
5
|
+
export interface PseudoToolOutputDetection {
|
|
6
|
+
toolName: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function detectPseudoToolOutput(input: PseudoToolOutputInput): PseudoToolOutputDetection | null;
|
|
@@ -17,7 +17,6 @@ export declare function recordToolFailureResult(input: {
|
|
|
17
17
|
ok: boolean;
|
|
18
18
|
softEmpty: boolean;
|
|
19
19
|
}): void;
|
|
20
|
-
export declare function recordInvalidArgumentsVariantFailure(toolFailureCounts: Map<string, number>, toolName: string): void;
|
|
21
20
|
export declare function newVariantFailureNudges(input: {
|
|
22
21
|
toolFailureCounts: ReadonlyMap<string, number>;
|
|
23
22
|
snapshot: ReadonlyMap<string, number>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type ToolGuardrailLevel = "allow" | "warn" | "block" | "halt";
|
|
2
|
+
export type ToolGuardrailReason = "exact_failure_repeat" | "same_tool_failure_repeat" | "idempotent_no_progress";
|
|
3
|
+
export interface ToolGuardrailDecision {
|
|
4
|
+
level: ToolGuardrailLevel;
|
|
5
|
+
reason?: ToolGuardrailReason;
|
|
6
|
+
message?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface ToolGuardrailConfig {
|
|
9
|
+
warnAfter?: number;
|
|
10
|
+
blockAfter?: number;
|
|
11
|
+
haltAfter?: number;
|
|
12
|
+
}
|
|
13
|
+
export declare class ToolCallGuardrailController {
|
|
14
|
+
private exact;
|
|
15
|
+
private sameToolFailures;
|
|
16
|
+
private readonly config;
|
|
17
|
+
constructor(config?: ToolGuardrailConfig);
|
|
18
|
+
record(input: {
|
|
19
|
+
toolName: string;
|
|
20
|
+
argumentsJson: string;
|
|
21
|
+
ok: boolean;
|
|
22
|
+
message: unknown;
|
|
23
|
+
}): ToolGuardrailDecision;
|
|
24
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type ToolResultClassification = "success" | "empty" | "error";
|
|
2
|
+
export declare function classifyToolResult(r: {
|
|
3
|
+
ok?: boolean;
|
|
4
|
+
toolName: string;
|
|
5
|
+
message: unknown;
|
|
6
|
+
}): ToolResultClassification;
|
|
7
|
+
export declare function isEmptyToolResult(r: {
|
|
8
|
+
toolName: string;
|
|
9
|
+
message: unknown;
|
|
10
|
+
}): boolean;
|
|
@@ -10,8 +10,7 @@
|
|
|
10
10
|
* Command-set decision (per plan): 9 direct commands + `/init` (degraded to a prompt, no automatic
|
|
11
11
|
* function). `/compact` is intentionally NOT registered — context compaction is triggered
|
|
12
12
|
* automatically by reactive-compact, so exposing it as an explicit command would be misleading.
|
|
13
|
-
*
|
|
14
|
-
* `SkillCommandSpec`, so the enumeration is empty (a foreseen degradation, not a stub).
|
|
13
|
+
* This codebase produces no user-invocable skill commands, so that enumeration is empty.
|
|
15
14
|
*/
|
|
16
15
|
import type { AcpSessionHost } from "./acp-session-host.js";
|
|
17
16
|
export interface AcpCommandReply {
|
|
@@ -26,8 +26,14 @@ export interface ResolvedSkill {
|
|
|
26
26
|
systemGenerated: boolean;
|
|
27
27
|
description?: string;
|
|
28
28
|
version?: string;
|
|
29
|
+
requiredTools?: string[];
|
|
30
|
+
environments?: string[];
|
|
29
31
|
}
|
|
30
32
|
export declare function isSystemGeneratedSkillName(name: string): boolean;
|
|
33
|
+
export interface SkillActivationContext {
|
|
34
|
+
availableToolNames?: Iterable<string>;
|
|
35
|
+
currentEnvironment?: string;
|
|
36
|
+
}
|
|
31
37
|
/**
|
|
32
38
|
* Resolve all skills in the global store, annotated with global/project mute state and whether
|
|
33
39
|
* they're active in the given project context.
|
|
@@ -35,9 +41,9 @@ export declare function isSystemGeneratedSkillName(name: string): boolean;
|
|
|
35
41
|
* Returns ALL store skills (active and inactive) so listing surfaces can show enable/disable state;
|
|
36
42
|
* callers that only want active skills filter `.active` (or use resolveActiveSkills).
|
|
37
43
|
*/
|
|
38
|
-
export declare function resolveSkills(projectRoot?: string): ResolvedSkill[];
|
|
44
|
+
export declare function resolveSkills(projectRoot?: string, activation?: SkillActivationContext): ResolvedSkill[];
|
|
39
45
|
/** Only the skills active in the given project (for the system-prompt skills catalog / resolution). */
|
|
40
|
-
export declare function resolveActiveSkills(projectRoot?: string): ResolvedSkill[];
|
|
46
|
+
export declare function resolveActiveSkills(projectRoot?: string, activation?: SkillActivationContext): ResolvedSkill[];
|
|
41
47
|
/**
|
|
42
48
|
* Resolve a single skill by name to its store paths, or null if not present.
|
|
43
49
|
* Resolution honors only the global store (single source of truth) and ignores
|
|
@@ -21,10 +21,19 @@ export interface McpServerEntry {
|
|
|
21
21
|
url?: string;
|
|
22
22
|
/** Extra HTTP headers (http only) */
|
|
23
23
|
headers?: Record<string, string>;
|
|
24
|
-
/** Init timeout (ms) — accepted for config compatibility; mcporter owns connect timeouts. */
|
|
25
|
-
initTimeoutMs?: number;
|
|
26
24
|
/** Whether this server is disabled (skip connection) */
|
|
27
25
|
disabled?: boolean;
|
|
26
|
+
/** Allow the MCP runtime to start an OAuth flow for this server; default is cached-token/headless only. */
|
|
27
|
+
oauth?: boolean;
|
|
28
|
+
/** Optional tool-name allow/deny filters applied after connect-time discovery. */
|
|
29
|
+
tools?: {
|
|
30
|
+
include?: string[];
|
|
31
|
+
exclude?: string[];
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export interface McpSecurityIssue {
|
|
35
|
+
code: "dangerous_egress" | "persistence" | "ioc_public_key";
|
|
36
|
+
message: string;
|
|
28
37
|
}
|
|
29
38
|
export interface McpManagerConfig {
|
|
30
39
|
servers: McpServerEntry[];
|
|
@@ -45,6 +54,8 @@ export declare class McpManager {
|
|
|
45
54
|
private log;
|
|
46
55
|
private workspaceRoot?;
|
|
47
56
|
private toolCatalog?;
|
|
57
|
+
private serverToolFilters;
|
|
58
|
+
private serverOAuth;
|
|
48
59
|
constructor(config: McpManagerConfig);
|
|
49
60
|
private toServerDefinition;
|
|
50
61
|
/**
|
|
@@ -56,6 +67,7 @@ export declare class McpManager {
|
|
|
56
67
|
* Register all snapshotted MCP tools into the tool pool.
|
|
57
68
|
*/
|
|
58
69
|
injectTools(): void;
|
|
70
|
+
refreshServerTools(serverName: string): Promise<number>;
|
|
59
71
|
/** Get names of all connected servers. */
|
|
60
72
|
getConnectedServers(): string[];
|
|
61
73
|
/** Get total number of MCP tools across all servers. */
|
|
@@ -67,9 +79,15 @@ export declare class McpManager {
|
|
|
67
79
|
disconnectAll(): Promise<void>;
|
|
68
80
|
private toPortableTool;
|
|
69
81
|
private wrapToolsForWorkspaceBoundary;
|
|
82
|
+
private injectPortableTools;
|
|
83
|
+
private retractServerTools;
|
|
70
84
|
private registerTools;
|
|
71
85
|
private removeRegisteredTool;
|
|
72
86
|
}
|
|
73
87
|
export declare function validateMcpToolWorkspaceBoundary(toolName: string, args: unknown, workspaceRoot: string | undefined): string | null;
|
|
74
88
|
export declare function parseMcpConfig(json: unknown): McpServerEntry[];
|
|
89
|
+
export declare function filterMcpTools<T extends {
|
|
90
|
+
name: string;
|
|
91
|
+
}>(tools: readonly T[], filter?: McpServerEntry["tools"]): T[];
|
|
92
|
+
export declare function validateMcpServerSecurity(entry: McpServerEntry): McpSecurityIssue[];
|
|
75
93
|
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface SkillBundle {
|
|
2
|
+
name: string;
|
|
3
|
+
skills: string[];
|
|
4
|
+
filePath: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function getSkillBundlesDir(): string;
|
|
7
|
+
export declare function listSkillBundles(bundleDir?: string): SkillBundle[];
|
|
8
|
+
export declare function resolveSkillBundle(name: string, bundleDir?: string): SkillBundle | undefined;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ParsedSkillFrontmatter,
|
|
1
|
+
import type { ParsedSkillFrontmatter, SkillMetadata } from "./skill-types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Parse a YAML-like frontmatter block into a flat key→value record.
|
|
4
4
|
* Uses a lightweight line parser to avoid a YAML library dependency.
|
|
@@ -9,10 +9,6 @@ export declare function parseFrontmatter(content: string): ParsedSkillFrontmatte
|
|
|
9
9
|
* Expects `metadata: {"openclaw": {...}}` (JSON format).
|
|
10
10
|
*/
|
|
11
11
|
export declare function resolveSkillMetadata(frontmatter: ParsedSkillFrontmatter): SkillMetadata | undefined;
|
|
12
|
-
/**
|
|
13
|
-
* Resolve invocation policy from frontmatter fields.
|
|
14
|
-
*/
|
|
15
|
-
export declare function resolveSkillInvocationPolicy(frontmatter: ParsedSkillFrontmatter): SkillInvocationPolicy;
|
|
16
12
|
/**
|
|
17
13
|
* Get the canonical key for a skill (metadata.skillKey or skill.name).
|
|
18
14
|
*/
|
|
@@ -10,6 +10,8 @@ export interface SkillLifecycleRecord {
|
|
|
10
10
|
archivedAt?: string;
|
|
11
11
|
pinned: boolean;
|
|
12
12
|
useCount: number;
|
|
13
|
+
positiveCount?: number;
|
|
14
|
+
negativeCount?: number;
|
|
13
15
|
source: "learned" | "created" | "installed" | "promoted";
|
|
14
16
|
resourceType?: string;
|
|
15
17
|
launcherRequired?: boolean;
|
|
@@ -28,6 +30,14 @@ export interface SkillLifecycleStore {
|
|
|
28
30
|
version: 1;
|
|
29
31
|
records: Record<string, SkillLifecycleRecord>;
|
|
30
32
|
}
|
|
33
|
+
export interface SkillUsageStats {
|
|
34
|
+
invokeCount: number;
|
|
35
|
+
activeCount: number;
|
|
36
|
+
positiveCount: number;
|
|
37
|
+
negativeCount: number;
|
|
38
|
+
lastUsedAt?: string;
|
|
39
|
+
successRate?: number;
|
|
40
|
+
}
|
|
31
41
|
export interface CuratorResult {
|
|
32
42
|
transitioned: Array<{
|
|
33
43
|
name: string;
|
|
@@ -45,7 +55,7 @@ export declare function ensureRecord(store: SkillLifecycleStore, name: string, s
|
|
|
45
55
|
/**
|
|
46
56
|
* Record a skill invocation — resets to active if stale.
|
|
47
57
|
*/
|
|
48
|
-
export declare function recordInvocation(store: SkillLifecycleStore, name: string): void;
|
|
58
|
+
export declare function recordInvocation(store: SkillLifecycleStore, name: string, success?: boolean): void;
|
|
49
59
|
/**
|
|
50
60
|
* Record that a skill was viewed/listed.
|
|
51
61
|
*/
|
|
@@ -87,6 +97,8 @@ export declare function getSkillsByState(store: SkillLifecycleStore, state: Skil
|
|
|
87
97
|
* Get lifecycle record for a skill. Returns undefined if not tracked.
|
|
88
98
|
*/
|
|
89
99
|
export declare function getLifecycleRecord(store: SkillLifecycleStore, name: string): SkillLifecycleRecord | undefined;
|
|
100
|
+
export declare function getLifecycleSkillStats(store: SkillLifecycleStore, name: string): SkillUsageStats | undefined;
|
|
101
|
+
export declare function getAllLifecycleSkillStats(store: SkillLifecycleStore): Record<string, SkillUsageStats>;
|
|
90
102
|
/**
|
|
91
103
|
* Remove a lifecycle record (e.g., when skill is deleted).
|
|
92
104
|
*/
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface SkillTemplateVars {
|
|
2
|
+
skillDir?: string;
|
|
3
|
+
sessionId?: string;
|
|
4
|
+
}
|
|
5
|
+
export interface SkillPreprocessOptions extends SkillTemplateVars {
|
|
6
|
+
inlineShell?: boolean;
|
|
7
|
+
runInlineShellCommand?: (command: string) => Promise<string>;
|
|
8
|
+
maxInlineShellOutput?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function preprocessSkillContent(content: string, options?: SkillPreprocessOptions): Promise<string>;
|
|
11
|
+
export declare function substituteSkillTemplateVars(content: string, vars?: SkillTemplateVars): string;
|
|
@@ -63,78 +63,3 @@ export interface SkillMetadata {
|
|
|
63
63
|
};
|
|
64
64
|
install?: SkillInstallSpec[];
|
|
65
65
|
}
|
|
66
|
-
/**
|
|
67
|
-
* Controls how a skill may be activated by user commands or model tool calls.
|
|
68
|
-
*/
|
|
69
|
-
export interface SkillInvocationPolicy {
|
|
70
|
-
/** Whether users can directly invoke this skill via slash-command. */
|
|
71
|
-
userInvocable: boolean;
|
|
72
|
-
/** If true, the model cannot trigger this skill autonomously. */
|
|
73
|
-
disableModelInvocation: boolean;
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Slash-command dispatch specification for a skill.
|
|
77
|
-
*/
|
|
78
|
-
export interface SkillCommandDispatchSpec {
|
|
79
|
-
kind: "tool";
|
|
80
|
-
toolName: string;
|
|
81
|
-
argMode?: "raw";
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* A skill-derived slash-command for IM platforms.
|
|
85
|
-
*/
|
|
86
|
-
export interface SkillCommandSpec {
|
|
87
|
-
name: string;
|
|
88
|
-
skillName: string;
|
|
89
|
-
description: string;
|
|
90
|
-
dispatch?: SkillCommandDispatchSpec;
|
|
91
|
-
}
|
|
92
|
-
export type SkillScanSeverity = "info" | "warn" | "critical";
|
|
93
|
-
export interface SkillScanFinding {
|
|
94
|
-
ruleId: string;
|
|
95
|
-
severity: SkillScanSeverity;
|
|
96
|
-
file: string;
|
|
97
|
-
line: number;
|
|
98
|
-
message: string;
|
|
99
|
-
evidence: string;
|
|
100
|
-
}
|
|
101
|
-
export interface SkillScanSummary {
|
|
102
|
-
scannedFiles: number;
|
|
103
|
-
critical: number;
|
|
104
|
-
warn: number;
|
|
105
|
-
info: number;
|
|
106
|
-
findings: SkillScanFinding[];
|
|
107
|
-
}
|
|
108
|
-
export interface SkillScanOptions {
|
|
109
|
-
includeFiles?: string[];
|
|
110
|
-
maxFiles?: number;
|
|
111
|
-
maxFileBytes?: number;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Filesystem dependencies injected by the host runtime.
|
|
115
|
-
* Keeps the skill system decoupled from Node.js `fs` / `path`.
|
|
116
|
-
*/
|
|
117
|
-
export interface SkillFsDeps {
|
|
118
|
-
readFileSync(path: string, encoding: "utf-8"): string;
|
|
119
|
-
readFile(path: string, encoding: "utf-8"): Promise<string>;
|
|
120
|
-
existsSync(path: string): boolean;
|
|
121
|
-
statSync(path: string): {
|
|
122
|
-
size: number;
|
|
123
|
-
mtimeMs: number;
|
|
124
|
-
isDirectory(): boolean;
|
|
125
|
-
};
|
|
126
|
-
readdirSync(path: string, opts: {
|
|
127
|
-
withFileTypes: true;
|
|
128
|
-
}): Array<{
|
|
129
|
-
name: string;
|
|
130
|
-
isDirectory(): boolean;
|
|
131
|
-
isSymbolicLink(): boolean;
|
|
132
|
-
}>;
|
|
133
|
-
realpathSync(path: string): string;
|
|
134
|
-
}
|
|
135
|
-
export interface SkillPathDeps {
|
|
136
|
-
join(...segments: string[]): string;
|
|
137
|
-
resolve(...segments: string[]): string;
|
|
138
|
-
extname(p: string): string;
|
|
139
|
-
sep: string;
|
|
140
|
-
}
|
|
@@ -5,6 +5,7 @@ export interface FrontmatterValidationResult {
|
|
|
5
5
|
/** Parsed frontmatter if valid. */
|
|
6
6
|
parsed?: Record<string, string>;
|
|
7
7
|
}
|
|
8
|
+
export declare const MAX_DESCRIPTION_LENGTH = 60;
|
|
8
9
|
/**
|
|
9
10
|
* Validate SKILL.md content for required frontmatter structure.
|
|
10
11
|
* Used before persisting agent-created skills.
|