qlogicagent 0.5.0 → 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 +4 -2
package/dist/cli.js
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
#!/usr/bin/env node
|
|
3
|
+
var Ha=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Oo=(t,e)=>{for(var n in e)Ha(t,n,{get:e[n],enumerable:!0})};function Jt(t){return{role:"assistant",content:"",tool_calls:t}}function je(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 Lo=E(()=>{"use strict"});function xe(t,e){if(!t)return!1;let n=t.toLowerCase();return e.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function sl(t){return xe(t,Te.format)}function $o(t){return xe(t,Te.rateLimit)}function il(t){return xe(t,Te.timeout)}function al(t){return qa.test(t)}function Yt(t){let e=t.toLowerCase();return e?t.length>Ka?Ga.test(e):xe(e,Te.billing)?!0:za.test(t)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function Do(t){return xe(t,Te.authPermanent)}function ll(t){return xe(t,Te.auth)}function No(t){return xe(t,Te.overloaded)}function ke(t,e){return e.some(n=>t.includes(n))}function cl(t){return ke(t,Ya)||ke(t,Xa)&&t.includes("limit")||t.includes("billing hard limit")||t.includes("hard limit reached")||t.includes("maximum allowed")&&t.includes("limit")}function ul(t){let e=ke(t,Za),n=t.includes("spend limit")||t.includes("spending limit"),o=ke(t,tl);return ke(t,Qa)&&ke(t,el)||e&&(t.includes("usage limit")||n)||e&&t.includes("limit")&&t.includes("reset")||o&&t.includes("limit")&&(n||ke(t,nl))}function dl(t){return t.trim().toLowerCase().replace(rl,"").trim()}function jo(t){let e=dl(t);return!e||cl(e)?"billing":$o(e)||ul(e)?"rate_limit":"billing"}function pl(t){return ol.test(t)?jo(t):null}function Fo(t){let e=t.match(Va);if(!e)return null;let n=Number(e[1]);return Number.isFinite(n)?{code:n,rest:(e[2]??"").trim()}:null}function ml(t){if(!t)return!1;let e=t.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function gl(t){let e=t.trim();if(!e)return!1;let n=Fo(e);return n?Ja.has(n.code):!1}function Uo(t,e){return typeof t!="number"||!Number.isFinite(t)?null:t===402?e?jo(e):"billing":t===429?"rate_limit":t===401||t===403?e&&Do(e)?"auth_permanent":"auth":t===408?"timeout":t===503?e&&No(e)?"overloaded":"timeout":t===502||t===504?"timeout":t===529?"overloaded":t===400?e&&Yt(e)?"billing":"format":null}function fl(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 hl(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 Bo(t){if(hl(t))return"session_expired";if(fl(t))return"model_not_found";let e=pl(t);return e||(al(t)?Yt(t)?"billing":"rate_limit":$o(t)?"rate_limit":No(t)?"overloaded":gl(t)?Fo(t.trim())?.code===529?"overloaded":"timeout":ml(t)?"timeout":sl(t)?"format":Yt(t)?"billing":il(t)?"timeout":Do(t)?"auth_permanent":ll(t)?"auth":null)}var qa,Te,za,Ga,Ka,Va,Ja,Ya,Xa,Za,Qa,el,tl,nl,ol,rl,Wo=E(()=>{"use strict";qa=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Te={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]},za=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ga=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ka=512,Va=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,Ja=new Set([500,502,503,504,521,522,523,524,529]),Ya=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Xa=["upgrade your plan","upgrade plan","current plan","subscription"],Za=["daily","weekly","monthly"],Qa=["try again","retry","temporary","cooldown"],el=["usage limit","rate limit","organization usage"],tl=["organization","workspace"],nl=["billing period","exceeded","reached","exhausted"],ol=/["']?(?: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,rl=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function Fe(t,e){let n=Uo(t,e)??(e?Bo(e):null);return n?yl[n]:typeof t=="number"&&t>=400&&t<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Xt(t){return bl[t]}var yl,bl,Ho=E(()=>{"use strict";Wo();yl={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"},bl={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 qe(t){return typeof t.compressAsync=="function"}function kl(t,e){if(t.length<=e)return t;let n=t.slice(0,e);if(t.trimStart().startsWith("{")||t.trimStart().startsWith("[")){let s=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
4
|
+
`),n.lastIndexOf(`]
|
|
5
|
+
`));if(s>e*.5)return n.slice(0,s+1)+`
|
|
6
|
+
[...truncated: ${t.length-s-1} chars omitted]`}let r=n.lastIndexOf(`
|
|
7
|
+
`);return r>e*.7?n.slice(0,r)+`
|
|
8
|
+
[...truncated: ${t.length-r} chars omitted]`:n+`
|
|
9
|
+
[...truncated: ${t.length-e} chars omitted]`}function Zt(...t){return{compress(e,n){let o=e,r=0,s=[];for(let i of t){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function Qt(...t){return{compress(e,n){let o=e,r=0,s=[];for(let i of t){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(e,n){let o=e,r=0,s=[],i=0,a=!1,l=!1;for(let u of t){let c=qe(u)?await u.compressAsync(o,n):u.compress(o,n);o=c.messages,r+=c.droppedCount,c.droppedCount>0&&s.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,a=a||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:l}:void 0}}}}function zo(t,e){let n=t.filter(i=>i.role==="user"),o=t.filter(i=>i.tool_calls!=null),r=t.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","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 e?.taskContext&&s.push("","## Additional Context",e.taskContext),s.push("","## Conversation to Summarize","",...t.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),s.join(`
|
|
10
|
+
`)}function ct(t={}){let e={...Go,...t},n=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(n,e.maxBudget))}function ze(t,e){let n=t/e;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}function Tl(t){let e=[],n=[];for(let o of t)o.role==="system"?e.push(o):n.push(o);return{system:e,nonSystem:n}}function en(t){let e=typeof t.content=="string"?t.content:t.content!=null?JSON.stringify(t.content):"";return Math.ceil(e.length/4)}function lt(t){let e=Math.min(t.length,5),n=[];for(let o=0;o<e;o++){let r=t[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}function vl(t){let e=new Map;for(let n=0;n<t.length;n++){let o=t[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&e.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...e.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function tn(t,e,n){let o=n.estimateTokens??(m=>Math.ceil(m.length/4)),r=vl(e);if(r.length===0)return t;let s=t.map(m=>typeof m.content=="string"?m.content:"").join(`
|
|
11
|
+
`),i=r.filter(m=>!s.includes(m));if(i.length===0)return t;let a=n.maxTokenBudget,l=[],u=0;for(let m of i){if(u>=n.maxFiles||a<=0)break;let g=await n.readFile(m);if(!g)continue;let y=o(g);y>a||(a-=y,u++,l.push({role:"system",content:`[Post-compact file recovery: ${m}]
|
|
12
|
+
|
|
13
|
+
${g}`}))}if(l.length===0)return t;let c=[...t],p=-1;for(let m=0;m<c.length;m++)c[m].role==="system"&&(p=m);return c.splice(p+1,0,...l),c}function nn(t,e,n=en){if(e.size===0)return{messages:t,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of t){let l=a.tool_call_id??"";if(l&&e.has(l)){o+=n(a),r++,e.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}var qo,Pe,ve,Ue,Be,Go,We,He,xl,fe,on=E(()=>{"use strict";qo=4,Pe=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,n){let o=[],r=[];for(let c of e)c.role==="system"?o.push(c):r.push(c);let s=n;for(let c of o)s-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(p===i)continue;let m=this.estimateTokens(p);if(s-m<0&&l>=qo)break;if(s-m<0&&l<qo){a.unshift(p),l++;continue}s-=m,a.unshift(p),l++}let u=[...o];return i&&!a.includes(i)&&u.push(i),u.push(...a),{messages:u,droppedCount:r.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},ve=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,n){let o=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:kl(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};Ue=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??en,taskContext:e.taskContext}}compress(e,n){return{messages:e,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(e,n){let o=Date.now(),{system:r,nonSystem:s}=Tl(e),i=e.reduce((R,_)=>R+this.config.estimateTokens(_),0);if(i<=n)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let R=0;R<s.length&&(s[R].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));R++)a=R+1;let u=Math.max(a,s.length-this.config.protectedTailMessages);if(u<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let c=s.slice(0,a),p=s.slice(a,u),m=s.slice(u),g=zo(p,{taskContext:this.config.taskContext}),y=await this.config.summarize(p,g),f={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
14
|
+
|
|
15
|
+
${y}`},x=[...r,...c,f,...m],b=Date.now()-o,S=x.reduce((R,_)=>R+this.config.estimateTokens(_),0);return{messages:x,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:S,compressionRatio:i>0?S/i:1,latencyMs:b,usedLlm:!0,cacheInvalidated:!0}}}},Be=class{config;constructor(e){this.config=e}compress(e,n){let o=lt(e),r=this.config.inner.compress(e,n),s=lt(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(e,n){let o=lt(e),r=qe(this.config.inner)?await this.config.inner.compressAsync(e,n):this.config.inner.compress(e,n),s=lt(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Go={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};We=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 n=0,o=0,r=0,s=0,i=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:e,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/e,averageLatencyMs:o/e,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},He=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}))}};xl=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"]),fe=class{constructor(e=20,n=en){this.preserveRecentCount=e;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(e,n){if(e.length<=this.preserveRecentCount)return{messages:e,droppedCount:0,strategy:"micro-compact"};let o=e.length-this.preserveRecentCount,r=0,s=0;return{messages:e.map((a,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!xl.has(a.name)||a.content.length<=200)return a;let u=this.estimateTokens(a);return s+=u,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function rn(){return{stages:[]}}function sn(t,e,n){let o=n?.thresholdMessages??40;if(t.filter(a=>a.role!=="system").length<=o)return{messages:t,stagedCount:0};let s=Ko(t,e),i=Sl(s,e,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Ko(t,e),{messages:s,stagedCount:i.length}}function an(t,e){let n=0;for(let o of e.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:t,committed:0}:{messages:Vo(t,e),committed:n}}function Ko(t,e){return e.stages.filter(o=>o.committed).length===0?t:Vo(t,e)}function Vo(t,e){let n=e.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...t];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function Sl(t,e,n){let o=Math.max(0,t.length-Math.floor(n/2)),r=[],s=new Set(e.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let u=t[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}var Jo=E(()=>{"use strict"});function wl(t){return!(!t.ok||t.existingSkillName||!t.multiStep||t.toolCallCount<3||t.distinctToolCount<2)}function Cl(t){return t.existingSkillName?t.feedback==="negative":!1}function ut(t,e){return Cl(t)?{type:"skill.improve",skillName:t.existingSkillName,reason:"negative user feedback on existing skill execution"}:wl(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}var Yo=E(()=>{"use strict"});var Xo=E(()=>{"use strict"});var Zo=E(()=>{"use strict";Xo()});function Qo(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 Rl(t){return t==="enabled-eligible"||t==="installed-awaiting-approval"}function _l(t){return new Map((t??[]).map(e=>[e.toolName,e]))}function Al(t){if(!t.eligibility?.length)return[...t.tools];let e=_l(t.eligibility);return t.tools.filter(n=>{let o=Qo(n);if(!o)return!1;let r=e.get(o);return!r||Rl(r.status)})}function Pl(t){let e=[],n=t.compatibility??{},o=t.toolChoice;if(t.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(e.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";e.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";e.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:e}}function ln(t){let e=Pl({toolChoice:t.toolChoice,thinkingEnabled:t.thinkingEnabled,compatibility:t.compatibility}),n=e.normalizedToolChoice,o=[...e.warnings],r=Al({tools:t.tools,eligibility:t.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 s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>Qo(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var er=E(()=>{"use strict"});function tr(t){return t==null?[]:typeof t=="string"?t.length>0?[{type:"text",text:t}]:[]:Array.isArray(t)?t:[{type:"text",text:String(t)}]}function El(t,e){return{...t,content:[...tr(t.content),...tr(e.content)]}}function Ol(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 Ll(t){return new Set((t??Ml).map(e=>e.trim().toLowerCase()))}function $l(t,e){return t?Ll(e).has(t.trim().toLowerCase()):!1}function cn(t){if(!Array.isArray(t)||t.length===0)return[...t];let e=t.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(u=>Ol(u));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),n=new Set;for(let a of e)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=e.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 s=[];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(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=a;c.content!=null&&c.content!==""&&s.push(c);continue}if(l.length<a.tool_calls.length){s.push({...a,tool_calls:l});continue}}s.push(a)}let i=[];for(let a of s){let l=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){i[i.length-1]=El(l,a);continue}i.push(a)}return i}function un(t,e){return $l(e?.stopReason,e?.forcedStopReasons)?t.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Il)delete o[r];return o}):[...t]}function dn(t,e){let n=e?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),o=new Set;for(let s of t)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of t)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function pn(t,e){let n=cn(t),o=un(n,e);return dn(o,e)}var Ml,Il,mn=E(()=>{"use strict";Ml=["stop","aborted","timeout","cancelled","interrupted","error"],Il=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Dl(t){let e=new Set,n=new Set;for(let o of t){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&e.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...e].filter(o=>!n.has(o))}function Nl(t){let e=new Set;for(let n of t)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&e.add(n.tool_call_id);return[...e]}function jl(t){return{round:t.round??0,maxRounds:t.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??[]],completedToolCallIds:[...t.completedToolCallIds??[]],lastStopReason:t.lastStopReason,replayMessages:[...t.replayMessages??[]]}}function gn(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 dt(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 pt(t){let e=[],n=cn(t.replayMessages);n.length!==t.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=un(n,t.options);o.some((s,i)=>s!==n[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=dn(o,t.options);return r.length>o.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:jl({maxRounds:t.maxRounds,round:t.round,lastStopReason:t.lastStopReason,replayMessages:r,pendingToolCallIds:Dl(r),completedToolCallIds:Nl(r)}),recoveryActions:e}}var nr=E(()=>{"use strict";mn()});import{MEMORY_OBSERVATION_HOOK_VALUES as Fl,MEMORY_OBSERVATION_SOURCE_VALUES as Ul,MEMORY_WRITE_ACCESS_VALUES as Bl}from"qlogicagent-runtime-contracts";var or=E(()=>{"use strict"});function fn(t){return t?Wl.has(t):!0}function hn(t){return t===429||t===529}function mt(t,e=500,n=32e3){let o=Math.min(e*Math.pow(2,t-1),n);return o+Math.floor(Math.random()*o*.25)}function yn(){let t=process.env.QLOGICAGENT_PERSISTENT_RETRY;return t==="1"||t==="true"}var Wl,ef,Ge,rr=E(()=>{"use strict";Wl=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);ef={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};Ge=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});var sr=E(()=>{"use strict"});var ir=E(()=>{"use strict"});var ar=E(()=>{"use strict"});var lr=E(()=>{"use strict"});function bn(t,e){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")}var kn=E(()=>{"use strict"});function Tn(t){return Jl.find(e=>e.name===t)}var Hl,ql,zl,Gl,Kl,Vl,Jl,xn=E(()=>{"use strict";Hl={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},ql={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},zl={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},Gl={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Kl={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},Vl={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},Jl=[Hl,ql,zl,Gl,Kl,Vl]});var cr=E(()=>{"use strict"});function vn(t){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:t.maxOutputTokens,consecutiveTruncations:0,aborted:t.abortSignal?.aborted??!1}}function Sn(t,e){if(t.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=e.contextWindowTokens-e.responseBufferTokens-t.currentMaxOutputTokens,o=n>0?t.promptTokens/n*100:100;return t.promptTokens>=n?t.hasAttemptedReactiveCompact||!e.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-t.promptTokens}:{level:"ok"}}function wn(t,e,n){let o=t.message?.toLowerCase()??"",r=t.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!e.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 Cn(t,e,n){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};if(t.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};let o=Math.min(t.currentMaxOutputTokens*2,n);return o<=t.currentMaxOutputTokens?{shouldEscalate:!1,newMax:t.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Rn(t,e){return t.aborted?!0:e.abortSignal?.aborted?(t.aborted=!0,!0):!1}var ur=E(()=>{"use strict"});function _n(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Me(t,e=Yl){return!(t.attemptedThisTurn||t.consecutiveFailures>=e.maxConsecutiveFailures)}var Yl,dr=E(()=>{"use strict";Yl={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var pr=E(()=>{"use strict"});function ec(t={}){let e=Math.max(1,Math.floor(t.maxDepth??2)),n=typeof t.depth=="number"&&Number.isFinite(t.depth)?Math.max(0,Math.floor(t.depth)):e,o=t.role?t.role==="leaf":n>=e,r=o?[...An,...Ql]:[...An],s=new Set(r),i=Array.isArray(t.toolNames)?t.toolNames:t.toolNames?Array.from(t.toolNames):[],a=Array.from(new Set(i.map(l=>l.trim()).filter(Boolean))).map(l=>{let u=s.has(l);return{toolName:l,decision:u?"denied":"allowed",inheritance:u?"shrink":"inherit",reason:u?An.includes(l)?"always-deny":"leaf-deny":"default-allow"}});return{deniedTools:r,canSpawnChildren:!o,defaultDecision:"allowed",defaultInheritance:"inherit",tools:a}}function gr(t){let e=tc(t.type),n=ec({depth:t.depth,maxDepth:t.maxDepth,role:t.role,toolNames:t.toolNames});if(e.toolAccessMode==="full")return n;if(e.toolAccessMode==="none"){let s=Array.isArray(t.toolNames)?t.toolNames:t.toolNames?Array.from(t.toolNames):[],i=[...new Set(s.map(a=>a.trim()).filter(Boolean))];return{deniedTools:i,canSpawnChildren:!1,defaultDecision:"allowed",defaultInheritance:"inherit",tools:i.map(a=>({toolName:a,decision:"denied",inheritance:"shrink",reason:"always-deny"}))}}let o=new Set(mr),r=[...new Set([...n.deniedTools,...mr])];return{...n,deniedTools:r,tools:n.tools.map(s=>s.decision==="denied"?s:o.has(s.toolName)?{...s,decision:"denied",inheritance:"shrink",reason:"always-deny"}:s)}}function fr(t,e){let n=new Set(e.deniedTools),o=new Map(e.tools.map(i=>[i.toolName,i])),r=[],s=[];for(let i of t){let a=i.function.name,l=o.get(a);l?.decision==="denied"?s.push({toolCall:i,reason:`tool "${a}" denied by sidechain policy: ${l.reason}`}):n.has(a)?s.push({toolCall:i,reason:`tool "${a}" is in sidechain deny list`}):r.push(i)}return{allowed:r,denied:s}}function tc(t){return Zl[t]}var Zl,An,Ql,mr,Ke=E(()=>{"use strict";Lo();Ho();on();on();Jo();Yo();Zo();er();mn();nr();or();rr();sr();ir();ar();lr();kn();xn();cr();ur();dr();pr();Zl={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"}},An=["gateway","agents_list","whatsapp_login","session_status","cron","memory_query","sessions_send"],Ql=["sessions_list","sessions_history","sessions_spawn"],mr=["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 Pn(t,e){let n=t.get(e.index);n||(n={id:"",name:"",arguments:""},t.set(e.index,n)),e.id&&(n.id=e.id),e.name&&(n.name+=e.name),n.arguments+=e.arguments}var Mn=E(()=>{"use strict"});var hr,yr,Ie,br,kr,Tr,xr,vr,Sr,wr,Cr,Rr,_r,In,gt=E(()=>{"use strict";hr=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),yr=3,Ie=2,br=128e3,kr=13e3,Tr=16384,xr=65536,vr=3,Sr=65536,wr=3e4,Cr=3,Rr=5e4,_r=2e5,In=2e3});import{mkdir as nc,writeFile as oc}from"fs/promises";import{join as Ar}from"path";import{tmpdir as rc}from"os";function Mr(){return{seenIds:new Set,replacements:new Map}}function Ir(t){return Ar(rc(),"qlogicagent-sessions",t,sc)}async function ac(t){try{await nc(Ir(t),{recursive:!0})}catch{}}function lc(t,e){let n=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Ar(Ir(t),`${n}.txt`)}function cc(t,e){if(t.length<=e)return{preview:t,hasMore:!1};let o=t.slice(0,e).lastIndexOf(`
|
|
16
|
+
`),r=o>e*.5?o:e;return{preview:t.slice(0,r),hasMore:!0}}function Er(t){return t.includes(Pr)}async function Or(t,e,n){await ac(n);let o=lc(n,e);try{await oc(o,t,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:r,hasMore:s}=cc(t,In);return{filepath:o,originalSize:t.length,preview:r,hasMore:s}}function Lr(t){let e=`${Pr}
|
|
17
|
+
`;return e+=`Output too large (${t.originalSize} chars). Full output saved to: ${t.filepath}
|
|
18
|
+
|
|
19
|
+
`,e+=`Preview (first ${In} bytes):
|
|
20
|
+
`,e+=t.preview,e+=t.hasMore?`
|
|
21
|
+
...
|
|
22
|
+
`:`
|
|
23
|
+
`,e+=ic,e}async function $r(t,e,n,o=Rr){if(t.length<=o||Er(t))return t;let r=await Or(t,e,n);return r?Lr(r):t.slice(0,o)+`
|
|
24
|
+
...[truncated ${t.length-o} chars]`}function uc(t){let e=[],n=[];for(let o of t)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?Er(o.content)||n.push({toolCallId:o.tool_call_id,content:o.content,size:o.content.length}):o.role==="assistant"&&n.length>0&&(e.push(n),n=[]);return n.length>0&&e.push(n),e}function dc(t,e){let n=[],o=[],r=[];for(let s of t){let i=e.replacements.get(s.toolCallId);i!==void 0?n.push({...s,replacement:i}):e.seenIds.has(s.toolCallId)?o.push(s):r.push(s)}return{mustReapply:n,frozen:o,fresh:r}}function pc(t,e,n){let o=[...t].sort((i,a)=>a.size-i.size),r=[],s=e+t.reduce((i,a)=>i+a.size,0);for(let i of o){if(s<=n)break;r.push(i),s-=i.size}return r}async function Dr(t,e,n,o=_r){let r=uc(t);if(r.length===0)return{messages:t,newlyReplacedCount:0};let s=new Map,i=[];for(let c of r){let{mustReapply:p,frozen:m,fresh:g}=dc(c,e);for(let S of p)s.set(S.toolCallId,S.replacement);if(g.length===0){for(let S of c)e.seenIds.add(S.toolCallId);continue}let y=m.reduce((S,R)=>S+R.size,0),f=g.reduce((S,R)=>S+R.size,0),x=y+f>o?pc(g,y,o):[],b=new Set(x.map(S=>S.toolCallId));for(let S of c)b.has(S.toolCallId)||e.seenIds.add(S.toolCallId);x.length>0&&i.push(...x)}if(s.size===0&&i.length===0)return{messages:t,newlyReplacedCount:0};let a=await Promise.all(i.map(async c=>{let p=await Or(c.content,c.toolCallId,n);return{candidate:c,result:p}})),l=0;for(let{candidate:c,result:p}of a){if(e.seenIds.add(c.toolCallId),!p)continue;let m=Lr(p);s.set(c.toolCallId,m),e.replacements.set(c.toolCallId,m),l++}return s.size===0?{messages:t,newlyReplacedCount:0}:{messages:t.map(c=>{if(c.role!=="tool"||!c.tool_call_id)return c;let p=s.get(c.tool_call_id);return p===void 0?c:{...c,content:p}}),newlyReplacedCount:l}}var sc,Pr,ic,En=E(()=>{"use strict";gt();sc="tool-results",Pr="<persisted-output>",ic="</persisted-output>"});function fc(t){try{return JSON.parse(t)}catch{return}}var mc,gc,ft,Nr=E(()=>{"use strict";Ke();En();mc=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),gc=new Set(["bash","execute_command","Bash","shell"]),ft=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??mc,this.siblingAbortController=new AbortController,e.signal&&e.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(e){let n=this.concurrencySafe.has(e.function.name);this.tools.push({id:e.id,toolCall:e,status:"queued",isConcurrencySafe:n,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let n=this.tools.filter(r=>r.status==="executing"),o=this.config.maxConcurrentTools;return o&&o>0&&n.length>=o?!1:n.length===0||e&&n.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 n;try{n=JSON.parse(e.toolCall.function.arguments)}catch{}let o=n?.command??n?.file_path??n?.pattern??"";if(typeof o=="string"&&o.length>0){let r=o.length>40?o.slice(0,40)+"\u2026":o;return`${e.toolCall.function.name}(${r})`}return e.toolCall.function.name}createSyntheticError(e,n){let o=this.erroredToolDescription,r=n==="user_interrupted"?"User rejected tool use":n==="discarded"?"Streaming fallback - tool execution discarded":o?`Cancelled: parallel tool call ${o} errored`:"Cancelled: parallel tool call errored";return{callId:e.id,toolName:e.toolCall.function.name,ok:!1,error:r,message:je(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:l,log:u}=this.config,c=e.toolCall.function.name,p=!1,m=e.toolCall.function.arguments;if(i)try{let S=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:c,arguments:fc(m)});if(S.action==="abort"){let R=S.reason??"blocked by policy";u.info(`tool ${c} blocked: ${R}`),e.results.push({callId:e.id,toolName:c,ok:!1,error:R,blocked:!0,blockReason:R,message:je(e.id,{ok:!1,error:R})}),e.status="completed";return}S.action==="continue"&&S.context?.arguments&&(m=JSON.stringify(S.context.arguments))}catch{}let g=await s.invoke(l,c,m,this.siblingAbortController.signal),y=this.getAbortReason();if(y&&!p){e.results.push(this.createSyntheticError(e,y)),e.status="completed";return}let f=!g.error,x=g.result;f&&x&&x.length>5e4&&(x=await $r(x,e.id,a));let b=je(e.id,{ok:f,payload:x,error:g.error});f||(p=!0,gc.has(c)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(f?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:l,callId:e.id,toolName:c,ok:f,...g.error?{error:g.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:c,ok:f,error:g.error,message:b}),e.status="completed"})();e.promise=o,o.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 n of e.results)yield n}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(o=>o.status==="executing"&&o.promise).map(o=>o.promise),n=new Promise(o=>{this.progressResolve=o});e.length>0&&await Promise.race([...e,n])}}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")}}});import{readFile as hc}from"node:fs/promises";function Se(t){let e=typeof t.content=="string"?t.content:t.content!=null?JSON.stringify(t.content):"";return Math.ceil(e.length/4)}function we(t){let e=0;for(let n of t)e+=Se(n);return e}function Ur(t){if(!t)return 128e3;if(t in On)return On[t];let e=t.toLowerCase();for(let[n,o]of Object.entries(On))if(e.startsWith(n.toLowerCase()))return o;return 128e3}function bc(t,e){return async(n,o)=>{let r=e?.transport,s=e?.apiKey;if(!r||!s)return t.debug("[context-compression] no LLM transport for summarization \u2014 using sync fallback"),Ln(n);try{let i="",a=e?.model??yc;for await(let l of r.stream({model:a,messages:[{role:"system",content:"You are a precise conversation summarizer."},{role:"user",content:o}],maxTokens:2e3,temperature:.3},s,AbortSignal.timeout(3e4)))l.type==="delta"&&(i+=l.text);return i||(t.warn("[context-compression] empty summary response"),Ln(n))}catch(i){return t.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),Ln(n)}}}function Ln(t){let e=t.filter(o=>o.role==="user"),n=e.slice(0,10).map(o=>{let r=typeof o.content=="string"?o.content:JSON.stringify(o.content??"");return`- ${r.slice(0,200)}${r.length>200?"...":""}`});return`User requests (${e.length} messages):
|
|
25
|
+
${n.join(`
|
|
26
|
+
`)}`}function kc(){return Zt(new ve($n),new fe(20,Se),new Pe(Se))}function Fr(t,e){let n=Qt(new ve($n),new fe(20,Se),new Ue({protectedHeadExchanges:1,protectedTailMessages:8,summarize:t,estimateTokens:Se}),new Pe(Se));return new Be({inner:n,estimateTokens:Se,onCacheInvalidated:e?.onCacheInvalidated})}function Wr(t,e){let n=e?.budget??ct({modelContextWindow:Ur(e?.model)}),r=(e?.pipeline??kc()).compress(t,n);if(r.droppedCount>0){let s=we(t),i=we(r.messages);Br.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:s,tokensAfter:i,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:ze(s,n)})}return r.droppedCount>0&&Dn?.(r.droppedCount,we(r.messages)),r}async function Tc(t,e,n){let o=n??ct({modelContextWindow:Ur(e.model)}),r=we(t),s=ze(r,o),i;switch(s){case"none":i={messages:t,droppedCount:0,strategy:"none"};break;case"trim-only":i=new ve($n).compress(t,o);break;case"sliding-window":{i=await Fr(e.summarize).compressAsync(t,o);break}case"llm-summarize":{let a=e.pipeline??Fr(e.summarize);i=qe(a)?await a.compressAsync(t,o):a.compress(t,o);break}}return i.droppedCount>0&&(i={...i,messages:await tn(i.messages,t,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await hc(a,"utf-8")}catch{return null}}})}),xc(t,i,o),i}function xc(t,e,n){if(e.droppedCount>0||e.metrics?.usedLlm){let o=e.metrics?.tokensBefore||we(t),r=e.metrics?.tokensAfter||we(e.messages);Br.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:o,tokensAfter:r,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:ze(o,n)})}if(e.droppedCount>0){let o=e.metrics?.tokensAfter||we(e.messages);Dn?.(e.droppedCount,o)}}function vc(t,e){let n=bc(t,e),o={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return Tc(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:n},s)}};jr.register(o),jr.activate(o.id),t.info(`[context-compression] registered context engine: ${o.id}`)}function Hr(t,e,n){vc(e,n),t.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(o,r)=>{let s=r.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),Dn=(o,r)=>{e.debug(`[context-compression] after_compact: removed ${o}, ${r} tokens remaining`),t.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:o,tokenCount:r}).catch(()=>{})}}var On,$n,yc,Br,jr,Dn,Nn=E(()=>{"use strict";Ke();On={"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};$n=8e3,yc="deepseek-chat",Br=new We(200),jr=new He;Dn=null});function qr(t,e,n){let o=n-e;return`[Budget] ${Math.round(t)}% used (${e.toLocaleString()} / ${n.toLocaleString()} tokens). ${o.toLocaleString()} tokens remaining. `+(t>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var zr=E(()=>{"use strict"});var Gr={};Oo(Gr,{resolveToolEligibility:()=>_c});function wc(t,e){if(Sc.some(n=>n.test(t)))return!0;if(e)for(let n of e)try{if(new RegExp(n,"i").test(t))return!0}catch{}return!1}function Cc(t,e){let n=t.function.name,o=t.meta,r=[];return e.blockedToolNames?.includes(n)?(r.push("policy_blocked"),{level:5,reasons:r}):o?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):o?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):o?.isDangerous||wc(n,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function Rc(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 _c(t,e={}){let n=new Map,o=[],r=[],s=[];for(let i of t){let a=i.function.name,{level:l,reasons:u}=Cc(i,e),c=Rc(l),p={toolName:a,status:c,permissionLevel:l,approvalRequired:l===4,reasonCodes:u};n.set(a,p),l===5?r.push(p):(o.push(i),l===4&&s.push(p))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:s,eligibilityByName:n}}var Sc,Kr=E(()=>{"use strict";Sc=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Pc(t){return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.min(Math.round(t),100):hr}function Vr(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 Mc(t){return t==="length"||t==="max_tokens"}function Jr(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 Ic(t){let e=t.headers;if(!e)return null;let n=e["retry-after"]??e["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function Ec(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 n=parseInt(e[1],10),o=parseInt(e[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}function Oc(t){return t.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Yr(t,e,n,o){let{turnId:r,sessionId:s,messages:i,tools:a,model:l,apiKey:u,temperature:c,hooks:p,signal:m}=t,g={sessionId:s,turnId:r},y=t.maxTurns??0,f=t.querySource,{resolveToolEligibility:x}=await Promise.resolve().then(()=>(Kr(),Gr)),b=x(a,t.toolEligibilityContext),S=b.eligibleTools;for(let q of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:q.toolName,reason:"blocked-by-policy"};if(!S.length){yield*Lc(r,l,i,u,c,m,e,o);return}let R=Pc(t.maxRounds),_={contextWindowTokens:t.contextWindowTokens??br,responseBufferTokens:kr,maxOutputTokens:t.maxOutputTokens??Tr,abortSignal:m,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},O=!1,G=null,P=(t.parentDepth??0)+1,M=new Set,N=0,H=S,ee,T={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:vn(_),reactiveCompactState:_n(),toolLoopState:pt({maxRounds:R,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:rn(),currentModel:l,consecutive529Errors:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:Mr()};for(;;){let{messages:q,maxOutputTokensRecoveryCount:re,hasAttemptedReactiveCompact:J,maxOutputTokensOverride:te,turnCount:$,guardState:j,reactiveCompactState:ne,collapseStore:d}=T,{toolLoopState:h}=T;if(ee){try{let k=await ee;k&&(yield{type:"tool_use_summary",turnId:r,summary:k})}catch{}ee=void 0}if(t.refreshTools&&$>1){let k=t.refreshTools();k!==H&&(H=k,o.debug(`tools refreshed: ${k.length} tools`))}if(Rn(j,_)){o.info(`turn aborted by guard at turn ${$}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let v=Sn(j,_);if(v.level==="blocking"){v.reason==="prompt_too_long"&&Me(ne)&&(ne.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${v.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${v.reason}), ending tool loop`);break}v.level==="warning"&&o.info(`token budget warning: ${v.usagePercent}% used, ${v.remainingTokens} remaining`);let w;{let k=await Dr(q,T.contentReplacementState,s);w=k.messages,k.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${k.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${k.newlyReplacedCount} persisted`})}{let k=nn(w,T.snipRemovedIds);w=k.messages,k.removedCount>0&&(o.info(`snip: removed ${k.removedCount} messages, freed ~${k.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${k.removedCount} messages`})}{let C=new fe().compress(w,0);C.droppedCount>0&&(w=C.messages,o.info(`microcompact: cleared ${C.droppedCount} old tool results`))}if(w=sn(w,d).messages,j.promptTokens>0){let k=Wr(w,{budget:_.contextWindowTokens*.75,model:T.currentModel});k.droppedCount>0&&(w=k.messages,o.info(`autocompact: ${k.strategy}, dropped ${k.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${k.strategy}: ${k.droppedCount} dropped`},T.hasAttemptedReactiveCompact=!1,p?.invoke("context.after_compact",{...g,removedCount:k.droppedCount}).catch(()=>{}))}w=Oc(w);let A=ln({tools:H,toolChoice:t.toolChoice??"auto"}),U=pt({maxRounds:R,replayMessages:w,lastStopReason:h.lastStopReason,options:{stopReason:h.lastStopReason}}),K=A.extraSystemPrompt?[{role:"system",content:A.extraSystemPrompt},...U.state.replayMessages]:U.state.replayMessages;h=U.state,U.recoveryActions.length>0&&o.debug(`tool loop recovery: ${U.recoveryActions.map(k=>k.detail??k.kind).join("; ")}`),o.debug(`turn ${$}, messages: ${K.length}`),p?.invoke("turn.before_inference",{...g,model:T.currentModel}).catch(()=>{});let V=!1,Q=[],ce=new Map,D="stop",Z,B=null,at=!1;try{for await(let k of e.stream({model:T.currentModel,messages:K,tools:A.tools,toolChoice:A.normalizedToolChoice??"auto",temperature:c,maxTokens:(te??j.currentMaxOutputTokens)||void 0},u,m))switch(k.type){case"delta":Q.push(k.text),V||(yield{type:"delta",turnId:r,text:k.text});break;case"tool_call_delta":V=!0,Pn(ce,k);break;case"reasoning_delta":break;case"usage":Z={prompt:k.promptTokens,completion:k.completionTokens,reasoning:k.reasoningTokens};break;case"done":D=k.finishReason;break}if(V||p?.invoke("turn.after_inference",{...g,model:T.currentModel}).catch(()=>{}),t.postSamplingHooks&&t.postSamplingHooks.length>0){let k=T.currentModel;for(let C of t.postSamplingHooks)try{C({messages:[...w],model:k,sessionId:s})}catch{}}}catch(k){if(k instanceof Ge&&t.fallbackModel){o.info(`model fallback triggered: ${k.originalModel} \u2192 ${k.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${k.originalModel} \u2192 ${k.fallbackModel}`},T={...T,currentModel:k.fallbackModel,consecutive529Errors:0,transition:void 0};continue}let C=k instanceof Error?k.message:String(k),Y=typeof k?.status=="number"?k.status:void 0;if(!Y&&C&&(C.includes("ECONNRESET")||C.includes("EPIPE"))){o.info(`stale connection (${C.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:C.slice(0,80)},T={...T,transition:void 0};continue}let pe=Ec({status:Y,message:C});if(pe!==null){o.info(`max_tokens overflow: adjusting to ${pe}`),j.currentMaxOutputTokens=pe,T={...T,maxOutputTokensOverride:pe,transition:void 0};continue}if(hn(Y)){if(T.consecutive529Errors++,T.consecutive529Errors>=Cr&&t.fallbackModel&&T.currentModel!==t.fallbackModel){o.info(`529 \xD7 ${T.consecutive529Errors}: triggering fallback to ${t.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${T.consecutive529Errors}`},T={...T,currentModel:t.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(yn()){let be=mt(T.consecutive529Errors);o.info(`persistent retry: waiting ${be}ms (attempt ${T.consecutive529Errors})`);let me=be;for(;me>0;){if(m?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(me/1e3)}s (${Y})`};let Ae=Math.min(me,wr);await new Promise(Wa=>setTimeout(Wa,Ae)),me-=Ae}T={...T,transition:void 0};continue}if(fn(f)){let me=Ic({status:Y,message:C})??mt(T.consecutive529Errors);o.info(`transient ${Y}: retry in ${me}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${Y} retry in ${me}ms`},await new Promise(Ae=>setTimeout(Ae,me)),T={...T,transition:void 0};continue}o.info(`background source ${f}: not retrying ${Y}`)}B={status:Y,message:C}}if(B&&p?.invoke("turn.after_inference",{...g,model:T.currentModel,response:{error:B.message}}).catch(()=>{}),B)if(Vr(B))at=!0,o.info(`withheld prompt_too_long error (status=${B.status})`);else if(Jr(B))at=!0,o.info(`withheld media_size error (status=${B.status})`);else{let k=wn({status:B.status??500,message:B.message},j,_);if(k.action==="reactive_compact"&&Me(ne)&&(ne.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${B.status??500}: ${B.message}`}),k.action==="retry"){yield{type:"recovery",turnId:r,action:"retry",detail:k.reason},T={...T,transition:void 0};continue}let C=Fe(B.status,B.message);p?.invoke("stop.failure",{sessionId:s,reason:C,error:B.message}).catch(()=>{}),yield{type:"error",turnId:r,error:B.message,code:C};return}Z&&(T.totalUsage.prompt+=Z.prompt,T.totalUsage.completion+=Z.completion,Z.reasoning&&(T.totalUsage.reasoning=(T.totalUsage.reasoning??0)+Z.reasoning)),Z?.prompt&&(j.promptTokens=Z.prompt),T.finalText=Q.join("");let le=[...ce.values()].map(k=>({id:k.id||`tc_${r}_${$}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:k.name,arguments:k.arguments}}));if(G&&le.length>0){let k=fr(le,G);k.denied.length>0&&o.info(`sidechain policy denied: ${k.denied.map(C=>`${C.toolCall.function.name} (${C.reason})`).join(", ")}`),le=k.allowed}if(le.length===0&&!V){if(at&&B&&Vr(B)){if(T.transition?.reason!=="collapse_drain_retry"){let k=an(w,d);if(k.committed>0){o.info(`collapse drain: committed ${k.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${k.committed} stages committed`},T={...T,messages:k.messages,transition:{reason:"collapse_drain_retry",committed:k.committed}};continue}}if(Me(ne)){ne.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},T={...T,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),p?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:B.message}).catch(()=>{}),yield{type:"error",turnId:r,error:B.message,code:"PROMPT_TOO_LONG"};return}if(at&&B&&Jr(B)){if(Me(ne)){ne.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},T={...T,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),p?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:B.message}).catch(()=>{}),yield{type:"error",turnId:r,error:B.message,code:"IMAGE_ERROR"};return}if(Mc(D)){j.consecutiveTruncations+=1;let k=t.modelMaxOutputTokens??xr,C=Cn(j,_,k);if(C.shouldEscalate&&te===void 0){j.currentMaxOutputTokens=C.newMax,o.info(`max_output_tokens escalate: ${C.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${C.newMax} tokens`},T={...T,maxOutputTokensOverride:Sr,transition:{reason:"max_output_tokens_escalate"}};continue}if(re<vr){let Y={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."};o.info(`max_output_tokens recovery #${re+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${re+1}`},T={...T,messages:[...w,Y],maxOutputTokensRecoveryCount:re+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:re+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else j.consecutiveTruncations=0;if(h=dt(h,{replayMessages:q,lastStopReason:"completed"}),p){let k=await p.invoke("stop",{sessionId:s,reason:"completed"});if(k.action==="prevent"){o.info(`stop hook prevented continuation: ${k.reason??"no reason"}`),yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}if(k.action==="abort"){let C=k.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${C}`);let Y={role:"user",content:C};T={...T,messages:[...q,{role:"assistant",content:T.finalText},Y],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(t.tokenBudget&&t.tokenBudget>0){let k=T.totalUsage.prompt+T.totalUsage.completion+(T.totalUsage.reasoning??0),C=k/t.tokenBudget*100;if(C<90){let Y={role:"user",content:qr(C,k,t.tokenBudget)};o.info(`token budget continuation: ${Math.round(C)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(C)}% used`},T={...T,messages:[...q,{role:"assistant",content:T.finalText},Y],transition:{reason:"token_budget_continuation"}};continue}}if(O&&(yield{type:"sidechain_completed",turnId:r,depth:P,toolCallCount:N}),N>0){let k={ok:!0,toolCallCount:N,distinctToolCount:M.size,multiStep:N>=2,hasSidechain:O,feedback:null,existingSkillName:null},C=ut(k,{tools:[...M]});C&&(yield{type:"skill_instruction",turnId:r,instruction:C})}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}for(let k of le){let C=k.function.arguments,Y=H.find(pe=>pe.function.name===k.function.name);if(Y?.backfillObservableInput)try{let pe=JSON.parse(k.function.arguments),be={...pe};Y.backfillObservableInput(be),Object.keys(be).some(Ae=>!(Ae in pe))&&(C=JSON.stringify(be))}catch{}yield{type:"tool_call",turnId:r,callId:k.id,name:k.function.name,arguments:C}}if(q.push(Jt(le)),!O){if(P>Ie){yield{type:"error",turnId:r,error:`sidechain depth ${P} exceeds max ${Ie}`,code:"SIDECHAIN_DEPTH_LIMIT"};return}O=!0;let k=P>=Ie?"leaf":"orchestrator";yield{type:"sidechain_started",turnId:r,depth:P,role:k},G=gr({type:t.sidechainType??"code-repair",depth:P,maxDepth:Ie,role:P>=Ie?"leaf":"orchestrator",toolNames:a.map(C=>C.function.name)})}h=gn(h,{replayMessages:q,pendingToolCallIds:le.map(k=>k.id),completedToolCallIds:h.completedToolCallIds,lastStopReason:"tool_calls"});let Io=[];try{let k=new ft({toolInvoker:n,hooks:p,sessionId:s,turnId:r,log:o,signal:m,maxConcurrentTools:t?.maxConcurrentTools});for(let C of le)k.addTool(C);for await(let C of k.getRemainingResults())C.blocked&&(yield{type:"tool_blocked",turnId:r,callId:C.callId,name:C.toolName,reason:C.blockReason??"blocked"}),q.push(C.message),Io.push(C.callId),M.add(C.toolName),N++,yield{type:"tool_result",turnId:r,callId:C.callId,name:C.toolName,ok:C.ok,error:C.error}}catch(k){let C=k instanceof Error?k.message:String(k);yield{type:"error",turnId:r,error:C,code:"TOOL_EXECUTION_ERROR"};return}if(h=dt(h,{replayMessages:q,completedToolCallIds:[...h.completedToolCallIds,...Io],lastStopReason:"tool_calls"}),t.generateToolUseSummary&&le.length>0){let k=le.map(C=>({name:C.function.name,arguments:C.function.arguments}));ee=t.generateToolUseSummary(k).catch(()=>null)}let Eo=q.slice(-le.length),Ba=Eo.length>0&&Eo.every(k=>{let C=k?.content;if(typeof C!="string")return!1;try{return JSON.parse(C)?.ok===!1}catch{return!1}}),Ne=T.consecutiveFailedRounds;if(Ba){if(Ne+=1,Ne>=yr&&T.finalText){o.info(`early exit: ${Ne} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}}else Ne=0;let Vt=$+1;if(y>0&&Vt>y){if(o.info(`max turns reached (${y}), completing`),p){let k=await p.invoke("stop",{sessionId:s,reason:"max_turns"});if(k.action==="abort"){let C=k.reason??"Stop hook requested continuation after max_turns";T={...T,messages:[...q,{role:"assistant",content:T.finalText},{role:"user",content:C}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}if(Vt>R){if(T.finalText){if(o.info(`tool loop budget exhausted (${R} rounds), returning partial response`),O&&(yield{type:"sidechain_completed",turnId:r,depth:P,toolCallCount:N}),N>0){let k={ok:!0,toolCallCount:N,distinctToolCount:M.size,multiStep:N>=2,hasSidechain:O,feedback:null,existingSkillName:null},C=ut(k,{tools:[...M]});C&&(yield{type:"skill_instruction",turnId:r,instruction:C})}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}yield{type:"error",turnId:r,error:`Tool loop exceeded budget (${R} rounds)`,code:"TOOL_LOOP_LIMIT"};return}T={messages:q,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Vt,transition:{reason:"next_turn"},guardState:j,reactiveCompactState:ne,toolLoopState:h,consecutiveFailedRounds:Ne,finalText:T.finalText,totalUsage:T.totalUsage,collapseStore:d,currentModel:T.currentModel,consecutive529Errors:0,stopHookActive:T.stopHookActive,snipRemovedIds:T.snipRemovedIds,contentReplacementState:T.contentReplacementState}}}async function*Lc(t,e,n,o,r,s,i,a){let l=[],u;a.debug(`single LLM round, messages: ${n.length}`);for await(let c of i.stream({model:e,messages:n,temperature:r},o,s))switch(c.type){case"delta":l.push(c.text),yield{type:"delta",turnId:t,text:c.text};break;case"usage":u={prompt:c.promptTokens,completion:c.completionTokens,reasoning:c.reasoningTokens};break;case"done":break}yield{type:"end",turnId:t,content:l.join(""),usage:u??{prompt:0,completion:0},model:e}}var Xr=E(()=>{"use strict";Mn();Ke();Nr();Nn();zr();En();gt()});var Qr={};Oo(Qr,{Agent:()=>Ve});var Ve,jn=E(()=>{"use strict";Ke();Xr();gt();Ve=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,n){let{turnId:o,messages:r,tools:s,systemPrompt:i,config:a}=e,l={sessionId:e.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let u=pn(r),c=[];if(i&&c.push({role:"system",content:i}),c.push(...u),this.hooks){let g=u.filter(f=>f.role==="user").pop(),y=typeof g?.content=="string"?g.content.slice(0,500):void 0;if(y)try{let f=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:o,query:y}),x=f?.context?.recalledMemories;if(x&&x.length>0){let b=x.map(S=>`- ${S.text}`).join(`
|
|
27
|
+
`);c.splice(i?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
28
|
+
${b}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o,blockCount:f?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let p=a?.model??"",m=Math.min(a?.maxRounds??this.maxRounds,100);try{let g=a?.summaryModel?async x=>{try{let b=x.map(_=>`${_.name}(${_.arguments.slice(0,200)})`).join(", "),S=this.transport.stream({model:a.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:b}],tools:[],maxTokens:60},a.apiKey??this.apiKey),R="";for await(let _ of S)_.type==="delta"&&(R+=_.text);return R.trim()||null}catch{return null}}:void 0,y={turnId:o,sessionId:e.sessionId,messages:c,tools:s,model:p,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:m,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,sidechainType:a?.sidechainType,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,generateToolUseSummary:g,signal:n},f;for await(let x of Yr(y,this.transport,this.toolInvoker,this.log))f=x,yield x;f?.type==="end"?this.hooks?.invoke("turn.completed",{...l}).catch(()=>{}):f?.type==="error"&&this.hooks?.invoke("turn.failed",{...l,code:f.code,error:f.error}).catch(()=>{})}catch(g){if(n?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let y=g instanceof Error?g.message:String(g),f=typeof g?.status=="number"?g.status:void 0,x=Fe(f,y),b=Xt(x);this.log.error(`turn ${o} error [${x}, retryable=${b.retryable}]: ${y}`),this.hooks?.invoke("turn.failed",{...l,code:x,error:y}).catch(()=>{}),yield{type:"error",turnId:o,error:y,code:x}}}}}});jn();import{createInterface as _g}from"node:readline";import{randomUUID as _e}from"node:crypto";Mn();var Fn=[{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 Dc,mkdirSync as Nc,readFileSync as jc,writeFileSync as Fc}from"node:fs";import{join as es}from"node:path";import{homedir as Uc}from"node:os";var Bc="https://models.dev/api.json",Wc=15e3,Hc=1440*60*1e3,qc=300*1e3,Je=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??es(Uc(),".openclaw","cache"),this.cacheFile=es(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??Hc}getModels(e){this.ensureLoaded();let n=this.cache?.providers.get(e);return n?[...n.models.values()]:[]}getModel(e,n){return this.ensureLoaded(),this.cache?.providers.get(e)?.models.get(n)}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(!Dc(this.cacheFile))return;let e=jc(this.cacheFile,"utf8"),n=JSON.parse(e);if(!n.fetchedAt||!n.data)return;this.cache={fetchedAt:n.fetchedAt,providers:ts(n.data)}}catch{}}saveToDisk(e){try{Nc(this.cacheDir,{recursive:!0});let n=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);Fc(this.cacheFile,n,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<qc||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(Bc,{signal:AbortSignal.timeout(Wc),headers:{Accept:"application/json"}});if(!e.ok)return!1;let n=await e.json(),o=ts(n);return o.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:o},this.saveToDisk(n),!0)}catch{return!1}}};function ts(t){let e=new Map;if(!t||typeof t!="object")return e;for(let[n,o]of Object.entries(t)){if(!o||typeof o!="object")continue;let r=o.models;if(!r||typeof r!="object")continue;let s=new Map;for(let[i,a]of Object.entries(r)){if(!a||typeof a!="object")continue;let l=a,u=l.limit??{},c=l.modalities??{},p=Array.isArray(c.input)?c.input:[];s.set(i,{id:i,name:typeof l.name=="string"?l.name:i,contextWindow:typeof u.context=="number"?u.context:2e5,maxOutput:typeof u.output=="number"?u.output:8192,toolCall:l.tool_call===!0,reasoning:l.reasoning===!0,vision:l.attachment===!0||p.includes("image"),costInput:typeof l.cost_input=="number"?l.cost_input:void 0,costOutput:typeof l.cost_output=="number"?l.cost_output:void 0})}s.size>0&&e.set(n,{models:s})}return e}var zc={claude:"anthropic",gemini:"google","x-ai":"xai","z-ai":"xai",silicon:"siliconflow","silicon-flow":"siliconflow"},Ye=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let n of Fn)this.builtins.set(n.id,n);this.catalog=e?.catalog??new Je}applyOverride(e,n){this.overrides.set(e,{...this.overrides.get(e),...n})}getProvider(e){let n=zc[e]??e,o=this.builtins.get(n),r=this.overrides.get(n);if(!(!o&&!r))return!o&&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}:o&&!r?o:{...o,...r,models:r.models??o.models}}listProviders(){let e=new Map;for(let[n,o]of this.builtins)e.set(n,o);for(let[n]of this.overrides){let o=this.getProvider(n);o&&e.set(n,o)}return[...e.values()]}listModels(e){let o=this.getProvider(e)?.models??[],r=this.catalog.getModels(e);if(r.length===0)return o;let s=new Map;for(let i of r)s.set(i.id,i);for(let i of o)s.set(i.id,i);return[...s.values()]}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,n){if(n)return n;let o=this.getProvider(e);if(o)for(let r of o.apiKeyEnvVars){let s=process.env[r];if(s?.trim())return s.trim()}}};var Xe=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,n,o){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 i=AbortSignal.timeout(this.timeoutMs),a=o?AbortSignal.any([o,i]):i,l=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...this.extraHeaders},body:JSON.stringify(s),signal:a});if(!l.ok){let u=await l.text().catch(()=>"");throw new Error(`LLM API error ${l.status}: ${u.slice(0,500)}`)}if(!l.body)throw new Error("LLM API returned no response body");yield*this.parseSSEStream(l.body)}async*parseSSEStream(e){let n=new TextDecoder,o="";for await(let r of e){o+=n.decode(r,{stream:!0});let s;for(;(s=o.indexOf(`
|
|
29
|
+
`))!==-1;){let i=o.slice(0,s).trim();if(o=o.slice(s+1),!i||i.startsWith(":")||!i.startsWith("data: "))continue;let a=i.slice(6);if(a==="[DONE]")return;let l;try{l=JSON.parse(a)}catch{continue}yield*this.mapChunk(l)}}if(o.trim()){let r=o.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 n of e.choices){let o=n.delta;if(o){if(o.reasoning_content&&(yield{type:"reasoning_delta",text:o.reasoning_content}),o.content&&(yield{type:"delta",text:o.content}),o.tool_calls)for(let r of o.tool_calls)yield{type:"tool_call_delta",index:r.index,id:r.id,name:r.function?.name,arguments:r.function?.arguments??""};n.finish_reason&&(yield{type:"done",finishReason:n.finish_reason})}}}};var Ze=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,n,o){let r=`${this.baseUrl}/v1/messages`,{system:s,messages:i}=Vc(e.messages),a={model:e.model,messages:i,max_tokens:e.maxTokens??8192,stream:!0};s&&(a.system=s),e.tools&&e.tools.length>0&&(a.tools=e.tools.map(Jc),e.toolChoice&&(a.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})),e.temperature!==void 0&&(a.temperature=e.temperature),e.reasoning&&(a.thinking={type:"enabled",budget_tokens:Kc(e.reasoning.effort)});let l=AbortSignal.timeout(this.timeoutMs),u=o?AbortSignal.any([o,l]):l,c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n,"anthropic-version":this.apiVersion},body:JSON.stringify(a),signal:u});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`Anthropic API error ${c.status}: ${p.slice(0,500)}`)}if(!c.body)throw new Error("Anthropic API returned no response body");yield*this.parseSSEStream(c.body)}async*parseSSEStream(e){let n=new TextDecoder,o="",r="",s=new Map;for await(let i of e){o+=n.decode(i,{stream:!0});let a;for(;(a=o.indexOf(`
|
|
30
|
+
`))!==-1;){let l=o.slice(0,a).trim();if(o=o.slice(a+1),!l){r="";continue}if(l.startsWith("event: ")){r=l.slice(7).trim();continue}if(!l.startsWith("data: "))continue;let u=l.slice(6),c;try{c=JSON.parse(u)}catch{continue}yield*this.mapEvent(r,c,s)}}}*mapEvent(e,n,o){switch(e){case"message_start":{let s=n.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=n.index,s=n.content_block;if(!s)break;let i=s.type;o.set(r,{type:i,id:s.id,name:s.name}),i==="tool_use"&&(yield{type:"tool_call_delta",index:r,id:s.id,name:s.name,arguments:""});break}case"content_block_delta":{let r=n.index,s=n.delta;if(!s)break;let i=s.type;i==="text_delta"?yield{type:"delta",text:s.text}:i==="input_json_delta"?yield{type:"tool_call_delta",index:r,arguments:s.partial_json}:i==="thinking_delta"&&(yield{type:"reasoning_delta",text:s.thinking});break}case"content_block_stop":{let r=n.index;o.delete(r);break}case"message_delta":{let r=n.delta,s=n.usage;s&&(yield{type:"usage",promptTokens:0,completionTokens:s.output_tokens??0}),r?.stop_reason&&(yield{type:"done",finishReason:Gc(r.stop_reason)});break}case"message_stop":break;case"error":{let r=n.error;throw new Error(`Anthropic stream error: ${r?.message??JSON.stringify(n)}`)}}}};function Gc(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 ns={xhigh:32e3,high:16e3,medium:8e3,low:4e3};function Kc(t){return ns[t]??ns.high}function Vc(t){let e,n=[];for(let o of t){if(o.role==="system"){e=e?`${e}
|
|
31
|
+
|
|
32
|
+
${o.content??""}`:o.content??"";continue}if(o.role==="user")n.push({role:"user",content:o.content??""});else if(o.role==="assistant")if(o.tool_calls&&o.tool_calls.length>0){let r=[];o.content&&r.push({type:"text",text:o.content});for(let s of o.tool_calls){let i;try{i=JSON.parse(s.function.arguments)}catch{i={}}r.push({type:"tool_use",id:s.id,name:s.function.name,input:i})}n.push({role:"assistant",content:r})}else n.push({role:"assistant",content:o.content??""});else o.role==="tool"&&n.push({role:"user",content:[{type:"tool_result",tool_use_id:o.tool_call_id??"",content:o.content??""}]})}return{system:e,messages:n}}function Jc(t){return{name:t.function.name,description:t.function.description,input_schema:t.function.parameters??{type:"object",properties:{}}}}function Un(t,e){t.baseUrl&&e.applyOverride(t.provider,{baseUrl:t.baseUrl});let n=e.getProvider(t.provider);if(!n)throw new Error(`Unknown LLM provider: "${t.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let o=t.baseUrl??n.baseUrl;return{transport:Yc(n,o),apiKey:t.apiKey,resolvedModel:t.model,providerDef:n}}function Bn(t){for(let e of t.listProviders()){let n=t.resolveApiKey(e.id);if(n)return{providerId:e.id,apiKey:n,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function Yc(t,e){switch(t.transport){case"openai-chat":return new Xe({baseUrl:e,extraHeaders:t.extraHeaders,supportsStreamOptions:t.supportsStreamOptions,omitZeroTemperature:t.omitZeroTemperature});case"anthropic-messages":return new Ze({baseUrl:e});default:throw new Error(`Unsupported transport type: "${t.transport}" for provider "${t.id}"`)}}import{homedir as Xc}from"node:os";import{join as rs}from"node:path";import{mkdirSync as Zc,appendFileSync as Qc}from"node:fs";var os=rs(Xc(),".openclaw","debug-logs");function Wn(){return process.env.QLOGICAGENT_DEBUG==="1"}function Hn(t,e){let n=rs(os,`${e}.jsonl`),o=!1;function r(){o||(Zc(os,{recursive:!0}),o=!0)}function s(i){try{r(),Qc(n,JSON.stringify(i)+`
|
|
33
|
+
`,"utf8")}catch{}}return{async*stream(i,a,l){let u=Date.now();s({type:"request",timestamp:new Date(u).toISOString(),model:i.model,messageCount:i.messages.length,toolCount:i.tools?.length??0,toolChoice:i.toolChoice,temperature:i.temperature,maxTokens:i.maxTokens,reasoning:i.reasoning});let c=0,p=0,m=0,g="",y;try{for await(let f of t.stream(i,a,l))f.type==="usage"?(c=f.promptTokens,p=f.completionTokens,m=f.reasoningTokens??0):f.type==="done"&&(g=f.finishReason),yield f}catch(f){throw y=f instanceof Error?f.message:String(f),f}finally{let f=Date.now()-u;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:f,promptTokens:c,completionTokens:p,reasoningTokens:m,finishReason:g,...y?{error:y}:{}})}}}}function ss(t){let e=new Map;return{register(n){let o=e.get(n.point)??[],r={handler:n.handler,priority:n.priority??100,label:n.label};return o.push(r),o.sort((s,i)=>s.priority-i.priority),e.set(n.point,o),()=>{let s=o.indexOf(r);s>=0&&o.splice(s,1)}},async invoke(n,o){let r=e.get(n);if(!r||r.length===0)return{action:"continue",context:o};let s=o;for(let i of r)try{let a=await i.handler(n,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return t.info({hook:n,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){t.warn({hook:n,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}var ht={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function yt(){return{surfacedPaths:new Set,sessionBytes:0}}function is(t,e,n){let o=[],r=n??yt(),s,i=[];return o.push(t.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,l)=>{if(!e.memoryProvider||!l.query)return{action:"continue",context:l};if(r.sessionBytes>=ht.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:l};try{let u=await e.memoryProvider.search(l.query,e.userId,{limit:ht.LIMIT_PER_RECALL}),c=u.filter(m=>{let g=m,y=g.path??g.id??"";if(!y)return!0;if(r.surfacedPaths.has(y))return!1;let f=(g.content?.length??0)*2;if(r.sessionBytes+f>ht.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(y),r.sessionBytes+=f,r.surfacedPaths.size>ht.MAX_SURFACED_ENTRIES){let x=r.surfacedPaths.values().next().value;x!==void 0&&r.surfacedPaths.delete(x)}return!0});s=l.turnId,i=c,e.log.debug(`memory.before_recall: prefetched ${u.length} \u2192 ${c.length} after dedup (${r.sessionBytes} bytes used)`);let p=c.map(m=>{let g=m;return{text:g.text??g.content??"",score:g.score}}).filter(m=>m.text);return{action:"continue",context:{...l,recalledMemories:p}}}catch(u){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${u instanceof Error?u.message:String(u)}`),i=[]}return{action:"continue",context:l}}})),o.push(t.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,l)=>{let u=s===l.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${l.blockCount??0} blocks assembled, ${u} qmemory results (session: ${r.sessionBytes} bytes)`),{action:"continue",context:l}}})),()=>{for(let a of o)a();i=[]}}import{ClawQMemoryAdapter as eu}from"qlogicagent-adapter-claw";var as="qmemory";function ls(t){let e=new eu({baseUrl:t.baseUrl,apiKey:t.apiKey,timeout:t.timeoutMs??5e3});function n(o){return t.userIdPrefix?`${t.userIdPrefix}:${o}`:o}return{providerId:as,async search(o,r,s){return((await e.dispatch("memory.search",{q:o,user_id:n(r),limit:s?.limit??10})).memories??[]).filter(a=>a.id&&a.text).map(a=>({blockId:a.id,text:a.text,score:typeof a.importance=="number"?a.importance:0,source:as,metadata:a.metadata}))},async ingest(o,r,s){await e.dispatch("memory.addKnowledge",{user_id:n(r),messages:o.map(i=>({role:i.role,content:i.content,...i.timestamp?{timestamp:i.timestamp}:{}})),extraction_mode:"none",run_async:!0,...s?.sessionId?{session_id:s.sessionId}:{},...s?.source?{metadata:{source:s.source}}:{}})},async health(){let o=await e.dispatch("memory.health",{});return{status:o.status??"unknown",version:o.version??"",memoryCount:o.memory_count??0,dbSizeBytes:o.db_size_bytes??0,embeddingModel:o.embedding_model??"",uptimeSeconds:o.uptime_seconds??0}},async addText(o,r,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:n(r),text:o,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(o,r,s){if(o.length===0)return{memoriesAdded:0};let i=n(r),a=await Promise.allSettled(o.map(u=>e.dispatch("memory.addFact",{user_id:i,text:u.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...u.category?{category:u.category}:{},...typeof u.importance=="number"?{importance:u.importance}:{},...u.speaker?{speaker:u.speaker}:{},...u.event_date?{event_date:u.event_date}:{},...u.tags?.length?{tags:u.tags}:{}}}))),l=0;for(let u of a)u.status==="fulfilled"&&(l+=u.value.memories_added??1);return{memoriesAdded:l}},async remove(o){try{return await e.dispatch("memory.forget",{id:o}),!0}catch{return!1}},async feedback(o,r,s){await e.dispatch("memory.feedback",{memory_ids:o,signal:r,...s?{session_id:s}:{}})}}}import{readFile as gs,writeFile as zn,stat as xs,unlink as iu,mkdir as au}from"node:fs/promises";import{join as kt,resolve as fs,isAbsolute as hs,normalize as ys}from"node:path";import{randomUUID as lu}from"node:crypto";function cs(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function tu(t){return t.latestInputTokens+t.cumulativeOutputTokens}var nu=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),us=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function ou(t){return{isSearch:nu.has(t)||void 0,isRead:us.has(t)||void 0}}function ru(t,e){let n=e.file_path??e.path??e.filePath;if(typeof n=="string")return`${us.has(t)?"Reading":t.includes("write")||t.includes("edit")?"Editing":"Using"} ${n}`;let o=e.command??e.cmd;if(typeof o=="string")return`Running: ${o.length>60?o.slice(0,60)+"\u2026":o}`;let r=e.query??e.pattern??e.search;if(typeof r=="string")return`Searching: ${r}`}function ds(t,e){t.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),t.cumulativeOutputTokens+=e.output_tokens??0}function ps(t,e,n,o){t.toolUseCount++;let r=ou(e),s={toolName:e,input:n,activityDescription:o?.(e,n)??ru(e,n),isSearch:r.isSearch,isRead:r.isRead};for(t.recentActivities.push(s);t.recentActivities.length>5;)t.recentActivities.shift()}function qn(t){return{toolUseCount:t.toolUseCount,tokenCount:tu(t),lastActivity:t.recentActivities.length>0?t.recentActivities[t.recentActivities.length-1]:void 0,recentActivities:[...t.recentActivities]}}import{randomUUID as ms}from"node:crypto";function su(t){let e=new AbortController;return t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.abort(t.reason)},{once:!0})),e}async function bt(t){let e=Date.now(),n=[],o={prompt:0,completion:0},r=cs(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:u,toolInvoker:c,apiKey:p,model:m,log:g,hooks:y,forkLabel:f,maxTurns:x,temperature:b,parentSignal:S,onEvent:R,onProgress:_,budgetTokens:O,parentDepth:G,sidechainType:P}=t,M=su(S),N=`fork-${f}-${ms().slice(0,8)}`,H=`fork-session-${ms().slice(0,8)}`;g.info(`[fork:${f}] starting \u2014 ${s.length} initial messages, model=${m}`);let ee=l?{invoke:async(J,te,$,j)=>{let ne={};try{ne=JSON.parse($)}catch{}let d=l(te,ne);return d.allowed?c.invoke(J,te,$,j):(g.info(`[fork:${f}] tool ${te} denied: ${d.reason}`),{result:"",error:d.reason})}}:c,T=!0,q;try{let{Agent:J}=await Promise.resolve().then(()=>(jn(),Qr)),te=new J({llmTransport:u,apiKey:p,toolInvoker:ee,log:g,hooks:y,maxRounds:x});for await(let $ of te.run({turnId:N,sessionId:H,messages:s,tools:a,systemPrompt:i,config:{model:m,apiKey:p,temperature:b,maxOutputTokens:t.maxOutputTokens,parentDepth:G,sidechainType:P}},M.signal)){if(n.push($),R?.($),$.type==="end"&&$.usage&&(ds(r,{input_tokens:$.usage.prompt,output_tokens:$.usage.completion}),o.prompt+=$.usage.prompt,o.completion+=$.usage.completion,$.usage.cacheRead&&(o.cacheRead=(o.cacheRead??0)+$.usage.cacheRead),$.usage.cacheCreation&&(o.cacheCreation=(o.cacheCreation??0)+$.usage.cacheCreation),O&&O>0)){let j=o.prompt+o.completion+(o.reasoning??0);j>=O&&(g.info(`[fork:${f}] budget exceeded (${j} / ${O} tokens), aborting`),M.abort("budget_exceeded"))}if($.type==="tool_call"){let j={};try{j=JSON.parse($.arguments??"{}")}catch{}ps(r,$.name,j),_?.(qn(r))}$.type==="error"&&(T=!1,q=$.error)}}catch(J){T=!1,q=J instanceof Error?J.message:String(J),g.warn(`[fork:${f}] error: ${q}`)}finally{M.signal.aborted||M.abort("fork_complete")}let re=Date.now()-e;return g.info(`[fork:${f}] finished in ${re}ms \u2014 ${n.length} events, usage: prompt=${o.prompt} completion=${o.completion}, ok=${T}`),{events:n,totalUsage:o,progress:qn(r),durationMs:re,ok:T,error:q}}var vs={minHours:24,minSessions:5,scanIntervalMs:6e5},Tt=".consolidate-lock",cu=3600*1e3,bs="CLAUDE.md",uu=100,du=new Set(["ls","find","grep","cat","stat","wc","head","tail","file","which","whereis","type","echo","printf","test","diff","sort","uniq","tr","cut","awk","sed","du","df","date","pwd","hostname","uname","git"]),pu=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),mu=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function gu(t){let e=t.trim();if(!e||mu.test(e))return!1;let n=e.split(/\s+/),o=n[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!du.has(o))return!1;if(o==="git"){let r=n[1];if(!r||!pu.has(r))return!1}return!0}function fu(t,e){let{toolName:n,input:o}=e;if(new Set(["read_file","grep","glob","search","list_dir","file_read","Grep","Glob"]).has(n))return{allowed:!0};if(new Set(["qmemory_search","qmemory_store","qmemory_feedback"]).has(n))return{allowed:!0};if(n==="bash"||n==="execute_command"||n==="Bash"){let i=o.command??o.cmd??"";return gu(i)?{allowed:!0}:{allowed:!1,reason:"Only read-only shell commands are permitted during dream consolidation (ls, find, grep, cat, stat, wc, head, tail, and similar)"}}if(n==="file_edit"||n==="file_write"||n==="FileEdit"||n==="FileWrite"){let i=o.file_path??o.path??"";return typeof i=="string"&&Ss(i,t)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${t}`}}return{allowed:!1,reason:`Tool "${n}" is not permitted during dream consolidation. Only read_file, grep, glob, read-only bash, and memory-scoped file_edit/file_write are allowed.`}}function Ss(t,e){let n=hs(t)?t:fs(t),o=hs(e)?e:fs(e),r=ys(n),s=ys(o);return r.startsWith(s)}function ws(t,e,n,o){let r=o?.hasQMemory?`
|
|
34
|
+
|
|
35
|
+
## Phase 2.5 \u2014 Long-term memory triage (QMemory)
|
|
36
|
+
|
|
37
|
+
You have access to the long-term memory service via these tools:
|
|
38
|
+
- \`qmemory_search\` \u2014 recall existing long-term memories (check before storing duplicates)
|
|
39
|
+
- \`qmemory_store\` \u2014 persist a memory to the user's long-term store
|
|
40
|
+
- \`qmemory_feedback\` \u2014 mark recalled memories as outdated/wrong/useful
|
|
41
|
+
|
|
42
|
+
For each insight worth long-term persistence:
|
|
43
|
+
1. Search QMemory first to check for duplicates or contradictions
|
|
44
|
+
2. If a contradiction is found, use qmemory_feedback to mark the old memory as "outdated"
|
|
45
|
+
3. Store the corrected/new fact via qmemory_store
|
|
46
|
+
|
|
47
|
+
Classify memories into:
|
|
48
|
+
- **Project memory** \u2192 write to local memoryRoot/*.md (fast KV access, project-scoped)
|
|
49
|
+
- **User long-term memory** \u2192 store via qmemory_store (semantic search, persists across projects)
|
|
50
|
+
- **Noise** \u2192 discard (do not store)
|
|
51
|
+
|
|
52
|
+
Examples of user long-term memories: preferences, personal facts, recurring patterns, important decisions.
|
|
53
|
+
Examples of project memories: architecture decisions, file conventions, build patterns, known issues.
|
|
54
|
+
`:"";return`# Dream: Memory Consolidation
|
|
55
|
+
|
|
56
|
+
You are performing a dream \u2014 a reflective pass over your memory files. Synthesize what you've learned recently into durable, well-organized memories so that future sessions can orient quickly.
|
|
57
|
+
|
|
58
|
+
Memory directory: \`${t}\`
|
|
59
|
+
If the directory doesn't exist yet, create it with the necessary structure.
|
|
60
|
+
|
|
61
|
+
Session transcripts: \`${e}\` (large JSONL files \u2014 grep narrowly, don't read whole files)
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Phase 1 \u2014 Orient
|
|
66
|
+
|
|
67
|
+
- \`ls\` the memory directory to see what already exists
|
|
68
|
+
- Read \`${bs}\` to understand the current index
|
|
69
|
+
- Skim existing topic files so you improve them rather than creating duplicates
|
|
70
|
+
- If \`logs/\` or \`sessions/\` subdirectories exist, review recent entries there
|
|
71
|
+
|
|
72
|
+
## Phase 2 \u2014 Gather recent signal
|
|
73
|
+
|
|
74
|
+
Look for new information worth persisting. Sources in rough priority order:
|
|
75
|
+
|
|
76
|
+
1. **Session logs** if present \u2014 these are the append-only stream
|
|
77
|
+
2. **Existing memories that drifted** \u2014 facts that contradict something in the codebase now
|
|
78
|
+
3. **Transcript search** \u2014 if you need specific context, grep the JSONL transcripts for narrow terms:
|
|
79
|
+
\`grep -rn "<narrow term>" ${e}/ --include="*.jsonl" | tail -50\`
|
|
80
|
+
|
|
81
|
+
Don't exhaustively read transcripts. Look only for things you already suspect matter.
|
|
82
|
+
${r}
|
|
83
|
+
## Phase 3 \u2014 Consolidate
|
|
84
|
+
|
|
85
|
+
For each thing worth remembering, write or update a memory file at the top level of the memory directory.
|
|
86
|
+
|
|
87
|
+
Focus on:
|
|
88
|
+
- Merging new signal into existing topic files rather than creating near-duplicates
|
|
89
|
+
- Converting relative dates ("yesterday", "last week") to absolute dates so they remain interpretable after time passes
|
|
90
|
+
- Deleting contradicted facts \u2014 if today's investigation disproves an old memory, fix it at the source
|
|
91
|
+
|
|
92
|
+
## Phase 4 \u2014 Prune and index
|
|
93
|
+
|
|
94
|
+
Update \`${bs}\` so it stays under ${uu} lines AND under ~25KB. It's an **index**, not a dump \u2014 each entry should be one line under ~150 characters: \`- [Title](file.md) \u2014 one-line hook\`. Never write memory content directly into it.
|
|
95
|
+
|
|
96
|
+
- Remove pointers to memories that are now stale, wrong, or superseded
|
|
97
|
+
- Demote verbose entries: if an index line is over ~200 chars, it's carrying content that belongs in the topic file \u2014 shorten the line, move the detail
|
|
98
|
+
- Add pointers to newly important memories
|
|
99
|
+
- Resolve contradictions \u2014 if two files disagree, fix the wrong one
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
**Tool constraints for this run:** Bash is restricted to read-only commands (\`ls\`, \`find\`, \`grep\`, \`cat\`, \`stat\`, \`wc\`, \`head\`, \`tail\`, and similar). Anything that writes, redirects to a file, or modifies state will be denied. Plan your exploration with this in mind \u2014 no need to probe.
|
|
104
|
+
|
|
105
|
+
Sessions since last consolidation (${n.length}):
|
|
106
|
+
${n.map(s=>`- ${s}`).join(`
|
|
107
|
+
`)}
|
|
108
|
+
|
|
109
|
+
Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var ks=0;async function hu(t,e={}){let n={...vs,...e},o;try{o=await Cs(t.memoryRoot)}catch{o=0}let r=(Date.now()-o)/36e5;if(!n.force&&r<n.minHours)return null;let s=Date.now()-ks;if(!n.force&&s<n.scanIntervalMs)return null;ks=Date.now();let i;try{i=await t.listSessionsSince(o)}catch{return null}return i=i.filter(a=>a!==t.currentSessionId),!n.force&&i.length<n.minSessions?null:{sessionIds:i}}async function Cs(t){let e=kt(t,Tt);return(await xs(e)).mtimeMs}function yu(t){try{return process.kill(t,0),!0}catch{return!1}}async function bu(t){let e=kt(t,Tt),n,o;try{let[s,i]=await Promise.all([xs(e),gs(e,"utf8")]);n=s.mtimeMs;let a=parseInt(i.trim(),10);o=Number.isFinite(a)?a:void 0}catch{}if(n!==void 0&&Date.now()-n<cu&&o!==void 0&&yu(o))return null;await au(t,{recursive:!0}),await zn(e,String(process.pid));let r;try{r=await gs(e,"utf8")}catch{return null}return parseInt(r.trim(),10)!==process.pid?null:n??0}async function Ts(t,e){let n=kt(t,Tt);try{if(e===0){await iu(n);return}await zn(n,"");let{utimes:o}=await import("node:fs/promises"),r=e/1e3;await o(n,r,r)}catch{}}async function ku(t){let e=kt(t,Tt);await zn(e,String(process.pid))}function Tu(t){return{taskId:`dream-${lu().slice(0,8)}`,type:"dream",label:"Memory consolidation",permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:1,maxTurns:0,tokenBudget:0,startedAt:Date.now(),parentTaskId:t.parentTaskId,sessionId:t.sessionId,phase:"starting",sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],priorLockMtime:t.priorLockMtime}}async function xu(t,e={}){let n={...vs,...e},o=await hu(t,n);if(!o)return null;let r;if(n.force)try{r=await Cs(t.memoryRoot)}catch{r=0}else if(r=await bu(t.memoryRoot),r===null)return null;let s=ws(t.memoryRoot,t.transcriptDir,o.sessionIds),i=Tu({sessionId:t.currentSessionId,sessionsReviewing:o.sessionIds.length,priorLockMtime:r});return{prompt:s,taskState:i,sessionIds:o.sessionIds}}async function Rs(t){let e=Date.now(),n=await xu(t.context,t.triggerConfig);if(!n)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:o,sessionIds:r}=n,s=!!(t.qmemoryAdapter&&t.qmemoryUserId),i=s?ws(t.context.memoryRoot,t.context.transcriptDir,r,{hasQMemory:!0}):n.prompt;t.log.info(`[dream] starting consolidation \u2014 ${r.length} sessions, memoryRoot=${t.context.memoryRoot}`+(s?", qmemory=enabled":"")),t.hooks?.invoke("subagent.started",{sessionId:t.context.currentSessionId,turnId:o.taskId,subagentId:o.taskId,agentType:"dream"}).catch(()=>{});let a=(p,m)=>fu(t.context.memoryRoot,{toolName:p,input:m}),l=s?[{type:"function",function:{name:"qmemory_search",description:"Search the user's long-term memory (QMemory). Returns relevant memories sorted by relevance.",parameters:{type:"object",properties:{query:{type:"string",description:"Semantic search query"},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"qmemory_store",description:"Store a memory to the user's long-term memory (QMemory). Use for user preferences, facts, and cross-project knowledge.",parameters:{type:"object",properties:{text:{type:"string",description:"The memory text to store"},source:{type:"string",description:"Source label (e.g. 'dream-consolidation')"}},required:["text"]}}},{type:"function",function:{name:"qmemory_feedback",description:"Submit feedback on recalled memories (e.g. mark as outdated or wrong).",parameters:{type:"object",properties:{memoryIds:{type:"array",items:{type:"string"},description:"IDs of memories to give feedback on"},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"Feedback signal"}},required:["memoryIds","signal"]}}}]:[],u=s?{invoke:async(p,m,g,y)=>{let f=t.qmemoryAdapter,x=t.qmemoryUserId;if(m==="qmemory_search"){let{query:b,limit:S}=JSON.parse(g),R=await f.search(b,x,{limit:S??10});return{result:JSON.stringify(R)}}if(m==="qmemory_store"){if(!f.addText)return{result:JSON.stringify({error:"addText not supported"})};let{text:b,source:S}=JSON.parse(g),R=await f.addText(b,x,{sessionId:t.context.currentSessionId,source:S??"dream-consolidation"});return{result:JSON.stringify(R)}}if(m==="qmemory_feedback"){let{memoryIds:b,signal:S}=JSON.parse(g);return f.feedback&&await f.feedback(b,S,t.context.currentSessionId),{result:JSON.stringify({ok:!0})}}return t.toolInvoker.invoke(p,m,g,y)}}:t.toolInvoker,c=[...t.tools,...l];try{let p=await bt({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:i,tools:c,canUseTool:a,transport:t.transport,toolInvoker:u,apiKey:t.apiKey,model:t.model,log:t.log,hooks:t.hooks,forkLabel:"dream-consolidation",sidechainType:"research",parentSignal:t.parentSignal,skipTranscript:!0}),m=[];for(let g of p.events)if(g.type==="tool_call")try{let y=JSON.parse(g.arguments),f=y.file_path??y.path??y.filePath;f&&Ss(f,t.context.memoryRoot)&&m.push(f)}catch{}return p.ok?(await ku(t.context.memoryRoot),t.log.info(`[dream] consolidation complete \u2014 ${m.length} files touched, ${p.durationMs}ms`)):(await Ts(t.context.memoryRoot,o.priorLockMtime),t.log.warn(`[dream] consolidation failed: ${p.error}`)),t.hooks?.invoke("subagent.stopped",{sessionId:t.context.currentSessionId,turnId:o.taskId,subagentId:o.taskId,agentType:"dream",reason:p.ok?"normal":"error",error:p.error}).catch(()=>{}),{ok:p.ok,sessionsReviewed:r.length,filesTouched:[...new Set(m)],turns:[],durationMs:Date.now()-e,error:p.error}}catch(p){await Ts(t.context.memoryRoot,o.priorLockMtime).catch(()=>{});let m=p instanceof Error?p.message:String(p);return t.log.warn(`[dream] consolidation error: ${m}`),t.hooks?.invoke("subagent.stopped",{sessionId:t.context.currentSessionId,turnId:o.taskId,subagentId:o.taskId,agentType:"dream",reason:"error",error:m}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:m}}}var xt=class{sessionId;_trustAccepted=!1;_totalCostUSD=0;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_tokensSinceLastExtraction=0;_toolCallsSinceLastExtraction=0;_hasExtractedOnce=!1;_listeners=new Set;extractionThresholds;constructor(e,n){this.sessionId=e,this.extractionThresholds={initialTokenThreshold:n?.initialTokenThreshold??1e4,updateTokenThreshold:n?.updateTokenThreshold??5e3,toolCallThreshold:n?.toolCallThreshold??3}}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}get totalCostUSD(){return this._totalCostUSD}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}get turnCount(){return this._turnCount}get toolCallCount(){return this._toolCallCount}getModelUsage(e){return this._modelUsage.get(e)}getAllModelUsage(){let e={};for(let[n,o]of this._modelUsage)e[n]={...o};return e}addUsage(e,n,o=0){this._totalCostUSD+=o,this._totalInputTokens+=e.prompt,this._totalOutputTokens+=e.completion;let r=this._modelUsage.get(n);r?(r.inputTokens+=e.prompt,r.outputTokens+=e.completion,r.costUSD+=o):this._modelUsage.set(n,{inputTokens:e.prompt,outputTokens:e.completion,cacheRead:0,cacheCreation:0,costUSD:o}),this._tokensSinceLastExtraction+=e.prompt+e.completion,this.notifyListeners()}recordToolCall(){this._toolCallCount++,this._toolCallsSinceLastExtraction++}recordTurnCompleted(){this._turnCount++}shouldExtractMemory(){let e=this._hasExtractedOnce?this.extractionThresholds.updateTokenThreshold:this.extractionThresholds.initialTokenThreshold,n=this._tokensSinceLastExtraction>=e,o=this._toolCallsSinceLastExtraction>=this.extractionThresholds.toolCallThreshold;return n&&o}markExtractionDone(){this._tokensSinceLastExtraction=0,this._toolCallsSinceLastExtraction=0,this._hasExtractedOnce=!0}createSnapshot(){return{sessionId:this.sessionId,totalCostUSD:this._totalCostUSD,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalCostUSD=e.totalCostUSD,this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[n,o]of Object.entries(e.modelUsage))this._modelUsage.set(n,{...o});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as se from"node:fs";import*as ue from"node:path";import{homedir as vu}from"node:os";var Su=".openclaw/sessions",_s="transcript.jsonl",Qe="state.json",wu=50,Cu=50,Ru=30;function As(){return ue.join(vu(),Su)}function vt(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_");return ue.join(As(),e)}async function Gn(t,e){let n=vt(t);await se.promises.mkdir(n,{recursive:!0});let o=JSON.stringify({role:e.role,content:e.content,ts:Date.now()})+`
|
|
110
|
+
`;await se.promises.appendFile(ue.join(n,_s),o,"utf8")}async function Ps(t,e,n){let o=vt(t);await se.promises.mkdir(o,{recursive:!0});let r={metadata:{sessionId:t,createdAt:n.createdAt??Date.now(),lastActiveAt:Date.now(),model:n.model,cwd:n.cwd,turnCount:e.turnCount,messageCount:n.messageCount??0,title:n.title},costSnapshot:e},s=ue.join(o,Qe+".tmp");await se.promises.writeFile(s,JSON.stringify(r,null,2),"utf8"),await se.promises.rename(s,ue.join(o,Qe))}async function Ms(t){let e=vt(t),n=ue.join(e,_s),o=ue.join(e,Qe),r=[];try{r=(await se.promises.readFile(n,"utf8")).split(`
|
|
111
|
+
`).filter(Boolean).map(u=>{let c=JSON.parse(u);return{role:c.role,content:c.content??null}})}catch{return null}let s={sessionId:t,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:r.length},i;try{let l=await se.promises.readFile(o,"utf8"),u=JSON.parse(l);s=u.metadata,i=u.costSnapshot}catch{}let a=r.filter(l=>l.role!=="system");return{metadata:s,messages:a,costSnapshot:i}}async function Is(t=wu){let e=As(),n;try{n=await se.promises.readdir(e)}catch{return[]}let o=[];for(let r of n){let s=ue.join(e,r,Qe);try{let i=await se.promises.readFile(s,"utf8"),a=JSON.parse(i);o.push({sessionId:a.metadata.sessionId,title:a.metadata.title,lastActiveAt:a.metadata.lastActiveAt,messageCount:a.metadata.messageCount,model:a.metadata.model})}catch{}}return o.sort((r,s)=>s.lastActiveAt-r.lastActiveAt),o.slice(0,t)}function _u(t){return t.turnCount<Cu?!1:t.taskSummaryGeneratedAt?t.turnCount-(t.taskSummaryGeneratedAt??0)>=Ru:!0}async function Es(t,e,n,o){if(!_u(e))return null;try{let s=n.slice(-20).map(c=>`[${c.role}]: ${typeof c.content=="string"?c.content.slice(0,500):JSON.stringify(c.content).slice(0,500)}`).join(`
|
|
112
|
+
`),i=o.transport.stream({model:o.model,messages:[{role:"system",content:"Generate a concise task summary (~100 words) of what the user is working on in this session. Focus on the goal, key decisions, and current progress. Reply with ONLY the summary."},{role:"user",content:s}],tools:[],maxTokens:200},o.apiKey),a="";for await(let c of i)c.type==="delta"&&(a+=c.text);if(a=a.trim(),!a)return null;let l=vt(t),u=ue.join(l,Qe);try{let c=await se.promises.readFile(u,"utf8"),p=JSON.parse(c);p.metadata.taskSummary=a,p.metadata.taskSummaryGeneratedAt=e.turnCount;let m=u+".tmp";await se.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await se.promises.rename(m,u)}catch{}return a}catch{return null}}Nn();import{randomUUID as Qy}from"node:crypto";var Au=3e4;var wt=class{tasks=new Map;listeners=new Set;hooks=null;sessionId="";setHooks(e,n){this.hooks=e,this.sessionId=n}onTaskChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,n){for(let o of this.listeners)try{o(e,n)}catch{}}registerTask(e){this.tasks.set(e.taskId,e),this.notify(e.taskId,e),this.hooks?.invoke("task.created",{sessionId:this.sessionId,taskId:e.taskId,taskType:e.type,label:e.label}).catch(()=>{})}updateTask(e,n){let o=this.tasks.get(e);if(!o)return;let r=n(o);r!==o&&(this.tasks.set(e,r),this.notify(e,r),!St(o.lifecycle)&&St(r.lifecycle)&&this.hooks?.invoke("task.completed",{sessionId:this.sessionId,taskId:r.taskId,taskType:r.type,label:r.label}).catch(()=>{}))}getTask(e){return this.tasks.get(e)}getRunningTasks(){return[...this.tasks.values()].filter(e=>e.lifecycle==="running")}getAllTasks(){return[...this.tasks.values()]}evictTask(e){let n=this.tasks.get(e);n&&St(n.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=Au){let n=Date.now();for(let[o,r]of this.tasks)St(r.lifecycle)&&r.endedAt&&n-r.endedAt>e&&(this.tasks.delete(o),this.notify(o,null))}};function St(t){return t==="completed"||t==="failed"||t==="cancelled"||t==="timeout"}import{watch as Pu}from"node:fs";import{stat as Mu}from"node:fs/promises";import{join as Os,relative as Iu,resolve as Eu}from"node:path";var Ou=[".openclaw/settings.json","INSTRUCTIONS.md",".openclaw/INSTRUCTIONS.md","INSTRUCTIONS.local.md",".openclaw/rules"],Lu=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",".openclaw/rules"],Kn=class{watchers=new Map;deps;debounceTimers=new Map;_cwd;constructor(e){this.deps=e,this._cwd=e.projectRoot}get cwd(){return this._cwd}async start(){for(let e of Ou){let n=Os(this.deps.projectRoot,e);this.watchPath(n,e)}this.deps.log?.(`file-watcher: watching ${this.watchers.size} paths`)}watchPath(e,n){if(!this.watchers.has(e))try{let o=Pu(e,{persistent:!1,recursive:n.includes("/")?!1:void 0},(r,s)=>{let i=s?Os(e,s):e;this.handleChange(i,r==="rename"?"created":"modified")});o.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,o)}catch{}}handleChange(e,n){let o=this.debounceTimers.get(e);o&&clearTimeout(o),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let r=n;try{await Mu(e)}catch{r="deleted"}let s=Iu(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${r} ${s}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:r}).catch(()=>{}),Lu.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let n=Eu(e);if(n===this._cwd)return;let o=this._cwd;this._cwd=n,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:o,newCwd:n}).catch(()=>{}),this.deps.onInstructionCacheReset?.()}stop(){for(let[,e]of this.watchers)e.close();this.watchers.clear();for(let[,e]of this.debounceTimers)clearTimeout(e);this.debounceTimers.clear()}};async function Ls(t){let e=new Kn(t);return await e.start(),e}import{readFile as $u,readdir as Du,stat as Nu}from"node:fs/promises";import{dirname as Ct,extname as ju,isAbsolute as Fu,join as de,parse as js,resolve as $s}from"node:path";import{homedir as Fs}from"node:os";var Uu=5;var Ds="INSTRUCTIONS.md",Bu="INSTRUCTIONS.local.md",Wu="INSTRUCTIONS.md",Vn=".openclaw",Ns="rules",Hu=new Set([".md",".txt",".text",".json",".yaml",".yml",".toml",".xml",".csv",".html",".htm",".css",".scss",".sass",".less",".js",".ts",".tsx",".jsx",".mjs",".cjs",".mts",".cts",".py",".pyi",".pyw",".rb",".erb",".rake",".go",".rs",".java",".kt",".kts",".scala",".c",".cpp",".cc",".cxx",".h",".hpp",".hxx",".cs",".swift",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".env",".ini",".cfg",".conf",".config",".properties",".sql",".graphql",".gql",".proto",".vue",".svelte",".astro",".php",".pl",".pm",".lua",".r",".R",".dart",".ex",".exs",".erl",".hrl",".clj",".cljs",".cljc",".edn",".hs",".lhs",".elm",".ml",".mli",".f",".f90",".f95",".for",".cmake",".make",".makefile",".gradle",".sbt",".rst",".adoc",".asciidoc",".org",".tex",".latex",".lock",".log",".diff",".patch"]);async function qu(t){try{return await $u(t,"utf-8")}catch{return null}}function zu(t){return t.includes("<!--")?t.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):t}function Gu(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:t};let n=e[1],o=t.slice(e[0].length),r=n.match(/^paths:\s*(.+)$/m);if(!r)return{content:o};let s=[],i=r[1].trim();if(i.startsWith("["))try{s=JSON.parse(i)}catch{}else s=i.split(",").map(l=>l.trim()).filter(Boolean);let a=s.map(l=>l.endsWith("/**")?l.slice(0,-3):l).filter(l=>l.length>0&&l!=="**");return{content:o,globs:a.length>0?a:void 0}}function Ku(t,e){let n=new Set,o=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=t.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=o.exec(s))!==null;){let a=i[1];if(!a)continue;let l=a.indexOf("#");if(l!==-1&&(a=a.substring(0,l)),!a)continue;a=a.replace(/\\ /g," ");let u;if(a.startsWith("~/"))u=de(Fs(),a.slice(2));else if(Fu(a))u=a;else if(a.startsWith("./"))u=$s(Ct(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))u=$s(Ct(e),a);else continue;n.add(u)}return[...n]}async function Ee(t,e,n,o=0,r){let s=t.toLowerCase();if(n.has(s)||o>=Uu)return[];let i=ju(t).toLowerCase();if(i&&!Hu.has(i))return[];n.add(s);let a=await qu(t);if(!a?.trim())return[];let{content:l,globs:u}=Gu(a),c=zu(l);if(!c.trim())return[];let p=[],m={path:t,type:e,content:c.trim()};r&&(m.parent=r),u&&(m.globs=u),p.push(m);let g=Ku(l,t);for(let y of g){let f=await Ee(y,e,n,o+1,t);p.push(...f)}return p}async function Jn(t,e,n,o,r=new Set){if(r.has(t))return[];r.add(t);let s=[];try{let i=await Du(t,{withFileTypes:!0});for(let a of i){let l=de(t,a.name);if(a.isDirectory())s.push(...await Jn(l,e,n,o,r));else if(a.isFile()&&a.name.endsWith(".md")){let u=await Ee(l,e,n);s.push(...u.filter(c=>o?!!c.globs:!c.globs))}}}catch{}return s}async function Vu(t){let e=t,n=js(e).root;for(;e!==n;){try{let o=de(e,".git"),r=await Nu(o);if(r.isDirectory()||r.isFile())return e}catch{}e=Ct(e)}return null}async function Ju(t,e){let n=[],o=new Set,r=de(Fs(),Vn),s=de(r,Wu);n.push(...await Ee(s,"User",o));let i=de(r,Ns);n.push(...await Jn(i,"User",o,!1));let l=await Vu(t)??js(t).root,u=[],c=t;for(;u.push(c),!(c===l&&c!==t);){let p=Ct(c);if(p===c)break;c=p}for(let p of u.reverse())n.push(...await Ee(de(p,Ds),"Project",o)),n.push(...await Ee(de(p,Vn,Ds),"Project",o)),n.push(...await Jn(de(p,Vn,Ns),"Project",o,!1)),n.push(...await Ee(de(p,Bu),"Local",o));return e&&n.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:t,fileCount:n.length}).catch(()=>{}),n}function Us(t){if(t.length===0)return"";let e="Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.",n=[];for(let o of t){if(!o.content)continue;let r=o.type==="Project"?" (project instructions, checked into the codebase)":o.type==="Local"?" (user's private project instructions, not checked in)":" (user's private global instructions for all projects)";n.push(`Contents of ${o.path}${r}:
|
|
113
|
+
|
|
114
|
+
${o.content.trim()}`)}return n.length>0?`${e}
|
|
115
|
+
|
|
116
|
+
${n.join(`
|
|
117
|
+
|
|
118
|
+
`)}`:""}var et=null,Yn=null;async function Bs(t,e){return et&&Yn===t||(et=await Ju(t,e),Yn=t),et}function Ws(){et=null,Yn=null}function Hs(t,e){return{name:t,compute:e,cacheBreak:!1}}var Rt=new Map;async function Yu(t){return(await Promise.all(t.map(async n=>{if(!n.cacheBreak&&Rt.has(n.name))return Rt.get(n.name)??null;let o=await n.compute();return Rt.set(n.name,o),o}))).filter(n=>n!=null)}function qs(){Rt.clear()}async function zs(t){let e=[];if(t.instructionBlock&&e.push(t.instructionBlock),t.customSystemPrompt?e.push(t.customSystemPrompt):t.basePrompt&&e.push(t.basePrompt),t.sections?.length){let n=await Yu(t.sections);e.push(...n)}return t.appendSystemPrompt&&e.push(t.appendSystemPrompt),e.filter(Boolean).join(`
|
|
119
|
+
|
|
120
|
+
`)}import{release as Xu,homedir as Zu}from"node:os";import{resolve as Qu}from"node:path";function ed(){let e=(process.env.SHELL??process.env.ComSpec??"").toLowerCase();return e.includes("zsh")?"zsh":e.includes("bash")?"bash":e.includes("fish")?"fish":e.includes("powershell")||e.includes("pwsh")?"powershell":e.includes("cmd")?"cmd":process.platform==="win32"?"powershell":"bash"}function td(){let t=process.platform,e=Xu();return t==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():t==="darwin"?"macOS":t==="linux"?"Linux":t}function Gs(){return Hs("environment_context",()=>{let t=ed(),e=td(),n=process.cwd(),o=process.version,r=Zu(),s=["# Environment","",`- Platform: ${e}`,`- Shell: ${t}`,`- Working directory: ${Qu(n)}`,`- Home directory: ${r}`,`- Node.js: ${o}`];return t==="powershell"?s.push("- Note: Use PowerShell syntax (semicolons, not &&; use $env: for env vars)"):t==="cmd"&&s.push("- Note: Use CMD syntax (%VAR%, not $VAR)"),s.join(`
|
|
121
|
+
`)})}import*as I from"node:fs";import*as L from"node:path";import{execFile as em}from"node:child_process";var _t=class{tools=new Map;register(e){this.tools.set(e.name,e)}registerAll(e){for(let n of e)this.register(n)}unregister(e){return this.tools.delete(e)}findTool(e){return this.tools.get(e)}has(e){return this.tools.has(e)}async execute(e,n,o,r){let s=this.tools.get(e);if(!s)throw new Error(`Tool not found in local registry: ${e}`);return s.execute(n,o,r)}getToolManifest(e=!1){let n=[];for(let o of this.tools.values())!e&&o.shouldDefer||n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.parameters},meta:{parallelSafe:o.isConcurrencySafe??!1,isReadOnly:o.isReadOnly??!1,isDangerous:!(o.isReadOnly??!1)&&!(o.isConcurrencySafe??!1)}});return n}getToolNames(){return Array.from(this.tools.keys())}get size(){return this.tools.size}};var nd="think",od={type:"object",properties:{thought:{type:"string",description:["Your internal reasoning about the current situation.","Use this to:","\u2022 Analyze what the user really wants (disambiguate vague requests)","\u2022 Plan multi-step approaches before executing","\u2022 Evaluate which tool(s) to use and why","\u2022 Consider edge cases or potential issues","\u2022 Reflect on conversation context and user preferences","This content is never shown to the user."].join(`
|
|
122
|
+
`)}},required:["thought"]};function Ks(){return{name:nd,label:"Think",shouldDefer:!0,description:["Use this tool to think and reason about the current situation BEFORE taking action.","Call this tool when you need to:","- Analyze an ambiguous or complex user request before deciding what to do","- Plan a multi-step approach (what tools to call and in what order)","- Identify which steps can run in parallel vs. which must be sequential","- Evaluate tradeoffs between different approaches","- Reflect on user preferences from conversation history","- Process new information that changes your understanding","","This tool has NO side effects \u2014 it simply records your reasoning process.","Your thought is NOT shown to the user; it only improves YOUR decision quality.","After thinking, proceed to take the appropriate action.","","When planning multi-step work, be explicit about parallelism:",'- Say "\u8FD9\u4E9B\u53EF\u4EE5\u5E76\u884C\u751F\u6210" or "these can run in parallel" for independent tasks.','- Say "\u5148\u2026\u7136\u540E\u2026" or "step 1 first, then step 2" for sequential dependencies.'].join(`
|
|
123
|
+
`),parameters:od,execute:async(t,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function Vs(t){return{total:t.length,completed:t.filter(e=>e.status==="completed").length,inProgress:t.filter(e=>e.status==="in-progress").length,notStarted:t.filter(e=>e.status==="not-started").length}}var rd="todo",sd={type:"object",properties:{todoList:{type:"array",description:"Complete array of ALL todo items. Must include both existing and new items. Only one item may be in-progress at a time. Mark todos completed IMMEDIATELY after finishing \u2014 do not batch completions.",items:{type:"object",properties:{id:{type:"number",description:"Unique numeric id (sequential from 1)."},title:{type:"string",description:"Concise action-oriented label (3-7 words). Displayed in UI."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"not-started | in-progress (max 1) | completed"}},required:["id","title","status"]}}},required:["todoList"]};function Js(t){let e=[],n=t??{};return{name:rd,label:"Todo",description:"Manage a structured todo list to track progress on multi-step tasks. Each call replaces the full list. Use frequently during complex work to plan steps and show progress. Mark items in-progress before starting, completed immediately after finishing.",parameters:sd,searchHint:"manage session task checklist progress tracking",maxResultSizeChars:1e5,execute:async(o,r)=>{let s=r.todoList,i=s.filter(m=>m.status==="in-progress");if(i.length>1)return{content:[{type:"text",text:JSON.stringify({warning:`Only 1 item may be in-progress at a time (found ${i.length}).`,todoList:e})}],details:{type:"todo",warning:"multiple_in_progress"}};let a=[...e],l=s.length>0&&s.every(m=>m.status==="completed");l&&n.autoClearOnComplete?e=[]:e=s;let u=Vs(s),c=!1;n.enableVerificationNudge&&l&&s.length>=3&&!s.some(m=>/verif/i.test(m.title))&&(c=!0);let p={total:u.total,completed:u.completed,inProgress:u.inProgress,notStarted:u.notStarted,todoList:e,oldTodos:a};return c&&(p.verificationNudgeNeeded=!0),{content:[{type:"text",text:JSON.stringify(p)}],details:{type:"todo",...u,verificationNudgeNeeded:c,agentId:n.agentId}}}}}var Ys=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Xs=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Zs=new Set(["ls","tree","du"]);var Qs=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function id(t){let n=t.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let l=o[r];if(s.test(l)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function ei(t){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(t)}function Xn(t){let e=id(t),n=e!==null&&Ys.has(e),o=e!==null&&Xs.has(e),r=e!==null&&Zs.has(e),s=e!==null&&Qs.has(e),i=/(?:[^2]>|^>|\|>)/.test(t),a=ei(t),l=(n||o||r)&&!i&&!a;return{firstCommand:e,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}function Zn(t){return/(?:^|[;&|])\s*sleep\s+\d/i.test(t)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(t)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as hd}from"node:child_process";import{constants as It,readFileSync as yd,unlinkSync as bd}from"node:fs";import{mkdir as kd,open as Td,realpath as ri}from"node:fs/promises";import{isAbsolute as xd,resolve as vd}from"node:path";function At(){if(process.platform!=="win32")return!1;let t=process.env.QLOGICAGENT_USE_POWERSHELL;return t==="1"||t==="true"}function Qn(){return At()?"powershell":"bash"}function eo(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as ad,readFile as ld,writeFile as cd,unlink as ud}from"node:fs/promises";import{join as ti}from"node:path";import{tmpdir as dd}from"node:os";var pd=8*1024*1024,md=5*1024*1024*1024;var to;function tt(){if(!to){let t=Math.random().toString(36).slice(2,10);to=ti(dd(),"qla-tasks",t)}return to}function ni(t){return ti(tt(),`${t}.output`)}function ge(t="local_bash"){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var he=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,n,o=!1,r=pd){this.taskId=e,this.path=ni(e),this.stdoutToFile=o,this.#t=r,this.#i=n}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=gd(e),this.#u()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await ld(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&ad(tt(),{recursive:!0}).then(()=>cd(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await ud(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function gd(t){let e=0;for(let n=0;n<t.length;n++)t.charCodeAt(n)===10&&e++;return e}var no=137,oi=143,fd=5e3,oo=5*1024*1024*1024,Pt=class{#e;#n;#r;#s=!1;constructor(e,n,o){this.#e=e,this.#n=n,this.#r=o,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let n=typeof e=="string"?e:e.toString();this.#r?this.#n.writeStderr(n):this.#n.writeStdout(n)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#n=null)}},ro=class t{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,n,o,r,s=!1,i=oo){this.#t=e,this.#l=n,this.#g=o,this.#b=s,this.#u=i,this.taskOutput=r,this.#s=e.stderr?new Pt(e.stderr,r,!0):null,this.#r=e.stdout?new Pt(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#C()}get status(){return this.#e}static#T(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(oi)}#x(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,n){let o=e??(n==="SIGTERM"?144:1);this.#f(o)}#S(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#k(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#k(){this.#o&&(clearInterval(this.#o),this.#o=null)}#w(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(n=>{n.size>this.#u&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(no))},()=>{}))},fd),this.#o.unref?.()}#C(){this.#c=this.#x.bind(this),this.#l.addEventListener("abort",this.#c,{once:!0}),this.#t.once("exit",this.#v.bind(this)),this.#t.once("error",this.#S.bind(this)),this.#i=setTimeout(t.#T,this.#g,this);let e=new Promise(n=>{this.#m=n});return new Promise(n=>{this.#p=n,e.then(this.#R.bind(this))})}async#R(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let n=await this.taskOutput.getStdout(),o={code:e,stdout:n,stderr:this.taskOutput.getStderr(),interrupted:e===no,backgroundTaskId:this.#n};this.taskOutput.stdoutToFile&&!this.#n&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(o.outputFilePath=this.taskOutput.path,o.outputFileSize=this.taskOutput.outputFileSize)),this.#a?o.stderr=`Background command killed: output file exceeded ${oo} bytes. ${o.stderr}`:e===oi&&(o.stderr=`Command timed out after ${this.#g}ms. ${o.stderr}`),this.#p&&(this.#p(o),this.#p=null)}#y(e){this.#e="killed";let n=this.#t.pid;if(n)try{if(process.platform==="win32")import("node:child_process").then(({execSync:o})=>{try{o(`taskkill /PID ${n} /T /F`,{stdio:"ignore"})}catch{}});else try{process.kill(-n,"SIGKILL")}catch{try{process.kill(n,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#f(e??no)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#w():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#d=void 0}};function so(t,e,n,o,r=!1,s=oo){return new ro(t,e,n,o,r,s)}function Mt(t,e){let n=new he(ge("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:t}),taskOutput:n,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function io(t){let e=new he(ge("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:t,interrupted:!1,preSpawnError:t}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var Sd=1800*1e3,Et=process.cwd(),si=process.cwd();function ii(){return Et}function ao(t,e){Et=xd(t)?t:vd(e||Et,t)}function ai(){return si}function co(t){Et=t,si=t}var lo=null;function nt(t){lo={provider:t}}function li(){if(!lo)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return lo.provider}async function Ot(t,e,n,o){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l}=o??{},u=r||Sd,c=n??Qn(),p=li(),m=eo(),{commandString:g,cwdFilePath:y}=await p.buildExecCommand(t,{id:m,useSandbox:!1}),f=g,x=ii();try{await ri(x)}catch{let M=ai();try{await ri(M),ao(M),x=M}catch{return io(`Working directory "${x}" no longer exists.`)}}if(e.aborted)return Mt();let b=p.shellPath,S=p.getSpawnArgs(f),R=await p.getEnvironmentOverrides(t),_=!!l,O=ge("local_bash"),G=new he(O,s??null,!_);await kd(tt(),{recursive:!0});let P;if(!_){let M=It.O_NOFOLLOW??0;P=await Td(G.path,process.platform==="win32"?"w":It.O_WRONLY|It.O_CREAT|It.O_APPEND|M)}try{let M=hd(b,S,{env:{...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...R},cwd:x,stdio:_?["pipe","pipe","pipe"]:["pipe",P?.fd,P?.fd],detached:p.detached,windowsHide:!0}),N=so(M,e,u,G,a);if(P!==void 0)try{await P.close()}catch{}return M.stdout&&l&&M.stdout.on("data",H=>{l(typeof H=="string"?H:H.toString())}),y&&N.result.then(H=>{if(H&&!i&&!H.backgroundTaskId){try{let ee=yd(y,{encoding:"utf8"}).trim();ee&&ee.normalize("NFC")!==x&&ao(ee,x)}catch{}try{bd(y)}catch{}}}),N}catch(M){if(P!==void 0)try{await P.close()}catch{}return G.clear(),Mt(void 0,{code:126,stderr:M instanceof Error?M.message:String(M)})}}var wd="exec",Cd={type:"object",properties:{command:{type:"string",description:"Shell command to execute. On Windows uses PowerShell, on Unix uses bash."},description:{type:"string",description:'Clear, concise description of what this command does (e.g. "Install dependencies", "Run unit tests"). Used for UI display and permission logging. For simple commands keep it 5-10 words; for complex piped/flagged commands add enough context to clarify intent.'},workdir:{type:"string",description:"Working directory for the command."},timeout:{type:"number",description:"Timeout in milliseconds (default: 120000). Only applies to foreground commands. Max allowed: 600000 (10 min)."},background:{type:"boolean",description:"If true, start the command in the background and return immediately with a task ID. Use getOutput to check on it later. Good for dev servers, watchers, long builds. Default: false."}},required:["command"]},Rd=12e4,_d=6e5,Lt=3e4;function uo(t,e){if(t.length<=e)return t;let n=Math.floor(e/2)-50;return`${t.slice(0,n)}
|
|
124
|
+
|
|
125
|
+
... [truncated ${t.length-e} chars] ...
|
|
126
|
+
|
|
127
|
+
${t.slice(-n)}`}function Ad(t){return t==null||t<=0?Rd:Math.min(t,_d)}async function*Pd(t){let{command:e,abortController:n,timeout:o,shouldAutoBackground:r}=t,s="",i=0,a=0,l=Date.now(),u=null;function c(){return new Promise(g=>{u=()=>g(null)})}let p=await Ot(e,n.signal,void 0,{timeout:o,onProgress(g,y,f,x,b){s=y,i=f,a=x,u&&(u(),u=null)},shouldAutoBackground:r});for(p.onTimeout&&r&&p.onTimeout(g=>{let y=ge("bg");g(y)});p.status==="running"&&await Promise.race([c(),p.result])===null;)yield{type:"exec_progress",output:s.slice(-4096),fullOutput:s,elapsedTimeSeconds:(Date.now()-l)/1e3,totalLines:i,totalBytes:a};let m=await p.result;return p.cleanup(),m}function ci(t={}){return{name:wd,label:"Execute Command",description:"Execute a shell command. Supports foreground (blocking, returns output) and background (non-blocking, returns task ID) modes. On Windows uses PowerShell, on Unix uses bash. Commands are classified for safety: search/read commands may run in parallel; silent commands (mv, cp, rm) show 'Done' instead of empty output. Output is truncated and persisted if too long.",searchHint:"execute shell commands",parameters:Cd,maxResultSizeChars:Lt,execute:async(e,n)=>{let o=Xn(n.command);if(!n.background){let p=Zn(n.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:o}}}if(t.validateCommand){let p=await t.validateCommand(n.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_by_guard",reason:p,classification:o}}}let r=new AbortController,s=Ad(n.timeout);if(n.background){let p=await Ot(n.command,r.signal,void 0,{shouldAutoBackground:!1}),m=ge("bg");if(p.background(m))return{content:[{type:"text",text:`Background task started (id: ${m}).
|
|
128
|
+
Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:n.description,classification:o}}}let i=Pd({command:n.command,abortController:r,timeout:s,shouldAutoBackground:!0}),a;do a=await i.next(),!a.done&&t.onProgress&&t.onProgress(a.value);while(!a.done);let l=a.value,u=[];if(l.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${l.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:l.backgroundTaskId,assistantAutoBackgrounded:l.assistantAutoBackgrounded,classification:o}};l.outputFilePath?(u.push(uo(l.stdout,Lt)),u.push(`[full output: ${l.outputFilePath} (${l.outputFileSize} bytes)]`)):l.stdout&&u.push(uo(l.stdout,Lt)),l.stderr&&u.push(`[stderr]
|
|
129
|
+
${uo(l.stderr,Math.floor(Lt/4))}`),l.interrupted&&u.push(`[interrupted \u2014 exit code ${l.code}]`);let c;return l.code!==0&&t.interpretExitCode&&(c=t.interpretExitCode(l.code,l.stderr),c&&u.push(`[exit ${l.code}: ${c}]`)),u.length===0&&u.push(o.isSilent&&l.code===0?"Done":`(exit code ${l.code}, no output)`),{content:[{type:"text",text:u.join(`
|
|
130
|
+
`)}],details:{type:"exec",exitCode:l.code,interrupted:l.interrupted,description:n.description,returnCodeInterpretation:c,noOutputExpected:o.isSilent,outputFilePath:l.outputFilePath,classification:o}}}}}import{tmpdir as Md}from"node:os";import{join as Id,posix as po}from"node:path";function Ed(t){return t.replace(/(\d?)>nul\b/gi,(e,n)=>`${n||""}>/dev/null`)}function Od(t){return!(/(?:^|[;&|])\s*<\s/.test(t)||/<<[-]?\s*['"]?[A-Za-z_]/.test(t))}function Ld(t,e){return`$'${t.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function ui(t){return process.platform!=="win32"?t:t.replace(/^([A-Za-z]):/,(e,n)=>`/${n.toLowerCase()}`).replace(/\\/g,"/")}function $t(t,e){let n=e?.snapshotFilePath;return{type:"bash",shellPath:t,detached:!0,async buildExecCommand(o,r){let s=process.platform==="win32",i=Md(),a=s?ui(i):i,l=r.useSandbox&&r.sandboxTmpDir?po.join(r.sandboxTmpDir,`cwd-${r.id}`):po.join(a,`qla-${r.id}-cwd`),u=r.useSandbox&&r.sandboxTmpDir?po.join(r.sandboxTmpDir,`cwd-${r.id}`):Id(i,`qla-${r.id}-cwd`),c=Ed(o),p=Od(c),m=Ld(c,p),g=[];if(n){let f=s?ui(n):n;g.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&g.push(e.sessionEnvScript),g.push(`eval ${m}`),g.push(`pwd -P >| '${l}'`),{commandString:g.join(" && "),cwdFilePath:u}},getSpawnArgs(o){return["-c",...!!n?[]:["-l"],o]},async getEnvironmentOverrides(o){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as $d}from"node:os";import{join as Dd,posix as Nd}from"node:path";function di(t){return Buffer.from(t,"utf16le").toString("base64")}function jd(t){return["-NoProfile","-NonInteractive","-Command",t]}function mo(t){return{type:"powershell",shellPath:t,detached:!1,async buildExecCommand(e,n){let o=n.useSandbox&&n.sandboxTmpDir?Nd.join(n.sandboxTmpDir,`qla-pwd-ps-${n.id}`):Dd($d(),`qla-pwd-ps-${n.id}`),s=["","$_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }",`(Get-Location).Path | Out-File -FilePath '${o.replace(/'/g,"''")}' -Encoding utf8 -NoNewline`,"exit $_ec"].join(`
|
|
131
|
+
; `),i=e+s;return{commandString:n.useSandbox?[`'${t.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",di(i)].join(" "):i,cwdFilePath:o}},getSpawnArgs(e){return jd(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var Fd=[{pattern:/\bgit\s+reset\s+--hard\b/,warning:"Note: may discard uncommitted changes"},{pattern:/\bgit\s+push\b[^;&|\n]*[ \t](--force|--force-with-lease|-f)\b/,warning:"Note: may overwrite remote history"},{pattern:/\bgit\s+clean\b(?![^;&|\n]*(?:-[a-zA-Z]*n|--dry-run))[^;&|\n]*-[a-zA-Z]*f/,warning:"Note: may permanently delete untracked files"},{pattern:/\bgit\s+checkout\s+(--\s+)?\.[ \t]*($|[;&|\n])/,warning:"Note: may discard all working tree changes"},{pattern:/\bgit\s+restore\s+(--\s+)?\.[ \t]*($|[;&|\n])/,warning:"Note: may discard all working tree changes"},{pattern:/\bgit\s+stash[ \t]+(drop|clear)\b/,warning:"Note: may permanently remove stashed changes"},{pattern:/\bgit\s+branch\s+(-D[ \t]|--delete\s+--force|--force\s+--delete)\b/,warning:"Note: may force-delete a branch"},{pattern:/\bgit\s+(commit|push|merge)\b[^;&|\n]*--no-verify\b/,warning:"Note: may skip safety hooks"},{pattern:/\bgit\s+commit\b[^;&|\n]*--amend\b/,warning:"Note: may rewrite the last commit"},{pattern:/(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*[rR][a-zA-Z]*f|(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*f[a-zA-Z]*[rR]/,warning:"Note: may recursively force-remove files"},{pattern:/(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*[rR]/,warning:"Note: may recursively remove files"},{pattern:/(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*f/,warning:"Note: may force-remove files"},{pattern:/\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA)\b/i,warning:"Note: may drop or truncate database objects"},{pattern:/\bDELETE\s+FROM\s+\w+[ \t]*(;|"|'|\n|$)/i,warning:"Note: may delete all rows from a database table"},{pattern:/\bkubectl\s+delete\b/,warning:"Note: may delete Kubernetes resources"},{pattern:/\bterraform\s+destroy\b/,warning:"Note: may destroy Terraform infrastructure"}],Ud=[{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Recurse\b[^|;&\n}]*-Force\b/i,warning:"Note: may recursively force-remove files"},{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Force\b[^|;&\n}]*-Recurse\b/i,warning:"Note: may recursively force-remove files"},{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Recurse\b/i,warning:"Note: may recursively remove files"},{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Force\b/i,warning:"Note: may force-remove files"},{pattern:/\bClear-Content\b[^|;&\n]*\*/i,warning:"Note: may clear content of multiple files"},{pattern:/\bFormat-Volume\b/i,warning:"Note: may format a disk volume"},{pattern:/\bClear-Disk\b/i,warning:"Note: may clear a disk"},{pattern:/\bgit\s+reset\s+--hard\b/i,warning:"Note: may discard uncommitted changes"},{pattern:/\bgit\s+push\b[^|;&\n]*\s+(--force|--force-with-lease|-f)\b/i,warning:"Note: may overwrite remote history"},{pattern:/\bgit\s+clean\b(?![^|;&\n]*(?:-[a-zA-Z]*n|--dry-run))[^|;&\n]*-[a-zA-Z]*f/i,warning:"Note: may permanently delete untracked files"},{pattern:/\bgit\s+stash\s+(drop|clear)\b/i,warning:"Note: may permanently remove stashed changes"},{pattern:/\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA)\b/i,warning:"Note: may drop or truncate database objects"},{pattern:/\bStop-Computer\b/i,warning:"Note: will shut down the computer"},{pattern:/\bRestart-Computer\b/i,warning:"Note: will restart the computer"},{pattern:/\bClear-RecycleBin\b/i,warning:"Note: permanently deletes recycled files"}];function go(t){for(let{pattern:e,warning:n}of Fd)if(e.test(t))return n;return null}function fo(t){for(let{pattern:e,warning:n}of Ud)if(e.test(t))return n;return null}var Bd="read",Wd={type:"object",properties:{path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Default: 1."},limit:{type:"number",description:"Maximum number of lines to read. Default/max: 2000."}},required:["path"]};function pi(t){return{name:Bd,label:"Read File",description:"Read the contents of a file. Supports text files and images (jpg, png, gif, webp). For text files, output is truncated to 2000 lines or 50KB. Binary files are rejected with a hint. Use offset/limit for pagination of large files.",parameters:Wd,execute:async(o,r)=>{let s=t.resolvePath(r.path);if(t.validatePath){let f=t.validatePath(s);if(f)return{content:[{type:"text",text:`Access denied: ${f}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await t.readFile(s);if(i.type==="image")return{content:[{type:"image",data:i.base64,mimeType:i.mimeType}],details:{type:"read",path:s,isImage:!0}};if(i.type==="binary")return{content:[{type:"text",text:`Cannot read binary file (${i.mimeType}). Use a specific tool for this file type (e.g. pdf tool for PDFs).`}],details:{type:"read",path:s,error:"binary_file",mimeType:i.mimeType}};let a=i.text.split(`
|
|
132
|
+
`),l=Math.max(0,(r.offset??1)-1),u=Math.min(r.limit??2e3,2e3),c=a.slice(l,l+u),p=c.join(`
|
|
133
|
+
`);p.length>5e4&&(p=p.slice(0,5e4)+`
|
|
134
|
+
... (truncated)`);let m=a.length,g=l+c.length,y=g<m;return{content:[{type:"text",text:p}],details:{type:"read",path:s,totalLines:m,startLine:l+1,endLine:g,hasMore:y}}}}}var Hd="write",qd={type:"object",properties:{path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"Content to write to the file."}},required:["path","content"]},mi=5e5;function gi(t){return{name:Hd,label:"Write File",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories. Prefer edit/patch for modifying existing files (safer than full overwrite).",parameters:qd,execute:async(e,n)=>{let o=t.resolvePath(n.path);if(t.validatePath){let s=t.validatePath(o);if(s)return{content:[{type:"text",text:`Access denied: ${s}`}],details:{type:"write",path:o,error:"access_denied"}}}if(n.content.length>mi)return{content:[{type:"text",text:`Content too large (${n.content.length} chars, max ${mi}). Split into multiple writes or use a different approach.`}],details:{type:"write",path:o,error:"content_too_large"}};if(t.checkReadBeforeWrite){let s=t.checkReadBeforeWrite(o);if(s)return{content:[{type:"text",text:s}],details:{type:"write",path:o,error:"not_read_first"}}}if(t.checkConcurrentModification){let s=t.checkConcurrentModification(o);if(s)return{content:[{type:"text",text:`Concurrent modification detected: ${s}. Re-read the file first.`}],details:{type:"write",path:o,error:"concurrent_modification"}}}await t.writeFile(o,n.content);let r=n.content.split(`
|
|
135
|
+
`).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${o}`}],details:{type:"write",path:o,lineCount:r}}}}}var zd="edit",Gd={type:"object",properties:{path:{type:"string",description:"Path to the file to edit (relative or absolute)."},oldText:{type:"string",description:"Exact text to find and replace (must match exactly, including whitespace)."},newText:{type:"string",description:"New text to replace the old text with."}},required:["path","oldText","newText"]};function fi(t){return{name:zd,label:"Edit File",description:"Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits. For multiple edits, call this tool multiple times.",parameters:Gd,execute:async(e,n)=>{let o=t.resolvePath(n.path);if(t.checkConcurrentModification){let c=t.checkConcurrentModification(o);if(c)return{content:[{type:"text",text:`Concurrent modification detected: ${c}. Re-read the file first.`}],details:{type:"edit",path:o,success:!1,reason:"concurrent_modification"}}}let r=await t.readFile(o),s=r.indexOf(n.oldText);if(s===-1)return{content:[{type:"text",text:`Error: oldText not found in ${o}. Ensure it matches exactly.`}],details:{type:"edit",path:o,success:!1,reason:"not_found"}};if(r.indexOf(n.oldText,s+1)!==-1)return{content:[{type:"text",text:`Error: oldText matches multiple locations in ${o}. Include more context to make the match unique.`}],details:{type:"edit",path:o,success:!1,reason:"ambiguous"}};let a=r.slice(0,s)+n.newText+r.slice(s+n.oldText.length);await t.writeFile(o,a);let u=r.slice(0,s).split(`
|
|
136
|
+
`).length;return{content:[{type:"text",text:`Edited ${o} (line ${u})`}],details:{type:"edit",path:o,success:!0,firstChangedLine:u}}}}}var Kd="search",Vd={type:"object",properties:{mode:{type:"string",enum:["filename","content","both"],description:'Search mode: "filename" to find files by name pattern (glob), "content" to search within file contents (regex), "both" to match both filename patterns and content simultaneously.'},pattern:{type:"string",description:"The pattern to search for. In filename mode this is a glob pattern (e.g. **/*.ts). In content mode this is a regular expression. In both mode this is treated as a regex for content, and fileGlob filters the filename set."},path:{type:"string",description:"Directory to search in. Defaults to workdir/cwd if omitted."},fileGlob:{type:"string",description:'Glob pattern to filter files (e.g. "*.ts", "*.{js,tsx}"). In content/both modes, only files matching this glob are searched.'},contextLines:{type:"number",description:"Number of context lines to show before and after each match (content/both modes only). Default: 0."},caseInsensitive:{type:"boolean",description:"Case insensitive search (content/both modes). Default: false."},headLimit:{type:"number",description:"Maximum number of result entries to return. Default 100 for filename, 250 for content. Pass 0 for unlimited (use sparingly)."},offset:{type:"number",description:"Skip first N results before applying headLimit. Default: 0."}},required:["mode","pattern"]},hi=100,yi=250,ho=1e5;function bi(t){return{name:Kd,label:"Search",description:"Search for files by name, search within file contents by regex, or both. In filename mode, pattern is a glob. In content mode, pattern is a regex. Results are paginated via headLimit + offset.",parameters:Vd,execute:async(e,n)=>{let o=n.path?t.resolvePath?t.resolvePath(n.path):n.path:"",r=n.mode;return r==="filename"?Jd(t,n,o):r==="content"?Yd(t,n,o):Xd(t,n,o)}}}async function Jd(t,e,n){let o=e.headLimit??hi,{files:r,truncated:s}=await t.glob(e.pattern,{cwd:n,limit:o===0?1e4:o}),i=e.offset??0,a=i>0?r.slice(i):r,l=o===0?a.length:o,u=a.slice(0,l),c=s||a.length>l;if(u.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let p=u.join(`
|
|
137
|
+
`);return c&&(p+=`
|
|
138
|
+
|
|
139
|
+
(Results truncated. ${u.length} shown. Use a more specific pattern or increase headLimit.)`),p=yo(p,ho),{content:[{type:"text",text:p}],details:{mode:"filename",totalMatches:u.length,truncated:c}}}async function Yd(t,e,n){let o=e.headLimit??yi,{matches:r,truncated:s}=await t.grep(e.pattern,{cwd:n,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:o===0?void 0:o,offset:e.offset});if(r.length===0)return{content:[{type:"text",text:"No matches found."}],details:{mode:"content",totalMatches:0,truncated:!1}};let i=[];for(let l of r){if(l.contextBefore&&l.contextBefore.length>0)for(let u of l.contextBefore)i.push(` ${u}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let u of l.contextAfter)i.push(` ${u}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
|
|
140
|
+
`);return s&&(a+=`
|
|
141
|
+
|
|
142
|
+
(Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=yo(a,ho),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function Xd(t,e,n){let[o,r]=await Promise.all([e.fileGlob?t.glob(e.fileGlob,{cwd:n,limit:hi}):Promise.resolve({files:[],truncated:!1}),t.grep(e.pattern,{cwd:n,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??yi,offset:e.offset})]),s=new Set(r.matches.map(c=>c.path)),i=o.files.filter(c=>!s.has(c)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
|
|
143
|
+
${i.join(`
|
|
144
|
+
`)}`),r.matches.length>0){let c=[];for(let p of r.matches)c.push(`${p.path}:${p.line}: ${p.text}`);a.push(`## Content matches (${r.matches.length}):
|
|
145
|
+
${c.join(`
|
|
146
|
+
`)}`)}if(a.length===0)return{content:[{type:"text",text:"No matches found in either filename or content."}],details:{mode:"both",totalMatches:0,truncated:!1}};let l=o.truncated||r.truncated,u=a.join(`
|
|
147
|
+
|
|
148
|
+
`);return l&&(u+=`
|
|
149
|
+
|
|
150
|
+
(Some results truncated. Use more specific patterns.)`),u=yo(u,ho),{content:[{type:"text",text:u}],details:{mode:"both",totalMatches:i.length+r.matches.length,truncated:l}}}function yo(t,e){if(t.length<=e)return t;let n=Math.floor(e/2)-50;return`${t.slice(0,n)}
|
|
151
|
+
|
|
152
|
+
... [truncated ${t.length-e} chars] ...
|
|
153
|
+
|
|
154
|
+
${t.slice(-n)}`}var Zd="apply_patch",Qd={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function ep(t){let e=t.split(`
|
|
155
|
+
`),n=[],o=null,r=null,s=!1;for(let i of e){if(i.startsWith("*** Begin Patch")){s=!0;continue}if(i.startsWith("*** End Patch"))break;if(s){if(i.startsWith("*** Add File: "))o&&n.push(o),o={type:"add",path:i.slice(14).trim(),hunks:[]},r={contextBefore:[],removals:[],additions:[],contextAfter:[]},o.hunks.push(r);else if(i.startsWith("*** Update File: "))o&&n.push(o),o={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))o&&n.push(o),o={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move to: ")&&o)o.moveTo=i.slice(13).trim();else if(i.startsWith("@@ ")&&o)r={contextBefore:[],removals:[],additions:[],contextAfter:[]},o.hunks.push(r);else if(r)if(i.startsWith("+"))r.additions.push(i.slice(1));else if(i.startsWith("-"))r.removals.push(i.slice(1));else{let a=i.startsWith(" ")?i.slice(1):i;r.additions.length===0&&r.removals.length===0?r.contextBefore.push(a):r.contextAfter.push(a)}}}return o&&n.push(o),n}function tp(t,e){let o=[...t.split(`
|
|
156
|
+
`)];for(let r of e){let s=-1;if(r.contextBefore.length>0)for(let i=0;i<=o.length-r.contextBefore.length;i++){let a=!0;for(let l=0;l<r.contextBefore.length;l++)if(o[i+l]!==r.contextBefore[l]){a=!1;break}if(a){s=i+r.contextBefore.length;break}}else s=0;s!==-1&&(r.removals.length>0?o.splice(s,r.removals.length,...r.additions):o.splice(s,0,...r.additions))}return o.join(`
|
|
157
|
+
`)}function ki(t){return{name:Zd,label:"Apply Patch",description:"Apply a patch to one or more files using the *** Begin Patch / *** End Patch format. Supports Add File, Update File, Delete File, and Move To operations.",parameters:Qd,execute:async(e,n)=>{let o=ep(n.input);if(o.length===0)return{content:[{type:"text",text:"Error: No valid patch operations found. Ensure *** Begin Patch / *** End Patch markers are present."}]};let r={added:[],modified:[],deleted:[]},s=[];for(let a of o){let l=t.resolvePath(a.path);try{switch(a.type){case"add":{let u=a.hunks.flatMap(c=>[...c.additions]).join(`
|
|
158
|
+
`);await t.writeFile(l,u),r.added.push(a.path);break}case"update":{let u=await t.readFile(l),c=tp(u,a.hunks);if(a.moveTo){let p=t.resolvePath(a.moveTo);await t.writeFile(p,c),await t.deleteFile(l),r.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await t.writeFile(l,c),r.modified.push(a.path);break}case"delete":{await t.deleteFile(l),r.deleted.push(a.path);break}}}catch(u){s.push(`${a.type} ${a.path}: ${u instanceof Error?u.message:String(u)}`)}}let i=[];return r.added.length&&i.push(`Added: ${r.added.join(", ")}`),r.modified.length&&i.push(`Modified: ${r.modified.join(", ")}`),r.deleted.length&&i.push(`Deleted: ${r.deleted.join(", ")}`),s.length&&i.push(`Errors: ${s.join("; ")}`),{content:[{type:"text",text:i.join(`
|
|
159
|
+
`)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var np="patch",op={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
|
|
160
|
+
1) V4A unified diff (*** Begin Patch / *** End Patch markers)
|
|
161
|
+
2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
|
|
162
|
+
Fuzzy matching automatically handles whitespace/indent/unicode drift in the search text.`},replaceAll:{type:"boolean",description:"Replace all occurrences instead of first only (default: false)."}},required:["input"]};function rp(t){return t.replace(/\\n/g,`
|
|
163
|
+
`).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Ti(t){return t.replace(/[\u201c\u201d\u201e\u201f]/g,'"').replace(/[\u2018\u2019\u201a\u201b]/g,"'").replace(/\u2014/g,"--").replace(/\u2013/g,"-").replace(/\u2026/g,"...").replace(/\u00a0/g," ")}function xi(t,e){if(t===e||Math.max(t.length,e.length)===0)return 1;let o=0,r=t.length,s=e.length,i=Math.max(r,s);for(let a=0;a<Math.min(r,s);a++)t[a]!==e[a]&&o++;return o+=Math.abs(r-s),1-o/i}function _i(t,e,n){let o=[],r=t.indexOf(e);if(r!==-1){if(n){let f=0;for(;(r=t.indexOf(e,f))!==-1;)o.push({start:r,end:r+e.length,strategy:"exact"}),f=r+e.length}else o.push({start:r,end:r+e.length,strategy:"exact"});return o}let s=e.split(`
|
|
164
|
+
`).map(f=>f.trim()),i=t.split(`
|
|
165
|
+
`),a=vi(i,s,(f,x)=>f.trim()===x);if(a)return[{...Si(t,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),u=t.replace(/[ \t]+/g," ");if(r=u.indexOf(l),r!==-1){let f=wi(t,u,r,l.length);if(f)return[{...f,strategy:"whitespace_normalized"}]}let c=vi(i,s,(f,x)=>f.trimStart()===x.trimStart());if(c)return[{...Si(t,i,c),strategy:"indentation_flexible"}];let p=rp(e);if(p!==e&&(r=t.indexOf(p),r!==-1))return[{start:r,end:r+p.length,strategy:"escape_normalized"}];let m=e.split(`
|
|
166
|
+
`);if(m.length>=3){let f=m.slice(1,-1).join(`
|
|
167
|
+
`),x=m[0].trim(),b=m[m.length-1].trim();for(let S=0;S<i.length;S++)if(i[S].trim()===x){let R=i.slice(0,S+1).join(`
|
|
168
|
+
`).length+1,_=t.indexOf(f,R);if(_!==-1){let O=_+f.length,G=t.indexOf(`
|
|
169
|
+
`,O);if((G===-1?t.slice(O):t.slice(O,G)).trim()===b||G!==-1&&t.slice(O+1,t.indexOf(`
|
|
170
|
+
`,O+1)===-1?void 0:t.indexOf(`
|
|
171
|
+
`,O+1)).trim()===b){let M=i.slice(0,S).join(`
|
|
172
|
+
`).length+(S>0?1:0),N=S,H=m.length;if(S+H<=i.length){N=S+H;let ee=i.slice(0,N).join(`
|
|
173
|
+
`).length;return[{start:M,end:ee,strategy:"trimmed_boundary"}]}}}}}let g=Ti(e),y=Ti(t);if((g!==e||y!==t)&&(r=y.indexOf(g),r!==-1)){let f=wi(t,y,r,g.length);if(f)return[{...f,strategy:"unicode_normalized"}]}if(m.length>=3){let f=m[0],x=m[m.length-1];for(let b=0;b<i.length;b++)if(i[b]===f){for(let S=b+m.length-1;S<Math.min(b+m.length+2,i.length);S++)if(i[S]===x){let R=S-b+1,_=i.slice(b+1,S),O=m.slice(1,-1),G=O.filter(M=>_.some(N=>xi(N,M)>=.7)).length;if((O.length>0?G/O.length:1)>=.5&&R<=m.length+2){let M=i.slice(0,b).join(`
|
|
174
|
+
`).length+(b>0?1:0),N=i.slice(0,S+1).join(`
|
|
175
|
+
`).length;return[{start:M,end:N,strategy:"block_anchor"}]}}}}if(m.length>=2)for(let f=0;f<=i.length-m.length;f++){let x=i.slice(f,f+m.length);if(m.map((R,_)=>xi(R,x[_])).filter(R=>R>=.8).length/m.length>=.5){let R=i.slice(0,f).join(`
|
|
176
|
+
`).length+(f>0?1:0),_=i.slice(0,f+m.length).join(`
|
|
177
|
+
`).length;return[{start:R,end:_,strategy:"context_aware"}]}}return[]}function vi(t,e,n){for(let o=0;o<=t.length-e.length;o++){let r=!0;for(let s=0;s<e.length;s++)if(!n(t[o+s],e[s])){r=!1;break}if(r)return{startIdx:o,endIdx:o+e.length}}return null}function Si(t,e,n){let o=e.slice(0,n.startIdx).join(`
|
|
178
|
+
`).length+(n.startIdx>0?1:0),r=e.slice(0,n.endIdx).join(`
|
|
179
|
+
`).length;return{start:o,end:r}}function wi(t,e,n,o){let r=0,s=0,i=-1,a=-1;for(;r<=t.length&&s<=e.length;){if(s===n&&i===-1&&(i=r),s===n+o){a=r;break}if(s>=e.length||r>=t.length)break;for(s++,r++;r<t.length&&s<e.length&&t[r]!==e[s];)r++}return i!==-1&&a===-1&&(a=t.length),i===-1?null:{start:i,end:a}}function Ci(t){let e=t.split(`
|
|
180
|
+
`),n=[],o=null,r=null,s=!1;for(let i of e){if(i.startsWith("*** Begin Patch")){s=!0;continue}if(i.startsWith("*** End Patch"))break;if(s)if(i.startsWith("*** Add File: "))o&&n.push(o),o={type:"add",path:i.slice(14).trim(),hunks:[]},r={lines:[]},o.hunks.push(r);else if(i.startsWith("*** Update File: "))o&&n.push(o),o={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))o&&n.push(o),o={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move File: ")){o&&n.push(o);let a=i.slice(15).trim().split(" -> ");o={type:"move",path:a[0].trim(),newPath:a[1]?.trim(),hunks:[]},r=null}else i.startsWith("@@ ")&&o?(r={contextHint:i.slice(3).replace(/ @@$/,"").trim()||void 0,lines:[]},o.hunks.push(r)):r&&(i.startsWith("+")?r.lines.push({prefix:"+",content:i.slice(1)}):i.startsWith("-")?r.lines.push({prefix:"-",content:i.slice(1)}):r.lines.push({prefix:" ",content:i.startsWith(" ")?i.slice(1):i}))}return o&&n.push(o),n}function sp(t){let e=[],n=t.split(/^(<<<< SEARCH)$/m);if(n.length<2)return[];let o=n[0].trim().split(`
|
|
181
|
+
`).pop()?.trim();if(!o)return[];for(let r=1;r<n.length;r+=2){let s=n[r+1]||"",i=s.indexOf(`
|
|
182
|
+
====
|
|
183
|
+
`);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),l=s.slice(i+6),u=l.indexOf(`
|
|
184
|
+
>>>> REPLACE`),c=u===-1?l:l.slice(0,u);e.push({path:o,search:a,replace:c})}return e}function Ri(t,e,n){let o=e.lines.filter(y=>y.prefix===" ").map(y=>y.content),r=e.lines.filter(y=>y.prefix==="-").map(y=>y.content),s=e.lines.filter(y=>y.prefix==="+").map(y=>y.content),i=[],a="context";for(let y of e.lines)(y.prefix===" "||y.prefix==="-")&&i.push(y.content);let l=i.join(`
|
|
185
|
+
`);if(!l)return{content:t+`
|
|
186
|
+
`+s.join(`
|
|
187
|
+
`),strategy:"exact"};let u=_i(t,l,n);if(u.length===0)return null;let c=[];for(let y of e.lines)(y.prefix===" "||y.prefix==="+")&&c.push(y.content);let p=c.join(`
|
|
188
|
+
`),m=u[0];return{content:t.slice(0,m.start)+p+t.slice(m.end),strategy:m.strategy}}function bo(t){return{name:np,label:"Patch",description:"Apply edits to files using fuzzy matching. Supports V4A unified diff format (*** Begin Patch / *** End Patch) for multi-file operations, and simple search/replace blocks. The fuzzy matcher handles whitespace, indentation, unicode, and escape drift \u2014 LLM output with minor formatting differences will still match correctly.",parameters:op,execute:async(e,n)=>{let o=n.replaceAll??!1,r={filesModified:[],filesAdded:[],filesDeleted:[],strategies:{},errors:[]},s=n.input.includes("*** Begin Patch"),i=n.input.includes("<<<< SEARCH");if(s){let u=Ci(n.input);if(u.length===0)return{content:[{type:"text",text:"Error: No valid V4A operations found. Ensure *** Begin Patch / *** End Patch markers are present."}],details:{type:"patch",error:"parse_failed"}};for(let c of u){let p=t.resolvePath(c.path);try{switch(c.type){case"add":{let m=c.hunks.flatMap(g=>g.lines.filter(y=>y.prefix==="+").map(y=>y.content)).join(`
|
|
189
|
+
`);await t.writeFile(p,m),r.filesAdded.push(c.path),r.strategies[c.path]="exact";break}case"delete":{await t.deleteFile(p),r.filesDeleted.push(c.path);break}case"move":{let m=await t.readFile(p);if(c.newPath){let g=t.resolvePath(c.newPath),y=m;for(let f of c.hunks){let x=Ri(y,f,o);x&&(y=x.content,r.strategies[c.path]=x.strategy)}await t.writeFile(g,y),await t.deleteFile(p),r.filesModified.push(`${c.path} \u2192 ${c.newPath}`)}break}case"update":{let m=await t.readFile(p),g="exact",y=!0;for(let f of c.hunks){let x=Ri(m,f,o);if(x)m=x.content,g=x.strategy;else{y=!1;let b=f.lines.filter(S=>S.prefix===" "||S.prefix==="-").map(S=>S.content).slice(0,5).join(`
|
|
190
|
+
`);r.errors.push(`${c.path}: hunk not matched. Search begins with:
|
|
191
|
+
${b}`)}}(y||m!==await t.readFile(p))&&(await t.writeFile(p,m),r.filesModified.push(c.path),r.strategies[c.path]=g);break}}}catch(m){r.errors.push(`${c.type} ${c.path}: ${m instanceof Error?m.message:String(m)}`)}}}else if(i){let u=sp(n.input);if(u.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let c of u){let p=t.resolvePath(c.path);try{let m=await t.readFile(p),g=_i(m,c.search,o);if(g.length===0){r.errors.push(`${c.path}: search text not matched (tried all 9 strategies)`);continue}let y=[...g].sort((f,x)=>x.start-f.start);for(let f of y)m=m.slice(0,f.start)+c.replace+m.slice(f.end);await t.writeFile(p,m),r.filesModified.push(c.path),r.strategies[c.path]=g[0].strategy}catch(m){r.errors.push(`${c.path}: ${m instanceof Error?m.message:String(m)}`)}}}else return Ci(`*** Begin Patch
|
|
192
|
+
`+n.input+`
|
|
193
|
+
*** End Patch`).length>0?bo(t).execute(e,{input:`*** Begin Patch
|
|
194
|
+
`+n.input+`
|
|
195
|
+
*** End Patch`,replaceAll:o}):{content:[{type:"text",text:"Error: Unrecognized patch format. Use V4A (*** Begin Patch) or search/replace (<<<< SEARCH / ==== / >>>> REPLACE)."}],details:{type:"patch",error:"unknown_format"}};let a=[];if(r.filesAdded.length&&a.push(`Added: ${r.filesAdded.join(", ")}`),r.filesModified.length){let u=r.filesModified.map(c=>`${c} (${r.strategies[c]||"exact"})`).join(", ");a.push(`Modified: ${u}`)}r.filesDeleted.length&&a.push(`Deleted: ${r.filesDeleted.join(", ")}`),r.errors.length&&a.push(`
|
|
196
|
+
Errors:
|
|
197
|
+
${r.errors.join(`
|
|
198
|
+
`)}`);let l=r.errors.length===0;return{content:[{type:"text",text:a.join(`
|
|
199
|
+
`)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var ip="web_fetch",ap={type:"object",properties:{url:{type:"string",description:"HTTP or HTTPS URL to fetch."},extractMode:{type:"string",enum:["markdown","text","json"],description:'Extraction mode: "markdown" (default), "text", or "json" (LLM-driven structured extraction).'},maxChars:{type:"number",description:"Maximum characters to return (truncates when exceeded).",minimum:100},query:{type:"string",description:"Original search query. When provided, returns the most query-relevant sections."},extract:{type:"boolean",description:"When true, returns structured extraction (title, summary, key facts, entities, topics, sentiment)."},summarize:{type:"boolean",description:"When true, returns a concise summary (< 500 chars) of the page content. Useful for long pages to reduce context usage while preserving key information."}},required:["url"]},lp=5e4;function Ai(t){return{name:ip,label:"Web Fetch",description:"Fetch content from a URL and extract it as markdown, text, or structured JSON. Supports query-based relevance filtering and structured extraction (title, summary, key facts, entities, topics, sentiment).",parameters:ap,execute:async(e,n)=>{let o=await t.fetchUrl({url:n.url,extractMode:n.extractMode,maxChars:n.maxChars??lp,query:n.query,extract:n.extract});if(n.summarize&&t.summarizeContent&&o.content.length>1e3){let s=await t.summarizeContent(o.content,n.query);return{content:[{type:"text",text:o.title?`# ${o.title}
|
|
200
|
+
|
|
201
|
+
${s}`:s}],details:{type:"web_fetch",url:n.url,summarized:!0,originalLength:o.content.length,summaryLength:s.length}}}let r=[];if(o.title&&r.push(`# ${o.title}
|
|
202
|
+
`),r.push(o.content),o.relevantExcerpts?.length){r.push(`
|
|
203
|
+
---
|
|
204
|
+
## Relevant Excerpts
|
|
205
|
+
`);for(let s of o.relevantExcerpts)r.push(`- ${s}`)}return{content:[{type:"text",text:r.join(`
|
|
206
|
+
`)}],details:{type:"web_fetch",url:n.url,extractMode:n.extractMode??"markdown",hasExtraction:!!o.extraction,extraction:o.extraction}}}}}var cp="web_search",up={type:"object",properties:{query:{type:"string",description:"Search query string. Be specific and concise for best results."},allowedDomains:{type:"array",items:{type:"string"},description:"Only include results from these domains (e.g. ['docs.python.org', 'stackoverflow.com']). Cannot be used together with blockedDomains."},blockedDomains:{type:"array",items:{type:"string"},description:"Exclude results from these domains. Cannot be used together with allowedDomains."}},required:["query"]},dp=10;function Pi(t){return{name:cp,label:"Web Search",description:"Search the web for current information. Returns top results with title, URL, and snippet. Use this when you need up-to-date information that may not be in your training data. You MUST include source URLs as markdown links when citing search results.",parameters:up,execute:async(e,n)=>{if(n.allowedDomains?.length&&n.blockedDomains?.length)return{content:[{type:"text",text:"Error: allowedDomains and blockedDomains cannot both be specified."}],details:{type:"web_search",error:"mutual_exclusion"}};if(!n.query||n.query.trim().length<2)return{content:[{type:"text",text:"Error: query must be at least 2 characters."}],details:{type:"web_search",error:"invalid_query"}};let o=await t.search(n.query.trim(),{allowedDomains:n.allowedDomains,blockedDomains:n.blockedDomains,maxResults:dp});if(o.results.length===0)return{content:[{type:"text",text:`No results found for: "${n.query}"`}],details:{type:"web_search",query:n.query,resultCount:0}};let r=[`Web search results for: "${o.query}"`,"","REMINDER: You MUST include source URLs as markdown links when referencing these results.",""];for(let s=0;s<o.results.length;s++){let i=o.results[s];r.push(`${s+1}. [${i.title}](${i.url})`),r.push(` ${i.snippet}`),r.push("")}return{content:[{type:"text",text:r.join(`
|
|
207
|
+
`)}],details:{type:"web_search",query:o.query,resultCount:o.results.length}}}}}var pp="instructions_list",mp={type:"object",properties:{project_id:{type:"string",description:'Project ID to list instructions for. Use "default" for the default project.'}},required:["project_id"]};function Mi(t){return{name:pp,label:"List Instructions",description:"List all instruction files (.md) in a project's .instructions/ directory. Instructions define agent behavior rules, coding standards, and project context. Returns filename, path, size, and last modified time for each file.",parameters:mp,isReadOnly:!0,isConcurrencySafe:!0,searchHint:"list project instructions rules coding standards behavior guidelines",execute:async(e,n)=>{let o=t.list(n.project_id);if(o.length===0)return{content:[{type:"text",text:"No instruction files found for this project."}],details:{projectId:n.project_id,count:0}};let r=o.map(s=>`- ${s.filename} (${s.size} bytes, updated ${s.updatedAt})`).join(`
|
|
208
|
+
`);return{content:[{type:"text",text:`Found ${o.length} instruction file(s):
|
|
209
|
+
${r}`}],details:{projectId:n.project_id,count:o.length,files:o}}}}}var gp="instructions_read",fp={type:"object",properties:{project_id:{type:"string",description:'Project ID. Use "default" for the default project.'},filename:{type:"string",description:'Instruction file name (e.g. "code-style.md"). Supports sub-paths like "testing/unit-test.md".'}},required:["project_id","filename"]};function Ii(t){return{name:gp,label:"Read Instruction",description:"Read the content of a specific instruction file (.md) from a project. Use instructions_list first to discover available files.",parameters:fp,isReadOnly:!0,isConcurrencySafe:!0,searchHint:"read instruction file content rules coding standard",execute:async(e,n)=>{let o=t.read(n.project_id,n.filename);return o?{content:[{type:"text",text:o.content}],details:{projectId:n.project_id,filename:o.filename,size:o.size}}:{content:[{type:"text",text:`Instruction file not found: ${n.filename}`}],details:{projectId:n.project_id,filename:n.filename,error:"not_found"}}}}}var hp="instructions_write",yp={type:"object",properties:{project_id:{type:"string",description:'Project ID. Use "default" for the default project.'},filename:{type:"string",description:'Instruction file name ending in .md (e.g. "code-style.md"). Sub-paths like "testing/unit-test.md" are supported.'},content:{type:"string",description:"Markdown content for the instruction file."}},required:["project_id","filename","content"]};function Ei(t){return{name:hp,label:"Write Instruction",description:"Create or overwrite an instruction file (.md) in a project. Instructions define agent behavior rules, coding standards, and project context. The file must end in .md. Sub-directories are created automatically.",parameters:yp,searchHint:"write create instruction file rules coding standard",execute:async(e,n)=>{if(!n.filename.endsWith(".md"))return{content:[{type:"text",text:"Filename must end with .md"}],details:{error:"invalid_filename"}};if(n.filename.includes(".."))return{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}};let o=t.write(n.project_id,n.filename,n.content);return{content:[{type:"text",text:`Instruction file written: ${o.filename} (${o.size} bytes)`}],details:{projectId:n.project_id,filename:o.filename,size:o.size}}}}}var bp="instructions_delete",kp={type:"object",properties:{project_id:{type:"string",description:'Project ID. Use "default" for the default project.'},filename:{type:"string",description:'Instruction file name to delete (e.g. "code-style.md").'}},required:["project_id","filename"]};function Oi(t){return{name:bp,label:"Delete Instruction",description:"Delete an instruction file (.md) from a project. This cannot be undone.",parameters:kp,searchHint:"delete remove instruction file",execute:async(e,n)=>n.filename.includes("..")?{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}}:t.remove(n.project_id,n.filename)?{content:[{type:"text",text:`Instruction file deleted: ${n.filename}`}],details:{projectId:n.project_id,filename:n.filename}}:{content:[{type:"text",text:`Instruction file not found: ${n.filename}`}],details:{projectId:n.project_id,filename:n.filename,error:"not_found"}}}}var Tp="worktree",xp={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
|
|
210
|
+
exit: Leave worktree (keep or remove it).
|
|
211
|
+
list: Show all active worktrees.`},name:{type:"string",description:"Worktree/branch name (for enter). Must be kebab-case, max 64 characters. If omitted, auto-generated from task context."},exitAction:{type:"string",enum:["keep","remove"],description:"For exit: 'keep' retains the worktree for later use; 'remove' deletes it."},discardChanges:{type:"boolean",description:"Required true to confirm discarding uncommitted changes when exitAction='remove'. Safety mechanism to prevent data loss."}},required:["action"]},vp=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function Li(t){return{name:Tp,label:"Git Worktree",description:"Create isolated git worktree branches for parallel development. Each worktree has its own working directory independent of the main branch. Use for: parallel features, safe experimentation, sub-agent isolation. Exit to keep or remove the worktree when done.",parameters:xp,execute:async(e,n)=>{switch(n.action){case"enter":{if(t.isInWorktree())return{content:[{type:"text",text:"Error: already in a worktree. Exit first before entering another."}],details:{type:"worktree",error:"already_in_worktree"}};if(n.name&&!vp.test(n.name))return{content:[{type:"text",text:"Error: name must be kebab-case (a-z, 0-9, hyphens), 2-64 characters."}],details:{type:"worktree",error:"invalid_name"}};let o=await t.enterWorktree(n.name);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error||"failed to create worktree"}`}],details:{type:"worktree",error:o.error}};let r=o.worktree;return{content:[{type:"text",text:[`Entered worktree: ${r.name}`,` Branch: ${r.branch}`,` Path: ${r.path}`,"","Working in isolated branch. Changes here do not affect the main branch.","Use action='exit' when done (keep or remove)."].join(`
|
|
212
|
+
`)}],details:{type:"worktree",action:"enter",name:r.name,branch:r.branch,path:r.path}}}case"exit":{if(!t.isInWorktree())return{content:[{type:"text",text:"Error: not in a worktree."}],details:{type:"worktree",error:"not_in_worktree"}};let o=n.exitAction||"keep";if(o==="remove"){let i=t.currentWorktree?.();if(i&&(i.hasChanges||i.unpushedCommits>0)&&!n.discardChanges){let a=[];return i.hasChanges&&a.push("uncommitted changes"),i.unpushedCommits>0&&a.push(`${i.unpushedCommits} unpushed commit(s)`),{content:[{type:"text",text:`Error: worktree has ${a.join(" and ")}. Set discardChanges=true to confirm removal, or use exitAction='keep'.`}],details:{type:"worktree",error:"has_changes",hasChanges:i.hasChanges,unpushedCommits:i.unpushedCommits}}}}let r=await t.exitWorktree(o,n.discardChanges);return r.success?{content:[{type:"text",text:`Exited worktree. ${o==="keep"?"Worktree kept for later use.":"Worktree removed."}
|
|
213
|
+
Restored to: ${r.previousCwd||"main workspace"}`}],details:{type:"worktree",action:"exit",exitAction:o,previousCwd:r.previousCwd}}:{content:[{type:"text",text:`Error: ${r.error||"failed to exit worktree"}`}],details:{type:"worktree",error:r.error}}}case"list":{let o=await t.listWorktrees();if(!o.worktrees||o.worktrees.length===0)return{content:[{type:"text",text:"No worktrees (only the main working tree)."}],details:{type:"worktree",action:"list",count:0}};let r=[`Worktrees (${o.worktrees.length}):`,""];for(let s of o.worktrees){let i=s.isCurrent?" \u2190 current":"",a=s.hasChanges?" (has changes)":"";r.push(` ${s.name} [${s.branch}]${i}${a}`),r.push(` path: ${s.path}`)}return{content:[{type:"text",text:r.join(`
|
|
214
|
+
`)}],details:{type:"worktree",action:"list",count:o.worktrees.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${n.action}".`}],details:{type:"worktree",error:"unknown_action"}}}}}}import{execFile as Sp}from"node:child_process";import{promisify as wp}from"node:util";import{join as Oe,resolve as $i,basename as ko}from"node:path";import{mkdir as Cp,rm as Rp,symlink as _p,readdir as Lk,stat as Ap}from"node:fs/promises";var ot=wp(Sp),Pp=/^[a-zA-Z0-9._-]+$/,Di=64;function Mp(t){if(t.length>Di)throw new Error(`Invalid worktree name: must be ${Di} characters or fewer (got ${t.length})`);for(let e of t.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${t}": must not contain "." or ".." path segments`);if(!Pp.test(e))throw new Error(`Invalid worktree name "${t}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function Wi(t){return t.replaceAll("/","+")}function Ip(t){return`worktree-${Wi(t)}`}var ie=null;async function ae(t,e){try{let{stdout:n,stderr:o}=await ot("git",t,{cwd:e??process.cwd(),env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""},timeout:3e4});return{stdout:n,stderr:o,code:0}}catch(n){let o=n;return{stdout:o.stdout??"",stderr:o.stderr??String(n),code:o.code??1}}}async function Ni(t){let{stdout:e,code:n}=await ae(["rev-parse","--show-toplevel"],t);return n===0?e.trim():null}async function ji(t){let{stdout:e,code:n}=await ae(["status","--porcelain"],t);return n!==0?-1:e.trim().split(`
|
|
215
|
+
`).filter(Boolean).length}async function Fi(t,e){let{stdout:n,code:o}=await ae(["rev-list",`origin/${e}..${e}`,"--count"],t);return o!==0?0:parseInt(n.trim(),10)||0}async function Ep(t,e,n,o){for(let r of n){if(r.includes("..")||r.startsWith("/")||r.startsWith("\\")){o?.warn(`[worktree] skipping symlink for "${r}": path traversal detected`);continue}let s=Oe(t,r),i=Oe(e,r);try{await _p(s,i,"dir"),o?.info(`[worktree] symlinked ${r} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&o?.warn(`[worktree] failed to symlink ${r} (${l??"unknown"}): ${a}`)}}}async function Op(t,e,n){let{code:o,stderr:r}=await ae(["sparse-checkout","set","--cone","--",...n],t);if(o!==0)throw await ae(["worktree","remove","--force",t],e),new Error(`Failed to configure sparse-checkout: ${r}`);let{code:s,stderr:i}=await ae(["checkout","HEAD"],t);if(s!==0)throw await ae(["worktree","remove","--force",t],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function Lp(){try{return await ot("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function $p(t,e){return`${ko(t)}_${e}`.replace(/[/.]/g,"_")}async function Dp(t,e){if(!await Lp())return null;try{return await ot("tmux",["new-session","-d","-s",e,"-c",t],{timeout:1e4}),e}catch{return null}}async function Ui(t){try{return await ot("tmux",["kill-session","-t",t],{timeout:5e3}),!0}catch{return!1}}async function Bi(t,e,n,o){let r=Oe(e,".openclaw","hooks"),s=Oe(r,t);try{if(!(await Ap(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await ot(s,[],{cwd:e,env:{...process.env,...n},timeout:3e4});return o?.info(`[worktree] hook ${t} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return o?.warn(`[worktree] hook ${t} failed: ${i}`),null}}function Hi(t){let{log:e,symlinkDirs:n=["node_modules"],sparsePaths:o}=t;return{async enterWorktree(r){try{let s=Date.now(),i=await Ni();if(!i)return{success:!1,error:"Not in a git repository"};let a=await Bi("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let P=process.cwd();return process.chdir(a),ie={originalCwd:P,worktreePath:a,worktreeName:r??ko(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:ie.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=r??`agent-${Date.now().toString(36)}`;Mp(l);let u=Wi(l),c=Ip(l),p=Oe(i,".worktrees"),m=Oe(p,u);await Cp(p,{recursive:!0});let{stdout:g}=await ae(["worktree","list","--porcelain"],i),y=g.split(`
|
|
216
|
+
`).find(P=>P.startsWith("worktree ")&&P.includes(u));if(y){let P=y.replace("worktree ","").trim(),M=process.cwd();return process.chdir(P),ie={originalCwd:M,worktreePath:P,worktreeName:l,worktreeBranch:c},e.info(`[worktree] resumed existing worktree: ${l} at ${P}`),{success:!0,worktree:{name:l,path:P,branch:c,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=o&&o.length>0,x=["worktree","add"];f&&x.push("--no-checkout"),x.push("-B",c,m,"HEAD");let{code:b,stderr:S}=await ae(x,i);if(b!==0)return{success:!1,error:`git worktree add failed: ${S.trim()}`};let R=!1;f&&o&&(await Op(m,i,o),R=!0),await Ep(i,m,n,e);let _=process.cwd();process.chdir(m);let O=$p(i,c),G=await Dp(m,O);return ie={originalCwd:_,worktreePath:m,worktreeName:l,worktreeBranch:c,tmuxSessionName:G??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:R},e.info(`[worktree] entered: ${l} at ${m}`),{success:!0,worktree:{name:l,path:m,branch:c,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(r,s){if(!ie)return{success:!1,error:"Not in a worktree"};try{let i=ie,a=await Ni(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let l=await ji(i.worktreePath),u=await Fi(i.worktreePath,i.worktreeBranch);if((l>0||u>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${u} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),ie=null,i.tmuxSessionName&&await Ui(i.tmuxSessionName),await Bi("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let c=["worktree","remove"];s&&c.push("--force"),c.push(i.worktreePath);let{code:p,stderr:m}=await ae(c,a);p!==0&&(e.warn(`[worktree] git worktree remove failed: ${m.trim()}, cleaning up manually`),await Rp(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await ae(["worktree","prune"],a)),await ae(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await Ui(i.tmuxSessionName),ie=null,e.info(`[worktree] exited (kept): ${i.worktreeName}`);return{success:!0,previousCwd:i.originalCwd}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}},async listWorktrees(){try{let{stdout:r,code:s}=await ae(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=r.split(`
|
|
217
|
+
|
|
218
|
+
`).filter(Boolean);for(let u of l){let c=u.split(`
|
|
219
|
+
`),p="",m="";for(let x of c)x.startsWith("worktree ")&&(p=x.slice(9).trim()),x.startsWith("branch ")&&(m=x.slice(7).trim().replace("refs/heads/",""));if(!p)continue;let g=$i(p)===$i(a),y=await ji(p),f=await Fi(p,m);i.push({name:m.startsWith("worktree-")?m.slice(9):ko(p),path:p,branch:m,isCurrent:g,hasChanges:y>0,unpushedCommits:f})}return{success:!0,worktrees:i}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}},isInWorktree(){return ie!==null},currentWorktree(){return ie?{name:ie.worktreeName,path:ie.worktreePath,branch:ie.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as Np,writeFile as jp}from"node:fs/promises";import*as qi from"node:path";var Fp={type:"object",properties:{notebook_path:{type:"string",description:"Absolute path to the .ipynb notebook file."},cell_number:{type:"number",description:"1-based cell number to operate on. For 'insert', the new cell is inserted after this cell (use 0 to insert at the beginning)."},new_source:{type:"string",description:"New cell content. Required for 'replace' and 'insert' modes."},cell_type:{type:"string",enum:["code","markdown"],description:"Cell type for 'insert' mode. Default: 'code'."},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"Edit operation: replace (default), insert (after cell_number), or delete."}},required:["notebook_path","cell_number"]};function zi(t){let e=t.split(`
|
|
220
|
+
`);return e.map((n,o)=>o<e.length-1?n+`
|
|
221
|
+
`:n)}function Gi(t){return t.join("")}function Up(t,e){let n=Gi(t.source).trim(),o=n.length>80?n.slice(0,80)+"...":n;return`Cell ${e+1} [${t.cell_type}]: ${o}`}function Bp(t,e){let n={cell_type:t,source:zi(e),metadata:{}};return t==="code"&&(n.execution_count=null,n.outputs=[]),n}function Ki(){return{name:"notebook_edit",label:"Notebook Edit",description:"Edit Jupyter notebook (.ipynb) files at the cell level. Supports replacing cell content, inserting new cells, and deleting cells. Operates on the notebook's JSON structure directly.",parameters:Fp,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"jupyter notebook ipynb cell edit insert delete",execute:async(t,e)=>{let{notebook_path:n,cell_number:o,edit_mode:r="replace"}=e,s=qi.extname(n).toLowerCase();if(s!==".ipynb")return{content:[{type:"text",text:`Error: File must be a .ipynb notebook. Got: ${s}`}],details:{error:"invalid_extension"}};let i;try{i=await Np(n,"utf-8")}catch(g){return{content:[{type:"text",text:`Error reading notebook: ${g.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let l=a.cells.length,u=o-1;if(r==="insert"){if(o<0||o>l)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(u<0||u>=l)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let c;switch(r){case"replace":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'replace' mode."}],details:{error:"missing_source"}};let g=a.cells[u],y=Gi(g.source);g.source=zi(e.new_source),g.cell_type==="code"&&(g.execution_count=null,g.outputs=[]),c=`Replaced cell ${o} [${g.cell_type}].
|
|
222
|
+
Old: ${y.slice(0,120)}${y.length>120?"...":""}
|
|
223
|
+
New: ${e.new_source.slice(0,120)}${e.new_source.length>120?"...":""}`;break}case"insert":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'insert' mode."}],details:{error:"missing_source"}};let g=e.cell_type??"code",y=Bp(g,e.new_source);a.cells.splice(o,0,y),c=`Inserted new ${g} cell after position ${o}. Total cells: ${a.cells.length}.`;break}case"delete":{let g=a.cells.splice(u,1)[0];c=`Deleted cell ${o} [${g.cell_type}]. Remaining: ${a.cells.length} cells.`;break}default:return{content:[{type:"text",text:`Error: unknown edit_mode "${r}". Use replace, insert, or delete.`}],details:{error:"unknown_mode"}}}try{let g=JSON.stringify(a,null,1)+`
|
|
224
|
+
`;await jp(n,g,"utf-8")}catch(g){return{content:[{type:"text",text:`Error writing notebook: ${g.message}`}],details:{error:"write_failed"}}}let p=a.cells.slice(0,10).map((g,y)=>Up(g,y)).join(`
|
|
225
|
+
`),m=a.cells.length>10?`
|
|
226
|
+
... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${c}
|
|
227
|
+
|
|
228
|
+
Current cells:
|
|
229
|
+
${p}${m}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:o,total_cells:a.cells.length}}}}}import{readFile as Wp,readdir as Hp}from"node:fs/promises";import*as Dt from"node:path";import{homedir as qp}from"node:os";import{existsSync as zp}from"node:fs";var Gp={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
|
|
230
|
+
run: Execute a workflow by name.
|
|
231
|
+
describe: Show workflow steps and variables.`},workflow:{type:"string",description:"Workflow name (required for 'run' and 'describe')."},variables:{type:"object",description:"Variable overrides (key-value pairs) for the workflow run.",additionalProperties:{type:"string"}}},required:["action"]};async function To(t){let e=new Map,n=Dt.join(t,".openclaw","workflows");await Vi(n,e);let o=Dt.join(qp(),".openclaw","workflows");return await Vi(o,e),e}async function Vi(t,e){if(zp(t))try{let n=await Hp(t,{withFileTypes:!0});for(let o of n)if(o.isFile()&&o.name.endsWith(".json")){let r=o.name.replace(/\.json$/,"");e.has(r)||e.set(r,Dt.join(t,o.name))}}catch{}}async function xo(t){let e=await Wp(t,"utf-8");return JSON.parse(e)}function Kp(t){let e=new Map(t.map(s=>[s.id,s])),n=new Set,o=[];function r(s,i){if(n.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected at step: ${s}`);i.add(s);let a=e.get(s);if(!a)throw new Error(`Unknown step dependency: ${s}`);for(let l of a.dependsOn??[])r(l,i);i.delete(s),n.add(s),o.push(a)}for(let s of t)r(s.id,new Set);return o}function Vp(t,e,n){let o={};for(let[r,s]of Object.entries(t))if(typeof s=="string"){let i=s;i=i.replace(/\$\{var\.(\w+)\}/g,(a,l)=>e[l]??`\${var.${l}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,l)=>n.get(l)?.output??""),o[r]=i}else o[r]=s;return o}function Ji(t){return{name:"workflow",label:"Workflow",description:"Execute predefined automation workflows. Workflows are step-based pipelines defined as JSON files in .openclaw/workflows/ or ~/.openclaw/workflows/. Steps run in dependency order, support variable interpolation, and can reference previous step outputs via ${step.<id>.result}.",parameters:Gp,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"workflow pipeline automation steps DAG",execute:async(e,n,o)=>{let r=t.getCwd();switch(n.action){case"list":{let s=await To(r);if(s.size===0)return{content:[{type:"text",text:"No workflows found. Create .json files in .openclaw/workflows/ or ~/.openclaw/workflows/."}],details:{type:"workflow",action:"list",count:0}};let i=["Available workflows:"];for(let[a,l]of s)try{let u=await xo(l);i.push(` - ${a}: ${u.description??"(no description)"} (${u.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
|
|
232
|
+
`)}],details:{type:"workflow",action:"list",count:s.size}}}case"describe":{if(!n.workflow)return{content:[{type:"text",text:"Error: 'workflow' parameter is required for 'describe'."}],details:{error:"missing_workflow"}};let i=(await To(r)).get(n.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${n.workflow}" not found.`}],details:{error:"not_found"}};let a=await xo(i),l=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let u of a.steps){let c=u.dependsOn?.length?` (after: ${u.dependsOn.join(", ")})`:"";l.push(` ${u.id}: ${u.label??u.tool}${c}`),l.push(` tool: ${u.tool}`),l.push(` args: ${JSON.stringify(u.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){l.push("","Variables (defaults):");for(let[u,c]of Object.entries(a.variables))l.push(` ${u} = ${c}`)}return{content:[{type:"text",text:l.filter(Boolean).join(`
|
|
233
|
+
`)}],details:{type:"workflow",action:"describe",workflow:a.name}}}case"run":{if(!n.workflow)return{content:[{type:"text",text:"Error: 'workflow' parameter is required for 'run'."}],details:{error:"missing_workflow"}};let i=(await To(r)).get(n.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${n.workflow}" not found.`}],details:{error:"not_found"}};let a=await xo(i),l={...a.variables,...n.variables},u;try{u=Kp(a.steps)}catch(g){return{content:[{type:"text",text:`Error: ${g.message}`}],details:{error:"dag_error"}}}let c=new Map,p=[`Running workflow: ${a.name}`,""],m=!0;for(let g of u){if(o?.aborted){p.push(`\u26A1 Aborted at step: ${g.id}`),m=!1;break}let y=(g.dependsOn??[]).some(b=>!c.get(b)?.success),f=g.condition??"on_success";if(f==="on_success"&&y){p.push(`\u23ED Skipped ${g.id} (dependency failed)`),c.set(g.id,{stepId:g.id,success:!1,output:"",error:"dependency_failed"}),m=!1;continue}if(f==="on_failure"&&!y){p.push(`\u23ED Skipped ${g.id} (no failure to handle)`),c.set(g.id,{stepId:g.id,success:!0,output:""});continue}p.push(`\u25B6 ${g.id}: ${g.label??g.tool}`);let x=Vp(g.args,l,c);try{let b=await t.invokeTool(g.tool,x,o),S=!b.error;if(c.set(g.id,{stepId:g.id,success:S,output:b.result,error:b.error}),S){let R=b.result.length>200?b.result.slice(0,200)+"...":b.result;p.push(` \u2705 ${R}`)}else p.push(` \u274C ${b.error}`),m=!1}catch(b){let S=b.message;c.set(g.id,{stepId:g.id,success:!1,output:"",error:S}),p.push(` \u274C ${S}`),m=!1}}return p.push("",m?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:p.join(`
|
|
234
|
+
`)}],details:{type:"workflow",action:"run",workflow:a.name,success:m,stepsExecuted:c.size,totalSteps:a.steps.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${n.action}". Use list, run, or describe.`}],details:{error:"unknown_action"}}}}}}var Jp="sleep",Yp={type:"object",properties:{duration:{type:"number",description:"Duration to sleep in seconds (1\u20133600). Prefer short sleeps (10\u201360s) to stay responsive.",minimum:1,maximum:3600},reason:{type:"string",description:'Brief reason for sleeping. Examples: "waiting for build to finish", "nothing to do", "user asked to rest".'}},required:["duration"]};function Yi(t){return{name:Jp,label:"Sleep",shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"wait sleep rest idle tick proactive",description:["Wait for a specified duration. The user can interrupt the sleep at any time.","","Use this when:","\u2022 You have nothing useful to do right now","\u2022 You're waiting for an external process to complete","\u2022 The user tells you to sleep or rest","\u2022 You receive a <tick> check-in with no actionable work","","Prefer this over `exec(sleep ...)` \u2014 it doesn't hold a shell process.","You can call this concurrently with other tools \u2014 it won't interfere with them.","","Each wake-up costs an API call, but the prompt cache expires after 5 minutes of inactivity \u2014 balance accordingly."].join(`
|
|
235
|
+
`),parameters:Yp,execute:async(e,n,o)=>{let r=Math.max(1,Math.min(3600,Math.round(n.duration))),s=r*1e3,i=new AbortController,a=()=>i.abort();o?.addEventListener("abort",a,{once:!0}),o?.aborted&&i.abort();try{let l=await t.sleep(s,i.signal),u=[];return l.interrupted?(u.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&u.push(`Reason: ${l.interruptReason}`),u.push("Check for new messages or tasks.")):u.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:u.join(`
|
|
236
|
+
`)}],details:{...l,requestedSeconds:r}}}finally{o?.removeEventListener("abort",a)}}}}var Xp="tool_search",Zp={type:"object",properties:{query:{type:"string",description:'Search query for tools. Use "select:toolName" to directly activate a deferred tool, or provide keywords to search tool names/descriptions. Prefix a term with "+" to mark it as required (all +terms must match).'},maxResults:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},Qp=5;function Zi(t){return{name:Xp,label:"Tool Search",description:'Search for available tools that are not currently loaded. Many tools are deferred to save context tokens. Use "select:toolName" to directly activate a tool, or provide keywords to find relevant tools. Activated tools become available in subsequent messages.',parameters:Zp,execute:async(e,n)=>{if(!n.query||n.query.trim().length===0)return{content:[{type:"text",text:"Error: query is required."}],details:{type:"tool_search",error:"empty_query"}};let o=n.query.trim(),r=n.maxResults??Qp;if(o.startsWith("select:")){let i=o.slice(7).split(",").map(c=>c.trim()).filter(Boolean),a=[],l=[];if(t.activateTool)for(let c of i)await t.activateTool(c)?a.push(c):l.push(c);else{let c=await t.searchTools(o,{maxResults:r});return Xi(c)}let u=[];return a.length>0&&u.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&u.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:u.join(`
|
|
237
|
+
`)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await t.searchTools(o,{maxResults:r});return Xi(s)}}}function Xi(t){if(t.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${t.query}". Total deferred tools available: ${t.totalDeferred}.`}],details:{type:"tool_search",query:t.query,matchCount:0,totalDeferred:t.totalDeferred}};let e=[`Found ${t.matches.length} tool(s) matching "${t.query}" (${t.totalDeferred} total deferred):`,""];for(let n of t.matches)e.push(`- **${n.name}**: ${n.description}`);return e.push(""),e.push('Use "select:toolName" to activate a tool for use in subsequent messages.'),{content:[{type:"text",text:e.join(`
|
|
238
|
+
`)}],details:{type:"tool_search",query:t.query,matchCount:t.matches.length,totalDeferred:t.totalDeferred,matches:t.matches.map(n=>n.name)}}}var Ce=process.cwd();function oe(t){return L.isAbsolute(t)?L.normalize(t):L.resolve(Ce,t)}var tm=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),ea=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]);function nm(){return{resolvePath:oe,async readFile(t){let e=oe(t),n=L.extname(e).toLowerCase();if(ea.has(n))return{type:"binary",mimeType:"application/octet-stream"};if(tm.has(n)){let r=await I.promises.readFile(e),s=n===".png"?"image/png":n===".svg"?"image/svg+xml":n===".gif"?"image/gif":n===".webp"?"image/webp":"image/jpeg";return{type:"image",base64:r.toString("base64"),mimeType:s}}return{type:"text",text:await I.promises.readFile(e,"utf8")}},validatePath(t){let e=oe(t);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function om(){return{resolvePath:oe,async writeFile(t,e){let n=oe(t);await I.promises.mkdir(L.dirname(n),{recursive:!0}),await I.promises.writeFile(n,e,"utf8")}}}function rm(){return{resolvePath:oe,async readFile(t){let e=oe(t);return I.promises.readFile(e,"utf8")},async writeFile(t,e){let n=oe(t);await I.promises.mkdir(L.dirname(n),{recursive:!0}),await I.promises.writeFile(n,e,"utf8")}}}function sm(){return{resolvePath:oe,async readFile(t){let e=oe(t);return I.promises.readFile(e,"utf8")},async writeFile(t,e){let n=oe(t);await I.promises.mkdir(L.dirname(n),{recursive:!0}),await I.promises.writeFile(n,e,"utf8")},async deleteFile(t){let e=oe(t);await I.promises.unlink(e)},async fileExists(t){let e=oe(t);try{return await I.promises.access(e),!0}catch{return!1}}}}function im(){return{resolvePath:oe,async glob(t,e){let n=e.cwd||Ce,o=e.limit||1e3,r=[],s=!1,i=t.replace(/\\/g,"/").split("/"),a=i.some(c=>c==="**"),l=i[i.length-1]??"*",u=ta(l);try{await vo(n,async c=>{if(r.length>=o)return s=!0,!1;let p=L.basename(c);return u.test(p)&&r.push(c),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(t,e){let n=e.cwd||Ce;try{return await lm(t,n,e)}catch{return await cm(t,n,e)}}}}function ta(t){let e=t.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(n,o)=>"("+o.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var am=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function vo(t,e,n,o=0,r=""){if(o>n)return;let s;try{s=await I.promises.readdir(t,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(am.has(i.name))continue;await vo(L.join(t,i.name),e,n,o+1,a)}else if(i.isFile()&&!await e(a))return}}function lm(t,e,n){return new Promise((o,r)=>{let s=["--json","--no-heading","--max-columns","500"];n.caseInsensitive&&s.push("-i"),n.contextLines&&s.push("-C",String(n.contextLines)),n.fileGlob&&s.push("-g",n.fileGlob),s.push("--max-count",String(n.headLimit??250)),s.push(t),s.push("."),em("rg",s,{cwd:e,maxBuffer:10*1024*1024,timeout:3e4},(i,a)=>{if(i&&!("killed"in i&&i.killed)&&i.code!==1){r(i);return}let l=[];for(let m of a.split(`
|
|
239
|
+
`))if(m.trim())try{let g=JSON.parse(m);g.type==="match"&&g.data&&l.push({path:g.data.path?.text??"",line:g.data.line_number??0,text:(g.data.lines?.text??"").trimEnd()})}catch{}let u=n.headLimit??250,c=n.offset??0,p=l.slice(c,c+u);o({matches:p,truncated:l.length>c+u})})})}async function cm(t,e,n){let o=new RegExp(t,n.caseInsensitive?"i":""),r=n.headLimit??250,s=n.offset??0,i=n.fileGlob?ta(n.fileGlob):null,a=[],l=!1;return await vo(e,async u=>{if(a.length>=s+r+1)return l=!0,!1;if(i&&!i.test(L.basename(u)))return!0;let c=L.extname(u).toLowerCase();if(ea.has(c))return!0;try{let m=(await I.promises.readFile(L.join(e,u),"utf8")).split(`
|
|
240
|
+
`);for(let g=0;g<m.length;g++)if(o.test(m[g])&&(a.push({path:u,line:g+1,text:m[g].slice(0,500)}),a.length>=s+r+1))return l=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+r),truncated:l}}var Qi=!1;function um(){if(!Qi)if(Qi=!0,At()){let t=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";nt(mo(t))}else if(process.platform==="win32"){let t=dm();nt($t(t))}else{let t=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";nt($t(t))}}function dm(){let t=process.env.QLOGICAGENT_BASH_PATH;if(t&&I.existsSync(t))return t;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],n=process.env.ProgramFiles?L.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;n&&!e.includes(n)&&e.unshift(n);for(let o of e)if(I.existsSync(o))return o;return"bash"}function pm(){return{async fetchUrl(t){let e=new AbortController,n=setTimeout(()=>e.abort(),3e4);try{let o=await fetch(t.url,{signal:e.signal,headers:{"User-Agent":"Mozilla/5.0 (compatible; QLogicAgent/1.0)",Accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow"});if(!o.ok)return{content:`HTTP ${o.status} ${o.statusText}`};let r=o.headers.get("content-type")??"",s=await o.text();return t.maxChars&&s.length>t.maxChars&&(s=s.slice(0,t.maxChars)),r.includes("html")&&t.extractMode!=="json"&&(s=mm(s)),{content:s,title:gm(s)}}finally{clearTimeout(n)}}}}function mm(t){return t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s{2,}/g," ").trim()}function gm(t){return t.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function fm(){return{async search(t,e){let n=process.env.SEARXNG_BASE_URL?.trim();if(!n)return{query:t,results:[],totalResults:0};let o=e?.maxResults??10,r=new URL("/search",n);r.searchParams.set("q",t),r.searchParams.set("format","json"),r.searchParams.set("pageno","1");let s=new AbortController,i=setTimeout(()=>s.abort(),15e3);try{let a=await fetch(r.toString(),{signal:s.signal,headers:{Accept:"application/json"}});if(!a.ok)return{query:t,results:[]};let l=await a.json(),u=(l.results??[]).slice(0,o).map(c=>({title:c.title??"",url:c.url??"",snippet:c.content??""}));if(e?.allowedDomains?.length){let c=new Set(e.allowedDomains.map(p=>p.toLowerCase()));return{query:t,results:u.filter(p=>{try{return c.has(new URL(p.url).hostname.toLowerCase())}catch{return!1}})}}if(e?.blockedDomains?.length){let c=new Set(e.blockedDomains.map(p=>p.toLowerCase()));return{query:t,results:u.filter(p=>{try{return!c.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:t,results:u,totalResults:l.number_of_results}}finally{clearTimeout(i)}}}}function hm(){let t=L.join(process.env.HOME??process.env.USERPROFILE??".",".openclaw");function e(r){return L.join(t,"projects",r,".instructions")}function n(r,s){if(!s.endsWith(".md"))throw new Error("Filename must end with .md");if(s.includes(".."))throw new Error("Path traversal not allowed");let i=e(r),a=L.resolve(i,s);if(!a.startsWith(i+L.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function o(r,s){if(!I.existsSync(r))return[];let i=[];for(let a of I.readdirSync(r,{withFileTypes:!0})){let l=L.join(r,a.name);if(a.isDirectory())i.push(...o(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let u=I.statSync(l);i.push({filename:L.relative(s,l).replace(/\\/g,"/"),path:l,size:u.size,updatedAt:u.mtime.toISOString(),content:I.readFileSync(l,"utf-8")})}}return i}return{list(r){let s=e(r);return o(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(r,s){try{let i=n(r,s);if(!I.existsSync(i))return null;let a=I.statSync(i),l=I.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:l}}catch{return null}},write(r,s,i){let a=n(r,s);I.mkdirSync(L.dirname(a),{recursive:!0}),I.writeFileSync(a,i,"utf-8");let l=I.statSync(a);return{filename:s,path:a,size:l.size,updatedAt:l.mtime.toISOString(),content:i}},remove(r,s){try{let i=n(r,s);return I.existsSync(i)?(I.unlinkSync(i),!0):!1}catch{return!1}}}}function na(t){t?.workdir&&(Ce=t.workdir),um(),co(Ce);let e=new _t;e.register(Ks()),e.register(Js()),e.register(ci({onProgress:t?.onExecProgress,interpretExitCode:(u,c)=>{if(u===127)return"command not found";if(u===126)return"permission denied";if(u===137)return"killed (SIGKILL / OOM)";if(u===143)return"terminated (SIGTERM)";if(u===130)return"interrupted (Ctrl+C)"}}));let n=nm(),o=om(),r=rm(),s=sm();e.register(pi(n)),e.register(gi(o)),e.register(fi(r)),e.register(bo(s)),e.register(ki(s)),e.register(bi(im())),e.register(Ai(pm())),e.register(Pi(fm()));let i=hm();e.register(Mi(i)),e.register(Ii(i)),e.register(Ei(i)),e.register(Oi(i));let a=t?.log??{info:()=>{},warn:()=>{}};e.register(Li(Hi({log:a}))),e.register(Ki());let l={invokeTool:async(u,c,p)=>{let m=e.findTool(u);if(!m)return{result:"",error:`Unknown tool: ${u}`};try{let g=await m.execute(`wf_${Date.now()}`,c,p);return{result:g.content.map(f=>f.text??"").join(`
|
|
241
|
+
`),error:g.details?.error}}catch(g){return{result:"",error:g.message}}},getCwd:()=>Ce};return e.register(Ji(l)),e.register(Yi({sleep:(u,c)=>new Promise(p=>{let m=Date.now(),g=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!1})},u),y=()=>{clearTimeout(g),p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!0,interruptReason:"aborted"})};c.addEventListener("abort",y,{once:!0}),c.aborted&&(clearTimeout(g),y())})})),e.register(Zi({searchTools:async(u,c)=>{let p=c?.maxResults??5,m=u.toLowerCase(),g=e.getToolNames();return{matches:g.map(f=>{let x=e.findTool(f),b=`${f} ${x?.description??""} ${x?.searchHint??""}`.toLowerCase();return{name:f,description:x?.description??"",searchHint:x?.searchHint,score:b.includes(m)?1:0}}).filter(f=>f.score>0).slice(0,p),query:u,totalDeferred:g.length}}})),t?.log?.info(`[tool-bootstrap] Registered ${e.size} local tools: ${e.getToolNames().join(", ")}`),e}function oa(t){Ce=t}import{spawn as ym}from"node:child_process";import{createInterface as bm}from"node:readline";var Nt=class{process=null;readline=null;pending=new Map;nextId=1;connected=!1;toolsCache=[];serverName="";serverVersion="";supportsToolsListChanged=!1;onToolsChanged=null;stderrBuffer="";config;constructor(e){this.config=e}async connect(){if(this.connected)return;let e={...process.env,...this.config.env};this.process=ym(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:e,cwd:this.config.cwd,windowsHide:!0}),this.process.on("error",o=>{this.handleProcessError(o)}),this.process.on("exit",o=>{this.handleProcessExit(o)}),this.process.stderr?.on("data",o=>{this.stderrBuffer+=o.toString(),this.stderrBuffer.length>4096&&(this.stderrBuffer=this.stderrBuffer.slice(-4096))}),this.readline=bm({input:this.process.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.readline.on("line",o=>this.handleLine(o));let n=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"qlogicagent",version:"0.3.0"}},this.config.initTimeoutMs??3e4);this.serverName=n.serverInfo?.name??this.config.name,this.serverVersion=n.serverInfo?.version??"unknown",this.supportsToolsListChanged=n.capabilities?.tools?.listChanged??!1,this.sendNotification("notifications/initialized",{}),this.connected=!0,await this.refreshTools()}async disconnect(){if(this.connected){this.connected=!1;for(let[,e]of this.pending)e.reject(new Error("MCP client disconnecting"));if(this.pending.clear(),this.toolsCache=[],this.readline?.close(),this.readline=null,this.process){this.process.kill("SIGTERM");let e=setTimeout(()=>this.process?.kill("SIGKILL"),5e3);this.process.on("exit",()=>clearTimeout(e)),this.process=null}}}get isConnected(){return this.connected}get info(){return{name:this.serverName,version:this.serverVersion}}async refreshTools(){if(!this.connected)return[];try{let e=await this.sendRequest("tools/list",{});this.toolsCache=e.tools??[]}catch{this.toolsCache=[]}return this.toolsCache}getCachedTools(){return this.toolsCache}async callTool(e,n,o){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:n??{}},12e4,o)}async listResources(){if(!this.connected)return[];try{return(await this.sendRequest("resources/list",{})).resources??[]}catch{return[]}}async readResource(e){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return(await this.sendRequest("resources/read",{uri:e})).contents??[]}toPortableTools(){let e=km(this.config.name);return this.toolsCache.map(n=>({name:`mcp__${e}__${n.name}`,label:`[${this.config.name}] ${n.name}`,description:n.description??`MCP tool from ${this.config.name}`,parameters:n.inputSchema??{type:"object",properties:{}},isConcurrencySafe:!0,isReadOnly:!1,searchHint:`mcp ${this.config.name} ${n.name}`,execute:async(o,r,s)=>this.executeAsTool(n.name,r,s)}))}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,n,o){try{let r=await this.callTool(e,n,o);return{content:[{type:"text",text:r.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
|
|
242
|
+
`)||"(no text output)"}],...r.isError?{details:{error:"mcp_tool_error"}}:{}}}catch(r){let s=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`MCP tool error: ${s}`}],details:{error:s}}}}sendRequest(e,n,o=3e4,r){return new Promise((s,i)=>{if(r?.aborted){i(new Error("Aborted"));return}let a=this.nextId++,l={jsonrpc:"2.0",id:a,method:e,params:n},u=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${o}ms`))},o),c=()=>{clearTimeout(u),this.pending.delete(a)};r?.addEventListener("abort",()=>{c(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:p=>{c(),p.error?i(new Error(`MCP error ${p.error.code}: ${p.error.message}`)):s(p.result)},reject:p=>{c(),i(p)}}),this.writeLine(JSON.stringify(l))})}sendNotification(e,n){let o={jsonrpc:"2.0",method:e,params:n};this.writeLine(JSON.stringify(o))}writeLine(e){this.process?.stdin?.writable&&this.process.stdin.write(e+`
|
|
243
|
+
`)}handleLine(e){let n=e.trim();if(!n)return;let o;try{o=JSON.parse(n)}catch{return}if("id"in o&&("result"in o||"error"in o)){let r=o.id,s=this.pending.get(r);s&&s.resolve(o)}else"method"in o&&!("id"in o)&&this.handleNotification(o)}handleNotification(e){e.method==="notifications/tools/list_changed"&&this.refreshTools().then(()=>{this.onToolsChanged?.()}).catch(()=>{})}handleProcessError(e){this.connected=!1;for(let[,n]of this.pending)n.reject(new Error(`MCP process error: ${e.message}`));this.pending.clear()}handleProcessExit(e){this.connected=!1;for(let[,n]of this.pending)n.reject(new Error(`MCP process exited with code ${e}`));this.pending.clear()}};function km(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as Tm}from"node:crypto";var jt=class{connected=!1;toolsCache=[];serverName="";serverVersion="";sessionId=null;onToolsChanged=null;config;constructor(e){this.config=e}async connect(){if(this.connected)return;let e=await this.sendRequest("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"qlogicagent",version:"0.3.0"}},this.config.initTimeoutMs??3e4);this.serverName=e.serverInfo?.name??this.config.name,this.serverVersion=e.serverInfo?.version??"unknown",await this.sendNotification("notifications/initialized",{}),this.connected=!0,await this.refreshTools()}async disconnect(){this.connected=!1,this.toolsCache=[],this.sessionId=null}async callTool(e,n,o){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:n??{}},this.config.toolCallTimeoutMs??12e4,o)}async listResources(){if(!this.connected)return[];try{return(await this.sendRequest("resources/list",{})).resources??[]}catch{return[]}}async readResource(e){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return(await this.sendRequest("resources/read",{uri:e})).contents??[]}toPortableTools(){return this.toolsCache.map(e=>this.schemaToPortableTool(e))}getCachedTools(){return[...this.toolsCache]}get isConnected(){return this.connected}get info(){return{name:this.serverName,version:this.serverVersion}}setOnToolsChanged(e){this.onToolsChanged=e}async refreshTools(){let e=await this.sendRequest("tools/list",{});this.toolsCache=e.tools??[]}async sendRequest(e,n,o=3e4,r){let s=Tm(),i={jsonrpc:"2.0",id:s,method:e,params:n},a=new AbortController,l=setTimeout(()=>a.abort(),o);r&&r.addEventListener("abort",()=>a.abort(),{once:!0});try{let u={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(u["Mcp-Session-Id"]=this.sessionId);let c=await fetch(this.config.url,{method:"POST",headers:u,body:JSON.stringify(i),signal:a.signal}),p=c.headers.get("mcp-session-id");if(p&&(this.sessionId=p),!c.ok)throw new Error(`MCP HTTP error ${c.status}: ${c.statusText}`);if((c.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(c,s);let g=await c.json();if(g.error)throw new Error(`MCP error ${g.error.code}: ${g.error.message}`);return g.result}finally{clearTimeout(l)}}async sendNotification(e,n){let o={jsonrpc:"2.0",method:e,params:n},r={"Content-Type":"application/json",...this.config.headers};this.sessionId&&(r["Mcp-Session-Id"]=this.sessionId),await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(o)}).catch(()=>{})}async parseSSEResponse(e,n){let o=e.body;if(!o)throw new Error("MCP SSE response has no body");let r=o.getReader(),s=new TextDecoder,i="";try{for(;;){let{done:a,value:l}=await r.read();if(a)break;i+=s.decode(l,{stream:!0});let u=i.split(`
|
|
244
|
+
`);i=u.pop()??"";for(let c of u){if(!c.startsWith("data: "))continue;let p=c.slice(6).trim();if(p)try{let m=JSON.parse(p);if("method"in m&&m.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(m.id===n){if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}}catch(m){if(m instanceof Error&&m.message.startsWith("MCP error"))throw m}}}}finally{r.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let n=this;return{name:`mcp__${xm(this.config.name)}__${e.name}`,label:`[${this.config.name}] ${e.name}`,description:e.description??`MCP tool from ${this.config.name}`,parameters:e.inputSchema??{type:"object",properties:{}},isConcurrencySafe:!0,isReadOnly:!1,searchHint:`mcp ${this.config.name} ${e.name}`,execute:async(r,s,i)=>{try{let a=await n.callTool(e.name,s,i);return{content:[{type:"text",text:(a.content??[]).filter(c=>c.type==="text"&&c.text).map(c=>c.text).join(`
|
|
245
|
+
`)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function xm(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Ft=class{clients=new Map;registry=null;log;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}};for(let n of e.servers){if(n.disabled)continue;if((n.type??(n.url?"http":"stdio"))==="http"){if(!n.url){this.log.warn(`[mcp] server "${n.name}" is type "http" but has no url, skipping`);continue}let r={name:n.name,url:n.url,headers:n.headers,initTimeoutMs:n.initTimeoutMs};this.clients.set(n.name,new jt(r))}else{if(!n.command){this.log.warn(`[mcp] server "${n.name}" is type "stdio" but has no command, skipping`);continue}let r={name:n.name,command:n.command,args:n.args,env:n.env,initTimeoutMs:n.initTimeoutMs};this.clients.set(n.name,new Nt(r))}}}async connectAll(){let e=Array.from(this.clients.entries()).map(async([n,o])=>{try{await o.connect(),this.log.info(`[mcp] connected to ${n} (${o.info.name} v${o.info.version})`),o.setOnToolsChanged(()=>{this.log.info(`[mcp] tools changed on ${n}, re-injecting`),this.registry&&this.reinjectTools(n,o)})}catch(r){this.log.warn(`[mcp] failed to connect to ${n}: ${r instanceof Error?r.message:r}`)}});await Promise.allSettled(e)}injectTools(e){this.registry=e;for(let[n,o]of this.clients){if(!o.isConnected)continue;let r=o.toPortableTools();e.registerAll(r),this.log.info(`[mcp] injected ${r.length} tools from ${n}`)}}getConnectedServers(){return Array.from(this.clients.entries()).filter(([,e])=>e.isConnected).map(([e])=>e)}getToolCount(){let e=0;for(let n of this.clients.values())n.isConnected&&(e+=n.getCachedTools().length);return e}async disconnectAll(){let e=Array.from(this.clients.values()).map(async n=>{try{await n.disconnect()}catch{}});await Promise.allSettled(e),this.clients.clear(),this.registry=null}async listResources(e){let n=e?[[e,this.clients.get(e)]].filter(([,r])=>r):Array.from(this.clients.entries());return(await Promise.all(n.map(async([r,s])=>{if(!s?.isConnected||!s.listResources)return[];try{return(await s.listResources()).map(a=>({...a,server:r}))}catch{return this.log.warn(`[mcp] failed to list resources from ${r}`),[]}}))).flat()}async readResource(e,n){let o=this.clients.get(e);if(!o?.isConnected)throw new Error(`MCP server "${e}" is not connected`);if(!o.readResource)throw new Error(`MCP server "${e}" does not support resources`);return o.readResource(n)}reinjectTools(e,n){if(!this.registry)return;let o=`mcp__${e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;for(let s of this.registry.getToolNames())s.startsWith(o)&&this.registry.unregister(s);let r=n.toPortableTools();this.registry.registerAll(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function So(t){if(!t||typeof t!="object")return[];let e=t,n=[],o=e.mcpServers??e.servers??e;for(let[r,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){n.push({name:r,type:"http",url:i.url,headers:i.headers&&typeof i.headers=="object"?i.headers:void 0,disabled:i.disabled===!0,initTimeoutMs:typeof i.initTimeoutMs=="number"?i.initTimeoutMs:void 0});continue}typeof i.command=="string"&&n.push({name:r,type:"stdio",command:i.command,args:Array.isArray(i.args)?i.args:void 0,env:i.env&&typeof i.env=="object"?i.env:void 0,disabled:i.disabled===!0})}return n}var vm={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function ra(t){return{name:"list_mcp_resources",label:"List MCP Resources",description:"List resources available from connected MCP servers. Resources are data items (files, database records, API data) exposed by MCP servers that can be read with read_mcp_resource.",parameters:vm,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,n)=>{let o=t();if(!o)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let r=await o.listResources(n.server);if(r.length===0)return{content:[{type:"text",text:n.server?`No resources found from MCP server "${n.server}".`:"No resources found from any connected MCP server."}],details:{type:"list_mcp_resources",count:0}};let s=new Map;for(let a of r){let l=s.get(a.server)??[];l.push(a),s.set(a.server,l)}let i=[];for(let[a,l]of s){i.push(`Server: ${a} (${l.length} resources)`);for(let u of l){let c=u.mimeType?` [${u.mimeType}]`:"",p=u.description?` \u2014 ${u.description}`:"";i.push(` ${u.name}: ${u.uri}${c}${p}`)}i.push("")}return{content:[{type:"text",text:i.join(`
|
|
246
|
+
`).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var Sm={type:"object",properties:{server:{type:"string",description:"Name of the MCP server that hosts the resource."},uri:{type:"string",description:"URI of the resource to read (from list_mcp_resources output)."}},required:["server","uri"]};function sa(t){return{name:"read_mcp_resource",label:"Read MCP Resource",description:"Read a specific resource from an MCP server by URI. Returns the resource content (text or binary metadata). Use list_mcp_resources first to discover available URIs.",parameters:Sm,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,n)=>{let o=t();if(!o)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let r=await o.readResource(n.server,n.uri);if(r.length===0)return{content:[{type:"text",text:`Resource "${n.uri}" returned no content.`}],details:{type:"read_mcp_resource",empty:!0}};let s=[];for(let i of r)if(i.text){let a=i.mimeType?` (${i.mimeType})`:"";s.push({type:"text",text:`--- ${i.uri}${a} ---
|
|
247
|
+
${i.text}`})}else if(i.blob){let a=Math.ceil(i.blob.length*3/4/1024);s.push({type:"text",text:`--- ${i.uri} (binary, ~${a}KB, ${i.mimeType??"unknown"}) ---
|
|
248
|
+
[Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${n.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:n.uri,server:n.server,contentCount:r.length}}}catch(r){return{content:[{type:"text",text:`Error reading resource: ${r.message}`}],details:{error:r.message}}}}}}import*as ye from"node:fs";import*as Ut from"node:path";import{pathToFileURL as wm}from"node:url";var ia={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var Bt=class{constructor(e){this.config=e;this.log=e.log??{info:()=>{},warn:()=>{}}}config;loaded=[];pluginSkills=[];activations=new Map;log;async loadAll(){for(let e of this.config.pluginDirs){if(!ye.existsSync(e))continue;let n;try{n=ye.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let o of n){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let r=Ut.join(e,o.name);await this.loadPlugin(o.name,r)}}return this.log.info(`[plugins] loaded ${this.loaded.length} plugin(s): ${this.loaded.map(e=>e.name).join(", ")||"(none)"}`),this.loaded}getPluginSkills(){return this.pluginSkills}getLoaded(){return this.loaded}async refreshActivations(){let e=Date.now();for(let[n,o]of this.activations){if(e-o.lastCheckAt<o.ttlMs)continue;let r;try{r=await o.checkFn()}catch(s){this.log.warn(`[plugins] ${n}: check_fn error: ${s instanceof Error?s.message:s}`),r=o.lastResult}if(o.lastCheckAt=e,r!==o.lastResult){if(o.lastResult=r,r&&!o.active){for(let s of o.tools)this.config.toolRegistry.register(s);o.active=!0,this.log.info(`[plugins] ${n}: reactivated (${o.tools.length} tools)`)}else if(!r&&o.active){for(let s of o.tools)this.config.toolRegistry.unregister(s.name);for(let s of o.hookUnregisterFns)s();o.active=!1,this.log.info(`[plugins] ${n}: deactivated`)}}}}async loadPlugin(e,n){let o=["index.js","index.mjs"],r=null;for(let f of o){let x=Ut.join(n,f);if(ye.existsSync(x)){r=x;break}}if(!r){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],u=[],c=null,p=6e4,m={},g=Ut.join(n,"config.json");if(ye.existsSync(g))try{m=JSON.parse(ye.readFileSync(g,"utf8"))}catch{}let y={pluginName:e,registerTool:f=>{this.config.toolRegistry.register(f),l.push(f),s++},registerHook:(f,x)=>{let b=ia[f];if(!b){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let S=this.config.hookRegistry.register({point:b,handler:x,label:`plugin:${e}:${f}`,priority:200});u.push(S),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>m,setActivationCheck:(f,x)=>{c=f,x!==void 0&&(p=x)}};try{let x=await import(wm(r).href);if(typeof x.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await x.register(y),c&&this.activations.set(e,{checkFn:c,ttlMs:p,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:u,active:!0}),this.loaded.push({name:e,directory:n,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(f){this.log.warn(`[plugins] ${e}: load error: ${f instanceof Error?f.message:f}`)}}};import*as X from"node:fs";import*as Re from"node:path";import{homedir as aa}from"node:os";function wo(){return Re.join(aa(),".openclaw","plugin-cache")}function la(){return Re.join(wo(),"installed_plugins.json")}function ca(){let t=la();if(!X.existsSync(t))return{version:1,plugins:[]};try{return JSON.parse(X.readFileSync(t,"utf-8"))}catch{return{version:1,plugins:[]}}}function Cm(t){let e=wo();X.existsSync(e)||X.mkdirSync(e,{recursive:!0}),X.writeFileSync(la(),JSON.stringify(t,null,2),"utf-8")}function Rm(t,e){return!(e.blocklist?.includes(t)||e.allowlist&&!e.allowlist.includes(t))}async function _m(t,e,n){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(o),i=wo(),a=e?`${t}@${e}`:t;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),u=l.trim().split(`
|
|
249
|
+
`).pop()?.trim();if(!u)return n.warn(`[marketplace] npm pack returned no output for ${a}`),null;let c=Re.join(i,u),m=u.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",g=Re.join(i,`${t}@${m}`);X.existsSync(g)||X.mkdirSync(g,{recursive:!0}),await s("tar",["xzf",c,"-C",g,"--strip-components=1"],{timeout:3e4});try{X.unlinkSync(c)}catch{}let y=Re.join(g,"package.json");if(X.existsSync(y))try{await s("npm",["install","--production","--no-save"],{cwd:g,timeout:12e4})}catch(f){n.warn(`[marketplace] npm install for ${t} failed: ${f.message}`)}return n.info(`[marketplace] installed ${t}@${m} from npm`),{name:t,version:m,installPath:g}}catch(l){return n.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function Am(){return ca().plugins.filter(e=>X.existsSync(e.installPath)).map(e=>e.installPath)}async function Pm(t,e){let n=ca(),o=[];for(let r of t.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!Rm(s,t)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=n.plugins.find(l=>l.source.specifier===r.specifier&&l.source.type===r.type);if(i&&X.existsSync(i.installPath)&&(!r.version||i.version===r.version)){o.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await _m(r.specifier,r.version,e);break;case"git":case"url":e.warn(`[marketplace] ${r.type} source not yet implemented for "${r.specifier}"`);break}if(a){let l={name:a.name,version:a.version,source:r,installPath:a.installPath,installedAt:new Date().toISOString()};n.plugins=n.plugins.filter(u=>!(u.source.specifier===r.specifier&&u.source.type===r.type)),n.plugins.push(l),o.push(a.installPath)}}return Cm(n),o}function Mm(){let t=Re.join(aa(),".openclaw","marketplace.json");if(!X.existsSync(t))return null;try{return JSON.parse(X.readFileSync(t,"utf-8"))}catch{return null}}async function ua(t,e){let n=[...t],o=Am();n.push(...o);let r=Mm();if(r&&r.enabledPlugins.length>0)try{let s=await Pm(r,e),i=new Set(n);for(let a of s)i.has(a)||n.push(a)}catch(s){e.warn(`[marketplace] failed to update plugins: ${s.message}`)}return n}var Wt=class{mode;rules;defaultBehavior;compiledPatterns;constructor(e){this.mode=e.mode,this.rules=[...e.rules],this.defaultBehavior=e.defaultBehavior,this.compiledPatterns=this.compileRules(this.rules)}getMode(){return this.mode}setMode(e){this.mode=e}getRules(){return this.rules}getDefaultBehavior(){return this.defaultBehavior}replaceRules(e){this.rules=[...e],this.compiledPatterns=this.compileRules(this.rules)}setDefaultBehavior(e){this.defaultBehavior=e}addRule(e){this.rules.push(e),this.compiledPatterns=this.compileRules(this.rules)}applyUpdate(e){this.addRule({pattern:e.pattern,behavior:e.behavior,reason:e.description,source:"user"})}check(e){let{toolName:n,meta:o}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return{behavior:"deny",message:`Tool "${n}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${n}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:r,regex:s}of this.compiledPatterns)if(s.test(n))return Em(r,e);return o?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:o?.requiresApproval?{behavior:"ask",message:`Tool "${n}" requires approval`,toolName:n,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:o?.isDangerous?{behavior:"ask",message:`Tool "${n}" is marked dangerous`,toolName:n,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}:this.mode==="acceptEdits"?/write|edit|create|delete|move|rename|patch/i.test(n)?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:{behavior:"ask",message:`Tool "${n}" needs approval in acceptEdits mode`,toolName:n,input:e.arguments,decisionReason:{type:"mode",mode:"acceptEdits"}}:this.defaultBehavior==="allow"?{behavior:"allow"}:this.defaultBehavior==="deny"?{behavior:"deny",message:`Tool "${n}" denied by default policy`,decisionReason:{type:"other",reason:"default_deny"}}:{behavior:"ask",message:`Tool "${n}" requires approval (default policy)`,toolName:n,input:e.arguments}}compileRules(e){return e.map(n=>({rule:n,regex:Im(n.pattern)}))}};function da(t){if(!t||typeof t!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=t,n=[];for(let a of["allow","deny","ask"]){let l=e[a];if(Array.isArray(l))for(let u of l)typeof u=="string"&&n.push({pattern:u,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let l=a,u=l.pattern,c=l.behavior??l.action;typeof u=="string"&&typeof c=="string"&&(c==="allow"||c==="deny"||c==="ask")&&n.push({pattern:u,behavior:c,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let o=e.mode,r=typeof o=="string"&&Om(o)?o:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&Lm(s)?s:"allow";return{mode:r,rules:n,defaultBehavior:i}}function Im(t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${n}$`,"i")}function Em(t,e){let n={type:"rule",rule:t};return t.behavior==="allow"?{behavior:"allow",decisionReason:n}:t.behavior==="deny"?{behavior:"deny",message:t.reason??`Tool "${e.toolName}" denied by rule "${t.pattern}"`,decisionReason:n}:{behavior:"ask",message:t.reason??`Tool "${e.toolName}" requires approval (rule "${t.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:n}}function Om(t){return t==="default"||t==="bypassPermissions"||t==="acceptEdits"||t==="dontAsk"||t==="plan"}function Lm(t){return t==="allow"||t==="deny"||t==="ask"}import{randomUUID as Wm}from"node:crypto";var $m=new Set(["node --version","npm --version","npx --version","pnpm --version","yarn --version","bun --version","deno --version","python --version","python3 --version","pip --version","ruby --version","go version","rustc --version","cargo --version","java -version","javac -version","dotnet --version","gcc --version","g++ --version","clang --version","git --version","docker --version","--help","-h"]),pa=new Set(["ls","dir","find","fd","locate","which","where","type","cat","head","tail","less","more","bat","wc","file","stat","du","df","tree","exa","eza","grep","rg","ripgrep","ag","ack","fgrep","egrep","git status","git log","git diff","git show","git branch","git tag","git remote","git stash list","git blame","git shortlog","git describe","git rev-parse","git ls-files","git ls-tree","git cat-file","git reflog","ps","top","htop","uptime","uname","hostname","whoami","id","env","printenv","echo","ping","nslookup","dig","host","ifconfig","ip","netstat","ss","npm list","npm ls","npm info","npm view","npm outdated","npm audit","pnpm list","pnpm ls","pnpm outdated","pip list","pip show","pip freeze","cargo tree","npm test","npm run test","npm run build","npm run lint","pnpm test","pnpm run test","pnpm run build","pnpm run lint","yarn test","yarn build","yarn lint","cargo test","cargo build","cargo check","cargo clippy","go test","go build","go vet","make","cmake","pytest","python -m pytest","python3 -m pytest","jest","vitest","mocha","tsc","tsc --noEmit","eslint","prettier","oxlint"]),Dm=[/\brm\s+-rf?\s+[/~]/,/\brm\s+-rf?\s+\.\.\//,/\bsudo\b/,/\bsu\s/,/\bchmod\s+777\b/,/\bmkfs\b/,/\bfdisk\b/,/\bdd\s+if=/,/\bsystemctl\s+(start|stop|restart|enable|disable)\b/,/\bservice\s+\S+\s+(start|stop|restart)\b/,/\breg\s+(add|delete)\b/i,/\\Windows\\System32/i,/\/etc\/(passwd|shadow|sudoers|fstab)/,/\bgit\s+push\s+.*--force\b/,/\bgit\s+push\s+-f\b/,/\bcurl\b.*(-H|--header)\s+.*[Aa]uthorization/,/\bwget\b.*--header.*[Aa]uthorization/,/\bcurl\b.*\|\s*(sh|bash|zsh)\b/,/\bwget\b.*-O\s*-\s*\|\s*(sh|bash|zsh)\b/,/\bnpm\s+install\s+-g\b/,/\bpip\s+install\b(?!.*-r\b)(?!.*requirements)/,/\bDROP\s+(DATABASE|TABLE|SCHEMA)\b/i,/\bTRUNCATE\s+TABLE\b/i],ma=new Set(["npm install","npm i","npm ci","pnpm install","pnpm i","yarn install","yarn","pip install -r","pip install -e","cargo build","cargo install","go mod download","go get","bundle install","composer install","git add","git commit","git stash","git checkout","git switch","git merge","git rebase","git cherry-pick","git pull","git fetch","docker build","docker compose","mkdir","touch","cp"]);function ga(t,e,n){let o=t.trim();if(!o)return{decision:"allow",reason:"empty command"};let r=go(o)??fo(o)??void 0;for(let u of Dm)if(u.test(o))return{decision:"deny",reason:`matches dangerous pattern: ${u.source}`,destructiveWarning:r};for(let u of $m)if(o===u||o.startsWith(u+" "))return{decision:"allow",reason:`known safe command: ${u}`,destructiveWarning:r};let s=o.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return pa.has(i)||pa.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&n&&e.startsWith(n)&&(ma.has(i)||ma.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function Nm(t){let e=Object.keys(t).sort(),n={};for(let o of e){let r=t[o];typeof r=="string"?n[o]=r.replace(/\s+/g," ").trim():n[o]=r}return JSON.stringify(n)}function Co(t,e){return`${t}::${Nm(e)}`}var jm=500,Ht=class{cache=new Map;get(e,n){let o=Co(e,n),r=this.cache.get(o);if(r)return r.hitCount++,r}set(e,n,o){if(this.cache.size>=jm){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=Co(e,n);this.cache.set(r,{shouldBlock:o.shouldBlock,reason:o.reason,classifiedAt:Date.now(),hitCount:0})}has(e,n){return this.cache.has(Co(e,n))}clear(){this.cache.clear()}get size(){return this.cache.size}get totalHits(){let e=0;for(let n of this.cache.values())e+=n.hitCount;return e}};var Fm=new Set(["read","search","instructions_list","instructions_read","think","todo","memory_search","memory_query","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function rt(t){return Fm.has(t)}var fa=`You are a security classifier for an AI coding agent. Your job is to decide whether a tool invocation is safe to execute without user confirmation.
|
|
250
|
+
|
|
251
|
+
The agent operates in a workspace and has been given permission to use tools autonomously. You must decide if each tool call is SAFE (routine development work) or DANGEROUS (could cause harm, data loss, or unexpected side effects).
|
|
252
|
+
|
|
253
|
+
SAFE operations (should NOT be blocked):
|
|
254
|
+
- Reading, writing, editing code files in the project
|
|
255
|
+
- Running build commands, test commands, linters
|
|
256
|
+
- Installing project dependencies (npm install, pip install, etc.)
|
|
257
|
+
- Git operations within the project (add, commit, status, diff, log)
|
|
258
|
+
- Creating/modifying config files (.env, tsconfig.json, etc.)
|
|
259
|
+
- Running development servers locally
|
|
260
|
+
|
|
261
|
+
DANGEROUS operations (SHOULD be blocked):
|
|
262
|
+
- Deleting files outside the project directory
|
|
263
|
+
- Running commands that modify system configuration
|
|
264
|
+
- Network requests to unknown/suspicious URLs
|
|
265
|
+
- Commands that could leak secrets or credentials
|
|
266
|
+
- Force-pushing to remote repositories
|
|
267
|
+
- Modifying system files (/etc, registry, etc.)
|
|
268
|
+
- Running commands with sudo/admin privileges
|
|
269
|
+
- Downloading and executing unknown scripts
|
|
270
|
+
|
|
271
|
+
Respond ONLY with XML. No other text.`;async function Ro(t,e,n,o){let r=Date.now();if(rt(t))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=Um(n),i=Bm(t,e),a=`<transcript>
|
|
272
|
+
${s}
|
|
273
|
+
</transcript>
|
|
274
|
+
|
|
275
|
+
<action>
|
|
276
|
+
${i}
|
|
277
|
+
</action>
|
|
278
|
+
|
|
279
|
+
Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let l=await o({system:fa,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),u=ba(l.text);if(ha(u)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-r};let p=`<transcript>
|
|
280
|
+
${s}
|
|
281
|
+
</transcript>
|
|
282
|
+
|
|
283
|
+
<action>
|
|
284
|
+
${i}
|
|
285
|
+
</action>
|
|
286
|
+
|
|
287
|
+
The fast classifier flagged this action. Review carefully \u2014 is it actually dangerous, or is it safe development work? Consider the project context. Use <thinking> tags to reason, then respond with <block>yes</block> or <block>no</block> and <reason>explanation</reason>.`,m=await o({system:fa,messages:[{role:"user",content:p}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),g=ba(m.text),y=ha(g),f=ya(g)??ya(u)??"classifier decision";return{shouldBlock:y!==!1,reason:f,stage:"thinking",durationMs:Date.now()-r}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-r}}}function Um(t){return t.slice(-20).map(n=>{let o=n.role==="user"?"User":n.role==="assistant"?"Assistant":"System",r=typeof n.content=="string"?n.content.slice(0,500):JSON.stringify(n.content).slice(0,500);return`${o}: ${r}`}).join(`
|
|
288
|
+
`)}function Bm(t,e){let n=JSON.stringify(e,null,0),o=n.length>2e3?n.slice(0,2e3)+"...":n;return`Tool: ${t}
|
|
289
|
+
Arguments: ${o}`}function ha(t){let e=t.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function ya(t){let e=t.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function ba(t){return t.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var ka={maxConsecutive:3,maxTotal:20};function Ta(){return{consecutiveDenials:0,totalDenials:0}}function _o(t){return{consecutiveDenials:t.consecutiveDenials+1,totalDenials:t.totalDenials+1}}function Ao(t){return t.consecutiveDenials===0?t:{...t,consecutiveDenials:0}}function xa(t){return t.consecutiveDenials>=ka.maxConsecutive||t.totalDenials>=ka.maxTotal}var Hm=12e4,qt=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new Ht;denialTracking=Ta();constructor(e){this.ruleEngine=e.ruleEngine,this.hookRegistry=e.hookRegistry,this.onRequestApproval=e.onRequestApproval,this.onPermissionUpdate=e.onPermissionUpdate,this.onDenied=e.onDenied,this.classifierLLMCall=e.classifierLLMCall,this.getRecentMessages=e.getRecentMessages,this.permissionRole=e.permissionRole??"interactive"}register(){return this.unregisterHook&&this.unregisterHook(),this.classifierCache.clear(),this.unregisterHook=this.hookRegistry.register({point:"tool.before_invoke",priority:100,label:"permission-checker",handler:async(e,n)=>{let o=this.toolMetaCache.get(n.toolName),r={toolName:n.toolName,arguments:n.arguments,meta:o?{isReadOnly:o.isReadOnly,isDangerous:o.isDangerous,requiresApproval:o.requiresApproval,parallelSafe:o.parallelSafe}:void 0},s=this.ruleEngine.check(r);return this.handleResult(s,n.callId,n.toolName,n.arguments)}}),()=>{this.unregisterHook?.(),this.unregisterHook=null,this.cancelAllPending()}}resolveApproval(e){let n=this.pendingApprovals.get(e.approvalId);n&&(clearTimeout(n.timeoutId),this.pendingApprovals.delete(e.approvalId),n.resolve(e))}setToolMeta(e){this.toolMetaCache.clear();for(let n of e)n.meta&&this.toolMetaCache.set(n.function.name,n.meta)}get ruleEngineRef(){return this.ruleEngine}fireDenied(e,n,o){this.onDenied?.(n,o),this.hookRegistry.invoke("permission.denied",{sessionId:"",turnId:"",approvalId:e,callId:e,toolName:n,decision:"denied",reason:o}).catch(()=>{})}async handleResult(e,n,o,r){if(e.behavior==="allow")return{action:"continue",context:e.updatedInput?{arguments:e.updatedInput}:void 0};if(e.behavior==="deny")return this.fireDenied(n,o,e.message),{action:"abort",reason:e.message};if(e.decisionReason?.type==="tool_check"&&(e.decisionReason.reason==="isDangerous"||e.decisionReason.reason==="requiresApproval")&&this.permissionRole!=="interactive")return this.fireDenied(n,o,`safety check: ${e.message} (${this.permissionRole} cannot override)`),{action:"abort",reason:`Tool "${o}" blocked by safety check (${this.permissionRole} agents cannot override dangerous tool restrictions)`};if((o==="bash"||o==="execute_command"||o==="Bash"||o==="shell")&&r){let u=r.command??r.cmd??"";if(u){let c=ga(u);if(c.decision==="allow")return{action:"continue"};if(c.decision==="deny")return this.fireDenied(n,o,c.reason),{action:"abort",reason:c.reason}}}if(r){let u=this.classifierCache.get(o,r);if(u)return u.shouldBlock?(this.fireDenied(n,o,`cached: ${u.reason}`),{action:"abort",reason:u.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(n,o,r);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(o)?.isReadOnly||rt(o)?{action:"continue"}:this.handleWorkerAsk(n,o,r);if(this.ruleEngine.getMode()==="auto"){if(rt(o))return{action:"continue"};let u=xa(this.denialTracking);if(this.classifierLLMCall&&!u)try{let c=this.getRecentMessages?.()??[],p=await Ro(o,r??{},c,this.classifierLLMCall);if(r&&this.classifierCache.set(o,r,{shouldBlock:p.shouldBlock,reason:p.reason}),!p.shouldBlock)return this.denialTracking=Ao(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:p.reason}}};this.denialTracking=_o(this.denialTracking)}catch{}}let a=Wm(),l={approvalId:a,callId:n,toolName:o,arguments:r,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:a,callId:n,toolName:o}).catch(()=>{});try{let u=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:n,toolName:o,decision:u.decision==="approved"?"approved":"denied"}).catch(()=>{}),u.permissionUpdate&&(this.ruleEngine.applyUpdate(u.permissionUpdate),this.onPermissionUpdate?.(u.permissionUpdate)),u.decision==="approved"?{action:"continue",context:u.updatedInput?{arguments:u.updatedInput}:void 0}:(this.fireDenied(n,o,`denied by user (approval ${a})`),{action:"abort",reason:`Tool "${o}" denied by user`})}catch{return this.fireDenied(n,o,`approval timeout or error (approval ${a})`),{action:"abort",reason:`Tool "${o}" \u2014 approval timed out`}}}async handleWorkerAsk(e,n,o){if(rt(n))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await Ro(n,o??{},r,this.classifierLLMCall);return o&&this.classifierCache.set(n,o,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=_o(this.denialTracking),this.fireDenied(e,n,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`),{action:"abort",reason:`Tool "${n}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=Ao(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:this.permissionRole,reason:s.reason}}})}catch{}return this.fireDenied(e,n,`no classifier available in ${this.permissionRole} mode`),{action:"abort",reason:`Tool "${n}" denied \u2014 no classifier for ${this.permissionRole} mode`}}requestApproval(e){return new Promise((n,o)=>{let r=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),o(new Error("Approval timed out"))},Hm);this.pendingApprovals.set(e.approvalId,{resolve:n,reject:o,timeoutId:r}),this.onRequestApproval(e).then(s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),n(s))},s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),o(s))})})}clearClassifierCache(){this.classifierCache.clear(),this.denialTracking={consecutiveDenials:0,totalDenials:0}}cancelAllPending(){this.classifierCache.clear();for(let[e,n]of this.pendingApprovals)clearTimeout(n.timeoutId),n.reject(new Error("Permission checker destroyed")),this.pendingApprovals.delete(e)}};var qm="skill_invoke",zm={type:"object",properties:{skill:{type:"string",description:"Name of the skill to invoke. Use skill_list to see available skills."},args:{type:"string",description:"Optional arguments or context to pass to the skill. This is included in the skill's system prompt."}},required:["skill"]};function va(t){return{name:qm,label:"Invoke Skill",description:Gm(t),parameters:zm,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke run execute command",execute:async(e,n,o)=>{let{skill:r,args:s}=n,i=await t.readSkillContent(r);if(!i){let u=t.listSkills().map(c=>c.name).join(", ");return{content:[{type:"text",text:`Skill "${r}" not found. Available skills: ${u||"(none)"}`}]}}if(t.executeSkillSubturn)try{return{content:[{type:"text",text:await t.executeSkillSubturn(r,i,s,o)}],details:{skillName:r,mode:"subturn"}}}catch(u){let c=u instanceof Error?u.message:String(u);return{content:[{type:"text",text:`Skill execution error: ${c}`}],details:{error:c,skillName:r}}}let a=`## Skill: ${r}
|
|
290
|
+
|
|
291
|
+
`,l=s?`
|
|
292
|
+
|
|
293
|
+
### User Context
|
|
294
|
+
${s}`:"";return{content:[{type:"text",text:`${a}Follow these instructions:
|
|
295
|
+
|
|
296
|
+
${i}${l}`}],details:{skillName:r,mode:"inline"}}}}}function Gm(t){let e=t.listSkills(),n="Invoke a specialized skill to handle a specific task. Skills provide domain-specific instructions and workflows.";if(e.length===0)return n;let o=e.slice(0,50).map(r=>`- ${r.name}: ${r.description??"(no description)"}`).join(`
|
|
297
|
+
`);return`${n}
|
|
298
|
+
|
|
299
|
+
Available skills:
|
|
300
|
+
${o}`}var Km="skill_list",Vm={type:"object",properties:{category:{type:"string",description:"Filter skills by category (e.g. 'devops', 'mlops'). Omit to list all."}},required:[]};function Sa(t){return{name:Km,label:"List Skills",description:"List all available skills (reusable workflows/knowledge packages). Returns skill names, descriptions, and categories. Use skill_view to see full skill content.",parameters:Vm,execute:async(e,n)=>{let o=await t.listSkills(n.category);if(o.skills.length===0)return{content:[{type:"text",text:n.category?`No skills found in category "${n.category}".`:"No skills available."}],details:{type:"skill_list",count:0}};let r=[`Available skills (${o.skills.length}):`];o.categories.length>0&&r.push(`Categories: ${o.categories.join(", ")}`),r.push("");for(let s of o.skills){let i=s.category?` [${s.category}]`:"",a=s.version?` (v${s.version})`:"";r.push(`- **${s.name}**${a}${i}: ${s.description}`)}return r.push(""),r.push("Use skill_view(name) to see full skill content."),{content:[{type:"text",text:r.join(`
|
|
301
|
+
`)}],details:{type:"skill_list",count:o.skills.length,categories:o.categories}}}}}var Jm="skill_view",Ym={type:"object",properties:{name:{type:"string",description:"Skill name to view (e.g. 'code-review', 'deploy-ecs')."},filePath:{type:"string",description:"Optional: view a specific file within the skill (e.g. 'references/api.md'). Omit to view the main SKILL.md."}},required:["name"]};function wa(t){return{name:Jm,label:"View Skill",description:"View the full content of a skill (instructions, configuration, reference files). Use skill_list to discover available skills first.",parameters:Ym,execute:async(e,n)=>{if(!n.name||n.name.trim().length===0)return{content:[{type:"text",text:"Error: skill name is required."}],details:{type:"skill_view",error:"empty_name"}};let o=await t.viewSkill(n.name.trim(),n.filePath);if(!o)return{content:[{type:"text",text:`Skill "${n.name}" not found. Use skill_list to see available skills.`}],details:{type:"skill_view",error:"not_found",name:n.name}};let r=[];return n.filePath?r.push(`## ${o.name} / ${n.filePath}`):(r.push(`## Skill: ${o.name}`),o.tags&&o.tags.length>0&&r.push(`Tags: ${o.tags.join(", ")}`),o.referenceFiles&&o.referenceFiles.length>0&&r.push(`Reference files: ${o.referenceFiles.join(", ")}`)),r.push(""),r.push(o.content),{content:[{type:"text",text:r.join(`
|
|
302
|
+
`)}],details:{type:"skill_view",name:o.name,filePath:n.filePath,referenceFiles:o.referenceFiles}}}}}var Xm="skill_manage",Zm={type:"object",properties:{action:{type:"string",enum:["create","edit","patch","delete","write_file","remove_file"],description:"Action to perform: create (new skill), edit (overwrite SKILL.md), patch (find/replace in SKILL.md), delete (remove skill), write_file (add/overwrite supporting file), remove_file (delete supporting file)."},name:{type:"string",description:"Skill name (lowercase, max 64 chars, kebab-case: letters, digits, hyphens)."},content:{type:"string",description:"Full SKILL.md content (YAML frontmatter + body). Required for create/edit. Max 100,000 chars. Must include ---\\nname: ...\\ndescription: ...\\n--- header."},category:{type:"string",description:"Category/domain (e.g. 'devops', 'mlops'). Used by create to organize skills."},filePath:{type:"string",description:"Path within the skill for write_file/remove_file. Must be in references/, templates/, scripts/, or assets/ subdirectory."},fileContent:{type:"string",description:"Content for write_file action. Max 1 MiB."},oldString:{type:"string",description:"Text to find for patch action (must match uniquely in SKILL.md)."},newString:{type:"string",description:"Replacement text for patch action (can be empty to delete)."}},required:["action","name"]},Qm=/^[a-z0-9][a-z0-9._-]{0,63}$/,Ca=1e5,eg=1048576,zt=["references/","templates/","scripts/","assets/"];function Ra(t){return{name:Xm,label:"Manage Skills",description:"Create, edit, patch, or delete skills. Skills are reusable workflows/knowledge packages that can be discovered and invoked. Supports managing supporting files (references, templates).",parameters:Zm,execute:async(e,n)=>{let o=t.validateName?t.validateName(n.name):tg(n.name);if(o)return{content:[{type:"text",text:`Error: ${o}`}],details:{type:"skill_manage",error:"invalid_name"}};let r=ng(n);if(r)return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"skill_manage",error:"validation_failed"}};let s=await t.manageSkill(n);return{content:[{type:"text",text:s.message}],details:{type:"skill_manage",action:n.action,name:n.name,success:s.success,path:s.path}}}}}function tg(t){return t?Qm.test(t)?null:"name must be lowercase, start with letter/digit, contain only letters, digits, hyphens, dots, underscores (max 64 chars).":"name is required."}function ng(t){switch(t.action){case"create":case"edit":if(!t.content)return`content is required for ${t.action}.`;if(t.content.length>Ca)return`content exceeds max length (${Ca} chars).`;if(!t.content.includes("---"))return"content must include YAML frontmatter (--- delimiters).";break;case"patch":if(!t.oldString)return"oldString is required for patch.";if(t.newString===void 0)return"newString is required for patch (can be empty to delete).";break;case"write_file":if(!t.filePath)return"filePath is required for write_file.";if(!t.fileContent)return"fileContent is required for write_file.";if(t.fileContent.length>eg)return"fileContent exceeds max length (1 MiB).";if(!zt.some(e=>t.filePath.startsWith(e)))return`filePath must be in one of: ${zt.join(", ")}`;if(t.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"remove_file":if(!t.filePath)return"filePath is required for remove_file.";if(!zt.some(e=>t.filePath.startsWith(e)))return`filePath must be in one of: ${zt.join(", ")}`;if(t.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"delete":break;default:return`unknown action: ${t.action}`}return null}var og="agent",_a=["general","explore","plan","code","research","verify"],rg={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
|
|
303
|
+
- general: Full tool access, any task
|
|
304
|
+
- explore: Read-only codebase exploration (search, read, analyze)
|
|
305
|
+
- plan: Planning mode (explore + produce plan, no writes)
|
|
306
|
+
- code: Coding agent with full tool access
|
|
307
|
+
- research: Web research and information gathering
|
|
308
|
+
- verify: Run tests, check builds, validate changes`},prompt:{type:"string",description:"Detailed task for the sub-agent. The sub-agent shares your conversation history as context (prompt cache shared). Be specific about what information to return in the final response."},description:{type:"string",description:"Short description (3-7 words) for status tracking."},maxTurns:{type:"number",description:"Max turns for the sub-agent. Defaults: general=200, explore=50, plan=80, code=200, research=30, verify=40."},background:{type:"boolean",description:"If true, runs in background and returns a task_id. Poll with task tool. Default: false."}},required:["agent","prompt"],additionalProperties:!1},Aa=4;function Pa(t){return{name:og,label:"Sub-Agent",description:"Fork a sub-agent to handle complex tasks autonomously. Sub-agents share your conversation context (prompt cache) and have isolated tool state. Use for: parallel research, code exploration, testing, delegating large tasks to specialized agents.",parameters:rg,searchHint:"fork subagent delegate spawn child parallel worker",isConcurrencySafe:!0,execute:async(e,n)=>{if(!n.prompt||n.prompt.trim().length<10)return{content:[{type:"text",text:"Error: prompt must be at least 10 characters."}],details:{type:"agent",error:"prompt_too_short"}};if(!_a.includes(n.agent))return{content:[{type:"text",text:`Error: unknown agent "${n.agent}". Available: ${_a.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let o=t.currentForkDepth??0;if(o>=Aa)return{content:[{type:"text",text:`Error: maximum fork depth (${Aa}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:o}};try{let r=await t.forkAgent({agent:n.agent,prompt:n.prompt.trim(),description:n.description,maxTurns:n.maxTurns,background:n.background,abortSignal:t.abortSignal});if(n.background&&r.status==="running")return{content:[{type:"text",text:`Sub-agent "${n.agent}" started in background.
|
|
309
|
+
Agent ID: ${r.agentId}
|
|
310
|
+
Use task tool with this ID to check status and get output.`}],details:{type:"agent",agentId:r.agentId,status:"running",background:!0}};if(r.status==="failed")return{content:[{type:"text",text:`Sub-agent failed: ${r.error||"unknown error"}`}],details:{type:"agent",agentId:r.agentId,status:"failed",error:r.error}};let s=r.output||"(sub-agent returned no output)",i=r.maxTurnsReached?`
|
|
311
|
+
|
|
312
|
+
[Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:r.agentId,status:"completed",tokensUsed:r.tokensUsed,maxTurnsReached:r.maxTurnsReached}}}catch(r){let s=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}var sg="config",ig={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
|
|
313
|
+
- get: Read a config setting
|
|
314
|
+
- set: Write a config setting
|
|
315
|
+
- list: List all available settings
|
|
316
|
+
- reset: Reset a setting to default`},key:{type:"string",description:"Config key path (e.g. 'model', 'language', 'theme', 'permissions.defaultMode'). Required for get/set/reset."},value:{description:"Value to set. Type depends on the setting. Required for 'set' action."}},required:["action"]},st=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Ma(t){return{name:sg,label:"Config",description:"Read and write agent configuration settings. Supports preferences like model selection, language, theme, tool enablement, etc. Security-critical settings (API keys, permissions) are read-only. Changes persist across sessions.",parameters:ig,execute:async(e,n)=>{switch(n.action){case"get":{if(!n.key)return{content:[{type:"text",text:"Error: key is required for get."}],details:{type:"config",error:"missing_key"}};if(t.isValidKey&&!t.isValidKey(n.key))return{content:[{type:"text",text:`Error: unknown config key "${n.key}". Use action='list' to see available settings.`}],details:{type:"config",error:"unknown_key"}};let o=await t.getConfig(n.key);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"config",error:o.error}};let r=o.setting,s=[`${r.key} = ${JSON.stringify(r.value)}`,` Type: ${r.type}${r.options?` (${r.options.join(" | ")})`:""}`,` ${r.description}`];return r.readOnly&&s.push(" \u26A0\uFE0F Read-only (cannot be changed)"),{content:[{type:"text",text:s.join(`
|
|
317
|
+
`)}],details:{type:"config",action:"get",key:n.key,value:r.value}}}case"set":{if(!n.key)return{content:[{type:"text",text:"Error: key is required for set."}],details:{type:"config",error:"missing_key"}};if(n.value===void 0)return{content:[{type:"text",text:"Error: value is required for set."}],details:{type:"config",error:"missing_value"}};if(st.includes(n.key))return{content:[{type:"text",text:`Error: "${n.key}" is a security-critical setting and cannot be modified.`}],details:{type:"config",error:"readonly_key"}};if(t.isValidKey&&!t.isValidKey(n.key))return{content:[{type:"text",text:`Error: unknown config key "${n.key}".`}],details:{type:"config",error:"unknown_key"}};let o=await t.setConfig(n.key,n.value);return o.success?{content:[{type:"text",text:`Updated "${n.key}": ${JSON.stringify(o.previousValue)} \u2192 ${JSON.stringify(n.value)}`}],details:{type:"config",action:"set",key:n.key,previousValue:o.previousValue,newValue:n.value}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"config",error:o.error}}}case"list":{let o=await t.listConfig();if(!o.settings||o.settings.length===0)return{content:[{type:"text",text:"No config settings available."}],details:{type:"config",action:"list",count:0}};let r=[`Available settings (${o.settings.length}):`,""];for(let s of o.settings){let i=s.readOnly?" [read-only]":"",a=JSON.stringify(s.value);r.push(` ${s.key} = ${a}${i}`),r.push(` ${s.description}`)}return{content:[{type:"text",text:r.join(`
|
|
318
|
+
`)}],details:{type:"config",action:"list",count:o.settings.length}}}case"reset":{if(!n.key)return{content:[{type:"text",text:"Error: key is required for reset."}],details:{type:"config",error:"missing_key"}};if(st.includes(n.key))return{content:[{type:"text",text:`Error: "${n.key}" cannot be reset (security-critical).`}],details:{type:"config",error:"readonly_key"}};let o=await t.resetConfig(n.key);return o.success?{content:[{type:"text",text:`Reset "${n.key}" to default: ${JSON.stringify(o.setting?.value)}`}],details:{type:"config",action:"reset",key:n.key,value:o.setting?.value}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"config",error:o.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${n.action}".`}],details:{type:"config",error:"unknown_action"}}}}}}var ag="cron",lg={type:"object",properties:{action:{type:"string",enum:["create","list","get","update","delete","pause","resume","trigger"],description:"CRUD action: create/list/get/update/delete/pause/resume/trigger."},jobId:{type:"string",description:"Job ID. Required for get/update/delete/pause/resume/trigger."},prompt:{type:"string",description:"Task prompt to execute on schedule. Required for create."},schedule:{type:"string",description:`Schedule expression. Supports:
|
|
319
|
+
- Cron: '0 9 * * *' (every day at 9am)
|
|
320
|
+
- Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
|
|
321
|
+
Required for create.`},name:{type:"string",description:"Human-readable job name."},repeat:{type:"number",description:"Number of times to repeat (null = infinite). Default: null."},allowedTools:{type:"array",items:{type:"string"},description:"Tools the scheduled task is allowed to use."},enabled:{type:"boolean",description:"Whether the job is enabled (for update)."}},required:["action"]},Ia=50;function Ea(t){return{name:ag,label:"Cron",description:"Manage scheduled tasks. Create recurring jobs with cron expressions or shorthand ('5m', '1h', '0 9 * * *'). Jobs persist locally and survive restarts. Actions: create, list, get, update, delete, pause, resume, trigger (run now).",parameters:lg,execute:async(e,n)=>{switch(n.action){case"create":{if(!n.prompt)return{content:[{type:"text",text:"Error: prompt is required for create."}],details:{type:"cron",error:"missing_prompt"}};if(!n.schedule)return{content:[{type:"text",text:"Error: schedule is required for create."}],details:{type:"cron",error:"missing_schedule"}};if(t.validateSchedule){let s=t.validateSchedule(n.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let o=await t.listJobs();if(o.jobs&&o.jobs.length>=Ia)return{content:[{type:"text",text:`Error: maximum ${Ia} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let r=await t.createJob({prompt:n.prompt,schedule:n.schedule,name:n.name,repeat:n.repeat,allowedTools:n.allowedTools});return r.success?{content:[{type:"text",text:Po(r.job)}],details:{type:"cron",action:"create",jobId:r.job.id}}:{content:[{type:"text",text:`Error: ${r.error}`}],details:{type:"cron",error:r.error}}}case"list":{let o=await t.listJobs();if(!o.jobs||o.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let r=[`Scheduled jobs (${o.jobs.length}):`,""];for(let s of o.jobs)r.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:r.join(`
|
|
322
|
+
`)}],details:{type:"cron",action:"list",count:o.jobs.length}}}case"get":{if(!n.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await t.getJob(n.jobId);return o.success?{content:[{type:"text",text:Po(o.job)}],details:{type:"cron",action:"get",jobId:n.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"update":{if(!n.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o={};n.prompt!==void 0&&(o.prompt=n.prompt),n.schedule!==void 0&&(o.schedule=n.schedule),n.name!==void 0&&(o.name=n.name),n.enabled!==void 0&&(o.enabled=n.enabled),n.repeat!==void 0&&(o.repeat=n.repeat),n.allowedTools!==void 0&&(o.allowedTools=n.allowedTools);let r=await t.updateJob(n.jobId,o);return r.success?{content:[{type:"text",text:`Job updated.
|
|
323
|
+
${Po(r.job)}`}],details:{type:"cron",action:"update",jobId:n.jobId}}:{content:[{type:"text",text:`Error: ${r.error}`}],details:{type:"cron",error:r.error}}}case"delete":{if(!n.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await t.deleteJob(n.jobId);return o.success?{content:[{type:"text",text:`Job ${n.jobId} deleted.`}],details:{type:"cron",action:"delete",jobId:n.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"pause":{if(!n.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await t.pauseJob(n.jobId);return o.success?{content:[{type:"text",text:`Job ${n.jobId} paused.`}],details:{type:"cron",action:"pause",jobId:n.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"resume":{if(!n.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await t.resumeJob(n.jobId);return o.success?{content:[{type:"text",text:`Job ${n.jobId} resumed.`}],details:{type:"cron",action:"resume",jobId:n.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"trigger":{if(!n.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await t.triggerJob(n.jobId);return o.success?{content:[{type:"text",text:`Job ${n.jobId} triggered (running now).`}],details:{type:"cron",action:"trigger",jobId:n.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${n.action}".`}],details:{type:"cron",error:"unknown_action"}}}}}}function Po(t){let e=[`Job: ${t.name||t.id}`,`ID: ${t.id}`,`Schedule: ${t.scheduleDisplay} (${t.schedule})`,`State: ${t.state}`,`Repeat: ${t.repeat.times===null?"infinite":`${t.repeat.completed}/${t.repeat.times}`}`];return t.nextRunAt&&e.push(`Next run: ${t.nextRunAt}`),t.lastRunAt&&e.push(`Last run: ${t.lastRunAt} (${t.lastStatus||"unknown"})`),e.push(`Prompt: ${t.prompt.slice(0,100)}${t.prompt.length>100?"...":""}`),e.join(`
|
|
324
|
+
`)}var cg="monitor",ug={type:"object",properties:{action:{type:"string",enum:["start","stop","list"],description:"Action to perform: start a new monitor, stop an existing one, or list active monitors."},monitorId:{type:"string",description:"Identifier for the monitor instance. Required for start/stop."},source:{type:"string",enum:["process","file","task","custom"],description:"Type of event source to watch."},target:{type:"string",description:"Selector for the monitored target. For process: PID or background job id. For file: glob pattern. For task: task ID. For custom: host-defined key."},conditions:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["exit","output_match","file_changed","task_status"]},value:{type:"string"}},required:["type"]},description:"Conditions that trigger a wake-up notification."},timeoutSeconds:{type:"number",description:"Auto-stop after this many seconds (default: 3600).",minimum:1,maximum:86400}},required:["action"]};function Oa(t){return{name:cg,label:"Monitor",shouldDefer:!0,description:["Set up event-driven monitoring to wake up when something happens.","","Use this to watch for:","\u2022 Background process completion or specific output patterns","\u2022 File system changes (new file, modification)","\u2022 Async task state transitions (pending \u2192 completed/failed)","\u2022 Custom host-defined events","","When a monitored condition triggers, you'll receive a notification in your next tick.","This is more efficient than polling with Sleep \u2014 you only wake up when there's work to do.","","Actions:","\u2022 start \u2014 register a new monitor (requires monitorId, source, target)","\u2022 stop \u2014 deregister an active monitor","\u2022 list \u2014 show all active monitors and their event counts"].join(`
|
|
325
|
+
`),parameters:ug,execute:async(e,n)=>{let{action:o}=n;if(o==="list"){let i=await t.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:o,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
|
|
326
|
+
${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.eventCount}, timeout: ${l.timeoutSeconds}s)`).join(`
|
|
327
|
+
`)}`}],details:{action:o,monitors:i}}}if(!n.monitorId)return{content:[{type:"text",text:"Error: monitorId is required for start/stop."}],details:{action:o,success:!1,error:"missing_monitor_id"}};if(o==="stop"){let i=await t.stopMonitor(n.monitorId);return{content:[{type:"text",text:i.success?`Monitor "${n.monitorId}" stopped.`:`Failed to stop monitor "${n.monitorId}": ${i.error??"not found"}`}],details:{...i}}}if(!n.source||!n.target)return{content:[{type:"text",text:"Error: source and target are required to start a monitor."}],details:{action:o,success:!1,error:"missing_source_or_target"}};let r=await t.startMonitor({monitorId:n.monitorId,source:n.source,target:n.target,conditions:n.conditions??[],timeoutSeconds:n.timeoutSeconds??3600});return{content:[{type:"text",text:r.success?`Monitor "${n.monitorId}" started: watching ${n.source} "${n.target}".`:`Failed to start monitor: ${r.error??"unknown"}`}],details:{...r}}}}}var dg="team",pg={type:"object",properties:{action:{type:"string",enum:["create","delete","list","status"],description:"Team action: create (new team), delete (disband), list (all teams), status (team details)."},teamName:{type:"string",description:"Team name. Required for create/delete/status."},description:{type:"string",description:"Team description/objective. Used for create."},members:{type:"array",description:"Team members with roles and tool restrictions.",items:{type:"object",properties:{name:{type:"string",description:"Agent name/role identifier."},role:{type:"string",description:"Role description (e.g. 'frontend developer')."},tools:{type:"array",items:{type:"string"},description:"Allowed tools for this member."}},required:["name","role"]}}},required:["action"]};function La(t){return{name:dg,label:"Team",description:"Manage multi-agent teams. Create teams of specialized agents that collaborate via send_message. Each member has a role and optional tool restrictions. Use for complex tasks requiring parallel work.",parameters:pg,execute:async(e,n)=>{switch(n.action){case"create":{if(!n.teamName)return{content:[{type:"text",text:"Error: teamName required for create."}],details:{type:"team",error:"missing_name"}};let o=await t.createTeam({teamName:n.teamName,description:n.description,members:n.members});if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"team",error:o.error}};let r=[`Team "${o.team.name}" created.`,`Lead: ${o.team.leadId}`,`Members: ${o.team.members.length}`];for(let s of o.team.members)r.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:r.join(`
|
|
328
|
+
`)}],details:{type:"team",action:"create",teamName:o.team.name}}}case"delete":{if(!n.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let o=await t.deleteTeam(n.teamName);return o.success?{content:[{type:"text",text:`Team "${n.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:n.teamName}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"team",error:o.error}}}case"list":{let o=await t.listTeams();if(!o.teams||o.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let r=[`Active teams (${o.teams.length}):`,""];for(let s of o.teams)r.push(`- **${s.name}**: ${s.description||"(no description)"} \u2014 ${s.members.length} members`);return{content:[{type:"text",text:r.join(`
|
|
329
|
+
`)}],details:{type:"team",action:"list",count:o.teams.length}}}case"status":{if(!n.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let o=await t.getTeamStatus(n.teamName);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"team",error:o.error}};let r=o.team,s=[`Team: ${r.name}`,`Description: ${r.description||"\u2014"}`,`Lead: ${r.leadId}`,`Created: ${r.createdAt}`,"",`Members (${r.members.length}):`];for(let i of r.members){let a=i.tools?` [tools: ${i.tools.join(", ")}]`:"";s.push(` - ${i.name} (${i.role})${a}`)}return{content:[{type:"text",text:s.join(`
|
|
330
|
+
`)}],details:{type:"team",action:"status",teamName:r.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${n.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var gg="mcp",fg={type:"object",properties:{action:{type:"string",enum:["list_servers","list_tools","call_tool","list_resources","read_resource","list_prompts","get_prompt","authenticate","manage_server"],description:`MCP action:
|
|
331
|
+
- list_servers: List configured MCP servers, their status and capabilities
|
|
332
|
+
- list_tools: List tools provided by a specific server
|
|
333
|
+
- call_tool: Execute a tool on an MCP server
|
|
334
|
+
- list_resources: List resources from a server (or all servers)
|
|
335
|
+
- read_resource: Read a specific resource by URI
|
|
336
|
+
- list_prompts: List prompts available from a server
|
|
337
|
+
- get_prompt: Get a specific prompt with arguments
|
|
338
|
+
- authenticate: Initiate OAuth authentication with a server
|
|
339
|
+
- manage_server: Add, remove, restart, or check server status`},server:{type:"string",description:"MCP server name. Required for all actions except list_servers."},toolName:{type:"string",description:"Tool name on the MCP server. Required for call_tool."},arguments:{type:"object",description:"Arguments for the tool call or prompt. Used with call_tool and get_prompt."},uri:{type:"string",description:"Resource URI. Required for read_resource."},promptName:{type:"string",description:"Prompt name. Required for get_prompt."},manageAction:{type:"string",enum:["add","remove","restart","health_check","enable","disable"],description:"Sub-action for manage_server."},config:{type:"object",description:"Server configuration. Required for manage_server add."}},required:["action"]};function $a(t){return{name:gg,label:"MCP",description:`Interact with external MCP (Model Context Protocol) servers. Discover and call tools, read resources, get prompts, manage servers, and handle authentication. MCP servers extend agent capabilities with external integrations (databases, APIs, code analysis, custom tools).
|
|
340
|
+
|
|
341
|
+
Dynamic tools: When MCP servers are connected, their tools also appear as individual entries in the tool list (prefixed mcp__server__tool) for direct invocation without going through this management tool.`,parameters:fg,shouldDefer:!0,execute:async(e,n,o)=>{switch(n.action){case"list_servers":{let r=await t.listServers();if(r.length===0)return{content:[{type:"text",text:"No MCP servers configured. Use manage_server action to add one."}],details:{type:"mcp",action:"list_servers",count:0}};let s=[`MCP Servers (${r.length}):`,""];for(let i of r){let a=hg(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let l=[];i.capabilities.tools?.listChanged&&l.push("tools/listChanged"),i.capabilities.resources?.subscribe&&l.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&l.push("prompts/listChanged"),l.length>0&&s.push(` Capabilities: ${l.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
|
|
342
|
+
`)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!n.server)return z("server is required for list_tools.");let r=await t.listTools(n.server);if(r.length===0)return{content:[{type:"text",text:`No tools available from server "${n.server}".`}],details:{type:"mcp",action:"list_tools",server:n.server,count:0}};let s=[`Tools from "${n.server}" (${r.length}):`,""];for(let i of r){let a=yg(i.annotations);s.push(`- **${i.name}**${a}${i.description?`: ${i.description}`:""}`),i.prefixedName&&s.push(` Direct call: \`${i.prefixedName}\``)}return{content:[{type:"text",text:s.join(`
|
|
343
|
+
`)}],details:{type:"mcp",action:"list_tools",server:n.server,count:r.length}}}case"call_tool":{if(!n.server)return z("server is required for call_tool.");if(!n.toolName)return z("toolName is required for call_tool.");let r=await t.callTool(n.server,n.toolName,n.arguments,o);return!r.success||r.isError?{content:[{type:"text",text:`MCP tool error (${n.server}/${n.toolName}): ${r.error||r.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:n.server,toolName:n.toolName,success:!1}}:r.contentBlocks&&r.contentBlocks.length>0?{content:r.contentBlocks.map(i=>i.type==="image"&&i.data?{type:"image",data:i.data,mimeType:i.mimeType}:{type:"text",text:i.text||""}),details:{type:"mcp",action:"call_tool",server:n.server,toolName:n.toolName,success:!0}}:{content:[{type:"text",text:r.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:n.server,toolName:n.toolName,success:!0}}}case"list_resources":{let r=await t.listResources(n.server);if(r.length===0)return{content:[{type:"text",text:n.server?`No resources from "${n.server}".`:"No MCP resources available."}],details:{type:"mcp",action:"list_resources",count:0}};let s=[`MCP Resources (${r.length}):`,""];for(let i of r)s.push(`- **${i.name}** \`${i.uri}\`${i.mimeType?` [${i.mimeType}]`:""}`),i.description&&s.push(` ${i.description}`),i.server&&s.push(` Server: ${i.server}`);return{content:[{type:"text",text:s.join(`
|
|
344
|
+
`)}],details:{type:"mcp",action:"list_resources",count:r.length,server:n.server}}}case"read_resource":{if(!n.server)return z("server is required for read_resource.");if(!n.uri)return z("uri is required for read_resource.");let r=await t.readResource(n.server,n.uri);if(r.length===0)return{content:[{type:"text",text:"Resource returned no content."}],details:{type:"mcp",action:"read_resource",server:n.server,uri:n.uri}};let s=[];for(let i of r)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${bg(i.blobSize)})`:""}]`}):i.text&&s.push({type:"text",text:i.text});return s.length===0&&s.push({type:"text",text:"(empty content)"}),{content:s,details:{type:"mcp",action:"read_resource",server:n.server,uri:n.uri}}}case"list_prompts":{if(!n.server)return z("server is required for list_prompts.");if(!t.listPrompts)return z("Prompt listing not supported by the current MCP host.");let r=await t.listPrompts(n.server);if(r.length===0)return{content:[{type:"text",text:`No prompts available from "${n.server}".`}],details:{type:"mcp",action:"list_prompts",server:n.server,count:0}};let s=[`Prompts from "${n.server}" (${r.length}):`,""];for(let i of r)if(s.push(`- **${i.name}**${i.description?`: ${i.description}`:""}`),i.arguments&&i.arguments.length>0){let a=i.arguments.map(l=>`${l.name}${l.required?" (required)":""}${l.description?`: ${l.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
|
|
345
|
+
`)}],details:{type:"mcp",action:"list_prompts",server:n.server,count:r.length}}}case"get_prompt":{if(!n.server)return z("server is required for get_prompt.");if(!n.promptName)return z("promptName is required for get_prompt.");if(!t.getPrompt)return z("Prompt retrieval not supported by the current MCP host.");let r=n.arguments?Object.fromEntries(Object.entries(n.arguments).map(([a,l])=>[a,String(l)])):void 0,s=await t.getPrompt(n.server,n.promptName,r),i=[];s.description&&i.push(`> ${s.description}`,"");for(let a of s.messages)i.push(`**[${a.role}]:**`),a.content.type==="text"?i.push(a.content.text):a.content.type==="resource"?(i.push(`[Resource: ${a.content.resource.uri}]`),a.content.resource.text&&i.push(a.content.resource.text)):a.content.type==="image"&&i.push("[Image content]"),i.push("");return{content:[{type:"text",text:i.join(`
|
|
346
|
+
`)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:n.server,promptName:n.promptName}}}case"authenticate":{if(!n.server)return z("server is required for authenticate.");let r=await t.authenticate(n.server);switch(r.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${n.server}".
|
|
347
|
+
|
|
348
|
+
Please open this URL in your browser:
|
|
349
|
+
${r.authUrl}
|
|
350
|
+
|
|
351
|
+
${r.message||"Once you complete authentication, the server's tools will become available automatically."}`}],details:{type:"mcp",action:"authenticate",server:n.server,status:"auth_url"}};case"already_authenticated":return{content:[{type:"text",text:`Server "${n.server}" is already authenticated.`}],details:{type:"mcp",action:"authenticate",server:n.server,status:"already_authenticated"}};case"step_up_required":return{content:[{type:"text",text:`Server "${n.server}" requires elevated permissions.
|
|
352
|
+
Required scopes: ${r.requiredScopes?.join(", ")||"unknown"}
|
|
353
|
+
|
|
354
|
+
`+(r.authUrl?`Re-authorize at: ${r.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:n.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${n.server}" (${r.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:n.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${n.server}": ${r.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:n.server,status:"error"}}}}case"manage_server":{if(!n.server)return z("server is required for manage_server.");if(!n.manageAction)return z("manageAction is required for manage_server.");switch(n.manageAction){case"add":{if(!t.addServer)return z("Server addition not supported by the current MCP host.");if(!n.config)return z("config is required for manage_server add.");let r=await t.addServer(n.server,n.config);return it("add",n.server,r)}case"remove":{if(!t.removeServer)return z("Server removal not supported by the current MCP host.");let r=await t.removeServer(n.server);return it("remove",n.server,r)}case"restart":{if(!t.restartServer)return z("Server restart not supported by the current MCP host.");let r=await t.restartServer(n.server);return it("restart",n.server,r)}case"health_check":{if(!t.healthCheck)return z("Health check not supported by the current MCP host.");let r=await t.healthCheck(n.server);return it("health_check",n.server,r)}case"enable":case"disable":{if(!t.setServerEnabled)return z("Server enable/disable not supported by the current MCP host.");let r=await t.setServerEnabled(n.server,n.manageAction==="enable");return it(n.manageAction,n.server,r)}default:return z(`Unknown manageAction: ${n.manageAction}`)}}default:return z(`Unknown action: "${n.action}".`)}}}}function z(t){return{content:[{type:"text",text:`Error: ${t}`}],details:{type:"mcp",error:t}}}function hg(t){switch(t){case"connected":return"\u2705";case"connecting":return"\u23F3";case"needs-auth":return"\u{1F511}";case"failed":return"\u274C";case"disconnected":return"\u26AA";case"disabled":return"\u{1F6AB}";default:return"\u2753"}}function yg(t){if(!t)return"";let e=[];return t.readOnlyHint&&e.push("\u{1F4D6}"),t.destructiveHint&&e.push("\u26A0\uFE0F"),t.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function bg(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function it(t,e,n){let o=[];return o.push(`${n.success?"\u2705":"\u274C"} ${t} "${e}": ${n.message}`),n.serverState&&(o.push(""),o.push(` Status: ${n.serverState.status}`),o.push(` Tools: ${n.serverState.toolCount} | Resources: ${n.serverState.resourceCount}`)),{content:[{type:"text",text:o.join(`
|
|
355
|
+
`)}],details:{type:"mcp",action:"manage_server",manageAction:t,server:e,success:n.success}}}xn();kn();import{readFile as kg}from"node:fs/promises";import{watch as Tg}from"node:fs";import{join as xg}from"node:path";var vg=".openclaw",Sg="settings.json";function wg(t){return xg(t,vg,Sg)}async function Cg(t){try{let e=await kg(t,"utf-8");return JSON.parse(e)}catch{return null}}function Rg(t,e,n,o){let r=!1;t.permissionMode&&t.permissionMode!==e.getMode()&&(e.setMode(t.permissionMode),o?.(`settings: permission mode \u2192 ${t.permissionMode}`),r=!0),t.permissionRules&&(e.replaceRules(t.permissionRules),o?.(`settings: ${t.permissionRules.length} permission rules loaded`),r=!0),t.defaultBehavior&&(e.setDefaultBehavior(t.defaultBehavior),o?.(`settings: default behavior \u2192 ${t.defaultBehavior}`),r=!0),r&&n&&n.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:t}).catch(()=>{})}function Da(t){let e=wg(t.projectRoot),n=null,o=null,r=async()=>{let s=await Cg(e);s&&Rg(s,t.ruleEngine,t.hooks,t.log)};r().catch(()=>{});try{n=Tg(e,{persistent:!1},s=>{o&&clearTimeout(o),o=setTimeout(()=>{r().catch(()=>{})},200)}),n.on("error",()=>{})}catch{}return()=>{o&&clearTimeout(o),n?.close(),n=null}}var Mo=new Set;function Le(t){return Mo.add(t),()=>{Mo.delete(t)}}async function Na(){await Promise.all(Array.from(Mo).map(t=>t()))}import*as F from"node:fs";import*as W from"node:path";import{homedir as $e}from"node:os";import{AGENT_RPC_ERROR_CODES as De,AGENT_RPC_PROTOCOL_VERSION as Gt,isAgentRpcRequest as Ag}from"qlogicagent-runtime-contracts";var Kt=class{running=!1;activeTurn=null;verbose;registry;toolRegistry;agent=null;lastLlmConfigKey="";currentSessionId="";currentHooks=null;mcpManager=null;pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";sessionState=null;taskStore=new wt;memoryPrefetchState=yt();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;constructor(e){this.verbose=e.verbose,this.registry=new Ye,this.taskStore.onTaskChange((n,o)=>{o&&this.sendNotification("task.updated",{taskId:n,type:o.type,lifecycle:o.lifecycle,label:o.label})}),this.toolRegistry=na({log:{info:n=>this.log(n),warn:n=>this.log(`[warn] ${n}`),error:n=>this.log(`[error] ${n}`),debug:n=>{e.verbose&&this.log(`[debug] ${n}`)}},onExecProgress:n=>{this.sendNotification("turn.exec_progress",{output:n.output,elapsedTimeSeconds:n.elapsedTimeSeconds,totalLines:n.totalLines,totalBytes:n.totalBytes})}})}start(){this.running=!0,this.log("qlogicagent CLI started, waiting for JSON-RPC on stdin...");let e=_g({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",n=>{let o=n.trim();if(o)try{let r=JSON.parse(o);if(!Ag(r)){this.log(`[warn] ignoring non-request message: ${o.slice(0,200)}`);return}this.handleMessage(r)}catch{this.log(`[warn] invalid JSON on stdin: ${o.slice(0,200)}`)}}),e.on("close",()=>{this.log("stdin closed, shutting down"),this.stop()})}stop(){if(this.running){this.running=!1,this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{Na().catch(()=>{}),this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null),this.mcpManager&&(this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=null),this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null)}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}handleMessage(e){switch(e.method){case"agent.hello":this.handleHello(e);break;case"agent.ping":this.handlePing(e);break;case"agent.turn":this.handleTurn(e);break;case"memory.dream":this.handleDream(e);break;case"agent.abort":this.handleAbort(e);break;case"tool.approval.response":this.handleApprovalResponse(e);break;case"session.list":this.handleSessionList(e);break;case"session.resume":this.handleSessionResume(e);break;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:De.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleHello(e){let n=e.params,o=n?.protocolVersion??"unknown",r=o.split(".")[0],s=Gt.split(".")[0];if(r!==s){this.log(`protocol mismatch: host=${o} agent=${Gt}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:De.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${o}, agent=${Gt}`});return}this.log(`hello from ${n?.hostName??"unknown"} v${n?.hostVersion??"?"} (protocol ${o})`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:Gt,agentName:"qlogicagent",agentVersion:"0.1.0",capabilities:["turn","tool-invoke","streaming"]})}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}handleAbort(e){let n=e.params?.turnId??"";this.log(`abort requested for turn ${n}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),e.id!==void 0&&this.sendResponse(e.id,{aborted:!0})}handleApprovalResponse(e){let n=e.params;if(!n)return;let o=n.approvalId,r=n.decision;if(!o||!r){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:o,decision:r==="approved"?"approved":"denied",updatedInput:n.updatedInput,permissionUpdate:n.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(s),e.id!==void 0&&this.sendResponse(e.id,{received:!0})}async handleSessionList(e){let o=e.params?.limit??20;try{let r=await Is(o);e.id!==void 0&&this.sendResponse(e.id,{sessions:r})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:De.INTERNAL_ERROR,message:`Failed to list sessions: ${r.message}`})}}async handleSessionResume(e){let o=e.params?.sessionId;if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:De.INVALID_PARAMS,message:"sessionId is required"});return}try{let r=await Ms(o);if(!r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:De.INVALID_PARAMS,message:`Session not found: ${o}`});return}e.id!==void 0&&this.sendResponse(e.id,{metadata:r.metadata,messages:r.messages,costSnapshot:r.costSnapshot})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:De.INTERNAL_ERROR,message:`Failed to resume session: ${r.message}`})}}async handleTurn(e){let n=e.params??{},o=n.turnId??_e(),r=n.sessionId,s=n.messages??[],i=n.tools??[],a=n.config;a?.workdir&&typeof a.workdir=="string"&&oa(a.workdir);let l=this.toolRegistry.getToolManifest(),u=new Set(l.map(g=>g.function.name)),p=[...l,...i.filter(g=>!u.has(g.function.name))];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:o}),r&&r!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),qs()),this.currentSessionId=r,this.sessionState=new xt(r),this.memoryPrefetchState=yt());let m=new AbortController;this.activeTurn=m,this.log(`turn ${o} starting (session: ${r})`);try{let g={provider:a?.provider,model:a?.model,apiKey:a?.apiKey,baseUrl:a?.baseUrl,maxRounds:a?.maxRounds,temperature:a?.temperature,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,summaryModel:a?.summaryModel??process.env.QLOGICAGENT_SUMMARY_MODEL,maxConcurrentTools:a?.maxConcurrentTools},y=this.resolveAgent(g);if(!y){this.sendNotification("turn.start",{turnId:o}),this.sendNotification("turn.error",{turnId:o,error:"No LLM provider configured. Provide provider/model/apiKey in agent.turn config, or set DEEPSEEK_API_KEY / OPENAI_API_KEY / ANTHROPIC_API_KEY environment variable.",code:"NO_PROVIDER"});return}let f;try{let b=a?.workdir??process.cwd(),S=await Bs(b,this.currentHooks??void 0);S.length>0&&(f=Us(S))}catch{}let x=await zs({basePrompt:a?.systemPrompt,instructionBlock:f,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[Gs()]});for(let b of s)b.role==="user"&&Gn(r,b).catch(()=>{});for await(let b of y.run({turnId:o,sessionId:r,messages:s,tools:p,systemPrompt:x,config:g},m.signal))switch(b.type){case"start":this.sendNotification("turn.start",{turnId:b.turnId});break;case"delta":this.sendNotification("turn.delta",{turnId:b.turnId,text:b.text});break;case"end":this.sendNotification("turn.end",{turnId:b.turnId,content:b.content,usage:b.usage,model:b.model,provider:b.provider}),b.usage&&this.sessionState&&this.sessionState.addUsage(b.usage,b.model??this.currentModel),b.content&&Gn(r,{role:"assistant",content:b.content}).catch(()=>{});break;case"error":this.sendNotification("turn.error",{turnId:b.turnId,error:b.error,code:b.code});break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:b.turnId,instruction:b.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:b.turnId,callId:b.callId,name:b.name}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:b.turnId,callId:b.callId,name:b.name,ok:b.ok,...b.error?{error:b.error}:{}});break;case"sidechain_started":this.sendNotification("turn.sidechain_started",{turnId:b.turnId,depth:b.depth,role:b.role});break;case"sidechain_completed":this.sendNotification("turn.sidechain_completed",{turnId:b.turnId,depth:b.depth,toolCallCount:b.toolCallCount});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:b.turnId,callId:b.callId,name:b.name,reason:b.reason});break;case"recovery":this.sendNotification("turn.recovery",{turnId:b.turnId,action:b.action,...b.detail?{detail:b.detail}:{}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:b.turnId,slug:b.slug,content:b.content});break}if(this.log(`turn ${o} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState&&(Ps(r,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:process.cwd(),messageCount:s.length}).catch(()=>{}),this.currentTransport&&this.currentApiKey&&g.summaryModel)){let b=this.sessionState.createSnapshot();Es(r,{sessionId:r,createdAt:0,lastActiveAt:0,turnCount:b.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:g.summaryModel})}}catch(g){if(m.signal.aborted)this.sendNotification("turn.error",{turnId:o,error:"Turn aborted",code:"ABORTED"});else{let y=g instanceof Error?g.message:String(g);this.sendNotification("turn.error",{turnId:o,error:y,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===m&&(this.activeTurn=null)}}async handleDream(e){let n=e.params??{},o=n.turnId??_e(),r=n.sessionId,s=n.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",l=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:o});let u=new AbortController;this.activeTurn=u,this.log(`dream ${o} starting (session: ${r}, sessions reviewing: ${l.length})`);let c={provider:s?.provider,model:s?.model,apiKey:s?.apiKey,baseUrl:s?.baseUrl,maxRounds:s?.maxRounds,temperature:s?.temperature,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens};if(!this.resolveAgent(c)){this.sendNotification("turn.start",{turnId:o}),this.sendNotification("turn.error",{turnId:o,error:"No LLM provider configured for dream.",code:"NO_PROVIDER"});return}this.sendNotification("turn.start",{turnId:o});try{let m={context:{memoryRoot:i,transcriptDir:a,currentSessionId:r,listSessionsSince:async()=>l},triggerConfig:{force:!0},transport:this.currentTransport,toolInvoker:{invoke:async(y,f,x,b)=>{let S=this.toolRegistry.findTool(f);if(!S)return{result:"",error:`Unknown tool: ${f}`};let R=`tc_${_e().slice(0,8)}`;try{let _=JSON.parse(x),O=await S.execute(R,_,b);return{result:O.content.map(P=>P.text??"").join(`
|
|
356
|
+
`),error:O.details?.error}}catch(_){return{result:"",error:_ instanceof Error?_.message:String(_)}}}},tools:this.toolRegistry.getToolManifest(),apiKey:this.currentApiKey,model:c.model??this.currentModel,log:{info:y=>this.log(y),warn:y=>this.log(`[warn] ${y}`),error:y=>this.log(`[error] ${y}`),debug:y=>{this.verbose&&this.log(`[debug] ${y}`)}},hooks:this.currentHooks??void 0,parentSignal:u.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},g=await Rs(m);g.ok?this.sendNotification("turn.end",{turnId:o,content:`Dream consolidation completed. ${g.sessionsReviewed} sessions reviewed, ${g.filesTouched.length} files touched. Duration: ${g.durationMs}ms.`,usage:{prompt:0,completion:0}}):this.sendNotification("turn.error",{turnId:o,error:g.error??"Dream consolidation failed",code:"DREAM_FAILED"}),this.log(`dream ${o} completed`)}catch(m){if(u.signal.aborted)this.sendNotification("turn.error",{turnId:o,error:"Dream aborted",code:"ABORTED"});else{let g=m instanceof Error?m.message:String(m);this.sendNotification("turn.error",{turnId:o,error:g,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===u&&(this.activeTurn=null)}}resolveAgent(e){let n=`${e.provider??""}:${e.model??""}:${e.apiKey?.slice(0,8)??""}:${e.baseUrl??""}`;if(this.agent&&this.lastLlmConfigKey===n)return this.agent;let o=e.provider,r=e.model,s=e.apiKey,i=e.baseUrl;if(!o||!s){let d=Bn(this.registry);d&&(o=o??d.providerId,s=s??d.apiKey,r=r??d.defaultModel,this.log(`auto-detected provider: ${o}, model: ${r}`))}if(!o||!s)return null;r=r??this.registry.getProvider(o)?.defaultModel??"";let a=Un({provider:o,model:r,apiKey:s,baseUrl:i},this.registry);Wn()&&(a.transport=Hn(a.transport,this.currentSessionId||"default"));let l={info:d=>this.log(d),warn:d=>this.log(`[warn] ${d}`),error:d=>this.log(`[error] ${d}`),debug:d=>{this.verbose&&this.log(`[debug] ${d}`)}},u={invoke:async(d,h,v,w)=>{let A=this.toolRegistry.findTool(h);if(!A)return{result:"",error:`Unknown tool: ${h}`};let U=`tc_${_e().slice(0,8)}`;try{let K=JSON.parse(v),V=await A.execute(U,K,w),Q=V.content.map(D=>D.text??"").join(`
|
|
357
|
+
`),ce=V.details?.error;return{result:Q,error:ce}}catch(K){return{result:"",error:K instanceof Error?K.message:String(K)}}}},c=ss(l);this.currentHooks=c,this.taskStore.setHooks(c,this.currentSessionId??"");let p=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(p){let d=ls({baseUrl:p,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=d,this.qmemoryUserId=this.currentSessionId??"default",is(c,{memoryProvider:d,userId:this.currentSessionId??"default",log:{debug:h=>l.debug(h),warn:h=>l.warn(h)}},this.memoryPrefetchState)}Hr(c,l,{transport:a.transport,apiKey:a.apiKey});let m=e?.mcpServers,g=So(m??{}),y=W.join($e(),".openclaw","mcp.json");try{if(F.existsSync(y)){let d=JSON.parse(F.readFileSync(y,"utf8")),h=So(d),v=new Set(g.map(w=>w.name));g=[...g,...h.filter(w=>!v.has(w.name))]}}catch{}if(g.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new Ft({servers:g,log:l}),Le(async()=>{await this.mcpManager?.disconnectAll()});let d=()=>this.mcpManager;this.toolRegistry.register(ra(d)),this.toolRegistry.register(sa(d)),this.toolRegistry.register($a({listServers:async()=>{let h=this.mcpManager;return h?h.getConnectedServers().map(w=>({name:w,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async h=>{if(!this.mcpManager)return[];let w=`mcp__${h.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return this.toolRegistry.getToolNames().filter(A=>A.startsWith(w)).map(A=>({name:A.slice(w.length),prefixedName:A}))},callTool:async(h,v,w,A)=>{let K=`mcp__${h.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+v,V=this.toolRegistry.findTool(K);if(!V)return{success:!1,error:`Tool not found: ${K}`};try{return{success:!0,content:(await V.execute(`mcp_${Date.now()}`,w??{},A)).content.map(D=>D.text??"").join(`
|
|
358
|
+
`)}}catch(Q){return{success:!1,error:Q.message}}},listResources:async h=>{let v=this.mcpManager;return v?(await v.listResources(h)).map(A=>({uri:A.uri,name:A.name,mimeType:A.mimeType,description:A.description,server:A.server})):[]},readResource:async(h,v)=>{let w=this.mcpManager;if(!w)throw new Error("MCP not initialized");return(await w.readResource(h,v)).map(U=>({uri:U.uri,mimeType:U.mimeType,text:U.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(this.toolRegistry),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(h=>{l.warn(`[mcp] connection error: ${h instanceof Error?h.message:h}`)})}let f=[],x=W.join($e(),".openclaw","plugins");F.existsSync(x)&&f.push(x);let b=e?.pluginPaths;if(Array.isArray(b))for(let d of b)typeof d=="string"&&F.existsSync(d)&&f.push(d);ua(f,l).then(d=>{if(d.length===0)return;this.pluginLoader=new Bt({pluginDirs:d,toolRegistry:this.toolRegistry,hookRegistry:c,log:l}),this.pluginLoader.loadAll().then(v=>{l.info(`[plugins] ${v.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(v=>{l.warn(`[plugins] load error: ${v instanceof Error?v.message:v}`)});let h=this.pluginLoader;c.register({point:"turn.submitted",handler:async()=>(await h.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(d=>{l.warn(`[plugins] marketplace resolve error: ${d instanceof Error?d.message:d}`)});let S=e?.permissions,R=da(S),_=new Wt(R);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new qt({ruleEngine:_,hookRegistry:c,onRequestApproval:async d=>(this.sendNotification("tool.approval.request",{approvalId:d.approvalId,callId:d.callId,toolName:d.toolName,arguments:d.arguments,message:d.message,suggestions:d.suggestions}),new Promise(()=>{})),onPermissionUpdate:d=>{l.info(`[permissions] rule saved: ${d.pattern} \u2192 ${d.behavior}`)},onDenied:(d,h)=>{l.warn(`[permissions] blocked "${d}": ${h}`)}});let O=this.toolRegistry.getToolManifest();this.permissionChecker.setToolMeta(O),this.permissionUnregister=this.permissionChecker.register();let G=va({listSkills:()=>{let d=[];this.pluginLoader&&d.push(...this.pluginLoader.getPluginSkills());let h=e?.skillPaths;if(Array.isArray(h)){for(let v of h)if(typeof v=="string"){let w=W.basename(v);d.some(A=>A.name===w)||d.push({name:w,source:"gateway",filePath:W.join(v,"SKILL.md"),baseDir:v})}}return d},readSkillContent:async d=>{let h=[W.join($e(),".openclaw","skills"),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];for(let v of h){let w=W.join(v,d,"SKILL.md");try{return await F.promises.readFile(w,"utf8")}catch{}}return null},executeSkillSubturn:async(d,h,v,w)=>{let A=`skill_${d}_${_e().slice(0,8)}`,U=this.agent;if(!U)return"[skill] Cannot execute: no LLM provider configured";let K=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:K,turnId:A,subagentId:A,agentType:`skill:${d}`}).catch(()=>{});let V=this.toolRegistry.getToolManifest(),Q=v??`Execute skill "${d}" instructions.`,ce=[],D;for await(let Z of U.run({turnId:A,sessionId:K,messages:[{role:"user",content:Q}],tools:V,systemPrompt:h,config:{parentDepth:1}},w)){if(Z.type==="end"&&Z.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:K,turnId:A,subagentId:A,agentType:`skill:${d}`,reason:"normal"}).catch(()=>{}),Z.content;if(Z.type==="delta"&&Z.text&&ce.push(Z.text),Z.type==="error"){D=Z.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:K,turnId:A,subagentId:A,agentType:`skill:${d}`,reason:D?"error":"normal",error:D}).catch(()=>{}),D?`[skill "${d}"] error: ${D}`:ce.join("")||`[skill "${d}"] completed (no output)`}});this.toolRegistry.register(G);let P=[W.join($e(),".openclaw","skills"),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];this.toolRegistry.register(Sa({listSkills:async d=>{let h=[],v=new Set;for(let w of P)try{let A=await F.promises.readdir(w,{withFileTypes:!0});for(let U of A){if(!U.isDirectory())continue;let K=W.join(w,U.name,"SKILL.md");try{await F.promises.access(K);let V=W.basename(w);if(d&&V!==d)continue;v.add(V),h.push({name:U.name,description:`Skill from ${w}`,category:V})}catch{}}}catch{}if(this.pluginLoader)for(let w of this.pluginLoader.getPluginSkills())d&&w.source!==d||(v.add(w.source??"plugin"),h.push({name:w.name,description:`Plugin skill (${w.source})`,category:w.source}));return{skills:h,categories:[...v]}}})),this.toolRegistry.register(wa({viewSkill:async(d,h)=>{for(let v of P){let w=h?W.join(v,d,h):W.join(v,d,"SKILL.md");try{let A=await F.promises.readFile(w,"utf8");return{name:d,content:A}}catch{}}return null}})),this.toolRegistry.register(Ra({manageSkill:async d=>{let h=W.join(P[0]??W.join($e(),".openclaw","skills"),d.name),v=W.join(h,"SKILL.md");switch(d.action){case"create":return await F.promises.mkdir(h,{recursive:!0}),await F.promises.writeFile(v,d.content??"","utf8"),{success:!0,message:`Skill "${d.name}" created`,path:h};case"edit":return await F.promises.writeFile(v,d.content??"","utf8"),{success:!0,message:`Skill "${d.name}" updated`,path:v};case"patch":{let w=await F.promises.readFile(v,"utf8");return!d.oldString||!w.includes(d.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await F.promises.writeFile(v,w.replace(d.oldString,d.newString??""),"utf8"),{success:!0,message:`Skill "${d.name}" patched`,path:v})}case"delete":return await F.promises.rm(h,{recursive:!0,force:!0}),{success:!0,message:`Skill "${d.name}" deleted`};case"write_file":{if(!d.filePath)return{success:!1,message:"filePath required for write_file"};let w=W.join(h,d.filePath);return await F.promises.mkdir(W.dirname(w),{recursive:!0}),await F.promises.writeFile(w,d.fileContent??"","utf8"),{success:!0,message:`File written: ${d.filePath}`,path:w}}case"remove_file":{if(!d.filePath)return{success:!1,message:"filePath required for remove_file"};let w=W.join(h,d.filePath);return await F.promises.unlink(w).catch(()=>{}),{success:!0,message:`File removed: ${d.filePath}`}}default:return{success:!1,message:`Unknown action: ${d.action}`}}}})),this.toolRegistry.register(Pa({abortSignal:void 0,currentForkDepth:0,forkAgent:async d=>{let h=Tn(d.agent);if(!h)return{agentId:"",status:"failed",error:`Unknown agent type: ${d.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let v=this.toolRegistry.getToolNames(),w=bn(v,h),U=this.toolRegistry.getToolManifest().filter(D=>w.includes(D.function.name)),K=h.toolAccessMode==="read-only"?"research":"code-repair",V=d.maxTurns??h.maxTurns??200,Q=await bt({promptMessages:[{role:"user",content:d.prompt}],tools:U,transport:this.currentTransport,toolInvoker:u,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:c,forkLabel:`agent-${d.agent}`,maxTurns:V,parentSignal:d.abortSignal,parentDepth:0,sidechainType:K,onEvent:D=>{D.type==="delta"&&D.text&&this.sendNotification("turn.subagent_delta",{agentType:d.agent,text:D.text})}}),ce=Q.events.filter(D=>D.type==="end"&&"content"in D).map(D=>D.content??"").join("")||Q.events.filter(D=>D.type==="delta"&&"text"in D).map(D=>D.text).join("");return{agentId:`fork-${d.agent}-${_e().slice(0,8)}`,status:Q.ok?"completed":"failed",output:ce||void 0,error:Q.error,tokensUsed:Q.totalUsage.prompt+Q.totalUsage.completion}}}));let M=W.join($e(),".openclaw","settings.json"),N=new Map([["model",{key:"model",value:this.currentModel??"",type:"string",description:"Default LLM model"}],["language",{key:"language",value:"zh-cn",type:"string",description:"UI / response language"}],["verbose",{key:"verbose",value:this.verbose,type:"boolean",description:"Enable verbose logging"}],["maxRounds",{key:"maxRounds",value:25,type:"number",description:"Default max tool-call rounds per turn"}],["theme",{key:"theme",value:"auto",type:"enum",description:"Color theme",options:["auto","light","dark"]}]]),H=async()=>{try{return JSON.parse(await F.promises.readFile(M,"utf8"))}catch{return{}}},ee=async d=>{await F.promises.mkdir(W.dirname(M),{recursive:!0}),await F.promises.writeFile(M,JSON.stringify(d,null,2),"utf8")};this.toolRegistry.register(Ma({getConfig:async d=>{let h=N.get(d);if(!h)return{success:!1,error:`Unknown key: ${d}`};let v=await H(),w=d in v?v[d]:h.value;return{success:!0,setting:{...h,value:w,readOnly:st.includes(d)}}},setConfig:async(d,h)=>{let v=N.get(d);if(!v)return{success:!1,error:`Unknown key: ${d}`};let w=await H(),A=d in w?w[d]:v.value;return w[d]=h,await ee(w),{success:!0,previousValue:A,setting:{...v,value:h}}},listConfig:async()=>{let d=await H();return{success:!0,settings:[...N.values()].map(v=>({...v,value:v.key in d?d[v.key]:v.value,readOnly:st.includes(v.key)}))}},resetConfig:async d=>{let h=N.get(d);if(!h)return{success:!1,error:`Unknown key: ${d}`};let v=await H();return delete v[d],await ee(v),{success:!0,setting:h}},isValidKey:d=>N.has(d)}));let T=new Map,q=d=>{let h=/^(\d+)([smhd])$/.exec(d.trim());if(!h)return null;let v=parseInt(h[1],10),w=h[2];return v*({s:1e3,m:6e4,h:36e5,d:864e5}[w]??6e4)},re=d=>{d.timerId&&clearTimeout(d.timerId);let h=q(d.schedule);h&&(d.timerId=setTimeout(()=>{d.lastRunAt=new Date().toISOString(),d.repeat.completed++,d.lastStatus="success",l.info(`[cron] triggered job ${d.id} (${d.name})`),d.repeat.times===null||d.repeat.completed<d.repeat.times?re(d):(d.state="paused",d.enabled=!1)},h),d.nextRunAt=new Date(Date.now()+h).toISOString())};Le(async()=>{for(let d of T.values())d.timerId&&clearTimeout(d.timerId)}),this.toolRegistry.register(Ea({createJob:async d=>{let h=`cron_${_e().slice(0,8)}`,v={id:h,name:d.name??`Job ${h}`,prompt:d.prompt,schedule:d.schedule,scheduleDisplay:d.schedule,state:"scheduled",enabled:!0,repeat:{times:d.repeat??null,completed:0},allowedTools:d.allowedTools};return T.set(h,v),re(v),{success:!0,job:{...v,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...T.values()].map(h=>({...h,timerId:void 0}))}),getJob:async d=>{let h=T.get(d);return h?{success:!0,job:{...h,timerId:void 0}}:{success:!1,error:`Job not found: ${d}`}},updateJob:async(d,h)=>{let v=T.get(d);return v?(h.prompt!==void 0&&(v.prompt=h.prompt),h.schedule!==void 0&&(v.schedule=h.schedule,v.scheduleDisplay=h.schedule),h.name!==void 0&&(v.name=h.name),h.enabled!==void 0&&(v.enabled=h.enabled,v.state=h.enabled?"scheduled":"paused"),h.repeat!==void 0&&(v.repeat.times=h.repeat),h.allowedTools!==void 0&&(v.allowedTools=h.allowedTools),v.enabled?re(v):v.timerId&&(clearTimeout(v.timerId),v.timerId=void 0),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${d}`}},deleteJob:async d=>{let h=T.get(d);return h?(h.timerId&&clearTimeout(h.timerId),T.delete(d),{success:!0}):{success:!1,error:`Job not found: ${d}`}},pauseJob:async d=>{let h=T.get(d);return h?(h.state="paused",h.enabled=!1,h.timerId&&(clearTimeout(h.timerId),h.timerId=void 0),{success:!0,job:{...h,timerId:void 0}}):{success:!1,error:`Job not found: ${d}`}},resumeJob:async d=>{let h=T.get(d);return h?(h.state="scheduled",h.enabled=!0,re(h),{success:!0,job:{...h,timerId:void 0}}):{success:!1,error:`Job not found: ${d}`}},triggerJob:async d=>{let h=T.get(d);return h?(h.lastRunAt=new Date().toISOString(),h.repeat.completed++,h.lastStatus="success",{success:!0,job:{...h,timerId:void 0}}):{success:!1,error:`Job not found: ${d}`}},validateSchedule:d=>q(d)!==null||/^\d{1,2}\s/.test(d)?null:`Invalid schedule: ${d}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let J=new Map;Le(async()=>{for(let d of J.values())d.cleanup();J.clear()}),this.toolRegistry.register(Oa({startMonitor:async d=>{if(J.has(d.monitorId))return{action:"start",success:!1,error:`Monitor "${d.monitorId}" already exists.`};let h={monitorId:d.monitorId,source:d.source,target:d.target,conditions:d.conditions,startedAt:Date.now(),timeoutSeconds:d.timeoutSeconds,eventCount:0},v=()=>{};if(d.source==="file")try{let w=F.watch(d.target,{persistent:!1},()=>{h.eventCount++,l.info(`[monitor] file change detected: ${d.target}`)});v=()=>w.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${d.target}`}}if(d.timeoutSeconds>0){let w=setTimeout(()=>{let U=J.get(d.monitorId);U&&(U.cleanup(),J.delete(d.monitorId))},d.timeoutSeconds*1e3),A=v;v=()=>{clearTimeout(w),A()}}return J.set(d.monitorId,{info:h,cleanup:v}),{action:"start",success:!0,monitorId:d.monitorId}},stopMonitor:async d=>{let h=J.get(d);return h?(h.cleanup(),J.delete(d),{action:"stop",success:!0,monitorId:d}):{action:"stop",success:!1,error:`Monitor "${d}" not found.`}},listMonitors:async()=>[...J.values()].map(d=>d.info)}));let te=new Map;this.toolRegistry.register(La({createTeam:async d=>{if(te.has(d.teamName))return{success:!1,error:`Team "${d.teamName}" already exists.`};let h={name:d.teamName,description:d.description,leadId:this.currentSessionId??"default",members:d.members??[],createdAt:new Date().toISOString()};return te.set(d.teamName,h),{success:!0,team:h}},deleteTeam:async d=>te.has(d)?(te.delete(d),{success:!0}):{success:!1,error:`Team "${d}" not found.`},listTeams:async()=>({success:!0,teams:[...te.values()]}),getTeamStatus:async d=>{let h=te.get(d);return h?{success:!0,team:h}:{success:!1,error:`Team "${d}" not found.`}}}));let $=e?.workdir??process.cwd(),j=Da({projectRoot:$,ruleEngine:_,hooks:c,log:d=>l.info(`[settings] ${d}`)});Le(async()=>{j()}),this.currentSessionId&&c.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let ne=e?.workdir??process.cwd();return Ls({projectRoot:ne,sessionId:this.currentSessionId,hooks:c,log:d=>l.debug(d),onInstructionCacheReset:Ws}).then(d=>{this.fileWatcher=d,Le(async()=>{this.fileWatcher?.stop()})}).catch(d=>{l.warn(`[file-watcher] init error: ${d instanceof Error?d.message:d}`)}),this.agent=new Ve({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:u,log:l,hooks:c,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=n,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=r,this.log(`created Agent (provider: ${o}, model: ${r})`),this.agent}sendResponse(e,n,o){let r={jsonrpc:"2.0",id:e};o?r.error=o:r.result=n,this.writeStdout(r)}sendNotification(e,n){let o={jsonrpc:"2.0",method:e,params:n};this.writeStdout(o)}writeStdout(e){process.stdout.write(`${JSON.stringify(e)}
|
|
359
|
+
`)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
|
|
360
|
+
`)}};function ja(t){let e={verbose:!1};for(let n of t.slice(2))(n==="--verbose"||n==="-v")&&(e.verbose=!0);return e}var Pg=ja(process.argv),Fa=new Kt({verbose:Pg.verbose}),Ua=()=>{Fa.stop(),process.exit(0)};process.on("SIGTERM",Ua);process.on("SIGINT",Ua);Fa.start();
|