qlogicagent 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +1 -0
- package/dist/cli.js +9 -0
- package/dist/contracts.js +1 -0
- package/dist/index.js +5 -15
- package/dist/orchestration.js +118 -0
- package/package.json +56 -42
- package/dist/agent/agent.js +0 -113
- package/dist/agent/tool-loop.js +0 -575
- package/dist/agent/types.js +0 -14
- package/dist/cli/main.js +0 -23
- package/dist/cli/stdio-server.js +0 -463
- package/dist/config/config.js +0 -21
- package/dist/contracts/hooks.js +0 -7
- package/dist/contracts/index.js +0 -10
- package/dist/contracts/planner.js +0 -2
- package/dist/contracts/skill-candidate.js +0 -195
- package/dist/contracts/todo.js +0 -9
- package/dist/llm/builtin-providers.js +0 -531
- package/dist/llm/index.js +0 -14
- package/dist/llm/llm-client.js +0 -67
- package/dist/llm/model-catalog.js +0 -191
- package/dist/llm/provider-def.js +0 -12
- package/dist/llm/provider-registry.js +0 -147
- package/dist/llm/transport.js +0 -27
- package/dist/llm/transports/anthropic-messages.js +0 -293
- package/dist/llm/transports/openai-chat.js +0 -165
- package/dist/orchestration/agent-registry.js +0 -116
- package/dist/orchestration/approval-aware-tool-plan.js +0 -87
- package/dist/orchestration/context-compression.js +0 -583
- package/dist/orchestration/conversation-repair.js +0 -429
- package/dist/orchestration/curator-scheduler.js +0 -135
- package/dist/orchestration/embedded-failover-policy.js +0 -168
- package/dist/orchestration/error-classification.js +0 -77
- package/dist/orchestration/failover-classification.js +0 -381
- package/dist/orchestration/failover-error.js +0 -198
- package/dist/orchestration/fork-subagent.js +0 -98
- package/dist/orchestration/index.js +0 -267
- package/dist/orchestration/memory-flush-policy.js +0 -85
- package/dist/orchestration/memory-provider.js +0 -2
- package/dist/orchestration/parallel-tool-calls.js +0 -59
- package/dist/orchestration/prompt-cache-strategy.js +0 -228
- package/dist/orchestration/reactive-compact.js +0 -78
- package/dist/orchestration/retry-loop.js +0 -24
- package/dist/orchestration/skill-candidate.js +0 -141
- package/dist/orchestration/skill-consolidation.js +0 -220
- package/dist/orchestration/skill-improvement.js +0 -66
- package/dist/orchestration/skill-similarity.js +0 -131
- package/dist/orchestration/streaming-tool-executor.js +0 -96
- package/dist/orchestration/team-orchestration.js +0 -369
- package/dist/orchestration/team-tool-loop-wiring.js +0 -147
- package/dist/orchestration/tool-choice-policy.js +0 -164
- package/dist/orchestration/tool-loop-state.js +0 -133
- package/dist/orchestration/tool-schema.js +0 -297
- package/dist/orchestration/transcript-repair.js +0 -426
- package/dist/orchestration/turn-loop-guard.js +0 -92
- package/dist/orchestration/web-browser-policy.js +0 -39
- package/dist/runtime/context-compression.js +0 -274
- package/dist/runtime/hook-registry.js +0 -53
- package/dist/runtime/memory-hooks.js +0 -65
- package/dist/runtime/tool-eligibility.js +0 -111
- package/dist/skills/index.js +0 -82
- package/dist/skills/memory-extractor.js +0 -173
- package/dist/skills/memory-query-tool.js +0 -127
- package/dist/skills/memory-store.js +0 -228
- package/dist/skills/memory-tool.js +0 -192
- package/dist/skills/portable-tool.js +0 -14
- package/dist/skills/qmemory-adapter.js +0 -165
- package/dist/skills/skill-frontmatter.js +0 -344
- package/dist/skills/skill-guard.js +0 -229
- package/dist/skills/skill-loader.js +0 -303
- package/dist/skills/skill-source.js +0 -126
- package/dist/skills/skill-types.js +0 -6
- package/dist/skills/think-tool.js +0 -59
- package/dist/skills/todo-tool.js +0 -114
- package/dist/skills/tools/agent-tool.js +0 -142
- package/dist/skills/tools/apply-patch-tool.js +0 -184
- package/dist/skills/tools/ask-user-tool.js +0 -121
- package/dist/skills/tools/brief-tool.js +0 -95
- package/dist/skills/tools/browser-tool.js +0 -155
- package/dist/skills/tools/checkpoint-tool.js +0 -102
- package/dist/skills/tools/config-tool.js +0 -143
- package/dist/skills/tools/cron-tool.js +0 -175
- package/dist/skills/tools/edit-tool.js +0 -70
- package/dist/skills/tools/exec-tool.js +0 -133
- package/dist/skills/tools/image-generate-tool.js +0 -67
- package/dist/skills/tools/instructions-tool.js +0 -187
- package/dist/skills/tools/lsp-tool.js +0 -227
- package/dist/skills/tools/mcp-client-types.js +0 -53
- package/dist/skills/tools/mcp-tool.js +0 -503
- package/dist/skills/tools/memory-tool.js +0 -88
- package/dist/skills/tools/monitor-tool.js +0 -131
- package/dist/skills/tools/music-generate-tool.js +0 -62
- package/dist/skills/tools/notify-tool.js +0 -62
- package/dist/skills/tools/patch-tool.js +0 -505
- package/dist/skills/tools/pdf-tool.js +0 -88
- package/dist/skills/tools/plan-mode-tool.js +0 -122
- package/dist/skills/tools/read-tool.js +0 -84
- package/dist/skills/tools/repl-tool.js +0 -69
- package/dist/skills/tools/search-tool.js +0 -225
- package/dist/skills/tools/send-message-tool.js +0 -76
- package/dist/skills/tools/skill-list-tool.js +0 -54
- package/dist/skills/tools/skill-manage-tool.js +0 -153
- package/dist/skills/tools/skill-view-tool.js +0 -72
- package/dist/skills/tools/sleep-tool.js +0 -81
- package/dist/skills/tools/structured-output-tool.js +0 -176
- package/dist/skills/tools/task-tool.js +0 -161
- package/dist/skills/tools/team-tool.js +0 -105
- package/dist/skills/tools/tool-search-tool.js +0 -110
- package/dist/skills/tools/tts-tool.js +0 -45
- package/dist/skills/tools/video-edit-tool.js +0 -74
- package/dist/skills/tools/video-generate-tool.js +0 -66
- package/dist/skills/tools/video-merge-tool.js +0 -92
- package/dist/skills/tools/video-upscale-tool.js +0 -52
- package/dist/skills/tools/web-fetch-tool.js +0 -92
- package/dist/skills/tools/web-search-tool.js +0 -86
- package/dist/skills/tools/worktree-tool.js +0 -147
- package/dist/skills/tools/write-tool.js +0 -81
- /package/dist/{agent → types/agent}/agent.d.ts +0 -0
- /package/dist/{agent → types/agent}/tool-loop.d.ts +0 -0
- /package/dist/{agent → types/agent}/types.d.ts +0 -0
- /package/dist/{cli → types/cli}/main.d.ts +0 -0
- /package/dist/{cli → types/cli}/stdio-server.d.ts +0 -0
- /package/dist/{config → types/config}/config.d.ts +0 -0
- /package/dist/{contracts → types/contracts}/hooks.d.ts +0 -0
- /package/dist/{contracts → types/contracts}/index.d.ts +0 -0
- /package/dist/{contracts → types/contracts}/planner.d.ts +0 -0
- /package/dist/{contracts → types/contracts}/skill-candidate.d.ts +0 -0
- /package/dist/{contracts → types/contracts}/todo.d.ts +0 -0
- /package/dist/{index.d.ts → types/index.d.ts} +0 -0
- /package/dist/{llm → types/llm}/builtin-providers.d.ts +0 -0
- /package/dist/{llm → types/llm}/index.d.ts +0 -0
- /package/dist/{llm → types/llm}/llm-client.d.ts +0 -0
- /package/dist/{llm → types/llm}/model-catalog.d.ts +0 -0
- /package/dist/{llm → types/llm}/provider-def.d.ts +0 -0
- /package/dist/{llm → types/llm}/provider-registry.d.ts +0 -0
- /package/dist/{llm → types/llm}/transport.d.ts +0 -0
- /package/dist/{llm → types/llm}/transports/anthropic-messages.d.ts +0 -0
- /package/dist/{llm → types/llm}/transports/openai-chat.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/agent-registry.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/approval-aware-tool-plan.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/context-compression.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/conversation-repair.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/curator-scheduler.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/embedded-failover-policy.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/error-classification.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/failover-classification.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/failover-error.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/fork-subagent.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/index.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/memory-flush-policy.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/memory-provider.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/parallel-tool-calls.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/prompt-cache-strategy.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/reactive-compact.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/retry-loop.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/skill-candidate.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/skill-consolidation.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/skill-improvement.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/skill-similarity.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/streaming-tool-executor.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/team-orchestration.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/team-tool-loop-wiring.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/tool-choice-policy.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/tool-loop-state.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/tool-schema.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/transcript-repair.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/turn-loop-guard.d.ts +0 -0
- /package/dist/{orchestration → types/orchestration}/web-browser-policy.d.ts +0 -0
- /package/dist/{runtime → types/runtime}/context-compression.d.ts +0 -0
- /package/dist/{runtime → types/runtime}/hook-registry.d.ts +0 -0
- /package/dist/{runtime → types/runtime}/memory-hooks.d.ts +0 -0
- /package/dist/{runtime → types/runtime}/tool-eligibility.d.ts +0 -0
- /package/dist/{skills → types/skills}/index.d.ts +0 -0
- /package/dist/{skills → types/skills}/memory-extractor.d.ts +0 -0
- /package/dist/{skills → types/skills}/memory-query-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/memory-store.d.ts +0 -0
- /package/dist/{skills → types/skills}/memory-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/portable-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/qmemory-adapter.d.ts +0 -0
- /package/dist/{skills → types/skills}/skill-frontmatter.d.ts +0 -0
- /package/dist/{skills → types/skills}/skill-guard.d.ts +0 -0
- /package/dist/{skills → types/skills}/skill-loader.d.ts +0 -0
- /package/dist/{skills → types/skills}/skill-source.d.ts +0 -0
- /package/dist/{skills → types/skills}/skill-types.d.ts +0 -0
- /package/dist/{skills → types/skills}/think-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/todo-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/agent-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/apply-patch-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/ask-user-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/brief-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/browser-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/checkpoint-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/config-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/cron-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/edit-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/exec-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/image-generate-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/instructions-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/lsp-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/mcp-client-types.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/mcp-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/memory-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/monitor-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/music-generate-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/notify-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/patch-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/pdf-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/plan-mode-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/read-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/repl-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/search-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/send-message-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/skill-list-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/skill-manage-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/skill-view-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/sleep-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/structured-output-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/task-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/team-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/tool-search-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/tts-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/video-edit-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/video-generate-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/video-merge-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/video-upscale-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/web-fetch-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/web-search-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/worktree-tool.d.ts +0 -0
- /package/dist/{skills → types/skills}/tools/write-tool.d.ts +0 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
function V(e){if(!e||typeof e!="object")return;let t=e;if(Array.isArray(t.enum))return t.enum;if("const"in t)return[t.const];let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(!n)return;let o=n.flatMap(r=>V(r)??[]);return o.length>0?o:void 0}function At(e,t){if(!e)return t;if(!t)return e;let n=V(e),o=V(t);if(!n&&!o)return e;let r=Array.from(new Set([...n??[],...o??[]])),i={};for(let a of[e,t]){if(!a||typeof a!="object")continue;let l=a;for(let c of["title","description","default"])!(c in i)&&c in l&&(i[c]=l[c])}let s=new Set(r.map(a=>typeof a));return s.size===1&&(i.type=Array.from(s)[0]),i.enum=r,i}var Mt=new Set(["patternProperties","additionalProperties","$schema","$id","$ref","$defs","definitions","examples","minLength","maxLength","minimum","maximum","multipleOf","pattern","format","minItems","maxItems","uniqueItems","minProperties","maxProperties"]),wt=new Set(["minLength","maxLength","minItems","maxItems","minContains","maxContains"]);function A(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>A(o));let t=e,n={};for(let[o,r]of Object.entries(t))if(!Mt.has(o)){if(o==="properties"&&r&&typeof r=="object"&&!Array.isArray(r)){n[o]=Object.fromEntries(Object.entries(r).map(([i,s])=>[i,A(s)]));continue}if((o==="items"||o==="additionalProperties")&&r&&typeof r=="object"){n[o]=Array.isArray(r)?r.map(i=>A(i)):A(r);continue}if((o==="anyOf"||o==="oneOf"||o==="allOf")&&Array.isArray(r)){n[o]=r.map(i=>A(i));continue}n[o]=r}return n}function _(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>_(o));let t=e,n={};for(let[o,r]of Object.entries(t))if(!wt.has(o)){if(o==="properties"&&r&&typeof r=="object"&&!Array.isArray(r)){n[o]=Object.fromEntries(Object.entries(r).map(([i,s])=>[i,_(s)]));continue}if(o==="items"&&r&&typeof r=="object"){n[o]=Array.isArray(r)?r.map(i=>_(i)):_(r);continue}if((o==="anyOf"||o==="oneOf"||o==="allOf")&&Array.isArray(r)){n[o]=r.map(i=>_(i));continue}n[o]=r}return n}function be(e,t){let n=e?.toLowerCase()??"";if(n.includes("xai")||n.includes("x-ai"))return!0;let o=t?.toLowerCase()??"";return!!(n==="openrouter"&&o.startsWith("x-ai/")||n==="venice"&&o.includes("grok"))}function ke(e,t){let n=e&&typeof e=="object"?e:{type:"object",properties:{},additionalProperties:!0},o=t?.modelProvider?.toLowerCase().includes("google")||t?.modelProvider?.toLowerCase().includes("gemini"),r=t?.modelProvider?.toLowerCase().includes("anthropic"),i=be(t?.modelProvider,t?.modelId),s=f=>o&&!r?A(f):i?_(f):f;if("type"in n&&"properties"in n&&!Array.isArray(n.anyOf))return s(n);if(!("type"in n)&&(typeof n.properties=="object"||Array.isArray(n.required))&&!Array.isArray(n.anyOf)&&!Array.isArray(n.oneOf))return s({...n,type:"object"});let a=Array.isArray(n.anyOf)?"anyOf":Array.isArray(n.oneOf)?"oneOf":null;if(!a)return s(n);let l=n[a],c={},u=new Map,d=0;for(let f of l){if(!f||typeof f!="object")continue;let T=f.properties;if(!T||typeof T!="object")continue;d+=1;for(let[C,b]of Object.entries(T))c[C]=C in c?At(c[C],b):b;let x=Array.isArray(f.required)?f.required:[];for(let C of x)typeof C=="string"&&u.set(C,(u.get(C)??0)+1)}let p=Array.isArray(n.required)?n.required.filter(f=>typeof f=="string"):void 0,m=p&&p.length>0?p:d>0?Array.from(u.entries()).filter(([,f])=>f===d).map(([f])=>f):void 0;return s({type:"object",...typeof n.title=="string"?{title:n.title}:{},...typeof n.description=="string"?{description:n.description}:{},properties:Object.keys(c).length>0?c:n.properties??{},...m&&m.length>0?{required:m}:{},additionalProperties:"additionalProperties"in n?n.additionalProperties:!0})}function xe(e,t){return e.map(n=>({type:"function",function:{name:n.name,...typeof n.description=="string"?{description:n.description}:{},parameters:ke(n.parameters,t)}}))}function Et(e){return xe(e.map(t=>({name:t.name,description:t.description,parameters:{type:"object",properties:Object.fromEntries((t.requiredParameters??[]).map(n=>[n,{type:"string"}])),additionalProperties:!0,...(t.requiredParameters?.length??0)>0?{required:t.requiredParameters}:{}}})))}function Re(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t&&typeof t=="object"&&"text"in t&&typeof t.text=="string"?t.text:"").filter(Boolean).join(`
|
|
2
|
+
`):""}function _t(e){try{let n=JSON.parse(e).choices?.[0]?.message;return{toolCalls:Array.isArray(n?.tool_calls)?n.tool_calls.filter(r=>r?.type==="function"&&typeof r.function?.name=="string"):[],responseText:Re(n?.content)}}catch{return{toolCalls:[],responseText:""}}}function It(e){return{role:"assistant",content:"",tool_calls:e}}function Pt(e,t){return{role:"tool",tool_call_id:e,content:JSON.stringify(t.ok?{ok:!0,payload:t.payload}:{ok:!1,error:t.error??"Tool invoke failed"})}}function Lt(e){return A(e)}var Ft=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,w={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]},Ot=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Nt=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Dt=512,Bt=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,$t=/^\s*(?:<!doctype\s+html\b|<html\b)/i,zt=new Set([521,522,523,524,525,526,530]),jt=new Set([500,502,503,504,521,522,523,524,529]),Ht=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ut=["upgrade your plan","upgrade plan","current plan","subscription"],qt=["daily","weekly","monthly"],Wt=["try again","retry","temporary","cooldown"],Yt=["usage limit","rate limit","organization usage"],Gt=["organization","workspace"],Kt=["billing period","exceeded","reached","exhausted"],Vt=/["']?(?: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,Xt=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function E(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Jt(e){return E(e,w.format)}function Se(e){return E(e,w.rateLimit)}function D(e){return E(e,w.timeout)}function Qt(e){return Ft.test(e)}function X(e){let t=e.toLowerCase();return t?e.length>Dt?Nt.test(t):E(t,w.billing)?!0:Ot.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ve(e){return E(e,w.authPermanent)}function Zt(e){return E(e,w.auth)}function Ae(e){return E(e,w.overloaded)}function M(e,t){return t.some(n=>e.includes(n))}function en(e){return M(e,Ht)||M(e,Ut)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function tn(e){let t=M(e,qt),n=e.includes("spend limit")||e.includes("spending limit"),o=M(e,Gt);return M(e,Wt)&&M(e,Yt)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||M(e,Kt))}function nn(e){return e.trim().toLowerCase().replace(Xt,"").trim()}function Me(e){let t=nn(e);return!t||en(t)?"billing":Se(t)||tn(t)?"rate_limit":"billing"}function on(e){return Vt.test(e)?Me(e):null}function J(e){let t=e.match(Bt);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function rn(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function sn(e){let t=e.trim();if(!t)return!1;let n=J(t);return!n||n.code<500?!1:zt.has(n.code)?!0:n.code<600&&$t.test(n.rest)&&/<\/html>/i.test(n.rest)}function we(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?jt.has(n.code):!1}function L(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Me(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ve(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ae(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&X(t)?"billing":"format":null}function Ee(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 an(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 I(e){if(an(e))return"session_expired";if(Ee(e))return"model_not_found";let t=on(e);return t||(Qt(e)?X(e)?"billing":"rate_limit":Se(e)?"rate_limit":Ae(e)?"overloaded":we(e)?J(e.trim())?.code===529?"overloaded":"timeout":rn(e)?"timeout":Jt(e)?"format":X(e)?"billing":D(e)?"timeout":ve(e)?"auth_permanent":Zt(e)?"auth":null)}function ln(e){return I(e)!==null}var _e={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"},cn={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 un(e,t){let n=L(e,t)??(t?I(t):null);return n?_e[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function dn(e){return _e[e]}function pn(e){return cn[e]}function se(e){return typeof e.compressAsync=="function"}var Q=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let a of t)a.role==="system"?o.push(a):r.push(a);let i=n;for(let a of o)i-=this.estimateTokens(a);if(i<=0)return{messages:o,droppedCount:r.length,strategy:"sliding-window"};let s=[];for(let a=r.length-1;a>=0;a--){let l=this.estimateTokens(r[a]);if(i-l<0)break;i-=l,s.unshift(r[a])}return{messages:[...o,...s],droppedCount:r.length-s.length,strategy:"sliding-window"}}},Z=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),s=r.slice(r.length-this.recentCount),a=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
3
|
+
${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},ee=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:i.content.slice(0,this.maxToolResultChars)+`
|
|
4
|
+
[...truncated]`})),droppedCount:o,strategy:"tool-result-trim"}}};function mn(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function fn(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],s=0,a=!1,l=!1;for(let c of e){let u=se(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&i.push(u.strategy),u.metrics&&(s+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:s>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:s,usedLlm:a,cacheInvalidated:l}:void 0}}}}function ae(e,t){let n=e.filter(s=>s.role==="user"),o=e.filter(s=>s.tool_calls!=null),r=e.filter(s=>s.role==="tool"),i=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","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&&i.push("","## Additional Context",t.taskContext),i.push("","## Conversation to Summarize","",...e.map(s=>{let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),l=a.length>2e3?a.slice(0,2e3)+"...":a;return`[${s.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."),i.join(`
|
|
5
|
+
`)}var te=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??Le,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=Pe(t),s=t.reduce((h,k)=>h+this.config.estimateTokens(k),0);if(s<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let h=0;h<i.length&&(i[h].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));h++)a=h+1;let c=Math.max(a,i.length-this.config.protectedTailMessages);if(c<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=i.slice(0,a),d=i.slice(a,c),p=i.slice(c),m=ae(d,{taskContext:this.config.taskContext}),f=await this.config.summarize(d,m),T={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
6
|
+
|
|
7
|
+
${f}`},x=[...r,...u,T,...p],C=Date.now()-o,b=x.reduce((h,k)=>h+this.config.estimateTokens(k),0);return{messages:x,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:s,tokensAfter:b,compressionRatio:s>0?b/s:1,latencyMs:C,usedLlm:!0,cacheInvalidated:!0}}}},ne=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??Le}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=Pe(t),s=r.findIndex(k=>typeof k.content=="string"&&k.content.startsWith("[Conversation summary")),a=s>=0?r[s]:void 0,l=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=Math.max(0,i.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((k,g)=>k+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,c),p=i.slice(c),m=a&&typeof a.content=="string"?`Previous summary:
|
|
8
|
+
${a.content}
|
|
9
|
+
|
|
10
|
+
New messages to integrate:`:void 0,f=ae(d,{taskContext:m}),T=await this.config.summarize(d,f),x={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
11
|
+
|
|
12
|
+
${T}`},C=[...l,x,...p],b=Date.now()-o,h=C.reduce((k,g)=>k+this.config.estimateTokens(g),0);return{messages:C,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:h,compressionRatio:u>0?h/u:1,latencyMs:b,usedLlm:!0,cacheInvalidated:!0}}}},oe=class{config;constructor(t){this.config=t}compress(t,n){let o=B(t),r=this.config.inner.compress(t,n),i=B(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}async compressAsync(t,n){let o=B(t),r=se(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=B(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}},Ie={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function gn(e={}){let t={...Ie,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function yn(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var re=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,i=0,s=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&i++,a.cacheInvalidated&&s++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:s,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},ie=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function Pe(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function Le(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function B(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}function Fe(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function Oe(e){return e.existingSkillName?e.feedback==="negative":!1}function hn(e,t){return Oe(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Fe(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 Tn=["submit-review","approve","reject","start-canary","record-effectiveness","promote","publish","mark-stale","mark-superseded","rollback"],Cn=["canary","published"];function y(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function v(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,t=0){let n=v(e);return n===void 0?Math.max(0,Math.floor(t)):Math.max(0,Math.floor(n))}function S(e){return e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function bn(e){return typeof e=="string"&&Tn.includes(e)}function kn(e){return typeof e=="string"&&Cn.includes(e)}function Ne(e){let t=y(e);return t&&bn(t)?t:null}function le(e){let t=y(e);return t&&kn(t)?t:null}function De(e){let t=S(e),n=y(t.uri);if(!n)return null;let o=y(t.sha256),r=y(t.workspaceDir),i=y(t.relativePath),s=y(t.sourceWorkspaceDir),a=y(t.stagedAt);return{uri:n,...o?{sha256:o}:{},...r?{workspaceDir:r}:{},...i?{relativePath:i}:{},...s?{sourceWorkspaceDir:s}:{},...a?{stagedAt:a}:{}}}function Be(e){let t=S(e),n=y(t.executionId),o=y(t.rootExecutionId),r=y(t.parentExecutionId),i=y(t.sidechainId),s=y(t.attemptId),a=y(t.outcomeId),l=y(t.sessionId),c=y(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 $e(e){let t=S(e),n=le(t.phase);if(!n)return null;let o=$(t.successCount),r=v(t.failureCount),i=$(t.sampleCount,r!==void 0?o+r:o),s=$(t.failureCount,Math.max(i-o,0)),a=$(t.regressionCount),l=v(t.successRate)??(i>0?o/i:0),c=v(t.regressionRate)??(i>0?a/i:0),u=v(t.avgLatencyMs),d=v(t.avgCostUsd),p=v(t.score),m=y(t.staleReason)??null,f=y(t.notes)??null,T=S(t.summary),x=y(t.lastObservedAt),C=y(t.updatedAt),b=y(t.lastActivityAt),h=v(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}:{},...m?{staleReason:m}:{},...f?{notes:f}:{},...Object.keys(T).length>0?{summary:T}:{},...x?{lastObservedAt:x}:{},...C?{updatedAt:C}:{},...b?{lastActivityAt:b}:{},...h!==void 0?{activityCount:h}:{}}}var ze={reviewRequired:!0,canaryRequired:!0,autoPromote:!1,minCanarySampleCount:10,minSuccessRate:.7,maxRegressionRate:.1,maxCostIncreaseRate:.25,staleAfterHours:168};function ce(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 F(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 xn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function Rn(e={}){return je(e,ze)}function je(e,t=ze){let n=S(e);return{reviewRequired:ce(n.reviewRequired,t.reviewRequired),canaryRequired:ce(n.canaryRequired,t.canaryRequired),autoPromote:ce(n.autoPromote,t.autoPromote),minCanarySampleCount:Math.max(1,Math.floor(F(n.minCanarySampleCount,t.minCanarySampleCount))),minSuccessRate:Math.max(0,Math.min(1,F(n.minSuccessRate,t.minSuccessRate))),maxRegressionRate:Math.max(0,Math.min(1,F(n.maxRegressionRate,t.maxRegressionRate))),maxCostIncreaseRate:Math.max(0,F(n.maxCostIncreaseRate,t.maxCostIncreaseRate)),staleAfterHours:Math.max(1,Math.floor(F(n.staleAfterHours,t.staleAfterHours)))}}function He(e){let t=S(e.evidence),n=e.artifact?De(e.artifact):null,o=e.sourceExecution?Be(e.sourceExecution):null,r=typeof e.sourceSessionKey=="string"?e.sourceSessionKey.trim():"";return{...t,...n?{artifact:n}:{},...o?{sourceExecution:o}:{},...r?{sourceSessionKey:r}:{}}}function Sn(e){let t=He(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=xn(e.validationRefs);return{...t,...n?{diffSummary:n}:{},...o?{baselineCandidateId:o}:{},...r?{rolloutNotes:r}:{},...i.length>0?{validationRefs:i}:{}}}function vn(e){return{action:Ne(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:S(e.payload),createdAt:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt.trim():new Date().toISOString()}}function An(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 $e({phase:le(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:S(e.summary),lastObservedAt:e.lastObservedAt??new Date().toISOString(),updatedAt:e.updatedAt??new Date().toISOString()})}function Ue(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 Mn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function wn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function qe(e){if(!e.eligibility?.length)return[...e.tools];let t=wn(e.eligibility);return e.tools.filter(n=>{let o=Ue(n);if(!o)return!1;let r=t.get(o);return!r||Mn(r.status)})}function En(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(t.function&&typeof t.function=="object")return t;let n=typeof t.name=="string"?t.name.trim():"";if(!n)return t;let o={name:n,parameters:t.input_schema&&typeof t.input_schema=="object"?t.input_schema:t.parameters&&typeof t.parameters=="object"?t.parameters:{type:"object",properties:{}}};return typeof t.description=="string"&&t.description.trim()&&(o.description=t.description),typeof t.strict=="boolean"&&(o.strict=t.strict),{type:"function",function:o}}function _n(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t=e;return t.type==="auto"?"auto":t.type==="none"?"none":t.type==="required"||t.type==="any"?"required":t.type==="tool"&&typeof t.name=="string"&&t.name.trim()?{type:"function",function:{name:t.name.trim()}}:e}function We(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 In(e){let t=We({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=qe({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",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=>Ue(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 Pn=["stop","aborted","timeout","cancelled","interrupted","error"],Ln=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Fn(e,t){return{...e,content:[...Ye(e.content),...Ye(t.content)]}}function On(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 Nn(e){return new Set((e??Pn).map(t=>t.trim().toLowerCase()))}function Ge(e,t){return e?Nn(t).has(e.trim().toLowerCase()):!1}function Ke(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 Ve(e){if(!e)return null;let t=null;if(typeof e=="string"){let r=e.trim();if(!r.startsWith("{")||!r.endsWith("}"))return null;try{t=JSON.parse(r)}catch{return null}}else typeof e=="object"&&(t=e);if(!t)return null;let n=typeof t.id=="string"?t.id:"",o=typeof t.type=="string"?t.type:"";return n.startsWith("rs_")&&(o==="reasoning"||o.startsWith("reasoning."))?{id:n,type:o}:null}function Dn(e,t){for(let n=t+1;n<e.length;n+=1){let o=e[n];if(!o||typeof o!="object"||o.type!=="thinking")return!0}return!1}function z(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=>On(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]=Fn(l,a);continue}s.push(a)}return s}function Bn(e,t=""){return e.map(n=>n.role==="assistant"&&!Object.hasOwn(n,"reasoning_content")?{...n,reasoning_content:t}:{...n})}function j(e,t){return Ge(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Ln)delete o[r];return o}):[...e]}function H(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 $n(e,t){let n=z(e),o=j(n,t);return H(o,t)}function zn(e){let t=!1,n=[],o=null;for(let r of e){if(!r||typeof r!="object"){o=null,n.push(r);continue}if(r.role==="assistant"){if(!Array.isArray(r.content)){o=null,n.push(r);continue}let i=new Map,s=!1,a=!1,l=r.content.map(c=>{if(!c||typeof c!="object")return c;let u=c;if(u.type==="thinking"&&Ve(u.thinkingSignature))return s=!0,c;let d=c;if(!["toolCall","toolUse","functionCall"].includes(String(d.type))||typeof d.id!="string")return c;let p=Ke(d.id);return s||!p.itemId||!p.itemId.startsWith("fc_")?c:(a=!0,i.set(d.id,p.callId),{...c,id:p.callId})});if(o=i.size>0?i:null,!a){n.push(r);continue}t=!0,n.push({...r,content:l});continue}if(r.role==="toolResult"&&o&&o.size>0){let i={},s=!1;if(typeof r.toolCallId=="string"){let a=o.get(r.toolCallId);a&&a!==r.toolCallId&&(i.toolCallId=a,s=!0)}if(typeof r.toolUseId=="string"){let a=o.get(r.toolUseId);a&&a!==r.toolUseId&&(i.toolUseId=a,s=!0)}if(!s){n.push(r);continue}t=!0,n.push({...r,...i});continue}o=null,n.push(r)}return t?n:[...e]}function jn(e){let t=[];for(let n of e){if(!n||typeof n!="object"){t.push(n);continue}if(n.role!=="assistant"){t.push(n);continue}if(!Array.isArray(n.content)){t.push(n);continue}let o=!1,r=[];for(let i=0;i<n.content.length;i+=1){let s=n.content[i];if(!s||typeof s!="object"){r.push(s);continue}let a=s;if(a.type!=="thinking"){r.push(s);continue}if(!Ve(a.thinkingSignature)){r.push(s);continue}if(Dn(n.content,i)){r.push(s);continue}o=!0}if(!o){t.push(n);continue}r.length!==0&&t.push({...n,content:r})}return t}function ue(e,t){let n=t?.placeholderFunctionCallOutput??JSON.stringify({ok:!1,error:"Tool loop interrupted before function_call_output was provided."}),o=Ge(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let d={...u};if(typeof d.id=="string"){let p=Ke(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}var Hn=/request was aborted|request aborted/i;function Xe(e){if(!e||typeof e!="object")return;let t=e.name;return typeof t=="string"&&t.trim()?t.trim():void 0}function pe(e){if(!e||typeof e!="object")return;let t=e.status??e.statusCode;if(typeof t=="number")return t;if(typeof t=="string"&&/^\d+$/.test(t))return Number(t)}function me(e){if(!e||typeof e!="object")return;let t=e.code;if(typeof t!="string")return;let n=t.trim();return n||void 0}function N(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="symbol")return e.description??"";if(e&&typeof e=="object"){let t=e.message;if(typeof t=="string")return t}return""}function de(e){if(!e)return!1;if(Xe(e)==="TimeoutError")return!0;let t=N(e);return!!(t&&D(t))}var O=class extends Error{reason;provider;model;profileId;status;code;constructor(t,n){super(t,{cause:n.cause}),this.name="FailoverError",this.reason=n.reason,this.provider=n.provider,this.model=n.model,this.profileId=n.profileId,this.status=n.status,this.code=n.code}};function U(e){return e instanceof O}function Je(e){switch(e){case"billing":return 402;case"rate_limit":return 429;case"overloaded":return 503;case"auth":return 401;case"auth_permanent":return 403;case"timeout":return 408;case"format":return 400;case"model_not_found":return 404;case"session_expired":return 410;default:return}}function Qe(e){if(de(e))return!0;if(!e||typeof e!="object"||Xe(e)!=="AbortError")return!1;let t=N(e);if(t&&Hn.test(t))return!0;let n="cause"in e?e.cause:void 0,o="reason"in e?e.reason:void 0;return de(n)||de(o)}function fe(e){if(U(e))return e.reason;let t=pe(e),n=N(e),o=L(t,n);if(o)return o;let r=(me(e)??"").toUpperCase();return["ETIMEDOUT","ESOCKETTIMEDOUT","ECONNRESET","ECONNABORTED","ECONNREFUSED","ENETUNREACH","EHOSTUNREACH","ENETRESET","EAI_AGAIN"].includes(r)||Qe(e)?"timeout":n?I(n):null}function Un(e){return U(e)?{message:e.message,reason:e.reason,status:e.status,code:e.code}:{message:N(e)||String(e),reason:fe(e)??void 0,status:pe(e),code:me(e)}}function qn(e,t){if(U(e))return e;let n=fe(e);if(!n)return null;let o=N(e)||String(e),r=pe(e)??Je(n),i=me(e);return new O(o,{reason:n,provider:t?.provider,model:t?.model,profileId:t?.profileId,status:r,code:i,cause:e instanceof Error?e:void 0})}var Wn=/^[A-Za-z0-9_-]+$/,ot=new Set(["toolCall","toolUse","functionCall"]),Yn=/rate limit|rate.limited|overloaded|too many requests|quota exceeded|timed?\s*out|billing|insufficient.*(balance|quota|credit)|try again later/i;function Ze(e){if(!e||typeof e!="object")return!1;let t=e.type;return typeof t=="string"&&ot.has(t)}function Gn(e){let t="input"in e?e.input!==void 0&&e.input!==null:!1,n="arguments"in e?e.arguments!==void 0&&e.arguments!==null:!1;return t||n}function Kn(e){return typeof e=="string"&&e.trim().length>0}function Vn(e){return Kn(e.id)}function et(e){return typeof e!="string"?void 0:e.trim()||void 0}function Xn(e){if(!e)return null;let t=new Set;for(let n of e){if(typeof n!="string")continue;let o=n.trim();o&&t.add(o.toLowerCase())}return t.size>0?t:null}function Jn(e,t){if(typeof e.name!="string")return!1;let n=e.name.trim();return!n||n.length>64||!Wn.test(n)?!1:t?t.has(n.toLowerCase()):!0}function tt(e){if(!e||typeof e!="object")return e;let t=e,n=t.attachments;if(!Array.isArray(n))return e;let o=n.map(r=>{if(!r||typeof r!="object")return r;let i=r;if(!Object.hasOwn(i,"content"))return r;let{content:s,...a}=i;return{...a,content:"__OPENCLAW_REDACTED__"}});return{...t,attachments:o}}function Qn(e){let t=typeof e.name=="string"?e.name:void 0,n=t?.trim(),o=typeof n=="string"&&n.length>0,r=o?n:void 0,i=o&&t!==n;if(!(r?.toLowerCase()==="sessions_spawn"))return i?{...e,name:r}:e;let a=tt(e.arguments),l=tt(e.input);if(a===e.arguments&&l===e.input&&!i)return e;let c={...e};return i&&r&&(c.name=r),(a!==e.arguments||Object.hasOwn(e,"arguments"))&&(c.arguments=a),(l!==e.input||Object.hasOwn(e,"input"))&&(c.input=l),c}function Zn(e,t){let n=e.toolName,o=et(n);if(o)return n===o?e:{...e,toolName:o};let r=et(t);return r?{...e,toolName:r}:typeof n=="string"?{...e,toolName:"unknown"}:e}function eo(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object")continue;let r=o;typeof r.id!="string"||!r.id||typeof r.type=="string"&&ot.has(r.type)&&n.push({id:r.id,name:typeof r.name=="string"?r.name:void 0})}return n}function nt(e){return typeof e.toolCallId=="string"&&e.toolCallId?e.toolCallId:typeof e.toolUseId=="string"&&e.toolUseId?e.toolUseId:null}function to(e){return{role:"toolResult",toolCallId:e.toolCallId,toolName:e.toolName??"unknown",content:[{type:"text",text:"[qlogicagent] missing tool result in session history; inserted synthetic error result for transcript repair."}],isError:!0,timestamp:0}}function no(e){let t=!1,n=[];for(let o of e){if(!o||typeof o!="object"||o.role!=="toolResult"){n.push(o);continue}if(!("details"in o)){n.push(o);continue}let r={...o};delete r.details,t=!0,n.push(r)}return t?n:[...e]}function rt(e,t){let n=0,o=0,r=!1,i=[],s=Xn(t?.allowedToolNames);for(let a of e){if(!a||typeof a!="object"){i.push(a);continue}if(a.role!=="assistant"||!Array.isArray(a.content)){i.push(a);continue}let l=[],c=0,u=!1;for(let d of a.content){if(Ze(d)&&(!Gn(d)||!Vn(d)||!Jn(d,s))){n+=1,c+=1,r=!0,u=!0;continue}if(Ze(d)){if((typeof d.name=="string"?d.name.trim():void 0)?.toLowerCase()==="sessions_spawn"){let m=Qn(d);m!==d&&(r=!0,u=!0),l.push(m);continue}if(typeof d.name=="string"){let m=d.name.trim();if(m&&m!==d.name){l.push({...d,name:m}),r=!0,u=!0;continue}}}l.push(d)}if(c>0){if(l.length===0){o+=1,r=!0;continue}i.push({...a,content:l});continue}if(u){i.push({...a,content:l});continue}i.push(a)}return{messages:r?i:[...e],droppedToolCalls:n,droppedAssistantMessages:o}}function oo(e,t){return rt(e,t).messages}function it(e,t){let n=[],o=[],r=new Set,i=0,s=0,a=!1,l=!1,c=t?.createMissingToolResult??to,u=p=>{let m=nt(p);if(m&&r.has(m)){i+=1,l=!0;return}m&&r.add(m),n.push(p)};for(let p=0;p<e.length;p+=1){let m=e[p];if(!m||typeof m!="object"){n.push(m);continue}if(m.role!=="assistant"){m.role!=="toolResult"?n.push(m):(s+=1,l=!0);continue}let f=m.stopReason;if(f==="error"||f==="aborted"){n.push(m);continue}let T=eo(m);if(T.length===0){n.push(m);continue}let x=new Set(T.map(g=>g.id)),C=new Map(T.map(g=>[g.id,g.name])),b=new Map,h=[],k=p+1;for(;k<e.length;k+=1){let g=e[k];if(!g||typeof g!="object"){h.push(g);continue}if(g.role==="assistant")break;if(g.role==="toolResult"){let R=nt(g);if(R&&x.has(R)){if(r.has(R)){i+=1,l=!0;continue}let P=Zn(g,C.get(R));P!==g&&(l=!0),b.has(R)||b.set(R,P);continue}}g.role!=="toolResult"?h.push(g):(s+=1,l=!0)}n.push(m),b.size>0&&h.length>0&&(a=!0,l=!0);for(let g of T){let R=b.get(g.id);if(R)u(R);else{let P=c({toolCallId:g.id,toolName:g.name});o.push(P),l=!0,u(P)}}for(let g of h)n.push(g);p=k-1}let d=l||a;return{messages:d?n:[...e],added:o,droppedDuplicateCount:i,droppedOrphanCount:s,moved:d}}function ro(e,t){return it(e,t).messages}function io(e){let t=!1,n=[];for(let o of e){if(!o||typeof o!="object"){n.push(o);continue}if(o.role!=="assistant"||o.stopReason!=="error"){n.push(o);continue}let r=o.content,i=typeof r=="string"?r:Array.isArray(r)?r.filter(s=>s.type==="text").map(s=>s.text??"").join(" "):"";if(!Yn.test(i)){n.push(o);continue}t=!0}return t?n:[...e]}function st(e){if(e!==void 0)return typeof e=="boolean"?{kind:"enabled",enabled:e}:e===null?{kind:"suppressed"}:{kind:"invalid",summary:typeof e=="string"?e:typeof e}}function so(e){let t=[],n=st(e.requestedPreference),o=new Map((e.toolCapabilities??[]).map(l=>[l.name,l])),r=e.providerSupportsParallel!==!1;n?.kind==="enabled"?r=n.enabled&&e.providerSupportsParallel!==!1:n?.kind==="suppressed"?r=!1:n?.kind==="invalid"&&t.push(`ignoring invalid parallel_tool_calls param: ${n.summary}`),r&&e.providerSupportsParallel===!1&&t.push("provider does not support parallel tool calls; downgraded to serial execution.");let i=[],s=[],a=()=>{s.length!==0&&(i.push({mode:"parallel",calls:s}),s=[])};for(let l of e.toolCalls){let c=o.get(l.function.name);if(!r||c?.requiresApproval===!0||c?.serialOnly===!0||c?.parallelSafe===!1||c?.approvalMode==="user-confirm"){a(),i.push({mode:"serial",calls:[l]});continue}s.push(l)}return a(),{enabled:r,mode:i.some(l=>l.mode==="parallel"&&l.calls.length>1)?"parallel":"serial",batches:i,warnings:t}}function ao(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 lo(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 co(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 uo(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 ge(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function po(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 mo(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 fo(e){let t=[],n=z(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=j(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=H(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:ge({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:ao(r),completedToolCallIds:lo(r)}),recoveryActions:t}}function go(e){let t=ue(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:ge({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:co(t),completedToolCallIds:uo(t)}),recoveryActions:n}}import{MEMORY_OBSERVATION_HOOK_VALUES as yo,MEMORY_OBSERVATION_SOURCE_VALUES as ho,MEMORY_WRITE_ACCESS_VALUES as To}from"qlogicagent-runtime-contracts";function at(e){let t=e.compactionCount??0,n=e.memoryFlushCompactionCount;return typeof n=="number"&&n===t}function Co(e){if(!e.entry)return!1;let t=e.tokenCount,o=(typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):void 0)??e.resolveFreshSessionTotalTokens(e.entry);if(!o||o<=0)return!1;let r=Math.max(1,Math.floor(e.contextWindowTokens)),i=Math.max(0,Math.floor(e.reserveTokensFloor)),s=Math.max(0,Math.floor(e.softThresholdTokens)),a=Math.max(0,r-i-s);return!(a<=0||o<a||at(e.entry))}function bo(e){let t=e.memoryFlushWritable&&!e.isHeartbeat&&!e.isCli,n=e.contextWindowTokens-e.reserveTokensFloor-e.softThresholdTokens,o=t&&e.hasSessionEntry&&e.hasFreshPersistedPromptTokens&&typeof e.promptTokenEstimate=="number"&&Number.isFinite(e.promptTokenEstimate)&&n>0&&(e.persistedPromptTokens??0)+e.promptTokenEstimate>=n-e.transcriptOutputReadBufferTokens,r=!!(t&&e.hasSessionEntry&&(!e.hasFreshPersistedPromptTokens||o)),i=!!(t&&e.hasSessionEntry&&Number.isFinite(e.forceFlushTranscriptBytes)&&e.forceFlushTranscriptBytes>0);return{canAttemptFlush:t,flushThreshold:n,shouldReadTranscriptForOutput:o,shouldReadTranscript:r,shouldCheckTranscriptSizeForForcedFlush:i,shouldReadSessionLog:r||i}}function ko(e){let t=typeof e.transcriptByteSize=="number"&&e.transcriptByteSize>=e.forceFlushTranscriptBytes,n=typeof e.transcriptPromptTokens=="number"&&Number.isFinite(e.transcriptPromptTokens)&&e.transcriptPromptTokens>0,o=n&&(!e.hasFreshPersistedPromptTokens||(e.transcriptPromptTokens??0)>(e.persistedPromptTokens??0)),r=Math.max(e.hasFreshPersistedPromptTokens?e.persistedPromptTokens??0:0,n?e.transcriptPromptTokens??0:0),i=r>0&&(e.hasFreshPersistedPromptTokens||n),s=i?e.resolveEffectivePromptTokens(r,e.transcriptOutputTokens,e.promptTokenEstimate):void 0,a=typeof s=="number"&&Number.isFinite(s)&&s>0?s:void 0;return{shouldForceFlushByTranscriptSize:t,shouldPersistTranscriptPromptTokens:o,promptTokensSnapshot:r,hasFreshPromptTokensSnapshot:i,projectedTokenCount:s,tokenCountForFlush:a}}async function xo(e){let t=0;for(;;){if(t>=e.maxIterations)return await e.onRetryLimit({iterations:t,maxIterations:e.maxIterations});t+=1;let n=await e.executeIteration({iteration:t});if(n.kind==="return")return n.result}}function Ro(e){let t=Math.max(0,Math.floor(e.baseIterations??24)),n=Math.max(0,Math.floor(e.perCandidateIterations??8)),o=Math.max(1,Math.floor(e.minIterations??32)),r=Math.max(o,Math.floor(e.maxIterations??160)),i=t+Math.max(1,Math.floor(e.candidateCount))*n;return Math.min(r,Math.max(o,i))}function So(e){return!e.reason||(e.nonRetryableReasons??[]).includes(e.reason)?null:e.reason}function vo(e){return e.allInCooldown?e.unavailableReason??e.cooldownFallbackReason:e.classifiedReason??e.defaultReason}function Ao(e){if(!(e.aborted||!e.fallbackThinking))return{thinkLevel:e.fallbackThinking,warningMessage:`unsupported thinking level for ${e.provider}/${e.modelId}; retrying with ${e.fallbackThinking}`}}function Mo(e){let t=e.match(/supported values are:\s*([^\n.]+)/i)??e.match(/supported values:\s*([^\n.]+)/i);if(!t?.[1])return[];let n=t[1],o=Array.from(n.matchAll(/['"]([^'"]+)['"]/g)).map(r=>r[1]?.trim());return o.length>0?o.filter(r=>!!r):n.split(/,|\band\b/gi).map(r=>r.replace(/^[^a-zA-Z]+|[^a-zA-Z]+$/g,"").trim()).filter(Boolean)}function wo(e){let t=e.message?.trim();if(!t)return;let n=Mo(t);if(n.length===0)return/not supported/i.test(t)&&e.offLevel&&!e.attempted.has(e.offLevel)?e.offLevel:void 0;for(let o of n){let r=e.normalizeThinkLevel(o);if(!(!r||e.attempted.has(r)))return r}}function Eo(e){return e.promptFailoverFailure?!(e.nonRotatableReasons??[]).includes(e.promptFailoverReason):!1}function lt(e){return e.failoverFailure||e.timedOut&&!e.timedOutDuringCompaction}function _o(e){return e.canRotate?{kind:"retry-rotated"}:e.fallbackThinking?{kind:"retry-thinking",thinkLevel:e.fallbackThinking}:e.fallbackConfigured&&e.promptFailoverFailure?{kind:"throw-failover",reason:e.promptFailoverReason}:{kind:"unhandled"}}function Io(e){return lt({timedOut:e.timedOut,timedOutDuringCompaction:e.timedOutDuringCompaction,failoverFailure:e.failoverFailure})?e.canRotate?{kind:"retry-rotated"}:e.shouldThrowFailover?{kind:"throw-failover",reason:e.failoverReason}:{kind:"unhandled"}:{kind:"unhandled"}}function Po(e){return!e.hasPromptError||e.aborted?{kind:"noop"}:e.roleAlternationError?{kind:"return-error",errorKind:"role_ordering",text:"Message ordering conflict - please try again. If this persists, use /new to start a fresh session.",message:e.errorText}:typeof e.imageSizeMaxMb=="number"&&Number.isFinite(e.imageSizeMaxMb)?{kind:"return-error",errorKind:"image_size",text:`Image too large for the model${` (max ${e.imageSizeMaxMb}MB)`}. Please compress or resize the image and try again.`,message:e.errorText}:e.promptFailureAction.kind==="retry-rotated"?{kind:"retry-rotated"}:e.promptFailureAction.kind==="retry-thinking"?{kind:"retry-thinking",thinkLevel:e.promptFailureAction.thinkLevel}:e.promptFailureAction.kind==="throw-failover"?{kind:"throw-failover",reason:e.promptFailureAction.reason}:{kind:"throw-original"}}function Lo(e){return{message:e.formattedAssistantErrorText||e.assistantErrorMessage?.trim()||(e.timedOut?"LLM request timed out.":e.rateLimitFailure?"LLM request rate limited.":e.billingFailureMessage?e.billingFailureMessage:e.authFailure?"LLM request unauthorized.":"LLM request failed."),status:e.failoverStatus??(e.timeoutDetectedFromMessage?e.timeoutStatus??408:void 0)}}function q(e){return e.length===0?"no tools":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e.at(-1)}`}function Fo(e){return e?e.requiresApproval===!0||e.approvalMode==="user-confirm":!1}function Oo(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function No(e){let t=e.eligibilityMap.get(e.toolName);return t?.approvalRequired!==void 0?t.approvalRequired:Fo(e.capabilityMap.get(e.toolName))}function Do(e){let t=new Map(e.toolCapabilities.map(r=>[r.name,r])),n=Oo(e.eligibility),o=e.batches.length;return e.batches.map((r,i)=>{let s=r.calls.map(d=>d.function.name),a=r.calls.map(d=>No({toolName:d.function.name,capabilityMap:t,eligibilityMap:n})?d.function.name:null).filter(d=>!!d),l=a.length>0,c=r.mode==="parallel"?`Step ${i+1}/${o}: run ${s.length} tools in parallel: ${q(s)}.`:l?`Step ${i+1}/${o}: approval-gated execution for ${q(a)}.`:`Step ${i+1}/${o}: run ${q(s)} serially.`,u=l?o>i+1?"This step must be approved before later steps continue.":"This is the final planned step and requires approval before execution.":r.mode==="parallel"?"Parallel-safe tools are grouped to avoid unnecessary waiting.":"This step stays serial because the tool is not parallel-safe.";return{stepIndex:i+1,stepCount:o,mode:r.mode,callIds:r.calls.map(d=>d.id),toolNames:s,approvalRequired:l,approvalToolNames:a,summary:`${c} ${u}`}})}function Bo(e){if(!e.step)return`semantic turn requested local tool: ${e.toolName}`;let t=e.step.approvalRequired?e.step.approvalToolNames.length>1?` Approval is currently blocking ${q(e.step.approvalToolNames)}.`:" Approval is required before this step can continue.":"";return`${e.step.summary}${t}`}function $o(e){return e?{stepIndex:e.stepIndex,stepTotal:e.stepCount,stepSummary:e.summary}:{}}function W(e,t,n){t&&e.add(n)}function zo(e){let t=e.capability,n=new Set(t?.escalationReasons??[]);return W(n,e.needsInteractiveSession===!0,"requires-interaction"),W(n,e.needsLoginState===!0,"requires-login-state"),W(n,e.needsPersistentSession===!0,"requires-persistent-session"),W(n,e.needsStateChangingAction===!0,"requires-state-changing-action"),t?.capabilityFamily==="browser-execution"||t?.taskMode==="interactive-browser"||n.size>0?e.browserAvailable!==!1?{selectedCapabilityFamily:"browser-execution",selectedTaskMode:"interactive-browser",shouldEscalateToBrowser:!0,escalationReasons:[...n]}:{selectedCapabilityFamily:t?.capabilityFamily??"web-intelligence",selectedTaskMode:t?.taskMode,shouldEscalateToBrowser:!1,degradationTarget:t?.degradationTarget,escalationReasons:[...n]}:{selectedCapabilityFamily:"web-intelligence",selectedTaskMode:t?.taskMode,shouldEscalateToBrowser:!1,escalationReasons:[]}}var ct={maxBreakpoints:4,retention:"short",minSegmentTokens:256,recentTailCount:2,markToolDefinitions:!0};function jo(e,t,n={}){let o={...ct,...n},r=t??Wo;if(o.retention==="none"||e.length===0)return{breakpoints:[],estimatedCacheableTokens:0,retention:o.retention};let i=Math.max(0,e.length-o.recentTailCount),s=e.map((p,m)=>({index:m,kind:m>=i?"recent":qo(p,o),tokens:r(p)})),a=[],l;for(let p of s)!l||l.kind!==p.kind?(l&&a.push(l),l={kind:p.kind,startIndex:p.index,endIndex:p.index,tokens:p.tokens}):(l.endIndex=p.index,l.tokens+=p.tokens);l&&a.push(l);let c=[];for(let p of a)p.kind!=="recent"&&(p.tokens<o.minSegmentTokens||c.push({index:p.endIndex,segment:p.kind,estimatedTokens:p.tokens}));c.sort((p,m)=>(m.estimatedTokens??0)-(p.estimatedTokens??0));let u=c.slice(0,o.maxBreakpoints);u.sort((p,m)=>p.index-m.index);let d=u.reduce((p,m)=>p+(m.estimatedTokens??0),0);return{breakpoints:u,estimatedCacheableTokens:d,retention:o.retention}}function Ho(e,t){let n=new Set(t.map(o=>o.index));return e.map((o,r)=>n.has(r)?Yo(o):o)}function Uo(e,t,n=1){return e<=0||t<=0?0:Math.min(1,t*Math.max(0,Math.min(1,n))/e)}function qo(e,t){let n=e.role;return n==="system"||n==="developer"?"system":(t.markToolDefinitions&&n==="tool"||e.tool_call_id,"conversation")}function Wo(e){let t=e.content;if(typeof t=="string")return Math.ceil(t.length/4);if(Array.isArray(t)){let n=0;for(let o of t)typeof o=="string"?n+=o.length:o&&typeof o=="object"&&"text"in o&&(n+=typeof o.text=="string"?o.text.length:0);return Math.ceil(n/4)}return 0}function Yo(e){let t={...e},n=t.content;if(typeof n=="string")t.content=[{type:"text",text:n,cache_control:{type:"ephemeral"}}];else if(Array.isArray(n)&&n.length>0){let o=n.map((r,i)=>i!==n.length-1?r:r&&typeof r=="object"?{...r,cache_control:{type:"ephemeral"}}:r);t.content=o}return t}function Go(e,t={}){return e<=0?-1:t.skipCacheWrite||t.isForkChild?Math.max(0,e-2):e-1}function Ko(){return{systemHash:null,toolsHash:null,modelId:null,thinkingEnabled:null}}function Vo(e,t){let n=[];return e.systemHash!==null&&e.systemHash!==t.systemHash&&n.push({field:"system",previousHash:e.systemHash,currentHash:t.systemHash}),e.toolsHash!==null&&e.toolsHash!==t.toolsHash&&n.push({field:"tools",previousHash:e.toolsHash,currentHash:t.toolsHash}),e.modelId!==null&&e.modelId!==t.modelId&&n.push({field:"model",previousHash:e.modelId,currentHash:t.modelId}),e.thinkingEnabled!==null&&e.thinkingEnabled!==t.thinkingEnabled&&n.push({field:"thinking",previousHash:String(e.thinkingEnabled),currentHash:String(t.thinkingEnabled)}),e.systemHash=t.systemHash,e.toolsHash=t.toolsHash,e.modelId=t.modelId,e.thinkingEnabled=t.thinkingEnabled,n}function Xo(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}var Y={minIdleSeconds:7200,intervalSeconds:604800,staleAfterDays:30,archiveAfterDays:90,maxReviewBatchSize:50},Jo={lastRunAt:null,lastRunDurationSeconds:0,lastRunSummary:"",paused:!1,runCount:0};function Qo(e){let t={...Y,...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 Zo(e,t,n){let o={...Y,...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 er(e,t){let n={...Y,...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 tr(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 nr(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(`
|
|
13
|
+
`),r=t.length>0?t.map(s=>`- ${s}`).join(`
|
|
14
|
+
`):"(none)";return`You are the Autonomous Curator for a skill library.
|
|
15
|
+
|
|
16
|
+
## Goal
|
|
17
|
+
|
|
18
|
+
Transform narrow, session-specific skills into a well-organized library of
|
|
19
|
+
class-level umbrella skills. A collection of hundreds of narrow skills is FAILURE.
|
|
20
|
+
|
|
21
|
+
## Ground Rules
|
|
22
|
+
|
|
23
|
+
1. **NEVER delete** \u2014 only archive (prune). Archived skills can be restored.
|
|
24
|
+
2. **Do NOT touch pinned or bundled skills** \u2014 they are already filtered out.
|
|
25
|
+
3. **Identify prefix clusters** and merge them into umbrella skills.
|
|
26
|
+
4. **Move session-specific details** into the umbrella's references/ folder.
|
|
27
|
+
5. **Preserve unique value** \u2014 only merge if the source is genuinely redundant
|
|
28
|
+
or a subset of the target.
|
|
29
|
+
|
|
30
|
+
## Detected Prefix Clusters
|
|
31
|
+
|
|
32
|
+
${n.length>0?n.map(s=>`- **${s.prefix}-***: ${s.skills.join(", ")}`).join(`
|
|
33
|
+
`):"(no clusters detected)"}
|
|
34
|
+
|
|
35
|
+
## Existing Umbrella Skills
|
|
36
|
+
|
|
37
|
+
${r}
|
|
38
|
+
|
|
39
|
+
## Candidate Skills for Review
|
|
40
|
+
|
|
41
|
+
${o}
|
|
42
|
+
|
|
43
|
+
## Required Output Format
|
|
44
|
+
|
|
45
|
+
Respond with EXACTLY this YAML block (no extra text outside the block):
|
|
46
|
+
|
|
47
|
+
\`\`\`yaml
|
|
48
|
+
consolidations:
|
|
49
|
+
- source: "skill-name-a"
|
|
50
|
+
target: "umbrella-skill"
|
|
51
|
+
reason: "subset of umbrella functionality"
|
|
52
|
+
- source: "skill-name-b"
|
|
53
|
+
target: "new-umbrella-name"
|
|
54
|
+
reason: "cluster merge"
|
|
55
|
+
|
|
56
|
+
prunings:
|
|
57
|
+
- skill: "skill-name-c"
|
|
58
|
+
reason: "trivial single-use, no ongoing value"
|
|
59
|
+
\`\`\`
|
|
60
|
+
|
|
61
|
+
If no consolidations or prunings are warranted, use empty lists.
|
|
62
|
+
Respond ONLY with the YAML block.`}function or(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 rr(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 ir(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 G={blockCreationThreshold:.75,curatorReviewThreshold:.55,toolWeight:.6,titleWeight:.3,stepWeight:.1};function dt(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 pt(e,t){let n=ut(e.toLowerCase()),o=ut(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 ut(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 mt(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 ft(e,t,n){let o={...G,...n},r=dt(e.tools,t.tools),i=pt(e.title,t.title),s=mt(e.stepCount,t.stepCount);return{overall:o.toolWeight*r+o.titleWeight*i+o.stepWeight*s,toolJaccard:r,titleSimilarity:i,stepProximity:s}}function sr(e,t,n){let o={...G,...n},r=[];for(let i of t){if(i.skillKey===e.skillKey)continue;let s=ft(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 ar(e,t){let n={...G,...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 gt={planner:3,executor:4,reviewer:2,researcher:3,custom:2},lr={parallel:4,sequential:1,pipeline:1,adaptive:3},K=8,cr=2;function ur(e){let t=e.subtasks.slice(0,K).map(i=>{let s=pr(i.role);return{agentId:i.id,role:i.role,label:i.label,sidechainType:yt(i.role),taskDescription:i.task,toolAccessMode:ht(i.role),budgetTier:s,dependsOn:i.dependsOn??[],maxTokenBudget:0,maxToolCalls:dr(i.role),timeoutMs:0}}),n=e.mode??Ct(t),o=e.totalTokenBudget??1e5,r=Tt(t,o);return{teamId:e.teamId,mode:n,aggregationPolicy:e.aggregationPolicy??bt(n,t),agents:r,maxConcurrency:lr[n],timeoutMs:e.timeoutMs??3e5,totalTokenBudget:o,failFast:e.failFast??n==="pipeline",sharedContext:e.sharedContext??"",mergePolicy:e.mergePolicy??"summary-only"}}function yt(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 ht(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 dr(e){switch(e){case"planner":return 0;case"executor":return 30;case"reviewer":return 10;case"researcher":return 15;case"custom":return 10}}function pr(e){switch(e){case"planner":return"high";case"executor":return"high";case"reviewer":return"medium";case"researcher":return"medium";case"custom":return"low"}}function Tt(e,t){let n=e.reduce((o,r)=>o+gt[r.role],0);return n===0?e:e.map(o=>({...o,maxTokenBudget:Math.floor(gt[o.role]/n*t)}))}function Ct(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 bt(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 mr(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 fr(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}]
|
|
63
|
+
${s.output}`).join(`
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
`);case"reviewer-gate":{let s=n.find(l=>l.role==="reviewer"),a=n.filter(l=>l.role!=="reviewer");return s?`[Review]
|
|
68
|
+
${s.output}
|
|
69
|
+
|
|
70
|
+
[Execution]
|
|
71
|
+
${a.map(l=>l.output).join(`
|
|
72
|
+
`)}`:a.map(l=>l.output).join(`
|
|
73
|
+
|
|
74
|
+
`)}case"planner-sync":{let s=n.find(l=>l.role==="planner"),a=n.filter(l=>l.role!=="planner");return s?`[Plan]
|
|
75
|
+
${s.output}
|
|
76
|
+
|
|
77
|
+
[Results]
|
|
78
|
+
${a.map(l=>`- ${l.agentId}: ${l.output.slice(0,500)}`).join(`
|
|
79
|
+
`)}`:a.map(l=>l.output).join(`
|
|
80
|
+
|
|
81
|
+
`)}}}function gr(e){let t=[];e.agents.length===0&&t.push("Team plan has no agents"),e.agents.length>K&&t.push(`Too many agents: ${e.agents.length} > ${K}`),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 yr(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 hr(e){let{agent:t,plan:n,dependencyResults:o}=e,r=[];if(n.sharedContext&&r.push(`[Shared Context]
|
|
82
|
+
${n.sharedContext}`),o.length>0){let i=o.filter(s=>s.status==="completed").map(s=>`[From ${s.agentId} (${s.role})]
|
|
83
|
+
${s.output}`).join(`
|
|
84
|
+
|
|
85
|
+
`);i&&r.push(`[Prior Results]
|
|
86
|
+
${i}`)}return r.push(`[Your Task]
|
|
87
|
+
${t.taskDescription}`),r.push(`[Your Role: ${t.role}]
|
|
88
|
+
${Tr(t.role)}`),r.join(`
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
`)}function Tr(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."}}function Cr(e,t={}){let n=Math.max(1,t.maxConcurrency??8),o=t.abortSignal,r=[],i=[],s=0,a=!1;o&&o.addEventListener("abort",()=>{a=!0},{once:!0});function l(d){if(a||r.length>=n)return!1;s+=1;let p=Date.now(),m={toolCallId:d.id,toolName:d.function.name,startedAt:p,promise:e(d,o).then(f=>({toolCallId:d.id,toolName:d.function.name,result:f,ok:!0,startedAt:p,completedAt:Date.now()})).catch(f=>({toolCallId:d.id,toolName:d.function.name,result:void 0,ok:!1,startedAt:p,completedAt:Date.now(),error:f instanceof Error?f.message:String(f)})).then(f=>{let T=r.indexOf(m);return T>=0&&r.splice(T,1),i.push(f),f})};return r.push(m),!0}function c(){return i.splice(0)}async function u(){return r.length>0&&await Promise.allSettled(r.map(d=>d.promise)),i.splice(0)}return{addTool:l,getCompletedResults:c,flush:u,get pendingCount(){return r.length},get dispatchedCount(){return s},get aborted(){return a}}}function br(e,t){return!(!t||t.approvalMode==="user-confirm"||t.requiresApproval||t.serialOnly)}var ye="<fork-child-context>",kt="Fork started \u2014 processing in background",kr=4,xr=2;function Rr(e){return JSON.stringify(e).includes(ye)}function Sr(e,t="in-memory"){return e<(t==="in-memory"?4:2)}function vr(e,t){let n=[...e.parentMessages],o={role:"user",content:[{type:"text",text:`${ye}
|
|
93
|
+
|
|
94
|
+
You are the "${t.agent.name}" agent.
|
|
95
|
+
|
|
96
|
+
${t.taskPrompt}`}]};return n.push(o),n}function Ar(e){return e.map(t=>({role:"tool",tool_call_id:t,content:kt}))}function Mr(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_tool")}function wr(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Er={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},_r={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_query","tool_search"],canFork:!1},Ir={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_query","todo","tool_search"],canFork:!1},Pr={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Lr={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_query"],canFork:!1},Fr={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},he=[Er,_r,Ir,Pr,Lr,Fr];function Or(){return[...he]}function Nr(e){return he.find(t=>t.name===e)}function Dr(e){return he.some(t=>t.name===e)}function Br(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")}function $r(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function zr(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 jr(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 Hr(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 Ur(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var xt={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function qr(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
|
|
97
|
+
${n.join(`
|
|
98
|
+
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
99
|
+
Step ${e.activeSkillContext.step}:
|
|
100
|
+
${e.activeSkillContext.instructions}`),e.toolDelta&&(e.toolDelta.added.length>0||e.toolDelta.removed.length>0)){let n=[];e.toolDelta.added.length>0&&n.push(`New tools available: ${e.toolDelta.added.join(", ")}`),e.toolDelta.removed.length>0&&n.push(`Tools no longer available: ${e.toolDelta.removed.join(", ")}`),t.push(`## Tool Changes
|
|
101
|
+
${n.join(`
|
|
102
|
+
`)}`)}if(e.customBlocks)for(let n of e.customBlocks)t.push(`## ${n.label}
|
|
103
|
+
${n.content}`);return t.length===0?null:`[Context was compressed. The following state has been restored:]
|
|
104
|
+
|
|
105
|
+
${t.join(`
|
|
106
|
+
|
|
107
|
+
`)}`}function Wr(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Yr(e,t=xt){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Gr(e,t){let n=new Set(e),o=new Set(t),r=e.filter(s=>!o.has(s)),i=t.filter(s=>!n.has(s));return{added:r,removed:i}}function Kr(e){let t=e.agents;if(t.length===0)return{batches:[],totalBudget:0,state:"planning"};if(t.length>8)throw new Error(`Team cannot have more than 8 agents (got ${t.length})`);if(e.mode==="parallel")return{batches:[{agents:t,mode:"parallel"}],totalBudget:t.length*5e4,state:"spawning"};if(e.mode==="sequential"||e.mode==="pipeline")return{batches:t.map(i=>({agents:[i],mode:"serial"})),totalBudget:t.length*5e4,state:"spawning"};let n=t.filter(i=>i.role==="planner"),o=t.filter(i=>i.role!=="planner"),r=[];return n.length>0&&r.push({agents:n,mode:"serial"}),o.length>0&&r.push({agents:o,mode:"parallel"}),{batches:r,totalBudget:t.length*5e4,state:"spawning"}}function Te(e,t){let n=e.reduce((i,s)=>i+s.result.tokensUsed,0),o=e.every(i=>i.result.ok),r=e.some(i=>i.result.ok);switch(t){case"first-success":{let i=e.find(s=>s.result.ok);return{ok:!!i,output:i?.result.output||"(No agent succeeded)",agentResults:e,totalTokensUsed:n,finalState:i?"completed":"failed"}}case"merge-all":{let i=e.map(s=>`### ${s.role} (${s.agentId})
|
|
108
|
+
${s.result.output||"(no output)"}`);return{ok:r,output:i.join(`
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
`),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(`
|
|
113
|
+
|
|
114
|
+
`);return i&&i.result.ok?{ok:!0,output:`## Reviewed Output
|
|
115
|
+
${a}
|
|
116
|
+
|
|
117
|
+
## Review
|
|
118
|
+
${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 Vr(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 Xr=["research","planner","plan-repair","code-repair","media-prep"],St={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"}},Ce=["gateway","agents_list","whatsapp_login","session_status","cron","memory_query","sessions_send"],Jr=["sessions_list","sessions_history","sessions_spawn"],Rt=["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 Qr(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?[...Ce,...Jr]:[...Ce],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?Ce.includes(l)?"always-deny":"leaf-deny":"default-allow"}});return{deniedTools:r,canSpawnChildren:!o,defaultDecision:"allowed",defaultInheritance:"inherit",tools:a}}function Oi(e){let t=vt(e.type),n=Qr({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(Rt),r=[...new Set([...n.deniedTools,...Rt])];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 Ni(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 Di(){return Xr.map(e=>St[e])}function vt(e){return St[e]}function Bi(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 $i(e,t={}){let n=vt(e);return Zr({forceManualReview:t.forceManualReview,preferFullContext:t.preferFullContext??n.preferFullContext,preserveConversationHistory:t.preserveConversationHistory??n.preserveConversationHistory})}function Zr(e={}){return e.forceManualReview?"manual":e.preferFullContext?e.preserveConversationHistory?"append-messages":"replace-context":"summary-only"}export{oe as CacheAwareCompressionStrategy,re as CompressionMetricsCollector,ie as ContextEngineRegistry,Ie as DEFAULT_ADAPTIVE_BUDGET_CONFIG,Y as DEFAULT_CURATOR_SCHEDULE_POLICY,ct as DEFAULT_PROMPT_CACHE_POLICY,xt as DEFAULT_REACTIVE_COMPACT_CONFIG,G as DEFAULT_SKILL_SIMILARITY_POLICY,kt as FORK_PLACEHOLDER_RESULT,ye as FORK_SENTINEL_TAG,O as FailoverError,te as HeadTailProtectedStrategy,Jo as INITIAL_CURATOR_STATE,ne as IncrementalCompactStrategy,kr as MAX_FORK_DEPTH,xr as MAX_SIDECHAIN_DB_DEPTH,yo as MEMORY_OBSERVATION_HOOK_VALUES,ho as MEMORY_OBSERVATION_SOURCE_VALUES,To as MEMORY_WRITE_ACCESS_VALUES,Ce as SIDECHAIN_TOOL_DENY_ALWAYS,Jr as SIDECHAIN_TOOL_DENY_LEAF,Rt as SIDECHAIN_TOOL_DENY_WRITE,Xr as SIDECHAIN_TYPE_VALUES,Q as SlidingWindowStrategy,Z as SummarizeOldStrategy,K as TEAM_MAX_AGENTS,cr as TEAM_MAX_DEPTH,ee as ToolResultTrimStrategy,po as advanceToolLoopState,fr as aggregateTeamResults,Te as aggregateTeamToolResults,Tt as allocateTokenBudgets,Ho as applyCacheMarkers,We as applyToolChoiceCompatibility,In as applyToolChoicePolicy,pt as bigramSimilarity,hr as buildAgentTaskPrompt,Bo as buildApprovalAwareReason,$o as buildApprovalStepContext,Lo as buildAssistantFailoverErrorDetails,It as buildAssistantToolCallMessage,nr as buildConsolidationPrompt,ir as buildCuratorRunSummary,Ar as buildForkPlaceholderResults,vr as buildForkedMessages,qr as buildPostCompactRestorationMessage,An as buildSkillCandidateEffectivenessSummary,He as buildSkillCandidateEvidencePayload,Sn as buildSkillCandidateImprovementEvidenceBundle,vn as buildSkillCandidateLatestReview,hn as buildSkillInstruction,ae as buildStructuredSummaryPrompt,Pt as buildToolResultMessage,zr as calculateTokenWarningState,br as canDispatchDuringStreaming,Sr as canForkAtDepth,un as classifyError,dn as classifyErrorFromReason,I as classifyFailoverReason,L as classifyFailoverReasonFromHttpStatus,Lt as cleanToolSchemaForGemini,qn as coerceToFailoverError,fn as composeAsyncStrategies,mn as composeStrategies,gn as computeAdaptiveBudget,jo as computeCacheBreakpoints,Zo as computeLifecycleTransitions,ft as computeSimilarity,Gr as computeToolDelta,Et as convertCapabilityToolManifestsToFunctionTools,xe as convertFunctionTools,Ko as createCacheBreakDetectionState,Rn as createDefaultSkillImprovementPolicy,Wr as createReactiveCompactState,Cr as createStreamingToolExecutor,ge as createToolLoopState,$r as createTurnLoopGuardState,ar as decideSimilarityAction,Un as describeFailoverError,Vo as detectCacheBreaks,tr as detectPrefixClusters,zn as downgradeOpenAiFunctionCallReasoningPairs,jn as downgradeOpenAiReasoningBlocks,Bn as ensureAssistantReasoningContent,Uo as estimateCacheSavingsRatio,xo as executeBoundedRetryLoop,qe as filterEligibleTools,Ni as filterToolCallsByAccessPolicy,sr as findSimilarSkills,wr as generateForkChildAgentId,Nr as getBuiltInAgent,Or as getBuiltInAgents,pn as getRetryStrategy,at as hasAlreadyFlushedForCurrentCompaction,bt as inferAggregationPolicy,Ct as inferExecutionMode,H as injectDanglingToolCallPlaceholders,se as isAsyncCompressionStrategy,Dr as isBuiltInAgent,sn as isCloudflareOrHtmlErrorPage,U as isFailoverError,ln as isFailoverErrorMessage,Rr as isInForkChild,Ee as isModelNotFoundErrorMessage,Qe as isTimeoutError,D as isTimeoutErrorMessage,we as isTransientHttpError,be as isXaiProvider,Di as listSidechainTypePolicies,yt as mapRoleToSidechainType,Vr as mapTeamRequestToForkConfigs,En as normalizeAnthropicFunctionToolDefinition,_n as normalizeAnthropicToolChoice,ke as normalizeFunctionToolParameters,Re as normalizeMessageTextContent,st as normalizeParallelToolCallsPreference,je as normalizeSkillImprovementPolicy,or as parseConsolidationOutput,_t as parseOpenAiToolCallsFromChatResponse,wo as pickFallbackThinkingLevel,Xo as quickHash,rr as reconcileConsolidationPlan,fo as recoverToolLoopStateFromChatConversation,go as recoverToolLoopStateFromResponsesItems,$n as repairOpenAiChatConversation,ue as repairOpenAiResponsesItems,rt as repairToolCallInputs,it as repairToolUseResultPairing,ht as resolveAgentToolAccess,Br as resolveAgentToolSet,jr as resolveApiErrorRecovery,Io as resolveAssistantFailureActionDecision,vo as resolveAuthProfileFailoverReason,mr as resolveExecutionOrder,fe as resolveFailoverReasonFromError,Je as resolveFailoverStatus,Ao as resolveFallbackThinkingDecision,Go as resolveForkCacheMarkerIndex,Mr as resolveForkChildTools,ko as resolveMemoryFlushProjection,bo as resolveMemoryFlushReadPlan,Hr as resolveOutputTokenEscalation,so as resolveParallelToolCallScheduling,Po as resolvePromptErrorPolicy,_o as resolvePromptFailureActionDecision,Bi as resolveRepairSidechainType,So as resolveRetryableFailureReason,Ro as resolveScaledRetryIterations,Zr as resolveSidechainMergePolicy,$i as resolveSidechainMergePolicyByType,Oi as resolveSidechainToolAccessByType,Qr as resolveSidechainToolAccessPolicy,vt as resolveSidechainTypePolicy,Kr as resolveTeamExecutionPlan,ur as resolveTeamPlan,zo as resolveWebBrowserPolicy,z as sanitizeOpenAiChatMessages,oo as sanitizeToolCallInputs,ro as sanitizeToolUseResultPairing,yn as selectCompressionTier,er as selectReviewCandidates,mo as settleToolLoopState,Ur as shouldAbortTurn,lt as shouldAttemptAssistantFailureRotation,Eo as shouldAttemptPromptFailureRotation,Yr as shouldAttemptReactiveCompact,yr as shouldCancelTeam,Fe as shouldCreateSkill,Oe as shouldImproveSkill,Qo as shouldRunCurator,Co as shouldRunMemoryFlush,mt as stepCountProximity,j as stripForcedStopAssistantToolMetadata,no as stripToolResultDetails,io as stripTransientErrorMessages,Do as summarizeApprovalAwareToolPlan,dt as toolSetJaccard,gr as validateTeamPlan};
|
package/package.json
CHANGED
|
@@ -1,43 +1,57 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "qlogicagent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "XiaozhiClaw Agent CLI — subprocess architecture (JSON-RPC over stdio)",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "dist/index.js",
|
|
7
|
-
"bin": {
|
|
8
|
-
"qlogicagent": "dist/cli
|
|
9
|
-
},
|
|
10
|
-
"exports": {
|
|
11
|
-
".":
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
"
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "qlogicagent",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "XiaozhiClaw Agent CLI — subprocess architecture (JSON-RPC over stdio)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"qlogicagent": "dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/types/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./agent": {
|
|
16
|
+
"types": "./dist/types/agent/agent.d.ts",
|
|
17
|
+
"default": "./dist/agent.js"
|
|
18
|
+
},
|
|
19
|
+
"./contracts": {
|
|
20
|
+
"types": "./dist/types/contracts/index.d.ts",
|
|
21
|
+
"default": "./dist/contracts.js"
|
|
22
|
+
},
|
|
23
|
+
"./orchestration": {
|
|
24
|
+
"types": "./dist/types/orchestration/index.d.ts",
|
|
25
|
+
"default": "./dist/orchestration.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist/"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"dev": "tsx watch src/index.ts",
|
|
33
|
+
"build": "node scripts/build.mjs",
|
|
34
|
+
"build:tsc": "tsc --noCheck",
|
|
35
|
+
"start": "node dist/cli/main.js",
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"test:watch": "vitest",
|
|
38
|
+
"lint": "oxlint ."
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22.0.0"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"dotenv": "^17.3.1",
|
|
45
|
+
"nanoid": "^5.1.5",
|
|
46
|
+
"pino": "^9.6.0",
|
|
47
|
+
"pino-pretty": "^13.0.0",
|
|
48
|
+
"qlogicagent-runtime-contracts": "^3.0.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/node": "^22.15.0",
|
|
52
|
+
"esbuild": "^0.28.0",
|
|
53
|
+
"tsx": "^4.19.0",
|
|
54
|
+
"typescript": "^5.9.0",
|
|
55
|
+
"vitest": "^3.1.0"
|
|
56
|
+
}
|
|
43
57
|
}
|
package/dist/agent/agent.js
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Agent — clean agent execution loop for CLI subprocess mode.
|
|
3
|
-
*
|
|
4
|
-
* Thin wrapper around tool-loop.ts. Handles:
|
|
5
|
-
* - DI injection (LLMTransport, ToolInvoker, AgentLogger)
|
|
6
|
-
* - Turn lifecycle (start event + message repair + delegate to tool loop)
|
|
7
|
-
* - Top-level error handling
|
|
8
|
-
*
|
|
9
|
-
* The actual tool loop state machine (turn-loop-guard, tool-loop-state,
|
|
10
|
-
* parallel scheduling, sidechain filtering, etc.) lives in tool-loop.ts,
|
|
11
|
-
* ported faithfully from Hub's semantic-turn-tools.ts.
|
|
12
|
-
*
|
|
13
|
-
* Zero imports from express/pg/ioredis/ws.
|
|
14
|
-
*/
|
|
15
|
-
import { repairOpenAiChatConversation, classifyError, getRetryStrategy, } from "../orchestration/index.js";
|
|
16
|
-
import { executeToolLoop } from "./tool-loop.js";
|
|
17
|
-
const MAX_ROUNDS_LIMIT = 100;
|
|
18
|
-
export class Agent {
|
|
19
|
-
transport;
|
|
20
|
-
apiKey;
|
|
21
|
-
toolInvoker;
|
|
22
|
-
log;
|
|
23
|
-
hooks;
|
|
24
|
-
maxRounds;
|
|
25
|
-
constructor(config) {
|
|
26
|
-
this.transport = config.llmTransport;
|
|
27
|
-
this.apiKey = config.apiKey;
|
|
28
|
-
this.toolInvoker = config.toolInvoker;
|
|
29
|
-
this.log = config.log;
|
|
30
|
-
this.hooks = config.hooks;
|
|
31
|
-
this.maxRounds = Math.min(config.maxRounds ?? 25, MAX_ROUNDS_LIMIT);
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Execute an agent turn. Yields TurnEvent stream.
|
|
35
|
-
*
|
|
36
|
-
* 1. Emit start
|
|
37
|
-
* 2. Repair conversation history
|
|
38
|
-
* 3. Delegate to executeToolLoop() (full Hub-ported tool loop state machine)
|
|
39
|
-
* 4. Catch unhandled errors
|
|
40
|
-
*/
|
|
41
|
-
async *run(request, signal) {
|
|
42
|
-
const { turnId, messages: inputMessages, tools, systemPrompt, config } = request;
|
|
43
|
-
const hookCtx = { sessionId: request.sessionId, turnId };
|
|
44
|
-
yield { type: "start", turnId };
|
|
45
|
-
// Hook: turn.submitted
|
|
46
|
-
this.hooks?.invoke("turn.submitted", {
|
|
47
|
-
...hookCtx,
|
|
48
|
-
prompt: inputMessages[inputMessages.length - 1]?.content ?? undefined,
|
|
49
|
-
}).catch(() => { });
|
|
50
|
-
// Repair malformed tool-call sequences in the input conversation history
|
|
51
|
-
const repairedMessages = repairOpenAiChatConversation(inputMessages);
|
|
52
|
-
// Build conversation: prepend system prompt if provided
|
|
53
|
-
const conversation = [];
|
|
54
|
-
if (systemPrompt) {
|
|
55
|
-
conversation.push({ role: "system", content: systemPrompt });
|
|
56
|
-
}
|
|
57
|
-
conversation.push(...repairedMessages);
|
|
58
|
-
const model = config?.model ?? "";
|
|
59
|
-
const maxRounds = Math.min(config?.maxRounds ?? this.maxRounds, MAX_ROUNDS_LIMIT);
|
|
60
|
-
try {
|
|
61
|
-
const toolLoopParams = {
|
|
62
|
-
turnId,
|
|
63
|
-
sessionId: request.sessionId,
|
|
64
|
-
messages: conversation,
|
|
65
|
-
tools,
|
|
66
|
-
model,
|
|
67
|
-
apiKey: config?.apiKey ?? this.apiKey,
|
|
68
|
-
temperature: config?.temperature,
|
|
69
|
-
maxRounds,
|
|
70
|
-
contextWindowTokens: config?.contextWindowTokens,
|
|
71
|
-
maxOutputTokens: config?.maxOutputTokens,
|
|
72
|
-
modelMaxOutputTokens: config?.modelMaxOutputTokens,
|
|
73
|
-
toolChoice: config?.toolChoice,
|
|
74
|
-
parentDepth: config?.parentDepth,
|
|
75
|
-
hooks: this.hooks,
|
|
76
|
-
signal,
|
|
77
|
-
};
|
|
78
|
-
let lastEvent;
|
|
79
|
-
for await (const event of executeToolLoop(toolLoopParams, this.transport, this.toolInvoker, this.log)) {
|
|
80
|
-
lastEvent = event;
|
|
81
|
-
yield event;
|
|
82
|
-
}
|
|
83
|
-
// Hook: turn.completed / turn.failed based on final event
|
|
84
|
-
if (lastEvent?.type === "end") {
|
|
85
|
-
this.hooks?.invoke("turn.completed", { ...hookCtx }).catch(() => { });
|
|
86
|
-
}
|
|
87
|
-
else if (lastEvent?.type === "error") {
|
|
88
|
-
this.hooks?.invoke("turn.failed", {
|
|
89
|
-
...hookCtx,
|
|
90
|
-
code: lastEvent.code,
|
|
91
|
-
error: lastEvent.error,
|
|
92
|
-
}).catch(() => { });
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
catch (err) {
|
|
96
|
-
if (signal?.aborted) {
|
|
97
|
-
this.hooks?.invoke("turn.failed", { ...hookCtx, code: "ABORTED", error: "Turn aborted" }).catch(() => { });
|
|
98
|
-
yield { type: "error", turnId, error: "Turn aborted", code: "ABORTED" };
|
|
99
|
-
}
|
|
100
|
-
else {
|
|
101
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
102
|
-
const status = typeof err?.status === "number"
|
|
103
|
-
? err.status
|
|
104
|
-
: undefined;
|
|
105
|
-
const category = classifyError(status, message);
|
|
106
|
-
const strategy = getRetryStrategy(category);
|
|
107
|
-
this.log.error(`turn ${turnId} error [${category}, retryable=${strategy.retryable}]: ${message}`);
|
|
108
|
-
this.hooks?.invoke("turn.failed", { ...hookCtx, code: category, error: message }).catch(() => { });
|
|
109
|
-
yield { type: "error", turnId, error: message, code: category };
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
}
|