qlogicagent 0.6.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/agent.js +9 -9
  2. package/dist/cli.js +158 -148
  3. package/dist/index.js +158 -148
  4. package/dist/orchestration.js +9 -9
  5. package/dist/types/agent/types.d.ts +50 -0
  6. package/dist/types/cli/stdio-server.d.ts +60 -0
  7. package/dist/types/cli/tool-bootstrap.d.ts +5 -13
  8. package/dist/types/llm/index.d.ts +7 -1
  9. package/dist/types/llm/media-client.d.ts +43 -0
  10. package/dist/types/llm/media-transport.d.ts +80 -0
  11. package/dist/types/llm/model-catalog.d.ts +4 -4
  12. package/dist/types/llm/provider-def.d.ts +7 -0
  13. package/dist/types/llm/provider-registry.d.ts +1 -1
  14. package/dist/types/llm/transport.d.ts +2 -0
  15. package/dist/types/llm/transports/anthropic-messages.d.ts +34 -11
  16. package/dist/types/llm/transports/gemini-media.d.ts +21 -0
  17. package/dist/types/llm/transports/minimax-media.d.ts +21 -0
  18. package/dist/types/llm/transports/openai-chat.d.ts +1 -1
  19. package/dist/types/llm/transports/openai-media.d.ts +24 -0
  20. package/dist/types/llm/transports/qwen-media.d.ts +25 -0
  21. package/dist/types/llm/transports/volcengine-media.d.ts +34 -0
  22. package/dist/types/orchestration/tool-loop/tool-schema.d.ts +1 -2
  23. package/dist/types/protocol/index.d.ts +7 -0
  24. package/dist/types/protocol/methods.d.ts +380 -0
  25. package/dist/types/protocol/notifications.d.ts +296 -0
  26. package/dist/types/runtime/prompt/environment-context.d.ts +1 -1
  27. package/dist/types/runtime/session/index.d.ts +1 -1
  28. package/dist/types/runtime/session/session-state.d.ts +18 -9
  29. package/dist/types/skills/memory/qmemory-adapter.d.ts +1 -0
  30. package/dist/types/skills/tools/shell/shell-exec.d.ts +2 -0
  31. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,37 +1,37 @@
1
1
  #!/usr/bin/env node
2
- var Sl=Object.defineProperty;var B=(o,e)=>()=>(o&&(e=o(o=0)),e);var Zn=(o,e)=>{for(var t in e)Sl(o,t,{get:e[t],enumerable:!0})};function ao(o){return{role:"assistant",content:"",tool_calls:o}}function Ge(o,e){return{role:"tool",tool_call_id:o,content:JSON.stringify(e.ok?{ok:!0,payload:e.payload}:{ok:!1,error:e.error??"Tool invoke failed"})}}var Qn=B(()=>{"use strict"});function Re(o,e){if(!o)return!1;let t=o.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(t):t.includes(n))}function Bl(o){return Re(o,_e.format)}function er(o){return Re(o,_e.rateLimit)}function ql(o){return Re(o,_e.timeout)}function Wl(o){return _l.test(o)}function lo(o){let e=o.toLowerCase();return e?o.length>Pl?Ml.test(e):Re(e,_e.billing)?!0:Rl.test(o)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function tr(o){return Re(o,_e.authPermanent)}function Hl(o){return Re(o,_e.auth)}function or(o){return Re(o,_e.overloaded)}function Ce(o,e){return e.some(t=>o.includes(t))}function Gl(o){return Ce(o,Il)||Ce(o,Ol)&&o.includes("limit")||o.includes("billing hard limit")||o.includes("hard limit reached")||o.includes("maximum allowed")&&o.includes("limit")}function zl(o){let e=Ce(o,Ll),t=o.includes("spend limit")||o.includes("spending limit"),n=Ce(o,Nl);return Ce(o,$l)&&Ce(o,Dl)||e&&(o.includes("usage limit")||t)||e&&o.includes("limit")&&o.includes("reset")||n&&o.includes("limit")&&(t||Ce(o,jl))}function Vl(o){return o.trim().toLowerCase().replace(Ul,"").trim()}function nr(o){let e=Vl(o);return!e||Gl(e)?"billing":er(e)||zl(e)?"rate_limit":"billing"}function Kl(o){return Fl.test(o)?nr(o):null}function rr(o){let e=o.match(Al);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function Jl(o){if(!o)return!1;let e=o.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function Yl(o){let e=o.trim();if(!e)return!1;let t=rr(e);return t?El.has(t.code):!1}function sr(o,e){return typeof o!="number"||!Number.isFinite(o)?null:o===402?e?nr(e):"billing":o===429?"rate_limit":o===401||o===403?e&&tr(e)?"auth_permanent":"auth":o===408?"timeout":o===503?e&&or(e)?"overloaded":"timeout":o===502||o===504?"timeout":o===529?"overloaded":o===400?e&&lo(e)?"billing":"format":null}function Xl(o){if(!o)return!1;let e=o.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(o)||/\b404\b/.test(o)&&/not[-_ ]?found/i.test(o))}function Zl(o){if(!o)return!1;let e=o.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 ir(o){if(Zl(o))return"session_expired";if(Xl(o))return"model_not_found";let e=Kl(o);return e||(Wl(o)?lo(o)?"billing":"rate_limit":er(o)?"rate_limit":or(o)?"overloaded":Yl(o)?rr(o.trim())?.code===529?"overloaded":"timeout":Jl(o)?"timeout":Bl(o)?"format":lo(o)?"billing":ql(o)?"timeout":tr(o)?"auth_permanent":Hl(o)?"auth":null)}var _l,_e,Rl,Ml,Pl,Al,El,Il,Ol,Ll,$l,Dl,Nl,jl,Fl,Ul,ar=B(()=>{"use strict";_l=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,_e={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]},Rl=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ml=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Pl=512,Al=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,El=new Set([500,502,503,504,521,522,523,524,529]),Il=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ol=["upgrade your plan","upgrade plan","current plan","subscription"],Ll=["daily","weekly","monthly"],$l=["try again","retry","temporary","cooldown"],Dl=["usage limit","rate limit","organization usage"],Nl=["organization","workspace"],jl=["billing period","exceeded","reached","exhausted"],Fl=/["']?(?: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,Ul=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function Ne(o,e){let t=sr(o,e)??(e?ir(e):null);return t?Ql[t]:typeof o=="number"&&o>=400&&o<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function co(o){return ec[o]}var Ql,ec,lr=B(()=>{"use strict";ar();Ql={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"},ec={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 Ye(o){return typeof o.compressAsync=="function"}function tc(o,e){if(o.length<=e)return o;let t=o.slice(0,e);if(o.trimStart().startsWith("{")||o.trimStart().startsWith("[")){let s=Math.max(t.lastIndexOf("},"),t.lastIndexOf("],"),t.lastIndexOf(`}
2
+ var Fl=Object.defineProperty;var q=(o,e)=>()=>(o&&(e=o(o=0)),e);var pr=(o,e)=>{for(var t in e)Fl(o,t,{get:e[t],enumerable:!0})};function vo(o,e){return{role:"assistant",content:e||null,tool_calls:o}}function Je(o,e){let t=e.ok?typeof e.payload=="string"?e.payload:JSON.stringify(e.payload??""):`Error: ${e.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:o,content:t}}var mr=q(()=>{"use strict"});function Ae(o,e){if(!o)return!1;let t=o.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(t):t.includes(n))}function nc(o){return Ae(o,Pe.format)}function gr(o){return Ae(o,Pe.rateLimit)}function rc(o){return Ae(o,Pe.timeout)}function sc(o){return Wl.test(o)}function wo(o){let e=o.toLowerCase();return e?o.length>Gl?Hl.test(e):Ae(e,Pe.billing)?!0:ql.test(o)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function fr(o){return Ae(o,Pe.authPermanent)}function ic(o){return Ae(o,Pe.auth)}function hr(o){return Ae(o,Pe.overloaded)}function Me(o,e){return e.some(t=>o.includes(t))}function ac(o){return Me(o,Kl)||Me(o,Jl)&&o.includes("limit")||o.includes("billing hard limit")||o.includes("hard limit reached")||o.includes("maximum allowed")&&o.includes("limit")}function lc(o){let e=Me(o,Yl),t=o.includes("spend limit")||o.includes("spending limit"),n=Me(o,Zl);return Me(o,Xl)&&Me(o,Ql)||e&&(o.includes("usage limit")||t)||e&&o.includes("limit")&&o.includes("reset")||n&&o.includes("limit")&&(t||Me(o,ec))}function cc(o){return o.trim().toLowerCase().replace(oc,"").trim()}function yr(o){let e=cc(o);return!e||ac(e)?"billing":gr(e)||lc(e)?"rate_limit":"billing"}function uc(o){return tc.test(o)?yr(o):null}function br(o){let e=o.match(zl);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function dc(o){if(!o)return!1;let e=o.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function pc(o){let e=o.trim();if(!e)return!1;let t=br(e);return t?Vl.has(t.code):!1}function Tr(o,e){return typeof o!="number"||!Number.isFinite(o)?null:o===402?e?yr(e):"billing":o===429?"rate_limit":o===401||o===403?e&&fr(e)?"auth_permanent":"auth":o===408?"timeout":o===503?e&&hr(e)?"overloaded":"timeout":o===502||o===504?"timeout":o===529?"overloaded":o===400?e&&wo(e)?"billing":"format":null}function mc(o){if(!o)return!1;let e=o.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(o)||/\b404\b/.test(o)&&/not[-_ ]?found/i.test(o))}function gc(o){if(!o)return!1;let e=o.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 kr(o){if(gc(o))return"session_expired";if(mc(o))return"model_not_found";let e=uc(o);return e||(sc(o)?wo(o)?"billing":"rate_limit":gr(o)?"rate_limit":hr(o)?"overloaded":pc(o)?br(o.trim())?.code===529?"overloaded":"timeout":dc(o)?"timeout":nc(o)?"format":wo(o)?"billing":rc(o)?"timeout":fr(o)?"auth_permanent":ic(o)?"auth":null)}var Wl,Pe,ql,Hl,Gl,zl,Vl,Kl,Jl,Yl,Xl,Ql,Zl,ec,tc,oc,xr=q(()=>{"use strict";Wl=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Pe={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]},ql=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Hl=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Gl=512,zl=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,Vl=new Set([500,502,503,504,521,522,523,524,529]),Kl=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Jl=["upgrade your plan","upgrade plan","current plan","subscription"],Yl=["daily","weekly","monthly"],Xl=["try again","retry","temporary","cooldown"],Ql=["usage limit","rate limit","organization usage"],Zl=["organization","workspace"],ec=["billing period","exceeded","reached","exhausted"],tc=/["']?(?: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,oc=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function We(o,e){let t=Tr(o,e)??(e?kr(e):null);return t?fc[t]:typeof o=="number"&&o>=400&&o<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function So(o){return hc[o]}var fc,hc,vr=q(()=>{"use strict";xr();fc={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"},hc={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 et(o){return typeof o.compressAsync=="function"}function yc(o,e){if(o.length<=e)return o;let t=o.slice(0,e);if(o.trimStart().startsWith("{")||o.trimStart().startsWith("[")){let s=Math.max(t.lastIndexOf("},"),t.lastIndexOf("],"),t.lastIndexOf(`}
3
3
  `),t.lastIndexOf(`]
4
4
  `));if(s>e*.5)return t.slice(0,s+1)+`
5
5
  [...truncated: ${o.length-s-1} chars omitted]`}let r=t.lastIndexOf(`
6
6
  `);return r>e*.7?t.slice(0,r)+`
7
7
  [...truncated: ${o.length-r} chars omitted]`:t+`
8
- [...truncated: ${o.length-e} chars omitted]`}function uo(...o){return{compress(e,t){let n=e,r=0,s=[];for(let i of o){let a=i.compress(n,t);n=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function po(...o){return{compress(e,t){let n=e,r=0,s=[];for(let i of o){let a=i.compress(n,t);n=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(e,t){let n=e,r=0,s=[],i=0,a=!1,l=!1;for(let c of o){let u=Ye(c)?await c.compressAsync(n,t):c.compress(n,t);n=u.messages,r+=u.droppedCount,u.droppedCount>0&&s.push(u.strategy),u.metrics&&(i+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:n,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 ur(o,e){let t=o.filter(i=>i.role==="user"),n=o.filter(i=>i.tool_calls!=null),r=o.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. ${n.length>0?`${n.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 ${t.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","",...o.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(`
9
- `)}function kt(o={}){let e={...dr,...o},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function Xe(o,e){let t=o/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function oc(o){let e=[],t=[];for(let n of o)n.role==="system"?e.push(n):t.push(n);return{system:e,nonSystem:t}}function mo(o){let e=typeof o.content=="string"?o.content:o.content!=null?JSON.stringify(o.content):"";return Math.ceil(e.length/4)}function Tt(o){let e=Math.min(o.length,5),t=[];for(let n=0;n<e;n++){let r=o[n],s=typeof r.content=="string"?r.content.slice(0,200):"";t.push(`${r.role}:${s}`)}return t.join("|")}function rc(o){let e=new Map;for(let t=0;t<o.length;t++){let n=o[t];if(n.tool_calls&&Array.isArray(n.tool_calls))for(let r of n.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,t)}catch{}}n.role==="tool"&&n.name&&/read|edit|write|file/i.test(n.name)}return[...e.entries()].sort((t,n)=>n[1]-t[1]).map(([t])=>t)}async function go(o,e,t){let n=t.estimateTokens??(d=>Math.ceil(d.length/4)),r=rc(e);if(r.length===0)return o;let s=o.map(d=>typeof d.content=="string"?d.content:"").join(`
10
- `),i=r.filter(d=>!s.includes(d));if(i.length===0)return o;let a=t.maxTokenBudget,l=[],c=0;for(let d of i){if(c>=t.maxFiles||a<=0)break;let m=await t.readFile(d);if(!m)continue;let h=n(m);h>a||(a-=h,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
8
+ [...truncated: ${o.length-e} chars omitted]`}function Co(...o){return{compress(e,t){let n=e,r=0,s=[];for(let i of o){let a=i.compress(n,t);n=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function _o(...o){return{compress(e,t){let n=e,r=0,s=[];for(let i of o){let a=i.compress(n,t);n=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(e,t){let n=e,r=0,s=[],i=0,a=!1,l=!1;for(let c of o){let u=et(c)?await c.compressAsync(n,t):c.compress(n,t);n=u.messages,r+=u.droppedCount,u.droppedCount>0&&s.push(u.strategy),u.metrics&&(i+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:n,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 Sr(o,e){let t=o.filter(i=>i.role==="user"),n=o.filter(i=>i.tool_calls!=null),r=o.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. ${n.length>0?`${n.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 ${t.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","",...o.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(`
9
+ `)}function Et(o={}){let e={...Cr,...o},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function tt(o,e){let t=o/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function bc(o){let e=[],t=[];for(let n of o)n.role==="system"?e.push(n):t.push(n);return{system:e,nonSystem:t}}function Ro(o){let e=typeof o.content=="string"?o.content:o.content!=null?JSON.stringify(o.content):"";return Math.ceil(e.length/4)}function At(o){let e=Math.min(o.length,5),t=[];for(let n=0;n<e;n++){let r=o[n],s=typeof r.content=="string"?r.content.slice(0,200):"";t.push(`${r.role}:${s}`)}return t.join("|")}function kc(o){let e=new Map;for(let t=0;t<o.length;t++){let n=o[t];if(n.tool_calls&&Array.isArray(n.tool_calls))for(let r of n.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,t)}catch{}}n.role==="tool"&&n.name&&/read|edit|write|file/i.test(n.name)}return[...e.entries()].sort((t,n)=>n[1]-t[1]).map(([t])=>t)}async function Mo(o,e,t){let n=t.estimateTokens??(d=>Math.ceil(d.length/4)),r=kc(e);if(r.length===0)return o;let s=o.map(d=>typeof d.content=="string"?d.content:"").join(`
10
+ `),i=r.filter(d=>!s.includes(d));if(i.length===0)return o;let a=t.maxTokenBudget,l=[],c=0;for(let d of i){if(c>=t.maxFiles||a<=0)break;let m=await t.readFile(d);if(!m)continue;let y=n(m);y>a||(a-=y,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
11
11
 
12
- ${m}`}))}if(l.length===0)return o;let u=[...o],g=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(g=d);return u.splice(g+1,0,...l),u}function fo(o,e,t=mo){if(e.size===0)return{messages:o,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of o){let l=a.tool_call_id??"";if(l&&e.has(l)){n+=t(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:n,removedCount:r,boundaryMessage:i}}var cr,je,Me,ze,Ve,dr,Ke,Je,nc,ke,ho=B(()=>{"use strict";cr=4,je=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let n=[],r=[];for(let u of e)u.role==="system"?n.push(u):r.push(u);let s=t;for(let u of n)s-=this.estimateTokens(u);let i;for(let u of r)if(u.role==="user"){i=u;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...n,i]:n,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let u=r.length-1;u>=0;u--){let g=r[u];if(g===i)continue;let d=this.estimateTokens(g);if(s-d<0&&l>=cr)break;if(s-d<0&&l<cr){a.unshift(g),l++;continue}s-=d,a.unshift(g),l++}let c=[...n];return i&&!a.includes(i)&&c.push(i),c.push(...a),{messages:c,droppedCount:r.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},Me=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,t){let n=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(n++,{...s,content:tc(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};ze=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??mo,taskContext:e.taskContext}}compress(e,t){return{messages:e,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(e,t){let n=Date.now(),{system:r,nonSystem:s}=oc(e),i=e.reduce((_,M)=>_+this.config.estimateTokens(M),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let _=0;_<s.length&&(s[_].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));_++)a=_+1;let c=Math.max(a,s.length-this.config.protectedTailMessages);if(c<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let u=s.slice(0,a),g=s.slice(a,c),d=s.slice(c),m=ur(g,{taskContext:this.config.taskContext}),h=await this.config.summarize(g,m),f={role:"system",content:`[Conversation summary \u2014 ${g.length} messages compressed]
12
+ ${m}`}))}if(l.length===0)return o;let u=[...o],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function Po(o,e,t=Ro){if(e.size===0)return{messages:o,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of o){let l=a.tool_call_id??"";if(l&&e.has(l)){n+=t(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:n,removedCount:r,boundaryMessage:i}}var wr,qe,Ee,Ye,Xe,Cr,Qe,Ze,Tc,xe,Ao=q(()=>{"use strict";wr=4,qe=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let n=[],r=[];for(let u of e)u.role==="system"?n.push(u):r.push(u);let s=t;for(let u of n)s-=this.estimateTokens(u);let i;for(let u of r)if(u.role==="user"){i=u;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...n,i]:n,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let u=r.length-1;u>=0;u--){let p=r[u];if(p===i)continue;let d=this.estimateTokens(p);if(s-d<0&&l>=wr)break;if(s-d<0&&l<wr){a.unshift(p),l++;continue}s-=d,a.unshift(p),l++}let c=[...n];return i&&!a.includes(i)&&c.push(i),c.push(...a),{messages:c,droppedCount:r.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},Ee=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,t){let n=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(n++,{...s,content:yc(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};Ye=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??Ro,taskContext:e.taskContext}}compress(e,t){return{messages:e,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(e,t){let n=Date.now(),{system:r,nonSystem:s}=bc(e),i=e.reduce((C,R)=>C+this.config.estimateTokens(R),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let C=0;C<s.length&&(s[C].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));C++)a=C+1;let c=Math.max(a,s.length-this.config.protectedTailMessages);if(c<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let u=s.slice(0,a),p=s.slice(a,c),d=s.slice(c),m=Sr(p,{taskContext:this.config.taskContext}),y=await this.config.summarize(p,m),h={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
13
13
 
14
- ${h}`},T=[...r,...u,f,...d],y=Date.now()-n,v=T.reduce((_,M)=>_+this.config.estimateTokens(M),0);return{messages:T,droppedCount:g.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:v,compressionRatio:i>0?v/i:1,latencyMs:y,usedLlm:!0,cacheInvalidated:!0}}}},Ve=class{config;constructor(e){this.config=e}compress(e,t){let n=Tt(e),r=this.config.inner.compress(e,t),s=Tt(r.messages),i=n!==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,t){let n=Tt(e),r=Ye(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=Tt(r.messages),i=n!==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}}}},dr={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};Ke=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 t=0,n=0,r=0,s=0,i=0;for(let a of this.events)t+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,n+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:e,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:t/e,averageLatencyMs:n/e,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},Je=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}))}};nc=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"]),ke=class{constructor(e=20,t=mo){this.preserveRecentCount=e;this.estimateTokens=t}preserveRecentCount;estimateTokens;compress(e,t){if(e.length<=this.preserveRecentCount)return{messages:e,droppedCount:0,strategy:"micro-compact"};let n=e.length-this.preserveRecentCount,r=0,s=0;return{messages:e.map((a,l)=>{if(l>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!nc.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return s+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function yo(){return{stages:[]}}function bo(o,e,t){let n=t?.thresholdMessages??40;if(o.filter(a=>a.role!=="system").length<=n)return{messages:o,stagedCount:0};let s=pr(o,e),i=sc(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=pr(o,e),{messages:s,stagedCount:i.length}}function To(o,e){let t=0;for(let n of e.stages)n.committed||(n.committed=!0,t++);return t===0?{messages:o,committed:0}:{messages:mr(o,e),committed:t}}function pr(o,e){return e.stages.filter(n=>n.committed).length===0?o:mr(o,e)}function mr(o,e){let t=e.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...o];for(let r of t){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),l={role:"system",content:r.summary};n.splice(s,a-s,l)}return n}function sc(o,e,t){let n=Math.max(0,o.length-Math.floor(t/2)),r=[],s=new Set(e.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<n;l++){let c=o[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let g=`${i}-${i+a}`;s.has(g)||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 gr=B(()=>{"use strict"});function ic(o){return!(!o.ok||o.existingSkillName||!o.multiStep||o.toolCallCount<3||o.distinctToolCount<2)}function ac(o){return o.existingSkillName?o.feedback==="negative":!1}function xt(o,e){return ac(o)?{type:"skill.improve",skillName:o.existingSkillName,reason:"negative user feedback on existing skill execution"}:ic(o)?{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:o.toolCallCount}:null}var fr=B(()=>{"use strict"});function hr(o){return o.function&&typeof o.function=="object"&&typeof o.function.name=="string"?o.function.name.trim():typeof o.name=="string"?o.name.trim():""}function lc(o){return o==="enabled-eligible"||o==="installed-awaiting-approval"}function cc(o){return new Map((o??[]).map(e=>[e.toolName,e]))}function uc(o){if(!o.eligibility?.length)return[...o.tools];let e=cc(o.eligibility);return o.tools.filter(t=>{let n=hr(t);if(!n)return!1;let r=e.get(n);return!r||lc(r.status)})}function dc(o){let e=[],t=o.compatibility??{},n=o.toolChoice;if(o.thinkingEnabled&&t.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&t.allowRequiredToolChoice===!1){let r=t.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&t.allowNamedToolChoice===!1){let r=t.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:e}}function ko(o){let e=dc({toolChoice:o.toolChoice,thinkingEnabled:o.thinkingEnabled,compatibility:o.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],r=uc({tools:o.tools,eligibility:o.eligibility});if(!t||t==="auto")return{tools:r,normalizedToolChoice:t,warnings:n};if(t==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(t==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof t=="object"&&!Array.isArray(t)&&t.type==="function"){let s=t.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=>hr(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:n}}return{tools:r,normalizedToolChoice:t,warnings:n}}var yr=B(()=>{"use strict"});function br(o){return o==null?[]:typeof o=="string"?o.length>0?[{type:"text",text:o}]:[]:Array.isArray(o)?o:[{type:"text",text:String(o)}]}function gc(o,e){return{...o,content:[...br(o.content),...br(e.content)]}}function fc(o){if(!o||typeof o!="object")return!1;if(o.function&&typeof o.function=="object"){let e=o.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof o.name=="string"&&o.name.length>0}function hc(o){return new Set((o??pc).map(e=>e.trim().toLowerCase()))}function yc(o,e){return o?hc(e).has(o.trim().toLowerCase()):!1}function xo(o){if(!Array.isArray(o)||o.length===0)return[...o];let e=o.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(c=>fc(c));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),t=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&&t.add(l.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),r=new Set;for(let a of n)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 n){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...u}=a;u.content!=null&&u.content!==""&&s.push(u);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]=gc(l,a);continue}i.push(a)}return i}function vo(o,e){return yc(e?.stopReason,e?.forcedStopReasons)?o.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let r of mc)delete n[r];return n}):[...o]}function wo(o,e){let t=e?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),n=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of o)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||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:t}));return r}function So(o,e){let t=xo(o),n=vo(t,e);return wo(n,e)}var pc,mc,Co=B(()=>{"use strict";pc=["stop","aborted","timeout","cancelled","interrupted","error"],mc=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function bc(o){let e=new Set,t=new Set;for(let n of o){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&e.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id)}return[...e].filter(n=>!t.has(n))}function Tc(o){let e=new Set;for(let t of o)t.role==="tool"&&typeof t.tool_call_id=="string"&&t.tool_call_id&&e.add(t.tool_call_id);return[...e]}function kc(o){return{round:o.round??0,maxRounds:o.maxRounds,pendingToolCallIds:[...o.pendingToolCallIds??[]],completedToolCallIds:[...o.completedToolCallIds??[]],lastStopReason:o.lastStopReason,replayMessages:[...o.replayMessages??[]]}}function _o(o,e){return{round:o.round+1,maxRounds:o.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??o.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??o.completedToolCallIds],lastStopReason:e.lastStopReason??o.lastStopReason,replayMessages:[...e.replayMessages??o.replayMessages]}}function vt(o,e){return{round:o.round,maxRounds:o.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??o.completedToolCallIds],lastStopReason:e.lastStopReason??o.lastStopReason,replayMessages:[...e.replayMessages??o.replayMessages]}}function wt(o){let e=[],t=xo(o.replayMessages);t.length!==o.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=vo(t,o.options);n.some((s,i)=>s!==t[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=wo(n,o.options);return r.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:kc({maxRounds:o.maxRounds,round:o.round,lastStopReason:o.lastStopReason,replayMessages:r,pendingToolCallIds:bc(r),completedToolCallIds:Tc(r)}),recoveryActions:e}}var Tr=B(()=>{"use strict";Co()});function Ro(o){return o?xc.has(o):!0}function Mo(o){return o===429||o===529}function St(o,e=500,t=32e3){let n=Math.min(e*Math.pow(2,o-1),t);return n+Math.floor(Math.random()*n*.25)}function Po(){let o=process.env.QLOGICAGENT_PERSISTENT_RETRY;return o==="1"||o==="true"}var xc,Kf,Ze,kr=B(()=>{"use strict";xc=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);Kf={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};Ze=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Ao(o,e){if(e.allowedTools&&e.allowedTools.length>0){let t=new Set(e.allowedTools);return o.filter(n=>t.has(n))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let t=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 o.filter(n=>!t.has(n))}return e.canFork?[...o]:o.filter(t=>t!=="agent")}var Eo=B(()=>{"use strict"});function Io(o){return Mc.find(e=>e.name===o)}var vc,wc,Sc,Cc,_c,Rc,Mc,Oo=B(()=>{"use strict";vc={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},wc={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},Sc={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","todo","tool_search"],canFork:!1},Cc={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},_c={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},Rc={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},Mc=[vc,wc,Sc,Cc,_c,Rc]});var xr=B(()=>{"use strict"});function Lo(o){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:o.maxOutputTokens,consecutiveTruncations:0,aborted:o.abortSignal?.aborted??!1}}function $o(o,e){if(o.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let t=e.contextWindowTokens-e.responseBufferTokens-o.currentMaxOutputTokens,n=t>0?o.promptTokens/t*100:100;return o.promptTokens>=t?o.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:t-o.promptTokens}:{level:"ok"}}function Do(o,e,t){let n=o.message?.toLowerCase()??"",r=o.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&t.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:{action:"abort",reason:n||"unknown_error"}}function No(o,e,t){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:o.currentMaxOutputTokens};if(o.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:o.currentMaxOutputTokens};let n=Math.min(o.currentMaxOutputTokens*2,t);return n<=o.currentMaxOutputTokens?{shouldEscalate:!1,newMax:o.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function jo(o,e){return o.aborted?!0:e.abortSignal?.aborted?(o.aborted=!0,!0):!1}var vr=B(()=>{"use strict"});function Fo(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Fe(o,e=Pc){return!(o.attemptedThisTurn||o.consecutiveFailures>=e.maxConsecutiveFailures)}var Pc,wr=B(()=>{"use strict";Pc={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var Qe=B(()=>{"use strict";Qn();lr();ho();ho();gr();fr();yr();Co();Tr();kr();Eo();Oo();xr();vr();wr()});function Uo(o,e){let t=o.get(e.index);t||(t={id:"",name:"",arguments:""},o.set(e.index,t)),e.id&&(t.id=e.id),e.name&&(t.name+=e.name),t.arguments+=e.arguments}var Bo=B(()=>{"use strict"});var Sr,Cr,_r,Rr,Mr,Pr,Ar,Er,Ir,Or,et,Lr,$r,qo,Ct=B(()=>{"use strict";Sr=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Cr=3,_r=128e3,Rr=13e3,Mr=16384,Pr=65536,Ar=3,Er=65536,Ir=3e4,Or=3,et=5,Lr=5e4,$r=2e5,qo=2e3});import{mkdir as Ec,writeFile as Ic}from"fs/promises";import{join as Dr}from"path";import{tmpdir as Oc}from"os";function jr(){return{seenIds:new Set,replacements:new Map}}function Fr(o){return Dr(Oc(),"qlogicagent-sessions",o,Lc)}async function Dc(o){try{await Ec(Fr(o),{recursive:!0})}catch{}}function Nc(o,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Dr(Fr(o),`${t}.txt`)}function jc(o,e){if(o.length<=e)return{preview:o,hasMore:!1};let n=o.slice(0,e).lastIndexOf(`
15
- `),r=n>e*.5?n:e;return{preview:o.slice(0,r),hasMore:!0}}function Ur(o){return o.includes(Nr)}async function Br(o,e,t){await Dc(t);let n=Nc(t,e);try{await Ic(n,o,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:r,hasMore:s}=jc(o,qo);return{filepath:n,originalSize:o.length,preview:r,hasMore:s}}function qr(o){let e=`${Nr}
14
+ ${y}`},k=[...r,...u,h,...d],w=Date.now()-n,f=k.reduce((C,R)=>C+this.config.estimateTokens(R),0);return{messages:k,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:f,compressionRatio:i>0?f/i:1,latencyMs:w,usedLlm:!0,cacheInvalidated:!0}}}},Xe=class{config;constructor(e){this.config=e}compress(e,t){let n=At(e),r=this.config.inner.compress(e,t),s=At(r.messages),i=n!==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,t){let n=At(e),r=et(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=At(r.messages),i=n!==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}}}},Cr={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};Qe=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 t=0,n=0,r=0,s=0,i=0;for(let a of this.events)t+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,n+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:e,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:t/e,averageLatencyMs:n/e,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},Ze=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}))}};Tc=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"]),xe=class{constructor(e=20,t=Ro){this.preserveRecentCount=e;this.estimateTokens=t}preserveRecentCount;estimateTokens;compress(e,t){if(e.length<=this.preserveRecentCount)return{messages:e,droppedCount:0,strategy:"micro-compact"};let n=e.length-this.preserveRecentCount,r=0,s=0;return{messages:e.map((a,l)=>{if(l>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!Tc.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return s+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function Eo(){return{stages:[]}}function Io(o,e,t){let n=t?.thresholdMessages??40;if(o.filter(a=>a.role!=="system").length<=n)return{messages:o,stagedCount:0};let s=_r(o,e),i=xc(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=_r(o,e),{messages:s,stagedCount:i.length}}function Oo(o,e){let t=0;for(let n of e.stages)n.committed||(n.committed=!0,t++);return t===0?{messages:o,committed:0}:{messages:Rr(o,e),committed:t}}function _r(o,e){return e.stages.filter(n=>n.committed).length===0?o:Rr(o,e)}function Rr(o,e){let t=e.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...o];for(let r of t){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),l={role:"system",content:r.summary};n.splice(s,a-s,l)}return n}function xc(o,e,t){let n=Math.max(0,o.length-Math.floor(t/2)),r=[],s=new Set(e.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<n;l++){let c=o[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.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 Mr=q(()=>{"use strict"});function vc(o){return!(!o.ok||o.existingSkillName||!o.multiStep||o.toolCallCount<3||o.distinctToolCount<2)}function wc(o){return o.existingSkillName?o.feedback==="negative":!1}function It(o,e){return wc(o)?{type:"skill.improve",skillName:o.existingSkillName,reason:"negative user feedback on existing skill execution"}:vc(o)?{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:o.toolCallCount}:null}var Pr=q(()=>{"use strict"});function Ar(o){return o.function&&typeof o.function=="object"&&typeof o.function.name=="string"?o.function.name.trim():typeof o.name=="string"?o.name.trim():""}function Sc(o){return o==="enabled-eligible"||o==="installed-awaiting-approval"}function Cc(o){return new Map((o??[]).map(e=>[e.toolName,e]))}function _c(o){if(!o.eligibility?.length)return[...o.tools];let e=Cc(o.eligibility);return o.tools.filter(t=>{let n=Ar(t);if(!n)return!1;let r=e.get(n);return!r||Sc(r.status)})}function Rc(o){let e=[],t=o.compatibility??{},n=o.toolChoice;if(o.thinkingEnabled&&t.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&t.allowRequiredToolChoice===!1){let r=t.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&t.allowNamedToolChoice===!1){let r=t.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:e}}function Lo(o){let e=Rc({toolChoice:o.toolChoice,thinkingEnabled:o.thinkingEnabled,compatibility:o.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],r=_c({tools:o.tools,eligibility:o.eligibility});if(!t||t==="auto")return{tools:r,normalizedToolChoice:t,warnings:n};if(t==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(t==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof t=="object"&&!Array.isArray(t)&&t.type==="function"){let s=t.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=>Ar(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:n}}return{tools:r,normalizedToolChoice:t,warnings:n}}var Er=q(()=>{"use strict"});function Ir(o){return o==null?[]:typeof o=="string"?o.length>0?[{type:"text",text:o}]:[]:Array.isArray(o)?o:[{type:"text",text:String(o)}]}function Ac(o,e){return{...o,content:[...Ir(o.content),...Ir(e.content)]}}function Ec(o){if(!o||typeof o!="object")return!1;if(o.function&&typeof o.function=="object"){let e=o.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof o.name=="string"&&o.name.length>0}function Ic(o){return new Set((o??Mc).map(e=>e.trim().toLowerCase()))}function Oc(o,e){return o?Ic(e).has(o.trim().toLowerCase()):!1}function $o(o){if(!Array.isArray(o)||o.length===0)return[...o];let e=o.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(c=>Ec(c));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),t=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&&t.add(l.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),r=new Set;for(let a of n)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 n){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...u}=a;u.content!=null&&u.content!==""&&s.push(u);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]=Ac(l,a);continue}i.push(a)}return i}function Do(o,e){return Oc(e?.stopReason,e?.forcedStopReasons)?o.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let r of Pc)delete n[r];return n}):[...o]}function No(o,e){let t=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of o)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||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:t}));return r}function Uo(o,e){let t=$o(o),n=Do(t,e);return No(n,e)}var Mc,Pc,jo=q(()=>{"use strict";Mc=["stop","aborted","timeout","cancelled","interrupted","error"],Pc=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Lc(o){let e=new Set,t=new Set;for(let n of o){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&e.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id)}return[...e].filter(n=>!t.has(n))}function $c(o){let e=new Set;for(let t of o)t.role==="tool"&&typeof t.tool_call_id=="string"&&t.tool_call_id&&e.add(t.tool_call_id);return[...e]}function Dc(o){return{round:o.round??0,maxRounds:o.maxRounds,pendingToolCallIds:[...o.pendingToolCallIds??[]],completedToolCallIds:[...o.completedToolCallIds??[]],lastStopReason:o.lastStopReason,replayMessages:[...o.replayMessages??[]]}}function Fo(o,e){return{round:o.round+1,maxRounds:o.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??o.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??o.completedToolCallIds],lastStopReason:e.lastStopReason??o.lastStopReason,replayMessages:[...e.replayMessages??o.replayMessages]}}function Ot(o,e){return{round:o.round,maxRounds:o.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??o.completedToolCallIds],lastStopReason:e.lastStopReason??o.lastStopReason,replayMessages:[...e.replayMessages??o.replayMessages]}}function Lt(o){let e=[],t=$o(o.replayMessages);t.length!==o.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=Do(t,o.options);n.some((s,i)=>s!==t[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=No(n,o.options);return r.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Dc({maxRounds:o.maxRounds,round:o.round,lastStopReason:o.lastStopReason,replayMessages:r,pendingToolCallIds:Lc(r),completedToolCallIds:$c(r)}),recoveryActions:e}}var Or=q(()=>{"use strict";jo()});function Bo(o){return o?Nc.has(o):!0}function Wo(o){return o===429||o===529}function $t(o,e=500,t=32e3){let n=Math.min(e*Math.pow(2,o-1),t);return n+Math.floor(Math.random()*n*.25)}function qo(){let o=process.env.QLOGICAGENT_PERSISTENT_RETRY;return o==="1"||o==="true"}var Nc,$h,ot,Lr=q(()=>{"use strict";Nc=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);$h={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};ot=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Ho(o,e){if(e.allowedTools&&e.allowedTools.length>0){let t=new Set(e.allowedTools);return o.filter(n=>t.has(n))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let t=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 o.filter(n=>!t.has(n))}return e.canFork?[...o]:o.filter(t=>t!=="agent")}var Go=q(()=>{"use strict"});function zo(o){return Hc.find(e=>e.name===o)}var Uc,jc,Fc,Bc,Wc,qc,Hc,Vo=q(()=>{"use strict";Uc={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},jc={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},Fc={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","todo","tool_search"],canFork:!1},Bc={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Wc={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},qc={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},Hc=[Uc,jc,Fc,Bc,Wc,qc]});var $r=q(()=>{"use strict"});function Ko(o){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:o.maxOutputTokens,consecutiveTruncations:0,aborted:o.abortSignal?.aborted??!1}}function Jo(o,e){if(o.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let t=e.contextWindowTokens-e.responseBufferTokens-o.currentMaxOutputTokens,n=t>0?o.promptTokens/t*100:100;return o.promptTokens>=t?o.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:t-o.promptTokens}:{level:"ok"}}function Yo(o,e,t){let n=o.message?.toLowerCase()??"",r=o.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&t.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:{action:"abort",reason:n||"unknown_error"}}function Xo(o,e,t){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:o.currentMaxOutputTokens};if(o.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:o.currentMaxOutputTokens};let n=Math.min(o.currentMaxOutputTokens*2,t);return n<=o.currentMaxOutputTokens?{shouldEscalate:!1,newMax:o.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function Qo(o,e){return o.aborted?!0:e.abortSignal?.aborted?(o.aborted=!0,!0):!1}var Dr=q(()=>{"use strict"});function Zo(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function He(o,e=Gc){return!(o.attemptedThisTurn||o.consecutiveFailures>=e.maxConsecutiveFailures)}var Gc,Nr=q(()=>{"use strict";Gc={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var nt=q(()=>{"use strict";mr();vr();Ao();Ao();Mr();Pr();Er();jo();Or();Lr();Go();Vo();$r();Dr();Nr()});function en(o,e){let t=o.get(e.index);t||(t={id:"",name:"",arguments:""},o.set(e.index,t)),e.id&&(t.id=e.id),e.name&&(t.name+=e.name),t.arguments+=e.arguments}var tn=q(()=>{"use strict"});var Ur,jr,Fr,Br,Wr,qr,Hr,Gr,zr,Vr,rt,Kr,Jr,on,Dt=q(()=>{"use strict";Ur=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),jr=3,Fr=128e3,Br=13e3,Wr=16384,qr=65536,Hr=3,Gr=65536,zr=3e4,Vr=3,rt=5,Kr=5e4,Jr=2e5,on=2e3});import{mkdir as Vc,writeFile as Kc}from"fs/promises";import{join as Yr}from"path";import{tmpdir as Jc}from"os";function Qr(){return{seenIds:new Set,replacements:new Map}}function Zr(o){return Yr(Jc(),"qlogicagent-sessions",o,Yc)}async function Qc(o){try{await Vc(Zr(o),{recursive:!0})}catch{}}function Zc(o,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Yr(Zr(o),`${t}.txt`)}function eu(o,e){if(o.length<=e)return{preview:o,hasMore:!1};let n=o.slice(0,e).lastIndexOf(`
15
+ `),r=n>e*.5?n:e;return{preview:o.slice(0,r),hasMore:!0}}function es(o){return o.includes(Xr)}async function ts(o,e,t){await Qc(t);let n=Zc(t,e);try{await Kc(n,o,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:r,hasMore:s}=eu(o,on);return{filepath:n,originalSize:o.length,preview:r,hasMore:s}}function os(o){let e=`${Xr}
16
16
  `;return e+=`Output too large (${o.originalSize} chars). Full output saved to: ${o.filepath}
17
17
 
18
- `,e+=`Preview (first ${qo} bytes):
18
+ `,e+=`Preview (first ${on} bytes):
19
19
  `,e+=o.preview,e+=o.hasMore?`
20
20
  ...
21
21
  `:`
22
- `,e+=$c,e}async function Wr(o,e,t,n=Lr){if(o.length<=n||Ur(o))return o;let r=await Br(o,e,t);return r?qr(r):o.slice(0,n)+`
23
- ...[truncated ${o.length-n} chars]`}function Fc(o){let e=[],t=[];for(let n of o)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?Ur(n.content)||t.push({toolCallId:n.tool_call_id,content:n.content,size:n.content.length}):n.role==="assistant"&&t.length>0&&(e.push(t),t=[]);return t.length>0&&e.push(t),e}function Uc(o,e){let t=[],n=[],r=[];for(let s of o){let i=e.replacements.get(s.toolCallId);i!==void 0?t.push({...s,replacement:i}):e.seenIds.has(s.toolCallId)?n.push(s):r.push(s)}return{mustReapply:t,frozen:n,fresh:r}}function Bc(o,e,t){let n=[...o].sort((i,a)=>a.size-i.size),r=[],s=e+o.reduce((i,a)=>i+a.size,0);for(let i of n){if(s<=t)break;r.push(i),s-=i.size}return r}async function Hr(o,e,t,n=$r){let r=Fc(o);if(r.length===0)return{messages:o,newlyReplacedCount:0};let s=new Map,i=[];for(let u of r){let{mustReapply:g,frozen:d,fresh:m}=Uc(u,e);for(let v of g)s.set(v.toolCallId,v.replacement);if(m.length===0){for(let v of u)e.seenIds.add(v.toolCallId);continue}let h=d.reduce((v,_)=>v+_.size,0),f=m.reduce((v,_)=>v+_.size,0),T=h+f>n?Bc(m,h,n):[],y=new Set(T.map(v=>v.toolCallId));for(let v of u)y.has(v.toolCallId)||e.seenIds.add(v.toolCallId);T.length>0&&i.push(...T)}if(s.size===0&&i.length===0)return{messages:o,newlyReplacedCount:0};let a=await Promise.all(i.map(async u=>{let g=await Br(u.content,u.toolCallId,t);return{candidate:u,result:g}})),l=0;for(let{candidate:u,result:g}of a){if(e.seenIds.add(u.toolCallId),!g)continue;let d=qr(g);s.set(u.toolCallId,d),e.replacements.set(u.toolCallId,d),l++}return s.size===0?{messages:o,newlyReplacedCount:0}:{messages:o.map(u=>{if(u.role!=="tool"||!u.tool_call_id)return u;let g=s.get(u.tool_call_id);return g===void 0?u:{...u,content:g}}),newlyReplacedCount:l}}var Lc,Nr,$c,Wo=B(()=>{"use strict";Ct();Lc="tool-results",Nr="<persisted-output>",$c="</persisted-output>"});function Hc(o){try{return JSON.parse(o)}catch{return}}var qc,Wc,_t,Gr=B(()=>{"use strict";Qe();Wo();qc=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),Wc=new Set(["bash","execute_command","Bash","shell"]),_t=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??qc,this.siblingAbortController=new AbortController,e.signal&&e.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(e){let t=this.concurrencySafe.has(e.function.name);this.tools.push({id:e.id,toolCall:e,status:"queued",isConcurrencySafe:t,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(r=>r.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&t.length>=n?!1:t.length===0||e&&t.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 t;try{t=JSON.parse(e.toolCall.function.arguments)}catch{}let n=t?.command??t?.file_path??t?.pattern??"";if(typeof n=="string"&&n.length>0){let r=n.length>40?n.slice(0,40)+"\u2026":n;return`${e.toolCall.function.name}(${r})`}return e.toolCall.function.name}createSyntheticError(e,t){let n=this.erroredToolDescription,r=t==="user_interrupted"?"User rejected tool use":t==="discarded"?"Streaming fallback - tool execution discarded":n?`Cancelled: parallel tool call ${n} errored`:"Cancelled: parallel tool call errored";return{callId:e.id,toolName:e.toolCall.function.name,ok:!1,error:r,message:Ge(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let n=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:l,log:c}=this.config,u=e.toolCall.function.name,g=!1,d=e.toolCall.function.arguments;if(i)try{let v=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:u,arguments:Hc(d)});if(v.action==="abort"){let _=v.reason??"blocked by policy";c.info(`tool ${u} blocked: ${_}`),e.results.push({callId:e.id,toolName:u,ok:!1,error:_,blocked:!0,blockReason:_,message:Ge(e.id,{ok:!1,error:_})}),e.status="completed";return}v.action==="continue"&&v.context?.arguments&&(d=JSON.stringify(v.context.arguments))}catch{}let m=await s.invoke(l,u,d,this.siblingAbortController.signal),h=this.getAbortReason();if(h&&!g){e.results.push(this.createSyntheticError(e,h)),e.status="completed";return}let f=!m.error,T=m.result;f&&T&&T.length>5e4&&(T=await Wr(T,e.id,a));let y=Ge(e.id,{ok:f,payload:T,error:m.error});f||(g=!0,Wc.has(u)&&(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:u,ok:f,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:u,ok:f,error:m.error,message:y}),e.status="completed"})();e.promise=n,n.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let e of this.tools)if(e.status!=="yielded"){if(e.status==="completed"&&e.results.length>0){e.status="yielded";for(let t of e.results)yield t}else if(e.status==="executing"&&!e.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let e=this.tools.filter(n=>n.status==="executing"&&n.promise).map(n=>n.promise),t=new Promise(n=>{this.progressResolve=n});e.length>0&&await Promise.race([...e,t])}}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 Gc}from"node:fs/promises";function Pe(o){let e=typeof o.content=="string"?o.content:o.content!=null?JSON.stringify(o.content):"";return Math.ceil(e.length/4)}function Ae(o){let e=0;for(let t of o)e+=Pe(t);return e}function Kr(o){if(!o)return 128e3;if(o in Ho)return Ho[o];let e=o.toLowerCase();for(let[t,n]of Object.entries(Ho))if(e.startsWith(t.toLowerCase()))return n;return 128e3}function Vc(o,e){return async(t,n)=>{let r=e?.transport,s=e?.apiKey;if(!r||!s)return o.debug("[context-compression] no LLM transport for summarization \u2014 using sync fallback"),Go(t);try{let i="",a=e?.model??zc;for await(let l of r.stream({model:a,messages:[{role:"system",content:"You are a precise conversation summarizer."},{role:"user",content:n}],maxTokens:2e3,temperature:.3},s,AbortSignal.timeout(3e4)))l.type==="delta"&&(i+=l.text);return i||(o.warn("[context-compression] empty summary response"),Go(t))}catch(i){return o.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),Go(t)}}}function Go(o){let e=o.filter(n=>n.role==="user"),t=e.slice(0,10).map(n=>{let r=typeof n.content=="string"?n.content:JSON.stringify(n.content??"");return`- ${r.slice(0,200)}${r.length>200?"...":""}`});return`User requests (${e.length} messages):
22
+ `,e+=Xc,e}async function ns(o,e,t,n=Kr){if(o.length<=n||es(o))return o;let r=await ts(o,e,t);return r?os(r):o.slice(0,n)+`
23
+ ...[truncated ${o.length-n} chars]`}function tu(o){let e=[],t=[];for(let n of o)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?es(n.content)||t.push({toolCallId:n.tool_call_id,content:n.content,size:n.content.length}):n.role==="assistant"&&t.length>0&&(e.push(t),t=[]);return t.length>0&&e.push(t),e}function ou(o,e){let t=[],n=[],r=[];for(let s of o){let i=e.replacements.get(s.toolCallId);i!==void 0?t.push({...s,replacement:i}):e.seenIds.has(s.toolCallId)?n.push(s):r.push(s)}return{mustReapply:t,frozen:n,fresh:r}}function nu(o,e,t){let n=[...o].sort((i,a)=>a.size-i.size),r=[],s=e+o.reduce((i,a)=>i+a.size,0);for(let i of n){if(s<=t)break;r.push(i),s-=i.size}return r}async function rs(o,e,t,n=Jr){let r=tu(o);if(r.length===0)return{messages:o,newlyReplacedCount:0};let s=new Map,i=[];for(let u of r){let{mustReapply:p,frozen:d,fresh:m}=ou(u,e);for(let f of p)s.set(f.toolCallId,f.replacement);if(m.length===0){for(let f of u)e.seenIds.add(f.toolCallId);continue}let y=d.reduce((f,C)=>f+C.size,0),h=m.reduce((f,C)=>f+C.size,0),k=y+h>n?nu(m,y,n):[],w=new Set(k.map(f=>f.toolCallId));for(let f of u)w.has(f.toolCallId)||e.seenIds.add(f.toolCallId);k.length>0&&i.push(...k)}if(s.size===0&&i.length===0)return{messages:o,newlyReplacedCount:0};let a=await Promise.all(i.map(async u=>{let p=await ts(u.content,u.toolCallId,t);return{candidate:u,result:p}})),l=0;for(let{candidate:u,result:p}of a){if(e.seenIds.add(u.toolCallId),!p)continue;let d=os(p);s.set(u.toolCallId,d),e.replacements.set(u.toolCallId,d),l++}return s.size===0?{messages:o,newlyReplacedCount:0}:{messages:o.map(u=>{if(u.role!=="tool"||!u.tool_call_id)return u;let p=s.get(u.tool_call_id);return p===void 0?u:{...u,content:p}}),newlyReplacedCount:l}}var Yc,Xr,Xc,nn=q(()=>{"use strict";Dt();Yc="tool-results",Xr="<persisted-output>",Xc="</persisted-output>"});function iu(o){try{return JSON.parse(o)}catch{return}}var ru,su,Nt,ss=q(()=>{"use strict";nt();nn();ru=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),su=new Set(["bash","execute_command","Bash","shell"]),Nt=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??ru,this.siblingAbortController=new AbortController,e.signal&&e.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(e){let t=this.concurrencySafe.has(e.function.name);this.tools.push({id:e.id,toolCall:e,status:"queued",isConcurrencySafe:t,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(r=>r.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&t.length>=n?!1:t.length===0||e&&t.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 t;try{t=JSON.parse(e.toolCall.function.arguments)}catch{}let n=t?.command??t?.file_path??t?.pattern??"";if(typeof n=="string"&&n.length>0){let r=n.length>40?n.slice(0,40)+"\u2026":n;return`${e.toolCall.function.name}(${r})`}return e.toolCall.function.name}createSyntheticError(e,t){let n=this.erroredToolDescription,r=t==="user_interrupted"?"User rejected tool use":t==="discarded"?"Streaming fallback - tool execution discarded":n?`Cancelled: parallel tool call ${n} errored`:"Cancelled: parallel tool call errored";return{callId:e.id,toolName:e.toolCall.function.name,ok:!1,error:r,message:Je(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let n=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:l,log:c}=this.config,u=e.toolCall.function.name,p=!1,d=e.toolCall.function.arguments;if(i)try{let f=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:u,arguments:iu(d)});if(f.action==="abort"){let C=f.reason??"blocked by policy";c.info(`tool ${u} blocked: ${C}`),e.results.push({callId:e.id,toolName:u,ok:!1,error:C,blocked:!0,blockReason:C,message:Je(e.id,{ok:!1,error:C})}),e.status="completed";return}f.action==="continue"&&f.context?.arguments&&(d=JSON.stringify(f.context.arguments))}catch{}let m=await s.invoke(l,u,d,this.siblingAbortController.signal),y=this.getAbortReason();if(y&&!p){e.results.push(this.createSyntheticError(e,y)),e.status="completed";return}let h=!m.error,k=m.result;h&&k&&k.length>5e4&&(k=await ns(k,e.id,a));let w=Je(e.id,{ok:h,payload:k,error:m.error});h||(p=!0,su.has(u)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(h?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:l,callId:e.id,toolName:u,ok:h,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:u,ok:h,error:m.error,message:w}),e.status="completed"})();e.promise=n,n.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let e of this.tools)if(e.status!=="yielded"){if(e.status==="completed"&&e.results.length>0){e.status="yielded";for(let t of e.results)yield t}else if(e.status==="executing"&&!e.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let e=this.tools.filter(n=>n.status==="executing"&&n.promise).map(n=>n.promise),t=new Promise(n=>{this.progressResolve=n});e.length>0&&await Promise.race([...e,t])}}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 au}from"node:fs/promises";function Ie(o){let e=typeof o.content=="string"?o.content:o.content!=null?JSON.stringify(o.content):"";return Math.ceil(e.length/4)}function Oe(o){let e=0;for(let t of o)e+=Ie(t);return e}function ls(o){if(!o)return 128e3;if(o in rn)return rn[o];let e=o.toLowerCase();for(let[t,n]of Object.entries(rn))if(e.startsWith(t.toLowerCase()))return n;return 128e3}function cu(o,e){return async(t,n)=>{let r=e?.transport,s=e?.apiKey;if(!r||!s)return o.debug("[context-compression] no LLM transport for summarization \u2014 using sync fallback"),sn(t);try{let i="",a=e?.model??lu;for await(let l of r.stream({model:a,messages:[{role:"system",content:"You are a precise conversation summarizer."},{role:"user",content:n}],maxTokens:2e3,temperature:.3},s,AbortSignal.timeout(3e4)))l.type==="delta"&&(i+=l.text);return i||(o.warn("[context-compression] empty summary response"),sn(t))}catch(i){return o.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),sn(t)}}}function sn(o){let e=o.filter(n=>n.role==="user"),t=e.slice(0,10).map(n=>{let r=typeof n.content=="string"?n.content:JSON.stringify(n.content??"");return`- ${r.slice(0,200)}${r.length>200?"...":""}`});return`User requests (${e.length} messages):
24
24
  ${t.join(`
25
- `)}`}function Kc(){return uo(new Me(zo),new ke(20,Pe),new je(Pe))}function Vr(o,e){let t=po(new Me(zo),new ke(20,Pe),new ze({protectedHeadExchanges:1,protectedTailMessages:8,summarize:o,estimateTokens:Pe}),new je(Pe));return new Ve({inner:t,estimateTokens:Pe,onCacheInvalidated:e?.onCacheInvalidated})}function Yr(o,e){let t=e?.budget??kt({modelContextWindow:Kr(e?.model)}),r=(e?.pipeline??Kc()).compress(o,t);if(r.droppedCount>0){let s=Ae(o),i=Ae(r.messages);Jr.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:Xe(s,t)})}return r.droppedCount>0&&Vo?.(r.droppedCount,Ae(r.messages)),r}async function Jc(o,e,t){let n=t??kt({modelContextWindow:Kr(e.model)}),r=Ae(o),s=Xe(r,n),i;switch(s){case"none":i={messages:o,droppedCount:0,strategy:"none"};break;case"trim-only":i=new Me(zo).compress(o,n);break;case"sliding-window":{i=await Vr(e.summarize).compressAsync(o,n);break}case"llm-summarize":{let a=e.pipeline??Vr(e.summarize);i=Ye(a)?await a.compressAsync(o,n):a.compress(o,n);break}}return i.droppedCount>0&&(i={...i,messages:await go(i.messages,o,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await Gc(a,"utf-8")}catch{return null}}})}),Yc(o,i,n),i}function Yc(o,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||Ae(o),r=e.metrics?.tokensAfter||Ae(e.messages);Jr.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:n,tokensAfter:r,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:Xe(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||Ae(e.messages);Vo?.(e.droppedCount,n)}}function Xc(o,e){let t=Vc(o,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return Jc(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};zr.register(n),zr.activate(n.id),o.info(`[context-compression] registered context engine: ${n.id}`)}function Xr(o,e,t){Xc(e,t),o.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(n,r)=>{let s=r.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),Vo=(n,r)=>{e.debug(`[context-compression] after_compact: removed ${n}, ${r} tokens remaining`),o.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:n,tokenCount:r}).catch(()=>{})}}var Ho,zo,zc,Jr,zr,Vo,Ko=B(()=>{"use strict";Qe();Ho={"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};zo=8e3,zc="deepseek-chat",Jr=new Ke(200),zr=new Je;Vo=null});function Zr(o,e,t){let n=t-e;return`[Budget] ${Math.round(o)}% used (${e.toLocaleString()} / ${t.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(o>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var Qr=B(()=>{"use strict"});var es={};Zn(es,{resolveToolEligibility:()=>ou});function Qc(o,e){if(Zc.some(t=>t.test(o)))return!0;if(e)for(let t of e)try{if(new RegExp(t,"i").test(o))return!0}catch{}return!1}function eu(o,e){let t=o.function.name,n=o.meta,r=[];return e.blockedToolNames?.includes(t)?(r.push("policy_blocked"),{level:5,reasons:r}):n?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):n?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):n?.isDangerous||Qc(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function tu(o){switch(o){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 ou(o,e={}){let t=new Map,n=[],r=[],s=[];for(let i of o){let a=i.function.name,{level:l,reasons:c}=eu(i,e),u=tu(l),g={toolName:a,status:u,permissionLevel:l,approvalRequired:l===4,reasonCodes:c};t.set(a,g),l===5?r.push(g):(n.push(i),l===4&&s.push(g))}return{eligibleTools:n,blockedTools:r,approvalRequiredTools:s,eligibilityByName:t}}var Zc,ts=B(()=>{"use strict";Zc=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function ru(o){return typeof o=="number"&&Number.isFinite(o)&&o>=1?Math.min(Math.round(o),100):Sr}function os(o){let e=o.message.toLowerCase();return o.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function su(o){return o==="length"||o==="max_tokens"}function ns(o){let e=o.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(o.status===413||e.includes("too large")||e.includes("size"))}function iu(o){let e=o.headers;if(!e)return null;let t=e["retry-after"]??e["Retry-After"];if(!t)return null;let n=parseInt(t,10);return!isNaN(n)&&n>0?n*1e3:null}function au(o){if(o.status!==400)return null;let e=o.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!e?.[1]||!e?.[3])return null;let t=parseInt(e[1],10),n=parseInt(e[3],10);if(isNaN(t)||isNaN(n))return null;let r=n-t-1e3;return r>=3e3?r:null}function lu(o){return o.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*rs(o,e,t,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:l,apiKey:c,temperature:u,hooks:g,signal:d}=o,m={sessionId:s,turnId:r},h=o.maxTurns??0,f=o.querySource,{resolveToolEligibility:T}=await Promise.resolve().then(()=>(ts(),es)),y=T(a,o.toolEligibilityContext),v=y.eligibleTools;for(let D of y.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:D.toolName,reason:"blocked-by-policy"};if(!v.length){yield*cu(r,l,i,c,u,d,e,n);return}let _=ru(o.maxRounds),M={contextWindowTokens:o.contextWindowTokens??_r,responseBufferTokens:Rr,maxOutputTokens:o.maxOutputTokens??Mr,abortSignal:d,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},$=new Set,q=0,E=v,O,k={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Lo(M),reactiveCompactState:Fo(),toolLoopState:wt({maxRounds:_,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:yo(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:jr()};for(;;){let{messages:D,maxOutputTokensRecoveryCount:K,hasAttemptedReactiveCompact:oe,maxOutputTokensOverride:Te,turnCount:Y,guardState:L,reactiveCompactState:P,collapseStore:ie}=k,{toolLoopState:Q}=k;if(O){try{let x=await O;x&&(yield{type:"tool_use_summary",turnId:r,summary:x})}catch{}O=void 0}if(o.refreshTools&&Y>1){let x=o.refreshTools();x!==E&&(E=x,n.debug(`tools refreshed: ${x.length} tools`))}if(jo(L,M)){n.info(`turn aborted by guard at turn ${Y}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let ae=$o(L,M);if(ae.level==="blocking"){ae.reason==="prompt_too_long"&&Fe(P)&&(P.attemptedThisTurn=!0,L.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ae.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${ae.reason}), ending tool loop`);break}ae.level==="warning"&&n.info(`token budget warning: ${ae.usagePercent}% used, ${ae.remainingTokens} remaining`);let p;{let x=await Hr(D,k.contentReplacementState,s);p=x.messages,x.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${x.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${x.newlyReplacedCount} persisted`})}{let x=fo(p,k.snipRemovedIds);p=x.messages,x.removedCount>0&&(n.info(`snip: removed ${x.removedCount} messages, freed ~${x.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${x.removedCount} messages`})}{let C=new ke().compress(p,0);C.droppedCount>0&&(p=C.messages,n.info(`microcompact: cleared ${C.droppedCount} old tool results`))}if(p=bo(p,ie).messages,L.promptTokens>0){let x=Yr(p,{budget:M.contextWindowTokens*.75,model:k.currentModel});x.droppedCount>0&&(p=x.messages,n.info(`autocompact: ${x.strategy}, dropped ${x.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${x.strategy}: ${x.droppedCount} dropped`},k.hasAttemptedReactiveCompact=!1,g?.invoke("context.after_compact",{...m,removedCount:x.droppedCount}).catch(()=>{}))}p=lu(p);let b=ko({tools:E,toolChoice:o.toolChoice??"auto"}),w=wt({maxRounds:_,replayMessages:p,lastStopReason:Q.lastStopReason,options:{stopReason:Q.lastStopReason}}),S=b.extraSystemPrompt?[{role:"system",content:b.extraSystemPrompt},...w.state.replayMessages]:w.state.replayMessages;Q=w.state,w.recoveryActions.length>0&&n.debug(`tool loop recovery: ${w.recoveryActions.map(x=>x.detail??x.kind).join("; ")}`),n.debug(`turn ${Y}, messages: ${S.length}`),g?.invoke("turn.before_inference",{...m,model:k.currentModel}).catch(()=>{});let R=!1,U=[],V=new Map,ee="stop",W,I=null,N=!1;try{for await(let x of e.stream({model:k.currentModel,messages:S,tools:b.tools,toolChoice:b.normalizedToolChoice??"auto",temperature:u,maxTokens:(Te??L.currentMaxOutputTokens)||void 0},c,d))switch(x.type){case"delta":U.push(x.text),R||(yield{type:"delta",turnId:r,text:x.text});break;case"tool_call_delta":R=!0,Uo(V,x);break;case"reasoning_delta":break;case"usage":W={prompt:x.promptTokens,completion:x.completionTokens,reasoning:x.reasoningTokens};break;case"done":ee=x.finishReason;break}if(R||g?.invoke("turn.after_inference",{...m,model:k.currentModel}).catch(()=>{}),o.postSamplingHooks&&o.postSamplingHooks.length>0){let x=k.currentModel;for(let C of o.postSamplingHooks)try{C({messages:[...p],model:x,sessionId:s})}catch{}}}catch(x){if(x instanceof Ze&&o.fallbackModel){n.info(`model fallback triggered: ${x.originalModel} \u2192 ${x.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${x.originalModel} \u2192 ${x.fallbackModel}`},k={...k,currentModel:x.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let C=x instanceof Error?x.message:String(x),G=typeof x?.status=="number"?x.status:void 0;if(!G&&C&&(C.includes("ECONNRESET")||C.includes("EPIPE"))){let pe=(k.consecutiveApiRetries??0)+1;if(pe>et){n.info(`stale connection retry limit reached (${et}), aborting`),yield{type:"error",turnId:r,error:C,code:"RETRIES_EXHAUSTED"};return}n.info(`stale connection (${C.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:C.slice(0,80)},k={...k,consecutiveApiRetries:pe,transition:void 0};continue}let de=au({status:G,message:C});if(de!==null){n.info(`max_tokens overflow: adjusting to ${de}`),L.currentMaxOutputTokens=de,k={...k,maxOutputTokensOverride:de,transition:void 0};continue}if(Mo(G)){if(k.consecutive529Errors++,k.consecutive529Errors>=Or&&o.fallbackModel&&k.currentModel!==o.fallbackModel){n.info(`529 \xD7 ${k.consecutive529Errors}: triggering fallback to ${o.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${k.consecutive529Errors}`},k={...k,currentModel:o.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Po()){let pe=St(k.consecutive529Errors);n.info(`persistent retry: waiting ${pe}ms (attempt ${k.consecutive529Errors})`);let he=pe;for(;he>0;){if(d?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(he/1e3)}s (${G})`};let $e=Math.min(he,Ir);await new Promise(wl=>setTimeout(wl,$e)),he-=$e}k={...k,transition:void 0};continue}if(Ro(f)){let he=iu({status:G,message:C})??St(k.consecutive529Errors);n.info(`transient ${G}: retry in ${he}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${G} retry in ${he}ms`},await new Promise($e=>setTimeout($e,he)),k={...k,transition:void 0};continue}n.info(`background source ${f}: not retrying ${G}`)}I={status:G,message:C}}if(I&&g?.invoke("turn.after_inference",{...m,model:k.currentModel,response:{error:I.message}}).catch(()=>{}),I)if(os(I))N=!0,n.info(`withheld prompt_too_long error (status=${I.status})`);else if(ns(I))N=!0,n.info(`withheld media_size error (status=${I.status})`);else{let x=Do({status:I.status??500,message:I.message},L,M);if(x.action==="reactive_compact"&&Fe(P)&&(P.attemptedThisTurn=!0,L.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${I.status??500}: ${I.message}`}),x.action==="retry"){let G=(k.consecutiveApiRetries??0)+1;if(G>et){n.info(`API retry limit reached (${et}), aborting`);let de=Ne(I.status,I.message);yield{type:"error",turnId:r,error:I.message,code:de};return}yield{type:"recovery",turnId:r,action:"retry",detail:x.reason},k={...k,consecutiveApiRetries:G,transition:void 0};continue}let C=Ne(I.status,I.message);g?.invoke("stop.failure",{sessionId:s,reason:C,error:I.message}).catch(()=>{}),yield{type:"error",turnId:r,error:I.message,code:C};return}W&&(k.totalUsage.prompt+=W.prompt,k.totalUsage.completion+=W.completion,W.reasoning&&(k.totalUsage.reasoning=(k.totalUsage.reasoning??0)+W.reasoning)),W?.prompt&&(L.promptTokens=W.prompt),k.finalText=U.join("");let te=[...V.values()].map(x=>({id:x.id||`tc_${r}_${Y}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:x.name,arguments:x.arguments}}));if(te.length===0&&!R){if(N&&I&&os(I)){if(k.transition?.reason!=="collapse_drain_retry"){let x=To(p,ie);if(x.committed>0){n.info(`collapse drain: committed ${x.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${x.committed} stages committed`},k={...k,messages:x.messages,transition:{reason:"collapse_drain_retry",committed:x.committed}};continue}}if(Fe(P)){P.attemptedThisTurn=!0,L.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},k={...k,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),g?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:I.message}).catch(()=>{}),yield{type:"error",turnId:r,error:I.message,code:"PROMPT_TOO_LONG"};return}if(N&&I&&ns(I)){if(Fe(P)){P.attemptedThisTurn=!0,L.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},k={...k,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),g?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:I.message}).catch(()=>{}),yield{type:"error",turnId:r,error:I.message,code:"IMAGE_ERROR"};return}if(su(ee)){L.consecutiveTruncations+=1;let x=o.modelMaxOutputTokens??Pr,C=No(L,M,x);if(C.shouldEscalate&&Te===void 0){L.currentMaxOutputTokens=C.newMax,n.info(`max_output_tokens escalate: ${C.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${C.newMax} tokens`},k={...k,maxOutputTokensOverride:Er,transition:{reason:"max_output_tokens_escalate"}};continue}if(K<Ar){let G={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${K+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${K+1}`},k={...k,messages:[...p,G],maxOutputTokensRecoveryCount:K+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:K+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else L.consecutiveTruncations=0;if(Q=vt(Q,{replayMessages:D,lastStopReason:"completed"}),g){let x=await g.invoke("stop",{sessionId:s,reason:"completed"});if(x.action==="prevent"){n.info(`stop hook prevented continuation: ${x.reason??"no reason"}`),yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}if(x.action==="abort"){let C=x.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${C}`);let G={role:"user",content:C};k={...k,messages:[...D,{role:"assistant",content:k.finalText},G],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(o.tokenBudget&&o.tokenBudget>0){let x=k.totalUsage.prompt+k.totalUsage.completion+(k.totalUsage.reasoning??0),C=x/o.tokenBudget*100;if(C<90){let G={role:"user",content:Zr(C,x,o.tokenBudget)};n.info(`token budget continuation: ${Math.round(C)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(C)}% used`},k={...k,messages:[...D,{role:"assistant",content:k.finalText},G],transition:{reason:"token_budget_continuation"}};continue}}if(q>0){let x={ok:!0,toolCallCount:q,distinctToolCount:$.size,multiStep:q>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},C=xt(x,{tools:[...$]});C&&(yield{type:"skill_instruction",turnId:r,instruction:C})}yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}for(let x of te){let C=x.function.arguments,G=E.find(de=>de.function.name===x.function.name);if(G?.backfillObservableInput)try{let de=JSON.parse(x.function.arguments),pe={...de};G.backfillObservableInput(pe),Object.keys(pe).some($e=>!($e in de))&&(C=JSON.stringify(pe))}catch{}yield{type:"tool_call",turnId:r,callId:x.id,name:x.function.name,arguments:C}}D.push(ao(te)),Q=_o(Q,{replayMessages:D,pendingToolCallIds:te.map(x=>x.id),completedToolCallIds:Q.completedToolCallIds,lastStopReason:"tool_calls"});let Yn=[];try{let x=new _t({toolInvoker:t,hooks:g,sessionId:s,turnId:r,log:n,signal:d,maxConcurrentTools:o?.maxConcurrentTools});for(let C of te)x.addTool(C);for await(let C of x.getRemainingResults())C.blocked&&(yield{type:"tool_blocked",turnId:r,callId:C.callId,name:C.toolName,reason:C.blockReason??"blocked"}),D.push(C.message),Yn.push(C.callId),$.add(C.toolName),q++,yield{type:"tool_result",turnId:r,callId:C.callId,name:C.toolName,ok:C.ok,error:C.error}}catch(x){let C=x instanceof Error?x.message:String(x);yield{type:"error",turnId:r,error:C,code:"TOOL_EXECUTION_ERROR"};return}if(Q=vt(Q,{replayMessages:D,completedToolCallIds:[...Q.completedToolCallIds,...Yn],lastStopReason:"tool_calls"}),o.generateToolUseSummary&&te.length>0){let x=te.map(C=>({name:C.function.name,arguments:C.function.arguments}));O=o.generateToolUseSummary(x).catch(()=>null)}let Xn=D.slice(-te.length),vl=Xn.length>0&&Xn.every(x=>{let C=x?.content;if(typeof C!="string")return!1;try{return JSON.parse(C)?.ok===!1}catch{return!1}}),He=k.consecutiveFailedRounds;if(vl){if(He+=1,He>=Cr&&k.finalText){n.info(`early exit: ${He} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}}else He=0;let io=Y+1;if(h>0&&io>h){if(n.info(`max turns reached (${h}), completing`),g){let x=await g.invoke("stop",{sessionId:s,reason:"max_turns"});if(x.action==="abort"){let C=x.reason??"Stop hook requested continuation after max_turns";k={...k,messages:[...D,{role:"assistant",content:k.finalText},{role:"user",content:C}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}if(io>_){if(k.finalText){if(n.info(`tool loop budget exhausted (${_} rounds), returning partial response`),q>0){let x={ok:!0,toolCallCount:q,distinctToolCount:$.size,multiStep:q>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},C=xt(x,{tools:[...$]});C&&(yield{type:"skill_instruction",turnId:r,instruction:C})}yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}yield{type:"error",turnId:r,error:`Tool loop exceeded budget (${_} rounds)`,code:"TOOL_LOOP_LIMIT"};return}k={messages:D,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:io,transition:{reason:"next_turn"},guardState:L,reactiveCompactState:P,toolLoopState:Q,consecutiveFailedRounds:He,finalText:k.finalText,totalUsage:k.totalUsage,collapseStore:ie,currentModel:k.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:k.stopHookActive,snipRemovedIds:k.snipRemovedIds,contentReplacementState:k.contentReplacementState}}}async function*cu(o,e,t,n,r,s,i,a){let l=[],c;a.debug(`single LLM round, messages: ${t.length}`);for await(let u of i.stream({model:e,messages:t,temperature:r},n,s))switch(u.type){case"delta":l.push(u.text),yield{type:"delta",turnId:o,text:u.text};break;case"usage":c={prompt:u.promptTokens,completion:u.completionTokens,reasoning:u.reasoningTokens};break;case"done":break}yield{type:"end",turnId:o,content:l.join(""),usage:c??{prompt:0,completion:0},model:e}}var ss=B(()=>{"use strict";Bo();Qe();Gr();Ko();Qr();Wo();Ct()});var as={};Zn(as,{Agent:()=>tt});var tt,Jo=B(()=>{"use strict";Qe();ss();Ct();tt=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,t){let{turnId:n,messages:r,tools:s,systemPrompt:i,config:a}=e,l={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let c=So(r),u=[];if(i&&u.push({role:"system",content:i}),u.push(...c),this.hooks){let m=c.filter(f=>f.role==="user").pop(),h=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(h)try{let f=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:h}),T=f?.context?.recalledMemories;if(T&&T.length>0){let y=T.map(v=>`- ${v.text}`).join(`
25
+ `)}`}function uu(){return Co(new Ee(an),new xe(20,Ie),new qe(Ie))}function as(o,e){let t=_o(new Ee(an),new xe(20,Ie),new Ye({protectedHeadExchanges:1,protectedTailMessages:8,summarize:o,estimateTokens:Ie}),new qe(Ie));return new Xe({inner:t,estimateTokens:Ie,onCacheInvalidated:e?.onCacheInvalidated})}function us(o,e){let t=e?.budget??Et({modelContextWindow:ls(e?.model)}),r=(e?.pipeline??uu()).compress(o,t);if(r.droppedCount>0){let s=Oe(o),i=Oe(r.messages);cs.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:tt(s,t)})}return r.droppedCount>0&&ln?.(r.droppedCount,Oe(r.messages)),r}async function du(o,e,t){let n=t??Et({modelContextWindow:ls(e.model)}),r=Oe(o),s=tt(r,n),i;switch(s){case"none":i={messages:o,droppedCount:0,strategy:"none"};break;case"trim-only":i=new Ee(an).compress(o,n);break;case"sliding-window":{i=await as(e.summarize).compressAsync(o,n);break}case"llm-summarize":{let a=e.pipeline??as(e.summarize);i=et(a)?await a.compressAsync(o,n):a.compress(o,n);break}}return i.droppedCount>0&&(i={...i,messages:await Mo(i.messages,o,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await au(a,"utf-8")}catch{return null}}})}),pu(o,i,n),i}function pu(o,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||Oe(o),r=e.metrics?.tokensAfter||Oe(e.messages);cs.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:n,tokensAfter:r,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:tt(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||Oe(e.messages);ln?.(e.droppedCount,n)}}function mu(o,e){let t=cu(o,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return du(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};is.register(n),is.activate(n.id),o.info(`[context-compression] registered context engine: ${n.id}`)}function ds(o,e,t){mu(e,t),o.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(n,r)=>{let s=r.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),ln=(n,r)=>{e.debug(`[context-compression] after_compact: removed ${n}, ${r} tokens remaining`),o.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:n,tokenCount:r}).catch(()=>{})}}var rn,an,lu,cs,is,ln,cn=q(()=>{"use strict";nt();rn={"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};an=8e3,lu="deepseek-chat",cs=new Qe(200),is=new Ze;ln=null});function ps(o,e,t){let n=t-e;return`[Budget] ${Math.round(o)}% used (${e.toLocaleString()} / ${t.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(o>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var ms=q(()=>{"use strict"});var gs={};pr(gs,{resolveToolEligibility:()=>bu});function fu(o,e){if(gu.some(t=>t.test(o)))return!0;if(e)for(let t of e)try{if(new RegExp(t,"i").test(o))return!0}catch{}return!1}function hu(o,e){let t=o.function.name,n=o.meta,r=[];return e.blockedToolNames?.includes(t)?(r.push("policy_blocked"),{level:5,reasons:r}):n?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):n?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):n?.isDangerous||fu(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function yu(o){switch(o){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 bu(o,e={}){let t=new Map,n=[],r=[],s=[];for(let i of o){let a=i.function.name,{level:l,reasons:c}=hu(i,e),u=yu(l),p={toolName:a,status:u,permissionLevel:l,approvalRequired:l===4,reasonCodes:c};t.set(a,p),l===5?r.push(p):(n.push(i),l===4&&s.push(p))}return{eligibleTools:n,blockedTools:r,approvalRequiredTools:s,eligibilityByName:t}}var gu,fs=q(()=>{"use strict";gu=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function xu(o){let e=o.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(e)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(e)?"diagram":["csv","tsv","xlsx","xls"].includes(e)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(e)?"code":"file"}function vu(o){let e=o.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[e]}function wu(o){return typeof o=="number"&&Number.isFinite(o)&&o>=1?Math.min(Math.round(o),100):Ur}function hs(o){let e=o.message.toLowerCase();return o.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function Su(o){return o==="length"||o==="max_tokens"}function ys(o){let e=o.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(o.status===413||e.includes("too large")||e.includes("size"))}function Cu(o){let e=o.headers;if(!e)return null;let t=e["retry-after"]??e["Retry-After"];if(!t)return null;let n=parseInt(t,10);return!isNaN(n)&&n>0?n*1e3:null}function _u(o){if(o.status!==400)return null;let e=o.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!e?.[1]||!e?.[3])return null;let t=parseInt(e[1],10),n=parseInt(e[3],10);if(isNaN(t)||isNaN(n))return null;let r=n-t-1e3;return r>=3e3?r:null}function Ru(o){return o.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*bs(o,e,t,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:l,apiKey:c,temperature:u,hooks:p,signal:d}=o,m={sessionId:s,turnId:r},y=o.maxTurns??0,h=o.querySource,{resolveToolEligibility:k}=await Promise.resolve().then(()=>(fs(),gs)),w=k(a,o.toolEligibilityContext),f=w.eligibleTools;for(let B of w.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:B.toolName,reason:"blocked-by-policy"};if(!f.length){yield*Mu(r,l,i,c,u,d,e,n);return}let C=wu(o.maxRounds),R={contextWindowTokens:o.contextWindowTokens??Fr,responseBufferTokens:Br,maxOutputTokens:o.maxOutputTokens??Wr,abortSignal:d,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,K=0,D=f,F,T={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ko(R),reactiveCompactState:Zo(),toolLoopState:Lt({maxRounds:C,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:Eo(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:Qr()};for(;;){let{messages:B,maxOutputTokensRecoveryCount:J,hasAttemptedReactiveCompact:Q,maxOutputTokensOverride:ke,turnCount:oe,guardState:$,reactiveCompactState:A,collapseStore:le}=T,{toolLoopState:se}=T;if(F){try{let x=await F;x&&(yield{type:"tool_use_summary",turnId:r,summary:x})}catch{}F=void 0}if(o.refreshTools&&oe>1){let x=o.refreshTools();x!==D&&(D=x,n.debug(`tools refreshed: ${x.length} tools`))}if(Qo($,R)){n.info(`turn aborted by guard at turn ${oe}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let ce=Jo($,R);if(ce.level==="blocking"){ce.reason==="prompt_too_long"&&He(A)&&(A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ce.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${ce.reason}), ending tool loop`);break}ce.level==="warning"&&n.info(`token budget warning: ${ce.usagePercent}% used, ${ce.remainingTokens} remaining`);let g;{let x=await rs(B,T.contentReplacementState,s);g=x.messages,x.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${x.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${x.newlyReplacedCount} persisted`})}{let x=Po(g,T.snipRemovedIds);g=x.messages,x.removedCount>0&&(n.info(`snip: removed ${x.removedCount} messages, freed ~${x.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${x.removedCount} messages`})}{let S=new xe().compress(g,0);S.droppedCount>0&&(g=S.messages,n.info(`microcompact: cleared ${S.droppedCount} old tool results`))}if(g=Io(g,le).messages,$.promptTokens>0){let x=us(g,{budget:R.contextWindowTokens*.75,model:T.currentModel});x.droppedCount>0&&(g=x.messages,n.info(`autocompact: ${x.strategy}, dropped ${x.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${x.strategy}: ${x.droppedCount} dropped`},T.hasAttemptedReactiveCompact=!1,p?.invoke("context.after_compact",{...m,removedCount:x.droppedCount}).catch(()=>{}))}g=Ru(g);let b=Lo({tools:D,toolChoice:o.toolChoice??"auto"}),v=Lt({maxRounds:C,replayMessages:g,lastStopReason:se.lastStopReason,options:{stopReason:se.lastStopReason}}),_=b.extraSystemPrompt?[{role:"system",content:b.extraSystemPrompt},...v.state.replayMessages]:v.state.replayMessages;se=v.state,v.recoveryActions.length>0&&n.debug(`tool loop recovery: ${v.recoveryActions.map(x=>x.detail??x.kind).join("; ")}`),n.debug(`turn ${oe}, messages: ${_.length}`),p?.invoke("turn.before_inference",{...m,model:T.currentModel}).catch(()=>{});let M=!1,W=[],Z=new Map,z="stop",j,E=null,O=!1;try{for await(let x of e.stream({model:T.currentModel,messages:_,tools:b.tools,toolChoice:b.normalizedToolChoice??"auto",temperature:u,maxTokens:(ke??$.currentMaxOutputTokens)||void 0},c,d))switch(x.type){case"delta":W.push(x.text),M||(yield{type:"delta",turnId:r,text:x.text});break;case"tool_call_delta":M=!0,en(Z,x);break;case"reasoning_delta":break;case"usage":j={prompt:x.promptTokens,completion:x.completionTokens,reasoning:x.reasoningTokens,cacheRead:x.cacheReadTokens,cacheCreation:x.cacheCreationTokens};break;case"done":z=x.finishReason;break}if(M||p?.invoke("turn.after_inference",{...m,model:T.currentModel}).catch(()=>{}),o.postSamplingHooks&&o.postSamplingHooks.length>0){let x=T.currentModel;for(let S of o.postSamplingHooks)try{S({messages:[...g],model:x,sessionId:s})}catch{}}}catch(x){if(x instanceof ot&&o.fallbackModel){n.info(`model fallback triggered: ${x.originalModel} \u2192 ${x.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${x.originalModel} \u2192 ${x.fallbackModel}`},T={...T,currentModel:x.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let S=x instanceof Error?x.message:String(x),G=typeof x?.status=="number"?x.status:void 0;if(!G&&S&&(S.includes("ECONNRESET")||S.includes("EPIPE"))){let ie=(T.consecutiveApiRetries??0)+1;if(ie>rt){n.info(`stale connection retry limit reached (${rt}), aborting`),yield{type:"error",turnId:r,error:S,code:"RETRIES_EXHAUSTED"};return}n.info(`stale connection (${S.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:S.slice(0,80)},T={...T,consecutiveApiRetries:ie,transition:void 0};continue}let ue=_u({status:G,message:S});if(ue!==null){n.info(`max_tokens overflow: adjusting to ${ue}`),$.currentMaxOutputTokens=ue,T={...T,maxOutputTokensOverride:ue,transition:void 0};continue}if(Wo(G)){if(T.consecutive529Errors++,T.consecutive529Errors>=Vr&&o.fallbackModel&&T.currentModel!==o.fallbackModel){n.info(`529 \xD7 ${T.consecutive529Errors}: triggering fallback to ${o.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${T.consecutive529Errors}`},T={...T,currentModel:o.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(qo()){let ie=$t(T.consecutive529Errors);n.info(`persistent retry: waiting ${ie}ms (attempt ${T.consecutive529Errors})`);let V=ie;for(;V>0;){if(d?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(V/1e3)}s (${G})`};let de=Math.min(V,zr);await new Promise(jl=>setTimeout(jl,de)),V-=de}T={...T,transition:void 0};continue}if(Bo(h)){let V=Cu({status:G,message:S})??$t(T.consecutive529Errors);n.info(`transient ${G}: retry in ${V}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${G} retry in ${V}ms`},await new Promise(de=>setTimeout(de,V)),T={...T,transition:void 0};continue}n.info(`background source ${h}: not retrying ${G}`)}E={status:G,message:S}}if(E&&p?.invoke("turn.after_inference",{...m,model:T.currentModel,response:{error:E.message}}).catch(()=>{}),E)if(hs(E))O=!0,n.info(`withheld prompt_too_long error (status=${E.status})`);else if(ys(E))O=!0,n.info(`withheld media_size error (status=${E.status})`);else{let x=Yo({status:E.status??500,message:E.message},$,R);if(x.action==="reactive_compact"&&He(A)&&(A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${E.status??500}: ${E.message}`}),x.action==="retry"){let G=(T.consecutiveApiRetries??0)+1;if(G>rt){n.info(`API retry limit reached (${rt}), aborting`);let ue=We(E.status,E.message);yield{type:"error",turnId:r,error:E.message,code:ue};return}yield{type:"recovery",turnId:r,action:"retry",detail:x.reason},T={...T,consecutiveApiRetries:G,transition:void 0};continue}let S=We(E.status,E.message);p?.invoke("stop.failure",{sessionId:s,reason:S,error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:S};return}j&&(T.totalUsage.prompt+=j.prompt,T.totalUsage.completion+=j.completion,j.reasoning&&(T.totalUsage.reasoning=(T.totalUsage.reasoning??0)+j.reasoning),j.cacheRead&&(T.totalUsage.cacheRead=(T.totalUsage.cacheRead??0)+j.cacheRead),j.cacheCreation&&(T.totalUsage.cacheCreation=(T.totalUsage.cacheCreation??0)+j.cacheCreation)),j?.prompt&&($.promptTokens=j.prompt),T.finalText=W.join("");let N=[...Z.values()].map(x=>({id:x.id||`tc_${r}_${oe}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:x.name,arguments:x.arguments}}));if(N.length===0&&!M){if(O&&E&&hs(E)){if(T.transition?.reason!=="collapse_drain_retry"){let x=Oo(g,le);if(x.committed>0){n.info(`collapse drain: committed ${x.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${x.committed} stages committed`},T={...T,messages:x.messages,transition:{reason:"collapse_drain_retry",committed:x.committed}};continue}}if(He(A)){A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,n.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}n.info("withheld 413: recovery exhausted, surfacing error"),p?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:"PROMPT_TOO_LONG"};return}if(O&&E&&ys(E)){if(He(A)){A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,n.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}n.info("withheld media error: recovery exhausted"),p?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:"IMAGE_ERROR"};return}if(Su(z)){$.consecutiveTruncations+=1;let x=o.modelMaxOutputTokens??qr,S=Xo($,R,x);if(S.shouldEscalate&&ke===void 0){$.currentMaxOutputTokens=S.newMax,n.info(`max_output_tokens escalate: ${S.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${S.newMax} tokens`},T={...T,maxOutputTokensOverride:Gr,transition:{reason:"max_output_tokens_escalate"}};continue}if(J<Hr){let G={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${J+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${J+1}`},T={...T,messages:[...g,G],maxOutputTokensRecoveryCount:J+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:J+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else $.consecutiveTruncations=0;if(se=Ot(se,{replayMessages:B,lastStopReason:"completed"}),p){let x=await p.invoke("stop",{sessionId:s,reason:"completed"});if(x.action==="prevent"){n.info(`stop hook prevented continuation: ${x.reason??"no reason"}`),yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}if(x.action==="abort"){let S=x.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${S}`);let G={role:"user",content:S};T={...T,messages:[...B,{role:"assistant",content:T.finalText},G],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(o.tokenBudget&&o.tokenBudget>0){let x=T.totalUsage.prompt+T.totalUsage.completion+(T.totalUsage.reasoning??0),S=x/o.tokenBudget*100;if(S<90){let G={role:"user",content:ps(S,x,o.tokenBudget)};n.info(`token budget continuation: ${Math.round(S)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(S)}% used`},T={...T,messages:[...B,{role:"assistant",content:T.finalText},G],transition:{reason:"token_budget_continuation"}};continue}}if(K>0){let x={ok:!0,toolCallCount:K,distinctToolCount:L.size,multiStep:K>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},S=It(x,{tools:[...L]});S&&(yield{type:"skill_instruction",turnId:r,instruction:S})}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}for(let x of N){let S=x.function.arguments,G=D.find(ue=>ue.function.name===x.function.name);if(G?.backfillObservableInput)try{let ue=JSON.parse(x.function.arguments),ie={...ue};G.backfillObservableInput(ie),Object.keys(ie).some(de=>!(de in ue))&&(S=JSON.stringify(ie))}catch{}yield{type:"tool_call",turnId:r,callId:x.id,name:x.function.name,arguments:S}}B.push(vo(N,T.finalText||void 0)),se=Fo(se,{replayMessages:B,pendingToolCallIds:N.map(x=>x.id),completedToolCallIds:se.completedToolCallIds,lastStopReason:"tool_calls"});let Mt=[];try{let x=new Nt({toolInvoker:t,hooks:p,sessionId:s,turnId:r,log:n,signal:d,maxConcurrentTools:o?.maxConcurrentTools});for(let S of N)x.addTool(S);for await(let S of x.getRemainingResults()){S.blocked&&(yield{type:"tool_blocked",turnId:r,callId:S.callId,name:S.toolName,reason:S.blockReason??"blocked"}),B.push(S.message),Mt.push(S.callId),L.add(S.toolName),K++;let G=typeof S.message?.content=="string"?S.message.content:"",ue=S.ok&&G?G.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:S.callId,name:S.toolName,ok:S.ok,error:S.error,outputPreview:ue},S.ok){let ie=N.find(V=>V.id===S.callId);if(ie){if(S.toolName==="plan_mode")try{let V=JSON.parse(ie.function.arguments);V.action==="exit"&&typeof V.plan=="string"&&V.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:V.plan})}catch{}if(ku.has(S.toolName))try{let V=JSON.parse(ie.function.arguments),de=typeof V.file_path=="string"?V.file_path:typeof V.filePath=="string"?V.filePath:typeof V.path=="string"?V.path:void 0;de&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${S.callId}`,artifactType:xu(de),title:de.split(/[\\/]/).pop()||de,filePath:de,language:vu(de)})}catch{}}}}}catch(x){let S=x instanceof Error?x.message:String(x);yield{type:"error",turnId:r,error:S,code:"TOOL_EXECUTION_ERROR"};return}if(se=Ot(se,{replayMessages:B,completedToolCallIds:[...se.completedToolCallIds,...Mt],lastStopReason:"tool_calls"}),o.generateToolUseSummary&&N.length>0){let x=N.map(S=>({name:S.function.name,arguments:S.function.arguments}));F=o.generateToolUseSummary(x).catch(()=>null)}let Pt=B.slice(-N.length),Ul=Pt.length>0&&Pt.every(x=>{let S=x?.content;return typeof S!="string"?!1:S.startsWith("Error: ")}),Ke=T.consecutiveFailedRounds;if(Ul){if(Ke+=1,Ke>=jr&&T.finalText){n.info(`early exit: ${Ke} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}}else Ke=0;let xo=oe+1;if(y>0&&xo>y){if(n.info(`max turns reached (${y}), completing`),p){let x=await p.invoke("stop",{sessionId:s,reason:"max_turns"});if(x.action==="abort"){let S=x.reason??"Stop hook requested continuation after max_turns";T={...T,messages:[...B,{role:"assistant",content:T.finalText},{role:"user",content:S}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}if(xo>C){if(n.info(`tool loop budget exhausted (${C} rounds), returning`),K>0){let x={ok:!0,toolCallCount:K,distinctToolCount:L.size,multiStep:K>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},S=It(x,{tools:[...L]});S&&(yield{type:"skill_instruction",turnId:r,instruction:S})}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}T={messages:B,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:xo,transition:{reason:"next_turn"},guardState:$,reactiveCompactState:A,toolLoopState:se,consecutiveFailedRounds:Ke,finalText:T.finalText,totalUsage:T.totalUsage,collapseStore:le,currentModel:T.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:T.stopHookActive,snipRemovedIds:T.snipRemovedIds,contentReplacementState:T.contentReplacementState}}}async function*Mu(o,e,t,n,r,s,i,a){let l=[],c;a.debug(`single LLM round, messages: ${t.length}`);for await(let u of i.stream({model:e,messages:t,temperature:r},n,s))switch(u.type){case"delta":l.push(u.text),yield{type:"delta",turnId:o,text:u.text};break;case"usage":c={prompt:u.promptTokens,completion:u.completionTokens,reasoning:u.reasoningTokens,cacheRead:u.cacheReadTokens,cacheCreation:u.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:o,content:l.join(""),usage:c??{prompt:0,completion:0},model:e}}var ku,Ts=q(()=>{"use strict";tn();nt();ss();cn();ms();nn();Dt();ku=new Set(["write","edit","patch","apply_patch"])});var xs={};pr(xs,{Agent:()=>st});var st,un=q(()=>{"use strict";nt();Ts();Dt();st=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,t){let{turnId:n,messages:r,tools:s,systemPrompt:i,config:a}=e,l={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let c=Uo(r),u=[];if(i&&u.push({role:"system",content:i}),u.push(...c),this.hooks){let m=c.filter(h=>h.role==="user").pop(),y=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(y)try{let h=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:y}),k=h?.context?.recalledMemories;if(k&&k.length>0){let w=k.map(f=>`- ${f.text}`).join(`
26
26
  `);u.splice(i?1:0,0,{role:"system",content:`[Recalled from long-term memory]
27
- ${y}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:f?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let g=a?.model??"",d=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=a?.summaryModel?async T=>{try{let y=T.map(M=>`${M.name}(${M.arguments.slice(0,200)})`).join(", "),v=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:y}],tools:[],maxTokens:60},a.apiKey??this.apiKey),_="";for await(let M of v)M.type==="delta"&&(_+=M.text);return _.trim()||null}catch{return null}}:void 0,h={turnId:n,sessionId:e.sessionId,messages:u,tools:s,model:g,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:d,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,generateToolUseSummary:m,signal:t},f;for await(let T of rs(h,this.transport,this.toolInvoker,this.log))f=T,yield T;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(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let h=m instanceof Error?m.message:String(m),f=typeof m?.status=="number"?m.status:void 0,T=Ne(f,h),y=co(T);this.log.error(`turn ${n} error [${T}, retryable=${y.retryable}]: ${h}`),this.hooks?.invoke("turn.failed",{...l,code:T,error:h}).catch(()=>{}),yield{type:"error",turnId:n,error:h,code:T}}}}}});import{randomUUID as fe}from"node:crypto";import{createInterface as Cl}from"node:readline";var De=class{messageHandler=null;closeHandler=null;verbose;constructor(e){this.verbose=e?.verbose??!1}onMessage(e){this.messageHandler=e}onClose(e){this.closeHandler=e}send(e){process.stdout.write(`${JSON.stringify(e)}
28
- `)}start(){let e=Cl({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let n=t.trim();if(n)try{let r=JSON.parse(n);this.messageHandler?.(r)}catch{this.log(`invalid JSON on stdin: ${n.slice(0,200)}`)}}),e.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
29
- `)}};Jo();Bo();var Yo=[{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 pu,mkdirSync as mu,readFileSync as gu,writeFileSync as fu}from"node:fs";import{join as hu}from"node:path";import{homedir as du}from"node:os";import{join as J}from"node:path";var me=".qlogicagent";function ne(){return J(du(),me)}function ls(){return J(ne(),"sessions")}function cs(){return J(ne(),"plugins")}function Rt(){return J(ne(),"skills")}function Xo(){return J(ne(),"settings.json")}function us(){return J(ne(),"cache")}function ds(){return J(ne(),"debug-logs")}function ps(o){let e=J(ne(),"checkpoints");return o?J(e,o):e}function ms(){return J(ne(),"plugin-cache")}function gs(){return J(ne(),"mcp.json")}function fs(){return J(ne(),"marketplace.json")}function hs(){return J(ne(),"workflows")}function ys(){return J(ne(),"rules")}function Zo(o){return J(o??process.cwd(),me)}function bs(o){return J(Zo(o),"workflows")}function Ts(o){return J(Zo(o),"INSTRUCTIONS.md")}function ks(o){return J(Zo(o),"rules")}function xs(o){return J(o,me,"hooks")}var yu="https://models.dev/api.json",bu=15e3,Tu=1440*60*1e3,ku=300*1e3,ot=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??us(),this.cacheFile=hu(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??Tu}getModels(e){this.ensureLoaded();let t=this.cache?.providers.get(e);return t?[...t.models.values()]:[]}getModel(e,t){return this.ensureLoaded(),this.cache?.providers.get(e)?.models.get(t)}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(!pu(this.cacheFile))return;let e=gu(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:vs(t.data)}}catch{}}saveToDisk(e){try{mu(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);fu(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<ku||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(yu,{signal:AbortSignal.timeout(bu),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=vs(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function vs(o){let e=new Map;if(!o||typeof o!="object")return e;for(let[t,n]of Object.entries(o)){if(!n||typeof n!="object")continue;let r=n.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,c=l.limit??{},u=l.modalities??{},g=Array.isArray(u.input)?u.input:[];s.set(i,{id:i,name:typeof l.name=="string"?l.name:i,contextWindow:typeof c.context=="number"?c.context:2e5,maxOutput:typeof c.output=="number"?c.output:8192,toolCall:l.tool_call===!0,reasoning:l.reasoning===!0,vision:l.attachment===!0||g.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(t,{models:s})}return e}var xu={claude:"anthropic",gemini:"google","x-ai":"xai","z-ai":"xai",silicon:"siliconflow","silicon-flow":"siliconflow"},nt=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of Yo)this.builtins.set(t.id,t);this.catalog=e?.catalog??new ot}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=xu[e]??e,n=this.builtins.get(t),r=this.overrides.get(t);if(!(!n&&!r))return!n&&r?!r.id||!r.transport||!r.baseUrl?void 0:{id:r.id,name:r.name??r.id,transport:r.transport,baseUrl:r.baseUrl,apiKeyEnvVars:r.apiKeyEnvVars??[],authType:r.authType??"bearer",isAggregator:r.isAggregator??!1,defaultModel:r.defaultModel,models:r.models}:n&&!r?n:{...n,...r,models:r.models??n.models}}listProviders(){let e=new Map;for(let[t,n]of this.builtins)e.set(t,n);for(let[t]of this.overrides){let n=this.getProvider(t);n&&e.set(t,n)}return[...e.values()]}listModels(e){let n=this.getProvider(e)?.models??[],r=this.catalog.getModels(e);if(r.length===0)return n;let s=new Map;for(let i of r)s.set(i.id,i);for(let i of n)s.set(i.id,i);return[...s.values()]}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,t){if(t)return t;let n=this.getProvider(e);if(n)for(let r of n.apiKeyEnvVars){let s=process.env[r];if(s?.trim())return s.trim()}}};var rt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;constructor(e){if(!e.baseUrl)throw new Error("OpenAIChatTransport: baseUrl is required (got empty or undefined)");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,t,n){let r=`${this.baseUrl}/v1/chat/completions`,s={model:e.model,messages:e.messages,stream:!0};this.supportsStreamOptions&&(s.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(s.tools=e.tools,e.toolChoice&&(s.tool_choice=e.toolChoice)),e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(s.temperature=e.temperature)),e.maxTokens!==void 0&&(s.max_tokens=e.maxTokens),e.reasoning&&(s.reasoning=e.reasoning);let i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,l=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`LLM API error ${l.status}: ${c.slice(0,500)}`)}if(!l.body)throw new Error("LLM API returned no response body");yield*this.parseSSEStream(l.body)}async*parseSSEStream(e){let t=new TextDecoder,n="";for await(let r of e){n+=t.decode(r,{stream:!0});let s;for(;(s=n.indexOf(`
30
- `))!==-1;){let i=n.slice(0,s).trim();if(n=n.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(n.trim()){let r=n.trim();if(r.startsWith("data: ")&&r.slice(6)!=="[DONE]")try{let s=JSON.parse(r.slice(6));yield*this.mapChunk(s)}catch{}}}*mapChunk(e){if(e.usage&&(yield{type:"usage",promptTokens:e.usage.prompt_tokens??0,completionTokens:e.usage.completion_tokens??0,reasoningTokens:e.usage.completion_tokens_details?.reasoning_tokens}),!(!e.choices||e.choices.length===0))for(let t of e.choices){let n=t.delta;if(n){if(n.reasoning_content&&(yield{type:"reasoning_delta",text:n.reasoning_content}),n.content&&(yield{type:"delta",text:n.content}),n.tool_calls)for(let r of n.tool_calls)yield{type:"tool_call_delta",index:r.index,id:r.id,name:r.function?.name,arguments:r.function?.arguments??""};t.finish_reason&&(yield{type:"done",finishReason:t.finish_reason})}}}};var st=class{baseUrl;apiVersion;timeoutMs;constructor(e){if(!e.baseUrl)throw new Error("AnthropicMessagesTransport: baseUrl is required (got empty or undefined)");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiVersion=e.apiVersion??"2023-06-01",this.timeoutMs=e.timeoutMs??18e4}async*stream(e,t,n){let r=`${this.baseUrl}/v1/messages`,{system:s,messages:i}=Su(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(Cu),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:wu(e.reasoning.effort)});let l=AbortSignal.timeout(this.timeoutMs),c=n?AbortSignal.any([n,l]):l,u=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion},body:JSON.stringify(a),signal:c});if(!u.ok){let g=await u.text().catch(()=>"");throw new Error(`Anthropic API error ${u.status}: ${g.slice(0,500)}`)}if(!u.body)throw new Error("Anthropic API returned no response body");yield*this.parseSSEStream(u.body)}async*parseSSEStream(e){let t=new TextDecoder,n="",r="",s=new Map;for await(let i of e){n+=t.decode(i,{stream:!0});let a;for(;(a=n.indexOf(`
31
- `))!==-1;){let l=n.slice(0,a).trim();if(n=n.slice(a+1),!l){r="";continue}if(l.startsWith("event: ")){r=l.slice(7).trim();continue}if(!l.startsWith("data: "))continue;let c=l.slice(6),u;try{u=JSON.parse(c)}catch{continue}yield*this.mapEvent(r,u,s)}}}*mapEvent(e,t,n){switch(e){case"message_start":{let s=t.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=t.index,s=t.content_block;if(!s)break;let i=s.type;n.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=t.index,s=t.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=t.index;n.delete(r);break}case"message_delta":{let r=t.delta,s=t.usage;s&&(yield{type:"usage",promptTokens:0,completionTokens:s.output_tokens??0}),r?.stop_reason&&(yield{type:"done",finishReason:vu(r.stop_reason)});break}case"message_stop":break;case"error":{let r=t.error;throw new Error(`Anthropic stream error: ${r?.message??JSON.stringify(t)}`)}}}};function vu(o){switch(o){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_calls";case"max_tokens":return"length";default:return o}}var ws={xhigh:32e3,high:16e3,medium:8e3,low:4e3};function wu(o){return ws[o]??ws.high}function Su(o){let e,t=[];for(let n of o){if(n.role==="system"){e=e?`${e}
27
+ ${w}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:h?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let p=a?.model??"",d=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=a?.summaryModel?async k=>{try{let w=k.map(R=>`${R.name}(${R.arguments.slice(0,200)})`).join(", "),f=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:w}],tools:[],maxTokens:60},a.apiKey??this.apiKey),C="";for await(let R of f)R.type==="delta"&&(C+=R.text);return C.trim()||null}catch{return null}}:void 0,y={turnId:n,sessionId:e.sessionId,messages:u,tools:s,model:p,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:d,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,generateToolUseSummary:m,signal:t},h;for await(let k of bs(y,this.transport,this.toolInvoker,this.log))h=k,yield k;h?.type==="end"?this.hooks?.invoke("turn.completed",{...l}).catch(()=>{}):h?.type==="error"&&this.hooks?.invoke("turn.failed",{...l,code:h.code,error:h.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let y=m instanceof Error?m.message:String(m),h=typeof m?.status=="number"?m.status:void 0,k=We(h,y),w=So(k);this.log.error(`turn ${n} error [${k}, retryable=${w.retryable}]: ${y}`),this.hooks?.invoke("turn.failed",{...l,code:k,error:y}).catch(()=>{}),yield{type:"error",turnId:n,error:y,code:k}}}}}});import{randomUUID as ye}from"node:crypto";import{createInterface as Bl}from"node:readline";var Be=class{messageHandler=null;closeHandler=null;verbose;constructor(e){this.verbose=e?.verbose??!1}onMessage(e){this.messageHandler=e}onClose(e){this.closeHandler=e}send(e){process.stdout.write(`${JSON.stringify(e)}
28
+ `)}start(){let e=Bl({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let n=t.trim();if(n)try{let r=JSON.parse(n);this.messageHandler?.(r)}catch{this.log(`invalid JSON on stdin: ${n.slice(0,200)}`)}}),e.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
29
+ `)}};un();tn();var it=class{supportedTypes=["image","video","3d"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4}async generate(e,t,n){switch(e.mediaType){case"image":return this.generateImage(e,t,n);case"video":return this.generateVideo(e,t,n);case"3d":return this.generate3D(e,t,n);default:throw new Error(`VolcengineMediaTransport: unsupported mediaType "${e.mediaType}"`)}}canHandle(e){return!!this.supportedTypes.includes(e.mediaType)}async generateImage(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v3/images/generations`,i={model:e.model,prompt:e.prompt,size:e.size??"1024x1024",n:e.n??1,response_format:"url"};e.imageUrl&&(i.image=e.imageUrl);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${u}`)}return{mediaUrls:((await a.json()).data??[]).map(u=>u.url).filter(u=>!!u),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r}}async generateVideo(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=[];if(e.sourceVideos?.length)for(let p of e.sourceVideos)i.push({type:"video_url",video_url:{url:p}});if(e.referenceImages?.length)for(let p of e.referenceImages)i.push({type:"image_url",image_url:{url:p}});else e.imageUrl&&i.push({type:"image_url",image_url:{url:e.imageUrl}});e.prompt&&i.push({type:"text",text:e.prompt});let a={model:e.model,content:i};e.duration&&(a.duration=e.duration),e.aspectRatio&&(a.aspect_ratio=e.aspectRatio),e.resolution&&(a.resolution=e.resolution);let l=await this.submitTask(s,a,t,n),c=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${l}`,t,n),u=[];if(Array.isArray(c.content))for(let p of c.content)p?.type==="video_url"&&p.video_url?.url&&u.push(p.video_url.url);return{mediaUrls:u,model:e.model,durationMs:Date.now()-r}}async generate3D(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v3/3d-contents/generations/tasks`,i={model:e.model};e.imageUrl&&(i.image={url:e.imageUrl}),e.prompt&&(i.prompt=e.prompt);let a=await this.submitTask(s,i,t,n),l=await this.pollTask(`${this.baseUrl}/v3/3d-contents/generations/tasks/${a}`,t,n),c=[],u=l.output;if(u?.model_urls){let p=u.model_urls;for(let d of Object.values(p))d&&c.push(d)}return{mediaUrls:c,model:e.model,durationMs:Date.now()-r}}async submitTask(e,t,n,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:r??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${l}`)}let i=await s.json(),a=i.id??i.task_id;if(!a)throw new Error("Volcengine task submit: no task_id in response");return a}async pollTask(e,t,n){let r=Date.now()+6e5;for(;Date.now()<r;){n?.throwIfAborted();let s=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Volcengine task poll error ${s.status}: ${l}`)}let i=await s.json(),a=i.status;if(a==="succeeded"||a==="complete")return i;if(a==="failed"||a==="cancelled"){let l=i.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${l}`)}await new Promise(l=>setTimeout(l,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as Eu,mkdirSync as Iu}from"node:fs";import{join as $s}from"node:path";import{randomUUID as Ou}from"node:crypto";import{homedir as Au}from"node:os";import{join as ee}from"node:path";var fe=".qlogicagent";function H(){return ee(Au(),fe)}function dn(){return ee(H(),"sessions")}function vs(o){return ee(dn(),o)}function ws(){return ee(H(),"plugins")}function Ut(){return ee(H(),"skills")}function Ge(){return ee(H(),"settings.json")}function jt(){return ee(H(),"cache")}function Ss(){return ee(H(),"debug-logs")}function Cs(o){let e=ee(H(),"checkpoints");return o?ee(e,o):e}function _s(){return ee(H(),"plugin-cache")}function Rs(){return ee(H(),"mcp.json")}function Ms(){return ee(H(),"marketplace.json")}function Ps(){return ee(H(),"workflows")}function As(){return ee(H(),"rules")}function pn(o){return ee(o??process.cwd(),fe)}function Es(o){return ee(pn(o),"workflows")}function Is(o){return ee(pn(o),"INSTRUCTIONS.md")}function Os(o){return ee(pn(o),"rules")}function Ls(o){return ee(o,fe,"hooks")}var Lu=18e4,at=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Lu}async generate(e,t,n){switch(e.mediaType){case"image":return this.generateImage(e,t,n);case"tts":return this.generateTTS(e,t,n);default:throw new Error(`OpenAIMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateImage(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v1/images/generations`,i={model:e.model,prompt:e.prompt,n:e.n??1,size:e.size??"1024x1024",response_format:"url"},a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${u}`)}return{mediaUrls:((await a.json()).data??[]).map(u=>u.url).filter(u=>!!u),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r}}async generateTTS(e,t,n){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("OpenAIMediaTransport: text or prompt is required for TTS");let i=`${this.baseUrl}/v1/audio/speech`,a={model:e.model||"tts-1",input:s,voice:"alloy",response_format:"mp3"},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${l.status}: ${m}`)}let c=Buffer.from(await l.arrayBuffer()),u=$s(jt(),"tts");Iu(u,{recursive:!0});let p=`openai-tts-${Ou()}.mp3`,d=$s(u,p);return Eu(d,c),{mediaUrls:[`file://${d}`],model:e.model||"tts-1",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:s.length}}};var lt=class{supportedTypes=["music"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??6e4}async generate(e,t,n){if(e.mediaType!=="music")throw new Error(`MiniMaxMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=`${this.baseUrl}/v1/music_generation`,i={model:e.model,prompt:e.prompt};e.lyrics&&(i.lyrics=e.lyrics),e.duration&&(i.duration=e.duration);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`MiniMax music submit error ${a.status}: ${d}`)}let l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax music submit rejected: ${l.base_resp.status_msg??"unknown"}`);let c=l.task_id;if(!c)throw new Error("MiniMax music submit: no task_id in response");let u=`${this.baseUrl}/v1/music_generation/${c}`;return{mediaUrls:(await this.pollTask(u,t,n)).audioUrls,model:e.model,durationMs:Date.now()-r}}async pollTask(e,t,n){let r=Date.now()+6e5;for(;Date.now()<r;){n?.throwIfAborted();let s=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`MiniMax music poll error ${s.status}: ${l}`)}let i=await s.json(),a=i.status;if(a==="Success"||a==="Finished"){let l=[];return i.audio_file&&l.push(i.audio_file),{audioUrls:l}}if(a==="Failed"||a==="Cancelled")throw new Error(`MiniMax music task failed: ${i.base_resp?.status_msg??"unknown"}`);await new Promise(l=>setTimeout(l,3e3))}throw new Error("MiniMax music task timed out after polling")}};var ct=class{supportedTypes=["image"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4}async generate(e,t,n){if(e.mediaType!=="image")throw new Error(`GeminiMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={contents:[{parts:[{text:e.prompt}]}],generationConfig:{responseModalities:["TEXT","IMAGE"]}},a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Gemini image API error ${a.status}: ${u}`)}let l=await a.json(),c=[];for(let u of l.candidates??[])for(let p of u.content?.parts??[])if(p.inlineData?.data){let d=`data:${p.inlineData.mimeType};base64,${p.inlineData.data}`;c.push(d)}return{mediaUrls:c,model:e.model,durationMs:Date.now()-r}}};var Ft=class{supportedTypes=["tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/apps\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??3e4}async generate(e,t,n){if(e.mediaType!=="tts")throw new Error(`QwenMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("QwenMediaTransport: text or prompt is required for TTS");let i=`${this.baseUrl}/api/v1/services/aigc/text2audio/generation`,a={model:e.model||"qwen3-tts-voicedesign",input:{text:s},parameters:{format:"mp3",sample_rate:24e3}},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let d=await l.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${l.status}: ${d}`)}let c=await l.json();if(c.code)throw new Error(`DashScope TTS submit rejected: ${c.code} \u2014 ${c.message??""}`);let u=c.output?.task_id;if(!u)throw new Error("DashScope TTS submit: no task_id in response");if(c.output?.task_status==="SUCCEEDED"){let d=this.extractAudioUrl(c);return{mediaUrls:d?[d]:[],model:e.model,durationMs:Date.now()-r}}return{mediaUrls:await this.pollTask(u,t,n),model:e.model,durationMs:Date.now()-r}}async pollTask(e,t,n){let r=Date.now()+12e4,s=`${this.baseUrl}/api/v1/tasks/${e}`;for(;Date.now()<r;){n?.throwIfAborted(),await $u(2e3);let i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${i.status}: ${c}`)}let a=await i.json();if(a.code)throw new Error(`DashScope TTS poll rejected: ${a.code} \u2014 ${a.message??""}`);let l=a.output?.task_status;if(l==="SUCCEEDED"){let c=this.extractAudioUrl(a);return c?[c]:[]}if(l==="FAILED")throw new Error(`DashScope TTS task failed: ${a.message??"unknown error"}`)}throw new Error("DashScope TTS task timed out")}extractAudioUrl(e){if(e.output?.audio_url)return e.output.audio_url;if(e.output?.results?.[0]?.url)return e.output.results[0].url}};function $u(o){return new Promise(e=>setTimeout(e,o))}var ut=class{registry;transports=new Map;constructor(e){this.registry=e.registry}resolveModel(e,t){if(t){let n=this.findModelInProvider(t,e);if(n)return n}for(let n of this.registry.listProviders()){let r=this.findModelInProvider(n.id,e);if(r)return r}}getTransport(e){let t=this.transports.get(e);if(t)return t;let n=this.registry.getProvider(e);if(!n)return;let r=Du(n);if(r)return this.transports.set(e,r),r}listMediaModels(e){let t=[];for(let n of this.registry.listProviders()){let r=this.registry.listModels(n.id);for(let s of r)s.mediaType&&(!e||s.mediaType===e)&&t.push({providerId:n.id,providerDef:n,modelInfo:s,mediaType:s.mediaType})}return t}findModelInProvider(e,t){let n=this.registry.getProvider(e);if(!n)return;let s=this.registry.listModels(e).find(i=>i.mediaType===t);if(s)return{providerId:e,providerDef:n,modelInfo:s,mediaType:t}}};function Du(o){let e=o.baseUrl;switch(o.id){case"doubao":return new it({baseUrl:e});case"openai":return new at({baseUrl:e});case"minimax":return new lt({baseUrl:e});case"google":return new ct({baseUrl:e});case"qwen":return new Ft({baseUrl:e});default:return}}var mn=[{id:"deepseek",name:"DeepSeek",transport:"anthropic-messages",baseUrl:"https://api.deepseek.com/anthropic",apiKeyEnvVars:["DEEPSEEK_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"deepseek-v4-flash",models:[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:1.74,costOutput:3.48}]},{id:"qwen",name:"Alibaba Qwen (DashScope)",transport:"anthropic-messages",baseUrl:"https://dashscope.aliyuncs.com/apps/anthropic",apiKeyEnvVars:["DASHSCOPE_API_KEY","QWEN_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"qwen3.6-plus",models:[{id:"qwen3.6-plus",name:"Qwen3.6 Plus",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:3,costCacheRead:.05,costCacheWrite:.625},{id:"qwen3-tts-voicedesign",name:"Qwen3 TTS VoiceDesign",contextWindow:32768,maxOutput:16384,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts"}]},{id:"zhipu",name:"\u667A\u8C31 GLM (Zhipu)",transport:"anthropic-messages",baseUrl:"https://open.bigmodel.cn/api/anthropic",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"glm-5",models:[{id:"glm-5",name:"GLM-5",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-5.1",name:"GLM-5.1",contextWindow:2e5,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:6,costOutput:24,costCacheRead:1.3}]},{id:"minimax",name:"MiniMax",transport:"anthropic-messages",baseUrl:"https://api.minimaxi.com/anthropic",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"MiniMax-M2.7",models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2,costCacheRead:.06,costCacheWrite:.375},{id:"music-2.6",name:"MiniMax Music 2.6",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"music"},{id:"music-cover",name:"MiniMax Music Cover",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"music"}]},{id:"moonshot",name:"Moonshot (Kimi)",transport:"openai-chat",baseUrl:"https://api.moonshot.cn",apiKeyEnvVars:["MOONSHOT_API_KEY"],authType:"bearer",isAggregator:!1,omitZeroTemperature:!0,defaultModel:"kimi-k2.6",models:[{id:"kimi-k2.6",name:"Kimi K2.6",contextWindow:262144,maxOutput:262144,toolCall:!0,reasoning:!0,vision:!0,costInput:.95,costOutput:4,costCacheRead:.16}]},{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-seedream-5-0-260128",models:[{id:"doubao-seedance-2-0-260128",name:"Doubao Seedance 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"video"},{id:"doubao-seedance-2-0-fast-260128",name:"Doubao Seedance 2.0 Fast",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"video"},{id:"doubao-seedream-5-0-260128",name:"Doubao Seedream 5.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"},{id:"doubao-seedream-4-5-251128",name:"Doubao Seedream 4.5",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"},{id:"doubao-seed3d-2-0-260328",name:"Doubao Seed3D 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d"},{id:"hyper3d-gen2-260112",name:"Hyper3D Gen2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d"},{id:"hitem3d-2-0-251223",name:"HiTem3D 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d"}]},{id:"openai",name:"OpenAI",transport:"openai-chat",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-5.5",models:[{id:"gpt-5.5",name:"GPT-5.5",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:30,costCacheRead:.5},{id:"gpt-5.4",name:"GPT-5.4",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:2.5,costOutput:15,costCacheRead:.25},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.75,costOutput:4.5,costCacheRead:.075},{id:"o3",name:"o3",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!0,costInput:2,costOutput:8,costCacheRead:.5},{id:"o4-mini",name:"o4-mini",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!0,costInput:1.1,costOutput:4.4,costCacheRead:.28},{id:"gpt-image-2",name:"GPT Image 2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"},{id:"tts-1",name:"OpenAI TTS-1",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts"},{id:"tts-1-hd",name:"OpenAI TTS-1 HD",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts"}]},{id:"anthropic",name:"Anthropic",transport:"anthropic-messages",baseUrl:"https://api.anthropic.com",apiKeyEnvVars:["ANTHROPIC_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"claude-opus-4-7",models:[{id:"claude-opus-4-7",name:"Claude Opus 4.7",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-opus-4-6",name:"Claude Opus 4.6",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindow:1e6,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:5,costCacheRead:.1,costCacheWrite:1.25}]},{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-pro",models:[{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,costCacheRead:.125},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.15,costOutput:.6,costCacheRead:.0375},{id:"gemini-3.1-flash-image-preview",name:"Gemini 3.1 Flash Image",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"}]},{id:"openrouter",name:"OpenRouter",transport:"openai-chat",baseUrl:"https://openrouter.ai/api",apiKeyEnvVars:["OPENROUTER_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"anthropic/claude-opus-4.7",extraHeaders:{"HTTP-Referer":"https://claw.bot","X-Title":"XiaozhiClaw"},models:[{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7 (via OpenRouter)",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5},{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6 (via OpenRouter)",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5},{id:"deepseek/deepseek-v4-flash",name:"DeepSeek V4 Flash (via OpenRouter)",contextWindow:1048576,maxOutput:393216,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28,costCacheRead:.028}]},{id:"qwen-coding",name:"Alibaba Qwen (Coding Plan)",transport:"anthropic-messages",baseUrl:"https://coding.dashscope.aliyuncs.com/apps/anthropic",apiKeyEnvVars:["DASHSCOPE_API_KEY","QWEN_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"qwen3-coder-plus",models:[{id:"qwen3-coder-plus",name:"Qwen3 Coder Plus (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1},{id:"qwen3-coder-flash",name:"Qwen3 Coder Flash (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1}]},{id:"doubao-coding",name:"\u8C46\u5305 Doubao (Coding Plan)",transport:"anthropic-messages",baseUrl:"https://ark.cn-beijing.volces.com/api/coding",apiKeyEnvVars:["ARK_API_KEY","DOUBAO_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"doubao-pro-256k",models:[{id:"doubao-pro-256k",name:"Doubao Pro 256K (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1}]}];import{existsSync as Nu,mkdirSync as Uu,readFileSync as ju,writeFileSync as Fu}from"node:fs";import{join as Bu}from"node:path";var Wu="https://models.dev/api.json",qu=3e4,Hu=1440*60*1e3,Gu=300*1e3,zu={deepseek:"deepseek",qwen:"qwen","qwen-coding-plan":"qwen-coding","alibaba-cn":"qwen",zhipuai:"zhipu",minimax:"minimax",moonshot:"moonshot",moonshotai:"moonshot",doubao:"doubao","doubao-coding-plan":"doubao-coding","bytedance-seed":"doubao",volcengine:"doubao","volcengine-coding-plan":"doubao-coding",openai:"openai",anthropic:"anthropic",google:"google",openrouter:"openrouter"},dt=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??jt(),this.cacheFile=Bu(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??Hu}getModels(e){this.ensureLoaded();let t=this.cache?.providers.get(e);return t?[...t.models.values()]:[]}getModel(e,t){return this.ensureLoaded(),this.cache?.providers.get(e)?.models.get(t)}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(!Nu(this.cacheFile))return;let e=ju(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:Ds(t.data)}}catch{}}saveToDisk(e){try{Uu(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);Fu(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<Gu||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(Wu,{signal:AbortSignal.timeout(qu),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=Ds(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function Ds(o){let e=new Map;if(!o||typeof o!="object")return e;for(let[t,n]of Object.entries(o)){let r=zu[t];if(!r||!n||typeof n!="object")continue;let i=n.models;if(!i||typeof i!="object")continue;let a=e.get(r);a||(a={models:new Map},e.set(r,a));for(let[l,c]of Object.entries(i)){if(!c||typeof c!="object"||a.models.has(l))continue;let u=c,p=u.cost??{},d=u.limit??{},m=u.modalities??{},y=Array.isArray(m.input)?m.input:[],h=Array.isArray(m.output)?m.output:[],k=Vu(h,y,l);a.models.set(l,{id:l,name:typeof u.name=="string"?u.name:l,contextWindow:typeof d.context=="number"?d.context:2e5,maxOutput:typeof d.output=="number"?d.output:8192,toolCall:u.tool_call===!0,reasoning:u.reasoning===!0,vision:u.attachment===!0||y.includes("image"),costInput:typeof p.input=="number"?p.input:void 0,costOutput:typeof p.output=="number"?p.output:void 0,costCacheRead:typeof p.cache_read=="number"?p.cache_read:void 0,costCacheWrite:typeof p.cache_write=="number"?p.cache_write:void 0,mediaType:k})}}return e}function Vu(o,e,t){if(o.includes("video"))return"video";if(o.includes("image")&&!o.includes("text"))return"image";if(o.includes("audio")&&!o.includes("text"))return"tts";if(o.includes("3d"))return"3d";let n=t.toLowerCase();if(n.includes("tts")||n.includes("speech")||n.includes("cosyvoice"))return"tts";if(n.includes("music")||n.includes("suno"))return"music";if(n.includes("seedream")||n.includes("image")||n.includes("dall"))return"image";if(n.includes("seedance")||n.includes("video"))return"video"}var Ku={claude:"anthropic",gemini:"google"},pt=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of mn)this.builtins.set(t.id,t);this.catalog=e?.catalog??new dt}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=Ku[e]??e,n=this.builtins.get(t),r=this.overrides.get(t);if(!(!n&&!r))return!n&&r?!r.id||!r.transport||!r.baseUrl?void 0:{id:r.id,name:r.name??r.id,transport:r.transport,baseUrl:r.baseUrl,apiKeyEnvVars:r.apiKeyEnvVars??[],authType:r.authType??"bearer",isAggregator:r.isAggregator??!1,defaultModel:r.defaultModel,models:r.models}:n&&!r?n:{...n,...r,models:r.models??n.models}}listProviders(){let e=new Map;for(let[t,n]of this.builtins)e.set(t,n);for(let[t]of this.overrides){let n=this.getProvider(t);n&&e.set(t,n)}return[...e.values()]}listModels(e){let n=this.getProvider(e)?.models??[],r=this.catalog.getModels(e);if(r.length===0)return n;let s=new Map;for(let i of r)s.set(i.id,i);for(let i of n)s.set(i.id,i);return[...s.values()]}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,t){if(t)return t;let n=this.getProvider(e);if(n)for(let r of n.apiKeyEnvVars){let s=process.env[r];if(s?.trim())return s.trim()}}};var mt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;constructor(e){if(!e.baseUrl)throw new Error("OpenAIChatTransport: baseUrl is required (got empty or undefined)");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,t,n){let r=`${this.baseUrl}/v1/chat/completions`,s={model:e.model,messages:e.messages,stream:!0};this.supportsStreamOptions&&(s.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(s.tools=e.tools,e.toolChoice&&(s.tool_choice=e.toolChoice)),e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||gn(e.model)||(s.temperature=e.temperature)),e.maxTokens!==void 0&&(gn(e.model)?s.max_completion_tokens=e.maxTokens:s.max_tokens=e.maxTokens),e.reasoning&&(gn(e.model)?s.reasoning_effort=e.reasoning.effort:s.reasoning=e.reasoning);let i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,l=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`LLM API error ${l.status}: ${c.slice(0,500)}`)}if(!l.body)throw new Error("LLM API returned no response body");yield*this.parseSSEStream(l.body)}async*parseSSEStream(e){let t=new TextDecoder,n="";for await(let r of e){n+=t.decode(r,{stream:!0});let s;for(;(s=n.indexOf(`
30
+ `))!==-1;){let i=n.slice(0,s).trim();if(n=n.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(n.trim()){let r=n.trim();if(r.startsWith("data: ")&&r.slice(6)!=="[DONE]")try{let s=JSON.parse(r.slice(6));yield*this.mapChunk(s)}catch{}}}*mapChunk(e){if(e.usage&&(yield{type:"usage",promptTokens:e.usage.prompt_tokens??0,completionTokens:e.usage.completion_tokens??0,reasoningTokens:e.usage.completion_tokens_details?.reasoning_tokens}),!(!e.choices||e.choices.length===0))for(let t of e.choices){let n=t.delta;if(n){if(n.reasoning_content&&(yield{type:"reasoning_delta",text:n.reasoning_content}),n.content&&(yield{type:"delta",text:n.content}),n.tool_calls)for(let r of n.tool_calls)yield{type:"tool_call_delta",index:r.index,id:r.id,name:r.function?.name,arguments:r.function?.arguments??""};t.finish_reason&&(yield{type:"done",finishReason:t.finish_reason})}}}};function gn(o){let e=o.toLowerCase();return/^o[1-9]/.test(e)}var Ju=new Set([429,529,502,503,504]),Yu="[Tool execution failed; output not available during conversation recovery]",Xu="interleaved-thinking-2025-05-14",Qu="context-1m-2025-08-07",Zu="token-efficient-tools-2026-03-28",ed="prompt-caching-scope-2026-01-05";function td(o,e,t){let n=[],r=o.toLowerCase();(r.includes("opus-4-6")||r.includes("opus-4-7")||r.includes("sonnet-4-6"))&&n.push(Qu),e&&!r.includes("haiku")&&n.push(Xu),t&&n.push(Zu),n.push(ed);let i=process.env.ANTHROPIC_BETAS;if(i)for(let a of i.split(",").map(l=>l.trim()).filter(Boolean))n.includes(a)||n.push(a);return n}var gt=class{baseUrl;apiVersion;timeoutMs;streamIdleTimeoutMs;enablePromptCaching;maxRetries;constructor(e){if(!e.baseUrl)throw new Error("AnthropicMessagesTransport: baseUrl is required (got empty or undefined)");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiVersion=e.apiVersion??"2023-06-01",this.timeoutMs=e.timeoutMs??18e4,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??9e4,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3}async*stream(e,t,n){let r=`${this.baseUrl}/v1/messages`,s=rd(e.messages),{system:i,messages:a}=sd(s),l=nd(i,this.enablePromptCaching),c=!!e.reasoning,u=e.maxTokens??8192,p={model:e.model,messages:a,max_tokens:u,stream:!0};if(l&&(p.system=l),e.tools&&e.tools.length>0&&(p.tools=e.tools.map(id),e.toolChoice&&(p.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})),!c&&e.temperature!==void 0&&(p.temperature=e.temperature),c){let h=od(e.reasoning.effort);p.thinking={type:"enabled",budget_tokens:Math.min(u-1,h)}}let d=td(e.model,c,(e.tools?.length??0)>0),m={"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion};d.length>0&&(m["anthropic-beta"]=d.join(","));let y=null;for(let h=0;h<=this.maxRetries;h++){if(n?.aborted)throw new Error("Request aborted");if(h>0&&y){let k=Math.min(1e3*Math.pow(2,h-1),3e4),w=Math.random()*.25*k;await ld(k+w,n)}try{yield*this.streamWithWatchdog(r,m,p,n);return}catch(k){y=k instanceof Error?k:new Error(String(k));let w=ad(y.message),f=w!==null&&Ju.has(w),C=y.message.includes("Stream idle timeout");if(y.message.includes("model_context_window_exceeded")||y.message.includes("context_length_exceeded")||!f&&!C)throw y;if(h===this.maxRetries){if(C||f)try{yield*this.nonStreamingFallback(r,m,p,n);return}catch{throw y}throw y}}}if(y)throw y}async*streamWithWatchdog(e,t,n,r){let s=AbortSignal.timeout(this.timeoutMs),i=r?AbortSignal.any([r,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(n),signal:i});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Anthropic API error ${a.status}: ${d.slice(0,500)}`)}if(!a.body)throw new Error("Anthropic API returned no response body");let l=null,c=!1,u=()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{c=!0},this.streamIdleTimeoutMs)},p=()=>{l!==null&&(clearTimeout(l),l=null)};u();try{yield*this.parseSSEStream(a.body,u,()=>c)}finally{p()}if(c)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,n,r){let s=cd({...n,stream:!1}),i=AbortSignal.timeout(3e5),a=r?AbortSignal.any([r,i]):i,l=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!l.ok){let u=await l.text().catch(()=>"");throw new Error(`Anthropic API error ${l.status}: ${u.slice(0,500)}`)}let c=await l.json();yield*this.mapNonStreamingResponse(c)}*mapNonStreamingResponse(e){let t=e.usage;t&&(yield{type:"usage",promptTokens:t.input_tokens??0,completionTokens:t.output_tokens??0,cacheReadTokens:t.cache_read_input_tokens>0?t.cache_read_input_tokens:void 0,cacheCreationTokens:t.cache_creation_input_tokens>0?t.cache_creation_input_tokens:void 0});let n=e.content;if(Array.isArray(n)){let s=0;for(let i of n){let a=i.type;a==="text"?yield{type:"delta",text:i.text}:a==="thinking"?yield{type:"reasoning_delta",text:i.thinking}:a==="tool_use"&&(yield{type:"tool_call_delta",index:s++,id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})})}}let r=e.stop_reason;r&&(yield{type:"done",finishReason:Us(r)})}async*parseSSEStream(e,t,n){let r=new TextDecoder,s="",i="",a=new Map,l={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};for await(let c of e){if(t(),n())break;s+=r.decode(c,{stream:!0});let u;for(;(u=s.indexOf(`
31
+ `))!==-1;){let p=s.slice(0,u).trim();if(s=s.slice(u+1),!p){i="";continue}if(p.startsWith("event: ")){i=p.slice(7).trim();continue}if(!p.startsWith("data: "))continue;let d=p.slice(6),m;try{m=JSON.parse(d)}catch{continue}yield*this.mapEvent(i,m,a,l)}}}*mapEvent(e,t,n,r){switch(e){case"message_start":{let i=t.message?.usage;i&&(Ns(r,i),yield{type:"usage",promptTokens:r.inputTokens,completionTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens>0?r.cacheReadTokens:void 0,cacheCreationTokens:r.cacheCreationTokens>0?r.cacheCreationTokens:void 0});break}case"content_block_start":{let s=t.index,i=t.content_block;if(!i)break;let a=i.type;n.set(s,{type:a,id:i.id,name:i.name,signature:a==="thinking"?"":void 0}),a==="tool_use"&&(yield{type:"tool_call_delta",index:s,id:i.id,name:i.name,arguments:""});break}case"content_block_delta":{let s=t.index,i=t.delta;if(!i)break;let a=i.type;if(a==="text_delta")yield{type:"delta",text:i.text};else if(a==="input_json_delta")yield{type:"tool_call_delta",index:s,arguments:i.partial_json};else if(a==="thinking_delta")yield{type:"reasoning_delta",text:i.thinking};else if(a==="signature_delta"){let l=n.get(s);l&&typeof i.signature=="string"&&(l.signature=i.signature)}break}case"content_block_stop":{let s=t.index;n.delete(s);break}case"message_delta":{let s=t.delta,i=t.usage;i&&(Ns(r,i),yield{type:"usage",promptTokens:r.inputTokens,completionTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens>0?r.cacheReadTokens:void 0,cacheCreationTokens:r.cacheCreationTokens>0?r.cacheCreationTokens:void 0}),s?.stop_reason&&(yield{type:"done",finishReason:Us(s.stop_reason)});break}case"message_stop":break;case"error":{let s=t.error;throw new Error(`Anthropic stream error: ${s?.message??JSON.stringify(t)}`)}}}};function Ns(o,e){e.input_tokens>0&&(o.inputTokens=e.input_tokens),o.outputTokens=e.output_tokens??o.outputTokens,e.cache_read_input_tokens>0&&(o.cacheReadTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens>0&&(o.cacheCreationTokens=e.cache_creation_input_tokens)}function Us(o){switch(o){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_calls";case"max_tokens":return"length";default:return o}}var js={high:16e3,medium:8e3,low:4e3};function od(o){return js[o]??js.high}function nd(o,e){if(o)return e?[{type:"text",text:o,cache_control:{type:"ephemeral"}}]:o}function rd(o){let e=[],t=new Set;for(let n=0;n<o.length;n++){let r=o[n];if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){let s=r.tool_calls.filter(u=>t.has(u.id)?!1:(t.add(u.id),!0)),i=new Set(s.map(u=>u.id)),a=new Set,l=o.slice(n+1);for(let u of l){if(u.role!=="tool")break;u.tool_call_id&&a.add(u.tool_call_id)}s.length!==r.tool_calls.length?e.push({...r,tool_calls:s}):e.push(r);let c=[...i].filter(u=>!a.has(u));for(let u of c){let p=s.find(d=>d.id===u);e.push({role:"tool",tool_call_id:u,name:p?.function.name,content:"[Tool execution failed; output not available during conversation recovery]"})}}else r.role==="tool"?t.has(r.tool_call_id??"")&&e.push(r):e.push(r)}return e}function sd(o){let e,t=[];for(let n of o){if(n.role==="system"){e=e?`${e}
32
32
 
33
- ${n.content??""}`:n.content??"";continue}if(n.role==="user")t.push({role:"user",content:n.content??""});else if(n.role==="assistant")if(n.tool_calls&&n.tool_calls.length>0){let r=[];n.content&&r.push({type:"text",text:n.content});for(let s of n.tool_calls){let i;try{i=JSON.parse(s.function.arguments)}catch{i={}}r.push({type:"tool_use",id:s.id,name:s.function.name,input:i})}t.push({role:"assistant",content:r})}else t.push({role:"assistant",content:n.content??""});else n.role==="tool"&&t.push({role:"user",content:[{type:"tool_result",tool_use_id:n.tool_call_id??"",content:n.content??""}]})}return{system:e,messages:t}}function Cu(o){return{name:o.function.name,description:o.function.description,input_schema:o.function.parameters??{type:"object",properties:{}}}}function Qo(o,e){o.baseUrl&&e.applyOverride(o.provider,{baseUrl:o.baseUrl});let t=e.getProvider(o.provider);if(!t)throw new Error(`Unknown LLM provider: "${o.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let n=o.baseUrl||t.baseUrl;return{transport:_u(t,n),apiKey:o.apiKey,resolvedModel:o.model,providerDef:t}}function en(o){for(let e of o.listProviders()){let t=o.resolveApiKey(e.id);if(t)return{providerId:e.id,apiKey:t,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function _u(o,e){switch(o.transport){case"openai-chat":return new rt({baseUrl:e,extraHeaders:o.extraHeaders,supportsStreamOptions:o.supportsStreamOptions,omitZeroTemperature:o.omitZeroTemperature});case"anthropic-messages":return new st({baseUrl:e});default:throw new Error(`Unsupported transport type: "${o.transport}" for provider "${o.id}"`)}}import{join as Ru}from"node:path";import{mkdirSync as Mu,appendFileSync as Pu}from"node:fs";var Ss=ds();function tn(){return process.env.QLOGICAGENT_DEBUG==="1"}function on(o,e){let t=Ru(Ss,`${e}.jsonl`),n=!1;function r(){n||(Mu(Ss,{recursive:!0}),n=!0)}function s(i){try{r(),Pu(t,JSON.stringify(i)+`
34
- `,"utf8")}catch{}}return{async*stream(i,a,l){let c=Date.now();s({type:"request",timestamp:new Date(c).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 u=0,g=0,d=0,m="",h;try{for await(let f of o.stream(i,a,l))f.type==="usage"?(u=f.promptTokens,g=f.completionTokens,d=f.reasoningTokens??0):f.type==="done"&&(m=f.finishReason),yield f}catch(f){throw h=f instanceof Error?f.message:String(f),f}finally{let f=Date.now()-c;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:f,promptTokens:u,completionTokens:g,reasoningTokens:d,finishReason:m,...h?{error:h}:{}})}}}}function Cs(o){let e=new Map;return{register(t){let n=e.get(t.point)??[],r={handler:t.handler,priority:t.priority??100,label:t.label};return n.push(r),n.sort((s,i)=>s.priority-i.priority),e.set(t.point,n),()=>{let s=n.indexOf(r);s>=0&&n.splice(s,1)}},async invoke(t,n){let r=e.get(t);if(!r||r.length===0)return{action:"continue",context:n};let s=n;for(let i of r)try{let a=await i.handler(t,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return o.info({hook:t,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){o.warn({hook:t,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}var Mt={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function it(){return{surfacedPaths:new Set,sessionBytes:0}}function _s(o,e,t){let n=[],r=t??it(),s,i=[];return n.push(o.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>=Mt.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:l};try{let c=await e.memoryProvider.search(l.query,e.userId,{limit:Mt.LIMIT_PER_RECALL}),u=c.filter(d=>{let m=d,h=m.path??m.id??"";if(!h)return!0;if(r.surfacedPaths.has(h))return!1;let f=(m.content?.length??0)*2;if(r.sessionBytes+f>Mt.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(h),r.sessionBytes+=f,r.surfacedPaths.size>Mt.MAX_SURFACED_ENTRIES){let T=r.surfacedPaths.values().next().value;T!==void 0&&r.surfacedPaths.delete(T)}return!0});s=l.turnId,i=u,e.log.debug(`memory.before_recall: prefetched ${c.length} \u2192 ${u.length} after dedup (${r.sessionBytes} bytes used)`);let g=u.map(d=>{let m=d;return{text:m.text??m.content??"",score:m.score}}).filter(d=>d.text);return{action:"continue",context:{...l,recalledMemories:g}}}catch(c){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${c instanceof Error?c.message:String(c)}`),i=[]}return{action:"continue",context:l}}})),n.push(o.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,l)=>{let c=s===l.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${l.blockCount??0} blocks assembled, ${c} qmemory results (session: ${r.sessionBytes} bytes)`),{action:"continue",context:l}}})),()=>{for(let a of n)a();i=[]}}import{ClawQMemoryAdapter as Au}from"qlogicagent-adapter-claw";var Rs="qmemory";function Ms(o){let e=new Au({baseUrl:o.baseUrl,apiKey:o.apiKey,timeout:o.timeoutMs??5e3});function t(n){return o.userIdPrefix?`${o.userIdPrefix}:${n}`:n}return{providerId:Rs,async search(n,r,s){return((await e.dispatch("memory.search",{q:n,user_id:t(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:Rs,metadata:a.metadata}))},async ingest(n,r,s){await e.dispatch("memory.addKnowledge",{user_id:t(r),messages:n.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 n=await e.dispatch("memory.health",{});return{status:n.status??"unknown",version:n.version??"",memoryCount:n.memory_count??0,dbSizeBytes:n.db_size_bytes??0,embeddingModel:n.embedding_model??"",uptimeSeconds:n.uptime_seconds??0}},async addText(n,r,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:t(r),text:n,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(n,r,s){if(n.length===0)return{memoriesAdded:0};let i=t(r),a=await Promise.allSettled(n.map(c=>e.dispatch("memory.addFact",{user_id:i,text:c.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...c.category?{category:c.category}:{},...typeof c.importance=="number"?{importance:c.importance}:{},...c.speaker?{speaker:c.speaker}:{},...c.event_date?{event_date:c.event_date}:{},...c.tags?.length?{tags:c.tags}:{}}}))),l=0;for(let c of a)c.status==="fulfilled"&&(l+=c.value.memories_added??1);return{memoriesAdded:l}},async remove(n){try{return await e.dispatch("memory.forget",{id:n}),!0}catch{return!1}},async feedback(n,r,s){await e.dispatch("memory.feedback",{memory_ids:n,signal:r,...s?{session_id:s}:{}})}}}import{readFile as Ls,writeFile as rn,stat as Bs,unlink as Du,mkdir as Nu}from"node:fs/promises";import{join as At,resolve as $s,isAbsolute as Ds,normalize as Ns}from"node:path";import{randomUUID as ju}from"node:crypto";function Ps(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function Eu(o){return o.latestInputTokens+o.cumulativeOutputTokens}var Iu=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),As=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function Ou(o){return{isSearch:Iu.has(o)||void 0,isRead:As.has(o)||void 0}}function Lu(o,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${As.has(o)?"Reading":o.includes("write")||o.includes("edit")?"Editing":"Using"} ${t}`;let n=e.command??e.cmd;if(typeof n=="string")return`Running: ${n.length>60?n.slice(0,60)+"\u2026":n}`;let r=e.query??e.pattern??e.search;if(typeof r=="string")return`Searching: ${r}`}function Es(o,e){o.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),o.cumulativeOutputTokens+=e.output_tokens??0}function Is(o,e,t,n){o.toolUseCount++;let r=Ou(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??Lu(e,t),isSearch:r.isSearch,isRead:r.isRead};for(o.recentActivities.push(s);o.recentActivities.length>5;)o.recentActivities.shift()}function nn(o){return{toolUseCount:o.toolUseCount,tokenCount:Eu(o),lastActivity:o.recentActivities.length>0?o.recentActivities[o.recentActivities.length-1]:void 0,recentActivities:[...o.recentActivities]}}import{randomUUID as Os}from"node:crypto";function $u(o){let e=new AbortController;return o&&(o.aborted?e.abort(o.reason):o.addEventListener("abort",()=>{e.abort(o.reason)},{once:!0})),e}async function Pt(o){let e=Date.now(),t=[],n={prompt:0,completion:0},r=Ps(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:c,toolInvoker:u,apiKey:g,model:d,log:m,hooks:h,forkLabel:f,maxTurns:T,temperature:y,parentSignal:v,onEvent:_,onProgress:M,budgetTokens:$,parentDepth:q}=o,E=$u(v),O=`fork-${f}-${Os().slice(0,8)}`,k=`fork-session-${Os().slice(0,8)}`;m.info(`[fork:${f}] starting \u2014 ${s.length} initial messages, model=${d}`);let D=l?{invoke:async(Y,L,P,ie)=>{let Q={};try{Q=JSON.parse(P)}catch{}let ae=l(L,Q);return ae.allowed?u.invoke(Y,L,P,ie):(m.info(`[fork:${f}] tool ${L} denied: ${ae.reason}`),{result:"",error:ae.reason})}}:u,K=!0,oe;try{let{Agent:Y}=await Promise.resolve().then(()=>(Jo(),as)),L=new Y({llmTransport:c,apiKey:g,toolInvoker:D,log:m,hooks:h,maxRounds:T});for await(let P of L.run({turnId:O,sessionId:k,messages:s,tools:a,systemPrompt:i,config:{model:d,apiKey:g,temperature:y,maxOutputTokens:o.maxOutputTokens,parentDepth:q}},E.signal)){if(t.push(P),_?.(P),P.type==="end"&&P.usage&&(Es(r,{input_tokens:P.usage.prompt,output_tokens:P.usage.completion}),n.prompt+=P.usage.prompt,n.completion+=P.usage.completion,P.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+P.usage.cacheRead),P.usage.cacheCreation&&(n.cacheCreation=(n.cacheCreation??0)+P.usage.cacheCreation),$&&$>0)){let ie=n.prompt+n.completion+(n.reasoning??0);ie>=$&&(m.info(`[fork:${f}] budget exceeded (${ie} / ${$} tokens), aborting`),E.abort("budget_exceeded"))}if(P.type==="tool_call"){let ie={};try{ie=JSON.parse(P.arguments??"{}")}catch{}Is(r,P.name,ie),M?.(nn(r))}P.type==="error"&&(K=!1,oe=P.error)}}catch(Y){K=!1,oe=Y instanceof Error?Y.message:String(Y),m.warn(`[fork:${f}] error: ${oe}`)}finally{E.signal.aborted||E.abort("fork_complete")}let Te=Date.now()-e;return m.info(`[fork:${f}] finished in ${Te}ms \u2014 ${t.length} events, usage: prompt=${n.prompt} completion=${n.completion}, ok=${K}`),{events:t,totalUsage:n,progress:nn(r),durationMs:Te,ok:K,error:oe}}var qs={minHours:24,minSessions:5,scanIntervalMs:6e5},Et=".consolidate-lock",Fu=3600*1e3,js="CLAUDE.md",Uu=100,Bu=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"]),qu=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),Wu=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function Hu(o){let e=o.trim();if(!e||Wu.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!Bu.has(n))return!1;if(n==="git"){let r=t[1];if(!r||!qu.has(r))return!1}return!0}function Gu(o,e){let{toolName:t,input:n}=e;if(new Set(["read_file","grep","glob","search","list_dir","file_read","Grep","Glob"]).has(t))return{allowed:!0};if(new Set(["qmemory_search","qmemory_store","qmemory_feedback"]).has(t))return{allowed:!0};if(t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return Hu(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(t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??"";return typeof i=="string"&&Ws(i,o)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${o}`}}return{allowed:!1,reason:`Tool "${t}" is not permitted during dream consolidation. Only read_file, grep, glob, read-only bash, and memory-scoped file_edit/file_write are allowed.`}}function Ws(o,e){let t=Ds(o)?o:$s(o),n=Ds(e)?e:$s(e),r=Ns(t),s=Ns(n);return r.startsWith(s)}function Hs(o,e,t,n){let r=n?.hasQMemory?`
33
+ ${n.content??""}`:n.content??"";continue}if(n.role==="user")t.push({role:"user",content:n.content??""});else if(n.role==="assistant")if(n.tool_calls&&n.tool_calls.length>0){let r=[];n.content&&r.push({type:"text",text:n.content});for(let s of n.tool_calls){let i;try{i=JSON.parse(s.function.arguments)}catch{i={}}r.push({type:"tool_use",id:s.id,name:s.function.name,input:i})}t.push({role:"assistant",content:r})}else t.push({role:"assistant",content:n.content??""});else if(n.role==="tool"){let r=n.content??"",s=r.startsWith("Error:")||r===Yu,i={type:"tool_result",tool_use_id:n.tool_call_id??"",content:r,...s&&{is_error:!0}},a=t[t.length-1];a&&a.role==="user"&&Array.isArray(a.content)?a.content.push(i):t.push({role:"user",content:[i]})}}return{system:e,messages:t}}function id(o){return{name:o.function.name,description:o.function.description,input_schema:o.function.parameters??{type:"object",properties:{}}}}function ad(o){let e=/Anthropic API error (\d{3})/.exec(o);return e?parseInt(e[1],10):null}function ld(o,e){return new Promise((t,n)=>{if(e?.aborted){n(new Error("Aborted"));return}let r=setTimeout(t,o);e?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("Aborted"))},{once:!0})})}function cd(o){let e=typeof o.max_tokens=="number"?o.max_tokens:8192,t=Math.min(e,64e3),n={...o,max_tokens:t},r=n.thinking;return r?.type==="enabled"&&r.budget_tokens&&(n.thinking={...r,budget_tokens:Math.min(r.budget_tokens,t-1)}),n}function fn(o,e){o.baseUrl&&e.applyOverride(o.provider,{baseUrl:o.baseUrl});let t=e.getProvider(o.provider);if(!t)throw new Error(`Unknown LLM provider: "${o.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let n=o.baseUrl||t.baseUrl;return{transport:ud(t,n),apiKey:o.apiKey,resolvedModel:o.model,providerDef:t}}function hn(o){for(let e of o.listProviders()){let t=o.resolveApiKey(e.id);if(t)return{providerId:e.id,apiKey:t,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function ud(o,e){switch(o.transport){case"openai-chat":return new mt({baseUrl:e,extraHeaders:o.extraHeaders,supportsStreamOptions:o.supportsStreamOptions,omitZeroTemperature:o.omitZeroTemperature});case"anthropic-messages":return new gt({baseUrl:e});default:throw new Error(`Unsupported transport type: "${o.transport}" for provider "${o.id}"`)}}import{join as dd}from"node:path";import{mkdirSync as pd,appendFileSync as md}from"node:fs";var Fs=Ss();function yn(){return process.env.QLOGICAGENT_DEBUG==="1"}function bn(o,e){let t=dd(Fs,`${e}.jsonl`),n=!1;function r(){n||(pd(Fs,{recursive:!0}),n=!0)}function s(i){try{r(),md(t,JSON.stringify(i)+`
34
+ `,"utf8")}catch{}}return{async*stream(i,a,l){let c=Date.now();s({type:"request",timestamp:new Date(c).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 u=0,p=0,d=0,m="",y;try{for await(let h of o.stream(i,a,l))h.type==="usage"?(u=h.promptTokens,p=h.completionTokens,d=h.reasoningTokens??0):h.type==="done"&&(m=h.finishReason),yield h}catch(h){throw y=h instanceof Error?h.message:String(h),h}finally{let h=Date.now()-c;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:h,promptTokens:u,completionTokens:p,reasoningTokens:d,finishReason:m,...y?{error:y}:{}})}}}}function Bs(o){let e=new Map;return{register(t){let n=e.get(t.point)??[],r={handler:t.handler,priority:t.priority??100,label:t.label};return n.push(r),n.sort((s,i)=>s.priority-i.priority),e.set(t.point,n),()=>{let s=n.indexOf(r);s>=0&&n.splice(s,1)}},async invoke(t,n){let r=e.get(t);if(!r||r.length===0)return{action:"continue",context:n};let s=n;for(let i of r)try{let a=await i.handler(t,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return o.info({hook:t,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){o.warn({hook:t,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}var Bt={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function ft(){return{surfacedPaths:new Set,sessionBytes:0}}function Ws(o,e,t){let n=[],r=t??ft(),s,i=[];return n.push(o.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>=Bt.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:l};try{let c=await e.memoryProvider.search(l.query,e.userId,{limit:Bt.LIMIT_PER_RECALL}),u=c.filter(d=>{let m=d,y=m.path??m.id??"";if(!y)return!0;if(r.surfacedPaths.has(y))return!1;let h=(m.content?.length??0)*2;if(r.sessionBytes+h>Bt.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(y),r.sessionBytes+=h,r.surfacedPaths.size>Bt.MAX_SURFACED_ENTRIES){let k=r.surfacedPaths.values().next().value;k!==void 0&&r.surfacedPaths.delete(k)}return!0});s=l.turnId,i=u,e.log.debug(`memory.before_recall: prefetched ${c.length} \u2192 ${u.length} after dedup (${r.sessionBytes} bytes used)`);let p=u.map(d=>{let m=d;return{text:m.text??m.content??"",score:m.score}}).filter(d=>d.text);return{action:"continue",context:{...l,recalledMemories:p}}}catch(c){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${c instanceof Error?c.message:String(c)}`),i=[]}return{action:"continue",context:l}}})),n.push(o.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,l)=>{let c=s===l.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${l.blockCount??0} blocks assembled, ${c} qmemory results (session: ${r.sessionBytes} bytes)`),{action:"continue",context:l}}})),()=>{for(let a of n)a();i=[]}}import{ClawQMemoryAdapter as gd}from"qlogicagent-adapter-claw";var qs="qmemory";function Hs(o){let e=new gd({baseUrl:o.baseUrl,apiKey:o.apiKey,timeout:o.timeoutMs??5e3});function t(n){return o.userIdPrefix?`${o.userIdPrefix}:${n}`:n}return{providerId:qs,async search(n,r,s){return((await e.dispatch("memory.search",{q:n,user_id:t(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:qs,metadata:a.metadata}))},async ingest(n,r,s){await e.dispatch("memory.addKnowledge",{user_id:t(r),messages:n.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 n=await e.dispatch("memory.health",{});return{status:n.status??"unknown",version:n.version??"",memoryCount:n.memory_count??0,dbSizeBytes:n.db_size_bytes??0,embeddingModel:n.embedding_model??"",uptimeSeconds:n.uptime_seconds??0}},async addText(n,r,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:t(r),text:n,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(n,r,s){if(n.length===0)return{memoriesAdded:0};let i=t(r),a=await Promise.allSettled(n.map(c=>e.dispatch("memory.addFact",{user_id:i,text:c.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...c.category?{category:c.category}:{},...typeof c.importance=="number"?{importance:c.importance}:{},...c.speaker?{speaker:c.speaker}:{},...c.event_date?{event_date:c.event_date}:{},...c.tags?.length?{tags:c.tags}:{}}}))),l=0;for(let c of a)c.status==="fulfilled"&&(l+=c.value.memories_added??1);return{memoriesAdded:l}},async remove(n){try{return await e.dispatch("memory.forget",{id:n}),!0}catch{return!1}},async feedback(n,r,s){await e.dispatch("memory.feedback",{memory_ids:n,signal:r,...s?{session_id:s}:{}})}}}import{readFile as Ys,writeFile as kn,stat as ni,unlink as kd,mkdir as xd}from"node:fs/promises";import{join as qt,resolve as Xs,isAbsolute as Qs,normalize as Zs}from"node:path";import{randomUUID as vd}from"node:crypto";function Gs(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function fd(o){return o.latestInputTokens+o.cumulativeOutputTokens}var hd=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),zs=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function yd(o){return{isSearch:hd.has(o)||void 0,isRead:zs.has(o)||void 0}}function bd(o,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${zs.has(o)?"Reading":o.includes("write")||o.includes("edit")?"Editing":"Using"} ${t}`;let n=e.command??e.cmd;if(typeof n=="string")return`Running: ${n.length>60?n.slice(0,60)+"\u2026":n}`;let r=e.query??e.pattern??e.search;if(typeof r=="string")return`Searching: ${r}`}function Vs(o,e){o.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),o.cumulativeOutputTokens+=e.output_tokens??0}function Ks(o,e,t,n){o.toolUseCount++;let r=yd(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??bd(e,t),isSearch:r.isSearch,isRead:r.isRead};for(o.recentActivities.push(s);o.recentActivities.length>5;)o.recentActivities.shift()}function Tn(o){return{toolUseCount:o.toolUseCount,tokenCount:fd(o),lastActivity:o.recentActivities.length>0?o.recentActivities[o.recentActivities.length-1]:void 0,recentActivities:[...o.recentActivities]}}import{randomUUID as Js}from"node:crypto";function Td(o){let e=new AbortController;return o&&(o.aborted?e.abort(o.reason):o.addEventListener("abort",()=>{e.abort(o.reason)},{once:!0})),e}async function Wt(o){let e=Date.now(),t=[],n={prompt:0,completion:0},r=Gs(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:c,toolInvoker:u,apiKey:p,model:d,log:m,hooks:y,forkLabel:h,maxTurns:k,temperature:w,parentSignal:f,onEvent:C,onProgress:R,budgetTokens:L,parentDepth:K}=o,D=Td(f),F=`fork-${h}-${Js().slice(0,8)}`,T=`fork-session-${Js().slice(0,8)}`;m.info(`[fork:${h}] starting \u2014 ${s.length} initial messages, model=${d}`);let B=l?{invoke:async(oe,$,A,le)=>{let se={};try{se=JSON.parse(A)}catch{}let ce=l($,se);return ce.allowed?u.invoke(oe,$,A,le):(m.info(`[fork:${h}] tool ${$} denied: ${ce.reason}`),{result:"",error:ce.reason})}}:u,J=!0,Q;try{let{Agent:oe}=await Promise.resolve().then(()=>(un(),xs)),$=new oe({llmTransport:c,apiKey:p,toolInvoker:B,log:m,hooks:y,maxRounds:k});for await(let A of $.run({turnId:F,sessionId:T,messages:s,tools:a,systemPrompt:i,config:{model:d,apiKey:p,temperature:w,maxOutputTokens:o.maxOutputTokens,parentDepth:K}},D.signal)){if(t.push(A),C?.(A),A.type==="end"&&A.usage&&(Vs(r,{input_tokens:A.usage.prompt,output_tokens:A.usage.completion}),n.prompt+=A.usage.prompt,n.completion+=A.usage.completion,A.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+A.usage.cacheRead),A.usage.cacheCreation&&(n.cacheCreation=(n.cacheCreation??0)+A.usage.cacheCreation),L&&L>0)){let le=n.prompt+n.completion+(n.reasoning??0);le>=L&&(m.info(`[fork:${h}] budget exceeded (${le} / ${L} tokens), aborting`),D.abort("budget_exceeded"))}if(A.type==="tool_call"){let le={};try{le=JSON.parse(A.arguments??"{}")}catch{}Ks(r,A.name,le),R?.(Tn(r))}A.type==="error"&&(J=!1,Q=A.error)}}catch(oe){J=!1,Q=oe instanceof Error?oe.message:String(oe),m.warn(`[fork:${h}] error: ${Q}`)}finally{D.signal.aborted||D.abort("fork_complete")}let ke=Date.now()-e;return m.info(`[fork:${h}] finished in ${ke}ms \u2014 ${t.length} events, usage: prompt=${n.prompt} completion=${n.completion}, ok=${J}`),{events:t,totalUsage:n,progress:Tn(r),durationMs:ke,ok:J,error:Q}}var ri={minHours:24,minSessions:5,scanIntervalMs:6e5},Ht=".consolidate-lock",wd=3600*1e3,ei="CLAUDE.md",Sd=100,Cd=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"]),_d=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),Rd=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function Md(o){let e=o.trim();if(!e||Rd.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!Cd.has(n))return!1;if(n==="git"){let r=t[1];if(!r||!_d.has(r))return!1}return!0}function Pd(o,e){let{toolName:t,input:n}=e;if(new Set(["read_file","grep","glob","search","list_dir","file_read","Grep","Glob"]).has(t))return{allowed:!0};if(new Set(["qmemory_search","qmemory_store","qmemory_feedback"]).has(t))return{allowed:!0};if(t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return Md(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(t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??"";return typeof i=="string"&&si(i,o)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${o}`}}return{allowed:!1,reason:`Tool "${t}" is not permitted during dream consolidation. Only read_file, grep, glob, read-only bash, and memory-scoped file_edit/file_write are allowed.`}}function si(o,e){let t=Qs(o)?o:Xs(o),n=Qs(e)?e:Xs(e),r=Zs(t),s=Zs(n);return r.startsWith(s)}function ii(o,e,t,n){let r=n?.hasQMemory?`
35
35
 
36
36
  ## Phase 2.5 \u2014 Long-term memory triage (QMemory)
37
37
 
@@ -66,7 +66,7 @@ Session transcripts: \`${e}\` (large JSONL files \u2014 grep narrowly, don't rea
66
66
  ## Phase 1 \u2014 Orient
67
67
 
68
68
  - \`ls\` the memory directory to see what already exists
69
- - Read \`${js}\` to understand the current index
69
+ - Read \`${ei}\` to understand the current index
70
70
  - Skim existing topic files so you improve them rather than creating duplicates
71
71
  - If \`logs/\` or \`sessions/\` subdirectories exist, review recent entries there
72
72
 
@@ -92,7 +92,7 @@ Focus on:
92
92
 
93
93
  ## Phase 4 \u2014 Prune and index
94
94
 
95
- Update \`${js}\` 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
+ Update \`${ei}\` so it stays under ${Sd} 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.
96
96
 
97
97
  - Remove pointers to memories that are now stale, wrong, or superseded
98
98
  - 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
@@ -107,147 +107,147 @@ Sessions since last consolidation (${t.length}):
107
107
  ${t.map(s=>`- ${s}`).join(`
108
108
  `)}
109
109
 
110
- Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var Fs=0;async function zu(o,e={}){let t={...qs,...e},n;try{n=await Gs(o.memoryRoot)}catch{n=0}let r=(Date.now()-n)/36e5;if(!t.force&&r<t.minHours)return null;let s=Date.now()-Fs;if(!t.force&&s<t.scanIntervalMs)return null;Fs=Date.now();let i;try{i=await o.listSessionsSince(n)}catch{return null}return i=i.filter(a=>a!==o.currentSessionId),!t.force&&i.length<t.minSessions?null:{sessionIds:i}}async function Gs(o){let e=At(o,Et);return(await Bs(e)).mtimeMs}function Vu(o){try{return process.kill(o,0),!0}catch{return!1}}async function Ku(o){let e=At(o,Et),t,n;try{let[s,i]=await Promise.all([Bs(e),Ls(e,"utf8")]);t=s.mtimeMs;let a=parseInt(i.trim(),10);n=Number.isFinite(a)?a:void 0}catch{}if(t!==void 0&&Date.now()-t<Fu&&n!==void 0&&Vu(n))return null;await Nu(o,{recursive:!0}),await rn(e,String(process.pid));let r;try{r=await Ls(e,"utf8")}catch{return null}return parseInt(r.trim(),10)!==process.pid?null:t??0}async function Us(o,e){let t=At(o,Et);try{if(e===0){await Du(t);return}await rn(t,"");let{utimes:n}=await import("node:fs/promises"),r=e/1e3;await n(t,r,r)}catch{}}async function Ju(o){let e=At(o,Et);await rn(e,String(process.pid))}function Yu(o){return{taskId:`dream-${ju().slice(0,8)}`,type:"dream",label:"Memory consolidation",permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:1,maxTurns:0,tokenBudget:0,startedAt:Date.now(),parentTaskId:o.parentTaskId,sessionId:o.sessionId,phase:"starting",sessionsReviewing:o.sessionsReviewing,filesTouched:[],turns:[],priorLockMtime:o.priorLockMtime}}async function Xu(o,e={}){let t={...qs,...e},n=await zu(o,t);if(!n)return null;let r;if(t.force)try{r=await Gs(o.memoryRoot)}catch{r=0}else if(r=await Ku(o.memoryRoot),r===null)return null;let s=Hs(o.memoryRoot,o.transcriptDir,n.sessionIds),i=Yu({sessionId:o.currentSessionId,sessionsReviewing:n.sessionIds.length,priorLockMtime:r});return{prompt:s,taskState:i,sessionIds:n.sessionIds}}async function zs(o){let e=Date.now(),t=await Xu(o.context,o.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:n,sessionIds:r}=t,s=!!(o.qmemoryAdapter&&o.qmemoryUserId),i=s?Hs(o.context.memoryRoot,o.context.transcriptDir,r,{hasQMemory:!0}):t.prompt;o.log.info(`[dream] starting consolidation \u2014 ${r.length} sessions, memoryRoot=${o.context.memoryRoot}`+(s?", qmemory=enabled":"")),o.hooks?.invoke("subagent.started",{sessionId:o.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let a=(g,d)=>Gu(o.context.memoryRoot,{toolName:g,input:d}),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"]}}}]:[],c=s?{invoke:async(g,d,m,h)=>{let f=o.qmemoryAdapter,T=o.qmemoryUserId;if(d==="qmemory_search"){let{query:y,limit:v}=JSON.parse(m),_=await f.search(y,T,{limit:v??10});return{result:JSON.stringify(_)}}if(d==="qmemory_store"){if(!f.addText)return{result:JSON.stringify({error:"addText not supported"})};let{text:y,source:v}=JSON.parse(m),_=await f.addText(y,T,{sessionId:o.context.currentSessionId,source:v??"dream-consolidation"});return{result:JSON.stringify(_)}}if(d==="qmemory_feedback"){let{memoryIds:y,signal:v}=JSON.parse(m);return f.feedback&&await f.feedback(y,v,o.context.currentSessionId),{result:JSON.stringify({ok:!0})}}return o.toolInvoker.invoke(g,d,m,h)}}:o.toolInvoker,u=[...o.tools,...l];try{let g=await Pt({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:i,tools:u,canUseTool:a,transport:o.transport,toolInvoker:c,apiKey:o.apiKey,model:o.model,log:o.log,hooks:o.hooks,forkLabel:"dream-consolidation",parentSignal:o.parentSignal,skipTranscript:!0}),d=[];for(let m of g.events)if(m.type==="tool_call")try{let h=JSON.parse(m.arguments),f=h.file_path??h.path??h.filePath;f&&Ws(f,o.context.memoryRoot)&&d.push(f)}catch{}return g.ok?(await Ju(o.context.memoryRoot),o.log.info(`[dream] consolidation complete \u2014 ${d.length} files touched, ${g.durationMs}ms`)):(await Us(o.context.memoryRoot,n.priorLockMtime),o.log.warn(`[dream] consolidation failed: ${g.error}`)),o.hooks?.invoke("subagent.stopped",{sessionId:o.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:g.ok?"normal":"error",error:g.error}).catch(()=>{}),{ok:g.ok,sessionsReviewed:r.length,filesTouched:[...new Set(d)],turns:[],durationMs:Date.now()-e,error:g.error}}catch(g){await Us(o.context.memoryRoot,n.priorLockMtime).catch(()=>{});let d=g instanceof Error?g.message:String(g);return o.log.warn(`[dream] consolidation error: ${d}`),o.hooks?.invoke("subagent.stopped",{sessionId:o.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:d}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:d}}}var at=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,t){this.sessionId=e,this.extractionThresholds={initialTokenThreshold:t?.initialTokenThreshold??1e4,updateTokenThreshold:t?.updateTokenThreshold??5e3,toolCallThreshold:t?.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[t,n]of this._modelUsage)e[t]={...n};return e}addUsage(e,t,n=0){this._totalCostUSD+=n,this._totalInputTokens+=e.prompt,this._totalOutputTokens+=e.completion;let r=this._modelUsage.get(t);r?(r.inputTokens+=e.prompt,r.outputTokens+=e.completion,r.costUSD+=n):this._modelUsage.set(t,{inputTokens:e.prompt,outputTokens:e.completion,cacheRead:0,cacheCreation:0,costUSD:n}),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,t=this._tokensSinceLastExtraction>=e,n=this._toolCallsSinceLastExtraction>=this.extractionThresholds.toolCallThreshold;return t&&n}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[t,n]of Object.entries(e.modelUsage))this._modelUsage.set(t,{...n});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 le from"node:fs";import*as ye from"node:path";var Vs="transcript.jsonl",lt="state.json",Zu=50,Qu=50,ed=30;function Ks(){return ls()}function It(o){let e=o.replace(/[^a-zA-Z0-9_-]/g,"_");return ye.join(Ks(),e)}async function sn(o,e){let t=It(o);await le.promises.mkdir(t,{recursive:!0});let n=JSON.stringify({role:e.role,content:e.content,ts:Date.now()})+`
111
- `;await le.promises.appendFile(ye.join(t,Vs),n,"utf8")}async function Js(o,e,t){let n=It(o);await le.promises.mkdir(n,{recursive:!0});let r={metadata:{sessionId:o,createdAt:t.createdAt??Date.now(),lastActiveAt:Date.now(),model:t.model,cwd:t.cwd,turnCount:e.turnCount,messageCount:t.messageCount??0,title:t.title},costSnapshot:e},s=ye.join(n,lt+".tmp");await le.promises.writeFile(s,JSON.stringify(r,null,2),"utf8"),await le.promises.rename(s,ye.join(n,lt))}async function Ys(o){let e=It(o),t=ye.join(e,Vs),n=ye.join(e,lt),r=[];try{r=(await le.promises.readFile(t,"utf8")).split(`
112
- `).filter(Boolean).map(c=>{let u=JSON.parse(c);return{role:u.role,content:u.content??null}})}catch{return null}let s={sessionId:o,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:r.length},i;try{let l=await le.promises.readFile(n,"utf8"),c=JSON.parse(l);s=c.metadata,i=c.costSnapshot}catch{}let a=r.filter(l=>l.role!=="system");return{metadata:s,messages:a,costSnapshot:i}}async function Xs(o=Zu){let e=Ks(),t;try{t=await le.promises.readdir(e)}catch{return[]}let n=[];for(let r of t){let s=ye.join(e,r,lt);try{let i=await le.promises.readFile(s,"utf8"),a=JSON.parse(i);n.push({sessionId:a.metadata.sessionId,title:a.metadata.title,lastActiveAt:a.metadata.lastActiveAt,messageCount:a.metadata.messageCount,model:a.metadata.model})}catch{}}return n.sort((r,s)=>s.lastActiveAt-r.lastActiveAt),n.slice(0,o)}function td(o){return o.turnCount<Qu?!1:o.taskSummaryGeneratedAt?o.turnCount-(o.taskSummaryGeneratedAt??0)>=ed:!0}async function Zs(o,e,t,n){if(!td(e))return null;try{let s=t.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
113
- `),i=n.transport.stream({model:n.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},n.apiKey),a="";for await(let u of i)u.type==="delta"&&(a+=u.text);if(a=a.trim(),!a)return null;let l=It(o),c=ye.join(l,lt);try{let u=await le.promises.readFile(c,"utf8"),g=JSON.parse(u);g.metadata.taskSummary=a,g.metadata.taskSummaryGeneratedAt=e.turnCount;let d=c+".tmp";await le.promises.writeFile(d,JSON.stringify(g,null,2),"utf8"),await le.promises.rename(d,c)}catch{}return a}catch{return null}}Ko();import{randomUUID as Xy}from"node:crypto";var od=3e4;var Lt=class{tasks=new Map;listeners=new Set;hooks=null;sessionId="";setHooks(e,t){this.hooks=e,this.sessionId=t}onTaskChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,t){for(let n of this.listeners)try{n(e,t)}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,t){let n=this.tasks.get(e);if(!n)return;let r=t(n);r!==n&&(this.tasks.set(e,r),this.notify(e,r),!Ot(n.lifecycle)&&Ot(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 t=this.tasks.get(e);t&&Ot(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=od){let t=Date.now();for(let[n,r]of this.tasks)Ot(r.lifecycle)&&r.endedAt&&t-r.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function Ot(o){return o==="completed"||o==="failed"||o==="cancelled"||o==="timeout"}import{watch as nd}from"node:fs";import{stat as rd}from"node:fs/promises";import{join as Qs,relative as sd,resolve as id}from"node:path";var ad=[`${me}/settings.json`,"INSTRUCTIONS.md",`${me}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${me}/rules`],ld=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${me}/rules`],an=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 ad){let t=Qs(this.deps.projectRoot,e);this.watchPath(t,e)}this.deps.log?.(`file-watcher: watching ${this.watchers.size} paths`)}watchPath(e,t){if(!this.watchers.has(e))try{let n=nd(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(r,s)=>{let i=s?Qs(e,s):e;this.handleChange(i,r==="rename"?"created":"modified")});n.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,n)}catch{}}handleChange(e,t){let n=this.debounceTimers.get(e);n&&clearTimeout(n),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let r=t;try{await rd(e)}catch{r="deleted"}let s=sd(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(()=>{}),ld.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=id(e);if(t===this._cwd)return;let n=this._cwd;this._cwd=t,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:n,newCwd:t}).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 ei(o){let e=new an(o);return await e.start(),e}import{readFile as cd,readdir as ud,stat as dd}from"node:fs/promises";import{dirname as $t,extname as pd,isAbsolute as md,join as Be,parse as oi,resolve as ti}from"node:path";import{homedir as gd}from"node:os";var fd=5;var hd="INSTRUCTIONS.md",yd="INSTRUCTIONS.local.md",bd="INSTRUCTIONS.md",Td=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 kd(o){try{return await cd(o,"utf-8")}catch{return null}}function xd(o){return o.includes("<!--")?o.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):o}function vd(o){let e=o.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:o};let t=e[1],n=o.slice(e[0].length),r=t.match(/^paths:\s*(.+)$/m);if(!r)return{content:n};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:n,globs:a.length>0?a:void 0}}function wd(o,e){let t=new Set,n=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=o.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=n.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 c;if(a.startsWith("~/"))c=Be(gd(),a.slice(2));else if(md(a))c=a;else if(a.startsWith("./"))c=ti($t(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))c=ti($t(e),a);else continue;t.add(c)}return[...t]}async function Ue(o,e,t,n=0,r){let s=o.toLowerCase();if(t.has(s)||n>=fd)return[];let i=pd(o).toLowerCase();if(i&&!Td.has(i))return[];t.add(s);let a=await kd(o);if(!a?.trim())return[];let{content:l,globs:c}=vd(a),u=xd(l);if(!u.trim())return[];let g=[],d={path:o,type:e,content:u.trim()};r&&(d.parent=r),c&&(d.globs=c),g.push(d);let m=wd(l,o);for(let h of m){let f=await Ue(h,e,t,n+1,o);g.push(...f)}return g}async function ln(o,e,t,n,r=new Set){if(r.has(o))return[];r.add(o);let s=[];try{let i=await ud(o,{withFileTypes:!0});for(let a of i){let l=Be(o,a.name);if(a.isDirectory())s.push(...await ln(l,e,t,n,r));else if(a.isFile()&&a.name.endsWith(".md")){let c=await Ue(l,e,t);s.push(...c.filter(u=>n?!!u.globs:!u.globs))}}}catch{}return s}async function Sd(o){let e=o,t=oi(e).root;for(;e!==t;){try{let n=Be(e,".git"),r=await dd(n);if(r.isDirectory()||r.isFile())return e}catch{}e=$t(e)}return null}async function Cd(o,e){let t=[],n=new Set,r=ne(),s=Be(r,bd);t.push(...await Ue(s,"User",n));let i=ys();t.push(...await ln(i,"User",n,!1));let l=await Sd(o)??oi(o).root,c=[],u=o;for(;c.push(u),!(u===l&&u!==o);){let g=$t(u);if(g===u)break;u=g}for(let g of c.reverse())t.push(...await Ue(Be(g,hd),"Project",n)),t.push(...await Ue(Ts(g),"Project",n)),t.push(...await ln(ks(g),"Project",n,!1)),t.push(...await Ue(Be(g,yd),"Local",n));return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:o,fileCount:t.length}).catch(()=>{}),t}function ni(o){if(o.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.",t=[];for(let n of o){if(!n.content)continue;let r=n.type==="Project"?" (project instructions, checked into the codebase)":n.type==="Local"?" (user's private project instructions, not checked in)":" (user's private global instructions for all projects)";t.push(`Contents of ${n.path}${r}:
110
+ Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var ti=0;async function Ad(o,e={}){let t={...ri,...e},n;try{n=await ai(o.memoryRoot)}catch{n=0}let r=(Date.now()-n)/36e5;if(!t.force&&r<t.minHours)return null;let s=Date.now()-ti;if(!t.force&&s<t.scanIntervalMs)return null;ti=Date.now();let i;try{i=await o.listSessionsSince(n)}catch{return null}return i=i.filter(a=>a!==o.currentSessionId),!t.force&&i.length<t.minSessions?null:{sessionIds:i}}async function ai(o){let e=qt(o,Ht);return(await ni(e)).mtimeMs}function Ed(o){try{return process.kill(o,0),!0}catch{return!1}}async function Id(o){let e=qt(o,Ht),t,n;try{let[s,i]=await Promise.all([ni(e),Ys(e,"utf8")]);t=s.mtimeMs;let a=parseInt(i.trim(),10);n=Number.isFinite(a)?a:void 0}catch{}if(t!==void 0&&Date.now()-t<wd&&n!==void 0&&Ed(n))return null;await xd(o,{recursive:!0}),await kn(e,String(process.pid));let r;try{r=await Ys(e,"utf8")}catch{return null}return parseInt(r.trim(),10)!==process.pid?null:t??0}async function oi(o,e){let t=qt(o,Ht);try{if(e===0){await kd(t);return}await kn(t,"");let{utimes:n}=await import("node:fs/promises"),r=e/1e3;await n(t,r,r)}catch{}}async function Od(o){let e=qt(o,Ht);await kn(e,String(process.pid))}function Ld(o){return{taskId:`dream-${vd().slice(0,8)}`,type:"dream",label:"Memory consolidation",permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:1,maxTurns:0,tokenBudget:0,startedAt:Date.now(),parentTaskId:o.parentTaskId,sessionId:o.sessionId,phase:"starting",sessionsReviewing:o.sessionsReviewing,filesTouched:[],turns:[],priorLockMtime:o.priorLockMtime}}async function $d(o,e={}){let t={...ri,...e},n=await Ad(o,t);if(!n)return null;let r;if(t.force)try{r=await ai(o.memoryRoot)}catch{r=0}else if(r=await Id(o.memoryRoot),r===null)return null;let s=ii(o.memoryRoot,o.transcriptDir,n.sessionIds),i=Ld({sessionId:o.currentSessionId,sessionsReviewing:n.sessionIds.length,priorLockMtime:r});return{prompt:s,taskState:i,sessionIds:n.sessionIds}}async function li(o){let e=Date.now(),t=await $d(o.context,o.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:n,sessionIds:r}=t,s=!!(o.qmemoryAdapter&&o.qmemoryUserId),i=s?ii(o.context.memoryRoot,o.context.transcriptDir,r,{hasQMemory:!0}):t.prompt;o.log.info(`[dream] starting consolidation \u2014 ${r.length} sessions, memoryRoot=${o.context.memoryRoot}`+(s?", qmemory=enabled":"")),o.hooks?.invoke("subagent.started",{sessionId:o.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let a=(p,d)=>Pd(o.context.memoryRoot,{toolName:p,input:d}),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"]}}}]:[],c=s?{invoke:async(p,d,m,y)=>{let h=o.qmemoryAdapter,k=o.qmemoryUserId;if(d==="qmemory_search"){let{query:w,limit:f}=JSON.parse(m),C=await h.search(w,k,{limit:f??10});return{result:JSON.stringify(C)}}if(d==="qmemory_store"){if(!h.addText)return{result:"",error:"addText not supported"};let{text:w,source:f}=JSON.parse(m),C=await h.addText(w,k,{sessionId:o.context.currentSessionId,source:f??"dream-consolidation"});return{result:JSON.stringify(C)}}if(d==="qmemory_feedback"){let{memoryIds:w,signal:f}=JSON.parse(m);return h.feedback&&await h.feedback(w,f,o.context.currentSessionId),{result:"Feedback recorded successfully."}}return o.toolInvoker.invoke(p,d,m,y)}}:o.toolInvoker,u=[...o.tools,...l];try{let p=await Wt({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:i,tools:u,canUseTool:a,transport:o.transport,toolInvoker:c,apiKey:o.apiKey,model:o.model,log:o.log,hooks:o.hooks,forkLabel:"dream-consolidation",parentSignal:o.parentSignal,skipTranscript:!0}),d=[];for(let m of p.events)if(m.type==="tool_call")try{let y=JSON.parse(m.arguments),h=y.file_path??y.path??y.filePath;h&&si(h,o.context.memoryRoot)&&d.push(h)}catch{}return p.ok?(await Od(o.context.memoryRoot),o.log.info(`[dream] consolidation complete \u2014 ${d.length} files touched, ${p.durationMs}ms`)):(await oi(o.context.memoryRoot,n.priorLockMtime),o.log.warn(`[dream] consolidation failed: ${p.error}`)),o.hooks?.invoke("subagent.stopped",{sessionId:o.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:p.ok?"normal":"error",error:p.error}).catch(()=>{}),{ok:p.ok,sessionsReviewed:r.length,filesTouched:[...new Set(d)],turns:[],durationMs:Date.now()-e,error:p.error}}catch(p){await oi(o.context.memoryRoot,n.priorLockMtime).catch(()=>{});let d=p instanceof Error?p.message:String(p);return o.log.warn(`[dream] consolidation error: ${d}`),o.hooks?.invoke("subagent.stopped",{sessionId:o.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:d}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:d}}}var ht=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_tokensSinceLastExtraction=0;_toolCallsSinceLastExtraction=0;_hasExtractedOnce=!1;_listeners=new Set;extractionThresholds;constructor(e,t){this.sessionId=e,this.extractionThresholds={initialTokenThreshold:t?.initialTokenThreshold??1e4,updateTokenThreshold:t?.updateTokenThreshold??5e3,toolCallThreshold:t?.toolCallThreshold??3}}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}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[t,n]of this._modelUsage)e[t]={...n};return e}addUsage(e,t){this._totalInputTokens+=e.prompt,this._totalOutputTokens+=e.completion;let n=this._modelUsage.get(t);n?(n.inputTokens+=e.prompt,n.outputTokens+=e.completion,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheCreation??0):this._modelUsage.set(t,{inputTokens:e.prompt,outputTokens:e.completion,cacheRead:e.cacheRead??0,cacheCreation:e.cacheCreation??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this._tokensSinceLastExtraction+=e.prompt+e.completion,this.notifyListeners()}addMediaUsage(e,t,n){let r=this._modelUsage.get(e),s=r??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(r||this._modelUsage.set(e,s),s.mediaCalls+=1,t){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++,this._toolCallsSinceLastExtraction++}recordTurnCompleted(){this._turnCount++}shouldExtractMemory(){let e=this._hasExtractedOnce?this.extractionThresholds.updateTokenThreshold:this.extractionThresholds.initialTokenThreshold,t=this._tokensSinceLastExtraction>=e,n=this._toolCallsSinceLastExtraction>=this.extractionThresholds.toolCallThreshold;return t&&n}markExtractionDone(){this._tokensSinceLastExtraction=0,this._toolCallsSinceLastExtraction=0,this._hasExtractedOnce=!0}createSnapshot(){return{sessionId:this.sessionId,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._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[t,n]of Object.entries(e.modelUsage))this._modelUsage.set(t,{...n});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 pe from"node:fs";import*as be from"node:path";var ci="transcript.jsonl",yt="state.json",Dd=50,Nd=50,Ud=30;function ui(){return dn()}function Gt(o){let e=o.replace(/[^a-zA-Z0-9_-]/g,"_");return be.join(ui(),e)}async function xn(o,e){let t=Gt(o);await pe.promises.mkdir(t,{recursive:!0});let n=JSON.stringify({role:e.role,content:e.content,ts:Date.now()})+`
111
+ `;await pe.promises.appendFile(be.join(t,ci),n,"utf8")}async function di(o,e,t){let n=Gt(o);await pe.promises.mkdir(n,{recursive:!0});let r={metadata:{sessionId:o,createdAt:t.createdAt??Date.now(),lastActiveAt:Date.now(),model:t.model,cwd:t.cwd,turnCount:e.turnCount,messageCount:t.messageCount??0,title:t.title},costSnapshot:e},s=be.join(n,yt+".tmp");await pe.promises.writeFile(s,JSON.stringify(r,null,2),"utf8"),await pe.promises.rename(s,be.join(n,yt))}async function pi(o){let e=Gt(o),t=be.join(e,ci),n=be.join(e,yt),r=[];try{r=(await pe.promises.readFile(t,"utf8")).split(`
112
+ `).filter(Boolean).map(c=>{let u=JSON.parse(c);return{role:u.role,content:u.content??null}})}catch{return null}let s={sessionId:o,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:r.length},i;try{let l=await pe.promises.readFile(n,"utf8"),c=JSON.parse(l);s=c.metadata,i=c.costSnapshot}catch{}let a=r.filter(l=>l.role!=="system");return{metadata:s,messages:a,costSnapshot:i}}async function mi(o=Dd){let e=ui(),t;try{t=await pe.promises.readdir(e)}catch{return[]}let n=[];for(let r of t){let s=be.join(e,r,yt);try{let i=await pe.promises.readFile(s,"utf8"),a=JSON.parse(i);n.push({sessionId:a.metadata.sessionId,title:a.metadata.title,lastActiveAt:a.metadata.lastActiveAt,messageCount:a.metadata.messageCount,model:a.metadata.model})}catch{}}return n.sort((r,s)=>s.lastActiveAt-r.lastActiveAt),n.slice(0,o)}function jd(o){return o.turnCount<Nd?!1:o.taskSummaryGeneratedAt?o.turnCount-(o.taskSummaryGeneratedAt??0)>=Ud:!0}async function gi(o,e,t,n){if(!jd(e))return null;try{let s=t.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
113
+ `),i=n.transport.stream({model:n.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},n.apiKey),a="";for await(let u of i)u.type==="delta"&&(a+=u.text);if(a=a.trim(),!a)return null;let l=Gt(o),c=be.join(l,yt);try{let u=await pe.promises.readFile(c,"utf8"),p=JSON.parse(u);p.metadata.taskSummary=a,p.metadata.taskSummaryGeneratedAt=e.turnCount;let d=c+".tmp";await pe.promises.writeFile(d,JSON.stringify(p,null,2),"utf8"),await pe.promises.rename(d,c)}catch{}return a}catch{return null}}cn();import{randomUUID as nT}from"node:crypto";var Fd=3e4;var Vt=class{tasks=new Map;listeners=new Set;hooks=null;sessionId="";setHooks(e,t){this.hooks=e,this.sessionId=t}onTaskChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,t){for(let n of this.listeners)try{n(e,t)}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,t){let n=this.tasks.get(e);if(!n)return;let r=t(n);r!==n&&(this.tasks.set(e,r),this.notify(e,r),!zt(n.lifecycle)&&zt(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 t=this.tasks.get(e);t&&zt(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=Fd){let t=Date.now();for(let[n,r]of this.tasks)zt(r.lifecycle)&&r.endedAt&&t-r.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function zt(o){return o==="completed"||o==="failed"||o==="cancelled"||o==="timeout"}import{watch as Bd}from"node:fs";import{stat as Wd}from"node:fs/promises";import{join as fi,relative as qd,resolve as Hd}from"node:path";var Gd=[`${fe}/settings.json`,"INSTRUCTIONS.md",`${fe}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${fe}/rules`],zd=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${fe}/rules`],vn=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 Gd){let t=fi(this.deps.projectRoot,e);this.watchPath(t,e)}this.deps.log?.(`file-watcher: watching ${this.watchers.size} paths`)}watchPath(e,t){if(!this.watchers.has(e))try{let n=Bd(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(r,s)=>{let i=s?fi(e,s):e;this.handleChange(i,r==="rename"?"created":"modified")});n.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,n)}catch{}}handleChange(e,t){let n=this.debounceTimers.get(e);n&&clearTimeout(n),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let r=t;try{await Wd(e)}catch{r="deleted"}let s=qd(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(()=>{}),zd.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=Hd(e);if(t===this._cwd)return;let n=this._cwd;this._cwd=t,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:n,newCwd:t}).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 hi(o){let e=new vn(o);return await e.start(),e}import{readFile as Vd,readdir as Kd,stat as Jd}from"node:fs/promises";import{dirname as Kt,extname as Yd,isAbsolute as Xd,join as $e,parse as bi,resolve as yi}from"node:path";import{homedir as Qd}from"node:os";var Zd=5;var ep="INSTRUCTIONS.md",tp="INSTRUCTIONS.local.md",op="INSTRUCTIONS.md",np=[".instructions.md"],rp=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 sp(o){try{return await Vd(o,"utf-8")}catch{return null}}function ip(o){return o.includes("<!--")?o.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):o}function ap(o){let e=o.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:o};let t=e[1],n=o.slice(e[0].length),r=t.match(/^paths:\s*(.+)$/m);if(!r)return{content:n};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:n,globs:a.length>0?a:void 0}}function lp(o,e){let t=new Set,n=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=o.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=n.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 c;if(a.startsWith("~/"))c=$e(Qd(),a.slice(2));else if(Xd(a))c=a;else if(a.startsWith("./"))c=yi(Kt(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))c=yi(Kt(e),a);else continue;t.add(c)}return[...t]}async function Le(o,e,t,n=0,r){let s=o.toLowerCase();if(t.has(s)||n>=Zd)return[];let i=Yd(o).toLowerCase();if(i&&!rp.has(i))return[];t.add(s);let a=await sp(o);if(!a?.trim())return[];let{content:l,globs:c}=ap(a),u=ip(l);if(!u.trim())return[];let p=[],d={path:o,type:e,content:u.trim()};r&&(d.parent=r),c&&(d.globs=c),p.push(d);let m=lp(l,o);for(let y of m){let h=await Le(y,e,t,n+1,o);p.push(...h)}return p}async function wn(o,e,t,n,r=new Set){if(r.has(o))return[];r.add(o);let s=[];try{let i=await Kd(o,{withFileTypes:!0});for(let a of i){let l=$e(o,a.name);if(a.isDirectory())s.push(...await wn(l,e,t,n,r));else if(a.isFile()&&a.name.endsWith(".md")){let c=await Le(l,e,t);s.push(...c.filter(u=>n?!!u.globs:!u.globs))}}}catch{}return s}async function cp(o){let e=o,t=bi(e).root;for(;e!==t;){try{let n=$e(e,".git"),r=await Jd(n);if(r.isDirectory()||r.isFile())return e}catch{}e=Kt(e)}return null}async function up(o,e){let t=[],n=new Set,r=H(),s=$e(r,op);t.push(...await Le(s,"User",n));let i=As();t.push(...await wn(i,"User",n,!1));let l=await cp(o)??bi(o).root,c=[],u=o;for(;c.push(u),!(u===l&&u!==o);){let p=Kt(u);if(p===u)break;u=p}for(let p of c.reverse()){t.push(...await Le($e(p,ep),"Project",n));for(let d of np)t.push(...await Le($e(p,d),"Project",n));t.push(...await Le(Is(p),"Project",n)),t.push(...await wn(Os(p),"Project",n,!1)),t.push(...await Le($e(p,tp),"Local",n))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:o,fileCount:t.length}).catch(()=>{}),t}function Ti(o){if(o.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.",t=[];for(let n of o){if(!n.content)continue;let r=n.type==="Project"?" (project instructions, checked into the codebase)":n.type==="Local"?" (user's private project instructions, not checked in)":" (user's private global instructions for all projects)";t.push(`Contents of ${n.path}${r}:
114
114
 
115
115
  ${n.content.trim()}`)}return t.length>0?`${e}
116
116
 
117
117
  ${t.join(`
118
118
 
119
- `)}`:""}var ct=null,cn=null;async function ri(o,e){return ct&&cn===o||(ct=await Cd(o,e),cn=o),ct}function si(){ct=null,cn=null}function ii(o,e){return{name:o,compute:e,cacheBreak:!1}}var Dt=new Map;async function _d(o){return(await Promise.all(o.map(async t=>{if(!t.cacheBreak&&Dt.has(t.name))return Dt.get(t.name)??null;let n=await t.compute();return Dt.set(t.name,n),n}))).filter(t=>t!=null)}function ai(){Dt.clear()}async function li(o){let e=[];if(o.instructionBlock&&e.push(o.instructionBlock),o.customSystemPrompt?e.push(o.customSystemPrompt):o.basePrompt&&e.push(o.basePrompt),o.sections?.length){let t=await _d(o.sections);e.push(...t)}return o.appendSystemPrompt&&e.push(o.appendSystemPrompt),e.filter(Boolean).join(`
119
+ `)}`:""}var bt=null,Sn=null;async function ki(o,e){return bt&&Sn===o||(bt=await up(o,e),Sn=o),bt}function xi(){bt=null,Sn=null}function vi(o,e){return{name:o,compute:e,cacheBreak:!1}}var Jt=new Map;async function dp(o){return(await Promise.all(o.map(async t=>{if(!t.cacheBreak&&Jt.has(t.name))return Jt.get(t.name)??null;let n=await t.compute();return Jt.set(t.name,n),n}))).filter(t=>t!=null)}function wi(){Jt.clear()}async function Si(o){let e=[];if(o.instructionBlock&&e.push(o.instructionBlock),o.customSystemPrompt?e.push(o.customSystemPrompt):o.basePrompt&&e.push(o.basePrompt),o.sections?.length){let t=await dp(o.sections);e.push(...t)}return o.appendSystemPrompt&&e.push(o.appendSystemPrompt),e.filter(Boolean).join(`
120
120
 
121
- `)}import{release as Rd,homedir as Md}from"node:os";import{resolve as Pd}from"node:path";function Ad(){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 Ed(){let o=process.platform,e=Rd();return o==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():o==="darwin"?"macOS":o==="linux"?"Linux":o}function ci(){return ii("environment_context",()=>{let o=Ad(),e=Ed(),t=process.cwd(),n=process.version,r=Md(),s=["# Environment","",`- Platform: ${e}`,`- Shell: ${o}`,`- Working directory: ${Pd(t)}`,`- Home directory: ${r}`,`- Node.js: ${n}`];return o==="powershell"?s.push("- Note: Use PowerShell syntax (semicolons, not &&; use $env: for env vars)"):o==="cmd"&&s.push("- Note: Use CMD syntax (%VAR%, not $VAR)"),s.join(`
122
- `)})}import*as A from"node:fs";import*as j from"node:path";import{execFile as Nm}from"node:child_process";var un=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),ui=new Set([...un,"agent"]);function dn(o,e){let t=e?un:ui;return o.filter(n=>n.function.name.startsWith("mcp__")?!0:!t.has(n.function.name))}var xe=new Map;function di(o){xe.clear();for(let e of o)xe.set(e.name,e)}function X(o){xe.set(o.name,o)}function pn(o){for(let e of o)xe.set(e.name,e)}function Nt(o){return xe.delete(o)}function Ee(o){return xe.get(o)}function ve(){return Array.from(xe.keys())}function Ie(o=!1){let e=[];for(let t of xe.values())t.isEnabled?.()!==!1&&(!o&&t.shouldDefer||e.push({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters},meta:{parallelSafe:t.isConcurrencySafe??!1,isReadOnly:t.isReadOnly??!1,isDangerous:!(t.isReadOnly??!1)&&!(t.isConcurrencySafe??!1)}}));return e}var Id="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(`
123
- `)}},required:["thought"]};function pi(){return{name:Id,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(`
124
- `),parameters:Od,execute:async(o,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function mi(o){let e=new Set(o.filter(t=>t.status==="completed").map(t=>t.id));return{total:o.length,completed:o.filter(t=>t.status==="completed").length,inProgress:o.filter(t=>t.status==="in-progress").length,notStarted:o.filter(t=>t.status==="not-started").length,blocked:o.filter(t=>t.status!=="completed"&&t.blockedBy?.some(n=>!e.has(n))).length}}var Ld="todo",$d=["create","update","delete","list"],Dd={type:"object",properties:{action:{type:"string",enum:[...$d],description:"create \u2014 add a single new task (auto-assigns id). update \u2014 modify a single task by id (partial). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list."},id:{type:"number",description:"[update|delete] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task."}},required:["action"]};function gi(o){let e=[],t=0,n=o??{};function r(){let d=e.reduce((m,h)=>Math.max(m,h.id),0);return t=Math.max(t,d)+1,t}function s(d){return{content:[{type:"text",text:JSON.stringify({error:d,todoList:e})}],details:{type:"todo",error:d}}}function i(d){let m=mi(e),h=new Set(e.filter(y=>y.status==="completed").map(y=>y.id)),f=e.map(y=>{let v=y.blockedBy?.filter(_=>!h.has(_));return{...y,...v?.length?{blockedBy:v}:{blockedBy:void 0}}}),T={...m,todoList:f,...d};return{content:[{type:"text",text:JSON.stringify(T)}],details:{type:"todo",...m,agentId:n.agentId}}}function a(d,m,h){let f=e.find(T=>T.id===d);if(f){if(m?.length){f.blocks=[...new Set([...f.blocks??[],...m])];for(let T of m){let y=e.find(v=>v.id===T);y&&(y.blockedBy=[...new Set([...y.blockedBy??[],d])])}}if(h?.length){f.blockedBy=[...new Set([...f.blockedBy??[],...h])];for(let T of h){let y=e.find(v=>v.id===T);y&&(y.blocks=[...new Set([...y.blocks??[],d])])}}}}function l(d){for(let m of e)m.blocks&&(m.blocks=m.blocks.filter(h=>h!==d)),m.blockedBy&&(m.blockedBy=m.blockedBy.filter(h=>h!==d))}function c(d){if(!d.title)return s("title is required for create action.");let m={id:r(),title:d.title,status:"not-started",...d.description!=null&&{description:d.description},...d.owner!=null&&{owner:d.owner}};return e.push(m),a(m.id,void 0,d.addBlockedBy),i({created:{id:m.id,title:m.title}})}function u(d){if(d.id==null)return s("id is required for update action.");let m=e.find(h=>h.id===d.id);if(!m)return s(`Task #${d.id} not found.`);if(d.status==="in-progress"){let h=e.find(f=>f.status==="in-progress"&&f.id!==d.id);if(h)return s(`Cannot set #${d.id} to in-progress: #${h.id} already is.`)}return d.title!=null&&(m.title=d.title),d.description!=null&&(m.description=d.description),d.owner!=null&&(m.owner=d.owner),d.status!=null&&(m.status=d.status),a(m.id,d.addBlocks,d.addBlockedBy),i({updated:{id:m.id,title:m.title}})}function g(d){if(d.id==null)return s("id is required for delete action.");let m=e.findIndex(h=>h.id===d.id);return m===-1?s(`Task #${d.id} not found.`):(t=Math.max(t,d.id),e.splice(m,1),l(d.id),i({deleted:d.id}))}return{name:Ld,label:"Todo",description:"Manage a structured todo list to track multi-step task progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all). Supports dependency tracking (blocks/blockedBy). Use frequently during complex work to plan steps and show progress.",parameters:Dd,searchHint:"manage session task checklist progress tracking dependencies",maxResultSizeChars:1e5,execute:async(d,m)=>{let h=m.action;switch(h){case"create":return c(m);case"update":return u(m);case"delete":return g(m);case"list":return i();default:return s(`Unknown action: ${h}. Valid: create, update, delete, list.`)}}}}var fi=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),hi=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),yi=new Set(["ls","tree","du"]);var bi=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Nd(o){let t=o.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!t)return null;let n=t.split(/\s+/),r=0;for(;r<n.length&&/^[A-Za-z_]\w*=/.test(n[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<n.length;){let l=n[r];if(s.test(l)){for(r++;r<n.length&&/^[-+]/.test(n[r]);)r++;r<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[r])&&r++;continue}break}if(r>=n.length)return null;let i=n[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Ti(o){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(o)}function mn(o){let e=Nd(o),t=e!==null&&fi.has(e),n=e!==null&&hi.has(e),r=e!==null&&yi.has(e),s=e!==null&&bi.has(e),i=/(?:[^2]>|^>|\|>)/.test(o),a=Ti(o),l=(t||n||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}function gn(o){return/(?:^|[;&|])\s*sleep\s+\d/i.test(o)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(o)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as Vd}from"node:child_process";import{constants as Bt,readFileSync as Kd,unlinkSync as Jd}from"node:fs";import{mkdir as Yd,open as Xd,realpath as wi}from"node:fs/promises";import{isAbsolute as Zd,resolve as Qd}from"node:path";function jt(){if(process.platform!=="win32")return!1;let o=process.env.QLOGICAGENT_USE_POWERSHELL;return o==="1"||o==="true"}function fn(){return jt()?"powershell":"bash"}function hn(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as jd,readFile as Fd,writeFile as Ud,unlink as Bd}from"node:fs/promises";import{join as ki}from"node:path";import{tmpdir as qd}from"node:os";var Wd=8*1024*1024,Hd=5*1024*1024*1024;var yn;function ut(){if(!yn){let o=Math.random().toString(36).slice(2,10);yn=ki(qd(),"qla-tasks",o)}return yn}function xi(o){return ki(ut(),`${o}.output`)}function be(o="local_bash"){return`${o}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var we=class{taskId;path;stdoutToFile;#e="";#o="";#r=0;#s=0;#t;#i;#n=0;#a=!1;constructor(e,t,n=!1,r=Wd){this.taskId=e,this.path=xi(e),this.stdoutToFile=n,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=Gd(e),this.#u()}writeStderr(e){this.#o+=e}async getStdout(){if(this.stdoutToFile)try{let e=await Fd(this.path,"utf-8");return this.#n=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#o}get outputFileSize(){return this.#n}get outputFileRedundant(){return this.#n<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&jd(ut(),{recursive:!0}).then(()=>Ud(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await Bd(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#o="",this.#i=null,this.deleteOutputFile())}};function Gd(o){let e=0;for(let t=0;t<o.length;t++)o.charCodeAt(t)===10&&e++;return e}var bn=137,vi=143,zd=5e3,Tn=5*1024*1024*1024,Ft=class{#e;#o;#r;#s=!1;constructor(e,t,n){this.#e=e,this.#o=t,this.#r=n,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let t=typeof e=="string"?e:e.toString();this.#r?this.#o.writeStderr(t):this.#o.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#o=null)}},kn=class o{#e="running";#o;#r;#s;#t;#i=null;#n=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,n,r,s=!1,i=Tn){this.#t=e,this.#l=t,this.#g=n,this.#b=s,this.#u=i,this.taskOutput=r,this.#s=e.stderr?new Ft(e.stderr,r,!0):null,this.#r=e.stdout?new Ft(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#C()}get status(){return this.#e}static#k(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(vi)}#x(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#w(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#T(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#T(){this.#n&&(clearInterval(this.#n),this.#n=null)}#S(){this.#n=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#u&&this.#e==="backgrounded"&&this.#n!==null&&(this.#a=!0,this.#T(),this.#y(bn))},()=>{}))},zd),this.#n.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.#w.bind(this)),this.#i=setTimeout(o.#k,this.#g,this);let e=new Promise(t=>{this.#m=t});return new Promise(t=>{this.#p=t,e.then(this.#_.bind(this))})}async#_(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let t=await this.taskOutput.getStdout(),n={code:e,stdout:t,stderr:this.taskOutput.getStderr(),interrupted:e===bn,backgroundTaskId:this.#o};this.taskOutput.stdoutToFile&&!this.#o&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(n.outputFilePath=this.taskOutput.path,n.outputFileSize=this.taskOutput.outputFileSize)),this.#a?n.stderr=`Background command killed: output file exceeded ${Tn} bytes. ${n.stderr}`:e===vi&&(n.stderr=`Command timed out after ${this.#g}ms. ${n.stderr}`),this.#p&&(this.#p(n),this.#p=null)}#y(e){this.#e="killed";let t=this.#t.pid;if(t)try{if(process.platform==="win32")import("node:child_process").then(({execSync:n})=>{try{n(`taskkill /PID ${t} /T /F`,{stdio:"ignore"})}catch{}});else try{process.kill(-t,"SIGKILL")}catch{try{process.kill(t,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#f(e??bn)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#o=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#S():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 xn(o,e,t,n,r=!1,s=Tn){return new kn(o,e,t,n,r,s)}function Ut(o,e){let t=new we(be("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:o}),taskOutput:t,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function vn(o){let e=new we(be("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:o,interrupted:!1,preSpawnError:o}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var ep=1800*1e3,qt=process.cwd(),Si=process.cwd();function Ci(){return qt}function wn(o,e){qt=Zd(o)?o:Qd(e||qt,o)}function _i(){return Si}function Wt(o){qt=o,Si=o}var Sn=null;function dt(o){Sn={provider:o}}function Ri(){if(!Sn)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return Sn.provider}async function Ht(o,e,t,n){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l}=n??{},c=r||ep,u=t??fn(),g=Ri(),d=hn(),{commandString:m,cwdFilePath:h}=await g.buildExecCommand(o,{id:d,useSandbox:!1}),f=m,T=Ci();try{await wi(T)}catch{let O=_i();try{await wi(O),wn(O),T=O}catch{return vn(`Working directory "${T}" no longer exists.`)}}if(e.aborted)return Ut();let y=g.shellPath,v=g.getSpawnArgs(f),_=await g.getEnvironmentOverrides(o),M=!!l,$=be("local_bash"),q=new we($,s??null,!M);await Yd(ut(),{recursive:!0});let E;if(!M){let O=Bt.O_NOFOLLOW??0;E=await Xd(q.path,process.platform==="win32"?"w":Bt.O_WRONLY|Bt.O_CREAT|Bt.O_APPEND|O)}try{let O=Vd(y,v,{env:{...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",..._},cwd:T,stdio:M?["pipe","pipe","pipe"]:["pipe",E?.fd,E?.fd],detached:g.detached,windowsHide:!0}),k=xn(O,e,c,q,a);if(E!==void 0)try{await E.close()}catch{}return O.stdout&&l&&O.stdout.on("data",D=>{l(typeof D=="string"?D:D.toString())}),h&&k.result.then(D=>{if(D&&!i&&!D.backgroundTaskId){try{let K=Kd(h,{encoding:"utf8"}).trim();K&&K.normalize("NFC")!==T&&wn(K,T)}catch{}try{Jd(h)}catch{}}}),k}catch(O){if(E!==void 0)try{await E.close()}catch{}return q.clear(),Ut(void 0,{code:126,stderr:O instanceof Error?O.message:String(O)})}}var tp="exec",op={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"]},np=12e4,rp=6e5,Gt=3e4;function Cn(o,e){if(o.length<=e)return o;let t=Math.floor(e/2)-50;return`${o.slice(0,t)}
121
+ `)}import{release as pp,homedir as mp}from"node:os";import{resolve as gp}from"node:path";function fp(){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 hp(){let o=process.platform,e=pp();return o==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():o==="darwin"?"macOS":o==="linux"?"Linux":o}function Ci(o){return vi("environment_context",()=>{let e=fp(),t=hp(),n=o??process.cwd(),r=process.version,s=mp(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${gp(n)}`,`- Home directory: ${s}`,`- Node.js: ${r}`];return e==="powershell"?i.push("- Note: Use PowerShell syntax (semicolons, not &&; use $env: for env vars)"):e==="cmd"&&i.push("- Note: Use CMD syntax (%VAR%, not $VAR)"),i.join(`
122
+ `)})}import*as I from"node:fs";import*as U from"node:path";import{execFile as Sg}from"node:child_process";var Cn=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),_i=new Set([...Cn,"agent"]);function _n(o,e){let t=e?Cn:_i;return o.filter(n=>n.function.name.startsWith("mcp__")?!0:!t.has(n.function.name))}var ve=new Map;function Ri(o){ve.clear();for(let e of o)ve.set(e.name,e)}function ne(o){ve.set(o.name,o)}function Rn(o){for(let e of o)ve.set(e.name,e)}function Yt(o){return ve.delete(o)}function we(o){return ve.get(o)}function Se(){return Array.from(ve.keys())}function Ce(o=!1){let e=[];for(let t of ve.values())t.isEnabled?.()!==!1&&(!o&&t.shouldDefer||e.push({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters},meta:{parallelSafe:t.isConcurrencySafe??!1,isReadOnly:t.isReadOnly??!1,isDangerous:!(t.isReadOnly??!1)&&!(t.isConcurrencySafe??!1)}}));return e}var yp="think",bp={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(`
123
+ `)}},required:["thought"]};function Mi(){return{name:yp,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(`
124
+ `),parameters:bp,execute:async(o,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function ze(o){let e=new Set(o.filter(t=>t.status==="completed").map(t=>t.id));return{total:o.length,completed:o.filter(t=>t.status==="completed").length,inProgress:o.filter(t=>t.status==="in-progress").length,notStarted:o.filter(t=>t.status==="not-started").length,blocked:o.filter(t=>t.status!=="completed"&&t.blockedBy?.some(n=>!e.has(n))).length}}var Tp="todo",kp=["create","update","delete","list"],xp={type:"object",properties:{action:{type:"string",enum:[...kp],description:"create \u2014 add a single new task (auto-assigns id). update \u2014 modify a single task by id (partial). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list."},id:{type:"number",description:"[update|delete] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task."}},required:["action"]};function Pi(o){let e=[],t=0,n=o??{};function r(){let d=e.reduce((m,y)=>Math.max(m,y.id),0);return t=Math.max(t,d)+1,t}function s(d){return{content:[{type:"text",text:JSON.stringify({error:d,todoList:e})}],details:{type:"todo",error:d}}}function i(d){let m=ze(e),y=new Set(e.filter(w=>w.status==="completed").map(w=>w.id)),h=e.map(w=>{let f=w.blockedBy?.filter(C=>!y.has(C));return{...w,...f?.length?{blockedBy:f}:{blockedBy:void 0}}}),k={...m,todoList:h,...d};return{content:[{type:"text",text:JSON.stringify(k)}],details:{type:"todo",...m,agentId:n.agentId}}}function a(d,m,y){let h=e.find(k=>k.id===d);if(h){if(m?.length){h.blocks=[...new Set([...h.blocks??[],...m])];for(let k of m){let w=e.find(f=>f.id===k);w&&(w.blockedBy=[...new Set([...w.blockedBy??[],d])])}}if(y?.length){h.blockedBy=[...new Set([...h.blockedBy??[],...y])];for(let k of y){let w=e.find(f=>f.id===k);w&&(w.blocks=[...new Set([...w.blocks??[],d])])}}}}function l(d){for(let m of e)m.blocks&&(m.blocks=m.blocks.filter(y=>y!==d)),m.blockedBy&&(m.blockedBy=m.blockedBy.filter(y=>y!==d))}function c(d){if(!d.title)return s("title is required for create action.");let m={id:r(),title:d.title,status:"not-started",...d.description!=null&&{description:d.description},...d.owner!=null&&{owner:d.owner}};return e.push(m),a(m.id,void 0,d.addBlockedBy),i({created:{id:m.id,title:m.title}})}function u(d){if(d.id==null)return s("id is required for update action.");let m=e.find(y=>y.id===d.id);if(!m)return s(`Task #${d.id} not found.`);if(d.status==="in-progress"){let y=e.find(h=>h.status==="in-progress"&&h.id!==d.id);if(y)return s(`Cannot set #${d.id} to in-progress: #${y.id} already is.`)}return d.title!=null&&(m.title=d.title),d.description!=null&&(m.description=d.description),d.owner!=null&&(m.owner=d.owner),d.status!=null&&(m.status=d.status),a(m.id,d.addBlocks,d.addBlockedBy),i({updated:{id:m.id,title:m.title}})}function p(d){if(d.id==null)return s("id is required for delete action.");let m=e.findIndex(y=>y.id===d.id);return m===-1?s(`Task #${d.id} not found.`):(t=Math.max(t,d.id),e.splice(m,1),l(d.id),i({deleted:d.id}))}return{name:Tp,label:"Todo",description:"Manage a structured todo list to track multi-step task progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all). Supports dependency tracking (blocks/blockedBy). Use frequently during complex work to plan steps and show progress.",parameters:xp,searchHint:"manage session task checklist progress tracking dependencies",maxResultSizeChars:1e5,execute:async(d,m)=>{let y=m.action;switch(y){case"create":return c(m);case"update":return u(m);case"delete":return p(m);case"list":return i();default:return s(`Unknown action: ${y}. Valid: create, update, delete, list.`)}}}}import{isAbsolute as Fp,resolve as Bp}from"node:path";var Ai=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Ei=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Ii=new Set(["ls","tree","du"]);var Oi=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function vp(o){let t=o.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!t)return null;let n=t.split(/\s+/),r=0;for(;r<n.length&&/^[A-Za-z_]\w*=/.test(n[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<n.length;){let l=n[r];if(s.test(l)){for(r++;r<n.length&&/^[-+]/.test(n[r]);)r++;r<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[r])&&r++;continue}break}if(r>=n.length)return null;let i=n[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Li(o){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(o)}function Mn(o){let e=vp(o),t=e!==null&&Ai.has(e),n=e!==null&&Ei.has(e),r=e!==null&&Ii.has(e),s=e!==null&&Oi.has(e),i=/(?:[^2]>|^>|\|>)/.test(o),a=Li(o),l=(t||n||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}function Pn(o){return/(?:^|[;&|])\s*sleep\s+\d/i.test(o)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(o)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as Ip}from"node:child_process";import{constants as eo,readFileSync as Op,unlinkSync as Lp}from"node:fs";import{mkdir as $p,open as Dp,realpath as Ui}from"node:fs/promises";import{isAbsolute as Np,resolve as Up}from"node:path";function Xt(){if(process.platform!=="win32")return!1;let o=process.env.QLOGICAGENT_USE_POWERSHELL;return o==="1"||o==="true"}function An(){return Xt()?"powershell":"bash"}function En(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as wp,readFile as Sp,writeFile as Cp,unlink as _p}from"node:fs/promises";import{join as $i}from"node:path";import{tmpdir as Rp}from"node:os";var Mp=8*1024*1024,Pp=5*1024*1024*1024;var In;function Tt(){if(!In){let o=Math.random().toString(36).slice(2,10);In=$i(Rp(),"qla-tasks",o)}return In}function Di(o){return $i(Tt(),`${o}.output`)}function Te(o="local_bash"){return`${o}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var _e=class{taskId;path;stdoutToFile;#e="";#o="";#r=0;#s=0;#t;#i;#n=0;#a=!1;constructor(e,t,n=!1,r=Mp){this.taskId=e,this.path=Di(e),this.stdoutToFile=n,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=Ap(e),this.#u()}writeStderr(e){this.#o+=e}async getStdout(){if(this.stdoutToFile)try{let e=await Sp(this.path,"utf-8");return this.#n=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#o}get outputFileSize(){return this.#n}get outputFileRedundant(){return this.#n<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&wp(Tt(),{recursive:!0}).then(()=>Cp(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await _p(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#o="",this.#i=null,this.deleteOutputFile())}};function Ap(o){let e=0;for(let t=0;t<o.length;t++)o.charCodeAt(t)===10&&e++;return e}var On=137,Ni=143,Ep=5e3,Ln=5*1024*1024*1024,Qt=class{#e;#o;#r;#s=!1;constructor(e,t,n){this.#e=e,this.#o=t,this.#r=n,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let t=typeof e=="string"?e:e.toString();this.#r?this.#o.writeStderr(t):this.#o.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#o=null)}},$n=class o{#e="running";#o;#r;#s;#t;#i=null;#n=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,n,r,s=!1,i=Ln){this.#t=e,this.#l=t,this.#g=n,this.#b=s,this.#u=i,this.taskOutput=r,this.#s=e.stderr?new Qt(e.stderr,r,!0):null,this.#r=e.stdout?new Qt(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#C()}get status(){return this.#e}static#k(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(Ni)}#x(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#w(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#T(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#T(){this.#n&&(clearInterval(this.#n),this.#n=null)}#S(){this.#n=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#u&&this.#e==="backgrounded"&&this.#n!==null&&(this.#a=!0,this.#T(),this.#y(On))},()=>{}))},Ep),this.#n.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.#w.bind(this)),this.#i=setTimeout(o.#k,this.#g,this);let e=new Promise(t=>{this.#m=t});return new Promise(t=>{this.#p=t,e.then(this.#_.bind(this))})}async#_(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let t=await this.taskOutput.getStdout(),n={code:e,stdout:t,stderr:this.taskOutput.getStderr(),interrupted:e===On,backgroundTaskId:this.#o};this.taskOutput.stdoutToFile&&!this.#o&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(n.outputFilePath=this.taskOutput.path,n.outputFileSize=this.taskOutput.outputFileSize)),this.#a?n.stderr=`Background command killed: output file exceeded ${Ln} bytes. ${n.stderr}`:e===Ni&&(n.stderr=`Command timed out after ${this.#g}ms. ${n.stderr}`),this.#p&&(this.#p(n),this.#p=null)}#y(e){this.#e="killed";let t=this.#t.pid;if(t)try{if(process.platform==="win32")import("node:child_process").then(({execSync:n})=>{try{n(`taskkill /PID ${t} /T /F`,{stdio:"ignore"})}catch{}});else try{process.kill(-t,"SIGKILL")}catch{try{process.kill(t,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#f(e??On)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#o=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#S():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 Dn(o,e,t,n,r=!1,s=Ln){return new $n(o,e,t,n,r,s)}function Zt(o,e){let t=new _e(Te("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:o}),taskOutput:t,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function Nn(o){let e=new _e(Te("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:o,interrupted:!1,preSpawnError:o}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var jp=1800*1e3,to=process.cwd(),ji=process.cwd();function oo(){return to}function Un(o,e){to=Np(o)?o:Up(e||to,o)}function Fi(){return ji}function no(o){to=o,ji=o}var jn=null;function kt(o){jn={provider:o}}function Bi(){if(!jn)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return jn.provider}async function ro(o,e,t,n){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:c}=n??{},u=r||jp,p=t??An(),d=Bi(),m=En(),{commandString:y,cwdFilePath:h}=await d.buildExecCommand(o,{id:m,useSandbox:!1}),k=y,w=c??oo();try{await Ui(w)}catch{let T=Fi();try{await Ui(T),Un(T),w=T}catch{return Nn(`Working directory "${w}" no longer exists.`)}}if(e.aborted)return Zt();let f=d.shellPath,C=d.getSpawnArgs(k),R=await d.getEnvironmentOverrides(o),L=!!l,K=Te("local_bash"),D=new _e(K,s??null,!L);await $p(Tt(),{recursive:!0});let F;if(!L){let T=eo.O_NOFOLLOW??0;F=await Dp(D.path,process.platform==="win32"?"w":eo.O_WRONLY|eo.O_CREAT|eo.O_APPEND|T)}try{let T=Ip(f,C,{env:{...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...R},cwd:w,stdio:L?["pipe","pipe","pipe"]:["pipe",F?.fd,F?.fd],detached:d.detached,windowsHide:!0}),B=Dn(T,e,u,D,a);if(F!==void 0)try{await F.close()}catch{}return T.stdout&&l&&T.stdout.on("data",J=>{l(typeof J=="string"?J:J.toString())}),h&&B.result.then(J=>{if(J&&!i&&!J.backgroundTaskId){try{let Q=Op(h,{encoding:"utf8"}).trim();Q&&Q.normalize("NFC")!==w&&Un(Q,w)}catch{}try{Lp(h)}catch{}}}),B}catch(T){if(F!==void 0)try{await F.close()}catch{}return D.clear(),Zt(void 0,{code:126,stderr:T instanceof Error?T.message:String(T)})}}var Wp="exec",qp={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"]},Hp=12e4,Gp=6e5,so=3e4;function Fn(o,e){if(o.length<=e)return o;let t=Math.floor(e/2)-50;return`${o.slice(0,t)}
125
125
 
126
126
  ... [truncated ${o.length-e} chars] ...
127
127
 
128
- ${o.slice(-t)}`}function sp(o){return o==null||o<=0?np:Math.min(o,rp)}async function*ip(o){let{command:e,abortController:t,timeout:n,shouldAutoBackground:r}=o,s="",i=0,a=0,l=Date.now(),c=null;function u(){return new Promise(m=>{c=()=>m(null)})}let g=await Ht(e,t.signal,void 0,{timeout:n,onProgress(m,h,f,T,y){s=h,i=f,a=T,c&&(c(),c=null)},shouldAutoBackground:r});for(g.onTimeout&&r&&g.onTimeout(m=>{let h=be("bg");m(h)});g.status==="running"&&await Promise.race([u(),g.result])===null;)yield{type:"exec_progress",output:s.slice(-4096),fullOutput:s,elapsedTimeSeconds:(Date.now()-l)/1e3,totalLines:i,totalBytes:a};let d=await g.result;return g.cleanup(),d}function Mi(o={}){return{name:tp,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:op,maxResultSizeChars:Gt,execute:async(e,t)=>{let n=mn(t.command);if(!t.background){let g=gn(t.command);if(g)return{content:[{type:"text",text:`Command blocked: ${g}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:n}}}if(o.validateCommand){let g=await o.validateCommand(t.command);if(g)return{content:[{type:"text",text:`Command blocked: ${g}`}],details:{type:"exec",error:"blocked_by_guard",reason:g,classification:n}}}let r=new AbortController,s=sp(t.timeout);if(t.background){let g=await Ht(t.command,r.signal,void 0,{shouldAutoBackground:!1}),d=be("bg");if(g.background(d))return{content:[{type:"text",text:`Background task started (id: ${d}).
129
- Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:d,description:t.description,classification:n}}}let i=ip({command:t.command,abortController:r,timeout:s,shouldAutoBackground:!0}),a;do a=await i.next(),!a.done&&o.onProgress&&o.onProgress(a.value);while(!a.done);let l=a.value,c=[];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:n}};l.outputFilePath?(c.push(Cn(l.stdout,Gt)),c.push(`[full output: ${l.outputFilePath} (${l.outputFileSize} bytes)]`)):l.stdout&&c.push(Cn(l.stdout,Gt)),l.stderr&&c.push(`[stderr]
130
- ${Cn(l.stderr,Math.floor(Gt/4))}`),l.interrupted&&c.push(`[interrupted \u2014 exit code ${l.code}]`);let u;return l.code!==0&&o.interpretExitCode&&(u=o.interpretExitCode(l.code,l.stderr),u&&c.push(`[exit ${l.code}: ${u}]`)),c.length===0&&c.push(n.isSilent&&l.code===0?"Done":`(exit code ${l.code}, no output)`),{content:[{type:"text",text:c.join(`
131
- `)}],details:{type:"exec",exitCode:l.code,interrupted:l.interrupted,description:t.description,returnCodeInterpretation:u,noOutputExpected:n.isSilent,outputFilePath:l.outputFilePath,classification:n}}}}}import{tmpdir as ap}from"node:os";import{join as lp,posix as _n}from"node:path";function cp(o){return o.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function up(o){return!(/(?:^|[;&|])\s*<\s/.test(o)||/<<[-]?\s*['"]?[A-Za-z_]/.test(o))}function dp(o,e){return`$'${o.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Pi(o){return process.platform!=="win32"?o:o.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function zt(o,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:o,detached:!0,async buildExecCommand(n,r){let s=process.platform==="win32",i=ap(),a=s?Pi(i):i,l=r.useSandbox&&r.sandboxTmpDir?_n.join(r.sandboxTmpDir,`cwd-${r.id}`):_n.join(a,`qla-${r.id}-cwd`),c=r.useSandbox&&r.sandboxTmpDir?_n.join(r.sandboxTmpDir,`cwd-${r.id}`):lp(i,`qla-${r.id}-cwd`),u=cp(n),g=up(u),d=dp(u,g),m=[];if(t){let f=s?Pi(t):t;m.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${d}`),m.push(`pwd -P >| '${l}'`),{commandString:m.join(" && "),cwdFilePath:c}},getSpawnArgs(n){return["-c",...!!t?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as pp}from"node:os";import{join as mp,posix as gp}from"node:path";function Ai(o){return Buffer.from(o,"utf16le").toString("base64")}function fp(o){return["-NoProfile","-NonInteractive","-Command",o]}function Rn(o){return{type:"powershell",shellPath:o,detached:!1,async buildExecCommand(e,t){let n=t.useSandbox&&t.sandboxTmpDir?gp.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):mp(pp(),`qla-pwd-ps-${t.id}`),s=["","$_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }",`(Get-Location).Path | Out-File -FilePath '${n.replace(/'/g,"''")}' -Encoding utf8 -NoNewline`,"exit $_ec"].join(`
132
- ; `),i=e+s;return{commandString:t.useSandbox?[`'${o.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Ai(i)].join(" "):i,cwdFilePath:n}},getSpawnArgs(e){return fp(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var hp=[{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"}],yp=[{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 Mn(o){for(let{pattern:e,warning:t}of hp)if(e.test(o))return t;return null}function Pn(o){for(let{pattern:e,warning:t}of yp)if(e.test(o))return t;return null}var bp="read",Tp={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 Ei(o){return{name:bp,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:Tp,execute:async(n,r)=>{let s=o.resolvePath(r.path);if(o.validatePath){let f=o.validatePath(s);if(f)return{content:[{type:"text",text:`Access denied: ${f}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await o.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(`
133
- `),l=Math.max(0,(r.offset??1)-1),c=Math.min(r.limit??2e3,2e3),u=a.slice(l,l+c),g=u.join(`
134
- `);g.length>5e4&&(g=g.slice(0,5e4)+`
135
- ... (truncated)`);let d=a.length,m=l+u.length,h=m<d;return{content:[{type:"text",text:g}],details:{type:"read",path:s,totalLines:d,startLine:l+1,endLine:m,hasMore:h}}}}}var kp="write",xp={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"]},Ii=5e5;function Oi(o){return{name:kp,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:xp,execute:async(e,t)=>{let n=o.resolvePath(t.path);if(o.validatePath){let s=o.validatePath(n);if(s)return{content:[{type:"text",text:`Access denied: ${s}`}],details:{type:"write",path:n,error:"access_denied"}}}if(t.content.length>Ii)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${Ii}). Split into multiple writes or use a different approach.`}],details:{type:"write",path:n,error:"content_too_large"}};if(o.checkReadBeforeWrite){let s=o.checkReadBeforeWrite(n);if(s)return{content:[{type:"text",text:s}],details:{type:"write",path:n,error:"not_read_first"}}}if(o.checkConcurrentModification){let s=o.checkConcurrentModification(n);if(s)return{content:[{type:"text",text:`Concurrent modification detected: ${s}. Re-read the file first.`}],details:{type:"write",path:n,error:"concurrent_modification"}}}await o.writeFile(n,t.content);let r=t.content.split(`
136
- `).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${n}`}],details:{type:"write",path:n,lineCount:r}}}}}var vp="edit",wp={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 Li(o){return{name:vp,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:wp,execute:async(e,t)=>{let n=o.resolvePath(t.path);if(o.checkConcurrentModification){let u=o.checkConcurrentModification(n);if(u)return{content:[{type:"text",text:`Concurrent modification detected: ${u}. Re-read the file first.`}],details:{type:"edit",path:n,success:!1,reason:"concurrent_modification"}}}let r=await o.readFile(n),s=r.indexOf(t.oldText);if(s===-1)return{content:[{type:"text",text:`Error: oldText not found in ${n}. Ensure it matches exactly.`}],details:{type:"edit",path:n,success:!1,reason:"not_found"}};if(r.indexOf(t.oldText,s+1)!==-1)return{content:[{type:"text",text:`Error: oldText matches multiple locations in ${n}. Include more context to make the match unique.`}],details:{type:"edit",path:n,success:!1,reason:"ambiguous"}};let a=r.slice(0,s)+t.newText+r.slice(s+t.oldText.length);await o.writeFile(n,a);let c=r.slice(0,s).split(`
137
- `).length;return{content:[{type:"text",text:`Edited ${n} (line ${c})`}],details:{type:"edit",path:n,success:!0,firstChangedLine:c}}}}}var Sp="search",Cp={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"]},$i=100,Di=250,An=1e5;function Ni(o){return{name:Sp,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:Cp,execute:async(e,t)=>{let n=t.path?o.resolvePath?o.resolvePath(t.path):t.path:"",r=t.mode;return r==="filename"?_p(o,t,n):r==="content"?Rp(o,t,n):Mp(o,t,n)}}}async function _p(o,e,t){let n=e.headLimit??$i,{files:r,truncated:s}=await o.glob(e.pattern,{cwd:t,limit:n===0?1e4:n}),i=e.offset??0,a=i>0?r.slice(i):r,l=n===0?a.length:n,c=a.slice(0,l),u=s||a.length>l;if(c.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let g=c.join(`
138
- `);return u&&(g+=`
139
-
140
- (Results truncated. ${c.length} shown. Use a more specific pattern or increase headLimit.)`),g=En(g,An),{content:[{type:"text",text:g}],details:{mode:"filename",totalMatches:c.length,truncated:u}}}async function Rp(o,e,t){let n=e.headLimit??Di,{matches:r,truncated:s}=await o.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:n===0?void 0:n,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 c of l.contextBefore)i.push(` ${c}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let c of l.contextAfter)i.push(` ${c}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
128
+ ${o.slice(-t)}`}function zp(o){return o==null||o<=0?Hp:Math.min(o,Gp)}async function*Vp(o){let{command:e,abortController:t,timeout:n,shouldAutoBackground:r,cwd:s}=o,i="",a=0,l=0,c=Date.now(),u=null;function p(){return new Promise(y=>{u=()=>y(null)})}let d=await ro(e,t.signal,void 0,{timeout:n,onProgress(y,h,k,w,f){i=h,a=k,l=w,u&&(u(),u=null)},shouldAutoBackground:r,cwd:s});for(d.onTimeout&&r&&d.onTimeout(y=>{let h=Te("bg");y(h)});d.status==="running"&&await Promise.race([p(),d.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-c)/1e3,totalLines:a,totalBytes:l};let m=await d.result;return d.cleanup(),m}function Wi(o={}){return{name:Wp,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:qp,maxResultSizeChars:so,execute:async(e,t)=>{let n=Mn(t.command);if(!t.background){let d=Pn(t.command);if(d)return{content:[{type:"text",text:`Command blocked: ${d}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:n}}}if(o.validateCommand){let d=await o.validateCommand(t.command);if(d)return{content:[{type:"text",text:`Command blocked: ${d}`}],details:{type:"exec",error:"blocked_by_guard",reason:d,classification:n}}}let r=new AbortController,s=zp(t.timeout),i=t.workdir?Fp(t.workdir)?t.workdir:Bp(oo(),t.workdir):void 0;if(t.background){let d=await ro(t.command,r.signal,void 0,{shouldAutoBackground:!1,cwd:i}),m=Te("bg");if(d.background(m))return{content:[{type:"text",text:`Background task started (id: ${m}).
129
+ Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:t.description,classification:n}}}let a=Vp({command:t.command,abortController:r,timeout:s,shouldAutoBackground:!0,cwd:i}),l;do l=await a.next(),!l.done&&o.onProgress&&o.onProgress(l.value);while(!l.done);let c=l.value,u=[];if(c.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${c.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:c.backgroundTaskId,assistantAutoBackgrounded:c.assistantAutoBackgrounded,classification:n}};c.outputFilePath?(u.push(Fn(c.stdout,so)),u.push(`[full output: ${c.outputFilePath} (${c.outputFileSize} bytes)]`)):c.stdout&&u.push(Fn(c.stdout,so)),c.stderr&&u.push(`[stderr]
130
+ ${Fn(c.stderr,Math.floor(so/4))}`),c.interrupted&&u.push(`[interrupted \u2014 exit code ${c.code}]`);let p;return c.code!==0&&o.interpretExitCode&&(p=o.interpretExitCode(c.code,c.stderr),p&&u.push(`[exit ${c.code}: ${p}]`)),u.length===0&&u.push(n.isSilent&&c.code===0?"Done":`(exit code ${c.code}, no output)`),{content:[{type:"text",text:u.join(`
131
+ `)}],details:{type:"exec",exitCode:c.code,interrupted:c.interrupted,description:t.description,returnCodeInterpretation:p,noOutputExpected:n.isSilent,outputFilePath:c.outputFilePath,classification:n}}}}}import{tmpdir as Kp}from"node:os";import{join as Jp,posix as Bn}from"node:path";function Yp(o){return o.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function Xp(o){return!(/(?:^|[;&|])\s*<\s/.test(o)||/<<[-]?\s*['"]?[A-Za-z_]/.test(o))}function Qp(o,e){return`$'${o.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function qi(o){return process.platform!=="win32"?o:o.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function io(o,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:o,detached:!0,async buildExecCommand(n,r){let s=process.platform==="win32",i=Kp(),a=s?qi(i):i,l=r.useSandbox&&r.sandboxTmpDir?Bn.join(r.sandboxTmpDir,`cwd-${r.id}`):Bn.join(a,`qla-${r.id}-cwd`),c=r.useSandbox&&r.sandboxTmpDir?Bn.join(r.sandboxTmpDir,`cwd-${r.id}`):Jp(i,`qla-${r.id}-cwd`),u=Yp(n),p=Xp(u),d=Qp(u,p),m=[];if(t){let h=s?qi(t):t;m.push(`source '${h}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${d}`),m.push(`pwd -P >| '${l}'`),{commandString:m.join(" && "),cwdFilePath:c}},getSpawnArgs(n){return["-c",...!!t?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as Zp}from"node:os";import{join as em,posix as tm}from"node:path";function Hi(o){return Buffer.from(o,"utf16le").toString("base64")}function om(o){return["-NoProfile","-NonInteractive","-Command",o]}function Wn(o){return{type:"powershell",shellPath:o,detached:!1,async buildExecCommand(e,t){let n=t.useSandbox&&t.sandboxTmpDir?tm.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):em(Zp(),`qla-pwd-ps-${t.id}`),s=["","$_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }",`(Get-Location).Path | Out-File -FilePath '${n.replace(/'/g,"''")}' -Encoding utf8 -NoNewline`,"exit $_ec"].join(`
132
+ ; `),i=e+s;return{commandString:t.useSandbox?[`'${o.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Hi(i)].join(" "):i,cwdFilePath:n}},getSpawnArgs(e){return om(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var nm=[{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"}],rm=[{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 qn(o){for(let{pattern:e,warning:t}of nm)if(e.test(o))return t;return null}function Hn(o){for(let{pattern:e,warning:t}of rm)if(e.test(o))return t;return null}var sm="read",im={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 Gi(o){return{name:sm,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:im,execute:async(n,r)=>{let s=o.resolvePath(r.path);if(o.validatePath){let h=o.validatePath(s);if(h)return{content:[{type:"text",text:`Access denied: ${h}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await o.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(`
133
+ `),l=Math.max(0,(r.offset??1)-1),c=Math.min(r.limit??2e3,2e3),u=a.slice(l,l+c),p=u.join(`
134
+ `);p.length>5e4&&(p=p.slice(0,5e4)+`
135
+ ... (truncated)`);let d=a.length,m=l+u.length,y=m<d;return{content:[{type:"text",text:p}],details:{type:"read",path:s,totalLines:d,startLine:l+1,endLine:m,hasMore:y}}}}}var am="write",lm={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"]},zi=5e5;function Vi(o){return{name:am,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:lm,execute:async(e,t)=>{let n=o.resolvePath(t.path);if(o.validatePath){let s=o.validatePath(n);if(s)return{content:[{type:"text",text:`Access denied: ${s}`}],details:{type:"write",path:n,error:"access_denied"}}}if(t.content.length>zi)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${zi}). Split into multiple writes or use a different approach.`}],details:{type:"write",path:n,error:"content_too_large"}};if(o.checkReadBeforeWrite){let s=o.checkReadBeforeWrite(n);if(s)return{content:[{type:"text",text:s}],details:{type:"write",path:n,error:"not_read_first"}}}if(o.checkConcurrentModification){let s=o.checkConcurrentModification(n);if(s)return{content:[{type:"text",text:`Concurrent modification detected: ${s}. Re-read the file first.`}],details:{type:"write",path:n,error:"concurrent_modification"}}}await o.writeFile(n,t.content);let r=t.content.split(`
136
+ `).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${n}`}],details:{type:"write",path:n,lineCount:r}}}}}var cm="edit",um={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 Ki(o){return{name:cm,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:um,execute:async(e,t)=>{let n=o.resolvePath(t.path);if(o.checkConcurrentModification){let u=o.checkConcurrentModification(n);if(u)return{content:[{type:"text",text:`Concurrent modification detected: ${u}. Re-read the file first.`}],details:{type:"edit",path:n,success:!1,reason:"concurrent_modification"}}}let r=await o.readFile(n),s=r.indexOf(t.oldText);if(s===-1)return{content:[{type:"text",text:`Error: oldText not found in ${n}. Ensure it matches exactly.`}],details:{type:"edit",path:n,success:!1,reason:"not_found"}};if(r.indexOf(t.oldText,s+1)!==-1)return{content:[{type:"text",text:`Error: oldText matches multiple locations in ${n}. Include more context to make the match unique.`}],details:{type:"edit",path:n,success:!1,reason:"ambiguous"}};let a=r.slice(0,s)+t.newText+r.slice(s+t.oldText.length);await o.writeFile(n,a);let c=r.slice(0,s).split(`
137
+ `).length;return{content:[{type:"text",text:`Edited ${n} (line ${c})`}],details:{type:"edit",path:n,success:!0,firstChangedLine:c}}}}}var dm="search",pm={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"]},Ji=100,Yi=250,Gn=1e5;function Xi(o){return{name:dm,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:pm,execute:async(e,t)=>{let n=t.path?o.resolvePath?o.resolvePath(t.path):t.path:"",r=t.mode;return r==="filename"?mm(o,t,n):r==="content"?gm(o,t,n):fm(o,t,n)}}}async function mm(o,e,t){let n=e.headLimit??Ji,{files:r,truncated:s}=await o.glob(e.pattern,{cwd:t,limit:n===0?1e4:n}),i=e.offset??0,a=i>0?r.slice(i):r,l=n===0?a.length:n,c=a.slice(0,l),u=s||a.length>l;if(c.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let p=c.join(`
138
+ `);return u&&(p+=`
139
+
140
+ (Results truncated. ${c.length} shown. Use a more specific pattern or increase headLimit.)`),p=zn(p,Gn),{content:[{type:"text",text:p}],details:{mode:"filename",totalMatches:c.length,truncated:u}}}async function gm(o,e,t){let n=e.headLimit??Yi,{matches:r,truncated:s}=await o.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:n===0?void 0:n,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 c of l.contextBefore)i.push(` ${c}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let c of l.contextAfter)i.push(` ${c}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
141
141
  `);return s&&(a+=`
142
142
 
143
- (Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=En(a,An),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function Mp(o,e,t){let[n,r]=await Promise.all([e.fileGlob?o.glob(e.fileGlob,{cwd:t,limit:$i}):Promise.resolve({files:[],truncated:!1}),o.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Di,offset:e.offset})]),s=new Set(r.matches.map(u=>u.path)),i=n.files.filter(u=>!s.has(u)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
143
+ (Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=zn(a,Gn),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function fm(o,e,t){let[n,r]=await Promise.all([e.fileGlob?o.glob(e.fileGlob,{cwd:t,limit:Ji}):Promise.resolve({files:[],truncated:!1}),o.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Yi,offset:e.offset})]),s=new Set(r.matches.map(u=>u.path)),i=n.files.filter(u=>!s.has(u)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
144
144
  ${i.join(`
145
- `)}`),r.matches.length>0){let u=[];for(let g of r.matches)u.push(`${g.path}:${g.line}: ${g.text}`);a.push(`## Content matches (${r.matches.length}):
145
+ `)}`),r.matches.length>0){let u=[];for(let p of r.matches)u.push(`${p.path}:${p.line}: ${p.text}`);a.push(`## Content matches (${r.matches.length}):
146
146
  ${u.join(`
147
147
  `)}`)}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=n.truncated||r.truncated,c=a.join(`
148
148
 
149
149
  `);return l&&(c+=`
150
150
 
151
- (Some results truncated. Use more specific patterns.)`),c=En(c,An),{content:[{type:"text",text:c}],details:{mode:"both",totalMatches:i.length+r.matches.length,truncated:l}}}function En(o,e){if(o.length<=e)return o;let t=Math.floor(e/2)-50;return`${o.slice(0,t)}
151
+ (Some results truncated. Use more specific patterns.)`),c=zn(c,Gn),{content:[{type:"text",text:c}],details:{mode:"both",totalMatches:i.length+r.matches.length,truncated:l}}}function zn(o,e){if(o.length<=e)return o;let t=Math.floor(e/2)-50;return`${o.slice(0,t)}
152
152
 
153
153
  ... [truncated ${o.length-e} chars] ...
154
154
 
155
- ${o.slice(-t)}`}var Pp="apply_patch",Ap={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function Ep(o){let e=o.split(`
156
- `),t=[],n=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: "))n&&t.push(n),n={type:"add",path:i.slice(14).trim(),hunks:[]},r={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.hunks.push(r);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move to: ")&&n)n.moveTo=i.slice(13).trim();else if(i.startsWith("@@ ")&&n)r={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.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 n&&t.push(n),t}function Ip(o,e){let n=[...o.split(`
155
+ ${o.slice(-t)}`}var hm="apply_patch",ym={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function bm(o){let e=o.split(`
156
+ `),t=[],n=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: "))n&&t.push(n),n={type:"add",path:i.slice(14).trim(),hunks:[]},r={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.hunks.push(r);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move to: ")&&n)n.moveTo=i.slice(13).trim();else if(i.startsWith("@@ ")&&n)r={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.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 n&&t.push(n),t}function Tm(o,e){let n=[...o.split(`
157
157
  `)];for(let r of e){let s=-1;if(r.contextBefore.length>0)for(let i=0;i<=n.length-r.contextBefore.length;i++){let a=!0;for(let l=0;l<r.contextBefore.length;l++)if(n[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?n.splice(s,r.removals.length,...r.additions):n.splice(s,0,...r.additions))}return n.join(`
158
- `)}function ji(o){return{name:Pp,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:Ap,execute:async(e,t)=>{let n=Ep(t.input);if(n.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 n){let l=o.resolvePath(a.path);try{switch(a.type){case"add":{let c=a.hunks.flatMap(u=>[...u.additions]).join(`
159
- `);await o.writeFile(l,c),r.added.push(a.path);break}case"update":{let c=await o.readFile(l),u=Ip(c,a.hunks);if(a.moveTo){let g=o.resolvePath(a.moveTo);await o.writeFile(g,u),await o.deleteFile(l),r.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await o.writeFile(l,u),r.modified.push(a.path);break}case"delete":{await o.deleteFile(l),r.deleted.push(a.path);break}}}catch(c){s.push(`${a.type} ${a.path}: ${c instanceof Error?c.message:String(c)}`)}}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(`
160
- `)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var Op="patch",Lp={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
158
+ `)}function Qi(o){return{name:hm,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:ym,execute:async(e,t)=>{let n=bm(t.input);if(n.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 n){let l=o.resolvePath(a.path);try{switch(a.type){case"add":{let c=a.hunks.flatMap(u=>[...u.additions]).join(`
159
+ `);await o.writeFile(l,c),r.added.push(a.path);break}case"update":{let c=await o.readFile(l),u=Tm(c,a.hunks);if(a.moveTo){let p=o.resolvePath(a.moveTo);await o.writeFile(p,u),await o.deleteFile(l),r.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await o.writeFile(l,u),r.modified.push(a.path);break}case"delete":{await o.deleteFile(l),r.deleted.push(a.path);break}}}catch(c){s.push(`${a.type} ${a.path}: ${c instanceof Error?c.message:String(c)}`)}}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(`
160
+ `)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var km="patch",xm={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
161
161
  1) V4A unified diff (*** Begin Patch / *** End Patch markers)
162
162
  2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
163
- 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 $p(o){return o.replace(/\\n/g,`
164
- `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Fi(o){return o.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 Ui(o,e){if(o===e||Math.max(o.length,e.length)===0)return 1;let n=0,r=o.length,s=e.length,i=Math.max(r,s);for(let a=0;a<Math.min(r,s);a++)o[a]!==e[a]&&n++;return n+=Math.abs(r-s),1-n/i}function zi(o,e,t){let n=[],r=o.indexOf(e);if(r!==-1){if(t){let f=0;for(;(r=o.indexOf(e,f))!==-1;)n.push({start:r,end:r+e.length,strategy:"exact"}),f=r+e.length}else n.push({start:r,end:r+e.length,strategy:"exact"});return n}let s=e.split(`
165
- `).map(f=>f.trim()),i=o.split(`
166
- `),a=Bi(i,s,(f,T)=>f.trim()===T);if(a)return[{...qi(o,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),c=o.replace(/[ \t]+/g," ");if(r=c.indexOf(l),r!==-1){let f=Wi(o,c,r,l.length);if(f)return[{...f,strategy:"whitespace_normalized"}]}let u=Bi(i,s,(f,T)=>f.trimStart()===T.trimStart());if(u)return[{...qi(o,i,u),strategy:"indentation_flexible"}];let g=$p(e);if(g!==e&&(r=o.indexOf(g),r!==-1))return[{start:r,end:r+g.length,strategy:"escape_normalized"}];let d=e.split(`
167
- `);if(d.length>=3){let f=d.slice(1,-1).join(`
168
- `),T=d[0].trim(),y=d[d.length-1].trim();for(let v=0;v<i.length;v++)if(i[v].trim()===T){let _=i.slice(0,v+1).join(`
169
- `).length+1,M=o.indexOf(f,_);if(M!==-1){let $=M+f.length,q=o.indexOf(`
170
- `,$);if((q===-1?o.slice($):o.slice($,q)).trim()===y||q!==-1&&o.slice($+1,o.indexOf(`
171
- `,$+1)===-1?void 0:o.indexOf(`
172
- `,$+1)).trim()===y){let O=i.slice(0,v).join(`
173
- `).length+(v>0?1:0),k=v,D=d.length;if(v+D<=i.length){k=v+D;let K=i.slice(0,k).join(`
174
- `).length;return[{start:O,end:K,strategy:"trimmed_boundary"}]}}}}}let m=Fi(e),h=Fi(o);if((m!==e||h!==o)&&(r=h.indexOf(m),r!==-1)){let f=Wi(o,h,r,m.length);if(f)return[{...f,strategy:"unicode_normalized"}]}if(d.length>=3){let f=d[0],T=d[d.length-1];for(let y=0;y<i.length;y++)if(i[y]===f){for(let v=y+d.length-1;v<Math.min(y+d.length+2,i.length);v++)if(i[v]===T){let _=v-y+1,M=i.slice(y+1,v),$=d.slice(1,-1),q=$.filter(O=>M.some(k=>Ui(k,O)>=.7)).length;if(($.length>0?q/$.length:1)>=.5&&_<=d.length+2){let O=i.slice(0,y).join(`
175
- `).length+(y>0?1:0),k=i.slice(0,v+1).join(`
176
- `).length;return[{start:O,end:k,strategy:"block_anchor"}]}}}}if(d.length>=2)for(let f=0;f<=i.length-d.length;f++){let T=i.slice(f,f+d.length);if(d.map((_,M)=>Ui(_,T[M])).filter(_=>_>=.8).length/d.length>=.5){let _=i.slice(0,f).join(`
177
- `).length+(f>0?1:0),M=i.slice(0,f+d.length).join(`
178
- `).length;return[{start:_,end:M,strategy:"context_aware"}]}}return[]}function Bi(o,e,t){for(let n=0;n<=o.length-e.length;n++){let r=!0;for(let s=0;s<e.length;s++)if(!t(o[n+s],e[s])){r=!1;break}if(r)return{startIdx:n,endIdx:n+e.length}}return null}function qi(o,e,t){let n=e.slice(0,t.startIdx).join(`
163
+ 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 vm(o){return o.replace(/\\n/g,`
164
+ `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Zi(o){return o.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 ea(o,e){if(o===e||Math.max(o.length,e.length)===0)return 1;let n=0,r=o.length,s=e.length,i=Math.max(r,s);for(let a=0;a<Math.min(r,s);a++)o[a]!==e[a]&&n++;return n+=Math.abs(r-s),1-n/i}function ia(o,e,t){let n=[],r=o.indexOf(e);if(r!==-1){if(t){let h=0;for(;(r=o.indexOf(e,h))!==-1;)n.push({start:r,end:r+e.length,strategy:"exact"}),h=r+e.length}else n.push({start:r,end:r+e.length,strategy:"exact"});return n}let s=e.split(`
165
+ `).map(h=>h.trim()),i=o.split(`
166
+ `),a=ta(i,s,(h,k)=>h.trim()===k);if(a)return[{...oa(o,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),c=o.replace(/[ \t]+/g," ");if(r=c.indexOf(l),r!==-1){let h=na(o,c,r,l.length);if(h)return[{...h,strategy:"whitespace_normalized"}]}let u=ta(i,s,(h,k)=>h.trimStart()===k.trimStart());if(u)return[{...oa(o,i,u),strategy:"indentation_flexible"}];let p=vm(e);if(p!==e&&(r=o.indexOf(p),r!==-1))return[{start:r,end:r+p.length,strategy:"escape_normalized"}];let d=e.split(`
167
+ `);if(d.length>=3){let h=d.slice(1,-1).join(`
168
+ `),k=d[0].trim(),w=d[d.length-1].trim();for(let f=0;f<i.length;f++)if(i[f].trim()===k){let C=i.slice(0,f+1).join(`
169
+ `).length+1,R=o.indexOf(h,C);if(R!==-1){let L=R+h.length,K=o.indexOf(`
170
+ `,L);if((K===-1?o.slice(L):o.slice(L,K)).trim()===w||K!==-1&&o.slice(L+1,o.indexOf(`
171
+ `,L+1)===-1?void 0:o.indexOf(`
172
+ `,L+1)).trim()===w){let F=i.slice(0,f).join(`
173
+ `).length+(f>0?1:0),T=f,B=d.length;if(f+B<=i.length){T=f+B;let J=i.slice(0,T).join(`
174
+ `).length;return[{start:F,end:J,strategy:"trimmed_boundary"}]}}}}}let m=Zi(e),y=Zi(o);if((m!==e||y!==o)&&(r=y.indexOf(m),r!==-1)){let h=na(o,y,r,m.length);if(h)return[{...h,strategy:"unicode_normalized"}]}if(d.length>=3){let h=d[0],k=d[d.length-1];for(let w=0;w<i.length;w++)if(i[w]===h){for(let f=w+d.length-1;f<Math.min(w+d.length+2,i.length);f++)if(i[f]===k){let C=f-w+1,R=i.slice(w+1,f),L=d.slice(1,-1),K=L.filter(F=>R.some(T=>ea(T,F)>=.7)).length;if((L.length>0?K/L.length:1)>=.5&&C<=d.length+2){let F=i.slice(0,w).join(`
175
+ `).length+(w>0?1:0),T=i.slice(0,f+1).join(`
176
+ `).length;return[{start:F,end:T,strategy:"block_anchor"}]}}}}if(d.length>=2)for(let h=0;h<=i.length-d.length;h++){let k=i.slice(h,h+d.length);if(d.map((C,R)=>ea(C,k[R])).filter(C=>C>=.8).length/d.length>=.5){let C=i.slice(0,h).join(`
177
+ `).length+(h>0?1:0),R=i.slice(0,h+d.length).join(`
178
+ `).length;return[{start:C,end:R,strategy:"context_aware"}]}}return[]}function ta(o,e,t){for(let n=0;n<=o.length-e.length;n++){let r=!0;for(let s=0;s<e.length;s++)if(!t(o[n+s],e[s])){r=!1;break}if(r)return{startIdx:n,endIdx:n+e.length}}return null}function oa(o,e,t){let n=e.slice(0,t.startIdx).join(`
179
179
  `).length+(t.startIdx>0?1:0),r=e.slice(0,t.endIdx).join(`
180
- `).length;return{start:n,end:r}}function Wi(o,e,t,n){let r=0,s=0,i=-1,a=-1;for(;r<=o.length&&s<=e.length;){if(s===t&&i===-1&&(i=r),s===t+n){a=r;break}if(s>=e.length||r>=o.length)break;for(s++,r++;r<o.length&&s<e.length&&o[r]!==e[s];)r++}return i!==-1&&a===-1&&(a=o.length),i===-1?null:{start:i,end:a}}function Hi(o){let e=o.split(`
181
- `),t=[],n=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: "))n&&t.push(n),n={type:"add",path:i.slice(14).trim(),hunks:[]},r={lines:[]},n.hunks.push(r);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move File: ")){n&&t.push(n);let a=i.slice(15).trim().split(" -> ");n={type:"move",path:a[0].trim(),newPath:a[1]?.trim(),hunks:[]},r=null}else i.startsWith("@@ ")&&n?(r={contextHint:i.slice(3).replace(/ @@$/,"").trim()||void 0,lines:[]},n.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 n&&t.push(n),t}function Dp(o){let e=[],t=o.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let n=t[0].trim().split(`
180
+ `).length;return{start:n,end:r}}function na(o,e,t,n){let r=0,s=0,i=-1,a=-1;for(;r<=o.length&&s<=e.length;){if(s===t&&i===-1&&(i=r),s===t+n){a=r;break}if(s>=e.length||r>=o.length)break;for(s++,r++;r<o.length&&s<e.length&&o[r]!==e[s];)r++}return i!==-1&&a===-1&&(a=o.length),i===-1?null:{start:i,end:a}}function ra(o){let e=o.split(`
181
+ `),t=[],n=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: "))n&&t.push(n),n={type:"add",path:i.slice(14).trim(),hunks:[]},r={lines:[]},n.hunks.push(r);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move File: ")){n&&t.push(n);let a=i.slice(15).trim().split(" -> ");n={type:"move",path:a[0].trim(),newPath:a[1]?.trim(),hunks:[]},r=null}else i.startsWith("@@ ")&&n?(r={contextHint:i.slice(3).replace(/ @@$/,"").trim()||void 0,lines:[]},n.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 n&&t.push(n),t}function wm(o){let e=[],t=o.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let n=t[0].trim().split(`
182
182
  `).pop()?.trim();if(!n)return[];for(let r=1;r<t.length;r+=2){let s=t[r+1]||"",i=s.indexOf(`
183
183
  ====
184
184
  `);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),l=s.slice(i+6),c=l.indexOf(`
185
- >>>> REPLACE`),u=c===-1?l:l.slice(0,c);e.push({path:n,search:a,replace:u})}return e}function Gi(o,e,t){let n=e.lines.filter(h=>h.prefix===" ").map(h=>h.content),r=e.lines.filter(h=>h.prefix==="-").map(h=>h.content),s=e.lines.filter(h=>h.prefix==="+").map(h=>h.content),i=[],a="context";for(let h of e.lines)(h.prefix===" "||h.prefix==="-")&&i.push(h.content);let l=i.join(`
185
+ >>>> REPLACE`),u=c===-1?l:l.slice(0,c);e.push({path:n,search:a,replace:u})}return e}function sa(o,e,t){let n=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(`
186
186
  `);if(!l)return{content:o+`
187
187
  `+s.join(`
188
- `),strategy:"exact"};let c=zi(o,l,t);if(c.length===0)return null;let u=[];for(let h of e.lines)(h.prefix===" "||h.prefix==="+")&&u.push(h.content);let g=u.join(`
189
- `),d=c[0];return{content:o.slice(0,d.start)+g+o.slice(d.end),strategy:d.strategy}}function In(o){return{name:Op,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:Lp,execute:async(e,t)=>{let n=t.replaceAll??!1,r={filesModified:[],filesAdded:[],filesDeleted:[],strategies:{},errors:[]},s=t.input.includes("*** Begin Patch"),i=t.input.includes("<<<< SEARCH");if(s){let c=Hi(t.input);if(c.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 u of c){let g=o.resolvePath(u.path);try{switch(u.type){case"add":{let d=u.hunks.flatMap(m=>m.lines.filter(h=>h.prefix==="+").map(h=>h.content)).join(`
190
- `);await o.writeFile(g,d),r.filesAdded.push(u.path),r.strategies[u.path]="exact";break}case"delete":{await o.deleteFile(g),r.filesDeleted.push(u.path);break}case"move":{let d=await o.readFile(g);if(u.newPath){let m=o.resolvePath(u.newPath),h=d;for(let f of u.hunks){let T=Gi(h,f,n);T&&(h=T.content,r.strategies[u.path]=T.strategy)}await o.writeFile(m,h),await o.deleteFile(g),r.filesModified.push(`${u.path} \u2192 ${u.newPath}`)}break}case"update":{let d=await o.readFile(g),m="exact",h=!0;for(let f of u.hunks){let T=Gi(d,f,n);if(T)d=T.content,m=T.strategy;else{h=!1;let y=f.lines.filter(v=>v.prefix===" "||v.prefix==="-").map(v=>v.content).slice(0,5).join(`
188
+ `),strategy:"exact"};let c=ia(o,l,t);if(c.length===0)return null;let u=[];for(let y of e.lines)(y.prefix===" "||y.prefix==="+")&&u.push(y.content);let p=u.join(`
189
+ `),d=c[0];return{content:o.slice(0,d.start)+p+o.slice(d.end),strategy:d.strategy}}function Vn(o){return{name:km,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:xm,execute:async(e,t)=>{let n=t.replaceAll??!1,r={filesModified:[],filesAdded:[],filesDeleted:[],strategies:{},errors:[]},s=t.input.includes("*** Begin Patch"),i=t.input.includes("<<<< SEARCH");if(s){let c=ra(t.input);if(c.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 u of c){let p=o.resolvePath(u.path);try{switch(u.type){case"add":{let d=u.hunks.flatMap(m=>m.lines.filter(y=>y.prefix==="+").map(y=>y.content)).join(`
190
+ `);await o.writeFile(p,d),r.filesAdded.push(u.path),r.strategies[u.path]="exact";break}case"delete":{await o.deleteFile(p),r.filesDeleted.push(u.path);break}case"move":{let d=await o.readFile(p);if(u.newPath){let m=o.resolvePath(u.newPath),y=d;for(let h of u.hunks){let k=sa(y,h,n);k&&(y=k.content,r.strategies[u.path]=k.strategy)}await o.writeFile(m,y),await o.deleteFile(p),r.filesModified.push(`${u.path} \u2192 ${u.newPath}`)}break}case"update":{let d=await o.readFile(p),m="exact",y=!0;for(let h of u.hunks){let k=sa(d,h,n);if(k)d=k.content,m=k.strategy;else{y=!1;let w=h.lines.filter(f=>f.prefix===" "||f.prefix==="-").map(f=>f.content).slice(0,5).join(`
191
191
  `);r.errors.push(`${u.path}: hunk not matched. Search begins with:
192
- ${y}`)}}(h||d!==await o.readFile(g))&&(await o.writeFile(g,d),r.filesModified.push(u.path),r.strategies[u.path]=m);break}}}catch(d){r.errors.push(`${u.type} ${u.path}: ${d instanceof Error?d.message:String(d)}`)}}}else if(i){let c=Dp(t.input);if(c.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let u of c){let g=o.resolvePath(u.path);try{let d=await o.readFile(g),m=zi(d,u.search,n);if(m.length===0){r.errors.push(`${u.path}: search text not matched (tried all 9 strategies)`);continue}let h=[...m].sort((f,T)=>T.start-f.start);for(let f of h)d=d.slice(0,f.start)+u.replace+d.slice(f.end);await o.writeFile(g,d),r.filesModified.push(u.path),r.strategies[u.path]=m[0].strategy}catch(d){r.errors.push(`${u.path}: ${d instanceof Error?d.message:String(d)}`)}}}else return Hi(`*** Begin Patch
192
+ ${w}`)}}(y||d!==await o.readFile(p))&&(await o.writeFile(p,d),r.filesModified.push(u.path),r.strategies[u.path]=m);break}}}catch(d){r.errors.push(`${u.type} ${u.path}: ${d instanceof Error?d.message:String(d)}`)}}}else if(i){let c=wm(t.input);if(c.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let u of c){let p=o.resolvePath(u.path);try{let d=await o.readFile(p),m=ia(d,u.search,n);if(m.length===0){r.errors.push(`${u.path}: search text not matched (tried all 9 strategies)`);continue}let y=[...m].sort((h,k)=>k.start-h.start);for(let h of y)d=d.slice(0,h.start)+u.replace+d.slice(h.end);await o.writeFile(p,d),r.filesModified.push(u.path),r.strategies[u.path]=m[0].strategy}catch(d){r.errors.push(`${u.path}: ${d instanceof Error?d.message:String(d)}`)}}}else return ra(`*** Begin Patch
193
193
  `+t.input+`
194
- *** End Patch`).length>0?In(o).execute(e,{input:`*** Begin Patch
194
+ *** End Patch`).length>0?Vn(o).execute(e,{input:`*** Begin Patch
195
195
  `+t.input+`
196
196
  *** End Patch`,replaceAll:n}):{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 c=r.filesModified.map(u=>`${u} (${r.strategies[u]||"exact"})`).join(", ");a.push(`Modified: ${c}`)}r.filesDeleted.length&&a.push(`Deleted: ${r.filesDeleted.join(", ")}`),r.errors.length&&a.push(`
197
197
  Errors:
198
198
  ${r.errors.join(`
199
199
  `)}`);let l=r.errors.length===0;return{content:[{type:"text",text:a.join(`
200
- `)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var Np="web_fetch",jp={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"]},Fp=5e4;function Vi(o){return{name:Np,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:jp,execute:async(e,t)=>{let n=await o.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??Fp,query:t.query,extract:t.extract});if(t.summarize&&o.summarizeContent&&n.content.length>1e3){let s=await o.summarizeContent(n.content,t.query);return{content:[{type:"text",text:n.title?`# ${n.title}
200
+ `)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var Sm="web_fetch",Cm={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"]},_m=5e4;function aa(o){return{name:Sm,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:Cm,execute:async(e,t)=>{let n=await o.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??_m,query:t.query,extract:t.extract});if(t.summarize&&o.summarizeContent&&n.content.length>1e3){let s=await o.summarizeContent(n.content,t.query);return{content:[{type:"text",text:n.title?`# ${n.title}
201
201
 
202
202
  ${s}`:s}],details:{type:"web_fetch",url:t.url,summarized:!0,originalLength:n.content.length,summaryLength:s.length}}}let r=[];if(n.title&&r.push(`# ${n.title}
203
203
  `),r.push(n.content),n.relevantExcerpts?.length){r.push(`
204
204
  ---
205
205
  ## Relevant Excerpts
206
206
  `);for(let s of n.relevantExcerpts)r.push(`- ${s}`)}return{content:[{type:"text",text:r.join(`
207
- `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!n.extraction,extraction:n.extraction}}}}}var Up="web_search",Bp={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"]},qp=10;function Ki(o){return{name:Up,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:Bp,execute:async(e,t)=>{if(t.allowedDomains?.length&&t.blockedDomains?.length)return{content:[{type:"text",text:"Error: allowedDomains and blockedDomains cannot both be specified."}],details:{type:"web_search",error:"mutual_exclusion"}};if(!t.query||t.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 n=await o.search(t.query.trim(),{allowedDomains:t.allowedDomains,blockedDomains:t.blockedDomains,maxResults:qp});if(n.results.length===0)return{content:[{type:"text",text:`No results found for: "${t.query}"`}],details:{type:"web_search",query:t.query,resultCount:0}};let r=[`Web search results for: "${n.query}"`,"","REMINDER: You MUST include source URLs as markdown links when referencing these results.",""];for(let s=0;s<n.results.length;s++){let i=n.results[s];r.push(`${s+1}. [${i.title}](${i.url})`),r.push(` ${i.snippet}`),r.push("")}return{content:[{type:"text",text:r.join(`
208
- `)}],details:{type:"web_search",query:n.query,resultCount:n.results.length}}}}}var Wp="instructions",Hp={type:"object",properties:{action:{type:"string",enum:["list","read","write","edit","delete"],description:"Operation: list all files, read a file, write (create/overwrite), edit (partial replace), or delete a file."},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"). Required for read/write/delete. Sub-paths like "testing/unit-test.md" are supported.'},content:{type:"string",description:"Markdown content for the instruction file. Required for write action."},old_text:{type:"string",description:"Required for edit action: the exact existing text to find and replace (must appear exactly once)."},new_text:{type:"string",description:"Required for edit action: the replacement text."}},required:["action","project_id"]};function Ji(o){return{name:Wp,label:"Instructions",description:"Manage project instruction files (.md) \u2014 list, read, write, edit, or delete. Instructions define agent behavior rules, coding standards, and project context.",parameters:Hp,isReadOnly:!1,isConcurrencySafe:!0,searchHint:"instructions list read write edit delete rules coding standards behavior guidelines",execute:async(e,t)=>{switch(t.action){case"list":{let n=o.list(t.project_id);if(n.length===0)return{content:[{type:"text",text:"No instruction files found for this project."}],details:{projectId:t.project_id,count:0}};let r=n.map(s=>`- ${s.filename} (${s.size} bytes, updated ${s.updatedAt})`).join(`
207
+ `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!n.extraction,extraction:n.extraction}}}}}var Rm="web_search",Mm={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"]},Pm=10;function la(o){return{name:Rm,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:Mm,execute:async(e,t)=>{if(t.allowedDomains?.length&&t.blockedDomains?.length)return{content:[{type:"text",text:"Error: allowedDomains and blockedDomains cannot both be specified."}],details:{type:"web_search",error:"mutual_exclusion"}};if(!t.query||t.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 n=await o.search(t.query.trim(),{allowedDomains:t.allowedDomains,blockedDomains:t.blockedDomains,maxResults:Pm});if(n.results.length===0)return{content:[{type:"text",text:`No results found for: "${t.query}"`}],details:{type:"web_search",query:t.query,resultCount:0}};let r=[`Web search results for: "${n.query}"`,"","REMINDER: You MUST include source URLs as markdown links when referencing these results.",""];for(let s=0;s<n.results.length;s++){let i=n.results[s];r.push(`${s+1}. [${i.title}](${i.url})`),r.push(` ${i.snippet}`),r.push("")}return{content:[{type:"text",text:r.join(`
208
+ `)}],details:{type:"web_search",query:n.query,resultCount:n.results.length}}}}}var Am="instructions",Em={type:"object",properties:{action:{type:"string",enum:["list","read","write","edit","delete"],description:"Operation: list all files, read a file, write (create/overwrite), edit (partial replace), or delete a file."},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"). Required for read/write/delete. Sub-paths like "testing/unit-test.md" are supported.'},content:{type:"string",description:"Markdown content for the instruction file. Required for write action."},old_text:{type:"string",description:"Required for edit action: the exact existing text to find and replace (must appear exactly once)."},new_text:{type:"string",description:"Required for edit action: the replacement text."}},required:["action","project_id"]};function ca(o){return{name:Am,label:"Instructions",description:"Manage project instruction files (.md) \u2014 list, read, write, edit, or delete. Instructions define agent behavior rules, coding standards, and project context.",parameters:Em,isReadOnly:!1,isConcurrencySafe:!0,searchHint:"instructions list read write edit delete rules coding standards behavior guidelines",execute:async(e,t)=>{switch(t.action){case"list":{let n=o.list(t.project_id);if(n.length===0)return{content:[{type:"text",text:"No instruction files found for this project."}],details:{projectId:t.project_id,count:0}};let r=n.map(s=>`- ${s.filename} (${s.size} bytes, updated ${s.updatedAt})`).join(`
209
209
  `);return{content:[{type:"text",text:`Found ${n.length} instruction file(s):
210
- ${r}`}],details:{projectId:t.project_id,count:n.length,files:n}}}case"read":{if(!t.filename)return{content:[{type:"text",text:"filename is required for read action"}],details:{error:"missing_filename"}};let n=o.read(t.project_id,t.filename);return n?{content:[{type:"text",text:n.content}],details:{projectId:t.project_id,filename:n.filename,size:n.size}}:{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}}}case"write":{if(!t.filename)return{content:[{type:"text",text:"filename is required for write action"}],details:{error:"missing_filename"}};if(t.content===void 0||t.content===null)return{content:[{type:"text",text:"content is required for write action"}],details:{error:"missing_content"}};if(!t.filename.endsWith(".md"))return{content:[{type:"text",text:"Filename must end with .md"}],details:{error:"invalid_filename"}};if(t.filename.includes(".."))return{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}};let n=o.write(t.project_id,t.filename,t.content);return{content:[{type:"text",text:`Instruction file written: ${n.filename} (${n.size} bytes)`}],details:{projectId:t.project_id,filename:n.filename,size:n.size}}}case"edit":{if(!t.filename)return{content:[{type:"text",text:"filename is required for edit action"}],details:{error:"missing_filename"}};if(!t.old_text)return{content:[{type:"text",text:"old_text is required for edit action"}],details:{error:"missing_old_text"}};if(t.new_text===void 0||t.new_text===null)return{content:[{type:"text",text:"new_text is required for edit action"}],details:{error:"missing_new_text"}};if(t.filename.includes(".."))return{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}};let n=o.read(t.project_id,t.filename);if(!n)return{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}};let r=n.content.split(t.old_text).length-1;if(r===0)return{content:[{type:"text",text:"old_text not found in the file"}],details:{projectId:t.project_id,filename:t.filename,error:"old_text_not_found"}};if(r>1)return{content:[{type:"text",text:`old_text matches ${r} locations \u2014 must match exactly once. Add more surrounding context to make it unique.`}],details:{projectId:t.project_id,filename:t.filename,error:"ambiguous_match",occurrences:r}};let s=n.content.replace(t.old_text,t.new_text),i=o.write(t.project_id,t.filename,s);return{content:[{type:"text",text:`Instruction file edited: ${i.filename} (${i.size} bytes)`}],details:{projectId:t.project_id,filename:i.filename,size:i.size}}}case"delete":return t.filename?t.filename.includes("..")?{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}}:o.remove(t.project_id,t.filename)?{content:[{type:"text",text:`Instruction file deleted: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename}}:{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}}:{content:[{type:"text",text:"filename is required for delete action"}],details:{error:"missing_filename"}};default:return{content:[{type:"text",text:`Unknown action: ${t.action}. Use list, read, write, edit, or delete.`}],details:{error:"unknown_action"}}}}}}var Gp="worktree",zp={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
210
+ ${r}`}],details:{projectId:t.project_id,count:n.length,files:n}}}case"read":{if(!t.filename)return{content:[{type:"text",text:"filename is required for read action"}],details:{error:"missing_filename"}};let n=o.read(t.project_id,t.filename);return n?{content:[{type:"text",text:n.content}],details:{projectId:t.project_id,filename:n.filename,size:n.size}}:{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}}}case"write":{if(!t.filename)return{content:[{type:"text",text:"filename is required for write action"}],details:{error:"missing_filename"}};if(t.content===void 0||t.content===null)return{content:[{type:"text",text:"content is required for write action"}],details:{error:"missing_content"}};if(!t.filename.endsWith(".md"))return{content:[{type:"text",text:"Filename must end with .md"}],details:{error:"invalid_filename"}};if(t.filename.includes(".."))return{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}};let n=o.write(t.project_id,t.filename,t.content);return{content:[{type:"text",text:`Instruction file written: ${n.filename} (${n.size} bytes)`}],details:{projectId:t.project_id,filename:n.filename,size:n.size}}}case"edit":{if(!t.filename)return{content:[{type:"text",text:"filename is required for edit action"}],details:{error:"missing_filename"}};if(!t.old_text)return{content:[{type:"text",text:"old_text is required for edit action"}],details:{error:"missing_old_text"}};if(t.new_text===void 0||t.new_text===null)return{content:[{type:"text",text:"new_text is required for edit action"}],details:{error:"missing_new_text"}};if(t.filename.includes(".."))return{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}};let n=o.read(t.project_id,t.filename);if(!n)return{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}};let r=n.content.split(t.old_text).length-1;if(r===0)return{content:[{type:"text",text:"old_text not found in the file"}],details:{projectId:t.project_id,filename:t.filename,error:"old_text_not_found"}};if(r>1)return{content:[{type:"text",text:`old_text matches ${r} locations \u2014 must match exactly once. Add more surrounding context to make it unique.`}],details:{projectId:t.project_id,filename:t.filename,error:"ambiguous_match",occurrences:r}};let s=n.content.replace(t.old_text,t.new_text),i=o.write(t.project_id,t.filename,s);return{content:[{type:"text",text:`Instruction file edited: ${i.filename} (${i.size} bytes)`}],details:{projectId:t.project_id,filename:i.filename,size:i.size}}}case"delete":return t.filename?t.filename.includes("..")?{content:[{type:"text",text:"Path traversal not allowed"}],details:{error:"path_traversal"}}:o.remove(t.project_id,t.filename)?{content:[{type:"text",text:`Instruction file deleted: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename}}:{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}}:{content:[{type:"text",text:"filename is required for delete action"}],details:{error:"missing_filename"}};default:return{content:[{type:"text",text:`Unknown action: ${t.action}. Use list, read, write, edit, or delete.`}],details:{error:"unknown_action"}}}}}}var Im="worktree",Om={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
211
211
  exit: Leave worktree (keep or remove it).
212
- 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 Yi(o){return{name:Gp,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:zp,execute:async(e,t)=>{switch(t.action){case"enter":{if(o.isInWorktree())return{content:[{type:"text",text:"Error: already in a worktree. Exit first before entering another."}],details:{type:"worktree",error:"already_in_worktree"}};if(t.name&&!Vp.test(t.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 n=await o.enterWorktree(t.name);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error||"failed to create worktree"}`}],details:{type:"worktree",error:n.error}};let r=n.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
+ 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"]},Lm=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function ua(o){return{name:Im,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:Om,execute:async(e,t)=>{switch(t.action){case"enter":{if(o.isInWorktree())return{content:[{type:"text",text:"Error: already in a worktree. Exit first before entering another."}],details:{type:"worktree",error:"already_in_worktree"}};if(t.name&&!Lm.test(t.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 n=await o.enterWorktree(t.name);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error||"failed to create worktree"}`}],details:{type:"worktree",error:n.error}};let r=n.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(`
213
213
  `)}],details:{type:"worktree",action:"enter",name:r.name,branch:r.branch,path:r.path}}}case"exit":{if(!o.isInWorktree())return{content:[{type:"text",text:"Error: not in a worktree."}],details:{type:"worktree",error:"not_in_worktree"}};let n=t.exitAction||"keep";if(n==="remove"){let i=o.currentWorktree?.();if(i&&(i.hasChanges||i.unpushedCommits>0)&&!t.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 o.exitWorktree(n,t.discardChanges);return r.success?{content:[{type:"text",text:`Exited worktree. ${n==="keep"?"Worktree kept for later use.":"Worktree removed."}
214
214
  Restored to: ${r.previousCwd||"main workspace"}`}],details:{type:"worktree",action:"exit",exitAction:n,previousCwd:r.previousCwd}}:{content:[{type:"text",text:`Error: ${r.error||"failed to exit worktree"}`}],details:{type:"worktree",error:r.error}}}case"list":{let n=await o.listWorktrees();if(!n.worktrees||n.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 (${n.worktrees.length}):`,""];for(let s of n.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(`
215
- `)}],details:{type:"worktree",action:"list",count:n.worktrees.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"worktree",error:"unknown_action"}}}}}}import{execFile as Kp}from"node:child_process";import{promisify as Jp}from"node:util";import{join as pt,resolve as Xi,basename as On}from"node:path";import{mkdir as Yp,rm as Xp,symlink as Zp,readdir as DT,stat as Qp}from"node:fs/promises";var mt=Jp(Kp),em=/^[a-zA-Z0-9._-]+$/,Zi=64;function tm(o){if(o.length>Zi)throw new Error(`Invalid worktree name: must be ${Zi} characters or fewer (got ${o.length})`);for(let e of o.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${o}": must not contain "." or ".." path segments`);if(!em.test(e))throw new Error(`Invalid worktree name "${o}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function ra(o){return o.replaceAll("/","+")}function om(o){return`worktree-${ra(o)}`}var ce=null;async function ue(o,e){try{let{stdout:t,stderr:n}=await mt("git",o,{cwd:e??process.cwd(),env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""},timeout:3e4});return{stdout:t,stderr:n,code:0}}catch(t){let n=t;return{stdout:n.stdout??"",stderr:n.stderr??String(t),code:n.code??1}}}async function Qi(o){let{stdout:e,code:t}=await ue(["rev-parse","--show-toplevel"],o);return t===0?e.trim():null}async function ea(o){let{stdout:e,code:t}=await ue(["status","--porcelain"],o);return t!==0?-1:e.trim().split(`
216
- `).filter(Boolean).length}async function ta(o,e){let{stdout:t,code:n}=await ue(["rev-list",`origin/${e}..${e}`,"--count"],o);return n!==0?0:parseInt(t.trim(),10)||0}async function nm(o,e,t,n){for(let r of t){if(r.includes("..")||r.startsWith("/")||r.startsWith("\\")){n?.warn(`[worktree] skipping symlink for "${r}": path traversal detected`);continue}let s=pt(o,r),i=pt(e,r);try{await Zp(s,i,"dir"),n?.info(`[worktree] symlinked ${r} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${r} (${l??"unknown"}): ${a}`)}}}async function rm(o,e,t){let{code:n,stderr:r}=await ue(["sparse-checkout","set","--cone","--",...t],o);if(n!==0)throw await ue(["worktree","remove","--force",o],e),new Error(`Failed to configure sparse-checkout: ${r}`);let{code:s,stderr:i}=await ue(["checkout","HEAD"],o);if(s!==0)throw await ue(["worktree","remove","--force",o],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function sm(){try{return await mt("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function im(o,e){return`${On(o)}_${e}`.replace(/[/.]/g,"_")}async function am(o,e){if(!await sm())return null;try{return await mt("tmux",["new-session","-d","-s",e,"-c",o],{timeout:1e4}),e}catch{return null}}async function oa(o){try{return await mt("tmux",["kill-session","-t",o],{timeout:5e3}),!0}catch{return!1}}async function na(o,e,t,n){let r=xs(e),s=pt(r,o);try{if(!(await Qp(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await mt(s,[],{cwd:e,env:{...process.env,...t},timeout:3e4});return n?.info(`[worktree] hook ${o} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return n?.warn(`[worktree] hook ${o} failed: ${i}`),null}}function sa(o){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:n}=o;return{async enterWorktree(r){try{let s=Date.now(),i=await Qi();if(!i)return{success:!1,error:"Not in a git repository"};let a=await na("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let E=process.cwd();return process.chdir(a),ce={originalCwd:E,worktreePath:a,worktreeName:r??On(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:ce.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=r??`agent-${Date.now().toString(36)}`;tm(l);let c=ra(l),u=om(l),g=pt(i,".worktrees"),d=pt(g,c);await Yp(g,{recursive:!0});let{stdout:m}=await ue(["worktree","list","--porcelain"],i),h=m.split(`
217
- `).find(E=>E.startsWith("worktree ")&&E.includes(c));if(h){let E=h.replace("worktree ","").trim(),O=process.cwd();return process.chdir(E),ce={originalCwd:O,worktreePath:E,worktreeName:l,worktreeBranch:u},e.info(`[worktree] resumed existing worktree: ${l} at ${E}`),{success:!0,worktree:{name:l,path:E,branch:u,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=n&&n.length>0,T=["worktree","add"];f&&T.push("--no-checkout"),T.push("-B",u,d,"HEAD");let{code:y,stderr:v}=await ue(T,i);if(y!==0)return{success:!1,error:`git worktree add failed: ${v.trim()}`};let _=!1;f&&n&&(await rm(d,i,n),_=!0),await nm(i,d,t,e);let M=process.cwd();process.chdir(d);let $=im(i,u),q=await am(d,$);return ce={originalCwd:M,worktreePath:d,worktreeName:l,worktreeBranch:u,tmuxSessionName:q??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:_},e.info(`[worktree] entered: ${l} at ${d}`),{success:!0,worktree:{name:l,path:d,branch:u,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(r,s){if(!ce)return{success:!1,error:"Not in a worktree"};try{let i=ce,a=await Qi(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let l=await ea(i.worktreePath),c=await ta(i.worktreePath,i.worktreeBranch);if((l>0||c>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${c} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),ce=null,i.tmuxSessionName&&await oa(i.tmuxSessionName),await na("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let u=["worktree","remove"];s&&u.push("--force"),u.push(i.worktreePath);let{code:g,stderr:d}=await ue(u,a);g!==0&&(e.warn(`[worktree] git worktree remove failed: ${d.trim()}, cleaning up manually`),await Xp(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await ue(["worktree","prune"],a)),await ue(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await oa(i.tmuxSessionName),ce=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 ue(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=r.split(`
215
+ `)}],details:{type:"worktree",action:"list",count:n.worktrees.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"worktree",error:"unknown_action"}}}}}}import{execFile as $m}from"node:child_process";import{promisify as Dm}from"node:util";import{join as xt,resolve as da,basename as Kn}from"node:path";import{mkdir as Nm,rm as Um,symlink as jm,readdir as qk,stat as Fm}from"node:fs/promises";var vt=Dm($m),Bm=/^[a-zA-Z0-9._-]+$/,pa=64;function Wm(o){if(o.length>pa)throw new Error(`Invalid worktree name: must be ${pa} characters or fewer (got ${o.length})`);for(let e of o.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${o}": must not contain "." or ".." path segments`);if(!Bm.test(e))throw new Error(`Invalid worktree name "${o}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function ba(o){return o.replaceAll("/","+")}function qm(o){return`worktree-${ba(o)}`}var me=null;async function ge(o,e){try{let{stdout:t,stderr:n}=await vt("git",o,{cwd:e??process.cwd(),env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""},timeout:3e4});return{stdout:t,stderr:n,code:0}}catch(t){let n=t;return{stdout:n.stdout??"",stderr:n.stderr??String(t),code:n.code??1}}}async function ma(o){let{stdout:e,code:t}=await ge(["rev-parse","--show-toplevel"],o);return t===0?e.trim():null}async function ga(o){let{stdout:e,code:t}=await ge(["status","--porcelain"],o);return t!==0?-1:e.trim().split(`
216
+ `).filter(Boolean).length}async function fa(o,e){let{stdout:t,code:n}=await ge(["rev-list",`origin/${e}..${e}`,"--count"],o);return n!==0?0:parseInt(t.trim(),10)||0}async function Hm(o,e,t,n){for(let r of t){if(r.includes("..")||r.startsWith("/")||r.startsWith("\\")){n?.warn(`[worktree] skipping symlink for "${r}": path traversal detected`);continue}let s=xt(o,r),i=xt(e,r);try{await jm(s,i,"dir"),n?.info(`[worktree] symlinked ${r} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${r} (${l??"unknown"}): ${a}`)}}}async function Gm(o,e,t){let{code:n,stderr:r}=await ge(["sparse-checkout","set","--cone","--",...t],o);if(n!==0)throw await ge(["worktree","remove","--force",o],e),new Error(`Failed to configure sparse-checkout: ${r}`);let{code:s,stderr:i}=await ge(["checkout","HEAD"],o);if(s!==0)throw await ge(["worktree","remove","--force",o],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function zm(){try{return await vt("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function Vm(o,e){return`${Kn(o)}_${e}`.replace(/[/.]/g,"_")}async function Km(o,e){if(!await zm())return null;try{return await vt("tmux",["new-session","-d","-s",e,"-c",o],{timeout:1e4}),e}catch{return null}}async function ha(o){try{return await vt("tmux",["kill-session","-t",o],{timeout:5e3}),!0}catch{return!1}}async function ya(o,e,t,n){let r=Ls(e),s=xt(r,o);try{if(!(await Fm(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await vt(s,[],{cwd:e,env:{...process.env,...t},timeout:3e4});return n?.info(`[worktree] hook ${o} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return n?.warn(`[worktree] hook ${o} failed: ${i}`),null}}function Ta(o){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:n}=o;return{async enterWorktree(r){try{let s=Date.now(),i=await ma();if(!i)return{success:!1,error:"Not in a git repository"};let a=await ya("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let D=process.cwd();return process.chdir(a),me={originalCwd:D,worktreePath:a,worktreeName:r??Kn(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:me.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=r??`agent-${Date.now().toString(36)}`;Wm(l);let c=ba(l),u=qm(l),p=xt(i,".worktrees"),d=xt(p,c);await Nm(p,{recursive:!0});let{stdout:m}=await ge(["worktree","list","--porcelain"],i),y=m.split(`
217
+ `).find(D=>D.startsWith("worktree ")&&D.includes(c));if(y){let D=y.replace("worktree ","").trim(),F=process.cwd();return process.chdir(D),me={originalCwd:F,worktreePath:D,worktreeName:l,worktreeBranch:u},e.info(`[worktree] resumed existing worktree: ${l} at ${D}`),{success:!0,worktree:{name:l,path:D,branch:u,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let h=n&&n.length>0,k=["worktree","add"];h&&k.push("--no-checkout"),k.push("-B",u,d,"HEAD");let{code:w,stderr:f}=await ge(k,i);if(w!==0)return{success:!1,error:`git worktree add failed: ${f.trim()}`};let C=!1;h&&n&&(await Gm(d,i,n),C=!0),await Hm(i,d,t,e);let R=process.cwd();process.chdir(d);let L=Vm(i,u),K=await Km(d,L);return me={originalCwd:R,worktreePath:d,worktreeName:l,worktreeBranch:u,tmuxSessionName:K??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:C},e.info(`[worktree] entered: ${l} at ${d}`),{success:!0,worktree:{name:l,path:d,branch:u,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(r,s){if(!me)return{success:!1,error:"Not in a worktree"};try{let i=me,a=await ma(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let l=await ga(i.worktreePath),c=await fa(i.worktreePath,i.worktreeBranch);if((l>0||c>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${c} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),me=null,i.tmuxSessionName&&await ha(i.tmuxSessionName),await ya("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let u=["worktree","remove"];s&&u.push("--force"),u.push(i.worktreePath);let{code:p,stderr:d}=await ge(u,a);p!==0&&(e.warn(`[worktree] git worktree remove failed: ${d.trim()}, cleaning up manually`),await Um(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await ge(["worktree","prune"],a)),await ge(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await ha(i.tmuxSessionName),me=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 ge(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=r.split(`
218
218
 
219
219
  `).filter(Boolean);for(let c of l){let u=c.split(`
220
- `),g="",d="";for(let T of u)T.startsWith("worktree ")&&(g=T.slice(9).trim()),T.startsWith("branch ")&&(d=T.slice(7).trim().replace("refs/heads/",""));if(!g)continue;let m=Xi(g)===Xi(a),h=await ea(g),f=await ta(g,d);i.push({name:d.startsWith("worktree-")?d.slice(9):On(g),path:g,branch:d,isCurrent:m,hasChanges:h>0,unpushedCommits:f})}return{success:!0,worktrees:i}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}},isInWorktree(){return ce!==null},currentWorktree(){return ce?{name:ce.worktreeName,path:ce.worktreePath,branch:ce.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as lm,writeFile as cm}from"node:fs/promises";import*as ia from"node:path";var um={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 aa(o){let e=o.split(`
220
+ `),p="",d="";for(let k of u)k.startsWith("worktree ")&&(p=k.slice(9).trim()),k.startsWith("branch ")&&(d=k.slice(7).trim().replace("refs/heads/",""));if(!p)continue;let m=da(p)===da(a),y=await ga(p),h=await fa(p,d);i.push({name:d.startsWith("worktree-")?d.slice(9):Kn(p),path:p,branch:d,isCurrent:m,hasChanges:y>0,unpushedCommits:h})}return{success:!0,worktrees:i}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}},isInWorktree(){return me!==null},currentWorktree(){return me?{name:me.worktreeName,path:me.worktreePath,branch:me.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as Jm,writeFile as Ym}from"node:fs/promises";import*as ka from"node:path";var Xm={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 xa(o){let e=o.split(`
221
221
  `);return e.map((t,n)=>n<e.length-1?t+`
222
- `:t)}function la(o){return o.join("")}function dm(o,e){let t=la(o.source).trim(),n=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${o.cell_type}]: ${n}`}function pm(o,e){let t={cell_type:o,source:aa(e),metadata:{}};return o==="code"&&(t.execution_count=null,t.outputs=[]),t}function ca(){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:um,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"jupyter notebook ipynb cell edit insert delete",execute:async(o,e)=>{let{notebook_path:t,cell_number:n,edit_mode:r="replace"}=e,s=ia.extname(t).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 lm(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.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,c=n-1;if(r==="insert"){if(n<0||n>l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(c<0||c>=l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let u;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 m=a.cells[c],h=la(m.source);m.source=aa(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),u=`Replaced cell ${n} [${m.cell_type}].
223
- Old: ${h.slice(0,120)}${h.length>120?"...":""}
224
- 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 m=e.cell_type??"code",h=pm(m,e.new_source);a.cells.splice(n,0,h),u=`Inserted new ${m} cell after position ${n}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(c,1)[0];u=`Deleted cell ${n} [${m.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 m=JSON.stringify(a,null,1)+`
225
- `;await cm(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let g=a.cells.slice(0,10).map((m,h)=>dm(m,h)).join(`
222
+ `:t)}function va(o){return o.join("")}function Qm(o,e){let t=va(o.source).trim(),n=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${o.cell_type}]: ${n}`}function Zm(o,e){let t={cell_type:o,source:xa(e),metadata:{}};return o==="code"&&(t.execution_count=null,t.outputs=[]),t}function wa(){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:Xm,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"jupyter notebook ipynb cell edit insert delete",execute:async(o,e)=>{let{notebook_path:t,cell_number:n,edit_mode:r="replace"}=e,s=ka.extname(t).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 Jm(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.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,c=n-1;if(r==="insert"){if(n<0||n>l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(c<0||c>=l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let u;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 m=a.cells[c],y=va(m.source);m.source=xa(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),u=`Replaced cell ${n} [${m.cell_type}].
223
+ Old: ${y.slice(0,120)}${y.length>120?"...":""}
224
+ 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 m=e.cell_type??"code",y=Zm(m,e.new_source);a.cells.splice(n,0,y),u=`Inserted new ${m} cell after position ${n}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(c,1)[0];u=`Deleted cell ${n} [${m.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 m=JSON.stringify(a,null,1)+`
225
+ `;await Ym(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let p=a.cells.slice(0,10).map((m,y)=>Qm(m,y)).join(`
226
226
  `),d=a.cells.length>10?`
227
227
  ... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${u}
228
228
 
229
229
  Current cells:
230
- ${g}${d}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:n,total_cells:a.cells.length}}}}}import{readFile as mm,readdir as gm}from"node:fs/promises";import*as da from"node:path";import{existsSync as fm}from"node:fs";var hm={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
230
+ ${p}${d}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:n,total_cells:a.cells.length}}}}}import{readFile as eg,readdir as tg}from"node:fs/promises";import*as Ca from"node:path";import{existsSync as og}from"node:fs";var ng={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
231
231
  run: Execute a workflow by name.
232
- 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 Ln(o){let e=new Map,t=bs(o);await ua(t,e);let n=hs();return await ua(n,e),e}async function ua(o,e){if(fm(o))try{let t=await gm(o,{withFileTypes:!0});for(let n of t)if(n.isFile()&&n.name.endsWith(".json")){let r=n.name.replace(/\.json$/,"");e.has(r)||e.set(r,da.join(o,n.name))}}catch{}}async function $n(o){let e=await mm(o,"utf-8");return JSON.parse(e)}function ym(o){let e=new Map(o.map(s=>[s.id,s])),t=new Set,n=[];function r(s,i){if(t.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),t.add(s),n.push(a)}for(let s of o)r(s.id,new Set);return n}function bm(o,e,t){let n={};for(let[r,s]of Object.entries(o))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)=>t.get(l)?.output??""),n[r]=i}else n[r]=s;return n}function pa(o){return{name:"workflow",label:"Workflow",description:"Execute predefined automation workflows. Workflows are step-based pipelines defined as JSON files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/. Steps run in dependency order, support variable interpolation, and can reference previous step outputs via ${step.<id>.result}.",parameters:hm,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"workflow pipeline automation steps DAG",execute:async(e,t,n)=>{let r=o.getCwd();switch(t.action){case"list":{let s=await Ln(r);if(s.size===0)return{content:[{type:"text",text:"No workflows found. Create .json files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/."}],details:{type:"workflow",action:"list",count:0}};let i=["Available workflows:"];for(let[a,l]of s)try{let c=await $n(l);i.push(` - ${a}: ${c.description??"(no description)"} (${c.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
233
- `)}],details:{type:"workflow",action:"list",count:s.size}}}case"describe":{if(!t.workflow)return{content:[{type:"text",text:"Error: 'workflow' parameter is required for 'describe'."}],details:{error:"missing_workflow"}};let i=(await Ln(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await $n(i),l=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let c of a.steps){let u=c.dependsOn?.length?` (after: ${c.dependsOn.join(", ")})`:"";l.push(` ${c.id}: ${c.label??c.tool}${u}`),l.push(` tool: ${c.tool}`),l.push(` args: ${JSON.stringify(c.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){l.push("","Variables (defaults):");for(let[c,u]of Object.entries(a.variables))l.push(` ${c} = ${u}`)}return{content:[{type:"text",text:l.filter(Boolean).join(`
234
- `)}],details:{type:"workflow",action:"describe",workflow:a.name}}}case"run":{if(!t.workflow)return{content:[{type:"text",text:"Error: 'workflow' parameter is required for 'run'."}],details:{error:"missing_workflow"}};let i=(await Ln(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await $n(i),l={...a.variables,...t.variables},c;try{c=ym(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let u=new Map,g=[`Running workflow: ${a.name}`,""],d=!0;for(let m of c){if(n?.aborted){g.push(`\u26A1 Aborted at step: ${m.id}`),d=!1;break}let h=(m.dependsOn??[]).some(y=>!u.get(y)?.success),f=m.condition??"on_success";if(f==="on_success"&&h){g.push(`\u23ED Skipped ${m.id} (dependency failed)`),u.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),d=!1;continue}if(f==="on_failure"&&!h){g.push(`\u23ED Skipped ${m.id} (no failure to handle)`),u.set(m.id,{stepId:m.id,success:!0,output:""});continue}g.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let T=bm(m.args,l,u);try{let y=await o.invokeTool(m.tool,T,n),v=!y.error;if(u.set(m.id,{stepId:m.id,success:v,output:y.result,error:y.error}),v){let _=y.result.length>200?y.result.slice(0,200)+"...":y.result;g.push(` \u2705 ${_}`)}else g.push(` \u274C ${y.error}`),d=!1}catch(y){let v=y.message;u.set(m.id,{stepId:m.id,success:!1,output:"",error:v}),g.push(` \u274C ${v}`),d=!1}}return g.push("",d?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:g.join(`
235
- `)}],details:{type:"workflow",action:"run",workflow:a.name,success:d,stepsExecuted:u.size,totalSteps:a.steps.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}". Use list, run, or describe.`}],details:{error:"unknown_action"}}}}}}var Tm="sleep",km={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 ma(o){return{name:Tm,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(`
236
- `),parameters:km,execute:async(e,t,n)=>{let r=Math.max(1,Math.min(3600,Math.round(t.duration))),s=r*1e3,i=new AbortController,a=()=>i.abort();n?.addEventListener("abort",a,{once:!0}),n?.aborted&&i.abort();try{let l=await o.sleep(s,i.signal),c=[];return l.interrupted?(c.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&c.push(`Reason: ${l.interruptReason}`),c.push("Check for new messages or tasks.")):c.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:c.join(`
237
- `)}],details:{...l,requestedSeconds:r}}}finally{n?.removeEventListener("abort",a)}}}}var xm="tool_search",vm={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"]},wm=5;function fa(o){return{name:xm,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:vm,execute:async(e,t)=>{if(!t.query||t.query.trim().length===0)return{content:[{type:"text",text:"Error: query is required."}],details:{type:"tool_search",error:"empty_query"}};let n=t.query.trim(),r=t.maxResults??wm;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(u=>u.trim()).filter(Boolean),a=[],l=[];if(o.activateTool)for(let u of i)await o.activateTool(u)?a.push(u):l.push(u);else{let u=await o.searchTools(n,{maxResults:r});return ga(u)}let c=[];return a.length>0&&c.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&c.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:c.join(`
238
- `)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await o.searchTools(n,{maxResults:r});return ga(s)}}}function ga(o){if(o.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${o.query}". Total deferred tools available: ${o.totalDeferred}.`}],details:{type:"tool_search",query:o.query,matchCount:0,totalDeferred:o.totalDeferred}};let e=[`Found ${o.matches.length} tool(s) matching "${o.query}" (${o.totalDeferred} total deferred):`,""];for(let t of o.matches)e.push(`- **${t.name}**: ${t.description}`);return e.push(""),e.push('Use "select:toolName" to activate a tool for use in subsequent messages.'),{content:[{type:"text",text:e.join(`
239
- `)}],details:{type:"tool_search",query:o.query,matchCount:o.matches.length,totalDeferred:o.totalDeferred,matches:o.matches.map(t=>t.name)}}}var Sm="image_generate",Cm={type:"object",properties:{prompt:{type:"string",description:"Image generation prompt. Enrich vague requests with style, lighting, composition, color, mood details."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video-cover', 'phone-wallpaper', 'avatar', 'poster', etc."},style:{type:"string",description:"Visual art style: 'photorealistic', 'anime', 'watercolor', 'oil-painting', '3d-render', etc."},size:{type:"string",description:"Dimensions: e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Default: '1024x1024'."},image_url:{type:"string",description:"Reference image URL for image-to-image generation (img2img). Character reference sheet or style transfer."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."}},required:["prompt"]};function ha(o){return{name:Sm,label:"Image Generate",description:"Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately.",parameters:Cm,execute:async(e,t)=>{let n=await o.generateImage({prompt:t.prompt,purpose:t.purpose,style:t.style,size:t.size,imageUrl:t.image_url,n:t.n}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} image${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var _m={type:"object",properties:{text:{type:"string",description:"Text to convert to speech."},channel:{type:"string",description:"Optional channel id to pick output format (e.g. telegram)."}},required:["text"]};function ya(o){return{name:"tts",label:"TTS",description:"Convert text to speech (TTS) \u2014 read text aloud as spoken audio. Use for narration, voice messages, or any spoken-word output. DO NOT use for music, songs, or melodies \u2014 use music_generate instead.",parameters:_m,execute:async(e,t)=>{let n=await o.textToSpeech({text:t.text,channel:t.channel});return{content:[{type:"text",text:"\u5DF2\u6210\u529F\u751F\u6210\u8BED\u97F3\u3002"}],details:{type:"tts",audioPath:n.audioPath,provider:n.provider,voiceCompatible:n.voiceCompatible,mediaUrls:n.mediaUrls}}}}}var Rm="video_generate",Mm={type:"object",properties:{prompt:{type:"string",description:"Video generation prompt. MUST be in English. Include scene, movement, camera motion, lighting, style."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video', 'presentation', etc."},style:{type:"string",description:"Visual style: 'cinematic', 'anime', 'watercolor', etc."},image_url:{type:"string",description:"Reference image for image-to-video. Preview image from storyboard Step 3, or user-uploaded image."},aspect_ratio:{type:"string",description:"Video aspect ratio: '9:16' (vertical), '16:9' (horizontal), '1:1' (square). Default: '16:9'."},duration:{type:"number",description:"Video duration in seconds (3-10s single-shot, >10s requires multi-shot workflow). Must be confirmed by user."}},required:["prompt"]};function ba(o){return{name:Rm,label:"Video Generate",description:"Generate a short video clip from a text prompt (and optional reference image). Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Single-shot: 3\u201310s. For longer videos (>10s), use multi-shot storyboard workflow.",parameters:Mm,execute:async(e,t)=>{let n=await o.generateVideo({prompt:t.prompt,purpose:t.purpose,style:t.style,imageUrl:t.image_url,aspectRatio:t.aspect_ratio,duration:t.duration}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} video${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var Pm="music_generate",Am={type:"object",properties:{prompt:{type:"string",description:"Music generation prompt. MUST be in English. Include genre, mood, tempo, instruments, and atmosphere details."},purpose:{type:"string",description:"Intended use: 'background-music', 'ringtone', 'short-video-bgm', 'full-song', 'notification-sound', etc."},style:{type:"string",description:"Musical style/genre: 'lo-fi', 'pop', 'rock', 'jazz', 'classical', 'electronic', 'ambient', etc."},lyrics:{type:"string",description:"Optional lyrics for vocal music. Structure with [verse], [chorus], [bridge] tags if desired."},duration:{type:"number",description:"Duration in seconds (5-300). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s."}},required:["prompt"]};function Ta(o){return{name:Pm,label:"Music Generate",description:"Generate music, songs, or melodies from text descriptions. Prompt MUST be in English. Supports lyrics for vocal songs. DO NOT use for spoken-word audio or TTS \u2014 use tts tool instead.",parameters:Am,execute:async(e,t)=>{let n=await o.generateMusic({prompt:t.prompt,purpose:t.purpose,style:t.style,lyrics:t.lyrics,duration:t.duration}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} audio track${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"music_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var Em="video_edit",Im={type:"object",properties:{prompt:{type:"string",description:"Edit instruction. Reference videos as \u89C6\u98911, \u89C6\u98912, \u89C6\u98913. Reference images as \u56FE\u72471, \u56FE\u72472. Operations: add/remove/modify elements, extend, track fill."},source_videos:{type:"array",items:{type:"string"},minItems:1,maxItems:3,description:"Video(s) to edit (1-3 URLs). Order: [0]=\u89C6\u98911, [1]=\u89C6\u98912, [2]=\u89C6\u98913."},reference_images:{type:"array",items:{type:"string"},description:"Optional reference images for element replacement (up to 9)."},duration:{type:"number",description:"Output duration in seconds (4-15s). Default: same as source."},aspect_ratio:{type:"string",description:"Output aspect ratio: 16:9, 9:16, 1:1, 4:3, 3:4, 21:9. Default: same as source."},resolution:{type:"string",description:"Output resolution: '480p' or '720p'. Default: '720p'."}},required:["prompt","source_videos"]};function ka(o){return{name:Em,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos. Max 3 source videos, max 720p. For generating NEW videos from scratch, use video_generate instead.",parameters:Im,execute:async(e,t)=>{if(!t.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await o.editVideo({prompt:t.prompt,sourceVideos:t.source_videos,referenceImages:t.reference_images,duration:t.duration,aspectRatio:t.aspect_ratio,resolution:t.resolution});return{content:[{type:"text",text:`Video edited successfully${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_edit",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var Om="video_merge",Lm={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video file path."},audio:{type:"string",description:"Narration audio file path (from TTS)."},trimStart:{type:"number",description:"Trim start in seconds (default 0)."},trimEnd:{type:"number",description:"Trim end in seconds (default: full)."}},required:["video"]},minItems:2,description:"Array of video clips to merge, in order."},transition:{type:"string",description:"Transition effect: 'crossfade' (default), 'fade', 'wipeleft', 'cut', 'dissolve', etc."},transitionDuration:{type:"number",description:"Transition duration in seconds (0.1-2.0, default 0.5)."},subtitles:{type:"string",description:"Path to SRT subtitle file to burn-in."},bgm:{type:"string",description:"Background music file path."},bgmVolume:{type:"number",description:"BGM volume (0.0-1.0, default 0.15)."},outputResolution:{type:"string",description:"Output resolution: '1920x1080', '1080x1920', etc. Default: auto."},outputFps:{type:"number",description:"Output FPS (default 30)."}},required:["clips"]};function xa(o){return{name:Om,label:"Video Merge",description:"Merge multiple video clips into a single video with transitions, subtitles, and background music. Requires at least 2 clips. Supports crossfade, fade, wipe, dissolve, and cut transitions. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:Lm,execute:async(e,t)=>{if(!t.clips||t.clips.length<2)return{content:[{type:"text",text:"Error: at least 2 clips are required for merging."}]};let n=await o.mergeVideos({clips:t.clips,transition:t.transition,transitionDuration:t.transitionDuration,subtitles:t.subtitles,bgm:t.bgm,bgmVolume:t.bgmVolume,outputResolution:t.outputResolution,outputFps:t.outputFps});return{content:[{type:"text",text:`Merged ${n.clipCount} clips \u2192 ${n.durationSec.toFixed(1)}s video`+(t.transition?` (transition: ${t.transition})`:"")}],details:{type:"video_merge",localPath:n.localPath,servePath:n.servePath,durationSec:n.durationSec,clipCount:n.clipCount,mediaUrls:n.mediaUrls}}}}}var $m="video_upscale",Dm={type:"object",properties:{video:{type:"string",description:"Video file path (local or serve path)."},targetResolution:{type:"string",description:"Target resolution: '1080p' (default, 1920x1080/1080x1920), '2k' (2560x1440/1440x2560)."},sharpness:{type:"string",description:"Sharpening intensity: 'light' (default), 'medium', 'strong'."}},required:["video"]};function va(o){return{name:$m,label:"Video Upscale",description:"Upscale a video to higher resolution with optional sharpening. Auto-detects orientation (landscape/portrait). Uses Lanczos interpolation + unsharp mask. Supports 1080p and 2K targets. Best used as post-processing after video_merge.",parameters:Dm,execute:async(e,t)=>{let n=await o.upscaleVideo({video:t.video,targetResolution:t.targetResolution,sharpness:t.sharpness});return{content:[{type:"text",text:`Upscaled to ${n.resolution}${t.sharpness?` (sharpness: ${t.sharpness})`:""}`}],details:{type:"video_upscale",localPath:n.localPath,servePath:n.servePath,resolution:n.resolution,durationSec:n.durationSec,mediaUrls:n.mediaUrls}}}}}var H;function Sa(o){H=o}var Oe=process.cwd();function se(o){return j.isAbsolute(o)?j.normalize(o):j.resolve(Oe,o)}var jm=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),Ca=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]);function Fm(){return{resolvePath:se,async readFile(o){let e=se(o),t=j.extname(e).toLowerCase();if(Ca.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(jm.has(t)){let r=await A.promises.readFile(e),s=t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg";return{type:"image",base64:r.toString("base64"),mimeType:s}}return{type:"text",text:await A.promises.readFile(e,"utf8")}},validatePath(o){let e=se(o);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function Um(){return{resolvePath:se,async writeFile(o,e){let t=se(o);await A.promises.mkdir(j.dirname(t),{recursive:!0}),await A.promises.writeFile(t,e,"utf8")}}}function Bm(){return{resolvePath:se,async readFile(o){let e=se(o);return A.promises.readFile(e,"utf8")},async writeFile(o,e){let t=se(o);await A.promises.mkdir(j.dirname(t),{recursive:!0}),await A.promises.writeFile(t,e,"utf8")}}}function qm(){return{resolvePath:se,async readFile(o){let e=se(o);return A.promises.readFile(e,"utf8")},async writeFile(o,e){let t=se(o);await A.promises.mkdir(j.dirname(t),{recursive:!0}),await A.promises.writeFile(t,e,"utf8")},async deleteFile(o){let e=se(o);await A.promises.unlink(e)},async fileExists(o){let e=se(o);try{return await A.promises.access(e),!0}catch{return!1}}}}function Wm(){return{resolvePath:se,async glob(o,e){let t=e.cwd||Oe,n=e.limit||1e3,r=[],s=!1,i=o.replace(/\\/g,"/").split("/"),a=i.some(u=>u==="**"),l=i[i.length-1]??"*",c=_a(l);try{await Dn(t,async u=>{if(r.length>=n)return s=!0,!1;let g=j.basename(u);return c.test(g)&&r.push(u),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(o,e){let t=e.cwd||Oe;try{return await Gm(o,t,e)}catch{return await zm(o,t,e)}}}}function _a(o){let e=o.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(t,n)=>"("+n.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var Hm=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function Dn(o,e,t,n=0,r=""){if(n>t)return;let s;try{s=await A.promises.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(Hm.has(i.name))continue;await Dn(j.join(o,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function Gm(o,e,t){return new Promise((n,r)=>{let s=["--json","--no-heading","--max-columns","500"];t.caseInsensitive&&s.push("-i"),t.contextLines&&s.push("-C",String(t.contextLines)),t.fileGlob&&s.push("-g",t.fileGlob),s.push("--max-count",String(t.headLimit??250)),s.push(o),s.push("."),Nm("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 d of a.split(`
240
- `))if(d.trim())try{let m=JSON.parse(d);m.type==="match"&&m.data&&l.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let c=t.headLimit??250,u=t.offset??0,g=l.slice(u,u+c);n({matches:g,truncated:l.length>u+c})})})}async function zm(o,e,t){let n=new RegExp(o,t.caseInsensitive?"i":""),r=t.headLimit??250,s=t.offset??0,i=t.fileGlob?_a(t.fileGlob):null,a=[],l=!1;return await Dn(e,async c=>{if(a.length>=s+r+1)return l=!0,!1;if(i&&!i.test(j.basename(c)))return!0;let u=j.extname(c).toLowerCase();if(Ca.has(u))return!0;try{let d=(await A.promises.readFile(j.join(e,c),"utf8")).split(`
241
- `);for(let m=0;m<d.length;m++)if(n.test(d[m])&&(a.push({path:c,line:m+1,text:d[m].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 wa=!1;function Vm(){if(!wa)if(wa=!0,jt()){let o=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";dt(Rn(o))}else if(process.platform==="win32"){let o=Km();dt(zt(o))}else{let o=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";dt(zt(o))}}function Km(){let o=process.env.QLOGICAGENT_BASH_PATH;if(o&&A.existsSync(o))return o;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],t=process.env.ProgramFiles?j.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let n of e)if(A.existsSync(n))return n;return"bash"}function Jm(){return{async fetchUrl(o){let e=new AbortController,t=setTimeout(()=>e.abort(),3e4);try{let n=await fetch(o.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(!n.ok)return{content:`HTTP ${n.status} ${n.statusText}`};let r=n.headers.get("content-type")??"",s=await n.text();return o.maxChars&&s.length>o.maxChars&&(s=s.slice(0,o.maxChars)),r.includes("html")&&o.extractMode!=="json"&&(s=Ym(s)),{content:s,title:Xm(s)}}finally{clearTimeout(t)}}}}function Ym(o){return o.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s{2,}/g," ").trim()}function Xm(o){return o.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function Zm(){return{async search(o,e){let t=process.env.SEARXNG_BASE_URL?.trim();if(!t)return{query:o,results:[],totalResults:0};let n=e?.maxResults??10,r=new URL("/search",t);r.searchParams.set("q",o),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:o,results:[]};let l=await a.json(),c=(l.results??[]).slice(0,n).map(u=>({title:u.title??"",url:u.url??"",snippet:u.content??""}));if(e?.allowedDomains?.length){let u=new Set(e.allowedDomains.map(g=>g.toLowerCase()));return{query:o,results:c.filter(g=>{try{return u.has(new URL(g.url).hostname.toLowerCase())}catch{return!1}})}}if(e?.blockedDomains?.length){let u=new Set(e.blockedDomains.map(g=>g.toLowerCase()));return{query:o,results:c.filter(g=>{try{return!u.has(new URL(g.url).hostname.toLowerCase())}catch{return!0}})}}return{query:o,results:c,totalResults:l.number_of_results}}finally{clearTimeout(i)}}}}function Qm(){let o=j.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(r){return j.join(o,"projects",r,".instructions")}function t(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=j.resolve(i,s);if(!a.startsWith(i+j.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(r,s){if(!A.existsSync(r))return[];let i=[];for(let a of A.readdirSync(r,{withFileTypes:!0})){let l=j.join(r,a.name);if(a.isDirectory())i.push(...n(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let c=A.statSync(l);i.push({filename:j.relative(s,l).replace(/\\/g,"/"),path:l,size:c.size,updatedAt:c.mtime.toISOString(),content:A.readFileSync(l,"utf-8")})}}return i}return{list(r){let s=e(r);return n(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(r,s){try{let i=t(r,s);if(!A.existsSync(i))return null;let a=A.statSync(i),l=A.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=t(r,s);A.mkdirSync(j.dirname(a),{recursive:!0}),A.writeFileSync(a,i,"utf-8");let l=A.statSync(a);return{filename:s,path:a,size:l.size,updatedAt:l.mtime.toISOString(),content:i}},remove(r,s){try{let i=t(r,s);return A.existsSync(i)?(A.unlinkSync(i),!0):!1}catch{return!1}}}}function eg(o){o?.workdir&&(Oe=o.workdir),Vm(),Wt(Oe);let e=[];e.push(pi()),e.push(gi()),e.push(Mi({onProgress:o?.onExecProgress,interpretExitCode:(c,u)=>{if(c===127)return"command not found";if(c===126)return"permission denied";if(c===137)return"killed (SIGKILL / OOM)";if(c===143)return"terminated (SIGTERM)";if(c===130)return"interrupted (Ctrl+C)"}}));let t=Fm(),n=Um(),r=Bm(),s=qm();e.push(Ei(t)),e.push(Oi(n)),e.push(Li(r)),e.push(In(s)),e.push(ji(s)),e.push(Ni(Wm())),e.push(Vi(Jm())),e.push(Ki(Zm()));let i=Qm();e.push(Ji(i));let a=o?.log??{info:()=>{},warn:()=>{}};e.push(Yi(sa({log:a}))),e.push(ca());let l={invokeTool:async(c,u,g)=>{let d=Ee(c);if(!d)return{result:"",error:`Unknown tool: ${c}`};try{let m=await d.execute(`wf_${Date.now()}`,u,g);return{result:m.content.map(f=>f.text??"").join(`
242
- `),error:m.details?.error}}catch(m){return{result:"",error:m.message}}},getCwd:()=>Oe};return e.push(pa(l)),e.push(ma({sleep:(c,u)=>new Promise(g=>{let d=Date.now(),m=setTimeout(()=>{g({sleptSeconds:Math.round((Date.now()-d)/1e3),interrupted:!1})},c),h=()=>{clearTimeout(m),g({sleptSeconds:Math.round((Date.now()-d)/1e3),interrupted:!0,interruptReason:"aborted"})};u.addEventListener("abort",h,{once:!0}),u.aborted&&(clearTimeout(m),h())})})),e.push(fa({searchTools:async(c,u)=>{let g=u?.maxResults??5,d=c.toLowerCase(),m=ve();return{matches:m.map(f=>{let T=Ee(f),y=`${f} ${T?.description??""} ${T?.searchHint??""}`.toLowerCase();return{name:f,description:T?.description??"",searchHint:T?.searchHint,score:y.includes(d)?1:0}}).filter(f=>f.score>0).slice(0,g),query:c,totalDeferred:m.length}}})),e.push({...ha({generateImage:async c=>H?.imageEndpoint?(await fetch(H.imageEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json():{mediaUrls:[],model:"none",durationMs:0,size:""}}),isEnabled:()=>!!H?.imageEndpoint}),e.push({...ya({textToSpeech:async c=>H?.ttsEndpoint?(await fetch(H.ttsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json():{audioPath:"",mediaUrls:[],provider:"none"}}),isEnabled:()=>!!H?.ttsEndpoint}),e.push({...ba({generateVideo:async c=>{if(!H?.videoEndpoint)throw new Error("Video generation not configured");return(await fetch(H.videoEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()}}),isEnabled:()=>!!H?.videoEndpoint}),e.push({...Ta({generateMusic:async c=>{if(!H?.musicEndpoint)throw new Error("Music generation not configured");return(await fetch(H.musicEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()}}),isEnabled:()=>!!H?.musicEndpoint}),e.push({...ka({editVideo:async c=>{if(!H?.videoEditEndpoint)throw new Error("Video editing not configured");return(await fetch(H.videoEditEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()}}),isEnabled:()=>!!H?.videoEditEndpoint}),e.push({...xa({mergeVideos:async c=>{if(!H?.videoMergeEndpoint)throw new Error("Video merging not configured");return(await fetch(H.videoMergeEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()}}),isEnabled:()=>!!H?.videoMergeEndpoint}),e.push({...va({upscaleVideo:async c=>{if(!H?.videoUpscaleEndpoint)throw new Error("Video upscaling not configured");return(await fetch(H.videoUpscaleEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()}}),isEnabled:()=>!!H?.videoUpscaleEndpoint}),di(e),o?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(c=>c.isEnabled?.()!==!1).length} enabled): ${ve().join(", ")}`),e}var Ra=eg;function Nn(o){Oe=o,Wt(o)}import{spawn as tg}from"node:child_process";import{createInterface as og}from"node:readline";var Vt=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=tg(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:e,cwd:this.config.cwd,windowsHide:!0}),this.process.on("error",n=>{this.handleProcessError(n)}),this.process.on("exit",n=>{this.handleProcessExit(n)}),this.process.stderr?.on("data",n=>{this.stderrBuffer+=n.toString(),this.stderrBuffer.length>4096&&(this.stderrBuffer=this.stderrBuffer.slice(-4096))}),this.readline=og({input:this.process.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.readline.on("line",n=>this.handleLine(n));let t=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"qlogicagent",version:"0.3.0"}},this.config.initTimeoutMs??3e4);this.serverName=t.serverInfo?.name??this.config.name,this.serverVersion=t.serverInfo?.version??"unknown",this.supportsToolsListChanged=t.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,t,n){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:t??{}},12e4,n)}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=ng(this.config.name);return this.toolsCache.map(t=>({name:`mcp__${e}__${t.name}`,label:`[${this.config.name}] ${t.name}`,description:t.description??`MCP tool from ${this.config.name}`,parameters:t.inputSchema??{type:"object",properties:{}},isConcurrencySafe:!0,isReadOnly:!1,searchHint:`mcp ${this.config.name} ${t.name}`,execute:async(n,r,s)=>this.executeAsTool(t.name,r,s)}))}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,t,n){try{let r=await this.callTool(e,t,n);return{content:[{type:"text",text:r.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
243
- `)||"(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,t,n=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:t},c=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${n}ms`))},n),u=()=>{clearTimeout(c),this.pending.delete(a)};r?.addEventListener("abort",()=>{u(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:g=>{u(),g.error?i(new Error(`MCP error ${g.error.code}: ${g.error.message}`)):s(g.result)},reject:g=>{u(),i(g)}}),this.writeLine(JSON.stringify(l))})}sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t};this.writeLine(JSON.stringify(n))}writeLine(e){this.process?.stdin?.writable&&this.process.stdin.write(e+`
244
- `)}handleLine(e){let t=e.trim();if(!t)return;let n;try{n=JSON.parse(t)}catch{return}if("id"in n&&("result"in n||"error"in n)){let r=n.id,s=this.pending.get(r);s&&s.resolve(n)}else"method"in n&&!("id"in n)&&this.handleNotification(n)}handleNotification(e){e.method==="notifications/tools/list_changed"&&this.refreshTools().then(()=>{this.onToolsChanged?.()}).catch(()=>{})}handleProcessError(e){this.connected=!1;for(let[,t]of this.pending)t.reject(new Error(`MCP process error: ${e.message}`));this.pending.clear()}handleProcessExit(e){this.connected=!1;for(let[,t]of this.pending)t.reject(new Error(`MCP process exited with code ${e}`));this.pending.clear()}};function ng(o){return o.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as rg}from"node:crypto";var Kt=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,t,n){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:t??{}},this.config.toolCallTimeoutMs??12e4,n)}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,t,n=3e4,r){let s=rg(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,l=setTimeout(()=>a.abort(),n);r&&r.addEventListener("abort",()=>a.abort(),{once:!0});try{let c={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(c["Mcp-Session-Id"]=this.sessionId);let u=await fetch(this.config.url,{method:"POST",headers:c,body:JSON.stringify(i),signal:a.signal}),g=u.headers.get("mcp-session-id");if(g&&(this.sessionId=g),!u.ok)throw new Error(`MCP HTTP error ${u.status}: ${u.statusText}`);if((u.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(u,s);let m=await u.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(l)}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t},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(n)}).catch(()=>{})}async parseSSEResponse(e,t){let n=e.body;if(!n)throw new Error("MCP SSE response has no body");let r=n.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 c=i.split(`
245
- `);i=c.pop()??"";for(let u of c){if(!u.startsWith("data: "))continue;let g=u.slice(6).trim();if(g)try{let d=JSON.parse(g);if("method"in d&&d.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(d.id===t){if(d.error)throw new Error(`MCP error ${d.error.code}: ${d.error.message}`);return d.result}}catch(d){if(d instanceof Error&&d.message.startsWith("MCP error"))throw d}}}}finally{r.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${sg(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 t.callTool(e.name,s,i);return{content:[{type:"text",text:(a.content??[]).filter(u=>u.type==="text"&&u.text).map(u=>u.text).join(`
246
- `)||"(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 sg(o){return o.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Jt=class{clients=new Map;injected=!1;log;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}};for(let t of e.servers){if(t.disabled)continue;if((t.type??(t.url?"http":"stdio"))==="http"){if(!t.url){this.log.warn(`[mcp] server "${t.name}" is type "http" but has no url, skipping`);continue}let r={name:t.name,url:t.url,headers:t.headers,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new Kt(r))}else{if(!t.command){this.log.warn(`[mcp] server "${t.name}" is type "stdio" but has no command, skipping`);continue}let r={name:t.name,command:t.command,args:t.args,env:t.env,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new Vt(r))}}}async connectAll(){let e=Array.from(this.clients.entries()).map(async([t,n])=>{try{await n.connect(),this.log.info(`[mcp] connected to ${t} (${n.info.name} v${n.info.version})`),n.setOnToolsChanged(()=>{this.log.info(`[mcp] tools changed on ${t}, re-injecting`),this.injected&&this.reinjectTools(t,n)})}catch(r){this.log.warn(`[mcp] failed to connect to ${t}: ${r instanceof Error?r.message:r}`)}});await Promise.allSettled(e)}injectTools(){this.injected=!0;for(let[e,t]of this.clients){if(!t.isConnected)continue;let n=t.toPortableTools();pn(n),this.log.info(`[mcp] injected ${n.length} tools from ${e}`)}}getConnectedServers(){return Array.from(this.clients.entries()).filter(([,e])=>e.isConnected).map(([e])=>e)}getToolCount(){let e=0;for(let t of this.clients.values())t.isConnected&&(e+=t.getCachedTools().length);return e}async disconnectAll(){let e=Array.from(this.clients.values()).map(async t=>{try{await t.disconnect()}catch{}});await Promise.allSettled(e),this.clients.clear(),this.injected=!1}async listResources(e){let t=e?[[e,this.clients.get(e)]].filter(([,r])=>r):Array.from(this.clients.entries());return(await Promise.all(t.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,t){let n=this.clients.get(e);if(!n?.isConnected)throw new Error(`MCP server "${e}" is not connected`);if(!n.readResource)throw new Error(`MCP server "${e}" does not support resources`);return n.readResource(t)}reinjectTools(e,t){if(!this.injected)return;let n=`mcp__${e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;for(let s of ve())s.startsWith(n)&&Nt(s);let r=t.toPortableTools();pn(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function jn(o){if(!o||typeof o!="object")return[];let e=o,t=[],n=e.mcpServers??e.servers??e;for(let[r,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){t.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"&&t.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 t}var ig={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function Ma(o){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:ig,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,t)=>{let n=o();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let r=await n.listResources(t.server);if(r.length===0)return{content:[{type:"text",text:t.server?`No resources found from MCP server "${t.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 c of l){let u=c.mimeType?` [${c.mimeType}]`:"",g=c.description?` \u2014 ${c.description}`:"";i.push(` ${c.name}: ${c.uri}${u}${g}`)}i.push("")}return{content:[{type:"text",text:i.join(`
247
- `).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var ag={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 Pa(o){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:ag,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,t)=>{let n=o();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let r=await n.readResource(t.server,t.uri);if(r.length===0)return{content:[{type:"text",text:`Resource "${t.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} ---
232
+ 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 Jn(o){let e=new Map,t=Es(o);await Sa(t,e);let n=Ps();return await Sa(n,e),e}async function Sa(o,e){if(og(o))try{let t=await tg(o,{withFileTypes:!0});for(let n of t)if(n.isFile()&&n.name.endsWith(".json")){let r=n.name.replace(/\.json$/,"");e.has(r)||e.set(r,Ca.join(o,n.name))}}catch{}}async function Yn(o){let e=await eg(o,"utf-8");return JSON.parse(e)}function rg(o){let e=new Map(o.map(s=>[s.id,s])),t=new Set,n=[];function r(s,i){if(t.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),t.add(s),n.push(a)}for(let s of o)r(s.id,new Set);return n}function sg(o,e,t){let n={};for(let[r,s]of Object.entries(o))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)=>t.get(l)?.output??""),n[r]=i}else n[r]=s;return n}function _a(o){return{name:"workflow",label:"Workflow",description:"Execute predefined automation workflows. Workflows are step-based pipelines defined as JSON files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/. Steps run in dependency order, support variable interpolation, and can reference previous step outputs via ${step.<id>.result}.",parameters:ng,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"workflow pipeline automation steps DAG",execute:async(e,t,n)=>{let r=o.getCwd();switch(t.action){case"list":{let s=await Jn(r);if(s.size===0)return{content:[{type:"text",text:"No workflows found. Create .json files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/."}],details:{type:"workflow",action:"list",count:0}};let i=["Available workflows:"];for(let[a,l]of s)try{let c=await Yn(l);i.push(` - ${a}: ${c.description??"(no description)"} (${c.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
233
+ `)}],details:{type:"workflow",action:"list",count:s.size}}}case"describe":{if(!t.workflow)return{content:[{type:"text",text:"Error: 'workflow' parameter is required for 'describe'."}],details:{error:"missing_workflow"}};let i=(await Jn(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Yn(i),l=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let c of a.steps){let u=c.dependsOn?.length?` (after: ${c.dependsOn.join(", ")})`:"";l.push(` ${c.id}: ${c.label??c.tool}${u}`),l.push(` tool: ${c.tool}`),l.push(` args: ${JSON.stringify(c.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){l.push("","Variables (defaults):");for(let[c,u]of Object.entries(a.variables))l.push(` ${c} = ${u}`)}return{content:[{type:"text",text:l.filter(Boolean).join(`
234
+ `)}],details:{type:"workflow",action:"describe",workflow:a.name}}}case"run":{if(!t.workflow)return{content:[{type:"text",text:"Error: 'workflow' parameter is required for 'run'."}],details:{error:"missing_workflow"}};let i=(await Jn(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Yn(i),l={...a.variables,...t.variables},c;try{c=rg(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let u=new Map,p=[`Running workflow: ${a.name}`,""],d=!0;for(let m of c){if(n?.aborted){p.push(`\u26A1 Aborted at step: ${m.id}`),d=!1;break}let y=(m.dependsOn??[]).some(w=>!u.get(w)?.success),h=m.condition??"on_success";if(h==="on_success"&&y){p.push(`\u23ED Skipped ${m.id} (dependency failed)`),u.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),d=!1;continue}if(h==="on_failure"&&!y){p.push(`\u23ED Skipped ${m.id} (no failure to handle)`),u.set(m.id,{stepId:m.id,success:!0,output:""});continue}p.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let k=sg(m.args,l,u);try{let w=await o.invokeTool(m.tool,k,n),f=!w.error;if(u.set(m.id,{stepId:m.id,success:f,output:w.result,error:w.error}),f){let C=w.result.length>200?w.result.slice(0,200)+"...":w.result;p.push(` \u2705 ${C}`)}else p.push(` \u274C ${w.error}`),d=!1}catch(w){let f=w.message;u.set(m.id,{stepId:m.id,success:!1,output:"",error:f}),p.push(` \u274C ${f}`),d=!1}}return p.push("",d?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:p.join(`
235
+ `)}],details:{type:"workflow",action:"run",workflow:a.name,success:d,stepsExecuted:u.size,totalSteps:a.steps.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}". Use list, run, or describe.`}],details:{error:"unknown_action"}}}}}}var ig="sleep",ag={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 Ra(o){return{name:ig,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(`
236
+ `),parameters:ag,execute:async(e,t,n)=>{let r=Math.max(1,Math.min(3600,Math.round(t.duration))),s=r*1e3,i=new AbortController,a=()=>i.abort();n?.addEventListener("abort",a,{once:!0}),n?.aborted&&i.abort();try{let l=await o.sleep(s,i.signal),c=[];return l.interrupted?(c.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&c.push(`Reason: ${l.interruptReason}`),c.push("Check for new messages or tasks.")):c.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:c.join(`
237
+ `)}],details:{...l,requestedSeconds:r}}}finally{n?.removeEventListener("abort",a)}}}}var lg="tool_search",cg={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"]},ug=5;function Pa(o){return{name:lg,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:cg,execute:async(e,t)=>{if(!t.query||t.query.trim().length===0)return{content:[{type:"text",text:"Error: query is required."}],details:{type:"tool_search",error:"empty_query"}};let n=t.query.trim(),r=t.maxResults??ug;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(u=>u.trim()).filter(Boolean),a=[],l=[];if(o.activateTool)for(let u of i)await o.activateTool(u)?a.push(u):l.push(u);else{let u=await o.searchTools(n,{maxResults:r});return Ma(u)}let c=[];return a.length>0&&c.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&c.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:c.join(`
238
+ `)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await o.searchTools(n,{maxResults:r});return Ma(s)}}}function Ma(o){if(o.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${o.query}". Total deferred tools available: ${o.totalDeferred}.`}],details:{type:"tool_search",query:o.query,matchCount:0,totalDeferred:o.totalDeferred}};let e=[`Found ${o.matches.length} tool(s) matching "${o.query}" (${o.totalDeferred} total deferred):`,""];for(let t of o.matches)e.push(`- **${t.name}**: ${t.description}`);return e.push(""),e.push('Use "select:toolName" to activate a tool for use in subsequent messages.'),{content:[{type:"text",text:e.join(`
239
+ `)}],details:{type:"tool_search",query:o.query,matchCount:o.matches.length,totalDeferred:o.totalDeferred,matches:o.matches.map(t=>t.name)}}}var dg="image_generate",pg={type:"object",properties:{prompt:{type:"string",description:"Image generation prompt. Enrich vague requests with style, lighting, composition, color, mood details."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video-cover', 'phone-wallpaper', 'avatar', 'poster', etc."},style:{type:"string",description:"Visual art style: 'photorealistic', 'anime', 'watercolor', 'oil-painting', '3d-render', etc."},size:{type:"string",description:"Dimensions: e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Default: '1024x1024'."},image_url:{type:"string",description:"Reference image URL for image-to-image generation (img2img). Character reference sheet or style transfer."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."}},required:["prompt"]};function Aa(o){return{name:dg,label:"Image Generate",description:"Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately. IMPORTANT: If the user has not specified purpose or preferred style, use ask_user to clarify (e.g. purpose: social-media / wallpaper / poster; style: photorealistic / anime / watercolor) before calling this tool. Infer image size automatically from purpose (e.g. 1024x1792 for phone wallpaper, 1792x1024 for landscape poster, 1024x1024 for avatar/social). Do NOT expose size as a raw number to the user.",parameters:pg,execute:async(e,t)=>{let n=await o.generateImage({prompt:t.prompt,purpose:t.purpose,style:t.style,size:t.size,imageUrl:t.image_url,n:t.n}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} image${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var mg={type:"object",properties:{text:{type:"string",description:"Text to convert to speech."},channel:{type:"string",description:"Optional channel id to pick output format (e.g. telegram)."}},required:["text"]};function Ea(o){return{name:"tts",label:"TTS",description:"Convert text to speech (TTS) \u2014 read text aloud as spoken audio. Use for narration, voice messages, or any spoken-word output. DO NOT use for music, songs, or melodies \u2014 use music_generate instead.",parameters:mg,execute:async(e,t)=>{let n=await o.textToSpeech({text:t.text,channel:t.channel});return{content:[{type:"text",text:"\u5DF2\u6210\u529F\u751F\u6210\u8BED\u97F3\u3002"}],details:{type:"tts",audioPath:n.audioPath,provider:n.provider,voiceCompatible:n.voiceCompatible,mediaUrls:n.mediaUrls}}}}}var gg="video_generate",fg={type:"object",properties:{prompt:{type:"string",description:"Video generation prompt. MUST be in English. Include scene, movement, camera motion, lighting, style."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video', 'presentation', etc."},style:{type:"string",description:"Visual style: 'cinematic', 'anime', 'watercolor', etc."},image_url:{type:"string",description:"Reference image for image-to-video. Preview image from storyboard Step 3, or user-uploaded image."},aspect_ratio:{type:"string",description:"Video aspect ratio: '9:16' (vertical), '16:9' (horizontal), '1:1' (square). Default: '16:9'."},duration:{type:"number",description:"Video duration in seconds (3-10s single-shot, >10s requires multi-shot workflow). Must be confirmed by user."}},required:["prompt"]};function Ia(o){return{name:gg,label:"Video Generate",description:"Generate a short video clip from a text prompt (and optional reference image). Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Single-shot: 3\u201310s. For longer videos (>10s), use multi-shot storyboard workflow. IMPORTANT: If the user has not specified aspect ratio or duration, use ask_user to clarify (e.g. aspect: 16:9 for landscape / 9:16 for vertical / 1:1 for square; duration: 3-10s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).",parameters:fg,execute:async(e,t)=>{let n=await o.generateVideo({prompt:t.prompt,purpose:t.purpose,style:t.style,imageUrl:t.image_url,aspectRatio:t.aspect_ratio,duration:t.duration}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} video${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var hg="music_generate",yg={type:"object",properties:{prompt:{type:"string",description:"Music generation prompt. MUST be in English. Include genre, mood, tempo, instruments, and atmosphere details."},purpose:{type:"string",description:"Intended use: 'background-music', 'ringtone', 'short-video-bgm', 'full-song', 'notification-sound', etc."},style:{type:"string",description:"Musical style/genre: 'lo-fi', 'pop', 'rock', 'jazz', 'classical', 'electronic', 'ambient', etc."},lyrics:{type:"string",description:"Optional lyrics for vocal music. Structure with [verse], [chorus], [bridge] tags if desired."},duration:{type:"number",description:"Duration in seconds (5-300). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s."}},required:["prompt"]};function Oa(o){return{name:hg,label:"Music Generate",description:"Generate music, songs, or melodies from text descriptions. Prompt MUST be in English. Supports lyrics for vocal songs. DO NOT use for spoken-word audio or TTS \u2014 use tts tool instead. IMPORTANT: If the user has not specified genre/style or duration, use ask_user to clarify (e.g. style: lo-fi / pop / rock / jazz; duration inferred from purpose: 30s for ringtone, 60-90s for BGM, 180-240s for full song). Auto-infer duration from purpose when possible.",parameters:yg,execute:async(e,t)=>{let n=await o.generateMusic({prompt:t.prompt,purpose:t.purpose,style:t.style,lyrics:t.lyrics,duration:t.duration}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} audio track${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"music_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var bg="video_edit",Tg={type:"object",properties:{prompt:{type:"string",description:"Edit instruction. Reference videos as \u89C6\u98911, \u89C6\u98912, \u89C6\u98913. Reference images as \u56FE\u72471, \u56FE\u72472. Operations: add/remove/modify elements, extend, track fill."},source_videos:{type:"array",items:{type:"string"},minItems:1,maxItems:3,description:"Video(s) to edit (1-3 URLs). Order: [0]=\u89C6\u98911, [1]=\u89C6\u98912, [2]=\u89C6\u98913."},reference_images:{type:"array",items:{type:"string"},description:"Optional reference images for element replacement (up to 9)."},duration:{type:"number",description:"Output duration in seconds (4-15s). Default: same as source."},aspect_ratio:{type:"string",description:"Output aspect ratio: 16:9, 9:16, 1:1, 4:3, 3:4, 21:9. Default: same as source."},resolution:{type:"string",description:"Output resolution: '480p' or '720p'. Default: '720p'."}},required:["prompt","source_videos"]};function La(o){return{name:bg,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos. Max 3 source videos, max 720p. For generating NEW videos from scratch, use video_generate instead.",parameters:Tg,execute:async(e,t)=>{if(!t.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await o.editVideo({prompt:t.prompt,sourceVideos:t.source_videos,referenceImages:t.reference_images,duration:t.duration,aspectRatio:t.aspect_ratio,resolution:t.resolution});return{content:[{type:"text",text:`Video edited successfully${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_edit",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var kg="video_merge",xg={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video file path."},audio:{type:"string",description:"Narration audio file path (from TTS)."},trimStart:{type:"number",description:"Trim start in seconds (default 0)."},trimEnd:{type:"number",description:"Trim end in seconds (default: full)."}},required:["video"]},minItems:2,description:"Array of video clips to merge, in order."},transition:{type:"string",description:"Transition effect: 'crossfade' (default), 'fade', 'wipeleft', 'cut', 'dissolve', etc."},transitionDuration:{type:"number",description:"Transition duration in seconds (0.1-2.0, default 0.5)."},subtitles:{type:"string",description:"Path to SRT subtitle file to burn-in."},bgm:{type:"string",description:"Background music file path."},bgmVolume:{type:"number",description:"BGM volume (0.0-1.0, default 0.15)."},outputResolution:{type:"string",description:"Output resolution: '1920x1080', '1080x1920', etc. Default: auto."},outputFps:{type:"number",description:"Output FPS (default 30)."}},required:["clips"]};function $a(o){return{name:kg,label:"Video Merge",description:"Merge multiple video clips into a single video with transitions, subtitles, and background music. Requires at least 2 clips. Supports crossfade, fade, wipe, dissolve, and cut transitions. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:xg,execute:async(e,t)=>{if(!t.clips||t.clips.length<2)return{content:[{type:"text",text:"Error: at least 2 clips are required for merging."}]};let n=await o.mergeVideos({clips:t.clips,transition:t.transition,transitionDuration:t.transitionDuration,subtitles:t.subtitles,bgm:t.bgm,bgmVolume:t.bgmVolume,outputResolution:t.outputResolution,outputFps:t.outputFps});return{content:[{type:"text",text:`Merged ${n.clipCount} clips \u2192 ${n.durationSec.toFixed(1)}s video`+(t.transition?` (transition: ${t.transition})`:"")}],details:{type:"video_merge",localPath:n.localPath,servePath:n.servePath,durationSec:n.durationSec,clipCount:n.clipCount,mediaUrls:n.mediaUrls}}}}}var vg="video_upscale",wg={type:"object",properties:{video:{type:"string",description:"Video file path (local or serve path)."},targetResolution:{type:"string",description:"Target resolution: '1080p' (default, 1920x1080/1080x1920), '2k' (2560x1440/1440x2560)."},sharpness:{type:"string",description:"Sharpening intensity: 'light' (default), 'medium', 'strong'."}},required:["video"]};function Da(o){return{name:vg,label:"Video Upscale",description:"Upscale a video to higher resolution with optional sharpening. Auto-detects orientation (landscape/portrait). Uses Lanczos interpolation + unsharp mask. Supports 1080p and 2K targets. Best used as post-processing after video_merge.",parameters:wg,execute:async(e,t)=>{let n=await o.upscaleVideo({video:t.video,targetResolution:t.targetResolution,sharpness:t.sharpness});return{content:[{type:"text",text:`Upscaled to ${n.resolution}${t.sharpness?` (sharpness: ${t.sharpness})`:""}`}],details:{type:"video_upscale",localPath:n.localPath,servePath:n.servePath,resolution:n.resolution,durationSec:n.durationSec,mediaUrls:n.mediaUrls}}}}}var Ue,Xn={},Ua;function ja(o,e,t){Ue=o,Xn=e??{},Ua=t}async function De(o){if(Ue){let e=Ue.resolveModel(o.mediaType);if(e){let t=Ue.getTransport(e.providerId),n=Xn[e.providerId];if(t&&n){let r={...o,model:o.model||e.modelInfo.id},s=await t.generate(r,n);s.billingUnit||(o.mediaType==="tts"&&o.text?(s.billingUnit="per_character",s.billingQuantity=o.text.length):(o.mediaType==="video"||o.mediaType==="music")&&o.duration?(s.billingUnit="per_second",s.billingQuantity=o.duration):(s.billingUnit="per_call",s.billingQuantity=1));let i=s.model??r.model,a=s.billingUnit??"per_call",l=s.billingQuantity??1;return Ua?.(i,a,l),s}}}throw new Error(`No media provider configured for ${o.mediaType}`)}function Ne(o){if(Ue){let e=Ue.resolveModel(o);if(e){let t=Ue.getTransport(e.providerId),n=Xn[e.providerId];if(t&&n)return!0}}return!1}var je=process.cwd();function ae(o){return U.isAbsolute(o)?U.normalize(o):U.resolve(je,o)}var Cg=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),Fa=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]);function _g(){return{resolvePath:ae,async readFile(o){let e=ae(o),t=U.extname(e).toLowerCase();if(Fa.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(Cg.has(t)){let r=await I.promises.readFile(e),s=t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".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(o){let e=ae(o);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function Rg(){return{resolvePath:ae,async writeFile(o,e){let t=ae(o);await I.promises.mkdir(U.dirname(t),{recursive:!0}),await I.promises.writeFile(t,e,"utf8")}}}function Mg(){return{resolvePath:ae,async readFile(o){let e=ae(o);return I.promises.readFile(e,"utf8")},async writeFile(o,e){let t=ae(o);await I.promises.mkdir(U.dirname(t),{recursive:!0}),await I.promises.writeFile(t,e,"utf8")}}}function Pg(){return{resolvePath:ae,async readFile(o){let e=ae(o);return I.promises.readFile(e,"utf8")},async writeFile(o,e){let t=ae(o);await I.promises.mkdir(U.dirname(t),{recursive:!0}),await I.promises.writeFile(t,e,"utf8")},async deleteFile(o){let e=ae(o);await I.promises.unlink(e)},async fileExists(o){let e=ae(o);try{return await I.promises.access(e),!0}catch{return!1}}}}function Ag(){return{resolvePath:ae,async glob(o,e){let t=e.cwd||je,n=e.limit||1e3,r=[],s=!1,i=o.replace(/\\/g,"/").split("/"),a=i.some(u=>u==="**"),l=i[i.length-1]??"*",c=Ba(l);try{await Qn(t,async u=>{if(r.length>=n)return s=!0,!1;let p=U.basename(u);return c.test(p)&&r.push(u),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(o,e){let t=e.cwd||je;try{return await Ig(o,t,e)}catch{return await Og(o,t,e)}}}}function Ba(o){let e=o.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(t,n)=>"("+n.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var Eg=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function Qn(o,e,t,n=0,r=""){if(n>t)return;let s;try{s=await I.promises.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(Eg.has(i.name))continue;await Qn(U.join(o,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function Ig(o,e,t){return new Promise((n,r)=>{let s=["--json","--no-heading","--max-columns","500"];t.caseInsensitive&&s.push("-i"),t.contextLines&&s.push("-C",String(t.contextLines)),t.fileGlob&&s.push("-g",t.fileGlob),s.push("--max-count",String(t.headLimit??250)),s.push(o),s.push("."),Sg("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 d of a.split(`
240
+ `))if(d.trim())try{let m=JSON.parse(d);m.type==="match"&&m.data&&l.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let c=t.headLimit??250,u=t.offset??0,p=l.slice(u,u+c);n({matches:p,truncated:l.length>u+c})})})}async function Og(o,e,t){let n=new RegExp(o,t.caseInsensitive?"i":""),r=t.headLimit??250,s=t.offset??0,i=t.fileGlob?Ba(t.fileGlob):null,a=[],l=!1;return await Qn(e,async c=>{if(a.length>=s+r+1)return l=!0,!1;if(i&&!i.test(U.basename(c)))return!0;let u=U.extname(c).toLowerCase();if(Fa.has(u))return!0;try{let d=(await I.promises.readFile(U.join(e,c),"utf8")).split(`
241
+ `);for(let m=0;m<d.length;m++)if(n.test(d[m])&&(a.push({path:c,line:m+1,text:d[m].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 Na=!1;function Lg(){if(!Na)if(Na=!0,Xt()){let o=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";kt(Wn(o))}else if(process.platform==="win32"){let o=$g();kt(io(o))}else{let o=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";kt(io(o))}}function $g(){let o=process.env.QLOGICAGENT_BASH_PATH;if(o&&I.existsSync(o))return o;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],t=process.env.ProgramFiles?U.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let n of e)if(I.existsSync(n))return n;return"bash"}function Dg(){return{async fetchUrl(o){let e=new AbortController,t=setTimeout(()=>e.abort(),3e4);try{let n=await fetch(o.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(!n.ok)return{content:`HTTP ${n.status} ${n.statusText}`};let r=n.headers.get("content-type")??"",s=await n.text();return o.maxChars&&s.length>o.maxChars&&(s=s.slice(0,o.maxChars)),r.includes("html")&&o.extractMode!=="json"&&(s=Ng(s)),{content:s,title:Ug(s)}}finally{clearTimeout(t)}}}}function Ng(o){return o.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s{2,}/g," ").trim()}function Ug(o){return o.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function jg(){return{async search(o,e){let t=process.env.SEARXNG_BASE_URL?.trim();if(!t)return{query:o,results:[],totalResults:0};let n=e?.maxResults??10,r=new URL("/search",t);r.searchParams.set("q",o),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:o,results:[]};let l=await a.json(),c=(l.results??[]).slice(0,n).map(u=>({title:u.title??"",url:u.url??"",snippet:u.content??""}));if(e?.allowedDomains?.length){let u=new Set(e.allowedDomains.map(p=>p.toLowerCase()));return{query:o,results:c.filter(p=>{try{return u.has(new URL(p.url).hostname.toLowerCase())}catch{return!1}})}}if(e?.blockedDomains?.length){let u=new Set(e.blockedDomains.map(p=>p.toLowerCase()));return{query:o,results:c.filter(p=>{try{return!u.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:o,results:c,totalResults:l.number_of_results}}finally{clearTimeout(i)}}}}function Fg(){let o=U.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(r){return U.join(o,"projects",r,".instructions")}function t(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=U.resolve(i,s);if(!a.startsWith(i+U.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(r,s){if(!I.existsSync(r))return[];let i=[];for(let a of I.readdirSync(r,{withFileTypes:!0})){let l=U.join(r,a.name);if(a.isDirectory())i.push(...n(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let c=I.statSync(l);i.push({filename:U.relative(s,l).replace(/\\/g,"/"),path:l,size:c.size,updatedAt:c.mtime.toISOString(),content:I.readFileSync(l,"utf-8")})}}return i}return{list(r){let s=e(r);return n(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(r,s){try{let i=t(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=t(r,s);I.mkdirSync(U.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=t(r,s);return I.existsSync(i)?(I.unlinkSync(i),!0):!1}catch{return!1}}}}function Bg(o){o?.workdir&&(je=o.workdir),Lg(),no(je);let e=[];e.push(Mi()),e.push(Pi()),e.push(Wi({onProgress:o?.onExecProgress,interpretExitCode:(c,u)=>{if(c===127)return"command not found";if(c===126)return"permission denied";if(c===137)return"killed (SIGKILL / OOM)";if(c===143)return"terminated (SIGTERM)";if(c===130)return"interrupted (Ctrl+C)"}}));let t=_g(),n=Rg(),r=Mg(),s=Pg();e.push(Gi(t)),e.push(Vi(n)),e.push(Ki(r)),e.push(Vn(s)),e.push(Qi(s)),e.push(Xi(Ag())),e.push(aa(Dg())),e.push(la(jg()));let i=Fg();e.push(ca(i));let a=o?.log??{info:()=>{},warn:()=>{}};e.push(ua(Ta({log:a}))),e.push(wa());let l={invokeTool:async(c,u,p)=>{let d=we(c);if(!d)return{result:"",error:`Unknown tool: ${c}`};try{let m=await d.execute(`wf_${Date.now()}`,u,p);return{result:m.content.map(h=>h.text??"").join(`
242
+ `),error:m.details?.error}}catch(m){return{result:"",error:m.message}}},getCwd:()=>je};return e.push(_a(l)),e.push(Ra({sleep:(c,u)=>new Promise(p=>{let d=Date.now(),m=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-d)/1e3),interrupted:!1})},c),y=()=>{clearTimeout(m),p({sleptSeconds:Math.round((Date.now()-d)/1e3),interrupted:!0,interruptReason:"aborted"})};u.addEventListener("abort",y,{once:!0}),u.aborted&&(clearTimeout(m),y())})})),e.push(Pa({searchTools:async(c,u)=>{let p=u?.maxResults??5,d=c.toLowerCase(),m=Se();return{matches:m.map(h=>{let k=we(h),w=`${h} ${k?.description??""} ${k?.searchHint??""}`.toLowerCase();return{name:h,description:k?.description??"",searchHint:k?.searchHint,score:w.includes(d)?1:0}}).filter(h=>h.score>0).slice(0,p),query:c,totalDeferred:m.length}}})),e.push({...Aa({generateImage:async c=>{let u=await De({mediaType:"image",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,size:c.size,imageUrl:c.imageUrl,n:c.n});return{mediaUrls:u.mediaUrls,model:u.model,size:u.size,durationMs:u.durationMs}}}),isEnabled:()=>Ne("image")}),e.push({...Ea({textToSpeech:async c=>{let u=await De({mediaType:"tts",model:"",prompt:"",text:c.text,channel:c.channel});return{audioPath:"",provider:u.model,mediaUrls:u.mediaUrls}}}),isEnabled:()=>Ne("tts")}),e.push({...Ia({generateVideo:async c=>{let u=await De({mediaType:"video",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,imageUrl:c.imageUrl,aspectRatio:c.aspectRatio,duration:c.duration});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),isEnabled:()=>Ne("video")}),e.push({...Oa({generateMusic:async c=>{let u=await De({mediaType:"music",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,lyrics:c.lyrics,duration:c.duration});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),isEnabled:()=>Ne("music")}),e.push({...La({editVideo:async c=>{let u=await De({mediaType:"video",model:"",prompt:c.prompt,operation:"edit",sourceVideos:c.sourceVideos,referenceImages:c.referenceImages,duration:c.duration,aspectRatio:c.aspectRatio,resolution:c.resolution});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),isEnabled:()=>Ne("video")}),e.push({...$a({mergeVideos:async c=>{let u=await De({mediaType:"video",model:"",prompt:c.prompt,operation:"merge",sourceVideos:c.sourceVideos,duration:c.duration,aspectRatio:c.aspectRatio,resolution:c.resolution});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),isEnabled:()=>Ne("video")}),e.push({...Da({upscaleVideo:async c=>{let u=await De({mediaType:"video",model:"",prompt:c.prompt||"upscale",operation:"upscale",sourceVideos:[c.sourceVideo],resolution:c.resolution});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),isEnabled:()=>Ne("video")}),Ri(e),o?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(c=>c.isEnabled?.()!==!1).length} enabled): ${Se().join(", ")}`),e}var Wa=Bg;function Zn(o){je=o,no(o)}import{spawn as Wg}from"node:child_process";import{createInterface as qg}from"node:readline";var ao=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=Wg(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:e,cwd:this.config.cwd,windowsHide:!0}),this.process.on("error",n=>{this.handleProcessError(n)}),this.process.on("exit",n=>{this.handleProcessExit(n)}),this.process.stderr?.on("data",n=>{this.stderrBuffer+=n.toString(),this.stderrBuffer.length>4096&&(this.stderrBuffer=this.stderrBuffer.slice(-4096))}),this.readline=qg({input:this.process.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.readline.on("line",n=>this.handleLine(n));let t=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"qlogicagent",version:"0.3.0"}},this.config.initTimeoutMs??3e4);this.serverName=t.serverInfo?.name??this.config.name,this.serverVersion=t.serverInfo?.version??"unknown",this.supportsToolsListChanged=t.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,t,n){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:t??{}},12e4,n)}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=Hg(this.config.name);return this.toolsCache.map(t=>({name:`mcp__${e}__${t.name}`,label:`[${this.config.name}] ${t.name}`,description:t.description??`MCP tool from ${this.config.name}`,parameters:t.inputSchema??{type:"object",properties:{}},isConcurrencySafe:!0,isReadOnly:!1,searchHint:`mcp ${this.config.name} ${t.name}`,execute:async(n,r,s)=>this.executeAsTool(t.name,r,s)}))}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,t,n){try{let r=await this.callTool(e,t,n);return{content:[{type:"text",text:r.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
243
+ `)||"(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,t,n=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:t},c=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${n}ms`))},n),u=()=>{clearTimeout(c),this.pending.delete(a)};r?.addEventListener("abort",()=>{u(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:p=>{u(),p.error?i(new Error(`MCP error ${p.error.code}: ${p.error.message}`)):s(p.result)},reject:p=>{u(),i(p)}}),this.writeLine(JSON.stringify(l))})}sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t};this.writeLine(JSON.stringify(n))}writeLine(e){this.process?.stdin?.writable&&this.process.stdin.write(e+`
244
+ `)}handleLine(e){let t=e.trim();if(!t)return;let n;try{n=JSON.parse(t)}catch{return}if("id"in n&&("result"in n||"error"in n)){let r=n.id,s=this.pending.get(r);s&&s.resolve(n)}else"method"in n&&!("id"in n)&&this.handleNotification(n)}handleNotification(e){e.method==="notifications/tools/list_changed"&&this.refreshTools().then(()=>{this.onToolsChanged?.()}).catch(()=>{})}handleProcessError(e){this.connected=!1;for(let[,t]of this.pending)t.reject(new Error(`MCP process error: ${e.message}`));this.pending.clear()}handleProcessExit(e){this.connected=!1;for(let[,t]of this.pending)t.reject(new Error(`MCP process exited with code ${e}`));this.pending.clear()}};function Hg(o){return o.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as Gg}from"node:crypto";var lo=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,t,n){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:t??{}},this.config.toolCallTimeoutMs??12e4,n)}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,t,n=3e4,r){let s=Gg(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,l=setTimeout(()=>a.abort(),n);r&&r.addEventListener("abort",()=>a.abort(),{once:!0});try{let c={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(c["Mcp-Session-Id"]=this.sessionId);let u=await fetch(this.config.url,{method:"POST",headers:c,body:JSON.stringify(i),signal:a.signal}),p=u.headers.get("mcp-session-id");if(p&&(this.sessionId=p),!u.ok)throw new Error(`MCP HTTP error ${u.status}: ${u.statusText}`);if((u.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(u,s);let m=await u.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(l)}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t},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(n)}).catch(()=>{})}async parseSSEResponse(e,t){let n=e.body;if(!n)throw new Error("MCP SSE response has no body");let r=n.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 c=i.split(`
245
+ `);i=c.pop()??"";for(let u of c){if(!u.startsWith("data: "))continue;let p=u.slice(6).trim();if(p)try{let d=JSON.parse(p);if("method"in d&&d.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(d.id===t){if(d.error)throw new Error(`MCP error ${d.error.code}: ${d.error.message}`);return d.result}}catch(d){if(d instanceof Error&&d.message.startsWith("MCP error"))throw d}}}}finally{r.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${zg(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 t.callTool(e.name,s,i);return{content:[{type:"text",text:(a.content??[]).filter(u=>u.type==="text"&&u.text).map(u=>u.text).join(`
246
+ `)||"(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 zg(o){return o.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var co=class{clients=new Map;injected=!1;log;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}};for(let t of e.servers){if(t.disabled)continue;if((t.type??(t.url?"http":"stdio"))==="http"){if(!t.url){this.log.warn(`[mcp] server "${t.name}" is type "http" but has no url, skipping`);continue}let r={name:t.name,url:t.url,headers:t.headers,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new lo(r))}else{if(!t.command){this.log.warn(`[mcp] server "${t.name}" is type "stdio" but has no command, skipping`);continue}let r={name:t.name,command:t.command,args:t.args,env:t.env,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new ao(r))}}}async connectAll(){let e=Array.from(this.clients.entries()).map(async([t,n])=>{try{await n.connect(),this.log.info(`[mcp] connected to ${t} (${n.info.name} v${n.info.version})`),n.setOnToolsChanged(()=>{this.log.info(`[mcp] tools changed on ${t}, re-injecting`),this.injected&&this.reinjectTools(t,n)})}catch(r){this.log.warn(`[mcp] failed to connect to ${t}: ${r instanceof Error?r.message:r}`)}});await Promise.allSettled(e)}injectTools(){this.injected=!0;for(let[e,t]of this.clients){if(!t.isConnected)continue;let n=t.toPortableTools();Rn(n),this.log.info(`[mcp] injected ${n.length} tools from ${e}`)}}getConnectedServers(){return Array.from(this.clients.entries()).filter(([,e])=>e.isConnected).map(([e])=>e)}getToolCount(){let e=0;for(let t of this.clients.values())t.isConnected&&(e+=t.getCachedTools().length);return e}async disconnectAll(){let e=Array.from(this.clients.values()).map(async t=>{try{await t.disconnect()}catch{}});await Promise.allSettled(e),this.clients.clear(),this.injected=!1}async listResources(e){let t=e?[[e,this.clients.get(e)]].filter(([,r])=>r):Array.from(this.clients.entries());return(await Promise.all(t.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,t){let n=this.clients.get(e);if(!n?.isConnected)throw new Error(`MCP server "${e}" is not connected`);if(!n.readResource)throw new Error(`MCP server "${e}" does not support resources`);return n.readResource(t)}reinjectTools(e,t){if(!this.injected)return;let n=`mcp__${e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;for(let s of Se())s.startsWith(n)&&Yt(s);let r=t.toPortableTools();Rn(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function er(o){if(!o||typeof o!="object")return[];let e=o,t=[],n=e.mcpServers??e.servers??e;for(let[r,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){t.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"&&t.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 t}var Vg={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function qa(o){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:Vg,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,t)=>{let n=o();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let r=await n.listResources(t.server);if(r.length===0)return{content:[{type:"text",text:t.server?`No resources found from MCP server "${t.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 c of l){let u=c.mimeType?` [${c.mimeType}]`:"",p=c.description?` \u2014 ${c.description}`:"";i.push(` ${c.name}: ${c.uri}${u}${p}`)}i.push("")}return{content:[{type:"text",text:i.join(`
247
+ `).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var Kg={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 Ha(o){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:Kg,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,t)=>{let n=o();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let r=await n.readResource(t.server,t.uri);if(r.length===0)return{content:[{type:"text",text:`Resource "${t.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} ---
248
248
  ${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"}) ---
249
- [Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${t.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:t.uri,server:t.server,contentCount:r.length}}}catch(r){return{content:[{type:"text",text:`Error reading resource: ${r.message}`}],details:{error:r.message}}}}}}import*as Se from"node:fs";import*as Yt from"node:path";import{pathToFileURL as lg}from"node:url";var Aa={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var Xt=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(!Se.existsSync(e))continue;let t;try{t=Se.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let r=Yt.join(e,n.name);await this.loadPlugin(n.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[t,n]of this.activations){if(e-n.lastCheckAt<n.ttlMs)continue;let r;try{r=await n.checkFn()}catch(s){this.log.warn(`[plugins] ${t}: check_fn error: ${s instanceof Error?s.message:s}`),r=n.lastResult}if(n.lastCheckAt=e,r!==n.lastResult){if(n.lastResult=r,r&&!n.active){for(let s of n.tools)X(s);n.active=!0,this.log.info(`[plugins] ${t}: reactivated (${n.tools.length} tools)`)}else if(!r&&n.active){for(let s of n.tools)Nt(s.name);for(let s of n.hookUnregisterFns)s();n.active=!1,this.log.info(`[plugins] ${t}: deactivated`)}}}}async loadPlugin(e,t){let n=["index.js","index.mjs"],r=null;for(let f of n){let T=Yt.join(t,f);if(Se.existsSync(T)){r=T;break}}if(!r){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],c=[],u=null,g=6e4,d={},m=Yt.join(t,"config.json");if(Se.existsSync(m))try{d=JSON.parse(Se.readFileSync(m,"utf8"))}catch{}let h={pluginName:e,registerTool:f=>{X(f),l.push(f),s++},registerHook:(f,T)=>{let y=Aa[f];if(!y){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let v=this.config.hookRegistry.register({point:y,handler:T,label:`plugin:${e}:${f}`,priority:200});c.push(v),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>d,setActivationCheck:(f,T)=>{u=f,T!==void 0&&(g=T)}};try{let T=await import(lg(r).href);if(typeof T.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await T.register(h),u&&this.activations.set(e,{checkFn:u,ttlMs:g,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:c,active:!0}),this.loaded.push({name:e,directory:t,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 Z from"node:fs";import*as gt from"node:path";function Fn(){return ms()}function Ea(){return gt.join(Fn(),"installed_plugins.json")}function Ia(){let o=Ea();if(!Z.existsSync(o))return{version:1,plugins:[]};try{return JSON.parse(Z.readFileSync(o,"utf-8"))}catch{return{version:1,plugins:[]}}}function cg(o){let e=Fn();Z.existsSync(e)||Z.mkdirSync(e,{recursive:!0}),Z.writeFileSync(Ea(),JSON.stringify(o,null,2),"utf-8")}function ug(o,e){return!(e.blocklist?.includes(o)||e.allowlist&&!e.allowlist.includes(o))}async function dg(o,e,t){let{execFile:n}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(n),i=Fn(),a=e?`${o}@${e}`:o;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),c=l.trim().split(`
250
- `).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let u=gt.join(i,c),d=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=gt.join(i,`${o}@${d}`);Z.existsSync(m)||Z.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",u,"-C",m,"--strip-components=1"],{timeout:3e4});try{Z.unlinkSync(u)}catch{}let h=gt.join(m,"package.json");if(Z.existsSync(h))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){t.warn(`[marketplace] npm install for ${o} failed: ${f.message}`)}return t.info(`[marketplace] installed ${o}@${d} from npm`),{name:o,version:d,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function pg(){return Ia().plugins.filter(e=>Z.existsSync(e.installPath)).map(e=>e.installPath)}async function mg(o,e){let t=Ia(),n=[];for(let r of o.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!ug(s,o)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(l=>l.source.specifier===r.specifier&&l.source.type===r.type);if(i&&Z.existsSync(i.installPath)&&(!r.version||i.version===r.version)){n.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await dg(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()};t.plugins=t.plugins.filter(c=>!(c.source.specifier===r.specifier&&c.source.type===r.type)),t.plugins.push(l),n.push(a.installPath)}}return cg(t),n}function gg(){let o=fs();if(!Z.existsSync(o))return null;try{return JSON.parse(Z.readFileSync(o,"utf-8"))}catch{return null}}async function Oa(o,e){let t=[...o],n=pg();t.push(...n);let r=gg();if(r&&r.enabledPlugins.length>0)try{let s=await mg(r,e),i=new Set(t);for(let a of s)i.has(a)||t.push(a)}catch(s){e.warn(`[marketplace] failed to update plugins: ${s.message}`)}return t}var Zt=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:t,meta:n}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return{behavior:"deny",message:`Tool "${t}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${t}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:r,regex:s}of this.compiledPatterns)if(s.test(t))return hg(r,e);return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:n?.requiresApproval?{behavior:"ask",message:`Tool "${t}" requires approval`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:n?.isDangerous?{behavior:"ask",message:`Tool "${t}" is marked dangerous`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}:this.mode==="acceptEdits"?/write|edit|create|delete|move|rename|patch/i.test(t)?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:{behavior:"ask",message:`Tool "${t}" needs approval in acceptEdits mode`,toolName:t,input:e.arguments,decisionReason:{type:"mode",mode:"acceptEdits"}}:this.defaultBehavior==="allow"?{behavior:"allow"}:this.defaultBehavior==="deny"?{behavior:"deny",message:`Tool "${t}" denied by default policy`,decisionReason:{type:"other",reason:"default_deny"}}:{behavior:"ask",message:`Tool "${t}" requires approval (default policy)`,toolName:t,input:e.arguments}}compileRules(e){return e.map(t=>({rule:t,regex:fg(t.pattern)}))}};function Un(o){if(!o||typeof o!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=o,t=[];for(let a of["allow","deny","ask"]){let l=e[a];if(Array.isArray(l))for(let c of l)typeof c=="string"&&t.push({pattern:c,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let l=a,c=l.pattern,u=l.behavior??l.action;typeof c=="string"&&typeof u=="string"&&(u==="allow"||u==="deny"||u==="ask")&&t.push({pattern:c,behavior:u,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let n=e.mode,r=typeof n=="string"&&yg(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&bg(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function fg(o){let t=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function hg(o,e){let t={type:"rule",rule:o};return o.behavior==="allow"?{behavior:"allow",decisionReason:t}:o.behavior==="deny"?{behavior:"deny",message:o.reason??`Tool "${e.toolName}" denied by rule "${o.pattern}"`,decisionReason:t}:{behavior:"ask",message:o.reason??`Tool "${e.toolName}" requires approval (rule "${o.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:t}}function yg(o){return o==="default"||o==="bypassPermissions"||o==="acceptEdits"||o==="dontAsk"||o==="plan"}function bg(o){return o==="allow"||o==="deny"||o==="ask"}import{randomUUID as _g}from"node:crypto";var Tg=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"]),La=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"]),kg=[/\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],$a=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 Da(o,e,t){let n=o.trim();if(!n)return{decision:"allow",reason:"empty command"};let r=Mn(n)??Pn(n)??void 0;for(let c of kg)if(c.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${c.source}`,destructiveWarning:r};for(let c of Tg)if(n===c||n.startsWith(c+" "))return{decision:"allow",reason:`known safe command: ${c}`,destructiveWarning:r};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return La.has(i)||La.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&($a.has(i)||$a.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function xg(o){let e=Object.keys(o).sort(),t={};for(let n of e){let r=o[n];typeof r=="string"?t[n]=r.replace(/\s+/g," ").trim():t[n]=r}return JSON.stringify(t)}function Bn(o,e){return`${o}::${xg(e)}`}var vg=500,Qt=class{cache=new Map;get(e,t){let n=Bn(e,t),r=this.cache.get(n);if(r)return r.hitCount++,r}set(e,t,n){if(this.cache.size>=vg){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=Bn(e,t);this.cache.set(r,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(Bn(e,t))}clear(){this.cache.clear()}get size(){return this.cache.size}get totalHits(){let e=0;for(let t of this.cache.values())e+=t.hitCount;return e}};var wg=new Set(["read","search","instructions","think","todo","memory","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function ft(o){return wg.has(o)}var Na=`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.
249
+ [Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${t.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:t.uri,server:t.server,contentCount:r.length}}}catch(r){return{content:[{type:"text",text:`Error reading resource: ${r.message}`}],details:{error:r.message}}}}}}import*as Re from"node:fs";import*as uo from"node:path";import{pathToFileURL as Jg}from"node:url";var Ga={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var po=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(!Re.existsSync(e))continue;let t;try{t=Re.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let r=uo.join(e,n.name);await this.loadPlugin(n.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[t,n]of this.activations){if(e-n.lastCheckAt<n.ttlMs)continue;let r;try{r=await n.checkFn()}catch(s){this.log.warn(`[plugins] ${t}: check_fn error: ${s instanceof Error?s.message:s}`),r=n.lastResult}if(n.lastCheckAt=e,r!==n.lastResult){if(n.lastResult=r,r&&!n.active){for(let s of n.tools)ne(s);n.active=!0,this.log.info(`[plugins] ${t}: reactivated (${n.tools.length} tools)`)}else if(!r&&n.active){for(let s of n.tools)Yt(s.name);for(let s of n.hookUnregisterFns)s();n.active=!1,this.log.info(`[plugins] ${t}: deactivated`)}}}}async loadPlugin(e,t){let n=["index.js","index.mjs"],r=null;for(let h of n){let k=uo.join(t,h);if(Re.existsSync(k)){r=k;break}}if(!r){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],c=[],u=null,p=6e4,d={},m=uo.join(t,"config.json");if(Re.existsSync(m))try{d=JSON.parse(Re.readFileSync(m,"utf8"))}catch{}let y={pluginName:e,registerTool:h=>{ne(h),l.push(h),s++},registerHook:(h,k)=>{let w=Ga[h];if(!w){this.log.warn(`[plugins] ${e}: unknown hook phase "${h}"`);return}let f=this.config.hookRegistry.register({point:w,handler:k,label:`plugin:${e}:${h}`,priority:200});c.push(f),i++},registerSkill:h=>{this.pluginSkills.push(h),a++},getConfig:()=>d,setActivationCheck:(h,k)=>{u=h,k!==void 0&&(p=k)}};try{let k=await import(Jg(r).href);if(typeof k.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await k.register(y),u&&this.activations.set(e,{checkFn:u,ttlMs:p,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:c,active:!0}),this.loaded.push({name:e,directory:t,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(h){this.log.warn(`[plugins] ${e}: load error: ${h instanceof Error?h.message:h}`)}}};import*as re from"node:fs";import*as wt from"node:path";function tr(){return _s()}function za(){return wt.join(tr(),"installed_plugins.json")}function Va(){let o=za();if(!re.existsSync(o))return{version:1,plugins:[]};try{return JSON.parse(re.readFileSync(o,"utf-8"))}catch{return{version:1,plugins:[]}}}function Yg(o){let e=tr();re.existsSync(e)||re.mkdirSync(e,{recursive:!0}),re.writeFileSync(za(),JSON.stringify(o,null,2),"utf-8")}function Xg(o,e){return!(e.blocklist?.includes(o)||e.allowlist&&!e.allowlist.includes(o))}async function Qg(o,e,t){let{execFile:n}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(n),i=tr(),a=e?`${o}@${e}`:o;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),c=l.trim().split(`
250
+ `).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let u=wt.join(i,c),d=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=wt.join(i,`${o}@${d}`);re.existsSync(m)||re.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",u,"-C",m,"--strip-components=1"],{timeout:3e4});try{re.unlinkSync(u)}catch{}let y=wt.join(m,"package.json");if(re.existsSync(y))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(h){t.warn(`[marketplace] npm install for ${o} failed: ${h.message}`)}return t.info(`[marketplace] installed ${o}@${d} from npm`),{name:o,version:d,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function Zg(){return Va().plugins.filter(e=>re.existsSync(e.installPath)).map(e=>e.installPath)}async function ef(o,e){let t=Va(),n=[];for(let r of o.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!Xg(s,o)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(l=>l.source.specifier===r.specifier&&l.source.type===r.type);if(i&&re.existsSync(i.installPath)&&(!r.version||i.version===r.version)){n.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await Qg(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()};t.plugins=t.plugins.filter(c=>!(c.source.specifier===r.specifier&&c.source.type===r.type)),t.plugins.push(l),n.push(a.installPath)}}return Yg(t),n}function tf(){let o=Ms();if(!re.existsSync(o))return null;try{return JSON.parse(re.readFileSync(o,"utf-8"))}catch{return null}}async function Ka(o,e){let t=[...o],n=Zg();t.push(...n);let r=tf();if(r&&r.enabledPlugins.length>0)try{let s=await ef(r,e),i=new Set(t);for(let a of s)i.has(a)||t.push(a)}catch(s){e.warn(`[marketplace] failed to update plugins: ${s.message}`)}return t}var mo=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:t,meta:n}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return{behavior:"deny",message:`Tool "${t}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${t}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:r,regex:s}of this.compiledPatterns)if(s.test(t))return nf(r,e);return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:n?.requiresApproval?{behavior:"ask",message:`Tool "${t}" requires approval`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:n?.isDangerous?{behavior:"ask",message:`Tool "${t}" is marked dangerous`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}:this.mode==="acceptEdits"?/write|edit|create|delete|move|rename|patch/i.test(t)?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:{behavior:"ask",message:`Tool "${t}" needs approval in acceptEdits mode`,toolName:t,input:e.arguments,decisionReason:{type:"mode",mode:"acceptEdits"}}:this.defaultBehavior==="allow"?{behavior:"allow"}:this.defaultBehavior==="deny"?{behavior:"deny",message:`Tool "${t}" denied by default policy`,decisionReason:{type:"other",reason:"default_deny"}}:{behavior:"ask",message:`Tool "${t}" requires approval (default policy)`,toolName:t,input:e.arguments}}compileRules(e){return e.map(t=>({rule:t,regex:of(t.pattern)}))}};function or(o){if(!o||typeof o!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=o,t=[];for(let a of["allow","deny","ask"]){let l=e[a];if(Array.isArray(l))for(let c of l)typeof c=="string"&&t.push({pattern:c,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let l=a,c=l.pattern,u=l.behavior??l.action;typeof c=="string"&&typeof u=="string"&&(u==="allow"||u==="deny"||u==="ask")&&t.push({pattern:c,behavior:u,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let n=e.mode,r=typeof n=="string"&&rf(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&sf(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function of(o){let t=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function nf(o,e){let t={type:"rule",rule:o};return o.behavior==="allow"?{behavior:"allow",decisionReason:t}:o.behavior==="deny"?{behavior:"deny",message:o.reason??`Tool "${e.toolName}" denied by rule "${o.pattern}"`,decisionReason:t}:{behavior:"ask",message:o.reason??`Tool "${e.toolName}" requires approval (rule "${o.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:t}}function rf(o){return o==="default"||o==="bypassPermissions"||o==="acceptEdits"||o==="dontAsk"||o==="plan"}function sf(o){return o==="allow"||o==="deny"||o==="ask"}import{randomUUID as gf}from"node:crypto";var af=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"]),Ja=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"]),lf=[/\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],Ya=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 Xa(o,e,t){let n=o.trim();if(!n)return{decision:"allow",reason:"empty command"};let r=qn(n)??Hn(n)??void 0;for(let c of lf)if(c.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${c.source}`,destructiveWarning:r};for(let c of af)if(n===c||n.startsWith(c+" "))return{decision:"allow",reason:`known safe command: ${c}`,destructiveWarning:r};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return Ja.has(i)||Ja.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&(Ya.has(i)||Ya.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function cf(o){let e=Object.keys(o).sort(),t={};for(let n of e){let r=o[n];typeof r=="string"?t[n]=r.replace(/\s+/g," ").trim():t[n]=r}return JSON.stringify(t)}function nr(o,e){return`${o}::${cf(e)}`}var uf=500,go=class{cache=new Map;get(e,t){let n=nr(e,t),r=this.cache.get(n);if(r)return r.hitCount++,r}set(e,t,n){if(this.cache.size>=uf){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=nr(e,t);this.cache.set(r,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(nr(e,t))}clear(){this.cache.clear()}get size(){return this.cache.size}get totalHits(){let e=0;for(let t of this.cache.values())e+=t.hitCount;return e}};var df=new Set(["read","search","instructions","think","todo","memory","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function St(o){return df.has(o)}var Qa=`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.
251
251
 
252
252
  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).
253
253
 
@@ -269,7 +269,7 @@ DANGEROUS operations (SHOULD be blocked):
269
269
  - Running commands with sudo/admin privileges
270
270
  - Downloading and executing unknown scripts
271
271
 
272
- Respond ONLY with XML. No other text.`;async function qn(o,e,t,n){let r=Date.now();if(ft(o))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=Sg(t),i=Cg(o,e),a=`<transcript>
272
+ Respond ONLY with XML. No other text.`;async function rr(o,e,t,n){let r=Date.now();if(St(o))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=pf(t),i=mf(o,e),a=`<transcript>
273
273
  ${s}
274
274
  </transcript>
275
275
 
@@ -277,7 +277,7 @@ ${s}
277
277
  ${i}
278
278
  </action>
279
279
 
280
- Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let l=await n({system:Na,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),c=Ua(l.text);if(ja(c)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-r};let g=`<transcript>
280
+ Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let l=await n({system:Qa,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),c=tl(l.text);if(Za(c)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-r};let p=`<transcript>
281
281
  ${s}
282
282
  </transcript>
283
283
 
@@ -285,50 +285,50 @@ ${s}
285
285
  ${i}
286
286
  </action>
287
287
 
288
- 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>.`,d=await n({system:Na,messages:[{role:"user",content:g}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=Ua(d.text),h=ja(m),f=Fa(m)??Fa(c)??"classifier decision";return{shouldBlock:h!==!1,reason:f,stage:"thinking",durationMs:Date.now()-r}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-r}}}function Sg(o){return o.slice(-20).map(t=>{let n=t.role==="user"?"User":t.role==="assistant"?"Assistant":"System",r=typeof t.content=="string"?t.content.slice(0,500):JSON.stringify(t.content).slice(0,500);return`${n}: ${r}`}).join(`
289
- `)}function Cg(o,e){let t=JSON.stringify(e,null,0),n=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${o}
290
- Arguments: ${n}`}function ja(o){let e=o.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function Fa(o){let e=o.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function Ua(o){return o.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var Ba={maxConsecutive:3,maxTotal:20};function qa(){return{consecutiveDenials:0,totalDenials:0}}function Wn(o){return{consecutiveDenials:o.consecutiveDenials+1,totalDenials:o.totalDenials+1}}function Hn(o){return o.consecutiveDenials===0?o:{...o,consecutiveDenials:0}}function Wa(o){return o.consecutiveDenials>=Ba.maxConsecutive||o.totalDenials>=Ba.maxTotal}var Rg=12e4,eo=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new Qt;denialTracking=qa();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,t)=>{let n=this.toolMetaCache.get(t.toolName),r={toolName:t.toolName,arguments:t.arguments,meta:n?{isReadOnly:n.isReadOnly,isDangerous:n.isDangerous,requiresApproval:n.requiresApproval,parallelSafe:n.parallelSafe}:void 0},s=this.ruleEngine.check(r);return this.handleResult(s,t.callId,t.toolName,t.arguments)}}),()=>{this.unregisterHook?.(),this.unregisterHook=null,this.cancelAllPending()}}resolveApproval(e){let t=this.pendingApprovals.get(e.approvalId);t&&(clearTimeout(t.timeoutId),this.pendingApprovals.delete(e.approvalId),t.resolve(e))}setToolMeta(e){this.toolMetaCache.clear();for(let t of e)t.meta&&this.toolMetaCache.set(t.function.name,t.meta)}get ruleEngineRef(){return this.ruleEngine}fireDenied(e,t,n){this.onDenied?.(t,n),this.hookRegistry.invoke("permission.denied",{sessionId:"",turnId:"",approvalId:e,callId:e,toolName:t,decision:"denied",reason:n}).catch(()=>{})}async handleResult(e,t,n,r){if(e.behavior==="allow")return{action:"continue",context:e.updatedInput?{arguments:e.updatedInput}:void 0};if(e.behavior==="deny")return this.fireDenied(t,n,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(t,n,`safety check: ${e.message} (${this.permissionRole} cannot override)`),{action:"abort",reason:`Tool "${n}" blocked by safety check (${this.permissionRole} agents cannot override dangerous tool restrictions)`};if((n==="bash"||n==="execute_command"||n==="Bash"||n==="shell")&&r){let c=r.command??r.cmd??"";if(c){let u=Da(c);if(u.decision==="allow")return{action:"continue"};if(u.decision==="deny")return this.fireDenied(t,n,u.reason),{action:"abort",reason:u.reason}}}if(r){let c=this.classifierCache.get(n,r);if(c)return c.shouldBlock?(this.fireDenied(t,n,`cached: ${c.reason}`),{action:"abort",reason:c.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,n,r);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||ft(n)?{action:"continue"}:this.handleWorkerAsk(t,n,r);if(this.ruleEngine.getMode()==="auto"){if(ft(n))return{action:"continue"};let c=Wa(this.denialTracking);if(this.classifierLLMCall&&!c)try{let u=this.getRecentMessages?.()??[],g=await qn(n,r??{},u,this.classifierLLMCall);if(r&&this.classifierCache.set(n,r,{shouldBlock:g.shouldBlock,reason:g.reason}),!g.shouldBlock)return this.denialTracking=Hn(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:g.reason}}};this.denialTracking=Wn(this.denialTracking)}catch{}}let a=_g(),l={approvalId:a,callId:t,toolName:n,arguments:r,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n}).catch(()=>{});try{let c=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n,decision:c.decision==="approved"?"approved":"denied"}).catch(()=>{}),c.permissionUpdate&&(this.ruleEngine.applyUpdate(c.permissionUpdate),this.onPermissionUpdate?.(c.permissionUpdate)),c.decision==="approved"?{action:"continue",context:c.updatedInput?{arguments:c.updatedInput}:void 0}:(this.fireDenied(t,n,`denied by user (approval ${a})`),{action:"abort",reason:`Tool "${n}" denied by user`})}catch{return this.fireDenied(t,n,`approval timeout or error (approval ${a})`),{action:"abort",reason:`Tool "${n}" \u2014 approval timed out`}}}async handleWorkerAsk(e,t,n){if(ft(t))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await qn(t,n??{},r,this.classifierLLMCall);return n&&this.classifierCache.set(t,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=Wn(this.denialTracking),this.fireDenied(e,t,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`),{action:"abort",reason:`Tool "${t}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=Hn(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:this.permissionRole,reason:s.reason}}})}catch{}return this.fireDenied(e,t,`no classifier available in ${this.permissionRole} mode`),{action:"abort",reason:`Tool "${t}" denied \u2014 no classifier for ${this.permissionRole} mode`}}requestApproval(e){return new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),n(new Error("Approval timed out"))},Rg);this.pendingApprovals.set(e.approvalId,{resolve:t,reject:n,timeoutId:r}),this.onRequestApproval(e).then(s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),t(s))},s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),n(s))})})}clearClassifierCache(){this.classifierCache.clear(),this.denialTracking={consecutiveDenials:0,totalDenials:0}}cancelAllPending(){this.classifierCache.clear();for(let[e,t]of this.pendingApprovals)clearTimeout(t.timeoutId),t.reject(new Error("Permission checker destroyed")),this.pendingApprovals.delete(e)}};var Mg="skill_invoke",Pg={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 Ha(o){return{name:Mg,label:"Invoke Skill",description:Ag(o),parameters:Pg,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke run execute command",execute:async(e,t,n)=>{let{skill:r,args:s}=t,i=await o.readSkillContent(r);if(!i){let c=o.listSkills().map(u=>u.name).join(", ");return{content:[{type:"text",text:`Skill "${r}" not found. Available skills: ${c||"(none)"}`}]}}if(o.executeSkillSubturn)try{return{content:[{type:"text",text:await o.executeSkillSubturn(r,i,s,n)}],details:{skillName:r,mode:"subturn"}}}catch(c){let u=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`Skill execution error: ${u}`}],details:{error:u,skillName:r}}}let a=`## Skill: ${r}
288
+ 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>.`,d=await n({system:Qa,messages:[{role:"user",content:p}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=tl(d.text),y=Za(m),h=el(m)??el(c)??"classifier decision";return{shouldBlock:y!==!1,reason:h,stage:"thinking",durationMs:Date.now()-r}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-r}}}function pf(o){return o.slice(-20).map(t=>{let n=t.role==="user"?"User":t.role==="assistant"?"Assistant":"System",r=typeof t.content=="string"?t.content.slice(0,500):JSON.stringify(t.content).slice(0,500);return`${n}: ${r}`}).join(`
289
+ `)}function mf(o,e){let t=JSON.stringify(e,null,0),n=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${o}
290
+ Arguments: ${n}`}function Za(o){let e=o.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function el(o){let e=o.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function tl(o){return o.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var ol={maxConsecutive:3,maxTotal:20};function nl(){return{consecutiveDenials:0,totalDenials:0}}function sr(o){return{consecutiveDenials:o.consecutiveDenials+1,totalDenials:o.totalDenials+1}}function ir(o){return o.consecutiveDenials===0?o:{...o,consecutiveDenials:0}}function rl(o){return o.consecutiveDenials>=ol.maxConsecutive||o.totalDenials>=ol.maxTotal}var ff=12e4,fo=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new go;denialTracking=nl();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,t)=>{let n=this.toolMetaCache.get(t.toolName),r={toolName:t.toolName,arguments:t.arguments,meta:n?{isReadOnly:n.isReadOnly,isDangerous:n.isDangerous,requiresApproval:n.requiresApproval,parallelSafe:n.parallelSafe}:void 0},s=this.ruleEngine.check(r);return this.handleResult(s,t.callId,t.toolName,t.arguments)}}),()=>{this.unregisterHook?.(),this.unregisterHook=null,this.cancelAllPending()}}resolveApproval(e){let t=this.pendingApprovals.get(e.approvalId);t&&(clearTimeout(t.timeoutId),this.pendingApprovals.delete(e.approvalId),t.resolve(e))}setToolMeta(e){this.toolMetaCache.clear();for(let t of e)t.meta&&this.toolMetaCache.set(t.function.name,t.meta)}get ruleEngineRef(){return this.ruleEngine}fireDenied(e,t,n){this.onDenied?.(t,n),this.hookRegistry.invoke("permission.denied",{sessionId:"",turnId:"",approvalId:e,callId:e,toolName:t,decision:"denied",reason:n}).catch(()=>{})}async handleResult(e,t,n,r){if(e.behavior==="allow")return{action:"continue",context:e.updatedInput?{arguments:e.updatedInput}:void 0};if(e.behavior==="deny")return this.fireDenied(t,n,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(t,n,`safety check: ${e.message} (${this.permissionRole} cannot override)`),{action:"abort",reason:`Tool "${n}" blocked by safety check (${this.permissionRole} agents cannot override dangerous tool restrictions)`};if((n==="bash"||n==="execute_command"||n==="Bash"||n==="shell")&&r){let c=r.command??r.cmd??"";if(c){let u=Xa(c);if(u.decision==="allow")return{action:"continue"};if(u.decision==="deny")return this.fireDenied(t,n,u.reason),{action:"abort",reason:u.reason}}}if(r){let c=this.classifierCache.get(n,r);if(c)return c.shouldBlock?(this.fireDenied(t,n,`cached: ${c.reason}`),{action:"abort",reason:c.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,n,r);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||St(n)?{action:"continue"}:this.handleWorkerAsk(t,n,r);if(this.ruleEngine.getMode()==="auto"){if(St(n))return{action:"continue"};let c=rl(this.denialTracking);if(this.classifierLLMCall&&!c)try{let u=this.getRecentMessages?.()??[],p=await rr(n,r??{},u,this.classifierLLMCall);if(r&&this.classifierCache.set(n,r,{shouldBlock:p.shouldBlock,reason:p.reason}),!p.shouldBlock)return this.denialTracking=ir(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:p.reason}}};this.denialTracking=sr(this.denialTracking)}catch{}}let a=gf(),l={approvalId:a,callId:t,toolName:n,arguments:r,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n}).catch(()=>{});try{let c=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n,decision:c.decision==="approved"?"approved":"denied"}).catch(()=>{}),c.permissionUpdate&&(this.ruleEngine.applyUpdate(c.permissionUpdate),this.onPermissionUpdate?.(c.permissionUpdate)),c.decision==="approved"?{action:"continue",context:c.updatedInput?{arguments:c.updatedInput}:void 0}:(this.fireDenied(t,n,`denied by user (approval ${a})`),{action:"abort",reason:`Tool "${n}" denied by user`})}catch{return this.fireDenied(t,n,`approval timeout or error (approval ${a})`),{action:"abort",reason:`Tool "${n}" \u2014 approval timed out`}}}async handleWorkerAsk(e,t,n){if(St(t))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await rr(t,n??{},r,this.classifierLLMCall);return n&&this.classifierCache.set(t,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=sr(this.denialTracking),this.fireDenied(e,t,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`),{action:"abort",reason:`Tool "${t}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=ir(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:this.permissionRole,reason:s.reason}}})}catch{}return this.fireDenied(e,t,`no classifier available in ${this.permissionRole} mode`),{action:"abort",reason:`Tool "${t}" denied \u2014 no classifier for ${this.permissionRole} mode`}}requestApproval(e){return new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),n(new Error("Approval timed out"))},ff);this.pendingApprovals.set(e.approvalId,{resolve:t,reject:n,timeoutId:r}),this.onRequestApproval(e).then(s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),t(s))},s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),n(s))})})}clearClassifierCache(){this.classifierCache.clear(),this.denialTracking={consecutiveDenials:0,totalDenials:0}}cancelAllPending(){this.classifierCache.clear();for(let[e,t]of this.pendingApprovals)clearTimeout(t.timeoutId),t.reject(new Error("Permission checker destroyed")),this.pendingApprovals.delete(e)}};var hf="skill_invoke",yf={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 sl(o){return{name:hf,label:"Invoke Skill",description:bf(o),parameters:yf,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke run execute command",execute:async(e,t,n)=>{let{skill:r,args:s}=t,i=await o.readSkillContent(r);if(!i){let c=o.listSkills().map(u=>u.name).join(", ");return{content:[{type:"text",text:`Skill "${r}" not found. Available skills: ${c||"(none)"}`}]}}if(o.executeSkillSubturn)try{return{content:[{type:"text",text:await o.executeSkillSubturn(r,i,s,n)}],details:{skillName:r,mode:"subturn"}}}catch(c){let u=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`Skill execution error: ${u}`}],details:{error:u,skillName:r}}}let a=`## Skill: ${r}
291
291
 
292
292
  `,l=s?`
293
293
 
294
294
  ### User Context
295
295
  ${s}`:"";return{content:[{type:"text",text:`${a}Follow these instructions:
296
296
 
297
- ${i}${l}`}],details:{skillName:r,mode:"inline"}}}}}function Ag(o){let e=o.listSkills(),t="Invoke a specialized skill to handle a specific task. Skills provide domain-specific instructions and workflows.";if(e.length===0)return t;let n=e.slice(0,50).map(r=>`- ${r.name}: ${r.description??"(no description)"}`).join(`
297
+ ${i}${l}`}],details:{skillName:r,mode:"inline"}}}}}function bf(o){let e=o.listSkills(),t="Invoke a specialized skill to handle a specific task. Skills provide domain-specific instructions and workflows.";if(e.length===0)return t;let n=e.slice(0,50).map(r=>`- ${r.name}: ${r.description??"(no description)"}`).join(`
298
298
  `);return`${t}
299
299
 
300
300
  Available skills:
301
- ${n}`}var Eg="skill_list",Ig={type:"object",properties:{category:{type:"string",description:"Filter skills by category (e.g. 'devops', 'mlops'). Omit to list all."}},required:[]};function Ga(o){return{name:Eg,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:Ig,execute:async(e,t)=>{let n=await o.listSkills(t.category);if(n.skills.length===0)return{content:[{type:"text",text:t.category?`No skills found in category "${t.category}".`:"No skills available."}],details:{type:"skill_list",count:0}};let r=[`Available skills (${n.skills.length}):`];n.categories.length>0&&r.push(`Categories: ${n.categories.join(", ")}`),r.push("");for(let s of n.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(`
302
- `)}],details:{type:"skill_list",count:n.skills.length,categories:n.categories}}}}}var Og="skill_view",Lg={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 za(o){return{name:Og,label:"View Skill",description:"View the full content of a skill (instructions, configuration, reference files). Use skill_list to discover available skills first.",parameters:Lg,execute:async(e,t)=>{if(!t.name||t.name.trim().length===0)return{content:[{type:"text",text:"Error: skill name is required."}],details:{type:"skill_view",error:"empty_name"}};let n=await o.viewSkill(t.name.trim(),t.filePath);if(!n)return{content:[{type:"text",text:`Skill "${t.name}" not found. Use skill_list to see available skills.`}],details:{type:"skill_view",error:"not_found",name:t.name}};let r=[];return t.filePath?r.push(`## ${n.name} / ${t.filePath}`):(r.push(`## Skill: ${n.name}`),n.tags&&n.tags.length>0&&r.push(`Tags: ${n.tags.join(", ")}`),n.referenceFiles&&n.referenceFiles.length>0&&r.push(`Reference files: ${n.referenceFiles.join(", ")}`)),r.push(""),r.push(n.content),{content:[{type:"text",text:r.join(`
303
- `)}],details:{type:"skill_view",name:n.name,filePath:t.filePath,referenceFiles:n.referenceFiles}}}}}var $g="skill_manage",Dg={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"]},Ng=/^[a-z0-9][a-z0-9._-]{0,63}$/,Va=1e5,jg=1048576,to=["references/","templates/","scripts/","assets/"];function Ka(o){return{name:$g,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:Dg,execute:async(e,t)=>{let n=o.validateName?o.validateName(t.name):Fg(t.name);if(n)return{content:[{type:"text",text:`Error: ${n}`}],details:{type:"skill_manage",error:"invalid_name"}};let r=Ug(t);if(r)return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"skill_manage",error:"validation_failed"}};let s=await o.manageSkill(t);return{content:[{type:"text",text:s.message}],details:{type:"skill_manage",action:t.action,name:t.name,success:s.success,path:s.path}}}}}function Fg(o){return o?Ng.test(o)?null:"name must be lowercase, start with letter/digit, contain only letters, digits, hyphens, dots, underscores (max 64 chars).":"name is required."}function Ug(o){switch(o.action){case"create":case"edit":if(!o.content)return`content is required for ${o.action}.`;if(o.content.length>Va)return`content exceeds max length (${Va} chars).`;if(!o.content.includes("---"))return"content must include YAML frontmatter (--- delimiters).";break;case"patch":if(!o.oldString)return"oldString is required for patch.";if(o.newString===void 0)return"newString is required for patch (can be empty to delete).";break;case"write_file":if(!o.filePath)return"filePath is required for write_file.";if(!o.fileContent)return"fileContent is required for write_file.";if(o.fileContent.length>jg)return"fileContent exceeds max length (1 MiB).";if(!to.some(e=>o.filePath.startsWith(e)))return`filePath must be in one of: ${to.join(", ")}`;if(o.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"remove_file":if(!o.filePath)return"filePath is required for remove_file.";if(!to.some(e=>o.filePath.startsWith(e)))return`filePath must be in one of: ${to.join(", ")}`;if(o.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"delete":break;default:return`unknown action: ${o.action}`}return null}var Bg="agent",Ja=["general","explore","plan","code","research","verify"],qg={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
301
+ ${n}`}var Tf="skill_list",kf={type:"object",properties:{category:{type:"string",description:"Filter skills by category (e.g. 'devops', 'mlops'). Omit to list all."}},required:[]};function il(o){return{name:Tf,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:kf,execute:async(e,t)=>{let n=await o.listSkills(t.category);if(n.skills.length===0)return{content:[{type:"text",text:t.category?`No skills found in category "${t.category}".`:"No skills available."}],details:{type:"skill_list",count:0}};let r=[`Available skills (${n.skills.length}):`];n.categories.length>0&&r.push(`Categories: ${n.categories.join(", ")}`),r.push("");for(let s of n.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(`
302
+ `)}],details:{type:"skill_list",count:n.skills.length,categories:n.categories}}}}}var xf="skill_view",vf={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 al(o){return{name:xf,label:"View Skill",description:"View the full content of a skill (instructions, configuration, reference files). Use skill_list to discover available skills first.",parameters:vf,execute:async(e,t)=>{if(!t.name||t.name.trim().length===0)return{content:[{type:"text",text:"Error: skill name is required."}],details:{type:"skill_view",error:"empty_name"}};let n=await o.viewSkill(t.name.trim(),t.filePath);if(!n)return{content:[{type:"text",text:`Skill "${t.name}" not found. Use skill_list to see available skills.`}],details:{type:"skill_view",error:"not_found",name:t.name}};let r=[];return t.filePath?r.push(`## ${n.name} / ${t.filePath}`):(r.push(`## Skill: ${n.name}`),n.tags&&n.tags.length>0&&r.push(`Tags: ${n.tags.join(", ")}`),n.referenceFiles&&n.referenceFiles.length>0&&r.push(`Reference files: ${n.referenceFiles.join(", ")}`)),r.push(""),r.push(n.content),{content:[{type:"text",text:r.join(`
303
+ `)}],details:{type:"skill_view",name:n.name,filePath:t.filePath,referenceFiles:n.referenceFiles}}}}}var wf="skill_manage",Sf={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"]},Cf=/^[a-z0-9][a-z0-9._-]{0,63}$/,ll=1e5,_f=1048576,ho=["references/","templates/","scripts/","assets/"];function cl(o){return{name:wf,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:Sf,execute:async(e,t)=>{let n=o.validateName?o.validateName(t.name):Rf(t.name);if(n)return{content:[{type:"text",text:`Error: ${n}`}],details:{type:"skill_manage",error:"invalid_name"}};let r=Mf(t);if(r)return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"skill_manage",error:"validation_failed"}};let s=await o.manageSkill(t);return{content:[{type:"text",text:s.message}],details:{type:"skill_manage",action:t.action,name:t.name,success:s.success,path:s.path}}}}}function Rf(o){return o?Cf.test(o)?null:"name must be lowercase, start with letter/digit, contain only letters, digits, hyphens, dots, underscores (max 64 chars).":"name is required."}function Mf(o){switch(o.action){case"create":case"edit":if(!o.content)return`content is required for ${o.action}.`;if(o.content.length>ll)return`content exceeds max length (${ll} chars).`;if(!o.content.includes("---"))return"content must include YAML frontmatter (--- delimiters).";break;case"patch":if(!o.oldString)return"oldString is required for patch.";if(o.newString===void 0)return"newString is required for patch (can be empty to delete).";break;case"write_file":if(!o.filePath)return"filePath is required for write_file.";if(!o.fileContent)return"fileContent is required for write_file.";if(o.fileContent.length>_f)return"fileContent exceeds max length (1 MiB).";if(!ho.some(e=>o.filePath.startsWith(e)))return`filePath must be in one of: ${ho.join(", ")}`;if(o.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"remove_file":if(!o.filePath)return"filePath is required for remove_file.";if(!ho.some(e=>o.filePath.startsWith(e)))return`filePath must be in one of: ${ho.join(", ")}`;if(o.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"delete":break;default:return`unknown action: ${o.action}`}return null}var Pf="agent",ul=["general","explore","plan","code","research","verify"],Af={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
304
304
  - general: Full tool access, any task
305
305
  - explore: Read-only codebase exploration (search, read, analyze)
306
306
  - plan: Planning mode (explore + produce plan, no writes)
307
307
  - code: Coding agent with full tool access
308
308
  - research: Web research and information gathering
309
- - 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},Ya=4;function Xa(o){return{name:Bg,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:qg,searchHint:"fork subagent delegate spawn child parallel worker",isConcurrencySafe:!0,execute:async(e,t)=>{if(!t.prompt||t.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(!Ja.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${Ja.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=o.currentForkDepth??0;if(n>=Ya)return{content:[{type:"text",text:`Error: maximum fork depth (${Ya}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:n}};try{let r=await o.forkAgent({agent:t.agent,prompt:t.prompt.trim(),description:t.description,maxTurns:t.maxTurns,background:t.background,abortSignal:o.abortSignal});if(t.background&&r.status==="running")return{content:[{type:"text",text:`Sub-agent "${t.agent}" started in background.
309
+ - 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},dl=4;function pl(o){return{name:Pf,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:Af,searchHint:"fork subagent delegate spawn child parallel worker",isConcurrencySafe:!0,execute:async(e,t)=>{if(!t.prompt||t.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(!ul.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${ul.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=o.currentForkDepth??0;if(n>=dl)return{content:[{type:"text",text:`Error: maximum fork depth (${dl}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:n}};try{let r=await o.forkAgent({agent:t.agent,prompt:t.prompt.trim(),description:t.description,maxTurns:t.maxTurns,background:t.background,abortSignal:o.abortSignal});if(t.background&&r.status==="running")return{content:[{type:"text",text:`Sub-agent "${t.agent}" started in background.
310
310
  Agent ID: ${r.agentId}
311
311
  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?`
312
312
 
313
- [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 Wg="config",Hg={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
313
+ [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 Ef="config",If={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
314
314
  - get: Read a config setting
315
315
  - set: Write a config setting
316
316
  - list: List all available settings
317
- - 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"]},ht=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Za(o){return{name:Wg,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:Hg,execute:async(e,t)=>{switch(t.action){case"get":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for get."}],details:{type:"config",error:"missing_key"}};if(o.isValidKey&&!o.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}". Use action='list' to see available settings.`}],details:{type:"config",error:"unknown_key"}};let n=await o.getConfig(t.key);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}};let r=n.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(`
318
- `)}],details:{type:"config",action:"get",key:t.key,value:r.value}}}case"set":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for set."}],details:{type:"config",error:"missing_key"}};if(t.value===void 0)return{content:[{type:"text",text:"Error: value is required for set."}],details:{type:"config",error:"missing_value"}};if(ht.includes(t.key))return{content:[{type:"text",text:`Error: "${t.key}" is a security-critical setting and cannot be modified.`}],details:{type:"config",error:"readonly_key"}};if(o.isValidKey&&!o.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}".`}],details:{type:"config",error:"unknown_key"}};let n=await o.setConfig(t.key,t.value);return n.success?{content:[{type:"text",text:`Updated "${t.key}": ${JSON.stringify(n.previousValue)} \u2192 ${JSON.stringify(t.value)}`}],details:{type:"config",action:"set",key:t.key,previousValue:n.previousValue,newValue:t.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}case"list":{let n=await o.listConfig();if(!n.settings||n.settings.length===0)return{content:[{type:"text",text:"No config settings available."}],details:{type:"config",action:"list",count:0}};let r=[`Available settings (${n.settings.length}):`,""];for(let s of n.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(`
319
- `)}],details:{type:"config",action:"list",count:n.settings.length}}}case"reset":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for reset."}],details:{type:"config",error:"missing_key"}};if(ht.includes(t.key))return{content:[{type:"text",text:`Error: "${t.key}" cannot be reset (security-critical).`}],details:{type:"config",error:"readonly_key"}};let n=await o.resetConfig(t.key);return n.success?{content:[{type:"text",text:`Reset "${t.key}" to default: ${JSON.stringify(n.setting?.value)}`}],details:{type:"config",action:"reset",key:t.key,value:n.setting?.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"config",error:"unknown_action"}}}}}}var Gg="cron",zg={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:
317
+ - 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"]},Ct=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function ml(o){return{name:Ef,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:If,execute:async(e,t)=>{switch(t.action){case"get":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for get."}],details:{type:"config",error:"missing_key"}};if(o.isValidKey&&!o.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}". Use action='list' to see available settings.`}],details:{type:"config",error:"unknown_key"}};let n=await o.getConfig(t.key);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}};let r=n.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(`
318
+ `)}],details:{type:"config",action:"get",key:t.key,value:r.value}}}case"set":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for set."}],details:{type:"config",error:"missing_key"}};if(t.value===void 0)return{content:[{type:"text",text:"Error: value is required for set."}],details:{type:"config",error:"missing_value"}};if(Ct.includes(t.key))return{content:[{type:"text",text:`Error: "${t.key}" is a security-critical setting and cannot be modified.`}],details:{type:"config",error:"readonly_key"}};if(o.isValidKey&&!o.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}".`}],details:{type:"config",error:"unknown_key"}};let n=await o.setConfig(t.key,t.value);return n.success?{content:[{type:"text",text:`Updated "${t.key}": ${JSON.stringify(n.previousValue)} \u2192 ${JSON.stringify(t.value)}`}],details:{type:"config",action:"set",key:t.key,previousValue:n.previousValue,newValue:t.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}case"list":{let n=await o.listConfig();if(!n.settings||n.settings.length===0)return{content:[{type:"text",text:"No config settings available."}],details:{type:"config",action:"list",count:0}};let r=[`Available settings (${n.settings.length}):`,""];for(let s of n.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(`
319
+ `)}],details:{type:"config",action:"list",count:n.settings.length}}}case"reset":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for reset."}],details:{type:"config",error:"missing_key"}};if(Ct.includes(t.key))return{content:[{type:"text",text:`Error: "${t.key}" cannot be reset (security-critical).`}],details:{type:"config",error:"readonly_key"}};let n=await o.resetConfig(t.key);return n.success?{content:[{type:"text",text:`Reset "${t.key}" to default: ${JSON.stringify(n.setting?.value)}`}],details:{type:"config",action:"reset",key:t.key,value:n.setting?.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"config",error:"unknown_action"}}}}}}var Of="cron",Lf={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:
320
320
  - Cron: '0 9 * * *' (every day at 9am)
321
321
  - Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
322
- 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"]},Qa=50;function el(o){return{name:Gg,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:zg,execute:async(e,t)=>{switch(t.action){case"create":{if(!t.prompt)return{content:[{type:"text",text:"Error: prompt is required for create."}],details:{type:"cron",error:"missing_prompt"}};if(!t.schedule)return{content:[{type:"text",text:"Error: schedule is required for create."}],details:{type:"cron",error:"missing_schedule"}};if(o.validateSchedule){let s=o.validateSchedule(t.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let n=await o.listJobs();if(n.jobs&&n.jobs.length>=Qa)return{content:[{type:"text",text:`Error: maximum ${Qa} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let r=await o.createJob({prompt:t.prompt,schedule:t.schedule,name:t.name,repeat:t.repeat,allowedTools:t.allowedTools});return r.success?{content:[{type:"text",text:Gn(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 n=await o.listJobs();if(!n.jobs||n.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let r=[`Scheduled jobs (${n.jobs.length}):`,""];for(let s of n.jobs)r.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:r.join(`
323
- `)}],details:{type:"cron",action:"list",count:n.jobs.length}}}case"get":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.getJob(t.jobId);return n.success?{content:[{type:"text",text:Gn(n.job)}],details:{type:"cron",action:"get",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"update":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n={};t.prompt!==void 0&&(n.prompt=t.prompt),t.schedule!==void 0&&(n.schedule=t.schedule),t.name!==void 0&&(n.name=t.name),t.enabled!==void 0&&(n.enabled=t.enabled),t.repeat!==void 0&&(n.repeat=t.repeat),t.allowedTools!==void 0&&(n.allowedTools=t.allowedTools);let r=await o.updateJob(t.jobId,n);return r.success?{content:[{type:"text",text:`Job updated.
324
- ${Gn(r.job)}`}],details:{type:"cron",action:"update",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${r.error}`}],details:{type:"cron",error:r.error}}}case"delete":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.deleteJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} deleted.`}],details:{type:"cron",action:"delete",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"pause":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.pauseJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} paused.`}],details:{type:"cron",action:"pause",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"resume":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.resumeJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} resumed.`}],details:{type:"cron",action:"resume",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"trigger":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.triggerJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} triggered (running now).`}],details:{type:"cron",action:"trigger",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"cron",error:"unknown_action"}}}}}}function Gn(o){let e=[`Job: ${o.name||o.id}`,`ID: ${o.id}`,`Schedule: ${o.scheduleDisplay} (${o.schedule})`,`State: ${o.state}`,`Repeat: ${o.repeat.times===null?"infinite":`${o.repeat.completed}/${o.repeat.times}`}`];return o.nextRunAt&&e.push(`Next run: ${o.nextRunAt}`),o.lastRunAt&&e.push(`Last run: ${o.lastRunAt} (${o.lastStatus||"unknown"})`),e.push(`Prompt: ${o.prompt.slice(0,100)}${o.prompt.length>100?"...":""}`),e.join(`
325
- `)}var Vg="monitor",Kg={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 tl(o){return{name:Vg,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(`
326
- `),parameters:Kg,execute:async(e,t)=>{let{action:n}=t;if(n==="list"){let i=await o.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:n,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
322
+ 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"]},gl=50;function fl(o){return{name:Of,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:Lf,execute:async(e,t)=>{switch(t.action){case"create":{if(!t.prompt)return{content:[{type:"text",text:"Error: prompt is required for create."}],details:{type:"cron",error:"missing_prompt"}};if(!t.schedule)return{content:[{type:"text",text:"Error: schedule is required for create."}],details:{type:"cron",error:"missing_schedule"}};if(o.validateSchedule){let s=o.validateSchedule(t.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let n=await o.listJobs();if(n.jobs&&n.jobs.length>=gl)return{content:[{type:"text",text:`Error: maximum ${gl} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let r=await o.createJob({prompt:t.prompt,schedule:t.schedule,name:t.name,repeat:t.repeat,allowedTools:t.allowedTools});return r.success?{content:[{type:"text",text:ar(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 n=await o.listJobs();if(!n.jobs||n.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let r=[`Scheduled jobs (${n.jobs.length}):`,""];for(let s of n.jobs)r.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:r.join(`
323
+ `)}],details:{type:"cron",action:"list",count:n.jobs.length}}}case"get":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.getJob(t.jobId);return n.success?{content:[{type:"text",text:ar(n.job)}],details:{type:"cron",action:"get",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"update":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n={};t.prompt!==void 0&&(n.prompt=t.prompt),t.schedule!==void 0&&(n.schedule=t.schedule),t.name!==void 0&&(n.name=t.name),t.enabled!==void 0&&(n.enabled=t.enabled),t.repeat!==void 0&&(n.repeat=t.repeat),t.allowedTools!==void 0&&(n.allowedTools=t.allowedTools);let r=await o.updateJob(t.jobId,n);return r.success?{content:[{type:"text",text:`Job updated.
324
+ ${ar(r.job)}`}],details:{type:"cron",action:"update",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${r.error}`}],details:{type:"cron",error:r.error}}}case"delete":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.deleteJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} deleted.`}],details:{type:"cron",action:"delete",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"pause":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.pauseJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} paused.`}],details:{type:"cron",action:"pause",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"resume":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.resumeJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} resumed.`}],details:{type:"cron",action:"resume",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"trigger":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await o.triggerJob(t.jobId);return n.success?{content:[{type:"text",text:`Job ${t.jobId} triggered (running now).`}],details:{type:"cron",action:"trigger",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"cron",error:"unknown_action"}}}}}}function ar(o){let e=[`Job: ${o.name||o.id}`,`ID: ${o.id}`,`Schedule: ${o.scheduleDisplay} (${o.schedule})`,`State: ${o.state}`,`Repeat: ${o.repeat.times===null?"infinite":`${o.repeat.completed}/${o.repeat.times}`}`];return o.nextRunAt&&e.push(`Next run: ${o.nextRunAt}`),o.lastRunAt&&e.push(`Last run: ${o.lastRunAt} (${o.lastStatus||"unknown"})`),e.push(`Prompt: ${o.prompt.slice(0,100)}${o.prompt.length>100?"...":""}`),e.join(`
325
+ `)}var $f="monitor",Df={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 hl(o){return{name:$f,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(`
326
+ `),parameters:Df,execute:async(e,t)=>{let{action:n}=t;if(n==="list"){let i=await o.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:n,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
327
327
  ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.eventCount}, timeout: ${l.timeoutSeconds}s)`).join(`
328
- `)}`}],details:{action:n,monitors:i}}}if(!t.monitorId)return{content:[{type:"text",text:"Error: monitorId is required for start/stop."}],details:{action:n,success:!1,error:"missing_monitor_id"}};if(n==="stop"){let i=await o.stopMonitor(t.monitorId);return{content:[{type:"text",text:i.success?`Monitor "${t.monitorId}" stopped.`:`Failed to stop monitor "${t.monitorId}": ${i.error??"not found"}`}],details:{...i}}}if(!t.source||!t.target)return{content:[{type:"text",text:"Error: source and target are required to start a monitor."}],details:{action:n,success:!1,error:"missing_source_or_target"}};let r=await o.startMonitor({monitorId:t.monitorId,source:t.source,target:t.target,conditions:t.conditions??[],timeoutSeconds:t.timeoutSeconds??3600});return{content:[{type:"text",text:r.success?`Monitor "${t.monitorId}" started: watching ${t.source} "${t.target}".`:`Failed to start monitor: ${r.error??"unknown"}`}],details:{...r}}}}}var Jg="team",Yg={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 ol(o){return{name:Jg,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:Yg,execute:async(e,t)=>{switch(t.action){case"create":{if(!t.teamName)return{content:[{type:"text",text:"Error: teamName required for create."}],details:{type:"team",error:"missing_name"}};let n=await o.createTeam({teamName:t.teamName,description:t.description,members:t.members});if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let r=[`Team "${n.team.name}" created.`,`Lead: ${n.team.leadId}`,`Members: ${n.team.members.length}`];for(let s of n.team.members)r.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:r.join(`
328
+ `)}`}],details:{action:n,monitors:i}}}if(!t.monitorId)return{content:[{type:"text",text:"Error: monitorId is required for start/stop."}],details:{action:n,success:!1,error:"missing_monitor_id"}};if(n==="stop"){let i=await o.stopMonitor(t.monitorId);return{content:[{type:"text",text:i.success?`Monitor "${t.monitorId}" stopped.`:`Failed to stop monitor "${t.monitorId}": ${i.error??"not found"}`}],details:{...i}}}if(!t.source||!t.target)return{content:[{type:"text",text:"Error: source and target are required to start a monitor."}],details:{action:n,success:!1,error:"missing_source_or_target"}};let r=await o.startMonitor({monitorId:t.monitorId,source:t.source,target:t.target,conditions:t.conditions??[],timeoutSeconds:t.timeoutSeconds??3600});return{content:[{type:"text",text:r.success?`Monitor "${t.monitorId}" started: watching ${t.source} "${t.target}".`:`Failed to start monitor: ${r.error??"unknown"}`}],details:{...r}}}}}var Nf="team",Uf={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 yl(o){return{name:Nf,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:Uf,execute:async(e,t)=>{switch(t.action){case"create":{if(!t.teamName)return{content:[{type:"text",text:"Error: teamName required for create."}],details:{type:"team",error:"missing_name"}};let n=await o.createTeam({teamName:t.teamName,description:t.description,members:t.members});if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let r=[`Team "${n.team.name}" created.`,`Lead: ${n.team.leadId}`,`Members: ${n.team.members.length}`];for(let s of n.team.members)r.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:r.join(`
329
329
  `)}],details:{type:"team",action:"create",teamName:n.team.name}}}case"delete":{if(!t.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let n=await o.deleteTeam(t.teamName);return n.success?{content:[{type:"text",text:`Team "${t.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:t.teamName}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}}}case"list":{let n=await o.listTeams();if(!n.teams||n.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let r=[`Active teams (${n.teams.length}):`,""];for(let s of n.teams)r.push(`- **${s.name}**: ${s.description||"(no description)"} \u2014 ${s.members.length} members`);return{content:[{type:"text",text:r.join(`
330
330
  `)}],details:{type:"team",action:"list",count:n.teams.length}}}case"status":{if(!t.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let n=await o.getTeamStatus(t.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let r=n.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(`
331
- `)}],details:{type:"team",action:"status",teamName:r.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var Zg="mcp",Qg={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
+ `)}],details:{type:"team",action:"status",teamName:r.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var Ff="mcp",Bf={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:
332
332
  - list_servers: List configured MCP servers, their status and capabilities
333
333
  - list_tools: List tools provided by a specific server
334
334
  - call_tool: Execute a tool on an MCP server
@@ -337,14 +337,14 @@ ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.
337
337
  - list_prompts: List prompts available from a server
338
338
  - get_prompt: Get a specific prompt with arguments
339
339
  - authenticate: Initiate OAuth authentication with a server
340
- - 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 nl(o){return{name:Zg,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
+ - 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 bl(o){return{name:Ff,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).
341
341
 
342
- 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:Qg,shouldDefer:!0,execute:async(e,t,n)=>{switch(t.action){case"list_servers":{let r=await o.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=ef(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(`
343
- `)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!t.server)return z("server is required for list_tools.");let r=await o.listTools(t.server);if(r.length===0)return{content:[{type:"text",text:`No tools available from server "${t.server}".`}],details:{type:"mcp",action:"list_tools",server:t.server,count:0}};let s=[`Tools from "${t.server}" (${r.length}):`,""];for(let i of r){let a=tf(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(`
344
- `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:r.length}}}case"call_tool":{if(!t.server)return z("server is required for call_tool.");if(!t.toolName)return z("toolName is required for call_tool.");let r=await o.callTool(t.server,t.toolName,t.arguments,n);return!r.success||r.isError?{content:[{type:"text",text:`MCP tool error (${t.server}/${t.toolName}): ${r.error||r.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.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:t.server,toolName:t.toolName,success:!0}}:{content:[{type:"text",text:r.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!0}}}case"list_resources":{let r=await o.listResources(t.server);if(r.length===0)return{content:[{type:"text",text:t.server?`No resources from "${t.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(`
345
- `)}],details:{type:"mcp",action:"list_resources",count:r.length,server:t.server}}}case"read_resource":{if(!t.server)return z("server is required for read_resource.");if(!t.uri)return z("uri is required for read_resource.");let r=await o.readResource(t.server,t.uri);if(r.length===0)return{content:[{type:"text",text:"Resource returned no content."}],details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}};let s=[];for(let i of r)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${of(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:t.server,uri:t.uri}}}case"list_prompts":{if(!t.server)return z("server is required for list_prompts.");if(!o.listPrompts)return z("Prompt listing not supported by the current MCP host.");let r=await o.listPrompts(t.server);if(r.length===0)return{content:[{type:"text",text:`No prompts available from "${t.server}".`}],details:{type:"mcp",action:"list_prompts",server:t.server,count:0}};let s=[`Prompts from "${t.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(`
346
- `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:r.length}}}case"get_prompt":{if(!t.server)return z("server is required for get_prompt.");if(!t.promptName)return z("promptName is required for get_prompt.");if(!o.getPrompt)return z("Prompt retrieval not supported by the current MCP host.");let r=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,l])=>[a,String(l)])):void 0,s=await o.getPrompt(t.server,t.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(`
347
- `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return z("server is required for authenticate.");let r=await o.authenticate(t.server);switch(r.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
342
+ 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:Bf,shouldDefer:!0,execute:async(e,t,n)=>{switch(t.action){case"list_servers":{let r=await o.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=Wf(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(`
343
+ `)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!t.server)return X("server is required for list_tools.");let r=await o.listTools(t.server);if(r.length===0)return{content:[{type:"text",text:`No tools available from server "${t.server}".`}],details:{type:"mcp",action:"list_tools",server:t.server,count:0}};let s=[`Tools from "${t.server}" (${r.length}):`,""];for(let i of r){let a=qf(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(`
344
+ `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:r.length}}}case"call_tool":{if(!t.server)return X("server is required for call_tool.");if(!t.toolName)return X("toolName is required for call_tool.");let r=await o.callTool(t.server,t.toolName,t.arguments,n);return!r.success||r.isError?{content:[{type:"text",text:`MCP tool error (${t.server}/${t.toolName}): ${r.error||r.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.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:t.server,toolName:t.toolName,success:!0}}:{content:[{type:"text",text:r.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!0}}}case"list_resources":{let r=await o.listResources(t.server);if(r.length===0)return{content:[{type:"text",text:t.server?`No resources from "${t.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(`
345
+ `)}],details:{type:"mcp",action:"list_resources",count:r.length,server:t.server}}}case"read_resource":{if(!t.server)return X("server is required for read_resource.");if(!t.uri)return X("uri is required for read_resource.");let r=await o.readResource(t.server,t.uri);if(r.length===0)return{content:[{type:"text",text:"Resource returned no content."}],details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}};let s=[];for(let i of r)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${Hf(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:t.server,uri:t.uri}}}case"list_prompts":{if(!t.server)return X("server is required for list_prompts.");if(!o.listPrompts)return X("Prompt listing not supported by the current MCP host.");let r=await o.listPrompts(t.server);if(r.length===0)return{content:[{type:"text",text:`No prompts available from "${t.server}".`}],details:{type:"mcp",action:"list_prompts",server:t.server,count:0}};let s=[`Prompts from "${t.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(`
346
+ `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:r.length}}}case"get_prompt":{if(!t.server)return X("server is required for get_prompt.");if(!t.promptName)return X("promptName is required for get_prompt.");if(!o.getPrompt)return X("Prompt retrieval not supported by the current MCP host.");let r=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,l])=>[a,String(l)])):void 0,s=await o.getPrompt(t.server,t.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(`
347
+ `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return X("server is required for authenticate.");let r=await o.authenticate(t.server);switch(r.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
348
348
 
349
349
  Please open this URL in your browser:
350
350
  ${r.authUrl}
@@ -352,17 +352,17 @@ ${r.authUrl}
352
352
  ${r.message||"Once you complete authentication, the server's tools will become available automatically."}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"auth_url"}};case"already_authenticated":return{content:[{type:"text",text:`Server "${t.server}" is already authenticated.`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"already_authenticated"}};case"step_up_required":return{content:[{type:"text",text:`Server "${t.server}" requires elevated permissions.
353
353
  Required scopes: ${r.requiredScopes?.join(", ")||"unknown"}
354
354
 
355
- `+(r.authUrl?`Re-authorize at: ${r.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:t.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${t.server}" (${r.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${t.server}": ${r.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"error"}}}}case"manage_server":{if(!t.server)return z("server is required for manage_server.");if(!t.manageAction)return z("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!o.addServer)return z("Server addition not supported by the current MCP host.");if(!t.config)return z("config is required for manage_server add.");let r=await o.addServer(t.server,t.config);return yt("add",t.server,r)}case"remove":{if(!o.removeServer)return z("Server removal not supported by the current MCP host.");let r=await o.removeServer(t.server);return yt("remove",t.server,r)}case"restart":{if(!o.restartServer)return z("Server restart not supported by the current MCP host.");let r=await o.restartServer(t.server);return yt("restart",t.server,r)}case"health_check":{if(!o.healthCheck)return z("Health check not supported by the current MCP host.");let r=await o.healthCheck(t.server);return yt("health_check",t.server,r)}case"enable":case"disable":{if(!o.setServerEnabled)return z("Server enable/disable not supported by the current MCP host.");let r=await o.setServerEnabled(t.server,t.manageAction==="enable");return yt(t.manageAction,t.server,r)}default:return z(`Unknown manageAction: ${t.manageAction}`)}}default:return z(`Unknown action: "${t.action}".`)}}}}function z(o){return{content:[{type:"text",text:`Error: ${o}`}],details:{type:"mcp",error:o}}}function ef(o){switch(o){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 tf(o){if(!o)return"";let e=[];return o.readOnlyHint&&e.push("\u{1F4D6}"),o.destructiveHint&&e.push("\u26A0\uFE0F"),o.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function of(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}function yt(o,e,t){let n=[];return n.push(`${t.success?"\u2705":"\u274C"} ${o} "${e}": ${t.message}`),t.serverState&&(n.push(""),n.push(` Status: ${t.serverState.status}`),n.push(` Tools: ${t.serverState.toolCount} | Resources: ${t.serverState.resourceCount}`)),{content:[{type:"text",text:n.join(`
356
- `)}],details:{type:"mcp",action:"manage_server",manageAction:o,server:e,success:t.success}}}var nf="checkpoint",rf={type:"object",properties:{action:{type:"string",enum:["create","list","restore","diff"],description:"Action: create (snapshot current state), list (show checkpoints), restore (revert to checkpoint), diff (show changes since checkpoint)."},checkpointId:{type:"string",description:"Checkpoint ID. Required for restore and diff."},message:{type:"string",description:"Optional descriptive message for the checkpoint."},paths:{type:"array",items:{type:"string"},description:"File paths to restore (partial restore). Omit to restore everything."}},required:["action"]},rl=/^[0-9a-fA-F]{4,64}$/;function sl(o){return{name:nf,label:"Checkpoint",description:"Manage workspace checkpoints (shadow snapshots independent of user's git). Create snapshots before risky operations, list history, restore on errors, or diff to see what changed. Checkpoints do NOT affect user's .git.",parameters:rf,execute:async(e,t)=>{switch(t.action){case"create":{let n=await o.createCheckpoint(t.message);return n.success?{content:[{type:"text",text:`Checkpoint created: ${n.checkpoint.id}
355
+ `+(r.authUrl?`Re-authorize at: ${r.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:t.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${t.server}" (${r.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${t.server}": ${r.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"error"}}}}case"manage_server":{if(!t.server)return X("server is required for manage_server.");if(!t.manageAction)return X("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!o.addServer)return X("Server addition not supported by the current MCP host.");if(!t.config)return X("config is required for manage_server add.");let r=await o.addServer(t.server,t.config);return _t("add",t.server,r)}case"remove":{if(!o.removeServer)return X("Server removal not supported by the current MCP host.");let r=await o.removeServer(t.server);return _t("remove",t.server,r)}case"restart":{if(!o.restartServer)return X("Server restart not supported by the current MCP host.");let r=await o.restartServer(t.server);return _t("restart",t.server,r)}case"health_check":{if(!o.healthCheck)return X("Health check not supported by the current MCP host.");let r=await o.healthCheck(t.server);return _t("health_check",t.server,r)}case"enable":case"disable":{if(!o.setServerEnabled)return X("Server enable/disable not supported by the current MCP host.");let r=await o.setServerEnabled(t.server,t.manageAction==="enable");return _t(t.manageAction,t.server,r)}default:return X(`Unknown manageAction: ${t.manageAction}`)}}default:return X(`Unknown action: "${t.action}".`)}}}}function X(o){return{content:[{type:"text",text:`Error: ${o}`}],details:{type:"mcp",error:o}}}function Wf(o){switch(o){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 qf(o){if(!o)return"";let e=[];return o.readOnlyHint&&e.push("\u{1F4D6}"),o.destructiveHint&&e.push("\u26A0\uFE0F"),o.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function Hf(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}function _t(o,e,t){let n=[];return n.push(`${t.success?"\u2705":"\u274C"} ${o} "${e}": ${t.message}`),t.serverState&&(n.push(""),n.push(` Status: ${t.serverState.status}`),n.push(` Tools: ${t.serverState.toolCount} | Resources: ${t.serverState.resourceCount}`)),{content:[{type:"text",text:n.join(`
356
+ `)}],details:{type:"mcp",action:"manage_server",manageAction:o,server:e,success:t.success}}}var Gf="checkpoint",zf={type:"object",properties:{action:{type:"string",enum:["create","list","restore","diff"],description:"Action: create (snapshot current state), list (show checkpoints), restore (revert to checkpoint), diff (show changes since checkpoint)."},checkpointId:{type:"string",description:"Checkpoint ID. Required for restore and diff."},message:{type:"string",description:"Optional descriptive message for the checkpoint."},paths:{type:"array",items:{type:"string"},description:"File paths to restore (partial restore). Omit to restore everything."}},required:["action"]},Tl=/^[0-9a-fA-F]{4,64}$/;function kl(o){return{name:Gf,label:"Checkpoint",description:"Manage workspace checkpoints (shadow snapshots independent of user's git). Create snapshots before risky operations, list history, restore on errors, or diff to see what changed. Checkpoints do NOT affect user's .git.",parameters:zf,execute:async(e,t)=>{switch(t.action){case"create":{let n=await o.createCheckpoint(t.message);return n.success?{content:[{type:"text",text:`Checkpoint created: ${n.checkpoint.id}
357
357
  Message: ${n.checkpoint.message}
358
358
  Files: ${n.checkpoint.fileCount}`}],details:{type:"checkpoint",action:"create",checkpointId:n.checkpoint.id}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}}}case"list":{let n=await o.listCheckpoints();if(!n.checkpoints||n.checkpoints.length===0)return{content:[{type:"text",text:"No checkpoints available."}],details:{type:"checkpoint",action:"list",count:0}};let r=[`Checkpoints (${n.checkpoints.length}):`,""];for(let s of n.checkpoints)r.push(`- ${s.id.slice(0,8)} [${s.timestamp}] ${s.message} (${s.fileCount} files)`);return{content:[{type:"text",text:r.join(`
359
- `)}],details:{type:"checkpoint",action:"list",count:n.checkpoints.length}}}case"restore":{if(!t.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for restore."}],details:{type:"checkpoint",error:"missing_id"}};if(!rl.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await o.restoreCheckpoint(t.checkpointId,t.paths);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}};let r=t.paths?`(${t.paths.length} files)`:"(full workspace)";return{content:[{type:"text",text:`Restored to checkpoint ${t.checkpointId.slice(0,8)} ${r}`}],details:{type:"checkpoint",action:"restore",checkpointId:t.checkpointId}}}case"diff":{if(!t.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for diff."}],details:{type:"checkpoint",error:"missing_id"}};if(!rl.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await o.diffCheckpoint(t.checkpointId);return n.success?{content:[{type:"text",text:n.diff||"(no changes since checkpoint)"}],details:{type:"checkpoint",action:"diff",checkpointId:t.checkpointId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"checkpoint",error:"unknown_action"}}}}}}import*as ge from"node:fs";import*as bt from"node:path";function il(o,e){let t=ps(e);return{createCheckpoint:async n=>{try{ge.mkdirSync(t,{recursive:!0});let{execSync:r}=await import("node:child_process"),s=bt.join(t,".git");ge.existsSync(s)||(r("git init",{cwd:t,stdio:"pipe"}),r('git config user.email "checkpoint@agent"',{cwd:t,stdio:"pipe"}),r('git config user.name "Checkpoint"',{cwd:t,stdio:"pipe"})),ge.cpSync(o,t,{recursive:!0,filter:c=>!c.includes(".git")&&!c.includes("node_modules")}),r("git add -A",{cwd:t,stdio:"pipe"});let i=n||`checkpoint ${new Date().toISOString()}`;r(`git commit --allow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:t,stdio:"pipe"});let a=r("git rev-parse HEAD",{cwd:t,stdio:"pipe"}).toString().trim(),l=parseInt(r("git ls-files | wc -l",{cwd:t,stdio:"pipe"}).toString().trim(),10)||0;return{success:!0,checkpoint:{id:a,message:i,timestamp:new Date().toISOString(),fileCount:l}}}catch(r){return{success:!1,error:r.message}}},listCheckpoints:async()=>{try{let{execSync:n}=await import("node:child_process"),r=bt.join(t,".git");if(!ge.existsSync(r))return{success:!0,checkpoints:[]};let s=n('git log --format="%H|%aI|%s" --max-count=20',{cwd:t,stdio:"pipe"}).toString().trim();return s?{success:!0,checkpoints:s.split(`
360
- `).map(a=>{let[l="",c="",...u]=a.split("|");return{id:l,timestamp:c,message:u.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(n){return{success:!1,error:n.message}}},restoreCheckpoint:async(n,r)=>{try{let{execSync:s}=await import("node:child_process");if(r&&r.length>0)for(let i of r){s(`git checkout ${n} -- "${i}"`,{cwd:t,stdio:"pipe"});let a=bt.join(t,i),l=bt.join(o,i);ge.existsSync(a)&&ge.cpSync(a,l,{recursive:!0})}else s(`git checkout ${n} -- .`,{cwd:t,stdio:"pipe"}),ge.cpSync(t,o,{recursive:!0,filter:i=>!i.includes(".git")});return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async n=>{try{let{execSync:r}=await import("node:child_process");return{success:!0,diff:r(`git diff ${n} HEAD`,{cwd:t,stdio:"pipe"}).toString()}}catch(r){return{success:!1,error:r.message}}}}}var al="memory";var sf=["add","replace","remove","search"],ll={type:"object",properties:{action:{type:"string",enum:sf,description:["The operation to perform:","\u2022 'add' \u2014 Save a concise note about this user (\u2192 local notes, always visible)","\u2022 'replace' \u2014 Update an existing note by matching a substring (\u2192 local notes)","\u2022 'remove' \u2014 Delete a note by matching a substring (\u2192 local notes)","\u2022 'search' \u2014 Search across long-term memory, recalled facts, user profile, and media preferences"].join(`
359
+ `)}],details:{type:"checkpoint",action:"list",count:n.checkpoints.length}}}case"restore":{if(!t.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for restore."}],details:{type:"checkpoint",error:"missing_id"}};if(!Tl.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await o.restoreCheckpoint(t.checkpointId,t.paths);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}};let r=t.paths?`(${t.paths.length} files)`:"(full workspace)";return{content:[{type:"text",text:`Restored to checkpoint ${t.checkpointId.slice(0,8)} ${r}`}],details:{type:"checkpoint",action:"restore",checkpointId:t.checkpointId}}}case"diff":{if(!t.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for diff."}],details:{type:"checkpoint",error:"missing_id"}};if(!Tl.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await o.diffCheckpoint(t.checkpointId);return n.success?{content:[{type:"text",text:n.diff||"(no changes since checkpoint)"}],details:{type:"checkpoint",action:"diff",checkpointId:t.checkpointId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"checkpoint",error:"unknown_action"}}}}}}import*as he from"node:fs";import*as Rt from"node:path";function xl(o,e){let t=Cs(e);return{createCheckpoint:async n=>{try{he.mkdirSync(t,{recursive:!0});let{execSync:r}=await import("node:child_process"),s=Rt.join(t,".git");he.existsSync(s)||(r("git init",{cwd:t,stdio:"pipe"}),r('git config user.email "checkpoint@agent"',{cwd:t,stdio:"pipe"}),r('git config user.name "Checkpoint"',{cwd:t,stdio:"pipe"})),he.cpSync(o,t,{recursive:!0,filter:c=>!c.includes(".git")&&!c.includes("node_modules")}),r("git add -A",{cwd:t,stdio:"pipe"});let i=n||`checkpoint ${new Date().toISOString()}`;r(`git commit --allow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:t,stdio:"pipe"});let a=r("git rev-parse HEAD",{cwd:t,stdio:"pipe"}).toString().trim(),l=parseInt(r("git ls-files | wc -l",{cwd:t,stdio:"pipe"}).toString().trim(),10)||0;return{success:!0,checkpoint:{id:a,message:i,timestamp:new Date().toISOString(),fileCount:l}}}catch(r){return{success:!1,error:r.message}}},listCheckpoints:async()=>{try{let{execSync:n}=await import("node:child_process"),r=Rt.join(t,".git");if(!he.existsSync(r))return{success:!0,checkpoints:[]};let s=n('git log --format="%H|%aI|%s" --max-count=20',{cwd:t,stdio:"pipe"}).toString().trim();return s?{success:!0,checkpoints:s.split(`
360
+ `).map(a=>{let[l="",c="",...u]=a.split("|");return{id:l,timestamp:c,message:u.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(n){return{success:!1,error:n.message}}},restoreCheckpoint:async(n,r)=>{try{let{execSync:s}=await import("node:child_process");if(r&&r.length>0)for(let i of r){s(`git checkout ${n} -- "${i}"`,{cwd:t,stdio:"pipe"});let a=Rt.join(t,i),l=Rt.join(o,i);he.existsSync(a)&&he.cpSync(a,l,{recursive:!0})}else s(`git checkout ${n} -- .`,{cwd:t,stdio:"pipe"}),he.cpSync(t,o,{recursive:!0,filter:i=>!i.includes(".git")});return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async n=>{try{let{execSync:r}=await import("node:child_process");return{success:!0,diff:r(`git diff ${n} HEAD`,{cwd:t,stdio:"pipe"}).toString()}}catch(r){return{success:!1,error:r.message}}}}}var vl="memory";var Vf=["add","replace","remove","search"],wl={type:"object",properties:{action:{type:"string",enum:Vf,description:["The operation to perform:","\u2022 'add' \u2014 Save a concise note about this user (\u2192 local notes, always visible)","\u2022 'replace' \u2014 Update an existing note by matching a substring (\u2192 local notes)","\u2022 'remove' \u2014 Delete a note by matching a substring (\u2192 local notes)","\u2022 'search' \u2014 Search across long-term memory, recalled facts, user profile, and media preferences"].join(`
361
361
  `)},target:{type:"string",enum:["memory","user"],description:["Which note target to operate on (for add/replace/remove):","\u2022 'memory' \u2014 Your personal observations/notes about this user (default)","\u2022 'user' \u2014 User profile facts (preferences, timezone, etc.)"].join(`
362
362
  `)},content:{type:"string",description:["Required for 'add' and 'replace'. The note content to store.","Write a concise, factual statement.","Good: '\u7528\u6237\u662F\u540E\u7AEF\u5DE5\u7A0B\u5E08\uFF0C\u4E3B\u8981\u4F7F\u7528 TypeScript \u548C Go'","Good: 'User prefers dark UI themes and minimalist design'","Bad: '\u7528\u6237\u8BF4\u4E86\u5F88\u591A\u8BDD' (too vague)","Bad: entire conversation transcripts (too long)"].join(`
363
363
  `)},old_text:{type:"string",description:"Required for 'replace' and 'remove'. A substring that uniquely identifies the note entry to modify."},query:{type:"string",description:"Required for 'search'. Natural language query to find relevant memories."},category:{type:"string",enum:["profile","facts","media","projects"],description:["Optional for 'search': narrow the search to a specific category.","\u2022 'profile' \u2014 user preferences, expertise, communication style","\u2022 'facts' \u2014 recalled long-term memories","\u2022 'media' \u2014 media generation preferences (image style, music genre, etc.)","\u2022 'projects' \u2014 project context and tech stack","If omitted, searches across all sources."].join(`
364
- `)}},required:["action"]},cl=["Manage your notes about this user and search long-term memory.","","Your notes (add/replace/remove) are always visible in the system prompt.","Long-term memories are automatically extracted from every conversation","and searchable via 'search'.","","Guidelines:","- Use 'add' to record important user preferences, facts, or context","- Use 'replace' to update outdated notes (match by substring)","- Use 'remove' to delete incorrect notes (match by substring)","- Use 'search' to recall conversation history, user profile, and media preferences","- Keep notes concise \u2014 there's a character limit"].join(`
365
- `),ul="Memory",af=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i];function zn(o){return!af.some(e=>e.test(o))}async function dl(o,e){let{action:t}=o,n=o.target??"memory";if(t==="add"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=o.content?.trim();if(!r)return{ok:!1,message:"content is required for 'add' action.",action:t,errorCode:"empty_content"};if(r.length>2e3)return{ok:!1,message:`Content too long (${r.length} chars, max 2000).`,action:t,errorCode:"too_long"};let s=e.store.add(n,r);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="replace"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=o.old_text?.trim(),s=o.content?.trim();if(!r)return{ok:!1,message:"old_text is required for 'replace' action.",action:t,errorCode:"empty_old_text"};if(!s)return{ok:!1,message:"content is required for 'replace' action.",action:t,errorCode:"empty_content"};if(s.length>2e3)return{ok:!1,message:`Content too long (${s.length} chars, max 2000).`,action:t,errorCode:"too_long"};let i=e.store.replace(n,r,s);return{ok:i.ok,message:i.ok?`${i.message} [${i.usage}]`:i.message,action:t,entryCount:i.entryCount,usage:i.usage,storeModified:i.ok,errorCode:i.errorCode}}if(t==="remove"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=o.old_text?.trim();if(!r)return{ok:!1,message:"old_text is required for 'remove' action.",action:t,errorCode:"empty_old_text"};let s=e.store.remove(n,r);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="search"){let r=o.query?.trim();if(!r)return{ok:!1,message:"query is required for 'search' action.",action:t,errorCode:"empty_query"};let s=o.category,i=[],a;if(!s||s==="facts"||s==="projects")try{let l=await e.provider.search(r,e.userId,{limit:10});a=l,l.length>0&&i.push(`## Long-term Memory
364
+ `)}},required:["action"]},Sl=["Manage your notes about this user and search long-term memory.","","Your notes (add/replace/remove) are always visible in the system prompt.","Long-term memories are automatically extracted from every conversation","and searchable via 'search'.","","Guidelines:","- Use 'add' to record important user preferences, facts, or context","- Use 'replace' to update outdated notes (match by substring)","- Use 'remove' to delete incorrect notes (match by substring)","- Use 'search' to recall conversation history, user profile, and media preferences","- Keep notes concise \u2014 there's a character limit"].join(`
365
+ `),Cl="Memory",Kf=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i];function lr(o){return!Kf.some(e=>e.test(o))}async function _l(o,e){let{action:t}=o,n=o.target??"memory";if(t==="add"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=o.content?.trim();if(!r)return{ok:!1,message:"content is required for 'add' action.",action:t,errorCode:"empty_content"};if(r.length>2e3)return{ok:!1,message:`Content too long (${r.length} chars, max 2000).`,action:t,errorCode:"too_long"};let s=e.store.add(n,r);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="replace"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=o.old_text?.trim(),s=o.content?.trim();if(!r)return{ok:!1,message:"old_text is required for 'replace' action.",action:t,errorCode:"empty_old_text"};if(!s)return{ok:!1,message:"content is required for 'replace' action.",action:t,errorCode:"empty_content"};if(s.length>2e3)return{ok:!1,message:`Content too long (${s.length} chars, max 2000).`,action:t,errorCode:"too_long"};let i=e.store.replace(n,r,s);return{ok:i.ok,message:i.ok?`${i.message} [${i.usage}]`:i.message,action:t,entryCount:i.entryCount,usage:i.usage,storeModified:i.ok,errorCode:i.errorCode}}if(t==="remove"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=o.old_text?.trim();if(!r)return{ok:!1,message:"old_text is required for 'remove' action.",action:t,errorCode:"empty_old_text"};let s=e.store.remove(n,r);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="search"){let r=o.query?.trim();if(!r)return{ok:!1,message:"query is required for 'search' action.",action:t,errorCode:"empty_query"};let s=o.category,i=[],a;if(!s||s==="facts"||s==="projects")try{let l=await e.provider.search(r,e.userId,{limit:10});a=l,l.length>0&&i.push(`## Long-term Memory
366
366
  `+l.map((c,u)=>`${u+1}. [${c.blockId}] ${c.text}`).join(`
367
367
  `))}catch{}if((!s||s==="facts"||s==="projects")&&e.queryGraph)try{let l=e.queryGraph(r,e.userId);l.length>0&&i.push(`## Recalled Facts
368
368
  `+l.map(c=>`\u2022 ${c}`).join(`
@@ -371,14 +371,24 @@ Files: ${n.checkpoint.fileCount}`}],details:{type:"checkpoint",action:"create",c
371
371
  `+c.join(`
372
372
  `))}}catch{}return i.length===0?{ok:!0,message:"No matching memories found.",action:t,results:[]}:{ok:!0,message:i.join(`
373
373
 
374
- `),action:t,results:a}}return{ok:!1,message:`Unknown action: ${t}. Use 'add', 'replace', 'remove', or 'search'.`,action:t,errorCode:"unknown_action"}}import{readFile as lf,writeFile as cf,mkdir as uf,rename as df,unlink as pf}from"node:fs/promises";import{dirname as mf,join as pl}from"node:path";import{randomUUID as gf}from"node:crypto";async function ff(o,e){let t=mf(o);await uf(t,{recursive:!0});let n=pl(t,`.tmp-${gf()}`);try{await cf(n,e,"utf-8"),await df(n,o)}catch(r){throw await pf(n).catch(()=>{}),r}}async function hf(o){try{let e=await lf(o,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function yf(o,e){await ff(o,JSON.stringify(e,null,2)+`
375
- `)}var bf="memory.json";function oo(){return pl(ne(),bf)}async function ml(){return hf(oo())}async function Vn(o){let e={...o,savedAt:new Date().toISOString()};await yf(oo(),e)}import{readFileSync as Tf,existsSync as kf}from"node:fs";var Le=`
374
+ `),action:t,results:a}}return{ok:!1,message:`Unknown action: ${t}. Use 'add', 'replace', 'remove', or 'search'.`,action:t,errorCode:"unknown_action"}}import{readFile as Jf,writeFile as Yf,mkdir as Xf,rename as Qf,unlink as Zf}from"node:fs/promises";import{dirname as eh,join as Rl}from"node:path";import{randomUUID as th}from"node:crypto";async function oh(o,e){let t=eh(o);await Xf(t,{recursive:!0});let n=Rl(t,`.tmp-${th()}`);try{await Yf(n,e,"utf-8"),await Qf(n,o)}catch(r){throw await Zf(n).catch(()=>{}),r}}async function nh(o){try{let e=await Jf(o,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function rh(o,e){await oh(o,JSON.stringify(e,null,2)+`
375
+ `)}var sh="memory.json";function yo(){return Rl(H(),sh)}async function Ml(){return nh(yo())}async function cr(o){let e={...o,savedAt:new Date().toISOString()};await rh(yo(),e)}import{readFileSync as ih,existsSync as ah}from"node:fs";var Fe=`
376
376
  \xA7
377
- `,xf=2200,vf=1375,no=class{memoryEntries=[];userEntries=[];frozenSnapshot={memory:"",user:""};snapshotFrozen=!1;saveTimer=null;memoryCharLimit;userCharLimit;persistToDisk;constructor(e){this.memoryCharLimit=e?.memoryCharLimit??xf,this.userCharLimit=e?.userCharLimit??vf,this.persistToDisk=e?.persistToDisk??!1}loadFromSerialized(e){this.memoryEntries=fl(gl(e.memory??"")),this.userEntries=fl(gl(e.user??""))}serialize(){return{memory:this.memoryEntries.join(Le),user:this.userEntries.join(Le)}}async loadFromDisk(){let e=await ml();e&&this.loadFromSerialized(e)}loadFromDiskSync(){let e=oo();try{if(!kf(e))return;let t=Tf(e,"utf-8"),n=JSON.parse(t);this.loadFromSerialized(n)}catch{}}scheduleSave(){this.persistToDisk&&(this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(()=>{this.saveTimer=null,Vn(this.serialize()).catch(()=>{})},500))}async flush(){this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.persistToDisk&&await Vn(this.serialize())}freezeSnapshot(){this.frozenSnapshot={memory:this.renderBlock("memory",this.memoryEntries),user:this.renderBlock("user",this.userEntries)},this.snapshotFrozen=!0}getSystemPromptBlock(e){return this.snapshotFrozen||this.freezeSnapshot(),this.frozenSnapshot[e]}add(e,t){let n=t.trim();if(!n)return this.errorResult(e,"Content cannot be empty.","empty_content");if(!zn(n))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let r=this.entriesFor(e);if(r.includes(n))return this.successResult(e,"Entry already exists (no change).");if([...r,n].join(Le).length>this.charLimitFor(e)){let a=this.formatUsage(e);return this.errorResult(e,`Memory full (${a}). Remove old entries first.`,"over_limit")}return r.push(n),this.scheduleSave(),this.successResult(e,"Entry added.")}replace(e,t,n){let r=t.trim(),s=n.trim();if(!r)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");if(!s)return this.errorResult(e,"content cannot be empty.","empty_content");if(!zn(s))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let i=this.entriesFor(e),a=i.map((g,d)=>g.includes(r)?d:-1).filter(g=>g>=0);if(a.length===0)return this.errorResult(e,`No entry contains: "${Kn(r)}"`,"not_found");if(a.length>1&&new Set(a.map(d=>i[d])).size>1)return this.errorResult(e,`Multiple entries match: "${Kn(r)}" (${a.length} matches). Be more specific.`,"ambiguous_match");let l=a[0],c=[...i];if(c[l]=s,c.join(Le).length>this.charLimitFor(e)){let g=this.formatUsage(e);return this.errorResult(e,`Replacement would exceed limit (${g}).`,"over_limit")}return i[l]=s,this.scheduleSave(),this.successResult(e,"Entry replaced.")}remove(e,t){let n=t.trim();if(!n)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");let r=this.entriesFor(e),s=r.map((i,a)=>i.includes(n)?a:-1).filter(i=>i>=0);if(s.length===0)return this.errorResult(e,`No entry contains: "${Kn(n)}"`,"not_found");for(let i=s.length-1;i>=0;i--)r.splice(s[i],1);return this.scheduleSave(),this.successResult(e,s.length===1?"Entry removed.":`${s.length} entries removed.`)}getEntries(e){return this.entriesFor(e)}getUsage(e){let t=this.entriesFor(e),n=t.length>0?t.join(Le).length:0,r=this.charLimitFor(e);return{used:n,limit:r,percent:r>0?Math.round(n/r*100):0}}isEmpty(){return this.memoryEntries.length===0&&this.userEntries.length===0}entriesFor(e){return e==="user"?this.userEntries:this.memoryEntries}charLimitFor(e){return e==="user"?this.userCharLimit:this.memoryCharLimit}formatUsage(e){let{used:t,limit:n,percent:r}=this.getUsage(e);return`${r}% \u2014 ${t}/${n} chars`}renderBlock(e,t){if(t.length===0)return"";let n=e==="user"?"USER PROFILE":"MEMORY",r=this.formatUsage(e),s="\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",i=t.join(Le);return`${s}
377
+ `,lh=2200,ch=1375,bo=class{memoryEntries=[];userEntries=[];frozenSnapshot={memory:"",user:""};snapshotFrozen=!1;saveTimer=null;memoryCharLimit;userCharLimit;persistToDisk;constructor(e){this.memoryCharLimit=e?.memoryCharLimit??lh,this.userCharLimit=e?.userCharLimit??ch,this.persistToDisk=e?.persistToDisk??!1}loadFromSerialized(e){this.memoryEntries=Al(Pl(e.memory??"")),this.userEntries=Al(Pl(e.user??""))}serialize(){return{memory:this.memoryEntries.join(Fe),user:this.userEntries.join(Fe)}}async loadFromDisk(){let e=await Ml();e&&this.loadFromSerialized(e)}loadFromDiskSync(){let e=yo();try{if(!ah(e))return;let t=ih(e,"utf-8"),n=JSON.parse(t);this.loadFromSerialized(n)}catch{}}scheduleSave(){this.persistToDisk&&(this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(()=>{this.saveTimer=null,cr(this.serialize()).catch(()=>{})},500))}async flush(){this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.persistToDisk&&await cr(this.serialize())}freezeSnapshot(){this.frozenSnapshot={memory:this.renderBlock("memory",this.memoryEntries),user:this.renderBlock("user",this.userEntries)},this.snapshotFrozen=!0}getSystemPromptBlock(e){return this.snapshotFrozen||this.freezeSnapshot(),this.frozenSnapshot[e]}add(e,t){let n=t.trim();if(!n)return this.errorResult(e,"Content cannot be empty.","empty_content");if(!lr(n))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let r=this.entriesFor(e);if(r.includes(n))return this.successResult(e,"Entry already exists (no change).");if([...r,n].join(Fe).length>this.charLimitFor(e)){let a=this.formatUsage(e);return this.errorResult(e,`Memory full (${a}). Remove old entries first.`,"over_limit")}return r.push(n),this.scheduleSave(),this.successResult(e,"Entry added.")}replace(e,t,n){let r=t.trim(),s=n.trim();if(!r)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");if(!s)return this.errorResult(e,"content cannot be empty.","empty_content");if(!lr(s))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let i=this.entriesFor(e),a=i.map((p,d)=>p.includes(r)?d:-1).filter(p=>p>=0);if(a.length===0)return this.errorResult(e,`No entry contains: "${ur(r)}"`,"not_found");if(a.length>1&&new Set(a.map(d=>i[d])).size>1)return this.errorResult(e,`Multiple entries match: "${ur(r)}" (${a.length} matches). Be more specific.`,"ambiguous_match");let l=a[0],c=[...i];if(c[l]=s,c.join(Fe).length>this.charLimitFor(e)){let p=this.formatUsage(e);return this.errorResult(e,`Replacement would exceed limit (${p}).`,"over_limit")}return i[l]=s,this.scheduleSave(),this.successResult(e,"Entry replaced.")}remove(e,t){let n=t.trim();if(!n)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");let r=this.entriesFor(e),s=r.map((i,a)=>i.includes(n)?a:-1).filter(i=>i>=0);if(s.length===0)return this.errorResult(e,`No entry contains: "${ur(n)}"`,"not_found");for(let i=s.length-1;i>=0;i--)r.splice(s[i],1);return this.scheduleSave(),this.successResult(e,s.length===1?"Entry removed.":`${s.length} entries removed.`)}getEntries(e){return this.entriesFor(e)}getUsage(e){let t=this.entriesFor(e),n=t.length>0?t.join(Fe).length:0,r=this.charLimitFor(e);return{used:n,limit:r,percent:r>0?Math.round(n/r*100):0}}isEmpty(){return this.memoryEntries.length===0&&this.userEntries.length===0}entriesFor(e){return e==="user"?this.userEntries:this.memoryEntries}charLimitFor(e){return e==="user"?this.userCharLimit:this.memoryCharLimit}formatUsage(e){let{used:t,limit:n,percent:r}=this.getUsage(e);return`${r}% \u2014 ${t}/${n} chars`}renderBlock(e,t){if(t.length===0)return"";let n=e==="user"?"USER PROFILE":"MEMORY",r=this.formatUsage(e),s="\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",i=t.join(Fe);return`${s}
378
378
  ${n} (your personal notes) [${r}]
379
379
  ${s}
380
- ${i}`}successResult(e,t){let n=this.entriesFor(e);return{ok:!0,message:t,target:e,entries:n,entryCount:n.length,usage:this.formatUsage(e)}}errorResult(e,t,n){let r=this.entriesFor(e);return{ok:!1,message:t,target:e,entries:r,entryCount:r.length,usage:this.formatUsage(e),errorCode:n}}};function gl(o){return o.trim()?o.split(Le).map(e=>e.trim()).filter(Boolean):[]}function fl(o){let e=new Set;return o.filter(t=>e.has(t)?!1:(e.add(t),!0))}function Kn(o,e=60){return o.length<=e?o:`${o.slice(0,e-1).trimEnd()}\u2026`}Oo();Eo();import{readFile as wf}from"node:fs/promises";import{watch as Sf}from"node:fs";import{join as Cf}from"node:path";var _f=me,Rf="settings.json";function Mf(o){return Cf(o,_f,Rf)}async function Pf(o){try{let e=await wf(o,"utf-8");return JSON.parse(e)}catch{return null}}function Af(o,e,t,n){let r=!1;o.permissionMode&&o.permissionMode!==e.getMode()&&(e.setMode(o.permissionMode),n?.(`settings: permission mode \u2192 ${o.permissionMode}`),r=!0),o.permissionRules&&(e.replaceRules(o.permissionRules),n?.(`settings: ${o.permissionRules.length} permission rules loaded`),r=!0),o.defaultBehavior&&(e.setDefaultBehavior(o.defaultBehavior),n?.(`settings: default behavior \u2192 ${o.defaultBehavior}`),r=!0),r&&t&&t.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:o}).catch(()=>{})}function hl(o){let e=Mf(o.projectRoot),t=null,n=null,r=async()=>{let s=await Pf(e);s&&Af(s,o.ruleEngine,o.hooks,o.log)};r().catch(()=>{});try{t=Sf(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{r().catch(()=>{})},200)}),t.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),t?.close(),t=null}}var Jn=new Set;function qe(o){return Jn.add(o),()=>{Jn.delete(o)}}async function yl(){await Promise.all(Array.from(Jn).map(o=>o()))}import*as F from"node:fs";import*as re from"node:path";import{AGENT_RPC_ERROR_CODES as We,AGENT_RPC_PROTOCOL_VERSION as ro,isAgentRpcRequest as Ef}from"qlogicagent-runtime-contracts";var so=class{running=!1;activeTurn=null;verbose;transport;registry;agent=null;lastLlmConfigKey="";currentSessionId="";currentHooks=null;mcpManager=null;pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";sessionState=null;taskStore=new Lt;memoryPrefetchState=it();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;constructor(e){this.verbose=e.verbose,this.registry=new nt,this.transport=e.transport??new De({verbose:e.verbose}),this.taskStore.onTaskChange((t,n)=>{n&&this.sendNotification("task.updated",{taskId:t,type:n.type,lifecycle:n.lifecycle,label:n.label})}),Ra({log:{info:t=>this.log(t),warn:t=>this.log(`[warn] ${t}`),error:t=>this.log(`[error] ${t}`),debug:t=>{e.verbose&&this.log(`[debug] ${t}`)}},onExecProgress:t=>{this.sendNotification("turn.exec_progress",{output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,totalBytes:t.totalBytes})}})}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(!Ef(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}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{yl().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),this.transport.close()}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"initialize":this.handleInitialize(e);break;case"agent.ping":this.handlePing(e);break;case"thread.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"thread.list":this.handleThreadList(e);break;case"session.resume":this.handleSessionResume(e);break;case"thread.create":this.handleThreadCreate(e);break;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:We.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleInitialize(e){let t=e.params,n=t?.protocolVersion??"unknown",r=t?.host?.name??t?.hostName??"unknown",s=t?.host?.version??t?.hostVersion??"?",i=n.split(".")[0],a=ro.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${ro}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:We.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${ro}`});return}this.log(`[initialize] host=${r} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:ro,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:Ie().map(l=>l.function.name),streaming:!0,threads:!0}})}handleThreadCreate(e){let t=e.params,n=t?.id??fe();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&Nn(t.cwd),this.currentSessionId=n,this.sessionState=new at(n),this.memoryPrefetchState=it(),e.id!==void 0&&this.sendResponse(e.id,{id:n,title:t?.title,status:"active",createdAt:new Date().toISOString()})}async handleThreadList(e){let n=e.params?.limit??20;try{let s=(await Xs(n)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:new Date(i.lastActiveAt).toISOString(),lastActiveAt:new Date(i.lastActiveAt).toISOString()}));e.id!==void 0&&this.sendResponse(e.id,{threads:s})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:We.INTERNAL_ERROR,message:`Failed to list threads: ${r.message}`})}}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}handleAbort(e){let t=e.params?.turnId??"";this.log(`abort requested for turn ${t}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),e.id!==void 0&&this.sendResponse(e.id,{aborted:!0})}handleApprovalResponse(e){let t=e.params;if(!t)return;let n=t.approvalId,r=t.decision;if(!n||!r){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:n,decision:r==="approved"?"approved":"denied",updatedInput:t.updatedInput,permissionUpdate:t.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(s),e.id!==void 0&&this.sendResponse(e.id,{received:!0})}async handleSessionResume(e){let n=e.params?.sessionId;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:We.INVALID_PARAMS,message:"sessionId is required"});return}try{let r=await Ys(n);if(!r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:We.INVALID_PARAMS,message:`Session not found: ${n}`});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:We.INTERNAL_ERROR,message:`Failed to resume session: ${r.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??fe(),r=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;a?.workdir&&typeof a.workdir=="string"&&Nn(a.workdir),Sa(a?.mediaRelay);let l=Ie(),c=new Set(l.map(m=>m.function.name)),g=[...l,...i.filter(m=>!c.has(m.function.name))];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n}),r&&r!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),ai()),this.currentSessionId=r,this.sessionState=new at(r),this.memoryPrefetchState=it());let d=new AbortController;this.activeTurn=d,this.log(`turn ${n} starting (session: ${r})`);try{let m={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},h=this.resolveAgent(m);if(this.permissionChecker&&a?.permissions){let y=a.permissions;if(typeof y?.mode=="string"){let v=Un(y);this.permissionChecker.ruleEngineRef.setMode(v.mode)}}if(!h){this.sendNotification("turn.start",{turnId:n}),this.sendNotification("turn.error",{turnId:n,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 y=a?.workdir??process.cwd(),v=await ri(y,this.currentHooks??void 0);v.length>0&&(f=ni(v))}catch{}let T=await li({basePrompt:a?.systemPrompt,instructionBlock:f,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[ci()]});for(let y of s)y.role==="user"&&sn(r,y).catch(()=>{});for await(let y of h.run({turnId:n,sessionId:r,messages:s,tools:g,systemPrompt:T,config:m},d.signal)){let v=new Date().toISOString();switch(y.type){case"start":this.sendNotification("turn.start",{turnId:y.turnId});break;case"delta":this.sendNotification("turn.delta",{turnId:y.turnId,text:y.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:y.text,createdAt:v}});break;case"end":this.sendNotification("turn.end",{turnId:y.turnId,content:y.content,usage:y.usage,model:y.model,provider:y.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:y.content,createdAt:v}}),y.usage&&this.sessionState&&this.sessionState.addUsage(y.usage,y.model??this.currentModel),y.content&&sn(r,{role:"assistant",content:y.content}).catch(()=>{});break;case"error":this.sendNotification("turn.error",{turnId:y.turnId,error:y.error,code:y.code});break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:y.turnId,instruction:y.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:y.turnId,callId:y.callId,name:y.name,item:{id:y.callId,type:"tool_call",role:"assistant",toolName:y.name,toolCallId:y.callId,createdAt:v}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:y.turnId,callId:y.callId,name:y.name,ok:y.ok,...y.error?{error:y.error}:{},item:{id:`${y.callId}-result`,type:"tool_result",role:"assistant",toolName:y.name,toolCallId:y.callId,output:y.ok?"":y.error,approved:y.ok,createdAt:v}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:y.turnId,callId:y.callId,name:y.name,reason:y.reason,item:{id:`${y.callId}-blocked`,type:"tool_blocked",role:"system",toolName:y.name,toolCallId:y.callId,text:y.reason,approved:!1,createdAt:v}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:y.turnId,action:y.action,...y.detail?{detail:y.detail}:{},item:{id:`${n}-recovery-${fe().slice(0,8)}`,type:"recovery",role:"system",strategy:y.action,text:y.detail,createdAt:v}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:y.turnId,slug:y.slug,content:y.content,item:{id:`${n}-plan-${fe().slice(0,8)}`,type:"plan_update",role:"assistant",text:y.content,createdAt:v}});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState&&(Js(r,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:process.cwd(),messageCount:s.length}).catch(()=>{}),this.currentTransport&&this.currentApiKey&&m.summaryModel)){let y=this.sessionState.createSnapshot();Zs(r,{sessionId:r,createdAt:0,lastActiveAt:0,turnCount:y.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:m.summaryModel})}}catch(m){if(d.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let h=m instanceof Error?m.message:String(m);this.sendNotification("turn.error",{turnId:n,error:h,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===d&&(this.activeTurn=null)}}async handleDream(e){let t=e.params??{},n=t.turnId??fe(),r=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",l=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n});let c=new AbortController;this.activeTurn=c,this.log(`dream ${n} starting (session: ${r}, sessions reviewing: ${l.length})`);let u={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(u)){this.sendNotification("turn.start",{turnId:n}),this.sendNotification("turn.error",{turnId:n,error:"No LLM provider configured for dream.",code:"NO_PROVIDER"});return}this.sendNotification("turn.start",{turnId:n});try{let d={context:{memoryRoot:i,transcriptDir:a,currentSessionId:r,listSessionsSince:async()=>l},triggerConfig:{force:!0},transport:this.currentTransport,toolInvoker:{invoke:async(h,f,T,y)=>{let v=Ee(f);if(!v)return{result:"",error:`Unknown tool: ${f}`};let _=`tc_${fe().slice(0,8)}`;try{let M=JSON.parse(T),$=await v.execute(_,M,y);return{result:$.content.map(E=>E.text??"").join(`
381
- `),error:$.details?.error}}catch(M){return{result:"",error:M instanceof Error?M.message:String(M)}}}},tools:Ie(),apiKey:this.currentApiKey,model:u.model??this.currentModel,log:{info:h=>this.log(h),warn:h=>this.log(`[warn] ${h}`),error:h=>this.log(`[error] ${h}`),debug:h=>{this.verbose&&this.log(`[debug] ${h}`)}},hooks:this.currentHooks??void 0,parentSignal:c.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},m=await zs(d);m.ok?this.sendNotification("turn.end",{turnId:n,content:`Dream consolidation completed. ${m.sessionsReviewed} sessions reviewed, ${m.filesTouched.length} files touched. Duration: ${m.durationMs}ms.`,usage:{prompt:0,completion:0}}):this.sendNotification("turn.error",{turnId:n,error:m.error??"Dream consolidation failed",code:"DREAM_FAILED"}),this.log(`dream ${n} completed`)}catch(d){if(c.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Dream aborted",code:"ABORTED"});else{let m=d instanceof Error?d.message:String(d);this.sendNotification("turn.error",{turnId:n,error:m,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===c&&(this.activeTurn=null)}}resolveAgent(e){let t=`${e.provider??""}:${e.model??""}:${e.apiKey?.slice(0,8)??""}:${e.baseUrl??""}`;if(this.agent&&this.lastLlmConfigKey===t)return this.agent;let n=e.provider,r=e.model,s=e.apiKey,i=e.baseUrl;if(!n||!s){let p=en(this.registry);p&&(n=n??p.providerId,s=s??p.apiKey,r=r??p.defaultModel,this.log(`auto-detected provider: ${n}, model: ${r}`))}if(!n||!s){let p=this.loadSettingsSync();p&&(n=n??p.provider,s=s??p.apiKey,r=r??p.model,n&&s&&this.log(`loaded provider from settings.json: ${n}, model: ${r}`))}if(!n||!s)return null;r=r??this.registry.getProvider(n)?.defaultModel??"";let a=Qo({provider:n,model:r,apiKey:s,baseUrl:i},this.registry);tn()&&(a.transport=on(a.transport,this.currentSessionId||"default"));let l={info:p=>this.log(p),warn:p=>this.log(`[warn] ${p}`),error:p=>this.log(`[error] ${p}`),debug:p=>{this.verbose&&this.log(`[debug] ${p}`)}},c={invoke:async(p,b,w,S)=>{let R=Ee(b);if(!R)return{result:"",error:`Unknown tool: ${b}`};let U=`tc_${fe().slice(0,8)}`;try{let V=JSON.parse(w),ee=await R.execute(U,V,S),W=ee.content.map(N=>N.text??"").join(`
382
- `),I=ee.details?.error;return{result:W,error:I}}catch(V){return{result:"",error:V instanceof Error?V.message:String(V)}}}},u=Cs(l);this.currentHooks=u,this.taskStore.setHooks(u,this.currentSessionId??"");let g=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(g){let p=Ms({baseUrl:g,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=p,this.qmemoryUserId=this.currentSessionId??"default",_s(u,{memoryProvider:p,userId:this.currentSessionId??"default",log:{debug:b=>l.debug(b),warn:b=>l.warn(b)}},this.memoryPrefetchState)}Xr(u,l,{transport:a.transport,apiKey:a.apiKey});let d=e?.mcpServers,m=jn(d??{}),h=gs();try{if(F.existsSync(h)){let p=JSON.parse(F.readFileSync(h,"utf8")),b=jn(p),w=new Set(m.map(S=>S.name));m=[...m,...b.filter(S=>!w.has(S.name))]}}catch{}if(m.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new Jt({servers:m,log:l}),qe(async()=>{await this.mcpManager?.disconnectAll()});let p=()=>this.mcpManager;X(Ma(p)),X(Pa(p)),X(nl({listServers:async()=>{let b=this.mcpManager;return b?b.getConnectedServers().map(S=>({name:S,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async b=>{if(!this.mcpManager)return[];let S=`mcp__${b.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return ve().filter(R=>R.startsWith(S)).map(R=>({name:R.slice(S.length),prefixedName:R}))},callTool:async(b,w,S,R)=>{let V=`mcp__${b.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+w,ee=Ee(V);if(!ee)return{success:!1,error:`Tool not found: ${V}`};try{return{success:!0,content:(await ee.execute(`mcp_${Date.now()}`,S??{},R)).content.map(N=>N.text??"").join(`
383
- `)}}catch(W){return{success:!1,error:W.message}}},listResources:async b=>{let w=this.mcpManager;return w?(await w.listResources(b)).map(R=>({uri:R.uri,name:R.name,mimeType:R.mimeType,description:R.description,server:R.server})):[]},readResource:async(b,w)=>{let S=this.mcpManager;if(!S)throw new Error("MCP not initialized");return(await S.readResource(b,w)).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(),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(b=>{l.warn(`[mcp] connection error: ${b instanceof Error?b.message:b}`)})}let f=[],T=cs();F.existsSync(T)&&f.push(T);let y=e?.pluginPaths;if(Array.isArray(y))for(let p of y)typeof p=="string"&&F.existsSync(p)&&f.push(p);Oa(f,l).then(p=>{if(p.length===0)return;this.pluginLoader=new Xt({pluginDirs:p,hookRegistry:u,log:l}),this.pluginLoader.loadAll().then(w=>{l.info(`[plugins] ${w.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(w=>{l.warn(`[plugins] load error: ${w instanceof Error?w.message:w}`)});let b=this.pluginLoader;u.register({point:"turn.submitted",handler:async()=>(await b.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(p=>{l.warn(`[plugins] marketplace resolve error: ${p instanceof Error?p.message:p}`)});let v=e?.permissions,_=Un(v),M=new Zt(_);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new eo({ruleEngine:M,hookRegistry:u,onRequestApproval:async p=>(this.sendNotification("tool.approval.request",{approvalId:p.approvalId,callId:p.callId,toolName:p.toolName,arguments:p.arguments,message:p.message,suggestions:p.suggestions}),new Promise(()=>{})),onPermissionUpdate:p=>{l.info(`[permissions] rule saved: ${p.pattern} \u2192 ${p.behavior}`)},onDenied:(p,b)=>{l.warn(`[permissions] blocked "${p}": ${b}`)}});let $=Ie();this.permissionChecker.setToolMeta($),this.permissionUnregister=this.permissionChecker.register();let q=Ha({listSkills:()=>{let p=[];this.pluginLoader&&p.push(...this.pluginLoader.getPluginSkills());let b=e?.skillPaths;if(Array.isArray(b)){for(let w of b)if(typeof w=="string"){let S=re.basename(w);p.some(R=>R.name===S)||p.push({name:S,source:"gateway",filePath:re.join(w,"SKILL.md"),baseDir:w})}}return p},readSkillContent:async p=>{let b=[Rt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];for(let w of b){let S=re.join(w,p,"SKILL.md");try{return await F.promises.readFile(S,"utf8")}catch{}}return null},executeSkillSubturn:async(p,b,w,S)=>{let R=`skill_${p}_${fe().slice(0,8)}`,U=this.agent;if(!U)return"[skill] Cannot execute: no LLM provider configured";let V=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:V,turnId:R,subagentId:R,agentType:`skill:${p}`}).catch(()=>{});let ee=Ie(),W=w??`Execute skill "${p}" instructions.`,I=[],N;for await(let te of U.run({turnId:R,sessionId:V,messages:[{role:"user",content:W}],tools:ee,systemPrompt:b,config:{parentDepth:1}},S)){if(te.type==="end"&&te.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:V,turnId:R,subagentId:R,agentType:`skill:${p}`,reason:"normal"}).catch(()=>{}),te.content;if(te.type==="delta"&&te.text&&I.push(te.text),te.type==="error"){N=te.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:V,turnId:R,subagentId:R,agentType:`skill:${p}`,reason:N?"error":"normal",error:N}).catch(()=>{}),N?`[skill "${p}"] error: ${N}`:I.join("")||`[skill "${p}"] completed (no output)`}});X(q);let E=[Rt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];X(Ga({listSkills:async p=>{let b=[],w=new Set;for(let S of E)try{let R=await F.promises.readdir(S,{withFileTypes:!0});for(let U of R){if(!U.isDirectory())continue;let V=re.join(S,U.name,"SKILL.md");try{await F.promises.access(V);let ee=re.basename(S);if(p&&ee!==p)continue;w.add(ee),b.push({name:U.name,description:`Skill from ${S}`,category:ee})}catch{}}}catch{}if(this.pluginLoader)for(let S of this.pluginLoader.getPluginSkills())p&&S.source!==p||(w.add(S.source??"plugin"),b.push({name:S.name,description:`Plugin skill (${S.source})`,category:S.source}));return{skills:b,categories:[...w]}}})),X(za({viewSkill:async(p,b)=>{for(let w of E){let S=b?re.join(w,p,b):re.join(w,p,"SKILL.md");try{let R=await F.promises.readFile(S,"utf8");return{name:p,content:R}}catch{}}return null}})),X(Ka({manageSkill:async p=>{let b=re.join(E[0]??Rt(),p.name),w=re.join(b,"SKILL.md");switch(p.action){case"create":return await F.promises.mkdir(b,{recursive:!0}),await F.promises.writeFile(w,p.content??"","utf8"),{success:!0,message:`Skill "${p.name}" created`,path:b};case"edit":return await F.promises.writeFile(w,p.content??"","utf8"),{success:!0,message:`Skill "${p.name}" updated`,path:w};case"patch":{let S=await F.promises.readFile(w,"utf8");return!p.oldString||!S.includes(p.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await F.promises.writeFile(w,S.replace(p.oldString,p.newString??""),"utf8"),{success:!0,message:`Skill "${p.name}" patched`,path:w})}case"delete":return await F.promises.rm(b,{recursive:!0,force:!0}),{success:!0,message:`Skill "${p.name}" deleted`};case"write_file":{if(!p.filePath)return{success:!1,message:"filePath required for write_file"};let S=re.join(b,p.filePath);return await F.promises.mkdir(re.dirname(S),{recursive:!0}),await F.promises.writeFile(S,p.fileContent??"","utf8"),{success:!0,message:`File written: ${p.filePath}`,path:S}}case"remove_file":{if(!p.filePath)return{success:!1,message:"filePath required for remove_file"};let S=re.join(b,p.filePath);return await F.promises.unlink(S).catch(()=>{}),{success:!0,message:`File removed: ${p.filePath}`}}default:return{success:!1,message:`Unknown action: ${p.action}`}}}})),X(Xa({abortSignal:void 0,currentForkDepth:0,forkAgent:async p=>{let b=Io(p.agent);if(!b)return{agentId:"",status:"failed",error:`Unknown agent type: ${p.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let w=ve(),S=Ao(w,b),U=Ie().filter(N=>S.includes(N.function.name)),V=dn(U,!0),ee=p.maxTurns??b.maxTurns??200,W=await Pt({promptMessages:[{role:"user",content:p.prompt}],tools:V,transport:this.currentTransport,toolInvoker:c,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:u,forkLabel:`agent-${p.agent}`,maxTurns:ee,parentSignal:p.abortSignal,parentDepth:0,onEvent:N=>{N.type==="delta"&&N.text&&this.sendNotification("turn.subagent_delta",{agentType:p.agent,text:N.text})}}),I=W.events.filter(N=>N.type==="end"&&"content"in N).map(N=>N.content??"").join("")||W.events.filter(N=>N.type==="delta"&&"text"in N).map(N=>N.text).join("");return{agentId:`fork-${p.agent}-${fe().slice(0,8)}`,status:W.ok?"completed":"failed",output:I||void 0,error:W.error,tokensUsed:W.totalUsage.prompt+W.totalUsage.completion}}}));let O=Xo(),k=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"]}]]),D=async()=>{try{return JSON.parse(await F.promises.readFile(O,"utf8"))}catch{return{}}},K=async p=>{await F.promises.mkdir(re.dirname(O),{recursive:!0}),await F.promises.writeFile(O,JSON.stringify(p,null,2),"utf8")};X(Za({getConfig:async p=>{let b=k.get(p);if(!b)return{success:!1,error:`Unknown key: ${p}`};let w=await D(),S=p in w?w[p]:b.value;return{success:!0,setting:{...b,value:S,readOnly:ht.includes(p)}}},setConfig:async(p,b)=>{let w=k.get(p);if(!w)return{success:!1,error:`Unknown key: ${p}`};let S=await D(),R=p in S?S[p]:w.value;return S[p]=b,await K(S),{success:!0,previousValue:R,setting:{...w,value:b}}},listConfig:async()=>{let p=await D();return{success:!0,settings:[...k.values()].map(w=>({...w,value:w.key in p?p[w.key]:w.value,readOnly:ht.includes(w.key)}))}},resetConfig:async p=>{let b=k.get(p);if(!b)return{success:!1,error:`Unknown key: ${p}`};let w=await D();return delete w[p],await K(w),{success:!0,setting:b}},isValidKey:p=>k.has(p)}));let oe=new Map,Te=p=>{let b=/^(\d+)([smhd])$/.exec(p.trim());if(!b)return null;let w=parseInt(b[1],10),S=b[2];return w*({s:1e3,m:6e4,h:36e5,d:864e5}[S]??6e4)},Y=p=>{p.timerId&&clearTimeout(p.timerId);let b=Te(p.schedule);b&&(p.timerId=setTimeout(()=>{p.lastRunAt=new Date().toISOString(),p.repeat.completed++,p.lastStatus="success",l.info(`[cron] triggered job ${p.id} (${p.name})`),p.repeat.times===null||p.repeat.completed<p.repeat.times?Y(p):(p.state="paused",p.enabled=!1)},b),p.nextRunAt=new Date(Date.now()+b).toISOString())};qe(async()=>{for(let p of oe.values())p.timerId&&clearTimeout(p.timerId)}),X(el({createJob:async p=>{let b=`cron_${fe().slice(0,8)}`,w={id:b,name:p.name??`Job ${b}`,prompt:p.prompt,schedule:p.schedule,scheduleDisplay:p.schedule,state:"scheduled",enabled:!0,repeat:{times:p.repeat??null,completed:0},allowedTools:p.allowedTools};return oe.set(b,w),Y(w),{success:!0,job:{...w,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...oe.values()].map(b=>({...b,timerId:void 0}))}),getJob:async p=>{let b=oe.get(p);return b?{success:!0,job:{...b,timerId:void 0}}:{success:!1,error:`Job not found: ${p}`}},updateJob:async(p,b)=>{let w=oe.get(p);return w?(b.prompt!==void 0&&(w.prompt=b.prompt),b.schedule!==void 0&&(w.schedule=b.schedule,w.scheduleDisplay=b.schedule),b.name!==void 0&&(w.name=b.name),b.enabled!==void 0&&(w.enabled=b.enabled,w.state=b.enabled?"scheduled":"paused"),b.repeat!==void 0&&(w.repeat.times=b.repeat),b.allowedTools!==void 0&&(w.allowedTools=b.allowedTools),w.enabled?Y(w):w.timerId&&(clearTimeout(w.timerId),w.timerId=void 0),{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${p}`}},deleteJob:async p=>{let b=oe.get(p);return b?(b.timerId&&clearTimeout(b.timerId),oe.delete(p),{success:!0}):{success:!1,error:`Job not found: ${p}`}},pauseJob:async p=>{let b=oe.get(p);return b?(b.state="paused",b.enabled=!1,b.timerId&&(clearTimeout(b.timerId),b.timerId=void 0),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${p}`}},resumeJob:async p=>{let b=oe.get(p);return b?(b.state="scheduled",b.enabled=!0,Y(b),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${p}`}},triggerJob:async p=>{let b=oe.get(p);return b?(b.lastRunAt=new Date().toISOString(),b.repeat.completed++,b.lastStatus="success",{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${p}`}},validateSchedule:p=>Te(p)!==null||/^\d{1,2}\s/.test(p)?null:`Invalid schedule: ${p}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let L=new Map;qe(async()=>{for(let p of L.values())p.cleanup();L.clear()}),X(tl({startMonitor:async p=>{if(L.has(p.monitorId))return{action:"start",success:!1,error:`Monitor "${p.monitorId}" already exists.`};let b={monitorId:p.monitorId,source:p.source,target:p.target,conditions:p.conditions,startedAt:Date.now(),timeoutSeconds:p.timeoutSeconds,eventCount:0},w=()=>{};if(p.source==="file")try{let S=F.watch(p.target,{persistent:!1},()=>{b.eventCount++,l.info(`[monitor] file change detected: ${p.target}`)});w=()=>S.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${p.target}`}}if(p.timeoutSeconds>0){let S=setTimeout(()=>{let U=L.get(p.monitorId);U&&(U.cleanup(),L.delete(p.monitorId))},p.timeoutSeconds*1e3),R=w;w=()=>{clearTimeout(S),R()}}return L.set(p.monitorId,{info:b,cleanup:w}),{action:"start",success:!0,monitorId:p.monitorId}},stopMonitor:async p=>{let b=L.get(p);return b?(b.cleanup(),L.delete(p),{action:"stop",success:!0,monitorId:p}):{action:"stop",success:!1,error:`Monitor "${p}" not found.`}},listMonitors:async()=>[...L.values()].map(p=>p.info)}));let P=new Map;X(ol({createTeam:async p=>{if(P.has(p.teamName))return{success:!1,error:`Team "${p.teamName}" already exists.`};let b={name:p.teamName,description:p.description,leadId:this.currentSessionId??"default",members:p.members??[],createdAt:new Date().toISOString()};return P.set(p.teamName,b),{success:!0,team:b}},deleteTeam:async p=>P.has(p)?(P.delete(p),{success:!0}):{success:!1,error:`Team "${p}" not found.`},listTeams:async()=>({success:!0,teams:[...P.values()]}),getTeamStatus:async p=>{let b=P.get(p);return b?{success:!0,team:b}:{success:!1,error:`Team "${p}" not found.`}}}));{let p=new no({persistToDisk:!0});p.loadFromDiskSync();let b={providerId:"null",search:async()=>[],ingest:async()=>{}},w=this.qmemoryAdapter??b;X({name:al,label:ul,description:cl,parameters:ll,execute:async(S,R)=>{let U=await dl(R,{provider:w,store:p,userId:this.qmemoryUserId||this.currentSessionId||"default",sessionId:this.currentSessionId});return{content:[{type:"text",text:U.message}],details:{type:"memory",action:U.action,ok:U.ok}}}})}{let p=e?.workdir??process.cwd(),b=il(p,this.currentSessionId||"default");X(sl(b))}let ie=e?.workdir??process.cwd(),Q=hl({projectRoot:ie,ruleEngine:M,hooks:u,log:p=>l.info(`[settings] ${p}`)});qe(async()=>{Q()}),this.currentSessionId&&u.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let ae=e?.workdir??process.cwd();return ei({projectRoot:ae,sessionId:this.currentSessionId,hooks:u,log:p=>l.debug(p),onInstructionCacheReset:si}).then(p=>{this.fileWatcher=p,qe(async()=>{this.fileWatcher?.stop()})}).catch(p=>{l.warn(`[file-watcher] init error: ${p instanceof Error?p.message:p}`)}),this.agent=new tt({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:c,log:l,hooks:u,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=t,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=r,this.log(`created Agent (provider: ${n}, model: ${r})`),this.agent}loadSettingsSync(){try{let e=Xo();if(!F.existsSync(e))return;let t=F.readFileSync(e,"utf-8"),n=JSON.parse(t);return{provider:n.provider,model:n.model,apiKey:n.apiKey,baseUrl:n.baseUrl}}catch{return}}sendResponse(e,t,n){let r={jsonrpc:"2.0",id:e};n?r.error=n:r.result=t,this.writeStdout(r)}sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t};this.writeStdout(n)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
384
- `)}};function bl(o){let e={verbose:!1};for(let t of o.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}var Tl=bl(process.argv),If=new De({verbose:Tl.verbose}),kl=new so({verbose:Tl.verbose,transport:If}),xl=()=>{kl.stop(),process.exit(0)};process.on("SIGTERM",xl);process.on("SIGINT",xl);kl.start();
380
+ ${i}`}successResult(e,t){let n=this.entriesFor(e);return{ok:!0,message:t,target:e,entries:n,entryCount:n.length,usage:this.formatUsage(e)}}errorResult(e,t,n){let r=this.entriesFor(e);return{ok:!1,message:t,target:e,entries:r,entryCount:r.length,usage:this.formatUsage(e),errorCode:n}}};function Pl(o){return o.trim()?o.split(Fe).map(e=>e.trim()).filter(Boolean):[]}function Al(o){let e=new Set;return o.filter(t=>e.has(t)?!1:(e.add(t),!0))}function ur(o,e=60){return o.length<=e?o:`${o.slice(0,e-1).trimEnd()}\u2026`}Vo();Go();import{readFile as uh}from"node:fs/promises";import{watch as dh}from"node:fs";import{join as ph}from"node:path";var mh=fe,gh="settings.json";function fh(o){return ph(o,mh,gh)}async function hh(o){try{let e=await uh(o,"utf-8");return JSON.parse(e)}catch{return null}}function yh(o,e,t,n){let r=!1;o.permissionMode&&o.permissionMode!==e.getMode()&&(e.setMode(o.permissionMode),n?.(`settings: permission mode \u2192 ${o.permissionMode}`),r=!0),o.permissionRules&&(e.replaceRules(o.permissionRules),n?.(`settings: ${o.permissionRules.length} permission rules loaded`),r=!0),o.defaultBehavior&&(e.setDefaultBehavior(o.defaultBehavior),n?.(`settings: default behavior \u2192 ${o.defaultBehavior}`),r=!0),r&&t&&t.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:o}).catch(()=>{})}function El(o){let e=fh(o.projectRoot),t=null,n=null,r=async()=>{let s=await hh(e);s&&yh(s,o.ruleEngine,o.hooks,o.log)};r().catch(()=>{});try{t=dh(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{r().catch(()=>{})},200)}),t.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),t?.close(),t=null}}var dr=new Set;function Ve(o){return dr.add(o),()=>{dr.delete(o)}}async function Il(){await Promise.all(Array.from(dr).map(o=>o()))}import*as P from"node:fs";import*as Y from"node:path";import{AGENT_RPC_ERROR_CODES as te,AGENT_RPC_PROTOCOL_VERSION as To,isAgentRpcRequest as bh}from"qlogicagent-runtime-contracts";var Ol=["initialize","thread.create","thread.list","thread.turn","session.resume","session.getInfo","memory.list","memory.read","memory.write","memory.search","memory.delete","memory.dream","tools.list","config.get","config.update","todos.list","tasks.list","tasks.cancel","agent.ping","agent.abort","tool.approval.response"];var ko=class o{running=!1;activeTurn=null;verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentHooks=null;mcpManager=null;pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";sessionState=null;taskStore=new Vt;memoryPrefetchState=ft();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;constructor(e){this.verbose=e.verbose,this.registry=new pt,this.mediaClient=new ut({registry:this.registry}),this.transport=e.transport??new Be({verbose:e.verbose}),this.taskStore.onTaskChange((t,n)=>{n&&this.sendNotification("task.updated",{taskId:t,type:n.type,lifecycle:n.lifecycle,label:n.label})}),Wa({log:{info:t=>this.log(t),warn:t=>this.log(`[warn] ${t}`),error:t=>this.log(`[error] ${t}`),debug:t=>{e.verbose&&this.log(`[debug] ${t}`)}},onExecProgress:t=>{this.sendNotification("turn.exec_progress",{output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,totalBytes:t.totalBytes})}})}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(!bh(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}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{Il().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),this.transport.close()}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"initialize":this.handleInitialize(e);break;case"agent.ping":this.handlePing(e);break;case"thread.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"thread.list":this.handleThreadList(e);break;case"session.resume":this.handleSessionResume(e);break;case"thread.create":this.handleThreadCreate(e);break;case"session.getInfo":this.handleSessionGetInfo(e);break;case"memory.list":this.handleMemoryList(e);break;case"memory.read":this.handleMemoryRead(e);break;case"memory.write":this.handleMemoryWrite(e);break;case"memory.search":this.handleMemorySearch(e);break;case"memory.delete":this.handleMemoryDelete(e);break;case"tools.list":this.handleToolsList(e);break;case"config.get":this.handleConfigGet(e);break;case"config.update":this.handleConfigUpdate(e);break;case"todos.list":this.handleTodosList(e);break;case"tasks.list":this.handleTasksList(e);break;case"tasks.cancel":this.handleTasksCancel(e);break;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleInitialize(e){let t=e.params,n=t?.protocolVersion??"unknown",r=t?.host?.name??t?.hostName??"unknown",s=t?.host?.version??t?.hostVersion??"?",i=n.split(".")[0],a=To.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${To}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${To}`});return}this.log(`[initialize] host=${r} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:To,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:Ce().map(l=>l.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...Ol]}})}handleThreadCreate(e){let t=e.params,n=t?.id??ye();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&Zn(t.cwd),this.currentSessionId=n,this.sessionState=new ht(n),this.memoryPrefetchState=ft(),e.id!==void 0&&this.sendResponse(e.id,{id:n,title:t?.title,status:"active",createdAt:new Date().toISOString()})}async handleThreadList(e){let n=e.params?.limit??20;try{let s=(await mi(n)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:new Date(i.lastActiveAt).toISOString(),lastActiveAt:new Date(i.lastActiveAt).toISOString()}));e.id!==void 0&&this.sendResponse(e.id,{threads:s})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:`Failed to list threads: ${r.message}`})}}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}handleAbort(e){let t=e.params?.turnId??"";this.log(`abort requested for turn ${t}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),e.id!==void 0&&this.sendResponse(e.id,{aborted:!0})}handleApprovalResponse(e){let t=e.params;if(!t)return;let n=t.approvalId,r=t.decision;if(!n||!r){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:n,decision:r==="approved"?"approved":"denied",updatedInput:t.updatedInput,permissionUpdate:t.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(s),e.id!==void 0&&this.sendResponse(e.id,{received:!0})}async handleSessionResume(e){let n=e.params?.sessionId;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"sessionId is required"});return}try{let r=await pi(n);if(!r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Session not found: ${n}`});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:te.INTERNAL_ERROR,message:`Failed to resume session: ${r.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??ye(),r=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;a?.workdir&&typeof a.workdir=="string"&&Zn(a.workdir);{let m={},y=a?.provider,h=a?.apiKey;y&&h&&(m[y]=h);let k=a?.mediaApiKeys;k&&Object.assign(m,k),ja(this.mediaClient,m,(w,f,C)=>{this.sessionState?.addMediaUsage(w,f,C)})}let l=Ce(),c=new Set(l.map(m=>m.function.name)),p=[...l,...i.filter(m=>!c.has(m.function.name))];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n}),r&&r!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),wi()),this.currentSessionId=r,this.sessionState=new ht(r),this.memoryPrefetchState=ft());let d=new AbortController;this.activeTurn=d,this.log(`turn ${n} starting (session: ${r})`),this.sendNotification("turn.start",{turnId:n,model:a?.model??(this.currentModel||void 0),provider:a?.provider||void 0});try{let m={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(m);if(this.permissionChecker&&a?.permissions){let f=a.permissions;if(typeof f?.mode=="string"){let C=or(f);this.permissionChecker.ruleEngineRef.setMode(C.mode)}}if(!y){this.sendNotification("turn.error",{turnId:n,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 h,k=a?.workdir??process.cwd();try{let f=await ki(k,this.currentHooks??void 0);f.length>0&&(h=Ti(f))}catch{}let w=await Si({basePrompt:a?.systemPrompt,instructionBlock:h,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[Ci(k)]});for(let f of s)f.role==="user"&&xn(r,f).catch(()=>{});for await(let f of y.run({turnId:n,sessionId:r,messages:s,tools:p,systemPrompt:w,config:m},d.signal)){let C=new Date().toISOString();switch(f.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:f.turnId,text:f.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:f.text,createdAt:C}});break;case"end":if(this.sendNotification("turn.end",{turnId:f.turnId,content:f.content,usage:f.usage,model:f.model,provider:f.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:f.content,createdAt:C}}),f.usage&&this.sessionState){this.sessionState.addUsage(f.usage,f.model??this.currentModel);let R=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:f.turnId,usage:f.usage,model:f.model??this.currentModel,sessionCostUSD:R.totalInputTokens*3e-6+R.totalOutputTokens*15e-6})}f.content&&xn(r,{role:"assistant",content:f.content}).catch(()=>{});break;case"error":this.sendNotification("turn.error",{turnId:f.turnId,error:f.error,code:f.code});break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:f.turnId,instruction:f.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:f.turnId,callId:f.callId,name:f.name,arguments:f.arguments,item:{id:f.callId,type:"tool_call",role:"assistant",toolName:f.name,toolCallId:f.callId,arguments:f.arguments,createdAt:C}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:f.turnId,callId:f.callId,name:f.name,ok:f.ok,...f.error?{error:f.error}:{},...f.outputPreview?{outputPreview:f.outputPreview}:{},item:{id:`${f.callId}-result`,type:"tool_result",role:"assistant",toolName:f.name,toolCallId:f.callId,output:f.ok?f.outputPreview??"":f.error,approved:f.ok,createdAt:C}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:f.turnId,callId:f.callId,name:f.name,reason:f.reason,item:{id:`${f.callId}-blocked`,type:"tool_blocked",role:"system",toolName:f.name,toolCallId:f.callId,text:f.reason,approved:!1,createdAt:C}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:f.turnId,action:f.action,...f.detail?{detail:f.detail}:{},item:{id:`${n}-recovery-${ye().slice(0,8)}`,type:"recovery",role:"system",strategy:f.action,text:f.detail,createdAt:C}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:f.turnId,slug:f.slug,content:f.content,item:{id:`${n}-plan-${ye().slice(0,8)}`,type:"plan_update",role:"assistant",text:f.content,createdAt:C}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:f.turnId,text:f.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:f.turnId,items:f.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:f.turnId,mediaType:f.mediaType,url:f.url,...f.model?{model:f.model}:{},...f.provider?{provider:f.provider}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:f.turnId,artifactId:f.artifactId,type:f.artifactType,title:f.title,...f.filePath?{filePath:f.filePath}:{},...f.language?{language:f.language}:{},...f.content?{content:f.content}:{},...f.mimeType?{mimeType:f.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:f.turnId,subagentId:f.subagentId,agentType:f.agentType,...f.prompt?{prompt:f.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:f.turnId,subagentId:f.subagentId,agentType:f.agentType,ok:f.ok,...f.outputPreview?{outputPreview:f.outputPreview}:{},...f.error?{error:f.error}:{}});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){di(r,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:process.cwd(),messageCount:s.length}).catch(()=>{});let f=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:r,model:this.currentModel||void 0,cwd:process.cwd(),turnCount:f.turnCount}),this.currentTransport&&this.currentApiKey&&m.summaryModel&&gi(r,{sessionId:r,createdAt:0,lastActiveAt:0,turnCount:f.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:m.summaryModel}),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(n,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(m){if(d.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let y=m instanceof Error?m.message:String(m);this.sendNotification("turn.error",{turnId:n,error:y,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===d&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
381
+ Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
382
+ Be specific: "run the tests" beats "continue".
383
+ Stay silent if the next step isn't obvious.
384
+ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,n,r,s){if(t.filter(c=>c.role==="assistant").length<1)return;let l=[...t.slice(-6),{role:"user",content:o.SUGGESTION_PROMPT}];try{let c="";for await(let p of n.stream({model:s,messages:l,temperature:.3,maxTokens:200},r))p.type==="delta"&&(c+=p.text);let u=c.match(/\[[\s\S]*\]/);if(u){let p=JSON.parse(u[0]),d=Array.isArray(p)?p.filter(m=>typeof m.text=="string"&&m.text.length>0).slice(0,5):[];d.length>0&&this.sendNotification("turn.suggestions",{turnId:e,items:d})}}catch{}}async handleDream(e){let t=e.params??{},n=t.turnId??ye(),r=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",l=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n});let c=new AbortController;this.activeTurn=c,this.log(`dream ${n} starting (session: ${r}, sessions reviewing: ${l.length})`);let u={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(u)){this.sendNotification("turn.start",{turnId:n}),this.sendNotification("turn.error",{turnId:n,error:"No LLM provider configured for dream.",code:"NO_PROVIDER"});return}this.sendNotification("turn.start",{turnId:n});try{let d={context:{memoryRoot:i,transcriptDir:a,currentSessionId:r,listSessionsSince:async()=>l},triggerConfig:{force:!0},transport:this.currentTransport,toolInvoker:{invoke:async(y,h,k,w)=>{let f=we(h);if(!f)return{result:"",error:`Unknown tool: ${h}`};let C=`tc_${ye().slice(0,8)}`;try{let R=JSON.parse(k),L=await f.execute(C,R,w);return{result:L.content.map(D=>D.text??"").join(`
385
+ `),error:L.details?.error}}catch(R){return{result:"",error:R instanceof Error?R.message:String(R)}}}},tools:Ce(),apiKey:this.currentApiKey,model:u.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:c.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},m=await li(d);m.ok?this.sendNotification("turn.end",{turnId:n,content:`Dream consolidation completed. ${m.sessionsReviewed} sessions reviewed, ${m.filesTouched.length} files touched. Duration: ${m.durationMs}ms.`,usage:{prompt:0,completion:0}}):this.sendNotification("turn.error",{turnId:n,error:m.error??"Dream consolidation failed",code:"DREAM_FAILED"}),this.log(`dream ${n} completed`)}catch(d){if(c.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Dream aborted",code:"ABORTED"});else{let m=d instanceof Error?d.message:String(d);this.sendNotification("turn.error",{turnId:n,error:m,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===c&&(this.activeTurn=null)}}resolveAgent(e){let t=`${e.provider??""}:${e.model??""}:${e.apiKey?.slice(0,8)??""}:${e.baseUrl??""}`;if(this.agent&&this.lastLlmConfigKey===t)return this.agent;let n=e.provider,r=e.model,s=e.apiKey,i=e.baseUrl;if(!n||!s){let g=hn(this.registry);g&&(n=n??g.providerId,s=s??g.apiKey,r=r??g.defaultModel,this.log(`auto-detected provider: ${n}, model: ${r}`))}if(!n||!s){let g=this.loadSettingsSync();g&&(n=n??g.provider,s=s??g.apiKey,r=r??g.model,n&&s&&this.log(`loaded provider from settings.json: ${n}, model: ${r}`))}if(!n||!s)return null;r=r??this.registry.getProvider(n)?.defaultModel??"";let a=fn({provider:n,model:r,apiKey:s,baseUrl:i},this.registry);yn()&&(a.transport=bn(a.transport,this.currentSessionId||"default"));let l={info:g=>this.log(g),warn:g=>this.log(`[warn] ${g}`),error:g=>this.log(`[error] ${g}`),debug:g=>{this.verbose&&this.log(`[debug] ${g}`)}},c={invoke:async(g,b,v,_)=>{let M=we(b);if(!M)return{result:"",error:`Unknown tool: ${b}`};let W=`tc_${ye().slice(0,8)}`;try{let Z=JSON.parse(v),z=await M.execute(W,Z,_),j=z.content.map(N=>N.text??"").join(`
386
+ `),E=z.details?.error,O=z.details?.type;if(O&&["image","tts","video","music"].includes(O)){let N=z.details?.mediaUrls??[],Mt=O==="music"?"tts":O;for(let Pt of N)this.sendNotification("turn.media_result",{turnId:g,mediaType:Mt,url:Pt,model:z.details?.model,provider:z.details?.provider,...z.details?.durationMs?{durationSeconds:z.details.durationMs/1e3}:{}})}if(O==="todo"&&!E)try{let N=JSON.parse(j);N.todoList&&this.sendNotification("turn.todos_updated",{turnId:g,items:N.todoList,summary:{total:N.total??N.todoList.length,completed:N.completed??0,inProgress:N.inProgress??0,notStarted:N.notStarted??0}})}catch{}return{result:j,error:E}}catch(Z){return{result:"",error:Z instanceof Error?Z.message:String(Z)}}}},u=Bs(l);this.currentHooks=u,this.taskStore.setHooks(u,this.currentSessionId??"");let p=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(p){let g=Hs({baseUrl:p,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=g,this.qmemoryUserId=this.currentSessionId??"default",Ws(u,{memoryProvider:g,userId:this.currentSessionId??"default",log:{debug:b=>l.debug(b),warn:b=>l.warn(b)}},this.memoryPrefetchState)}ds(u,l,{transport:a.transport,apiKey:a.apiKey});let d=e?.mcpServers,m=er(d??{}),y=Rs();try{if(P.existsSync(y)){let g=JSON.parse(P.readFileSync(y,"utf8")),b=er(g),v=new Set(m.map(_=>_.name));m=[...m,...b.filter(_=>!v.has(_.name))]}}catch{}if(m.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new co({servers:m,log:l}),Ve(async()=>{await this.mcpManager?.disconnectAll()});let g=()=>this.mcpManager;ne(qa(g)),ne(Ha(g)),ne(bl({listServers:async()=>{let b=this.mcpManager;return b?b.getConnectedServers().map(_=>({name:_,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async b=>{if(!this.mcpManager)return[];let _=`mcp__${b.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return Se().filter(M=>M.startsWith(_)).map(M=>({name:M.slice(_.length),prefixedName:M}))},callTool:async(b,v,_,M)=>{let Z=`mcp__${b.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+v,z=we(Z);if(!z)return{success:!1,error:`Tool not found: ${Z}`};try{return{success:!0,content:(await z.execute(`mcp_${Date.now()}`,_??{},M)).content.map(O=>O.text??"").join(`
387
+ `)}}catch(j){return{success:!1,error:j.message}}},listResources:async b=>{let v=this.mcpManager;return v?(await v.listResources(b)).map(M=>({uri:M.uri,name:M.name,mimeType:M.mimeType,description:M.description,server:M.server})):[]},readResource:async(b,v)=>{let _=this.mcpManager;if(!_)throw new Error("MCP not initialized");return(await _.readResource(b,v)).map(W=>({uri:W.uri,mimeType:W.mimeType,text:W.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(b=>{l.warn(`[mcp] connection error: ${b instanceof Error?b.message:b}`)})}let h=[],k=ws();P.existsSync(k)&&h.push(k);let w=e?.pluginPaths;if(Array.isArray(w))for(let g of w)typeof g=="string"&&P.existsSync(g)&&h.push(g);Ka(h,l).then(g=>{if(g.length===0)return;this.pluginLoader=new po({pluginDirs:g,hookRegistry:u,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 b=this.pluginLoader;u.register({point:"turn.submitted",handler:async()=>(await b.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(g=>{l.warn(`[plugins] marketplace resolve error: ${g instanceof Error?g.message:g}`)});let f=e?.permissions,C=or(f),R=new mo(C);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new fo({ruleEngine:R,hookRegistry:u,onRequestApproval:async g=>(this.sendNotification("tool.approval.request",{approvalId:g.approvalId,callId:g.callId,toolName:g.toolName,arguments:g.arguments?JSON.stringify(g.arguments):"",message:g.message,suggestions:g.suggestions?.map(b=>`${b.pattern}:${b.behavior}`)}),new Promise(()=>{})),onPermissionUpdate:g=>{l.info(`[permissions] rule saved: ${g.pattern} \u2192 ${g.behavior}`),this.sendNotification("permission.rule_updated",{pattern:g.pattern,behavior:g.behavior})},onDenied:(g,b)=>{l.warn(`[permissions] blocked "${g}": ${b}`)}});let L=Ce();this.permissionChecker.setToolMeta(L),this.permissionUnregister=this.permissionChecker.register();let K=sl({listSkills:()=>{let g=[];this.pluginLoader&&g.push(...this.pluginLoader.getPluginSkills());let b=e?.skillPaths;if(Array.isArray(b)){for(let v of b)if(typeof v=="string"){let _=Y.basename(v);g.some(M=>M.name===_)||g.push({name:_,source:"gateway",filePath:Y.join(v,"SKILL.md"),baseDir:v})}}return g},readSkillContent:async g=>{let b=[Ut(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];for(let v of b){let _=Y.join(v,g,"SKILL.md");try{return await P.promises.readFile(_,"utf8")}catch{}}return null},executeSkillSubturn:async(g,b,v,_)=>{let M=`skill_${g}_${ye().slice(0,8)}`,W=this.agent;if(!W)return"[skill] Cannot execute: no LLM provider configured";let Z=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`}).catch(()=>{});let z=Ce(),j=v??`Execute skill "${g}" instructions.`,E=[],O;for await(let N of W.run({turnId:M,sessionId:Z,messages:[{role:"user",content:j}],tools:z,systemPrompt:b,config:{parentDepth:1}},_)){if(N.type==="end"&&N.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`,reason:"normal"}).catch(()=>{}),N.content;if(N.type==="delta"&&N.text&&E.push(N.text),N.type==="error"){O=N.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`,reason:O?"error":"normal",error:O}).catch(()=>{}),O?`[skill "${g}"] error: ${O}`:E.join("")||`[skill "${g}"] completed (no output)`}});ne(K);let D=[Ut(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];ne(il({listSkills:async g=>{let b=[],v=new Set;for(let _ of D)try{let M=await P.promises.readdir(_,{withFileTypes:!0});for(let W of M){if(!W.isDirectory())continue;let Z=Y.join(_,W.name,"SKILL.md");try{await P.promises.access(Z);let z=Y.basename(_);if(g&&z!==g)continue;v.add(z),b.push({name:W.name,description:`Skill from ${_}`,category:z})}catch{}}}catch{}if(this.pluginLoader)for(let _ of this.pluginLoader.getPluginSkills())g&&_.source!==g||(v.add(_.source??"plugin"),b.push({name:_.name,description:`Plugin skill (${_.source})`,category:_.source}));return{skills:b,categories:[...v]}}})),ne(al({viewSkill:async(g,b)=>{for(let v of D){let _=b?Y.join(v,g,b):Y.join(v,g,"SKILL.md");try{let M=await P.promises.readFile(_,"utf8");return{name:g,content:M}}catch{}}return null}})),ne(cl({manageSkill:async g=>{let b=Y.join(D[0]??Ut(),g.name),v=Y.join(b,"SKILL.md");switch(g.action){case"create":return await P.promises.mkdir(b,{recursive:!0}),await P.promises.writeFile(v,g.content??"","utf8"),{success:!0,message:`Skill "${g.name}" created`,path:b};case"edit":return await P.promises.writeFile(v,g.content??"","utf8"),{success:!0,message:`Skill "${g.name}" updated`,path:v};case"patch":{let _=await P.promises.readFile(v,"utf8");return!g.oldString||!_.includes(g.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await P.promises.writeFile(v,_.replace(g.oldString,g.newString??""),"utf8"),{success:!0,message:`Skill "${g.name}" patched`,path:v})}case"delete":return await P.promises.rm(b,{recursive:!0,force:!0}),{success:!0,message:`Skill "${g.name}" deleted`};case"write_file":{if(!g.filePath)return{success:!1,message:"filePath required for write_file"};let _=Y.join(b,g.filePath);return await P.promises.mkdir(Y.dirname(_),{recursive:!0}),await P.promises.writeFile(_,g.fileContent??"","utf8"),{success:!0,message:`File written: ${g.filePath}`,path:_}}case"remove_file":{if(!g.filePath)return{success:!1,message:"filePath required for remove_file"};let _=Y.join(b,g.filePath);return await P.promises.unlink(_).catch(()=>{}),{success:!0,message:`File removed: ${g.filePath}`}}default:return{success:!1,message:`Unknown action: ${g.action}`}}}})),ne(pl({abortSignal:void 0,currentForkDepth:0,forkAgent:async g=>{let b=zo(g.agent);if(!b)return{agentId:"",status:"failed",error:`Unknown agent type: ${g.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let v=Se(),_=Ho(v,b),W=Ce().filter(O=>_.includes(O.function.name)),Z=_n(W,!0),z=g.maxTurns??b.maxTurns??200,j=await Wt({promptMessages:[{role:"user",content:g.prompt}],tools:Z,transport:this.currentTransport,toolInvoker:c,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:u,forkLabel:`agent-${g.agent}`,maxTurns:z,parentSignal:g.abortSignal,parentDepth:0,onEvent:O=>{O.type==="delta"&&O.text&&this.sendNotification("turn.subagent_delta",{agentType:g.agent,text:O.text})}}),E=j.events.filter(O=>O.type==="end"&&"content"in O).map(O=>O.content??"").join("")||j.events.filter(O=>O.type==="delta"&&"text"in O).map(O=>O.text).join("");return{agentId:`fork-${g.agent}-${ye().slice(0,8)}`,status:j.ok?"completed":"failed",output:E||void 0,error:j.error,tokensUsed:j.totalUsage.prompt+j.totalUsage.completion}}}));let F=Ge(),T=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"]}]]),B=async()=>{try{return JSON.parse(await P.promises.readFile(F,"utf8"))}catch{return{}}},J=async g=>{await P.promises.mkdir(Y.dirname(F),{recursive:!0}),await P.promises.writeFile(F,JSON.stringify(g,null,2),"utf8")};ne(ml({getConfig:async g=>{let b=T.get(g);if(!b)return{success:!1,error:`Unknown key: ${g}`};let v=await B(),_=g in v?v[g]:b.value;return{success:!0,setting:{...b,value:_,readOnly:Ct.includes(g)}}},setConfig:async(g,b)=>{let v=T.get(g);if(!v)return{success:!1,error:`Unknown key: ${g}`};let _=await B(),M=g in _?_[g]:v.value;return _[g]=b,await J(_),{success:!0,previousValue:M,setting:{...v,value:b}}},listConfig:async()=>{let g=await B();return{success:!0,settings:[...T.values()].map(v=>({...v,value:v.key in g?g[v.key]:v.value,readOnly:Ct.includes(v.key)}))}},resetConfig:async g=>{let b=T.get(g);if(!b)return{success:!1,error:`Unknown key: ${g}`};let v=await B();return delete v[g],await J(v),{success:!0,setting:b}},isValidKey:g=>T.has(g)}));let Q=new Map,ke=g=>{let b=/^(\d+)([smhd])$/.exec(g.trim());if(!b)return null;let v=parseInt(b[1],10),_=b[2];return v*({s:1e3,m:6e4,h:36e5,d:864e5}[_]??6e4)},oe=g=>{g.timerId&&clearTimeout(g.timerId);let b=ke(g.schedule);b&&(g.timerId=setTimeout(()=>{g.lastRunAt=new Date().toISOString(),g.repeat.completed++,g.lastStatus="success",l.info(`[cron] triggered job ${g.id} (${g.name})`),g.repeat.times===null||g.repeat.completed<g.repeat.times?oe(g):(g.state="paused",g.enabled=!1)},b),g.nextRunAt=new Date(Date.now()+b).toISOString())};Ve(async()=>{for(let g of Q.values())g.timerId&&clearTimeout(g.timerId)}),ne(fl({createJob:async g=>{let b=`cron_${ye().slice(0,8)}`,v={id:b,name:g.name??`Job ${b}`,prompt:g.prompt,schedule:g.schedule,scheduleDisplay:g.schedule,state:"scheduled",enabled:!0,repeat:{times:g.repeat??null,completed:0},allowedTools:g.allowedTools};return Q.set(b,v),oe(v),{success:!0,job:{...v,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...Q.values()].map(b=>({...b,timerId:void 0}))}),getJob:async g=>{let b=Q.get(g);return b?{success:!0,job:{...b,timerId:void 0}}:{success:!1,error:`Job not found: ${g}`}},updateJob:async(g,b)=>{let v=Q.get(g);return v?(b.prompt!==void 0&&(v.prompt=b.prompt),b.schedule!==void 0&&(v.schedule=b.schedule,v.scheduleDisplay=b.schedule),b.name!==void 0&&(v.name=b.name),b.enabled!==void 0&&(v.enabled=b.enabled,v.state=b.enabled?"scheduled":"paused"),b.repeat!==void 0&&(v.repeat.times=b.repeat),b.allowedTools!==void 0&&(v.allowedTools=b.allowedTools),v.enabled?oe(v):v.timerId&&(clearTimeout(v.timerId),v.timerId=void 0),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},deleteJob:async g=>{let b=Q.get(g);return b?(b.timerId&&clearTimeout(b.timerId),Q.delete(g),{success:!0}):{success:!1,error:`Job not found: ${g}`}},pauseJob:async g=>{let b=Q.get(g);return b?(b.state="paused",b.enabled=!1,b.timerId&&(clearTimeout(b.timerId),b.timerId=void 0),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},resumeJob:async g=>{let b=Q.get(g);return b?(b.state="scheduled",b.enabled=!0,oe(b),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},triggerJob:async g=>{let b=Q.get(g);return b?(b.lastRunAt=new Date().toISOString(),b.repeat.completed++,b.lastStatus="success",{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},validateSchedule:g=>ke(g)!==null||/^\d{1,2}\s/.test(g)?null:`Invalid schedule: ${g}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let $=new Map;Ve(async()=>{for(let g of $.values())g.cleanup();$.clear()}),ne(hl({startMonitor:async g=>{if($.has(g.monitorId))return{action:"start",success:!1,error:`Monitor "${g.monitorId}" already exists.`};let b={monitorId:g.monitorId,source:g.source,target:g.target,conditions:g.conditions,startedAt:Date.now(),timeoutSeconds:g.timeoutSeconds,eventCount:0},v=()=>{};if(g.source==="file")try{let _=P.watch(g.target,{persistent:!1},()=>{b.eventCount++,l.info(`[monitor] file change detected: ${g.target}`)});v=()=>_.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${g.target}`}}if(g.timeoutSeconds>0){let _=setTimeout(()=>{let W=$.get(g.monitorId);W&&(W.cleanup(),$.delete(g.monitorId))},g.timeoutSeconds*1e3),M=v;v=()=>{clearTimeout(_),M()}}return $.set(g.monitorId,{info:b,cleanup:v}),{action:"start",success:!0,monitorId:g.monitorId}},stopMonitor:async g=>{let b=$.get(g);return b?(b.cleanup(),$.delete(g),{action:"stop",success:!0,monitorId:g}):{action:"stop",success:!1,error:`Monitor "${g}" not found.`}},listMonitors:async()=>[...$.values()].map(g=>g.info)}));let A=new Map;ne(yl({createTeam:async g=>{if(A.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let b={name:g.teamName,description:g.description,leadId:this.currentSessionId??"default",members:g.members??[],createdAt:new Date().toISOString()};return A.set(g.teamName,b),this.sendNotification("team.updated",{teamName:g.teamName,action:"created",members:b.members.map(v=>({agentName:v.name,role:v.role}))}),{success:!0,team:b}},deleteTeam:async g=>A.has(g)?(A.delete(g),this.sendNotification("team.updated",{teamName:g,action:"destroyed",members:[]}),{success:!0}):{success:!1,error:`Team "${g}" not found.`},listTeams:async()=>({success:!0,teams:[...A.values()]}),getTeamStatus:async g=>{let b=A.get(g);return b?{success:!0,team:b}:{success:!1,error:`Team "${g}" not found.`}}}));{let g=new bo({persistToDisk:!0});g.loadFromDiskSync();let b={providerId:"null",search:async()=>[],ingest:async()=>{}},v=this.qmemoryAdapter??b;ne({name:vl,label:Cl,description:Sl,parameters:wl,execute:async(_,M)=>{let W=await _l(M,{provider:v,store:g,userId:this.qmemoryUserId||this.currentSessionId||"default",sessionId:this.currentSessionId});return{content:[{type:"text",text:W.message}],details:{type:"memory",action:W.action,ok:W.ok}}}})}{let g=e?.workdir??process.cwd(),b=xl(g,this.currentSessionId||"default");ne(kl(b))}let le=e?.workdir??process.cwd(),se=El({projectRoot:le,ruleEngine:R,hooks:u,log:g=>l.info(`[settings] ${g}`)});Ve(async()=>{se()}),this.currentSessionId&&u.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let ce=e?.workdir??process.cwd();return hi({projectRoot:ce,sessionId:this.currentSessionId,hooks:u,log:g=>l.debug(g),onInstructionCacheReset:xi}).then(g=>{this.fileWatcher=g,Ve(async()=>{this.fileWatcher?.stop()})}).catch(g=>{l.warn(`[file-watcher] init error: ${g instanceof Error?g.message:g}`)}),this.agent=new st({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:c,log:l,hooks:u,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=t,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=r,this.log(`created Agent (provider: ${n}, model: ${r})`),this.agent}loadSettingsSync(){try{let e=Ge();if(!P.existsSync(e))return;let t=P.readFileSync(e,"utf-8"),n=JSON.parse(t);return{provider:n.provider,model:n.model,apiKey:n.apiKey,baseUrl:n.baseUrl}}catch{return}}handleSessionGetInfo(e){let t=this.currentSessionId||"default",n=this.sessionState?.createSnapshot(),r={sessionId:t,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:vs(t),agentHome:H(),settings:Ge()},usage:n?{turnCount:n.turnCount,inputTokens:n.totalInputTokens,outputTokens:n.totalOutputTokens}:void 0};e.id!==void 0&&this.sendResponse(e.id,r)}async handleMemoryList(e){let t=[],n=Y.join(H(),"memory.json");P.existsSync(n)&&t.push({id:"local",type:"json",path:n}),this.qmemoryAdapter&&t.push({id:"qmemory",type:"vector"}),e.id!==void 0&&this.sendResponse(e.id,{sources:t})}async handleMemoryRead(e){let t=e.params,n=t?.source??"local",r=t?.target??"memory";if(n==="local")try{let s=Y.join(H(),"memory.json"),i=await P.promises.readFile(s,"utf-8"),a=JSON.parse(i);e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:r,content:a[r]??""})}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:r,content:""})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Unknown memory source: ${n}`})}async handleMemoryWrite(e){let t=e.params,n=t?.target??"memory",r=t?.content;if(n!=="memory"&&n!=="user"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Invalid memory target: ${n}. Must be "memory" or "user".`});return}if(r==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"content is required."});return}try{let s=Y.join(H(),"memory.json"),i={};try{let a=await P.promises.readFile(s,"utf-8");i=JSON.parse(a)}catch{}i[n]=r,i.savedAt=new Date().toISOString(),await P.promises.mkdir(H(),{recursive:!0}),await P.promises.writeFile(s,JSON.stringify(i,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,target:n}),this.sendNotification("memory.updated",{target:n,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,r=Ce().map(s=>({name:s.function.name,description:s.function.description??"",parameters:s.function.parameters,source:"builtin"}));if(t?.category){let s=r.filter(i=>i.name.startsWith(t.category)||i.description.toLowerCase().includes(t.category.toLowerCase()));e.id!==void 0&&this.sendResponse(e.id,{tools:s,total:s.length})}else e.id!==void 0&&this.sendResponse(e.id,{tools:r,total:r.length})}handleConfigGet(e){try{let t=Ge(),n={};if(P.existsSync(t)){let r=P.readFileSync(t,"utf-8");n=JSON.parse(r)}e.id!==void 0&&this.sendResponse(e.id,{config:n,paths:{userSettings:t,agentHome:H()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleConfigUpdate(e){let t=e.params;if(!t?.updates||typeof t.updates!="object"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"updates (object) is required."});return}try{let n=Ge(),r={};try{let s=await P.promises.readFile(n,"utf-8");r=JSON.parse(s)}catch{}Object.assign(r,t.updates),await P.promises.mkdir(Y.dirname(n),{recursive:!0}),await P.promises.writeFile(n,JSON.stringify(r,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}async handleTodosList(e){let t=we("todo");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:ze([])});return}try{let r=(await t.execute("rpc-todos-list",{action:"list"},void 0)).content.map(a=>a.text??"").join(""),i=JSON.parse(r).todoList??[];e.id!==void 0&&this.sendResponse(e.id,{items:i,summary:ze(i)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:ze([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){try{let n=Y.join(H(),"memory.json"),r=await P.promises.readFile(n,"utf-8"),s=JSON.parse(r),i=[],a=t.query.toLowerCase();for(let[l,c]of Object.entries(s)){if(typeof c!="string")continue;let u=c.split(`
388
+ \xA7
389
+ `).filter(p=>p.trim());for(let p=0;p<u.length;p++)u[p].toLowerCase().includes(a)&&i.push({id:`local-${l}-${p}`,text:u[p],score:1,source:"local"})}e.id!==void 0&&this.sendResponse(e.id,{results:i.slice(0,t.limit??10)})}catch{e.id!==void 0&&this.sendResponse(e.id,{results:[]})}return}try{let n=t.userId??(this.qmemoryUserId||"default"),r=await this.qmemoryAdapter.search(t.query,n,{limit:t.limit??10});e.id!==void 0&&this.sendResponse(e.id,{results:r.map(s=>({id:s.blockId??"",text:s.text,score:s.score,source:"qmemory",metadata:s.metadata}))})}catch(n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}async handleMemoryDelete(e){let t=e.params;if(!t?.match){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"match is required."});return}let n=t.source??"local";if(n==="local"){let r=t.target??"memory";try{let s=Y.join(H(),"memory.json"),i=await P.promises.readFile(s,"utf-8"),a=JSON.parse(i),c=(a[r]??"").split(`
390
+ \xA7
391
+ `).filter(m=>m.trim()),u=c.length,p=c.filter(m=>!m.includes(t.match));a[r]=p.join(`
392
+ \xA7
393
+ `),a.savedAt=new Date().toISOString(),await P.promises.writeFile(s,JSON.stringify(a,null,2),"utf-8");let d=u-p.length;e.id!==void 0&&this.sendResponse(e.id,{ok:!0,removedCount:d,message:`Removed ${d} entries.`}),d>0&&this.sendNotification("memory.updated",{source:"local",target:r})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}else if(n==="qmemory"&&this.qmemoryAdapter)try{await this.qmemoryAdapter.remove(t.match),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,removedCount:1,message:"Removed from QMemory."}),this.sendNotification("memory.updated",{source:"qmemory"})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:n==="qmemory"?"QMemory not configured.":`Unknown source: ${n}`})}handleTasksList(e){let n=e.params?.lifecycle??"all",r=this.taskStore.getAllTasks(),s=n==="all"?r:r.filter(i=>i.lifecycle===n);e.id!==void 0&&this.sendResponse(e.id,{tasks:s.map(i=>({taskId:i.taskId,type:i.type,lifecycle:i.lifecycle,label:i.label}))})}handleTasksCancel(e){let t=e.params;if(!t?.taskId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"taskId is required."});return}let r=this.taskStore.getAllTasks().find(s=>s.taskId===t.taskId);if(!r){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} not found.`});return}if(r.lifecycle!=="running"&&r.lifecycle!=="pending"){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} is already ${r.lifecycle}.`});return}this.taskStore.updateTask(t.taskId,s=>(s.lifecycle="cancelled",s)),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,message:`Task ${t.taskId} cancelled.`})}sendResponse(e,t,n){let r={jsonrpc:"2.0",id:e};n?r.error=n:r.result=t,this.writeStdout(r)}sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t};this.writeStdout(n)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
394
+ `)}};function Ll(o){let e={verbose:!1};for(let t of o.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}var $l=Ll(process.argv),Th=new Be({verbose:$l.verbose}),Dl=new ko({verbose:$l.verbose,transport:Th}),Nl=()=>{Dl.stop(),process.exit(0)};process.on("SIGTERM",Nl);process.on("SIGINT",Nl);Dl.start();