qlogicagent 0.5.2 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +402 -402
- package/dist/agent.js +18 -0
- package/dist/cli.js +360 -0
- package/dist/contracts.js +1 -0
- package/dist/index.js +22 -0
- package/dist/orchestration.js +125 -0
- package/dist/types/agent/agent.d.ts +43 -0
- package/dist/types/agent/constants.d.ts +47 -0
- package/dist/types/agent/tool-loop.d.ts +96 -0
- package/dist/types/agent/types.d.ts +250 -0
- package/dist/types/cli/main.d.ts +11 -0
- package/dist/types/cli/stdio-server.d.ts +56 -0
- package/dist/types/cli/tool-bootstrap.d.ts +21 -0
- package/dist/types/config/config.d.ts +17 -0
- package/dist/types/contracts/hooks.d.ts +175 -0
- package/dist/types/contracts/index.d.ts +10 -0
- package/dist/types/contracts/planner.d.ts +35 -0
- package/dist/types/contracts/skill-candidate.d.ts +63 -0
- package/dist/types/contracts/todo.d.ts +14 -0
- package/dist/types/index.d.ts +13 -0
- package/dist/types/llm/builtin-providers.d.ts +10 -0
- package/dist/types/llm/debug-transport.d.ts +12 -0
- package/dist/types/llm/index.d.ts +16 -0
- package/dist/types/llm/llm-client.d.ts +43 -0
- package/dist/types/llm/model-catalog.d.ts +53 -0
- package/dist/types/llm/provider-def.d.ts +59 -0
- package/dist/types/llm/provider-registry.d.ts +54 -0
- package/dist/types/llm/transport.d.ts +62 -0
- package/dist/types/llm/transports/anthropic-messages.d.ts +31 -0
- package/dist/types/llm/transports/openai-chat.d.ts +36 -0
- package/dist/types/orchestration/agent-registry.d.ts +46 -0
- package/dist/types/orchestration/context-collapse.d.ts +58 -0
- package/dist/types/orchestration/context-compression.d.ts +301 -0
- package/dist/types/orchestration/conversation-repair.d.ts +61 -0
- package/dist/types/orchestration/curator-scheduler.d.ts +119 -0
- package/dist/types/orchestration/error-classification.d.ts +12 -0
- package/dist/types/orchestration/failover-classification.d.ts +8 -0
- package/dist/types/orchestration/failover-error.d.ts +33 -0
- package/dist/types/orchestration/fork-subagent.d.ts +100 -0
- package/dist/types/orchestration/index.d.ts +113 -0
- package/dist/types/orchestration/memory-provider.d.ts +14 -0
- package/dist/types/orchestration/reactive-compact.d.ts +73 -0
- package/dist/types/orchestration/retry-loop.d.ts +69 -0
- package/dist/types/orchestration/skill-candidate.d.ts +52 -0
- package/dist/types/orchestration/skill-consolidation.d.ts +123 -0
- package/dist/types/orchestration/skill-improvement.d.ts +59 -0
- package/dist/types/orchestration/skill-similarity.d.ts +98 -0
- package/dist/types/orchestration/task-types.d.ts +142 -0
- package/dist/types/orchestration/team-orchestration.d.ts +195 -0
- package/dist/types/orchestration/team-tool-loop-wiring.d.ts +92 -0
- package/dist/types/orchestration/tool-choice-policy.d.ts +54 -0
- package/dist/types/orchestration/tool-loop-state.d.ts +50 -0
- package/dist/types/orchestration/tool-schema.d.ts +39 -0
- package/dist/types/orchestration/turn-loop-guard.d.ts +86 -0
- package/dist/types/runtime/execution/dream-agent.d.ts +199 -0
- package/dist/types/runtime/execution/forked-agent.d.ts +111 -0
- package/dist/types/runtime/execution/index.d.ts +6 -0
- package/dist/types/runtime/execution/progress-tracker.d.ts +78 -0
- package/dist/types/runtime/execution/remote-agent.d.ts +63 -0
- package/dist/types/runtime/execution/streaming-tool-executor.d.ts +100 -0
- package/dist/types/runtime/execution/tool-eligibility.d.ts +59 -0
- package/dist/types/runtime/execution/tool-result-storage.d.ts +87 -0
- package/dist/types/runtime/hooks/context-compression.d.ts +61 -0
- package/dist/types/runtime/hooks/hook-registry.d.ts +12 -0
- package/dist/types/runtime/hooks/index.d.ts +3 -0
- package/dist/types/runtime/hooks/memory-hooks.d.ts +49 -0
- package/dist/types/runtime/index.d.ts +5 -0
- package/dist/types/runtime/infra/cleanup-registry.d.ts +23 -0
- package/dist/types/runtime/infra/file-watcher.d.ts +72 -0
- package/dist/types/runtime/infra/index.d.ts +6 -0
- package/dist/types/runtime/infra/secure-storage.d.ts +81 -0
- package/dist/types/runtime/infra/task-runtime.d.ts +108 -0
- package/dist/types/runtime/infra/token-budget.d.ts +92 -0
- package/dist/types/runtime/infra/worktree-backend.d.ts +85 -0
- package/dist/types/runtime/prompt/environment-context.d.ts +23 -0
- package/dist/types/runtime/prompt/index.d.ts +3 -0
- package/dist/types/runtime/prompt/instruction-loader.d.ts +64 -0
- package/dist/types/runtime/prompt/system-prompt-sections.d.ts +63 -0
- package/dist/types/runtime/session/index.d.ts +2 -0
- package/dist/types/runtime/session/session-memory.d.ts +91 -0
- package/dist/types/runtime/session/session-persistence.d.ts +94 -0
- package/dist/types/runtime/session/session-state.d.ts +117 -0
- package/dist/types/skills/index.d.ts +125 -0
- package/dist/types/skills/mcp/index.d.ts +3 -0
- package/dist/types/skills/mcp/mcp-http-client.d.ts +66 -0
- package/dist/types/skills/mcp/mcp-manager.d.ts +84 -0
- package/dist/types/skills/mcp/mcp-stdio-client.d.ts +84 -0
- package/dist/types/skills/memory-extractor.d.ts +64 -0
- package/dist/types/skills/memory-query-tool.d.ts +43 -0
- package/dist/types/skills/memory-store.d.ts +66 -0
- package/dist/types/skills/memory-tool.d.ts +67 -0
- package/dist/types/skills/permissions/bash-classifier.d.ts +30 -0
- package/dist/types/skills/permissions/classifier-cache.d.ts +51 -0
- package/dist/types/skills/permissions/denial-tracking.d.ts +42 -0
- package/dist/types/skills/permissions/hook-runner.d.ts +85 -0
- package/dist/types/skills/permissions/index.d.ts +12 -0
- package/dist/types/skills/permissions/permission-classifier.d.ts +41 -0
- package/dist/types/skills/permissions/rule-engine.d.ts +41 -0
- package/dist/types/skills/permissions/settings-watcher.d.ts +46 -0
- package/dist/types/skills/permissions/types.d.ts +113 -0
- package/dist/types/skills/plugins/index.d.ts +2 -0
- package/dist/types/skills/plugins/plugin-api.d.ts +38 -0
- package/dist/types/skills/plugins/plugin-loader.d.ts +45 -0
- package/dist/types/skills/plugins/plugin-marketplace.d.ts +61 -0
- package/dist/types/skills/portable-tool.d.ts +71 -0
- package/dist/types/skills/qmemory-adapter.d.ts +42 -0
- package/dist/types/skills/skill-frontmatter.d.ts +19 -0
- package/dist/types/skills/skill-guard.d.ts +23 -0
- package/dist/types/skills/skill-loader.d.ts +16 -0
- package/dist/types/skills/skill-source.d.ts +119 -0
- package/dist/types/skills/skill-types.d.ts +199 -0
- package/dist/types/skills/think-tool.d.ts +16 -0
- package/dist/types/skills/todo-tool.d.ts +63 -0
- package/dist/types/skills/tool-registry.d.ts +29 -0
- package/dist/types/skills/tools/agent-tool.d.ts +91 -0
- package/dist/types/skills/tools/apply-patch-tool.d.ts +29 -0
- package/dist/types/skills/tools/ask-user-tool.d.ts +80 -0
- package/dist/types/skills/tools/brief-tool.d.ts +74 -0
- package/dist/types/skills/tools/browser-tool.d.ts +114 -0
- package/dist/types/skills/tools/checkpoint-tool.d.ts +66 -0
- package/dist/types/skills/tools/config-tool.d.ts +63 -0
- package/dist/types/skills/tools/cron-tool.d.ts +116 -0
- package/dist/types/skills/tools/edit-tool.d.ts +43 -0
- package/dist/types/skills/tools/exec-tool.d.ts +97 -0
- package/dist/types/skills/tools/image-generate-tool.d.ts +62 -0
- package/dist/types/skills/tools/instructions-tool.d.ts +103 -0
- package/dist/types/skills/tools/lsp-tool.d.ts +153 -0
- package/dist/types/skills/tools/mcp-client-types.d.ts +269 -0
- package/dist/types/skills/tools/mcp-resource-tools.d.ts +14 -0
- package/dist/types/skills/tools/mcp-tool.d.ts +249 -0
- package/dist/types/skills/tools/memory-tool.d.ts +74 -0
- package/dist/types/skills/tools/monitor-tool.d.ts +113 -0
- package/dist/types/skills/tools/music-generate-tool.d.ts +55 -0
- package/dist/types/skills/tools/notebook-edit-tool.d.ts +15 -0
- package/dist/types/skills/tools/notify-tool.d.ts +53 -0
- package/dist/types/skills/tools/patch-tool.d.ts +45 -0
- package/dist/types/skills/tools/pdf-tool.d.ts +66 -0
- package/dist/types/skills/tools/plan-mode-tool.d.ts +98 -0
- package/dist/types/skills/tools/read-tool.d.ts +51 -0
- package/dist/types/skills/tools/repl-tool.d.ts +70 -0
- package/dist/types/skills/tools/search-tool.d.ts +112 -0
- package/dist/types/skills/tools/send-message-tool.d.ts +51 -0
- package/dist/types/skills/tools/shell/bash-provider.d.ts +26 -0
- package/dist/types/skills/tools/shell/command-classification.d.ts +44 -0
- package/dist/types/skills/tools/shell/command-semantics.d.ts +14 -0
- package/dist/types/skills/tools/shell/destructive-command-warning.d.ts +10 -0
- package/dist/types/skills/tools/shell/exec-permissions.d.ts +52 -0
- package/dist/types/skills/tools/shell/index.d.ts +17 -0
- package/dist/types/skills/tools/shell/powershell-provider.d.ts +15 -0
- package/dist/types/skills/tools/shell/shell-command.d.ts +54 -0
- package/dist/types/skills/tools/shell/shell-exec.d.ts +33 -0
- package/dist/types/skills/tools/shell/shell-provider.d.ts +85 -0
- package/dist/types/skills/tools/shell/task-output.d.ts +45 -0
- package/dist/types/skills/tools/skill-invoke-tool.d.ts +46 -0
- package/dist/types/skills/tools/skill-list-tool.d.ts +33 -0
- package/dist/types/skills/tools/skill-manage-tool.d.ts +73 -0
- package/dist/types/skills/tools/skill-view-tool.d.ts +37 -0
- package/dist/types/skills/tools/sleep-tool.d.ts +49 -0
- package/dist/types/skills/tools/structured-output-tool.d.ts +116 -0
- package/dist/types/skills/tools/task-tool.d.ts +104 -0
- package/dist/types/skills/tools/team-tool.d.ts +89 -0
- package/dist/types/skills/tools/tool-search-tool.d.ts +51 -0
- package/dist/types/skills/tools/tts-tool.d.ts +38 -0
- package/dist/types/skills/tools/video-edit-tool.d.ts +69 -0
- package/dist/types/skills/tools/video-generate-tool.d.ts +62 -0
- package/dist/types/skills/tools/video-merge-tool.d.ts +105 -0
- package/dist/types/skills/tools/video-upscale-tool.d.ts +45 -0
- package/dist/types/skills/tools/web-fetch-tool.d.ts +78 -0
- package/dist/types/skills/tools/web-search-tool.d.ts +57 -0
- package/dist/types/skills/tools/workflow-tool.d.ts +44 -0
- package/dist/types/skills/tools/worktree-tool.d.ts +69 -0
- package/dist/types/skills/tools/write-tool.d.ts +45 -0
- package/package.json +3 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var U=["pending","in-progress","completed","skipped"],D=["active","completed","abandoned"];var R=["not-started","in-progress","completed"];function z(n){return{total:n.length,completed:n.filter(t=>t.status==="completed").length,inProgress:n.filter(t=>t.status==="in-progress").length,notStarted:n.filter(t=>t.status==="not-started").length}}var I=["draft","in_review","approved","rejected","canary","published","stale","superseded","rolled_back"],b=["submit-review","approve","reject","start-canary","record-effectiveness","promote","publish","mark-stale","mark-superseded","rollback"],_=["canary","published"];function e(n){if(typeof n!="string")return;let t=n.trim();return t||void 0}function c(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n!="string")return;let t=n.trim();if(!t)return;let r=Number(t);return Number.isFinite(r)?r:void 0}function S(n,t=0){let r=c(n);return r===void 0?Math.max(0,Math.floor(t)):Math.max(0,Math.floor(r))}function d(n){return n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{}}function h(n){return typeof n=="string"&&I.includes(n)}function L(n){return typeof n=="string"&&b.includes(n)}function v(n){return typeof n=="string"&&_.includes(n)}function O(n,t="draft"){let r=e(n);return r&&h(r)?r:t}function w(n){let t=e(n);return t&&L(t)?t:null}function P(n){let t=e(n);return t&&v(t)?t:null}function K(n){let t=d(n),r=e(t.uri);if(!r)return null;let o=e(t.sha256),i=e(t.workspaceDir),s=e(t.relativePath),a=e(t.sourceWorkspaceDir),u=e(t.stagedAt);return{uri:r,...o?{sha256:o}:{},...i?{workspaceDir:i}:{},...s?{relativePath:s}:{},...a?{sourceWorkspaceDir:a}:{},...u?{stagedAt:u}:{}}}function M(n){let t=d(n),r=e(t.executionId),o=e(t.rootExecutionId),i=e(t.parentExecutionId),s=e(t.sidechainId),a=e(t.attemptId),u=e(t.outcomeId),l=e(t.sessionId),p=e(t.turnId);return!r&&!o&&!i&&!s&&!a&&!u&&!l&&!p?null:{...r?{executionId:r}:{},...o?{rootExecutionId:o}:{},...i?{parentExecutionId:i}:{},...s?{sidechainId:s}:{},...a?{attemptId:a}:{},...u?{outcomeId:u}:{},...l?{sessionId:l}:{},...p?{turnId:p}:{}}}function F(n){let t=d(n),r=w(t.action);if(!r)return null;let o=e(t.actor)??null,i=e(t.notes)??null,s=d(t.payload),a=e(t.createdAt);return{action:r,actor:o,notes:i,payload:s,...a?{createdAt:a}:{}}}function j(n){let t=d(n),r=P(t.phase);if(!r)return null;let o=S(t.successCount),i=c(t.failureCount),s=S(t.sampleCount,i!==void 0?o+i:o),a=S(t.failureCount,Math.max(s-o,0)),u=S(t.regressionCount),l=c(t.successRate)??(s>0?o/s:0),p=c(t.regressionRate)??(s>0?u/s:0),f=c(t.avgLatencyMs),m=c(t.avgCostUsd),g=c(t.score),A=e(t.staleReason)??null,k=e(t.notes)??null,C=d(t.summary),x=e(t.lastObservedAt),T=e(t.updatedAt),y=e(t.lastActivityAt),E=c(t.activityCount);return{phase:r,sampleCount:s,successCount:o,failureCount:a,regressionCount:u,successRate:l,regressionRate:p,...f!==void 0?{avgLatencyMs:f}:{},...m!==void 0?{avgCostUsd:m}:{},...g!==void 0?{score:g}:{},...A?{staleReason:A}:{},...k?{notes:k}:{},...Object.keys(C).length>0?{summary:C}:{},...x?{lastObservedAt:x}:{},...T?{updatedAt:T}:{},...y?{lastActivityAt:y}:{},...E!==void 0?{activityCount:E}:{}}}export{b as SKILL_CANDIDATE_ACTION_VALUES,_ as SKILL_CANDIDATE_EFFECTIVENESS_PHASE_VALUES,I as SKILL_CANDIDATE_STATUS_VALUES,D as TASK_PLAN_STATUS_VALUES,U as TASK_STEP_STATUS_VALUES,R as TODO_ITEM_STATUS_VALUES,d as coerceSkillCandidateJsonObject,L as isSkillCandidateAction,v as isSkillCandidateEffectivenessPhase,h as isSkillCandidateStatus,w as normalizeSkillCandidateAction,K as normalizeSkillCandidateArtifact,j as normalizeSkillCandidateEffectiveness,P as normalizeSkillCandidateEffectivenessPhase,F as normalizeSkillCandidateReview,M as normalizeSkillCandidateSourceExecution,O as normalizeSkillCandidateStatus,z as summarizeTodoList};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
var ln=Object.defineProperty;var cn=(t,e)=>()=>(t&&(e=t(t=0)),e);var un=(t,e)=>{for(var o in e)ln(t,o,{get:e[o],enumerable:!0})};var Yt={};un(Yt,{resolveToolEligibility:()=>zo});function Bo(t,e){if($o.some(o=>o.test(t)))return!0;if(e)for(let o of e)try{if(new RegExp(o,"i").test(t))return!0}catch{}return!1}function Ho(t,e){let o=t.function.name,n=t.meta,r=[];return e.blockedToolNames?.includes(o)?(r.push("policy_blocked"),{level:5,reasons:r}):n?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):n?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):n?.isDangerous||Bo(o,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function jo(t){switch(t){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function zo(t,e={}){let o=new Map,n=[],r=[],s=[];for(let a of t){let i=a.function.name,{level:c,reasons:m}=Ho(a,e),d=jo(c),g={toolName:i,status:d,permissionLevel:c,approvalRequired:c===4,reasonCodes:m};o.set(i,g),c===5?r.push(g):(n.push(a),c===4&&s.push(g))}return{eligibleTools:n,blockedTools:r,approvalRequiredTools:s,eligibilityByName:o}}var $o,Vt=cn(()=>{"use strict";$o=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function xe(t){return{role:"assistant",content:"",tool_calls:t}}function Q(t,e){return{role:"tool",tool_call_id:t,content:JSON.stringify(e.ok?{ok:!0,payload:e.payload}:{ok:!1,error:e.error??"Tool invoke failed"})}}var dn=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,B={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]},pn=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,mn=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,gn=512,fn=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var yn=new Set([500,502,503,504,521,522,523,524,529]),hn=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Tn=["upgrade your plan","upgrade plan","current plan","subscription"],Cn=["daily","weekly","monthly"],bn=["try again","retry","temporary","cooldown"],kn=["usage limit","rate limit","organization usage"],xn=["organization","workspace"],Sn=["billing period","exceeded","reached","exhausted"],vn=/["']?(?: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,Rn=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function H(t,e){if(!t)return!1;let o=t.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function _n(t){return H(t,B.format)}function lt(t){return H(t,B.rateLimit)}function An(t){return H(t,B.timeout)}function Mn(t){return dn.test(t)}function Se(t){let e=t.toLowerCase();return e?t.length>gn?mn.test(e):H(e,B.billing)?!0:pn.test(t)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function ct(t){return H(t,B.authPermanent)}function wn(t){return H(t,B.auth)}function ut(t){return H(t,B.overloaded)}function $(t,e){return e.some(o=>t.includes(o))}function En(t){return $(t,hn)||$(t,Tn)&&t.includes("limit")||t.includes("billing hard limit")||t.includes("hard limit reached")||t.includes("maximum allowed")&&t.includes("limit")}function In(t){let e=$(t,Cn),o=t.includes("spend limit")||t.includes("spending limit"),n=$(t,xn);return $(t,bn)&&$(t,kn)||e&&(t.includes("usage limit")||o)||e&&t.includes("limit")&&t.includes("reset")||n&&t.includes("limit")&&(o||$(t,Sn))}function Ln(t){return t.trim().toLowerCase().replace(Rn,"").trim()}function dt(t){let e=Ln(t);return!e||En(e)?"billing":lt(e)||In(e)?"rate_limit":"billing"}function On(t){return vn.test(t)?dt(t):null}function pt(t){let e=t.match(fn);if(!e)return null;let o=Number(e[1]);return Number.isFinite(o)?{code:o,rest:(e[2]??"").trim()}:null}function Pn(t){if(!t)return!1;let e=t.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function Dn(t){let e=t.trim();if(!e)return!1;let o=pt(e);return o?yn.has(o.code):!1}function mt(t,e){return typeof t!="number"||!Number.isFinite(t)?null:t===402?e?dt(e):"billing":t===429?"rate_limit":t===401||t===403?e&&ct(e)?"auth_permanent":"auth":t===408?"timeout":t===503?e&&ut(e)?"overloaded":"timeout":t===502||t===504?"timeout":t===529?"overloaded":t===400?e&&Se(e)?"billing":"format":null}function Nn(t){if(!t)return!1;let e=t.toLowerCase();return!!(e.includes("unknown model")||e.includes("model not found")||e.includes("model_not_found")||e.includes("not_found_error")||e.includes("does not exist")&&e.includes("model")||e.includes("invalid model")&&!e.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(t)||/\b404\b/.test(t)&&/not[-_ ]?found/i.test(t))}function Fn(t){if(!t)return!1;let e=t.toLowerCase();return e.includes("session not found")||e.includes("session does not exist")||e.includes("session expired")||e.includes("session invalid")||e.includes("conversation not found")||e.includes("conversation does not exist")||e.includes("conversation expired")||e.includes("conversation invalid")||e.includes("no such session")||e.includes("invalid session")||e.includes("session id not found")||e.includes("conversation id not found")}function gt(t){if(Fn(t))return"session_expired";if(Nn(t))return"model_not_found";let e=On(t);return e||(Mn(t)?Se(t)?"billing":"rate_limit":lt(t)?"rate_limit":ut(t)?"overloaded":Dn(t)?pt(t.trim())?.code===529?"overloaded":"timeout":Pn(t)?"timeout":_n(t)?"format":Se(t)?"billing":An(t)?"timeout":ct(t)?"auth_permanent":wn(t)?"auth":null)}var Un={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"},$n={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 Z(t,e){let o=mt(t,e)??(e?gt(e):null);return o?Un[o]:typeof t=="number"&&t>=400&&t<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ve(t){return $n[t]}var ft=4,ee=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,o){let n=[],r=[];for(let d of e)d.role==="system"?n.push(d):r.push(d);let s=o;for(let d of n)s-=this.estimateTokens(d);let a;for(let d of r)if(d.role==="user"){a=d;break}if(a&&(s-=this.estimateTokens(a)),s<=0)return{messages:a?[...n,a]:n,droppedCount:r.length-(a?1:0),strategy:"sliding-window"};let i=[],c=0;for(let d=r.length-1;d>=0;d--){let g=r[d];if(g===a)continue;let b=this.estimateTokens(g);if(s-b<0&&c>=ft)break;if(s-b<0&&c<ft){i.unshift(g),c++;continue}s-=b,i.unshift(g),c++}let m=[...n];return a&&!i.includes(a)&&m.push(a),m.push(...i),{messages:m,droppedCount:r.length-(i.length+(a&&!i.includes(a)?1:0)),strategy:"sliding-window"}}};var te=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,o){let n=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(n++,{...s,content:Bn(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};function Bn(t,e){if(t.length<=e)return t;let o=t.slice(0,e);if(t.trimStart().startsWith("{")||t.trimStart().startsWith("[")){let s=Math.max(o.lastIndexOf("},"),o.lastIndexOf("],"),o.lastIndexOf(`}
|
|
2
|
+
`),o.lastIndexOf(`]
|
|
3
|
+
`));if(s>e*.5)return o.slice(0,s+1)+`
|
|
4
|
+
[...truncated: ${t.length-s-1} chars omitted]`}let r=o.lastIndexOf(`
|
|
5
|
+
`);return r>e*.7?o.slice(0,r)+`
|
|
6
|
+
[...truncated: ${t.length-r} chars omitted]`:o+`
|
|
7
|
+
[...truncated: ${t.length-e} chars omitted]`}function Re(...t){return{compress(e,o){let n=e,r=0,s=[];for(let a of t){let i=a.compress(n,o);n=i.messages,r+=i.droppedCount,i.droppedCount>0&&s.push(i.strategy)}return{messages:n,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}var yt={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function _e(t={}){let e={...yt,...t},o=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(o,e.maxBudget))}function Ae(t,e){let o=t/e;return o<=.8?"none":o<=1?"trim-only":o<=1.5?"sliding-window":"llm-summarize"}var ne=class{events=[];maxEvents;constructor(e=100){this.maxEvents=e}record(e){this.events.push(e),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let e=this.events.length;if(e===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let o=0,n=0,r=0,s=0,a=0;for(let i of this.events)o+=i.tokensBefore>0?i.tokensAfter/i.tokensBefore:1,n+=i.latencyMs,r+=Math.max(0,i.tokensBefore-i.tokensAfter),i.usedLlm&&s++,i.cacheInvalidated&&a++;return{totalCompressions:e,totalLlmCalls:s,totalCacheInvalidations:a,averageCompressionRatio:o/e,averageLatencyMs:n/e,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},oe=class{engines=new Map;activeId;register(e){this.engines.set(e.id,e)}activate(e){return this.engines.has(e)?(this.activeId=e,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(e=>({id:e.id,label:e.label,active:e.id===this.activeId}))}};function ht(t){let e=typeof t.content=="string"?t.content:t.content!=null?JSON.stringify(t.content):"";return Math.ceil(e.length/4)}var Hn=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),j=class{constructor(e=20,o=ht){this.preserveRecentCount=e;this.estimateTokens=o}preserveRecentCount;estimateTokens;compress(e,o){if(e.length<=this.preserveRecentCount)return{messages:e,droppedCount:0,strategy:"micro-compact"};let n=e.length-this.preserveRecentCount,r=0,s=0;return{messages:e.map((i,c)=>{if(c>=n||i.role!=="tool"||typeof i.content!="string"||!i.name||!Hn.has(i.name)||i.content.length<=200)return i;let m=this.estimateTokens(i);return s+=m,r++,{...i,content:`[result cleared \u2014 ${i.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Me(t,e,o=ht){if(e.size===0)return{messages:t,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let i of t){let c=i.tool_call_id??"";if(c&&e.has(c)){n+=o(i),r++,e.delete(c);continue}s.push(i)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:r,boundaryMessage:a}}function we(){return{stages:[]}}function Ee(t,e,o){let n=o?.thresholdMessages??40;if(t.filter(i=>i.role!=="system").length<=n)return{messages:t,stagedCount:0};let s=Tt(t,e),a=jn(s,e,n);if(a.length===0)return{messages:s,stagedCount:0};for(let i of a)e.stages.push(i);return s=Tt(t,e),{messages:s,stagedCount:a.length}}function Ie(t,e){let o=0;for(let n of e.stages)n.committed||(n.committed=!0,o++);return o===0?{messages:t,committed:0}:{messages:Ct(t,e),committed:o}}function Tt(t,e){return e.stages.filter(n=>n.committed).length===0?t:Ct(t,e)}function Ct(t,e){let o=e.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...t];for(let r of o){let[s,a]=r.range;if(s>=n.length)continue;let i=Math.min(a,n.length),c={role:"system",content:r.summary};n.splice(s,i-s,c)}return n}function jn(t,e,o){let n=Math.max(0,t.length-Math.floor(o/2)),r=[],s=new Set(e.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),a=-1,i=0;for(let c=0;c<n;c++){let m=t[c];if(m.role==="tool"||m.role==="assistant"&&typeof m.content=="string"&&m.content==="")a<0&&(a=c),i++;else{if(i>=3){let g=`${a}-${a+i}`;s.has(g)||r.push({id:`collapse_${a}_${a+i}`,range:[a,a+i],summary:`[${i} tool results collapsed]`,committed:!1})}a=-1,i=0}}if(i>=3){let c=`${a}-${a+i}`;s.has(c)||r.push({id:`collapse_${a}_${a+i}`,range:[a,a+i],summary:`[${i} tool results collapsed]`,committed:!1})}return r}function zn(t){return!(!t.ok||t.existingSkillName||!t.multiStep||t.toolCallCount<3||t.distinctToolCount<2)}function Kn(t){return t.existingSkillName?t.feedback==="negative":!1}function re(t,e){return Kn(t)?{type:"skill.improve",skillName:t.existingSkillName,reason:"negative user feedback on existing skill execution"}:zn(t)?{type:"skill.create",suggestedName:e.suggestedName??`auto-skill-${e.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${e.tools.join(", ")}`,tools:e.tools,stepCount:t.toolCallCount}:null}function bt(t){return t.function&&typeof t.function=="object"&&typeof t.function.name=="string"?t.function.name.trim():typeof t.name=="string"?t.name.trim():""}function Gn(t){return t==="enabled-eligible"||t==="installed-awaiting-approval"}function Wn(t){return new Map((t??[]).map(e=>[e.toolName,e]))}function qn(t){if(!t.eligibility?.length)return[...t.tools];let e=Wn(t.eligibility);return t.tools.filter(o=>{let n=bt(o);if(!n)return!1;let r=e.get(n);return!r||Gn(r.status)})}function Yn(t){let e=[],o=t.compatibility??{},n=t.toolChoice;if(t.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:e}}function Le(t){let e=Yn({toolChoice:t.toolChoice,thinkingEnabled:t.thinkingEnabled,compatibility:t.compatibility}),o=e.normalizedToolChoice,n=[...e.warnings],r=qn({tools:t.tools,eligibility:t.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="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:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let s=o.function??void 0,a=typeof s?.name=="string"?s.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let i=r.filter(c=>bt(c)===a);if(i.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:i,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var Vn=["stop","aborted","timeout","cancelled","interrupted","error"],Xn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function kt(t){return t==null?[]:typeof t=="string"?t.length>0?[{type:"text",text:t}]:[]:Array.isArray(t)?t:[{type:"text",text:String(t)}]}function Jn(t,e){return{...t,content:[...kt(t.content),...kt(e.content)]}}function Qn(t){if(!t||typeof t!="object")return!1;if(t.function&&typeof t.function=="object"){let e=t.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof t.name=="string"&&t.name.length>0}function Zn(t){return new Set((t??Vn).map(e=>e.trim().toLowerCase()))}function eo(t,e){return t?Zn(e).has(t.trim().toLowerCase()):!1}function Oe(t){if(!Array.isArray(t)||t.length===0)return[...t];let e=t.map(i=>{if(i.role==="assistant"&&Array.isArray(i.tool_calls)){let c=i.tool_calls.filter(m=>Qn(m));return{...i,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...i}}),o=new Set;for(let i of e)if(!(i.role!=="assistant"||!Array.isArray(i.tool_calls)))for(let c of i.tool_calls)typeof c.id=="string"&&c.id&&o.add(c.id);let n=e.filter(i=>i.role!=="tool"?!0:!!(i.tool_call_id&&o.has(i.tool_call_id))),r=new Set;for(let i of n)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&r.add(i.tool_call_id);let s=[];for(let i of n){if(i.role==="assistant"&&Array.isArray(i.tool_calls)&&i.tool_calls.length>0){let c=i.tool_calls.filter(m=>typeof m.id=="string"&&r.has(m.id));if(c.length===0){let{tool_calls:m,...d}=i;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<i.tool_calls.length){s.push({...i,tool_calls:c});continue}}s.push(i)}let a=[];for(let i of s){let c=a.length>0?a[a.length-1]:void 0;if(i.role==="user"&&c?.role==="user"){a[a.length-1]=Jn(c,i);continue}a.push(i)}return a}function Pe(t,e){return eo(e?.stopReason,e?.forcedStopReasons)?t.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of Xn)delete n[r];return n}):[...t]}function De(t,e){let o=e?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),n=new Set;for(let s of t)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of t)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let a of s.tool_calls)typeof a.id!="string"||!a.id||n.has(a.id)||(n.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:o}));return r}function Ne(t,e){let o=Oe(t),n=Pe(o,e);return De(n,e)}function to(t){let e=new Set,o=new Set;for(let n of t){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&e.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...e].filter(n=>!o.has(n))}function no(t){let e=new Set;for(let o of t)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&e.add(o.tool_call_id);return[...e]}function oo(t){return{round:t.round??0,maxRounds:t.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??[]],completedToolCallIds:[...t.completedToolCallIds??[]],lastStopReason:t.lastStopReason,replayMessages:[...t.replayMessages??[]]}}function Fe(t,e){return{round:t.round+1,maxRounds:t.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??t.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??t.completedToolCallIds],lastStopReason:e.lastStopReason??t.lastStopReason,replayMessages:[...e.replayMessages??t.replayMessages]}}function ge(t,e){return{round:t.round,maxRounds:t.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??t.completedToolCallIds],lastStopReason:e.lastStopReason??t.lastStopReason,replayMessages:[...e.replayMessages??t.replayMessages]}}function fe(t){let e=[],o=Oe(t.replayMessages);o.length!==t.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=Pe(o,t.options);n.some((s,a)=>s!==o[a])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=De(n,t.options);return r.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:oo({maxRounds:t.maxRounds,round:t.round,lastStopReason:t.lastStopReason,replayMessages:r,pendingToolCallIds:to(r),completedToolCallIds:no(r)}),recoveryActions:e}}import{MEMORY_OBSERVATION_HOOK_VALUES as ro,MEMORY_OBSERVATION_SOURCE_VALUES as so,MEMORY_WRITE_ACCESS_VALUES as io}from"qlogicagent-runtime-contracts";var ao=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ue(t){return t?ao.has(t):!0}function $e(t){return t===429||t===529}function ye(t,e=500,o=32e3){let n=Math.min(e*Math.pow(2,t-1),o);return n+Math.floor(Math.random()*n*.25)}var jr={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Be(){let t=process.env.QLOGICAGENT_PERSISTENT_RETRY;return t==="1"||t==="true"}var se=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function He(t){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:t.maxOutputTokens,consecutiveTruncations:0,aborted:t.abortSignal?.aborted??!1}}function je(t,e){if(t.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=e.contextWindowTokens-e.responseBufferTokens-t.currentMaxOutputTokens,n=o>0?t.promptTokens/o*100:100;return t.promptTokens>=o?t.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-t.promptTokens}:{level:"ok"}}function ze(t,e,o){let n=t.message?.toLowerCase()??"",r=t.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&o.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:n||"unknown_error"}}function Ke(t,e,o){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};if(t.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};let n=Math.min(t.currentMaxOutputTokens*2,o);return n<=t.currentMaxOutputTokens?{shouldEscalate:!1,newMax:t.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function Ge(t,e){return t.aborted?!0:e.abortSignal?.aborted?(t.aborted=!0,!0):!1}var lo={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function We(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function G(t,e=lo){return!(t.attemptedThisTurn||t.consecutiveFailures>=e.maxConsecutiveFailures)}var yo={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"}},qe=["gateway","agents_list","whatsapp_login","session_status","cron","memory_query","sessions_send"],ho=["sessions_list","sessions_history","sessions_spawn"],xt=["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 To(t={}){let e=Math.max(1,Math.floor(t.maxDepth??2)),o=typeof t.depth=="number"&&Number.isFinite(t.depth)?Math.max(0,Math.floor(t.depth)):e,n=t.role?t.role==="leaf":o>=e,r=n?[...qe,...ho]:[...qe],s=new Set(r),a=Array.isArray(t.toolNames)?t.toolNames:t.toolNames?Array.from(t.toolNames):[],i=Array.from(new Set(a.map(c=>c.trim()).filter(Boolean))).map(c=>{let m=s.has(c);return{toolName:c,decision:m?"denied":"allowed",inheritance:m?"shrink":"inherit",reason:m?qe.includes(c)?"always-deny":"leaf-deny":"default-allow"}});return{deniedTools:r,canSpawnChildren:!n,defaultDecision:"allowed",defaultInheritance:"inherit",tools:i}}function St(t){let e=Co(t.type),o=To({depth:t.depth,maxDepth:t.maxDepth,role:t.role,toolNames:t.toolNames});if(e.toolAccessMode==="full")return o;if(e.toolAccessMode==="none"){let s=Array.isArray(t.toolNames)?t.toolNames:t.toolNames?Array.from(t.toolNames):[],a=[...new Set(s.map(i=>i.trim()).filter(Boolean))];return{deniedTools:a,canSpawnChildren:!1,defaultDecision:"allowed",defaultInheritance:"inherit",tools:a.map(i=>({toolName:i,decision:"denied",inheritance:"shrink",reason:"always-deny"}))}}let n=new Set(xt),r=[...new Set([...o.deniedTools,...xt])];return{...o,deniedTools:r,tools:o.tools.map(s=>s.decision==="denied"?s:n.has(s.toolName)?{...s,decision:"denied",inheritance:"shrink",reason:"always-deny"}:s)}}function vt(t,e){let o=new Set(e.deniedTools),n=new Map(e.tools.map(a=>[a.toolName,a])),r=[],s=[];for(let a of t){let i=a.function.name,c=n.get(i);c?.decision==="denied"?s.push({toolCall:a,reason:`tool "${i}" denied by sidechain policy: ${c.reason}`}):o.has(i)?s.push({toolCall:a,reason:`tool "${i}" is in sidechain deny list`}):r.push(a)}return{allowed:r,denied:s}}function Co(t){return yo[t]}function Ye(t,e){let o=t.get(e.index);o||(o={id:"",name:"",arguments:""},t.set(e.index,o)),e.id&&(o.id=e.id),e.name&&(o.name+=e.name),o.arguments+=e.arguments}import{mkdir as bo,writeFile as ko}from"fs/promises";import{join as Ft}from"path";import{tmpdir as xo}from"os";var Rt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),_t=3,W=2,At=128e3,Mt=13e3,wt=16384,Et=65536,It=3,Lt=65536,Ot=3e4,Pt=3,Dt=5e4,Nt=2e5,Ve=2e3;var So="tool-results",Ut="<persisted-output>",vo="</persisted-output>";function $t(){return{seenIds:new Set,replacements:new Map}}function Bt(t){return Ft(xo(),"qlogicagent-sessions",t,So)}async function Ro(t){try{await bo(Bt(t),{recursive:!0})}catch{}}function _o(t,e){let o=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Ft(Bt(t),`${o}.txt`)}function Ao(t,e){if(t.length<=e)return{preview:t,hasMore:!1};let n=t.slice(0,e).lastIndexOf(`
|
|
8
|
+
`),r=n>e*.5?n:e;return{preview:t.slice(0,r),hasMore:!0}}function Ht(t){return t.includes(Ut)}async function jt(t,e,o){await Ro(o);let n=_o(o,e);try{await ko(n,t,{encoding:"utf-8",flag:"wx"})}catch(a){if(a.code!=="EEXIST")return null}let{preview:r,hasMore:s}=Ao(t,Ve);return{filepath:n,originalSize:t.length,preview:r,hasMore:s}}function zt(t){let e=`${Ut}
|
|
9
|
+
`;return e+=`Output too large (${t.originalSize} chars). Full output saved to: ${t.filepath}
|
|
10
|
+
|
|
11
|
+
`,e+=`Preview (first ${Ve} bytes):
|
|
12
|
+
`,e+=t.preview,e+=t.hasMore?`
|
|
13
|
+
...
|
|
14
|
+
`:`
|
|
15
|
+
`,e+=vo,e}async function Kt(t,e,o,n=Dt){if(t.length<=n||Ht(t))return t;let r=await jt(t,e,o);return r?zt(r):t.slice(0,n)+`
|
|
16
|
+
...[truncated ${t.length-n} chars]`}function Mo(t){let e=[],o=[];for(let n of t)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?Ht(n.content)||o.push({toolCallId:n.tool_call_id,content:n.content,size:n.content.length}):n.role==="assistant"&&o.length>0&&(e.push(o),o=[]);return o.length>0&&e.push(o),e}function wo(t,e){let o=[],n=[],r=[];for(let s of t){let a=e.replacements.get(s.toolCallId);a!==void 0?o.push({...s,replacement:a}):e.seenIds.has(s.toolCallId)?n.push(s):r.push(s)}return{mustReapply:o,frozen:n,fresh:r}}function Eo(t,e,o){let n=[...t].sort((a,i)=>i.size-a.size),r=[],s=e+t.reduce((a,i)=>a+i.size,0);for(let a of n){if(s<=o)break;r.push(a),s-=a.size}return r}async function Gt(t,e,o,n=Nt){let r=Mo(t);if(r.length===0)return{messages:t,newlyReplacedCount:0};let s=new Map,a=[];for(let d of r){let{mustReapply:g,frozen:b,fresh:f}=wo(d,e);for(let y of g)s.set(y.toolCallId,y.replacement);if(f.length===0){for(let y of d)e.seenIds.add(y.toolCallId);continue}let k=b.reduce((y,S)=>y+S.size,0),T=f.reduce((y,S)=>y+S.size,0),h=k+T>n?Eo(f,k,n):[],A=new Set(h.map(y=>y.toolCallId));for(let y of d)A.has(y.toolCallId)||e.seenIds.add(y.toolCallId);h.length>0&&a.push(...h)}if(s.size===0&&a.length===0)return{messages:t,newlyReplacedCount:0};let i=await Promise.all(a.map(async d=>{let g=await jt(d.content,d.toolCallId,o);return{candidate:d,result:g}})),c=0;for(let{candidate:d,result:g}of i){if(e.seenIds.add(d.toolCallId),!g)continue;let b=zt(g);s.set(d.toolCallId,b),e.replacements.set(d.toolCallId,b),c++}return s.size===0?{messages:t,newlyReplacedCount:0}:{messages:t.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let g=s.get(d.tool_call_id);return g===void 0?d:{...d,content:g}}),newlyReplacedCount:c}}var Io=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),Lo=new Set(["bash","execute_command","Bash","shell"]),he=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??Io,this.siblingAbortController=new AbortController,e.signal&&e.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(e){let o=this.concurrencySafe.has(e.function.name);this.tools.push({id:e.id,toolCall:e,status:"queued",isConcurrencySafe:o,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let o=this.tools.filter(r=>r.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&o.length>=n?!1:o.length===0||e&&o.every(r=>r.isConcurrencySafe)}async processQueue(){for(let e of this.tools)if(e.status==="queued"){if(this.canExecuteTool(e.isConcurrencySafe))await this.executeTool(e);else if(!e.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(e){let o;try{o=JSON.parse(e.toolCall.function.arguments)}catch{}let n=o?.command??o?.file_path??o?.pattern??"";if(typeof n=="string"&&n.length>0){let r=n.length>40?n.slice(0,40)+"\u2026":n;return`${e.toolCall.function.name}(${r})`}return e.toolCall.function.name}createSyntheticError(e,o){let n=this.erroredToolDescription,r=o==="user_interrupted"?"User rejected tool use":o==="discarded"?"Streaming fallback - tool execution discarded":n?`Cancelled: parallel tool call ${n} errored`:"Cancelled: parallel tool call errored";return{callId:e.id,toolName:e.toolCall.function.name,ok:!1,error:r,message:Q(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let n=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:a,sessionId:i,turnId:c,log:m}=this.config,d=e.toolCall.function.name,g=!1,b=e.toolCall.function.arguments;if(a)try{let y=await a.invoke("tool.before_invoke",{sessionId:i,turnId:c,callId:e.id,toolName:d,arguments:Oo(b)});if(y.action==="abort"){let S=y.reason??"blocked by policy";m.info(`tool ${d} blocked: ${S}`),e.results.push({callId:e.id,toolName:d,ok:!1,error:S,blocked:!0,blockReason:S,message:Q(e.id,{ok:!1,error:S})}),e.status="completed";return}y.action==="continue"&&y.context?.arguments&&(b=JSON.stringify(y.context.arguments))}catch{}let f=await s.invoke(c,d,b,this.siblingAbortController.signal),k=this.getAbortReason();if(k&&!g){e.results.push(this.createSyntheticError(e,k)),e.status="completed";return}let T=!f.error,h=f.result;T&&h&&h.length>5e4&&(h=await Kt(h,e.id,i));let A=Q(e.id,{ok:T,payload:h,error:f.error});T||(g=!0,Lo.has(d)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),a?.invoke(T?"tool.after_invoke":"tool.invoke_failed",{sessionId:i,turnId:c,callId:e.id,toolName:d,ok:T,...f.error?{error:f.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:d,ok:T,error:f.error,message:A}),e.status="completed"})();e.promise=n,n.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let e of this.tools)if(e.status!=="yielded"){if(e.status==="completed"&&e.results.length>0){e.status="yielded";for(let o of e.results)yield o}else if(e.status==="executing"&&!e.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let e=this.tools.filter(n=>n.status==="executing"&&n.promise).map(n=>n.promise),o=new Promise(n=>{this.progressResolve=n});e.length>0&&await Promise.race([...e,o])}}for(let e of this.getCompletedResults())yield e}}hasCompletedResults(){return this.tools.some(e=>e.status==="completed")}hasExecutingTools(){return this.tools.some(e=>e.status==="executing")}hasUnfinishedTools(){return this.tools.some(e=>e.status!=="yielded")}};function Oo(t){try{return JSON.parse(t)}catch{return}}import{readFile as Bi}from"node:fs/promises";function Qe(t){let e=typeof t.content=="string"?t.content:t.content!=null?JSON.stringify(t.content):"";return Math.ceil(e.length/4)}function Xe(t){let e=0;for(let o of t)e+=Qe(o);return e}var Je={"deepseek-chat":64e3,"deepseek-reasoner":64e3,"deepseek-v4-flash":64e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};function Po(t){if(!t)return 128e3;if(t in Je)return Je[t];let e=t.toLowerCase();for(let[o,n]of Object.entries(Je))if(e.startsWith(o.toLowerCase()))return n;return 128e3}var Do=8e3;var No=new ne(200);var Hi=new oe;function Fo(){return Re(new te(Do),new j(20,Qe),new ee(Qe))}var Uo=null;function Wt(t,e){let o=e?.budget??_e({modelContextWindow:Po(e?.model)}),r=(e?.pipeline??Fo()).compress(t,o);if(r.droppedCount>0){let s=Xe(t),a=Xe(r.messages);No.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:s,tokensAfter:a,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:Ae(s,o)})}return r.droppedCount>0&&Uo?.(r.droppedCount,Xe(r.messages)),r}function qt(t,e,o){let n=o-e;return`[Budget] ${Math.round(t)}% used (${e.toLocaleString()} / ${o.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(t>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}function Go(t){return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.min(Math.round(t),100):Rt}function Xt(t){let e=t.message.toLowerCase();return t.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function Wo(t){return t==="length"||t==="max_tokens"}function Jt(t){let e=t.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(t.status===413||e.includes("too large")||e.includes("size"))}function qo(t){let e=t.headers;if(!e)return null;let o=e["retry-after"]??e["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function Yo(t){if(t.status!==400)return null;let e=t.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!e?.[1]||!e?.[3])return null;let o=parseInt(e[1],10),n=parseInt(e[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}function Vo(t){return t.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Qt(t,e,o,n){let{turnId:r,sessionId:s,messages:a,tools:i,model:c,apiKey:m,temperature:d,hooks:g,signal:b}=t,f={sessionId:s,turnId:r},k=t.maxTurns??0,T=t.querySource,{resolveToolEligibility:h}=await Promise.resolve().then(()=>(Vt(),Yt)),A=h(i,t.toolEligibilityContext),y=A.eligibleTools;for(let _ of A.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:_.toolName,reason:"blocked-by-policy"};if(!y.length){yield*Xo(r,c,a,m,d,b,e,n);return}let S=Go(t.maxRounds),M={contextWindowTokens:t.contextWindowTokens??At,responseBufferTokens:Mt,maxOutputTokens:t.maxOutputTokens??wt,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},z=!1,Ce=null,D=(t.parentDepth??0)+1,q=new Set,I=0,ce=y,ue,u={messages:[...a],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:He(M),reactiveCompactState:We(),toolLoopState:fe({maxRounds:S,replayMessages:[...a]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:we(),currentModel:c,consecutive529Errors:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:$t()};for(;;){let{messages:_,maxOutputTokensRecoveryCount:Y,hasAttemptedReactiveCompact:hr,maxOutputTokensOverride:tt,turnCount:V,guardState:v,reactiveCompactState:L,collapseStore:be}=u,{toolLoopState:w}=u;if(ue){try{let l=await ue;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}ue=void 0}if(t.refreshTools&&V>1){let l=t.refreshTools();l!==ce&&(ce=l,n.debug(`tools refreshed: ${l.length} tools`))}if(Ge(v,M)){n.info(`turn aborted by guard at turn ${V}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let F=je(v,M);if(F.level==="blocking"){F.reason==="prompt_too_long"&&G(L)&&(L.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${F.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${F.reason}), ending tool loop`);break}F.level==="warning"&&n.info(`token budget warning: ${F.usagePercent}% used, ${F.remainingTokens} remaining`);let R;{let l=await Gt(_,u.contentReplacementState,s);R=l.messages,l.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${l.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${l.newlyReplacedCount} persisted`})}{let l=Me(R,u.snipRemovedIds);R=l.messages,l.removedCount>0&&(n.info(`snip: removed ${l.removedCount} messages, freed ~${l.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${l.removedCount} messages`})}{let p=new j().compress(R,0);p.droppedCount>0&&(R=p.messages,n.info(`microcompact: cleared ${p.droppedCount} old tool results`))}if(R=Ee(R,be).messages,v.promptTokens>0){let l=Wt(R,{budget:M.contextWindowTokens*.75,model:u.currentModel});l.droppedCount>0&&(R=l.messages,n.info(`autocompact: ${l.strategy}, dropped ${l.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${l.strategy}: ${l.droppedCount} dropped`},u.hasAttemptedReactiveCompact=!1,g?.invoke("context.after_compact",{...f,removedCount:l.droppedCount}).catch(()=>{}))}R=Vo(R);let de=Le({tools:ce,toolChoice:t.toolChoice??"auto"}),X=fe({maxRounds:S,replayMessages:R,lastStopReason:w.lastStopReason,options:{stopReason:w.lastStopReason}}),nt=de.extraSystemPrompt?[{role:"system",content:de.extraSystemPrompt},...X.state.replayMessages]:X.state.replayMessages;w=X.state,X.recoveryActions.length>0&&n.debug(`tool loop recovery: ${X.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${V}, messages: ${nt.length}`),g?.invoke("turn.before_inference",{...f,model:u.currentModel}).catch(()=>{});let pe=!1,ot=[],rt=new Map,st="stop",N,C=null,me=!1;try{for await(let l of e.stream({model:u.currentModel,messages:nt,tools:de.tools,toolChoice:de.normalizedToolChoice??"auto",temperature:d,maxTokens:(tt??v.currentMaxOutputTokens)||void 0},m,b))switch(l.type){case"delta":ot.push(l.text),pe||(yield{type:"delta",turnId:r,text:l.text});break;case"tool_call_delta":pe=!0,Ye(rt,l);break;case"reasoning_delta":break;case"usage":N={prompt:l.promptTokens,completion:l.completionTokens,reasoning:l.reasoningTokens};break;case"done":st=l.finishReason;break}if(pe||g?.invoke("turn.after_inference",{...f,model:u.currentModel}).catch(()=>{}),t.postSamplingHooks&&t.postSamplingHooks.length>0){let l=u.currentModel;for(let p of t.postSamplingHooks)try{p({messages:[...R],model:l,sessionId:s})}catch{}}}catch(l){if(l instanceof se&&t.fallbackModel){n.info(`model fallback triggered: ${l.originalModel} \u2192 ${l.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${l.originalModel} \u2192 ${l.fallbackModel}`},u={...u,currentModel:l.fallbackModel,consecutive529Errors:0,transition:void 0};continue}let p=l instanceof Error?l.message:String(l),x=typeof l?.status=="number"?l.status:void 0;if(!x&&p&&(p.includes("ECONNRESET")||p.includes("EPIPE"))){n.info(`stale connection (${p.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:p.slice(0,80)},u={...u,transition:void 0};continue}let O=Yo({status:x,message:p});if(O!==null){n.info(`max_tokens overflow: adjusting to ${O}`),v.currentMaxOutputTokens=O,u={...u,maxOutputTokensOverride:O,transition:void 0};continue}if($e(x)){if(u.consecutive529Errors++,u.consecutive529Errors>=Pt&&t.fallbackModel&&u.currentModel!==t.fallbackModel){n.info(`529 \xD7 ${u.consecutive529Errors}: triggering fallback to ${t.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${u.consecutive529Errors}`},u={...u,currentModel:t.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Be()){let U=ye(u.consecutive529Errors);n.info(`persistent retry: waiting ${U}ms (attempt ${u.consecutive529Errors})`);let P=U;for(;P>0;){if(b?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(P/1e3)}s (${x})`};let K=Math.min(P,Ot);await new Promise(an=>setTimeout(an,K)),P-=K}u={...u,transition:void 0};continue}if(Ue(T)){let P=qo({status:x,message:p})??ye(u.consecutive529Errors);n.info(`transient ${x}: retry in ${P}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${x} retry in ${P}ms`},await new Promise(K=>setTimeout(K,P)),u={...u,transition:void 0};continue}n.info(`background source ${T}: not retrying ${x}`)}C={status:x,message:p}}if(C&&g?.invoke("turn.after_inference",{...f,model:u.currentModel,response:{error:C.message}}).catch(()=>{}),C)if(Xt(C))me=!0,n.info(`withheld prompt_too_long error (status=${C.status})`);else if(Jt(C))me=!0,n.info(`withheld media_size error (status=${C.status})`);else{let l=ze({status:C.status??500,message:C.message},v,M);if(l.action==="reactive_compact"&&G(L)&&(L.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${C.status??500}: ${C.message}`}),l.action==="retry"){yield{type:"recovery",turnId:r,action:"retry",detail:l.reason},u={...u,transition:void 0};continue}let p=Z(C.status,C.message);g?.invoke("stop.failure",{sessionId:s,reason:p,error:C.message}).catch(()=>{}),yield{type:"error",turnId:r,error:C.message,code:p};return}N&&(u.totalUsage.prompt+=N.prompt,u.totalUsage.completion+=N.completion,N.reasoning&&(u.totalUsage.reasoning=(u.totalUsage.reasoning??0)+N.reasoning)),N?.prompt&&(v.promptTokens=N.prompt),u.finalText=ot.join("");let E=[...rt.values()].map(l=>({id:l.id||`tc_${r}_${V}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(Ce&&E.length>0){let l=vt(E,Ce);l.denied.length>0&&n.info(`sidechain policy denied: ${l.denied.map(p=>`${p.toolCall.function.name} (${p.reason})`).join(", ")}`),E=l.allowed}if(E.length===0&&!pe){if(me&&C&&Xt(C)){if(u.transition?.reason!=="collapse_drain_retry"){let l=Ie(R,be);if(l.committed>0){n.info(`collapse drain: committed ${l.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${l.committed} stages committed`},u={...u,messages:l.messages,transition:{reason:"collapse_drain_retry",committed:l.committed}};continue}}if(G(L)){L.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),g?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:C.message}).catch(()=>{}),yield{type:"error",turnId:r,error:C.message,code:"PROMPT_TOO_LONG"};return}if(me&&C&&Jt(C)){if(G(L)){L.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),g?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:C.message}).catch(()=>{}),yield{type:"error",turnId:r,error:C.message,code:"IMAGE_ERROR"};return}if(Wo(st)){v.consecutiveTruncations+=1;let l=t.modelMaxOutputTokens??Et,p=Ke(v,M,l);if(p.shouldEscalate&&tt===void 0){v.currentMaxOutputTokens=p.newMax,n.info(`max_output_tokens escalate: ${p.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${p.newMax} tokens`},u={...u,maxOutputTokensOverride:Lt,transition:{reason:"max_output_tokens_escalate"}};continue}if(Y<It){let x={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${Y+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${Y+1}`},u={...u,messages:[...R,x],maxOutputTokensRecoveryCount:Y+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:Y+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;if(w=ge(w,{replayMessages:_,lastStopReason:"completed"}),g){let l=await g.invoke("stop",{sessionId:s,reason:"completed"});if(l.action==="prevent"){n.info(`stop hook prevented continuation: ${l.reason??"no reason"}`),yield{type:"end",turnId:r,content:u.finalText,usage:u.totalUsage,model:u.currentModel};return}if(l.action==="abort"){let p=l.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${p}`);let x={role:"user",content:p};u={...u,messages:[..._,{role:"assistant",content:u.finalText},x],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(t.tokenBudget&&t.tokenBudget>0){let l=u.totalUsage.prompt+u.totalUsage.completion+(u.totalUsage.reasoning??0),p=l/t.tokenBudget*100;if(p<90){let x={role:"user",content:qt(p,l,t.tokenBudget)};n.info(`token budget continuation: ${Math.round(p)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(p)}% used`},u={...u,messages:[..._,{role:"assistant",content:u.finalText},x],transition:{reason:"token_budget_continuation"}};continue}}if(z&&(yield{type:"sidechain_completed",turnId:r,depth:D,toolCallCount:I}),I>0){let l={ok:!0,toolCallCount:I,distinctToolCount:q.size,multiStep:I>=2,hasSidechain:z,feedback:null,existingSkillName:null},p=re(l,{tools:[...q]});p&&(yield{type:"skill_instruction",turnId:r,instruction:p})}yield{type:"end",turnId:r,content:u.finalText,usage:u.totalUsage,model:u.currentModel};return}for(let l of E){let p=l.function.arguments,x=ce.find(O=>O.function.name===l.function.name);if(x?.backfillObservableInput)try{let O=JSON.parse(l.function.arguments),U={...O};x.backfillObservableInput(U),Object.keys(U).some(K=>!(K in O))&&(p=JSON.stringify(U))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:p}}if(_.push(xe(E)),!z){if(D>W){yield{type:"error",turnId:r,error:`sidechain depth ${D} exceeds max ${W}`,code:"SIDECHAIN_DEPTH_LIMIT"};return}z=!0;let l=D>=W?"leaf":"orchestrator";yield{type:"sidechain_started",turnId:r,depth:D,role:l},Ce=St({type:t.sidechainType??"code-repair",depth:D,maxDepth:W,role:D>=W?"leaf":"orchestrator",toolNames:i.map(p=>p.function.name)})}w=Fe(w,{replayMessages:_,pendingToolCallIds:E.map(l=>l.id),completedToolCallIds:w.completedToolCallIds,lastStopReason:"tool_calls"});let it=[];try{let l=new he({toolInvoker:o,hooks:g,sessionId:s,turnId:r,log:n,signal:b,maxConcurrentTools:t?.maxConcurrentTools});for(let p of E)l.addTool(p);for await(let p of l.getRemainingResults())p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),_.push(p.message),it.push(p.callId),q.add(p.toolName),I++,yield{type:"tool_result",turnId:r,callId:p.callId,name:p.toolName,ok:p.ok,error:p.error}}catch(l){let p=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:p,code:"TOOL_EXECUTION_ERROR"};return}if(w=ge(w,{replayMessages:_,completedToolCallIds:[...w.completedToolCallIds,...it],lastStopReason:"tool_calls"}),t.generateToolUseSummary&&E.length>0){let l=E.map(p=>({name:p.function.name,arguments:p.function.arguments}));ue=t.generateToolUseSummary(l).catch(()=>null)}let at=_.slice(-E.length),sn=at.length>0&&at.every(l=>{let p=l?.content;if(typeof p!="string")return!1;try{return JSON.parse(p)?.ok===!1}catch{return!1}}),J=u.consecutiveFailedRounds;if(sn){if(J+=1,J>=_t&&u.finalText){n.info(`early exit: ${J} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:u.finalText,usage:u.totalUsage,model:u.currentModel};return}}else J=0;let ke=V+1;if(k>0&&ke>k){if(n.info(`max turns reached (${k}), completing`),g){let l=await g.invoke("stop",{sessionId:s,reason:"max_turns"});if(l.action==="abort"){let p=l.reason??"Stop hook requested continuation after max_turns";u={...u,messages:[..._,{role:"assistant",content:u.finalText},{role:"user",content:p}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:u.finalText,usage:u.totalUsage,model:u.currentModel};return}if(ke>S){if(u.finalText){if(n.info(`tool loop budget exhausted (${S} rounds), returning partial response`),z&&(yield{type:"sidechain_completed",turnId:r,depth:D,toolCallCount:I}),I>0){let l={ok:!0,toolCallCount:I,distinctToolCount:q.size,multiStep:I>=2,hasSidechain:z,feedback:null,existingSkillName:null},p=re(l,{tools:[...q]});p&&(yield{type:"skill_instruction",turnId:r,instruction:p})}yield{type:"end",turnId:r,content:u.finalText,usage:u.totalUsage,model:u.currentModel};return}yield{type:"error",turnId:r,error:`Tool loop exceeded budget (${S} rounds)`,code:"TOOL_LOOP_LIMIT"};return}u={messages:_,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:ke,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:L,toolLoopState:w,consecutiveFailedRounds:J,finalText:u.finalText,totalUsage:u.totalUsage,collapseStore:be,currentModel:u.currentModel,consecutive529Errors:0,stopHookActive:u.stopHookActive,snipRemovedIds:u.snipRemovedIds,contentReplacementState:u.contentReplacementState}}}async function*Xo(t,e,o,n,r,s,a,i){let c=[],m;i.debug(`single LLM round, messages: ${o.length}`);for await(let d of a.stream({model:e,messages:o,temperature:r},n,s))switch(d.type){case"delta":c.push(d.text),yield{type:"delta",turnId:t,text:d.text};break;case"usage":m={prompt:d.promptTokens,completion:d.completionTokens,reasoning:d.reasoningTokens};break;case"done":break}yield{type:"end",turnId:t,content:c.join(""),usage:m??{prompt:0,completion:0},model:e}}var Ze=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(e){this.transport=e.llmTransport,this.apiKey=e.apiKey,this.toolInvoker=e.toolInvoker,this.log=e.log,this.hooks=e.hooks,this.maxRounds=Math.min(e.maxRounds??25,100)}async*run(e,o){let{turnId:n,messages:r,tools:s,systemPrompt:a,config:i}=e,c={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...c,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let m=Ne(r),d=[];if(a&&d.push({role:"system",content:a}),d.push(...m),this.hooks){let f=m.filter(T=>T.role==="user").pop(),k=typeof f?.content=="string"?f.content.slice(0,500):void 0;if(k)try{let T=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:k}),h=T?.context?.recalledMemories;if(h&&h.length>0){let A=h.map(y=>`- ${y.text}`).join(`
|
|
17
|
+
`);d.splice(a?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
18
|
+
${A}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:T?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let g=i?.model??"",b=Math.min(i?.maxRounds??this.maxRounds,100);try{let f=i?.summaryModel?async h=>{try{let A=h.map(M=>`${M.name}(${M.arguments.slice(0,200)})`).join(", "),y=this.transport.stream({model:i.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:A}],tools:[],maxTokens:60},i.apiKey??this.apiKey),S="";for await(let M of y)M.type==="delta"&&(S+=M.text);return S.trim()||null}catch{return null}}:void 0,k={turnId:n,sessionId:e.sessionId,messages:d,tools:s,model:g,apiKey:i?.apiKey??this.apiKey,temperature:i?.temperature,maxRounds:b,contextWindowTokens:i?.contextWindowTokens,maxOutputTokens:i?.maxOutputTokens,modelMaxOutputTokens:i?.modelMaxOutputTokens,toolChoice:i?.toolChoice,parentDepth:i?.parentDepth,sidechainType:i?.sidechainType,hooks:this.hooks,fallbackModel:i?.fallbackModel,maxTurns:i?.maxTurns,tokenBudget:i?.tokenBudget,maxConcurrentTools:i?.maxConcurrentTools,generateToolUseSummary:f,signal:o},T;for await(let h of Qt(k,this.transport,this.toolInvoker,this.log))T=h,yield h;T?.type==="end"?this.hooks?.invoke("turn.completed",{...c}).catch(()=>{}):T?.type==="error"&&this.hooks?.invoke("turn.failed",{...c,code:T.code,error:T.error}).catch(()=>{})}catch(f){if(o?.aborted)this.hooks?.invoke("turn.failed",{...c,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let k=f instanceof Error?f.message:String(f),T=typeof f?.status=="number"?f.status:void 0,h=Z(T,k),A=ve(h);this.log.error(`turn ${n} error [${h}, retryable=${A.retryable}]: ${k}`),this.hooks?.invoke("turn.failed",{...c,code:h,error:k}).catch(()=>{}),yield{type:"error",turnId:n,error:k,code:h}}}}};function Qo(t){let e={verbose:!1};for(let o of t.slice(2))(o==="--verbose"||o==="-v")&&(e.verbose=!0);return e}var et=[{id:"deepseek",name:"DeepSeek",transport:"openai-chat",baseUrl:"https://api.deepseek.com",apiKeyEnvVars:["DEEPSEEK_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"deepseek-chat",models:[{id:"deepseek-chat",name:"DeepSeek Chat V3",contextWindow:64e3,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.27,costOutput:1.1},{id:"deepseek-reasoner",name:"DeepSeek R1",contextWindow:64e3,maxOutput:8192,toolCall:!0,reasoning:!0,vision:!1,costInput:.55,costOutput:2.19}]},{id:"qwen",name:"Alibaba Qwen (DashScope)",transport:"openai-chat",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode",apiKeyEnvVars:["DASHSCOPE_API_KEY","QWEN_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"qwen-plus",models:[{id:"qwen-plus",name:"Qwen Plus",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.8,costOutput:2},{id:"qwen-max",name:"Qwen Max",contextWindow:32768,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:2,costOutput:6},{id:"qwen-turbo",name:"Qwen Turbo",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.3,costOutput:.6},{id:"qwq-plus",name:"QwQ Plus (Reasoning)",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!0,vision:!1,costInput:.8,costOutput:2}]},{id:"zhipu",name:"\u667A\u8C31 GLM (Zhipu)",transport:"openai-chat",baseUrl:"https://open.bigmodel.cn/api/paas",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"glm-4-plus",models:[{id:"glm-4-plus",name:"GLM-4 Plus",contextWindow:128e3,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.5,costOutput:.5}]},{id:"minimax",name:"MiniMax",transport:"openai-chat",baseUrl:"https://api.minimax.chat",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"MiniMax-Text-01",models:[{id:"MiniMax-Text-01",name:"MiniMax Text 01",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!1,vision:!1,costInput:1,costOutput:8}]},{id:"moonshot",name:"Moonshot (Kimi)",transport:"openai-chat",baseUrl:"https://api.moonshot.cn",apiKeyEnvVars:["MOONSHOT_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"moonshot-v1-128k",omitZeroTemperature:!0,models:[{id:"moonshot-v1-128k",name:"Moonshot V1 128K",contextWindow:128e3,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.6,costOutput:.6}]},{id:"doubao",name:"\u8C46\u5305 (Doubao/Volcengine)",transport:"openai-chat",baseUrl:"https://ark.cn-beijing.volces.com/api",apiKeyEnvVars:["ARK_API_KEY","DOUBAO_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"doubao-1.5-pro-32k",models:[{id:"doubao-1.5-pro-32k",name:"Doubao 1.5 Pro 32K",contextWindow:32768,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.8,costOutput:2}]},{id:"baichuan",name:"\u767E\u5DDD (Baichuan)",transport:"openai-chat",baseUrl:"https://api.baichuan-ai.com",apiKeyEnvVars:["BAICHUAN_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"Baichuan4",models:[{id:"Baichuan4",name:"Baichuan 4",contextWindow:32768,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:1,costOutput:1}]},{id:"stepfun",name:"\u9636\u8DC3\u661F\u8FB0 (StepFun)",transport:"openai-chat",baseUrl:"https://api.stepfun.com",apiKeyEnvVars:["STEPFUN_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"step-2-16k",models:[{id:"step-2-16k",name:"Step 2 16K",contextWindow:16384,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.38,costOutput:.12}]},{id:"openai",name:"OpenAI",transport:"openai-chat",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-4o",models:[{id:"gpt-4o",name:"GPT-4o",contextWindow:128e3,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:2.5,costOutput:10},{id:"gpt-4o-mini",name:"GPT-4o Mini",contextWindow:128e3,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:.15,costOutput:.6},{id:"o3-mini",name:"o3-mini",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!1,costInput:1.1,costOutput:4.4}]},{id:"anthropic",name:"Anthropic",transport:"anthropic-messages",baseUrl:"https://api.anthropic.com",apiKeyEnvVars:["ANTHROPIC_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"claude-sonnet-4-20250514",models:[{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",contextWindow:2e5,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15},{id:"claude-opus-4-20250514",name:"Claude Opus 4",contextWindow:2e5,maxOutput:32768,toolCall:!0,reasoning:!0,vision:!0,costInput:15,costOutput:75},{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku",contextWindow:2e5,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!0,costInput:.8,costOutput:4}]},{id:"google",name:"Google Gemini",transport:"openai-chat",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",apiKeyEnvVars:["GOOGLE_API_KEY","GEMINI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gemini-2.5-flash",models:[{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.15,costOutput:.6},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:1.25,costOutput:10}]},{id:"mistral",name:"Mistral AI",transport:"openai-chat",baseUrl:"https://api.mistral.ai",apiKeyEnvVars:["MISTRAL_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"mistral-large-latest",models:[{id:"mistral-large-latest",name:"Mistral Large",contextWindow:128e3,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:2,costOutput:6}]},{id:"xai",name:"xAI (Grok)",transport:"openai-chat",baseUrl:"https://api.x.ai",apiKeyEnvVars:["XAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"grok-3-mini-fast",models:[{id:"grok-3-mini-fast",name:"Grok 3 Mini Fast",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:.5}]},{id:"siliconflow",name:"\u7845\u57FA\u6D41\u52A8 (SiliconFlow)",transport:"openai-chat",baseUrl:"https://api.siliconflow.cn",apiKeyEnvVars:["SILICONFLOW_API_KEY","SF_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"deepseek-ai/DeepSeek-V3",models:[{id:"deepseek-ai/DeepSeek-V3",name:"DeepSeek V3 (via SiliconFlow)",contextWindow:64e3,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.5,costOutput:2},{id:"Qwen/Qwen3-235B-A22B",name:"Qwen3 235B (via SiliconFlow)",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:4}]},{id:"openrouter",name:"OpenRouter",transport:"openai-chat",baseUrl:"https://openrouter.ai/api",apiKeyEnvVars:["OPENROUTER_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"anthropic/claude-sonnet-4",extraHeaders:{"HTTP-Referer":"https://claw.bot","X-Title":"XiaozhiClaw"},models:[{id:"anthropic/claude-sonnet-4",name:"Claude Sonnet 4 (via OpenRouter)",contextWindow:2e5,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15},{id:"deepseek/deepseek-chat",name:"DeepSeek V3 (via OpenRouter)",contextWindow:64e3,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.27,costOutput:1.1}]},{id:"groq",name:"Groq",transport:"openai-chat",baseUrl:"https://api.groq.com/openai",apiKeyEnvVars:["GROQ_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"llama-3.3-70b-versatile",models:[{id:"llama-3.3-70b-versatile",name:"Llama 3.3 70B (via Groq)",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.59,costOutput:.79}]},{id:"together",name:"Together AI",transport:"openai-chat",baseUrl:"https://api.together.xyz",apiKeyEnvVars:["TOGETHER_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",models:[{id:"meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",name:"Llama 3.1 70B Turbo (via Together)",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.88,costOutput:.88}]}];import{existsSync as Zo,mkdirSync as er,readFileSync as tr,writeFileSync as nr}from"node:fs";import{join as en}from"node:path";import{homedir as or}from"node:os";var rr="https://models.dev/api.json",sr=15e3,ir=1440*60*1e3,ar=300*1e3,ie=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??en(or(),".openclaw","cache"),this.cacheFile=en(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??ir}getModels(e){this.ensureLoaded();let o=this.cache?.providers.get(e);return o?[...o.models.values()]:[]}getModel(e,o){return this.ensureLoaded(),this.cache?.providers.get(e)?.models.get(o)}listProviderIds(){return this.ensureLoaded(),this.cache?[...this.cache.providers.keys()]:[]}async refreshCatalog(){return this.fetchRemote()}ensureLoaded(){this.cache&&!this.isStale()||(this.cache||this.loadFromDisk(),(!this.cache||this.isStale())&&this.backgroundFetch())}isStale(){return this.cache?Date.now()-this.cache.fetchedAt>this.ttlMs:!0}loadFromDisk(){try{if(!Zo(this.cacheFile))return;let e=tr(this.cacheFile,"utf8"),o=JSON.parse(e);if(!o.fetchedAt||!o.data)return;this.cache={fetchedAt:o.fetchedAt,providers:tn(o.data)}}catch{}}saveToDisk(e){try{er(this.cacheDir,{recursive:!0});let o=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);nr(this.cacheFile,o,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<ar||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(rr,{signal:AbortSignal.timeout(sr),headers:{Accept:"application/json"}});if(!e.ok)return!1;let o=await e.json(),n=tn(o);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(o),!0)}catch{return!1}}};function tn(t){let e=new Map;if(!t||typeof t!="object")return e;for(let[o,n]of Object.entries(t)){if(!n||typeof n!="object")continue;let r=n.models;if(!r||typeof r!="object")continue;let s=new Map;for(let[a,i]of Object.entries(r)){if(!i||typeof i!="object")continue;let c=i,m=c.limit??{},d=c.modalities??{},g=Array.isArray(d.input)?d.input:[];s.set(a,{id:a,name:typeof c.name=="string"?c.name:a,contextWindow:typeof m.context=="number"?m.context:2e5,maxOutput:typeof m.output=="number"?m.output:8192,toolCall:c.tool_call===!0,reasoning:c.reasoning===!0,vision:c.attachment===!0||g.includes("image"),costInput:typeof c.cost_input=="number"?c.cost_input:void 0,costOutput:typeof c.cost_output=="number"?c.cost_output:void 0})}s.size>0&&e.set(o,{models:s})}return e}var lr={claude:"anthropic",gemini:"google","x-ai":"xai","z-ai":"xai",silicon:"siliconflow","silicon-flow":"siliconflow"},Te=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let o of et)this.builtins.set(o.id,o);this.catalog=e?.catalog??new ie}applyOverride(e,o){this.overrides.set(e,{...this.overrides.get(e),...o})}getProvider(e){let o=lr[e]??e,n=this.builtins.get(o),r=this.overrides.get(o);if(!(!n&&!r))return!n&&r?!r.id||!r.transport||!r.baseUrl?void 0:{id:r.id,name:r.name??r.id,transport:r.transport,baseUrl:r.baseUrl,apiKeyEnvVars:r.apiKeyEnvVars??[],authType:r.authType??"bearer",isAggregator:r.isAggregator??!1,defaultModel:r.defaultModel,models:r.models}:n&&!r?n:{...n,...r,models:r.models??n.models}}listProviders(){let e=new Map;for(let[o,n]of this.builtins)e.set(o,n);for(let[o]of this.overrides){let n=this.getProvider(o);n&&e.set(o,n)}return[...e.values()]}listModels(e){let n=this.getProvider(e)?.models??[],r=this.catalog.getModels(e);if(r.length===0)return n;let s=new Map;for(let a of r)s.set(a.id,a);for(let a of n)s.set(a.id,a);return[...s.values()]}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,o){if(o)return o;let n=this.getProvider(e);if(n)for(let r of n.apiKeyEnvVars){let s=process.env[r];if(s?.trim())return s.trim()}}};var ae=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.supportsStreamOptions=e.supportsStreamOptions??!0,this.omitZeroTemperature=e.omitZeroTemperature??!1}async*stream(e,o,n){let r=`${this.baseUrl}/v1/chat/completions`,s={model:e.model,messages:e.messages,stream:!0};this.supportsStreamOptions&&(s.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(s.tools=e.tools,e.toolChoice&&(s.tool_choice=e.toolChoice)),e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(s.temperature=e.temperature)),e.maxTokens!==void 0&&(s.max_tokens=e.maxTokens),e.reasoning&&(s.reasoning=e.reasoning);let a=AbortSignal.timeout(this.timeoutMs),i=n?AbortSignal.any([n,a]):a,c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...this.extraHeaders},body:JSON.stringify(s),signal:i});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`LLM API error ${c.status}: ${m.slice(0,500)}`)}if(!c.body)throw new Error("LLM API returned no response body");yield*this.parseSSEStream(c.body)}async*parseSSEStream(e){let o=new TextDecoder,n="";for await(let r of e){n+=o.decode(r,{stream:!0});let s;for(;(s=n.indexOf(`
|
|
19
|
+
`))!==-1;){let a=n.slice(0,s).trim();if(n=n.slice(s+1),!a||a.startsWith(":")||!a.startsWith("data: "))continue;let i=a.slice(6);if(i==="[DONE]")return;let c;try{c=JSON.parse(i)}catch{continue}yield*this.mapChunk(c)}}if(n.trim()){let r=n.trim();if(r.startsWith("data: ")&&r.slice(6)!=="[DONE]")try{let s=JSON.parse(r.slice(6));yield*this.mapChunk(s)}catch{}}}*mapChunk(e){if(e.usage&&(yield{type:"usage",promptTokens:e.usage.prompt_tokens??0,completionTokens:e.usage.completion_tokens??0,reasoningTokens:e.usage.completion_tokens_details?.reasoning_tokens}),!(!e.choices||e.choices.length===0))for(let o of e.choices){let n=o.delta;if(n){if(n.reasoning_content&&(yield{type:"reasoning_delta",text:n.reasoning_content}),n.content&&(yield{type:"delta",text:n.content}),n.tool_calls)for(let r of n.tool_calls)yield{type:"tool_call_delta",index:r.index,id:r.id,name:r.function?.name,arguments:r.function?.arguments??""};o.finish_reason&&(yield{type:"done",finishReason:o.finish_reason})}}}};var le=class{baseUrl;apiVersion;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiVersion=e.apiVersion??"2023-06-01",this.timeoutMs=e.timeoutMs??18e4}async*stream(e,o,n){let r=`${this.baseUrl}/v1/messages`,{system:s,messages:a}=dr(e.messages),i={model:e.model,messages:a,max_tokens:e.maxTokens??8192,stream:!0};s&&(i.system=s),e.tools&&e.tools.length>0&&(i.tools=e.tools.map(pr),e.toolChoice&&(i.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})),e.temperature!==void 0&&(i.temperature=e.temperature),e.reasoning&&(i.thinking={type:"enabled",budget_tokens:ur(e.reasoning.effort)});let c=AbortSignal.timeout(this.timeoutMs),m=n?AbortSignal.any([n,c]):c,d=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":o,"anthropic-version":this.apiVersion},body:JSON.stringify(i),signal:m});if(!d.ok){let g=await d.text().catch(()=>"");throw new Error(`Anthropic API error ${d.status}: ${g.slice(0,500)}`)}if(!d.body)throw new Error("Anthropic API returned no response body");yield*this.parseSSEStream(d.body)}async*parseSSEStream(e){let o=new TextDecoder,n="",r="",s=new Map;for await(let a of e){n+=o.decode(a,{stream:!0});let i;for(;(i=n.indexOf(`
|
|
20
|
+
`))!==-1;){let c=n.slice(0,i).trim();if(n=n.slice(i+1),!c){r="";continue}if(c.startsWith("event: ")){r=c.slice(7).trim();continue}if(!c.startsWith("data: "))continue;let m=c.slice(6),d;try{d=JSON.parse(m)}catch{continue}yield*this.mapEvent(r,d,s)}}}*mapEvent(e,o,n){switch(e){case"message_start":{let s=o.message?.usage;s?.input_tokens&&(yield{type:"usage",promptTokens:s.input_tokens??0,completionTokens:s.output_tokens??0});break}case"content_block_start":{let r=o.index,s=o.content_block;if(!s)break;let a=s.type;n.set(r,{type:a,id:s.id,name:s.name}),a==="tool_use"&&(yield{type:"tool_call_delta",index:r,id:s.id,name:s.name,arguments:""});break}case"content_block_delta":{let r=o.index,s=o.delta;if(!s)break;let a=s.type;a==="text_delta"?yield{type:"delta",text:s.text}:a==="input_json_delta"?yield{type:"tool_call_delta",index:r,arguments:s.partial_json}:a==="thinking_delta"&&(yield{type:"reasoning_delta",text:s.thinking});break}case"content_block_stop":{let r=o.index;n.delete(r);break}case"message_delta":{let r=o.delta,s=o.usage;s&&(yield{type:"usage",promptTokens:0,completionTokens:s.output_tokens??0}),r?.stop_reason&&(yield{type:"done",finishReason:cr(r.stop_reason)});break}case"message_stop":break;case"error":{let r=o.error;throw new Error(`Anthropic stream error: ${r?.message??JSON.stringify(o)}`)}}}};function cr(t){switch(t){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_calls";case"max_tokens":return"length";default:return t}}var nn={xhigh:32e3,high:16e3,medium:8e3,low:4e3};function ur(t){return nn[t]??nn.high}function dr(t){let e,o=[];for(let n of t){if(n.role==="system"){e=e?`${e}
|
|
21
|
+
|
|
22
|
+
${n.content??""}`:n.content??"";continue}if(n.role==="user")o.push({role:"user",content:n.content??""});else if(n.role==="assistant")if(n.tool_calls&&n.tool_calls.length>0){let r=[];n.content&&r.push({type:"text",text:n.content});for(let s of n.tool_calls){let a;try{a=JSON.parse(s.function.arguments)}catch{a={}}r.push({type:"tool_use",id:s.id,name:s.function.name,input:a})}o.push({role:"assistant",content:r})}else o.push({role:"assistant",content:n.content??""});else n.role==="tool"&&o.push({role:"user",content:[{type:"tool_result",tool_use_id:n.tool_call_id??"",content:n.content??""}]})}return{system:e,messages:o}}function pr(t){return{name:t.function.name,description:t.function.description,input_schema:t.function.parameters??{type:"object",properties:{}}}}function on(t,e){t.baseUrl&&e.applyOverride(t.provider,{baseUrl:t.baseUrl});let o=e.getProvider(t.provider);if(!o)throw new Error(`Unknown LLM provider: "${t.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let n=t.baseUrl??o.baseUrl;return{transport:mr(o,n),apiKey:t.apiKey,resolvedModel:t.model,providerDef:o}}function rn(t){for(let e of t.listProviders()){let o=t.resolveApiKey(e.id);if(o)return{providerId:e.id,apiKey:o,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function mr(t,e){switch(t.transport){case"openai-chat":return new ae({baseUrl:e,extraHeaders:t.extraHeaders,supportsStreamOptions:t.supportsStreamOptions,omitZeroTemperature:t.omitZeroTemperature});case"anthropic-messages":return new le({baseUrl:e});default:throw new Error(`Unsupported transport type: "${t.transport}" for provider "${t.id}"`)}}import{homedir as gr}from"node:os";import{join as fr}from"node:path";import{mkdirSync as ba,appendFileSync as ka}from"node:fs";var xa=fr(gr(),".openclaw","debug-logs");function yr(t){let e=new Map;return{register(o){let n=e.get(o.point)??[],r={handler:o.handler,priority:o.priority??100,label:o.label};return n.push(r),n.sort((s,a)=>s.priority-a.priority),e.set(o.point,n),()=>{let s=n.indexOf(r);s>=0&&n.splice(s,1)}},async invoke(o,n){let r=e.get(o);if(!r||r.length===0)return{action:"continue",context:n};let s=n;for(let a of r)try{let i=await a.handler(o,s);if(!i||i.action==="continue"){i?.context&&(s=i.context);continue}if(i.action==="abort"||i.action==="skip")return t.info({hook:o,label:a.label,action:i.action,reason:i.reason},"hook intercepted"),i}catch(i){t.warn({hook:o,label:a.label,err:i.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}export{Ze as Agent,Te as ProviderRegistry,rn as autoDetectProvider,re as buildSkillInstruction,yr as createHookRegistry,on as createLLMClient,Qo as parseCliArgs};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
function ze(e){return{role:"assistant",content:"",tool_calls:e}}function He(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"})}}var qe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,R={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]},Ye=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,We=512,Ke=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ve=new Set([500,502,503,504,521,522,523,524,529]),Xe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Je=["upgrade your plan","upgrade plan","current plan","subscription"],Qe=["daily","weekly","monthly"],Ze=["try again","retry","temporary","cooldown"],et=["usage limit","rate limit","organization usage"],tt=["organization","workspace"],nt=["billing period","exceeded","reached","exhausted"],ot=/["']?(?: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,rt=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function A(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function it(e){return A(e,R.format)}function oe(e){return A(e,R.rateLimit)}function st(e){return A(e,R.timeout)}function at(e){return qe.test(e)}function N(e){let t=e.toLowerCase();return t?e.length>We?Ge.test(t):A(t,R.billing)?!0:Ye.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function re(e){return A(e,R.authPermanent)}function lt(e){return A(e,R.auth)}function ie(e){return A(e,R.overloaded)}function x(e,t){return t.some(n=>e.includes(n))}function ct(e){return x(e,Xe)||x(e,Je)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ut(e){let t=x(e,Qe),n=e.includes("spend limit")||e.includes("spending limit"),o=x(e,tt);return x(e,Ze)&&x(e,et)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||x(e,nt))}function dt(e){return e.trim().toLowerCase().replace(rt,"").trim()}function se(e){let t=dt(e);return!t||ct(t)?"billing":oe(t)||ut(t)?"rate_limit":"billing"}function pt(e){return ot.test(e)?se(e):null}function ae(e){let t=e.match(Ke);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function mt(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ft(e){let t=e.trim();if(!t)return!1;let n=ae(t);return n?Ve.has(n.code):!1}function le(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?se(t):"billing":e===429?"rate_limit":e===401||e===403?t&&re(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&ie(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&N(t)?"billing":"format":null}function gt(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 yt(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 ce(e){if(yt(e))return"session_expired";if(gt(e))return"model_not_found";let t=pt(e);return t||(at(e)?N(e)?"billing":"rate_limit":oe(e)?"rate_limit":ie(e)?"overloaded":ft(e)?ae(e.trim())?.code===529?"overloaded":"timeout":mt(e)?"timeout":it(e)?"format":N(e)?"billing":st(e)?"timeout":re(e)?"auth_permanent":lt(e)?"auth":null)}var ht={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"},Ct={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 Tt(e,t){let n=le(e,t)??(t?ce(t):null);return n?ht[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function bt(e){return Ct[e]}function Y(e){return typeof e.compressAsync=="function"}var ue=4,D=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let u of t)u.role==="system"?o.push(u):r.push(u);let i=n;for(let u of o)i-=this.estimateTokens(u);let s;for(let u of r)if(u.role==="user"){s=u;break}if(s&&(i-=this.estimateTokens(s)),i<=0)return{messages:s?[...o,s]:o,droppedCount:r.length-(s?1:0),strategy:"sliding-window"};let a=[],l=0;for(let u=r.length-1;u>=0;u--){let d=r[u];if(d===s)continue;let p=this.estimateTokens(d);if(i-p<0&&l>=ue)break;if(i-p<0&&l<ue){a.unshift(d),l++;continue}i-=p,a.unshift(d),l++}let c=[...o];return s&&!a.includes(s)&&c.push(s),c.push(...a),{messages:c,droppedCount:r.length-(a.length+(s&&!a.includes(s)?1:0)),strategy:"sliding-window"}}},F=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]
|
|
2
|
+
${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},B=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:St(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function St(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
3
|
+
`),n.lastIndexOf(`]
|
|
4
|
+
`));if(i>t*.5)return n.slice(0,i+1)+`
|
|
5
|
+
[...truncated: ${e.length-i-1} chars omitted]`}let r=n.lastIndexOf(`
|
|
6
|
+
`);return r>t*.7?n.slice(0,r)+`
|
|
7
|
+
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
8
|
+
[...truncated: ${e.length-t} chars omitted]`}function kt(...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 xt(...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=Y(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 G(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=s.role==="user"?a: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(`
|
|
9
|
+
`)}var $=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,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((g,y)=>g+this.config.estimateTokens(y),0);if(s<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let g=0;g<i.length&&(i[g].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));g++)a=g+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),f=G(d,{taskContext:this.config.taskContext}),h=await this.config.summarize(d,f),v={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
10
|
+
|
|
11
|
+
${h}`},b=[...r,...u,v,...p],S=Date.now()-o,k=b.reduce((g,y)=>g+this.config.estimateTokens(y),0);return{messages:b,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:s,tokensAfter:k,compressionRatio:s>0?k/s:1,latencyMs:S,usedLlm:!0,cacheInvalidated:!0}}}},j=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}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(y=>typeof y.content=="string"&&y.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((y,O)=>y+this.config.estimateTokens(O),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,c),p=i.slice(c),f=a&&typeof a.content=="string"?`Previous summary:
|
|
12
|
+
${a.content}
|
|
13
|
+
|
|
14
|
+
New messages to integrate:`:void 0,h=G(d,{taskContext:f}),v=await this.config.summarize(d,h),b={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
15
|
+
|
|
16
|
+
${v}`},S=[...l,b,...p],k=Date.now()-o,g=S.reduce((y,O)=>y+this.config.estimateTokens(O),0);return{messages:S,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:g,compressionRatio:u>0?g/u:1,latencyMs:k,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config=t}compress(t,n){let o=w(t),r=this.config.inner.compress(t,n),i=w(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=w(t),r=Y(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=w(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}}}},de={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function Rt(e={}){let t={...de,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function At(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var z=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}},H=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 M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function w(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("|")}var vt=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),q=class{constructor(t=20,n=M){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((a,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!vt.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return i+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function _t(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let s=JSON.parse(r.function.arguments),a=s.path??s.filePath??s.file_path??s.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function wt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=_t(t);if(r.length===0)return e;let i=e.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
17
|
+
`),s=r.filter(p=>!i.includes(p));if(s.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let p of s){if(c>=n.maxFiles||a<=0)break;let f=await n.readFile(p);if(!f)continue;let h=o(f);h>a||(a-=h,c++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
18
|
+
|
|
19
|
+
${f}`}))}if(l.length===0)return e;let u=[...e],d=-1;for(let p=0;p<u.length;p++)u[p].role==="system"&&(d=p);return u.splice(d+1,0,...l),u}function Mt(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}i.push(a)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function Et(){return{stages:[]}}function It(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=Lt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=me(e,t),{messages:i,stagedCount:s.length}}function Pt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let a=Math.min(s,o.length),l={role:"system",content:r.summary};o.splice(i,a-i,l)}return o}function Lt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),s=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=l),a++;else{if(a>=3){let d=`${s}-${s+a}`;i.has(d)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}s=-1,a=0}}if(a>=3){let l=`${s}-${s+a}`;i.has(l)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function Ot(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function Nt(e){return e.existingSkillName?e.feedback==="negative":!1}function Dt(e,t){return Nt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Ot(e)?{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}:null}var Ft=["submit-review","approve","reject","start-canary","record-effectiveness","promote","publish","mark-stale","mark-superseded","rollback"],Bt=["canary","published"];function m(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}function T(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function E(e,t=0){let n=T(e);return n===void 0?Math.max(0,Math.floor(t)):Math.max(0,Math.floor(n))}function C(e){return e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function $t(e){return typeof e=="string"&&Ft.includes(e)}function jt(e){return typeof e=="string"&&Bt.includes(e)}function ge(e){let t=m(e);return t&&$t(t)?t:null}function W(e){let t=m(e);return t&&jt(t)?t:null}function ye(e){let t=C(e),n=m(t.uri);if(!n)return null;let o=m(t.sha256),r=m(t.workspaceDir),i=m(t.relativePath),s=m(t.sourceWorkspaceDir),a=m(t.stagedAt);return{uri:n,...o?{sha256:o}:{},...r?{workspaceDir:r}:{},...i?{relativePath:i}:{},...s?{sourceWorkspaceDir:s}:{},...a?{stagedAt:a}:{}}}function he(e){let t=C(e),n=m(t.executionId),o=m(t.rootExecutionId),r=m(t.parentExecutionId),i=m(t.sidechainId),s=m(t.attemptId),a=m(t.outcomeId),l=m(t.sessionId),c=m(t.turnId);return!n&&!o&&!r&&!i&&!s&&!a&&!l&&!c?null:{...n?{executionId:n}:{},...o?{rootExecutionId:o}:{},...r?{parentExecutionId:r}:{},...i?{sidechainId:i}:{},...s?{attemptId:s}:{},...a?{outcomeId:a}:{},...l?{sessionId:l}:{},...c?{turnId:c}:{}}}function Ce(e){let t=C(e),n=W(t.phase);if(!n)return null;let o=E(t.successCount),r=T(t.failureCount),i=E(t.sampleCount,r!==void 0?o+r:o),s=E(t.failureCount,Math.max(i-o,0)),a=E(t.regressionCount),l=T(t.successRate)??(i>0?o/i:0),c=T(t.regressionRate)??(i>0?a/i:0),u=T(t.avgLatencyMs),d=T(t.avgCostUsd),p=T(t.score),f=m(t.staleReason)??null,h=m(t.notes)??null,v=C(t.summary),b=m(t.lastObservedAt),S=m(t.updatedAt),k=m(t.lastActivityAt),g=T(t.activityCount);return{phase:n,sampleCount:i,successCount:o,failureCount:s,regressionCount:a,successRate:l,regressionRate:c,...u!==void 0?{avgLatencyMs:u}:{},...d!==void 0?{avgCostUsd:d}:{},...p!==void 0?{score:p}:{},...f?{staleReason:f}:{},...h?{notes:h}:{},...Object.keys(v).length>0?{summary:v}:{},...b?{lastObservedAt:b}:{},...S?{updatedAt:S}:{},...k?{lastActivityAt:k}:{},...g!==void 0?{activityCount:g}:{}}}var Te={reviewRequired:!0,canaryRequired:!0,autoPromote:!1,minCanarySampleCount:10,minSuccessRate:.7,maxRegressionRate:.1,maxCostIncreaseRate:.25,staleAfterHours:168};function K(e,t){if(typeof e=="boolean")return e;if(typeof e=="string"){let n=e.trim().toLowerCase();if(n==="true")return!0;if(n==="false")return!1}return t}function _(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=e.trim();if(n){let o=Number(n);if(Number.isFinite(o))return o}}return t}function Ut(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean):[]}function zt(e={}){return be(e,Te)}function be(e,t=Te){let n=C(e);return{reviewRequired:K(n.reviewRequired,t.reviewRequired),canaryRequired:K(n.canaryRequired,t.canaryRequired),autoPromote:K(n.autoPromote,t.autoPromote),minCanarySampleCount:Math.max(1,Math.floor(_(n.minCanarySampleCount,t.minCanarySampleCount))),minSuccessRate:Math.max(0,Math.min(1,_(n.minSuccessRate,t.minSuccessRate))),maxRegressionRate:Math.max(0,Math.min(1,_(n.maxRegressionRate,t.maxRegressionRate))),maxCostIncreaseRate:Math.max(0,_(n.maxCostIncreaseRate,t.maxCostIncreaseRate)),staleAfterHours:Math.max(1,Math.floor(_(n.staleAfterHours,t.staleAfterHours)))}}function Se(e){let t=C(e.evidence),n=e.artifact?ye(e.artifact):null,o=e.sourceExecution?he(e.sourceExecution):null,r=typeof e.sourceSessionKey=="string"?e.sourceSessionKey.trim():"";return{...t,...n?{artifact:n}:{},...o?{sourceExecution:o}:{},...r?{sourceSessionKey:r}:{}}}function Ht(e){let t=Se(e),n=typeof e.diffSummary=="string"&&e.diffSummary.trim()?e.diffSummary.trim():"",o=typeof e.baselineCandidateId=="string"&&e.baselineCandidateId.trim()?e.baselineCandidateId.trim():"",r=typeof e.rolloutNotes=="string"&&e.rolloutNotes.trim()?e.rolloutNotes.trim():"",i=Ut(e.validationRefs);return{...t,...n?{diffSummary:n}:{},...o?{baselineCandidateId:o}:{},...r?{rolloutNotes:r}:{},...i.length>0?{validationRefs:i}:{}}}function qt(e){return{action:ge(e.action)??e.action,actor:typeof e.actor=="string"&&e.actor.trim()?e.actor.trim():null,notes:typeof e.notes=="string"&&e.notes.trim()?e.notes.trim():null,payload:C(e.payload),createdAt:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt.trim():new Date().toISOString()}}function Yt(e){let t=Math.max(0,Math.floor(e.sampleCount??0)),n=Math.max(0,Math.floor(e.successCount??0)),o=Math.max(0,Math.floor(e.failureCount??Math.max(t-n,0))),r=Math.max(0,Math.floor(e.regressionCount??0)),i=t>0?n/t:0,s=t>0?r/t:0,a=typeof e.score=="number"&&Number.isFinite(e.score)?e.score:Number((i-s).toFixed(4));return Ce({phase:W(e.phase)??e.phase,sampleCount:t,successCount:n,failureCount:o,regressionCount:r,successRate:i,regressionRate:s,avgLatencyMs:e.avgLatencyMs,avgCostUsd:e.avgCostUsd,score:a,staleReason:e.staleReason,notes:e.notes,summary:C(e.summary),lastObservedAt:e.lastObservedAt??new Date().toISOString(),updatedAt:e.updatedAt??new Date().toISOString()})}function ke(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Gt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Wt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Kt(e){if(!e.eligibility?.length)return[...e.tools];let t=Wt(e.eligibility);return e.tools.filter(n=>{let o=ke(n);if(!o)return!1;let r=t.get(o);return!r||Gt(r.status)})}function Vt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Xt(e){let t=Vt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Kt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>ke(l)===s);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Jt=["stop","aborted","timeout","cancelled","interrupted","error"],Qt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function xe(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Zt(e,t){return{...e,content:[...xe(e.content),...xe(t.content)]}}function en(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function tn(e){return new Set((e??Jt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?tn(t).has(e.trim().toLowerCase()):!1}function nn(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function V(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(c=>en(c));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),n=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let l of a.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&n.has(a.tool_call_id))),r=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&r.add(a.tool_call_id);let i=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...u}=a;u.content!=null&&u.content!==""&&i.push(u);continue}if(l.length<a.tool_calls.length){i.push({...a,tool_calls:l});continue}}i.push(a)}let s=[];for(let a of i){let l=s.length>0?s[s.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){s[s.length-1]=Zt(l,a);continue}s.push(a)}return s}function X(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Qt)delete o[r];return o}):[...e]}function J(e,t){let n=t?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function on(e,t){let n=V(e),o=X(n,t);return J(o,t)}function Ae(e,t){let n=t?.placeholderFunctionCallOutput??JSON.stringify({ok:!1,error:"Tool loop interrupted before function_call_output was provided."}),o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let d={...u};if(typeof d.id=="string"){let p=nn(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;a.add(u)}l.push(c)}for(let[c]of s)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function rn(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function sn(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function an(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function ln(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function ve(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function cn(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function un(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function dn(e){let t=[],n=V(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=X(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=J(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:ve({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:rn(r),completedToolCallIds:sn(r)}),recoveryActions:t}}function pn(e){let t=Ae(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:ve({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:an(t),completedToolCallIds:ln(t)}),recoveryActions:n}}import{MEMORY_OBSERVATION_HOOK_VALUES as mn,MEMORY_OBSERVATION_SOURCE_VALUES as fn,MEMORY_WRITE_ACCESS_VALUES as gn}from"qlogicagent-runtime-contracts";var yn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function hn(e){return e?yn.has(e):!0}function Cn(e){return e===429||e===529}function Tn(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var zo={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function bn(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Q=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var I={minIdleSeconds:7200,intervalSeconds:604800,staleAfterDays:30,archiveAfterDays:90,maxReviewBatchSize:50},Sn={lastRunAt:null,lastRunDurationSeconds:0,lastRunSummary:"",paused:!1,runCount:0};function kn(e){let t={...I,...e.policy};if(!e.enabled)return{shouldRun:!1,reason:"curator disabled"};if(e.state.paused)return{shouldRun:!1,reason:"curator paused by user"};if(e.idleSeconds<t.minIdleSeconds)return{shouldRun:!1,reason:`session not idle long enough (${e.idleSeconds}s < ${t.minIdleSeconds}s)`};if(e.state.lastRunAt){let n=(new Date(e.now).getTime()-new Date(e.state.lastRunAt).getTime())/1e3;if(n<t.intervalSeconds)return{shouldRun:!1,reason:`last run too recent (${Math.round(n)}s < ${t.intervalSeconds}s)`}}return{shouldRun:!0,reason:"all gates passed"}}function xn(e,t,n){let o={...I,...n},r=new Date(t).getTime(),i=[],s=0;for(let a of e){if(!a.agentCreated||(s++,a.pinned))continue;let l=a.lastActivityAt?new Date(a.lastActivityAt).getTime():new Date(a.createdAt).getTime(),c=(r-l)/(1e3*60*60*24);a.state==="active"&&c>=o.staleAfterDays?i.push({skillName:a.name,from:"active",to:"stale",reason:`inactive for ${Math.floor(c)} days (threshold: ${o.staleAfterDays})`}):a.state==="stale"&&c>=o.archiveAfterDays&&i.push({skillName:a.name,from:"stale",to:"archived",reason:`inactive for ${Math.floor(c)} days (threshold: ${o.archiveAfterDays})`}),(a.state==="stale"||a.state==="archived")&&a.useCount>0&&c<o.staleAfterDays&&i.push({skillName:a.name,from:a.state,to:"active",reason:"recent activity detected \u2014 reactivated"})}return{checked:s,transitions:i,markedStale:i.filter(a=>a.to==="stale").length,archived:i.filter(a=>a.to==="archived").length,reactivated:i.filter(a=>a.to==="active").length}}function Rn(e,t){let n={...I,...t};return e.filter(o=>o.agentCreated&&!o.pinned&&(o.state==="active"||o.state==="stale")).sort((o,r)=>o.useCount-r.useCount).slice(0,n.maxReviewBatchSize).map(o=>o.name)}function An(e,t=2){let n=new Map;for(let r of e){let i=r.indexOf("-");if(i<2)continue;let s=r.slice(0,i),a=n.get(s);a?a.push(r):n.set(s,[r])}let o=[];for(let[r,i]of n)i.length>=t&&o.push({prefix:r,skills:i.sort()});return o.sort((r,i)=>i.skills.length-r.skills.length)}function vn(e,t,n){let o=e.map(s=>`- **${s.name}** (${s.state}, uses: ${s.useCount}, tools: ${s.tools})${s.lastActivityAt?` last active: ${s.lastActivityAt}`:""}`).join(`
|
|
20
|
+
`),r=t.length>0?t.map(s=>`- ${s}`).join(`
|
|
21
|
+
`):"(none)";return`You are the Autonomous Curator for a skill library.
|
|
22
|
+
|
|
23
|
+
## Goal
|
|
24
|
+
|
|
25
|
+
Transform narrow, session-specific skills into a well-organized library of
|
|
26
|
+
class-level umbrella skills. A collection of hundreds of narrow skills is FAILURE.
|
|
27
|
+
|
|
28
|
+
## Ground Rules
|
|
29
|
+
|
|
30
|
+
1. **NEVER delete** \u2014 only archive (prune). Archived skills can be restored.
|
|
31
|
+
2. **Do NOT touch pinned or bundled skills** \u2014 they are already filtered out.
|
|
32
|
+
3. **Identify prefix clusters** and merge them into umbrella skills.
|
|
33
|
+
4. **Move session-specific details** into the umbrella's references/ folder.
|
|
34
|
+
5. **Preserve unique value** \u2014 only merge if the source is genuinely redundant
|
|
35
|
+
or a subset of the target.
|
|
36
|
+
|
|
37
|
+
## Detected Prefix Clusters
|
|
38
|
+
|
|
39
|
+
${n.length>0?n.map(s=>`- **${s.prefix}-***: ${s.skills.join(", ")}`).join(`
|
|
40
|
+
`):"(no clusters detected)"}
|
|
41
|
+
|
|
42
|
+
## Existing Umbrella Skills
|
|
43
|
+
|
|
44
|
+
${r}
|
|
45
|
+
|
|
46
|
+
## Candidate Skills for Review
|
|
47
|
+
|
|
48
|
+
${o}
|
|
49
|
+
|
|
50
|
+
## Required Output Format
|
|
51
|
+
|
|
52
|
+
Respond with EXACTLY this YAML block (no extra text outside the block):
|
|
53
|
+
|
|
54
|
+
\`\`\`yaml
|
|
55
|
+
consolidations:
|
|
56
|
+
- source: "skill-name-a"
|
|
57
|
+
target: "umbrella-skill"
|
|
58
|
+
reason: "subset of umbrella functionality"
|
|
59
|
+
- source: "skill-name-b"
|
|
60
|
+
target: "new-umbrella-name"
|
|
61
|
+
reason: "cluster merge"
|
|
62
|
+
|
|
63
|
+
prunings:
|
|
64
|
+
- skill: "skill-name-c"
|
|
65
|
+
reason: "trivial single-use, no ongoing value"
|
|
66
|
+
\`\`\`
|
|
67
|
+
|
|
68
|
+
If no consolidations or prunings are warranted, use empty lists.
|
|
69
|
+
Respond ONLY with the YAML block.`}function _n(e,t){let n=[],o=[],r=[],i=e.match(/```(?:yaml)?\s*\n([\s\S]*?)```/),s=i?i[1]:e,a=s.match(/consolidations:\s*\n((?:\s+-[\s\S]*?)?)(?=prunings:|$)/);if(a?.[1]){let c=a[1].matchAll(/- source:\s*"([^"]+)"\s*\n\s*target:\s*"([^"]+)"\s*\n\s*reason:\s*"([^"]+)"/g);for(let[,u,d,p]of c){if(!t.has(u)){r.push(u);continue}n.push({sourceSkill:u,targetUmbrella:d,targetExists:t.has(d),reason:p})}}let l=s.match(/prunings:\s*\n([\s\S]*?)$/);if(l?.[1]){let c=l[1].matchAll(/- skill:\s*"([^"]+)"\s*\n\s*reason:\s*"([^"]+)"/g);for(let[,u,d]of c){if(!t.has(u)){r.push(u);continue}o.push({skillName:u,reason:d})}}return{consolidations:n,prunings:o,hallucinations:r}}function wn(e,t){let n=[],o=[],r=[],i=new Set;for(let s of e.consolidations){if(!t.has(s.sourceSkill)){r.push({action:`consolidate ${s.sourceSkill} \u2192 ${s.targetUmbrella}`,reason:`source skill "${s.sourceSkill}" not found`});continue}if(i.has(s.sourceSkill)){r.push({action:`consolidate ${s.sourceSkill} \u2192 ${s.targetUmbrella}`,reason:`source skill "${s.sourceSkill}" already consolidated in this plan`});continue}if(s.sourceSkill===s.targetUmbrella){r.push({action:`consolidate ${s.sourceSkill} \u2192 ${s.targetUmbrella}`,reason:"source and target are the same skill"});continue}i.add(s.sourceSkill),n.push(s)}for(let s of e.prunings){if(!t.has(s.skillName)){r.push({action:`prune ${s.skillName}`,reason:`skill "${s.skillName}" not found`});continue}if(i.has(s.skillName)){r.push({action:`prune ${s.skillName}`,reason:`skill "${s.skillName}" is being consolidated, not pruned`});continue}o.push(s)}return{validConsolidations:n,validPrunings:o,rejected:r}}function Mn(e){let t=[];return t.push(`Curator run at ${e.runAt} (${e.durationSeconds.toFixed(1)}s)`),t.push(`Auto: ${e.autoTransitionsChecked} checked, ${e.autoMarkedStale} stale, ${e.autoArchived} archived, ${e.autoReactivated} reactivated`),t.push(`LLM: ${e.consolidationsAccepted} consolidated, ${e.pruningsAccepted} pruned, ${e.actionsRejected} rejected, ${e.hallucinations} hallucinated`),t.join("; ")}var P={blockCreationThreshold:.75,curatorReviewThreshold:.55,toolWeight:.6,titleWeight:.3,stepWeight:.1};function we(e,t){let n=new Set(e.map(s=>s.toLowerCase())),o=new Set(t.map(s=>s.toLowerCase()));if(n.size===0&&o.size===0)return 0;let r=0;for(let s of n)o.has(s)&&r++;let i=n.size+o.size-r;return i===0?0:r/i}function Me(e,t){let n=_e(e.toLowerCase()),o=_e(t.toLowerCase());if(n.size===0&&o.size===0||n.size===0||o.size===0)return 0;let r=0;for(let i of n)o.has(i)&&r++;return 2*r/(n.size+o.size)}function _e(e){let t=new Set,n=e.replace(/[^a-z0-9\u4e00-\u9fff]/g," ").trim();for(let o=0;o<n.length-1;o++)t.add(n.slice(o,o+2));return t}function Ee(e,t){if(e==null||t==null)return .5;if(e===0&&t===0)return 1;let n=Math.abs(e-t),o=Math.max(e,t);return 1-n/o}function Ie(e,t,n){let o={...P,...n},r=we(e.tools,t.tools),i=Me(e.title,t.title),s=Ee(e.stepCount,t.stepCount);return{overall:o.toolWeight*r+o.titleWeight*i+o.stepWeight*s,toolJaccard:r,titleSimilarity:i,stepProximity:s}}function En(e,t,n){let o={...P,...n},r=[];for(let i of t){if(i.skillKey===e.skillKey)continue;let s=Ie(e,i,o);s.overall>=o.curatorReviewThreshold&&r.push({existingSkillKey:i.skillKey,score:s})}return r.sort((i,s)=>s.score.overall-i.score.overall)}function In(e,t){let n={...P,...t};if(e.length===0)return{action:"create",reason:"no similar skills found"};let o=e[0];return o.score.overall>=n.blockCreationThreshold?{action:"improve",targetSkillKey:o.existingSkillKey,reason:`similarity ${(o.score.overall*100).toFixed(0)}% \u2265 creation threshold ${(n.blockCreationThreshold*100).toFixed(0)}% (tool overlap: ${(o.score.toolJaccard*100).toFixed(0)}%)`}:{action:"flag-for-review",targetSkillKey:o.existingSkillKey,reason:`similarity ${(o.score.overall*100).toFixed(0)}% between review and creation thresholds`}}var Pe={planner:3,executor:4,reviewer:2,researcher:3,custom:2},Pn={parallel:4,sequential:1,pipeline:1,adaptive:3},L=8,Ln=2;function On(e){let t=e.subtasks.slice(0,L).map(i=>{let s=Dn(i.role);return{agentId:i.id,role:i.role,label:i.label,sidechainType:Le(i.role),taskDescription:i.task,toolAccessMode:Oe(i.role),budgetTier:s,dependsOn:i.dependsOn??[],maxTokenBudget:0,maxToolCalls:Nn(i.role),timeoutMs:0}}),n=e.mode??De(t),o=e.totalTokenBudget??1e5,r=Ne(t,o);return{teamId:e.teamId,mode:n,aggregationPolicy:e.aggregationPolicy??Fe(n,t),agents:r,maxConcurrency:Pn[n],timeoutMs:e.timeoutMs??3e5,totalTokenBudget:o,failFast:e.failFast??n==="pipeline",sharedContext:e.sharedContext??"",mergePolicy:e.mergePolicy??"summary-only"}}function Le(e){switch(e){case"planner":return"planner";case"executor":return"code-repair";case"reviewer":return"research";case"researcher":return"research";case"custom":return"research"}}function Oe(e){switch(e){case"planner":return"none";case"executor":return"full";case"reviewer":return"read-only";case"researcher":return"read-only";case"custom":return"read-only"}}function Nn(e){switch(e){case"planner":return 0;case"executor":return 30;case"reviewer":return 10;case"researcher":return 15;case"custom":return 10}}function Dn(e){switch(e){case"planner":return"high";case"executor":return"high";case"reviewer":return"medium";case"researcher":return"medium";case"custom":return"low"}}function Ne(e,t){let n=e.reduce((o,r)=>o+Pe[r.role],0);return n===0?e:e.map(o=>({...o,maxTokenBudget:Math.floor(Pe[o.role]/n*t)}))}function De(e){return e.some(o=>o.dependsOn.length>0)?e.every((o,r)=>r===0?o.dependsOn.length===0:o.dependsOn.includes(e[r-1].agentId))?"pipeline":"sequential":"parallel"}function Fe(e,t){let n=t.some(r=>r.role==="reviewer"),o=t.some(r=>r.role==="planner");return n?"reviewer-gate":o&&e==="adaptive"?"planner-sync":e==="parallel"&&t.length>=3?"majority-vote":"merge-all"}function Fn(e){let t=new Set(e.map(l=>l.agentId)),n=new Map(e.map(l=>[l.agentId,l.dependsOn.filter(c=>t.has(c))])),o=new Set,r=[],i=new Set(t),s=0,a=e.length+1;for(;i.size>0&&s<a;){let l=[];for(let c of i)(n.get(c)??[]).every(d=>o.has(d))&&l.push(c);if(l.length===0){let c=i.values().next().value;c&&l.push(c)}for(let c of l)i.delete(c),o.add(c);r.push(l),s++}return r}function Bn(e,t){let n=e.filter(o=>o.status==="completed");switch(t){case"first-success":return n[0]?.output??"[No successful agent output]";case"majority-vote":if(n.length===0)return"[No successful agent output]";let o=new Map;for(let s of n){let a=s.output.trim();o.set(a,(o.get(a)??0)+1)}let r="",i=0;for(let[s,a]of o)a>i&&(r=s,i=a);return r||n[0].output;case"merge-all":return n.map(s=>`[${s.role}:${s.agentId}]
|
|
70
|
+
${s.output}`).join(`
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
`);case"reviewer-gate":{let s=n.find(l=>l.role==="reviewer"),a=n.filter(l=>l.role!=="reviewer");return s?`[Review]
|
|
75
|
+
${s.output}
|
|
76
|
+
|
|
77
|
+
[Execution]
|
|
78
|
+
${a.map(l=>l.output).join(`
|
|
79
|
+
`)}`:a.map(l=>l.output).join(`
|
|
80
|
+
|
|
81
|
+
`)}case"planner-sync":{let s=n.find(l=>l.role==="planner"),a=n.filter(l=>l.role!=="planner");return s?`[Plan]
|
|
82
|
+
${s.output}
|
|
83
|
+
|
|
84
|
+
[Results]
|
|
85
|
+
${a.map(l=>`- ${l.agentId}: ${l.output.slice(0,500)}`).join(`
|
|
86
|
+
`)}`:a.map(l=>l.output).join(`
|
|
87
|
+
|
|
88
|
+
`)}}}function $n(e){let t=[];e.agents.length===0&&t.push("Team plan has no agents"),e.agents.length>L&&t.push(`Too many agents: ${e.agents.length} > ${L}`),e.totalTokenBudget<=0&&t.push("Total token budget must be positive");let n=e.agents.map(r=>r.agentId),o=new Set(n);o.size!==n.length&&t.push("Duplicate agent IDs in team plan");for(let r of e.agents)for(let i of r.dependsOn)o.has(i)||t.push(`Agent "${r.agentId}" depends on non-existent agent "${i}"`),i===r.agentId&&t.push(`Agent "${r.agentId}" depends on itself`);if(e.mode==="pipeline")for(let r=1;r<e.agents.length;r++)e.agents[r].dependsOn.includes(e.agents[r-1].agentId)||t.push(`Pipeline mode requires linear dependencies; agent "${e.agents[r].agentId}" doesn't depend on previous`);return t}function jn(e){let{plan:t,results:n,elapsedMs:o}=e;return t.timeoutMs>0&&o>t.timeoutMs?{cancel:!0,reason:"team_timeout"}:t.failFast&&n.some(i=>i.status==="failed")?{cancel:!0,reason:"fail_fast"}:n.length>=t.agents.length?{cancel:!1,reason:""}:n.reduce((i,s)=>i+s.tokenUsage.prompt+s.tokenUsage.completion,0)>=t.totalTokenBudget*.95?{cancel:!0,reason:"budget_exhausted"}:{cancel:!1,reason:""}}function Un(e){let{agent:t,plan:n,dependencyResults:o}=e,r=[];if(n.sharedContext&&r.push(`[Shared Context]
|
|
89
|
+
${n.sharedContext}`),o.length>0){let i=o.filter(s=>s.status==="completed").map(s=>`[From ${s.agentId} (${s.role})]
|
|
90
|
+
${s.output}`).join(`
|
|
91
|
+
|
|
92
|
+
`);i&&r.push(`[Prior Results]
|
|
93
|
+
${i}`)}return r.push(`[Your Task]
|
|
94
|
+
${t.taskDescription}`),r.push(`[Your Role: ${t.role}]
|
|
95
|
+
${zn(t.role)}`),r.join(`
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
`)}function zn(e){switch(e){case"planner":return"You are the planner. Break down the task, identify dependencies, and create a clear execution plan. Do NOT execute actions yourself.";case"executor":return"You are the executor. Follow the plan and use tools to accomplish the task. Report what you did and any issues encountered.";case"reviewer":return"You are the reviewer. Examine the execution results for correctness, completeness, and quality. Point out any issues or improvements needed.";case"researcher":return"You are the researcher. Gather information, search for relevant context, and provide evidence-based findings. Do NOT modify any files.";case"custom":return"Complete the assigned task to the best of your ability."}}var Z="<fork-child-context>",Be="Fork started \u2014 processing in background",Hn=4,qn=2;function Yn(e){return JSON.stringify(e).includes(Z)}function Gn(e,t="in-memory"){return e<(t==="in-memory"?4:2)}function Wn(e,t){let n=[...e.parentMessages],o={role:"user",content:[{type:"text",text:`${Z}
|
|
100
|
+
|
|
101
|
+
You are the "${t.agent.name}" agent.
|
|
102
|
+
|
|
103
|
+
${t.taskPrompt}`}]};return n.push(o),n}function Kn(e){return e.map(t=>({role:"tool",tool_call_id:t,content:Be}))}function Vn(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 Xn(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Jn={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},Qn={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},Zn={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},eo={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},to={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},no={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},ee=[Jn,Qn,Zn,eo,to,no];function oo(){return[...ee]}function ro(e){return ee.find(t=>t.name===e)}function io(e){return ee.some(t=>t.name===e)}function so(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent_tool"&&n!=="team_create")}var ao=new Set(["agent_tool","team_create","fork_agent","send_message"]);function lo(e,t){switch(e){case"worker":return t.filter(n=>!ao.has(n));case"coordinator":return[...t];default:return[...t]}}function co(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function uo(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function po(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 mo(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 fo(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 go(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var yo={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function ho(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
|
|
104
|
+
${n.join(`
|
|
105
|
+
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
106
|
+
Step ${e.activeSkillContext.step}:
|
|
107
|
+
${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
|
|
108
|
+
${n.join(`
|
|
109
|
+
`)}`)}if(e.customBlocks)for(let n of e.customBlocks)t.push(`## ${n.label}
|
|
110
|
+
${n.content}`);return t.length===0?null:`[Context was compressed. The following state has been restored:]
|
|
111
|
+
|
|
112
|
+
${t.join(`
|
|
113
|
+
|
|
114
|
+
`)}`}function Co(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function To(e,t=yo){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function bo(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})
|
|
115
|
+
${s.result.output||"(no output)"}`);return{ok:r,output:i.join(`
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
`),agentResults:e,totalTokensUsed:n,finalState:r?"completed":"failed"}}case"reviewer-gate":{let i=e.find(l=>l.role==="reviewer"),a=e.filter(l=>l.role!=="reviewer").map(l=>l.result.output).filter(Boolean).join(`
|
|
120
|
+
|
|
121
|
+
`);return i&&i.result.ok?{ok:!0,output:`## Reviewed Output
|
|
122
|
+
${a}
|
|
123
|
+
|
|
124
|
+
## Review
|
|
125
|
+
${i.result.output}`,agentResults:e,totalTokensUsed:n,finalState:"completed"}:{ok:!1,output:`Review failed: ${i?.result.output||"no reviewer result"}`,agentResults:e,totalTokensUsed:n,finalState:"failed"}}case"planner-sync":{let i=e.find(s=>s.role==="planner");return i?{ok:i.result.ok,output:i.result.output,agentResults:e,totalTokensUsed:n,finalState:i.result.ok?"completed":"failed"}:te(e,"merge-all")}default:return te(e,"merge-all")}}function So(e,t){return e.agents.map(n=>{let o=t(n.agentType);if(!o)throw new Error(`Unknown agent type "${n.agentType}" in team request`);return{agentDef:o,prompt:n.prompt,maxTurns:n.maxTurns,role:n.role}})}var ko=["research","planner","plan-repair","code-repair","media-prep"],je={research:{type:"research",label:"Research",description:"Independent retrieval or evidence gathering branches.",mergePolicy:"summary-only",budgetTier:"medium",budgetWeight:2,preferFullContext:!1,preserveConversationHistory:!0,toolAccessMode:"read-only"},planner:{type:"planner",label:"Planner",description:"Planning and tool orchestration branches that may return structured context.",mergePolicy:"append-messages",budgetTier:"high",budgetWeight:3,preferFullContext:!0,preserveConversationHistory:!0,toolAccessMode:"none"},"plan-repair":{type:"plan-repair",label:"Plan Repair",description:"Failure repair or fallback branches that re-plan tool choice, ordering, or approval strategy.",mergePolicy:"replace-context",budgetTier:"medium",budgetWeight:2,preferFullContext:!0,preserveConversationHistory:!1,toolAccessMode:"none"},"code-repair":{type:"code-repair",label:"Code Repair",description:"Recovery branches focused on file edits, patch validation, or workspace mutation repair.",mergePolicy:"replace-context",budgetTier:"high",budgetWeight:3,preferFullContext:!0,preserveConversationHistory:!1,toolAccessMode:"full"},"media-prep":{type:"media-prep",label:"Media Prep",description:"Preparation branches for media generation, normalization, or staging.",mergePolicy:"summary-only",budgetTier:"low",budgetWeight:1,preferFullContext:!1,preserveConversationHistory:!1,toolAccessMode:"read-only"}},ne=["gateway","agents_list","whatsapp_login","session_status","cron","memory_query","sessions_send"],xo=["sessions_list","sessions_history","sessions_spawn"],$e=["file_edit","create_file","replace_string_in_file","multi_replace_string_in_file","create_directory","run_in_terminal","run_command","delete_file","rename_file","move_file","git_commit","git_push","manage_todo_list"];function Ro(e={}){let t=Math.max(1,Math.floor(e.maxDepth??2)),n=typeof e.depth=="number"&&Number.isFinite(e.depth)?Math.max(0,Math.floor(e.depth)):t,o=e.role?e.role==="leaf":n>=t,r=o?[...ne,...xo]:[...ne],i=new Set(r),s=Array.isArray(e.toolNames)?e.toolNames:e.toolNames?Array.from(e.toolNames):[],a=Array.from(new Set(s.map(l=>l.trim()).filter(Boolean))).map(l=>{let c=i.has(l);return{toolName:l,decision:c?"denied":"allowed",inheritance:c?"shrink":"inherit",reason:c?ne.includes(l)?"always-deny":"leaf-deny":"default-allow"}});return{deniedTools:r,canSpawnChildren:!o,defaultDecision:"allowed",defaultInheritance:"inherit",tools:a}}function er(e){let t=Ue(e.type),n=Ro({depth:e.depth,maxDepth:e.maxDepth,role:e.role,toolNames:e.toolNames});if(t.toolAccessMode==="full")return n;if(t.toolAccessMode==="none"){let i=Array.isArray(e.toolNames)?e.toolNames:e.toolNames?Array.from(e.toolNames):[],s=[...new Set(i.map(a=>a.trim()).filter(Boolean))];return{deniedTools:s,canSpawnChildren:!1,defaultDecision:"allowed",defaultInheritance:"inherit",tools:s.map(a=>({toolName:a,decision:"denied",inheritance:"shrink",reason:"always-deny"}))}}let o=new Set($e),r=[...new Set([...n.deniedTools,...$e])];return{...n,deniedTools:r,tools:n.tools.map(i=>i.decision==="denied"?i:o.has(i.toolName)?{...i,decision:"denied",inheritance:"shrink",reason:"always-deny"}:i)}}function tr(e,t){let n=new Set(t.deniedTools),o=new Map(t.tools.map(s=>[s.toolName,s])),r=[],i=[];for(let s of e){let a=s.function.name,l=o.get(a);l?.decision==="denied"?i.push({toolCall:s,reason:`tool "${a}" denied by sidechain policy: ${l.reason}`}):n.has(a)?i.push({toolCall:s,reason:`tool "${a}" is in sidechain deny list`}):r.push(s)}return{allowed:r,denied:i}}function nr(){return ko.map(e=>je[e])}function Ue(e){return je[e]}function or(e={}){if(e.preferCodeRepair)return"code-repair";let t=typeof e.trigger=="string"?e.trigger.trim().toLowerCase():"";if(t.includes("code")||t.includes("patch")||t.includes("workspace"))return"code-repair";let n=Array.from(e.toolNames??[]).map(r=>r.trim().toLowerCase()).filter(Boolean),o=["code","edit","patch","diff","file","workspace","git","terminal"];return n.some(r=>o.some(i=>r.includes(i)))?"code-repair":"plan-repair"}function rr(e,t={}){let n=Ue(e);return Ao({forceManualReview:t.forceManualReview,preferFullContext:t.preferFullContext??n.preferFullContext,preserveConversationHistory:t.preserveConversationHistory??n.preserveConversationHistory})}function Ao(e={}){return e.forceManualReview?"manual":e.preferFullContext?e.preserveConversationHistory?"append-messages":"replace-context":"summary-only"}export{U as CacheAwareCompressionStrategy,z as CompressionMetricsCollector,H as ContextEngineRegistry,de as DEFAULT_ADAPTIVE_BUDGET_CONFIG,I as DEFAULT_CURATOR_SCHEDULE_POLICY,P as DEFAULT_SKILL_SIMILARITY_POLICY,Be as FORK_PLACEHOLDER_RESULT,Z as FORK_SENTINEL_TAG,Q as FallbackTriggeredError,$ as HeadTailProtectedStrategy,Sn as INITIAL_CURATOR_STATE,j as IncrementalCompactStrategy,Hn as MAX_FORK_DEPTH,qn as MAX_SIDECHAIN_DB_DEPTH,mn as MEMORY_OBSERVATION_HOOK_VALUES,fn as MEMORY_OBSERVATION_SOURCE_VALUES,gn as MEMORY_WRITE_ACCESS_VALUES,q as MicroCompactStrategy,ne as SIDECHAIN_TOOL_DENY_ALWAYS,xo as SIDECHAIN_TOOL_DENY_LEAF,$e as SIDECHAIN_TOOL_DENY_WRITE,ko as SIDECHAIN_TYPE_VALUES,D as SlidingWindowStrategy,F as SummarizeOldStrategy,L as TEAM_MAX_AGENTS,Ln as TEAM_MAX_DEPTH,B as ToolResultTrimStrategy,cn as advanceToolLoopState,Bn as aggregateTeamResults,te as aggregateTeamToolResults,Ne as allocateTokenBudgets,It as applyContextCollapsesIfNeeded,Xt as applyToolChoicePolicy,Me as bigramSimilarity,Un as buildAgentTaskPrompt,ze as buildAssistantToolCallMessage,vn as buildConsolidationPrompt,Mn as buildCuratorRunSummary,Kn as buildForkPlaceholderResults,Wn as buildForkedMessages,ho as buildPostCompactRestorationMessage,Yt as buildSkillCandidateEffectivenessSummary,Se as buildSkillCandidateEvidencePayload,Ht as buildSkillCandidateImprovementEvidenceBundle,qt as buildSkillCandidateLatestReview,Dt as buildSkillInstruction,G as buildStructuredSummaryPrompt,He as buildToolResultMessage,po as calculateTokenWarningState,Gn as canForkAtDepth,Tt as classifyError,xt as composeAsyncStrategies,kt as composeStrategies,Rt as computeAdaptiveBudget,xn as computeLifecycleTransitions,Tn as computeRetryBackoff,Ie as computeSimilarity,Et as createCollapseStore,zt as createDefaultSkillImprovementPolicy,Co as createReactiveCompactState,co as createTaskState,uo as createTurnLoopGuardState,In as decideSimilarityAction,An as detectPrefixClusters,tr as filterToolCallsByAccessPolicy,lo as filterToolsByRole,En as findSimilarSkills,Xn as generateForkChildAgentId,ro as getBuiltInAgent,oo as getBuiltInAgents,bt as getRetryStrategy,Fe as inferAggregationPolicy,De as inferExecutionMode,Y as isAsyncCompressionStrategy,io as isBuiltInAgent,hn as isForegroundSource,Yn as isInForkChild,bn as isPersistentRetryEnabled,Cn as isTransientCapacityError,nr as listSidechainTypePolicies,Le as mapRoleToSidechainType,So as mapTeamRequestToForkConfigs,be as normalizeSkillImprovementPolicy,_n as parseConsolidationOutput,wt as postCompactFileRecovery,wn as reconcileConsolidationPlan,Pt as recoverContextCollapseFromOverflow,dn as recoverToolLoopStateFromChatConversation,pn as recoverToolLoopStateFromResponsesItems,on as repairOpenAiChatConversation,Oe as resolveAgentToolAccess,so as resolveAgentToolSet,mo as resolveApiErrorRecovery,Fn as resolveExecutionOrder,Vn as resolveForkChildTools,fo as resolveOutputTokenEscalation,or as resolveRepairSidechainType,Ao as resolveSidechainMergePolicy,rr as resolveSidechainMergePolicyByType,er as resolveSidechainToolAccessByType,Ro as resolveSidechainToolAccessPolicy,Ue as resolveSidechainTypePolicy,bo as resolveTeamExecutionPlan,On as resolveTeamPlan,At as selectCompressionTier,Rn as selectReviewCandidates,un as settleToolLoopState,go as shouldAbortTurn,To as shouldAttemptReactiveCompact,jn as shouldCancelTeam,kn as shouldRunCurator,Mt as snipCompactIfNeeded,Ee as stepCountProximity,we as toolSetJaccard,$n as validateTeamPlan};
|
|
@@ -0,0 +1,43 @@
|
|
|
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 type { AgentLogger, ToolInvoker, TurnEvent, TurnRequest, HookRegistry } from "./types.js";
|
|
16
|
+
import type { LLMTransport } from "../llm/transport.js";
|
|
17
|
+
export interface AgentConfig {
|
|
18
|
+
llmTransport: LLMTransport;
|
|
19
|
+
apiKey: string;
|
|
20
|
+
toolInvoker: ToolInvoker;
|
|
21
|
+
log: AgentLogger;
|
|
22
|
+
hooks?: HookRegistry;
|
|
23
|
+
maxRounds?: number;
|
|
24
|
+
verbose?: boolean;
|
|
25
|
+
}
|
|
26
|
+
export declare class Agent {
|
|
27
|
+
private transport;
|
|
28
|
+
private apiKey;
|
|
29
|
+
private toolInvoker;
|
|
30
|
+
private log;
|
|
31
|
+
private hooks?;
|
|
32
|
+
private maxRounds;
|
|
33
|
+
constructor(config: AgentConfig);
|
|
34
|
+
/**
|
|
35
|
+
* Execute an agent turn. Yields TurnEvent stream.
|
|
36
|
+
*
|
|
37
|
+
* 1. Emit start
|
|
38
|
+
* 2. Repair conversation history
|
|
39
|
+
* 3. Delegate to executeToolLoop() (full Hub-ported tool loop state machine)
|
|
40
|
+
* 4. Catch unhandled errors
|
|
41
|
+
*/
|
|
42
|
+
run(request: TurnRequest, signal?: AbortSignal): AsyncGenerator<TurnEvent>;
|
|
43
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized agent configuration constants.
|
|
3
|
+
*
|
|
4
|
+
* All default parameters for agent loop, tool loop, and
|
|
5
|
+
* CC-aligned recovery live here. Consumers import from this module
|
|
6
|
+
* instead of hardcoding magic numbers.
|
|
7
|
+
*
|
|
8
|
+
* CC reference: Various — CC scatters these across query.ts,
|
|
9
|
+
* withRetry.ts, tokenBudget.ts. We centralize for maintainability.
|
|
10
|
+
*/
|
|
11
|
+
/** Absolute max rounds any agent can run (hard cap). */
|
|
12
|
+
export declare const MAX_ROUNDS_LIMIT = 100;
|
|
13
|
+
/** Default rounds for a top-level agent turn. */
|
|
14
|
+
export declare const DEFAULT_MAX_ROUNDS = 25;
|
|
15
|
+
/** Hard cap on tool calls per round (prevents runaway). */
|
|
16
|
+
export declare const MAX_TOOL_BUDGET_CAP = 100;
|
|
17
|
+
/** Default tool budget per round. Overridable via TOOL_LOOP_DEFAULT_BUDGET env. */
|
|
18
|
+
export declare const DEFAULT_TOOL_BUDGET: number;
|
|
19
|
+
/** Max consecutive tool call failures before early exit. */
|
|
20
|
+
export declare const MAX_CONSECUTIVE_FAILURES = 3;
|
|
21
|
+
/** Max sidechain recursion depth (0 = top-level, 2 = max nesting). */
|
|
22
|
+
export declare const MAX_SIDECHAIN_DEPTH = 2;
|
|
23
|
+
/** Default context window size (tokens). Used when model-specific size unknown. */
|
|
24
|
+
export declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 128000;
|
|
25
|
+
/** Reserved tokens for model response output in turn-loop-guard budget check. */
|
|
26
|
+
export declare const RESPONSE_BUFFER_TOKENS = 13000;
|
|
27
|
+
/** Default max output tokens per LLM API call. */
|
|
28
|
+
export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
29
|
+
/** Model's absolute max output tokens (escalation ceiling). */
|
|
30
|
+
export declare const DEFAULT_MODEL_MAX_OUTPUT_TOKENS = 65536;
|
|
31
|
+
/** Max max_output_tokens recovery attempts before surfacing the error (CC: 3). */
|
|
32
|
+
export declare const MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3;
|
|
33
|
+
/** Escalated max output tokens — retry at this ceiling before multi-turn recovery (CC: 64k). */
|
|
34
|
+
export declare const ESCALATED_MAX_OUTPUT_TOKENS = 65536;
|
|
35
|
+
/** Heartbeat interval during persistent retry waits (CC: 30 seconds). */
|
|
36
|
+
export declare const HEARTBEAT_INTERVAL_MS = 30000;
|
|
37
|
+
/** Max consecutive 529 errors before fallback model switch (CC: 3). */
|
|
38
|
+
export declare const MAX_529_RETRIES = 3;
|
|
39
|
+
/** Per-tool result size threshold (chars). Results exceeding this are persisted to disk
|
|
40
|
+
* and replaced with a preview reference (CC: DEFAULT_MAX_RESULT_SIZE_CHARS = 50_000). */
|
|
41
|
+
export declare const DEFAULT_MAX_RESULT_SIZE_CHARS = 50000;
|
|
42
|
+
/** Per-message aggregate budget (chars). When a group of tool results in one response
|
|
43
|
+
* batch exceeds this, the largest fresh results are persisted until under budget
|
|
44
|
+
* (CC: MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200_000). */
|
|
45
|
+
export declare const MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200000;
|
|
46
|
+
/** Preview size for persisted tool result reference messages (CC: PREVIEW_SIZE_BYTES = 2000). */
|
|
47
|
+
export declare const TOOL_RESULT_PREVIEW_BYTES = 2000;
|