qlogicagent 0.5.3 → 1.0.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/README.md +24 -23
- package/dist/agent.js +13 -13
- package/dist/cli.js +218 -184
- package/dist/contracts.js +1 -1
- package/dist/index.js +391 -20
- package/dist/orchestration.js +14 -105
- package/dist/types/agent/agent.d.ts +1 -1
- package/dist/types/agent/constants.d.ts +2 -2
- package/dist/types/agent/tool-access.d.ts +30 -0
- package/dist/types/agent/tool-loop.d.ts +2 -4
- package/dist/types/agent/types.d.ts +51 -13
- package/dist/types/cli/main.d.ts +3 -3
- package/dist/types/cli/stdio-server.d.ts +89 -7
- package/dist/types/cli/tool-bootstrap.d.ts +16 -5
- package/dist/types/cli/transport.d.ts +40 -0
- package/dist/types/contracts/index.d.ts +0 -1
- package/dist/types/contracts/todo.d.ts +9 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/llm/index.d.ts +7 -1
- package/dist/types/llm/media-client.d.ts +43 -0
- package/dist/types/llm/media-transport.d.ts +80 -0
- package/dist/types/llm/model-catalog.d.ts +5 -5
- package/dist/types/llm/provider-def.d.ts +7 -0
- package/dist/types/llm/provider-registry.d.ts +1 -1
- package/dist/types/llm/transport.d.ts +2 -0
- package/dist/types/llm/transports/anthropic-messages.d.ts +34 -11
- package/dist/types/llm/transports/gemini-media.d.ts +21 -0
- package/dist/types/llm/transports/minimax-media.d.ts +21 -0
- package/dist/types/llm/transports/openai-chat.d.ts +1 -1
- package/dist/types/llm/transports/openai-media.d.ts +24 -0
- package/dist/types/llm/transports/qwen-media.d.ts +25 -0
- package/dist/types/llm/transports/volcengine-media.d.ts +34 -0
- package/dist/types/orchestration/index.d.ts +14 -112
- package/dist/types/orchestration/skill-improvement.d.ts +2 -2
- package/dist/types/orchestration/{fork-subagent.d.ts → subagent/fork-subagent.d.ts} +2 -4
- package/dist/types/orchestration/{tool-schema.d.ts → tool-loop/tool-schema.d.ts} +1 -2
- package/dist/types/protocol/index.d.ts +7 -0
- package/dist/types/protocol/methods.d.ts +380 -0
- package/dist/types/protocol/notifications.d.ts +296 -0
- package/dist/types/runtime/execution/dream-agent.d.ts +1 -1
- package/dist/types/runtime/execution/forked-agent.d.ts +1 -3
- package/dist/types/runtime/hooks/context-compression.d.ts +1 -1
- package/dist/types/runtime/infra/agent-paths.d.ts +57 -0
- package/dist/types/runtime/infra/checkpoint-backend.d.ts +8 -0
- package/dist/types/runtime/infra/disk-storage.d.ts +36 -0
- package/dist/types/runtime/infra/file-watcher.d.ts +2 -2
- package/dist/types/runtime/infra/index.d.ts +2 -0
- package/dist/types/runtime/infra/secure-storage.d.ts +1 -1
- package/dist/types/runtime/infra/task-runtime.d.ts +1 -1
- package/dist/types/runtime/prompt/environment-context.d.ts +1 -1
- package/dist/types/runtime/prompt/instruction-loader.d.ts +6 -6
- package/dist/types/runtime/session/index.d.ts +1 -1
- package/dist/types/runtime/session/session-memory.d.ts +0 -1
- package/dist/types/runtime/session/session-persistence.d.ts +1 -1
- package/dist/types/runtime/session/session-state.d.ts +18 -9
- package/dist/types/skills/index.d.ts +20 -26
- package/dist/types/skills/mcp/mcp-manager.d.ts +3 -4
- package/dist/types/skills/mcp/mcp-stdio-client.d.ts +1 -1
- package/dist/types/skills/{memory-store.d.ts → memory/memory-store.d.ts} +20 -0
- package/dist/types/skills/{memory-tool.d.ts → memory/memory-tool.d.ts} +20 -0
- package/dist/types/skills/{qmemory-adapter.d.ts → memory/qmemory-adapter.d.ts} +1 -0
- package/dist/types/skills/permissions/hook-runner.d.ts +1 -1
- package/dist/types/skills/permissions/settings-watcher.d.ts +2 -2
- package/dist/types/skills/plugins/plugin-api.d.ts +1 -1
- package/dist/types/skills/plugins/plugin-loader.d.ts +1 -4
- package/dist/types/skills/plugins/plugin-marketplace.d.ts +1 -1
- package/dist/types/skills/portable-tool.d.ts +34 -1
- package/dist/types/skills/todo-tool.d.ts +51 -42
- package/dist/types/skills/tools/instructions-tool.d.ts +20 -58
- package/dist/types/skills/tools/shell/shell-exec.d.ts +2 -0
- package/dist/types/skills/tools/skill-invoke-tool.d.ts +2 -2
- package/dist/types/skills/tools.d.ts +65 -0
- package/package.json +2 -2
- package/dist/types/contracts/skill-candidate.d.ts +0 -63
- package/dist/types/orchestration/curator-scheduler.d.ts +0 -119
- package/dist/types/orchestration/memory-provider.d.ts +0 -14
- package/dist/types/orchestration/skill-candidate.d.ts +0 -52
- package/dist/types/orchestration/skill-consolidation.d.ts +0 -123
- package/dist/types/orchestration/skill-similarity.d.ts +0 -98
- package/dist/types/orchestration/team-orchestration.d.ts +0 -195
- package/dist/types/orchestration/team-tool-loop-wiring.d.ts +0 -92
- package/dist/types/skills/memory-query-tool.d.ts +0 -43
- package/dist/types/skills/tool-registry.d.ts +0 -29
- package/dist/types/skills/tools/memory-tool.d.ts +0 -74
- package/dist/types/skills/tools/pdf-tool.d.ts +0 -66
- /package/dist/types/orchestration/{context-collapse.d.ts → context/context-collapse.d.ts} +0 -0
- /package/dist/types/orchestration/{context-compression.d.ts → context/context-compression.d.ts} +0 -0
- /package/dist/types/orchestration/{reactive-compact.d.ts → context/reactive-compact.d.ts} +0 -0
- /package/dist/types/orchestration/{turn-loop-guard.d.ts → context/turn-loop-guard.d.ts} +0 -0
- /package/dist/types/orchestration/{error-classification.d.ts → error-handling/error-classification.d.ts} +0 -0
- /package/dist/types/orchestration/{failover-classification.d.ts → error-handling/failover-classification.d.ts} +0 -0
- /package/dist/types/orchestration/{failover-error.d.ts → error-handling/failover-error.d.ts} +0 -0
- /package/dist/types/orchestration/{retry-loop.d.ts → error-handling/retry-loop.d.ts} +0 -0
- /package/dist/types/orchestration/{agent-registry.d.ts → subagent/agent-registry.d.ts} +0 -0
- /package/dist/types/orchestration/{task-types.d.ts → subagent/task-types.d.ts} +0 -0
- /package/dist/types/orchestration/{conversation-repair.d.ts → tool-loop/conversation-repair.d.ts} +0 -0
- /package/dist/types/orchestration/{tool-choice-policy.d.ts → tool-loop/tool-choice-policy.d.ts} +0 -0
- /package/dist/types/orchestration/{tool-loop-state.d.ts → tool-loop/tool-loop-state.d.ts} +0 -0
- /package/dist/types/skills/{memory-extractor.d.ts → memory/memory-extractor.d.ts} +0 -0
- /package/dist/types/skills/{skill-frontmatter.d.ts → skill-system/skill-frontmatter.d.ts} +0 -0
- /package/dist/types/skills/{skill-guard.d.ts → skill-system/skill-guard.d.ts} +0 -0
- /package/dist/types/skills/{skill-loader.d.ts → skill-system/skill-loader.d.ts} +0 -0
- /package/dist/types/skills/{skill-source.d.ts → skill-system/skill-source.d.ts} +0 -0
- /package/dist/types/skills/{skill-types.d.ts → skill-system/skill-types.d.ts} +0 -0
package/dist/orchestration.js
CHANGED
|
@@ -1,106 +1,26 @@
|
|
|
1
|
-
function
|
|
2
|
-
${
|
|
1
|
+
function ce(e,t){return{role:"assistant",content:t||null,tool_calls:e}}function ue(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}}var pe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},de=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,me=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,fe=512,ge=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ye=new Set([500,502,503,504,521,522,523,524,529]),he=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Te=["upgrade your plan","upgrade plan","current plan","subscription"],Ce=["daily","weekly","monthly"],be=["try again","retry","temporary","cooldown"],ke=["usage limit","rate limit","organization usage"],_e=["organization","workspace"],Re=["billing period","exceeded","reached","exhausted"],xe=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Se=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function T(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Ae(e){return T(e,h.format)}function H(e){return T(e,h.rateLimit)}function ve(e){return T(e,h.timeout)}function Me(e){return pe.test(e)}function v(e){let t=e.toLowerCase();return t?e.length>fe?me.test(t):T(t,h.billing)?!0:de.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Y(e){return T(e,h.authPermanent)}function we(e){return T(e,h.auth)}function W(e){return T(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function Ee(e){return y(e,he)||y(e,Te)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ie(e){let t=y(e,Ce),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,_e);return y(e,be)&&y(e,ke)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Re))}function Le(e){return e.trim().toLowerCase().replace(Se,"").trim()}function K(e){let t=Le(e);return!t||Ee(t)?"billing":H(t)||Ie(t)?"rate_limit":"billing"}function Oe(e){return xe.test(e)?K(e):null}function J(e){let t=e.match(ge);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Pe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Fe(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?ye.has(n.code):!1}function V(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?K(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Y(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&&v(t)?"billing":"format":null}function Ne(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 De(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 X(e){if(De(e))return"session_expired";if(Ne(e))return"model_not_found";let t=Oe(e);return t||(Me(e)?v(e)?"billing":"rate_limit":H(e)?"rate_limit":W(e)?"overloaded":Fe(e)?J(e.trim())?.code===529?"overloaded":"timeout":Pe(e)?"timeout":Ae(e)?"format":v(e)?"billing":ve(e)?"timeout":Y(e)?"auth_permanent":we(e)?"auth":null)}var Be={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"},je={RETRYABLE_TRANSIENT:{retryable:!0,maxRetries:3,baseDelayMs:1e3,backoffMultiplier:2,switchProvider:!0},RETRYABLE_DEGRADED:{retryable:!0,maxRetries:2,baseDelayMs:5e3,backoffMultiplier:3,switchProvider:!0},NON_RETRYABLE_AUTH:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},NON_RETRYABLE_CONTENT:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!1},NON_RETRYABLE_QUOTA:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},TOOL_EXECUTION_FAILED:{retryable:!0,maxRetries:1,baseDelayMs:500,backoffMultiplier:1,switchProvider:!1}};function $e(e,t){let n=V(e,t)??(t?X(t):null);return n?Be[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function qe(e){return je[e]}function D(e){return typeof e.compressAsync=="function"}var Q=4,M=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>=Q)break;if(a-p<0&&l<Q){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"}}},w=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"}}},E=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:Ge(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ge(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
|
-
`));if(
|
|
5
|
-
[...truncated: ${e.length-
|
|
4
|
+
`));if(a>t*.5)return n.slice(0,a+1)+`
|
|
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 ze(...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 Ue(...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","Note any critical facts, constraints, or preferences the user mentioned that must be preserved.","","### 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 I=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}=ee(t),i=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let s=0,l=0;for(let f=0;f<a.length&&(a[f].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));f++)s=f+1;let u=Math.max(s,a.length-this.config.protectedTailMessages);if(u<=s)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let c=a.slice(0,s),d=a.slice(s,u),p=a.slice(u),m=B(d,{taskContext:this.config.taskContext}),C=await this.config.summarize(d,m),S={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
${
|
|
11
|
+
${C}`},b=[...r,...c,S,...p],k=Date.now()-o,_=b.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:b,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:_,compressionRatio:i>0?_/i:1,latencyMs:k,usedLlm:!0,cacheInvalidated:!0}}}},L=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}=ee(t),i=r.findIndex(g=>typeof g.content=="string"&&g.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((g,A)=>g+this.config.estimateTokens(A),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=a.slice(0,u),p=a.slice(u),m=s&&typeof s.content=="string"?`Previous summary:
|
|
12
|
+
${s.content}
|
|
13
13
|
|
|
14
|
-
New messages to integrate:`:void 0,
|
|
14
|
+
New messages to integrate:`:void 0,C=B(d,{taskContext:m}),S=await this.config.summarize(d,C),b={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),
|
|
16
|
+
${S}`},k=[...l,b,...p],_=Date.now()-o,f=k.reduce((g,A)=>g+this.config.estimateTokens(A),0);return{messages:k,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:f,compressionRatio:c>0?f/c:1,latencyMs:_,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}}}},Z={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function He(e={}){let t={...Z,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function Ye(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}},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 ee(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 We=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"]),N=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||!We.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 Ke(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 Je(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=Ke(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 m=await n.readFile(p);if(!m)continue;let C=o(m);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 u=[...e],d=-1;for(let p=0;p<u.length;p++)u[p].role==="system"&&(d=p);return u.splice(d+1,0,...l),u}function Mt(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}i.push(a)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function Et(){return{stages:[]}}function It(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=Lt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=me(e,t),{messages:i,stagedCount:s.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:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let a=Math.min(s,o.length),l={role:"system",content:r.summary};o.splice(i,a-i,l)}return o}function Lt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),s=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=l),a++;else{if(a>=3){let d=`${s}-${s+a}`;i.has(d)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}s=-1,a=0}}if(a>=3){let l=`${s}-${s+a}`;i.has(l)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function Ot(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 Dt(e,t){return Nt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Ot(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}var Ft=["submit-review","approve","reject","start-canary","record-effectiveness","promote","publish","mark-stale","mark-superseded","rollback"],Bt=["canary","published"];function m(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function T(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function E(e,t=0){let n=T(e);return n===void 0?Math.max(0,Math.floor(t)):Math.max(0,Math.floor(n))}function C(e){return e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function $t(e){return typeof e=="string"&&Ft.includes(e)}function jt(e){return typeof e=="string"&&Bt.includes(e)}function ge(e){let t=m(e);return t&&$t(t)?t:null}function W(e){let t=m(e);return t&&jt(t)?t:null}function ye(e){let t=C(e),n=m(t.uri);if(!n)return null;let o=m(t.sha256),r=m(t.workspaceDir),i=m(t.relativePath),s=m(t.sourceWorkspaceDir),a=m(t.stagedAt);return{uri:n,...o?{sha256:o}:{},...r?{workspaceDir:r}:{},...i?{relativePath:i}:{},...s?{sourceWorkspaceDir:s}:{},...a?{stagedAt:a}:{}}}function he(e){let t=C(e),n=m(t.executionId),o=m(t.rootExecutionId),r=m(t.parentExecutionId),i=m(t.sidechainId),s=m(t.attemptId),a=m(t.outcomeId),l=m(t.sessionId),c=m(t.turnId);return!n&&!o&&!r&&!i&&!s&&!a&&!l&&!c?null:{...n?{executionId:n}:{},...o?{rootExecutionId:o}:{},...r?{parentExecutionId:r}:{},...i?{sidechainId:i}:{},...s?{attemptId:s}:{},...a?{outcomeId:a}:{},...l?{sessionId:l}:{},...c?{turnId:c}:{}}}function Ce(e){let t=C(e),n=W(t.phase);if(!n)return null;let o=E(t.successCount),r=T(t.failureCount),i=E(t.sampleCount,r!==void 0?o+r:o),s=E(t.failureCount,Math.max(i-o,0)),a=E(t.regressionCount),l=T(t.successRate)??(i>0?o/i:0),c=T(t.regressionRate)??(i>0?a/i:0),u=T(t.avgLatencyMs),d=T(t.avgCostUsd),p=T(t.score),f=m(t.staleReason)??null,h=m(t.notes)??null,v=C(t.summary),b=m(t.lastObservedAt),S=m(t.updatedAt),k=m(t.lastActivityAt),g=T(t.activityCount);return{phase:n,sampleCount:i,successCount:o,failureCount:s,regressionCount:a,successRate:l,regressionRate:c,...u!==void 0?{avgLatencyMs:u}:{},...d!==void 0?{avgCostUsd:d}:{},...p!==void 0?{score:p}:{},...f?{staleReason:f}:{},...h?{notes:h}:{},...Object.keys(v).length>0?{summary:v}:{},...b?{lastObservedAt:b}:{},...S?{updatedAt:S}:{},...k?{lastActivityAt:k}:{},...g!==void 0?{activityCount:g}:{}}}var Te={reviewRequired:!0,canaryRequired:!0,autoPromote:!1,minCanarySampleCount:10,minSuccessRate:.7,maxRegressionRate:.1,maxCostIncreaseRate:.25,staleAfterHours:168};function K(e,t){if(typeof e=="boolean")return e;if(typeof e=="string"){let n=e.trim().toLowerCase();if(n==="true")return!0;if(n==="false")return!1}return t}function _(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=e.trim();if(n){let o=Number(n);if(Number.isFinite(o))return o}}return t}function Ut(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function zt(e={}){return be(e,Te)}function be(e,t=Te){let n=C(e);return{reviewRequired:K(n.reviewRequired,t.reviewRequired),canaryRequired:K(n.canaryRequired,t.canaryRequired),autoPromote:K(n.autoPromote,t.autoPromote),minCanarySampleCount:Math.max(1,Math.floor(_(n.minCanarySampleCount,t.minCanarySampleCount))),minSuccessRate:Math.max(0,Math.min(1,_(n.minSuccessRate,t.minSuccessRate))),maxRegressionRate:Math.max(0,Math.min(1,_(n.maxRegressionRate,t.maxRegressionRate))),maxCostIncreaseRate:Math.max(0,_(n.maxCostIncreaseRate,t.maxCostIncreaseRate)),staleAfterHours:Math.max(1,Math.floor(_(n.staleAfterHours,t.staleAfterHours)))}}function Se(e){let t=C(e.evidence),n=e.artifact?ye(e.artifact):null,o=e.sourceExecution?he(e.sourceExecution):null,r=typeof e.sourceSessionKey=="string"?e.sourceSessionKey.trim():"";return{...t,...n?{artifact:n}:{},...o?{sourceExecution:o}:{},...r?{sourceSessionKey:r}:{}}}function Ht(e){let t=Se(e),n=typeof e.diffSummary=="string"&&e.diffSummary.trim()?e.diffSummary.trim():"",o=typeof e.baselineCandidateId=="string"&&e.baselineCandidateId.trim()?e.baselineCandidateId.trim():"",r=typeof e.rolloutNotes=="string"&&e.rolloutNotes.trim()?e.rolloutNotes.trim():"",i=Ut(e.validationRefs);return{...t,...n?{diffSummary:n}:{},...o?{baselineCandidateId:o}:{},...r?{rolloutNotes:r}:{},...i.length>0?{validationRefs:i}:{}}}function qt(e){return{action:ge(e.action)??e.action,actor:typeof e.actor=="string"&&e.actor.trim()?e.actor.trim():null,notes:typeof e.notes=="string"&&e.notes.trim()?e.notes.trim():null,payload:C(e.payload),createdAt:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt.trim():new Date().toISOString()}}function Yt(e){let t=Math.max(0,Math.floor(e.sampleCount??0)),n=Math.max(0,Math.floor(e.successCount??0)),o=Math.max(0,Math.floor(e.failureCount??Math.max(t-n,0))),r=Math.max(0,Math.floor(e.regressionCount??0)),i=t>0?n/t:0,s=t>0?r/t:0,a=typeof e.score=="number"&&Number.isFinite(e.score)?e.score:Number((i-s).toFixed(4));return Ce({phase:W(e.phase)??e.phase,sampleCount:t,successCount:n,failureCount:o,regressionCount:r,successRate:i,regressionRate:s,avgLatencyMs:e.avgLatencyMs,avgCostUsd:e.avgCostUsd,score:a,staleReason:e.staleReason,notes:e.notes,summary:C(e.summary),lastObservedAt:e.lastObservedAt??new Date().toISOString(),updatedAt:e.updatedAt??new Date().toISOString()})}function ke(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 Gt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Wt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Kt(e){if(!e.eligibility?.length)return[...e.tools];let t=Wt(e.eligibility);return e.tools.filter(n=>{let o=ke(n);if(!o)return!1;let r=t.get(o);return!r||Gt(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 Xt(e){let t=Vt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Kt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>ke(l)===s);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Jt=["stop","aborted","timeout","cancelled","interrupted","error"],Qt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function xe(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Zt(e,t){return{...e,content:[...xe(e.content),...xe(t.content)]}}function en(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 tn(e){return new Set((e??Jt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?tn(t).has(e.trim().toLowerCase()):!1}function nn(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 V(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(c=>en(c));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),n=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let l of a.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&n.has(a.tool_call_id))),r=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&r.add(a.tool_call_id);let i=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...u}=a;u.content!=null&&u.content!==""&&i.push(u);continue}if(l.length<a.tool_calls.length){i.push({...a,tool_calls:l});continue}}i.push(a)}let s=[];for(let a of i){let l=s.length>0?s[s.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){s[s.length-1]=Zt(l,a);continue}s.push(a)}return s}function X(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Qt)delete o[r];return o}):[...e]}function J(e,t){let n=t?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function on(e,t){let n=V(e),o=X(n,t);return J(o,t)}function Ae(e,t){let n=t?.placeholderFunctionCallOutput??JSON.stringify({ok:!1,error:"Tool loop interrupted before function_call_output was provided."}),o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let d={...u};if(typeof d.id=="string"){let p=nn(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;a.add(u)}l.push(c)}for(let[c]of s)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function rn(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 sn(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 an(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 ln(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 ve(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function cn(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 un(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 dn(e){let t=[],n=V(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=X(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=J(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:ve({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:rn(r),completedToolCallIds:sn(r)}),recoveryActions:t}}function pn(e){let t=Ae(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:ve({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:an(t),completedToolCallIds:ln(t)}),recoveryActions:n}}import{MEMORY_OBSERVATION_HOOK_VALUES as mn,MEMORY_OBSERVATION_SOURCE_VALUES as fn,MEMORY_WRITE_ACCESS_VALUES as gn}from"qlogicagent-runtime-contracts";var yn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function hn(e){return e?yn.has(e):!0}function Cn(e){return e===429||e===529}function Tn(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 zo={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function bn(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Q=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var I={minIdleSeconds:7200,intervalSeconds:604800,staleAfterDays:30,archiveAfterDays:90,maxReviewBatchSize:50},Sn={lastRunAt:null,lastRunDurationSeconds:0,lastRunSummary:"",paused:!1,runCount:0};function kn(e){let t={...I,...e.policy};if(!e.enabled)return{shouldRun:!1,reason:"curator disabled"};if(e.state.paused)return{shouldRun:!1,reason:"curator paused by user"};if(e.idleSeconds<t.minIdleSeconds)return{shouldRun:!1,reason:`session not idle long enough (${e.idleSeconds}s < ${t.minIdleSeconds}s)`};if(e.state.lastRunAt){let n=(new Date(e.now).getTime()-new Date(e.state.lastRunAt).getTime())/1e3;if(n<t.intervalSeconds)return{shouldRun:!1,reason:`last run too recent (${Math.round(n)}s < ${t.intervalSeconds}s)`}}return{shouldRun:!0,reason:"all gates passed"}}function xn(e,t,n){let o={...I,...n},r=new Date(t).getTime(),i=[],s=0;for(let a of e){if(!a.agentCreated||(s++,a.pinned))continue;let l=a.lastActivityAt?new Date(a.lastActivityAt).getTime():new Date(a.createdAt).getTime(),c=(r-l)/(1e3*60*60*24);a.state==="active"&&c>=o.staleAfterDays?i.push({skillName:a.name,from:"active",to:"stale",reason:`inactive for ${Math.floor(c)} days (threshold: ${o.staleAfterDays})`}):a.state==="stale"&&c>=o.archiveAfterDays&&i.push({skillName:a.name,from:"stale",to:"archived",reason:`inactive for ${Math.floor(c)} days (threshold: ${o.archiveAfterDays})`}),(a.state==="stale"||a.state==="archived")&&a.useCount>0&&c<o.staleAfterDays&&i.push({skillName:a.name,from:a.state,to:"active",reason:"recent activity detected \u2014 reactivated"})}return{checked:s,transitions:i,markedStale:i.filter(a=>a.to==="stale").length,archived:i.filter(a=>a.to==="archived").length,reactivated:i.filter(a=>a.to==="active").length}}function Rn(e,t){let n={...I,...t};return e.filter(o=>o.agentCreated&&!o.pinned&&(o.state==="active"||o.state==="stale")).sort((o,r)=>o.useCount-r.useCount).slice(0,n.maxReviewBatchSize).map(o=>o.name)}function An(e,t=2){let n=new Map;for(let r of e){let i=r.indexOf("-");if(i<2)continue;let s=r.slice(0,i),a=n.get(s);a?a.push(r):n.set(s,[r])}let o=[];for(let[r,i]of n)i.length>=t&&o.push({prefix:r,skills:i.sort()});return o.sort((r,i)=>i.skills.length-r.skills.length)}function vn(e,t,n){let o=e.map(s=>`- **${s.name}** (${s.state}, uses: ${s.useCount}, tools: ${s.tools})${s.lastActivityAt?` last active: ${s.lastActivityAt}`:""}`).join(`
|
|
20
|
-
`),r=t.length>0?t.map(s=>`- ${s}`).join(`
|
|
21
|
-
`):"(none)";return`You are the Autonomous Curator for a skill library.
|
|
22
|
-
|
|
23
|
-
## Goal
|
|
24
|
-
|
|
25
|
-
Transform narrow, session-specific skills into a well-organized library of
|
|
26
|
-
class-level umbrella skills. A collection of hundreds of narrow skills is FAILURE.
|
|
27
|
-
|
|
28
|
-
## Ground Rules
|
|
29
|
-
|
|
30
|
-
1. **NEVER delete** \u2014 only archive (prune). Archived skills can be restored.
|
|
31
|
-
2. **Do NOT touch pinned or bundled skills** \u2014 they are already filtered out.
|
|
32
|
-
3. **Identify prefix clusters** and merge them into umbrella skills.
|
|
33
|
-
4. **Move session-specific details** into the umbrella's references/ folder.
|
|
34
|
-
5. **Preserve unique value** \u2014 only merge if the source is genuinely redundant
|
|
35
|
-
or a subset of the target.
|
|
36
|
-
|
|
37
|
-
## Detected Prefix Clusters
|
|
38
|
-
|
|
39
|
-
${n.length>0?n.map(s=>`- **${s.prefix}-***: ${s.skills.join(", ")}`).join(`
|
|
40
|
-
`):"(no clusters detected)"}
|
|
41
|
-
|
|
42
|
-
## Existing Umbrella Skills
|
|
43
|
-
|
|
44
|
-
${r}
|
|
45
|
-
|
|
46
|
-
## Candidate Skills for Review
|
|
47
|
-
|
|
48
|
-
${o}
|
|
49
|
-
|
|
50
|
-
## Required Output Format
|
|
51
|
-
|
|
52
|
-
Respond with EXACTLY this YAML block (no extra text outside the block):
|
|
53
|
-
|
|
54
|
-
\`\`\`yaml
|
|
55
|
-
consolidations:
|
|
56
|
-
- source: "skill-name-a"
|
|
57
|
-
target: "umbrella-skill"
|
|
58
|
-
reason: "subset of umbrella functionality"
|
|
59
|
-
- source: "skill-name-b"
|
|
60
|
-
target: "new-umbrella-name"
|
|
61
|
-
reason: "cluster merge"
|
|
62
|
-
|
|
63
|
-
prunings:
|
|
64
|
-
- skill: "skill-name-c"
|
|
65
|
-
reason: "trivial single-use, no ongoing value"
|
|
66
|
-
\`\`\`
|
|
67
|
-
|
|
68
|
-
If no consolidations or prunings are warranted, use empty lists.
|
|
69
|
-
Respond ONLY with the YAML block.`}function _n(e,t){let n=[],o=[],r=[],i=e.match(/```(?:yaml)?\s*\n([\s\S]*?)```/),s=i?i[1]:e,a=s.match(/consolidations:\s*\n((?:\s+-[\s\S]*?)?)(?=prunings:|$)/);if(a?.[1]){let c=a[1].matchAll(/- source:\s*"([^"]+)"\s*\n\s*target:\s*"([^"]+)"\s*\n\s*reason:\s*"([^"]+)"/g);for(let[,u,d,p]of c){if(!t.has(u)){r.push(u);continue}n.push({sourceSkill:u,targetUmbrella:d,targetExists:t.has(d),reason:p})}}let l=s.match(/prunings:\s*\n([\s\S]*?)$/);if(l?.[1]){let c=l[1].matchAll(/- skill:\s*"([^"]+)"\s*\n\s*reason:\s*"([^"]+)"/g);for(let[,u,d]of c){if(!t.has(u)){r.push(u);continue}o.push({skillName:u,reason:d})}}return{consolidations:n,prunings:o,hallucinations:r}}function wn(e,t){let n=[],o=[],r=[],i=new Set;for(let s of e.consolidations){if(!t.has(s.sourceSkill)){r.push({action:`consolidate ${s.sourceSkill} \u2192 ${s.targetUmbrella}`,reason:`source skill "${s.sourceSkill}" not found`});continue}if(i.has(s.sourceSkill)){r.push({action:`consolidate ${s.sourceSkill} \u2192 ${s.targetUmbrella}`,reason:`source skill "${s.sourceSkill}" already consolidated in this plan`});continue}if(s.sourceSkill===s.targetUmbrella){r.push({action:`consolidate ${s.sourceSkill} \u2192 ${s.targetUmbrella}`,reason:"source and target are the same skill"});continue}i.add(s.sourceSkill),n.push(s)}for(let s of e.prunings){if(!t.has(s.skillName)){r.push({action:`prune ${s.skillName}`,reason:`skill "${s.skillName}" not found`});continue}if(i.has(s.skillName)){r.push({action:`prune ${s.skillName}`,reason:`skill "${s.skillName}" is being consolidated, not pruned`});continue}o.push(s)}return{validConsolidations:n,validPrunings:o,rejected:r}}function Mn(e){let t=[];return t.push(`Curator run at ${e.runAt} (${e.durationSeconds.toFixed(1)}s)`),t.push(`Auto: ${e.autoTransitionsChecked} checked, ${e.autoMarkedStale} stale, ${e.autoArchived} archived, ${e.autoReactivated} reactivated`),t.push(`LLM: ${e.consolidationsAccepted} consolidated, ${e.pruningsAccepted} pruned, ${e.actionsRejected} rejected, ${e.hallucinations} hallucinated`),t.join("; ")}var P={blockCreationThreshold:.75,curatorReviewThreshold:.55,toolWeight:.6,titleWeight:.3,stepWeight:.1};function we(e,t){let n=new Set(e.map(s=>s.toLowerCase())),o=new Set(t.map(s=>s.toLowerCase()));if(n.size===0&&o.size===0)return 0;let r=0;for(let s of n)o.has(s)&&r++;let i=n.size+o.size-r;return i===0?0:r/i}function Me(e,t){let n=_e(e.toLowerCase()),o=_e(t.toLowerCase());if(n.size===0&&o.size===0||n.size===0||o.size===0)return 0;let r=0;for(let i of n)o.has(i)&&r++;return 2*r/(n.size+o.size)}function _e(e){let t=new Set,n=e.replace(/[^a-z0-9\u4e00-\u9fff]/g," ").trim();for(let o=0;o<n.length-1;o++)t.add(n.slice(o,o+2));return t}function Ee(e,t){if(e==null||t==null)return .5;if(e===0&&t===0)return 1;let n=Math.abs(e-t),o=Math.max(e,t);return 1-n/o}function Ie(e,t,n){let o={...P,...n},r=we(e.tools,t.tools),i=Me(e.title,t.title),s=Ee(e.stepCount,t.stepCount);return{overall:o.toolWeight*r+o.titleWeight*i+o.stepWeight*s,toolJaccard:r,titleSimilarity:i,stepProximity:s}}function En(e,t,n){let o={...P,...n},r=[];for(let i of t){if(i.skillKey===e.skillKey)continue;let s=Ie(e,i,o);s.overall>=o.curatorReviewThreshold&&r.push({existingSkillKey:i.skillKey,score:s})}return r.sort((i,s)=>s.score.overall-i.score.overall)}function In(e,t){let n={...P,...t};if(e.length===0)return{action:"create",reason:"no similar skills found"};let o=e[0];return o.score.overall>=n.blockCreationThreshold?{action:"improve",targetSkillKey:o.existingSkillKey,reason:`similarity ${(o.score.overall*100).toFixed(0)}% \u2265 creation threshold ${(n.blockCreationThreshold*100).toFixed(0)}% (tool overlap: ${(o.score.toolJaccard*100).toFixed(0)}%)`}:{action:"flag-for-review",targetSkillKey:o.existingSkillKey,reason:`similarity ${(o.score.overall*100).toFixed(0)}% between review and creation thresholds`}}var Pe={planner:3,executor:4,reviewer:2,researcher:3,custom:2},Pn={parallel:4,sequential:1,pipeline:1,adaptive:3},L=8,Ln=2;function On(e){let t=e.subtasks.slice(0,L).map(i=>{let s=Dn(i.role);return{agentId:i.id,role:i.role,label:i.label,sidechainType:Le(i.role),taskDescription:i.task,toolAccessMode:Oe(i.role),budgetTier:s,dependsOn:i.dependsOn??[],maxTokenBudget:0,maxToolCalls:Nn(i.role),timeoutMs:0}}),n=e.mode??De(t),o=e.totalTokenBudget??1e5,r=Ne(t,o);return{teamId:e.teamId,mode:n,aggregationPolicy:e.aggregationPolicy??Fe(n,t),agents:r,maxConcurrency:Pn[n],timeoutMs:e.timeoutMs??3e5,totalTokenBudget:o,failFast:e.failFast??n==="pipeline",sharedContext:e.sharedContext??"",mergePolicy:e.mergePolicy??"summary-only"}}function Le(e){switch(e){case"planner":return"planner";case"executor":return"code-repair";case"reviewer":return"research";case"researcher":return"research";case"custom":return"research"}}function Oe(e){switch(e){case"planner":return"none";case"executor":return"full";case"reviewer":return"read-only";case"researcher":return"read-only";case"custom":return"read-only"}}function Nn(e){switch(e){case"planner":return 0;case"executor":return 30;case"reviewer":return 10;case"researcher":return 15;case"custom":return 10}}function Dn(e){switch(e){case"planner":return"high";case"executor":return"high";case"reviewer":return"medium";case"researcher":return"medium";case"custom":return"low"}}function Ne(e,t){let n=e.reduce((o,r)=>o+Pe[r.role],0);return n===0?e:e.map(o=>({...o,maxTokenBudget:Math.floor(Pe[o.role]/n*t)}))}function De(e){return e.some(o=>o.dependsOn.length>0)?e.every((o,r)=>r===0?o.dependsOn.length===0:o.dependsOn.includes(e[r-1].agentId))?"pipeline":"sequential":"parallel"}function Fe(e,t){let n=t.some(r=>r.role==="reviewer"),o=t.some(r=>r.role==="planner");return n?"reviewer-gate":o&&e==="adaptive"?"planner-sync":e==="parallel"&&t.length>=3?"majority-vote":"merge-all"}function Fn(e){let t=new Set(e.map(l=>l.agentId)),n=new Map(e.map(l=>[l.agentId,l.dependsOn.filter(c=>t.has(c))])),o=new Set,r=[],i=new Set(t),s=0,a=e.length+1;for(;i.size>0&&s<a;){let l=[];for(let c of i)(n.get(c)??[]).every(d=>o.has(d))&&l.push(c);if(l.length===0){let c=i.values().next().value;c&&l.push(c)}for(let c of l)i.delete(c),o.add(c);r.push(l),s++}return r}function Bn(e,t){let n=e.filter(o=>o.status==="completed");switch(t){case"first-success":return n[0]?.output??"[No successful agent output]";case"majority-vote":if(n.length===0)return"[No successful agent output]";let o=new Map;for(let s of n){let a=s.output.trim();o.set(a,(o.get(a)??0)+1)}let r="",i=0;for(let[s,a]of o)a>i&&(r=s,i=a);return r||n[0].output;case"merge-all":return n.map(s=>`[${s.role}:${s.agentId}]
|
|
70
|
-
${s.output}`).join(`
|
|
71
|
-
|
|
72
|
-
---
|
|
73
|
-
|
|
74
|
-
`);case"reviewer-gate":{let s=n.find(l=>l.role==="reviewer"),a=n.filter(l=>l.role!=="reviewer");return s?`[Review]
|
|
75
|
-
${s.output}
|
|
76
|
-
|
|
77
|
-
[Execution]
|
|
78
|
-
${a.map(l=>l.output).join(`
|
|
79
|
-
`)}`:a.map(l=>l.output).join(`
|
|
80
|
-
|
|
81
|
-
`)}case"planner-sync":{let s=n.find(l=>l.role==="planner"),a=n.filter(l=>l.role!=="planner");return s?`[Plan]
|
|
82
|
-
${s.output}
|
|
83
|
-
|
|
84
|
-
[Results]
|
|
85
|
-
${a.map(l=>`- ${l.agentId}: ${l.output.slice(0,500)}`).join(`
|
|
86
|
-
`)}`:a.map(l=>l.output).join(`
|
|
87
|
-
|
|
88
|
-
`)}}}function $n(e){let t=[];e.agents.length===0&&t.push("Team plan has no agents"),e.agents.length>L&&t.push(`Too many agents: ${e.agents.length} > ${L}`),e.totalTokenBudget<=0&&t.push("Total token budget must be positive");let n=e.agents.map(r=>r.agentId),o=new Set(n);o.size!==n.length&&t.push("Duplicate agent IDs in team plan");for(let r of e.agents)for(let i of r.dependsOn)o.has(i)||t.push(`Agent "${r.agentId}" depends on non-existent agent "${i}"`),i===r.agentId&&t.push(`Agent "${r.agentId}" depends on itself`);if(e.mode==="pipeline")for(let r=1;r<e.agents.length;r++)e.agents[r].dependsOn.includes(e.agents[r-1].agentId)||t.push(`Pipeline mode requires linear dependencies; agent "${e.agents[r].agentId}" doesn't depend on previous`);return t}function jn(e){let{plan:t,results:n,elapsedMs:o}=e;return t.timeoutMs>0&&o>t.timeoutMs?{cancel:!0,reason:"team_timeout"}:t.failFast&&n.some(i=>i.status==="failed")?{cancel:!0,reason:"fail_fast"}:n.length>=t.agents.length?{cancel:!1,reason:""}:n.reduce((i,s)=>i+s.tokenUsage.prompt+s.tokenUsage.completion,0)>=t.totalTokenBudget*.95?{cancel:!0,reason:"budget_exhausted"}:{cancel:!1,reason:""}}function Un(e){let{agent:t,plan:n,dependencyResults:o}=e,r=[];if(n.sharedContext&&r.push(`[Shared Context]
|
|
89
|
-
${n.sharedContext}`),o.length>0){let i=o.filter(s=>s.status==="completed").map(s=>`[From ${s.agentId} (${s.role})]
|
|
90
|
-
${s.output}`).join(`
|
|
91
|
-
|
|
92
|
-
`);i&&r.push(`[Prior Results]
|
|
93
|
-
${i}`)}return r.push(`[Your Task]
|
|
94
|
-
${t.taskDescription}`),r.push(`[Your Role: ${t.role}]
|
|
95
|
-
${zn(t.role)}`),r.join(`
|
|
96
|
-
|
|
97
|
-
---
|
|
98
|
-
|
|
99
|
-
`)}function zn(e){switch(e){case"planner":return"You are the planner. Break down the task, identify dependencies, and create a clear execution plan. Do NOT execute actions yourself.";case"executor":return"You are the executor. Follow the plan and use tools to accomplish the task. Report what you did and any issues encountered.";case"reviewer":return"You are the reviewer. Examine the execution results for correctness, completeness, and quality. Point out any issues or improvements needed.";case"researcher":return"You are the researcher. Gather information, search for relevant context, and provide evidence-based findings. Do NOT modify any files.";case"custom":return"Complete the assigned task to the best of your ability."}}var Z="<fork-child-context>",Be="Fork started \u2014 processing in background",Hn=4,qn=2;function Yn(e){return JSON.stringify(e).includes(Z)}function Gn(e,t="in-memory"){return e<(t==="in-memory"?4:2)}function Wn(e,t){let n=[...e.parentMessages],o={role:"user",content:[{type:"text",text:`${Z}
|
|
19
|
+
${m}`}))}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=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 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(m=>m&&typeof m=="object"&&m.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 Tt(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 Ct(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:Tt(t),completedToolCallIds:Ct(t)}),recoveryActions:n}}var xt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function St(e){return e?xt.has(e):!0}function At(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 yn={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 z="<fork-child-context>",le="Fork started \u2014 processing in background",wt=4;function Et(e){return JSON.stringify(e).includes(z)}function It(e){return e<4}function Lt(e,t){let n=[...e.parentMessages],o={role:"user",content:[{type:"text",text:`${z}
|
|
100
20
|
|
|
101
21
|
You are the "${t.agent.name}" agent.
|
|
102
22
|
|
|
103
|
-
${t.taskPrompt}`}]};return n.push(o),n}function
|
|
23
|
+
${t.taskPrompt}`}]};return n.push(o),n}function Ot(e){return e.map(t=>({role:"tool",tool_call_id:t,content:le}))}function Pt(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 Ft(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Nt={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},Dt={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},Bt={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","todo","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},$t={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},U=[Nt,Dt,Bt,jt,$t,qt];function Gt(){return[...U]}function zt(e){return U.find(t=>t.name===e)}function Ut(e){return U.some(t=>t.name===e)}function Ht(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 Yt=new Set(["agent_tool","team_create","fork_agent","send_message"]);function Wt(e,t){switch(e){case"worker":return t.filter(n=>!Yt.has(n));case"coordinator":return[...t];default:return[...t]}}function Kt(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Jt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Vt(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 Xt(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"}:{action:"abort",reason:o||"unknown_error"}}function Qt(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 Zt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var en={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function tn(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
|
|
104
24
|
${n.join(`
|
|
105
25
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
106
26
|
Step ${e.activeSkillContext.step}:
|
|
@@ -111,15 +31,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
111
31
|
|
|
112
32
|
${t.join(`
|
|
113
33
|
|
|
114
|
-
`)}`}function
|
|
115
|
-
${s.result.output||"(no output)"}`);return{ok:r,output:i.join(`
|
|
116
|
-
|
|
117
|
-
---
|
|
118
|
-
|
|
119
|
-
`),agentResults:e,totalTokensUsed:n,finalState:r?"completed":"failed"}}case"reviewer-gate":{let i=e.find(l=>l.role==="reviewer"),a=e.filter(l=>l.role!=="reviewer").map(l=>l.result.output).filter(Boolean).join(`
|
|
120
|
-
|
|
121
|
-
`);return i&&i.result.ok?{ok:!0,output:`## Reviewed Output
|
|
122
|
-
${a}
|
|
123
|
-
|
|
124
|
-
## Review
|
|
125
|
-
${i.result.output}`,agentResults:e,totalTokensUsed:n,finalState:"completed"}:{ok:!1,output:`Review failed: ${i?.result.output||"no reviewer result"}`,agentResults:e,totalTokensUsed:n,finalState:"failed"}}case"planner-sync":{let i=e.find(s=>s.role==="planner");return i?{ok:i.result.ok,output:i.result.output,agentResults:e,totalTokensUsed:n,finalState:i.result.ok?"completed":"failed"}:te(e,"merge-all")}default:return te(e,"merge-all")}}function So(e,t){return e.agents.map(n=>{let o=t(n.agentType);if(!o)throw new Error(`Unknown agent type "${n.agentType}" in team request`);return{agentDef:o,prompt:n.prompt,maxTurns:n.maxTurns,role:n.role}})}var ko=["research","planner","plan-repair","code-repair","media-prep"],je={research:{type:"research",label:"Research",description:"Independent retrieval or evidence gathering branches.",mergePolicy:"summary-only",budgetTier:"medium",budgetWeight:2,preferFullContext:!1,preserveConversationHistory:!0,toolAccessMode:"read-only"},planner:{type:"planner",label:"Planner",description:"Planning and tool orchestration branches that may return structured context.",mergePolicy:"append-messages",budgetTier:"high",budgetWeight:3,preferFullContext:!0,preserveConversationHistory:!0,toolAccessMode:"none"},"plan-repair":{type:"plan-repair",label:"Plan Repair",description:"Failure repair or fallback branches that re-plan tool choice, ordering, or approval strategy.",mergePolicy:"replace-context",budgetTier:"medium",budgetWeight:2,preferFullContext:!0,preserveConversationHistory:!1,toolAccessMode:"none"},"code-repair":{type:"code-repair",label:"Code Repair",description:"Recovery branches focused on file edits, patch validation, or workspace mutation repair.",mergePolicy:"replace-context",budgetTier:"high",budgetWeight:3,preferFullContext:!0,preserveConversationHistory:!1,toolAccessMode:"full"},"media-prep":{type:"media-prep",label:"Media Prep",description:"Preparation branches for media generation, normalization, or staging.",mergePolicy:"summary-only",budgetTier:"low",budgetWeight:1,preferFullContext:!1,preserveConversationHistory:!1,toolAccessMode:"read-only"}},ne=["gateway","agents_list","whatsapp_login","session_status","cron","memory_query","sessions_send"],xo=["sessions_list","sessions_history","sessions_spawn"],$e=["file_edit","create_file","replace_string_in_file","multi_replace_string_in_file","create_directory","run_in_terminal","run_command","delete_file","rename_file","move_file","git_commit","git_push","manage_todo_list"];function Ro(e={}){let t=Math.max(1,Math.floor(e.maxDepth??2)),n=typeof e.depth=="number"&&Number.isFinite(e.depth)?Math.max(0,Math.floor(e.depth)):t,o=e.role?e.role==="leaf":n>=t,r=o?[...ne,...xo]:[...ne],i=new Set(r),s=Array.isArray(e.toolNames)?e.toolNames:e.toolNames?Array.from(e.toolNames):[],a=Array.from(new Set(s.map(l=>l.trim()).filter(Boolean))).map(l=>{let c=i.has(l);return{toolName:l,decision:c?"denied":"allowed",inheritance:c?"shrink":"inherit",reason:c?ne.includes(l)?"always-deny":"leaf-deny":"default-allow"}});return{deniedTools:r,canSpawnChildren:!o,defaultDecision:"allowed",defaultInheritance:"inherit",tools:a}}function er(e){let t=Ue(e.type),n=Ro({depth:e.depth,maxDepth:e.maxDepth,role:e.role,toolNames:e.toolNames});if(t.toolAccessMode==="full")return n;if(t.toolAccessMode==="none"){let i=Array.isArray(e.toolNames)?e.toolNames:e.toolNames?Array.from(e.toolNames):[],s=[...new Set(i.map(a=>a.trim()).filter(Boolean))];return{deniedTools:s,canSpawnChildren:!1,defaultDecision:"allowed",defaultInheritance:"inherit",tools:s.map(a=>({toolName:a,decision:"denied",inheritance:"shrink",reason:"always-deny"}))}}let o=new Set($e),r=[...new Set([...n.deniedTools,...$e])];return{...n,deniedTools:r,tools:n.tools.map(i=>i.decision==="denied"?i:o.has(i.toolName)?{...i,decision:"denied",inheritance:"shrink",reason:"always-deny"}:i)}}function tr(e,t){let n=new Set(t.deniedTools),o=new Map(t.tools.map(s=>[s.toolName,s])),r=[],i=[];for(let s of e){let a=s.function.name,l=o.get(a);l?.decision==="denied"?i.push({toolCall:s,reason:`tool "${a}" denied by sidechain policy: ${l.reason}`}):n.has(a)?i.push({toolCall:s,reason:`tool "${a}" is in sidechain deny list`}):r.push(s)}return{allowed:r,denied:i}}function nr(){return ko.map(e=>je[e])}function Ue(e){return je[e]}function or(e={}){if(e.preferCodeRepair)return"code-repair";let t=typeof e.trigger=="string"?e.trigger.trim().toLowerCase():"";if(t.includes("code")||t.includes("patch")||t.includes("workspace"))return"code-repair";let n=Array.from(e.toolNames??[]).map(r=>r.trim().toLowerCase()).filter(Boolean),o=["code","edit","patch","diff","file","workspace","git","terminal"];return n.some(r=>o.some(i=>r.includes(i)))?"code-repair":"plan-repair"}function rr(e,t={}){let n=Ue(e);return Ao({forceManualReview:t.forceManualReview,preferFullContext:t.preferFullContext??n.preferFullContext,preserveConversationHistory:t.preserveConversationHistory??n.preserveConversationHistory})}function Ao(e={}){return e.forceManualReview?"manual":e.preferFullContext?e.preserveConversationHistory?"append-messages":"replace-context":"summary-only"}export{U as CacheAwareCompressionStrategy,z as CompressionMetricsCollector,H as ContextEngineRegistry,de as DEFAULT_ADAPTIVE_BUDGET_CONFIG,I as DEFAULT_CURATOR_SCHEDULE_POLICY,P as DEFAULT_SKILL_SIMILARITY_POLICY,Be as FORK_PLACEHOLDER_RESULT,Z as FORK_SENTINEL_TAG,Q as FallbackTriggeredError,$ as HeadTailProtectedStrategy,Sn as INITIAL_CURATOR_STATE,j as IncrementalCompactStrategy,Hn as MAX_FORK_DEPTH,qn as MAX_SIDECHAIN_DB_DEPTH,mn as MEMORY_OBSERVATION_HOOK_VALUES,fn as MEMORY_OBSERVATION_SOURCE_VALUES,gn as MEMORY_WRITE_ACCESS_VALUES,q as MicroCompactStrategy,ne as SIDECHAIN_TOOL_DENY_ALWAYS,xo as SIDECHAIN_TOOL_DENY_LEAF,$e as SIDECHAIN_TOOL_DENY_WRITE,ko as SIDECHAIN_TYPE_VALUES,D as SlidingWindowStrategy,F as SummarizeOldStrategy,L as TEAM_MAX_AGENTS,Ln as TEAM_MAX_DEPTH,B as ToolResultTrimStrategy,cn as advanceToolLoopState,Bn as aggregateTeamResults,te as aggregateTeamToolResults,Ne as allocateTokenBudgets,It as applyContextCollapsesIfNeeded,Xt as applyToolChoicePolicy,Me as bigramSimilarity,Un as buildAgentTaskPrompt,ze as buildAssistantToolCallMessage,vn as buildConsolidationPrompt,Mn as buildCuratorRunSummary,Kn as buildForkPlaceholderResults,Wn as buildForkedMessages,ho as buildPostCompactRestorationMessage,Yt as buildSkillCandidateEffectivenessSummary,Se as buildSkillCandidateEvidencePayload,Ht as buildSkillCandidateImprovementEvidenceBundle,qt as buildSkillCandidateLatestReview,Dt as buildSkillInstruction,G as buildStructuredSummaryPrompt,He as buildToolResultMessage,po as calculateTokenWarningState,Gn as canForkAtDepth,Tt as classifyError,xt as composeAsyncStrategies,kt as composeStrategies,Rt as computeAdaptiveBudget,xn as computeLifecycleTransitions,Tn as computeRetryBackoff,Ie as computeSimilarity,Et as createCollapseStore,zt as createDefaultSkillImprovementPolicy,Co as createReactiveCompactState,co as createTaskState,uo as createTurnLoopGuardState,In as decideSimilarityAction,An as detectPrefixClusters,tr as filterToolCallsByAccessPolicy,lo as filterToolsByRole,En as findSimilarSkills,Xn as generateForkChildAgentId,ro as getBuiltInAgent,oo as getBuiltInAgents,bt as getRetryStrategy,Fe as inferAggregationPolicy,De as inferExecutionMode,Y as isAsyncCompressionStrategy,io as isBuiltInAgent,hn as isForegroundSource,Yn as isInForkChild,bn as isPersistentRetryEnabled,Cn as isTransientCapacityError,nr as listSidechainTypePolicies,Le as mapRoleToSidechainType,So as mapTeamRequestToForkConfigs,be as normalizeSkillImprovementPolicy,_n as parseConsolidationOutput,wt as postCompactFileRecovery,wn as reconcileConsolidationPlan,Pt as recoverContextCollapseFromOverflow,dn as recoverToolLoopStateFromChatConversation,pn as recoverToolLoopStateFromResponsesItems,on as repairOpenAiChatConversation,Oe as resolveAgentToolAccess,so as resolveAgentToolSet,mo as resolveApiErrorRecovery,Fn as resolveExecutionOrder,Vn as resolveForkChildTools,fo as resolveOutputTokenEscalation,or as resolveRepairSidechainType,Ao as resolveSidechainMergePolicy,rr as resolveSidechainMergePolicyByType,er as resolveSidechainToolAccessByType,Ro as resolveSidechainToolAccessPolicy,Ue as resolveSidechainTypePolicy,bo as resolveTeamExecutionPlan,On as resolveTeamPlan,At as selectCompressionTier,Rn as selectReviewCandidates,un as settleToolLoopState,go as shouldAbortTurn,To as shouldAttemptReactiveCompact,jn as shouldCancelTeam,kn as shouldRunCurator,Mt as snipCompactIfNeeded,Ee as stepCountProximity,we as toolSetJaccard,$n as validateTeamPlan};
|
|
34
|
+
`)}`}function nn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function on(e,t=en){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{O as CacheAwareCompressionStrategy,P as CompressionMetricsCollector,F as ContextEngineRegistry,Z as DEFAULT_ADAPTIVE_BUDGET_CONFIG,le as FORK_PLACEHOLDER_RESULT,z as FORK_SENTINEL_TAG,G as FallbackTriggeredError,I as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,wt as MAX_FORK_DEPTH,N as MicroCompactStrategy,M as SlidingWindowStrategy,w as SummarizeOldStrategy,E as ToolResultTrimStrategy,bt as advanceToolLoopState,Qe as applyContextCollapsesIfNeeded,lt as applyToolChoicePolicy,ce as buildAssistantToolCallMessage,Ot as buildForkPlaceholderResults,Lt as buildForkedMessages,tn as buildPostCompactRestorationMessage,ot as buildSkillInstruction,B as buildStructuredSummaryPrompt,ue as buildToolResultMessage,Vt as calculateTokenWarningState,It as canForkAtDepth,$e as classifyError,Ue as composeAsyncStrategies,ze as composeStrategies,He as computeAdaptiveBudget,vt as computeRetryBackoff,Xe as createCollapseStore,nn as createReactiveCompactState,Kt as createTaskState,Jt as createTurnLoopGuardState,Wt as filterToolsByRole,Ft as generateForkChildAgentId,zt as getBuiltInAgent,Gt as getBuiltInAgents,qe as getRetryStrategy,D as isAsyncCompressionStrategy,Ut as isBuiltInAgent,St as isForegroundSource,Et as isInForkChild,Mt as isPersistentRetryEnabled,At as isTransientCapacityError,Je as postCompactFileRecovery,Ze as recoverContextCollapseFromOverflow,_t as recoverToolLoopStateFromChatConversation,Rt as recoverToolLoopStateFromResponsesItems,gt as repairOpenAiChatConversation,Ht as resolveAgentToolSet,Xt as resolveApiErrorRecovery,Pt as resolveForkChildTools,Qt as resolveOutputTokenEscalation,Ye as selectCompressionTier,kt as settleToolLoopState,Zt as shouldAbortTurn,on as shouldAttemptReactiveCompact,Ve as snipCompactIfNeeded};
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* - Top-level error handling
|
|
8
8
|
*
|
|
9
9
|
* The actual tool loop state machine (turn-loop-guard, tool-loop-state,
|
|
10
|
-
* parallel scheduling,
|
|
10
|
+
* parallel scheduling, tool filtering, etc.) lives in tool-loop.ts,
|
|
11
11
|
* ported faithfully from Hub's semantic-turn-tools.ts.
|
|
12
12
|
*
|
|
13
13
|
* Zero imports from express/pg/ioredis/ws.
|
|
@@ -18,8 +18,6 @@ export declare const MAX_TOOL_BUDGET_CAP = 100;
|
|
|
18
18
|
export declare const DEFAULT_TOOL_BUDGET: number;
|
|
19
19
|
/** Max consecutive tool call failures before early exit. */
|
|
20
20
|
export declare const MAX_CONSECUTIVE_FAILURES = 3;
|
|
21
|
-
/** Max sidechain recursion depth (0 = top-level, 2 = max nesting). */
|
|
22
|
-
export declare const MAX_SIDECHAIN_DEPTH = 2;
|
|
23
21
|
/** Default context window size (tokens). Used when model-specific size unknown. */
|
|
24
22
|
export declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 128000;
|
|
25
23
|
/** Reserved tokens for model response output in turn-loop-guard budget check. */
|
|
@@ -36,6 +34,8 @@ export declare const ESCALATED_MAX_OUTPUT_TOKENS = 65536;
|
|
|
36
34
|
export declare const HEARTBEAT_INTERVAL_MS = 30000;
|
|
37
35
|
/** Max consecutive 529 errors before fallback model switch (CC: 3). */
|
|
38
36
|
export declare const MAX_529_RETRIES = 3;
|
|
37
|
+
/** Max consecutive API error retries before aborting (prevents infinite retry loops). */
|
|
38
|
+
export declare const MAX_API_RETRIES = 5;
|
|
39
39
|
/** Per-tool result size threshold (chars). Results exceeding this are persisted to disk
|
|
40
40
|
* and replaced with a preview reference (CC: DEFAULT_MAX_RESULT_SIZE_CHARS = 50_000). */
|
|
41
41
|
export declare const DEFAULT_MAX_RESULT_SIZE_CHARS = 50000;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool access constants for sub-agent tool filtering.
|
|
3
|
+
*
|
|
4
|
+
* CC-aligned: constants/tools.ts pattern.
|
|
5
|
+
* Tool filtering happens at agent SPAWN time (not per-iteration in tool loop).
|
|
6
|
+
*
|
|
7
|
+
* CC reference: claude-code-haha/src/constants/tools.ts
|
|
8
|
+
* CC reference: claude-code-haha/src/tools/AgentTool/agentToolUtils.ts
|
|
9
|
+
*/
|
|
10
|
+
import type { ToolDefinition } from "./types.js";
|
|
11
|
+
/**
|
|
12
|
+
* Tools that ALL sub-agents are forbidden from using.
|
|
13
|
+
* CC: ALL_AGENT_DISALLOWED_TOOLS
|
|
14
|
+
*/
|
|
15
|
+
export declare const AGENT_DISALLOWED_TOOLS: Set<string>;
|
|
16
|
+
/**
|
|
17
|
+
* Additional tools denied for custom (user-defined) agents.
|
|
18
|
+
* CC: CUSTOM_AGENT_DISALLOWED_TOOLS
|
|
19
|
+
*/
|
|
20
|
+
export declare const CUSTOM_AGENT_DISALLOWED_TOOLS: Set<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Filter tools available to a sub-agent.
|
|
23
|
+
*
|
|
24
|
+
* CC pattern: tool filtering happens at agent SPAWN time,
|
|
25
|
+
* not per-iteration inside the tool loop.
|
|
26
|
+
*
|
|
27
|
+
* @param tools - Parent's full tool pool
|
|
28
|
+
* @param isBuiltIn - Whether the agent is a built-in agent type (vs custom)
|
|
29
|
+
*/
|
|
30
|
+
export declare function filterToolsForAgent(tools: ToolDefinition[], isBuiltIn: boolean): ToolDefinition[];
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* - Media error recovery: image/media errors → reactive compact retry
|
|
12
12
|
* - Hermes delta suppression preserved
|
|
13
13
|
* - StreamingToolExecutor preserved
|
|
14
|
-
* -
|
|
14
|
+
* - Sub-agent fork depth preserved
|
|
15
15
|
* - Skill learning evaluation preserved
|
|
16
16
|
*
|
|
17
17
|
* CC reference: src/query.ts queryLoop()
|
|
@@ -37,10 +37,8 @@ export interface ToolLoopParams {
|
|
|
37
37
|
modelMaxOutputTokens?: number;
|
|
38
38
|
/** Tool choice strategy (default "auto") */
|
|
39
39
|
toolChoice?: "auto" | "none" | "required";
|
|
40
|
-
/** Parent
|
|
40
|
+
/** Parent fork depth (0 = top-level) */
|
|
41
41
|
parentDepth?: number;
|
|
42
|
-
/** Sidechain type for tool access policy (default "code-repair" = full access) */
|
|
43
|
-
sidechainType?: import("../orchestration/index.js").SidechainType;
|
|
44
42
|
/** Tool eligibility context for policy-based filtering */
|
|
45
43
|
toolEligibilityContext?: import("../runtime/execution/tool-eligibility.js").ToolEligibilityContext;
|
|
46
44
|
/** Hook registry for lifecycle events (optional, fire-and-forget) */
|
|
@@ -141,10 +141,8 @@ export interface TurnConfig {
|
|
|
141
141
|
modelMaxOutputTokens?: number;
|
|
142
142
|
/** Tool choice strategy: "auto" (default), "none", "required" */
|
|
143
143
|
toolChoice?: "auto" | "none" | "required";
|
|
144
|
-
/** Parent
|
|
144
|
+
/** Parent fork depth (0 = top-level, default 0). CC: depth tracking for fork recursion limit. */
|
|
145
145
|
parentDepth?: number;
|
|
146
|
-
/** Sidechain type for tool access policy (default "code-repair" = full access) */
|
|
147
|
-
sidechainType?: import("../orchestration/index.js").SidechainType;
|
|
148
146
|
/** Per-turn token budget (prompt + completion). 0 or undefined = unlimited. */
|
|
149
147
|
tokenBudget?: number;
|
|
150
148
|
/** Fallback model to switch to after repeated 529 errors (CC parity). */
|
|
@@ -192,16 +190,7 @@ export type TurnEvent = {
|
|
|
192
190
|
name: string;
|
|
193
191
|
ok: boolean;
|
|
194
192
|
error?: string;
|
|
195
|
-
|
|
196
|
-
type: "sidechain_started";
|
|
197
|
-
turnId: string;
|
|
198
|
-
depth: number;
|
|
199
|
-
role: "orchestrator" | "leaf";
|
|
200
|
-
} | {
|
|
201
|
-
type: "sidechain_completed";
|
|
202
|
-
turnId: string;
|
|
203
|
-
depth: number;
|
|
204
|
-
toolCallCount: number;
|
|
193
|
+
outputPreview?: string;
|
|
205
194
|
} | {
|
|
206
195
|
type: "tool_blocked";
|
|
207
196
|
turnId: string;
|
|
@@ -226,6 +215,55 @@ export type TurnEvent = {
|
|
|
226
215
|
type: "tool_use_summary";
|
|
227
216
|
turnId: string;
|
|
228
217
|
summary: string;
|
|
218
|
+
} | {
|
|
219
|
+
type: "reasoning_delta";
|
|
220
|
+
turnId: string;
|
|
221
|
+
text: string;
|
|
222
|
+
} | {
|
|
223
|
+
type: "suggestions";
|
|
224
|
+
turnId: string;
|
|
225
|
+
items: Array<{
|
|
226
|
+
text: string;
|
|
227
|
+
icon?: string;
|
|
228
|
+
action?: string;
|
|
229
|
+
}>;
|
|
230
|
+
} | {
|
|
231
|
+
type: "media_result";
|
|
232
|
+
turnId: string;
|
|
233
|
+
mediaType: "image" | "tts" | "video";
|
|
234
|
+
url: string;
|
|
235
|
+
model?: string;
|
|
236
|
+
provider?: string;
|
|
237
|
+
durationSeconds?: number;
|
|
238
|
+
width?: number;
|
|
239
|
+
height?: number;
|
|
240
|
+
mimeType?: string;
|
|
241
|
+
billingUnit?: string;
|
|
242
|
+
billingQuantity?: number;
|
|
243
|
+
} | {
|
|
244
|
+
type: "artifact";
|
|
245
|
+
turnId: string;
|
|
246
|
+
artifactId: string;
|
|
247
|
+
artifactType: "code" | "file" | "image" | "document" | "diagram" | "table";
|
|
248
|
+
title: string;
|
|
249
|
+
filePath?: string;
|
|
250
|
+
language?: string;
|
|
251
|
+
content?: string;
|
|
252
|
+
mimeType?: string;
|
|
253
|
+
} | {
|
|
254
|
+
type: "subagent_started";
|
|
255
|
+
turnId: string;
|
|
256
|
+
subagentId: string;
|
|
257
|
+
agentType: string;
|
|
258
|
+
prompt?: string;
|
|
259
|
+
} | {
|
|
260
|
+
type: "subagent_ended";
|
|
261
|
+
turnId: string;
|
|
262
|
+
subagentId: string;
|
|
263
|
+
agentType: string;
|
|
264
|
+
ok: boolean;
|
|
265
|
+
outputPreview?: string;
|
|
266
|
+
error?: string;
|
|
229
267
|
};
|
|
230
268
|
/**
|
|
231
269
|
* ToolInvoker: request tool execution from the host process (Gateway).
|
package/dist/types/cli/main.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
1
|
/**
|
|
3
2
|
* qlogicagent CLI — Agent subprocess entry point.
|
|
4
3
|
*
|
|
5
|
-
* Communicates with
|
|
6
|
-
*
|
|
4
|
+
* Communicates with host applications via JSON-RPC over pluggable transports.
|
|
5
|
+
* Default transport: line-delimited JSON over stdin/stdout.
|
|
6
|
+
* All log/debug output goes to stderr (never pollutes the protocol).
|
|
7
7
|
*
|
|
8
8
|
* Usage:
|
|
9
9
|
* qlogicagent [--verbose]
|