qlogicagent 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +10 -9
- package/dist/cli.js +204 -203
- package/dist/index.js +202 -201
- package/dist/orchestration.js +13 -12
- package/dist/types/agent/constants.d.ts +4 -53
- package/dist/types/agent/tunable-defaults.d.ts +221 -0
- package/dist/types/cli/stdio-server.d.ts +33 -0
- package/dist/types/orchestration/skill-improvement.d.ts +39 -8
- package/dist/types/orchestration/subagent/fork-subagent.d.ts +2 -2
- package/dist/types/protocol/notifications.d.ts +19 -0
- package/dist/types/runtime/hooks/memory-hooks.d.ts +0 -3
- package/dist/types/runtime/hooks/skill-recall-hooks.d.ts +2 -4
- package/dist/types/runtime/infra/project-store.d.ts +6 -0
- package/dist/types/runtime/infra/skill-injector.d.ts +9 -2
- package/dist/types/skills/skill-system/skill-source.d.ts +65 -0
- package/dist/types/transport/acp-server.d.ts +2 -0
- package/package.json +1 -1
package/dist/orchestration.js
CHANGED
|
@@ -1,29 +1,30 @@
|
|
|
1
|
-
function
|
|
2
|
-
${s}`},...i],droppedCount:a.length,strategy:"summarize-old"}}},
|
|
1
|
+
function Ce(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function _e(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var be=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={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]},Re=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,xe=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Se=512,ke=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ae=new Set([500,502,503,504,521,522,523,524,529]),Me=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ee=["upgrade your plan","upgrade plan","current plan","subscription"],Ie=["daily","weekly","monthly"],ve=["try again","retry","temporary","cooldown"],Le=["usage limit","rate limit","organization usage"],we=["organization","workspace"],Oe=["billing period","exceeded","reached","exhausted"],Pe=/["']?(?: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,Ne=/^(?: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 Fe(e){return h(e,T.format)}function Y(e){return h(e,T.rateLimit)}function De(e){return h(e,T.timeout)}function Be(e){return be.test(e)}function M(e){let t=e.toLowerCase();return t?e.length>Se?xe.test(t):h(t,T.billing)?!0:Re.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function K(e){return h(e,T.authPermanent)}function Ue(e){return h(e,T.auth)}function W(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function je(e){return y(e,Me)||y(e,Ee)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ge(e){let t=y(e,Ie),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,we);return y(e,ve)&&y(e,Le)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Oe))}function $e(e){return e.trim().toLowerCase().replace(Ne,"").trim()}function V(e){let t=$e(e);return!t||je(t)?"billing":Y(t)||Ge(t)?"rate_limit":"billing"}function He(e){return Pe.test(e)?V(e):null}function J(e){let t=e.match(ke);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function ze(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function qe(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?Ae.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&&M(t)?"billing":"format":null}function Xe(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 Ye(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(Ye(e))return"session_expired";if(Xe(e))return"model_not_found";let t=He(e);return t||(Be(e)?M(e)?"billing":"rate_limit":Y(e)?"rate_limit":W(e)?"overloaded":qe(e)?J(e.trim())?.code===529?"overloaded":"timeout":ze(e)?"timeout":Fe(e)?"format":M(e)?"billing":De(e)?"timeout":K(e)?"auth_permanent":Ue(e)?"auth":null)}var Ke={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"},We=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Ve(e,t){let n=Z(e,t)??(t?Q(t):null);return n?Ke[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Je(e){return We.has(e)}function D(e){return typeof e.compressAsync=="function"}var ee=4,E=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 a=n;for(let c of o)a-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(a-=this.estimateTokens(i)),a<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let s=[],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(a-p<0&&l>=ee)break;if(a-p<0&&l<ee){s.unshift(d),l++;continue}a-=p,s.unshift(d),l++}let u=[...o];return i&&!s.includes(i)&&u.push(i),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(i&&!s.includes(i)?1:0)),strategy:"sliding-window"}}},I=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 a=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),s=this.summarize(a);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
2
|
+
${s}`},...i],droppedCount:a.length,strategy:"summarize-old"}}},v=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(a=>a.role!=="tool"||typeof a.content!="string"||a.content.length<=this.maxToolResultChars?a:(o++,{...a,content:Ze(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ze(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let a=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
3
3
|
`),n.lastIndexOf(`]
|
|
4
4
|
`));if(a>t*.5)return n.slice(0,a+1)+`
|
|
5
5
|
[...truncated: ${e.length-a-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 Qe(...e){return{compress(t,n){let o=t,r=0,a=[];for(let i of e){let s=i.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none"}}}}function et(...e){return{compress(t,n){let o=t,r=0,a=[];for(let i of e){let s=i.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,a=[],i=0,s=!1,l=!1;for(let u of e){let c=D(u)?await u.compressAsync(o,n):u.compress(o,n);o=c.messages,r+=c.droppedCount,c.droppedCount>0&&a.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,s=s||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none",metrics:i>0||s?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:s,cacheInvalidated:l}:void 0}}}}function B(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"),a=["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. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 7. User Preferences Expressed",`The user sent ${n.length} messages. Note any stated preferences about style, approach, or constraints.`,"","### 8. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 9. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&a.push("","## Additional Context",t.taskContext),a.push("","## Conversation to Summarize","",...e.map(i=>{let s=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?s:s.length>2e3?s.slice(0,2e3)+"...":s;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),a.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:a}=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 s=0,l=0;for(let m=0;m<a.length&&(a[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)s=m+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(a.length*.4)),c=Math.max(s,a.length-u);if(c<=s)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=a.slice(0,s),p=a.slice(s,c),f=a.slice(c),C=B(p,{taskContext:this.config.taskContext}),S=await this.config.summarize(p,C),k={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
10
10
|
|
|
11
|
-
${
|
|
11
|
+
${S}`},_=[...r,...d,k,...f],A=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:A,usedLlm:!0,cacheInvalidated:!0}}}},w=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:a}=ne(t),i=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),s=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,u=Math.max(0,a.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=a.slice(0,u),p=a.slice(u),f=s&&typeof s.content=="string"?`Previous summary:
|
|
12
12
|
${s.content}
|
|
13
13
|
|
|
14
|
-
New messages to integrate:`:void 0,
|
|
14
|
+
New messages to integrate:`:void 0,C=B(d,{taskContext:f}),S=await this.config.summarize(d,C),k={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),i=r.filter(p=>!a.includes(p));if(i.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=n.maxFiles||s<=0)break;let f=await n.readFile(p);if(!f)continue;let
|
|
16
|
+
${S}`},_=[...l,k,...p],A=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:A,usedLlm:!0,cacheInvalidated:!0}}}},O=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),a=R(r.messages),i=o!==a&&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=D(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),a=R(r.messages),i=o!==a&&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 tt(e={}){let t={...te,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function nt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var P=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,a=0,i=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&a++,s.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:a,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},N=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],a=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${a}`)}return n.join("|")}var ot=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"]),F=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,a=0;return{messages:t.map((s,l)=>{if(l>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!ot.has(s.name)||s.content.length<=200)return s;let u=this.estimateTokens(s);return a+=u,r++,{...s,content:`[result cleared \u2014 ${s.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 rt(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 a=r.function?.name??"";if(/read|edit|write|file/i.test(a)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),s=i.path??i.filePath??i.file_path??i.file;s&&typeof s=="string"&&t.set(s,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 st(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=rt(t);if(r.length===0)return e;let a=e.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
17
|
+
`),i=r.filter(p=>!a.includes(p));if(i.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of i){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
|
-
${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 Ve(e,t,n=R){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function Xe(){return{stages:[]}}function Qe(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=te(e,t),i=et(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=te(e,t),{messages:a,stagedCount:i.length}}function Ze(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:ne(e,t),committed:n}}function te(e,t){return t.stages.filter(o=>o.committed).length===0?e:ne(e,t)}function ne(e,t){let n=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function et(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-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==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function tt(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function nt(e){return e.existingSkillName?e.feedback==="negative":!1}function ot(e,t){return nt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:tt(e)?{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 oe(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 rt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function st(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function it(e){if(!e.eligibility?.length)return[...e.tools];let t=st(e.eligibility);return e.tools.filter(n=>{let o=oe(n);if(!o)return!1;let r=t.get(o);return!r||rt(r.status)})}function at(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 lt(e){let t=at({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,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 a=n.function??void 0,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>oe(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,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 ct=["stop","aborted","timeout","cancelled","interrupted","error"],ut=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function re(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:[...re(e.content),...re(t.content)]}}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 mt(e){return new Set((e??ct).map(t=>t.trim().toLowerCase()))}function se(e,t){return e?mt(t).has(e.trim().toLowerCase()):!1}function ft(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(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>dt(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 a=[];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!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=pt(l,s);continue}i.push(s)}return i}function $(e,t){return se(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ut)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 a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let i of a.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 q(o,t)}function ie(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=se(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=ft(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=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&&(a.add(c),i.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||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function yt(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 Ct(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 Tt(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 ae(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function bt(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 kt(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 _t(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((a,i)=>a!==n[i])&&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:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:yt(r),completedToolCallIds:ht(r)}),recoveryActions:t}}function Rt(e){let t=ie(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:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ct(t),completedToolCallIds:Tt(t)}),recoveryActions:n}}var xt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function At(e){return e?xt.has(e):!0}function St(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 Tn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Mt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var G=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var U="<fork-child-context>",le="Fork started \u2014 processing in background",wt=4;function Et(e){return JSON.stringify(e).includes(U)}function It(e){return e<4}function Lt(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 it(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function at(){return{stages:[]}}function lt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=oe(e,t),i=ut(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=oe(e,t),{messages:a,stagedCount:i.length}}function ct(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,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function ut(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-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==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as j,readdirSync as ue,readFileSync as pt}from"node:fs";import{join as pe}from"node:path";var An=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var se=20;var ie=3,ae=2,le=300*1e3;var Mn=300*1e3,U=4;var En=50*1024,In=500*1024,vn=500*1024*1024;var Ln=60*1024;var de=0;function ce(e){return[...e].sort().join("+")}function dt(e,t){if(!j(t))return null;let n=ce(e);try{let o=ue(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let a=pe(t,r.name,"SKILL.md");try{let s=pt(a,"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(ce(l)===n)return r.name}}catch{}}}catch{}return null}function mt(e){if(!j(e))return 0;try{return ue(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&j(pe(e,t.name,"SKILL.md"))).length}catch{return 0}}function ft(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ie||e.distinctToolCount<ae||Date.now()-de<le||t?.projectSkillsDir&&(mt(t.projectSkillsDir)>=se||t.tools.length>0&&dt(t.tools,t.projectSkillsDir)))}function gt(e){return e.existingSkillName?e.feedback==="negative":!1}function yt(e,t){return gt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ft(e,t)?(de=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 me(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 Tt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ht(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ct(e){if(!e.eligibility?.length)return[...e.tools];let t=ht(e.eligibility);return e.tools.filter(n=>{let o=me(n);if(!o)return!1;let r=t.get(o);return!r||Tt(r.status)})}function _t(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function bt(e){let t=_t({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Ct({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 a=n.function??void 0,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>me(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,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 Rt=["stop","aborted","timeout","cancelled","interrupted","error"],xt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function fe(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function St(e,t){return{...e,content:[...fe(e.content),...fe(t.content)]}}function kt(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 At(e){return new Set((e??Rt).map(t=>t.trim().toLowerCase()))}function ge(e,t){return e?At(t).has(e.trim().toLowerCase()):!1}function Mt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function G(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=>kt(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 a=[];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!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=St(l,s);continue}i.push(s)}return i}function $(e,t){return ge(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of xt)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 a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let i of a.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 Et(e,t){let n=G(e),o=$(n,t);return H(o,t)}function ye(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=ge(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=Mt(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=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&&(a.add(c),i.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||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function It(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function vt(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 Lt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function wt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Te(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ot(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 Pt(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 Nt(e){let t=[],n=G(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((a,i)=>a!==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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:vt(r)}),recoveryActions:t}}function Ft(e){let t=ye(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Lt(t),completedToolCallIds:wt(t)}),recoveryActions:n}}var Dt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Dt.has(e):!0}function Ut(e){return e===429||e===529}function jt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var $n={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Gt(){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>",he="Fork started \u2014 processing in background";function $t(e){return JSON.stringify(e).includes(q)}function Ht(e){return e<U}function zt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
20
21
|
|
|
21
22
|
Your working directory is: ${e.worktreePath}
|
|
22
|
-
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${
|
|
23
|
+
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
|
|
23
24
|
|
|
24
25
|
You are the "${t.agent.name}" agent.${o}
|
|
25
26
|
|
|
26
|
-
${t.taskPrompt}`}]};return n.push(r),n}function
|
|
27
|
+
${t.taskPrompt}`}]};return n.push(r),n}function qt(e){return e.map(t=>({role:"tool",tool_call_id:t,content:he}))}function Xt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolAccessMode==="none")return[];if(t.toolAccessMode==="read-only"){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 Yt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Kt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolAccessMode:"full",canFork:!1},Wt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},Vt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},Jt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Zt={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},Qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolAccessMode:"full",allowedTools:["exec","read_file","search","think"],canFork:!1},X=[Kt,Wt,Vt,Jt,Zt,Qt];function en(){return[...X]}function tn(e){return X.find(t=>t.name===e)}function nn(e){return X.some(t=>t.name===e)}function on(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){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_tool"&&n!=="team_create")}var rn=new Set(["agent_tool","team_create","fork_agent","send_message"]);function sn(e,t){switch(e){case"worker":return t.filter(n=>!rn.has(n));case"coordinator":return[...t];default:return[...t]}}function an(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function ln(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 un(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 pn(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 dn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var mn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function fn(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
28
|
${n.join(`
|
|
28
29
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
29
30
|
Step ${e.activeSkillContext.step}:
|
|
@@ -34,4 +35,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
34
35
|
|
|
35
36
|
${t.join(`
|
|
36
37
|
|
|
37
|
-
`)}`}function
|
|
38
|
+
`)}`}function gn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function yn(e,t=mn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{O as CacheAwareCompressionStrategy,P as CompressionMetricsCollector,N as ContextEngineRegistry,te as DEFAULT_ADAPTIVE_BUDGET_CONFIG,he as FORK_PLACEHOLDER_RESULT,q as FORK_SENTINEL_TAG,z as FallbackTriggeredError,L as HeadTailProtectedStrategy,w as IncrementalCompactStrategy,U as MAX_FORK_DEPTH,F as MicroCompactStrategy,E as SlidingWindowStrategy,I as SummarizeOldStrategy,v as ToolResultTrimStrategy,Ot as advanceToolLoopState,lt as applyContextCollapsesIfNeeded,bt as applyToolChoicePolicy,Ce as buildAssistantToolCallMessage,qt as buildForkPlaceholderResults,zt as buildForkedMessages,fn as buildPostCompactRestorationMessage,yt as buildSkillInstruction,B as buildStructuredSummaryPrompt,_e as buildToolResultMessage,cn as calculateTokenWarningState,Ht as canForkAtDepth,Ve as classifyError,et as composeAsyncStrategies,Qe as composeStrategies,tt as computeAdaptiveBudget,jt as computeRetryBackoff,at as createCollapseStore,gn as createReactiveCompactState,an as createTaskState,ln as createTurnLoopGuardState,sn as filterToolsByRole,Yt as generateForkChildAgentId,tn as getBuiltInAgent,en as getBuiltInAgents,D as isAsyncCompressionStrategy,nn as isBuiltInAgent,Bt as isForegroundSource,$t as isInForkChild,Gt as isPersistentRetryEnabled,Je as isRetryableCategory,Ut as isTransientCapacityError,st as postCompactFileRecovery,ct as recoverContextCollapseFromOverflow,Nt as recoverToolLoopStateFromChatConversation,Ft as recoverToolLoopStateFromResponsesItems,Et as repairOpenAiChatConversation,on as resolveAgentToolSet,un as resolveApiErrorRecovery,Xt as resolveForkChildTools,pn as resolveOutputTokenEscalation,nt as selectCompressionTier,Pt as settleToolLoopState,dn as shouldAbortTurn,yn as shouldAttemptReactiveCompact,it as snipCompactIfNeeded};
|
|
@@ -1,57 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Centralized agent configuration constants.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* CC reference: Various — CC scatters these across query.ts,
|
|
9
|
-
* withRetry.ts, tokenBudget.ts. We centralize for maintainability.
|
|
4
|
+
* Re-exports from `tunable-defaults.ts` which is the single source of truth.
|
|
5
|
+
* This file exists for backward compatibility — new consumers should import
|
|
6
|
+
* from `./tunable-defaults.js` directly.
|
|
10
7
|
*/
|
|
11
|
-
|
|
12
|
-
export declare const MAX_ROUNDS_LIMIT = 100;
|
|
13
|
-
/** Default rounds for a top-level agent turn. */
|
|
14
|
-
export declare const DEFAULT_MAX_ROUNDS = 25;
|
|
15
|
-
/** Default temperature for tool loop LLM calls.
|
|
16
|
-
* CC uses temp=1 for main loop (Anthropic API forces it for thinking),
|
|
17
|
-
* temp=0 for classifiers. We default to 0 for deterministic behaviour
|
|
18
|
-
* with DeepSeek/OpenAI-compat models — callers can override. */
|
|
19
|
-
export declare const DEFAULT_TEMPERATURE = 0;
|
|
20
|
-
/** Hard cap on tool calls per round (prevents runaway). */
|
|
21
|
-
export declare const MAX_TOOL_BUDGET_CAP = 100;
|
|
22
|
-
/** Default tool budget per round. Overridable via TOOL_LOOP_DEFAULT_BUDGET env. */
|
|
23
|
-
export declare const DEFAULT_TOOL_BUDGET: number;
|
|
24
|
-
/** Max consecutive tool call failures before early exit. */
|
|
25
|
-
export declare const MAX_CONSECUTIVE_FAILURES = 3;
|
|
26
|
-
/** Default context window size (tokens). Used when model-specific size unknown. */
|
|
27
|
-
export declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 128000;
|
|
28
|
-
/** Reserved tokens for model response output in turn-loop-guard budget check. */
|
|
29
|
-
export declare const RESPONSE_BUFFER_TOKENS = 13000;
|
|
30
|
-
/** Default max output tokens per LLM API call. */
|
|
31
|
-
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
32
|
-
/** Model's absolute max output tokens (escalation ceiling). */
|
|
33
|
-
export declare const DEFAULT_MODEL_MAX_OUTPUT_TOKENS = 65536;
|
|
34
|
-
/** Max max_output_tokens recovery attempts before surfacing the error (CC: 3). */
|
|
35
|
-
export declare const MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3;
|
|
36
|
-
/** Escalated max output tokens — retry at this ceiling before multi-turn recovery (CC: 64k). */
|
|
37
|
-
export declare const ESCALATED_MAX_OUTPUT_TOKENS = 65536;
|
|
38
|
-
/** Heartbeat interval during persistent retry waits (CC: 30 seconds). */
|
|
39
|
-
export declare const HEARTBEAT_INTERVAL_MS = 30000;
|
|
40
|
-
/** Max consecutive 529 errors before fallback model switch (CC: 3). */
|
|
41
|
-
export declare const MAX_529_RETRIES = 3;
|
|
42
|
-
/** Max consecutive API error retries before aborting (CC: 10). */
|
|
43
|
-
export declare const MAX_API_RETRIES = 10;
|
|
44
|
-
/** Delta threshold (tokens) below which a budget continuation is "diminishing returns".
|
|
45
|
-
* CC: DIMINISHING_THRESHOLD = 500. */
|
|
46
|
-
export declare const DIMINISHING_RETURNS_THRESHOLD = 500;
|
|
47
|
-
/** Min consecutive continuations before diminishing returns check activates (CC: 3). */
|
|
48
|
-
export declare const DIMINISHING_RETURNS_MIN_CONTINUATIONS = 3;
|
|
49
|
-
/** Per-tool result size threshold (chars). Results exceeding this are persisted to disk
|
|
50
|
-
* and replaced with a preview reference (CC: DEFAULT_MAX_RESULT_SIZE_CHARS = 50_000). */
|
|
51
|
-
export declare const DEFAULT_MAX_RESULT_SIZE_CHARS = 50000;
|
|
52
|
-
/** Per-message aggregate budget (chars). When a group of tool results in one response
|
|
53
|
-
* batch exceeds this, the largest fresh results are persisted until under budget
|
|
54
|
-
* (CC: MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200_000). */
|
|
55
|
-
export declare const MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200000;
|
|
56
|
-
/** Preview size for persisted tool result reference messages (CC: PREVIEW_SIZE_BYTES = 2000). */
|
|
57
|
-
export declare const TOOL_RESULT_PREVIEW_BYTES = 2000;
|
|
8
|
+
export { MAX_ROUNDS_LIMIT, DEFAULT_MAX_ROUNDS, DEFAULT_TEMPERATURE, MAX_TOOL_BUDGET_CAP, DEFAULT_TOOL_BUDGET, MAX_CONSECUTIVE_FAILURES, MAX_IDENTICAL_CALL_REPEATS, DEFAULT_CONTEXT_WINDOW_TOKENS, RESPONSE_BUFFER_TOKENS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_MODEL_MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS_RECOVERY_LIMIT, ESCALATED_MAX_OUTPUT_TOKENS, DIMINISHING_RETURNS_THRESHOLD, DIMINISHING_RETURNS_MIN_CONTINUATIONS, DEFAULT_MAX_RESULT_SIZE_CHARS, MAX_TOOL_RESULTS_PER_MESSAGE_CHARS, TOOL_RESULT_PREVIEW_BYTES, HEARTBEAT_INTERVAL_MS, MAX_529_RETRIES, MAX_API_RETRIES, } from "./tunable-defaults.js";
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized tunable defaults — single source of truth.
|
|
3
|
+
*
|
|
4
|
+
* ALL configurable constants that external apps (Electron UI, CLI config)
|
|
5
|
+
* may want to read or override are defined here. This enables:
|
|
6
|
+
*
|
|
7
|
+
* 1. A future `config.tunables` RPC endpoint for visual editing
|
|
8
|
+
* 2. Serialization to JSON for persistence (settings.json)
|
|
9
|
+
* 3. Environment variable overrides via QLOGICAGENT_* prefix
|
|
10
|
+
*
|
|
11
|
+
* Consumers import individual constants from this module.
|
|
12
|
+
* The full shape is exported as `TunableDefaults` interface for RPC typing.
|
|
13
|
+
*
|
|
14
|
+
* Grouping follows subsystem boundaries.
|
|
15
|
+
*/
|
|
16
|
+
/** Absolute max rounds any agent can run (hard cap). */
|
|
17
|
+
export declare const MAX_ROUNDS_LIMIT = 100;
|
|
18
|
+
/** Default rounds for a top-level agent turn. */
|
|
19
|
+
export declare const DEFAULT_MAX_ROUNDS = 25;
|
|
20
|
+
/** Default temperature for LLM calls (0 = deterministic). */
|
|
21
|
+
export declare const DEFAULT_TEMPERATURE = 0;
|
|
22
|
+
/** Hard cap on tool calls per round (prevents runaway). */
|
|
23
|
+
export declare const MAX_TOOL_BUDGET_CAP = 100;
|
|
24
|
+
/** Default tool budget per round. Overridable via TOOL_LOOP_DEFAULT_BUDGET env. */
|
|
25
|
+
export declare const DEFAULT_TOOL_BUDGET: number;
|
|
26
|
+
/** Max consecutive tool call failures before early exit. */
|
|
27
|
+
export declare const MAX_CONSECUTIVE_FAILURES = 3;
|
|
28
|
+
/** Max times the exact same (tool_name, arguments) pair can repeat. */
|
|
29
|
+
export declare const MAX_IDENTICAL_CALL_REPEATS = 2;
|
|
30
|
+
/** Default context window size (tokens). */
|
|
31
|
+
export declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 128000;
|
|
32
|
+
/** Reserved tokens for model response output. */
|
|
33
|
+
export declare const RESPONSE_BUFFER_TOKENS = 13000;
|
|
34
|
+
/** Default max output tokens per LLM API call. */
|
|
35
|
+
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
36
|
+
/** Model's absolute max output tokens (escalation ceiling). */
|
|
37
|
+
export declare const DEFAULT_MODEL_MAX_OUTPUT_TOKENS = 65536;
|
|
38
|
+
/** Max max_output_tokens recovery attempts (CC: 3). */
|
|
39
|
+
export declare const MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3;
|
|
40
|
+
/** Escalated max output tokens during recovery (CC: 64k). */
|
|
41
|
+
export declare const ESCALATED_MAX_OUTPUT_TOKENS = 65536;
|
|
42
|
+
/** Delta threshold for "diminishing returns" detection (CC: 500). */
|
|
43
|
+
export declare const DIMINISHING_RETURNS_THRESHOLD = 500;
|
|
44
|
+
/** Min consecutive continuations before diminishing returns kicks in. */
|
|
45
|
+
export declare const DIMINISHING_RETURNS_MIN_CONTINUATIONS = 3;
|
|
46
|
+
/** Per-tool result size threshold (chars) for disk persistence. */
|
|
47
|
+
export declare const DEFAULT_MAX_RESULT_SIZE_CHARS = 50000;
|
|
48
|
+
/** Per-message aggregate tool result budget (chars). */
|
|
49
|
+
export declare const MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200000;
|
|
50
|
+
/** Preview size for persisted tool result references (bytes). */
|
|
51
|
+
export declare const TOOL_RESULT_PREVIEW_BYTES = 2000;
|
|
52
|
+
/** Heartbeat interval during persistent retry waits (ms). */
|
|
53
|
+
export declare const HEARTBEAT_INTERVAL_MS = 30000;
|
|
54
|
+
/** Max 529 errors before fallback model switch. */
|
|
55
|
+
export declare const MAX_529_RETRIES = 3;
|
|
56
|
+
/** Max consecutive API error retries before aborting. */
|
|
57
|
+
export declare const MAX_API_RETRIES = 10;
|
|
58
|
+
/** Max backoff interval for persistent retry (ms). */
|
|
59
|
+
export declare const PERSISTENT_RETRY_MAX_BACKOFF_MS = 300000;
|
|
60
|
+
/** Total retry time cap for persistent retry (ms). */
|
|
61
|
+
export declare const PERSISTENT_RETRY_RESET_CAP_MS = 21600000;
|
|
62
|
+
/** Target usage ratio after compression (0-1). */
|
|
63
|
+
export declare const COMPRESSION_TARGET_USAGE_RATIO = 0.75;
|
|
64
|
+
/** Min token budget floor after compression. */
|
|
65
|
+
export declare const COMPRESSION_MIN_BUDGET = 16000;
|
|
66
|
+
/** Max token budget ceiling. */
|
|
67
|
+
export declare const COMPRESSION_MAX_BUDGET = 120000;
|
|
68
|
+
/** Max consecutive reactive compaction failures. */
|
|
69
|
+
export declare const REACTIVE_COMPACT_MAX_FAILURES = 3;
|
|
70
|
+
/** Min messages to keep after reactive compaction. */
|
|
71
|
+
export declare const REACTIVE_COMPACT_MIN_MESSAGES = 4;
|
|
72
|
+
/** Target usage percentage for reactive compaction. */
|
|
73
|
+
export declare const REACTIVE_COMPACT_TARGET_PERCENT = 50;
|
|
74
|
+
/** Max auto-learned skills per project. */
|
|
75
|
+
export declare const MAX_SKILLS_PER_PROJECT = 20;
|
|
76
|
+
/** Max global (user-level) skills. */
|
|
77
|
+
export declare const MAX_SKILLS_GLOBAL = 50;
|
|
78
|
+
/** Min tool calls to consider a turn "complex enough" for skill creation. */
|
|
79
|
+
export declare const MIN_TOOL_CALLS_FOR_SKILL = 3;
|
|
80
|
+
/** Min distinct tools to suggest a new skill. */
|
|
81
|
+
export declare const MIN_DISTINCT_TOOLS_FOR_SKILL = 2;
|
|
82
|
+
/** Cooldown between skill creation suggestions (ms). */
|
|
83
|
+
export declare const SKILL_CREATION_COOLDOWN_MS: number;
|
|
84
|
+
/** Max chars of skill content injected into system prompt. */
|
|
85
|
+
export declare const SKILL_INJECTION_MAX_CHARS = 4000;
|
|
86
|
+
/** Max skills injected into a single prompt. */
|
|
87
|
+
export declare const SKILL_INJECTION_MAX_COUNT = 5;
|
|
88
|
+
/** Max skills recalled from other projects per turn. */
|
|
89
|
+
export declare const SKILL_RECALL_MAX_SKILLS = 3;
|
|
90
|
+
/** Max chars per recalled skill content. */
|
|
91
|
+
export declare const SKILL_RECALL_MAX_CONTENT_CHARS = 800;
|
|
92
|
+
/** Skill recall index cache TTL (ms). */
|
|
93
|
+
export declare const SKILL_RECALL_CACHE_TTL_MS: number;
|
|
94
|
+
/** Max nested fork depth for sub-agents. */
|
|
95
|
+
export declare const MAX_FORK_DEPTH = 4;
|
|
96
|
+
/** Max historical sessions retained on disk. */
|
|
97
|
+
export declare const MAX_SESSIONS = 50;
|
|
98
|
+
/** Turn count threshold for triggering task summary. */
|
|
99
|
+
export declare const TASK_SUMMARY_TURN_THRESHOLD = 50;
|
|
100
|
+
/** Interval (turns) between summary regeneration. */
|
|
101
|
+
export declare const TASK_SUMMARY_REGEN_INTERVAL = 30;
|
|
102
|
+
/** Max include nesting depth in instruction files. */
|
|
103
|
+
export declare const MAX_INCLUDE_DEPTH = 5;
|
|
104
|
+
/** Max total chars loaded from instruction files. */
|
|
105
|
+
export declare const MAX_INSTRUCTION_CHARS = 40000;
|
|
106
|
+
/** Max single instruction file size (bytes). */
|
|
107
|
+
export declare const INSTRUCTIONS_MAX_FILE_SIZE: number;
|
|
108
|
+
/** Max total instruction directory size (bytes). */
|
|
109
|
+
export declare const INSTRUCTIONS_MAX_DIR_SIZE: number;
|
|
110
|
+
/** Max single media file download size (bytes, 500 MB). */
|
|
111
|
+
export declare const MEDIA_MAX_DOWNLOAD_SIZE: number;
|
|
112
|
+
/** Media download timeout (ms). */
|
|
113
|
+
export declare const MEDIA_DOWNLOAD_TIMEOUT_MS = 300000;
|
|
114
|
+
/** Max retries when spawning an ACP agent process. */
|
|
115
|
+
export declare const ACP_MAX_SPAWN_RETRIES = 2;
|
|
116
|
+
/** Backoff base for agent spawn retries (ms). */
|
|
117
|
+
export declare const ACP_RETRY_BACKOFF_BASE = 3000;
|
|
118
|
+
/** Max automatic restarts after agent process crash. */
|
|
119
|
+
export declare const ACP_RUNTIME_RESTART_MAX = 3;
|
|
120
|
+
/** Backoff base for crash restarts (ms). */
|
|
121
|
+
export declare const ACP_RUNTIME_RESTART_BACKOFF_BASE = 5000;
|
|
122
|
+
/** Running task poll interval (ms). */
|
|
123
|
+
export declare const TASK_POLL_INTERVAL_MS = 1000;
|
|
124
|
+
/** How long to display stopped tasks before removal (ms). */
|
|
125
|
+
export declare const TASK_STOPPED_DISPLAY_MS = 3000;
|
|
126
|
+
/** Terminal task cleanup grace period (ms). */
|
|
127
|
+
export declare const TASK_PANEL_GRACE_MS = 30000;
|
|
128
|
+
/** Max bytes injected for session memory prefetch. */
|
|
129
|
+
export declare const MEMORY_PREFETCH_MAX_SESSION_BYTES: number;
|
|
130
|
+
/** Max results per memory recall query. */
|
|
131
|
+
export declare const MEMORY_PREFETCH_LIMIT_PER_RECALL = 10;
|
|
132
|
+
/** LRU dedup set size for surfaced memory entries. */
|
|
133
|
+
export declare const MEMORY_MAX_SURFACED_ENTRIES = 100;
|
|
134
|
+
/** Min hours between dream consolidation runs. */
|
|
135
|
+
export declare const DREAM_MIN_INTERVAL_HOURS = 24;
|
|
136
|
+
/** Min sessions before dream triggers. */
|
|
137
|
+
export declare const DREAM_MIN_SESSIONS = 5;
|
|
138
|
+
/** Dream scan throttle interval (ms). */
|
|
139
|
+
export declare const DREAM_SCAN_INTERVAL_MS = 600000;
|
|
140
|
+
/** Idle dream timer (minutes). */
|
|
141
|
+
export declare const IDLE_DREAM_MINUTES = 30;
|
|
142
|
+
/** Dream cooldown between runs (ms, 4 hours). */
|
|
143
|
+
export declare const DREAM_COOLDOWN_MS = 14400000;
|
|
144
|
+
/** Max dream run duration (ms). */
|
|
145
|
+
export declare const DREAM_MAX_DURATION_MS = 300000;
|
|
146
|
+
/**
|
|
147
|
+
* Full typed shape of all tunable defaults.
|
|
148
|
+
* Used by `config.tunables` RPC for external app visualization.
|
|
149
|
+
*/
|
|
150
|
+
export interface TunableDefaults {
|
|
151
|
+
maxRoundsLimit: number;
|
|
152
|
+
defaultMaxRounds: number;
|
|
153
|
+
defaultTemperature: number;
|
|
154
|
+
maxToolBudgetCap: number;
|
|
155
|
+
defaultToolBudget: number;
|
|
156
|
+
maxConsecutiveFailures: number;
|
|
157
|
+
maxIdenticalCallRepeats: number;
|
|
158
|
+
defaultContextWindowTokens: number;
|
|
159
|
+
responseBufferTokens: number;
|
|
160
|
+
defaultMaxOutputTokens: number;
|
|
161
|
+
defaultModelMaxOutputTokens: number;
|
|
162
|
+
maxOutputTokensRecoveryLimit: number;
|
|
163
|
+
escalatedMaxOutputTokens: number;
|
|
164
|
+
diminishingReturnsThreshold: number;
|
|
165
|
+
diminishingReturnsMinContinuations: number;
|
|
166
|
+
defaultMaxResultSizeChars: number;
|
|
167
|
+
maxToolResultsPerMessageChars: number;
|
|
168
|
+
toolResultPreviewBytes: number;
|
|
169
|
+
heartbeatIntervalMs: number;
|
|
170
|
+
max529Retries: number;
|
|
171
|
+
maxApiRetries: number;
|
|
172
|
+
persistentRetryMaxBackoffMs: number;
|
|
173
|
+
persistentRetryResetCapMs: number;
|
|
174
|
+
compressionTargetUsageRatio: number;
|
|
175
|
+
compressionMinBudget: number;
|
|
176
|
+
compressionMaxBudget: number;
|
|
177
|
+
reactiveCompactMaxFailures: number;
|
|
178
|
+
reactiveCompactMinMessages: number;
|
|
179
|
+
reactiveCompactTargetPercent: number;
|
|
180
|
+
maxSkillsPerProject: number;
|
|
181
|
+
maxSkillsGlobal: number;
|
|
182
|
+
minToolCallsForSkill: number;
|
|
183
|
+
minDistinctToolsForSkill: number;
|
|
184
|
+
skillCreationCooldownMs: number;
|
|
185
|
+
skillInjectionMaxChars: number;
|
|
186
|
+
skillInjectionMaxCount: number;
|
|
187
|
+
skillRecallMaxSkills: number;
|
|
188
|
+
skillRecallMaxContentChars: number;
|
|
189
|
+
skillRecallCacheTtlMs: number;
|
|
190
|
+
maxForkDepth: number;
|
|
191
|
+
maxSessions: number;
|
|
192
|
+
taskSummaryTurnThreshold: number;
|
|
193
|
+
taskSummaryRegenInterval: number;
|
|
194
|
+
maxIncludeDepth: number;
|
|
195
|
+
maxInstructionChars: number;
|
|
196
|
+
instructionsMaxFileSize: number;
|
|
197
|
+
instructionsMaxDirSize: number;
|
|
198
|
+
mediaMaxDownloadSize: number;
|
|
199
|
+
mediaDownloadTimeoutMs: number;
|
|
200
|
+
acpMaxSpawnRetries: number;
|
|
201
|
+
acpRetryBackoffBase: number;
|
|
202
|
+
acpRuntimeRestartMax: number;
|
|
203
|
+
acpRuntimeRestartBackoffBase: number;
|
|
204
|
+
taskPollIntervalMs: number;
|
|
205
|
+
taskStoppedDisplayMs: number;
|
|
206
|
+
taskPanelGraceMs: number;
|
|
207
|
+
memoryPrefetchMaxSessionBytes: number;
|
|
208
|
+
memoryPrefetchLimitPerRecall: number;
|
|
209
|
+
memoryMaxSurfacedEntries: number;
|
|
210
|
+
dreamMinIntervalHours: number;
|
|
211
|
+
dreamMinSessions: number;
|
|
212
|
+
dreamScanIntervalMs: number;
|
|
213
|
+
idleDreamMinutes: number;
|
|
214
|
+
dreamCooldownMs: number;
|
|
215
|
+
dreamMaxDurationMs: number;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Snapshot of all current tunable values.
|
|
219
|
+
* Use this for RPC serialization and external app display.
|
|
220
|
+
*/
|
|
221
|
+
export declare function getTunableDefaults(): TunableDefaults;
|
|
@@ -92,6 +92,11 @@ export declare class StdioServer {
|
|
|
92
92
|
* Always returns the InitializeResult shape.
|
|
93
93
|
*/
|
|
94
94
|
private handleInitialize;
|
|
95
|
+
/**
|
|
96
|
+
* Ensure a default project exists on first start.
|
|
97
|
+
* Called from both legacy handleInitialize and ACP acpHandleInitialize.
|
|
98
|
+
*/
|
|
99
|
+
private ensureDefaultProject;
|
|
95
100
|
/**
|
|
96
101
|
* `thread.create` — create a new thread (session container).
|
|
97
102
|
* Maps threadId → sessionId for the underlying session system.
|
|
@@ -173,6 +178,16 @@ export declare class StdioServer {
|
|
|
173
178
|
* `config.update` — Update agent runtime configuration (merges into settings.json).
|
|
174
179
|
*/
|
|
175
180
|
private handleConfigUpdate;
|
|
181
|
+
/**
|
|
182
|
+
* `config.tunables` — Return all tunable default values with their current overrides.
|
|
183
|
+
*/
|
|
184
|
+
private handleConfigTunables;
|
|
185
|
+
/**
|
|
186
|
+
* `config.updateTunable` — Write a single tunable override into settings.json.tunables.
|
|
187
|
+
* Params: { key: string, value: number | boolean | string }
|
|
188
|
+
* Only keys that exist in TunableDefaults are accepted (validation).
|
|
189
|
+
*/
|
|
190
|
+
private handleConfigUpdateTunable;
|
|
176
191
|
/**
|
|
177
192
|
* `todos.list` — Query current todo items and summary.
|
|
178
193
|
* Invokes the registered todo tool's list action.
|
|
@@ -303,6 +318,9 @@ export declare class StdioServer {
|
|
|
303
318
|
private handleProjectCreate;
|
|
304
319
|
private handleProjectList;
|
|
305
320
|
private handleProjectDelete;
|
|
321
|
+
private handleProjectRename;
|
|
322
|
+
private handleProjectArchive;
|
|
323
|
+
private handleProjectUnarchive;
|
|
306
324
|
private handleProjectArchiveByGroup;
|
|
307
325
|
private handleSessionSwitchProject;
|
|
308
326
|
private handleSessionGetState;
|
|
@@ -312,8 +330,23 @@ export declare class StdioServer {
|
|
|
312
330
|
private handleInstructionsWrite;
|
|
313
331
|
private handleInstructionsDelete;
|
|
314
332
|
private handleSkillsList;
|
|
333
|
+
/** Extract version and description from a SKILL.md frontmatter. */
|
|
334
|
+
private extractSkillMeta;
|
|
315
335
|
private handleSkillsActivate;
|
|
316
336
|
private handleSkillsDeactivate;
|
|
337
|
+
/**
|
|
338
|
+
* `skills.delete` — Permanently remove a skill from project or global scope.
|
|
339
|
+
* Params: { name: string, scope?: "project" | "global" }
|
|
340
|
+
* Default scope: "project"
|
|
341
|
+
*/
|
|
342
|
+
private handleSkillsDelete;
|
|
343
|
+
/**
|
|
344
|
+
* `skills.promote` — Copy a project-level skill to global (user-level).
|
|
345
|
+
* Params: { name: string, keepLocal?: boolean }
|
|
346
|
+
* By default removes the project-level copy after promoting.
|
|
347
|
+
*/
|
|
348
|
+
private handleSkillsPromote;
|
|
349
|
+
private handleSkillsStats;
|
|
317
350
|
private getProjectPlanStore;
|
|
318
351
|
private handlePlansList;
|
|
319
352
|
private handlePlansGet;
|