qlogicagent 2.3.0 → 2.4.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 (65) hide show
  1. package/dist/agent.js +6 -6
  2. package/dist/cli.js +212 -211
  3. package/dist/index.js +211 -210
  4. package/dist/orchestration.js +2 -2
  5. package/dist/protocol.js +1 -0
  6. package/dist/types/agent/tunable-defaults.d.ts +4 -0
  7. package/dist/types/agent/types.d.ts +24 -100
  8. package/dist/types/cli/stdio-server.d.ts +7 -0
  9. package/dist/types/cli/tool-bootstrap.d.ts +6 -0
  10. package/dist/types/contracts/index.d.ts +2 -3
  11. package/dist/types/llm/provider-def.d.ts +3 -0
  12. package/dist/types/llm/transport.d.ts +25 -25
  13. package/dist/types/llm/transports/anthropic-messages.d.ts +2 -2
  14. package/dist/types/llm/transports/gemini-generatecontent.d.ts +2 -2
  15. package/dist/types/llm/transports/openai-chat.d.ts +2 -2
  16. package/dist/types/llm/transports/openai-responses.d.ts +9 -9
  17. package/dist/types/llm/transports/volcengine-responses.d.ts +11 -11
  18. package/dist/types/orchestration/agent-instance.d.ts +15 -0
  19. package/dist/types/orchestration/solo-evaluator.d.ts +7 -0
  20. package/dist/types/orchestration/tool-loop/tool-choice-policy.d.ts +1 -1
  21. package/dist/types/protocol/methods.d.ts +143 -53
  22. package/dist/types/protocol/notifications.d.ts +4 -514
  23. package/dist/types/protocol/wire/acp-protocol.d.ts +411 -0
  24. package/dist/types/protocol/wire/agent-events.d.ts +32 -0
  25. package/dist/types/protocol/wire/agent-methods.d.ts +587 -0
  26. package/dist/types/protocol/wire/agent-rpc.d.ts +97 -0
  27. package/dist/types/protocol/wire/capability-manifest.d.ts +111 -0
  28. package/dist/types/protocol/wire/capability-transport.d.ts +207 -0
  29. package/dist/types/protocol/wire/channel-ingress.d.ts +29 -0
  30. package/dist/types/protocol/wire/channel.d.ts +89 -0
  31. package/dist/types/protocol/wire/chat-types.d.ts +87 -0
  32. package/dist/types/protocol/wire/checkpoint-runtime.d.ts +61 -0
  33. package/dist/types/protocol/wire/checkpoint.d.ts +72 -0
  34. package/dist/types/protocol/wire/execution.d.ts +391 -0
  35. package/dist/types/protocol/wire/gateway-rpc.d.ts +314 -0
  36. package/dist/types/protocol/wire/gateway.d.ts +62 -0
  37. package/dist/types/protocol/wire/hook-protocol.d.ts +37 -0
  38. package/dist/types/protocol/wire/index.d.ts +25 -0
  39. package/dist/types/protocol/wire/memory-provider-lifecycle.d.ts +80 -0
  40. package/dist/types/protocol/wire/notification-payloads.d.ts +581 -0
  41. package/dist/types/protocol/wire/provider-runtime-contract.d.ts +66 -0
  42. package/dist/types/protocol/wire/provider-runtime-core.d.ts +147 -0
  43. package/dist/types/protocol/wire/provider-runtime-io.d.ts +20 -0
  44. package/dist/types/protocol/wire/resource-manifest.d.ts +68 -0
  45. package/dist/types/protocol/wire/session.d.ts +32 -0
  46. package/dist/types/protocol/wire/thread-protocol.d.ts +157 -0
  47. package/dist/types/protocol/wire/transport.d.ts +57 -0
  48. package/dist/types/protocol/wire/turn.d.ts +208 -0
  49. package/dist/types/protocol/wire/web-capability.d.ts +51 -0
  50. package/dist/types/runtime/hooks/memory-hooks.d.ts +2 -2
  51. package/dist/types/runtime/infra/acp-types.d.ts +3 -142
  52. package/dist/types/runtime/infra/token-budget.d.ts +3 -3
  53. package/dist/types/runtime/session/index.d.ts +1 -1
  54. package/dist/types/runtime/session/session-memory.d.ts +46 -0
  55. package/dist/types/runtime/session/session-persistence.d.ts +34 -8
  56. package/dist/types/runtime/session/session-state.d.ts +4 -4
  57. package/dist/types/skills/memory/memory-tool.d.ts +1 -1
  58. package/dist/types/skills/memory/qmemory-adapter.d.ts +1 -1
  59. package/dist/types/skills/permissions/hook-runner.d.ts +4 -4
  60. package/dist/types/skills/permissions/permission-classifier.d.ts +2 -2
  61. package/dist/types/skills/tools/project-switch-tool.d.ts +24 -0
  62. package/dist/types/skills/tools.d.ts +5 -5
  63. package/dist/types/transport/acp-event-emitter.d.ts +1 -1
  64. package/dist/types/transport/acp-server.d.ts +17 -10
  65. package/package.json +14 -3
package/dist/index.js CHANGED
@@ -1,45 +1,45 @@
1
- var wm=Object.defineProperty;var ee=(r,e)=>()=>(r&&(e=r(r=0)),e);var Pa=(r,e)=>{for(var t in e)wm(r,t,{get:e[t],enumerable:!0})};function We(r){if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(n=>We(n));let e=r,t={};for(let[n,o]of Object.entries(e))if(!vm.has(n)){if(n==="properties"&&o&&typeof o=="object"&&!Array.isArray(o)){t[n]=Object.fromEntries(Object.entries(o).map(([s,i])=>[s,We(i)]));continue}if(n==="items"&&o&&typeof o=="object"){t[n]=Array.isArray(o)?o.map(s=>We(s)):We(o);continue}if((n==="anyOf"||n==="oneOf"||n==="allOf")&&Array.isArray(o)){t[n]=o.map(s=>We(s));continue}if(o&&typeof o=="object"&&!Array.isArray(o)){t[n]=We(o);continue}if(Array.isArray(o)){t[n]=o.map(s=>We(s));continue}t[n]=o}return t}var vm,$r=ee(()=>{"use strict";vm=new Set(["patternProperties","additionalProperties","$schema","$id","$ref","$defs","definitions","examples","minLength","maxLength","minimum","maximum","multipleOf","pattern","format","minItems","maxItems","uniqueItems","minProperties","maxProperties","const"])});function Ur(r,e,t,n){return{role:"assistant",content:e||null,tool_calls:r,...t&&t.length>0?{thinkingBlocks:t}:{},...n?{reasoning_content:n}:{}}}function Zt(r,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:r,content:t,...!e.ok&&{is_error:!0},...e.toolReferences?.length?{toolReferences:e.toolReferences}:{},...e.imageUrls?.length?{imageUrls:e.imageUrls}:{}}}var Ma=ee(()=>{"use strict";$r()});function Tt(r,e){if(!r)return!1;let t=r.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(t):t.includes(n))}function Nm(r){return Tt(r,kt.format)}function Ea(r){return Tt(r,kt.rateLimit)}function jm(r){return Tt(r,kt.timeout)}function Fm(r){return Sm.test(r)}function Nr(r){let e=r.toLowerCase();return e?r.length>_m?Rm.test(e):Tt(e,kt.billing)?!0:xm.test(r)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function Oa(r){return Tt(r,kt.authPermanent)}function Bm(r){return Tt(r,kt.auth)}function Da(r){return Tt(r,kt.overloaded)}function bt(r,e){return e.some(t=>r.includes(t))}function Gm(r){return bt(r,Im)||bt(r,Pm)&&r.includes("limit")||r.includes("billing hard limit")||r.includes("hard limit reached")||r.includes("maximum allowed")&&r.includes("limit")}function Hm(r){let e=bt(r,Mm),t=r.includes("spend limit")||r.includes("spending limit"),n=bt(r,Dm);return bt(r,Em)&&bt(r,Om)||e&&(r.includes("usage limit")||t)||e&&r.includes("limit")&&r.includes("reset")||n&&r.includes("limit")&&(t||bt(r,Lm))}function Wm(r){return r.trim().toLowerCase().replace(Um,"").trim()}function La(r){let e=Wm(r);return!e||Gm(e)?"billing":Ea(e)||Hm(e)?"rate_limit":"billing"}function zm(r){return $m.test(r)?La(r):null}function $a(r){let e=r.match(Cm);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function Vm(r){if(!r)return!1;let e=r.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function qm(r){let e=r.trim();if(!e)return!1;let t=$a(e);return t?Am.has(t.code):!1}function Ua(r,e){return typeof r!="number"||!Number.isFinite(r)?null:r===402?e?La(e):"billing":r===429?"rate_limit":r===401||r===403?e&&Oa(e)?"auth_permanent":"auth":r===408?"timeout":r===503?e&&Da(e)?"overloaded":"timeout":r===502||r===504?"timeout":r===529?"overloaded":r===400?e&&Nr(e)?"billing":"format":null}function Km(r){if(!r)return!1;let e=r.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(r)||/\b404\b/.test(r)&&/not[-_ ]?found/i.test(r))}function Jm(r){if(!r)return!1;let e=r.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 Na(r){if(Jm(r))return"session_expired";if(Km(r))return"model_not_found";let e=zm(r);return e||(Fm(r)?Nr(r)?"billing":"rate_limit":Ea(r)?"rate_limit":Da(r)?"overloaded":qm(r)?$a(r.trim())?.code===529?"overloaded":"timeout":Vm(r)?"timeout":Nm(r)?"format":Nr(r)?"billing":jm(r)?"timeout":Oa(r)?"auth_permanent":Bm(r)?"auth":null)}var Sm,kt,xm,Rm,_m,Cm,Am,Im,Pm,Mm,Em,Om,Dm,Lm,$m,Um,ja=ee(()=>{"use strict";Sm=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,kt={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]},xm=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Rm=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,_m=512,Cm=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,Am=new Set([500,502,503,504,521,522,523,524,529]),Im=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Pm=["upgrade your plan","upgrade plan","current plan","subscription"],Mm=["daily","weekly","monthly"],Em=["try again","retry","temporary","cooldown"],Om=["usage limit","rate limit","organization usage"],Dm=["organization","workspace"],Lm=["billing period","exceeded","reached","exhausted"],$m=/["']?(?: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,Um=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function Nt(r,e){let t=Ua(r,e)??(e?Na(e):null);return t?Xm[t]:typeof r=="number"&&r>=400&&r<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function jr(r){return Ym.has(r)}var Xm,Ym,Fa=ee(()=>{"use strict";ja();Xm={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"},Ym=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"])});function rn(r){return typeof r.compressAsync=="function"}function Qm(r,e){if(r.length<=e)return r;let t=r.slice(0,e);if(r.trimStart().startsWith("{")||r.trimStart().startsWith("[")){let s=Math.max(t.lastIndexOf("},"),t.lastIndexOf("],"),t.lastIndexOf(`}
1
+ var Dm=Object.defineProperty;var te=(r,e)=>()=>(r&&(e=r(r=0)),e);var Na=(r,e)=>{for(var t in e)Dm(r,t,{get:e[t],enumerable:!0})};function qe(r){if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(n=>qe(n));let e=r,t={};for(let[n,o]of Object.entries(e))if(!Lm.has(n)){if(n==="properties"&&o&&typeof o=="object"&&!Array.isArray(o)){t[n]=Object.fromEntries(Object.entries(o).map(([s,i])=>[s,qe(i)]));continue}if(n==="items"&&o&&typeof o=="object"){t[n]=Array.isArray(o)?o.map(s=>qe(s)):qe(o);continue}if((n==="anyOf"||n==="oneOf"||n==="allOf")&&Array.isArray(o)){t[n]=o.map(s=>qe(s));continue}if(o&&typeof o=="object"&&!Array.isArray(o)){t[n]=qe(o);continue}if(Array.isArray(o)){t[n]=o.map(s=>qe(s));continue}t[n]=o}return t}var Lm,jr=te(()=>{"use strict";Lm=new Set(["patternProperties","additionalProperties","$schema","$id","$ref","$defs","definitions","examples","minLength","maxLength","minimum","maximum","multipleOf","pattern","format","minItems","maxItems","uniqueItems","minProperties","maxProperties","const"])});function Fr(r,e,t,n){return{role:"assistant",content:e||null,tool_calls:r,...t&&t.length>0?{thinkingBlocks:t}:{},...n?{reasoning_content:n}:{}}}function on(r,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:r,content:t,...!e.ok&&{is_error:!0},...e.toolReferences?.length?{toolReferences:e.toolReferences}:{},...e.imageUrls?.length?{imageUrls:e.imageUrls}:{}}}var Ua=te(()=>{"use strict";jr()});function vt(r,e){if(!r)return!1;let t=r.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(t):t.includes(n))}function Jm(r){return vt(r,wt.format)}function $a(r){return vt(r,wt.rateLimit)}function Qm(r){return vt(r,wt.timeout)}function Zm(r){return Nm.test(r)}function Br(r){let e=r.toLowerCase();return e?r.length>jm?$m.test(e):vt(e,wt.billing)?!0:Um.test(r)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function ja(r){return vt(r,wt.authPermanent)}function eg(r){return vt(r,wt.auth)}function Fa(r){return vt(r,wt.overloaded)}function Tt(r,e){return e.some(t=>r.includes(t))}function tg(r){return Tt(r,Wm)||Tt(r,Gm)&&r.includes("limit")||r.includes("billing hard limit")||r.includes("hard limit reached")||r.includes("maximum allowed")&&r.includes("limit")}function ng(r){let e=Tt(r,Hm),t=r.includes("spend limit")||r.includes("spending limit"),n=Tt(r,Km);return Tt(r,Vm)&&Tt(r,zm)||e&&(r.includes("usage limit")||t)||e&&r.includes("limit")&&r.includes("reset")||n&&r.includes("limit")&&(t||Tt(r,qm))}function og(r){return r.trim().toLowerCase().replace(Ym,"").trim()}function Ba(r){let e=og(r);return!e||tg(e)?"billing":$a(e)||ng(e)?"rate_limit":"billing"}function rg(r){return Xm.test(r)?Ba(r):null}function Wa(r){let e=r.match(Fm);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function sg(r){if(!r)return!1;let e=r.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function ig(r){let e=r.trim();if(!e)return!1;let t=Wa(e);return t?Bm.has(t.code):!1}function Ga(r,e){return typeof r!="number"||!Number.isFinite(r)?null:r===402?e?Ba(e):"billing":r===429?"rate_limit":r===401||r===403?e&&ja(e)?"auth_permanent":"auth":r===408?"timeout":r===503?e&&Fa(e)?"overloaded":"timeout":r===502||r===504?"timeout":r===529?"overloaded":r===400?e&&Br(e)?"billing":"format":null}function ag(r){if(!r)return!1;let e=r.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(r)||/\b404\b/.test(r)&&/not[-_ ]?found/i.test(r))}function cg(r){if(!r)return!1;let e=r.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 Ha(r){if(cg(r))return"session_expired";if(ag(r))return"model_not_found";let e=rg(r);return e||(Zm(r)?Br(r)?"billing":"rate_limit":$a(r)?"rate_limit":Fa(r)?"overloaded":ig(r)?Wa(r.trim())?.code===529?"overloaded":"timeout":sg(r)?"timeout":Jm(r)?"format":Br(r)?"billing":Qm(r)?"timeout":ja(r)?"auth_permanent":eg(r)?"auth":null)}var Nm,wt,Um,$m,jm,Fm,Bm,Wm,Gm,Hm,Vm,zm,Km,qm,Xm,Ym,Va=te(()=>{"use strict";Nm=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,wt={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]},Um=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,$m=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,jm=512,Fm=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,Bm=new Set([500,502,503,504,521,522,523,524,529]),Wm=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Gm=["upgrade your plan","upgrade plan","current plan","subscription"],Hm=["daily","weekly","monthly"],Vm=["try again","retry","temporary","cooldown"],zm=["usage limit","rate limit","organization usage"],Km=["organization","workspace"],qm=["billing period","exceeded","reached","exhausted"],Xm=/["']?(?: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,Ym=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function Bt(r,e){let t=Ga(r,e)??(e?Ha(e):null);return t?lg[t]:typeof r=="number"&&r>=400&&r<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Wr(r){return dg.has(r)}var lg,dg,za=te(()=>{"use strict";Va();lg={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"},dg=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"])});function ln(r){return typeof r.compressAsync=="function"}function ug(r,e){if(r.length<=e)return r;let t=r.slice(0,e);if(r.trimStart().startsWith("{")||r.trimStart().startsWith("[")){let s=Math.max(t.lastIndexOf("},"),t.lastIndexOf("],"),t.lastIndexOf(`}
2
2
  `),t.lastIndexOf(`]
3
3
  `));if(s>e*.5)return t.slice(0,s+1)+`
4
4
  [...truncated: ${r.length-s-1} chars omitted]`}let o=t.lastIndexOf(`
5
5
  `);return o>e*.7?t.slice(0,o)+`
6
6
  [...truncated: ${r.length-o} chars omitted]`:t+`
7
- [...truncated: ${r.length-e} chars omitted]`}function Fr(...r){return{compress(e,t){let n=e,o=0,s=[];for(let i of r){let a=i.compress(n,t);n=a.messages,o+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:o,strategy:s.length>0?s.join("+"):"none"}}}}function Br(...r){return{compress(e,t){let n=e,o=0,s=[];for(let i of r){let a=i.compress(n,t);n=a.messages,o+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:o,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(e,t){let n=e,o=0,s=[],i=0,a=!1,c=!1;for(let d of r){let l=rn(d)?await d.compressAsync(n,t):d.compress(n,t);n=l.messages,o+=l.droppedCount,l.droppedCount>0&&s.push(l.strategy),l.metrics&&(i+=l.metrics.latencyMs,a=a||l.metrics.usedLlm,c=c||!!l.metrics.cacheInvalidated)}return{messages:n,droppedCount:o,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:c}:void 0}}}}function Ga(r,e){let t=r.filter(i=>i.role==="user"),n=r.filter(i=>i.tool_calls!=null),o=r.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 ${o.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","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 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","",...r.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),c=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${c}`}),"","## 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(`
8
- `)}function Zn(r={}){let e={...Ha,...r},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function sn(r,e){let t=r/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function Zm(r){let e=[],t=[];for(let n of r)n.role==="system"?e.push(n):t.push(n);return{system:e,nonSystem:t}}function Gr(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function Qn(r){let e=Math.min(r.length,5),t=[];for(let n=0;n<e;n++){let o=r[n],s=typeof o.content=="string"?o.content.slice(0,200):"";t.push(`${o.role}:${s}`)}return t.join("|")}function tg(r){let e=new Map;for(let t=0;t<r.length;t++){let n=r[t];if(n.tool_calls&&Array.isArray(n.tool_calls))for(let o of n.tool_calls){let s=o.function?.name??"";if(/read|edit|write|file/i.test(s)&&o.function?.arguments)try{let i=JSON.parse(o.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 Hr(r,e,t){let n=t.estimateTokens??(p=>Math.ceil(p.length/4)),o=tg(e);if(o.length===0)return r;let s=r.map(p=>typeof p.content=="string"?p.content:"").join(`
9
- `),i=o.filter(p=>!s.includes(p));if(i.length===0)return r;let a=t.maxTokenBudget,c=[],d=0;for(let p of i){if(d>=t.maxFiles||a<=0)break;let g=await t.readFile(p);if(!g)continue;let f=n(g);f>a||(a-=f,d++,c.push({role:"system",content:`[Post-compact file recovery: ${p}]
7
+ [...truncated: ${r.length-e} chars omitted]`}function Gr(...r){return{compress(e,t){let n=e,o=0,s=[];for(let i of r){let a=i.compress(n,t);n=a.messages,o+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:o,strategy:s.length>0?s.join("+"):"none"}}}}function Hr(...r){return{compress(e,t){let n=e,o=0,s=[];for(let i of r){let a=i.compress(n,t);n=a.messages,o+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:n,droppedCount:o,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(e,t){let n=e,o=0,s=[],i=0,a=!1,c=!1;for(let d of r){let l=ln(d)?await d.compressAsync(n,t):d.compress(n,t);n=l.messages,o+=l.droppedCount,l.droppedCount>0&&s.push(l.strategy),l.metrics&&(i+=l.metrics.latencyMs,a=a||l.metrics.usedLlm,c=c||!!l.metrics.cacheInvalidated)}return{messages:n,droppedCount:o,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:c}:void 0}}}}function qa(r,e){let t=r.filter(i=>i.role==="user"),n=r.filter(i=>i.tool_calls!=null),o=r.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 ${o.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","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 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","",...r.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),c=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${c}`}),"","## 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(`
8
+ `)}function oo(r={}){let e={...Xa,...r},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function dn(r,e){let t=r/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function pg(r){let e=[],t=[];for(let n of r)n.role==="system"?e.push(n):t.push(n);return{system:e,nonSystem:t}}function Vr(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function no(r){let e=Math.min(r.length,5),t=[];for(let n=0;n<e;n++){let o=r[n],s=typeof o.content=="string"?o.content.slice(0,200):"";t.push(`${o.role}:${s}`)}return t.join("|")}function gg(r){let e=new Map;for(let t=0;t<r.length;t++){let n=r[t];if(n.tool_calls&&Array.isArray(n.tool_calls))for(let o of n.tool_calls){let s=o.function?.name??"";if(/read|edit|write|file/i.test(s)&&o.function?.arguments)try{let i=JSON.parse(o.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 zr(r,e,t){let n=t.estimateTokens??(p=>Math.ceil(p.length/4)),o=gg(e);if(o.length===0)return r;let s=r.map(p=>typeof p.content=="string"?p.content:"").join(`
9
+ `),i=o.filter(p=>!s.includes(p));if(i.length===0)return r;let a=t.maxTokenBudget,c=[],d=0;for(let p of i){if(d>=t.maxFiles||a<=0)break;let m=await t.readFile(p);if(!m)continue;let f=n(m);f>a||(a-=f,d++,c.push({role:"system",content:`[Post-compact file recovery: ${p}]
10
10
 
11
- ${g}`}))}if(c.length===0)return r;let l=[...r],u=-1;for(let p=0;p<l.length;p++)l[p].role==="system"&&(u=p);return l.splice(u+1,0,...c),l}function Wr(r,e,t=Gr){if(e.size===0)return{messages:r,tokensFreed:0,removedCount:0};let n=0,o=0,s=[];for(let a of r){let c=a.tool_call_id??"";if(c&&e.has(c)){n+=t(a),o++,e.delete(c);continue}s.push(a)}let i=o>0?{role:"system",content:`[${o} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:o,boundaryMessage:i}}var Ba,jt,wt,en,tn,Ha,nn,on,eg,dt,zr=ee(()=>{"use strict";Ba=4,jt=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let n=[],o=[];for(let l of e)l.role==="system"?n.push(l):o.push(l);let s=t;for(let l of n)s-=this.estimateTokens(l);let i;for(let l of o)if(l.role==="user"){i=l;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...n,i]:n,droppedCount:o.length-(i?1:0),strategy:"sliding-window"};let a=[],c=0;for(let l=o.length-1;l>=0;l--){let u=o[l];if(u===i)continue;let p=this.estimateTokens(u);if(s-p<0&&c>=Ba)break;if(s-p<0&&c<Ba){a.unshift(u),c++;continue}s-=p,a.unshift(u),c++}let d=[...n];return i&&!a.includes(i)&&d.push(i),d.push(...a),{messages:d,droppedCount:o.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},wt=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:Qm(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};en=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??Gr,taskContext:e.taskContext}}compress(e,t){return{messages:e,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(e,t){let n=Date.now(),{system:o,nonSystem:s}=Zm(e),i=e.reduce((S,A)=>S+this.config.estimateTokens(A),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,c=0;for(let S=0;S<s.length&&(s[S].role==="user"&&c++,!(c>this.config.protectedHeadExchanges));S++)a=S+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),l=Math.max(a,s.length-d);if(l<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let u=s.slice(0,a),p=s.slice(a,l),g=s.slice(l),f=Ga(p,{taskContext:this.config.taskContext}),m=await this.config.summarize(p,f),y={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
11
+ ${m}`}))}if(c.length===0)return r;let l=[...r],u=-1;for(let p=0;p<l.length;p++)l[p].role==="system"&&(u=p);return l.splice(u+1,0,...c),l}function Kr(r,e,t=Vr){if(e.size===0)return{messages:r,tokensFreed:0,removedCount:0};let n=0,o=0,s=[];for(let a of r){let c=a.tool_call_id??"";if(c&&e.has(c)){n+=t(a),o++,e.delete(c);continue}s.push(a)}let i=o>0?{role:"system",content:`[${o} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:o,boundaryMessage:i}}var Ka,Wt,St,rn,sn,Xa,an,cn,mg,ut,qr=te(()=>{"use strict";Ka=4,Wt=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let n=[],o=[];for(let l of e)l.role==="system"?n.push(l):o.push(l);let s=t;for(let l of n)s-=this.estimateTokens(l);let i;for(let l of o)if(l.role==="user"){i=l;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...n,i]:n,droppedCount:o.length-(i?1:0),strategy:"sliding-window"};let a=[],c=0;for(let l=o.length-1;l>=0;l--){let u=o[l];if(u===i)continue;let p=this.estimateTokens(u);if(s-p<0&&c>=Ka)break;if(s-p<0&&c<Ka){a.unshift(u),c++;continue}s-=p,a.unshift(u),c++}let d=[...n];return i&&!a.includes(i)&&d.push(i),d.push(...a),{messages:d,droppedCount:o.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},St=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:ug(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};rn=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??Vr,taskContext:e.taskContext}}compress(e,t){return{messages:e,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(e,t){let n=Date.now(),{system:o,nonSystem:s}=pg(e),i=e.reduce((R,P)=>R+this.config.estimateTokens(P),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,c=0;for(let R=0;R<s.length&&(s[R].role==="user"&&c++,!(c>this.config.protectedHeadExchanges));R++)a=R+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),l=Math.max(a,s.length-d);if(l<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let u=s.slice(0,a),p=s.slice(a,l),m=s.slice(l),f=qa(p,{taskContext:this.config.taskContext}),g=await this.config.summarize(p,f),y={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
12
12
 
13
- ${m}`},k=[...o,...u,y,...g],b=Date.now()-n,x=k.reduce((S,A)=>S+this.config.estimateTokens(A),0);return{messages:k,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:x,compressionRatio:i>0?x/i:1,latencyMs:b,usedLlm:!0,cacheInvalidated:!0}}}},tn=class{config;constructor(e){this.config=e}compress(e,t){let n=Qn(e),o=this.config.inner.compress(e,t),s=Qn(o.messages),i=n!==s&&o.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:o.droppedCount,strategy:o.strategy}),{...o,metrics:{...o.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(e,t){let n=Qn(e),o=rn(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=Qn(o.messages),i=n!==s&&o.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:o.droppedCount,strategy:o.strategy}),{...o,metrics:{...o.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Ha={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};nn=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,o=0,s=0,i=0;for(let a of this.events)t+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,n+=a.latencyMs,o+=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:o,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},on=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}))}};eg=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"]),dt=class{constructor(e=20,t=Gr){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,o=0,s=0;return{messages:e.map((a,c)=>{if(c>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!eg.has(a.name)||a.content.length<=200)return a;let d=this.estimateTokens(a);return s+=d,o++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:o,strategy:"micro-compact",metrics:o>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function Vr(){return{stages:[]}}function qr(r,e,t){let n=t?.thresholdMessages??40;if(r.filter(a=>a.role!=="system").length<=n)return{messages:r,stagedCount:0};let s=Wa(r,e),i=ng(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Wa(r,e),{messages:s,stagedCount:i.length}}function Kr(r,e){let t=0;for(let n of e.stages)n.committed||(n.committed=!0,t++);return t===0?{messages:r,committed:0}:{messages:za(r,e),committed:t}}function Wa(r,e){return e.stages.filter(n=>n.committed).length===0?r:za(r,e)}function za(r,e){let t=e.stages.filter(o=>o.committed).sort((o,s)=>s.range[0]-o.range[0]),n=[...r];for(let o of t){let[s,i]=o.range;if(s>=n.length)continue;let a=Math.min(i,n.length),c={role:"system",content:o.summary};n.splice(s,a-s,c)}return n}function ng(r,e,t){let n=Math.max(0,r.length-Math.floor(t/2)),o=[],s=new Set(e.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<n;c++){let d=r[c];if(d.role==="tool"||d.role==="assistant"&&typeof d.content=="string"&&d.content==="")i<0&&(i=c),a++;else{if(a>=3){let u=`${i}-${i+a}`;s.has(u)||o.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 c=`${i}-${i+a}`;s.has(c)||o.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return o}var Va=ee(()=>{"use strict"});function bs(){return{maxRoundsLimit:100,defaultMaxRounds:25,defaultTemperature:0,maxToolBudgetCap:100,defaultToolBudget:eo,maxConsecutiveFailures:to,maxIdenticalCallRepeats:no,defaultContextWindowTokens:oo,responseBufferTokens:ro,defaultMaxOutputTokens:so,defaultModelMaxOutputTokens:io,maxOutputTokensRecoveryLimit:ao,escalatedMaxOutputTokens:lo,diminishingReturnsThreshold:an,diminishingReturnsMinContinuations:co,defaultMaxResultSizeChars:uo,maxToolResultsPerMessageChars:po,toolResultPreviewBytes:ln,heartbeatIntervalMs:mo,max529Retries:go,maxApiRetries:vt,persistentRetryMaxBackoffMs:og,persistentRetryResetCapMs:rg,compressionTargetUsageRatio:sg,compressionMinBudget:ig,compressionMaxBudget:ag,reactiveCompactMaxFailures:lg,reactiveCompactMinMessages:cg,reactiveCompactTargetPercent:dg,maxSkillsPerProject:Jr,maxSkillsGlobal:qa,minToolCallsForSkill:Xr,minDistinctToolsForSkill:Yr,skillCreationCooldownMs:Qr,skillInjectionMaxChars:ug,skillInjectionMaxCount:pg,skillRecallMaxSkills:Zr,skillRecallMaxContentChars:es,skillRecallCacheTtlMs:ts,maxForkDepth:ns,maxSessions:os,taskSummaryTurnThreshold:rs,taskSummaryRegenInterval:ss,maxIncludeDepth:is,maxInstructionChars:mg,instructionsMaxFileSize:as,instructionsMaxDirSize:ls,mediaMaxDownloadSize:cs,mediaDownloadTimeoutMs:ds,acpMaxSpawnRetries:us,acpRetryBackoffBase:ps,acpRuntimeRestartMax:ms,acpRuntimeRestartBackoffBase:gs,taskPollIntervalMs:gg,taskStoppedDisplayMs:fg,taskPanelGraceMs:hg,memoryPrefetchMaxSessionBytes:fs,memoryPrefetchLimitPerRecall:hs,memoryMaxSurfacedEntries:ys,dreamMinIntervalHours:yg,dreamMinSessions:bg,dreamScanIntervalMs:kg,idleDreamMinutes:Tg,dreamCooldownMs:wg,dreamMaxDurationMs:vg}}var eo,to,no,oo,ro,so,io,ao,lo,an,co,uo,po,ln,mo,go,vt,og,rg,sg,ig,ag,lg,cg,dg,Jr,qa,Xr,Yr,Qr,ug,pg,Zr,es,ts,ns,os,rs,ss,is,mg,as,ls,cs,ds,us,ps,ms,gs,gg,fg,hg,fs,hs,ys,yg,bg,kg,Tg,wg,vg,De=ee(()=>{"use strict";eo=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),to=3,no=2,oo=128e3,ro=13e3,so=16384,io=65536,ao=3,lo=65536,an=500,co=3,uo=5e4,po=2e5,ln=2e3,mo=3e4,go=3,vt=10,og=3e5,rg=216e5,sg=.75,ig=16e3,ag=12e4,lg=3,cg=4,dg=50,Jr=20,qa=50,Xr=3,Yr=2,Qr=300*1e3,ug=4e3,pg=5,Zr=3,es=800,ts=300*1e3,ns=4,os=50,rs=50,ss=30,is=5,mg=4e4,as=50*1024,ls=500*1024,cs=500*1024*1024,ds=3e5,us=2,ps=3e3,ms=3,gs=5e3,gg=1e3,fg=3e3,hg=3e4,fs=60*1024,hs=10,ys=100,yg=24,bg=5,kg=6e5,Tg=30,wg=144e5,vg=3e5});import{existsSync as ks,readdirSync as Ja,readFileSync as Sg}from"node:fs";import{join as Xa}from"node:path";function Ka(r){return[...r].sort().join("+")}function xg(r,e){if(!ks(e))return null;let t=Ka(r);try{let n=Ja(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=Xa(e,o.name,"SKILL.md");try{let a=Sg(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let c=a[1].split(`
14
- `).map(d=>d.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Ka(c)===t)return o.name}}catch{}}}catch{}return null}function Rg(r){if(!ks(r))return 0;try{return Ja(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&ks(Xa(r,e.name,"SKILL.md"))).length}catch{return 0}}function _g(r,e){return!(!r.ok||r.existingSkillName||!r.multiStep||r.toolCallCount<Xr||r.distinctToolCount<Yr||Date.now()-Ya<Qr||e?.projectSkillsDir&&(Rg(e.projectSkillsDir)>=Jr||e.tools.length>0&&xg(e.tools,e.projectSkillsDir)))}function Cg(r){return r.existingSkillName?r.feedback==="negative":!1}function cn(r,e){return Cg(r)?{type:"skill.improve",skillName:r.existingSkillName,reason:"negative user feedback on existing skill execution"}:_g(r,e)?(Ya=Date.now(),{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:r.toolCallCount}):null}var Ya,Qa=ee(()=>{"use strict";De();Ya=0});function Za(r){return r.function&&typeof r.function=="object"&&typeof r.function.name=="string"?r.function.name.trim():typeof r.name=="string"?r.name.trim():""}function Ag(r){return r==="enabled-eligible"||r==="installed-awaiting-approval"}function Ig(r){return new Map((r??[]).map(e=>[e.toolName,e]))}function Pg(r){if(!r.eligibility?.length)return[...r.tools];let e=Ig(r.eligibility);return r.tools.filter(t=>{let n=Za(t);if(!n)return!1;let o=e.get(n);return!o||Ag(o.status)})}function Mg(r){let e=[],t=r.compatibility??{},n=r.toolChoice;if(r.thinkingEnabled&&t.requireAutoWhenThinking){let o=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;o&&o!=="auto"&&o!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&t.allowRequiredToolChoice===!1){let o=t.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${o}.`),n=o}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&t.allowNamedToolChoice===!1){let o=t.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${o}.`),n=o}return{normalizedToolChoice:n,warnings:e}}function Ts(r){let e=Mg({toolChoice:r.toolChoice,thinkingEnabled:r.thinkingEnabled,compatibility:r.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],o=Pg({tools:r.tools,eligibility:r.eligibility});if(!t||t==="auto")return{tools:o,normalizedToolChoice:t,warnings:n};if(t==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(t==="required"){if(o.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:o,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=o.filter(c=>Za(c)===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:o,normalizedToolChoice:t,warnings:n}}var el=ee(()=>{"use strict"});function tl(r){return r==null?[]:typeof r=="string"?r.length>0?[{type:"text",text:r}]:[]:Array.isArray(r)?r:[{type:"text",text:String(r)}]}function Dg(r,e){return{...r,content:[...tl(r.content),...tl(e.content)]}}function Lg(r){if(!r||typeof r!="object")return!1;if(r.function&&typeof r.function=="object"){let e=r.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof r.name=="string"&&r.name.length>0}function $g(r){return new Set((r??Eg).map(e=>e.trim().toLowerCase()))}function Ug(r,e){return r?$g(e).has(r.trim().toLowerCase()):!1}function ws(r){if(!Array.isArray(r)||r.length===0)return[...r];let e=r.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(d=>Lg(d));return{...a,...c.length>0?{tool_calls:c}:{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 c of a.tool_calls)typeof c.id=="string"&&c.id&&t.add(c.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),o=new Set;for(let a of n)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.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 c=a.tool_calls.filter(d=>typeof d.id=="string"&&o.has(d.id));if(c.length===0){let{tool_calls:d,...l}=a;l.content!=null&&l.content!==""&&s.push(l);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=[];for(let a of s){let c=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){i[i.length-1]=Dg(c,a);continue}i.push(a)}return i}function vs(r,e){return Ug(e?.stopReason,e?.forcedStopReasons)?r.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let o of Og)delete n[o];return n}):[...r]}function Ss(r,e){let t=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of r)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let o=[];for(let s of r)if(o.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),o.push({role:"tool",tool_call_id:i.id,content:t}));return o}function xs(r,e){let t=ws(r),n=vs(t,e);return Ss(n,e)}var Eg,Og,Rs=ee(()=>{"use strict";Eg=["stop","aborted","timeout","cancelled","interrupted","error"],Og=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Ng(r){let e=new Set,t=new Set;for(let n of r){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)typeof o.id=="string"&&o.id&&e.add(o.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 jg(r){let e=new Set;for(let t of r)t.role==="tool"&&typeof t.tool_call_id=="string"&&t.tool_call_id&&e.add(t.tool_call_id);return[...e]}function Fg(r){return{round:r.round??0,maxRounds:r.maxRounds,pendingToolCallIds:[...r.pendingToolCallIds??[]],completedToolCallIds:[...r.completedToolCallIds??[]],lastStopReason:r.lastStopReason,replayMessages:[...r.replayMessages??[]]}}function _s(r,e){return{round:r.round+1,maxRounds:r.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??r.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??r.completedToolCallIds],lastStopReason:e.lastStopReason??r.lastStopReason,replayMessages:[...e.replayMessages??r.replayMessages]}}function fo(r,e){return{round:r.round,maxRounds:r.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??r.completedToolCallIds],lastStopReason:e.lastStopReason??r.lastStopReason,replayMessages:[...e.replayMessages??r.replayMessages]}}function ho(r){let e=[],t=ws(r.replayMessages);t.length!==r.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=vs(t,r.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 o=Ss(n,r.options);return o.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Fg({maxRounds:r.maxRounds,round:r.round,lastStopReason:r.lastStopReason,replayMessages:o,pendingToolCallIds:Ng(o),completedToolCallIds:jg(o)}),recoveryActions:e}}var nl=ee(()=>{"use strict";Rs()});function Cs(r){return r?Bg.has(r):!0}function As(r){return r===429||r===529}function yo(r,e=500,t=32e3){let n=Math.min(e*Math.pow(2,r-1),t);return n+Math.floor(Math.random()*n*.25)}function Is(){let r=process.env.QLOGICAGENT_PERSISTENT_RETRY;return r==="1"||r==="true"}var Bg,Kx,dn,ol=ee(()=>{"use strict";Bg=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);Kx={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};dn=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Ps(r,e){if(e.allowedTools&&e.allowedTools.length>0){let t=new Set(e.allowedTools);return r.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 r.filter(n=>!t.has(n))}return e.canFork?[...r]:r.filter(t=>t!=="agent")}var Ms=ee(()=>{"use strict";De()});function bo(r){return Kg.find(e=>e.name===r)}var Gg,Hg,Wg,zg,Vg,qg,Kg,Es=ee(()=>{"use strict";Gg={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},Hg={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},Wg={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","task","tool_search"],canFork:!1},zg={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Vg={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},qg={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},Kg=[Gg,Hg,Wg,zg,Vg,qg]});var rl=ee(()=>{"use strict"});function Os(r){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:r.maxOutputTokens,consecutiveTruncations:0,aborted:r.abortSignal?.aborted??!1}}function Ds(r,e){if(r.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let t=e.contextWindowTokens-e.responseBufferTokens-r.currentMaxOutputTokens,n=t>0?r.promptTokens/t*100:100;return r.promptTokens>=t?r.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-r.promptTokens}:{level:"ok"}}function Ls(r,e,t){let n=r.message?.toLowerCase()??"",o=r.status??0;return o===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"}:o>=500&&o<600?{action:"retry",reason:`server_error_${o}`}:o===429?{action:"retry",reason:"rate_limited"}:o===401||o===403?{action:"abort",reason:"auth_error"}:o===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:n||"unknown_error"}}function $s(r,e,t){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:r.currentMaxOutputTokens};if(r.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:r.currentMaxOutputTokens};let n=Math.min(r.currentMaxOutputTokens*2,t);return n<=r.currentMaxOutputTokens?{shouldEscalate:!1,newMax:r.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function Us(r,e){return r.aborted?!0:e.abortSignal?.aborted?(r.aborted=!0,!0):!1}var sl=ee(()=>{"use strict"});function Ns(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Ft(r,e=Jg){return!(r.attemptedThisTurn||r.consecutiveFailures>=e.maxConsecutiveFailures)}var Jg,il=ee(()=>{"use strict";Jg={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var Bt=ee(()=>{"use strict";Ma();Fa();zr();zr();Va();Qa();el();Rs();nl();ol();Ms();Es();rl();sl();il()});function js(r,e){let t=r.get(e.index);t||(t={id:"",name:"",arguments:""},r.set(e.index,t)),e.id&&(t.id=e.id),e.name&&(t.name+=e.name),t.arguments+=e.arguments}var Fs=ee(()=>{"use strict"});var ko=ee(()=>{"use strict";De()});import{mkdir as Yg,writeFile as Qg}from"fs/promises";import{join as dl}from"path";import{tmpdir as Zg}from"os";function pl(){return{seenIds:new Set,replacements:new Map}}function ml(r){return dl(Zg(),"qlogicagent-sessions",r,ef)}async function nf(r){try{await Yg(ml(r),{recursive:!0})}catch{}}function of(r,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return dl(ml(r),`${t}.txt`)}function rf(r,e){if(r.length<=e)return{preview:r,hasMore:!1};let n=r.slice(0,e).lastIndexOf(`
15
- `),o=n>e*.5?n:e;return{preview:r.slice(0,o),hasMore:!0}}function gl(r){return r.includes(ul)}async function fl(r,e,t){await nf(t);let n=of(t,e);try{await Qg(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:o,hasMore:s}=rf(r,ln);return{filepath:n,originalSize:r.length,preview:o,hasMore:s}}function hl(r){let e=`${ul}
13
+ ${g}`},b=[...o,...u,y,...m],k=Date.now()-n,S=b.reduce((R,P)=>R+this.config.estimateTokens(P),0);return{messages:b,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:S,compressionRatio:i>0?S/i:1,latencyMs:k,usedLlm:!0,cacheInvalidated:!0}}}},sn=class{config;constructor(e){this.config=e}compress(e,t){let n=no(e),o=this.config.inner.compress(e,t),s=no(o.messages),i=n!==s&&o.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:o.droppedCount,strategy:o.strategy}),{...o,metrics:{...o.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(e,t){let n=no(e),o=ln(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=no(o.messages),i=n!==s&&o.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:o.droppedCount,strategy:o.strategy}),{...o,metrics:{...o.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Xa={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};an=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,o=0,s=0,i=0;for(let a of this.events)t+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,n+=a.latencyMs,o+=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:o,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},cn=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}))}};mg=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"]),ut=class{constructor(e=20,t=Vr){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,o=0,s=0;return{messages:e.map((a,c)=>{if(c>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!mg.has(a.name)||a.content.length<=200)return a;let d=this.estimateTokens(a);return s+=d,o++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:o,strategy:"micro-compact",metrics:o>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function Xr(){return{stages:[]}}function Yr(r,e,t){let n=t?.thresholdMessages??40;if(r.filter(a=>a.role!=="system").length<=n)return{messages:r,stagedCount:0};let s=Ya(r,e),i=fg(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Ya(r,e),{messages:s,stagedCount:i.length}}function Jr(r,e){let t=0;for(let n of e.stages)n.committed||(n.committed=!0,t++);return t===0?{messages:r,committed:0}:{messages:Ja(r,e),committed:t}}function Ya(r,e){return e.stages.filter(n=>n.committed).length===0?r:Ja(r,e)}function Ja(r,e){let t=e.stages.filter(o=>o.committed).sort((o,s)=>s.range[0]-o.range[0]),n=[...r];for(let o of t){let[s,i]=o.range;if(s>=n.length)continue;let a=Math.min(i,n.length),c={role:"system",content:o.summary};n.splice(s,a-s,c)}return n}function fg(r,e,t){let n=Math.max(0,r.length-Math.floor(t/2)),o=[],s=new Set(e.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<n;c++){let d=r[c];if(d.role==="tool"||d.role==="assistant"&&typeof d.content=="string"&&d.content==="")i<0&&(i=c),a++;else{if(a>=3){let u=`${i}-${i+a}`;s.has(u)||o.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 c=`${i}-${i+a}`;s.has(c)||o.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return o}var Qa=te(()=>{"use strict"});function ws(){return{maxRoundsLimit:100,defaultMaxRounds:25,defaultTemperature:0,maxToolBudgetCap:100,defaultToolBudget:ro,maxConsecutiveFailures:so,maxIdenticalCallRepeats:io,defaultContextWindowTokens:ao,responseBufferTokens:co,defaultMaxOutputTokens:lo,defaultModelMaxOutputTokens:uo,maxOutputTokensRecoveryLimit:po,escalatedMaxOutputTokens:mo,diminishingReturnsThreshold:un,diminishingReturnsMinContinuations:go,defaultMaxResultSizeChars:fo,maxToolResultsPerMessageChars:ho,toolResultPreviewBytes:pn,heartbeatIntervalMs:yo,max529Retries:bo,maxApiRetries:Rt,persistentRetryMaxBackoffMs:hg,persistentRetryResetCapMs:yg,compressionTargetUsageRatio:bg,compressionMinBudget:kg,compressionMaxBudget:Tg,reactiveCompactMaxFailures:wg,reactiveCompactMinMessages:vg,reactiveCompactTargetPercent:Sg,maxSkillsPerProject:Qr,maxSkillsGlobal:Za,minToolCallsForSkill:Zr,minDistinctToolsForSkill:es,skillCreationCooldownMs:ts,skillInjectionMaxChars:Rg,skillInjectionMaxCount:_g,skillRecallMaxSkills:ns,skillRecallMaxContentChars:os,skillRecallCacheTtlMs:rs,maxForkDepth:ss,maxSessions:is,taskSummaryTurnThreshold:as,taskSummaryRegenInterval:cs,maxIncludeDepth:ls,maxInstructionChars:xg,instructionsMaxFileSize:ds,instructionsMaxDirSize:us,mediaMaxDownloadSize:ps,mediaMaxUploadSize:$e,mediaDownloadTimeoutMs:ms,acpMaxSpawnRetries:gs,acpRetryBackoffBase:fs,acpRuntimeRestartMax:hs,acpRuntimeRestartBackoffBase:ys,taskPollIntervalMs:Ag,taskStoppedDisplayMs:Cg,taskPanelGraceMs:Pg,memoryPrefetchMaxSessionBytes:bs,memoryPrefetchLimitPerRecall:ks,memoryMaxSurfacedEntries:Ts,dreamMinIntervalHours:Ig,dreamMinSessions:Mg,dreamScanIntervalMs:Eg,idleDreamMinutes:Og,dreamCooldownMs:Dg,dreamMaxDurationMs:Lg}}var ro,so,io,ao,co,lo,uo,po,mo,un,go,fo,ho,pn,yo,bo,Rt,hg,yg,bg,kg,Tg,wg,vg,Sg,Qr,Za,Zr,es,ts,Rg,_g,ns,os,rs,ss,is,as,cs,ls,xg,ds,us,ps,$e,ms,gs,fs,hs,ys,Ag,Cg,Pg,bs,ks,Ts,Ig,Mg,Eg,Og,Dg,Lg,ye=te(()=>{"use strict";ro=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),so=3,io=2,ao=128e3,co=13e3,lo=16384,uo=65536,po=3,mo=65536,un=500,go=3,fo=5e4,ho=2e5,pn=2e3,yo=3e4,bo=3,Rt=10,hg=3e5,yg=216e5,bg=.75,kg=16e3,Tg=12e4,wg=3,vg=4,Sg=50,Qr=20,Za=50,Zr=3,es=2,ts=300*1e3,Rg=4e3,_g=5,ns=3,os=800,rs=300*1e3,ss=4,is=50,as=50,cs=30,ls=5,xg=4e4,ds=50*1024,us=500*1024,ps=500*1024*1024,$e=50*1024*1024,ms=3e5,gs=2,fs=3e3,hs=3,ys=5e3,Ag=1e3,Cg=3e3,Pg=3e4,bs=60*1024,ks=10,Ts=100,Ig=24,Mg=5,Eg=6e5,Og=30,Dg=144e5,Lg=3e5});import{existsSync as vs,readdirSync as tc,readFileSync as Ng}from"node:fs";import{join as nc}from"node:path";function ec(r){return[...r].sort().join("+")}function Ug(r,e){if(!vs(e))return null;let t=ec(r);try{let n=tc(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=nc(e,o.name,"SKILL.md");try{let a=Ng(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let c=a[1].split(`
14
+ `).map(d=>d.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(ec(c)===t)return o.name}}catch{}}}catch{}return null}function $g(r){if(!vs(r))return 0;try{return tc(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&vs(nc(r,e.name,"SKILL.md"))).length}catch{return 0}}function jg(r,e){return!(!r.ok||r.existingSkillName||!r.multiStep||r.toolCallCount<Zr||r.distinctToolCount<es||Date.now()-oc<ts||e?.projectSkillsDir&&($g(e.projectSkillsDir)>=Qr||e.tools.length>0&&Ug(e.tools,e.projectSkillsDir)))}function Fg(r){return r.existingSkillName?r.feedback==="negative":!1}function mn(r,e){return Fg(r)?{type:"skill.improve",skillName:r.existingSkillName,reason:"negative user feedback on existing skill execution"}:jg(r,e)?(oc=Date.now(),{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:r.toolCallCount}):null}var oc,rc=te(()=>{"use strict";ye();oc=0});function sc(r){return r.function&&typeof r.function=="object"&&typeof r.function.name=="string"?r.function.name.trim():typeof r.name=="string"?r.name.trim():""}function Bg(r){return r==="enabled-eligible"||r==="installed-awaiting-approval"}function Wg(r){return new Map((r??[]).map(e=>[e.toolName,e]))}function Gg(r){if(!r.eligibility?.length)return[...r.tools];let e=Wg(r.eligibility);return r.tools.filter(t=>{let n=sc(t);if(!n)return!1;let o=e.get(n);return!o||Bg(o.status)})}function Hg(r){let e=[],t=r.compatibility??{},n=r.toolChoice;if(r.thinkingEnabled&&t.requireAutoWhenThinking){let o=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;o&&o!=="auto"&&o!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&t.allowRequiredToolChoice===!1){let o=t.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${o}.`),n=o}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&t.allowNamedToolChoice===!1){let o=t.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${o}.`),n=o}return{normalizedToolChoice:n,warnings:e}}function Ss(r){let e=Hg({toolChoice:r.toolChoice,thinkingEnabled:r.thinkingEnabled,compatibility:r.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],o=Gg({tools:r.tools,eligibility:r.eligibility});if(!t||t==="auto")return{tools:o,normalizedToolChoice:t,warnings:n};if(t==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(t==="required"){if(o.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:o,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=o.filter(c=>sc(c)===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:o,normalizedToolChoice:t,warnings:n}}var ic=te(()=>{"use strict"});function ac(r){return r==null?[]:typeof r=="string"?r.length>0?[{type:"text",text:r}]:[]:Array.isArray(r)?r:[{type:"text",text:String(r)}]}function Kg(r,e){return{...r,content:[...ac(r.content),...ac(e.content)]}}function qg(r){if(!r||typeof r!="object")return!1;if(r.function&&typeof r.function=="object"){let e=r.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof r.name=="string"&&r.name.length>0}function Xg(r){return new Set((r??Vg).map(e=>e.trim().toLowerCase()))}function Yg(r,e){return r?Xg(e).has(r.trim().toLowerCase()):!1}function Rs(r){if(!Array.isArray(r)||r.length===0)return[...r];let e=r.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(d=>qg(d));return{...a,...c.length>0?{tool_calls:c}:{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 c of a.tool_calls)typeof c.id=="string"&&c.id&&t.add(c.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),o=new Set;for(let a of n)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.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 c=a.tool_calls.filter(d=>typeof d.id=="string"&&o.has(d.id));if(c.length===0){let{tool_calls:d,...l}=a;l.content!=null&&l.content!==""&&s.push(l);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=[];for(let a of s){let c=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){i[i.length-1]=Kg(c,a);continue}i.push(a)}return i}function _s(r,e){return Yg(e?.stopReason,e?.forcedStopReasons)?r.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let o of zg)delete n[o];return n}):[...r]}function xs(r,e){let t=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of r)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let o=[];for(let s of r)if(o.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),o.push({role:"tool",tool_call_id:i.id,content:t}));return o}function As(r,e){let t=Rs(r),n=_s(t,e);return xs(n,e)}var Vg,zg,Cs=te(()=>{"use strict";Vg=["stop","aborted","timeout","cancelled","interrupted","error"],zg=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Jg(r){let e=new Set,t=new Set;for(let n of r){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)typeof o.id=="string"&&o.id&&e.add(o.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 Qg(r){let e=new Set;for(let t of r)t.role==="tool"&&typeof t.tool_call_id=="string"&&t.tool_call_id&&e.add(t.tool_call_id);return[...e]}function Zg(r){return{round:r.round??0,maxRounds:r.maxRounds,pendingToolCallIds:[...r.pendingToolCallIds??[]],completedToolCallIds:[...r.completedToolCallIds??[]],lastStopReason:r.lastStopReason,replayMessages:[...r.replayMessages??[]]}}function Ps(r,e){return{round:r.round+1,maxRounds:r.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??r.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??r.completedToolCallIds],lastStopReason:e.lastStopReason??r.lastStopReason,replayMessages:[...e.replayMessages??r.replayMessages]}}function ko(r,e){return{round:r.round,maxRounds:r.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??r.completedToolCallIds],lastStopReason:e.lastStopReason??r.lastStopReason,replayMessages:[...e.replayMessages??r.replayMessages]}}function To(r){let e=[],t=Rs(r.replayMessages);t.length!==r.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=_s(t,r.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 o=xs(n,r.options);return o.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Zg({maxRounds:r.maxRounds,round:r.round,lastStopReason:r.lastStopReason,replayMessages:o,pendingToolCallIds:Jg(o),completedToolCallIds:Qg(o)}),recoveryActions:e}}var cc=te(()=>{"use strict";Cs()});function Is(r){return r?ef.has(r):!0}function Ms(r){return r===429||r===529}function wo(r,e=500,t=32e3){let n=Math.min(e*Math.pow(2,r-1),t);return n+Math.floor(Math.random()*n*.25)}function Es(){let r=process.env.QLOGICAGENT_PERSISTENT_RETRY;return r==="1"||r==="true"}var ef,n_,gn,lc=te(()=>{"use strict";ef=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);n_={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};gn=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Os(r,e){if(e.allowedTools&&e.allowedTools.length>0){let t=new Set(e.allowedTools);return r.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 r.filter(n=>!t.has(n))}return e.canFork?[...r]:r.filter(t=>t!=="agent")}var Ds=te(()=>{"use strict";ye()});function Ls(){return[...dc]}function vo(r){return dc.find(e=>e.name===r)}var tf,nf,of,rf,sf,af,dc,Ns=te(()=>{"use strict";tf={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},nf={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},of={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","task","tool_search"],canFork:!1},rf={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},sf={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},af={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},dc=[tf,nf,of,rf,sf,af]});var uc=te(()=>{"use strict"});function Us(r){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:r.maxOutputTokens,consecutiveTruncations:0,aborted:r.abortSignal?.aborted??!1}}function $s(r,e){if(r.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let t=e.contextWindowTokens-e.responseBufferTokens-r.currentMaxOutputTokens,n=t>0?r.promptTokens/t*100:100;return r.promptTokens>=t?r.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-r.promptTokens}:{level:"ok"}}function js(r,e,t){let n=r.message?.toLowerCase()??"",o=r.status??0;return o===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"}:o>=500&&o<600?{action:"retry",reason:`server_error_${o}`}:o===429?{action:"retry",reason:"rate_limited"}:o===401||o===403?{action:"abort",reason:"auth_error"}:o===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:n||"unknown_error"}}function Fs(r,e,t){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:r.currentMaxOutputTokens};if(r.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:r.currentMaxOutputTokens};let n=Math.min(r.currentMaxOutputTokens*2,t);return n<=r.currentMaxOutputTokens?{shouldEscalate:!1,newMax:r.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function Bs(r,e){return r.aborted?!0:e.abortSignal?.aborted?(r.aborted=!0,!0):!1}var pc=te(()=>{"use strict"});function Ws(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Gt(r,e=cf){return!(r.attemptedThisTurn||r.consecutiveFailures>=e.maxConsecutiveFailures)}var cf,mc=te(()=>{"use strict";cf={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var Ht=te(()=>{"use strict";Ua();za();qr();qr();Qa();rc();ic();Cs();cc();lc();Ds();Ns();uc();pc();mc()});function Gs(r,e){let t=r.get(e.index);t||(t={id:"",name:"",arguments:""},r.set(e.index,t)),e.id&&(t.id=e.id),e.name&&(t.name+=e.name),t.arguments+=e.arguments}var Hs=te(()=>{"use strict"});var So=te(()=>{"use strict";ye()});import{mkdir as df,writeFile as uf}from"fs/promises";import{join as yc}from"path";import{tmpdir as pf}from"os";function kc(){return{seenIds:new Set,replacements:new Map}}function Tc(r){return yc(pf(),"qlogicagent-sessions",r,mf)}async function ff(r){try{await df(Tc(r),{recursive:!0})}catch{}}function hf(r,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return yc(Tc(r),`${t}.txt`)}function yf(r,e){if(r.length<=e)return{preview:r,hasMore:!1};let n=r.slice(0,e).lastIndexOf(`
15
+ `),o=n>e*.5?n:e;return{preview:r.slice(0,o),hasMore:!0}}function wc(r){return r.includes(bc)}async function vc(r,e,t){await ff(t);let n=hf(t,e);try{await uf(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:o,hasMore:s}=yf(r,pn);return{filepath:n,originalSize:r.length,preview:o,hasMore:s}}function Sc(r){let e=`${bc}
16
16
  `;return e+=`Output too large (${r.originalSize} chars). Full output saved to: ${r.filepath}
17
17
 
18
- `,e+=`Preview (first ${ln} bytes):
18
+ `,e+=`Preview (first ${pn} bytes):
19
19
  `,e+=r.preview,e+=r.hasMore?`
20
20
  ...
21
21
  `:`
22
- `,e+=tf,e}async function yl(r,e,t,n=uo){if(r.length<=n||gl(r))return r;let o=await fl(r,e,t);return o?hl(o):r.slice(0,n)+`
23
- ...[truncated ${r.length-n} chars]`}function sf(r){let e=[],t=[];for(let n of r)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?gl(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 af(r,e){let t=[],n=[],o=[];for(let s of r){let i=e.replacements.get(s.toolCallId);i!==void 0?t.push({...s,replacement:i}):e.seenIds.has(s.toolCallId)?n.push(s):o.push(s)}return{mustReapply:t,frozen:n,fresh:o}}function lf(r,e,t){let n=[...r].sort((i,a)=>a.size-i.size),o=[],s=e+r.reduce((i,a)=>i+a.size,0);for(let i of n){if(s<=t)break;o.push(i),s-=i.size}return o}async function bl(r,e,t,n=po){let o=sf(r);if(o.length===0)return{messages:r,newlyReplacedCount:0};let s=new Map,i=[];for(let l of o){let{mustReapply:u,frozen:p,fresh:g}=af(l,e);for(let b of u)s.set(b.toolCallId,b.replacement);if(g.length===0){for(let b of l)e.seenIds.add(b.toolCallId);continue}let f=p.reduce((b,x)=>b+x.size,0),m=g.reduce((b,x)=>b+x.size,0),y=f+m>n?lf(g,f,n):[],k=new Set(y.map(b=>b.toolCallId));for(let b of l)k.has(b.toolCallId)||e.seenIds.add(b.toolCallId);y.length>0&&i.push(...y)}if(s.size===0&&i.length===0)return{messages:r,newlyReplacedCount:0};let a=await Promise.all(i.map(async l=>{let u=await fl(l.content,l.toolCallId,t);return{candidate:l,result:u}})),c=0;for(let{candidate:l,result:u}of a){if(e.seenIds.add(l.toolCallId),!u)continue;let p=hl(u);s.set(l.toolCallId,p),e.replacements.set(l.toolCallId,p),c++}return s.size===0?{messages:r,newlyReplacedCount:0}:{messages:r.map(l=>{if(l.role!=="tool"||!l.tool_call_id)return l;let u=s.get(l.tool_call_id);return u===void 0?l:{...l,content:u}}),newlyReplacedCount:c}}var ef,ul,tf,Gs=ee(()=>{"use strict";ko();ef="tool-results",ul="<persisted-output>",tf="</persisted-output>"});function uf(r){try{return JSON.parse(r)}catch{return}}var cf,df,To,kl=ee(()=>{"use strict";Bt();Gs();cf=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),df=new Set(["bash","execute_command","Bash","shell"]),To=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??cf,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(o=>o.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&t.length>=n?!1:t.length===0||e&&t.every(o=>o.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 o=n.length>40?n.slice(0,40)+"\u2026":n;return`${e.toolCall.function.name}(${o})`}return e.toolCall.function.name}createSyntheticError(e,t){let n=this.erroredToolDescription,o=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:o,message:Zt(e.id,{ok:!1,error:o})}}async executeTool(e){e.status="executing";let n=(async()=>{let o=this.getAbortReason();if(o){e.results.push(this.createSyntheticError(e,o)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:c,log:d}=this.config,l=e.toolCall.function.name,u=!1,p=e.toolCall.function.arguments;if(i)try{let b=await i.invoke("tool.before_invoke",{sessionId:a,turnId:c,callId:e.id,toolName:l,arguments:uf(p)});if(b.action==="abort"){let x=b.reason??"blocked by policy";d.info(`tool ${l} blocked: ${x}`),e.results.push({callId:e.id,toolName:l,ok:!1,error:x,blocked:!0,blockReason:x,message:Zt(e.id,{ok:!1,error:x})}),e.status="completed";return}b.action==="continue"&&b.context?.arguments&&(p=JSON.stringify(b.context.arguments))}catch{}let g=await s.invoke(c,l,p,this.siblingAbortController.signal),f=this.getAbortReason();if(f&&!u){e.results.push(this.createSyntheticError(e,f)),e.status="completed";return}let m=!g.error,y=g.result;m&&y&&y.length>5e4&&(y=await yl(y,e.id,a));let k=Zt(e.id,{ok:m,payload:y,error:g.error,toolReferences:g.toolReferences,imageUrls:g.imageUrls});m||(u=!0,df.has(l)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(m?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:c,callId:e.id,toolName:l,ok:m,...g.error?{error:g.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:l,ok:m,error:g.error,message:k}),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 pf}from"node:fs/promises";function St(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function xt(r){let e=0;for(let t of r)e+=St(t);return e}function vl(r){if(!r)return 128e3;if(r in Hs)return Hs[r];let e=r.toLowerCase();for(let[t,n]of Object.entries(Hs))if(e.startsWith(t.toLowerCase()))return n;return 128e3}function gf(r,e){return async(t,n)=>{let o=e?.transport,s=e?.apiKey;if(!o||!s)return r.debug("[context-compression] no LLM transport for summarization \u2014 using sync fallback"),Ws(t);try{let i="",a=e?.model??mf;for await(let c of o.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)))c.type==="delta"&&(i+=c.text);return i||(r.warn("[context-compression] empty summary response"),Ws(t))}catch(i){return r.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),Ws(t)}}}function Ws(r){let e=r.filter(n=>n.role==="user"),t=e.slice(0,10).map(n=>{let o=typeof n.content=="string"?n.content:JSON.stringify(n.content??"");return`- ${o.slice(0,200)}${o.length>200?"...":""}`});return`User requests (${e.length} messages):
22
+ `,e+=gf,e}async function Rc(r,e,t,n=fo){if(r.length<=n||wc(r))return r;let o=await vc(r,e,t);return o?Sc(o):r.slice(0,n)+`
23
+ ...[truncated ${r.length-n} chars]`}function bf(r){let e=[],t=[];for(let n of r)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?wc(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 kf(r,e){let t=[],n=[],o=[];for(let s of r){let i=e.replacements.get(s.toolCallId);i!==void 0?t.push({...s,replacement:i}):e.seenIds.has(s.toolCallId)?n.push(s):o.push(s)}return{mustReapply:t,frozen:n,fresh:o}}function Tf(r,e,t){let n=[...r].sort((i,a)=>a.size-i.size),o=[],s=e+r.reduce((i,a)=>i+a.size,0);for(let i of n){if(s<=t)break;o.push(i),s-=i.size}return o}async function _c(r,e,t,n=ho){let o=bf(r);if(o.length===0)return{messages:r,newlyReplacedCount:0};let s=new Map,i=[];for(let l of o){let{mustReapply:u,frozen:p,fresh:m}=kf(l,e);for(let k of u)s.set(k.toolCallId,k.replacement);if(m.length===0){for(let k of l)e.seenIds.add(k.toolCallId);continue}let f=p.reduce((k,S)=>k+S.size,0),g=m.reduce((k,S)=>k+S.size,0),y=f+g>n?Tf(m,f,n):[],b=new Set(y.map(k=>k.toolCallId));for(let k of l)b.has(k.toolCallId)||e.seenIds.add(k.toolCallId);y.length>0&&i.push(...y)}if(s.size===0&&i.length===0)return{messages:r,newlyReplacedCount:0};let a=await Promise.all(i.map(async l=>{let u=await vc(l.content,l.toolCallId,t);return{candidate:l,result:u}})),c=0;for(let{candidate:l,result:u}of a){if(e.seenIds.add(l.toolCallId),!u)continue;let p=Sc(u);s.set(l.toolCallId,p),e.replacements.set(l.toolCallId,p),c++}return s.size===0?{messages:r,newlyReplacedCount:0}:{messages:r.map(l=>{if(l.role!=="tool"||!l.tool_call_id)return l;let u=s.get(l.tool_call_id);return u===void 0?l:{...l,content:u}}),newlyReplacedCount:c}}var mf,bc,gf,zs=te(()=>{"use strict";So();mf="tool-results",bc="<persisted-output>",gf="</persisted-output>"});function Sf(r){try{return JSON.parse(r)}catch{return}}var wf,vf,Ro,xc=te(()=>{"use strict";Ht();zs();wf=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),vf=new Set(["bash","execute_command","Bash","shell"]),Ro=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??wf,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(o=>o.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&t.length>=n?!1:t.length===0||e&&t.every(o=>o.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 o=n.length>40?n.slice(0,40)+"\u2026":n;return`${e.toolCall.function.name}(${o})`}return e.toolCall.function.name}createSyntheticError(e,t){let n=this.erroredToolDescription,o=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:o,message:on(e.id,{ok:!1,error:o})}}async executeTool(e){e.status="executing";let n=(async()=>{let o=this.getAbortReason();if(o){e.results.push(this.createSyntheticError(e,o)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:c,log:d}=this.config,l=e.toolCall.function.name,u=!1,p=e.toolCall.function.arguments;if(i)try{let k=await i.invoke("tool.before_invoke",{sessionId:a,turnId:c,callId:e.id,toolName:l,arguments:Sf(p)});if(k.action==="abort"){let S=k.reason??"blocked by policy";d.info(`tool ${l} blocked: ${S}`),e.results.push({callId:e.id,toolName:l,ok:!1,error:S,blocked:!0,blockReason:S,message:on(e.id,{ok:!1,error:S})}),e.status="completed";return}k.action==="continue"&&k.context?.arguments&&(p=JSON.stringify(k.context.arguments))}catch{}let m=await s.invoke(c,l,p,this.siblingAbortController.signal),f=this.getAbortReason();if(f&&!u){e.results.push(this.createSyntheticError(e,f)),e.status="completed";return}let g=!m.error,y=m.result;g&&y&&y.length>5e4&&(y=await Rc(y,e.id,a));let b=on(e.id,{ok:g,payload:y,error:m.error,toolReferences:m.toolReferences,imageUrls:m.imageUrls});g||(u=!0,vf.has(l)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(g?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:c,callId:e.id,toolName:l,ok:g,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:l,ok:g,error:m.error,message:b}),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 Rf}from"node:fs/promises";function _t(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function xt(r){let e=0;for(let t of r)e+=_t(t);return e}function Pc(r){if(!r)return 128e3;if(r in Ks)return Ks[r];let e=r.toLowerCase();for(let[t,n]of Object.entries(Ks))if(e.startsWith(t.toLowerCase()))return n;return 128e3}function xf(r,e){return async(t,n)=>{let o=e?.transport,s=e?.apiKey;if(!o||!s)return r.debug("[context-compression] no LLM transport for summarization \u2014 using sync fallback"),qs(t);try{let i="",a=e?.model??_f;for await(let c of o.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)))c.type==="delta"&&(i+=c.text);return i||(r.warn("[context-compression] empty summary response"),qs(t))}catch(i){return r.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),qs(t)}}}function qs(r){let e=r.filter(n=>n.role==="user"),t=e.slice(0,10).map(n=>{let o=typeof n.content=="string"?n.content:JSON.stringify(n.content??"");return`- ${o.slice(0,200)}${o.length>200?"...":""}`});return`User requests (${e.length} messages):
24
24
  ${t.join(`
25
- `)}`}function ff(){return Fr(new wt(zs),new dt(20,St),new jt(St))}function wl(r,e){let t=Br(new wt(zs),new dt(20,St),new en({protectedHeadExchanges:1,protectedTailMessages:8,summarize:r,estimateTokens:St}),new jt(St));return new tn({inner:t,estimateTokens:St,onCacheInvalidated:e?.onCacheInvalidated})}function xl(r,e){let t=e?.budget??Zn({modelContextWindow:vl(e?.model)}),o=(e?.pipeline??ff()).compress(r,t);if(o.droppedCount>0){let s=xt(r),i=xt(o.messages);Sl.record({timestamp:Date.now(),strategy:o.strategy,tokensBefore:s,tokensAfter:i,droppedCount:o.droppedCount,latencyMs:o.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:o.metrics?.cacheInvalidated??!1,tier:sn(s,t)})}return o.droppedCount>0&&Vs?.(o.droppedCount,xt(o.messages)),o}async function hf(r,e,t){let n=t??Zn({modelContextWindow:vl(e.model)}),o=xt(r),s=sn(o,n),i;switch(s){case"none":i={messages:r,droppedCount:0,strategy:"none"};break;case"trim-only":i=new wt(zs).compress(r,n);break;case"sliding-window":{i=await wl(e.summarize).compressAsync(r,n);break}case"llm-summarize":{let a=e.pipeline??wl(e.summarize);i=rn(a)?await a.compressAsync(r,n):a.compress(r,n);break}}return i.droppedCount>0&&(i={...i,messages:await Hr(i.messages,r,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await pf(a,"utf-8")}catch{return null}}})}),yf(r,i,n),i}function yf(r,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||xt(r),o=e.metrics?.tokensAfter||xt(e.messages);Sl.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:n,tokensAfter:o,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:sn(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||xt(e.messages);Vs?.(e.droppedCount,n)}}function bf(r,e){let t=gf(r,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(o,s,i){return hf(o,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};Tl.register(n),Tl.activate(n.id),r.info(`[context-compression] registered context engine: ${n.id}`)}function Rl(r,e,t){bf(e,t),r.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(n,o)=>{let s=o.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),Vs=(n,o)=>{e.debug(`[context-compression] after_compact: removed ${n}, ${o} tokens remaining`),r.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:n,tokenCount:o}).catch(()=>{})}}var Hs,zs,mf,Sl,Tl,Vs,qs=ee(()=>{"use strict";Bt();Hs={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-3.1-pro-preview":1e6,"gemini-3-flash-preview":1e6,"gemini-3.1-flash-lite":1e6};zs=8e3,mf="deepseek-v4-flash",Sl=new nn(200),Tl=new on;Vs=null});function _l(r,e,t){let n=t-e;return`[Budget] ${Math.round(r)}% used (${e.toLocaleString()} / ${t.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(r>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var Cl=ee(()=>{"use strict"});var Al={};Pa(Al,{resolveToolEligibility:()=>Sf});function Tf(r,e){if(kf.some(t=>t.test(r)))return!0;if(e)for(let t of e)try{if(new RegExp(t,"i").test(r))return!0}catch{}return!1}function wf(r,e){let t=r.function.name,n=r.meta,o=[];return e.blockedToolNames?.includes(t)?(o.push("policy_blocked"),{level:5,reasons:o}):n?.isReadOnly?(o.push("always_allowed"),{level:1,reasons:o}):n?.requiresApproval?(o.push("approval_required"),{level:4,reasons:o}):n?.isDangerous||Tf(t,e.dangerousPatterns)?(o.push("dangerous_tool"),{level:3,reasons:o}):{level:2,reasons:o}}function vf(r){switch(r){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 Sf(r,e={}){let t=new Map,n=[],o=[],s=[];for(let i of r){let a=i.function.name,{level:c,reasons:d}=wf(i,e),l=vf(c),u={toolName:a,status:l,permissionLevel:c,approvalRequired:c===4,reasonCodes:d};t.set(a,u),c===5?o.push(u):(n.push(i),c===4&&s.push(u))}return{eligibleTools:n,blockedTools:o,approvalRequiredTools:s,eligibilityByName:t}}var kf,Il=ee(()=>{"use strict";kf=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Rf(r){let e=r.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 _f(r){let e=r.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 Cf(r){return typeof r=="number"&&Number.isFinite(r)&&r>=1?Math.min(Math.round(r),100):eo}function Pl(r){let e=r.message.toLowerCase();return r.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function Af(r){return r==="length"||r==="max_tokens"}function Ml(r){let e=r.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(r.status===413||e.includes("too large")||e.includes("size"))}function If(r){let e=r.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 Pf(r){if(r.status!==400)return null;let e=r.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 o=n-t-1e3;return o>=3e3?o:null}function Mf(r){return r.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*El(r,e,t,n){let{turnId:o,sessionId:s,messages:i,tools:a,model:c,apiKey:d,temperature:l=0,hooks:u,signal:p}=r,g={sessionId:s,turnId:o},f=r.maxTurns??0,m=r.querySource,{resolveToolEligibility:y}=await Promise.resolve().then(()=>(Il(),Al)),k=y(a,r.toolEligibilityContext),b=k.eligibleTools;for(let E of k.blockedTools)yield{type:"tool_blocked",turnId:o,callId:"",name:E.toolName,reason:"blocked-by-policy"};if(!b.length){yield*Ef(o,c,i,d,l,p,e,n);return}let x=Cf(r.maxRounds),S={contextWindowTokens:r.contextWindowTokens??oo,responseBufferTokens:ro,maxOutputTokens:r.maxOutputTokens??so,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},A=new Set,$=0,D=b,B,v={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Os(S),reactiveCompactState:Ns(),toolLoopState:ho({maxRounds:x,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:Vr(),currentModel:c,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:pl(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map},oe=Math.max(f*5,200),T=0;for(;;){if(T++,T>oe){n.info(`hard iteration cap reached (${oe}), forcing completion`);let I=v.finalText||un(v.messages,n);yield{type:"end",turnId:o,content:I,usage:v.totalUsage,model:v.currentModel};return}let{messages:E,maxOutputTokensRecoveryCount:V,hasAttemptedReactiveCompact:me,maxOutputTokensOverride:Ae,turnCount:q,guardState:X,reactiveCompactState:be,collapseStore:ge}=v,{toolLoopState:Re}=v;if(B){try{let I=await B;I&&(yield{type:"tool_use_summary",turnId:o,summary:I})}catch{}B=void 0}if(r.refreshTools&&q>1){let I=r.refreshTools();I!==D&&(D=I,n.debug(`tools refreshed: ${I.length} tools`))}if(Us(X,S)){n.info(`turn aborted by guard at turn ${q}`),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED",usage:v.totalUsage};return}let Ye=Ds(X,S);if(Ye.level==="blocking"){Ye.reason==="prompt_too_long"&&Ft(be)&&(be.attemptedThisTurn=!0,X.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${Ye.reason}), reactive compact needed`),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${Ye.reason}), ending tool loop`);break}Ye.level==="warning"&&n.info(`token budget warning: ${Ye.usagePercent}% used, ${Ye.remainingTokens} remaining`);let fe;{let I=await bl(E,v.contentReplacementState,s);fe=I.messages,I.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${I.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:o,action:"tool_result_budget",detail:`${I.newlyReplacedCount} persisted`})}{let I=Wr(fe,v.snipRemovedIds);fe=I.messages,I.removedCount>0&&(n.info(`snip: removed ${I.removedCount} messages, freed ~${I.tokensFreed} tokens`),yield{type:"recovery",turnId:o,action:"snip",detail:`${I.removedCount} messages`})}{let O=new dt().compress(fe,0);O.droppedCount>0&&(fe=O.messages,n.info(`microcompact: cleared ${O.droppedCount} old tool results`))}if(fe=qr(fe,ge).messages,X.promptTokens>0){let I=xl(fe,{budget:S.contextWindowTokens*.75,model:v.currentModel});I.droppedCount>0&&(fe=I.messages,n.info(`autocompact: ${I.strategy}, dropped ${I.droppedCount}`),yield{type:"recovery",turnId:o,action:"autocompact",detail:`${I.strategy}: ${I.droppedCount} dropped`},v.hasAttemptedReactiveCompact=!1,u?.invoke("context.after_compact",{...g,removedCount:I.droppedCount}).catch(()=>{}))}fe=Mf(fe);let h=Ts({tools:D,toolChoice:r.toolChoice??"auto"}),w=ho({maxRounds:x,replayMessages:fe,lastStopReason:Re.lastStopReason,options:{stopReason:Re.lastStopReason}}),R=h.extraSystemPrompt?[{role:"system",content:h.extraSystemPrompt},...w.state.replayMessages]:w.state.replayMessages;Re=w.state,w.recoveryActions.length>0&&n.debug(`tool loop recovery: ${w.recoveryActions.map(I=>I.detail??I.kind).join("; ")}`),n.debug(`turn ${q}, messages: ${R.length}`),u?.invoke("turn.before_inference",{...g,model:v.currentModel}).catch(()=>{});let P=!1,C=[],j=new Map,G="stop",L,U=null,ce=!1,Y=[],ne=[];try{for await(let I of e.stream({model:v.currentModel,messages:R,tools:h.tools,toolChoice:h.normalizedToolChoice??"auto",temperature:l,maxTokens:(Ae??X.currentMaxOutputTokens)||void 0,streamRequired:r.streamRequired,previousResponseId:v.lastResponseId,reasoning:r.reasoning,promptCacheKey:r.promptCacheKey,promptCacheRetention:r.promptCacheRetention,serviceTier:r.serviceTier,openaiBuiltinTools:r.openaiBuiltinTools,maxToolCalls:r.maxToolCalls,parallelToolCalls:r.parallelToolCalls,textVerbosity:r.textVerbosity},d,p))switch(I.type){case"delta":C.push(I.text),P||(yield{type:"delta",turnId:o,text:I.text});break;case"tool_call_delta":P=!0,js(j,I);break;case"reasoning_delta":Y.push(I.text);break;case"reasoning_block_complete":I.signature&&ne.push({thinking:Y.join(""),signature:I.signature}),Y.length=0;break;case"usage":L={prompt:I.promptTokens,completion:I.completionTokens,reasoning:I.reasoningTokens,cacheRead:I.cacheReadTokens,cacheCreation:I.cacheCreationTokens};break;case"response_id":v.lastResponseId=I.id;break;case"annotations":yield{type:"annotations",turnId:o,annotations:I.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:o,message:`${I.toolType}: ${I.event}`};break;case"done":G=I.finishReason;break}if(P||u?.invoke("turn.after_inference",{...g,model:v.currentModel}).catch(()=>{}),r.postSamplingHooks&&r.postSamplingHooks.length>0){let I=v.currentModel;for(let O of r.postSamplingHooks)try{O({messages:[...fe],model:I,sessionId:s})}catch{}}}catch(I){if(I instanceof dn&&r.fallbackModel){n.info(`model fallback triggered: ${I.originalModel} \u2192 ${I.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`${I.originalModel} \u2192 ${I.fallbackModel}`},v={...v,currentModel:I.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let O=I instanceof Error?I.message:String(I),N=typeof I?.status=="number"?I.status:void 0;if(!N&&O&&(O.includes("ECONNRESET")||O.includes("EPIPE"))){let Q=(v.consecutiveApiRetries??0)+1;if(Q>vt){n.info(`stale connection retry limit reached (${vt}), aborting`),yield{type:"error",turnId:o,error:O,code:"RETRIES_EXHAUSTED",usage:v.totalUsage};return}n.info(`stale connection (${O.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:o,action:"stale_connection_retry",detail:O.slice(0,80)},v={...v,consecutiveApiRetries:Q,transition:void 0};continue}let W=Pf({status:N,message:O});if(W!==null){n.info(`max_tokens overflow: adjusting to ${W}`),X.currentMaxOutputTokens=W,v={...v,maxOutputTokensOverride:W,transition:void 0};continue}if(As(N)){if(v.consecutive529Errors++,v.consecutive529Errors>=go&&r.fallbackModel&&v.currentModel!==r.fallbackModel){n.info(`529 \xD7 ${v.consecutive529Errors}: triggering fallback to ${r.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`529 \xD7 ${v.consecutive529Errors}`},v={...v,currentModel:r.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Is()){let Q=yo(v.consecutive529Errors);n.info(`persistent retry: waiting ${Q}ms (attempt ${v.consecutive529Errors})`);let K=Q;for(;K>0;){if(p?.aborted){yield{type:"error",turnId:o,error:"Aborted during retry wait",code:"ABORTED",usage:v.totalUsage};return}yield{type:"heartbeat",turnId:o,message:`Retrying in ${Math.ceil(K/1e3)}s (${N})`};let le=Math.min(K,mo);await new Promise(Lr=>setTimeout(Lr,le)),K-=le}v={...v,transition:void 0};continue}if(Cs(m)){let K=If({status:N,message:O})??yo(v.consecutive529Errors);n.info(`transient ${N}: retry in ${K}ms`),yield{type:"recovery",turnId:o,action:"retry",detail:`${N} retry in ${K}ms`},await new Promise(le=>setTimeout(le,K)),v={...v,transition:void 0};continue}n.info(`background source ${m}: not retrying ${N}`)}U={status:N,message:O}}if(U&&u?.invoke("turn.after_inference",{...g,model:v.currentModel,response:{error:U.message}}).catch(()=>{}),U)if(Pl(U))ce=!0,n.info(`withheld prompt_too_long error (status=${U.status})`);else if(Ml(U))ce=!0,n.info(`withheld media_size error (status=${U.status})`);else{let I=Ls({status:U.status??500,message:U.message},X,S);if(I.action==="reactive_compact"&&Ft(be)&&(be.attemptedThisTurn=!0,X.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:o,action:"reactive_compact",detail:`API ${U.status??500}: ${U.message}`}),I.action==="retry"){let N=(v.consecutiveApiRetries??0)+1;if(N>vt){n.info(`API retry limit reached (${vt}), aborting`);let W=Nt(U.status,U.message);yield{type:"error",turnId:o,error:U.message,code:W,usage:v.totalUsage};return}yield{type:"recovery",turnId:o,action:"retry",detail:I.reason},v={...v,consecutiveApiRetries:N,transition:void 0};continue}let O=Nt(U.status,U.message);u?.invoke("stop.failure",{sessionId:s,reason:O,error:U.message}).catch(()=>{}),yield{type:"error",turnId:o,error:U.message,code:O,usage:v.totalUsage};return}L&&(v.totalUsage.prompt+=L.prompt,v.totalUsage.completion+=L.completion,L.reasoning&&(v.totalUsage.reasoning=(v.totalUsage.reasoning??0)+L.reasoning),L.cacheRead&&(v.totalUsage.cacheRead=(v.totalUsage.cacheRead??0)+L.cacheRead),L.cacheCreation&&(v.totalUsage.cacheCreation=(v.totalUsage.cacheCreation??0)+L.cacheCreation)),L?.prompt&&(X.promptTokens=L.prompt);let ae=C.join("");ae&&(v.finalText=ae);let ke=[...j.values()].map(I=>({id:I.id||`tc_${o}_${q}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:I.name,arguments:I.arguments}}));if(ke.length===0&&!P){if(ce&&U&&Pl(U)){if(v.transition?.reason!=="collapse_drain_retry"){let N=Kr(fe,ge);if(N.committed>0){n.info(`collapse drain: committed ${N.committed} stages`),yield{type:"recovery",turnId:o,action:"collapse_drain",detail:`${N.committed} stages committed`},v={...v,messages:N.messages,transition:{reason:"collapse_drain_retry",committed:N.committed}};continue}}if(Ft(be)){be.attemptedThisTurn=!0,X.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"withheld prompt_too_long"},v={...v,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),u?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:U.message}).catch(()=>{}),yield{type:"error",turnId:o,error:U.message,code:"PROMPT_TOO_LONG",usage:v.totalUsage};return}if(ce&&U&&Ml(U)){if(Ft(be)){be.attemptedThisTurn=!0,X.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"media error strip-retry"},v={...v,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),u?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:U.message}).catch(()=>{}),yield{type:"error",turnId:o,error:U.message,code:"IMAGE_ERROR",usage:v.totalUsage};return}if(Af(G)){X.consecutiveTruncations+=1;let N=r.modelMaxOutputTokens??io,W=$s(X,S,N);if(W.shouldEscalate&&Ae===void 0){X.currentMaxOutputTokens=W.newMax,n.info(`max_output_tokens escalate: ${W.newMax} tokens`),yield{type:"recovery",turnId:o,action:"output_escalation",detail:`${W.newMax} tokens`},v={...v,maxOutputTokensOverride:lo,transition:{reason:"max_output_tokens_escalate"}};continue}if(V<ao){let Q={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 #${V+1}`),yield{type:"recovery",turnId:o,action:"max_output_tokens_recovery",detail:`attempt ${V+1}`},v={...v,messages:[...fe,Q],maxOutputTokensRecoveryCount:V+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:V+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else X.consecutiveTruncations=0;if(Re=fo(Re,{replayMessages:E,lastStopReason:"completed"}),u){let N=await u.invoke("stop",{sessionId:s,reason:"completed"});if(N.action==="prevent"){n.info(`stop hook prevented continuation: ${N.reason??"no reason"}`),yield{type:"end",turnId:o,content:v.finalText,usage:v.totalUsage,model:v.currentModel};return}if(N.action==="abort"){let W=N.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${W}`);let Q={role:"user",content:W},K={role:"assistant",content:v.finalText,...ne.length>0&&{thinkingBlocks:[...ne]}};v={...v,messages:[...E,K,Q],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(r.tokenBudget&&r.tokenBudget>0&&v.budgetContinuationCount<5){let N=v.totalUsage.prompt+v.totalUsage.completion+(v.totalUsage.reasoning??0),W=N/r.tokenBudget*100,Q=N-v.lastBudgetGlobalTokens,K=v.budgetContinuationCount>=co&&Q<an&&v.lastBudgetDeltaTokens<an;if(K&&n.info(`token budget early stop: diminishing returns at ${Math.round(W)}% (delta=${Q})`),!K&&W<90){let le=v.budgetContinuationCount+1,Lr={role:"user",content:_l(W,N,r.tokenBudget)};n.info(`token budget continuation #${le}: ${Math.round(W)}% used`),yield{type:"recovery",turnId:o,action:"budget_continuation",detail:`${Math.round(W)}% used (#${le})`};let Tm={role:"assistant",content:v.finalText,...ne.length>0&&{thinkingBlocks:[...ne]}};v={...v,messages:[...E,Tm,Lr],budgetContinuationCount:le,lastBudgetDeltaTokens:Q,lastBudgetGlobalTokens:N,transition:{reason:"token_budget_continuation"}};continue}}if(!v.stopHookActive&&$===0){let N=i.find(K=>K.role==="user"),W=typeof N?.content=="string"?N.content:"";if(/创建文件|生成文件|写入|写一个|建一个|新建|create\s+(a\s+)?file|write\s+(a\s+)?file|make\s+(a\s+)?file|修改|改成|把.*改/i.test(W)){n.info("AP1 action-verification: user requested file action but no tools were called, injecting nudge");let K={role:"user",content:"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes \u2014 actually make them."},le={role:"assistant",content:v.finalText,...ne.length>0&&{thinkingBlocks:[...ne]}};v={...v,messages:[...E,le,K],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!v.stopHookActive&&$>=3&&A.has("write")){let N=0;for(let W of E){let Q=W,K=Q.is_error===!0||typeof Q.content=="string"&&Q.content.startsWith("Error:");Q.role==="tool"&&typeof Q.content=="string"&&!K&&N++}if(N>=3){n.info("AP3 verification nudge: 3+ files created, injecting completeness check");let W={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},Q={role:"assistant",content:v.finalText,...ne.length>0&&{thinkingBlocks:[...ne]}};v={...v,messages:[...E,Q,W],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if($>0){let N={ok:!0,toolCallCount:$,distinctToolCount:A.size,multiStep:$>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},W=cn(N,{tools:[...A]});W&&(yield{type:"skill_instruction",turnId:o,instruction:W})}let O=v.finalText||un(E,n);yield{type:"end",turnId:o,content:O,usage:v.totalUsage,model:v.currentModel};return}for(let I of ke){let O=I.function.arguments,N=D.find(W=>W.function.name===I.function.name);if(N?.backfillObservableInput)try{let W=JSON.parse(I.function.arguments),Q={...W};N.backfillObservableInput(Q),Object.keys(Q).some(le=>!(le in W))&&(O=JSON.stringify(Q))}catch{}yield{type:"tool_call",turnId:o,callId:I.id,name:I.function.name,arguments:O}}let Yn=ne.length===0&&Y.length>0?Y.join(""):void 0;E.push(Ur(ke,v.finalText||void 0,ne.length>0?ne:void 0,Yn)),Re=_s(Re,{replayMessages:E,pendingToolCallIds:ke.map(I=>I.id),completedToolCallIds:Re.completedToolCallIds,lastStopReason:"tool_calls"});let re=[];try{let I=new To({toolInvoker:t,hooks:u,sessionId:s,turnId:o,log:n,signal:p,maxConcurrentTools:r?.maxConcurrentTools});for(let O of ke)I.addTool(O);for await(let O of I.getRemainingResults()){O.blocked&&(yield{type:"tool_blocked",turnId:o,callId:O.callId,name:O.toolName,reason:O.blockReason??"blocked"}),E.push(O.message),re.push(O.callId),A.add(O.toolName),$++;let N=typeof O.message?.content=="string"?O.message.content:"",W=O.ok&&N?N.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:o,callId:O.callId,name:O.toolName,ok:O.ok,error:O.error,outputPreview:W},O.ok){let Q=ke.find(K=>K.id===O.callId);if(Q){if(O.toolName==="plan_mode")try{let K=JSON.parse(Q.function.arguments);K.action==="exit"&&typeof K.plan=="string"&&K.plan.length>0&&(yield{type:"plan_update",turnId:o,slug:"approved-plan",content:K.plan})}catch{}if(xf.has(O.toolName))try{let K=JSON.parse(Q.function.arguments),le=typeof K.file_path=="string"?K.file_path:typeof K.filePath=="string"?K.filePath:typeof K.path=="string"?K.path:void 0;le&&(yield{type:"artifact",turnId:o,artifactId:`artifact-${O.callId}`,artifactType:Rf(le),title:le.split(/[\\/]/).pop()||le,filePath:le,language:_f(le)})}catch{}}}}}catch(I){let O=I instanceof Error?I.message:String(I);yield{type:"error",turnId:o,error:O,code:"TOOL_EXECUTION_ERROR",usage:v.totalUsage};return}if(Re=fo(Re,{replayMessages:E,completedToolCallIds:[...Re.completedToolCallIds,...re],lastStopReason:"tool_calls"}),r.generateToolUseSummary&&ke.length>0){let I=ke.map(O=>({name:O.function.name,arguments:O.function.arguments}));B=r.generateToolUseSummary(I).catch(()=>null)}let ct=E.slice(-ke.length),He=ct.length>0&&ct.every(I=>{let O=I?.content;return typeof O!="string"?!1:O.startsWith("Error: ")}),Te=v.consecutiveFailedRounds;if(He){if(Te+=1,Te>=to){let I=v.finalText||un(E,n);n.info(`early exit: ${Te} consecutive failed rounds, returning ${v.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:o,content:I,usage:v.totalUsage,model:v.currentModel};return}}else Te=0;let Or=v.identicalCallCounts,Ia=!1;for(let I of ke){let O=`${I.function.name}::${I.function.arguments}`,N=Or.get(O)??0;if(Or.set(O,N+1),N+1>no&&!Ia){let W={role:"user",content:`You have called tool "${I.function.name}" with the exact same arguments ${N+1} times. This is not working. Stop repeating this call. Either try a different approach, different arguments, or report the issue to the user.`};E.push(W),Ia=!0,n.info(`AP4 identical-call nudge: ${I.function.name} repeated ${N+1}x`)}}let Dr=q+1;if(f>0&&Dr>f){if(n.info(`max turns reached (${f}), completing`),u){let O=await u.invoke("stop",{sessionId:s,reason:"max_turns"});if(O.action==="abort"){let N=O.reason??"Stop hook requested continuation after max_turns",W={role:"assistant",content:v.finalText,...ne.length>0&&{thinkingBlocks:[...ne]}};v={...v,messages:[...E,W,{role:"user",content:N}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let I=v.finalText||un(E,n);yield{type:"end",turnId:o,content:I,usage:v.totalUsage,model:v.currentModel};return}if(Dr>x){if(n.info(`tool loop budget exhausted (${x} rounds), returning`),$>0){let O={ok:!0,toolCallCount:$,distinctToolCount:A.size,multiStep:$>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},N=cn(O,{tools:[...A]});N&&(yield{type:"skill_instruction",turnId:o,instruction:N})}let I=v.finalText||un(E,n);yield{type:"end",turnId:o,content:I,usage:v.totalUsage,model:v.currentModel};return}v={messages:E,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Dr,transition:{reason:"next_turn"},guardState:X,reactiveCompactState:be,toolLoopState:Re,consecutiveFailedRounds:Te,finalText:v.finalText,totalUsage:v.totalUsage,collapseStore:ge,currentModel:v.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:v.stopHookActive,lastResponseId:v.lastResponseId,snipRemovedIds:v.snipRemovedIds,contentReplacementState:v.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:Or}}}function un(r,e){let t=[];for(let n=r.length-1;n>=0;n--){let o=r[n];if(o.role==="tool"&&typeof o.content=="string")t.unshift(o.content.slice(0,500));else if(o.role==="assistant"){if(typeof o.content=="string"&&o.content.trim())return e.info("synthesizeFallbackContent: found assistant text, using it"),o.content;break}else break}return t.length>0?(e.info(`synthesizeFallbackContent: synthesized from ${t.length} tool result(s)`),t.join(`
25
+ `)}`}function Af(){return Gr(new St(Xs),new ut(20,_t),new Wt(_t))}function Cc(r,e){let t=Hr(new St(Xs),new ut(20,_t),new rn({protectedHeadExchanges:1,protectedTailMessages:8,summarize:r,estimateTokens:_t}),new Wt(_t));return new sn({inner:t,estimateTokens:_t,onCacheInvalidated:e?.onCacheInvalidated})}function Mc(r,e){let t=e?.budget??oo({modelContextWindow:Pc(e?.model)}),o=(e?.pipeline??Af()).compress(r,t);if(o.droppedCount>0){let s=xt(r),i=xt(o.messages);Ic.record({timestamp:Date.now(),strategy:o.strategy,tokensBefore:s,tokensAfter:i,droppedCount:o.droppedCount,latencyMs:o.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:o.metrics?.cacheInvalidated??!1,tier:dn(s,t)})}return o.droppedCount>0&&Ys?.(o.droppedCount,xt(o.messages)),o}async function Cf(r,e,t){let n=t??oo({modelContextWindow:Pc(e.model)}),o=xt(r),s=dn(o,n),i;switch(s){case"none":i={messages:r,droppedCount:0,strategy:"none"};break;case"trim-only":i=new St(Xs).compress(r,n);break;case"sliding-window":{i=await Cc(e.summarize).compressAsync(r,n);break}case"llm-summarize":{let a=e.pipeline??Cc(e.summarize);i=ln(a)?await a.compressAsync(r,n):a.compress(r,n);break}}return i.droppedCount>0&&(i={...i,messages:await zr(i.messages,r,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await Rf(a,"utf-8")}catch{return null}}})}),Pf(r,i,n),i}function Pf(r,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||xt(r),o=e.metrics?.tokensAfter||xt(e.messages);Ic.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:n,tokensAfter:o,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:dn(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||xt(e.messages);Ys?.(e.droppedCount,n)}}function If(r,e){let t=xf(r,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(o,s,i){return Cf(o,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};Ac.register(n),Ac.activate(n.id),r.info(`[context-compression] registered context engine: ${n.id}`)}function Ec(r,e,t){If(e,t),r.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(n,o)=>{let s=o.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),Ys=(n,o)=>{e.debug(`[context-compression] after_compact: removed ${n}, ${o} tokens remaining`),r.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:n,tokenCount:o}).catch(()=>{})}}var Ks,Xs,_f,Ic,Ac,Ys,Js=te(()=>{"use strict";Ht();Ks={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-3.1-pro-preview":1e6,"gemini-3-flash-preview":1e6,"gemini-3.1-flash-lite":1e6};Xs=8e3,_f="deepseek-v4-flash",Ic=new an(200),Ac=new cn;Ys=null});function Oc(r,e,t){let n=t-e;return`[Budget] ${Math.round(r)}% used (${e.toLocaleString()} / ${t.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(r>=90?"Wrap up your current task \u9225?you are near the token limit.":"Continue working \u9225?do not summarize prematurely.")}var Dc=te(()=>{"use strict"});var Lc={};Na(Lc,{resolveToolEligibility:()=>Lf});function Ef(r,e){if(Mf.some(t=>t.test(r)))return!0;if(e)for(let t of e)try{if(new RegExp(t,"i").test(r))return!0}catch{}return!1}function Of(r,e){let t=r.function.name,n=r.meta,o=[];return e.blockedToolNames?.includes(t)?(o.push("policy_blocked"),{level:5,reasons:o}):n?.isReadOnly?(o.push("always_allowed"),{level:1,reasons:o}):n?.requiresApproval?(o.push("approval_required"),{level:4,reasons:o}):n?.isDangerous||Ef(t,e.dangerousPatterns)?(o.push("dangerous_tool"),{level:3,reasons:o}):{level:2,reasons:o}}function Df(r){switch(r){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 Lf(r,e={}){let t=new Map,n=[],o=[],s=[];for(let i of r){let a=i.function.name,{level:c,reasons:d}=Of(i,e),l=Df(c),u={toolName:a,status:l,permissionLevel:c,approvalRequired:c===4,reasonCodes:d};t.set(a,u),c===5?o.push(u):(n.push(i),c===4&&s.push(u))}return{eligibleTools:n,blockedTools:o,approvalRequiredTools:s,eligibilityByName:t}}var Mf,Nc=te(()=>{"use strict";Mf=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Uf(r){let e=r.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 $f(r){let e=r.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 jf(r){return typeof r=="number"&&Number.isFinite(r)&&r>=1?Math.min(Math.round(r),100):ro}function Uc(r){let e=r.message.toLowerCase();return r.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function Ff(r){return r==="length"||r==="max_tokens"}function $c(r){let e=r.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(r.status===413||e.includes("too large")||e.includes("size"))}function Bf(r){let e=r.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 Wf(r){if(r.status!==400)return null;let e=r.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 o=n-t-1e3;return o>=3e3?o:null}function Gf(r){return r.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*jc(r,e,t,n){let{turnId:o,sessionId:s,messages:i,tools:a,model:c,apiKey:d,temperature:l=0,hooks:u,signal:p}=r,m={sessionId:s,turnId:o},f=r.maxTurns??0,g=r.querySource,{resolveToolEligibility:y}=await Promise.resolve().then(()=>(Nc(),Lc)),b=y(a,r.toolEligibilityContext),k=b.eligibleTools;for(let E of b.blockedTools)yield{type:"tool_blocked",turnId:o,callId:"",name:E.toolName,reason:"blocked-by-policy"};if(!k.length){yield*Hf(o,c,i,d,l,p,e,n);return}let S=jf(r.maxRounds),R={contextWindowTokens:r.contextWindowTokens??ao,responseBufferTokens:co,maxOutputTokens:r.maxOutputTokens??lo,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},P=new Set,O=0,L=k,B,v={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Us(R),reactiveCompactState:Ws(),toolLoopState:To({maxRounds:S,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Xr(),currentModel:c,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:kc(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map},ee=Math.max(f*5,200),T=0;for(;;){if(T++,T>ee){n.info(`hard iteration cap reached (${ee}), forcing completion`);let C=v.finalText||fn(v.messages,n);yield{type:"end",turnId:o,content:C,usage:v.totalUsage,model:v.currentModel};return}let{messages:E,maxOutputTokensRecoveryCount:V,hasAttemptedReactiveCompact:re,maxOutputTokensOverride:Me,turnCount:K,guardState:Y,reactiveCompactState:Te,collapseStore:fe}=v,{toolLoopState:Ae}=v;if(B){try{let C=await B;C&&(yield{type:"tool_use_summary",turnId:o,summary:C})}catch{}B=void 0}if(r.refreshTools&&K>1){let C=r.refreshTools();C!==L&&(L=C,n.debug(`tools refreshed: ${C.length} tools`))}if(Bs(Y,R)){n.info(`turn aborted by guard at turn ${K}`),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED",usage:v.totalUsage};return}let nt=$s(Y,R);if(nt.level==="blocking"){nt.reason==="prompt_too_long"&&Gt(Te)&&(Te.attemptedThisTurn=!0,Y.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${nt.reason}), reactive compact needed`),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${nt.reason}), ending tool loop`);break}nt.level==="warning"&&n.info(`token budget warning: ${nt.usagePercent}% used, ${nt.remainingTokens} remaining`);let he;{let C=await _c(E,v.contentReplacementState,s);he=C.messages,C.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${C.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:o,action:"tool_result_budget",detail:`${C.newlyReplacedCount} persisted`})}{let C=Kr(he,v.snipRemovedIds);he=C.messages,C.removedCount>0&&(n.info(`snip: removed ${C.removedCount} messages, freed ~${C.tokensFreed} tokens`),yield{type:"recovery",turnId:o,action:"snip",detail:`${C.removedCount} messages`})}{let D=new ut().compress(he,0);D.droppedCount>0&&(he=D.messages,n.info(`microcompact: cleared ${D.droppedCount} old tool results`))}if(he=Yr(he,fe).messages,Y.promptTokens>0){let C=Mc(he,{budget:R.contextWindowTokens*.75,model:v.currentModel});C.droppedCount>0&&(he=C.messages,n.info(`autocompact: ${C.strategy}, dropped ${C.droppedCount}`),yield{type:"recovery",turnId:o,action:"autocompact",detail:`${C.strategy}: ${C.droppedCount} dropped`},v.hasAttemptedReactiveCompact=!1,u?.invoke("context.after_compact",{...m,removedCount:C.droppedCount}).catch(()=>{}))}he=Gf(he);let h=Ss({tools:L,toolChoice:r.toolChoice??"auto"}),w=To({maxRounds:S,replayMessages:he,lastStopReason:Ae.lastStopReason,options:{stopReason:Ae.lastStopReason}}),_=h.extraSystemPrompt?[{role:"system",content:h.extraSystemPrompt},...w.state.replayMessages]:w.state.replayMessages;Ae=w.state,w.recoveryActions.length>0&&n.debug(`tool loop recovery: ${w.recoveryActions.map(C=>C.detail??C.kind).join("; ")}`),n.debug(`turn ${K}, messages: ${_.length}`),u?.invoke("turn.before_inference",{...m,model:v.currentModel}).catch(()=>{});let I=!1,A=[],j=new Map,W="stop",N,U=null,ue=!1,J=[],oe=[];try{for await(let C of e.stream({model:v.currentModel,messages:_,tools:h.tools,toolChoice:h.normalizedToolChoice??"auto",temperature:l,maxTokens:(Me??Y.currentMaxOutputTokens)||void 0,streamRequired:r.streamRequired,previousResponseId:v.lastResponseId,reasoning:r.reasoning,promptCacheKey:r.promptCacheKey,promptCacheRetention:r.promptCacheRetention,serviceTier:r.serviceTier,openaiBuiltinTools:r.openaiBuiltinTools,maxToolCalls:r.maxToolCalls,parallelToolCalls:r.parallelToolCalls,textVerbosity:r.textVerbosity},d,p))switch(C.type){case"delta":A.push(C.text),I||(yield{type:"delta",turnId:o,text:C.text});break;case"tool_call_delta":I=!0,Gs(j,C);break;case"reasoning_delta":J.push(C.text);break;case"reasoning_block_complete":C.signature&&oe.push({thinking:J.join(""),signature:C.signature}),J.length=0;break;case"usage":N={inputTokens:C.promptTokens,outputTokens:C.completionTokens,reasoningTokens:C.reasoningTokens,cacheRead:C.cacheReadTokens,cacheWrite:C.cacheCreationTokens};break;case"response_id":v.lastResponseId=C.id;break;case"annotations":yield{type:"annotations",turnId:o,annotations:C.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:o,message:`${C.toolType}: ${C.event}`};break;case"done":W=C.finishReason;break}if(I||u?.invoke("turn.after_inference",{...m,model:v.currentModel}).catch(()=>{}),r.postSamplingHooks&&r.postSamplingHooks.length>0){let C=v.currentModel;for(let D of r.postSamplingHooks)try{D({messages:[...he],model:C,sessionId:s})}catch{}}}catch(C){if(C instanceof gn&&r.fallbackModel){n.info(`model fallback triggered: ${C.originalModel} \u2192 ${C.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`${C.originalModel} \u2192 ${C.fallbackModel}`},v={...v,currentModel:C.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let D=C instanceof Error?C.message:String(C),$=typeof C?.status=="number"?C.status:void 0;if(!$&&D&&(D.includes("ECONNRESET")||D.includes("EPIPE"))){let Q=(v.consecutiveApiRetries??0)+1;if(Q>Rt){n.info(`stale connection retry limit reached (${Rt}), aborting`),yield{type:"error",turnId:o,error:D,code:"RETRIES_EXHAUSTED",usage:v.totalUsage};return}n.info(`stale connection (${D.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:o,action:"stale_connection_retry",detail:D.slice(0,80)},v={...v,consecutiveApiRetries:Q,transition:void 0};continue}let H=Wf({status:$,message:D});if(H!==null){n.info(`max_tokens overflow: adjusting to ${H}`),Y.currentMaxOutputTokens=H,v={...v,maxOutputTokensOverride:H,transition:void 0};continue}if(Ms($)){if(v.consecutive529Errors++,v.consecutive529Errors>=bo&&r.fallbackModel&&v.currentModel!==r.fallbackModel){n.info(`529 \xD7 ${v.consecutive529Errors}: triggering fallback to ${r.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`529 \xD7 ${v.consecutive529Errors}`},v={...v,currentModel:r.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Es()){let Q=wo(v.consecutive529Errors);n.info(`persistent retry: waiting ${Q}ms (attempt ${v.consecutive529Errors})`);let q=Q;for(;q>0;){if(p?.aborted){yield{type:"error",turnId:o,error:"Aborted during retry wait",code:"ABORTED",usage:v.totalUsage};return}yield{type:"heartbeat",turnId:o,message:`Retrying in ${Math.ceil(q/1e3)}s (${$})`};let de=Math.min(q,yo);await new Promise($r=>setTimeout($r,de)),q-=de}v={...v,transition:void 0};continue}if(Is(g)){let q=Bf({status:$,message:D})??wo(v.consecutive529Errors);n.info(`transient ${$}: retry in ${q}ms`),yield{type:"recovery",turnId:o,action:"retry",detail:`${$} retry in ${q}ms`},await new Promise(de=>setTimeout(de,q)),v={...v,transition:void 0};continue}n.info(`background source ${g}: not retrying ${$}`)}U={status:$,message:D}}if(U&&u?.invoke("turn.after_inference",{...m,model:v.currentModel,response:{error:U.message}}).catch(()=>{}),U)if(Uc(U))ue=!0,n.info(`withheld prompt_too_long error (status=${U.status})`);else if($c(U))ue=!0,n.info(`withheld media_size error (status=${U.status})`);else{let C=js({status:U.status??500,message:U.message},Y,R);if(C.action==="reactive_compact"&&Gt(Te)&&(Te.attemptedThisTurn=!0,Y.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:o,action:"reactive_compact",detail:`API ${U.status??500}: ${U.message}`}),C.action==="retry"){let $=(v.consecutiveApiRetries??0)+1;if($>Rt){n.info(`API retry limit reached (${Rt}), aborting`);let H=Bt(U.status,U.message);yield{type:"error",turnId:o,error:U.message,code:H,usage:v.totalUsage};return}yield{type:"recovery",turnId:o,action:"retry",detail:C.reason},v={...v,consecutiveApiRetries:$,transition:void 0};continue}let D=Bt(U.status,U.message);u?.invoke("stop.failure",{sessionId:s,reason:D,error:U.message}).catch(()=>{}),yield{type:"error",turnId:o,error:U.message,code:D,usage:v.totalUsage};return}N&&(v.totalUsage.inputTokens+=N.inputTokens,v.totalUsage.outputTokens+=N.outputTokens,N.reasoningTokens&&(v.totalUsage.reasoningTokens=(v.totalUsage.reasoningTokens??0)+N.reasoningTokens),N.cacheRead&&(v.totalUsage.cacheRead=(v.totalUsage.cacheRead??0)+N.cacheRead),N.cacheWrite&&(v.totalUsage.cacheWrite=(v.totalUsage.cacheWrite??0)+N.cacheWrite)),N?.inputTokens&&(Y.promptTokens=N.inputTokens);let le=A.join("");le&&(v.finalText=le);let we=[...j.values()].map(C=>({id:C.id||`tc_${o}_${K}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:C.name,arguments:C.arguments}}));if(we.length===0&&!I){if(ue&&U&&Uc(U)){if(v.transition?.reason!=="collapse_drain_retry"){let $=Jr(he,fe);if($.committed>0){n.info(`collapse drain: committed ${$.committed} stages`),yield{type:"recovery",turnId:o,action:"collapse_drain",detail:`${$.committed} stages committed`},v={...v,messages:$.messages,transition:{reason:"collapse_drain_retry",committed:$.committed}};continue}}if(Gt(Te)){Te.attemptedThisTurn=!0,Y.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"withheld prompt_too_long"},v={...v,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),u?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:U.message}).catch(()=>{}),yield{type:"error",turnId:o,error:U.message,code:"PROMPT_TOO_LONG",usage:v.totalUsage};return}if(ue&&U&&$c(U)){if(Gt(Te)){Te.attemptedThisTurn=!0,Y.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"media error strip-retry"},v={...v,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),u?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:U.message}).catch(()=>{}),yield{type:"error",turnId:o,error:U.message,code:"IMAGE_ERROR",usage:v.totalUsage};return}if(Ff(W)){Y.consecutiveTruncations+=1;let $=r.modelMaxOutputTokens??uo,H=Fs(Y,R,$);if(H.shouldEscalate&&Me===void 0){Y.currentMaxOutputTokens=H.newMax,n.info(`max_output_tokens escalate: ${H.newMax} tokens`),yield{type:"recovery",turnId:o,action:"output_escalation",detail:`${H.newMax} tokens`},v={...v,maxOutputTokensOverride:mo,transition:{reason:"max_output_tokens_escalate"}};continue}if(V<po){let Q={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 #${V+1}`),yield{type:"recovery",turnId:o,action:"max_output_tokens_recovery",detail:`attempt ${V+1}`},v={...v,messages:[...he,Q],maxOutputTokensRecoveryCount:V+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:V+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else Y.consecutiveTruncations=0;if(Ae=ko(Ae,{replayMessages:E,lastStopReason:"completed"}),u){let $=await u.invoke("stop",{sessionId:s,reason:"completed"});if($.action==="prevent"){n.info(`stop hook prevented continuation: ${$.reason??"no reason"}`),yield{type:"end",turnId:o,content:v.finalText,usage:v.totalUsage,model:v.currentModel};return}if($.action==="abort"){let H=$.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${H}`);let Q={role:"user",content:H},q={role:"assistant",content:v.finalText,...oe.length>0&&{thinkingBlocks:[...oe]}};v={...v,messages:[...E,q,Q],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(r.tokenBudget&&r.tokenBudget>0&&v.budgetContinuationCount<5){let $=v.totalUsage.inputTokens+v.totalUsage.outputTokens+(v.totalUsage.reasoningTokens??0),H=$/r.tokenBudget*100,Q=$-v.lastBudgetGlobalTokens,q=v.budgetContinuationCount>=go&&Q<un&&v.lastBudgetDeltaTokens<un;if(q&&n.info(`token budget early stop: diminishing returns at ${Math.round(H)}% (delta=${Q})`),!q&&H<90){let de=v.budgetContinuationCount+1,$r={role:"user",content:Oc(H,$,r.tokenBudget)};n.info(`token budget continuation #${de}: ${Math.round(H)}% used`),yield{type:"recovery",turnId:o,action:"budget_continuation",detail:`${Math.round(H)}% used (#${de})`};let Om={role:"assistant",content:v.finalText,...oe.length>0&&{thinkingBlocks:[...oe]}};v={...v,messages:[...E,Om,$r],budgetContinuationCount:de,lastBudgetDeltaTokens:Q,lastBudgetGlobalTokens:$,transition:{reason:"token_budget_continuation"}};continue}}if(!v.stopHookActive&&O===0){let $=i.find(q=>q.role==="user"),H=typeof $?.content=="string"?$.content:"";if(/创建文件|生成文件|写入|写一个|建一个|新建|create\s+(a\s+)?file|write\s+(a\s+)?file|make\s+(a\s+)?file|修改|改成|把.*改/i.test(H)){n.info("AP1 action-verification: user requested file action but no tools were called, injecting nudge");let q={role:"user",content:"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes \u2014 actually make them."},de={role:"assistant",content:v.finalText,...oe.length>0&&{thinkingBlocks:[...oe]}};v={...v,messages:[...E,de,q],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!v.stopHookActive&&O>=3&&P.has("write")){let $=0;for(let H of E){let Q=H,q=Q.is_error===!0||typeof Q.content=="string"&&Q.content.startsWith("Error:");Q.role==="tool"&&typeof Q.content=="string"&&!q&&$++}if($>=3){n.info("AP3 verification nudge: 3+ files created, injecting completeness check");let H={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},Q={role:"assistant",content:v.finalText,...oe.length>0&&{thinkingBlocks:[...oe]}};v={...v,messages:[...E,Q,H],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(O>0){let $={ok:!0,toolCallCount:O,distinctToolCount:P.size,multiStep:O>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},H=mn($,{tools:[...P]});H&&(yield{type:"skill_instruction",turnId:o,instruction:H})}let D=v.finalText||fn(E,n);yield{type:"end",turnId:o,content:D,usage:v.totalUsage,model:v.currentModel};return}for(let C of we){let D=C.function.arguments,$=L.find(H=>H.function.name===C.function.name);if($?.backfillObservableInput)try{let H=JSON.parse(C.function.arguments),Q={...H};$.backfillObservableInput(Q),Object.keys(Q).some(de=>!(de in H))&&(D=JSON.stringify(Q))}catch{}yield{type:"tool_call",turnId:o,callId:C.id,name:C.function.name,arguments:D}}let to=oe.length===0&&J.length>0?J.join(""):void 0;E.push(Fr(we,v.finalText||void 0,oe.length>0?oe:void 0,to)),Ae=Ps(Ae,{replayMessages:E,pendingToolCallIds:we.map(C=>C.id),completedToolCallIds:Ae.completedToolCallIds,lastStopReason:"tool_calls"});let se=[];try{let C=new Ro({toolInvoker:t,hooks:u,sessionId:s,turnId:o,log:n,signal:p,maxConcurrentTools:r?.maxConcurrentTools});for(let D of we)C.addTool(D);for await(let D of C.getRemainingResults()){D.blocked&&(yield{type:"tool_blocked",turnId:o,callId:D.callId,name:D.toolName,reason:D.blockReason??"blocked"}),E.push(D.message),se.push(D.callId),P.add(D.toolName),O++;let $=typeof D.message?.content=="string"?D.message.content:"",H=D.ok&&$?$.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:o,callId:D.callId,name:D.toolName,ok:D.ok,error:D.error,outputPreview:H},D.ok){let Q=we.find(q=>q.id===D.callId);if(Q){if(D.toolName==="plan_mode")try{let q=JSON.parse(Q.function.arguments);q.action==="exit"&&typeof q.plan=="string"&&q.plan.length>0&&(yield{type:"plan_update",turnId:o,slug:"approved-plan",content:q.plan})}catch{}if(Nf.has(D.toolName))try{let q=JSON.parse(Q.function.arguments),de=typeof q.file_path=="string"?q.file_path:typeof q.filePath=="string"?q.filePath:typeof q.path=="string"?q.path:void 0;de&&(yield{type:"artifact",turnId:o,artifactId:`artifact-${D.callId}`,artifactType:Uf(de),title:de.split(/[\\/]/).pop()||de,filePath:de,language:$f(de)})}catch{}}}}}catch(C){let D=C instanceof Error?C.message:String(C);yield{type:"error",turnId:o,error:D,code:"TOOL_EXECUTION_ERROR",usage:v.totalUsage};return}if(Ae=ko(Ae,{replayMessages:E,completedToolCallIds:[...Ae.completedToolCallIds,...se],lastStopReason:"tool_calls"}),r.generateToolUseSummary&&we.length>0){let C=we.map(D=>({name:D.function.name,arguments:D.function.arguments}));B=r.generateToolUseSummary(C).catch(()=>null)}let dt=E.slice(-we.length),Ke=dt.length>0&&dt.every(C=>{let D=C?.content;return typeof D!="string"?!1:D.startsWith("Error: ")}),ve=v.consecutiveFailedRounds;if(Ke){if(ve+=1,ve>=so){let C=v.finalText||fn(E,n);n.info(`early exit: ${ve} consecutive failed rounds, returning ${v.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:o,content:C,usage:v.totalUsage,model:v.currentModel};return}}else ve=0;let Nr=v.identicalCallCounts,La=!1;for(let C of we){let D=`${C.function.name}::${C.function.arguments}`,$=Nr.get(D)??0;if(Nr.set(D,$+1),$+1>io&&!La){let H={role:"user",content:`You have called tool "${C.function.name}" with the exact same arguments ${$+1} times. This is not working. Stop repeating this call. Either try a different approach, different arguments, or report the issue to the user.`};E.push(H),La=!0,n.info(`AP4 identical-call nudge: ${C.function.name} repeated ${$+1}x`)}}let Ur=K+1;if(f>0&&Ur>f){if(n.info(`max turns reached (${f}), completing`),u){let D=await u.invoke("stop",{sessionId:s,reason:"max_turns"});if(D.action==="abort"){let $=D.reason??"Stop hook requested continuation after max_turns",H={role:"assistant",content:v.finalText,...oe.length>0&&{thinkingBlocks:[...oe]}};v={...v,messages:[...E,H,{role:"user",content:$}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let C=v.finalText||fn(E,n);yield{type:"end",turnId:o,content:C,usage:v.totalUsage,model:v.currentModel};return}if(Ur>S){if(n.info(`tool loop budget exhausted (${S} rounds), returning`),O>0){let D={ok:!0,toolCallCount:O,distinctToolCount:P.size,multiStep:O>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},$=mn(D,{tools:[...P]});$&&(yield{type:"skill_instruction",turnId:o,instruction:$})}let C=v.finalText||fn(E,n);yield{type:"end",turnId:o,content:C,usage:v.totalUsage,model:v.currentModel};return}v={messages:E,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Ur,transition:{reason:"next_turn"},guardState:Y,reactiveCompactState:Te,toolLoopState:Ae,consecutiveFailedRounds:ve,finalText:v.finalText,totalUsage:v.totalUsage,collapseStore:fe,currentModel:v.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:v.stopHookActive,lastResponseId:v.lastResponseId,snipRemovedIds:v.snipRemovedIds,contentReplacementState:v.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:Nr}}}function fn(r,e){let t=[];for(let n=r.length-1;n>=0;n--){let o=r[n];if(o.role==="tool"&&typeof o.content=="string")t.unshift(o.content.slice(0,500));else if(o.role==="assistant"){if(typeof o.content=="string"&&o.content.trim())return e.info("synthesizeFallbackContent: found assistant text, using it"),o.content;break}else break}return t.length>0?(e.info(`synthesizeFallbackContent: synthesized from ${t.length} tool result(s)`),t.join(`
26
26
 
27
- `)):""}async function*Ef(r,e,t,n,o,s,i,a){let c=[],d;a.debug(`single LLM round, messages: ${t.length}`);for await(let l of i.stream({model:e,messages:t,temperature:o},n,s))switch(l.type){case"delta":c.push(l.text),yield{type:"delta",turnId:r,text:l.text};break;case"usage":d={prompt:l.promptTokens,completion:l.completionTokens,reasoning:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheCreation:l.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:r,content:c.join(""),usage:d??{prompt:0,completion:0},model:e}}var xf,Ol=ee(()=>{"use strict";Fs();Bt();kl();qs();Cl();Gs();ko();xf=new Set(["write","edit","patch","apply_patch"])});function Dl(r){if(!r||r.length<5)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};let e=[];for(let[o,s]of Object.entries(Of)){if(o==="general")continue;let i=s.filter(a=>a.test(r)).length;if(i>0){let a=Math.min(1,i/2);e.push({scenario:o,score:a})}}if(e.length===0)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};e.sort((o,s)=>s.score-o.score);let t=e[0];if(t.score<.5)return{scenario:"general",preferred:[],deprioritized:[],confidence:t.score};let n=Df[t.scenario];return{scenario:t.scenario,preferred:n.preferred,deprioritized:n.deprioritized,confidence:t.score}}function Ks(r,e,t){return!e||t.scenario==="general"?r:t.preferred.includes(e)?Math.min(1,r*1.2):t.deprioritized.includes(e)?r*.7:r}function Ll(r){let e=r.replace(/\.md$/,"").toLowerCase();for(let[t,n]of Object.entries(Lf))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return n;return null}var Of,Df,Lf,Js=ee(()=>{"use strict";Of={coding:[/(?:bug|error|fix|debug|报错|修复|编译|compile|build|lint)/i,/(?:implement|refactor|重构|实现|代码|code|function|method|class)/i,/(?:test|测试|vitest|jest|断言|assert)/i,/(?:type(?:script)?|接口|interface|generic|泛型)/i,/(?:import|export|module|依赖|package|npm|pnpm)/i,/(?:git|commit|branch|merge|rebase|PR|MR)/i],config:[/(?:deploy|部署|运维|docker|container|kubernetes|k8s)/i,/(?:port|端口|config|配置|env|环境变量|.env)/i,/(?:server|service|daemon|进程|systemd|nginx|redis)/i,/(?:版本|version|upgrade|migrate|迁移)/i,/(?:domain|域名|ssl|cert|证书|DNS)/i],conversation:[/(?:你好|hi|hello|hey|请问|问一下)/i,/(?:我(?:喜欢|偏好|习惯|想)|prefer|I (?:like|want|need))/i,/(?:帮我|help me|能不能|可以吗|would you)/i,/(?:style|风格|format|格式|命名|naming)/i],learning:[/(?:best practice|最佳实践|pattern|模式|惯例|convention)/i,/(?:怎么做|how to|how do|what's the|推荐|recommend)/i,/(?:为什么|why|原因|reason|explain|解释)/i,/(?:lesson|经验|教训|gotcha|pitfall|坑)/i],decision:[/(?:should|应该|选择|choose|decision|决定|trade-?off|权衡)/i,/(?:vs|versus|对比|compare|区别|difference)/i,/(?:architecture|架构|方案|approach|strategy)/i,/(?:pros|cons|优缺点|利弊|好处|坏处)/i],general:[]},Df={coding:{preferred:["lesson","pattern","fact"],deprioritized:["preference"]},config:{preferred:["fact","decision","lesson"],deprioritized:["preference","skill-learning"]},conversation:{preferred:["preference","fact"],deprioritized:["pattern","skill-learning"]},learning:{preferred:["lesson","pattern","skill-learning"],deprioritized:["preference"]},decision:{preferred:["decision","fact","lesson"],deprioritized:["skill-learning","preference"]},general:{preferred:[],deprioritized:[]}};Lf={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",skill:"skill-learning",workflow:"skill-learning"}});var $l={};Pa($l,{Agent:()=>Gt});var Gt,wo=ee(()=>{"use strict";Bt();Ol();ko();Js();Gt=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:o,tools:s,systemPrompt:i,config:a}=e,c={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...c,prompt:o[o.length-1]?.content??void 0}).catch(()=>{});let d=xs(o),l=[];if(i&&l.push({role:"system",content:i}),l.push(...d),this.hooks){let g=d.filter(m=>m.role==="user").pop(),f=typeof g?.content=="string"?g.content.slice(0,500):void 0;if(f)try{let m=Dl(f),y=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:f,preferredCategories:m.preferred.length>0?m.preferred:void 0,deprioritizedCategories:m.deprioritized.length>0?m.deprioritized:void 0}),k=y?.context?.recalledMemories;if(k&&k.length>0){let b=k.map(x=>`- ${x.text}`).join(`
27
+ `)):""}async function*Hf(r,e,t,n,o,s,i,a){let c=[],d;a.debug(`single LLM round, messages: ${t.length}`);for await(let l of i.stream({model:e,messages:t,temperature:o},n,s))switch(l.type){case"delta":c.push(l.text),yield{type:"delta",turnId:r,text:l.text};break;case"usage":d={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:r,content:c.join(""),usage:d??{inputTokens:0,outputTokens:0},model:e}}var Nf,Fc=te(()=>{"use strict";Hs();Ht();xc();Js();Dc();zs();So();Nf=new Set(["write","edit","patch","apply_patch"])});function Bc(r){if(!r||r.length<5)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};let e=[];for(let[o,s]of Object.entries(Vf)){if(o==="general")continue;let i=s.filter(a=>a.test(r)).length;if(i>0){let a=Math.min(1,i/2);e.push({scenario:o,score:a})}}if(e.length===0)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};e.sort((o,s)=>s.score-o.score);let t=e[0];if(t.score<.5)return{scenario:"general",preferred:[],deprioritized:[],confidence:t.score};let n=zf[t.scenario];return{scenario:t.scenario,preferred:n.preferred,deprioritized:n.deprioritized,confidence:t.score}}function Qs(r,e,t){return!e||t.scenario==="general"?r:t.preferred.includes(e)?Math.min(1,r*1.2):t.deprioritized.includes(e)?r*.7:r}function Wc(r){let e=r.replace(/\.md$/,"").toLowerCase();for(let[t,n]of Object.entries(Kf))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return n;return null}var Vf,zf,Kf,Zs=te(()=>{"use strict";Vf={coding:[/(?:bug|error|fix|debug|报错|修复|编译|compile|build|lint)/i,/(?:implement|refactor|重构|实现|代码|code|function|method|class)/i,/(?:test|测试|vitest|jest|断言|assert)/i,/(?:type(?:script)?|接口|interface|generic|泛型)/i,/(?:import|export|module|依赖|package|npm|pnpm)/i,/(?:git|commit|branch|merge|rebase|PR|MR)/i],config:[/(?:deploy|部署|运维|docker|container|kubernetes|k8s)/i,/(?:port|端口|config|配置|env|环境变量|.env)/i,/(?:server|service|daemon|进程|systemd|nginx|redis)/i,/(?:版本|version|upgrade|migrate|迁移)/i,/(?:domain|域名|ssl|cert|证书|DNS)/i],conversation:[/(?:你好|hi|hello|hey|请问|问一下)/i,/(?:我(?:喜欢|偏好|习惯|想)|prefer|I (?:like|want|need))/i,/(?:帮我|help me|能不能|可以吗|would you)/i,/(?:style|风格|format|格式|命名|naming)/i],learning:[/(?:best practice|最佳实践|pattern|模式|惯例|convention)/i,/(?:怎么做|how to|how do|what's the|推荐|recommend)/i,/(?:为什么|why|原因|reason|explain|解释)/i,/(?:lesson|经验|教训|gotcha|pitfall|坑)/i],decision:[/(?:should|应该|选择|choose|decision|决定|trade-?off|权衡)/i,/(?:vs|versus|对比|compare|区别|difference)/i,/(?:architecture|架构|方案|approach|strategy)/i,/(?:pros|cons|优缺点|利弊|好处|坏处)/i],general:[]},zf={coding:{preferred:["lesson","pattern","fact"],deprioritized:["preference"]},config:{preferred:["fact","decision","lesson"],deprioritized:["preference","skill-learning"]},conversation:{preferred:["preference","fact"],deprioritized:["pattern","skill-learning"]},learning:{preferred:["lesson","pattern","skill-learning"],deprioritized:["preference"]},decision:{preferred:["decision","fact","lesson"],deprioritized:["skill-learning","preference"]},general:{preferred:[],deprioritized:[]}};Kf={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",skill:"skill-learning",workflow:"skill-learning"}});var Gc={};Na(Gc,{Agent:()=>Vt});var Vt,_o=te(()=>{"use strict";Ht();Fc();So();Zs();Vt=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:o,tools:s,systemPrompt:i,config:a}=e,c={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...c,prompt:o[o.length-1]?.content??void 0}).catch(()=>{});let d=As(o),l=[];if(i&&l.push({role:"system",content:i}),l.push(...d),this.hooks){let m=d.filter(g=>g.role==="user").pop(),f=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(f)try{let g=Bc(f),y=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:f,preferredCategories:g.preferred.length>0?g.preferred:void 0,deprioritizedCategories:g.deprioritized.length>0?g.deprioritized:void 0}),b=y?.context?.recalledMemories;if(b&&b.length>0){let k=b.map(S=>`- ${S.text}`).join(`
28
28
  `);l.splice(i?1:0,0,{role:"system",content:`[Recalled from long-term memory]
29
- ${b}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:y?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let u=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let g=a?.summaryModel?async y=>{try{let k=y.map(S=>`${S.name}(${S.arguments.slice(0,200)})`).join(", "),b=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:k}],tools:[],maxTokens:60},a.apiKey??this.apiKey),x="";for await(let S of b)S.type==="delta"&&(x+=S.text);return x.trim()||null}catch{return null}}:void 0,f={turnId:n,sessionId:e.sessionId,messages:l,tools:s,model:u,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:p,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,streamRequired:a?.streamRequired,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,generateToolUseSummary:g,signal:t},m;for await(let y of El(f,this.transport,this.toolInvoker,this.log))m=y,yield y;m?.type==="end"?this.hooks?.invoke("turn.completed",{...c}).catch(()=>{}):m?.type==="error"&&this.hooks?.invoke("turn.failed",{...c,code:m.code,error:m.error}).catch(()=>{})}catch(g){if(t?.aborted)this.hooks?.invoke("turn.failed",{...c,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let f=g instanceof Error?g.message:String(g),m=typeof g?.status=="number"?g.status:void 0,y=Nt(m,f);this.log.error(`turn ${n} error [${y}, retryable=${jr(y)}]: ${f}`),this.hooks?.invoke("turn.failed",{...c,code:y,error:f}).catch(()=>{}),yield{type:"error",turnId:n,error:f,code:y}}}}}});wo();function $f(r){let e={verbose:!1};for(let t of r.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{createInterface as Uf}from"node:readline";var pn=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)}
29
+ ${k}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:y?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let u=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=a?.summaryModel?async y=>{try{let b=y.map(R=>`${R.name}(${R.arguments.slice(0,200)})`).join(", "),k=this.transport.stream({model:a.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:b}],tools:[],maxTokens:60},a.apiKey??this.apiKey),S="";for await(let R of k)R.type==="delta"&&(S+=R.text);return S.trim()||null}catch{return null}}:void 0,f={turnId:n,sessionId:e.sessionId,messages:l,tools:s,model:u,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:p,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,streamRequired:a?.streamRequired,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,generateToolUseSummary:m,signal:t},g;for await(let y of jc(f,this.transport,this.toolInvoker,this.log))g=y,yield y;g?.type==="end"?this.hooks?.invoke("turn.completed",{...c}).catch(()=>{}):g?.type==="error"&&this.hooks?.invoke("turn.failed",{...c,code:g.code,error:g.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...c,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let f=m instanceof Error?m.message:String(m),g=typeof m?.status=="number"?m.status:void 0,y=Bt(g,f);this.log.error(`turn ${n} error [${y}, retryable=${Wr(y)}]: ${f}`),this.hooks?.invoke("turn.failed",{...c,code:y,error:f}).catch(()=>{}),yield{type:"error",turnId:n,error:f,code:y}}}}}});_o();function qf(r){let e={verbose:!1};for(let t of r.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{createInterface as Xf}from"node:readline";var hn=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)}
30
30
  `)}start(){process.stdin.on("data",t=>{process.stderr.write(`[transport] raw stdin data (${t.length} bytes): ${t.toString().slice(0,300)}
31
- `)});let e=Uf({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let n=t.trim();if(n){process.stderr.write(`[transport] line: ${n.slice(0,300)}
31
+ `)});let e=Xf({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let n=t.trim();if(n){process.stderr.write(`[transport] line: ${n.slice(0,300)}
32
32
  `);try{let o=JSON.parse(n);this.messageHandler?.(o)}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}
33
- `)}};import{randomUUID as pe}from"node:crypto";wo();Fs();var Ue=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 o=Date.now(),s=`${this.baseUrl}/v3/images/generations`,i={model:e.model,prompt:e.prompt,size:e.size??"2K",n:e.n??1,response_format:"url",sequential_image_generation:"disabled",watermark:!0};e.imageUrl&&(i.image=e.imageUrl),e.referenceImages&&e.referenceImages.length>0&&(i.image_urls=e.referenceImages),e.style&&(i.style=e.style),e.quality&&(i.quality=e.quality),e.seed!==void 0&&(i.seed=e.seed),e.guidanceScale!==void 0&&(i.guidance_scale=e.guidanceScale),e.enhancePrompt!==void 0&&(i.enhance_prompt=e.enhancePrompt),e.streamImage&&(i.stream=!0);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 l=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${l}`)}return e.streamImage&&a.body?this.parseStreamingImage(a.body,e,o):{mediaUrls:((await a.json()).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-o}}async parseStreamingImage(e,t,n){let o=new TextDecoder,s="",i="",a=e.getReader();try{for(;;){let{done:c,value:d}=await a.read();if(c)break;s+=o.decode(d,{stream:!0});let l;for(;(l=s.indexOf(`
34
- `))!==-1;){let u=s.slice(0,l).trim();if(s=s.slice(l+1),!u||u.startsWith(":")||!u.startsWith("data:"))continue;let p=u.slice(5).trim();if(p==="[DONE]")break;try{let f=JSON.parse(p).data?.[0]?.url;f&&(i=f,t.onProgress?.(50,"streaming"))}catch{}}}}finally{a.releaseLock()}return t.onProgress?.(100,"completed"),{mediaUrls:i?[i]:[],model:t.model,size:t.size??"1024x1024",durationMs:Date.now()-n}}async generateVideo(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=e.referenceVideos?.length??0,a=e.referenceAudios?.length??0,c=e.referenceImages?.length??0,d=!!(e.imageUrl||c>0);if(i>3)throw new Error(`Seedance 2.0: max 3 reference videos (got ${i}). Total duration must be \u226415s.`);if(a>3)throw new Error(`Seedance 2.0: max 3 reference audios (got ${a}). Total duration must be \u226415s.`);if(a>0&&!d&&i===0)throw new Error("Seedance 2.0: reference audio cannot be used alone. Provide at least one reference image or video.");if(e.operation==="edit"&&c>9)throw new Error(`Seedance 2.0 video edit: max 9 reference images (got ${c}).`);let l=[];switch(e.draftTaskId&&l.push({type:"draft_task",id:e.draftTaskId}),e.operation){case"multimodal_reference":{if(e.prompt&&l.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let k=0;k<e.referenceImages.length;k++){let b=e.imageRoles?.[k]??"reference_image";l.push({type:"image_url",image_url:{url:e.referenceImages[k]},role:b})}if(e.referenceVideos?.length)for(let k of e.referenceVideos)l.push({type:"video_url",video_url:{url:k},role:"reference_video"});if(e.referenceAudios?.length)for(let k of e.referenceAudios)l.push({type:"audio_url",audio_url:{url:k},role:"reference_audio"});break}case"extend":{if(e.sourceVideos?.length)for(let k of e.sourceVideos)l.push({type:"video_url",video_url:{url:k},role:"reference_video"});e.prompt&&l.push({type:"text",text:e.prompt});break}case"merge":for(let k of e.sourceVideos??[])l.push({type:"video_url",video_url:{url:k}});e.prompt&&l.push({type:"text",text:e.prompt});break;case"upscale":e.sourceVideos?.[0]&&l.push({type:"video_url",video_url:{url:e.sourceVideos[0]}}),l.push({type:"text",text:e.prompt||"upscale"});break;case"edit":for(let k of e.sourceVideos??[])l.push({type:"video_url",video_url:{url:k},role:"reference_video"});if(e.referenceImages?.length)for(let k of e.referenceImages)l.push({type:"image_url",image_url:{url:k},role:"reference_image"});e.prompt&&l.push({type:"text",text:e.prompt});break;default:{let k=(e.referenceVideos?.length??0)>0,b=(e.referenceAudios?.length??0)>0,x=(e.imageRoles?.length??0)>0;if(k||b||x){if(e.prompt&&l.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let S=0;S<e.referenceImages.length;S++){let A=e.imageRoles?.[S]??"reference_image";l.push({type:"image_url",image_url:{url:e.referenceImages[S]},role:A})}if(k)for(let S of e.referenceVideos)l.push({type:"video_url",video_url:{url:S},role:"reference_video"});if(b)for(let S of e.referenceAudios)l.push({type:"audio_url",audio_url:{url:S},role:"reference_audio"})}else if(e.referenceImages?.length){for(let S of e.referenceImages)l.push({type:"image_url",image_url:{url:S}});e.prompt&&l.push({type:"text",text:e.prompt})}else e.imageUrl?(l.push({type:"image_url",image_url:{url:e.imageUrl}}),e.prompt&&l.push({type:"text",text:e.prompt})):e.prompt&&l.push({type:"text",text:e.prompt});break}}let u={model:e.model,content:l};e.duration&&(u.duration=e.duration),e.aspectRatio&&(u.ratio=e.aspectRatio),e.resolution&&(u.resolution=e.resolution),e.seed!==void 0&&(u.seed=e.seed),e.fps&&(u.fps=e.fps),e.generateAudio!==void 0&&(u.generate_audio=e.generateAudio),e.watermark!==void 0&&(u.watermark=e.watermark),e.enhancePrompt!==void 0&&(u.enhance_prompt=e.enhancePrompt),e.cameraFixed!==void 0&&(u.camera_fixed=e.cameraFixed),e.returnLastFrame!==void 0&&(u.return_last_frame=e.returnLastFrame),e.serviceTier&&(u.service_tier=e.serviceTier),e.executionExpiresAfterSeconds!==void 0&&(u.execution_expires_after=e.executionExpiresAfterSeconds),e.draft!==void 0&&(u.draft=e.draft),e.safetyIdentifier&&(u.safety_identifier=e.safetyIdentifier),e.callbackUrl&&(u.callback_url=e.callbackUrl),e.videoTools?.length&&(u.tools=e.videoTools.map(k=>({type:k})));let p=await this.submitTask(s,u,t,n),g=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${p}`,t,n,e.onProgress,p),f=[],m=g.content;typeof m?.video_url=="string"&&f.push(m.video_url);let y=typeof m?.last_frame_url=="string"?m.last_frame_url:void 0;return{mediaUrls:f,model:e.model,durationMs:Date.now()-o,lastFrameUrl:y,taskId:p}}async generate3D(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=[],a=[];e.outputFormat&&a.push(`--fileformat ${e.outputFormat}`),e.prompt&&a.push(e.prompt),a.length>0&&i.push({type:"text",text:a.join(" ")}),e.imageUrl&&i.push({type:"image_url",image_url:{url:e.imageUrl}});let c={model:e.model,content:i},d=await this.submitTask(s,c,t,n),l=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${d}`,t,n,e.onProgress,d),u=[],p=l.content;if(typeof p?.video_url=="string"&&u.push(p.video_url),u.length===0&&p)for(let[,f]of Object.entries(p))typeof f=="string"&&/^https?:\/\//.test(f)&&u.push(f);let g=l.output;if(g?.model_urls){let f=g.model_urls;for(let m of Object.values(f))m&&!u.includes(m)&&u.push(m)}if(u.length===0){let f=Object.keys(l),m=p?Object.keys(p):[],y=g?Object.keys(g):[];console.error(`[volcengine-3d] No media URLs found. Response keys: [${f}], content keys: [${m}], output keys: [${y}]`);let k=l.data;if(k?.content){let b=k.content;for(let[,x]of Object.entries(b))typeof x=="string"&&/^https?:\/\//.test(x)&&u.push(x)}}return{mediaUrls:u,model:e.model,durationMs:Date.now()-o,metadata:u.length===0?{debugResponseKeys:Object.keys(l),debugContentKeys:p?Object.keys(p):null,debugContentSample:p?JSON.stringify(p).slice(0,500):null,debugOutputKeys:g?Object.keys(g):null,debugResultSample:JSON.stringify(l).slice(0,800)}:void 0}}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/v3/contents/generations/tasks/${e}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Volcengine task status error ${s.status}: ${c}`)}let i=await s.json();return{status:i.status??"unknown",task:i}}async listVideoTasks(e,t,n){let o=new URLSearchParams;t?.after&&o.set("after",t.after),t?.limit&&o.set("limit",String(t.limit)),t?.status&&o.set("status",t.status);let s=o.toString(),i=`${this.baseUrl}/v3/contents/generations/tasks${s?`?${s}`:""}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Volcengine list tasks error ${a.status}: ${c}`)}return await a.json()}async deleteVideoTask(e,t,n){let o=`${this.baseUrl}/v3/contents/generations/tasks/${e}`,s=await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Volcengine delete task error ${s.status}: ${i}`)}}async uploadFile(e,t,n,o){let s=`${this.baseUrl}/v3/files`,i=new FormData;i.append("file",e instanceof Blob?e:new Blob([e]),n?.filename??"upload"),i.append("purpose",n?.purpose??"user_data");let a=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:i,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Volcengine file upload error ${a.status}: ${d}`)}let c=await a.json();return{id:String(c.id??""),status:String(c.status??"")}}async getFile(e,t,n){let o=`${this.baseUrl}/v3/files/${e}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Volcengine get file error ${s.status}: ${i}`)}return await s.json()}async listFiles(e,t,n){let o=new URLSearchParams;t?.after&&o.set("after",t.after),t?.limit&&o.set("limit",String(t.limit)),t?.purpose&&o.set("purpose",t.purpose),t?.order&&o.set("order",t.order);let s=o.toString(),i=`${this.baseUrl}/v3/files${s?`?${s}`:""}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Volcengine list files error ${a.status}: ${c}`)}return await a.json()}async deleteFile(e,t,n){let o=`${this.baseUrl}/v3/files/${e}`,s=await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Volcengine delete file error ${s.status}: ${i}`)}}async submitTask(e,t,n,o){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${c}`)}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,o,s){let i=Date.now()+6e5,a=0;for(;Date.now()<i;){n?.throwIfAborted();let c=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`Volcengine task poll error ${c.status}: ${g}`)}let d=await c.json(),l=d.status;if(l==="succeeded"||l==="complete")return o?.(100,"completed",s),d;if(l==="failed"||l==="cancelled"){let g=d.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${g}`)}a++;let u=Date.now()-(i-6e5),p=Math.min(95,Math.round(u/6e5*100));o?.(p,l??"running",s),await new Promise(g=>setTimeout(g,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as Bf,mkdirSync as Gf}from"node:fs";import{join as tc}from"node:path";import{randomUUID as Hf}from"node:crypto";import{homedir as Nf}from"node:os";import{join as te}from"node:path";import{existsSync as Ul,readdirSync as jf,readFileSync as Ff}from"node:fs";var we=".qlogicagent";function J(){return process.env.QLOGICAGENT_HOME||te(Nf(),we)}function vo(){return te(J(),"sessions")}function Nl(r){return te(vo(),r)}function jl(){return te(J(),"plugins")}function Qe(){return te(J(),"skills")}function ut(){return te(J(),"settings.json")}function Ne(){return te(J(),"cache")}function Fl(){return te(J(),"debug-logs")}function Bl(r){let e=te(J(),"checkpoints");return r?te(e,r):e}function Gl(){return te(J(),"plugin-cache")}function Hl(){return te(J(),"mcp.json")}function Wl(){return te(J(),"marketplace.json")}function zl(){return te(J(),"workflows")}function Vl(){return te(J(),"rules")}function je(r){return te(r??process.cwd(),we)}function ql(r){return te(je(r),"workflows")}function Ze(r){return te(je(r),"skills")}function Kl(r){return te(je(r),"INSTRUCTIONS.md")}function Jl(r){return te(je(r),"instructions")}function Xl(r){return te(je(r),"plans")}function Yl(r){return te(je(r),"rules")}function Ql(r){return te(je(r),"sessions")}function Zl(r){return te(r,we,"hooks")}function ec(r){let e=vo();if(!Ul(e))return[];let t=new Set;try{let n=jf(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=te(e,o.name,"state.json");try{let i=Ff(s,"utf8"),c=JSON.parse(i).metadata?.cwd;c&&c!==r&&Ul(te(c,we,"skills"))&&t.add(c)}catch{}}}catch{}return[...t]}var Wf=18e4,mn=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Wf}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 o=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"};e.quality&&(i.quality=e.quality),e.style&&(i.style=e.style),e.background&&(i.background=e.background);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 l=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${l}`)}return{mediaUrls:((await a.json()).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-o}}async generateTTS(e,t,n){let o=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:e.voice??"alloy",response_format:e.audioFormat??"mp3"};e.speed!==void 0&&(a.speed=e.speed);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${c.status}: ${g}`)}let d=Buffer.from(await c.arrayBuffer()),l=tc(Ne(),"tts");Gf(l,{recursive:!0});let u=`openai-tts-${Hf()}.mp3`,p=tc(l,u);return Bf(p,d),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-o,billingUnit:"per_character",billingQuantity:s.length}}};var Rt=class{supportedTypes=["music","video"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??6e4}async generate(e,t,n){switch(e.mediaType){case"music":return this.generateMusic(e,t,n);case"video":return this.generateVideo(e,t,n);default:throw new Error(`MiniMaxMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateMusic(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v1/music_generation`,i={model:e.model,prompt:e.prompt,output_format:"url"};e.lyrics&&(i.lyrics=e.lyrics),e.duration&&(i.duration=e.duration),(e.isInstrumental||!e.lyrics)&&(i.is_instrumental=!0),e.audioUrl&&(i.audio_url=e.audioUrl),e.lyricsOptimizer&&(i.lyrics_optimizer=!0),(e.audioFormat||e.voice)&&(i.audio_setting={sample_rate:44100,bitrate:256e3,format:e.audioFormat??"mp3"});let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(6e5)});if(!a.ok){let g=await a.text().catch(()=>"");throw new Error(`MiniMax music error ${a.status}: ${g}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax music rejected: ${c.base_resp.status_msg??"unknown"}`);let d=c.data?.audio??c.audio_file;if(d)return{mediaUrls:[d],model:e.model,durationMs:Date.now()-o};let l=c.task_id;if(!l)throw new Error("MiniMax music: no audio_file or task_id in response");let u=`${this.baseUrl}/v1/music_generation/${l}`;return{mediaUrls:(await this.pollTask(u,t,n,e.onProgress,l)).audioUrls,model:e.model,durationMs:Date.now()-o}}async pollTask(e,t,n,o,s){let i=Date.now()+6e5;for(;Date.now()<i;){n?.throwIfAborted();let a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`MiniMax music poll error ${a.status}: ${u}`)}let c=await a.json(),d=c.status;if(d==="Success"||d==="Finished"){o?.(100,"completed",s);let u=[];return c.audio_file&&u.push(c.audio_file),{audioUrls:u}}if(d==="Failed"||d==="Cancelled")throw new Error(`MiniMax music task failed: ${c.base_resp?.status_msg??"unknown"}`);let l=Date.now()-(i-6e5);o?.(Math.min(95,Math.round(l/6e5*100)),d??"running",s),await new Promise(u=>setTimeout(u,3e3))}throw new Error("MiniMax music task timed out after polling")}async generateLyrics(e,t,n){let o=`${this.baseUrl}/v1/lyrics_generation`,s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({prompt:e}),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`MiniMax lyrics API error ${s.status}: ${a}`)}let i=await s.json();if(i.base_resp?.status_code&&i.base_resp.status_code!==0)throw new Error(`MiniMax lyrics error: ${i.base_resp.status_msg??"unknown"}`);return i.data?.lyrics??""}async generateVideo(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v1/video_generation`,i={model:e.model||"S2V-01",prompt:e.prompt};if(e.referenceImages?.length&&e.imageRoles){let u=e.imageRoles.includes("first_frame"),p=e.imageRoles.includes("last_frame");if(u&&p){let g=e.imageRoles.indexOf("first_frame"),f=e.imageRoles.indexOf("last_frame");i.first_frame_image=e.referenceImages[g],i.last_frame_image=e.referenceImages[f]}else if(u){let g=e.imageRoles.indexOf("first_frame");i.first_frame_image=e.referenceImages[g]}else i.subject_reference=e.referenceImages.map((g,f)=>({type:"character",image:g}))}else e.imageUrl&&(i.first_frame_image=e.imageUrl);e.callbackUrl&&(i.callback_url=e.callbackUrl);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(`MiniMax video submit error ${a.status}: ${u}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax video rejected: ${c.base_resp.status_msg??"unknown"}`);let d=c.task_id;if(!d)throw new Error("MiniMax video: no task_id in response");let l=await this.pollVideoTask(d,t,n,e.onProgress);return{mediaUrls:l.downloadUrl?[l.downloadUrl]:[],model:e.model||"S2V-01",durationMs:Date.now()-o,taskId:d,metadata:{fileId:l.fileId,width:l.width,height:l.height}}}async pollVideoTask(e,t,n,o){let s=Date.now()+6e5;for(;Date.now()<s;){n?.throwIfAborted();let i=`${this.baseUrl}/v1/query/video_generation?task_id=${encodeURIComponent(e)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let g=await a.text().catch(()=>"");throw new Error(`MiniMax video poll error ${a.status}: ${g}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax video task error ${c.base_resp.status_code}: ${c.base_resp.status_msg??""}`);let d=c.status;if(d==="Success"){o?.(100,"completed",e);let g;if(c.file_id)try{g=await this.getFileDownloadUrl(c.file_id,t,n)}catch{}return{fileId:c.file_id,downloadUrl:g,width:c.video_width,height:c.video_height}}if(d==="Fail")throw new Error(`MiniMax video task failed: ${c.base_resp?.status_msg??"unknown"}`);let l=d??"running",u=Date.now()-(s-6e5),p=Math.min(95,Math.round(u/6e5*100));o?.(p,l,e),await new Promise(g=>setTimeout(g,3e3))}throw new Error("MiniMax video task timed out after polling")}async getFileDownloadUrl(e,t,n){let o=`${this.baseUrl}/v1/files/retrieve?file_id=${encodeURIComponent(e)}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`MiniMax file retrieve error ${s.status}: ${c}`)}let a=(await s.json()).file?.download_url;if(!a)throw new Error("MiniMax file retrieve: no download_url in response");return a}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/v1/query/video_generation?task_id=${encodeURIComponent(e)}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`MiniMax task status error ${s.status}: ${d}`)}let i=await s.json(),a=i.status??"unknown";return{status:a==="Success"?"succeeded":a==="Fail"?"failed":a.toLowerCase(),task:i}}async listVideoTasks(e,t,n){return{data:[]}}async deleteVideoTask(e,t,n){throw new Error("MiniMax does not support video task cancellation.")}};import{writeFileSync as oc,mkdirSync as rc}from"node:fs";import{join as xo}from"node:path";import{randomUUID as sc}from"node:crypto";import{writeFileSync as zf,mkdirSync as Vf}from"node:fs";import{join as nc}from"node:path";import{randomUUID as qf}from"node:crypto";var So=class{ws=null;wsUrl;model="models/lyria-realtime-exp";onAudioChunk=null;onFilteredPrompt=null;onError=null;onClose=null;constructor(e){let t=e.baseUrl.replace(/\/+$/,""),n=new URL(t).origin.replace(/^http/,"ws");this.wsUrl=`${n}/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent`}async connect(e,t){t.model&&(this.model=t.model.startsWith("models/")?t.model:`models/${t.model}`);let n=`${this.wsUrl}?key=${encodeURIComponent(e)}`,o=new WebSocket(n);this.ws=o,await new Promise((s,i)=>{let a=()=>{o.removeEventListener("error",c),s()},c=()=>{o.removeEventListener("open",a),i(new Error("Lyria RealTime WebSocket connection failed"))};o.addEventListener("open",a,{once:!0}),o.addEventListener("error",c,{once:!0})}),o.addEventListener("message",s=>this.handleMessage(s)),o.addEventListener("error",()=>{this.onError?.(new Error("Lyria RealTime WebSocket error"))}),o.addEventListener("close",()=>{this.ws=null,this.onClose?.()}),this.send({setup:{model:this.model}}),await new Promise(s=>setTimeout(s,100)),await this.setWeightedPrompts(t.prompts),t.config&&await this.setMusicGenerationConfig(t.config)}async setWeightedPrompts(e){this.send({musicInput:{weightedPrompts:e.map(t=>({text:t.text,weight:t.weight}))}})}async setMusicGenerationConfig(e){let t={};e.bpm!==void 0&&(t.bpm=e.bpm),e.density!==void 0&&(t.density=e.density),e.brightness!==void 0&&(t.brightness=e.brightness),e.guidance!==void 0&&(t.guidance=e.guidance),e.scale!==void 0&&(t.scale=e.scale),e.temperature!==void 0&&(t.temperature=e.temperature),e.topK!==void 0&&(t.top_k=e.topK),e.seed!==void 0&&(t.seed=e.seed),e.muteBass!==void 0&&(t.mute_bass=e.muteBass),e.muteDrums!==void 0&&(t.mute_drums=e.muteDrums),e.onlyBassAndDrums!==void 0&&(t.only_bass_and_drums=e.onlyBassAndDrums),e.musicGenerationMode!==void 0&&(t.music_generation_mode=e.musicGenerationMode),e.audioFormat!==void 0&&(t.audio_format=e.audioFormat),e.sampleRateHz!==void 0&&(t.sample_rate_hz=e.sampleRateHz),this.send({musicInput:{musicGenerationConfig:t}})}async play(){this.send({musicInput:{playbackControl:"PLAY"}})}async pause(){this.send({musicInput:{playbackControl:"PAUSE"}})}async stop(){this.send({musicInput:{playbackControl:"STOP"}})}async resetContext(){this.send({musicInput:{playbackControl:"RESET_CONTEXT"}})}close(){this.ws&&this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=null}get connected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Lyria RealTime session not connected");this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(typeof e.data=="string"?e.data:e.data.toString())}catch{return}let n=t.serverContent;if(!n)return;let o=n.audioChunks;if(o&&this.onAudioChunk)for(let i of o)i.data&&this.onAudioChunk({data:Buffer.from(i.data,"base64")});let s=n.filteredPrompt;s&&this.onFilteredPrompt?.(s)}};async function Xs(r,e,t){let n=t.durationSeconds??30,o=Date.now(),s=new So(e),i=[];s.onAudioChunk=c=>{i.push(c.data)};let a=null;s.onError=c=>{a=c};try{await s.connect(r,{model:t.model??"lyria-realtime-exp",prompts:t.prompts,config:t.musicConfig}),t.onProgress?.(5,"connected"),await s.play(),t.onProgress?.(10,"streaming");let c=Date.now()+n*1e3,d=500;for(;Date.now()<c;){if(t.signal?.throwIfAborted(),a)throw a;if(!s.connected)break;let m=Date.now()-o,y=n*1e3,k=Math.min(95,Math.round(10+m/y*85));t.onProgress?.(k,"streaming"),await new Promise(b=>setTimeout(b,d))}s.connected&&await s.stop(),t.onProgress?.(98,"assembling");let l=Buffer.concat(i),u=Kf(l,48e3,2,16),p=nc(Ne(),"gemini-music-realtime");Vf(p,{recursive:!0});let g=`lyria-rt-${qf()}.wav`,f=nc(p,g);return zf(f,u),t.onProgress?.(100,"completed"),{filePath:`file://${f}`,durationMs:Date.now()-o}}finally{s.close()}}function Kf(r,e,t,n){let o=e*t*(n/8),s=t*(n/8),i=r.length,a=Buffer.alloc(44);return a.write("RIFF",0),a.writeUInt32LE(36+i,4),a.write("WAVE",8),a.write("fmt ",12),a.writeUInt32LE(16,16),a.writeUInt16LE(1,20),a.writeUInt16LE(t,22),a.writeUInt32LE(e,24),a.writeUInt32LE(o,28),a.writeUInt16LE(s,30),a.writeUInt16LE(n,32),a.write("data",36),a.writeUInt32LE(i,40),Buffer.concat([a,r])}var Jf=18e4,Xf=1e4,Ys=6e5,gn=class{supportedTypes=["image","video","music","music_realtime","tts","embedding"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Jf}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"music":return this.generateMusic(e,t,n);case"music_realtime":return this.generateMusicRealtime(e,t,n);case"tts":return this.generateTTS(e,t,n);case"embedding":return this.generateEmbedding(e,t,n);default:throw new Error(`GeminiMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async deleteVideoTask(e,t,n){throw new Error("Gemini does not support deleting video generation tasks")}async listVideoTasks(e,t,n){return{data:[]}}async getTaskStatus(e,t,n){let o=`${this.apiBase}/${e}`,s=await fetch(o,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Gemini operation query error ${s.status}: ${c}`)}let i=await s.json();return{status:i.done?"completed":"running",task:i}}async generateImage(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={responseModalities:["TEXT","IMAGE"]};e.aspectRatio&&(i.aspectRatio=e.aspectRatio);let a={contents:[{parts:[{text:e.prompt}]}],generationConfig:i},c=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineImages(c),model:e.model,durationMs:Date.now()-o}}async generateVideo(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:predictLongRunning`,i={prompt:e.prompt};e.imageUrl&&(i.image={inlineData:await this.resolveImageData(e.imageUrl)}),e.referenceImages?.length&&(i.referenceImages=await Promise.all(e.referenceImages.map(async y=>({image:{inlineData:await this.resolveImageData(y)},referenceType:"asset"}))));let a={};e.aspectRatio&&(a.aspectRatio=e.aspectRatio),e.resolution&&(a.resolution=e.resolution),e.duration&&(a.durationSeconds=String(e.duration)),e.n&&(a.numberOfVideos=e.n),e.seed!==void 0&&(a.seed=e.seed);let c={instances:[i]};Object.keys(a).length>0&&(c.parameters=a);let l=(await this.postJson(s,c,t,n)).name;if(!l)throw new Error("Gemini video submit: no operation name in response");let u=l;e.onProgress?.(5,"submitted",u);let f=(await this.pollOperation(l,t,n,e.onProgress,u)).response?.generateVideoResponse?.generatedSamples??[],m=[];for(let y of f)y.video?.uri&&m.push(y.video.uri);return{mediaUrls:m,model:e.model,durationMs:Date.now()-o,taskId:u}}async generateMusic(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i=[{text:e.prompt}],a={};e.audioFormat==="wav"&&(a.responseModalities=["AUDIO","TEXT"],a.responseFormat={audio:{mimeType:"audio/wav"}});let c={contents:[{parts:i}]};Object.keys(a).length>0&&(c.generationConfig=a);let d=await this.postJson(s,c,t,n);return{mediaUrls:this.extractInlineAudio(d,"gemini-music"),model:e.model,durationMs:Date.now()-o}}async generateMusicRealtime(e,t,n){let o=await Xs(t,{baseUrl:this.apiBase},{prompts:[{text:e.prompt,weight:1}],durationSeconds:e.duration??30,musicConfig:{audioFormat:e.audioFormat==="wav"?"pcm16":void 0,sampleRateHz:48e3},model:e.model,signal:n,onProgress:e.onProgress});return{mediaUrls:[o.filePath],model:e.model,durationMs:o.durationMs}}async generateTTS(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={responseModalities:["AUDIO"]};e.voice&&(i.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}});let a={contents:[{parts:[{text:e.text??e.prompt}]}],generationConfig:i},c=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineAudio(c,"gemini-tts"),model:e.model,durationMs:Date.now()-o}}async generateEmbedding(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:embedContent`,i={content:{parts:[{text:e.text??e.prompt}]}},a=e.metadata?.outputDimensionality;a!==void 0&&(i.output_dimensionality=a);let d=(await this.postJson(s,i,t,n)).embeddings?.[0]?.values??[];return{mediaUrls:[],model:e.model,durationMs:Date.now()-o,metadata:{embedding:d,dimensions:d.length}}}async postJson(e,t,n,o){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":n},body:JSON.stringify(t),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini API error ${s.status}: ${i}`)}return s.json()}async pollOperation(e,t,n,o,s){let i=Date.now()+Ys;for(;Date.now()<i;){n?.throwIfAborted();let a=`${this.apiBase}/${e}`,c=await fetch(a,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`Gemini operation poll error ${c.status}: ${p}`)}let d=await c.json();if(d.done===!0)return o?.(100,"completed",s),d;if(d.error){let p=d.error;throw new Error(`Gemini video generation failed: ${p.message??JSON.stringify(p)}`)}let l=Date.now()-(i-Ys),u=Math.min(95,Math.round(l/Ys*100));o?.(u,"running",s),await new Promise(p=>setTimeout(p,Xf))}throw new Error("Gemini video generation timed out after polling")}async resolveImageData(e){if(e.startsWith("data:")){let s=e.match(/^data:([^;]+);base64,(.+)$/);if(s)return{mimeType:s[1],data:s[2]}}if(e.startsWith("file://")){let{readFileSync:s}=await import("node:fs"),i=e.replace(/^file:\/\//,""),a=s(i).toString("base64"),c=i.split(".").pop()?.toLowerCase()??"png";return{mimeType:c==="jpg"||c==="jpeg"?"image/jpeg":c==="webp"?"image/webp":"image/png",data:a}}let t=await fetch(e,{signal:AbortSignal.timeout(6e4)});if(!t.ok)throw new Error(`Failed to fetch image ${e}: ${t.status}`);let n=Buffer.from(await t.arrayBuffer());return{mimeType:t.headers.get("content-type")??"image/png",data:n.toString("base64")}}extractInlineImages(e){let t=[],n=xo(Ne(),"gemini-images");rc(n,{recursive:!0});for(let o of e.candidates??[])for(let s of o.content?.parts??[])if(s.inlineData?.data){let i=s.inlineData.mimeType==="image/png"?"png":s.inlineData.mimeType==="image/webp"?"webp":"jpg",a=`gemini-${sc()}.${i}`,c=xo(n,a);oc(c,Buffer.from(s.inlineData.data,"base64")),t.push(`file://${c}`)}return t}extractInlineAudio(e,t){let n=[],o=xo(Ne(),t);rc(o,{recursive:!0});for(let s of e.candidates??[])for(let i of s.content?.parts??[])if(i.inlineData?.data&&i.inlineData.mimeType?.startsWith("audio/")){let a=i.inlineData.mimeType.includes("wav")?"wav":i.inlineData.mimeType.includes("mpeg")||i.inlineData.mimeType.includes("mp3")?"mp3":"pcm",c=Buffer.from(i.inlineData.data,"base64"),d=a==="pcm"?Yf(c,24e3,1,16):c,l=`gemini-${sc()}.${a==="pcm"?"wav":a}`,u=xo(o,l);oc(u,d),n.push(`file://${u}`)}return n}};function Yf(r,e,t,n){let o=e*t*(n/8),s=t*(n/8),i=r.length,a=Buffer.alloc(44);return a.write("RIFF",0),a.writeUInt32LE(36+i,4),a.write("WAVE",8),a.write("fmt ",12),a.writeUInt32LE(16,16),a.writeUInt16LE(1,20),a.writeUInt16LE(t,22),a.writeUInt32LE(e,24),a.writeUInt32LE(o,28),a.writeUInt16LE(s,30),a.writeUInt16LE(n,32),a.write("data",36),a.writeUInt32LE(i,40),Buffer.concat([a,r])}var Ro=class{supportedTypes=["tts","video"];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==="video")return this.generateVideo(e,t,n);if(e.mediaType!=="tts")throw new Error(`QwenMediaTransport: unsupported mediaType "${e.mediaType}"`);let o=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={format:e.audioFormat??"mp3",sample_rate:24e3},c={text:s};e.voice&&(c.voice=e.voice),e.speed!==void 0&&(a.speech_rate=e.speed);let d={model:e.model||"qwen3-tts-voicedesign",input:c,parameters:a},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(d),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let f=await l.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${l.status}: ${f}`)}let u=await l.json();if(u.code)throw new Error(`DashScope TTS submit rejected: ${u.code} \u2014 ${u.message??""}`);let p=u.output?.task_id;if(!p)throw new Error("DashScope TTS submit: no task_id in response");if(u.output?.task_status==="SUCCEEDED"){let f=this.extractMediaUrl(u);return{mediaUrls:f?[f]:[],model:e.model,durationMs:Date.now()-o}}return{mediaUrls:await this.pollTask(p,t,n,e.onProgress),model:e.model,durationMs:Date.now()-o}}async pollTask(e,t,n,o,s=12e4){let i=Date.now()+s,a=`${this.baseUrl}/api/v1/tasks/${e}`;for(;Date.now()<i;){n?.throwIfAborted(),await Qf(2e3);let c=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${c.status}: ${p}`)}let d=await c.json();if(d.code)throw new Error(`DashScope poll rejected: ${d.code} \u2014 ${d.message??""}`);let l=d.output?.task_status;if(l==="SUCCEEDED"){o?.(100,"completed",e);let p=this.extractMediaUrl(d);return p?[p]:[]}if(l==="FAILED")throw new Error(`DashScope task failed: ${d.message??"unknown error"}`);let u=Date.now()-(i-s);o?.(Math.min(95,Math.round(u/s*100)),l??"running",e)}throw new Error("DashScope task timed out")}async generateVideo(e,t,n){let o=Date.now(),s=e.model||"wan2.1-t2v-turbo",i={prompt:e.prompt};if(e.imageUrl)i.img_url=e.imageUrl;else if(e.referenceImages?.length)if(e.imageRoles){let f=e.imageRoles.indexOf("first_frame"),m=e.imageRoles.indexOf("last_frame");f>=0&&(i.img_url=e.referenceImages[f]),m>=0&&(i.tail_image_url=e.referenceImages[m]);let y=e.imageRoles.map((k,b)=>k==="reference_image"?b:-1).filter(k=>k>=0);y.length>0&&(i.ref_image_url=e.referenceImages[y[0]])}else i.img_url=e.referenceImages[0];let a={};e.duration&&(a.duration=e.duration),e.resolution&&(a.resolution=e.resolution),e.aspectRatio&&(a.ratio=e.aspectRatio),e.metadata?.size&&(a.size=e.metadata.size);let c=`${this.baseUrl}/api/v1/services/aigc/generation/generation`,d={model:s,input:i};Object.keys(a).length>0&&(d.parameters=a);let l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(d),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let f=await l.text().catch(()=>"");throw new Error(`DashScope video submit error ${l.status}: ${f}`)}let u=await l.json();if(u.code)throw new Error(`DashScope video submit rejected: ${u.code} \u2014 ${u.message??""}`);let p=u.output?.task_id;if(!p)throw new Error("DashScope video submit: no task_id in response");return{mediaUrls:await this.pollTask(p,t,n,e.onProgress,6e5),model:s,durationMs:Date.now()-o,taskId:p}}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/api/v1/tasks/${e}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`DashScope task status error ${s.status}: ${l}`)}let i=await s.json(),c=i.output?.task_status??"unknown";return{status:c==="SUCCEEDED"?"succeeded":c==="FAILED"?"failed":c.toLowerCase(),task:i}}async listVideoTasks(e,t,n){let o=new URLSearchParams;o.set("page_size",String(t?.limit??20)),t?.status&&o.set("status",t.status.toUpperCase());let s=`${this.baseUrl}/api/v1/tasks?${o.toString()}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n??AbortSignal.timeout(this.timeoutMs)});return i.ok?await i.json():{data:[]}}async deleteVideoTask(e,t,n){throw new Error("DashScope does not support task cancellation.")}extractMediaUrl(e){if(e.output?.video_url)return e.output.video_url;if(e.output?.audio_url)return e.output.audio_url;if(e.output?.results?.[0]?.url)return e.output.results[0].url}};function Qf(r){return new Promise(e=>setTimeout(e,r))}import{writeFileSync as Zf,mkdirSync as eh}from"node:fs";import{join as ic}from"node:path";import{randomUUID as th}from"node:crypto";var nh=18e4,oh=3e3,_o=6e5,rh=new Set(["glm-image"]),fn=class{supportedTypes=["image","video","tts","stt","embedding","voice_clone","document_parsing","rerank"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??nh}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"tts":return this.generateTTS(e,t,n);case"stt":return this.generateSTT(e,t,n);case"embedding":return this.generateEmbedding(e,t,n);case"voice_clone":return this.generateVoiceClone(e,t,n);case"document_parsing":return this.generateDocumentParsing(e,t,n);case"rerank":return this.generateRerank(e,t,n);default:throw new Error(`ZhipuMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateImage(e,t,n){return rh.has(e.model)?this.generateImageAsync(e,t,n):this.generateImageSync(e,t,n)}async generateImageSync(e,t,n){let o=Date.now(),s=`${this.baseUrl}/images/generations`,i={model:e.model,prompt:e.prompt};return e.size&&(i.size=e.size),e.quality&&e.model.startsWith("cogview-4")&&(i.quality=e.quality),{mediaUrls:((await this.postJSON(s,i,t,n)).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size,durationMs:Date.now()-o}}async generateImageAsync(e,t,n){let o=Date.now(),s=`${this.baseUrl}/async/images/generations`,i={model:e.model,prompt:e.prompt};e.size&&(i.size=e.size),e.quality&&(i.quality=e.quality);let c=(await this.postJSON(s,i,t,n)).id;if(!c)throw new Error("Zhipu async image: no task id in response");return{mediaUrls:((await this.pollAsyncResult(c,t,n,e.onProgress)).data??[]).map(p=>p.url).filter(p=>!!p),model:e.model,size:e.size,durationMs:Date.now()-o}}async generateVideo(e,t,n){let o=Date.now(),s=`${this.baseUrl}/videos/generations`,i={model:e.model,prompt:e.prompt};e.imageUrl&&(i.image_url=e.imageUrl),e.size&&(i.size=e.size),e.duration&&(i.duration=e.duration);let c=(await this.postJSON(s,i,t,n)).id;if(!c)throw new Error("Zhipu video generation: no task id in response");return{mediaUrls:((await this.pollAsyncResult(c,t,n,e.onProgress)).video_result??[]).map(p=>p.url).filter(p=>!!p),model:e.model,durationMs:Date.now()-o}}async generateTTS(e,t,n){let o=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: text or prompt required for TTS");let i=`${this.baseUrl}/audio/speech`,a={model:e.model||"glm-tts",input:s};e.voice&&(a.voice=e.voice),e.speed!==void 0&&(a.speed=e.speed),e.audioFormat&&(a.response_format=e.audioFormat);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let f=await c.text().catch(()=>"");throw new Error(`Zhipu TTS API error ${c.status}: ${f}`)}let d=Buffer.from(await c.arrayBuffer()),l=ic(Ne(),"tts");eh(l,{recursive:!0});let u=e.audioFormat??"wav",p=`zhipu-tts-${th()}.${u}`,g=ic(l,p);return Zf(g,d),{mediaUrls:[`file://${g}`],model:e.model||"glm-tts",durationMs:Date.now()-o,billingUnit:"per_character",billingQuantity:s.length}}async generateSTT(e,t,n){let o=Date.now();if(!e.audioUrl)throw new Error("ZhipuMediaTransport: audioUrl required for STT");let s=`${this.baseUrl}/audio/transcriptions`,i=await fetch(e.audioUrl,{headers:{"User-Agent":"qlogicagent/1.0"},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok)throw new Error(`Failed to fetch audio from ${e.audioUrl}`);let a=await i.blob(),c=new FormData;c.append("model",e.model||"glm-asr-2512"),c.append("file",a,"audio.wav");let d=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:c,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`Zhipu STT API error ${d.status}: ${u}`)}let l=await d.json();return{mediaUrls:[],model:e.model||"glm-asr-2512",durationMs:Date.now()-o,metadata:{transcription:l.text??""}}}async generateEmbedding(e,t,n){let o=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: text or prompt required for embedding");let i=`${this.baseUrl}/embeddings`,a={model:e.model||"embedding-3",input:s},d=(await this.postJSON(i,a,t,n)).data??[];return{mediaUrls:[],model:e.model||"embedding-3",durationMs:Date.now()-o,metadata:{embeddings:d.map(l=>l.embedding).filter(Boolean)}}}async generateVoiceClone(e,t,n){let o=Date.now();if(!e.audioUrl)throw new Error("ZhipuMediaTransport: audioUrl required for voice_clone (sample audio)");let s=await fetch(e.audioUrl,{signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`Failed to fetch audio sample from ${e.audioUrl}`);let i=await s.blob(),a=new FormData;a.append("model",e.model||"glm-tts-clone"),a.append("file",i,"sample.wav"),(e.text||e.prompt)&&a.append("text",e.text||e.prompt||"");let c=`${this.baseUrl}/voice/clone`,d=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:a,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let p=await d.text().catch(()=>"");throw new Error(`Zhipu Voice Clone API error ${d.status}: ${p}`)}let l=await d.json();return{mediaUrls:(l.data??[]).map(p=>p.url).filter(p=>!!p),model:e.model||"glm-tts-clone",durationMs:Date.now()-o,metadata:{voiceId:l.voice_id}}}async generateDocumentParsing(e,t,n){let o=Date.now(),s=e.imageUrl||e.audioUrl;if(!s&&!e.prompt)throw new Error("ZhipuMediaTransport: imageUrl/audioUrl (file URL) or prompt (base64) required for document_parsing");let i=`${this.baseUrl}/layout_parsing`,a={model:e.model||"glm-ocr"};s?a.file_url=s:e.prompt&&(a.content=e.prompt);let l=(await this.postJSON(i,a,t,n)).pages??[];return{mediaUrls:[],model:e.model||"glm-ocr",durationMs:Date.now()-o,metadata:{pages:l.map(u=>({pageNum:u.page_num,content:u.content,layouts:u.layouts}))}}}async generateRerank(e,t,n){let o=Date.now(),s=e.prompt;if(!s)throw new Error("ZhipuMediaTransport: prompt (query) required for rerank");if(!e.metadata?.documents)throw new Error("ZhipuMediaTransport: metadata.documents required for rerank");let i=`${this.baseUrl}/rerank`,a={model:e.model||"rerank",query:s,documents:e.metadata.documents};e.metadata.topN!==void 0&&(a.top_n=e.metadata.topN);let c=await this.postJSON(i,a,t,n);return{mediaUrls:[],model:e.model||"rerank",durationMs:Date.now()-o,metadata:{results:(c.results??[]).map(d=>({index:d.index,relevanceScore:d.relevance_score,document:d.document}))}}}async postJSON(e,t,n,o){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Zhipu API error ${s.status}: ${i}`)}return s.json()}async pollAsyncResult(e,t,n,o){let s=Date.now()+_o,i=`${this.baseUrl}/async-result/${encodeURIComponent(e)}`;for(;Date.now()<s;){n?.throwIfAborted();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Zhipu async-result error ${a.status}: ${l}`)}let c=await a.json();if(c.task_status==="SUCCESS")return o?.(100,"completed",e),c;if(c.task_status==="FAIL")throw new Error("Zhipu async task failed");let d=Date.now()-(s-_o);o?.(Math.min(95,Math.round(d/_o*100)),c.task_status??"running",e),await new Promise(l=>setTimeout(l,oh))}throw new Error(`Zhipu async task timed out after ${_o/1e3}s`)}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/async-result/${encodeURIComponent(e)}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`Zhipu task query error ${s.status}: ${d}`)}let i=await s.json(),a=i.task_status??"unknown";return{status:a==="SUCCESS"?"succeeded":a==="FAIL"?"failed":a==="PROCESSING"?"running":a.toLowerCase(),task:i}}async listVideoTasks(e,t,n){return{data:[]}}async deleteVideoTask(e,t,n){throw new Error("Zhipu does not support task cancellation. Tasks complete or timeout automatically.")}async listVoices(e,t){let n=`${this.baseUrl}/voice/`,o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:t??AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let i=await o.text().catch(()=>"");throw new Error(`Zhipu voice list error ${o.status}: ${i}`)}return(await o.json()).data??[]}async deleteVoice(e,t,n){let o=`${this.baseUrl}/voice/${encodeURIComponent(e)}`,s=await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Zhipu voice delete error ${s.status}: ${i}`)}}};var hn=class{registry;transports=new Map;constructor(e){this.registry=e.registry}resolveModelById(e,t,n){let o=this.registry.getProvider(e);if(!o)return;let i=this.registry.listModels(e).find(a=>a.id===t&&a.mediaType===n);if(i)return{providerId:e,providerDef:o,modelInfo:i,mediaType:n}}getTransport(e){let t=this.transports.get(e);if(t)return t;let n=this.registry.getProvider(e);if(!n)return;let o=ah(n);if(o)return this.transports.set(e,o),o}listMediaModels(e){let t=[];for(let n of this.registry.listProviders()){let o=this.registry.listModels(n.id);for(let s of o)s.mediaType&&(!e||s.mediaType===e)&&t.push({providerId:n.id,providerDef:n,modelInfo:s,mediaType:s.mediaType})}return t}findModelInProvider(e,t,n){let o=this.registry.getProvider(e);if(!o)return;let s=this.registry.listModels(e),i=n?sh(n):void 0,a=s.find(c=>c.mediaType!==t?!1:!i||!c.mediaCapabilities?!0:ih(c.mediaCapabilities,i));if(a)return{providerId:e,providerDef:o,modelInfo:a,mediaType:t}}};function sh(r){switch(r.mediaType){case"video":return r.operation==="merge"?"merge":r.operation==="upscale"?"upscale":r.operation==="edit"?"edit":r.imageUrl?"img2video":"text2video";case"image":return r.operation==="edit"?"inpainting":r.imageUrl?"img2img":"text2image";case"music":return r.audioUrl?"cover":"text2music";case"music_realtime":return"realtime";case"tts":return"text2speech";case"3d":return r.imageUrl?"img2_3d":"text2_3d";default:return}}function ih(r,e){return!("operations"in r)||!r.operations?!0:r.operations.includes(e)}function ah(r){let e=r.baseUrl;switch(r.id){case"volcengine":return new Ue({baseUrl:e});case"openai":return new mn({baseUrl:e});case"minimax":return new Rt({baseUrl:e});case"google":return new gn({baseUrl:e});case"qwen":return new Ro({baseUrl:e});case"zhipu":return new fn({baseUrl:e.replace(/\/api\/anthropic\/?$/,"/api/paas/v4")});case"zhipu-openai":case"zhipu-coding":return new fn({baseUrl:e.replace(/\/api\/coding\/paas\/v4\/?$/,"/api/paas/v4")});default:return}}var Qs=[{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",quirks:{useEffortInsteadOfBudget:!0,filterImageBlocks:!0,maxReasoningEffort:"max",supportsPrefixCompletion:!0},models:[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28,costCacheRead:.003},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:1.74,costOutput:3.48,costCacheRead:.014}]},{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-max-preview",name:"Qwen3.6 Max (Preview)",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:2,costOutput:8,costCacheRead:.2,costCacheWrite:2.5},{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.6-flash",name:"Qwen3.6 Flash",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.1,costOutput:.5,costCacheRead:.01,costCacheWrite:.125},{id:"qwq-plus",name:"QwQ Plus",contextWindow:131072,maxOutput:65536,toolCall:!0,reasoning:!0,reasoningRequired:!0,streamRequired:!0,vision:!1,costInput:.5,costOutput:3,costCacheRead:.05,costCacheWrite:.625},{id:"qwen-max",name:"Qwen Max",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:2,costOutput:6,costCacheRead:.2,costCacheWrite:2.5},{id:"qwen-plus",name:"Qwen Plus",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:.85,costCacheRead:.03,costCacheWrite:.375},{id:"qwen-flash",name:"Qwen Flash",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1},{id:"qwen-turbo",name:"Qwen Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!1},{id:"qwen-vl-max",name:"Qwen VL Max",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:3,costOutput:8.5},{id:"qwen3.5-omni-plus",name:"Qwen3.5 Omni Plus",contextWindow:131072,maxOutput:16384,toolCall:!1,reasoning:!1,streamRequired:!0,vision:!0},{id:"qwen-vl-ocr",name:"Qwen VL OCR",contextWindow:131072,maxOutput:4096,toolCall:!1,reasoning:!1,vision:!0,mediaType:"document_parsing",mediaCapabilities:{type:"document_parsing",supportedFormats:["jpg","jpeg","png","bmp","tiff","pdf"],maxFileSizeMB:10}},{id:"qwen3-tts-voicedesign",name:"Qwen3 TTS VoiceDesign",contextWindow:32768,maxOutput:16384,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],maxCharacters:32768,formats:["mp3","wav"]}},{id:"cosyvoice-v2",name:"CosyVoice V2",contextWindow:1e4,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],maxCharacters:1e4,formats:["mp3","wav","pcm"]}},{id:"wan2.7-image-pro",name:"Wan 2.7 Image Pro",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","1280x720","720x1280","2048x2048","3840x2160"]}},{id:"wanx2.1-t2i-turbo",name:"Wan 2.1 Text-to-Image Turbo",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","720x1280","1280x720"]}},{id:"wan2.7-t2v-plus",name:"Wan 2.7 Text/Image-to-Video Plus",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:15,resolutions:["720P","1080P"]}},{id:"wanx2.1-t2v-turbo",name:"Wan 2.1 Text/Image-to-Video Turbo",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:5,resolutions:["480P","720P"]}},{id:"text-embedding-v4",name:"Text Embedding V4",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:1024,maxTokens:8192}},{id:"wanx-background-generation-v2",name:"Wan Background Generation V2",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["inpainting"],sizes:["1024x1024","1280x720","720x1280"]}},{id:"qwen3-rerank",name:"Qwen3 Rerank",contextWindow:32768,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"rerank",mediaCapabilities:{type:"rerank",maxDocuments:100}}]},{id:"zhipu",name:"\u667A\u8C31 GLM (Zhipu)",group:"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.1",quirks:{filterThinkingBlocks:!0},models:[{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:"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-turbo",name:"GLM-5 Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1,costCacheRead:.1},{id:"glm-4.7",name:"GLM-4.7",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.6",name:"GLM-4.6",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.5-air",name:"GLM-4.5 Air",contextWindow:131072,maxOutput:98304,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1.5,costCacheRead:.1},{id:"glm-4-long",name:"GLM-4 Long",contextWindow:1e6,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.1,costOutput:.1},{id:"glm-4.7-flash",name:"GLM-4.7 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-4.5-flash",name:"GLM-4.5 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-5v-turbo",name:"GLM-5V Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:1},{id:"glm-4.6v",name:"GLM-4.6V",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:3.2},{id:"glm-4.6v-flash",name:"GLM-4.6V Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:0,costOutput:0},{id:"cogview-4-250304",name:"CogView-4",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","768x1344","864x1152","1344x768","1152x864","1440x720","720x1440"]}},{id:"cogview-3-flash",name:"CogView-3 Flash (Free)",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","768x1344","864x1152","1344x768","1152x864","1440x720","720x1440"]}},{id:"glm-image",name:"GLM-Image",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1280x1280","1568x1056","1056x1568","1472x1088","1088x1472","1728x960","960x1728"]}},{id:"cogvideox-3",name:"CogVideoX-3",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["1080p"]}},{id:"cogvideox-flash",name:"CogVideoX Flash (Free)",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:6}},{id:"glm-tts",name:"GLM-TTS",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],voices:["tongtong","chuichui","xiaochen","jam","kazi","douji","luodo"],maxCharacters:1024,formats:["wav","pcm"]}},{id:"glm-tts-clone",name:"GLM-TTS Clone",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"voice_clone",mediaCapabilities:{type:"voice_clone",maxSampleDurationSeconds:30,maxSampleSizeMB:10,formats:["wav","mp3"]}},{id:"glm-asr-2512",name:"GLM-ASR-2512",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"stt",mediaCapabilities:{type:"stt",languages:["zh","en"],maxDurationSeconds:30,formats:["wav","mp3"]}},{id:"embedding-3",name:"Embedding-3",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:2048,maxTokens:3072}},{id:"embedding-2",name:"Embedding-2",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:1024,maxTokens:512}},{id:"rerank",name:"GLM Rerank",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"rerank",mediaCapabilities:{type:"rerank",maxDocuments:128,maxQueryLength:4096,maxDocumentLength:4096}},{id:"glm-ocr",name:"GLM-OCR",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"document_parsing",mediaCapabilities:{type:"document_parsing",supportedFormats:["pdf","jpg","png"],maxPageCount:100,maxFileSizeMB:50}}]},{id:"zhipu-openai",name:"\u667A\u8C31 GLM OpenAI (Zhipu)",group:"zhipu",transport:"openai-chat",baseUrl:"https://open.bigmodel.cn/api/paas/v4",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"glm-5.1",quirks:{supportsReasoningEffort:!0,supportsThinkingParam:!0,supportsToolStream:!0,builtinWebSearch:!0,builtinCodeInterpreter:!0},models:[{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:"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-turbo",name:"GLM-5 Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1,costCacheRead:.1},{id:"glm-4.7",name:"GLM-4.7",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.6",name:"GLM-4.6",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.5-air",name:"GLM-4.5 Air",contextWindow:131072,maxOutput:98304,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1.5,costCacheRead:.1},{id:"glm-4-long",name:"GLM-4 Long",contextWindow:1e6,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.1,costOutput:.1},{id:"glm-4.7-flash",name:"GLM-4.7 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-4.5-flash",name:"GLM-4.5 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-5v-turbo",name:"GLM-5V Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:1},{id:"glm-4.6v",name:"GLM-4.6V",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:3.2},{id:"glm-4.6v-flash",name:"GLM-4.6V Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:0,costOutput:0}]},{id:"zhipu-coding",name:"\u667A\u8C31 GLM Coding (Zhipu)",group:"zhipu",transport:"openai-chat",baseUrl:"https://open.bigmodel.cn/api/coding/paas/v4",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"codegeex-4",quirks:{supportsReasoningEffort:!0,supportsThinkingParam:!0,supportsToolStream:!0},models:[{id:"codegeex-4",name:"CodeGeeX-4",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.1,costOutput:.1}]},{id:"minimax",name:"MiniMax",group:"minimax",transport:"anthropic-messages",baseUrl:"https://api.minimaxi.com/anthropic",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"MiniMax-M2.7",omitZeroTemperature:!0,quirks:{filterImageBlocks:!0},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:"MiniMax-M2.7-highspeed",name:"MiniMax M2.7 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2,costCacheRead:.06,costCacheWrite:.375},{id:"MiniMax-M2.5",name:"MiniMax M2.5",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6,costCacheRead:.03,costCacheWrite:.19},{id:"MiniMax-M2.5-highspeed",name:"MiniMax M2.5 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6,costCacheRead:.03,costCacheWrite:.19},{id:"MiniMax-M2.1",name:"MiniMax M2.1 (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.1-highspeed",name:"MiniMax M2.1 Highspeed (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2",name:"MiniMax M2 (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.1,costOutput:.4},{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",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:300,formats:["mp3","wav"]}},{id:"music-cover",name:"MiniMax Music Cover",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"music",mediaCapabilities:{type:"music",operations:["cover"],maxDurationSeconds:300,formats:["mp3","wav"]}},{id:"MiniMax-Hailuo-2.3",name:"Hailuo 2.3",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["768P","1080P"]}},{id:"MiniMax-Hailuo-2.3-Fast",name:"Hailuo 2.3 Fast",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["768P","1080P"]}},{id:"MiniMax-Hailuo-02",name:"Hailuo 02",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["512P","768P","1080P"]}},{id:"image-01",name:"MiniMax Image 01",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["512x512","1024x1024","2048x2048"]}},{id:"image-01-live",name:"MiniMax Image 01 Live",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024"]}},{id:"speech-2.8-hd",name:"MiniMax Speech 2.8 HD",contextWindow:1e4,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],formats:["mp3","pcm","flac","wav","opus"]}},{id:"speech-2.8-turbo",name:"MiniMax Speech 2.8 Turbo",contextWindow:1e4,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],formats:["mp3","pcm","flac","wav","opus"]}}]},{id:"minimax-openai",name:"MiniMax (OpenAI)",group:"minimax",transport:"openai-chat",baseUrl:"https://api.minimaxi.com/v1",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"bearer",isAggregator:!1,omitZeroTemperature:!0,defaultModel:"MiniMax-M2.7",quirks:{supportsReasoningSplit:!0},models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2},{id:"MiniMax-M2.7-highspeed",name:"MiniMax M2.7 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2},{id:"MiniMax-M2.5",name:"MiniMax M2.5",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.5-highspeed",name:"MiniMax M2.5 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.1",name:"MiniMax M2.1 (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.1-highspeed",name:"MiniMax M2.1 Highspeed (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6}]},{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",quirks:{supportsReasoningEffort:!0,supportsThinkingParam:!0,builtinWebSearch:!0},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:"kimi-k2.5",name:"Kimi K2.5",contextWindow:262144,maxOutput:262144,toolCall:!0,reasoning:!0,vision:!0,costInput:.8,costOutput:4,costCacheRead:.2},{id:"moonshot-v1-128k",name:"Moonshot V1 128K",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.84,costOutput:.84}]},{id:"volcengine",name:"\u8C46\u5305 (Doubao/Volcengine)",transport:"volcengine-responses",baseUrl:"https://ark.cn-beijing.volces.com/api",apiKeyEnvVars:["ARK_API_KEY","DOUBAO_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"doubao-seed-2-0-lite-260215",models:[{id:"doubao-seed-2-0-pro-260215",name:"Doubao Seed 2.0 Pro",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-lite-260428",name:"Doubao Seed 2.0 Lite (0428)",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-lite-260215",name:"Doubao Seed 2.0 Lite",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-mini-260428",name:"Doubao Seed 2.0 Mini (0428)",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-mini-260215",name:"Doubao Seed 2.0 Mini",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-code-preview-260215",name:"Doubao Seed 2.0 Code Preview",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-1-8-251228",name:"Doubao Seed 1.8",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{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",mediaCapabilities:{type:"video",operations:["text2video","img2video","video2video","edit","merge","upscale"],maxDurationSeconds:15,resolutions:["480p","720p","1080p"],aspectRatios:["16:9","9:16","1:1"],fps:[24]}},{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",mediaCapabilities:{type:"video",operations:["text2video","img2video","video2video","edit","merge","upscale"],maxDurationSeconds:15,resolutions:["480p","720p"],aspectRatios:["16:9","9:16","1:1"],fps:[24]}},{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",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["512x512","1024x1024","2K"]}},{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",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["512x512","1024x1024","2K"]}},{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",mediaCapabilities:{type:"3d",operations:["img2_3d"],outputFormats:["glb","obj","usd","usdz"]}},{id:"hyper3d-gen2-260112",name:"Hyper3D Gen2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d",mediaCapabilities:{type:"3d",operations:["text2_3d","img2_3d"],outputFormats:["glb","obj"]}},{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",mediaCapabilities:{type:"3d",operations:["img2_3d"],outputFormats:["glb","obj","usd"]}}]},{id:"openai",name:"OpenAI",transport:"openai-responses",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-5.5",quirks:{builtinWebSearch:!0,builtinCodeInterpreter:!0,builtinFileSearch:!0},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:"gpt-5.4-nano",name:"GPT-5.4 Nano",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.2,costOutput:1.25,costCacheRead:.02},{id:"gpt-image-2",name:"GPT Image 2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img","inpainting"],sizes:["1024x1024","1536x1024","1024x1536","auto"],transparentBackground:!0}},{id:"gpt-realtime-2",name:"GPT Realtime 2",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!0,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}},{id:"gpt-realtime-translate",name:"GPT Realtime Translate",contextWindow:128e3,maxOutput:16e3,toolCall:!1,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!1}},{id:"gpt-realtime-1.5",name:"GPT Realtime 1.5",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}},{id:"gpt-realtime-mini",name:"GPT Realtime Mini",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}}]},{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:"gemini-generatecontent",baseUrl:"https://generativelanguage.googleapis.com/v1beta",apiKeyEnvVars:["GOOGLE_API_KEY","GEMINI_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"gemini-3-flash-preview",quirks:{builtinWebSearch:!0,builtinCodeInterpreter:!0,builtinUrlContext:!0,builtinMapsGrounding:!0,builtinFileSearch:!0},models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,reasoningRequired:!0,vision:!0,costInput:2,costOutput:12},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:3},{id:"gemini-3.1-flash-lite",name:"Gemini 3.1 Flash-Lite",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.25,costOutput:1.5},{id:"gemini-3.1-flash-image-preview",name:"Gemini 3.1 Flash Image (Nano Banana 2)",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}},{id:"gemini-3-pro-image-preview",name:"Gemini 3 Pro Image (Nano Banana Pro)",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}},{id:"veo-3.1-generate-preview",name:"Veo 3.1 Standard",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P","4K"]}},{id:"veo-3.1-fast-generate-preview",name:"Veo 3.1 Fast",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P","4K"]}},{id:"veo-3.1-lite-generate-preview",name:"Veo 3.1 Lite",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P"]}},{id:"lyria-3-pro-preview",name:"Lyria 3 Pro",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:300,formats:["mp3"]}},{id:"lyria-3-clip-preview",name:"Lyria 3 Clip",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:30,formats:["mp3"]}},{id:"lyria-realtime-exp",name:"Lyria RealTime (Experimental)",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music_realtime",mediaCapabilities:{type:"music",operations:["realtime"],formats:["wav"]}},{id:"gemini-3.1-flash-tts-preview",name:"Gemini 3.1 Flash TTS",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:1,costOutput:20,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],maxCharacters:8e3,formats:["mp3","wav"]}},{id:"gemini-embedding-2",name:"Gemini Embedding 2 (Multimodal)",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:.2,costOutput:0,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:3072,maxTokens:8192}}]},{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}]}];import{existsSync as lh,mkdirSync as ch,readFileSync as dh,writeFileSync as uh}from"node:fs";import{join as ph}from"node:path";var mh="https://models.dev/api.json",gh=3e4,fh=1440*60*1e3,hh=300*1e3,yh={deepseek:"deepseek",qwen:"qwen","qwen-coding-plan":"qwen-coding","alibaba-cn":"qwen",zhipuai:"zhipu",minimax:"minimax",moonshot:"moonshot",moonshotai:"moonshot",doubao:"volcengine","bytedance-seed":"volcengine",volcengine:"volcengine",openai:"openai",anthropic:"anthropic",google:"google",openrouter:"openrouter"},yn=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??Ne(),this.cacheFile=ph(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??fh}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(!lh(this.cacheFile))return;let e=dh(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:ac(t.data)}}catch{}}saveToDisk(e){try{ch(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);uh(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<hh||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(mh,{signal:AbortSignal.timeout(gh),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=ac(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function ac(r){let e=new Map;if(!r||typeof r!="object")return e;for(let[t,n]of Object.entries(r)){let o=yh[t];if(!o||!n||typeof n!="object")continue;let i=n.models;if(!i||typeof i!="object")continue;let a=e.get(o);a||(a={models:new Map},e.set(o,a));for(let[c,d]of Object.entries(i)){if(!d||typeof d!="object"||a.models.has(c))continue;let l=d,u=l.cost??{},p=l.limit??{},g=l.modalities??{},f=Array.isArray(g.input)?g.input:[],m=Array.isArray(g.output)?g.output:[],y=bh(m,f,c);a.models.set(c,{id:c,name:typeof l.name=="string"?l.name:c,contextWindow:typeof p.context=="number"?p.context:2e5,maxOutput:typeof p.output=="number"?p.output:8192,toolCall:l.tool_call===!0,reasoning:l.reasoning===!0,vision:l.attachment===!0||f.includes("image"),costInput:typeof u.input=="number"?u.input:void 0,costOutput:typeof u.output=="number"?u.output:void 0,costCacheRead:typeof u.cache_read=="number"?u.cache_read:void 0,costCacheWrite:typeof u.cache_write=="number"?u.cache_write:void 0,mediaType:y})}}return e}function bh(r,e,t){if(r.includes("video"))return"video";if(r.includes("image")&&!r.includes("text"))return"image";if(r.includes("audio")&&!r.includes("text"))return"tts";if(r.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 kh={claude:"anthropic",gemini:"google",doubao:"volcengine"},Ht=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of Qs)this.builtins.set(t.id,t);this.catalog=e?.catalog??new yn}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=kh[e]??e,n=this.builtins.get(t),o=this.overrides.get(t);if(!(!n&&!o))return!n&&o?!o.id||!o.transport||!o.baseUrl?void 0:{id:o.id,name:o.name??o.id,transport:o.transport,baseUrl:o.baseUrl,apiKeyEnvVars:o.apiKeyEnvVars??[],authType:o.authType??"bearer",isAggregator:o.isAggregator??!1,defaultModel:o.defaultModel,models:o.models}:n&&!o?n:{...n,...o,models:o.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??[],o=this.catalog.getModels(e);if(o.length===0)return n;let s=new Map;for(let i of o)s.set(i.id,i);for(let i of n)s.set(i.id,i);return[...s.values()]}getModelInfo(e,t){return this.listModels(e).find(n=>n.id===t)}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,t){if(t)return t;let n=this.getProvider(e);if(n)for(let o of n.apiKeyEnvVars){let s=process.env[o];if(s?.trim())return s.trim()}}};var Th={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".avif":"image/avif",".heic":"image/heic",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".aac":"audio/aac",".flac":"audio/flac",".m4a":"audio/mp4",".opus":"audio/opus",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".json":"application/json"};function wh(r){let e=r.slice(r.lastIndexOf(".")).toLowerCase();return Th[e]||"application/octet-stream"}var vh=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i;function Sh(r){return vh.test(r)}async function lc(r,e,t,n){if(r.startsWith("data:")||!Sh(r))return r;let o=await fetch(r,{signal:n});if(!o.ok)throw new Error(`Failed to fetch local media ${r}: ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),i=xh(r),a=o.headers.get("content-type")||wh(i);return(await e.uploadFile(s,i,a,t,n)).url}function xh(r){try{let t=new URL(r).pathname.split("/").pop();return t&&t.includes(".")?t:"upload"}catch{return"upload"}}var Rh=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i;function H(r){return Rh.test(r)}async function Fe(r,e){return lc(r,e.uploadAdapter,e.apiKey,e.signal)}var _h=20*1024*1024;async function Co(r,e){if(r.startsWith("data:")||!H(r))return r;let t=await fetch(r);if(!t.ok)throw new Error(`Failed to fetch local media ${r}: ${t.status}`);let n=Buffer.from(await t.arrayBuffer());if(n.byteLength>_h)throw new Error(`Local media too large for base64 (${(n.byteLength/1024/1024).toFixed(1)}MB). Use file upload API instead.`);return`data:${t.headers.get("content-type")||e||Ch(r)};base64,${n.toString("base64")}`}function Ch(r){let e=r.split("?")[0].split("#")[0],t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".avif":"image/avif",".heic":"image/heic",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".aac":"audio/aac",".flac":"audio/flac",".m4a":"audio/mp4",".opus":"audio/opus",".pdf":"application/pdf"}[t]||"application/octet-stream"}var Zs=new Set([429,529,502,503,504]),ze=9e4;function Ve(r){let e=Math.min(1e3*Math.pow(2,r-1),3e4),t=Math.random()*.25*e;return e+t}function et(r){return r!=null&&Zs.has(r)}function qe(r,e){return new Promise((t,n)=>{if(e?.aborted){n(new Error("Request aborted"));return}let o=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(o),n(new Error("Request aborted"))},{once:!0})})}function tt(r){if(r&&typeof r=="object"){let e=r;if(typeof e.status=="number")return e.status;if(typeof e.statusCode=="number")return e.statusCode;if(e.response&&typeof e.response.status=="number")return e.response.status}return null}function Ao(r){return r.toLowerCase().startsWith("gpt-5")}function Io(r){return r.toLowerCase().includes("5.4-nano")}function bn(r){return/^o[1-4](-|$)/.test(r.toLowerCase())}var Wt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;quirks;fileUploadAdapter;cumulativeReasoningLen=0;cumulativeContentLen=0;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,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){this.cumulativeReasoningLen=0,this.cumulativeContentLen=0;let o=e.prefixMessage&&this.quirks.supportsPrefixCompletion,s=/\/v\d+$/.test(this.baseUrl),i;o?i=`${this.baseUrl}/beta/v1/chat/completions`:s?i=`${this.baseUrl}/chat/completions`:i=`${this.baseUrl}/v1/chat/completions`;let a={model:e.model,messages:Ph(await Ih(e.messages,this.fileUploadAdapter,t,n),this.quirks),stream:!0};this.supportsStreamOptions&&(a.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(a.tools=e.tools,e.toolChoice&&(a.tool_choice=e.toolChoice));let c=!e.disableBuiltinTools,d=!1;if(c&&this.quirks.builtinWebSearch&&a.tools){let m=a.tools;this.quirks.builtinCodeInterpreter?m.push({type:"web_search",web_search:{enable:!0,search_result:!0}}):(m.push({type:"builtin_function",function:{name:"$web_search"}}),d=!0)}c&&this.quirks.builtinCodeInterpreter&&a.tools&&a.tools.push({type:"code_interpreter",code_interpreter:{sandbox:"none"}}),this.quirks.supportsToolStream&&a.tools&&(a.tool_stream=!0);let l=this.quirks.useEffortInsteadOfBudget&&!!e.reasoning,u=e.model.startsWith("kimi-k2.6"),p=Ao(e.model);if(e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p||!bn(e.model)&&!l&&!u)&&(a.temperature=e.temperature)),e.topP!==void 0&&(p||!bn(e.model)&&!l&&!u)&&(a.top_p=e.topP),e.maxTokens!==void 0&&(p||bn(e.model)||e.model.startsWith("kimi-k2")?a.max_completion_tokens=e.maxTokens:a.max_tokens=e.maxTokens),e.reasoning)if(p){let m=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;Io(e.model)&&(m==="high"||m==="xhigh")&&(m="medium"),a.reasoning={effort:m}}else if(bn(e.model))a.reasoning_effort=e.reasoning.effort;else if(this.quirks.useEffortInsteadOfBudget){a.thinking={type:"enabled"};let m=this.quirks.maxReasoningEffort??"high",y=e.reasoning.effort??"high";a.reasoning_effort=y==="low"||y==="medium"?"high":m}else this.quirks.supportsThinkingParam?(d?a.thinking={type:"disabled"}:this.quirks.supportsToolStream?a.thinking={type:"enabled",clear_thinking:!1}:a.thinking={type:"enabled"},this.quirks.supportsReasoningEffort&&(a.reasoning_effort=e.reasoning.effort)):this.quirks.supportsReasoningEffort?a.reasoning_effort=e.reasoning.effort:a.reasoning=e.reasoning;else d&&(a.thinking={type:"disabled"});e.structuredOutput&&(e.structuredOutput.mode==="json_object"?a.response_format={type:"json_object"}:e.structuredOutput.mode==="json_schema"&&(a.response_format={type:"json_schema",json_schema:{name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}})),this.quirks.supportsReasoningSplit&&e.reasoning&&(a.reasoning_split=!0),e.prediction&&p&&(a.prediction=e.prediction),o&&e.prefixMessage&&a.messages.push({role:"assistant",content:e.prefixMessage,prefix:!0});let g={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},f=null;for(let m=0;m<=3;m++){if(n?.aborted)throw new Error("Request aborted");m>0&&f&&await qe(Ve(m),n);try{yield*this.fetchAndStream(i,g,a,n);return}catch(y){f=y instanceof Error?y:new Error(String(y));let k=f.message.includes("Stream idle timeout");if(!et(tt(f))&&!k||m===3)throw f}}}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`LLM API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("LLM API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStreamWithWatchdog(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();t.usage&&(yield{type:"usage",promptTokens:t.usage.prompt_tokens??0,completionTokens:t.usage.completion_tokens??0,reasoningTokens:t.usage.completion_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.prompt_tokens_details?.cached_tokens});for(let n of t.choices??[]){let o=n.message;if(o){if(o.reasoning_content&&(yield{type:"reasoning_delta",text:o.reasoning_content}),o.content&&(yield{type:"delta",text:o.content}),o.tool_calls)for(let s=0;s<o.tool_calls.length;s++){let i=o.tool_calls[s];yield{type:"tool_call_delta",index:s,id:i.id,name:i.function.name,arguments:i.function.arguments}}n.finish_reason&&(yield{type:"done",finishReason:n.finish_reason})}}}async*parseSSEStreamWithWatchdog(e){let t=new TextDecoder,n="",o=null,s=new AbortController,i=()=>{o&&clearTimeout(o),o=setTimeout(()=>{s.abort()},ze)};try{i();let a=e.getReader();try{for(;;){let{done:c,value:d}=await a.read();if(c)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(d,{stream:!0});let l;for(;(l=n.indexOf(`
35
- `))!==-1;){let u=n.slice(0,l).trim();if(n=n.slice(l+1),!u||u.startsWith(":")||!u.startsWith("data: "))continue;let p=u.slice(6);if(p==="[DONE]")return;let g;try{g=JSON.parse(p)}catch{continue}yield*this.processChunk(g)}}}finally{a.releaseLock()}}finally{o&&clearTimeout(o)}}*processChunk(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,cacheReadTokens:e.usage.prompt_tokens_details?.cached_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.reasoning_details){let o=n.reasoning_details.slice(this.cumulativeReasoningLen);o&&(this.cumulativeReasoningLen=n.reasoning_details.length,yield{type:"reasoning_delta",text:o})}if(n.content)if(this.quirks.supportsReasoningSplit){let o=n.content.slice(this.cumulativeContentLen);o&&(this.cumulativeContentLen=n.content.length,yield{type:"delta",text:o})}else yield{type:"delta",text:n.content};if(n.tool_calls)for(let o of n.tool_calls)yield{type:"tool_call_delta",index:o.index,id:o.id,name:o.function?.name,arguments:o.function?.arguments??""};t.finish_reason&&(yield{type:"done",finishReason:Ah(t.finish_reason)})}}}async*complete(e,t,n){if(!this.quirks.supportsPrefixCompletion)throw new Error("FIM completion is not supported by this provider");let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/beta/completions`:`${this.baseUrl}/beta/v1/completions`,i={model:e.model,prompt:e.prompt,stream:!0,max_tokens:e.maxTokens??4096};e.suffix&&(i.suffix=e.suffix),e.temperature!==void 0&&(i.temperature=e.temperature),e.stop&&(i.stop=e.stop);let a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},c=AbortSignal.timeout(this.timeoutMs),d=n?AbortSignal.any([n,c]):c,l=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(i),signal:d});if(!l.ok){let f=await l.text().catch(()=>"");throw new Error(`FIM API error ${l.status}: ${f.slice(0,500)}`)}if(!l.body)throw new Error("FIM API returned no response body");let u=new TextDecoder,p="",g=l.body.getReader();try{for(;;){let{done:f,value:m}=await g.read();if(f)break;p+=u.decode(m,{stream:!0});let y;for(;(y=p.indexOf(`
36
- `))!==-1;){let k=p.slice(0,y).trim();if(p=p.slice(y+1),!k||k.startsWith(":")||!k.startsWith("data: "))continue;let b=k.slice(6);if(b==="[DONE]")return;let x;try{x=JSON.parse(b)}catch{continue}for(let S of x.choices??[])S.text&&(yield{type:"delta",text:S.text}),S.finish_reason&&(yield{type:"done",finishReason:S.finish_reason})}}}finally{g.releaseLock()}}async uploadFile(e,t,n,o,s){let a=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/files`:`${this.baseUrl}/v1/files`,c=new FormData;c.append("file",e,t),c.append("purpose",n);let d=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`,...this.extraHeaders},body:c,signal:s??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`File upload error ${d.status}: ${u}`)}let l=await d.json();return{fileId:l.id??"",filename:l.filename??t,bytes:l.bytes??0}}async getFileInfo(e,t,n){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/files/${encodeURIComponent(e)}`:`${this.baseUrl}/v1/files/${encodeURIComponent(e)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${t}`,...this.extraHeaders},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`File info error ${i.status}: ${c}`)}let a=await i.json();return{id:a.id??e,filename:a.filename??"",bytes:a.bytes??0,status:a.status??"unknown"}}};function Ah(r){switch(r){case"sensitive":return"content_filter";case"model_context_window_exceeded":return"length";case"network_error":return"error";default:return r}}async function Ih(r,e,t,n){return r.some(s=>s.audioUrls?.some(H)||s.imageUrls?.some(H))?Promise.all(r.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.role==="user"&&s.audioUrls?.some(H)&&(i.audioUrls=await Promise.all(s.audioUrls.map(a=>H(a)?Co(a):Promise.resolve(a)))),s.imageUrls?.some(H)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>H(a)?Fe(a,{uploadAdapter:e,apiKey:t,signal:n}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):r}function Ph(r,e){return r.map(t=>{if(t.role==="user"){let n=t.imageUrls&&t.imageUrls.length>0&&!e.filterImageBlocks,o=t.videoUrls&&t.videoUrls.length>0,s=t.audioUrls&&t.audioUrls.length>0,i=t.fileIds&&t.fileIds.length>0;if(n||o||s||i){let c=[];if(t.content&&c.push({type:"text",text:t.content}),n)for(let d of t.imageUrls){let l={url:d};t.imageDetail&&(l.detail=t.imageDetail),c.push({type:"image_url",image_url:l})}if(o)for(let d of t.videoUrls)c.push({type:"video_url",video_url:{url:d}});if(s)for(let d of t.audioUrls){let l=d,u=t.audioFormat??"mp3";if(d.startsWith("data:")){let p=/^data:audio\/([^;]+);base64,(.+)$/.exec(d);p&&(u=p[1]==="mpeg"?"mp3":p[1],l=p[2])}c.push({type:"input_audio",input_audio:{data:l,format:u}})}if(i)for(let d of t.fileIds)if(d.id.startsWith("http://")||d.id.startsWith("https://")){let l=d.mimeType?`[Attached: ${d.id} (${d.mimeType})]`:`[Attached: ${d.id}]`;c.push({type:"text",text:l})}else c.push({type:"file",file:{file_id:d.id}});return{role:"user",content:c}}return{role:"user",content:t.content??""}}if(t.role==="assistant"){let n={role:"assistant"};return t.thinkingBlocks&&t.thinkingBlocks.length>0&&(n.reasoning_content=t.thinkingBlocks.map(o=>o.thinking).join("")),n.content=t.content??null,t.tool_calls&&t.tool_calls.length>0&&(n.tool_calls=t.tool_calls.map(o=>({id:o.id,type:o.type,function:{name:o.function.name,arguments:o.function.arguments}}))),n}if(t.role==="tool"){if(t.imageUrls&&t.imageUrls.length>0&&!e.filterImageBlocks){let n=[];t.content&&n.push({type:"text",text:t.content});for(let o of t.imageUrls)n.push({type:"image_url",image_url:{url:o}});return{role:"tool",content:n,tool_call_id:t.tool_call_id??""}}return{role:"tool",content:t.content??"",tool_call_id:t.tool_call_id??""}}return{role:t.role,content:t.content??""}})}var Po=class{baseUrl;extraHeaders;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("OpenAIResponsesTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/responses`:`${this.baseUrl}/v1/responses`,i=await this.buildRequestBody(e,t,n),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},c=null;for(let d=0;d<=3;d++){if(n?.aborted)throw new Error("Request aborted");d>0&&c&&await qe(Ve(d),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(l){c=l instanceof Error?l:new Error(String(l));let u=c.message.includes("Stream idle timeout");if(!et(tt(c))&&!u||d===3)throw c}}}async buildRequestBody(e,t,n){let o={model:e.model,input:Eh(await Mh(e.messages,this.fileUploadAdapter,t,n)),stream:!0};if(e.conversationId?o.conversation=e.conversationId:e.previousResponseId&&(o.previous_response_id=e.previousResponseId),e.store!==void 0&&(o.store=e.store),e.instructions&&(o.instructions=e.instructions),e.structuredOutput&&(e.structuredOutput.mode==="json_object"?o.text={format:{type:"json_object"}}:o.text={format:{type:"json_schema",name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}}),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(s=>({type:"function",name:s.function.name,description:s.function.description,parameters:s.function.parameters,strict:!0}))),e.toolChoice!==void 0&&(typeof e.toolChoice=="string"?o.tool_choice=e.toolChoice:o.tool_choice={type:e.toolChoice.type,name:e.toolChoice.name}),e.temperature!==void 0&&(o.temperature=e.temperature),e.topP!==void 0&&(o.top_p=e.topP),e.maxTokens!==void 0&&(o.max_output_tokens=e.maxTokens),e.reasoning){let s=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;Io(e.model)&&(s==="high"||s==="xhigh")&&(s="medium");let i={effort:s};i.summary="auto",i.generate_summary="auto",o.reasoning=i}if(e.prediction&&Ao(e.model)&&(o.prediction=e.prediction),o.truncation="auto",e.promptCacheKey&&(o.prompt_cache_key=e.promptCacheKey),e.promptCacheRetention&&(o.prompt_cache_retention=e.promptCacheRetention),e.serviceTier&&(o.service_tier=e.serviceTier),e.reasoning?.includeEncryptedReasoning&&(e.store===void 0&&(o.store=!1),o.include=["reasoning.encrypted_content"]),e.contextManagement&&(o.context_management=e.contextManagement.edits.map(s=>{let i={type:s.type};return s.type==="clear_thinking"&&s.keep!==void 0?i.keep=s.keep:s.type==="clear_tool_uses"&&(s.trigger&&(i.trigger=s.trigger),s.keep&&(i.keep=s.keep),s.excludeTools&&(i.exclude_tools=s.excludeTools),s.clearToolInput!==void 0&&(i.clear_tool_input=s.clearToolInput)),i})),!e.disableBuiltinTools){let s=o.tools??[],i=o.include??[];if(e.openaiBuiltinTools&&e.openaiBuiltinTools.length>0){for(let c of e.openaiBuiltinTools)s.push({...c});let a=new Set(e.openaiBuiltinTools.map(c=>c.type));a.has("web_search_preview")&&i.push("web_search_call.action.sources"),a.has("file_search")&&i.push("file_search_call.results"),a.has("code_interpreter")&&i.push("code_interpreter_call.outputs"),a.has("computer_use_preview")&&i.push("computer_call_output.output.image_url")}else this.quirks.builtinWebSearch&&(s.push({type:"web_search_preview"}),i.push("web_search_call.action.sources")),this.quirks.builtinCodeInterpreter&&(s.push({type:"code_interpreter"}),i.push("code_interpreter_call.outputs")),this.quirks.builtinFileSearch&&(s.push({type:"file_search"}),i.push("file_search_call.results"));s.length>0&&(o.tools=s),i.length>0&&(o.include=i)}if(e.maxToolCalls!==void 0&&(o.max_tool_calls=e.maxToolCalls),e.parallelToolCalls!==void 0&&(o.parallel_tool_calls=e.parallelToolCalls),e.textVerbosity){let s=o.text??{};s.verbosity=e.textVerbosity,o.text=s}return o}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`OpenAI Responses API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("OpenAI Responses API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStream(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();if(t.id&&(yield{type:"response_id",id:t.id}),t.usage&&(yield{type:"usage",promptTokens:t.usage.input_tokens??0,completionTokens:t.usage.output_tokens??0,reasoningTokens:t.usage.output_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.input_tokens_details?.cached_tokens}),t.output)for(let n of t.output){if(n.type==="message"&&n.content)for(let o of n.content)o.type==="output_text"&&(yield{type:"delta",text:o.text??""},o.annotations&&o.annotations.length>0&&(yield{type:"annotations",annotations:o.annotations.map(s=>({...s,type:s.type??"url_citation",url:s.url,title:s.title}))}));if(n.type==="reasoning"&&n.summary)for(let o of n.summary)o.type==="summary_text"&&(yield{type:"reasoning_delta",text:o.text??""});n.type==="function_call"&&(yield{type:"tool_call_delta",index:0,id:n.call_id,name:n.name,arguments:n.arguments??""})}yield{type:"done",finishReason:t.status==="completed"?"stop":t.status??"stop"}}async*parseSSEStream(e){let t=new TextDecoder,n="",o="",s=null,i=new AbortController,a=0,c=new Map,d=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},ze)};try{d();let l=e.getReader();try{for(;;){let{done:u,value:p}=await l.read();if(u)break;if(i.signal.aborted)throw new Error("Stream idle timeout");d(),n+=t.decode(p,{stream:!0});let g;for(;(g=n.indexOf(`
37
- `))!==-1;){let f=n.slice(0,g).trim();if(n=n.slice(g+1),!f){o="";continue}if(!f.startsWith(":")){if(f.startsWith("event:")){o=f.slice(6).trim();continue}if(f.startsWith("data:")){let m=f.slice(5).trim();if(m==="[DONE]")return;let y;try{y=JSON.parse(m)}catch{continue}yield*this.processEvent(o,y,c,()=>a++)}}}}}finally{l.releaseLock()}}finally{s&&clearTimeout(s)}}*processEvent(e,t,n,o){switch(e){case"response.output_text.delta":{let s=t.delta;s&&(yield{type:"delta",text:s});break}case"response.reasoning_summary_text.delta":{let s=t.delta;s&&(yield{type:"reasoning_delta",text:s});break}case"response.function_call_arguments.delta":{let s=t.delta,i=t.call_id,a=t.name;if(s!==void 0&&i){let c=n.get(i);c===void 0&&(c=o(),n.set(i,c)),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:s}}break}case"response.output_item.added":{let s=t.item;if(s&&s.type==="function_call"){let i=s.call_id,a=s.name;if(i&&!n.has(i)){let c=o();n.set(i,c),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:""}}}break}case"response.function_call_arguments.done":break;case"response.content_part.done":{let s=t.part;if(s?.type==="output_text"){let i=s.annotations;i&&i.length>0&&(yield{type:"annotations",annotations:i.map(a=>({type:a.type??"url_citation",url:a.url,title:a.title,...a}))})}break}case"response.output_item.done":{let s=t.item;if(s?.type==="message"){let i=s.content;if(i)for(let a of i){let c=a.annotations;c&&c.length>0&&(yield{type:"annotations",annotations:c.map(d=>({type:d.type??"url_citation",url:d.url,title:d.title,...d}))})}}break}case"response.completed":{let s=t.response;if(s){let i=s.id;i&&(yield{type:"response_id",id:i});let a=s.usage;if(a){let d=a.input_tokens_details,l=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:l?.reasoning_tokens,cacheReadTokens:d?.cached_tokens}}yield{type:"done",finishReason:s.status==="incomplete"?"tool_calls":"stop"}}else yield{type:"done",finishReason:"stop"};break}case"response.failed":{yield{type:"error",message:t.response?.error?.message??"Unknown error"},yield{type:"done",finishReason:"error"};break}default:{e.startsWith("response.web_search_call")&&(yield{type:"builtin_tool_status",toolType:"web_search",event:e,data:t});break}}}};async function Mh(r,e,t,n){return r.some(s=>s.audioUrls?.some(H)||s.imageUrls?.some(H))?Promise.all(r.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.role==="user"&&s.audioUrls?.some(H)&&(i.audioUrls=await Promise.all(s.audioUrls.map(a=>H(a)?Co(a):Promise.resolve(a)))),s.imageUrls?.some(H)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>H(a)?Fe(a,{uploadAdapter:e,apiKey:t,signal:n}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):r}function Eh(r){let e=[];for(let t of r){if(t.role==="system"){e.push({role:"developer",content:t.content??""});continue}if(t.role==="user"){let n=t.imageUrls&&t.imageUrls.length>0,o=t.videoUrls&&t.videoUrls.length>0,s=t.audioUrls&&t.audioUrls.length>0,i=t.fileIds&&t.fileIds.length>0;if(n||o||s||i){let c=[];if(n)for(let d of t.imageUrls){let l={type:"input_image",image_url:d};t.imageDetail&&(l.detail=t.imageDetail),c.push(l)}if(o)for(let d of t.videoUrls)c.push({type:"input_video",video_url:d});if(s)for(let d of t.audioUrls){let l=d,u=t.audioFormat??"mp3";if(d.startsWith("data:")){let p=/^data:audio\/([^;]+);base64,(.+)$/.exec(d);p&&(u=p[1]==="mpeg"?"mp3":p[1],l=p[2])}c.push({type:"input_audio",data:l,format:u})}if(i)for(let d of t.fileIds)if(d.id.startsWith("http://")||d.id.startsWith("https://")){let l=d.mimeType?`[Attached: ${d.id} (${d.mimeType})]`:`[Attached: ${d.id}]`;c.push({type:"input_text",text:l})}else c.push({type:"input_file",file_id:d.id});t.content&&c.push({type:"input_text",text:t.content}),e.push({role:"user",content:c})}else e.push({role:"user",content:t.content??""});continue}if(t.role==="assistant"){if(t.content&&e.push({role:"assistant",content:t.content}),t.tool_calls&&t.tool_calls.length>0)for(let n of t.tool_calls)e.push({type:"function_call",call_id:n.id,name:n.function.name,arguments:n.function.arguments});continue}if(t.role==="tool"){if(!t.tool_call_id)continue;if(t.imageUrls&&t.imageUrls.length>0){let n=[];t.content&&n.push({type:"input_text",text:t.content});for(let o of t.imageUrls)n.push({type:"input_image",image_url:o});e.push({type:"function_call_output",call_id:t.tool_call_id,output:n})}else e.push({type:"function_call_output",call_id:t.tool_call_id,output:t.content??""});continue}}return e}var Oh=18e4,Dh=3e5,Lh=64e3,$h="[Tool execution failed; output not available during conversation recovery]",Uh="interleaved-thinking-2025-05-14",Nh="context-1m-2025-08-07",jh="token-efficient-tools-2026-03-28",Fh="prompt-caching-scope-2026-01-05",Bh="pdfs-2024-09-25";function Gh(r){let e=r.toLowerCase();return e.includes("opus-4-6")||e.includes("opus-4-7")||e.includes("sonnet-4-6")}function Hh(r,e,t){let n=[],o=r.toLowerCase();(o.includes("opus-4-6")||o.includes("opus-4-7")||o.includes("sonnet-4-6"))&&n.push(Nh),n.push(Bh),e&&!o.includes("haiku")&&n.push(Uh),t&&n.push(jh),n.push(Fh);let i=process.env.ANTHROPIC_BETAS;if(i)for(let a of i.split(",").map(c=>c.trim()).filter(Boolean))n.includes(a)||n.push(a);return n}var kn=class{baseUrl;apiVersion;timeoutMs;streamIdleTimeoutMs;enablePromptCaching;maxRetries;omitZeroTemperature;quirks;fileUploadAdapter;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??Oh,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??ze,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3,this.omitZeroTemperature=e.omitZeroTemperature??!1,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let o=`${this.baseUrl}/v1/messages`,s=qh(e.messages),i=await Kh(s,this.fileUploadAdapter,t,n),{system:a,messages:c}=Jh(i,this.quirks,e.model),d=Vh(a,this.enablePromptCaching),l=!!e.reasoning,u=e.maxTokens??8192,p={model:e.model,messages:c,max_tokens:l?Math.max(u,4096):u,stream:!0};if(d&&(p.system=d),e.tools&&e.tools.length>0){let y=e.tools.map(Xh);this.enablePromptCaching&&y.length>0&&(y[y.length-1].cache_control={type:"ephemeral"}),p.tools=y,e.toolChoice&&(p.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})}if(!l&&e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p.temperature=e.temperature)),!l&&e.topP!==void 0&&(p.top_p=e.topP),l)if(this.quirks.useEffortInsteadOfBudget){p.thinking={type:"enabled"};let y=this.quirks.maxReasoningEffort??"high",k=e.reasoning?.effort??"high",b=k==="low"||k==="medium"?"high":y;if(p.output_config={effort:b},a){let x=2166136261;for(let S=0;S<a.length;S++)x^=a.charCodeAt(S),x=Math.imul(x,16777619);p.metadata={user_id:`qa-${(x>>>0).toString(36)}`}}}else if(Gh(e.model))p.thinking={type:"adaptive"};else{let y=zh(e.reasoning.effort,e.maxTokens);p.thinking={type:"enabled",budget_tokens:Math.min(u-1,y)}}let g=Hh(e.model,l,(e.tools?.length??0)>0),f={"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion};g.length>0&&(f["anthropic-beta"]=g.join(","));let m=null;for(let y=0;y<=this.maxRetries;y++){if(n?.aborted)throw new Error("Request aborted");y>0&&m&&await qe(Ve(y),n);try{yield*this.streamWithWatchdog(o,f,p,n);return}catch(k){m=k instanceof Error?k:new Error(String(k));let b=Yh(m.message),x=b!==null&&Zs.has(b),S=m.message.includes("Stream idle timeout");if(m.message.includes("model_context_window_exceeded")||m.message.includes("context_length_exceeded")||!x&&!S)throw m;if(y===this.maxRetries){if((S||x)&&!e.streamRequired)try{yield*this.nonStreamingFallback(o,f,p,n);return}catch{throw m}throw m}}}if(m)throw m}async*streamWithWatchdog(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(n),signal:i});if(!a.ok){let p=await a.text().catch(()=>""),g=new Error(`Anthropic API error ${a.status}: ${p.slice(0,500)}`);throw g.status=a.status,g}if(!a.body)throw new Error("Anthropic API returned no response body");let c=null,d=!1,l=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{d=!0},this.streamIdleTimeoutMs)},u=()=>{c!==null&&(clearTimeout(c),c=null)};l();try{yield*this.parseSSEStream(a.body,l,()=>d)}finally{u()}if(d)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,n,o){let s=Qh({...n,stream:!1}),i=AbortSignal.timeout(Dh),a=o?AbortSignal.any([o,i]):i,c=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!c.ok){let l=await c.text().catch(()=>""),u=new Error(`Anthropic API error ${c.status}: ${l.slice(0,500)}`);throw u.status=c.status,u}let d=await c.json();yield*this.mapNonStreamingResponse(d)}*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,reasoningTokens:t.reasoning_input_tokens>0?t.reasoning_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 o=e.stop_reason;o&&(yield{type:"done",finishReason:dc(o)})}async*parseSSEStream(e,t,n){let o=new TextDecoder,s="",i="",a=new Map,c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0};for await(let d of e){if(t(),n())break;s+=o.decode(d,{stream:!0});let l;for(;(l=s.indexOf(`
38
- `))!==-1;){let u=s.slice(0,l).trim();if(s=s.slice(l+1),!u){i="";continue}if(u.startsWith("event:")){i=u.slice(6).trimStart();continue}if(!u.startsWith("data:"))continue;let p=u.slice(5).trimStart(),g;try{g=JSON.parse(p)}catch{continue}yield*this.mapEvent(i,g,a,c)}}}*mapEvent(e,t,n,o){switch(e){case"message_start":{let i=t.message?.usage;i&&(cc(o,i),yield{type:"usage",promptTokens:o.inputTokens,completionTokens:o.outputTokens,cacheReadTokens:o.cacheReadTokens>0?o.cacheReadTokens:void 0,cacheCreationTokens:o.cacheCreationTokens>0?o.cacheCreationTokens:void 0,reasoningTokens:o.reasoningTokens>0?o.reasoningTokens: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 c=n.get(s);c&&typeof i.signature=="string"&&(c.signature=i.signature)}break}case"content_block_stop":{let s=t.index,i=n.get(s);i?.type==="thinking"&&typeof i.signature=="string"&&(yield{type:"reasoning_block_complete",thinking:"",signature:i.signature}),n.delete(s);break}case"message_delta":{let s=t.delta,i=t.usage;i&&(cc(o,i),yield{type:"usage",promptTokens:o.inputTokens,completionTokens:o.outputTokens,cacheReadTokens:o.cacheReadTokens>0?o.cacheReadTokens:void 0,cacheCreationTokens:o.cacheCreationTokens>0?o.cacheCreationTokens:void 0,reasoningTokens:o.reasoningTokens>0?o.reasoningTokens:void 0}),s?.stop_reason&&(yield{type:"done",finishReason:dc(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 cc(r,e){e.input_tokens>0&&(r.inputTokens=e.input_tokens),r.outputTokens=e.output_tokens??r.outputTokens,e.cache_read_input_tokens>0&&(r.cacheReadTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens>0&&(r.cacheCreationTokens=e.cache_creation_input_tokens),e.reasoning_input_tokens>0&&(r.reasoningTokens=e.reasoning_input_tokens)}function dc(r){switch(r){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_calls";case"max_tokens":return"length";default:return r}}function Wh(r){return!/haiku/i.test(r)}var ei={high:16e3,medium:8e3,low:4e3};function zh(r,e){if(e&&e>16384)switch(r){case"high":return Math.min(e-1,Math.max(16e3,Math.floor(e*.5)));case"medium":return Math.min(e-1,Math.max(8e3,Math.floor(e*.25)));case"low":return Math.min(e-1,4e3);default:return ei.high}return ei[r]??ei.high}function Vh(r,e){if(r)return e?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:r}function qh(r){let e=[],t=new Set;for(let n=0;n<r.length;n++){let o=r[n];if(o.role==="assistant"&&o.tool_calls&&o.tool_calls.length>0){let s=o.tool_calls.filter(l=>t.has(l.id)?!1:(t.add(l.id),!0)),i=new Set(s.map(l=>l.id)),a=new Set,c=r.slice(n+1);for(let l of c){if(l.role!=="tool")break;l.tool_call_id&&a.add(l.tool_call_id)}s.length!==o.tool_calls.length?e.push({...o,tool_calls:s}):e.push(o);let d=[...i].filter(l=>!a.has(l));for(let l of d){let u=s.find(p=>p.id===l);e.push({role:"tool",tool_call_id:l,name:u?.function.name,content:"[Tool execution failed; output not available during conversation recovery]"})}}else o.role==="tool"?t.has(o.tool_call_id??"")&&e.push(o):e.push(o)}return e}async function Kh(r,e,t,n){return r.some(s=>s.imageUrls?.some(H)||s.fileIds?.some(i=>H(i.id)))?Promise.all(r.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.imageUrls?.some(H)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>H(a)?Fe(a,{uploadAdapter:e,apiKey:t,signal:n}):Promise.resolve(a)))}if(s.role==="user"&&s.fileIds?.some(a=>H(a.id))){if(!e||!t)throw new Error("FileUploadAdapter required for local file URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.fileIds=await Promise.all(s.fileIds.map(async a=>{if(!H(a.id))return a;let c=await Fe(a.id,{uploadAdapter:e,apiKey:t,signal:n});return{...a,id:c}}))}return Object.keys(i).length>0?{...s,...i}:s})):r}function Jh(r,e={},t){let n,o=[];for(let s of r){if(s.role==="system"){n=n?`${n}
39
-
40
- ${s.content??""}`:s.content??"";continue}if(s.role==="user"){let i=s.imageUrls&&s.imageUrls.length>0&&!e.filterImageBlocks,a=s.fileIds&&s.fileIds.length>0;if(i||a){let c=[];if(s.content&&c.push({type:"text",text:s.content}),i)for(let d of s.imageUrls)if(d.startsWith("data:")){let l=/^data:([^;]+);base64,(.+)$/.exec(d);if(l){let u=l[1];u==="application/pdf"?c.push({type:"document",source:{type:"base64",media_type:u,data:l[2]}}):c.push({type:"image",source:{type:"base64",media_type:u,data:l[2]}})}}else d.endsWith(".pdf")||d.includes(".pdf?")?c.push({type:"document",source:{type:"url",url:d}}):c.push({type:"image",source:{type:"url",url:d}});if(a)for(let d of s.fileIds){let l=d.mimeType||"";if(l==="application/pdf"||d.id.endsWith(".pdf"))if(d.id.startsWith("data:")){let u=/^data:[^;]+;base64,(.+)$/.exec(d.id);u&&c.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:u[1]}})}else c.push({type:"document",source:{type:"url",url:d.id}});else{let u=l?`[Attached: ${d.id} (${l})]`:`[Attached: ${d.id}]`;c.push({type:"text",text:u})}}o.push({role:"user",content:c})}else o.push({role:"user",content:s.content??""})}else if(s.role==="assistant"){let i=e.filterThinkingBlocks?void 0:s.thinkingBlocks;if(s.tool_calls&&s.tool_calls.length>0){let a=[];if(i)for(let c of i)c.signature&&a.push({type:"thinking",thinking:c.thinking,signature:c.signature});s.content&&a.push({type:"text",text:s.content});for(let c of s.tool_calls){let d;try{d=JSON.parse(c.function.arguments)}catch{d={}}a.push({type:"tool_use",id:c.id,name:c.function.name,input:d})}o.push({role:"assistant",content:a})}else if(i&&i.length>0){let a=[];for(let c of i)c.signature&&a.push({type:"thinking",thinking:c.thinking,signature:c.signature});s.content&&a.push({type:"text",text:s.content}),o.push({role:"assistant",content:a})}else o.push({role:"assistant",content:s.content??""})}else if(s.role==="tool"){let i=s.content??"",a=s.is_error===!0||i.startsWith("Error:")||i===$h,c=s.toolReferences,d=c&&c.length>0&&!a&&(!t||Wh(t)),l=s.imageUrls,u;if(d)u=c.map(f=>({type:"tool_reference",tool_name:f}));else if(l&&l.length>0&&!a){let f=[];i&&f.push({type:"text",text:i});for(let m of l)if(m.startsWith("data:")){let y=/^data:([^;]+);base64,(.+)$/.exec(m);y&&f.push({type:"image",source:{type:"base64",media_type:y[1],data:y[2]}})}else f.push({type:"image",source:{type:"url",url:m}});u=f}else u=i;let p={type:"tool_result",tool_use_id:s.tool_call_id??"",content:u,...a&&{is_error:!0}},g=o[o.length-1];g&&g.role==="user"&&Array.isArray(g.content)?g.content.push(p):o.push({role:"user",content:[p]})}}return{system:n,messages:o}}function Xh(r){return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters??{type:"object",properties:{}}}}function Yh(r){let e=/Anthropic API error (\d{3})/.exec(r);return e?parseInt(e[1],10):null}function Qh(r){let e=typeof r.max_tokens=="number"?r.max_tokens:8192,t=Math.min(e,Lh),n={...r,max_tokens:t},o=n.thinking;return o?.type==="enabled"&&o.budget_tokens&&(n.thinking={...o,budget_tokens:Math.min(o.budget_tokens,t-1)}),n}var Mo=class{baseUrl;extraHeaders;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("VolcengineResponsesTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let s=`${this.baseUrl.replace(/\/v\d+$/,"")}/v3/responses`,i=await this.buildRequestBody(e,t,n),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders};if(e.builtinTools&&!e.disableBuiltinTools&&e.builtinTools.length>0)for(let d of e.builtinTools)d.type==="builtin_web_search"?a["ark-beta-web-search"]="true":d.type==="builtin_image_process"?a["ark-beta-image-process"]="true":d.type==="builtin_knowledge_search"?a["ark-beta-knowledge-search"]="true":d.type==="builtin_doubao_app"&&(a["ark-beta-doubao-app"]="true");let c=null;for(let d=0;d<=3;d++){if(n?.aborted)throw new Error("Request aborted");d>0&&c&&await qe(Ve(d),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(l){c=l instanceof Error?l:new Error(String(l));let u=c.message.includes("Stream idle timeout");if(!et(tt(c))&&!u||d===3)throw c}}}resolveConstraints(e){let t=e;if(t.caching&&t.caching.type==="enabled"){if(t.instructions)return t={...t,caching:void 0},t;if(t.structuredOutput&&t.structuredOutput.mode==="json_schema"&&(t={...t,structuredOutput:{mode:"json_object"}}),t.builtinTools&&t.builtinTools.length>0){let o=t.builtinTools.filter(s=>s.type!=="builtin_web_search"&&s.type!=="builtin_image_process");o.length!==t.builtinTools.length&&(t={...t,builtinTools:o.length>0?o:void 0})}}return t}async buildRequestBody(e,t,n){let o=this.resolveConstraints(e),s=await Zh(o.messages,this.fileUploadAdapter,t,n),i={model:o.model,input:ey(s),stream:!0};if(o.previousResponseId&&(i.previous_response_id=o.previousResponseId),o.store!==void 0&&(i.store=o.store),o.storeExpireAt!==void 0&&(i.expire_at=o.storeExpireAt),o.instructions&&(i.instructions=o.instructions),o.structuredOutput)if(o.structuredOutput.mode==="json_object")i.text={format:{type:"json_object"}};else{let c={type:"json_schema",name:o.structuredOutput.name,schema:o.structuredOutput.schema};o.structuredOutput.strict!==void 0&&(c.strict=o.structuredOutput.strict),i.text={format:c}}if(o.caching){let c={type:o.caching.type};o.caching.prefix!==void 0&&(c.prefix=o.caching.prefix),i.caching=c,o.caching.prefix&&(i.stream=!1)}if(o.contextManagement){let c=o.contextManagement.edits.map(d=>{let l={type:d.type};return d.type==="clear_thinking"&&d.keep!==void 0?l.keep=d.keep:d.type==="clear_tool_uses"&&(d.trigger&&(l.trigger=d.trigger),d.keep&&(l.keep=d.keep),d.excludeTools&&(l.exclude_tools=d.excludeTools),d.clearToolInput!==void 0&&(l.clear_tool_input=d.clearToolInput)),l});i.context_management={edits:c}}let a=[];if(o.tools&&o.tools.length>0)for(let c of o.tools)a.push({type:"function",name:c.function.name,description:c.function.description,parameters:c.function.parameters});if(o.builtinTools&&!o.disableBuiltinTools&&o.builtinTools.length>0)for(let c of o.builtinTools){let l={type:c.type.replace(/^builtin_/,"")};c.config&&Object.assign(l,c.config),a.push(l)}if(a.length>0&&(i.tools=a),o.maxToolCalls!==void 0&&(i.max_tool_calls=o.maxToolCalls),o.toolChoice!==void 0&&(typeof o.toolChoice=="string"?i.tool_choice=o.toolChoice:i.tool_choice={type:o.toolChoice.type,name:o.toolChoice.name}),o.temperature!==void 0&&(i.temperature=o.temperature),o.topP!==void 0&&(i.top_p=o.topP),o.maxTokens!==void 0&&(i.max_output_tokens=o.maxTokens),o.reasoning){let c=o.reasoning.effort??"high";c==="minimal"?i.thinking={type:"disabled"}:(i.thinking={type:"enabled"},i.reasoning={effort:c}),o.reasoning.includeEncryptedReasoning&&(i.include=["reasoning.encrypted_content"])}return o.prefixMessage&&i.input.push({role:"assistant",content:o.prefixMessage,partial:!0}),i}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`Volcengine Responses API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("Volcengine Responses API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStream(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();if(t.id&&(yield{type:"response_id",id:t.id}),t.usage&&(yield{type:"usage",promptTokens:t.usage.input_tokens??0,completionTokens:t.usage.output_tokens??0,reasoningTokens:t.usage.output_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.input_tokens_details?.cached_tokens}),t.output)for(let n of t.output){if(n.type==="message"&&n.content)for(let o of n.content)o.type==="output_text"&&(yield{type:"delta",text:o.text??""});if(n.type==="reasoning"&&n.summary)for(let o of n.summary)o.type==="summary_text"&&(yield{type:"reasoning_delta",text:o.text??""});n.type==="function_call"&&(yield{type:"tool_call_delta",index:0,id:n.call_id,name:n.name,arguments:n.arguments??""})}yield{type:"done",finishReason:t.status==="completed"?"stop":t.status??"stop"}}async*parseSSEStream(e){let t=new TextDecoder,n="",o="",s=null,i=new AbortController,a=0,c=new Map,d=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},ze)};try{d();let l=e.getReader();try{for(;;){let{done:u,value:p}=await l.read();if(u)break;if(i.signal.aborted)throw new Error("Stream idle timeout");d(),n+=t.decode(p,{stream:!0});let g;for(;(g=n.indexOf(`
41
- `))!==-1;){let f=n.slice(0,g).trim();if(n=n.slice(g+1),!f){o="";continue}if(!f.startsWith(":")){if(f.startsWith("event:")){o=f.slice(6).trim();continue}if(f.startsWith("data:")){let m=f.slice(5).trim();if(m==="[DONE]")return;let y;try{y=JSON.parse(m)}catch{continue}yield*this.processEvent(o,y,c,()=>a++)}}}}}finally{l.releaseLock()}}finally{s&&clearTimeout(s)}}*processEvent(e,t,n,o){switch(e){case"response.output_text.delta":{let s=t.delta;s&&(yield{type:"delta",text:s});break}case"response.reasoning_summary_text.delta":{let s=t.delta;s&&(yield{type:"reasoning_delta",text:s});break}case"response.function_call_arguments.delta":{let s=t.delta,i=t.call_id,a=t.name;if(s!==void 0&&i){let c=n.get(i);c===void 0&&(c=o(),n.set(i,c)),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:s}}break}case"response.output_item.added":{let s=t.item;if(s&&s.type==="function_call"){let i=s.call_id,a=s.name;if(i&&!n.has(i)){let c=o();n.set(i,c),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:""}}}break}case"response.function_call_arguments.done":break;case"response.output_item.done":{let s=t.item;if(s?.type==="message"){let i=s.content;if(i)for(let a of i){let c=a.annotations;c&&c.length>0&&(yield{type:"annotations",annotations:c.map(d=>({type:d.type??"url_citation",url:d.url,title:d.title,...d}))})}}if(s?.type==="function_call"){let i=s.call_id,a=s.name,c=s.arguments??"";if(i&&c){let d=n.get(i),l=d!==void 0;l||(d=o(),n.set(i,d)),yield{type:"tool_call_delta",index:d,id:i,name:l?void 0:a,arguments:c}}}break}case"response.completed":{let s=t.response;if(s){let i=s.id;i&&(yield{type:"response_id",id:i});let a=s.usage;if(a){let d=a.input_tokens_details,l=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:l?.reasoning_tokens,cacheReadTokens:d?.cached_tokens}}yield{type:"done",finishReason:s.status==="incomplete"?"tool_calls":"stop"}}else yield{type:"done",finishReason:"stop"};break}case"response.failed":{yield{type:"error",message:t.response?.error?.message??"Unknown error"},yield{type:"done",finishReason:"error"};break}default:{e.startsWith("response.web_search_call")?yield{type:"builtin_tool_status",toolType:"web_search",event:e,data:t}:e.startsWith("response.image_process")&&(yield{type:"builtin_tool_status",toolType:"image_process",event:e,data:t});break}}}};async function Zh(r,e,t,n){if(!r.some(i=>i.imageUrls?.some(H)||i.videoUrls?.some(H)||i.audioUrls?.some(H)))return r;let s=i=>{if(!H(i))return Promise.resolve(i);if(!e||!t)throw new Error("FileUploadAdapter required for local media URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");return Fe(i,{uploadAdapter:e,apiKey:t,signal:n})};return Promise.all(r.map(async i=>{if(i.role!=="user"&&i.role!=="tool")return i;let a={};return i.imageUrls?.some(H)&&(a.imageUrls=await Promise.all(i.imageUrls.map(s))),i.role==="user"&&i.videoUrls?.some(H)&&(a.videoUrls=await Promise.all(i.videoUrls.map(s))),i.role==="user"&&i.audioUrls?.some(H)&&(a.audioUrls=await Promise.all(i.audioUrls.map(s))),Object.keys(a).length>0?{...i,...a}:i}))}function ey(r){let e=[];for(let t of r){if(t.role==="system"){e.push({role:"system",content:t.content??""});continue}if(t.role==="user"){let n=t.imageUrls&&t.imageUrls.length>0,o=t.videoUrls&&t.videoUrls.length>0,s=t.audioUrls&&t.audioUrls.length>0,i=t.fileIds&&t.fileIds.length>0;if(n||o||s||i){let c=[];if(n)for(let d of t.imageUrls){let l={type:"input_image",image_url:d};t.imageDetail&&(l.detail=t.imageDetail),t.imagePixelLimit&&(l.image_pixel_limit=t.imagePixelLimit),c.push(l)}if(o)for(let d of t.videoUrls){let l={type:"input_video",video_url:d};t.videoFps!==void 0&&(l.fps=t.videoFps),c.push(l)}if(s)for(let d of t.audioUrls){let l={type:"input_audio",audio_url:d};t.audioFormat&&(l.format=t.audioFormat),c.push(l)}if(i)for(let d of t.fileIds)if(d.id.startsWith("http://")||d.id.startsWith("https://")){let l=d.mimeType?`[Attached: ${d.id} (${d.mimeType})]`:`[Attached: ${d.id}]`;c.push({type:"input_text",text:l})}else c.push({type:"input_file",file_id:d.id});t.content&&c.push({type:"input_text",text:t.content}),e.push({role:"user",content:c})}else e.push({role:"user",content:t.content??""});continue}if(t.role==="assistant"){if(t.content&&e.push({role:"assistant",content:t.content}),t.tool_calls&&t.tool_calls.length>0)for(let n of t.tool_calls)e.push({type:"function_call",call_id:n.id,name:n.function.name,arguments:n.function.arguments||"{}"});continue}if(t.role==="tool"){if(!t.tool_call_id)continue;if(t.imageUrls&&t.imageUrls.length>0){let n=[];t.content&&n.push({type:"input_text",text:t.content});for(let o of t.imageUrls)n.push({type:"input_image",image_url:o});e.push({type:"function_call_output",call_id:t.tool_call_id,output:n})}else e.push({type:"function_call_output",call_id:t.tool_call_id,output:t.content??""});continue}}return e}$r();var ty=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_CIVIC_INTEGRITY",threshold:"BLOCK_ONLY_HIGH"}];function ny(r){switch(r){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";default:return"HIGH"}}var Tn=class{baseUrl;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("GeminiGenerateContentTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:streamGenerateContent?alt=sse`,s=await this.buildRequestBody(e,t,n),i={"Content-Type":"application/json","x-goog-api-key":t},a=null;for(let c=0;c<=3;c++){if(n?.aborted)throw new Error("Request aborted");c>0&&a&&await qe(Ve(c),n);try{yield*this.fetchAndStream(o,i,s,n);return}catch(d){a=d instanceof Error?d:new Error(String(d));let l=a.message.includes("Stream idle timeout");if(!et(tt(a))&&!l)throw a;if(c===3){if((l||et(tt(a)))&&!e.streamRequired)try{yield*this.nonStreamingFallback(e,t,n);return}catch{throw a}throw a}}}}async buildRequestBody(e,t,n){let o=await oy(e.messages,this.fileUploadAdapter,t,n),{systemInstruction:s,contents:i}=ry(o),a={contents:i};s&&(a.system_instruction=s);let c=this.buildTools(e);c.length>0&&(a.tools=c),e.tools&&e.tools.length>0&&e.toolChoice&&(a.toolConfig=this.buildToolConfig(e.toolChoice));let d=this.buildGenerationConfig(e);return Object.keys(d).length>0&&(a.generationConfig=d),a.safetySettings=ty,e.cachedContent&&(a.cachedContent=e.cachedContent),a}buildTools(e){let t=[];if(e.tools&&e.tools.length>0){let n=e.tools.map(sy);t.push({functionDeclarations:n})}return e.disableBuiltinTools||(this.quirks.builtinWebSearch&&t.push({googleSearch:{}}),this.quirks.builtinCodeInterpreter&&t.push({codeExecution:{}}),this.quirks.builtinUrlContext&&t.push({urlContext:{}}),this.quirks.builtinMapsGrounding&&t.push({googleMaps:{}}),this.quirks.builtinFileSearch&&t.push({fileSearch:{}})),t}buildToolConfig(e){return typeof e=="string"?{functionCallingConfig:{mode:{auto:"AUTO",none:"NONE",required:"ANY"}[e]??"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.name]}}}buildGenerationConfig(e){let t={};if(e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.maxTokens!==void 0&&(t.maxOutputTokens=e.maxTokens),e.reasoning){let n=ny(e.reasoning.effort);n==="MINIMAL"&&e.model.includes("pro")&&(n="LOW"),t.thinkingConfig={thinkingLevel:n,includeThoughts:!0}}return e.structuredOutput&&(e.structuredOutput.mode==="json_object"?t.responseMimeType="application/json":e.structuredOutput.mode==="json_schema"&&(t.responseMimeType="application/json",t.responseSchema=e.structuredOutput.schema)),t}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`Gemini API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("Gemini API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){let d=await a.json();yield*this.processResponse(d);return}yield*this.parseSSEStreamWithWatchdog(a.body)}async*parseSSEStreamWithWatchdog(e){let t=new TextDecoder,n="",o=null,s=new AbortController,i=()=>{o&&clearTimeout(o),o=setTimeout(()=>{s.abort()},ze)};try{i();let a=e.getReader();try{for(;;){let{done:c,value:d}=await a.read();if(c)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(d,{stream:!0});let l;for(;(l=n.indexOf(`
42
- `))!==-1;){let u=n.slice(0,l).trim();if(n=n.slice(l+1),!u||u.startsWith(":")||!u.startsWith("data: "))continue;let p=u.slice(6);if(p==="[DONE]")return;let g;try{g=JSON.parse(p)}catch{continue}yield*this.processResponse(g)}}}finally{a.releaseLock()}}finally{o&&clearTimeout(o)}}*processResponse(e){if(e.error){yield{type:"error",message:`Gemini error ${e.error.code}: ${e.error.message}`};return}if(e.usageMetadata){let t=e.usageMetadata;yield{type:"usage",promptTokens:t.promptTokenCount??0,completionTokens:t.candidatesTokenCount??0,reasoningTokens:t.thoughtsTokenCount,cacheReadTokens:t.cachedContentTokenCount}}if(!(!e.candidates||e.candidates.length===0))for(let t of e.candidates){if(t.finishReason==="SAFETY"){yield{type:"error",message:"Response blocked by Gemini safety filters"},yield{type:"done",finishReason:"content_filter"};return}let n=t.content?.parts??[],o=0;for(let s of n){if(s.thought&&s.text){yield{type:"reasoning_delta",text:s.text},s.thoughtSignature&&(yield{type:"reasoning_block_complete",thinking:s.text,signature:s.thoughtSignature});continue}if(s.text&&!s.thought){yield{type:"delta",text:s.text};continue}if(s.functionCall){let i=s.functionCall;yield{type:"tool_call_delta",index:o,id:i.id??`gemini-tc-${o}`,name:i.name,arguments:JSON.stringify(i.args??{})},s.thoughtSignature&&(yield{type:"reasoning_block_complete",thinking:"",signature:s.thoughtSignature}),o++;continue}if(s.codeExecutionResult){yield{type:"delta",text:`
33
+ `)}};import{randomUUID as ge}from"node:crypto";_o();Hs();var je=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 o=Date.now(),s=`${this.baseUrl}/v3/images/generations`,i={model:e.model,prompt:e.prompt,size:e.size??"2K",n:e.n??1,response_format:"url",sequential_image_generation:"disabled",watermark:!0};e.imageUrl&&(i.image=e.imageUrl),e.referenceImages&&e.referenceImages.length>0&&(i.image_urls=e.referenceImages),e.style&&(i.style=e.style),e.quality&&(i.quality=e.quality),e.seed!==void 0&&(i.seed=e.seed),e.guidanceScale!==void 0&&(i.guidance_scale=e.guidanceScale),e.enhancePrompt!==void 0&&(i.enhance_prompt=e.enhancePrompt),e.streamImage&&(i.stream=!0);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 l=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${l}`)}return e.streamImage&&a.body?this.parseStreamingImage(a.body,e,o):{mediaUrls:((await a.json()).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-o}}async parseStreamingImage(e,t,n){let o=new TextDecoder,s="",i="",a=e.getReader();try{for(;;){let{done:c,value:d}=await a.read();if(c)break;s+=o.decode(d,{stream:!0});let l;for(;(l=s.indexOf(`
34
+ `))!==-1;){let u=s.slice(0,l).trim();if(s=s.slice(l+1),!u||u.startsWith(":")||!u.startsWith("data:"))continue;let p=u.slice(5).trim();if(p==="[DONE]")break;try{let f=JSON.parse(p).data?.[0]?.url;f&&(i=f,t.onProgress?.(50,"streaming"))}catch{}}}}finally{a.releaseLock()}return t.onProgress?.(100,"completed"),{mediaUrls:i?[i]:[],model:t.model,size:t.size??"1024x1024",durationMs:Date.now()-n}}async generateVideo(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=e.referenceVideos?.length??0,a=e.referenceAudios?.length??0,c=e.referenceImages?.length??0,d=!!(e.imageUrl||c>0);if(i>3)throw new Error(`Seedance 2.0: max 3 reference videos (got ${i}). Total duration must be \u226415s.`);if(a>3)throw new Error(`Seedance 2.0: max 3 reference audios (got ${a}). Total duration must be \u226415s.`);if(a>0&&!d&&i===0)throw new Error("Seedance 2.0: reference audio cannot be used alone. Provide at least one reference image or video.");if(e.operation==="edit"&&c>9)throw new Error(`Seedance 2.0 video edit: max 9 reference images (got ${c}).`);let l=[];switch(e.draftTaskId&&l.push({type:"draft_task",id:e.draftTaskId}),e.operation){case"multimodal_reference":{if(e.prompt&&l.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let b=0;b<e.referenceImages.length;b++){let k=e.imageRoles?.[b]??"reference_image";l.push({type:"image_url",image_url:{url:e.referenceImages[b]},role:k})}if(e.referenceVideos?.length)for(let b of e.referenceVideos)l.push({type:"video_url",video_url:{url:b},role:"reference_video"});if(e.referenceAudios?.length)for(let b of e.referenceAudios)l.push({type:"audio_url",audio_url:{url:b},role:"reference_audio"});break}case"extend":{if(e.sourceVideos?.length)for(let b of e.sourceVideos)l.push({type:"video_url",video_url:{url:b},role:"reference_video"});e.prompt&&l.push({type:"text",text:e.prompt});break}case"merge":for(let b of e.sourceVideos??[])l.push({type:"video_url",video_url:{url:b}});e.prompt&&l.push({type:"text",text:e.prompt});break;case"upscale":e.sourceVideos?.[0]&&l.push({type:"video_url",video_url:{url:e.sourceVideos[0]}}),l.push({type:"text",text:e.prompt||"upscale"});break;case"edit":for(let b of e.sourceVideos??[])l.push({type:"video_url",video_url:{url:b},role:"reference_video"});if(e.referenceImages?.length)for(let b of e.referenceImages)l.push({type:"image_url",image_url:{url:b},role:"reference_image"});e.prompt&&l.push({type:"text",text:e.prompt});break;default:{let b=(e.referenceVideos?.length??0)>0,k=(e.referenceAudios?.length??0)>0,S=(e.imageRoles?.length??0)>0;if(b||k||S){if(e.prompt&&l.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let R=0;R<e.referenceImages.length;R++){let P=e.imageRoles?.[R]??"reference_image";l.push({type:"image_url",image_url:{url:e.referenceImages[R]},role:P})}if(b)for(let R of e.referenceVideos)l.push({type:"video_url",video_url:{url:R},role:"reference_video"});if(k)for(let R of e.referenceAudios)l.push({type:"audio_url",audio_url:{url:R},role:"reference_audio"})}else if(e.referenceImages?.length){for(let R of e.referenceImages)l.push({type:"image_url",image_url:{url:R}});e.prompt&&l.push({type:"text",text:e.prompt})}else e.imageUrl?(l.push({type:"image_url",image_url:{url:e.imageUrl}}),e.prompt&&l.push({type:"text",text:e.prompt})):e.prompt&&l.push({type:"text",text:e.prompt});break}}let u={model:e.model,content:l};e.duration&&(u.duration=e.duration),e.aspectRatio&&(u.ratio=e.aspectRatio),e.resolution&&(u.resolution=e.resolution),e.seed!==void 0&&(u.seed=e.seed),e.fps&&(u.fps=e.fps),e.generateAudio!==void 0&&(u.generate_audio=e.generateAudio),e.watermark!==void 0&&(u.watermark=e.watermark),e.enhancePrompt!==void 0&&(u.enhance_prompt=e.enhancePrompt),e.cameraFixed!==void 0&&(u.camera_fixed=e.cameraFixed),e.returnLastFrame!==void 0&&(u.return_last_frame=e.returnLastFrame),e.serviceTier&&(u.service_tier=e.serviceTier),e.executionExpiresAfterSeconds!==void 0&&(u.execution_expires_after=e.executionExpiresAfterSeconds),e.draft!==void 0&&(u.draft=e.draft),e.safetyIdentifier&&(u.safety_identifier=e.safetyIdentifier),e.callbackUrl&&(u.callback_url=e.callbackUrl),e.videoTools?.length&&(u.tools=e.videoTools.map(b=>({type:b})));let p=await this.submitTask(s,u,t,n),m=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${p}`,t,n,e.onProgress,p),f=[],g=m.content;typeof g?.video_url=="string"&&f.push(g.video_url);let y=typeof g?.last_frame_url=="string"?g.last_frame_url:void 0;return{mediaUrls:f,model:e.model,durationMs:Date.now()-o,lastFrameUrl:y,taskId:p}}async generate3D(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=[],a=[];e.outputFormat&&a.push(`--fileformat ${e.outputFormat}`),e.prompt&&a.push(e.prompt),a.length>0&&i.push({type:"text",text:a.join(" ")}),e.imageUrl&&i.push({type:"image_url",image_url:{url:e.imageUrl}});let c={model:e.model,content:i},d=await this.submitTask(s,c,t,n),l=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${d}`,t,n,e.onProgress,d),u=[],p=l.content;if(typeof p?.video_url=="string"&&u.push(p.video_url),u.length===0&&p)for(let[,f]of Object.entries(p))typeof f=="string"&&/^https?:\/\//.test(f)&&u.push(f);let m=l.output;if(m?.model_urls){let f=m.model_urls;for(let g of Object.values(f))g&&!u.includes(g)&&u.push(g)}if(u.length===0){let f=Object.keys(l),g=p?Object.keys(p):[],y=m?Object.keys(m):[];console.error(`[volcengine-3d] No media URLs found. Response keys: [${f}], content keys: [${g}], output keys: [${y}]`);let b=l.data;if(b?.content){let k=b.content;for(let[,S]of Object.entries(k))typeof S=="string"&&/^https?:\/\//.test(S)&&u.push(S)}}return{mediaUrls:u,model:e.model,durationMs:Date.now()-o,metadata:u.length===0?{debugResponseKeys:Object.keys(l),debugContentKeys:p?Object.keys(p):null,debugContentSample:p?JSON.stringify(p).slice(0,500):null,debugOutputKeys:m?Object.keys(m):null,debugResultSample:JSON.stringify(l).slice(0,800)}:void 0}}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/v3/contents/generations/tasks/${e}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Volcengine task status error ${s.status}: ${c}`)}let i=await s.json();return{status:i.status??"unknown",task:i}}async listVideoTasks(e,t,n){let o=new URLSearchParams;t?.after&&o.set("after",t.after),t?.limit&&o.set("limit",String(t.limit)),t?.status&&o.set("status",t.status);let s=o.toString(),i=`${this.baseUrl}/v3/contents/generations/tasks${s?`?${s}`:""}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Volcengine list tasks error ${a.status}: ${c}`)}return await a.json()}async deleteVideoTask(e,t,n){let o=`${this.baseUrl}/v3/contents/generations/tasks/${e}`,s=await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Volcengine delete task error ${s.status}: ${i}`)}}async uploadFile(e,t,n,o){let s=`${this.baseUrl}/v3/files`,i=new FormData;i.append("file",e instanceof Blob?e:new Blob([e]),n?.filename??"upload"),i.append("purpose",n?.purpose??"user_data");let a=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:i,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Volcengine file upload error ${a.status}: ${d}`)}let c=await a.json();return{id:String(c.id??""),status:String(c.status??"")}}async getFile(e,t,n){let o=`${this.baseUrl}/v3/files/${e}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Volcengine get file error ${s.status}: ${i}`)}return await s.json()}async listFiles(e,t,n){let o=new URLSearchParams;t?.after&&o.set("after",t.after),t?.limit&&o.set("limit",String(t.limit)),t?.purpose&&o.set("purpose",t.purpose),t?.order&&o.set("order",t.order);let s=o.toString(),i=`${this.baseUrl}/v3/files${s?`?${s}`:""}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Volcengine list files error ${a.status}: ${c}`)}return await a.json()}async deleteFile(e,t,n){let o=`${this.baseUrl}/v3/files/${e}`,s=await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Volcengine delete file error ${s.status}: ${i}`)}}async submitTask(e,t,n,o){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${c}`)}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,o,s){let i=Date.now()+6e5,a=0;for(;Date.now()<i;){n?.throwIfAborted();let c=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Volcengine task poll error ${c.status}: ${m}`)}let d=await c.json(),l=d.status;if(l==="succeeded"||l==="complete")return o?.(100,"completed",s),d;if(l==="failed"||l==="cancelled"){let m=d.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${m}`)}a++;let u=Date.now()-(i-6e5),p=Math.min(95,Math.round(u/6e5*100));o?.(p,l??"running",s),await new Promise(m=>setTimeout(m,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as Zf,mkdirSync as eh}from"node:fs";import{join as cl}from"node:path";import{randomUUID as th}from"node:crypto";import{homedir as Yf}from"node:os";import{join as ne}from"node:path";import{existsSync as Hc,readdirSync as Jf,readFileSync as Qf}from"node:fs";var Se=".qlogicagent";function X(){return process.env.QLOGICAGENT_HOME||ne(Yf(),Se)}function xo(){return ne(X(),"sessions")}function Vc(r){return ne(xo(),r)}function zc(){return ne(X(),"plugins")}function ot(){return ne(X(),"skills")}function pt(){return ne(X(),"settings.json")}function Fe(){return ne(X(),"cache")}function Kc(){return ne(X(),"debug-logs")}function qc(r){let e=ne(X(),"checkpoints");return r?ne(e,r):e}function Xc(){return ne(X(),"plugin-cache")}function Yc(){return ne(X(),"mcp.json")}function Jc(){return ne(X(),"marketplace.json")}function Qc(){return ne(X(),"workflows")}function Zc(){return ne(X(),"rules")}function Be(r){return ne(r??process.cwd(),Se)}function el(r){return ne(Be(r),"workflows")}function rt(r){return ne(Be(r),"skills")}function tl(r){return ne(Be(r),"INSTRUCTIONS.md")}function nl(r){return ne(Be(r),"instructions")}function ol(r){return ne(Be(r),"plans")}function rl(r){return ne(Be(r),"rules")}function sl(r){return ne(Be(r),"sessions")}function il(r){return ne(r,Se,"hooks")}function al(r){let e=xo();if(!Hc(e))return[];let t=new Set;try{let n=Jf(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=ne(e,o.name,"state.json");try{let i=Qf(s,"utf8"),c=JSON.parse(i).metadata?.cwd;c&&c!==r&&Hc(ne(c,Se,"skills"))&&t.add(c)}catch{}}}catch{}return[...t]}var nh=18e4,yn=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??nh}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 o=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"};e.quality&&(i.quality=e.quality),e.style&&(i.style=e.style),e.background&&(i.background=e.background);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 l=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${l}`)}return{mediaUrls:((await a.json()).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-o}}async generateTTS(e,t,n){let o=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:e.voice??"alloy",response_format:e.audioFormat??"mp3"};e.speed!==void 0&&(a.speed=e.speed);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${c.status}: ${m}`)}let d=Buffer.from(await c.arrayBuffer()),l=cl(Fe(),"tts");eh(l,{recursive:!0});let u=`openai-tts-${th()}.mp3`,p=cl(l,u);return Zf(p,d),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-o,billingUnit:"per_character",billingQuantity:s.length}}};var At=class{supportedTypes=["music","video"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??6e4}async generate(e,t,n){switch(e.mediaType){case"music":return this.generateMusic(e,t,n);case"video":return this.generateVideo(e,t,n);default:throw new Error(`MiniMaxMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateMusic(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v1/music_generation`,i={model:e.model,prompt:e.prompt,output_format:"url"};e.lyrics&&(i.lyrics=e.lyrics),e.duration&&(i.duration=e.duration),(e.isInstrumental||!e.lyrics)&&(i.is_instrumental=!0),e.audioUrl&&(i.audio_url=e.audioUrl),e.lyricsOptimizer&&(i.lyrics_optimizer=!0),(e.audioFormat||e.voice)&&(i.audio_setting={sample_rate:44100,bitrate:256e3,format:e.audioFormat??"mp3"});let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(6e5)});if(!a.ok){let m=await a.text().catch(()=>"");throw new Error(`MiniMax music error ${a.status}: ${m}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax music rejected: ${c.base_resp.status_msg??"unknown"}`);let d=c.data?.audio??c.audio_file;if(d)return{mediaUrls:[d],model:e.model,durationMs:Date.now()-o};let l=c.task_id;if(!l)throw new Error("MiniMax music: no audio_file or task_id in response");let u=`${this.baseUrl}/v1/music_generation/${l}`;return{mediaUrls:(await this.pollTask(u,t,n,e.onProgress,l)).audioUrls,model:e.model,durationMs:Date.now()-o}}async pollTask(e,t,n,o,s){let i=Date.now()+6e5;for(;Date.now()<i;){n?.throwIfAborted();let a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`MiniMax music poll error ${a.status}: ${u}`)}let c=await a.json(),d=c.status;if(d==="Success"||d==="Finished"){o?.(100,"completed",s);let u=[];return c.audio_file&&u.push(c.audio_file),{audioUrls:u}}if(d==="Failed"||d==="Cancelled")throw new Error(`MiniMax music task failed: ${c.base_resp?.status_msg??"unknown"}`);let l=Date.now()-(i-6e5);o?.(Math.min(95,Math.round(l/6e5*100)),d??"running",s),await new Promise(u=>setTimeout(u,3e3))}throw new Error("MiniMax music task timed out after polling")}async generateLyrics(e,t,n){let o=`${this.baseUrl}/v1/lyrics_generation`,s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({prompt:e}),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`MiniMax lyrics API error ${s.status}: ${a}`)}let i=await s.json();if(i.base_resp?.status_code&&i.base_resp.status_code!==0)throw new Error(`MiniMax lyrics error: ${i.base_resp.status_msg??"unknown"}`);return i.data?.lyrics??""}async generateVideo(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v1/video_generation`,i={model:e.model||"S2V-01",prompt:e.prompt};if(e.referenceImages?.length&&e.imageRoles){let u=e.imageRoles.includes("first_frame"),p=e.imageRoles.includes("last_frame");if(u&&p){let m=e.imageRoles.indexOf("first_frame"),f=e.imageRoles.indexOf("last_frame");i.first_frame_image=e.referenceImages[m],i.last_frame_image=e.referenceImages[f]}else if(u){let m=e.imageRoles.indexOf("first_frame");i.first_frame_image=e.referenceImages[m]}else i.subject_reference=e.referenceImages.map((m,f)=>({type:"character",image:m}))}else e.imageUrl&&(i.first_frame_image=e.imageUrl);e.callbackUrl&&(i.callback_url=e.callbackUrl);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(`MiniMax video submit error ${a.status}: ${u}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax video rejected: ${c.base_resp.status_msg??"unknown"}`);let d=c.task_id;if(!d)throw new Error("MiniMax video: no task_id in response");let l=await this.pollVideoTask(d,t,n,e.onProgress);return{mediaUrls:l.downloadUrl?[l.downloadUrl]:[],model:e.model||"S2V-01",durationMs:Date.now()-o,taskId:d,metadata:{fileId:l.fileId,width:l.width,height:l.height}}}async pollVideoTask(e,t,n,o){let s=Date.now()+6e5;for(;Date.now()<s;){n?.throwIfAborted();let i=`${this.baseUrl}/v1/query/video_generation?task_id=${encodeURIComponent(e)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let m=await a.text().catch(()=>"");throw new Error(`MiniMax video poll error ${a.status}: ${m}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax video task error ${c.base_resp.status_code}: ${c.base_resp.status_msg??""}`);let d=c.status;if(d==="Success"){o?.(100,"completed",e);let m;if(c.file_id)try{m=await this.getFileDownloadUrl(c.file_id,t,n)}catch{}return{fileId:c.file_id,downloadUrl:m,width:c.video_width,height:c.video_height}}if(d==="Fail")throw new Error(`MiniMax video task failed: ${c.base_resp?.status_msg??"unknown"}`);let l=d??"running",u=Date.now()-(s-6e5),p=Math.min(95,Math.round(u/6e5*100));o?.(p,l,e),await new Promise(m=>setTimeout(m,3e3))}throw new Error("MiniMax video task timed out after polling")}async getFileDownloadUrl(e,t,n){let o=`${this.baseUrl}/v1/files/retrieve?file_id=${encodeURIComponent(e)}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`MiniMax file retrieve error ${s.status}: ${c}`)}let a=(await s.json()).file?.download_url;if(!a)throw new Error("MiniMax file retrieve: no download_url in response");return a}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/v1/query/video_generation?task_id=${encodeURIComponent(e)}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`MiniMax task status error ${s.status}: ${d}`)}let i=await s.json(),a=i.status??"unknown";return{status:a==="Success"?"succeeded":a==="Fail"?"failed":a.toLowerCase(),task:i}}async listVideoTasks(e,t,n){return{data:[]}}async deleteVideoTask(e,t,n){throw new Error("MiniMax does not support video task cancellation.")}};import{writeFileSync as dl,mkdirSync as ul}from"node:fs";import{join as Co}from"node:path";import{randomUUID as pl}from"node:crypto";import{writeFileSync as oh,mkdirSync as rh}from"node:fs";import{join as ll}from"node:path";import{randomUUID as sh}from"node:crypto";var Ao=class{ws=null;wsUrl;model="models/lyria-realtime-exp";onAudioChunk=null;onFilteredPrompt=null;onError=null;onClose=null;constructor(e){let t=e.baseUrl.replace(/\/+$/,""),n=new URL(t).origin.replace(/^http/,"ws");this.wsUrl=`${n}/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent`}async connect(e,t){t.model&&(this.model=t.model.startsWith("models/")?t.model:`models/${t.model}`);let n=`${this.wsUrl}?key=${encodeURIComponent(e)}`,o=new WebSocket(n);this.ws=o,await new Promise((s,i)=>{let a=()=>{o.removeEventListener("error",c),s()},c=()=>{o.removeEventListener("open",a),i(new Error("Lyria RealTime WebSocket connection failed"))};o.addEventListener("open",a,{once:!0}),o.addEventListener("error",c,{once:!0})}),o.addEventListener("message",s=>this.handleMessage(s)),o.addEventListener("error",()=>{this.onError?.(new Error("Lyria RealTime WebSocket error"))}),o.addEventListener("close",()=>{this.ws=null,this.onClose?.()}),this.send({setup:{model:this.model}}),await new Promise(s=>setTimeout(s,100)),await this.setWeightedPrompts(t.prompts),t.config&&await this.setMusicGenerationConfig(t.config)}async setWeightedPrompts(e){this.send({musicInput:{weightedPrompts:e.map(t=>({text:t.text,weight:t.weight}))}})}async setMusicGenerationConfig(e){let t={};e.bpm!==void 0&&(t.bpm=e.bpm),e.density!==void 0&&(t.density=e.density),e.brightness!==void 0&&(t.brightness=e.brightness),e.guidance!==void 0&&(t.guidance=e.guidance),e.scale!==void 0&&(t.scale=e.scale),e.temperature!==void 0&&(t.temperature=e.temperature),e.topK!==void 0&&(t.top_k=e.topK),e.seed!==void 0&&(t.seed=e.seed),e.muteBass!==void 0&&(t.mute_bass=e.muteBass),e.muteDrums!==void 0&&(t.mute_drums=e.muteDrums),e.onlyBassAndDrums!==void 0&&(t.only_bass_and_drums=e.onlyBassAndDrums),e.musicGenerationMode!==void 0&&(t.music_generation_mode=e.musicGenerationMode),e.audioFormat!==void 0&&(t.audio_format=e.audioFormat),e.sampleRateHz!==void 0&&(t.sample_rate_hz=e.sampleRateHz),this.send({musicInput:{musicGenerationConfig:t}})}async play(){this.send({musicInput:{playbackControl:"PLAY"}})}async pause(){this.send({musicInput:{playbackControl:"PAUSE"}})}async stop(){this.send({musicInput:{playbackControl:"STOP"}})}async resetContext(){this.send({musicInput:{playbackControl:"RESET_CONTEXT"}})}close(){this.ws&&this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=null}get connected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Lyria RealTime session not connected");this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(typeof e.data=="string"?e.data:e.data.toString())}catch{return}let n=t.serverContent;if(!n)return;let o=n.audioChunks;if(o&&this.onAudioChunk)for(let i of o)i.data&&this.onAudioChunk({data:Buffer.from(i.data,"base64")});let s=n.filteredPrompt;s&&this.onFilteredPrompt?.(s)}};async function ei(r,e,t){let n=t.durationSeconds??30,o=Date.now(),s=new Ao(e),i=[];s.onAudioChunk=c=>{i.push(c.data)};let a=null;s.onError=c=>{a=c};try{await s.connect(r,{model:t.model??"lyria-realtime-exp",prompts:t.prompts,config:t.musicConfig}),t.onProgress?.(5,"connected"),await s.play(),t.onProgress?.(10,"streaming");let c=Date.now()+n*1e3,d=500;for(;Date.now()<c;){if(t.signal?.throwIfAborted(),a)throw a;if(!s.connected)break;let g=Date.now()-o,y=n*1e3,b=Math.min(95,Math.round(10+g/y*85));t.onProgress?.(b,"streaming"),await new Promise(k=>setTimeout(k,d))}s.connected&&await s.stop(),t.onProgress?.(98,"assembling");let l=Buffer.concat(i),u=ih(l,48e3,2,16),p=ll(Fe(),"gemini-music-realtime");rh(p,{recursive:!0});let m=`lyria-rt-${sh()}.wav`,f=ll(p,m);return oh(f,u),t.onProgress?.(100,"completed"),{filePath:`file://${f}`,durationMs:Date.now()-o}}finally{s.close()}}function ih(r,e,t,n){let o=e*t*(n/8),s=t*(n/8),i=r.length,a=Buffer.alloc(44);return a.write("RIFF",0),a.writeUInt32LE(36+i,4),a.write("WAVE",8),a.write("fmt ",12),a.writeUInt32LE(16,16),a.writeUInt16LE(1,20),a.writeUInt16LE(t,22),a.writeUInt32LE(e,24),a.writeUInt32LE(o,28),a.writeUInt16LE(s,30),a.writeUInt16LE(n,32),a.write("data",36),a.writeUInt32LE(i,40),Buffer.concat([a,r])}var ah=18e4,ch=1e4,ti=6e5,bn=class{supportedTypes=["image","video","music","music_realtime","tts","embedding"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??ah}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"music":return this.generateMusic(e,t,n);case"music_realtime":return this.generateMusicRealtime(e,t,n);case"tts":return this.generateTTS(e,t,n);case"embedding":return this.generateEmbedding(e,t,n);default:throw new Error(`GeminiMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async deleteVideoTask(e,t,n){throw new Error("Gemini does not support deleting video generation tasks")}async listVideoTasks(e,t,n){return{data:[]}}async getTaskStatus(e,t,n){let o=`${this.apiBase}/${e}`,s=await fetch(o,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Gemini operation query error ${s.status}: ${c}`)}let i=await s.json();return{status:i.done?"completed":"running",task:i}}async generateImage(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={responseModalities:["TEXT","IMAGE"]};e.aspectRatio&&(i.aspectRatio=e.aspectRatio);let a={contents:[{parts:[{text:e.prompt}]}],generationConfig:i},c=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineImages(c),model:e.model,durationMs:Date.now()-o}}async generateVideo(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:predictLongRunning`,i={prompt:e.prompt};e.imageUrl&&(i.image={inlineData:await this.resolveImageData(e.imageUrl)}),e.referenceImages?.length&&(i.referenceImages=await Promise.all(e.referenceImages.map(async y=>({image:{inlineData:await this.resolveImageData(y)},referenceType:"asset"}))));let a={};e.aspectRatio&&(a.aspectRatio=e.aspectRatio),e.resolution&&(a.resolution=e.resolution),e.duration&&(a.durationSeconds=String(e.duration)),e.n&&(a.numberOfVideos=e.n),e.seed!==void 0&&(a.seed=e.seed);let c={instances:[i]};Object.keys(a).length>0&&(c.parameters=a);let l=(await this.postJson(s,c,t,n)).name;if(!l)throw new Error("Gemini video submit: no operation name in response");let u=l;e.onProgress?.(5,"submitted",u);let f=(await this.pollOperation(l,t,n,e.onProgress,u)).response?.generateVideoResponse?.generatedSamples??[],g=[];for(let y of f)y.video?.uri&&g.push(y.video.uri);return{mediaUrls:g,model:e.model,durationMs:Date.now()-o,taskId:u}}async generateMusic(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i=[{text:e.prompt}],a={};e.audioFormat==="wav"&&(a.responseModalities=["AUDIO","TEXT"],a.responseFormat={audio:{mimeType:"audio/wav"}});let c={contents:[{parts:i}]};Object.keys(a).length>0&&(c.generationConfig=a);let d=await this.postJson(s,c,t,n);return{mediaUrls:this.extractInlineAudio(d,"gemini-music"),model:e.model,durationMs:Date.now()-o}}async generateMusicRealtime(e,t,n){let o=await ei(t,{baseUrl:this.apiBase},{prompts:[{text:e.prompt,weight:1}],durationSeconds:e.duration??30,musicConfig:{audioFormat:e.audioFormat==="wav"?"pcm16":void 0,sampleRateHz:48e3},model:e.model,signal:n,onProgress:e.onProgress});return{mediaUrls:[o.filePath],model:e.model,durationMs:o.durationMs}}async generateTTS(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={responseModalities:["AUDIO"]};e.voice&&(i.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}});let a={contents:[{parts:[{text:e.text??e.prompt}]}],generationConfig:i},c=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineAudio(c,"gemini-tts"),model:e.model,durationMs:Date.now()-o}}async generateEmbedding(e,t,n){let o=Date.now(),s=`${this.apiBase}/models/${e.model}:embedContent`,i={content:{parts:[{text:e.text??e.prompt}]}},a=e.metadata?.outputDimensionality;a!==void 0&&(i.output_dimensionality=a);let d=(await this.postJson(s,i,t,n)).embeddings?.[0]?.values??[];return{mediaUrls:[],model:e.model,durationMs:Date.now()-o,metadata:{embedding:d,dimensions:d.length}}}async postJson(e,t,n,o){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":n},body:JSON.stringify(t),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini API error ${s.status}: ${i}`)}return s.json()}async pollOperation(e,t,n,o,s){let i=Date.now()+ti;for(;Date.now()<i;){n?.throwIfAborted();let a=`${this.apiBase}/${e}`,c=await fetch(a,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`Gemini operation poll error ${c.status}: ${p}`)}let d=await c.json();if(d.done===!0)return o?.(100,"completed",s),d;if(d.error){let p=d.error;throw new Error(`Gemini video generation failed: ${p.message??JSON.stringify(p)}`)}let l=Date.now()-(i-ti),u=Math.min(95,Math.round(l/ti*100));o?.(u,"running",s),await new Promise(p=>setTimeout(p,ch))}throw new Error("Gemini video generation timed out after polling")}async resolveImageData(e){if(e.startsWith("data:")){let s=e.match(/^data:([^;]+);base64,(.+)$/);if(s)return{mimeType:s[1],data:s[2]}}if(e.startsWith("file://")){let{readFileSync:s}=await import("node:fs"),i=e.replace(/^file:\/\//,""),a=s(i).toString("base64"),c=i.split(".").pop()?.toLowerCase()??"png";return{mimeType:c==="jpg"||c==="jpeg"?"image/jpeg":c==="webp"?"image/webp":"image/png",data:a}}let t=await fetch(e,{signal:AbortSignal.timeout(6e4)});if(!t.ok)throw new Error(`Failed to fetch image ${e}: ${t.status}`);let n=Buffer.from(await t.arrayBuffer());return{mimeType:t.headers.get("content-type")??"image/png",data:n.toString("base64")}}extractInlineImages(e){let t=[],n=Co(Fe(),"gemini-images");ul(n,{recursive:!0});for(let o of e.candidates??[])for(let s of o.content?.parts??[])if(s.inlineData?.data){let i=s.inlineData.mimeType==="image/png"?"png":s.inlineData.mimeType==="image/webp"?"webp":"jpg",a=`gemini-${pl()}.${i}`,c=Co(n,a);dl(c,Buffer.from(s.inlineData.data,"base64")),t.push(`file://${c}`)}return t}extractInlineAudio(e,t){let n=[],o=Co(Fe(),t);ul(o,{recursive:!0});for(let s of e.candidates??[])for(let i of s.content?.parts??[])if(i.inlineData?.data&&i.inlineData.mimeType?.startsWith("audio/")){let a=i.inlineData.mimeType.includes("wav")?"wav":i.inlineData.mimeType.includes("mpeg")||i.inlineData.mimeType.includes("mp3")?"mp3":"pcm",c=Buffer.from(i.inlineData.data,"base64"),d=a==="pcm"?lh(c,24e3,1,16):c,l=`gemini-${pl()}.${a==="pcm"?"wav":a}`,u=Co(o,l);dl(u,d),n.push(`file://${u}`)}return n}};function lh(r,e,t,n){let o=e*t*(n/8),s=t*(n/8),i=r.length,a=Buffer.alloc(44);return a.write("RIFF",0),a.writeUInt32LE(36+i,4),a.write("WAVE",8),a.write("fmt ",12),a.writeUInt32LE(16,16),a.writeUInt16LE(1,20),a.writeUInt16LE(t,22),a.writeUInt32LE(e,24),a.writeUInt32LE(o,28),a.writeUInt16LE(s,30),a.writeUInt16LE(n,32),a.write("data",36),a.writeUInt32LE(i,40),Buffer.concat([a,r])}var Po=class{supportedTypes=["tts","video"];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==="video")return this.generateVideo(e,t,n);if(e.mediaType!=="tts")throw new Error(`QwenMediaTransport: unsupported mediaType "${e.mediaType}"`);let o=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={format:e.audioFormat??"mp3",sample_rate:24e3},c={text:s};e.voice&&(c.voice=e.voice),e.speed!==void 0&&(a.speech_rate=e.speed);let d={model:e.model||"qwen3-tts-voicedesign",input:c,parameters:a},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(d),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let f=await l.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${l.status}: ${f}`)}let u=await l.json();if(u.code)throw new Error(`DashScope TTS submit rejected: ${u.code} \u2014 ${u.message??""}`);let p=u.output?.task_id;if(!p)throw new Error("DashScope TTS submit: no task_id in response");if(u.output?.task_status==="SUCCEEDED"){let f=this.extractMediaUrl(u);return{mediaUrls:f?[f]:[],model:e.model,durationMs:Date.now()-o}}return{mediaUrls:await this.pollTask(p,t,n,e.onProgress),model:e.model,durationMs:Date.now()-o}}async pollTask(e,t,n,o,s=12e4){let i=Date.now()+s,a=`${this.baseUrl}/api/v1/tasks/${e}`;for(;Date.now()<i;){n?.throwIfAborted(),await dh(2e3);let c=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${c.status}: ${p}`)}let d=await c.json();if(d.code)throw new Error(`DashScope poll rejected: ${d.code} \u2014 ${d.message??""}`);let l=d.output?.task_status;if(l==="SUCCEEDED"){o?.(100,"completed",e);let p=this.extractMediaUrl(d);return p?[p]:[]}if(l==="FAILED")throw new Error(`DashScope task failed: ${d.message??"unknown error"}`);let u=Date.now()-(i-s);o?.(Math.min(95,Math.round(u/s*100)),l??"running",e)}throw new Error("DashScope task timed out")}async generateVideo(e,t,n){let o=Date.now(),s=e.model||"wan2.1-t2v-turbo",i={prompt:e.prompt};if(e.imageUrl)i.img_url=e.imageUrl;else if(e.referenceImages?.length)if(e.imageRoles){let f=e.imageRoles.indexOf("first_frame"),g=e.imageRoles.indexOf("last_frame");f>=0&&(i.img_url=e.referenceImages[f]),g>=0&&(i.tail_image_url=e.referenceImages[g]);let y=e.imageRoles.map((b,k)=>b==="reference_image"?k:-1).filter(b=>b>=0);y.length>0&&(i.ref_image_url=e.referenceImages[y[0]])}else i.img_url=e.referenceImages[0];let a={};e.duration&&(a.duration=e.duration),e.resolution&&(a.resolution=e.resolution),e.aspectRatio&&(a.ratio=e.aspectRatio),e.metadata?.size&&(a.size=e.metadata.size);let c=`${this.baseUrl}/api/v1/services/aigc/generation/generation`,d={model:s,input:i};Object.keys(a).length>0&&(d.parameters=a);let l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(d),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let f=await l.text().catch(()=>"");throw new Error(`DashScope video submit error ${l.status}: ${f}`)}let u=await l.json();if(u.code)throw new Error(`DashScope video submit rejected: ${u.code} \u2014 ${u.message??""}`);let p=u.output?.task_id;if(!p)throw new Error("DashScope video submit: no task_id in response");return{mediaUrls:await this.pollTask(p,t,n,e.onProgress,6e5),model:s,durationMs:Date.now()-o,taskId:p}}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/api/v1/tasks/${e}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`DashScope task status error ${s.status}: ${l}`)}let i=await s.json(),c=i.output?.task_status??"unknown";return{status:c==="SUCCEEDED"?"succeeded":c==="FAILED"?"failed":c.toLowerCase(),task:i}}async listVideoTasks(e,t,n){let o=new URLSearchParams;o.set("page_size",String(t?.limit??20)),t?.status&&o.set("status",t.status.toUpperCase());let s=`${this.baseUrl}/api/v1/tasks?${o.toString()}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n??AbortSignal.timeout(this.timeoutMs)});return i.ok?await i.json():{data:[]}}async deleteVideoTask(e,t,n){throw new Error("DashScope does not support task cancellation.")}extractMediaUrl(e){if(e.output?.video_url)return e.output.video_url;if(e.output?.audio_url)return e.output.audio_url;if(e.output?.results?.[0]?.url)return e.output.results[0].url}};function dh(r){return new Promise(e=>setTimeout(e,r))}import{writeFileSync as uh,mkdirSync as ph}from"node:fs";import{join as ml}from"node:path";import{randomUUID as mh}from"node:crypto";var gh=18e4,fh=3e3,Io=6e5,hh=new Set(["glm-image"]),kn=class{supportedTypes=["image","video","tts","stt","embedding","voice_clone","document_parsing","rerank"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??gh}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"tts":return this.generateTTS(e,t,n);case"stt":return this.generateSTT(e,t,n);case"embedding":return this.generateEmbedding(e,t,n);case"voice_clone":return this.generateVoiceClone(e,t,n);case"document_parsing":return this.generateDocumentParsing(e,t,n);case"rerank":return this.generateRerank(e,t,n);default:throw new Error(`ZhipuMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateImage(e,t,n){return hh.has(e.model)?this.generateImageAsync(e,t,n):this.generateImageSync(e,t,n)}async generateImageSync(e,t,n){let o=Date.now(),s=`${this.baseUrl}/images/generations`,i={model:e.model,prompt:e.prompt};return e.size&&(i.size=e.size),e.quality&&e.model.startsWith("cogview-4")&&(i.quality=e.quality),{mediaUrls:((await this.postJSON(s,i,t,n)).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size,durationMs:Date.now()-o}}async generateImageAsync(e,t,n){let o=Date.now(),s=`${this.baseUrl}/async/images/generations`,i={model:e.model,prompt:e.prompt};e.size&&(i.size=e.size),e.quality&&(i.quality=e.quality);let c=(await this.postJSON(s,i,t,n)).id;if(!c)throw new Error("Zhipu async image: no task id in response");return{mediaUrls:((await this.pollAsyncResult(c,t,n,e.onProgress)).data??[]).map(p=>p.url).filter(p=>!!p),model:e.model,size:e.size,durationMs:Date.now()-o}}async generateVideo(e,t,n){let o=Date.now(),s=`${this.baseUrl}/videos/generations`,i={model:e.model,prompt:e.prompt};e.imageUrl&&(i.image_url=e.imageUrl),e.size&&(i.size=e.size),e.duration&&(i.duration=e.duration);let c=(await this.postJSON(s,i,t,n)).id;if(!c)throw new Error("Zhipu video generation: no task id in response");return{mediaUrls:((await this.pollAsyncResult(c,t,n,e.onProgress)).video_result??[]).map(p=>p.url).filter(p=>!!p),model:e.model,durationMs:Date.now()-o}}async generateTTS(e,t,n){let o=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: text or prompt required for TTS");let i=`${this.baseUrl}/audio/speech`,a={model:e.model||"glm-tts",input:s};e.voice&&(a.voice=e.voice),e.speed!==void 0&&(a.speed=e.speed),e.audioFormat&&(a.response_format=e.audioFormat);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let f=await c.text().catch(()=>"");throw new Error(`Zhipu TTS API error ${c.status}: ${f}`)}let d=Buffer.from(await c.arrayBuffer()),l=ml(Fe(),"tts");ph(l,{recursive:!0});let u=e.audioFormat??"wav",p=`zhipu-tts-${mh()}.${u}`,m=ml(l,p);return uh(m,d),{mediaUrls:[`file://${m}`],model:e.model||"glm-tts",durationMs:Date.now()-o,billingUnit:"per_character",billingQuantity:s.length}}async generateSTT(e,t,n){let o=Date.now();if(!e.audioUrl)throw new Error("ZhipuMediaTransport: audioUrl required for STT");let s=`${this.baseUrl}/audio/transcriptions`,i=await fetch(e.audioUrl,{headers:{"User-Agent":"qlogicagent/1.0"},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok)throw new Error(`Failed to fetch audio from ${e.audioUrl}`);let a=await i.blob(),c=new FormData;c.append("model",e.model||"glm-asr-2512"),c.append("file",a,"audio.wav");let d=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:c,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`Zhipu STT API error ${d.status}: ${u}`)}let l=await d.json();return{mediaUrls:[],model:e.model||"glm-asr-2512",durationMs:Date.now()-o,metadata:{transcription:l.text??""}}}async generateEmbedding(e,t,n){let o=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: text or prompt required for embedding");let i=`${this.baseUrl}/embeddings`,a={model:e.model||"embedding-3",input:s},d=(await this.postJSON(i,a,t,n)).data??[];return{mediaUrls:[],model:e.model||"embedding-3",durationMs:Date.now()-o,metadata:{embeddings:d.map(l=>l.embedding).filter(Boolean)}}}async generateVoiceClone(e,t,n){let o=Date.now();if(!e.audioUrl)throw new Error("ZhipuMediaTransport: audioUrl required for voice_clone (sample audio)");let s=await fetch(e.audioUrl,{signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`Failed to fetch audio sample from ${e.audioUrl}`);let i=await s.blob(),a=new FormData;a.append("model",e.model||"glm-tts-clone"),a.append("file",i,"sample.wav"),(e.text||e.prompt)&&a.append("text",e.text||e.prompt||"");let c=`${this.baseUrl}/voice/clone`,d=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:a,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let p=await d.text().catch(()=>"");throw new Error(`Zhipu Voice Clone API error ${d.status}: ${p}`)}let l=await d.json();return{mediaUrls:(l.data??[]).map(p=>p.url).filter(p=>!!p),model:e.model||"glm-tts-clone",durationMs:Date.now()-o,metadata:{voiceId:l.voice_id}}}async generateDocumentParsing(e,t,n){let o=Date.now(),s=e.imageUrl||e.audioUrl;if(!s&&!e.prompt)throw new Error("ZhipuMediaTransport: imageUrl/audioUrl (file URL) or prompt (base64) required for document_parsing");let i=`${this.baseUrl}/layout_parsing`,a={model:e.model||"glm-ocr"};s?a.file_url=s:e.prompt&&(a.content=e.prompt);let l=(await this.postJSON(i,a,t,n)).pages??[];return{mediaUrls:[],model:e.model||"glm-ocr",durationMs:Date.now()-o,metadata:{pages:l.map(u=>({pageNum:u.page_num,content:u.content,layouts:u.layouts}))}}}async generateRerank(e,t,n){let o=Date.now(),s=e.prompt;if(!s)throw new Error("ZhipuMediaTransport: prompt (query) required for rerank");if(!e.metadata?.documents)throw new Error("ZhipuMediaTransport: metadata.documents required for rerank");let i=`${this.baseUrl}/rerank`,a={model:e.model||"rerank",query:s,documents:e.metadata.documents};e.metadata.topN!==void 0&&(a.top_n=e.metadata.topN);let c=await this.postJSON(i,a,t,n);return{mediaUrls:[],model:e.model||"rerank",durationMs:Date.now()-o,metadata:{results:(c.results??[]).map(d=>({index:d.index,relevanceScore:d.relevance_score,document:d.document}))}}}async postJSON(e,t,n,o){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Zhipu API error ${s.status}: ${i}`)}return s.json()}async pollAsyncResult(e,t,n,o){let s=Date.now()+Io,i=`${this.baseUrl}/async-result/${encodeURIComponent(e)}`;for(;Date.now()<s;){n?.throwIfAborted();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Zhipu async-result error ${a.status}: ${l}`)}let c=await a.json();if(c.task_status==="SUCCESS")return o?.(100,"completed",e),c;if(c.task_status==="FAIL")throw new Error("Zhipu async task failed");let d=Date.now()-(s-Io);o?.(Math.min(95,Math.round(d/Io*100)),c.task_status??"running",e),await new Promise(l=>setTimeout(l,fh))}throw new Error(`Zhipu async task timed out after ${Io/1e3}s`)}async getTaskStatus(e,t,n){let o=`${this.baseUrl}/async-result/${encodeURIComponent(e)}`,s=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`Zhipu task query error ${s.status}: ${d}`)}let i=await s.json(),a=i.task_status??"unknown";return{status:a==="SUCCESS"?"succeeded":a==="FAIL"?"failed":a==="PROCESSING"?"running":a.toLowerCase(),task:i}}async listVideoTasks(e,t,n){return{data:[]}}async deleteVideoTask(e,t,n){throw new Error("Zhipu does not support task cancellation. Tasks complete or timeout automatically.")}async listVoices(e,t){let n=`${this.baseUrl}/voice/`,o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:t??AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let i=await o.text().catch(()=>"");throw new Error(`Zhipu voice list error ${o.status}: ${i}`)}return(await o.json()).data??[]}async deleteVoice(e,t,n){let o=`${this.baseUrl}/voice/${encodeURIComponent(e)}`,s=await fetch(o,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Zhipu voice delete error ${s.status}: ${i}`)}}};var Tn=class{registry;transports=new Map;constructor(e){this.registry=e.registry}resolveModelById(e,t,n){let o=this.registry.getProvider(e);if(!o)return;let i=this.registry.listModels(e).find(a=>a.id===t&&a.mediaType===n);if(i)return{providerId:e,providerDef:o,modelInfo:i,mediaType:n}}getTransport(e){let t=this.transports.get(e);if(t)return t;let n=this.registry.getProvider(e);if(!n)return;let o=kh(n);if(o)return this.transports.set(e,o),o}listMediaModels(e){let t=[];for(let n of this.registry.listProviders()){let o=this.registry.listModels(n.id);for(let s of o)s.mediaType&&(!e||s.mediaType===e)&&t.push({providerId:n.id,providerDef:n,modelInfo:s,mediaType:s.mediaType})}return t}findModelInProvider(e,t,n){let o=this.registry.getProvider(e);if(!o)return;let s=this.registry.listModels(e),i=n?yh(n):void 0,a=s.find(c=>c.mediaType!==t?!1:!i||!c.mediaCapabilities?!0:bh(c.mediaCapabilities,i));if(a)return{providerId:e,providerDef:o,modelInfo:a,mediaType:t}}};function yh(r){switch(r.mediaType){case"video":return r.operation==="merge"?"merge":r.operation==="upscale"?"upscale":r.operation==="edit"?"edit":r.imageUrl?"img2video":"text2video";case"image":return r.operation==="edit"?"inpainting":r.imageUrl?"img2img":"text2image";case"music":return r.audioUrl?"cover":"text2music";case"music_realtime":return"realtime";case"tts":return"text2speech";case"3d":return r.imageUrl?"img2_3d":"text2_3d";default:return}}function bh(r,e){return!("operations"in r)||!r.operations?!0:r.operations.includes(e)}function kh(r){let e=r.baseUrl;switch(r.id){case"volcengine":return new je({baseUrl:e});case"openai":return new yn({baseUrl:e});case"minimax":return new At({baseUrl:e});case"google":return new bn({baseUrl:e});case"qwen":return new Po({baseUrl:e});case"zhipu":return new kn({baseUrl:e.replace(/\/api\/anthropic\/?$/,"/api/paas/v4")});case"zhipu-openai":case"zhipu-coding":return new kn({baseUrl:e.replace(/\/api\/coding\/paas\/v4\/?$/,"/api/paas/v4")});default:return}}var ni=[{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",quirks:{useEffortInsteadOfBudget:!0,filterImageBlocks:!0,maxReasoningEffort:"max",supportsPrefixCompletion:!0},models:[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28,costCacheRead:.003},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:1.74,costOutput:3.48,costCacheRead:.014}]},{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-max-preview",name:"Qwen3.6 Max (Preview)",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:2,costOutput:8,costCacheRead:.2,costCacheWrite:2.5},{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.6-flash",name:"Qwen3.6 Flash",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.1,costOutput:.5,costCacheRead:.01,costCacheWrite:.125},{id:"qwq-plus",name:"QwQ Plus",contextWindow:131072,maxOutput:65536,toolCall:!0,reasoning:!0,reasoningRequired:!0,streamRequired:!0,vision:!1,costInput:.5,costOutput:3,costCacheRead:.05,costCacheWrite:.625},{id:"qwen-max",name:"Qwen Max",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:2,costOutput:6,costCacheRead:.2,costCacheWrite:2.5},{id:"qwen-plus",name:"Qwen Plus",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:.85,costCacheRead:.03,costCacheWrite:.375},{id:"qwen-flash",name:"Qwen Flash",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1},{id:"qwen-turbo",name:"Qwen Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!1},{id:"qwen-vl-max",name:"Qwen VL Max",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:3,costOutput:8.5},{id:"qwen3.5-omni-plus",name:"Qwen3.5 Omni Plus",contextWindow:131072,maxOutput:16384,toolCall:!1,reasoning:!1,streamRequired:!0,vision:!0},{id:"qwen-vl-ocr",name:"Qwen VL OCR",contextWindow:131072,maxOutput:4096,toolCall:!1,reasoning:!1,vision:!0,mediaType:"document_parsing",mediaCapabilities:{type:"document_parsing",supportedFormats:["jpg","jpeg","png","bmp","tiff","pdf"],maxFileSizeMB:10}},{id:"qwen3-tts-voicedesign",name:"Qwen3 TTS VoiceDesign",contextWindow:32768,maxOutput:16384,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],maxCharacters:32768,formats:["mp3","wav"]}},{id:"cosyvoice-v2",name:"CosyVoice V2",contextWindow:1e4,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],maxCharacters:1e4,formats:["mp3","wav","pcm"]}},{id:"wan2.7-image-pro",name:"Wan 2.7 Image Pro",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","1280x720","720x1280","2048x2048","3840x2160"]}},{id:"wanx2.1-t2i-turbo",name:"Wan 2.1 Text-to-Image Turbo",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","720x1280","1280x720"]}},{id:"wan2.7-t2v-plus",name:"Wan 2.7 Text/Image-to-Video Plus",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:15,resolutions:["720P","1080P"]}},{id:"wanx2.1-t2v-turbo",name:"Wan 2.1 Text/Image-to-Video Turbo",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:5,resolutions:["480P","720P"]}},{id:"text-embedding-v4",name:"Text Embedding V4",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:1024,maxTokens:8192}},{id:"wanx-background-generation-v2",name:"Wan Background Generation V2",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["inpainting"],sizes:["1024x1024","1280x720","720x1280"]}},{id:"qwen3-rerank",name:"Qwen3 Rerank",contextWindow:32768,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"rerank",mediaCapabilities:{type:"rerank",maxDocuments:100}}]},{id:"zhipu",name:"\u667A\u8C31 GLM (Zhipu)",group:"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.1",quirks:{filterThinkingBlocks:!0},models:[{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:"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-turbo",name:"GLM-5 Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1,costCacheRead:.1},{id:"glm-4.7",name:"GLM-4.7",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.6",name:"GLM-4.6",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.5-air",name:"GLM-4.5 Air",contextWindow:131072,maxOutput:98304,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1.5,costCacheRead:.1},{id:"glm-4-long",name:"GLM-4 Long",contextWindow:1e6,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.1,costOutput:.1},{id:"glm-4.7-flash",name:"GLM-4.7 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-4.5-flash",name:"GLM-4.5 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-5v-turbo",name:"GLM-5V Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:1},{id:"glm-4.6v",name:"GLM-4.6V",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:3.2},{id:"glm-4.6v-flash",name:"GLM-4.6V Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:0,costOutput:0},{id:"cogview-4-250304",name:"CogView-4",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","768x1344","864x1152","1344x768","1152x864","1440x720","720x1440"]}},{id:"cogview-3-flash",name:"CogView-3 Flash (Free)",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024","768x1344","864x1152","1344x768","1152x864","1440x720","720x1440"]}},{id:"glm-image",name:"GLM-Image",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1280x1280","1568x1056","1056x1568","1472x1088","1088x1472","1728x960","960x1728"]}},{id:"cogvideox-3",name:"CogVideoX-3",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["1080p"]}},{id:"cogvideox-flash",name:"CogVideoX Flash (Free)",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:6}},{id:"glm-tts",name:"GLM-TTS",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],voices:["tongtong","chuichui","xiaochen","jam","kazi","douji","luodo"],maxCharacters:1024,formats:["wav","pcm"]}},{id:"glm-tts-clone",name:"GLM-TTS Clone",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"voice_clone",mediaCapabilities:{type:"voice_clone",maxSampleDurationSeconds:30,maxSampleSizeMB:10,formats:["wav","mp3"]}},{id:"glm-asr-2512",name:"GLM-ASR-2512",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"stt",mediaCapabilities:{type:"stt",languages:["zh","en"],maxDurationSeconds:30,formats:["wav","mp3"]}},{id:"embedding-3",name:"Embedding-3",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:2048,maxTokens:3072}},{id:"embedding-2",name:"Embedding-2",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:1024,maxTokens:512}},{id:"rerank",name:"GLM Rerank",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"rerank",mediaCapabilities:{type:"rerank",maxDocuments:128,maxQueryLength:4096,maxDocumentLength:4096}},{id:"glm-ocr",name:"GLM-OCR",contextWindow:0,maxOutput:0,toolCall:!1,reasoning:!1,vision:!1,mediaType:"document_parsing",mediaCapabilities:{type:"document_parsing",supportedFormats:["pdf","jpg","png"],maxPageCount:100,maxFileSizeMB:50}}]},{id:"zhipu-openai",name:"\u667A\u8C31 GLM OpenAI (Zhipu)",group:"zhipu",transport:"openai-chat",baseUrl:"https://open.bigmodel.cn/api/paas/v4",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"glm-5.1",quirks:{supportsReasoningEffort:!0,supportsThinkingParam:!0,supportsToolStream:!0,builtinWebSearch:!0,builtinCodeInterpreter:!0},models:[{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:"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-turbo",name:"GLM-5 Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1,costCacheRead:.1},{id:"glm-4.7",name:"GLM-4.7",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.6",name:"GLM-4.6",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-4.5-air",name:"GLM-4.5 Air",contextWindow:131072,maxOutput:98304,toolCall:!0,reasoning:!0,vision:!1,costInput:.5,costOutput:1.5,costCacheRead:.1},{id:"glm-4-long",name:"GLM-4 Long",contextWindow:1e6,maxOutput:4096,toolCall:!0,reasoning:!1,vision:!1,costInput:.1,costOutput:.1},{id:"glm-4.7-flash",name:"GLM-4.7 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-4.5-flash",name:"GLM-4.5 Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:0,costOutput:0},{id:"glm-5v-turbo",name:"GLM-5V Turbo",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:1},{id:"glm-4.6v",name:"GLM-4.6V",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:3.2},{id:"glm-4.6v-flash",name:"GLM-4.6V Flash (Free)",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!1,vision:!0,costInput:0,costOutput:0}]},{id:"zhipu-coding",name:"\u667A\u8C31 GLM Coding (Zhipu)",group:"zhipu",transport:"openai-chat",baseUrl:"https://open.bigmodel.cn/api/coding/paas/v4",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"codegeex-4",quirks:{supportsReasoningEffort:!0,supportsThinkingParam:!0,supportsToolStream:!0},models:[{id:"codegeex-4",name:"CodeGeeX-4",contextWindow:131072,maxOutput:16384,toolCall:!0,reasoning:!0,vision:!1,costInput:.1,costOutput:.1}]},{id:"minimax",name:"MiniMax",group:"minimax",transport:"anthropic-messages",baseUrl:"https://api.minimaxi.com/anthropic",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"MiniMax-M2.7",omitZeroTemperature:!0,quirks:{filterImageBlocks:!0},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:"MiniMax-M2.7-highspeed",name:"MiniMax M2.7 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2,costCacheRead:.06,costCacheWrite:.375},{id:"MiniMax-M2.5",name:"MiniMax M2.5",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6,costCacheRead:.03,costCacheWrite:.19},{id:"MiniMax-M2.5-highspeed",name:"MiniMax M2.5 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6,costCacheRead:.03,costCacheWrite:.19},{id:"MiniMax-M2.1",name:"MiniMax M2.1 (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.1-highspeed",name:"MiniMax M2.1 Highspeed (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2",name:"MiniMax M2 (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.1,costOutput:.4},{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",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:300,formats:["mp3","wav"]}},{id:"music-cover",name:"MiniMax Music Cover",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"music",mediaCapabilities:{type:"music",operations:["cover"],maxDurationSeconds:300,formats:["mp3","wav"]}},{id:"MiniMax-Hailuo-2.3",name:"Hailuo 2.3",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["768P","1080P"]}},{id:"MiniMax-Hailuo-2.3-Fast",name:"Hailuo 2.3 Fast",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["768P","1080P"]}},{id:"MiniMax-Hailuo-02",name:"Hailuo 02",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:10,resolutions:["512P","768P","1080P"]}},{id:"image-01",name:"MiniMax Image 01",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["512x512","1024x1024","2048x2048"]}},{id:"image-01-live",name:"MiniMax Image 01 Live",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image"],sizes:["1024x1024"]}},{id:"speech-2.8-hd",name:"MiniMax Speech 2.8 HD",contextWindow:1e4,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],formats:["mp3","pcm","flac","wav","opus"]}},{id:"speech-2.8-turbo",name:"MiniMax Speech 2.8 Turbo",contextWindow:1e4,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech","voice_clone"],formats:["mp3","pcm","flac","wav","opus"]}}]},{id:"minimax-openai",name:"MiniMax (OpenAI)",group:"minimax",transport:"openai-chat",baseUrl:"https://api.minimaxi.com/v1",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"bearer",isAggregator:!1,omitZeroTemperature:!0,defaultModel:"MiniMax-M2.7",quirks:{supportsReasoningSplit:!0},models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2},{id:"MiniMax-M2.7-highspeed",name:"MiniMax M2.7 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2},{id:"MiniMax-M2.5",name:"MiniMax M2.5",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.5-highspeed",name:"MiniMax M2.5 Highspeed",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.1",name:"MiniMax M2.1 (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6},{id:"MiniMax-M2.1-highspeed",name:"MiniMax M2.1 Highspeed (legacy)",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!1,vision:!1,costInput:.15,costOutput:.6}]},{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",quirks:{supportsReasoningEffort:!0,supportsThinkingParam:!0,builtinWebSearch:!0},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:"kimi-k2.5",name:"Kimi K2.5",contextWindow:262144,maxOutput:262144,toolCall:!0,reasoning:!0,vision:!0,costInput:.8,costOutput:4,costCacheRead:.2},{id:"moonshot-v1-128k",name:"Moonshot V1 128K",contextWindow:131072,maxOutput:8192,toolCall:!0,reasoning:!1,vision:!1,costInput:.84,costOutput:.84}]},{id:"volcengine",name:"\u8C46\u5305 (Doubao/Volcengine)",transport:"volcengine-responses",baseUrl:"https://ark.cn-beijing.volces.com/api",apiKeyEnvVars:["ARK_API_KEY","DOUBAO_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"doubao-seed-2-0-lite-260215",models:[{id:"doubao-seed-2-0-pro-260215",name:"Doubao Seed 2.0 Pro",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-lite-260428",name:"Doubao Seed 2.0 Lite (0428)",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-lite-260215",name:"Doubao Seed 2.0 Lite",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-mini-260428",name:"Doubao Seed 2.0 Mini (0428)",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-mini-260215",name:"Doubao Seed 2.0 Mini",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-2-0-code-preview-260215",name:"Doubao Seed 2.0 Code Preview",contextWindow:262144,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{id:"doubao-seed-1-8-251228",name:"Doubao Seed 1.8",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:0,costOutput:0},{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",mediaCapabilities:{type:"video",operations:["text2video","img2video","video2video","edit","merge","upscale"],maxDurationSeconds:15,resolutions:["480p","720p","1080p"],aspectRatios:["16:9","9:16","1:1"],fps:[24]}},{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",mediaCapabilities:{type:"video",operations:["text2video","img2video","video2video","edit","merge","upscale"],maxDurationSeconds:15,resolutions:["480p","720p"],aspectRatios:["16:9","9:16","1:1"],fps:[24]}},{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",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["512x512","1024x1024","2K"]}},{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",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["512x512","1024x1024","2K"]}},{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",mediaCapabilities:{type:"3d",operations:["img2_3d"],outputFormats:["glb","obj","usd","usdz"]}},{id:"hyper3d-gen2-260112",name:"Hyper3D Gen2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d",mediaCapabilities:{type:"3d",operations:["text2_3d","img2_3d"],outputFormats:["glb","obj"]}},{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",mediaCapabilities:{type:"3d",operations:["img2_3d"],outputFormats:["glb","obj","usd"]}}]},{id:"openai",name:"OpenAI",transport:"openai-responses",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-5.5",quirks:{builtinWebSearch:!0,builtinCodeInterpreter:!0,builtinFileSearch:!0},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:"gpt-5.4-nano",name:"GPT-5.4 Nano",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.2,costOutput:1.25,costCacheRead:.02},{id:"gpt-image-2",name:"GPT Image 2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img","inpainting"],sizes:["1024x1024","1536x1024","1024x1536","auto"],transparentBackground:!0}},{id:"gpt-realtime-2",name:"GPT Realtime 2",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!0,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}},{id:"gpt-realtime-translate",name:"GPT Realtime Translate",contextWindow:128e3,maxOutput:16e3,toolCall:!1,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!1}},{id:"gpt-realtime-1.5",name:"GPT Realtime 1.5",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}},{id:"gpt-realtime-mini",name:"GPT Realtime Mini",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}}]},{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",quirks:{supportsDocumentVision:!0},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:"gemini-generatecontent",baseUrl:"https://generativelanguage.googleapis.com/v1beta",apiKeyEnvVars:["GOOGLE_API_KEY","GEMINI_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"gemini-3-flash-preview",quirks:{builtinWebSearch:!0,builtinCodeInterpreter:!0,builtinUrlContext:!0,builtinMapsGrounding:!0,builtinFileSearch:!0,supportsDocumentVision:!0},models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,reasoningRequired:!0,vision:!0,costInput:2,costOutput:12},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:3},{id:"gemini-3.1-flash-lite",name:"Gemini 3.1 Flash-Lite",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.25,costOutput:1.5},{id:"gemini-3.1-flash-image-preview",name:"Gemini 3.1 Flash Image (Nano Banana 2)",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}},{id:"gemini-3-pro-image-preview",name:"Gemini 3 Pro Image (Nano Banana Pro)",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}},{id:"veo-3.1-generate-preview",name:"Veo 3.1 Standard",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P","4K"]}},{id:"veo-3.1-fast-generate-preview",name:"Veo 3.1 Fast",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P","4K"]}},{id:"veo-3.1-lite-generate-preview",name:"Veo 3.1 Lite",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P"]}},{id:"lyria-3-pro-preview",name:"Lyria 3 Pro",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:300,formats:["mp3"]}},{id:"lyria-3-clip-preview",name:"Lyria 3 Clip",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:30,formats:["mp3"]}},{id:"lyria-realtime-exp",name:"Lyria RealTime (Experimental)",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music_realtime",mediaCapabilities:{type:"music",operations:["realtime"],formats:["wav"]}},{id:"gemini-3.1-flash-tts-preview",name:"Gemini 3.1 Flash TTS",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:1,costOutput:20,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],maxCharacters:8e3,formats:["mp3","wav"]}},{id:"gemini-embedding-2",name:"Gemini Embedding 2 (Multimodal)",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:.2,costOutput:0,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:3072,maxTokens:8192}}]},{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}]}];import{existsSync as Th,mkdirSync as wh,readFileSync as vh,writeFileSync as Sh}from"node:fs";import{join as Rh}from"node:path";var _h="https://models.dev/api.json",xh=3e4,Ah=1440*60*1e3,Ch=300*1e3,Ph={deepseek:"deepseek",qwen:"qwen","qwen-coding-plan":"qwen-coding","alibaba-cn":"qwen",zhipuai:"zhipu",minimax:"minimax",moonshot:"moonshot",moonshotai:"moonshot",doubao:"volcengine","bytedance-seed":"volcengine",volcengine:"volcengine",openai:"openai",anthropic:"anthropic",google:"google",openrouter:"openrouter"},wn=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??Fe(),this.cacheFile=Rh(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??Ah}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(!Th(this.cacheFile))return;let e=vh(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:gl(t.data)}}catch{}}saveToDisk(e){try{wh(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);Sh(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<Ch||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(_h,{signal:AbortSignal.timeout(xh),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=gl(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function gl(r){let e=new Map;if(!r||typeof r!="object")return e;for(let[t,n]of Object.entries(r)){let o=Ph[t];if(!o||!n||typeof n!="object")continue;let i=n.models;if(!i||typeof i!="object")continue;let a=e.get(o);a||(a={models:new Map},e.set(o,a));for(let[c,d]of Object.entries(i)){if(!d||typeof d!="object"||a.models.has(c))continue;let l=d,u=l.cost??{},p=l.limit??{},m=l.modalities??{},f=Array.isArray(m.input)?m.input:[],g=Array.isArray(m.output)?m.output:[],y=Ih(g,f,c);a.models.set(c,{id:c,name:typeof l.name=="string"?l.name:c,contextWindow:typeof p.context=="number"?p.context:2e5,maxOutput:typeof p.output=="number"?p.output:8192,toolCall:l.tool_call===!0,reasoning:l.reasoning===!0,vision:l.attachment===!0||f.includes("image"),costInput:typeof u.input=="number"?u.input:void 0,costOutput:typeof u.output=="number"?u.output:void 0,costCacheRead:typeof u.cache_read=="number"?u.cache_read:void 0,costCacheWrite:typeof u.cache_write=="number"?u.cache_write:void 0,mediaType:y})}}return e}function Ih(r,e,t){if(r.includes("video"))return"video";if(r.includes("image")&&!r.includes("text"))return"image";if(r.includes("audio")&&!r.includes("text"))return"tts";if(r.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 Mh={claude:"anthropic",gemini:"google",doubao:"volcengine"},zt=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of ni)this.builtins.set(t.id,t);this.catalog=e?.catalog??new wn}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=Mh[e]??e,n=this.builtins.get(t),o=this.overrides.get(t);if(!(!n&&!o))return!n&&o?!o.id||!o.transport||!o.baseUrl?void 0:{id:o.id,name:o.name??o.id,transport:o.transport,baseUrl:o.baseUrl,apiKeyEnvVars:o.apiKeyEnvVars??[],authType:o.authType??"bearer",isAggregator:o.isAggregator??!1,defaultModel:o.defaultModel,models:o.models}:n&&!o?n:{...n,...o,models:o.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??[],o=this.catalog.getModels(e);if(o.length===0)return n;let s=new Map;for(let i of o)s.set(i.id,i);for(let i of n)s.set(i.id,i);return[...s.values()]}getModelInfo(e,t){return this.listModels(e).find(n=>n.id===t)}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,t){if(t)return t;let n=this.getProvider(e);if(n)for(let o of n.apiKeyEnvVars){let s=process.env[o];if(s?.trim())return s.trim()}}};ye();var Eh={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".avif":"image/avif",".heic":"image/heic",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".aac":"audio/aac",".flac":"audio/flac",".m4a":"audio/mp4",".opus":"audio/opus",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".json":"application/json"};function Oh(r){let e=r.slice(r.lastIndexOf(".")).toLowerCase();return Eh[e]||"application/octet-stream"}var Dh=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i;function Lh(r){return Dh.test(r)}async function fl(r,e,t,n){if(r.startsWith("data:")||!Lh(r))return r;let o=await fetch(r,{signal:n});if(!o.ok)throw new Error(`Failed to fetch local media ${r}: ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),i=Nh(r),a=o.headers.get("content-type")||Oh(i);return(await e.uploadFile(s,i,a,t,n)).url}function Nh(r){try{let t=new URL(r).pathname.split("/").pop();return t&&t.includes(".")?t:"upload"}catch{return"upload"}}var Uh=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i;function G(r){return Uh.test(r)}async function We(r,e){return fl(r,e.uploadAdapter,e.apiKey,e.signal)}var $h=20*1024*1024;async function Mo(r,e){if(r.startsWith("data:")||!G(r))return r;let t=await fetch(r);if(!t.ok)throw new Error(`Failed to fetch local media ${r}: ${t.status}`);let n=Buffer.from(await t.arrayBuffer());if(n.byteLength>$h)throw new Error(`Local media too large for base64 (${(n.byteLength/1024/1024).toFixed(1)}MB). Use file upload API instead.`);return`data:${t.headers.get("content-type")||e||jh(r)};base64,${n.toString("base64")}`}function jh(r){let e=r.split("?")[0].split("#")[0],t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".avif":"image/avif",".heic":"image/heic",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".aac":"audio/aac",".flac":"audio/flac",".m4a":"audio/mp4",".opus":"audio/opus",".pdf":"application/pdf"}[t]||"application/octet-stream"}var oi=new Set([429,529,502,503,504]),Xe=9e4;function Ye(r){let e=Math.min(1e3*Math.pow(2,r-1),3e4),t=Math.random()*.25*e;return e+t}function st(r){return r!=null&&oi.has(r)}function Je(r,e){return new Promise((t,n)=>{if(e?.aborted){n(new Error("Request aborted"));return}let o=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(o),n(new Error("Request aborted"))},{once:!0})})}function it(r){if(r&&typeof r=="object"){let e=r;if(typeof e.status=="number")return e.status;if(typeof e.statusCode=="number")return e.statusCode;if(e.response&&typeof e.response.status=="number")return e.response.status}return null}function Eo(r){return r.toLowerCase().startsWith("gpt-5")}function Oo(r){return r.toLowerCase().includes("5.4-nano")}function vn(r){return/^o[1-4](-|$)/.test(r.toLowerCase())}var Kt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;quirks;fileUploadAdapter;cumulativeReasoningLen=0;cumulativeContentLen=0;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,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){this.cumulativeReasoningLen=0,this.cumulativeContentLen=0;let o=e.prefixMessage&&this.quirks.supportsPrefixCompletion,s=/\/v\d+$/.test(this.baseUrl),i;o?i=`${this.baseUrl}/beta/v1/chat/completions`:s?i=`${this.baseUrl}/chat/completions`:i=`${this.baseUrl}/v1/chat/completions`;let a={model:e.model,messages:Wh(await Bh(e.messages,this.fileUploadAdapter,t,n),this.quirks),stream:!0};this.supportsStreamOptions&&(a.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(a.tools=e.tools,e.toolChoice&&(a.tool_choice=e.toolChoice));let c=!e.disableBuiltinTools,d=!1;if(c&&this.quirks.builtinWebSearch&&a.tools){let g=a.tools;this.quirks.builtinCodeInterpreter?g.push({type:"web_search",web_search:{enable:!0,search_result:!0}}):(g.push({type:"builtin_function",function:{name:"$web_search"}}),d=!0)}c&&this.quirks.builtinCodeInterpreter&&a.tools&&a.tools.push({type:"code_interpreter",code_interpreter:{sandbox:"none"}}),this.quirks.supportsToolStream&&a.tools&&(a.tool_stream=!0);let l=this.quirks.useEffortInsteadOfBudget&&!!e.reasoning,u=e.model.startsWith("kimi-k2.6"),p=Eo(e.model);if(e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p||!vn(e.model)&&!l&&!u)&&(a.temperature=e.temperature)),e.topP!==void 0&&(p||!vn(e.model)&&!l&&!u)&&(a.top_p=e.topP),e.maxTokens!==void 0&&(p||vn(e.model)||e.model.startsWith("kimi-k2")?a.max_completion_tokens=e.maxTokens:a.max_tokens=e.maxTokens),e.reasoning)if(p){let g=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;Oo(e.model)&&(g==="high"||g==="xhigh")&&(g="medium"),a.reasoning={effort:g}}else if(vn(e.model))a.reasoning_effort=e.reasoning.effort;else if(this.quirks.useEffortInsteadOfBudget){a.thinking={type:"enabled"};let g=this.quirks.maxReasoningEffort??"high",y=e.reasoning.effort??"high";a.reasoning_effort=y==="low"||y==="medium"?"high":g}else this.quirks.supportsThinkingParam?(d?a.thinking={type:"disabled"}:this.quirks.supportsToolStream?a.thinking={type:"enabled",clear_thinking:!1}:a.thinking={type:"enabled"},this.quirks.supportsReasoningEffort&&(a.reasoning_effort=e.reasoning.effort)):this.quirks.supportsReasoningEffort?a.reasoning_effort=e.reasoning.effort:a.reasoning=e.reasoning;else d&&(a.thinking={type:"disabled"});e.structuredOutput&&(e.structuredOutput.mode==="json_object"?a.response_format={type:"json_object"}:e.structuredOutput.mode==="json_schema"&&(a.response_format={type:"json_schema",json_schema:{name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}})),this.quirks.supportsReasoningSplit&&e.reasoning&&(a.reasoning_split=!0),e.prediction&&p&&(a.prediction=e.prediction),o&&e.prefixMessage&&a.messages.push({role:"assistant",content:e.prefixMessage,prefix:!0});let m={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},f=null;for(let g=0;g<=3;g++){if(n?.aborted)throw new Error("Request aborted");g>0&&f&&await Je(Ye(g),n);try{yield*this.fetchAndStream(i,m,a,n);return}catch(y){f=y instanceof Error?y:new Error(String(y));let b=f.message.includes("Stream idle timeout");if(!st(it(f))&&!b||g===3)throw f}}}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`LLM API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("LLM API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStreamWithWatchdog(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();t.usage&&(yield{type:"usage",promptTokens:t.usage.prompt_tokens??0,completionTokens:t.usage.completion_tokens??0,reasoningTokens:t.usage.completion_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.prompt_tokens_details?.cached_tokens});for(let n of t.choices??[]){let o=n.message;if(o){if(o.reasoning_content&&(yield{type:"reasoning_delta",text:o.reasoning_content}),o.content&&(yield{type:"delta",text:o.content}),o.tool_calls)for(let s=0;s<o.tool_calls.length;s++){let i=o.tool_calls[s];yield{type:"tool_call_delta",index:s,id:i.id,name:i.function.name,arguments:i.function.arguments}}n.finish_reason&&(yield{type:"done",finishReason:n.finish_reason})}}}async*parseSSEStreamWithWatchdog(e){let t=new TextDecoder,n="",o=null,s=new AbortController,i=()=>{o&&clearTimeout(o),o=setTimeout(()=>{s.abort()},Xe)};try{i();let a=e.getReader();try{for(;;){let{done:c,value:d}=await a.read();if(c)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(d,{stream:!0});let l;for(;(l=n.indexOf(`
35
+ `))!==-1;){let u=n.slice(0,l).trim();if(n=n.slice(l+1),!u||u.startsWith(":")||!u.startsWith("data: "))continue;let p=u.slice(6);if(p==="[DONE]")return;let m;try{m=JSON.parse(p)}catch{continue}yield*this.processChunk(m)}}}finally{a.releaseLock()}}finally{o&&clearTimeout(o)}}*processChunk(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,cacheReadTokens:e.usage.prompt_tokens_details?.cached_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.reasoning_details){let o=n.reasoning_details.slice(this.cumulativeReasoningLen);o&&(this.cumulativeReasoningLen=n.reasoning_details.length,yield{type:"reasoning_delta",text:o})}if(n.content)if(this.quirks.supportsReasoningSplit){let o=n.content.slice(this.cumulativeContentLen);o&&(this.cumulativeContentLen=n.content.length,yield{type:"delta",text:o})}else yield{type:"delta",text:n.content};if(n.tool_calls)for(let o of n.tool_calls)yield{type:"tool_call_delta",index:o.index,id:o.id,name:o.function?.name,arguments:o.function?.arguments??""};t.finish_reason&&(yield{type:"done",finishReason:Fh(t.finish_reason)})}}}async*complete(e,t,n){if(!this.quirks.supportsPrefixCompletion)throw new Error("FIM completion is not supported by this provider");let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/beta/completions`:`${this.baseUrl}/beta/v1/completions`,i={model:e.model,prompt:e.prompt,stream:!0,max_tokens:e.maxTokens??4096};e.suffix&&(i.suffix=e.suffix),e.temperature!==void 0&&(i.temperature=e.temperature),e.stop&&(i.stop=e.stop);let a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},c=AbortSignal.timeout(this.timeoutMs),d=n?AbortSignal.any([n,c]):c,l=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(i),signal:d});if(!l.ok){let f=await l.text().catch(()=>"");throw new Error(`FIM API error ${l.status}: ${f.slice(0,500)}`)}if(!l.body)throw new Error("FIM API returned no response body");let u=new TextDecoder,p="",m=l.body.getReader();try{for(;;){let{done:f,value:g}=await m.read();if(f)break;p+=u.decode(g,{stream:!0});let y;for(;(y=p.indexOf(`
36
+ `))!==-1;){let b=p.slice(0,y).trim();if(p=p.slice(y+1),!b||b.startsWith(":")||!b.startsWith("data: "))continue;let k=b.slice(6);if(k==="[DONE]")return;let S;try{S=JSON.parse(k)}catch{continue}for(let R of S.choices??[])R.text&&(yield{type:"delta",text:R.text}),R.finish_reason&&(yield{type:"done",finishReason:R.finish_reason})}}}finally{m.releaseLock()}}async uploadFile(e,t,n,o,s){let a=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/files`:`${this.baseUrl}/v1/files`,c=new FormData;c.append("file",e,t),c.append("purpose",n);let d=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`,...this.extraHeaders},body:c,signal:s??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let u=await d.text().catch(()=>"");throw new Error(`File upload error ${d.status}: ${u}`)}let l=await d.json();return{fileId:l.id??"",filename:l.filename??t,bytes:l.bytes??0}}async getFileInfo(e,t,n){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/files/${encodeURIComponent(e)}`:`${this.baseUrl}/v1/files/${encodeURIComponent(e)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${t}`,...this.extraHeaders},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`File info error ${i.status}: ${c}`)}let a=await i.json();return{id:a.id??e,filename:a.filename??"",bytes:a.bytes??0,status:a.status??"unknown"}}};function Fh(r){switch(r){case"sensitive":return"content_filter";case"model_context_window_exceeded":return"length";case"network_error":return"error";default:return r}}async function Bh(r,e,t,n){return r.some(s=>s.audioUrls?.some(G)||s.imageUrls?.some(G))?Promise.all(r.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.role==="user"&&s.audioUrls?.some(G)&&(i.audioUrls=await Promise.all(s.audioUrls.map(a=>G(a)?Mo(a):Promise.resolve(a)))),s.imageUrls?.some(G)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>G(a)?We(a,{uploadAdapter:e,apiKey:t,signal:n}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):r}function Wh(r,e){return r.map(t=>{if(t.role==="user"){let n=t.imageUrls&&t.imageUrls.length>0&&!e.filterImageBlocks,o=t.videoUrls&&t.videoUrls.length>0,s=t.audioUrls&&t.audioUrls.length>0,i=t.fileIds&&t.fileIds.length>0;if(n||o||s||i){let c=[];if(t.content&&c.push({type:"text",text:t.content}),n){let d=t.imageUrls.length>1;for(let l=0;l<t.imageUrls.length;l++){let u=t.imageUrls[l];d&&c.push({type:"text",text:`[Image ${l+1}]`});let p={url:u};t.imageDetail&&(p.detail=t.imageDetail),c.push({type:"image_url",image_url:p})}}if(o)for(let d of t.videoUrls)c.push({type:"video_url",video_url:{url:d}});if(s)for(let d of t.audioUrls){let l=d,u=t.audioFormat??"mp3";if(d.startsWith("data:")){let p=/^data:audio\/([^;]+);base64,(.+)$/.exec(d);p&&(u=p[1]==="mpeg"?"mp3":p[1],l=p[2])}c.push({type:"input_audio",input_audio:{data:l,format:u}})}if(i)for(let d of t.fileIds){let l=d.mimeType||"";if(d.size!=null&&d.size>$e){let p=`${(d.size/1048576).toFixed(1)}MB`;c.push({type:"text",text:`[Attached: ${d.id} (${l||"unknown"}, ${p}) \u9225?file too large for direct vision, use tools to process]`})}else if(e.supportsDocumentVision&&(l==="application/pdf"||d.id.endsWith(".pdf")))d.id.startsWith("http://")||d.id.startsWith("https://")?c.push({type:"text",text:`[Attached PDF: ${d.id}]`}):c.push({type:"file",file:{file_id:d.id}});else if(d.id.startsWith("http://")||d.id.startsWith("https://")){let p=l?`[Attached: ${d.id} (${l})]`:`[Attached: ${d.id}]`;c.push({type:"text",text:p})}else c.push({type:"file",file:{file_id:d.id}})}return{role:"user",content:c}}return{role:"user",content:t.content??""}}if(t.role==="assistant"){let n={role:"assistant"};return t.thinkingBlocks&&t.thinkingBlocks.length>0&&(n.reasoning_content=t.thinkingBlocks.map(o=>o.thinking).join("")),n.content=t.content??null,t.tool_calls&&t.tool_calls.length>0&&(n.tool_calls=t.tool_calls.map(o=>({id:o.id,type:o.type,function:{name:o.function.name,arguments:o.function.arguments}}))),n}if(t.role==="tool"){if(t.imageUrls&&t.imageUrls.length>0&&!e.filterImageBlocks){let n=[];t.content&&n.push({type:"text",text:t.content});for(let o of t.imageUrls)n.push({type:"image_url",image_url:{url:o}});return{role:"tool",content:n,tool_call_id:t.tool_call_id??""}}return{role:"tool",content:t.content??"",tool_call_id:t.tool_call_id??""}}return{role:t.role,content:t.content??""}})}ye();var Do=class{baseUrl;extraHeaders;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("OpenAIResponsesTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/responses`:`${this.baseUrl}/v1/responses`,i=await this.buildRequestBody(e,t,n),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},c=null;for(let d=0;d<=3;d++){if(n?.aborted)throw new Error("Request aborted");d>0&&c&&await Je(Ye(d),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(l){c=l instanceof Error?l:new Error(String(l));let u=c.message.includes("Stream idle timeout");if(!st(it(c))&&!u||d===3)throw c}}}async buildRequestBody(e,t,n){let o={model:e.model,input:Hh(await Gh(e.messages,this.fileUploadAdapter,t,n),this.quirks),stream:!0};if(e.conversationId?o.conversation=e.conversationId:e.previousResponseId&&(o.previous_response_id=e.previousResponseId),e.store!==void 0&&(o.store=e.store),e.instructions&&(o.instructions=e.instructions),e.structuredOutput&&(e.structuredOutput.mode==="json_object"?o.text={format:{type:"json_object"}}:o.text={format:{type:"json_schema",name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}}),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(s=>({type:"function",name:s.function.name,description:s.function.description,parameters:s.function.parameters,strict:!0}))),e.toolChoice!==void 0&&(typeof e.toolChoice=="string"?o.tool_choice=e.toolChoice:o.tool_choice={type:e.toolChoice.type,name:e.toolChoice.name}),e.temperature!==void 0&&(o.temperature=e.temperature),e.topP!==void 0&&(o.top_p=e.topP),e.maxTokens!==void 0&&(o.max_output_tokens=e.maxTokens),e.reasoning){let s=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;Oo(e.model)&&(s==="high"||s==="xhigh")&&(s="medium");let i={effort:s};i.summary="auto",i.generate_summary="auto",o.reasoning=i}if(e.prediction&&Eo(e.model)&&(o.prediction=e.prediction),o.truncation="auto",e.promptCacheKey&&(o.prompt_cache_key=e.promptCacheKey),e.promptCacheRetention&&(o.prompt_cache_retention=e.promptCacheRetention),e.serviceTier&&(o.service_tier=e.serviceTier),e.reasoning?.includeEncryptedReasoning&&(e.store===void 0&&(o.store=!1),o.include=["reasoning.encrypted_content"]),e.contextManagement&&(o.context_management=e.contextManagement.edits.map(s=>{let i={type:s.type};return s.type==="clear_thinking"&&s.keep!==void 0?i.keep=s.keep:s.type==="clear_tool_uses"&&(s.trigger&&(i.trigger=s.trigger),s.keep&&(i.keep=s.keep),s.excludeTools&&(i.exclude_tools=s.excludeTools),s.clearToolInput!==void 0&&(i.clear_tool_input=s.clearToolInput)),i})),!e.disableBuiltinTools){let s=o.tools??[],i=o.include??[];if(e.openaiBuiltinTools&&e.openaiBuiltinTools.length>0){for(let c of e.openaiBuiltinTools)s.push({...c});let a=new Set(e.openaiBuiltinTools.map(c=>c.type));a.has("web_search_preview")&&i.push("web_search_call.action.sources"),a.has("file_search")&&i.push("file_search_call.results"),a.has("code_interpreter")&&i.push("code_interpreter_call.outputs"),a.has("computer_use_preview")&&i.push("computer_call_output.output.image_url")}else this.quirks.builtinWebSearch&&(s.push({type:"web_search_preview"}),i.push("web_search_call.action.sources")),this.quirks.builtinCodeInterpreter&&(s.push({type:"code_interpreter"}),i.push("code_interpreter_call.outputs")),this.quirks.builtinFileSearch&&(s.push({type:"file_search"}),i.push("file_search_call.results"));s.length>0&&(o.tools=s),i.length>0&&(o.include=i)}if(e.maxToolCalls!==void 0&&(o.max_tool_calls=e.maxToolCalls),e.parallelToolCalls!==void 0&&(o.parallel_tool_calls=e.parallelToolCalls),e.textVerbosity){let s=o.text??{};s.verbosity=e.textVerbosity,o.text=s}return o}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`OpenAI Responses API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("OpenAI Responses API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStream(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();if(t.id&&(yield{type:"response_id",id:t.id}),t.usage&&(yield{type:"usage",promptTokens:t.usage.input_tokens??0,completionTokens:t.usage.output_tokens??0,reasoningTokens:t.usage.output_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.input_tokens_details?.cached_tokens}),t.output)for(let n of t.output){if(n.type==="message"&&n.content)for(let o of n.content)o.type==="output_text"&&(yield{type:"delta",text:o.text??""},o.annotations&&o.annotations.length>0&&(yield{type:"annotations",annotations:o.annotations.map(s=>({...s,type:s.type??"url_citation",url:s.url,title:s.title}))}));if(n.type==="reasoning"&&n.summary)for(let o of n.summary)o.type==="summary_text"&&(yield{type:"reasoning_delta",text:o.text??""});n.type==="function_call"&&(yield{type:"tool_call_delta",index:0,id:n.call_id,name:n.name,arguments:n.arguments??""})}yield{type:"done",finishReason:t.status==="completed"?"stop":t.status??"stop"}}async*parseSSEStream(e){let t=new TextDecoder,n="",o="",s=null,i=new AbortController,a=0,c=new Map,d=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},Xe)};try{d();let l=e.getReader();try{for(;;){let{done:u,value:p}=await l.read();if(u)break;if(i.signal.aborted)throw new Error("Stream idle timeout");d(),n+=t.decode(p,{stream:!0});let m;for(;(m=n.indexOf(`
37
+ `))!==-1;){let f=n.slice(0,m).trim();if(n=n.slice(m+1),!f){o="";continue}if(!f.startsWith(":")){if(f.startsWith("event:")){o=f.slice(6).trim();continue}if(f.startsWith("data:")){let g=f.slice(5).trim();if(g==="[DONE]")return;let y;try{y=JSON.parse(g)}catch{continue}yield*this.processEvent(o,y,c,()=>a++)}}}}}finally{l.releaseLock()}}finally{s&&clearTimeout(s)}}*processEvent(e,t,n,o){switch(e){case"response.output_text.delta":{let s=t.delta;s&&(yield{type:"delta",text:s});break}case"response.reasoning_summary_text.delta":{let s=t.delta;s&&(yield{type:"reasoning_delta",text:s});break}case"response.function_call_arguments.delta":{let s=t.delta,i=t.call_id,a=t.name;if(s!==void 0&&i){let c=n.get(i);c===void 0&&(c=o(),n.set(i,c)),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:s}}break}case"response.output_item.added":{let s=t.item;if(s&&s.type==="function_call"){let i=s.call_id,a=s.name;if(i&&!n.has(i)){let c=o();n.set(i,c),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:""}}}break}case"response.function_call_arguments.done":break;case"response.content_part.done":{let s=t.part;if(s?.type==="output_text"){let i=s.annotations;i&&i.length>0&&(yield{type:"annotations",annotations:i.map(a=>({type:a.type??"url_citation",url:a.url,title:a.title,...a}))})}break}case"response.output_item.done":{let s=t.item;if(s?.type==="message"){let i=s.content;if(i)for(let a of i){let c=a.annotations;c&&c.length>0&&(yield{type:"annotations",annotations:c.map(d=>({type:d.type??"url_citation",url:d.url,title:d.title,...d}))})}}break}case"response.completed":{let s=t.response;if(s){let i=s.id;i&&(yield{type:"response_id",id:i});let a=s.usage;if(a){let d=a.input_tokens_details,l=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:l?.reasoning_tokens,cacheReadTokens:d?.cached_tokens}}yield{type:"done",finishReason:s.status==="incomplete"?"tool_calls":"stop"}}else yield{type:"done",finishReason:"stop"};break}case"response.failed":{yield{type:"error",message:t.response?.error?.message??"Unknown error"},yield{type:"done",finishReason:"error"};break}default:{e.startsWith("response.web_search_call")&&(yield{type:"builtin_tool_status",toolType:"web_search",event:e,data:t});break}}}};async function Gh(r,e,t,n){return r.some(s=>s.audioUrls?.some(G)||s.imageUrls?.some(G))?Promise.all(r.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.role==="user"&&s.audioUrls?.some(G)&&(i.audioUrls=await Promise.all(s.audioUrls.map(a=>G(a)?Mo(a):Promise.resolve(a)))),s.imageUrls?.some(G)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>G(a)?We(a,{uploadAdapter:e,apiKey:t,signal:n}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):r}function Hh(r,e={}){let t=[];for(let n of r){if(n.role==="system"){t.push({role:"developer",content:n.content??""});continue}if(n.role==="user"){let o=n.imageUrls&&n.imageUrls.length>0,s=n.videoUrls&&n.videoUrls.length>0,i=n.audioUrls&&n.audioUrls.length>0,a=n.fileIds&&n.fileIds.length>0;if(o||s||i||a){let d=[];if(o){let l=n.imageUrls.length>1;for(let u=0;u<n.imageUrls.length;u++){let p=n.imageUrls[u];l&&d.push({type:"input_text",text:`[Image ${u+1}]`});let m={type:"input_image",image_url:p};n.imageDetail&&(m.detail=n.imageDetail),d.push(m)}}if(s)for(let l of n.videoUrls)d.push({type:"input_video",video_url:l});if(i)for(let l of n.audioUrls){let u=l,p=n.audioFormat??"mp3";if(l.startsWith("data:")){let m=/^data:audio\/([^;]+);base64,(.+)$/.exec(l);m&&(p=m[1]==="mpeg"?"mp3":m[1],u=m[2])}d.push({type:"input_audio",data:u,format:p})}if(a)for(let l of n.fileIds){let u=l.mimeType||"";if(l.size!=null&&l.size>$e){let m=`${(l.size/1048576).toFixed(1)}MB`;d.push({type:"input_text",text:`[Attached: ${l.id} (${u||"unknown"}, ${m}) \u2014 file too large for direct vision, use tools to process]`})}else if(e.supportsDocumentVision&&(u==="application/pdf"||l.id.endsWith(".pdf")))l.id.startsWith("http://")||l.id.startsWith("https://")?d.push({type:"input_text",text:`[Attached PDF: ${l.id}]`}):d.push({type:"input_file",file_id:l.id});else if(l.id.startsWith("http://")||l.id.startsWith("https://")){let m=u?`[Attached: ${l.id} (${u})]`:`[Attached: ${l.id}]`;d.push({type:"input_text",text:m})}else d.push({type:"input_file",file_id:l.id})}n.content&&d.push({type:"input_text",text:n.content}),t.push({role:"user",content:d})}else t.push({role:"user",content:n.content??""});continue}if(n.role==="assistant"){if(n.content&&t.push({role:"assistant",content:n.content}),n.tool_calls&&n.tool_calls.length>0)for(let o of n.tool_calls)t.push({type:"function_call",call_id:o.id,name:o.function.name,arguments:o.function.arguments});continue}if(n.role==="tool"){if(!n.tool_call_id)continue;if(n.imageUrls&&n.imageUrls.length>0){let o=[];n.content&&o.push({type:"input_text",text:n.content});for(let s of n.imageUrls)o.push({type:"input_image",image_url:s});t.push({type:"function_call_output",call_id:n.tool_call_id,output:o})}else t.push({type:"function_call_output",call_id:n.tool_call_id,output:n.content??""});continue}}return t}ye();var Vh=18e4,zh=3e5,Kh=64e3,qh="[Tool execution failed; output not available during conversation recovery]",Xh="interleaved-thinking-2025-05-14",Yh="context-1m-2025-08-07",Jh="token-efficient-tools-2026-03-28",Qh="prompt-caching-scope-2026-01-05",Zh="pdfs-2024-09-25";function ey(r){let e=r.toLowerCase();return e.includes("opus-4-6")||e.includes("opus-4-7")||e.includes("sonnet-4-6")}function ty(r,e,t){let n=[],o=r.toLowerCase();if(!o.startsWith("claude")){let c=process.env.ANTHROPIC_BETAS;if(c)for(let d of c.split(",").map(l=>l.trim()).filter(Boolean))n.push(d);return n}(o.includes("opus-4-6")||o.includes("opus-4-7")||o.includes("sonnet-4-6"))&&n.push(Yh),n.push(Zh),e&&!o.includes("haiku")&&n.push(Xh),t&&n.push(Jh),n.push(Qh);let a=process.env.ANTHROPIC_BETAS;if(a)for(let c of a.split(",").map(d=>d.trim()).filter(Boolean))n.includes(c)||n.push(c);return n}var Sn=class{baseUrl;apiVersion;timeoutMs;streamIdleTimeoutMs;enablePromptCaching;maxRetries;omitZeroTemperature;quirks;fileUploadAdapter;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??Vh,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??Xe,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3,this.omitZeroTemperature=e.omitZeroTemperature??!1,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let o=`${this.baseUrl}/v1/messages`,s=sy(e.messages),i=await iy(s,this.fileUploadAdapter,t,n),{system:a,messages:c}=ay(i,this.quirks,e.model),d=ry(a,this.enablePromptCaching),l=!!e.reasoning,u=e.maxTokens??8192,p={model:e.model,messages:c,max_tokens:l?Math.max(u,4096):u,stream:!0};if(d&&(p.system=d),e.tools&&e.tools.length>0){let y=e.tools.map(cy);this.enablePromptCaching&&y.length>0&&(y[y.length-1].cache_control={type:"ephemeral"}),p.tools=y,e.toolChoice&&(p.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})}if(!l&&e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p.temperature=e.temperature)),!l&&e.topP!==void 0&&(p.top_p=e.topP),l)if(this.quirks.useEffortInsteadOfBudget){p.thinking={type:"enabled"};let y=this.quirks.maxReasoningEffort??"high",b=e.reasoning?.effort??"high",k=b==="low"||b==="medium"?"high":y;if(p.output_config={effort:k},a){let S=2166136261;for(let R=0;R<a.length;R++)S^=a.charCodeAt(R),S=Math.imul(S,16777619);p.metadata={user_id:`qa-${(S>>>0).toString(36)}`}}}else if(ey(e.model))p.thinking={type:"adaptive"};else{let y=oy(e.reasoning.effort,e.maxTokens);p.thinking={type:"enabled",budget_tokens:Math.min(u-1,y)}}let m=ty(e.model,l,(e.tools?.length??0)>0),f={"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion};m.length>0&&(f["anthropic-beta"]=m.join(","));let g=null;for(let y=0;y<=this.maxRetries;y++){if(n?.aborted)throw new Error("Request aborted");y>0&&g&&await Je(Ye(y),n);try{yield*this.streamWithWatchdog(o,f,p,n);return}catch(b){g=b instanceof Error?b:new Error(String(b));let k=ly(g.message),S=k!==null&&oi.has(k),R=g.message.includes("Stream idle timeout");if(g.message.includes("model_context_window_exceeded")||g.message.includes("context_length_exceeded")||!S&&!R)throw g;if(y===this.maxRetries){if((R||S)&&!e.streamRequired)try{yield*this.nonStreamingFallback(o,f,p,n);return}catch{throw g}throw g}}}if(g)throw g}async*streamWithWatchdog(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(n),signal:i});if(!a.ok){let p=await a.text().catch(()=>""),m=new Error(`Anthropic API error ${a.status}: ${p.slice(0,500)}`);throw m.status=a.status,m}if(!a.body)throw new Error("Anthropic API returned no response body");let c=null,d=!1,l=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{d=!0},this.streamIdleTimeoutMs)},u=()=>{c!==null&&(clearTimeout(c),c=null)};l();try{yield*this.parseSSEStream(a.body,l,()=>d)}finally{u()}if(d)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,n,o){let s=dy({...n,stream:!1}),i=AbortSignal.timeout(zh),a=o?AbortSignal.any([o,i]):i,c=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!c.ok){let l=await c.text().catch(()=>""),u=new Error(`Anthropic API error ${c.status}: ${l.slice(0,500)}`);throw u.status=c.status,u}let d=await c.json();yield*this.mapNonStreamingResponse(d)}*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,reasoningTokens:t.reasoning_input_tokens>0?t.reasoning_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 o=e.stop_reason;o&&(yield{type:"done",finishReason:yl(o)})}async*parseSSEStream(e,t,n){let o=new TextDecoder,s="",i="",a=new Map,c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0};for await(let d of e){if(t(),n())break;s+=o.decode(d,{stream:!0});let l;for(;(l=s.indexOf(`
38
+ `))!==-1;){let u=s.slice(0,l).trim();if(s=s.slice(l+1),!u){i="";continue}if(u.startsWith("event:")){i=u.slice(6).trimStart();continue}if(!u.startsWith("data:"))continue;let p=u.slice(5).trimStart(),m;try{m=JSON.parse(p)}catch{continue}yield*this.mapEvent(i,m,a,c)}}}*mapEvent(e,t,n,o){switch(e){case"message_start":{let i=t.message?.usage;i&&(hl(o,i),yield{type:"usage",promptTokens:o.inputTokens,completionTokens:o.outputTokens,cacheReadTokens:o.cacheReadTokens>0?o.cacheReadTokens:void 0,cacheCreationTokens:o.cacheCreationTokens>0?o.cacheCreationTokens:void 0,reasoningTokens:o.reasoningTokens>0?o.reasoningTokens: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 c=n.get(s);c&&typeof i.signature=="string"&&(c.signature=i.signature)}break}case"content_block_stop":{let s=t.index,i=n.get(s);i?.type==="thinking"&&typeof i.signature=="string"&&(yield{type:"reasoning_block_complete",thinking:"",signature:i.signature}),n.delete(s);break}case"message_delta":{let s=t.delta,i=t.usage;i&&(hl(o,i),yield{type:"usage",promptTokens:o.inputTokens,completionTokens:o.outputTokens,cacheReadTokens:o.cacheReadTokens>0?o.cacheReadTokens:void 0,cacheCreationTokens:o.cacheCreationTokens>0?o.cacheCreationTokens:void 0,reasoningTokens:o.reasoningTokens>0?o.reasoningTokens:void 0}),s?.stop_reason&&(yield{type:"done",finishReason:yl(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 hl(r,e){e.input_tokens>0&&(r.inputTokens=e.input_tokens),r.outputTokens=e.output_tokens??r.outputTokens,e.cache_read_input_tokens>0&&(r.cacheReadTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens>0&&(r.cacheCreationTokens=e.cache_creation_input_tokens),e.reasoning_input_tokens>0&&(r.reasoningTokens=e.reasoning_input_tokens)}function yl(r){switch(r){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_calls";case"max_tokens":return"length";default:return r}}function ny(r){return!/haiku/i.test(r)}var ri={high:16e3,medium:8e3,low:4e3};function oy(r,e){if(e&&e>16384)switch(r){case"high":return Math.min(e-1,Math.max(16e3,Math.floor(e*.5)));case"medium":return Math.min(e-1,Math.max(8e3,Math.floor(e*.25)));case"low":return Math.min(e-1,4e3);default:return ri.high}return ri[r]??ri.high}function ry(r,e){if(r)return e?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:r}function sy(r){let e=[],t=new Set;for(let n=0;n<r.length;n++){let o=r[n];if(o.role==="assistant"&&o.tool_calls&&o.tool_calls.length>0){let s=o.tool_calls.filter(l=>t.has(l.id)?!1:(t.add(l.id),!0)),i=new Set(s.map(l=>l.id)),a=new Set,c=r.slice(n+1);for(let l of c){if(l.role!=="tool")break;l.tool_call_id&&a.add(l.tool_call_id)}s.length!==o.tool_calls.length?e.push({...o,tool_calls:s}):e.push(o);let d=[...i].filter(l=>!a.has(l));for(let l of d){let u=s.find(p=>p.id===l);e.push({role:"tool",tool_call_id:l,name:u?.function.name,content:"[Tool execution failed; output not available during conversation recovery]"})}}else o.role==="tool"?t.has(o.tool_call_id??"")&&e.push(o):e.push(o)}return e}async function iy(r,e,t,n){return r.some(s=>s.imageUrls?.some(G)||s.fileIds?.some(i=>G(i.id)))?Promise.all(r.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.imageUrls?.some(G)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>G(a)?We(a,{uploadAdapter:e,apiKey:t,signal:n}):Promise.resolve(a)))}if(s.role==="user"&&s.fileIds?.some(a=>G(a.id))){if(!e||!t)throw new Error("FileUploadAdapter required for local file URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.fileIds=await Promise.all(s.fileIds.map(async a=>{if(!G(a.id))return a;let c=await We(a.id,{uploadAdapter:e,apiKey:t,signal:n});return{...a,id:c}}))}return Object.keys(i).length>0?{...s,...i}:s})):r}function ay(r,e={},t){let n,o=[];for(let s of r){if(s.role==="system"){n=n?`${n}
39
+
40
+ ${s.content??""}`:s.content??"";continue}if(s.role==="user"){let i=s.imageUrls&&s.imageUrls.length>0&&!e.filterImageBlocks,a=s.fileIds&&s.fileIds.length>0;if(i||a){let c=[];if(s.content&&c.push({type:"text",text:s.content}),i){let d=s.imageUrls.length>1;for(let l=0;l<s.imageUrls.length;l++){let u=s.imageUrls[l];if(d&&c.push({type:"text",text:`[Image ${l+1}]`}),u.startsWith("data:")){let p=/^data:([^;]+);base64,(.+)$/.exec(u);if(p){let m=p[1];m==="application/pdf"?c.push({type:"document",source:{type:"base64",media_type:m,data:p[2]}}):c.push({type:"image",source:{type:"base64",media_type:m,data:p[2]}})}}else u.endsWith(".pdf")||u.includes(".pdf?")?c.push({type:"document",source:{type:"url",url:u}}):c.push({type:"image",source:{type:"url",url:u}})}}if(a)for(let d of s.fileIds){let l=d.mimeType||"";if(d.size!=null&&d.size>$e){let p=`${(d.size/1048576).toFixed(1)}MB`;c.push({type:"text",text:`[Attached: ${d.id} (${l||"unknown"}, ${p}) \u9225?file too large for direct vision, use tools to process]`})}else if(l==="application/pdf"||d.id.endsWith(".pdf"))if(d.id.startsWith("data:")){let p=/^data:[^;]+;base64,(.+)$/.exec(d.id);p&&c.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:p[1]}})}else c.push({type:"document",source:{type:"url",url:d.id}});else{let p=l?`[Attached: ${d.id} (${l})]`:`[Attached: ${d.id}]`;c.push({type:"text",text:p})}}o.push({role:"user",content:c})}else o.push({role:"user",content:s.content??""})}else if(s.role==="assistant"){let i=e.filterThinkingBlocks?void 0:s.thinkingBlocks;if(s.tool_calls&&s.tool_calls.length>0){let a=[];if(i)for(let c of i)c.signature&&a.push({type:"thinking",thinking:c.thinking,signature:c.signature});s.content&&a.push({type:"text",text:s.content});for(let c of s.tool_calls){let d;try{d=JSON.parse(c.function.arguments)}catch{d={}}a.push({type:"tool_use",id:c.id,name:c.function.name,input:d})}o.push({role:"assistant",content:a})}else if(i&&i.length>0){let a=[];for(let c of i)c.signature&&a.push({type:"thinking",thinking:c.thinking,signature:c.signature});s.content&&a.push({type:"text",text:s.content}),o.push({role:"assistant",content:a})}else o.push({role:"assistant",content:s.content??""})}else if(s.role==="tool"){let i=s.content??"",a=s.is_error===!0||i.startsWith("Error:")||i===qh,c=s.toolReferences,d=c&&c.length>0&&!a&&(!t||ny(t)),l=s.imageUrls,u;if(d)u=c.map(f=>({type:"tool_reference",tool_name:f}));else if(l&&l.length>0&&!a){let f=[];i&&f.push({type:"text",text:i});for(let g of l)if(g.startsWith("data:")){let y=/^data:([^;]+);base64,(.+)$/.exec(g);y&&f.push({type:"image",source:{type:"base64",media_type:y[1],data:y[2]}})}else f.push({type:"image",source:{type:"url",url:g}});u=f}else u=i;let p={type:"tool_result",tool_use_id:s.tool_call_id??"",content:u,...a&&{is_error:!0}},m=o[o.length-1];m&&m.role==="user"&&Array.isArray(m.content)?m.content.push(p):o.push({role:"user",content:[p]})}}return{system:n,messages:o}}function cy(r){return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters??{type:"object",properties:{}}}}function ly(r){let e=/Anthropic API error (\d{3})/.exec(r);return e?parseInt(e[1],10):null}function dy(r){let e=typeof r.max_tokens=="number"?r.max_tokens:8192,t=Math.min(e,Kh),n={...r,max_tokens:t},o=n.thinking;return o?.type==="enabled"&&o.budget_tokens&&(n.thinking={...o,budget_tokens:Math.min(o.budget_tokens,t-1)}),n}ye();var Lo=class{baseUrl;extraHeaders;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("VolcengineResponsesTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let s=`${this.baseUrl.replace(/\/v\d+$/,"")}/v3/responses`,i=await this.buildRequestBody(e,t,n),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders};if(e.builtinTools&&!e.disableBuiltinTools&&e.builtinTools.length>0)for(let d of e.builtinTools)d.type==="builtin_web_search"?a["ark-beta-web-search"]="true":d.type==="builtin_image_process"?a["ark-beta-image-process"]="true":d.type==="builtin_knowledge_search"?a["ark-beta-knowledge-search"]="true":d.type==="builtin_doubao_app"&&(a["ark-beta-doubao-app"]="true");let c=null;for(let d=0;d<=3;d++){if(n?.aborted)throw new Error("Request aborted");d>0&&c&&await Je(Ye(d),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(l){c=l instanceof Error?l:new Error(String(l));let u=c.message.includes("Stream idle timeout");if(!st(it(c))&&!u||d===3)throw c}}}resolveConstraints(e){let t=e;if(t.caching&&t.caching.type==="enabled"){if(t.instructions)return t={...t,caching:void 0},t;if(t.structuredOutput&&t.structuredOutput.mode==="json_schema"&&(t={...t,structuredOutput:{mode:"json_object"}}),t.builtinTools&&t.builtinTools.length>0){let o=t.builtinTools.filter(s=>s.type!=="builtin_web_search"&&s.type!=="builtin_image_process");o.length!==t.builtinTools.length&&(t={...t,builtinTools:o.length>0?o:void 0})}}return t}async buildRequestBody(e,t,n){let o=this.resolveConstraints(e),s=await uy(o.messages,this.fileUploadAdapter,t,n),i={model:o.model,input:py(s,this.quirks),stream:!0};if(o.previousResponseId&&(i.previous_response_id=o.previousResponseId),o.store!==void 0&&(i.store=o.store),o.storeExpireAt!==void 0&&(i.expire_at=o.storeExpireAt),o.instructions&&(i.instructions=o.instructions),o.structuredOutput)if(o.structuredOutput.mode==="json_object")i.text={format:{type:"json_object"}};else{let c={type:"json_schema",name:o.structuredOutput.name,schema:o.structuredOutput.schema};o.structuredOutput.strict!==void 0&&(c.strict=o.structuredOutput.strict),i.text={format:c}}if(o.caching){let c={type:o.caching.type};o.caching.prefix!==void 0&&(c.prefix=o.caching.prefix),i.caching=c,o.caching.prefix&&(i.stream=!1)}if(o.contextManagement){let c=o.contextManagement.edits.map(d=>{let l={type:d.type};return d.type==="clear_thinking"&&d.keep!==void 0?l.keep=d.keep:d.type==="clear_tool_uses"&&(d.trigger&&(l.trigger=d.trigger),d.keep&&(l.keep=d.keep),d.excludeTools&&(l.exclude_tools=d.excludeTools),d.clearToolInput!==void 0&&(l.clear_tool_input=d.clearToolInput)),l});i.context_management={edits:c}}let a=[];if(o.tools&&o.tools.length>0)for(let c of o.tools)a.push({type:"function",name:c.function.name,description:c.function.description,parameters:c.function.parameters});if(o.builtinTools&&!o.disableBuiltinTools&&o.builtinTools.length>0)for(let c of o.builtinTools){let l={type:c.type.replace(/^builtin_/,"")};c.config&&Object.assign(l,c.config),a.push(l)}if(a.length>0&&(i.tools=a),o.maxToolCalls!==void 0&&(i.max_tool_calls=o.maxToolCalls),o.toolChoice!==void 0&&(typeof o.toolChoice=="string"?i.tool_choice=o.toolChoice:i.tool_choice={type:o.toolChoice.type,name:o.toolChoice.name}),o.temperature!==void 0&&(i.temperature=o.temperature),o.topP!==void 0&&(i.top_p=o.topP),o.maxTokens!==void 0&&(i.max_output_tokens=o.maxTokens),o.reasoning){let c=o.reasoning.effort??"high";c==="minimal"?i.thinking={type:"disabled"}:(i.thinking={type:"enabled"},i.reasoning={effort:c}),o.reasoning.includeEncryptedReasoning&&(i.include=["reasoning.encrypted_content"])}return o.prefixMessage&&i.input.push({role:"assistant",content:o.prefixMessage,partial:!0}),i}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`Volcengine Responses API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("Volcengine Responses API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStream(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();if(t.id&&(yield{type:"response_id",id:t.id}),t.usage&&(yield{type:"usage",promptTokens:t.usage.input_tokens??0,completionTokens:t.usage.output_tokens??0,reasoningTokens:t.usage.output_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.input_tokens_details?.cached_tokens}),t.output)for(let n of t.output){if(n.type==="message"&&n.content)for(let o of n.content)o.type==="output_text"&&(yield{type:"delta",text:o.text??""});if(n.type==="reasoning"&&n.summary)for(let o of n.summary)o.type==="summary_text"&&(yield{type:"reasoning_delta",text:o.text??""});n.type==="function_call"&&(yield{type:"tool_call_delta",index:0,id:n.call_id,name:n.name,arguments:n.arguments??""})}yield{type:"done",finishReason:t.status==="completed"?"stop":t.status??"stop"}}async*parseSSEStream(e){let t=new TextDecoder,n="",o="",s=null,i=new AbortController,a=0,c=new Map,d=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},Xe)};try{d();let l=e.getReader();try{for(;;){let{done:u,value:p}=await l.read();if(u)break;if(i.signal.aborted)throw new Error("Stream idle timeout");d(),n+=t.decode(p,{stream:!0});let m;for(;(m=n.indexOf(`
41
+ `))!==-1;){let f=n.slice(0,m).trim();if(n=n.slice(m+1),!f){o="";continue}if(!f.startsWith(":")){if(f.startsWith("event:")){o=f.slice(6).trim();continue}if(f.startsWith("data:")){let g=f.slice(5).trim();if(g==="[DONE]")return;let y;try{y=JSON.parse(g)}catch{continue}yield*this.processEvent(o,y,c,()=>a++)}}}}}finally{l.releaseLock()}}finally{s&&clearTimeout(s)}}*processEvent(e,t,n,o){switch(e){case"response.output_text.delta":{let s=t.delta;s&&(yield{type:"delta",text:s});break}case"response.reasoning_summary_text.delta":{let s=t.delta;s&&(yield{type:"reasoning_delta",text:s});break}case"response.function_call_arguments.delta":{let s=t.delta,i=t.call_id,a=t.name;if(s!==void 0&&i){let c=n.get(i);c===void 0&&(c=o(),n.set(i,c)),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:s}}break}case"response.output_item.added":{let s=t.item;if(s&&s.type==="function_call"){let i=s.call_id,a=s.name;if(i&&!n.has(i)){let c=o();n.set(i,c),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:""}}}break}case"response.function_call_arguments.done":break;case"response.output_item.done":{let s=t.item;if(s?.type==="message"){let i=s.content;if(i)for(let a of i){let c=a.annotations;c&&c.length>0&&(yield{type:"annotations",annotations:c.map(d=>({type:d.type??"url_citation",url:d.url,title:d.title,...d}))})}}if(s?.type==="function_call"){let i=s.call_id,a=s.name,c=s.arguments??"";if(i&&c){let d=n.get(i),l=d!==void 0;l||(d=o(),n.set(i,d)),yield{type:"tool_call_delta",index:d,id:i,name:l?void 0:a,arguments:c}}}break}case"response.completed":{let s=t.response;if(s){let i=s.id;i&&(yield{type:"response_id",id:i});let a=s.usage;if(a){let d=a.input_tokens_details,l=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:l?.reasoning_tokens,cacheReadTokens:d?.cached_tokens}}yield{type:"done",finishReason:s.status==="incomplete"?"tool_calls":"stop"}}else yield{type:"done",finishReason:"stop"};break}case"response.failed":{yield{type:"error",message:t.response?.error?.message??"Unknown error"},yield{type:"done",finishReason:"error"};break}default:{e.startsWith("response.web_search_call")?yield{type:"builtin_tool_status",toolType:"web_search",event:e,data:t}:e.startsWith("response.image_process")&&(yield{type:"builtin_tool_status",toolType:"image_process",event:e,data:t});break}}}};async function uy(r,e,t,n){if(!r.some(i=>i.imageUrls?.some(G)||i.videoUrls?.some(G)||i.audioUrls?.some(G)))return r;let s=i=>{if(!G(i))return Promise.resolve(i);if(!e||!t)throw new Error("FileUploadAdapter required for local media URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");return We(i,{uploadAdapter:e,apiKey:t,signal:n})};return Promise.all(r.map(async i=>{if(i.role!=="user"&&i.role!=="tool")return i;let a={};return i.imageUrls?.some(G)&&(a.imageUrls=await Promise.all(i.imageUrls.map(s))),i.role==="user"&&i.videoUrls?.some(G)&&(a.videoUrls=await Promise.all(i.videoUrls.map(s))),i.role==="user"&&i.audioUrls?.some(G)&&(a.audioUrls=await Promise.all(i.audioUrls.map(s))),Object.keys(a).length>0?{...i,...a}:i}))}function py(r,e={}){let t=[];for(let n of r){if(n.role==="system"){t.push({role:"system",content:n.content??""});continue}if(n.role==="user"){let o=n.imageUrls&&n.imageUrls.length>0,s=n.videoUrls&&n.videoUrls.length>0,i=n.audioUrls&&n.audioUrls.length>0,a=n.fileIds&&n.fileIds.length>0;if(o||s||i||a){let d=[];if(o){let l=n.imageUrls.length>1;for(let u=0;u<n.imageUrls.length;u++){let p=n.imageUrls[u];l&&d.push({type:"input_text",text:`[Image ${u+1}]`});let m={type:"input_image",image_url:p};n.imageDetail&&(m.detail=n.imageDetail),n.imagePixelLimit&&(m.image_pixel_limit=n.imagePixelLimit),d.push(m)}}if(s)for(let l of n.videoUrls){let u={type:"input_video",video_url:l};n.videoFps!==void 0&&(u.fps=n.videoFps),d.push(u)}if(i)for(let l of n.audioUrls){let u={type:"input_audio",audio_url:l};n.audioFormat&&(u.format=n.audioFormat),d.push(u)}if(a)for(let l of n.fileIds){let u=l.mimeType||"";if(l.size!=null&&l.size>$e){let m=`${(l.size/1048576).toFixed(1)}MB`;d.push({type:"input_text",text:`[Attached: ${l.id} (${u||"unknown"}, ${m}) \u2014 file too large for direct vision, use tools to process]`})}else if(e.supportsDocumentVision&&(u==="application/pdf"||l.id.endsWith(".pdf")))l.id.startsWith("http://")||l.id.startsWith("https://")?d.push({type:"input_text",text:`[Attached PDF: ${l.id}]`}):d.push({type:"input_file",file_id:l.id});else if(l.id.startsWith("http://")||l.id.startsWith("https://")){let m=u?`[Attached: ${l.id} (${u})]`:`[Attached: ${l.id}]`;d.push({type:"input_text",text:m})}else d.push({type:"input_file",file_id:l.id})}n.content&&d.push({type:"input_text",text:n.content}),t.push({role:"user",content:d})}else t.push({role:"user",content:n.content??""});continue}if(n.role==="assistant"){if(n.content&&t.push({role:"assistant",content:n.content}),n.tool_calls&&n.tool_calls.length>0)for(let o of n.tool_calls)t.push({type:"function_call",call_id:o.id,name:o.function.name,arguments:o.function.arguments||"{}"});continue}if(n.role==="tool"){if(!n.tool_call_id)continue;if(n.imageUrls&&n.imageUrls.length>0){let o=[];n.content&&o.push({type:"input_text",text:n.content});for(let s of n.imageUrls)o.push({type:"input_image",image_url:s});t.push({type:"function_call_output",call_id:n.tool_call_id,output:o})}else t.push({type:"function_call_output",call_id:n.tool_call_id,output:n.content??""});continue}}return t}ye();jr();var my=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_ONLY_HIGH"},{category:"HARM_CATEGORY_CIVIC_INTEGRITY",threshold:"BLOCK_ONLY_HIGH"}];function gy(r){switch(r){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";default:return"HIGH"}}var Rn=class{baseUrl;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("GeminiGenerateContentTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:streamGenerateContent?alt=sse`,s=await this.buildRequestBody(e,t,n),i={"Content-Type":"application/json","x-goog-api-key":t},a=null;for(let c=0;c<=3;c++){if(n?.aborted)throw new Error("Request aborted");c>0&&a&&await Je(Ye(c),n);try{yield*this.fetchAndStream(o,i,s,n);return}catch(d){a=d instanceof Error?d:new Error(String(d));let l=a.message.includes("Stream idle timeout");if(!st(it(a))&&!l)throw a;if(c===3){if((l||st(it(a)))&&!e.streamRequired)try{yield*this.nonStreamingFallback(e,t,n);return}catch{throw a}throw a}}}}async buildRequestBody(e,t,n){let o=await fy(e.messages,this.fileUploadAdapter,t,n),{systemInstruction:s,contents:i}=hy(o),a={contents:i};s&&(a.system_instruction=s);let c=this.buildTools(e);c.length>0&&(a.tools=c),e.tools&&e.tools.length>0&&e.toolChoice&&(a.toolConfig=this.buildToolConfig(e.toolChoice));let d=this.buildGenerationConfig(e);return Object.keys(d).length>0&&(a.generationConfig=d),a.safetySettings=my,e.cachedContent&&(a.cachedContent=e.cachedContent),a}buildTools(e){let t=[];if(e.tools&&e.tools.length>0){let n=e.tools.map(yy);t.push({functionDeclarations:n})}return e.disableBuiltinTools||(this.quirks.builtinWebSearch&&t.push({googleSearch:{}}),this.quirks.builtinCodeInterpreter&&t.push({codeExecution:{}}),this.quirks.builtinUrlContext&&t.push({urlContext:{}}),this.quirks.builtinMapsGrounding&&t.push({googleMaps:{}}),this.quirks.builtinFileSearch&&t.push({fileSearch:{}})),t}buildToolConfig(e){return typeof e=="string"?{functionCallingConfig:{mode:{auto:"AUTO",none:"NONE",required:"ANY"}[e]??"AUTO"}}:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[e.name]}}}buildGenerationConfig(e){let t={};if(e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.maxTokens!==void 0&&(t.maxOutputTokens=e.maxTokens),e.reasoning){let n=gy(e.reasoning.effort);n==="MINIMAL"&&e.model.includes("pro")&&(n="LOW"),t.thinkingConfig={thinkingLevel:n,includeThoughts:!0}}return e.structuredOutput&&(e.structuredOutput.mode==="json_object"?t.responseMimeType="application/json":e.structuredOutput.mode==="json_schema"&&(t.responseMimeType="application/json",t.responseSchema=e.structuredOutput.schema)),t}async*fetchAndStream(e,t,n,o){let s=AbortSignal.timeout(this.timeoutMs),i=o?AbortSignal.any([o,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(()=>""),l=new Error(`Gemini API error ${a.status}: ${d.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("Gemini API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){let d=await a.json();yield*this.processResponse(d);return}yield*this.parseSSEStreamWithWatchdog(a.body)}async*parseSSEStreamWithWatchdog(e){let t=new TextDecoder,n="",o=null,s=new AbortController,i=()=>{o&&clearTimeout(o),o=setTimeout(()=>{s.abort()},Xe)};try{i();let a=e.getReader();try{for(;;){let{done:c,value:d}=await a.read();if(c)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(d,{stream:!0});let l;for(;(l=n.indexOf(`
42
+ `))!==-1;){let u=n.slice(0,l).trim();if(n=n.slice(l+1),!u||u.startsWith(":")||!u.startsWith("data: "))continue;let p=u.slice(6);if(p==="[DONE]")return;let m;try{m=JSON.parse(p)}catch{continue}yield*this.processResponse(m)}}}finally{a.releaseLock()}}finally{o&&clearTimeout(o)}}*processResponse(e){if(e.error){yield{type:"error",message:`Gemini error ${e.error.code}: ${e.error.message}`};return}if(e.usageMetadata){let t=e.usageMetadata;yield{type:"usage",promptTokens:t.promptTokenCount??0,completionTokens:t.candidatesTokenCount??0,reasoningTokens:t.thoughtsTokenCount,cacheReadTokens:t.cachedContentTokenCount}}if(!(!e.candidates||e.candidates.length===0))for(let t of e.candidates){if(t.finishReason==="SAFETY"){yield{type:"error",message:"Response blocked by Gemini safety filters"},yield{type:"done",finishReason:"content_filter"};return}let n=t.content?.parts??[],o=0;for(let s of n){if(s.thought&&s.text){yield{type:"reasoning_delta",text:s.text},s.thoughtSignature&&(yield{type:"reasoning_block_complete",thinking:s.text,signature:s.thoughtSignature});continue}if(s.text&&!s.thought){yield{type:"delta",text:s.text};continue}if(s.functionCall){let i=s.functionCall;yield{type:"tool_call_delta",index:o,id:i.id??`gemini-tc-${o}`,name:i.name,arguments:JSON.stringify(i.args??{})},s.thoughtSignature&&(yield{type:"reasoning_block_complete",thinking:"",signature:s.thoughtSignature}),o++;continue}if(s.codeExecutionResult){yield{type:"delta",text:`
43
43
  \`\`\`output
44
44
  ${s.codeExecutionResult.output??""}
45
45
  \`\`\`
@@ -47,28 +47,28 @@ ${s.codeExecutionResult.output??""}
47
47
  \`\`\`${s.executableCode.language??"python"}
48
48
  ${s.executableCode.code}
49
49
  \`\`\`
50
- `};continue}}if(t.groundingMetadata?.groundingChunks){let s=t.groundingMetadata.groundingChunks.filter(i=>i.web?.uri).map(i=>({type:"web_search",url:i.web.uri,title:i.web.title}));s.length>0&&(yield{type:"annotations",annotations:s})}t.finishReason&&(yield{type:"done",finishReason:iy(t.finishReason)})}}async*nonStreamingFallback(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:generateContent`,s=await this.buildRequestBody(e,t,n),i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(s),signal:a});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`Gemini API error ${c.status}: ${l.slice(0,500)}`)}let d=await c.json();yield*this.processResponse(d)}};async function oy(r,e,t,n){if(!r.some(i=>i.imageUrls?.some(H)||i.videoUrls?.some(H)||i.audioUrls?.some(H)||i.fileIds?.some(a=>H(a.id))))return r;let s=(i,a)=>{if(!H(i))return Promise.resolve(i);if(!e||!t)throw new Error("FileUploadAdapter required for local media URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");return Fe(i,{uploadAdapter:e,apiKey:t,signal:n})};return Promise.all(r.map(async i=>{if(i.role!=="user"&&i.role!=="tool")return i;let a={};return i.imageUrls?.some(H)&&(a.imageUrls=await Promise.all(i.imageUrls.map(c=>s(c)))),i.role==="user"&&i.videoUrls?.some(H)&&(a.videoUrls=await Promise.all(i.videoUrls.map(c=>s(c)))),i.role==="user"&&i.audioUrls?.some(H)&&(a.audioUrls=await Promise.all(i.audioUrls.map(c=>s(c)))),i.role==="user"&&i.fileIds?.some(c=>H(c.id))&&(a.fileIds=await Promise.all(i.fileIds.map(async c=>{if(!H(c.id))return c;let d=await s(c.id,c.mimeType);return{...c,id:d}}))),Object.keys(a).length>0?{...i,...a}:i}))}function ry(r){let e=null,t=[],n=[],o=()=>{n.length>0&&(t.push({role:"user",parts:n}),n=[])};for(let s of r)switch(s.role){case"system":{e={parts:[{text:s.content??""}]};break}case"user":{o();let i=[];if(s.content&&i.push({text:s.content}),s.imageUrls&&s.imageUrls.length>0)for(let a of s.imageUrls)if(a.startsWith("data:")){let c=a.match(/^data:([^;]+);base64,(.+)$/);c&&i.push({inlineData:{mimeType:c[1],data:c[2]}})}else i.push({fileData:{mimeType:"image/jpeg",fileUri:a}});if(s.audioUrls&&s.audioUrls.length>0)for(let a of s.audioUrls){let c=s.audioFormat?`audio/${s.audioFormat==="m4a"?"mp4":s.audioFormat}`:"audio/mp3";i.push({fileData:{mimeType:c,fileUri:a}})}if(s.videoUrls&&s.videoUrls.length>0)for(let a of s.videoUrls)i.push({fileData:{mimeType:"video/mp4",fileUri:a}});if(s.fileIds&&s.fileIds.length>0)for(let a of s.fileIds)if(a.id.startsWith("data:")){let c=a.id.match(/^data:([^;]+);base64,(.+)$/);c&&i.push({inlineData:{mimeType:c[1],data:c[2]}})}else a.id.startsWith("http://")||a.id.startsWith("https://")?i.push({fileData:{mimeType:a.mimeType??"application/octet-stream",fileUri:a.id}}):i.push({fileData:{mimeType:a.mimeType??"application/octet-stream",fileUri:a.id}});i.length>0&&t.push({role:"user",parts:i});break}case"assistant":{o();let i=[];if(s.thinkingBlocks&&s.thinkingBlocks.length>0)for(let a of s.thinkingBlocks){let c={text:a.thinking,thought:!0};a.signature&&(c.thoughtSignature=a.signature),i.push(c)}if(s.content&&i.push({text:s.content}),s.tool_calls&&s.tool_calls.length>0)for(let a of s.tool_calls){let c={};try{c=JSON.parse(a.function.arguments)}catch{}i.push({functionCall:{name:a.function.name,args:c,id:a.id}})}i.length>0&&t.push({role:"model",parts:i});break}case"tool":{let i;try{i=JSON.parse(s.content??"{}")}catch{i={result:s.content??""}}if(n.push({functionResponse:{name:s.name??"",response:i,id:s.tool_call_id??""}}),s.imageUrls&&s.imageUrls.length>0)for(let a of s.imageUrls)if(a.startsWith("data:")){let c=/^data:([^;]+);base64,(.+)$/.exec(a);c&&n.push({inlineData:{mimeType:c[1],data:c[2]}})}else{let c=a.endsWith(".png")?"image/png":a.endsWith(".jpg")||a.endsWith(".jpeg")?"image/jpeg":a.endsWith(".gif")?"image/gif":a.endsWith(".webp")?"image/webp":"image/png";n.push({fileData:{mimeType:c,fileUri:a}})}break}}return o(),{systemInstruction:e,contents:t}}function sy(r){let e={name:r.function.name,description:r.function.description};return r.function.parameters&&(e.parameters=We(r.function.parameters)),e}function iy(r){switch(r){case"STOP":return"stop";case"MAX_TOKENS":return"length";case"SAFETY":return"content_filter";case"RECITATION":return"content_filter";case"LANGUAGE":return"content_filter";case"FINISH_REASON_UNSPECIFIED":return"stop";default:return r.toLowerCase()}}var Eo=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let i=this.config.baseUrl.replace(/\/+$/,""),c=/\/v\d+$/.test(i)?`${i}/files`:`${i}/v1/files`,d=new FormData,l=new Blob([e],{type:n});d.append("file",l,t),d.append("purpose",this.config.defaultPurpose??"file-extract");let u=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${o}`,...this.config.extraHeaders},body:d,signal:s??AbortSignal.timeout(this.config.timeoutMs??12e4)});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`File upload to ${this.config.provider} failed (${u.status}): ${m}`)}let p=await u.json(),g=String(p.id??"");return{url:String(p.download_url??p.url??p.file_url??"")||g,fileId:g,filename:String(p.filename??t),bytes:Number(p.bytes??e.byteLength),mimeType:n,provider:this.config.provider}}};var Oo=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let a=`${this.config.baseUrl.replace(/\/+$/,"")}/v3/files`,c=new FormData,d=new Blob([e],{type:n});c.append("file",d,t),c.append("purpose",this.config.defaultPurpose??"user_data");let l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:c,signal:s??AbortSignal.timeout(this.config.timeoutMs??12e4)});if(!l.ok){let g=await l.text().catch(()=>"");throw new Error(`Volcengine file upload failed (${l.status}): ${g}`)}let u=await l.json(),p=String(u.id??"");return{url:p,fileId:p,filename:t,bytes:e.byteLength,mimeType:n,provider:"volcengine"}}};var Do=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let i=this.config.timeoutMs??18e4,a=s??AbortSignal.timeout(i),c=this.config.baseUrl.replace(/(\/v1beta)$/,"/upload$1/files"),d=await fetch(c,{method:"POST",headers:{"x-goog-api-key":o,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(e.length),"X-Goog-Upload-Header-Content-Type":n,"Content-Type":"application/json"},body:JSON.stringify({file:{display_name:t}}),signal:a});if(!d.ok){let f=await d.text().catch(()=>"");throw new Error(`Gemini file upload init failed (${d.status}): ${f.slice(0,500)}`)}let l=d.headers.get("x-goog-upload-url");if(!l)throw new Error("Gemini file upload: missing x-goog-upload-url in response");let u=await fetch(l,{method:"PUT",headers:{"Content-Length":String(e.length),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:e,signal:a});if(!u.ok){let f=await u.text().catch(()=>"");throw new Error(`Gemini file upload failed (${u.status}): ${f.slice(0,500)}`)}let g=(await u.json()).file;return g.state==="PROCESSING"&&await this.waitForProcessing(g.name,o,a),{url:g.uri,fileId:g.name,filename:t,bytes:parseInt(g.sizeBytes??"0",10)||e.length,mimeType:n,provider:"gemini"}}async waitForProcessing(e,t,n,o=30){let s=`${this.config.baseUrl}/files/${e.replace("files/","")}`;for(let i=0;i<o;i++){if(await new Promise(d=>setTimeout(d,2e3)),n.aborted)throw new Error("Upload aborted during processing wait");let a=await fetch(`${s}?key=${t}`,{signal:n});if(!a.ok)continue;let c=await a.json();if(c.state==="ACTIVE")return;if(c.state==="FAILED")throw new Error("Gemini file processing failed")}}};var Lo=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let a=`${this.config.hubBaseUrl.replace(/\/+$/,"")}/api/v1/files/upload`,c=new FormData,d=new Blob([e],{type:n});c.append("file",d,t),c.append("purpose","llm_input");let l={};this.config.hubApiKey&&(l.Authorization=`Bearer ${this.config.hubApiKey}`);let u=await fetch(a,{method:"POST",headers:l,body:c,signal:s??AbortSignal.timeout(this.config.timeoutMs??12e4)});if(!u.ok){let g=await u.text().catch(()=>"");throw new Error(`Hub OSS upload failed ${u.status}: ${g.slice(0,200)}`)}let p=await u.json();if(!p.url)throw new Error("Hub OSS upload response missing 'url' field");return{url:p.url,fileId:p.fileId??t,filename:t,bytes:p.bytes??e.byteLength,mimeType:n,provider:this.config.provider??"hub-oss"}}};import{createHmac as ay,randomUUID as ly}from"node:crypto";function uc(){let r=(process.env.OSS_ACCESS_KEY_ID??process.env.ALIYUN_OSS_ACCESS_KEY_ID??"").trim(),e=(process.env.OSS_ACCESS_KEY_SECRET??process.env.ALIYUN_OSS_ACCESS_KEY_SECRET??"").trim();if(!(!r||!e))return new ti({accessKeyId:r,accessKeySecret:e,bucket:(process.env.OSS_BUCKET??process.env.ALIYUN_OSS_BUCKET??"qlogicagent").trim(),region:(process.env.OSS_REGION??process.env.ALIYUN_OSS_REGION??"cn-beijing").trim(),endpoint:(process.env.OSS_ENDPOINT??"").trim()||void 0})}var ti=class{config;constructor(e){let t=e.bucket||"qlogicagent",n=e.region||"cn-beijing";this.config={accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,bucket:t,region:n,endpoint:e.endpoint||`${t}.oss-${n}.aliyuncs.com`,pathPrefix:e.pathPrefix||"media",timeoutMs:e.timeoutMs??12e4}}async uploadFile(e,t,n,o,s){let i=new Date().toISOString().slice(0,10),a=ly().slice(0,8),c=t.replace(/[^a-zA-Z0-9._-]/g,"_"),d=`${this.config.pathPrefix}/${i}/${a}_${c}`,l=`https://${this.config.endpoint}/${d}`,u=new Date().toUTCString(),p=["PUT","",n,u,`/${this.config.bucket}/${d}`].join(`
51
- `),g=ay("sha1",this.config.accessKeySecret).update(p).digest("base64"),f={Date:u,"Content-Type":n,"Content-Length":String(e.byteLength),Authorization:`OSS ${this.config.accessKeyId}:${g}`},m=await fetch(l,{method:"PUT",headers:f,body:e,signal:s??AbortSignal.timeout(this.config.timeoutMs)});if(!m.ok){let y=await m.text().catch(()=>"");throw new Error(`Aliyun OSS upload failed ${m.status}: ${y.slice(0,300)}`)}return{url:l,fileId:d,filename:c,bytes:e.byteLength,mimeType:n,provider:"aliyun-oss"}}};function $o(r,e){let n=e.getProvider(r.provider)?.baseUrl;r.baseUrl&&e.applyOverride(r.provider,{baseUrl:r.baseUrl});let o=e.getProvider(r.provider);if(!o)throw new Error(`Unknown LLM provider: "${r.provider}". Available: ${e.listProviders().map(a=>a.id).join(", ")}`);let s=r.baseUrl||o.baseUrl;if(r.baseUrl&&n)try{let a=new URL(r.baseUrl),c=new URL(n);(a.pathname==="/"||a.pathname==="")&&c.pathname!=="/"&&c.pathname!==""&&(s=new URL(c.pathname,r.baseUrl).toString().replace(/\/$/,""))}catch{}return{transport:uy(o,s),apiKey:r.apiKey,resolvedModel:r.model,providerDef:o}}function cy(r,e,t){switch(r){case"openai-chat":case"openai-responses":return new Eo({baseUrl:e,provider:t.id,extraHeaders:t.extraHeaders});case"volcengine-responses":return new Oo({baseUrl:e});case"gemini-generatecontent":return new Do({baseUrl:e});default:return dy()}}var _t=null;function dy(){if(_t!==null)return _t||void 0;let r=(process.env.QLOGICAGENT_HUB_URL??process.env.HUB_BASE_URL??"").trim();if(r)return _t=new Lo({hubBaseUrl:r,hubApiKey:(process.env.QLOGICAGENT_HUB_API_KEY??process.env.HUB_API_KEY??"").trim()||void 0}),_t;let e=uc();if(e)return _t=e,_t;_t=void 0}function uy(r,e){let t,n=cy(r.transport,e,r);switch(r.transport){case"openai-chat":t=new Wt({baseUrl:e,extraHeaders:r.extraHeaders,supportsStreamOptions:r.supportsStreamOptions,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks,fileUploadAdapter:n});break;case"openai-responses":t=new Po({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks,fileUploadAdapter:n});break;case"anthropic-messages":t=new kn({baseUrl:e,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks,fileUploadAdapter:n});break;case"volcengine-responses":t=new Mo({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks,fileUploadAdapter:n});break;case"gemini-generatecontent":t=new Tn({baseUrl:e,quirks:r.quirks,fileUploadAdapter:n});break;default:throw new Error(`Unsupported transport type: "${r.transport}" for provider "${r.id}"`)}if(r.transport==="anthropic-messages"&&r.quirks?.supportsPrefixCompletion){let o=e.replace(/\/anthropic\/?$/,""),s=new Wt({baseUrl:o,quirks:r.quirks});return new ni(t,s)}return t}var ni=class{constructor(e,t){this.primary=e;this.prefixTransport=t}primary;prefixTransport;async*stream(e,t,n){yield*(e.prefixMessage?this.prefixTransport:this.primary).stream(e,t,n)}async*complete(e,t,n){if(this.prefixTransport.complete)yield*this.prefixTransport.complete(e,t,n);else throw new Error("FIM completion is not supported by this transport")}};var wn=class{baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??3e5}async uploadFile(e,t,n,o){let s=e instanceof Blob?Buffer.from(await e.arrayBuffer()):e,i=n?.mimeType??"application/octet-stream",a=n?.displayName??"upload",c=this.baseUrl.replace(/(\/v1beta)$/,"/upload$1/files"),d=await fetch(c,{method:"POST",headers:{"x-goog-api-key":t,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(s.length),"X-Goog-Upload-Header-Content-Type":i,"Content-Type":"application/json"},body:JSON.stringify({file:{display_name:a}}),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let g=await d.text().catch(()=>"");throw new Error(`Gemini file upload init error ${d.status}: ${g.slice(0,500)}`)}let l=d.headers.get("x-goog-upload-url");if(!l)throw new Error("Gemini file upload: missing x-goog-upload-url in response headers");let u=await fetch(l,{method:"PUT",headers:{"Content-Length":String(s.length),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:s,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let g=await u.text().catch(()=>"");throw new Error(`Gemini file upload error ${u.status}: ${g.slice(0,500)}`)}return(await u.json()).file}async waitForProcessing(e,t,n){let o=n?.pollIntervalMs??2500,s=n?.maxWaitMs??12e4,i=Date.now();for(;Date.now()-i<s;){let a=await this.getFile(e,t);if(a.state==="ACTIVE")return a;if(a.state==="FAILED")throw new Error(`Gemini file processing failed: ${a.error?.message??"unknown error"}`);await new Promise(c=>setTimeout(c,o))}throw new Error(`Gemini file processing timed out after ${s}ms`)}async getFile(e,t,n){let o=`${this.baseUrl}/${e}`,s=await fetch(o,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini file get error ${s.status}: ${i.slice(0,500)}`)}return await s.json()}async listFiles(e,t,n){let o=new URLSearchParams;t?.pageSize&&o.set("pageSize",String(t.pageSize)),t?.pageToken&&o.set("pageToken",t.pageToken);let s=`${this.baseUrl}/files?${o.toString()}`,i=await fetch(s,{method:"GET",headers:{"x-goog-api-key":e},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Gemini file list error ${i.status}: ${c.slice(0,500)}`)}let a=await i.json();return{files:a.files??[],nextPageToken:a.nextPageToken}}async deleteFile(e,t,n){let o=`${this.baseUrl}/${e}`,s=await fetch(o,{method:"DELETE",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini file delete error ${s.status}: ${i.slice(0,500)}`)}}};import{join as py}from"node:path";import{mkdirSync as my,appendFileSync as gy}from"node:fs";var pc=Fl();function oi(){return process.env.QLOGICAGENT_DEBUG==="1"}function ri(r,e){let t=py(pc,`${e}.jsonl`),n=!1;function o(){n||(my(pc,{recursive:!0}),n=!0)}function s(i){try{o(),gy(t,JSON.stringify(i)+`
52
- `,"utf8")}catch{}}return{async*stream(i,a,c){let d=Date.now();s({type:"request",timestamp:new Date(d).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 l=0,u=0,p=0,g="",f;try{for await(let m of r.stream(i,a,c))m.type==="usage"?(l=m.promptTokens,u=m.completionTokens,p=m.reasoningTokens??0):m.type==="done"&&(g=m.finishReason),yield m}catch(m){throw f=m instanceof Error?m.message:String(m),m}finally{let m=Date.now()-d;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:m,promptTokens:l,completionTokens:u,reasoningTokens:p,finishReason:g,...f?{error:f}:{}})}}}}function si(r){return typeof r.deleteVideoTask=="function"&&typeof r.listVideoTasks=="function"}function ii(r){let e=new Map;return{register(t){let n=e.get(t.point)??[],o={handler:t.handler,priority:t.priority??100,label:t.label};return n.push(o),n.sort((s,i)=>s.priority-i.priority),e.set(t.point,n),()=>{let s=n.indexOf(o);s>=0&&n.splice(s,1)}},async invoke(t,n){let o=e.get(t);if(!o||o.length===0)return{action:"continue",context:n};let s=n;for(let i of o)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 r.info({hook:t,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){r.warn({hook:t,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}import{readFile as mc,readdir as fy,stat as hy}from"node:fs/promises";import{existsSync as gc}from"node:fs";import{join as yy}from"node:path";var Le={MAX_SCAN_FILES:100,MAX_SELECTED:5,MAX_FILE_BYTES:4096,MAX_TOTAL_BYTES:20*1024,MIN_SCORE:.2,HEADER_LINES:10,RECENCY_DAYS:7,RECENCY_BOOST:.15};async function fc(r,e,t=new Set){if(!r.trim()||!gc(e))return[];let n=r.trim().split(/\s+/);if(n.length<2&&n[0].length<4)return[];let o=await by(e);if(o.length===0)return[];let s=o.filter(c=>!t.has(c.filePath));if(s.length===0)return[];let a=ky(r,s).filter(c=>c.score>=Le.MIN_SCORE).slice(0,Le.MAX_SELECTED);return a.length===0?[]:Ty(a)}async function by(r){if(!gc(r))return[];let e;try{e=await fy(r)}catch{return[]}let t=e.filter(o=>o.endsWith(".md")&&o!=="INDEX.md");return(await Promise.allSettled(t.map(async o=>{let s=yy(r,o),i=await hy(s),c=(await mc(s,"utf-8")).split(`
53
- `),d=null;for(let u=0;u<Math.min(c.length,Le.HEADER_LINES);u++){let p=c[u].trim();if(!(!p||p.startsWith("#")||p.startsWith("---"))){d=p.slice(0,150);break}}let l=wy(o);return{filename:o,filePath:s,mtimeMs:i.mtimeMs,sizeBytes:i.size,description:d,category:l}}))).filter(o=>o.status==="fulfilled").map(o=>o.value).sort((o,s)=>s.mtimeMs-o.mtimeMs).slice(0,Le.MAX_SCAN_FILES)}function ky(r,e){let t=ai(r);if(t.length===0)return[];let n=Date.now(),o=Le.RECENCY_DAYS*24*60*60*1e3;return e.map(i=>{let a=0,c=ai(i.filename.replace(/\.md$/,"").replace(/[-_]/g," ")),d=t.filter(l=>c.some(u=>u.includes(l)||l.includes(u))).length;if(a+=Math.min(.5,d/t.length*.5),i.description){let l=ai(i.description),u=t.filter(p=>l.some(g=>g.includes(p)||p.includes(g))).length;a+=Math.min(.3,u/t.length*.3)}return i.category&&vy(r).includes(i.category)&&(a+=.1),n-i.mtimeMs<o&&(a+=Le.RECENCY_BOOST),{header:i,score:a}}).sort((i,a)=>a.score-i.score)}async function Ty(r){let e=[],t=0;for(let{header:n,score:o}of r){if(t>=Le.MAX_TOTAL_BYTES)break;try{let s=await mc(n.filePath,"utf-8"),i=!1;s.length>Le.MAX_FILE_BYTES&&(s=s.slice(0,Le.MAX_FILE_BYTES)+`
50
+ `};continue}}if(t.groundingMetadata?.groundingChunks){let s=t.groundingMetadata.groundingChunks.filter(i=>i.web?.uri).map(i=>({type:"web_search",url:i.web.uri,title:i.web.title}));s.length>0&&(yield{type:"annotations",annotations:s})}t.finishReason&&(yield{type:"done",finishReason:by(t.finishReason)})}}async*nonStreamingFallback(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:generateContent`,s=await this.buildRequestBody(e,t,n),i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(s),signal:a});if(!c.ok){let l=await c.text().catch(()=>"");throw new Error(`Gemini API error ${c.status}: ${l.slice(0,500)}`)}let d=await c.json();yield*this.processResponse(d)}};async function fy(r,e,t,n){if(!r.some(i=>i.imageUrls?.some(G)||i.videoUrls?.some(G)||i.audioUrls?.some(G)||i.fileIds?.some(a=>G(a.id))))return r;let s=(i,a)=>{if(!G(i))return Promise.resolve(i);if(!e||!t)throw new Error("FileUploadAdapter required for local media URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");return We(i,{uploadAdapter:e,apiKey:t,signal:n})};return Promise.all(r.map(async i=>{if(i.role!=="user"&&i.role!=="tool")return i;let a={};return i.imageUrls?.some(G)&&(a.imageUrls=await Promise.all(i.imageUrls.map(c=>s(c)))),i.role==="user"&&i.videoUrls?.some(G)&&(a.videoUrls=await Promise.all(i.videoUrls.map(c=>s(c)))),i.role==="user"&&i.audioUrls?.some(G)&&(a.audioUrls=await Promise.all(i.audioUrls.map(c=>s(c)))),i.role==="user"&&i.fileIds?.some(c=>G(c.id))&&(a.fileIds=await Promise.all(i.fileIds.map(async c=>{if(!G(c.id))return c;let d=await s(c.id,c.mimeType);return{...c,id:d}}))),Object.keys(a).length>0?{...i,...a}:i}))}function hy(r){let e=null,t=[],n=[],o=()=>{n.length>0&&(t.push({role:"user",parts:n}),n=[])};for(let s of r)switch(s.role){case"system":{e={parts:[{text:s.content??""}]};break}case"user":{o();let i=[];if(s.content&&i.push({text:s.content}),s.imageUrls&&s.imageUrls.length>0)for(let a of s.imageUrls)if(a.startsWith("data:")){let c=a.match(/^data:([^;]+);base64,(.+)$/);c&&i.push({inlineData:{mimeType:c[1],data:c[2]}})}else i.push({fileData:{mimeType:"image/jpeg",fileUri:a}});if(s.audioUrls&&s.audioUrls.length>0)for(let a of s.audioUrls){let c=s.audioFormat?`audio/${s.audioFormat==="m4a"?"mp4":s.audioFormat}`:"audio/mp3";i.push({fileData:{mimeType:c,fileUri:a}})}if(s.videoUrls&&s.videoUrls.length>0)for(let a of s.videoUrls)i.push({fileData:{mimeType:"video/mp4",fileUri:a}});if(s.fileIds&&s.fileIds.length>0)for(let a of s.fileIds)if(a.size!=null&&a.size>$e){let d=a.mimeType||"unknown",l=`${(a.size/(1024*1024)).toFixed(1)}MB`;i.push({text:`[Attached: ${a.id} (${d}, ${l}) \u9225?file too large for direct vision, use tools to process]`})}else if(a.id.startsWith("data:")){let d=a.id.match(/^data:([^;]+);base64,(.+)$/);d&&i.push({inlineData:{mimeType:d[1],data:d[2]}})}else a.id.startsWith("http://")||a.id.startsWith("https://")?i.push({fileData:{mimeType:a.mimeType??"application/octet-stream",fileUri:a.id}}):i.push({fileData:{mimeType:a.mimeType??"application/octet-stream",fileUri:a.id}});i.length>0&&t.push({role:"user",parts:i});break}case"assistant":{o();let i=[];if(s.thinkingBlocks&&s.thinkingBlocks.length>0)for(let a of s.thinkingBlocks){let c={text:a.thinking,thought:!0};a.signature&&(c.thoughtSignature=a.signature),i.push(c)}if(s.content&&i.push({text:s.content}),s.tool_calls&&s.tool_calls.length>0)for(let a of s.tool_calls){let c={};try{c=JSON.parse(a.function.arguments)}catch{}i.push({functionCall:{name:a.function.name,args:c,id:a.id}})}i.length>0&&t.push({role:"model",parts:i});break}case"tool":{let i;try{i=JSON.parse(s.content??"{}")}catch{i={result:s.content??""}}if(n.push({functionResponse:{name:s.name??"",response:i,id:s.tool_call_id??""}}),s.imageUrls&&s.imageUrls.length>0)for(let a of s.imageUrls)if(a.startsWith("data:")){let c=/^data:([^;]+);base64,(.+)$/.exec(a);c&&n.push({inlineData:{mimeType:c[1],data:c[2]}})}else{let c=a.endsWith(".png")?"image/png":a.endsWith(".jpg")||a.endsWith(".jpeg")?"image/jpeg":a.endsWith(".gif")?"image/gif":a.endsWith(".webp")?"image/webp":"image/png";n.push({fileData:{mimeType:c,fileUri:a}})}break}}return o(),{systemInstruction:e,contents:t}}function yy(r){let e={name:r.function.name,description:r.function.description};return r.function.parameters&&(e.parameters=qe(r.function.parameters)),e}function by(r){switch(r){case"STOP":return"stop";case"MAX_TOKENS":return"length";case"SAFETY":return"content_filter";case"RECITATION":return"content_filter";case"LANGUAGE":return"content_filter";case"FINISH_REASON_UNSPECIFIED":return"stop";default:return r.toLowerCase()}}var No=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let i=this.config.baseUrl.replace(/\/+$/,""),c=/\/v\d+$/.test(i)?`${i}/files`:`${i}/v1/files`,d=new FormData,l=new Blob([e],{type:n});d.append("file",l,t),d.append("purpose",this.config.defaultPurpose??"file-extract");let u=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${o}`,...this.config.extraHeaders},body:d,signal:s??AbortSignal.timeout(this.config.timeoutMs??12e4)});if(!u.ok){let g=await u.text().catch(()=>"");throw new Error(`File upload to ${this.config.provider} failed (${u.status}): ${g}`)}let p=await u.json(),m=String(p.id??"");return{url:String(p.download_url??p.url??p.file_url??"")||m,fileId:m,filename:String(p.filename??t),bytes:Number(p.bytes??e.byteLength),mimeType:n,provider:this.config.provider}}};var Uo=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let a=`${this.config.baseUrl.replace(/\/+$/,"")}/v3/files`,c=new FormData,d=new Blob([e],{type:n});c.append("file",d,t),c.append("purpose",this.config.defaultPurpose??"user_data");let l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:c,signal:s??AbortSignal.timeout(this.config.timeoutMs??12e4)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`Volcengine file upload failed (${l.status}): ${m}`)}let u=await l.json(),p=String(u.id??"");return{url:p,fileId:p,filename:t,bytes:e.byteLength,mimeType:n,provider:"volcengine"}}};var $o=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let i=this.config.timeoutMs??18e4,a=s??AbortSignal.timeout(i),c=this.config.baseUrl.replace(/(\/v1beta)$/,"/upload$1/files"),d=await fetch(c,{method:"POST",headers:{"x-goog-api-key":o,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(e.length),"X-Goog-Upload-Header-Content-Type":n,"Content-Type":"application/json"},body:JSON.stringify({file:{display_name:t}}),signal:a});if(!d.ok){let f=await d.text().catch(()=>"");throw new Error(`Gemini file upload init failed (${d.status}): ${f.slice(0,500)}`)}let l=d.headers.get("x-goog-upload-url");if(!l)throw new Error("Gemini file upload: missing x-goog-upload-url in response");let u=await fetch(l,{method:"PUT",headers:{"Content-Length":String(e.length),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:e,signal:a});if(!u.ok){let f=await u.text().catch(()=>"");throw new Error(`Gemini file upload failed (${u.status}): ${f.slice(0,500)}`)}let m=(await u.json()).file;return m.state==="PROCESSING"&&await this.waitForProcessing(m.name,o,a),{url:m.uri,fileId:m.name,filename:t,bytes:parseInt(m.sizeBytes??"0",10)||e.length,mimeType:n,provider:"gemini"}}async waitForProcessing(e,t,n,o=30){let s=`${this.config.baseUrl}/files/${e.replace("files/","")}`;for(let i=0;i<o;i++){if(await new Promise(d=>setTimeout(d,2e3)),n.aborted)throw new Error("Upload aborted during processing wait");let a=await fetch(`${s}?key=${t}`,{signal:n});if(!a.ok)continue;let c=await a.json();if(c.state==="ACTIVE")return;if(c.state==="FAILED")throw new Error("Gemini file processing failed")}}};var jo=class{config;constructor(e){this.config=e}async uploadFile(e,t,n,o,s){let a=`${this.config.hubBaseUrl.replace(/\/+$/,"")}/api/v1/files/upload`,c=new FormData,d=new Blob([e],{type:n});c.append("file",d,t),c.append("purpose","llm_input");let l={};this.config.hubApiKey&&(l.Authorization=`Bearer ${this.config.hubApiKey}`);let u=await fetch(a,{method:"POST",headers:l,body:c,signal:s??AbortSignal.timeout(this.config.timeoutMs??12e4)});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Hub OSS upload failed ${u.status}: ${m.slice(0,200)}`)}let p=await u.json();if(!p.url)throw new Error("Hub OSS upload response missing 'url' field");return{url:p.url,fileId:p.fileId??t,filename:t,bytes:p.bytes??e.byteLength,mimeType:n,provider:this.config.provider??"hub-oss"}}};import{createHmac as ky,randomUUID as Ty}from"node:crypto";function bl(){let r=(process.env.OSS_ACCESS_KEY_ID??process.env.ALIYUN_OSS_ACCESS_KEY_ID??"").trim(),e=(process.env.OSS_ACCESS_KEY_SECRET??process.env.ALIYUN_OSS_ACCESS_KEY_SECRET??"").trim();if(!(!r||!e))return new si({accessKeyId:r,accessKeySecret:e,bucket:(process.env.OSS_BUCKET??process.env.ALIYUN_OSS_BUCKET??"qlogicagent").trim(),region:(process.env.OSS_REGION??process.env.ALIYUN_OSS_REGION??"cn-beijing").trim(),endpoint:(process.env.OSS_ENDPOINT??"").trim()||void 0})}var si=class{config;constructor(e){let t=e.bucket||"qlogicagent",n=e.region||"cn-beijing";this.config={accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,bucket:t,region:n,endpoint:e.endpoint||`${t}.oss-${n}.aliyuncs.com`,pathPrefix:e.pathPrefix||"media",timeoutMs:e.timeoutMs??12e4}}async uploadFile(e,t,n,o,s){let i=new Date().toISOString().slice(0,10),a=Ty().slice(0,8),c=t.replace(/[^a-zA-Z0-9._-]/g,"_"),d=`${this.config.pathPrefix}/${i}/${a}_${c}`,l=`https://${this.config.endpoint}/${d}`,u=new Date().toUTCString(),p=["PUT","",n,u,`/${this.config.bucket}/${d}`].join(`
51
+ `),m=ky("sha1",this.config.accessKeySecret).update(p).digest("base64"),f={Date:u,"Content-Type":n,"Content-Length":String(e.byteLength),Authorization:`OSS ${this.config.accessKeyId}:${m}`},g=await fetch(l,{method:"PUT",headers:f,body:e,signal:s??AbortSignal.timeout(this.config.timeoutMs)});if(!g.ok){let y=await g.text().catch(()=>"");throw new Error(`Aliyun OSS upload failed ${g.status}: ${y.slice(0,300)}`)}return{url:l,fileId:d,filename:c,bytes:e.byteLength,mimeType:n,provider:"aliyun-oss"}}};function Fo(r,e){let n=e.getProvider(r.provider)?.baseUrl;r.baseUrl&&e.applyOverride(r.provider,{baseUrl:r.baseUrl});let o=e.getProvider(r.provider);if(!o)throw new Error(`Unknown LLM provider: "${r.provider}". Available: ${e.listProviders().map(a=>a.id).join(", ")}`);let s=r.baseUrl||o.baseUrl;if(r.baseUrl&&n)try{let a=new URL(r.baseUrl),c=new URL(n);(a.pathname==="/"||a.pathname==="")&&c.pathname!=="/"&&c.pathname!==""&&(s=new URL(c.pathname,r.baseUrl).toString().replace(/\/$/,""))}catch{}return{transport:Sy(o,s),apiKey:r.apiKey,resolvedModel:r.model,providerDef:o}}function wy(r,e,t){switch(r){case"openai-chat":case"openai-responses":return new No({baseUrl:e,provider:t.id,extraHeaders:t.extraHeaders});case"volcengine-responses":return new Uo({baseUrl:e});case"gemini-generatecontent":return new $o({baseUrl:e});default:return vy()}}var Ct=null;function vy(){if(Ct!==null)return Ct||void 0;let r=(process.env.QLOGICAGENT_HUB_URL??process.env.HUB_BASE_URL??"").trim();if(r)return Ct=new jo({hubBaseUrl:r,hubApiKey:(process.env.QLOGICAGENT_HUB_API_KEY??process.env.HUB_API_KEY??"").trim()||void 0}),Ct;let e=bl();if(e)return Ct=e,Ct;Ct=void 0}function Sy(r,e){let t,n=wy(r.transport,e,r);switch(r.transport){case"openai-chat":t=new Kt({baseUrl:e,extraHeaders:r.extraHeaders,supportsStreamOptions:r.supportsStreamOptions,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks,fileUploadAdapter:n});break;case"openai-responses":t=new Do({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks,fileUploadAdapter:n});break;case"anthropic-messages":t=new Sn({baseUrl:e,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks,fileUploadAdapter:n});break;case"volcengine-responses":t=new Lo({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks,fileUploadAdapter:n});break;case"gemini-generatecontent":t=new Rn({baseUrl:e,quirks:r.quirks,fileUploadAdapter:n});break;default:throw new Error(`Unsupported transport type: "${r.transport}" for provider "${r.id}"`)}if(r.transport==="anthropic-messages"&&r.quirks?.supportsPrefixCompletion){let o=e.replace(/\/anthropic\/?$/,""),s=new Kt({baseUrl:o,quirks:r.quirks});return new ii(t,s)}return t}var ii=class{constructor(e,t){this.primary=e;this.prefixTransport=t}primary;prefixTransport;async*stream(e,t,n){yield*(e.prefixMessage?this.prefixTransport:this.primary).stream(e,t,n)}async*complete(e,t,n){if(this.prefixTransport.complete)yield*this.prefixTransport.complete(e,t,n);else throw new Error("FIM completion is not supported by this transport")}};var _n=class{baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??3e5}async uploadFile(e,t,n,o){let s=e instanceof Blob?Buffer.from(await e.arrayBuffer()):e,i=n?.mimeType??"application/octet-stream",a=n?.displayName??"upload",c=this.baseUrl.replace(/(\/v1beta)$/,"/upload$1/files"),d=await fetch(c,{method:"POST",headers:{"x-goog-api-key":t,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(s.length),"X-Goog-Upload-Header-Content-Type":i,"Content-Type":"application/json"},body:JSON.stringify({file:{display_name:a}}),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let m=await d.text().catch(()=>"");throw new Error(`Gemini file upload init error ${d.status}: ${m.slice(0,500)}`)}let l=d.headers.get("x-goog-upload-url");if(!l)throw new Error("Gemini file upload: missing x-goog-upload-url in response headers");let u=await fetch(l,{method:"PUT",headers:{"Content-Length":String(s.length),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:s,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Gemini file upload error ${u.status}: ${m.slice(0,500)}`)}return(await u.json()).file}async waitForProcessing(e,t,n){let o=n?.pollIntervalMs??2500,s=n?.maxWaitMs??12e4,i=Date.now();for(;Date.now()-i<s;){let a=await this.getFile(e,t);if(a.state==="ACTIVE")return a;if(a.state==="FAILED")throw new Error(`Gemini file processing failed: ${a.error?.message??"unknown error"}`);await new Promise(c=>setTimeout(c,o))}throw new Error(`Gemini file processing timed out after ${s}ms`)}async getFile(e,t,n){let o=`${this.baseUrl}/${e}`,s=await fetch(o,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini file get error ${s.status}: ${i.slice(0,500)}`)}return await s.json()}async listFiles(e,t,n){let o=new URLSearchParams;t?.pageSize&&o.set("pageSize",String(t.pageSize)),t?.pageToken&&o.set("pageToken",t.pageToken);let s=`${this.baseUrl}/files?${o.toString()}`,i=await fetch(s,{method:"GET",headers:{"x-goog-api-key":e},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Gemini file list error ${i.status}: ${c.slice(0,500)}`)}let a=await i.json();return{files:a.files??[],nextPageToken:a.nextPageToken}}async deleteFile(e,t,n){let o=`${this.baseUrl}/${e}`,s=await fetch(o,{method:"DELETE",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini file delete error ${s.status}: ${i.slice(0,500)}`)}}};import{join as Ry}from"node:path";import{mkdirSync as _y,appendFileSync as xy}from"node:fs";var kl=Kc();function ai(){return process.env.QLOGICAGENT_DEBUG==="1"}function ci(r,e){let t=Ry(kl,`${e}.jsonl`),n=!1;function o(){n||(_y(kl,{recursive:!0}),n=!0)}function s(i){try{o(),xy(t,JSON.stringify(i)+`
52
+ `,"utf8")}catch{}}return{async*stream(i,a,c){let d=Date.now();s({type:"request",timestamp:new Date(d).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 l=0,u=0,p=0,m="",f;try{for await(let g of r.stream(i,a,c))g.type==="usage"?(l=g.promptTokens,u=g.completionTokens,p=g.reasoningTokens??0):g.type==="done"&&(m=g.finishReason),yield g}catch(g){throw f=g instanceof Error?g.message:String(g),g}finally{let g=Date.now()-d;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:g,promptTokens:l,completionTokens:u,reasoningTokens:p,finishReason:m,...f?{error:f}:{}})}}}}function li(r){return typeof r.deleteVideoTask=="function"&&typeof r.listVideoTasks=="function"}function di(r){let e=new Map;return{register(t){let n=e.get(t.point)??[],o={handler:t.handler,priority:t.priority??100,label:t.label};return n.push(o),n.sort((s,i)=>s.priority-i.priority),e.set(t.point,n),()=>{let s=n.indexOf(o);s>=0&&n.splice(s,1)}},async invoke(t,n){let o=e.get(t);if(!o||o.length===0)return{action:"continue",context:n};let s=n;for(let i of o)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 r.info({hook:t,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){r.warn({hook:t,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}import{readFile as Tl,readdir as Ay,stat as Cy}from"node:fs/promises";import{existsSync as wl}from"node:fs";import{join as Py}from"node:path";var Ne={MAX_SCAN_FILES:100,MAX_SELECTED:5,MAX_FILE_BYTES:4096,MAX_TOTAL_BYTES:20*1024,MIN_SCORE:.2,HEADER_LINES:10,RECENCY_DAYS:7,RECENCY_BOOST:.15};async function vl(r,e,t=new Set){if(!r.trim()||!wl(e))return[];let n=r.trim().split(/\s+/);if(n.length<2&&n[0].length<4)return[];let o=await Iy(e);if(o.length===0)return[];let s=o.filter(c=>!t.has(c.filePath));if(s.length===0)return[];let a=My(r,s).filter(c=>c.score>=Ne.MIN_SCORE).slice(0,Ne.MAX_SELECTED);return a.length===0?[]:Ey(a)}async function Iy(r){if(!wl(r))return[];let e;try{e=await Ay(r)}catch{return[]}let t=e.filter(o=>o.endsWith(".md")&&o!=="INDEX.md");return(await Promise.allSettled(t.map(async o=>{let s=Py(r,o),i=await Cy(s),c=(await Tl(s,"utf-8")).split(`
53
+ `),d=null;for(let u=0;u<Math.min(c.length,Ne.HEADER_LINES);u++){let p=c[u].trim();if(!(!p||p.startsWith("#")||p.startsWith("---"))){d=p.slice(0,150);break}}let l=Oy(o);return{filename:o,filePath:s,mtimeMs:i.mtimeMs,sizeBytes:i.size,description:d,category:l}}))).filter(o=>o.status==="fulfilled").map(o=>o.value).sort((o,s)=>s.mtimeMs-o.mtimeMs).slice(0,Ne.MAX_SCAN_FILES)}function My(r,e){let t=ui(r);if(t.length===0)return[];let n=Date.now(),o=Ne.RECENCY_DAYS*24*60*60*1e3;return e.map(i=>{let a=0,c=ui(i.filename.replace(/\.md$/,"").replace(/[-_]/g," ")),d=t.filter(l=>c.some(u=>u.includes(l)||l.includes(u))).length;if(a+=Math.min(.5,d/t.length*.5),i.description){let l=ui(i.description),u=t.filter(p=>l.some(m=>m.includes(p)||p.includes(m))).length;a+=Math.min(.3,u/t.length*.3)}return i.category&&Dy(r).includes(i.category)&&(a+=.1),n-i.mtimeMs<o&&(a+=Ne.RECENCY_BOOST),{header:i,score:a}}).sort((i,a)=>a.score-i.score)}async function Ey(r){let e=[],t=0;for(let{header:n,score:o}of r){if(t>=Ne.MAX_TOTAL_BYTES)break;try{let s=await Tl(n.filePath,"utf-8"),i=!1;s.length>Ne.MAX_FILE_BYTES&&(s=s.slice(0,Ne.MAX_FILE_BYTES)+`
54
54
 
55
- > [Truncated at ${Le.MAX_FILE_BYTES} bytes. Use memory tool read_file for full content: ${n.filename}]`,i=!0);let a=Buffer.byteLength(s,"utf-8");if(t+a>Le.MAX_TOTAL_BYTES){let c=Le.MAX_TOTAL_BYTES-t;s=s.slice(0,c)+`
55
+ > [Truncated at ${Ne.MAX_FILE_BYTES} bytes. Use memory tool read_file for full content: ${n.filename}]`,i=!0);let a=Buffer.byteLength(s,"utf-8");if(t+a>Ne.MAX_TOTAL_BYTES){let c=Ne.MAX_TOTAL_BYTES-t;s=s.slice(0,c)+`
56
56
 
57
- > [Truncated to fit session budget. Use memory tool read_file for full content: ${n.filename}]`,i=!0}t+=Buffer.byteLength(s,"utf-8"),e.push({filename:n.filename,filePath:n.filePath,mtimeMs:n.mtimeMs,score:o,content:s,truncated:i})}catch{}}return e}function ai(r){return r.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g," ").split(/\s+/).filter(e=>e.length>1)}function wy(r){let e=r.replace(/\.md$/,""),t=["lesson","project","pattern","preference","fact","decision","task","reference"];for(let n of t)if(e.startsWith(n+"-")||e.startsWith(n+"_"))return n;return null}function vy(r){let e=[],t=r.toLowerCase();return/(?:bug|error|fix|debug|issue|问题|报错|修复)/.test(t)&&e.push("lesson"),/(?:architecture|设计|架构|决定|decision)/.test(t)&&e.push("decision"),/(?:pattern|convention|惯例|标准|practice)/.test(t)&&e.push("pattern"),/(?:prefer|style|偏好|风格|习惯)/.test(t)&&e.push("preference"),/(?:deploy|port|config|version|部署|配置|环境)/.test(t)&&e.push("fact"),/(?:project|repo|codebase|项目|仓库)/.test(t)&&e.push("project"),/(?:task|todo|plan|任务|计划)/.test(t)&&e.push("task"),/(?:api|doc|guide|reference|文档|手册)/.test(t)&&e.push("reference"),e}function hc(r){if(r.length===0)return"";let e=Date.now();return r.map(n=>{let o=Math.floor((e-n.mtimeMs)/864e5);return`## Memory (saved ${o===0?"today":o===1?"yesterday":`${o} days ago`}): ${n.filename}
57
+ > [Truncated to fit session budget. Use memory tool read_file for full content: ${n.filename}]`,i=!0}t+=Buffer.byteLength(s,"utf-8"),e.push({filename:n.filename,filePath:n.filePath,mtimeMs:n.mtimeMs,score:o,content:s,truncated:i})}catch{}}return e}function ui(r){return r.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g," ").split(/\s+/).filter(e=>e.length>1)}function Oy(r){let e=r.replace(/\.md$/,""),t=["lesson","project","pattern","preference","fact","decision","task","reference"];for(let n of t)if(e.startsWith(n+"-")||e.startsWith(n+"_"))return n;return null}function Dy(r){let e=[],t=r.toLowerCase();return/(?:bug|error|fix|debug|issue|问题|报错|修复)/.test(t)&&e.push("lesson"),/(?:architecture|设计|架构|决定|decision)/.test(t)&&e.push("decision"),/(?:pattern|convention|惯例|标准|practice)/.test(t)&&e.push("pattern"),/(?:prefer|style|偏好|风格|习惯)/.test(t)&&e.push("preference"),/(?:deploy|port|config|version|部署|配置|环境)/.test(t)&&e.push("fact"),/(?:project|repo|codebase|项目|仓库)/.test(t)&&e.push("project"),/(?:task|todo|plan|任务|计划)/.test(t)&&e.push("task"),/(?:api|doc|guide|reference|文档|手册)/.test(t)&&e.push("reference"),e}function Sl(r){if(r.length===0)return"";let e=Date.now();return r.map(n=>{let o=Math.floor((e-n.mtimeMs)/864e5);return`## Memory (saved ${o===0?"today":o===1?"yesterday":`${o} days ago`}): ${n.filename}
58
58
 
59
59
  ${n.content}`}).join(`
60
60
 
61
61
  ---
62
62
 
63
- `)}Js();De();var zt={MAX_SESSION_BYTES:fs,LIMIT_PER_RECALL:hs,MAX_SURFACED_ENTRIES:ys};function Ct(){return{surfacedPaths:new Set,sessionBytes:0}}function yc(r,e,t){let n=[],o=t??Ct(),s,i=[];return n.push(r.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,c)=>{if(!e.memoryProvider||!c.query)return{action:"continue",context:c};if(o.sessionBytes>=zt.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:c};try{let d=await e.memoryProvider.search(c.query,e.userId,{limit:zt.LIMIT_PER_RECALL}),l=d.filter(p=>{let g=p,f=g.path??g.id??"";if(!f)return!0;if(o.surfacedPaths.has(f))return!1;let m=(g.content?.length??0)*2;if(o.sessionBytes+m>zt.MAX_SESSION_BYTES)return!1;if(o.surfacedPaths.add(f),o.sessionBytes+=m,o.surfacedPaths.size>zt.MAX_SURFACED_ENTRIES){let y=o.surfacedPaths.values().next().value;y!==void 0&&o.surfacedPaths.delete(y)}return!0});s=c.turnId,i=l,e.log.debug(`memory.before_recall: prefetched ${d.length} \u2192 ${l.length} after dedup (${o.sessionBytes} bytes used)`);let u=l.map(p=>{let g=p;return{text:g.text??g.content??"",score:g.score,category:g.metadata?.category??null}}).filter(p=>p.text);if(c.preferredCategories?.length||c.deprioritizedCategories?.length){let p={scenario:"general",preferred:c.preferredCategories??[],deprioritized:c.deprioritizedCategories??[],confidence:1};u=u.map(g=>({...g,score:Ks(g.score??.5,g.category,p)})).sort((g,f)=>(f.score??0)-(g.score??0))}return{action:"continue",context:{...c,recalledMemories:u}}}catch(d){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${d instanceof Error?d.message:String(d)}`),i=[]}return{action:"continue",context:c}}})),n.push(r.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,c)=>{let d=s===c.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${c.blockCount??0} blocks assembled, ${d} qmemory results (session: ${o.sessionBytes} bytes)`),{action:"continue",context:c}}})),()=>{for(let a of n)a();i=[]}}function bc(r,e,t){let n=t??Ct();return r.register({point:"memory.before_recall",priority:40,label:"memdir-cross-file-recall",handler:async(s,i)=>{let a=e.getMemdir();if(!a||!i.query)return{action:"continue",context:i};if(n.sessionBytes>=zt.MAX_SESSION_BYTES)return e.log.debug("memdir-recall: session byte budget exhausted, skipping"),{action:"continue",context:i};try{let c=a.getRootPath(),d=await fc(i.query,c,n.surfacedPaths);if(d.length===0)return{action:"continue",context:i};if(i.preferredCategories?.length||i.deprioritizedCategories?.length){let f={scenario:"general",preferred:i.preferredCategories??[],deprioritized:i.deprioritizedCategories??[],confidence:1};d=d.map(m=>({...m,score:Ks(m.score,Ll(m.filename),f)})).sort((m,y)=>y.score-m.score)}let l=d.filter(f=>{let m=Buffer.byteLength(f.content,"utf-8");return n.sessionBytes+m>zt.MAX_SESSION_BYTES?!1:(n.surfacedPaths.add(f.filePath),n.sessionBytes+=m,!0)});if(l.length===0)return{action:"continue",context:i};e.log.debug(`memdir-recall: found ${d.length} \u2192 accepted ${l.length} files (${n.sessionBytes} bytes used)`);let u=hc(l),p=i.recalledMemories??[];return{action:"continue",context:{...i,recalledMemories:[...[{text:u,score:.9}],...p]}}}catch(c){e.log.warn(`memdir-recall: cross-file recall failed: ${c instanceof Error?c.message:String(c)}`)}return{action:"continue",context:i}}})}import*as jo from"node:fs";import*as vn from"node:path";De();var No={MAX_RECALLED_SKILLS:Zr,MAX_SKILL_CONTENT_CHARS:es,CACHE_TTL_MS:ts};function Sy(r){let e=[/之前.{0,8}(?:做过|写过|实现过|处理过|用过|搞过|弄过)/,/以前.{0,8}(?:做过|写过|实现过|处理过|用过)/,/(?:上次|上回|之前|以前).{0,12}(?:不是|是不是|已经).{0,8}(?:做|写|实现|处理)/,/(?:参考|参照|照着|按照).{0,6}(?:项目|工程|仓库)/,/(?:那个|那边|另一个).{0,6}(?:项目|工程).{0,6}(?:里|中|的)/,/(?:跟|和|像).{0,6}(?:项目|工程).{0,6}(?:一样|类似|差不多)/,/(?:复用|重用|搬过来|拿过来|移过来|copy过来)/],t=[/(?:有没有|有无|是否有).{0,6}(?:技能|skill|模板|template|现成的)/,/(?:能不能|可以).{0,6}(?:自动|像之前|快速).{0,6}(?:生成|创建|写|做)/,/(?:跟|和|类似|像).{0,4}(?:上次|之前|其他|那个).{0,4}(?:一样|类似)/,/(?:批量|自动化|一键).{0,6}(?:生成|创建|部署|处理)/,/(?:同样的|相同的|一样的).{0,4}(?:方式|方法|流程|步骤)/],n=[/(?:before|previously|earlier|last time).{0,20}(?:did|done|made|built|implemented|wrote)/i,/(?:didn't|did) you.{0,15}(?:already|before|earlier)/i,/(?:same|similar).{0,10}(?:as|to|like).{0,10}(?:project|repo)/i,/(?:reuse|re-use|copy from|bring over|port from).{0,15}(?:project|repo)/i,/(?:remember|recall).{0,10}(?:doing|making|building|writing)/i,/(?:other|another|different)\s+project/i],o=[/(?:is there|do you have|any).{0,10}(?:skill|template|automation|workflow)/i,/(?:like|similar to|same as).{0,15}(?:last time|before|the other)/i,/(?:automate|batch|bulk).{0,10}(?:create|generate|process|build)/i,/(?:can you|could you).{0,10}(?:do the same|repeat|replicate)/i];if(![...e,...t,...n,...o].some(c=>c.test(r)))return null;let a=xy(r);return a.length>0?a:null}function xy(r){let t=r.replace(/之前|以前|上次|上回|不是|是不是|已经|做过|写过|实现过|处理过|用过|搞过|弄过/g," ").replace(/参考|参照|照着|按照|项目|工程|仓库|那个|那边|另一个|里|中|的|跟|和|像|一样|类似|差不多/g," ").replace(/复用|重用|搬过来|拿过来|移过来/g," ").replace(/\b(the|a|an|is|was|were|did|didn't|do|you|i|we|it|this|that|before|previously|earlier|last|time|already|same|similar|as|to|like|from|project|repo|remember|recall|doing|making|building|writing|other|another|different)\b/gi," ").trim().split(/[\s,;.!?,。!?、;:""''()\[\]{}]+/).filter(n=>n.length>=2).map(n=>n.toLowerCase());return[...new Set(t)].slice(0,8)}var Uo=null,li=0;function Ry(r){let e=Date.now();if(Uo&&e-li<No.CACHE_TTL_MS)return Uo;let t=[],n=ec(r);for(let o of n){let s=vn.join(o,".qlogicagent","skills");try{let i=jo.readdirSync(s,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=vn.join(s,a.name,"SKILL.md");try{let d=jo.readFileSync(c,"utf8"),l=d.split(`
64
- `).slice(0,5).join(" ").toLowerCase();t.push({name:a.name,projectDir:o,projectName:vn.basename(o),content:d,searchText:`${a.name.toLowerCase()} ${l}`})}catch{}}}catch{}}return Uo=t,li=e,t}function _y(r,e){if(r.length===0)return[];let t=Ry(e);return t.length===0?[]:t.map(o=>{let s=0;for(let i of r)o.searchText.includes(i)&&(s+=2),o.name.includes(i)&&(s+=3);return{skill:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,No.MAX_RECALLED_SKILLS).map(o=>o.skill)}function kc(r,e){return r.register({point:"memory.before_recall",priority:60,label:"cross-project-skill-recall",handler:(n,o)=>{let s=o.query;if(!s)return{action:"continue",context:o};let i=Sy(s);if(!i)return{action:"continue",context:o};e.log.debug(`skill-recall: retrospective trigger detected, keywords: [${i.join(", ")}]`);let a=_y(i,e.currentCwd);if(a.length===0)return e.log.debug("skill-recall: no cross-project skill matches found"),{action:"continue",context:o};e.log.debug(`skill-recall: found ${a.length} cross-project skill(s): ${a.map(l=>`${l.name}@${l.projectName}`).join(", ")}`);let c=o.recalledMemories??[],d=a.map(l=>{let u=l.content.length>No.MAX_SKILL_CONTENT_CHARS?l.content.slice(0,No.MAX_SKILL_CONTENT_CHARS)+`
63
+ `)}Zs();ye();var qt={MAX_SESSION_BYTES:bs,LIMIT_PER_RECALL:ks,MAX_SURFACED_ENTRIES:Ts};function Pt(){return{surfacedPaths:new Set,sessionBytes:0}}function Rl(r,e,t){let n=[],o=t??Pt(),s,i=[];return n.push(r.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,c)=>{if(!e.memoryProvider||!c.query)return{action:"continue",context:c};if(o.sessionBytes>=qt.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:c};try{let d=await e.memoryProvider.search(c.query,e.userId,{limit:qt.LIMIT_PER_RECALL}),l=d.filter(p=>{let m=p,f=m.path??m.id??"";if(!f)return!0;if(o.surfacedPaths.has(f))return!1;let g=(m.content?.length??0)*2;if(o.sessionBytes+g>qt.MAX_SESSION_BYTES)return!1;if(o.surfacedPaths.add(f),o.sessionBytes+=g,o.surfacedPaths.size>qt.MAX_SURFACED_ENTRIES){let y=o.surfacedPaths.values().next().value;y!==void 0&&o.surfacedPaths.delete(y)}return!0});s=c.turnId,i=l,e.log.debug(`memory.before_recall: prefetched ${d.length} \u922B?${l.length} after dedup (${o.sessionBytes} bytes used)`);let u=l.map(p=>{let m=p;return{text:m.text??m.content??"",score:m.score,category:m.metadata?.category??null}}).filter(p=>p.text);if(c.preferredCategories?.length||c.deprioritizedCategories?.length){let p={scenario:"general",preferred:c.preferredCategories??[],deprioritized:c.deprioritizedCategories??[],confidence:1};u=u.map(m=>({...m,score:Qs(m.score??.5,m.category,p)})).sort((m,f)=>(f.score??0)-(m.score??0))}return{action:"continue",context:{...c,recalledMemories:u}}}catch(d){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${d instanceof Error?d.message:String(d)}`),i=[]}return{action:"continue",context:c}}})),n.push(r.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,c)=>{let d=s===c.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${c.blockCount??0} blocks assembled, ${d} qmemory results (session: ${o.sessionBytes} bytes)`),{action:"continue",context:c}}})),()=>{for(let a of n)a();i=[]}}function _l(r,e,t){let n=t??Pt();return r.register({point:"memory.before_recall",priority:40,label:"memdir-cross-file-recall",handler:async(s,i)=>{let a=e.getMemdir();if(!a||!i.query)return{action:"continue",context:i};if(n.sessionBytes>=qt.MAX_SESSION_BYTES)return e.log.debug("memdir-recall: session byte budget exhausted, skipping"),{action:"continue",context:i};try{let c=a.getRootPath(),d=await vl(i.query,c,n.surfacedPaths);if(d.length===0)return{action:"continue",context:i};if(i.preferredCategories?.length||i.deprioritizedCategories?.length){let f={scenario:"general",preferred:i.preferredCategories??[],deprioritized:i.deprioritizedCategories??[],confidence:1};d=d.map(g=>({...g,score:Qs(g.score,Wc(g.filename),f)})).sort((g,y)=>y.score-g.score)}let l=d.filter(f=>{let g=Buffer.byteLength(f.content,"utf-8");return n.sessionBytes+g>qt.MAX_SESSION_BYTES?!1:(n.surfacedPaths.add(f.filePath),n.sessionBytes+=g,!0)});if(l.length===0)return{action:"continue",context:i};e.log.debug(`memdir-recall: found ${d.length} \u922B?accepted ${l.length} files (${n.sessionBytes} bytes used)`);let u=Sl(l),p=i.recalledMemories??[];return{action:"continue",context:{...i,recalledMemories:[...[{text:u,score:.9}],...p]}}}catch(c){e.log.warn(`memdir-recall: cross-file recall failed: ${c instanceof Error?c.message:String(c)}`)}return{action:"continue",context:i}}})}import*as Go from"node:fs";import*as xn from"node:path";ye();var Wo={MAX_RECALLED_SKILLS:ns,MAX_SKILL_CONTENT_CHARS:os,CACHE_TTL_MS:rs};function Ly(r){let e=[/之前.{0,8}(?:做过|写过|实现过|处理过|用过|搞过|弄过)/,/以前.{0,8}(?:做过|写过|实现过|处理过|用过)/,/(?:上次|上回|之前|以前).{0,12}(?:不是|是不是|已经).{0,8}(?:做|写|实现|处理)/,/(?:参考|参照|照着|按照).{0,6}(?:项目|工程|仓库)/,/(?:那个|那边|另一个).{0,6}(?:项目|工程).{0,6}(?:里|中|的)/,/(?:跟|和|像).{0,6}(?:项目|工程).{0,6}(?:一样|类似|差不多)/,/(?:复用|重用|搬过来|拿过来|移过来|copy过来)/],t=[/(?:有没有|有无|是否有).{0,6}(?:技能|skill|模板|template|现成的)/,/(?:能不能|可以).{0,6}(?:自动|像之前|快速).{0,6}(?:生成|创建|写|做)/,/(?:跟|和|类似|像).{0,4}(?:上次|之前|其他|那个).{0,4}(?:一样|类似)/,/(?:批量|自动化|一键).{0,6}(?:生成|创建|部署|处理)/,/(?:同样的|相同的|一样的).{0,4}(?:方式|方法|流程|步骤)/],n=[/(?:before|previously|earlier|last time).{0,20}(?:did|done|made|built|implemented|wrote)/i,/(?:didn't|did) you.{0,15}(?:already|before|earlier)/i,/(?:same|similar).{0,10}(?:as|to|like).{0,10}(?:project|repo)/i,/(?:reuse|re-use|copy from|bring over|port from).{0,15}(?:project|repo)/i,/(?:remember|recall).{0,10}(?:doing|making|building|writing)/i,/(?:other|another|different)\s+project/i],o=[/(?:is there|do you have|any).{0,10}(?:skill|template|automation|workflow)/i,/(?:like|similar to|same as).{0,15}(?:last time|before|the other)/i,/(?:automate|batch|bulk).{0,10}(?:create|generate|process|build)/i,/(?:can you|could you).{0,10}(?:do the same|repeat|replicate)/i];if(![...e,...t,...n,...o].some(c=>c.test(r)))return null;let a=Ny(r);return a.length>0?a:null}function Ny(r){let t=r.replace(/之前|以前|上次|上回|不是|是不是|已经|做过|写过|实现过|处理过|用过|搞过|弄过/g," ").replace(/参考|参照|照着|按照|项目|工程|仓库|那个|那边|另一个|里|中|的|跟|和|像|一样|类似|差不多/g," ").replace(/复用|重用|搬过来|拿过来|移过来/g," ").replace(/\b(the|a|an|is|was|were|did|didn't|do|you|i|we|it|this|that|before|previously|earlier|last|time|already|same|similar|as|to|like|from|project|repo|remember|recall|doing|making|building|writing|other|another|different)\b/gi," ").trim().split(/[\s,;.!?,。!?、;:""''()\[\]{}]+/).filter(n=>n.length>=2).map(n=>n.toLowerCase());return[...new Set(t)].slice(0,8)}var Bo=null,pi=0;function Uy(r){let e=Date.now();if(Bo&&e-pi<Wo.CACHE_TTL_MS)return Bo;let t=[],n=al(r);for(let o of n){let s=xn.join(o,".qlogicagent","skills");try{let i=Go.readdirSync(s,{withFileTypes:!0});for(let a of i){if(!a.isDirectory())continue;let c=xn.join(s,a.name,"SKILL.md");try{let d=Go.readFileSync(c,"utf8"),l=d.split(`
64
+ `).slice(0,5).join(" ").toLowerCase();t.push({name:a.name,projectDir:o,projectName:xn.basename(o),content:d,searchText:`${a.name.toLowerCase()} ${l}`})}catch{}}}catch{}}return Bo=t,pi=e,t}function $y(r,e){if(r.length===0)return[];let t=Uy(e);return t.length===0?[]:t.map(o=>{let s=0;for(let i of r)o.searchText.includes(i)&&(s+=2),o.name.includes(i)&&(s+=3);return{skill:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,Wo.MAX_RECALLED_SKILLS).map(o=>o.skill)}function xl(r,e){return r.register({point:"memory.before_recall",priority:60,label:"cross-project-skill-recall",handler:(n,o)=>{let s=o.query;if(!s)return{action:"continue",context:o};let i=Ly(s);if(!i)return{action:"continue",context:o};e.log.debug(`skill-recall: retrospective trigger detected, keywords: [${i.join(", ")}]`);let a=$y(i,e.currentCwd);if(a.length===0)return e.log.debug("skill-recall: no cross-project skill matches found"),{action:"continue",context:o};e.log.debug(`skill-recall: found ${a.length} cross-project skill(s): ${a.map(l=>`${l.name}@${l.projectName}`).join(", ")}`);let c=o.recalledMemories??[],d=a.map(l=>{let u=l.content.length>Wo.MAX_SKILL_CONTENT_CHARS?l.content.slice(0,Wo.MAX_SKILL_CONTENT_CHARS)+`
65
65
  ...(truncated)`:l.content;return{text:[`[Cross-project skill available] Skill "${l.name}" learned in project "${l.projectName}" (${l.projectDir}):`,u,`\u2192 To use this skill in current project: use skill tool with action "create" name "${l.name}" and copy the content above`,`\u2192 After creating locally, promote to global: skill tool with action "promote" name "${l.name}"`,"\u2192 Or just follow the instructions above directly without saving"].join(`
66
- `),score:.85}});return{action:"continue",context:{...o,recalledMemories:[...c,...d]}}}})}function At(){Uo=null,li=0}import{ClawQMemoryAdapter as Cy}from"qlogicagent-adapter-claw";var Tc="qmemory";function wc(r){let e=new Cy({baseUrl:r.baseUrl,apiKey:r.apiKey,timeout:r.timeoutMs??5e3});function t(n){return r.userIdPrefix?`${r.userIdPrefix}:${n}`:n}return{providerId:Tc,async search(n,o,s){return((await e.dispatch("memory.search",{q:n,user_id:t(o),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:Tc,metadata:a.metadata}))},async ingest(n,o,s){await e.dispatch("memory.addKnowledge",{user_id:t(o),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,o,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:t(o),text:n,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(n,o,s){if(n.length===0)return{memoriesAdded:0};let i=t(o),a=await Promise.allSettled(n.map(d=>e.dispatch("memory.addFact",{user_id:i,text:d.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...d.category?{category:d.category}:{},...typeof d.importance=="number"?{importance:d.importance}:{},...d.speaker?{speaker:d.speaker}:{},...d.event_date?{event_date:d.event_date}:{},...d.tags?.length?{tags:d.tags}:{}}}))),c=0;for(let d of a)d.status==="fulfilled"&&(c+=d.value.memories_added??1);return{memoriesAdded:c}},async remove(n){try{return await e.dispatch("memory.forget",{id:n}),!0}catch{return!1}},async feedback(n,o,s){await e.dispatch("memory.feedback",{memory_ids:n,signal:o,...s?{session_id:s}:{}})},async triggerDecay(n,o){let s=await e.dispatch("memory.decay",{user_id:t(n),temporal_expiry:o?.temporalExpiry??!0,staleness_decay:o?.stalenessDecay??!0,noise_archival:o?.noiseArchival??!0});return{decayed:s.decayed??0,archived:s.archived??0}}}}import{readFile as Ic,writeFile as di,stat as $c,unlink as Gy,mkdir as Hy}from"node:fs/promises";import{join as Fo,resolve as Pc,isAbsolute as Mc,normalize as Ec}from"node:path";import{randomUUID as Wy}from"node:crypto";function vc(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function Ay(r){return r.latestInputTokens+r.cumulativeOutputTokens}var Iy=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),Sc=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function Py(r){return{isSearch:Iy.has(r)||void 0,isRead:Sc.has(r)||void 0}}function My(r,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${Sc.has(r)?"Reading":r.includes("write")||r.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 o=e.query??e.pattern??e.search;if(typeof o=="string")return`Searching: ${o}`}function xc(r,e){r.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),r.cumulativeOutputTokens+=e.output_tokens??0}function Rc(r,e,t,n){r.toolUseCount++;let o=Py(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??My(e,t),isSearch:o.isSearch,isRead:o.isRead};for(r.recentActivities.push(s);r.recentActivities.length>5;)r.recentActivities.shift()}function ci(r){return{toolUseCount:r.toolUseCount,tokenCount:Ay(r),lastActivity:r.recentActivities.length>0?r.recentActivities[r.recentActivities.length-1]:void 0,recentActivities:[...r.recentActivities]}}import{randomUUID as _c}from"node:crypto";function Ey(r){let e=new AbortController;return r&&(r.aborted?e.abort(r.reason):r.addEventListener("abort",()=>{e.abort(r.reason)},{once:!0})),e}async function Sn(r){let e=Date.now(),t=[],n={prompt:0,completion:0},o=vc(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:c,transport:d,toolInvoker:l,apiKey:u,model:p,log:g,hooks:f,forkLabel:m,maxTurns:y,temperature:k,parentSignal:b,onEvent:x,onProgress:S,budgetTokens:A,parentDepth:$}=r,D=Ey(b),B=`fork-${m}-${_c().slice(0,8)}`,v=`fork-session-${_c().slice(0,8)}`;g.info(`[fork:${m}] starting \u2014 ${s.length} initial messages, model=${p}`);let oe=c?{invoke:async(me,Ae,q,X)=>{let be={};try{be=JSON.parse(q)}catch{}let ge=c(Ae,be);return ge.allowed?l.invoke(me,Ae,q,X):(g.info(`[fork:${m}] tool ${Ae} denied: ${ge.reason}`),{result:"",error:ge.reason})}}:l,T=!0,E;try{let{Agent:me}=await Promise.resolve().then(()=>(wo(),$l)),Ae=new me({llmTransport:d,apiKey:u,toolInvoker:oe,log:g,hooks:f,maxRounds:y});for await(let q of Ae.run({turnId:B,sessionId:v,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:u,temperature:k,maxOutputTokens:r.maxOutputTokens,parentDepth:$}},D.signal)){if(t.push(q),x?.(q),q.type==="end"&&q.usage&&(xc(o,{input_tokens:q.usage.prompt,output_tokens:q.usage.completion}),n.prompt+=q.usage.prompt,n.completion+=q.usage.completion,q.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+q.usage.cacheRead),q.usage.cacheCreation&&(n.cacheCreation=(n.cacheCreation??0)+q.usage.cacheCreation),A&&A>0)){let X=n.prompt+n.completion+(n.reasoning??0);X>=A&&(g.info(`[fork:${m}] budget exceeded (${X} / ${A} tokens), aborting`),D.abort("budget_exceeded"))}if(q.type==="tool_call"){let X={};try{X=JSON.parse(q.arguments??"{}")}catch{}Rc(o,q.name,X),S?.(ci(o))}q.type==="error"&&(T=!1,E=q.error)}}catch(me){T=!1,E=me instanceof Error?me.message:String(me),g.warn(`[fork:${m}] error: ${E}`)}finally{D.signal.aborted||D.abort("fork_complete")}let V=Date.now()-e;return g.info(`[fork:${m}] finished in ${V}ms \u2014 ${t.length} events, usage: prompt=${n.prompt} completion=${n.completion}, ok=${T}`),{events:t,totalUsage:n,progress:ci(o),durationMs:V,ok:T,error:E}}import{readFile as Oy,readdir as Dy}from"node:fs/promises";import{existsSync as Ly}from"node:fs";import{join as $y}from"node:path";var Uy={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",tradeoff:"decision",skill:"skill-learning",workflow:"skill-learning"},Ny={lesson:[/(?:原来|root cause|turns out|the issue was|问题出在|踩坑|gotcha|pitfall)/i,/(?:以后|下次|remember to|don't forget|务必|切记)/i],preference:[/(?:我(?:喜欢|偏好|习惯)|I (?:prefer|like|always))/i,/(?:请(?:用|使用)|please use|always use)/i],pattern:[/(?:每次|always|whenever|pattern|惯例|convention|best practice)/i],fact:[/(?:架构|architecture|port|version|部署|deployed|环境|配置|config)/i],decision:[/(?:决定|decided|选择|chosen|采用|因为|because|rationale|trade-?off)/i],"skill-learning":[/(?:skill|workflow|tool|command|命令|工具)/i]};function jy(r){let e=r.replace(/\.md$/,"").toLowerCase();for(let[t,n]of Object.entries(Uy))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return n;return null}function Fy(r){let e=r.slice(0,500),t=null,n=0;for(let[o,s]of Object.entries(Ny)){let i=s.filter(a=>a.test(e)).length;i>n&&(n=i,t=o)}return t}async function Cc(r){let e={},t=0,n=0;if(!Ly(r))return{categories:e,totalFiles:0,uncategorizedCount:0};let o;try{o=await Dy(r)}catch{return{categories:e,totalFiles:0,uncategorizedCount:0}}let s=o.filter(i=>i.endsWith(".md")&&i!=="INDEX.md");for(let i of s){let a=$y(r,i);try{let c=await Oy(a,"utf-8");t++;let d=jy(i)??Fy(c)??"uncategorized";d==="uncategorized"&&n++;let l=c.split(`
67
- `),u="";for(let g of l){let f=g.trim();if(!(!f||f.startsWith("#")||f.startsWith("---"))){u=f.slice(0,120);break}}let p=l.filter(g=>/^\s*[-*+]\s|^\s*\d+[.)]\s/.test(g)).length;e[d]||(e[d]=[]),e[d].push({filename:i,category:d,description:u,sizeBytes:Buffer.byteLength(c,"utf-8"),entryCount:p})}catch{}}return{categories:e,totalFiles:t,uncategorizedCount:n}}var By={fact:"SUPERSEDE: If a newer fact contradicts an older one (e.g. port changed, version updated), update the existing entry in-place. Do not keep both \u2014 stale facts cause confusion. Convert relative dates to absolute. Mark the update date.",lesson:"ACCUMULATE: Lessons learned are valuable even when old. Append new insights to existing lesson files. Only remove a lesson if it's provably wrong (not just outdated). Group related lessons under the same topic file.",preference:"OVERWRITE: User preferences evolve. If a newer statement contradicts an older preference, the newer one wins. Remove the old entry and write the current preference. Keep preferences concise (one line each).",pattern:"MERGE: If multiple entries describe the same pattern, merge them into one authoritative entry with examples. Remove redundant duplicates. A pattern that's been superseded by a better practice should be removed.",decision:"UPDATE: Decisions have context and rationale. When a decision changes, don't delete the old one \u2014 add an 'Updated (date):' section explaining what changed and why. This preserves the decision history.","skill-learning":"CONSOLIDATE: Group related skill entries by tool/workflow. Remove entries for skills that are now obvious or well-documented elsewhere. Keep the most actionable version of each skill note.",uncategorized:"CLASSIFY: Try to infer a category from the content. If it matches lesson/preference/pattern/fact/decision, rename the file with the appropriate prefix. If truly uncategorizable, leave as-is but ensure it has a clear description."};function Ac(r){if(r.totalFiles===0)return"\n## Category Context\n\nNo existing memory files found. Create new files using the naming convention: `<category>-<topic>.md` (e.g. `lesson-docker.md`, `fact-ports.md`, `decision-framework.md`).\n";let e=[];e.push(`
66
+ `),score:.85}});return{action:"continue",context:{...o,recalledMemories:[...c,...d]}}}})}function It(){Bo=null,pi=0}import{ClawQMemoryAdapter as jy}from"qlogicagent-adapter-claw";var Al="qmemory";function Cl(r){let e=new jy({baseUrl:r.baseUrl,apiKey:r.apiKey,timeout:r.timeoutMs??5e3});function t(n){return r.userIdPrefix?`${r.userIdPrefix}:${n}`:n}return{providerId:Al,async search(n,o,s){return((await e.dispatch("memory.search",{q:n,user_id:t(o),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:Al,metadata:a.metadata}))},async ingest(n,o,s){await e.dispatch("memory.addKnowledge",{user_id:t(o),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,o,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:t(o),text:n,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(n,o,s){if(n.length===0)return{memoriesAdded:0};let i=t(o),a=await Promise.allSettled(n.map(d=>e.dispatch("memory.addFact",{user_id:i,text:d.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...d.category?{category:d.category}:{},...typeof d.importance=="number"?{importance:d.importance}:{},...d.speaker?{speaker:d.speaker}:{},...d.event_date?{event_date:d.event_date}:{},...d.tags?.length?{tags:d.tags}:{}}}))),c=0;for(let d of a)d.status==="fulfilled"&&(c+=d.value.memories_added??1);return{memoriesAdded:c}},async remove(n){try{return await e.dispatch("memory.forget",{id:n}),!0}catch{return!1}},async feedback(n,o,s){await e.dispatch("memory.feedback",{memory_ids:n,signal:o,...s?{session_id:s}:{}})},async triggerDecay(n,o){let s=await e.dispatch("memory.decay",{user_id:t(n),temporal_expiry:o?.temporalExpiry??!0,staleness_decay:o?.stalenessDecay??!0,noise_archival:o?.noiseArchival??!0});return{decayed:s.decayed??0,archived:s.archived??0}}}}import{readFile as Nl,writeFile as gi,stat as Gl,unlink as eb,mkdir as tb}from"node:fs/promises";import{join as Ho,resolve as Ul,isAbsolute as $l,normalize as jl}from"node:path";import{randomUUID as nb}from"node:crypto";function Pl(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function Fy(r){return r.latestInputTokens+r.cumulativeOutputTokens}var By=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),Il=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function Wy(r){return{isSearch:By.has(r)||void 0,isRead:Il.has(r)||void 0}}function Gy(r,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${Il.has(r)?"Reading":r.includes("write")||r.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 o=e.query??e.pattern??e.search;if(typeof o=="string")return`Searching: ${o}`}function Ml(r,e){r.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),r.cumulativeOutputTokens+=e.output_tokens??0}function El(r,e,t,n){r.toolUseCount++;let o=Wy(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??Gy(e,t),isSearch:o.isSearch,isRead:o.isRead};for(r.recentActivities.push(s);r.recentActivities.length>5;)r.recentActivities.shift()}function mi(r){return{toolUseCount:r.toolUseCount,tokenCount:Fy(r),lastActivity:r.recentActivities.length>0?r.recentActivities[r.recentActivities.length-1]:void 0,recentActivities:[...r.recentActivities]}}import{randomUUID as Ol}from"node:crypto";function Hy(r){let e=new AbortController;return r&&(r.aborted?e.abort(r.reason):r.addEventListener("abort",()=>{e.abort(r.reason)},{once:!0})),e}async function An(r){let e=Date.now(),t=[],n={inputTokens:0,outputTokens:0},o=Pl(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:c,transport:d,toolInvoker:l,apiKey:u,model:p,log:m,hooks:f,forkLabel:g,maxTurns:y,temperature:b,parentSignal:k,onEvent:S,onProgress:R,budgetTokens:P,parentDepth:O}=r,L=Hy(k),B=`fork-${g}-${Ol().slice(0,8)}`,v=`fork-session-${Ol().slice(0,8)}`;m.info(`[fork:${g}] starting \u2014 ${s.length} initial messages, model=${p}`);let ee=c?{invoke:async(re,Me,K,Y)=>{let Te={};try{Te=JSON.parse(K)}catch{}let fe=c(Me,Te);return fe.allowed?l.invoke(re,Me,K,Y):(m.info(`[fork:${g}] tool ${Me} denied: ${fe.reason}`),{result:"",error:fe.reason})}}:l,T=!0,E;try{let{Agent:re}=await Promise.resolve().then(()=>(_o(),Gc)),Me=new re({llmTransport:d,apiKey:u,toolInvoker:ee,log:m,hooks:f,maxRounds:y});for await(let K of Me.run({turnId:B,sessionId:v,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:u,temperature:b,maxOutputTokens:r.maxOutputTokens,parentDepth:O}},L.signal)){if(t.push(K),S?.(K),K.type==="end"&&K.usage&&(Ml(o,{input_tokens:K.usage.inputTokens,output_tokens:K.usage.outputTokens}),n.inputTokens+=K.usage.inputTokens,n.outputTokens+=K.usage.outputTokens,K.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+K.usage.cacheRead),K.usage.cacheWrite&&(n.cacheWrite=(n.cacheWrite??0)+K.usage.cacheWrite),P&&P>0)){let Y=n.inputTokens+n.outputTokens+(n.reasoningTokens??0);Y>=P&&(m.info(`[fork:${g}] budget exceeded (${Y} / ${P} tokens), aborting`),L.abort("budget_exceeded"))}if(K.type==="tool_call"){let Y={};try{Y=JSON.parse(K.arguments??"{}")}catch{}El(o,K.name,Y),R?.(mi(o))}K.type==="error"&&(T=!1,E=K.error)}}catch(re){T=!1,E=re instanceof Error?re.message:String(re),m.warn(`[fork:${g}] error: ${E}`)}finally{L.signal.aborted||L.abort("fork_complete")}let V=Date.now()-e;return m.info(`[fork:${g}] finished in ${V}ms \u2014 ${t.length} events, usage: prompt=${n.inputTokens} completion=${n.outputTokens}, ok=${T}`),{events:t,totalUsage:n,progress:mi(o),durationMs:V,ok:T,error:E}}import{readFile as Vy,readdir as zy}from"node:fs/promises";import{existsSync as Ky}from"node:fs";import{join as qy}from"node:path";var Xy={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",tradeoff:"decision",skill:"skill-learning",workflow:"skill-learning"},Yy={lesson:[/(?:原来|root cause|turns out|the issue was|问题出在|踩坑|gotcha|pitfall)/i,/(?:以后|下次|remember to|don't forget|务必|切记)/i],preference:[/(?:我(?:喜欢|偏好|习惯)|I (?:prefer|like|always))/i,/(?:请(?:用|使用)|please use|always use)/i],pattern:[/(?:每次|always|whenever|pattern|惯例|convention|best practice)/i],fact:[/(?:架构|architecture|port|version|部署|deployed|环境|配置|config)/i],decision:[/(?:决定|decided|选择|chosen|采用|因为|because|rationale|trade-?off)/i],"skill-learning":[/(?:skill|workflow|tool|command|命令|工具)/i]};function Jy(r){let e=r.replace(/\.md$/,"").toLowerCase();for(let[t,n]of Object.entries(Xy))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return n;return null}function Qy(r){let e=r.slice(0,500),t=null,n=0;for(let[o,s]of Object.entries(Yy)){let i=s.filter(a=>a.test(e)).length;i>n&&(n=i,t=o)}return t}async function Dl(r){let e={},t=0,n=0;if(!Ky(r))return{categories:e,totalFiles:0,uncategorizedCount:0};let o;try{o=await zy(r)}catch{return{categories:e,totalFiles:0,uncategorizedCount:0}}let s=o.filter(i=>i.endsWith(".md")&&i!=="INDEX.md");for(let i of s){let a=qy(r,i);try{let c=await Vy(a,"utf-8");t++;let d=Jy(i)??Qy(c)??"uncategorized";d==="uncategorized"&&n++;let l=c.split(`
67
+ `),u="";for(let m of l){let f=m.trim();if(!(!f||f.startsWith("#")||f.startsWith("---"))){u=f.slice(0,120);break}}let p=l.filter(m=>/^\s*[-*+]\s|^\s*\d+[.)]\s/.test(m)).length;e[d]||(e[d]=[]),e[d].push({filename:i,category:d,description:u,sizeBytes:Buffer.byteLength(c,"utf-8"),entryCount:p})}catch{}}return{categories:e,totalFiles:t,uncategorizedCount:n}}var Zy={fact:"SUPERSEDE: If a newer fact contradicts an older one (e.g. port changed, version updated), update the existing entry in-place. Do not keep both \u2014 stale facts cause confusion. Convert relative dates to absolute. Mark the update date.",lesson:"ACCUMULATE: Lessons learned are valuable even when old. Append new insights to existing lesson files. Only remove a lesson if it's provably wrong (not just outdated). Group related lessons under the same topic file.",preference:"OVERWRITE: User preferences evolve. If a newer statement contradicts an older preference, the newer one wins. Remove the old entry and write the current preference. Keep preferences concise (one line each).",pattern:"MERGE: If multiple entries describe the same pattern, merge them into one authoritative entry with examples. Remove redundant duplicates. A pattern that's been superseded by a better practice should be removed.",decision:"UPDATE: Decisions have context and rationale. When a decision changes, don't delete the old one \u2014 add an 'Updated (date):' section explaining what changed and why. This preserves the decision history.","skill-learning":"CONSOLIDATE: Group related skill entries by tool/workflow. Remove entries for skills that are now obvious or well-documented elsewhere. Keep the most actionable version of each skill note.",uncategorized:"CLASSIFY: Try to infer a category from the content. If it matches lesson/preference/pattern/fact/decision, rename the file with the appropriate prefix. If truly uncategorizable, leave as-is but ensure it has a clear description."};function Ll(r){if(r.totalFiles===0)return"\n## Category Context\n\nNo existing memory files found. Create new files using the naming convention: `<category>-<topic>.md` (e.g. `lesson-docker.md`, `fact-ports.md`, `decision-framework.md`).\n";let e=[];e.push(`
68
68
  ## Category Context (${r.totalFiles} files)
69
69
  `),e.push(`Use category-specific merge rules when updating files:
70
- `);for(let[t,n]of Object.entries(r.categories)){if(n.length===0)continue;let o=By[t]??"",s=n.reduce((i,a)=>i+a.entryCount,0);e.push(`### ${t} (${n.length} files, ~${s} entries)`),e.push(`**Merge rule**: ${o}`),e.push("Files:");for(let i of n.slice(0,10)){let a=i.description?` \u2014 ${i.description}`:"";e.push(`- \`${i.filename}\` (${i.entryCount} entries, ${Math.ceil(i.sizeBytes/1024)}KB)${a}`)}n.length>10&&e.push(`- ... and ${n.length-10} more files`),e.push("")}return e.push("### File naming convention"),e.push("New files MUST use category prefix: `<category>-<topic>.md`"),e.push("Valid prefixes: lesson-, preference-, pattern-, fact-, decision-, skill-"),e.push(""),e.join(`
71
- `)}var Uc={minHours:24,minSessions:5,scanIntervalMs:6e5},Bo=".consolidate-lock",zy=3600*1e3,Oc="CLAUDE.md",Vy=100,qy=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"]),Ky=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),Jy=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function Xy(r){let e=r.trim();if(!e||Jy.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!qy.has(n))return!1;if(n==="git"){let o=t[1];if(!o||!Ky.has(o))return!1}return!0}function Yy(r,e){let{toolName:t,input:n}=e;if(new Set(["read","search","read_file","grep","glob","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==="exec"||t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return Xy(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==="write"||t==="edit"||t==="patch"||t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??n.filePath??"";return typeof i=="string"&&Nc(i,r)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${r}`}}return{allowed:!1,reason:`Tool "${t}" is not permitted during dream consolidation. Only read, search, read-only exec, and memory-scoped write/edit/patch are allowed.`}}function Nc(r,e){let t=Mc(r)?r:Pc(r),n=Mc(e)?e:Pc(e),o=Ec(t),s=Ec(n);return o.startsWith(s)}function jc(r,e,t,n){let o=n?.hasQMemory?`
70
+ `);for(let[t,n]of Object.entries(r.categories)){if(n.length===0)continue;let o=Zy[t]??"",s=n.reduce((i,a)=>i+a.entryCount,0);e.push(`### ${t} (${n.length} files, ~${s} entries)`),e.push(`**Merge rule**: ${o}`),e.push("Files:");for(let i of n.slice(0,10)){let a=i.description?` \u2014 ${i.description}`:"";e.push(`- \`${i.filename}\` (${i.entryCount} entries, ${Math.ceil(i.sizeBytes/1024)}KB)${a}`)}n.length>10&&e.push(`- ... and ${n.length-10} more files`),e.push("")}return e.push("### File naming convention"),e.push("New files MUST use category prefix: `<category>-<topic>.md`"),e.push("Valid prefixes: lesson-, preference-, pattern-, fact-, decision-, skill-"),e.push(""),e.join(`
71
+ `)}var Hl={minHours:24,minSessions:5,scanIntervalMs:6e5},Vo=".consolidate-lock",ob=3600*1e3,Fl="CLAUDE.md",rb=100,sb=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"]),ib=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),ab=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function cb(r){let e=r.trim();if(!e||ab.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!sb.has(n))return!1;if(n==="git"){let o=t[1];if(!o||!ib.has(o))return!1}return!0}function lb(r,e){let{toolName:t,input:n}=e;if(new Set(["read","search","read_file","grep","glob","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==="exec"||t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return cb(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==="write"||t==="edit"||t==="patch"||t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??n.filePath??"";return typeof i=="string"&&Vl(i,r)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${r}`}}return{allowed:!1,reason:`Tool "${t}" is not permitted during dream consolidation. Only read, search, read-only exec, and memory-scoped write/edit/patch are allowed.`}}function Vl(r,e){let t=$l(r)?r:Ul(r),n=$l(e)?e:Ul(e),o=jl(t),s=jl(n);return o.startsWith(s)}function zl(r,e,t,n){let o=n?.hasQMemory?`
72
72
 
73
73
  ## Phase 2.5 \u2014 Long-term memory triage (QMemory)
74
74
 
@@ -103,7 +103,7 @@ Session transcripts: \`${e}\` (large JSONL files \u2014 grep narrowly, don't rea
103
103
  ## Phase 1 \u2014 Orient
104
104
 
105
105
  - \`ls\` the memory directory to see what already exists
106
- - Read \`${Oc}\` to understand the current index
106
+ - Read \`${Fl}\` to understand the current index
107
107
  - Skim existing topic files so you improve them rather than creating duplicates
108
108
  - If \`logs/\` or \`sessions/\` subdirectories exist, review recent entries there
109
109
 
@@ -129,7 +129,7 @@ Focus on:
129
129
 
130
130
  ## Phase 4 \u2014 Prune and index
131
131
 
132
- Update \`${Oc}\` so it stays under ${Vy} 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.
132
+ Update \`${Fl}\` so it stays under ${rb} 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.
133
133
 
134
134
  - Remove pointers to memories that are now stale, wrong, or superseded
135
135
  - 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
@@ -144,50 +144,50 @@ Sessions since last consolidation (${t.length}):
144
144
  ${t.map(s=>`- ${s}`).join(`
145
145
  `)}
146
146
 
147
- Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var Dc=0;async function Qy(r,e={}){let t={...Uc,...e},n;try{n=await Fc(r.memoryRoot)}catch{n=0}let o=(Date.now()-n)/36e5;if(!t.force&&o<t.minHours)return null;let s=Date.now()-Dc;if(!t.force&&s<t.scanIntervalMs)return null;Dc=Date.now();let i;try{i=await r.listSessionsSince(n)}catch{return null}return i=i.filter(a=>a!==r.currentSessionId),!t.force&&i.length<t.minSessions?null:{sessionIds:i}}async function Fc(r){let e=Fo(r,Bo);return(await $c(e)).mtimeMs}function Zy(r){try{return process.kill(r,0),!0}catch{return!1}}async function eb(r){let e=Fo(r,Bo),t,n;try{let[s,i]=await Promise.all([$c(e),Ic(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<zy&&n!==void 0&&Zy(n))return null;await Hy(r,{recursive:!0}),await di(e,String(process.pid));let o;try{o=await Ic(e,"utf8")}catch{return null}return parseInt(o.trim(),10)!==process.pid?null:t??0}async function Lc(r,e){let t=Fo(r,Bo);try{if(e===0){await Gy(t);return}await di(t,"");let{utimes:n}=await import("node:fs/promises"),o=e/1e3;await n(t,o,o)}catch{}}async function tb(r){let e=Fo(r,Bo);await di(e,String(process.pid))}function nb(r){return{taskId:`dream-${Wy().slice(0,8)}`,type:"dream",label:"Memory consolidation",permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:1,maxTurns:0,tokenBudget:0,startedAt:Date.now(),parentTaskId:r.parentTaskId,sessionId:r.sessionId,phase:"starting",sessionsReviewing:r.sessionsReviewing,filesTouched:[],turns:[],priorLockMtime:r.priorLockMtime}}async function ob(r,e={}){let t={...Uc,...e},n=await Qy(r,t);if(!n)return null;let o;if(t.force)try{o=await Fc(r.memoryRoot)}catch{o=0}else if(o=await eb(r.memoryRoot),o===null)return null;let s=jc(r.memoryRoot,r.transcriptDir,n.sessionIds),i=nb({sessionId:r.currentSessionId,sessionsReviewing:n.sessionIds.length,priorLockMtime:o});return{prompt:s,taskState:i,sessionIds:n.sessionIds}}async function Bc(r){let e=Date.now(),t=await ob(r.context,r.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:n,sessionIds:o}=t,s="";try{let f=await Cc(r.context.memoryRoot);f.totalFiles>0&&(s=Ac(f))}catch{}let i=!!(r.qmemoryAdapter&&r.qmemoryUserId),a=jc(r.context.memoryRoot,r.context.transcriptDir,o,{hasQMemory:i,categoryContext:s||void 0});r.log.info(`[dream] starting consolidation \u2014 ${o.length} sessions, memoryRoot=${r.context.memoryRoot}`+(i?", qmemory=enabled":"")),r.hooks?.invoke("subagent.started",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let c=(f,m)=>Yy(r.context.memoryRoot,{toolName:f,input:m}),d=i?[{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"]}}}]:[],l=i?{invoke:async(f,m,y,k)=>{let b=r.qmemoryAdapter,x=r.qmemoryUserId;if(m==="qmemory_search"){let{query:S,limit:A}=JSON.parse(y),$=await b.search(S,x,{limit:A??10});return{result:JSON.stringify($)}}if(m==="qmemory_store"){if(!b.addText)return{result:"",error:"addText not supported"};let{text:S,source:A}=JSON.parse(y),$=await b.addText(S,x,{sessionId:r.context.currentSessionId,source:A??"dream-consolidation"});return{result:JSON.stringify($)}}if(m==="qmemory_feedback"){let{memoryIds:S,signal:A}=JSON.parse(y);return b.feedback&&await b.feedback(S,A,r.context.currentSessionId),{result:"Feedback recorded successfully."}}return r.toolInvoker.invoke(f,m,y,k)}}:r.toolInvoker,u=new Set(["read","write","edit","patch","exec","search","qmemory_search","qmemory_store","qmemory_feedback"]),g=[...r.tools.filter(f=>u.has(f.function.name)),...d];try{let f=await Sn({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:a,tools:g,canUseTool:c,transport:r.transport,toolInvoker:l,apiKey:r.apiKey,model:r.model,log:r.log,hooks:void 0,forkLabel:"dream-consolidation",maxTurns:15,parentSignal:r.parentSignal,skipTranscript:!0}),m=[];for(let y of f.events)if(y.type==="tool_call")try{let k=JSON.parse(y.arguments),b=k.file_path??k.path??k.filePath;b&&Nc(b,r.context.memoryRoot)&&m.push(b)}catch{}return f.ok?(await tb(r.context.memoryRoot),r.log.info(`[dream] consolidation complete \u2014 ${m.length} files touched, ${f.durationMs}ms`)):(await Lc(r.context.memoryRoot,n.priorLockMtime),r.log.warn(`[dream] consolidation failed: ${f.error}`)),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:f.ok?"normal":"error",error:f.error}).catch(()=>{}),{ok:f.ok,sessionsReviewed:o.length,filesTouched:[...new Set(m)],turns:[],durationMs:Date.now()-e,error:f.error}}catch(f){await Lc(r.context.memoryRoot,n.priorLockMtime).catch(()=>{});let m=f instanceof Error?f.message:String(f);return r.log.warn(`[dream] consolidation error: ${m}`),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:m}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:m}}}import*as Go from"node:fs/promises";import*as ui from"node:path";var Gc={minIntervalHours:24,temporalExpiry:!0,stalenessDecay:!0,noiseArchival:!0},Hc=".last-decay";async function rb(r,e={}){let t=(e.minIntervalHours??Gc.minIntervalHours)*36e5,n=ui.join(r,Hc);try{let o=await Go.readFile(n,"utf-8"),s=parseInt(o.trim(),10);return isNaN(s)?!0:Date.now()-s>=t}catch{return!0}}async function sb(r){let e=ui.join(r,Hc);await Go.writeFile(e,String(Date.now()),"utf-8")}async function Wc(r){let e=Date.now(),t={...Gc,...r.config};if(!await rb(r.memoryRoot,t))return r.log?.debug?.("[decay] Skipped \u2014 cooldown not elapsed"),{ran:!1,decayed:0,archived:0,durationMs:Date.now()-e};r.log?.info("[decay] Starting importance decay cycle");try{let o=await r.adapter.triggerDecay(r.userId,{temporalExpiry:t.temporalExpiry,stalenessDecay:t.stalenessDecay,noiseArchival:t.noiseArchival});await sb(r.memoryRoot);let s=Date.now()-e;return r.log?.info(`[decay] Completed \u2014 decayed=${o.decayed}, archived=${o.archived}, ${s}ms`),{ran:!0,decayed:o.decayed,archived:o.archived,durationMs:s}}catch(o){let s=Date.now()-e;return r.log?.info(`[decay] Failed \u2014 ${o instanceof Error?o.message:String(o)}`),{ran:!1,decayed:0,archived:0,durationMs:s}}}var Vt=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_listeners=new Set;constructor(e){this.sessionId=e}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.notifyListeners()}addMediaUsage(e,t,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||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++}recordTurnCompleted(){this._turnCount++}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 nt from"node:path";De();var zc="transcript.jsonl",xn="state.json";function Vc(r){return r?Ql(r):vo()}function Ho(r,e){let t=r.replace(/[^a-zA-Z0-9_-]/g,"_");return nt.join(Vc(e),t)}async function pi(r,e,t,n){let o=Ho(r,t);await Pe.promises.mkdir(o,{recursive:!0});let s={role:e.role,content:e.content,ts:Date.now()};n&&(s.turnId=n);let i=JSON.stringify(s)+`
148
- `;await Pe.promises.appendFile(nt.join(o,zc),i,"utf8")}async function qc(r,e,t,n){let o=Ho(r,n);await Pe.promises.mkdir(o,{recursive:!0});let s={metadata:{sessionId:r,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},i=nt.join(o,xn+".tmp");await Pe.promises.writeFile(i,JSON.stringify(s,null,2),"utf8"),await Pe.promises.rename(i,nt.join(o,xn))}async function Kc(r,e){let t=Ho(r,e),n=nt.join(t,zc),o=nt.join(t,xn),s=[];try{s=(await Pe.promises.readFile(n,"utf8")).split(`
149
- `).filter(Boolean).map(l=>{let u=JSON.parse(l);return{role:u.role,content:u.content??null}})}catch{return null}let i={sessionId:r,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:s.length},a;try{let d=await Pe.promises.readFile(o,"utf8"),l=JSON.parse(d);i=l.metadata,a=l.costSnapshot}catch{}let c=s.filter(d=>d.role!=="system");return{metadata:i,messages:c,costSnapshot:a}}async function Jc(r=os,e){let t=Vc(e),n;try{n=await Pe.promises.readdir(t)}catch{return[]}let o=[];for(let s of n){let i=nt.join(t,s,xn);try{let a=await Pe.promises.readFile(i,"utf8"),c=JSON.parse(a);o.push({sessionId:c.metadata.sessionId,title:c.metadata.title,lastActiveAt:c.metadata.lastActiveAt,messageCount:c.metadata.messageCount,model:c.metadata.model})}catch{}}return o.sort((s,i)=>i.lastActiveAt-s.lastActiveAt),o.slice(0,r)}function ib(r){return r.turnCount<rs?!1:r.taskSummaryGeneratedAt?r.turnCount-(r.taskSummaryGeneratedAt??0)>=ss:!0}async function Xc(r,e,t,n,o){if(!ib(e))return null;try{let i=t.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
150
- `),a=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:i}],tools:[],maxTokens:200},n.apiKey),c="";for await(let u of a)u.type==="delta"&&(c+=u.text);if(c=c.trim(),!c)return null;let d=Ho(r,o),l=nt.join(d,xn);try{let u=await Pe.promises.readFile(l,"utf8"),p=JSON.parse(u);p.metadata.taskSummary=c,p.metadata.taskSummaryGeneratedAt=e.turnCount;let g=l+".tmp";await Pe.promises.writeFile(g,JSON.stringify(p,null,2),"utf8"),await Pe.promises.rename(g,l)}catch{}return c}catch{return null}}qs();import{randomUUID as XA}from"node:crypto";var ab=3e4;var zo=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 o=t(n);o!==n&&(this.tasks.set(e,o),this.notify(e,o),!Wo(n.lifecycle)&&Wo(o.lifecycle)&&this.hooks?.invoke("task.completed",{sessionId:this.sessionId,taskId:o.taskId,taskType:o.type,label:o.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&&Wo(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=ab){let t=Date.now();for(let[n,o]of this.tasks)Wo(o.lifecycle)&&o.endedAt&&t-o.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function Wo(r){return r==="completed"||r==="failed"||r==="cancelled"||r==="timeout"}import{watch as lb}from"node:fs";import{stat as cb}from"node:fs/promises";import{join as Yc,relative as db,resolve as ub}from"node:path";var pb=[`${we}/settings.json`,"INSTRUCTIONS.md",`${we}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${we}/rules`],mb=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${we}/rules`],mi=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 pb){let t=Yc(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=lb(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(o,s)=>{let i=s?Yc(e,s):e;this.handleChange(i,o==="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 o=t;try{await cb(e)}catch{o="deleted"}let s=db(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${o} ${s}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:o}).catch(()=>{}),mb.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=ub(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 Qc(r){let e=new mi(r);return await e.start(),e}import{readFile as gb,readdir as fb,stat as hb}from"node:fs/promises";import{dirname as Vo,extname as yb,isAbsolute as bb,join as Pt,parse as ed,resolve as Zc}from"node:path";import{homedir as kb}from"node:os";De();var Tb="INSTRUCTIONS.md",wb="INSTRUCTIONS.local.md",vb="INSTRUCTIONS.md",Sb=[".instructions.md"],xb=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 Rb(r){try{return await gb(r,"utf-8")}catch{return null}}function _b(r){return r.includes("<!--")?r.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):r}function Cb(r){let e=r.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:r};let t=e[1],n=r.slice(e[0].length),o=t.match(/^paths:\s*(.+)$/m);if(!o)return{content:n};let s=[],i=o[1].trim();if(i.startsWith("["))try{s=JSON.parse(i)}catch{}else s=i.split(",").map(c=>c.trim()).filter(Boolean);let a=s.map(c=>c.endsWith("/**")?c.slice(0,-3):c).filter(c=>c.length>0&&c!=="**");return{content:n,globs:a.length>0?a:void 0}}function Ab(r,e){let t=new Set,n=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=r.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=n.exec(s))!==null;){let a=i[1];if(!a)continue;let c=a.indexOf("#");if(c!==-1&&(a=a.substring(0,c)),!a)continue;a=a.replace(/\\ /g," ");let d;if(a.startsWith("~/"))d=Pt(kb(),a.slice(2));else if(bb(a))d=a;else if(a.startsWith("./"))d=Zc(Vo(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))d=Zc(Vo(e),a);else continue;t.add(d)}return[...t]}async function It(r,e,t,n=0,o){let s=r.toLowerCase();if(t.has(s)||n>=is)return[];let i=yb(r).toLowerCase();if(i&&!xb.has(i))return[];t.add(s);let a=await Rb(r);if(!a?.trim())return[];let{content:c,globs:d}=Cb(a),l=_b(c);if(!l.trim())return[];let u=[],p={path:r,type:e,content:l.trim()};o&&(p.parent=o),d&&(p.globs=d),u.push(p);let g=Ab(c,r);for(let f of g){let m=await It(f,e,t,n+1,r);u.push(...m)}return u}async function gi(r,e,t,n,o=new Set){if(o.has(r))return[];o.add(r);let s=[];try{let i=await fb(r,{withFileTypes:!0});for(let a of i){let c=Pt(r,a.name);if(a.isDirectory())s.push(...await gi(c,e,t,n,o));else if(a.isFile()&&a.name.endsWith(".md")){let d=await It(c,e,t);s.push(...d.filter(l=>n?!!l.globs:!l.globs))}}}catch{}return s}async function Ib(r){let e=r,t=ed(e).root;for(;e!==t;){try{let n=Pt(e,".git"),o=await hb(n);if(o.isDirectory()||o.isFile())return e}catch{}e=Vo(e)}return null}async function Pb(r,e){let t=[],n=new Set,o=J(),s=Pt(o,vb);t.push(...await It(s,"User",n));let i=Vl();t.push(...await gi(i,"User",n,!1));let c=await Ib(r)??ed(r).root,d=[],l=r;for(;d.push(l),!(l===c&&l!==r);){let u=Vo(l);if(u===l)break;l=u}for(let u of d.reverse()){t.push(...await It(Pt(u,Tb),"Project",n));for(let p of Sb)t.push(...await It(Pt(u,p),"Project",n));t.push(...await It(Kl(u),"Project",n)),t.push(...await gi(Yl(u),"Project",n,!1)),t.push(...await It(Pt(u,wb),"Local",n))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:r,fileCount:t.length}).catch(()=>{}),t}function td(r){if(r.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 r){if(!n.content)continue;let o=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}${o}:
147
+ Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var Bl=0;async function db(r,e={}){let t={...Hl,...e},n;try{n=await Kl(r.memoryRoot)}catch{n=0}let o=(Date.now()-n)/36e5;if(!t.force&&o<t.minHours)return null;let s=Date.now()-Bl;if(!t.force&&s<t.scanIntervalMs)return null;Bl=Date.now();let i;try{i=await r.listSessionsSince(n)}catch{return null}return i=i.filter(a=>a!==r.currentSessionId),!t.force&&i.length<t.minSessions?null:{sessionIds:i}}async function Kl(r){let e=Ho(r,Vo);return(await Gl(e)).mtimeMs}function ub(r){try{return process.kill(r,0),!0}catch{return!1}}async function pb(r){let e=Ho(r,Vo),t,n;try{let[s,i]=await Promise.all([Gl(e),Nl(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<ob&&n!==void 0&&ub(n))return null;await tb(r,{recursive:!0}),await gi(e,String(process.pid));let o;try{o=await Nl(e,"utf8")}catch{return null}return parseInt(o.trim(),10)!==process.pid?null:t??0}async function Wl(r,e){let t=Ho(r,Vo);try{if(e===0){await eb(t);return}await gi(t,"");let{utimes:n}=await import("node:fs/promises"),o=e/1e3;await n(t,o,o)}catch{}}async function mb(r){let e=Ho(r,Vo);await gi(e,String(process.pid))}function gb(r){return{taskId:`dream-${nb().slice(0,8)}`,type:"dream",label:"Memory consolidation",permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:1,maxTurns:0,tokenBudget:0,startedAt:Date.now(),parentTaskId:r.parentTaskId,sessionId:r.sessionId,phase:"starting",sessionsReviewing:r.sessionsReviewing,filesTouched:[],turns:[],priorLockMtime:r.priorLockMtime}}async function fb(r,e={}){let t={...Hl,...e},n=await db(r,t);if(!n)return null;let o;if(t.force)try{o=await Kl(r.memoryRoot)}catch{o=0}else if(o=await pb(r.memoryRoot),o===null)return null;let s=zl(r.memoryRoot,r.transcriptDir,n.sessionIds),i=gb({sessionId:r.currentSessionId,sessionsReviewing:n.sessionIds.length,priorLockMtime:o});return{prompt:s,taskState:i,sessionIds:n.sessionIds}}async function ql(r){let e=Date.now(),t=await fb(r.context,r.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:n,sessionIds:o}=t,s="";try{let f=await Dl(r.context.memoryRoot);f.totalFiles>0&&(s=Ll(f))}catch{}let i=!!(r.qmemoryAdapter&&r.qmemoryUserId),a=zl(r.context.memoryRoot,r.context.transcriptDir,o,{hasQMemory:i,categoryContext:s||void 0});r.log.info(`[dream] starting consolidation \u2014 ${o.length} sessions, memoryRoot=${r.context.memoryRoot}`+(i?", qmemory=enabled":"")),r.hooks?.invoke("subagent.started",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let c=(f,g)=>lb(r.context.memoryRoot,{toolName:f,input:g}),d=i?[{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"]}}}]:[],l=i?{invoke:async(f,g,y,b)=>{let k=r.qmemoryAdapter,S=r.qmemoryUserId;if(g==="qmemory_search"){let{query:R,limit:P}=JSON.parse(y),O=await k.search(R,S,{limit:P??10});return{result:JSON.stringify(O)}}if(g==="qmemory_store"){if(!k.addText)return{result:"",error:"addText not supported"};let{text:R,source:P}=JSON.parse(y),O=await k.addText(R,S,{sessionId:r.context.currentSessionId,source:P??"dream-consolidation"});return{result:JSON.stringify(O)}}if(g==="qmemory_feedback"){let{memoryIds:R,signal:P}=JSON.parse(y);return k.feedback&&await k.feedback(R,P,r.context.currentSessionId),{result:"Feedback recorded successfully."}}return r.toolInvoker.invoke(f,g,y,b)}}:r.toolInvoker,u=new Set(["read","write","edit","patch","exec","search","qmemory_search","qmemory_store","qmemory_feedback"]),m=[...r.tools.filter(f=>u.has(f.function.name)),...d];try{let f=await An({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:a,tools:m,canUseTool:c,transport:r.transport,toolInvoker:l,apiKey:r.apiKey,model:r.model,log:r.log,hooks:void 0,forkLabel:"dream-consolidation",maxTurns:15,parentSignal:r.parentSignal,skipTranscript:!0}),g=[];for(let y of f.events)if(y.type==="tool_call")try{let b=JSON.parse(y.arguments),k=b.file_path??b.path??b.filePath;k&&Vl(k,r.context.memoryRoot)&&g.push(k)}catch{}return f.ok?(await mb(r.context.memoryRoot),r.log.info(`[dream] consolidation complete \u2014 ${g.length} files touched, ${f.durationMs}ms`)):(await Wl(r.context.memoryRoot,n.priorLockMtime),r.log.warn(`[dream] consolidation failed: ${f.error}`)),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:f.ok?"normal":"error",error:f.error}).catch(()=>{}),{ok:f.ok,sessionsReviewed:o.length,filesTouched:[...new Set(g)],turns:[],durationMs:Date.now()-e,error:f.error}}catch(f){await Wl(r.context.memoryRoot,n.priorLockMtime).catch(()=>{});let g=f instanceof Error?f.message:String(f);return r.log.warn(`[dream] consolidation error: ${g}`),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:g}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:g}}}import*as zo from"node:fs/promises";import*as fi from"node:path";var Xl={minIntervalHours:24,temporalExpiry:!0,stalenessDecay:!0,noiseArchival:!0},Yl=".last-decay";async function hb(r,e={}){let t=(e.minIntervalHours??Xl.minIntervalHours)*36e5,n=fi.join(r,Yl);try{let o=await zo.readFile(n,"utf-8"),s=parseInt(o.trim(),10);return isNaN(s)?!0:Date.now()-s>=t}catch{return!0}}async function yb(r){let e=fi.join(r,Yl);await zo.writeFile(e,String(Date.now()),"utf-8")}async function Jl(r){let e=Date.now(),t={...Xl,...r.config};if(!await hb(r.memoryRoot,t))return r.log?.debug?.("[decay] Skipped \u2014 cooldown not elapsed"),{ran:!1,decayed:0,archived:0,durationMs:Date.now()-e};r.log?.info("[decay] Starting importance decay cycle");try{let o=await r.adapter.triggerDecay(r.userId,{temporalExpiry:t.temporalExpiry,stalenessDecay:t.stalenessDecay,noiseArchival:t.noiseArchival});await yb(r.memoryRoot);let s=Date.now()-e;return r.log?.info(`[decay] Completed \u2014 decayed=${o.decayed}, archived=${o.archived}, ${s}ms`),{ran:!0,decayed:o.decayed,archived:o.archived,durationMs:s}}catch(o){let s=Date.now()-e;return r.log?.info(`[decay] Failed \u2014 ${o instanceof Error?o.message:String(o)}`),{ran:!1,decayed:0,archived:0,durationMs:s}}}var Xt=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_listeners=new Set;constructor(e){this.sessionId=e}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.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(t,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,t,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||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++}recordTurnCompleted(){this._turnCount++}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 Ce from"node:fs";import*as Qe from"node:path";ye();var Ql="transcript.jsonl",Yt="state.json";function Zl(r){return r?sl(r):xo()}function Ko(r,e){let t=r.replace(/[^a-zA-Z0-9_-]/g,"_");return Qe.join(Zl(e),t)}async function hi(r,e,t,n){let o=Ko(r,t);await Ce.promises.mkdir(o,{recursive:!0});let s={role:e.role,content:e.content,ts:Date.now()};n&&(s.turnId=n);let i=JSON.stringify(s)+`
148
+ `;await Ce.promises.appendFile(Qe.join(o,Ql),i,"utf8")}async function ed(r,e,t,n){let o=Ko(r,n);await Ce.promises.mkdir(o,{recursive:!0});let s={};try{let c=await Ce.promises.readFile(Qe.join(o,Yt),"utf8"),d=JSON.parse(c);d.metadata&&(s=d.metadata)}catch{}let i={metadata:{...s,sessionId:r,createdAt:t.createdAt??s.createdAt??Date.now(),lastActiveAt:Date.now(),model:t.model??s.model,cwd:t.cwd??s.cwd,turnCount:e.turnCount,messageCount:t.messageCount??s.messageCount??0,title:t.title??s.title,pinnedAt:t.pinnedAt!==void 0?t.pinnedAt:s.pinnedAt,archivedAt:t.archivedAt!==void 0?t.archivedAt:s.archivedAt,projectId:t.projectId!==void 0?t.projectId:s.projectId,type:t.type??s.type,ownerId:t.ownerId??s.ownerId,groupKey:t.groupKey??s.groupKey,groupName:t.groupName??s.groupName,groupPlatform:t.groupPlatform??s.groupPlatform},costSnapshot:e},a=Qe.join(o,Yt+".tmp");await Ce.promises.writeFile(a,JSON.stringify(i,null,2),"utf8"),await Ce.promises.rename(a,Qe.join(o,Yt))}async function td(r,e){let t=Ko(r,e),n=Qe.join(t,Ql),o=Qe.join(t,Yt),s=[];try{s=(await Ce.promises.readFile(n,"utf8")).split(`
149
+ `).filter(Boolean).map(l=>{let u=JSON.parse(l);return{role:u.role,content:u.content??null}})}catch{return null}let i={sessionId:r,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:s.length},a;try{let d=await Ce.promises.readFile(o,"utf8"),l=JSON.parse(d);i=l.metadata,a=l.costSnapshot}catch{}let c=s.filter(d=>d.role!=="system");return{metadata:i,messages:c,costSnapshot:a}}async function nd(r=is,e){let t=Zl(e),n;try{n=await Ce.promises.readdir(t)}catch{return[]}let o=[];for(let s of n){let i=Qe.join(t,s,Yt);try{let a=await Ce.promises.readFile(i,"utf8"),c=JSON.parse(a);o.push({sessionId:c.metadata.sessionId,title:c.metadata.title,lastActiveAt:c.metadata.lastActiveAt,messageCount:c.metadata.messageCount,model:c.metadata.model,pinnedAt:c.metadata.pinnedAt,archivedAt:c.metadata.archivedAt,projectId:c.metadata.projectId,type:c.metadata.type,createdAt:c.metadata.createdAt})}catch{}}return o.sort((s,i)=>i.lastActiveAt-s.lastActiveAt),o.slice(0,r)}function bb(r){return r.turnCount<as?!1:r.taskSummaryGeneratedAt?r.turnCount-(r.taskSummaryGeneratedAt??0)>=cs:!0}async function od(r,e,t,n,o){if(!bb(e))return null;try{let i=t.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
150
+ `),a=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:i}],tools:[],maxTokens:200},n.apiKey),c="";for await(let u of a)u.type==="delta"&&(c+=u.text);if(c=c.trim(),!c)return null;let d=Ko(r,o),l=Qe.join(d,Yt);try{let u=await Ce.promises.readFile(l,"utf8"),p=JSON.parse(u);p.metadata.taskSummary=c,p.metadata.taskSummaryGeneratedAt=e.turnCount;let m=l+".tmp";await Ce.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await Ce.promises.rename(m,l)}catch{}return c}catch{return null}}Js();import{randomUUID as cP}from"node:crypto";var kb=3e4;var Xo=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 o=t(n);o!==n&&(this.tasks.set(e,o),this.notify(e,o),!qo(n.lifecycle)&&qo(o.lifecycle)&&this.hooks?.invoke("task.completed",{sessionId:this.sessionId,taskId:o.taskId,taskType:o.type,label:o.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&&qo(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=kb){let t=Date.now();for(let[n,o]of this.tasks)qo(o.lifecycle)&&o.endedAt&&t-o.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function qo(r){return r==="completed"||r==="failed"||r==="cancelled"||r==="timeout"}import{watch as Tb}from"node:fs";import{stat as wb}from"node:fs/promises";import{join as rd,relative as vb,resolve as Sb}from"node:path";var Rb=[`${Se}/settings.json`,"INSTRUCTIONS.md",`${Se}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${Se}/rules`],_b=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${Se}/rules`],yi=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 Rb){let t=rd(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=Tb(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(o,s)=>{let i=s?rd(e,s):e;this.handleChange(i,o==="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 o=t;try{await wb(e)}catch{o="deleted"}let s=vb(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${o} ${s}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:o}).catch(()=>{}),_b.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=Sb(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 sd(r){let e=new yi(r);return await e.start(),e}import{readFile as xb,readdir as Ab,stat as Cb}from"node:fs/promises";import{dirname as Yo,extname as Pb,isAbsolute as Ib,join as Et,parse as ad,resolve as id}from"node:path";import{homedir as Mb}from"node:os";ye();var Eb="INSTRUCTIONS.md",Ob="INSTRUCTIONS.local.md",Db="INSTRUCTIONS.md",Lb=[".instructions.md"],Nb=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 Ub(r){try{return await xb(r,"utf-8")}catch{return null}}function $b(r){return r.includes("<!--")?r.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):r}function jb(r){let e=r.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:r};let t=e[1],n=r.slice(e[0].length),o=t.match(/^paths:\s*(.+)$/m);if(!o)return{content:n};let s=[],i=o[1].trim();if(i.startsWith("["))try{s=JSON.parse(i)}catch{}else s=i.split(",").map(c=>c.trim()).filter(Boolean);let a=s.map(c=>c.endsWith("/**")?c.slice(0,-3):c).filter(c=>c.length>0&&c!=="**");return{content:n,globs:a.length>0?a:void 0}}function Fb(r,e){let t=new Set,n=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=r.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=n.exec(s))!==null;){let a=i[1];if(!a)continue;let c=a.indexOf("#");if(c!==-1&&(a=a.substring(0,c)),!a)continue;a=a.replace(/\\ /g," ");let d;if(a.startsWith("~/"))d=Et(Mb(),a.slice(2));else if(Ib(a))d=a;else if(a.startsWith("./"))d=id(Yo(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))d=id(Yo(e),a);else continue;t.add(d)}return[...t]}async function Mt(r,e,t,n=0,o){let s=r.toLowerCase();if(t.has(s)||n>=ls)return[];let i=Pb(r).toLowerCase();if(i&&!Nb.has(i))return[];t.add(s);let a=await Ub(r);if(!a?.trim())return[];let{content:c,globs:d}=jb(a),l=$b(c);if(!l.trim())return[];let u=[],p={path:r,type:e,content:l.trim()};o&&(p.parent=o),d&&(p.globs=d),u.push(p);let m=Fb(c,r);for(let f of m){let g=await Mt(f,e,t,n+1,r);u.push(...g)}return u}async function bi(r,e,t,n,o=new Set){if(o.has(r))return[];o.add(r);let s=[];try{let i=await Ab(r,{withFileTypes:!0});for(let a of i){let c=Et(r,a.name);if(a.isDirectory())s.push(...await bi(c,e,t,n,o));else if(a.isFile()&&a.name.endsWith(".md")){let d=await Mt(c,e,t);s.push(...d.filter(l=>n?!!l.globs:!l.globs))}}}catch{}return s}async function Bb(r){let e=r,t=ad(e).root;for(;e!==t;){try{let n=Et(e,".git"),o=await Cb(n);if(o.isDirectory()||o.isFile())return e}catch{}e=Yo(e)}return null}async function Wb(r,e){let t=[],n=new Set,o=X(),s=Et(o,Db);t.push(...await Mt(s,"User",n));let i=Zc();t.push(...await bi(i,"User",n,!1));let c=await Bb(r)??ad(r).root,d=[],l=r;for(;d.push(l),!(l===c&&l!==r);){let u=Yo(l);if(u===l)break;l=u}for(let u of d.reverse()){t.push(...await Mt(Et(u,Eb),"Project",n));for(let p of Lb)t.push(...await Mt(Et(u,p),"Project",n));t.push(...await Mt(tl(u),"Project",n)),t.push(...await bi(rl(u),"Project",n,!1)),t.push(...await Mt(Et(u,Ob),"Local",n))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:r,fileCount:t.length}).catch(()=>{}),t}function cd(r){if(r.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 r){if(!n.content)continue;let o=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}${o}:
151
151
 
152
152
  ${n.content.trim()}`)}return t.length>0?`${e}
153
153
 
154
154
  ${t.join(`
155
155
 
156
- `)}`:""}var Rn=null,fi=null;async function nd(r,e){return Rn&&fi===r||(Rn=await Pb(r,e),fi=r),Rn}function od(){Rn=null,fi=null}function hi(r,e){return{name:r,compute:e,cacheBreak:!1}}function _n(r,e,t){return{name:r,compute:e,cacheBreak:!0}}var qo=new Map;async function Mb(r){return(await Promise.all(r.map(async t=>{if(!t.cacheBreak&&qo.has(t.name))return qo.get(t.name)??null;let n=await t.compute();return qo.set(t.name,n),n}))).filter(t=>t!=null)}function rd(){qo.clear()}async function sd(r){let e=[];if(r.instructionBlock&&e.push(r.instructionBlock),r.customSystemPrompt?e.push(r.customSystemPrompt):r.basePrompt&&e.push(r.basePrompt),r.sections?.length){let t=await Mb(r.sections);e.push(...t)}return r.appendSystemPrompt&&e.push(r.appendSystemPrompt),e.filter(Boolean).join(`
156
+ `)}`:""}var Cn=null,ki=null;async function ld(r,e){return Cn&&ki===r||(Cn=await Wb(r,e),ki=r),Cn}function dd(){Cn=null,ki=null}function Ti(r,e){return{name:r,compute:e,cacheBreak:!1}}function Pn(r,e,t){return{name:r,compute:e,cacheBreak:!0}}var Jo=new Map;async function Gb(r){return(await Promise.all(r.map(async t=>{if(!t.cacheBreak&&Jo.has(t.name))return Jo.get(t.name)??null;let n=await t.compute();return Jo.set(t.name,n),n}))).filter(t=>t!=null)}function ud(){Jo.clear()}async function pd(r){let e=[];if(r.instructionBlock&&e.push(r.instructionBlock),r.customSystemPrompt?e.push(r.customSystemPrompt):r.basePrompt&&e.push(r.basePrompt),r.sections?.length){let t=await Gb(r.sections);e.push(...t)}return r.appendSystemPrompt&&e.push(r.appendSystemPrompt),e.filter(Boolean).join(`
157
157
 
158
- `)}import{release as Eb,homedir as Ob}from"node:os";import{resolve as Db}from"node:path";function Lb(){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 $b(){let r=process.platform,e=Eb();return r==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():r==="darwin"?"macOS":r==="linux"?"Linux":r}function id(r){return hi("environment_context",()=>{let e=Lb(),t=$b(),n=r??process.cwd(),o=process.version,s=Ob(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${Db(n)}`,`- Home directory: ${s}`,`- Node.js: ${o}`];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(`
159
- `)})}function Ko(){return["## Problem Solving","- If an approach fails, diagnose why before switching tactics \u2014 read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.","- Report outcomes faithfully: if verification fails, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded.","- Do not create files unless they are absolutely necessary for achieving your goal. Prefer editing an existing file to creating a new one.","","## Safety","- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities.","- If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code."]}function Ub(){return["# Doing Tasks","","You will primarily perform software engineering tasks: solving bugs, adding new functionality, refactoring code, and more.","","## Code Quality","- In general, do not propose changes to code you haven't read. If you need to modify a file, read it first. Understand existing code before suggesting modifications.","","## Implementation Discipline",`- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.`,"- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).","- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. Three similar lines of code is better than a premature abstraction.","- Default to writing no comments unless the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug. Don't explain WHAT the code does \u2014 well-named identifiers already do that.",'- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding "// removed" comments for removed code. If code is unused, delete it completely.',"","## Completeness and Correctness","- When a task lists multiple constraints or requirements, implement ALL of them explicitly. Do not drop any.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns in the same codebase.","- After making changes, verify you met every requirement from the original request.","- For security fixes, use standard proven patterns (parameterized queries, input validation, etc.).","- NEVER leave TODO comments, placeholder implementations, or stub functions. Every function you write must have a complete, working implementation.","- When creating multiple files that import from each other, ensure every import resolves to a real export. Do not leave dead imports or forward declarations without implementations.","- If you create a file with a function signature, you MUST provide the full body \u2014 not `// implement later` or `throw new Error('not implemented')`.","","## Proactive Action","- When asked to fix, change, or improve code, implement the changes directly by writing to the file. Do not merely describe what should be changed.","- When you identify issues (bugs, security vulnerabilities, style problems), fix them immediately using your tools rather than listing recommendations.","- Default to action: read the file, make the fix, write it back. Only describe without acting when explicitly asked for advice or review only.","","## Faithful Reporting","- Report outcomes faithfully: if a tool call failed, say so with the error output. Do not claim success when a tool returned an error.","- If you did not run a verification step, say that rather than implying it succeeded.","- Never claim 'all tests pass' or 'file created successfully' when tool output shows otherwise.","- If you are unsure whether your changes are complete, state that explicitly rather than asserting completeness."]}function Nb(){return["# Doing Tasks","","You will assist with office and analytical tasks: reports, data analysis, documents, presentations, and more.","","## Accuracy and Rigor","- Verify numerical calculations and statistical claims. When presenting data, ensure totals, percentages, and comparisons are mathematically correct.","- Distinguish clearly between facts, inferences, and assumptions. Label uncertain information explicitly.","- When summarizing source material, preserve the original meaning. Do not introduce information not present in the source.","","## Structure and Formatting","- Use clear headings, bullet points, and tables to organize information. Match the formatting conventions of the document type (report, memo, email, slides).","- For data-heavy outputs, prefer tables over prose. Include units, time periods, and comparison baselines.","- Keep language professional and concise. Avoid filler, hedging, and unnecessary qualifiers.","","## Completeness","- When the task lists multiple sections, data points, or requirements, address ALL of them. Do not silently omit items.","- If source data is insufficient to answer a question, state what is missing rather than guessing."]}function jb(){return["# Doing Tasks","","You will assist with creative and content tasks: writing, copywriting, brainstorming, and content strategy.","","## Voice and Style","- Match the requested tone, register, and style. If no style is specified, adapt to the content type (formal for press releases, conversational for blog posts, punchy for ad copy).","- Vary sentence length and structure for rhythm. Avoid monotonous patterns.","- Show, don't tell where appropriate. Use concrete details and vivid language over abstract statements.","","## Audience Awareness","- Write for the intended audience. Consider their knowledge level, interests, and expectations.","- For marketing/copywriting, lead with the benefit. Focus on what matters to the reader, not the feature list.","- Respect cultural context and sensitivity in language choices.","","## Creative Process","- When brainstorming, provide diverse options rather than variations on a single idea. Quantity and variety first, then refine.","- When editing existing text, preserve the author's voice. Make targeted improvements rather than rewriting from scratch.","- If creative constraints are given (word count, format, platform), follow them precisely."]}function ad(r="general"){return _n("task_guidance",()=>{let e;switch(r){case"coding":e=[...Ub(),"",...Ko()];break;case"office":e=[...Nb(),"",...Ko()];break;case"creative":e=[...jb(),"",...Ko()];break;default:e=["# Doing Tasks","","You are a versatile assistant that handles software engineering, office, and creative tasks.","",...Ko(),"","## When Coding","- Read existing code before modifying it. Understand the structure before making changes.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns.","- Implement ALL listed constraints or requirements explicitly. Do not drop any.","- Don't add features or abstractions beyond what was asked.","- When asked to fix or change code, implement changes directly by writing to the file \u2014 do not merely describe what to change.","","## When Writing Documents or Analyzing Data","- Verify numerical calculations and statistical claims for correctness.","- Use clear structure: headings, tables, bullet points as appropriate.","- Distinguish facts from inferences. Label uncertain information.","","## When Creating Content","- Match the requested tone, style, and audience. Adapt if not specified.","- Lead with the benefit for marketing/copywriting tasks.","- Provide diverse options when brainstorming."];break}return e.join(`
160
- `)})}function ld(){return hi("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify ambiguous requests before proceeding,","especially for expensive operations like media generation."].join(`
161
- `))}import{existsSync as cd,mkdirSync as Fb,readFileSync as Cn,writeFileSync as dd}from"node:fs";import{join as An}from"node:path";var Jo=new Set(["coding","office","creative","general"]),ud="settings.yaml";function Bb(r){try{let e=An(r,we,ud),n=Cn(e,"utf-8").match(/^taskDomain\s*:\s*(\w+)/m);if(n){let o=n[1].toLowerCase();if(Jo.has(o))return o}}catch{}try{let e=An(r,we,"INSTRUCTIONS.md"),n=Cn(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(n){let o=n[0].match(/^domain\s*:\s*(\w+)/m);if(o){let s=o[1].toLowerCase();if(Jo.has(s))return s}}}catch{}try{let e=An(r,"INSTRUCTIONS.md"),n=Cn(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(n){let o=n[0].match(/^domain\s*:\s*(\w+)/m);if(o){let s=o[1].toLowerCase();if(Jo.has(s))return s}}}catch{}}var Gb=3;function Hb(r,e){let t=qb(r);return e?t===e||t==="general"?e:(bi(r)[t]??0)>=Gb?t:e:t}var Wb=/\b(?:code|coding|bug|debug|fix|refactor|function|class|method|api|compile|build|deploy|test|unittest|lint|git|commit|merge|branch|pull\s*request|PR|npm|pnpm|yarn|pip|docker|k8s|kubernetes|sql|database|migration|endpoint|route|middleware|typescript|javascript|python|java|rust|go(?:lang)?|css|html|react|vue|angular|nextjs|express|fastapi|flask|django|springboot|webpack|vite|rollup|esbuild|CI\/?CD|GitHub\s*Actions|workflow|pipeline|variable|const|let|var|import|export|module|package|dependency|dependencies|node_modules|tsconfig|eslint|prettier|interface|type\b|enum|struct|async|await|promise|callback|exception|error\s*handling|stack\s*trace|breakpoint|源码|代码|编程|编码|调试|重构|修复|Bug|函数|类|方法|接口|模块|依赖|组件|编译|构建|部署|测试|单元测试|提交|合并|分支|数据库|迁移|路由|中间件)\b/i,zb=/\b(?:report|document|spreadsheet|excel|csv|table|chart|graph|data\s*analysis|statistics|slides?|presentation|ppt|powerpoint|email|mail|memo|minutes|meeting|schedule|calendar|summary|summarize|brief|overview|outline|template|format|agenda|invoice|budget|forecast|dashboard|KPI|OKR|metric|analytics|insight|文档|报告|报表|表格|数据分析|统计|幻灯片|PPT|演示|邮件|信件|备忘录|会议纪要|日程|摘要|总结|概要|简报|模板|格式|议程|发票|预算|预测|看板|报表|分析)\b/i,Vb=/\b(?:write|writing|essay|article|blog|story|novel|poem|poetry|lyrics|copywriting|copy|slogan|tagline|headline|marketing|campaign|branding|creative|brainstorm|idea|concept|draft|narrative|character|dialogue|script|screenplay|pitch|proposal|content\s*strategy|social\s*media|SEO|newsletter|press\s*release|写作|文章|博客|故事|小说|诗|歌词|文案|标语|营销|策划|品牌|创意|头脑风暴|灵感|构思|草稿|叙事|角色|对话|剧本|策划案|提案|内容策略|自媒体|公众号|推文|软文|种草)\b/i;function qb(r){if(!r||r.trim().length===0)return"general";let e=bi(r),t=Math.max(e.coding,e.office,e.creative);return t===0||[e.coding,e.office,e.creative].filter(o=>o>=t-1&&o>0).length>=2&&t<=2?"general":e.coding===t?"coding":e.office===t?"office":e.creative===t?"creative":"general"}function bi(r){return{coding:yi(r,Wb),office:yi(r,zb),creative:yi(r,Vb),general:0}}function yi(r,e){let t=new RegExp(e.source,"gi"),n=r.match(t);return n?n.length:0}function pd(r){let e=Bb(r.cwd);if(e)return{domain:e,source:"project-file"};if(r.hostOverride&&Jo.has(r.hostOverride))return{domain:r.hostOverride,source:"host-override"};let t=Hb(r.userText,r.sessionDomain);return r.sessionDomain&&t===r.sessionDomain?{domain:t,source:"session-sticky"}:{domain:t,source:"auto-detect"}}var Kb=3;function md(r,e){if(e==="general")return!1;try{let t=An(r,we),n=An(t,ud);if(cd(n)){let s=Cn(n,"utf-8");if(/^taskDomain\s*:/m.test(s))return!1}Fb(t,{recursive:!0});let o=`# Auto-detected task domain for this workspace.
158
+ `)}import{release as Hb,homedir as Vb}from"node:os";import{resolve as zb}from"node:path";function Kb(){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 qb(){let r=process.platform,e=Hb();return r==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():r==="darwin"?"macOS":r==="linux"?"Linux":r}function md(r){return Ti("environment_context",()=>{let e=Kb(),t=qb(),n=r??process.cwd(),o=process.version,s=Vb(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${zb(n)}`,`- Home directory: ${s}`,`- Node.js: ${o}`];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(`
159
+ `)})}function Qo(){return["## Problem Solving","- If an approach fails, diagnose why before switching tactics \u2014 read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.","- Report outcomes faithfully: if verification fails, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded.","- Do not create files unless they are absolutely necessary for achieving your goal. Prefer editing an existing file to creating a new one.","","## Safety","- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities.","- If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code."]}function Xb(){return["# Doing Tasks","","You will primarily perform software engineering tasks: solving bugs, adding new functionality, refactoring code, and more.","","## Code Quality","- In general, do not propose changes to code you haven't read. If you need to modify a file, read it first. Understand existing code before suggesting modifications.","","## Implementation Discipline",`- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.`,"- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).","- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. Three similar lines of code is better than a premature abstraction.","- Default to writing no comments unless the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug. Don't explain WHAT the code does \u2014 well-named identifiers already do that.",'- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding "// removed" comments for removed code. If code is unused, delete it completely.',"","## Completeness and Correctness","- When a task lists multiple constraints or requirements, implement ALL of them explicitly. Do not drop any.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns in the same codebase.","- After making changes, verify you met every requirement from the original request.","- For security fixes, use standard proven patterns (parameterized queries, input validation, etc.).","- NEVER leave TODO comments, placeholder implementations, or stub functions. Every function you write must have a complete, working implementation.","- When creating multiple files that import from each other, ensure every import resolves to a real export. Do not leave dead imports or forward declarations without implementations.","- If you create a file with a function signature, you MUST provide the full body \u2014 not `// implement later` or `throw new Error('not implemented')`.","","## Proactive Action","- When asked to fix, change, or improve code, implement the changes directly by writing to the file. Do not merely describe what should be changed.","- When you identify issues (bugs, security vulnerabilities, style problems), fix them immediately using your tools rather than listing recommendations.","- Default to action: read the file, make the fix, write it back. Only describe without acting when explicitly asked for advice or review only.","","## Faithful Reporting","- Report outcomes faithfully: if a tool call failed, say so with the error output. Do not claim success when a tool returned an error.","- If you did not run a verification step, say that rather than implying it succeeded.","- Never claim 'all tests pass' or 'file created successfully' when tool output shows otherwise.","- If you are unsure whether your changes are complete, state that explicitly rather than asserting completeness."]}function Yb(){return["# Doing Tasks","","You will assist with office and analytical tasks: reports, data analysis, documents, presentations, and more.","","## Accuracy and Rigor","- Verify numerical calculations and statistical claims. When presenting data, ensure totals, percentages, and comparisons are mathematically correct.","- Distinguish clearly between facts, inferences, and assumptions. Label uncertain information explicitly.","- When summarizing source material, preserve the original meaning. Do not introduce information not present in the source.","","## Structure and Formatting","- Use clear headings, bullet points, and tables to organize information. Match the formatting conventions of the document type (report, memo, email, slides).","- For data-heavy outputs, prefer tables over prose. Include units, time periods, and comparison baselines.","- Keep language professional and concise. Avoid filler, hedging, and unnecessary qualifiers.","","## Completeness","- When the task lists multiple sections, data points, or requirements, address ALL of them. Do not silently omit items.","- If source data is insufficient to answer a question, state what is missing rather than guessing."]}function Jb(){return["# Doing Tasks","","You will assist with creative and content tasks: writing, copywriting, brainstorming, and content strategy.","","## Voice and Style","- Match the requested tone, register, and style. If no style is specified, adapt to the content type (formal for press releases, conversational for blog posts, punchy for ad copy).","- Vary sentence length and structure for rhythm. Avoid monotonous patterns.","- Show, don't tell where appropriate. Use concrete details and vivid language over abstract statements.","","## Audience Awareness","- Write for the intended audience. Consider their knowledge level, interests, and expectations.","- For marketing/copywriting, lead with the benefit. Focus on what matters to the reader, not the feature list.","- Respect cultural context and sensitivity in language choices.","","## Creative Process","- When brainstorming, provide diverse options rather than variations on a single idea. Quantity and variety first, then refine.","- When editing existing text, preserve the author's voice. Make targeted improvements rather than rewriting from scratch.","- If creative constraints are given (word count, format, platform), follow them precisely."]}function gd(r="general"){return Pn("task_guidance",()=>{let e;switch(r){case"coding":e=[...Xb(),"",...Qo()];break;case"office":e=[...Yb(),"",...Qo()];break;case"creative":e=[...Jb(),"",...Qo()];break;default:e=["# Doing Tasks","","You are a versatile assistant that handles software engineering, office, and creative tasks.","",...Qo(),"","## When Coding","- Read existing code before modifying it. Understand the structure before making changes.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns.","- Implement ALL listed constraints or requirements explicitly. Do not drop any.","- Don't add features or abstractions beyond what was asked.","- When asked to fix or change code, implement changes directly by writing to the file \u2014 do not merely describe what to change.","","## When Writing Documents or Analyzing Data","- Verify numerical calculations and statistical claims for correctness.","- Use clear structure: headings, tables, bullet points as appropriate.","- Distinguish facts from inferences. Label uncertain information.","","## When Creating Content","- Match the requested tone, style, and audience. Adapt if not specified.","- Lead with the benefit for marketing/copywriting tasks.","- Provide diverse options when brainstorming."];break}return e.join(`
160
+ `)})}function fd(){return Ti("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify ambiguous requests before proceeding,","especially for expensive operations like media generation."].join(`
161
+ `))}import{existsSync as hd,mkdirSync as Qb,readFileSync as In,writeFileSync as yd}from"node:fs";import{join as Mn}from"node:path";var Zo=new Set(["coding","office","creative","general"]),bd="settings.yaml";function Zb(r){try{let e=Mn(r,Se,bd),n=In(e,"utf-8").match(/^taskDomain\s*:\s*(\w+)/m);if(n){let o=n[1].toLowerCase();if(Zo.has(o))return o}}catch{}try{let e=Mn(r,Se,"INSTRUCTIONS.md"),n=In(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(n){let o=n[0].match(/^domain\s*:\s*(\w+)/m);if(o){let s=o[1].toLowerCase();if(Zo.has(s))return s}}}catch{}try{let e=Mn(r,"INSTRUCTIONS.md"),n=In(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(n){let o=n[0].match(/^domain\s*:\s*(\w+)/m);if(o){let s=o[1].toLowerCase();if(Zo.has(s))return s}}}catch{}}var ek=3;function tk(r,e){let t=sk(r);return e?t===e||t==="general"?e:(vi(r)[t]??0)>=ek?t:e:t}var nk=/\b(?:code|coding|bug|debug|fix|refactor|function|class|method|api|compile|build|deploy|test|unittest|lint|git|commit|merge|branch|pull\s*request|PR|npm|pnpm|yarn|pip|docker|k8s|kubernetes|sql|database|migration|endpoint|route|middleware|typescript|javascript|python|java|rust|go(?:lang)?|css|html|react|vue|angular|nextjs|express|fastapi|flask|django|springboot|webpack|vite|rollup|esbuild|CI\/?CD|GitHub\s*Actions|workflow|pipeline|variable|const|let|var|import|export|module|package|dependency|dependencies|node_modules|tsconfig|eslint|prettier|interface|type\b|enum|struct|async|await|promise|callback|exception|error\s*handling|stack\s*trace|breakpoint|源码|代码|编程|编码|调试|重构|修复|Bug|函数|类|方法|接口|模块|依赖|组件|编译|构建|部署|测试|单元测试|提交|合并|分支|数据库|迁移|路由|中间件)\b/i,ok=/\b(?:report|document|spreadsheet|excel|csv|table|chart|graph|data\s*analysis|statistics|slides?|presentation|ppt|powerpoint|email|mail|memo|minutes|meeting|schedule|calendar|summary|summarize|brief|overview|outline|template|format|agenda|invoice|budget|forecast|dashboard|KPI|OKR|metric|analytics|insight|文档|报告|报表|表格|数据分析|统计|幻灯片|PPT|演示|邮件|信件|备忘录|会议纪要|日程|摘要|总结|概要|简报|模板|格式|议程|发票|预算|预测|看板|报表|分析)\b/i,rk=/\b(?:write|writing|essay|article|blog|story|novel|poem|poetry|lyrics|copywriting|copy|slogan|tagline|headline|marketing|campaign|branding|creative|brainstorm|idea|concept|draft|narrative|character|dialogue|script|screenplay|pitch|proposal|content\s*strategy|social\s*media|SEO|newsletter|press\s*release|写作|文章|博客|故事|小说|诗|歌词|文案|标语|营销|策划|品牌|创意|头脑风暴|灵感|构思|草稿|叙事|角色|对话|剧本|策划案|提案|内容策略|自媒体|公众号|推文|软文|种草)\b/i;function sk(r){if(!r||r.trim().length===0)return"general";let e=vi(r),t=Math.max(e.coding,e.office,e.creative);return t===0||[e.coding,e.office,e.creative].filter(o=>o>=t-1&&o>0).length>=2&&t<=2?"general":e.coding===t?"coding":e.office===t?"office":e.creative===t?"creative":"general"}function vi(r){return{coding:wi(r,nk),office:wi(r,ok),creative:wi(r,rk),general:0}}function wi(r,e){let t=new RegExp(e.source,"gi"),n=r.match(t);return n?n.length:0}function kd(r){let e=Zb(r.cwd);if(e)return{domain:e,source:"project-file"};if(r.hostOverride&&Zo.has(r.hostOverride))return{domain:r.hostOverride,source:"host-override"};let t=tk(r.userText,r.sessionDomain);return r.sessionDomain&&t===r.sessionDomain?{domain:t,source:"session-sticky"}:{domain:t,source:"auto-detect"}}var ik=3;function Td(r,e){if(e==="general")return!1;try{let t=Mn(r,Se),n=Mn(t,bd);if(hd(n)){let s=In(n,"utf-8");if(/^taskDomain\s*:/m.test(s))return!1}Qb(t,{recursive:!0});let o=`# Auto-detected task domain for this workspace.
162
162
  # Values: coding | office | creative | general
163
- `;if(cd(n)){let s=Cn(n,"utf-8");dd(n,s.trimEnd()+`
163
+ `;if(hd(n)){let s=In(n,"utf-8");yd(n,s.trimEnd()+`
164
164
 
165
165
  `+o+`taskDomain: ${e}
166
- `,"utf-8")}else dd(n,o+`taskDomain: ${e}
167
- `,"utf-8");return!0}catch{return!1}}function gd(r,e){return e==="general"?!1:(bi(r)[e]??0)>=Kb}import*as z from"node:fs";import*as Z from"node:path";import{execFile as fw}from"node:child_process";var ki=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),fd=new Set([...ki,"agent"]);function Ti(r,e){let t=e?ki:fd;return r.filter(n=>n.function.name.startsWith("mcp__")?!0:!t.has(n.function.name))}var ot=new Map,wi=new Set;function hd(r){ot.clear(),wi.clear();for(let e of r)ot.set(e.name,e)}function ve(r){ot.set(r.name,r)}function vi(r){for(let e of r)ot.set(e.name,e)}function Xo(r){return ot.delete(r)}function Me(r){return ot.get(r)}function pt(){return Array.from(ot.keys())}function yd(r){let e=ot.get(r);return!e||e.isEnabled?.()===!1?!1:(wi.add(r),!0)}function rt(r=!1){let e=[];for(let t of ot.values())t.isEnabled?.()!==!1&&(!r&&t.shouldDefer&&!wi.has(t.name)||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 Jb="think",Xb={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(`
168
- `)}},required:["thought"]};function bd(){return{name:Jb,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(`
169
- `),parameters:Xb,execute:async(r,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}var Yb="task",Qb=["create","update","delete","list","get"];var Zb={type:"object",properties:{action:{type:"string",enum:[...Qb],description:"create \u2014 add a new task (auto-assigns id). update \u2014 modify a task by id (partial, supports dependency wiring). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list with summary. get \u2014 get a single task by id."},id:{type:"number",description:"[update|delete|get] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words, imperative form)."},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 (they depend on this task)."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task (this task depends on them)."}},required:["action"]};function Si(r){let e=new Set(r.filter(t=>t.status==="completed").map(t=>t.id));return{total:r.length,completed:r.filter(t=>t.status==="completed").length,inProgress:r.filter(t=>t.status==="in-progress").length,notStarted:r.filter(t=>t.status==="not-started").length,blocked:r.filter(t=>t.status!=="completed"&&t.blockedBy?.some(n=>!e.has(n))).length}}function kd(r,e){let t=[],n=0,o=r??{},s=o.verificationNudge!==!1;function i(){let m=t.reduce((y,k)=>Math.max(y,k.id),0);return n=Math.max(n,m)+1,n}function a(m){return{content:[{type:"text",text:`Error: ${m}`}],details:{type:"task",error:m}}}function c(m){let y=Si(t),k=new Set(t.filter(A=>A.status==="completed").map(A=>A.id)),b=t.map(A=>{let $=A.blockedBy?.filter(D=>!k.has(D));return{...A,...$?.length?{blockedBy:$}:{blockedBy:void 0}}}),x=[];if(x.push(`Task list updated. ${y.total} tasks: ${y.completed} completed, ${y.inProgress} in-progress, ${y.notStarted} not-started.`),y.blocked>0&&x.push(`${y.blocked} blocked.`),m?.created){let A=m.created;x.push(`Created task #${A.id}: "${A.title}"`)}if(m?.updated){let A=m.updated;x.push(`Updated task #${A.id}: "${A.title}"`)}if(m?.deleted!=null&&x.push(`Deleted task #${m.deleted}`),b.length>0){x.push("");for(let A of b){let $=A.status==="completed"?"\u2713":A.status==="in-progress"?"\u2192":"\u25CB",D=A.blockedBy?.length?` [blocked by #${A.blockedBy.join(", #")}]`:"",B=A.owner?` (${A.owner})`:"";x.push(` ${$} #${A.id}: ${A.title} (${A.status})${B}${D}`)}}let S=!1;if(s&&m?.updated&&m.updated.status==="completed"){let $=t.every(v=>v.status==="completed"),D=t.length,B=t.some(v=>/verif/i.test(v.title));$&&D>=3&&!B&&(S=!0,x.push(""),x.push("NOTE: You just closed out "+D+' tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (agent type="verify"). You cannot self-assign PARTIAL by listing caveats in your summary \u2014 only the verifier issues a verdict.'))}return{content:[{type:"text",text:x.join(`
170
- `)}],details:{type:"task",...y,...m,taskList:b,agentId:o.agentId,...S&&{verificationNudgeNeeded:!0}}}}function d(m,y,k){let b=t.find(x=>x.id===m);if(b){if(y?.length){b.blocks=[...new Set([...b.blocks??[],...y])];for(let x of y){let S=t.find(A=>A.id===x);S&&(S.blockedBy=[...new Set([...S.blockedBy??[],m])])}}if(k?.length){b.blockedBy=[...new Set([...b.blockedBy??[],...k])];for(let x of k){let S=t.find(A=>A.id===x);S&&(S.blocks=[...new Set([...S.blocks??[],m])])}}}}function l(m){for(let y of t)y.blocks&&(y.blocks=y.blocks.filter(k=>k!==m)),y.blockedBy&&(y.blockedBy=y.blockedBy.filter(k=>k!==m))}function u(m){if(!m.title)return a("title is required for create action.");let y={id:i(),title:m.title,status:m.status??"not-started",...m.description!=null&&{description:m.description},...m.owner!=null&&{owner:m.owner}};return t.push(y),d(y.id,void 0,m.addBlockedBy),e?.onTaskCreated?.(y),c({created:{id:y.id,title:y.title}})}function p(m){if(m.id==null)return a("id is required for update action.");let y=t.find(k=>k.id===m.id);if(!y)return a(`Task #${m.id} not found.`);if(m.status==="in-progress"){let k=new Set(t.filter(x=>x.status==="completed").map(x=>x.id)),b=y.blockedBy?.filter(x=>!k.has(x));if(b?.length)return a(`Cannot set #${m.id} to in-progress: blocked by unresolved task(s) #${b.join(", #")}.`)}if(m.title!=null&&(y.title=m.title),m.description!=null&&(y.description=m.description),m.owner!=null&&(y.owner=m.owner),m.status!=null){let k=y.status;y.status=m.status,k!=="completed"&&m.status==="completed"&&e?.onTaskCompleted?.(y)}return d(y.id,m.addBlocks,m.addBlockedBy),c({updated:{id:y.id,title:y.title,status:y.status}})}function g(m){if(m.id==null)return a("id is required for delete action.");let y=t.findIndex(k=>k.id===m.id);return y===-1?a(`Task #${m.id} not found.`):(n=Math.max(n,m.id),t.splice(y,1),l(m.id),c({deleted:m.id}))}function f(m){if(m.id==null)return a("id is required for get action.");let y=t.find(S=>S.id===m.id);if(!y)return a(`Task #${m.id} not found.`);let k=new Set(t.filter(S=>S.status==="completed").map(S=>S.id)),b=y.blockedBy?.filter(S=>!k.has(S));return{content:[{type:"text",text:[`Task #${y.id}: ${y.title}`,`Status: ${y.status}`,y.description?`Description: ${y.description}`:"",y.owner?`Owner: ${y.owner}`:"",b?.length?`Blocked by: #${b.join(", #")}`:"",y.blocks?.length?`Blocks: #${y.blocks.join(", #")}`:""].filter(Boolean).join(`
171
- `)}],details:{type:"task",action:"get",task:y}}}return{name:Yb,label:"Task",description:"Manage a structured task list to track multi-step work progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all), get (single task). Supports dependency tracking (blocks/blockedBy) \u2014 tasks cannot start until blockers complete. Use frequently during complex work to plan steps, coordinate subagents, and show progress.",parameters:Zb,searchHint:"manage session task checklist progress tracking dependencies planning",maxResultSizeChars:1e5,execute:async(m,y)=>{let k=y.action;switch(k){case"create":return u(y);case"update":return p(y);case"delete":return g(y);case"list":return c();case"get":return f(y);default:return a(`Unknown action: ${k}. Valid: create, update, delete, list, get.`)}}}}import{isAbsolute as wk,resolve as vk}from"node:path";var Td=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),wd=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),vd=new Set(["ls","tree","du"]);var Sd=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function ek(r){let t=r.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!t)return null;let n=t.split(/\s+/),o=0;for(;o<n.length&&/^[A-Za-z_]\w*=/.test(n[o]);)o++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;o<n.length;){let c=n[o];if(s.test(c)){for(o++;o<n.length&&/^[-+]/.test(n[o]);)o++;o<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[o])&&o++;continue}break}if(o>=n.length)return null;let i=n[o],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function xd(r){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(r)}function xi(r){let e=ek(r),t=e!==null&&Td.has(e),n=e!==null&&wd.has(e),o=e!==null&&vd.has(e),s=e!==null&&Sd.has(e),i=/(?:[^2]>|^>|\|>)/.test(r),a=xd(r),c=(t||n||o)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:o,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}function Ri(r){return/(?:^|[;&|])\s*sleep\s+\d/i.test(r)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(r)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as mk}from"node:child_process";import{constants as er,readFileSync as gk,unlinkSync as fk}from"node:fs";import{mkdir as hk,open as yk,realpath as Ad}from"node:fs/promises";import{isAbsolute as bk,resolve as kk}from"node:path";function Yo(){if(process.platform!=="win32")return!1;let r=process.env.QLOGICAGENT_USE_POWERSHELL;return r==="1"||r==="true"}function _i(){return Yo()?"powershell":"bash"}function Ci(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as tk,readFile as nk,writeFile as ok,unlink as rk}from"node:fs/promises";import{join as Rd}from"node:path";import{tmpdir as sk}from"node:os";var ik=8*1024*1024,ak=5*1024*1024*1024;var Ai;function In(){if(!Ai){let r=Math.random().toString(36).slice(2,10);Ai=Rd(sk(),"qla-tasks",r)}return Ai}function _d(r){return Rd(In(),`${r}.output`)}function st(r="local_bash"){return`${r}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var mt=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,n=!1,o=ik){this.taskId=e,this.path=_d(e),this.stdoutToFile=n,this.#t=o,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=lk(e),this.#d()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await nk(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#d(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&tk(In(),{recursive:!0}).then(()=>ok(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await rk(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function lk(r){let e=0;for(let t=0;t<r.length;t++)r.charCodeAt(t)===10&&e++;return e}var Ii=137,Cd=143,ck=5e3,Pi=5*1024*1024*1024,Qo=class{#e;#n;#r;#s=!1;constructor(e,t,n){this.#e=e,this.#n=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.#n.writeStderr(t):this.#n.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#n=null)}},Mi=class r{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#d;#l;#u;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,n,o,s=!1,i=Pi){this.#t=e,this.#l=t,this.#g=n,this.#b=s,this.#d=i,this.taskOutput=o,this.#s=e.stderr?new Qo(e.stderr,o,!0):null,this.#r=e.stdout?new Qo(e.stdout,o,!1):null,s&&(this.onTimeout=a=>{this.#u=a}),this.result=this.#R()}get status(){return this.#e}static#T(e){e.#b&&e.#u?e.#u(e.background.bind(e)):e.#y(Cd)}#w(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#S(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#k(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#k(){this.#o&&(clearInterval(this.#o),this.#o=null)}#x(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#d&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(Ii))},()=>{}))},ck),this.#o.unref?.()}#R(){this.#c=this.#w.bind(this),this.#l.addEventListener("abort",this.#c,{once:!0}),this.#t.once("exit",this.#v.bind(this)),this.#t.once("error",this.#S.bind(this)),this.#i=setTimeout(r.#T,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===Ii,backgroundTaskId:this.#n};this.taskOutput.stdoutToFile&&!this.#n&&(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 ${Pi} bytes. ${n.stderr}`:e===Cd&&(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??Ii)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#x():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#u=void 0}};function Ei(r,e,t,n,o=!1,s=Pi){return new Mi(r,e,t,n,o,s)}function Zo(r,e){let t=new mt(st("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:r}),taskOutput:t,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function Oi(r){let e=new mt(st("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:r,interrupted:!1,preSpawnError:r}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var dk=new Set(["API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","DEEPSEEK_API_KEY","DOUBAO_API_KEY","MINIMAX_API_KEY","GLM_API_KEY","KIMI_API_KEY","QWEN_API_KEY","MOONSHOT_API_KEY","ZHIPU_API_KEY","BAICHUAN_API_KEY","VOLCENGINE_API_KEY","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","GOOGLE_APPLICATION_CREDENTIALS","AZURE_CLIENT_SECRET","AZURE_CLIENT_ID","AZURE_TENANT_ID","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_RUNTIME_TOKEN","GITHUB_TOKEN","GH_TOKEN","GITLAB_TOKEN","CI_JOB_TOKEN","DATABASE_URL","REDIS_URL","REDIS_PASSWORD"]),uk=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function Di(){let r={...process.env};for(let e of Object.keys(r))pk(e)&&delete r[e];return r}function pk(r){if(dk.has(r))return!0;let e=r.toUpperCase();for(let t of uk)if(e.includes(t))return!0;return!1}var Tk=1800*1e3,tr=process.cwd(),Id=process.cwd();function nr(){return tr}function Li(r,e){tr=bk(r)?r:kk(e||tr,r)}function Pd(){return Id}function or(r){tr=r,Id=r}var $i=null;function Pn(r){$i={provider:r}}function Md(){if(!$i)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return $i.provider}async function rr(r,e,t,n){let{timeout:o,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:c,cwd:d}=n??{},l=o||Tk,u=t??_i(),p=Md(),g=Ci(),{commandString:f,cwdFilePath:m}=await p.buildExecCommand(r,{id:g,useSandbox:!1}),y=f,k=d??nr();try{await Ad(k)}catch{let v=Pd();try{await Ad(v),Li(v),k=v}catch{return Oi(`Working directory "${k}" no longer exists.`)}}if(e.aborted)return Zo();let b=p.shellPath,x=p.getSpawnArgs(y),S=await p.getEnvironmentOverrides(r),A=!!c,$=st("local_bash"),D=new mt($,s??null,!A);await hk(In(),{recursive:!0});let B;if(!A){let v=er.O_NOFOLLOW??0;B=await yk(D.path,process.platform==="win32"?"w":er.O_WRONLY|er.O_CREAT|er.O_APPEND|v)}try{let v=mk(b,x,{env:{...Di(),GIT_EDITOR:"true",QLOGICAGENT:"1",...S},cwd:k,stdio:A?["pipe","pipe","pipe"]:["pipe",B?.fd,B?.fd],detached:p.detached,windowsHide:!0}),oe=Ei(v,e,l,D,a);if(B!==void 0)try{await B.close()}catch{}return v.stdout&&c&&v.stdout.on("data",T=>{c(typeof T=="string"?T:T.toString())}),m&&oe.result.then(T=>{if(T&&!i&&!T.backgroundTaskId){try{let E=gk(m,{encoding:"utf8"}).trim();E&&E.normalize("NFC")!==k&&Li(E,k)}catch{}try{fk(m)}catch{}}}),oe}catch(v){if(B!==void 0)try{await B.close()}catch{}return D.clear(),Zo(void 0,{code:126,stderr:v instanceof Error?v.message:String(v)})}}var Sk="exec",xk={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"]},Rk=12e4,_k=6e5,sr=3e4;function Ui(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
166
+ `,"utf-8")}else yd(n,o+`taskDomain: ${e}
167
+ `,"utf-8");return!0}catch{return!1}}function wd(r,e){return e==="general"?!1:(vi(r)[e]??0)>=ik}import*as z from"node:fs";import*as Z from"node:path";import{execFile as Ow}from"node:child_process";var Si=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),vd=new Set([...Si,"agent"]);function Ri(r,e){let t=e?Si:vd;return r.filter(n=>n.function.name.startsWith("mcp__")?!0:!t.has(n.function.name))}var at=new Map,_i=new Set;function Sd(r){at.clear(),_i.clear();for(let e of r)at.set(e.name,e)}function Re(r){at.set(r.name,r)}function xi(r){for(let e of r)at.set(e.name,e)}function er(r){return at.delete(r)}function Oe(r){return at.get(r)}function mt(){return Array.from(at.keys())}function Rd(r){let e=at.get(r);return!e||e.isEnabled?.()===!1?!1:(_i.add(r),!0)}function ct(r=!1){let e=[];for(let t of at.values())t.isEnabled?.()!==!1&&(!r&&t.shouldDefer&&!_i.has(t.name)||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 ak="think",ck={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(`
168
+ `)}},required:["thought"]};function _d(){return{name:ak,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(`
169
+ `),parameters:ck,execute:async(r,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}var lk="task",dk=["create","update","delete","list","get"];var uk={type:"object",properties:{action:{type:"string",enum:[...dk],description:"create \u2014 add a new task (auto-assigns id). update \u2014 modify a task by id (partial, supports dependency wiring). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list with summary. get \u2014 get a single task by id."},id:{type:"number",description:"[update|delete|get] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words, imperative form)."},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 (they depend on this task)."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task (this task depends on them)."}},required:["action"]};function Ai(r){let e=new Set(r.filter(t=>t.status==="completed").map(t=>t.id));return{total:r.length,completed:r.filter(t=>t.status==="completed").length,inProgress:r.filter(t=>t.status==="in-progress").length,notStarted:r.filter(t=>t.status==="not-started").length,blocked:r.filter(t=>t.status!=="completed"&&t.blockedBy?.some(n=>!e.has(n))).length}}function xd(r,e){let t=[],n=0,o=r??{},s=o.verificationNudge!==!1;function i(){let g=t.reduce((y,b)=>Math.max(y,b.id),0);return n=Math.max(n,g)+1,n}function a(g){return{content:[{type:"text",text:`Error: ${g}`}],details:{type:"task",error:g}}}function c(g){let y=Ai(t),b=new Set(t.filter(P=>P.status==="completed").map(P=>P.id)),k=t.map(P=>{let O=P.blockedBy?.filter(L=>!b.has(L));return{...P,...O?.length?{blockedBy:O}:{blockedBy:void 0}}}),S=[];if(S.push(`Task list updated. ${y.total} tasks: ${y.completed} completed, ${y.inProgress} in-progress, ${y.notStarted} not-started.`),y.blocked>0&&S.push(`${y.blocked} blocked.`),g?.created){let P=g.created;S.push(`Created task #${P.id}: "${P.title}"`)}if(g?.updated){let P=g.updated;S.push(`Updated task #${P.id}: "${P.title}"`)}if(g?.deleted!=null&&S.push(`Deleted task #${g.deleted}`),k.length>0){S.push("");for(let P of k){let O=P.status==="completed"?"\u2713":P.status==="in-progress"?"\u2192":"\u25CB",L=P.blockedBy?.length?` [blocked by #${P.blockedBy.join(", #")}]`:"",B=P.owner?` (${P.owner})`:"";S.push(` ${O} #${P.id}: ${P.title} (${P.status})${B}${L}`)}}let R=!1;if(s&&g?.updated&&g.updated.status==="completed"){let O=t.every(v=>v.status==="completed"),L=t.length,B=t.some(v=>/verif/i.test(v.title));O&&L>=3&&!B&&(R=!0,S.push(""),S.push("NOTE: You just closed out "+L+' tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (agent type="verify"). You cannot self-assign PARTIAL by listing caveats in your summary \u2014 only the verifier issues a verdict.'))}return{content:[{type:"text",text:S.join(`
170
+ `)}],details:{type:"task",...y,...g,taskList:k,agentId:o.agentId,...R&&{verificationNudgeNeeded:!0}}}}function d(g,y,b){let k=t.find(S=>S.id===g);if(k){if(y?.length){k.blocks=[...new Set([...k.blocks??[],...y])];for(let S of y){let R=t.find(P=>P.id===S);R&&(R.blockedBy=[...new Set([...R.blockedBy??[],g])])}}if(b?.length){k.blockedBy=[...new Set([...k.blockedBy??[],...b])];for(let S of b){let R=t.find(P=>P.id===S);R&&(R.blocks=[...new Set([...R.blocks??[],g])])}}}}function l(g){for(let y of t)y.blocks&&(y.blocks=y.blocks.filter(b=>b!==g)),y.blockedBy&&(y.blockedBy=y.blockedBy.filter(b=>b!==g))}function u(g){if(!g.title)return a("title is required for create action.");let y={id:i(),title:g.title,status:g.status??"not-started",...g.description!=null&&{description:g.description},...g.owner!=null&&{owner:g.owner}};return t.push(y),d(y.id,void 0,g.addBlockedBy),e?.onTaskCreated?.(y),c({created:{id:y.id,title:y.title}})}function p(g){if(g.id==null)return a("id is required for update action.");let y=t.find(b=>b.id===g.id);if(!y)return a(`Task #${g.id} not found.`);if(g.status==="in-progress"){let b=new Set(t.filter(S=>S.status==="completed").map(S=>S.id)),k=y.blockedBy?.filter(S=>!b.has(S));if(k?.length)return a(`Cannot set #${g.id} to in-progress: blocked by unresolved task(s) #${k.join(", #")}.`)}if(g.title!=null&&(y.title=g.title),g.description!=null&&(y.description=g.description),g.owner!=null&&(y.owner=g.owner),g.status!=null){let b=y.status;y.status=g.status,b!=="completed"&&g.status==="completed"&&e?.onTaskCompleted?.(y)}return d(y.id,g.addBlocks,g.addBlockedBy),c({updated:{id:y.id,title:y.title,status:y.status}})}function m(g){if(g.id==null)return a("id is required for delete action.");let y=t.findIndex(b=>b.id===g.id);return y===-1?a(`Task #${g.id} not found.`):(n=Math.max(n,g.id),t.splice(y,1),l(g.id),c({deleted:g.id}))}function f(g){if(g.id==null)return a("id is required for get action.");let y=t.find(R=>R.id===g.id);if(!y)return a(`Task #${g.id} not found.`);let b=new Set(t.filter(R=>R.status==="completed").map(R=>R.id)),k=y.blockedBy?.filter(R=>!b.has(R));return{content:[{type:"text",text:[`Task #${y.id}: ${y.title}`,`Status: ${y.status}`,y.description?`Description: ${y.description}`:"",y.owner?`Owner: ${y.owner}`:"",k?.length?`Blocked by: #${k.join(", #")}`:"",y.blocks?.length?`Blocks: #${y.blocks.join(", #")}`:""].filter(Boolean).join(`
171
+ `)}],details:{type:"task",action:"get",task:y}}}return{name:lk,label:"Task",description:"Manage a structured task list to track multi-step work progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all), get (single task). Supports dependency tracking (blocks/blockedBy) \u2014 tasks cannot start until blockers complete. Use frequently during complex work to plan steps, coordinate subagents, and show progress.",parameters:uk,searchHint:"manage session task checklist progress tracking dependencies planning",maxResultSizeChars:1e5,execute:async(g,y)=>{let b=y.action;switch(b){case"create":return u(y);case"update":return p(y);case"delete":return m(y);case"list":return c();case"get":return f(y);default:return a(`Unknown action: ${b}. Valid: create, update, delete, list, get.`)}}}}import{isAbsolute as Ok,resolve as Dk}from"node:path";var Ad=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Cd=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Pd=new Set(["ls","tree","du"]);var Id=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function pk(r){let t=r.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!t)return null;let n=t.split(/\s+/),o=0;for(;o<n.length&&/^[A-Za-z_]\w*=/.test(n[o]);)o++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;o<n.length;){let c=n[o];if(s.test(c)){for(o++;o<n.length&&/^[-+]/.test(n[o]);)o++;o<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[o])&&o++;continue}break}if(o>=n.length)return null;let i=n[o],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Md(r){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(r)}function Ci(r){let e=pk(r),t=e!==null&&Ad.has(e),n=e!==null&&Cd.has(e),o=e!==null&&Pd.has(e),s=e!==null&&Id.has(e),i=/(?:[^2]>|^>|\|>)/.test(r),a=Md(r),c=(t||n||o)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:o,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}function Pi(r){return/(?:^|[;&|])\s*sleep\s+\d/i.test(r)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(r)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as _k}from"node:child_process";import{constants as rr,readFileSync as xk,unlinkSync as Ak}from"node:fs";import{mkdir as Ck,open as Pk,realpath as Ld}from"node:fs/promises";import{isAbsolute as Ik,resolve as Mk}from"node:path";function tr(){if(process.platform!=="win32")return!1;let r=process.env.QLOGICAGENT_USE_POWERSHELL;return r==="1"||r==="true"}function Ii(){return tr()?"powershell":"bash"}function Mi(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as mk,readFile as gk,writeFile as fk,unlink as hk}from"node:fs/promises";import{join as Ed}from"node:path";import{tmpdir as yk}from"node:os";var bk=8*1024*1024,kk=5*1024*1024*1024;var Ei;function En(){if(!Ei){let r=Math.random().toString(36).slice(2,10);Ei=Ed(yk(),"qla-tasks",r)}return Ei}function Od(r){return Ed(En(),`${r}.output`)}function lt(r="local_bash"){return`${r}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var gt=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,n=!1,o=bk){this.taskId=e,this.path=Od(e),this.stdoutToFile=n,this.#t=o,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=Tk(e),this.#d()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await gk(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#d(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&mk(En(),{recursive:!0}).then(()=>fk(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await hk(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function Tk(r){let e=0;for(let t=0;t<r.length;t++)r.charCodeAt(t)===10&&e++;return e}var Oi=137,Dd=143,wk=5e3,Di=5*1024*1024*1024,nr=class{#e;#n;#r;#s=!1;constructor(e,t,n){this.#e=e,this.#n=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.#n.writeStderr(t):this.#n.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#n=null)}},Li=class r{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#d;#c;#u;#g;#b;#p=null;#m=null;#l=null;taskOutput;result;onTimeout;constructor(e,t,n,o,s=!1,i=Di){this.#t=e,this.#c=t,this.#g=n,this.#b=s,this.#d=i,this.taskOutput=o,this.#s=e.stderr?new nr(e.stderr,o,!0):null,this.#r=e.stdout?new nr(e.stdout,o,!1):null,s&&(this.onTimeout=a=>{this.#u=a}),this.result=this.#_()}get status(){return this.#e}static#T(e){e.#b&&e.#u?e.#u(e.background.bind(e)):e.#y(Dd)}#w(){this.#c.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#S(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#k(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#l&&(this.#c.removeEventListener("abort",this.#l),this.#l=null)}#k(){this.#o&&(clearInterval(this.#o),this.#o=null)}#R(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#d&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(Oi))},()=>{}))},wk),this.#o.unref?.()}#_(){this.#l=this.#w.bind(this),this.#c.addEventListener("abort",this.#l,{once:!0}),this.#t.once("exit",this.#v.bind(this)),this.#t.once("error",this.#S.bind(this)),this.#i=setTimeout(r.#T,this.#g,this);let e=new Promise(t=>{this.#m=t});return new Promise(t=>{this.#p=t,e.then(this.#x.bind(this))})}async#x(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===Oi,backgroundTaskId:this.#n};this.taskOutput.stdoutToFile&&!this.#n&&(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 ${Di} bytes. ${n.stderr}`:e===Dd&&(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??Oi)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#R():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#c=null,this.#u=void 0}};function Ni(r,e,t,n,o=!1,s=Di){return new Li(r,e,t,n,o,s)}function or(r,e){let t=new gt(lt("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:r}),taskOutput:t,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function Ui(r){let e=new gt(lt("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:r,interrupted:!1,preSpawnError:r}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var vk=new Set(["API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","DEEPSEEK_API_KEY","DOUBAO_API_KEY","MINIMAX_API_KEY","GLM_API_KEY","KIMI_API_KEY","QWEN_API_KEY","MOONSHOT_API_KEY","ZHIPU_API_KEY","BAICHUAN_API_KEY","VOLCENGINE_API_KEY","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","GOOGLE_APPLICATION_CREDENTIALS","AZURE_CLIENT_SECRET","AZURE_CLIENT_ID","AZURE_TENANT_ID","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_RUNTIME_TOKEN","GITHUB_TOKEN","GH_TOKEN","GITLAB_TOKEN","CI_JOB_TOKEN","DATABASE_URL","REDIS_URL","REDIS_PASSWORD"]),Sk=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function $i(){let r={...process.env};for(let e of Object.keys(r))Rk(e)&&delete r[e];return r}function Rk(r){if(vk.has(r))return!0;let e=r.toUpperCase();for(let t of Sk)if(e.includes(t))return!0;return!1}var Ek=1800*1e3,sr=process.cwd(),Nd=process.cwd();function ir(){return sr}function ji(r,e){sr=Ik(r)?r:Mk(e||sr,r)}function Ud(){return Nd}function ar(r){sr=r,Nd=r}var Fi=null;function On(r){Fi={provider:r}}function $d(){if(!Fi)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return Fi.provider}async function cr(r,e,t,n){let{timeout:o,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:c,cwd:d}=n??{},l=o||Ek,u=t??Ii(),p=$d(),m=Mi(),{commandString:f,cwdFilePath:g}=await p.buildExecCommand(r,{id:m,useSandbox:!1}),y=f,b=d??ir();try{await Ld(b)}catch{let v=Ud();try{await Ld(v),ji(v),b=v}catch{return Ui(`Working directory "${b}" no longer exists.`)}}if(e.aborted)return or();let k=p.shellPath,S=p.getSpawnArgs(y),R=await p.getEnvironmentOverrides(r),P=!!c,O=lt("local_bash"),L=new gt(O,s??null,!P);await Ck(En(),{recursive:!0});let B;if(!P){let v=rr.O_NOFOLLOW??0;B=await Pk(L.path,process.platform==="win32"?"w":rr.O_WRONLY|rr.O_CREAT|rr.O_APPEND|v)}try{let v=_k(k,S,{env:{...$i(),GIT_EDITOR:"true",QLOGICAGENT:"1",...R},cwd:b,stdio:P?["pipe","pipe","pipe"]:["pipe",B?.fd,B?.fd],detached:p.detached,windowsHide:!0}),ee=Ni(v,e,l,L,a);if(B!==void 0)try{await B.close()}catch{}return v.stdout&&c&&v.stdout.on("data",T=>{c(typeof T=="string"?T:T.toString())}),g&&ee.result.then(T=>{if(T&&!i&&!T.backgroundTaskId){try{let E=xk(g,{encoding:"utf8"}).trim();E&&E.normalize("NFC")!==b&&ji(E,b)}catch{}try{Ak(g)}catch{}}}),ee}catch(v){if(B!==void 0)try{await B.close()}catch{}return L.clear(),or(void 0,{code:126,stderr:v instanceof Error?v.message:String(v)})}}var Lk="exec",Nk={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"]},Uk=12e4,$k=6e5,lr=3e4;function Bi(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
172
172
 
173
173
  ... [truncated ${r.length-e} chars] ...
174
174
 
175
- ${r.slice(-t)}`}function Ck(r){return r==null||r<=0?Rk:Math.min(r,_k)}async function*Ak(r){let{command:e,abortController:t,timeout:n,shouldAutoBackground:o,cwd:s}=r,i="",a=0,c=0,d=Date.now(),l=null;function u(){return new Promise(f=>{l=()=>f(null)})}let p=await rr(e,t.signal,void 0,{timeout:n,onProgress(f,m,y,k,b){i=m,a=y,c=k,l&&(l(),l=null)},shouldAutoBackground:o,cwd:s});for(p.onTimeout&&o&&p.onTimeout(f=>{let m=st("bg");f(m)});p.status==="running"&&await Promise.race([u(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-d)/1e3,totalLines:a,totalBytes:c};let g=await p.result;return p.cleanup(),g}function Ed(r={}){return{name:Sk,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:xk,maxResultSizeChars:sr,execute:async(e,t)=>{let n=xi(t.command);if(!t.background){let p=Ri(t.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:n}}}if(r.validateCommand){let p=await r.validateCommand(t.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_by_guard",reason:p,classification:n}}}let o=new AbortController,s=Ck(t.timeout),i=t.workdir?wk(t.workdir)?t.workdir:vk(nr(),t.workdir):void 0;if(t.background){let p=await rr(t.command,o.signal,void 0,{shouldAutoBackground:!1,cwd:i}),g=st("bg");if(p.background(g))return{content:[{type:"text",text:`Background task started (id: ${g}).
176
- Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:g,description:t.description,classification:n}}}let a=Ak({command:t.command,abortController:o,timeout:s,shouldAutoBackground:!0,cwd:i}),c;do c=await a.next(),!c.done&&r.onProgress&&r.onProgress(c.value);while(!c.done);let d=c.value,l=[];if(d.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${d.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:d.backgroundTaskId,assistantAutoBackgrounded:d.assistantAutoBackgrounded,classification:n}};d.outputFilePath?(l.push(Ui(d.stdout,sr)),l.push(`[full output: ${d.outputFilePath} (${d.outputFileSize} bytes)]`)):d.stdout&&l.push(Ui(d.stdout,sr)),d.stderr&&l.push(`[stderr]
177
- ${Ui(d.stderr,Math.floor(sr/4))}`),d.interrupted&&l.push(`[interrupted \u2014 exit code ${d.code}]`);let u;return d.code!==0&&r.interpretExitCode&&(u=r.interpretExitCode(d.code,d.stderr),u&&l.push(`[exit ${d.code}: ${u}]`)),l.length===0&&l.push(n.isSilent&&d.code===0?"Done":`(exit code ${d.code}, no output)`),{content:[{type:"text",text:l.join(`
178
- `)}],details:{type:"exec",exitCode:d.code,interrupted:d.interrupted,description:t.description,returnCodeInterpretation:u,noOutputExpected:n.isSilent,outputFilePath:d.outputFilePath,classification:n}}}}}import{tmpdir as Ik}from"node:os";import{join as Pk,posix as Ni}from"node:path";function Mk(r){return r.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function Ek(r){return!(/(?:^|[;&|])\s*<\s/.test(r)||/<<[-]?\s*['"]?[A-Za-z_]/.test(r))}function Ok(r,e){return`$'${r.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Od(r){return process.platform!=="win32"?r:r.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function ir(r,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:r,detached:!0,async buildExecCommand(n,o){let s=process.platform==="win32",i=Ik(),a=s?Od(i):i,c=o.useSandbox&&o.sandboxTmpDir?Ni.join(o.sandboxTmpDir,`cwd-${o.id}`):Ni.join(a,`qla-${o.id}-cwd`),d=o.useSandbox&&o.sandboxTmpDir?Ni.join(o.sandboxTmpDir,`cwd-${o.id}`):Pk(i,`qla-${o.id}-cwd`),l=Mk(n),u=Ek(l),p=Ok(l,u),g=[];if(t){let m=s?Od(t):t;g.push(`source '${m}' 2>/dev/null || true`)}return e?.sessionEnvScript&&g.push(e.sessionEnvScript),g.push(`eval ${p}`),g.push(`pwd -P >| '${c}'`),{commandString:g.join(" && "),cwdFilePath:d}},getSpawnArgs(n){return["-c",...!!t?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as Dk}from"node:os";import{join as Lk,posix as $k}from"node:path";function Dd(r){return Buffer.from(r,"utf16le").toString("base64")}function Uk(r){return["-NoProfile","-NonInteractive","-Command",r]}function ji(r){return{type:"powershell",shellPath:r,detached:!1,async buildExecCommand(e,t){let n=t.useSandbox&&t.sandboxTmpDir?$k.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):Lk(Dk(),`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(`
179
- ; `),i=e+s;return{commandString:t.useSandbox?[`'${r.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Dd(i)].join(" "):i,cwdFilePath:n}},getSpawnArgs(e){return Uk(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var Nk=[{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"}],jk=[{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 Fi(r){for(let{pattern:e,warning:t}of Nk)if(e.test(r))return t;return null}function Bi(r){for(let{pattern:e,warning:t}of jk)if(e.test(r))return t;return null}var Fk="read",Bk={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 Ld(r){return{name:Fk,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:Bk,execute:async(n,o)=>{let s=r.resolvePath(o.path);if(r.validatePath){let m=r.validatePath(s);if(m)return{content:[{type:"text",text:`Access denied: ${m}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await r.readFile(s);if(i.type==="image")return{content:[{type:"text",text:`[Image: ${s}] (${i.mimeType})`}],details:{type:"read",path:s,isImage:!0},imageUrls:[i.localPath]};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(`
175
+ ${r.slice(-t)}`}function jk(r){return r==null||r<=0?Uk:Math.min(r,$k)}async function*Fk(r){let{command:e,abortController:t,timeout:n,shouldAutoBackground:o,cwd:s}=r,i="",a=0,c=0,d=Date.now(),l=null;function u(){return new Promise(f=>{l=()=>f(null)})}let p=await cr(e,t.signal,void 0,{timeout:n,onProgress(f,g,y,b,k){i=g,a=y,c=b,l&&(l(),l=null)},shouldAutoBackground:o,cwd:s});for(p.onTimeout&&o&&p.onTimeout(f=>{let g=lt("bg");f(g)});p.status==="running"&&await Promise.race([u(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-d)/1e3,totalLines:a,totalBytes:c};let m=await p.result;return p.cleanup(),m}function jd(r={}){return{name:Lk,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:Nk,maxResultSizeChars:lr,execute:async(e,t)=>{let n=Ci(t.command);if(!t.background){let p=Pi(t.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:n}}}if(r.validateCommand){let p=await r.validateCommand(t.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_by_guard",reason:p,classification:n}}}let o=new AbortController,s=jk(t.timeout),i=t.workdir?Ok(t.workdir)?t.workdir:Dk(ir(),t.workdir):void 0;if(t.background){let p=await cr(t.command,o.signal,void 0,{shouldAutoBackground:!1,cwd:i}),m=lt("bg");if(p.background(m))return{content:[{type:"text",text:`Background task started (id: ${m}).
176
+ Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:t.description,classification:n}}}let a=Fk({command:t.command,abortController:o,timeout:s,shouldAutoBackground:!0,cwd:i}),c;do c=await a.next(),!c.done&&r.onProgress&&r.onProgress(c.value);while(!c.done);let d=c.value,l=[];if(d.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${d.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:d.backgroundTaskId,assistantAutoBackgrounded:d.assistantAutoBackgrounded,classification:n}};d.outputFilePath?(l.push(Bi(d.stdout,lr)),l.push(`[full output: ${d.outputFilePath} (${d.outputFileSize} bytes)]`)):d.stdout&&l.push(Bi(d.stdout,lr)),d.stderr&&l.push(`[stderr]
177
+ ${Bi(d.stderr,Math.floor(lr/4))}`),d.interrupted&&l.push(`[interrupted \u2014 exit code ${d.code}]`);let u;return d.code!==0&&r.interpretExitCode&&(u=r.interpretExitCode(d.code,d.stderr),u&&l.push(`[exit ${d.code}: ${u}]`)),l.length===0&&l.push(n.isSilent&&d.code===0?"Done":`(exit code ${d.code}, no output)`),{content:[{type:"text",text:l.join(`
178
+ `)}],details:{type:"exec",exitCode:d.code,interrupted:d.interrupted,description:t.description,returnCodeInterpretation:u,noOutputExpected:n.isSilent,outputFilePath:d.outputFilePath,classification:n}}}}}import{tmpdir as Bk}from"node:os";import{join as Wk,posix as Wi}from"node:path";function Gk(r){return r.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function Hk(r){return!(/(?:^|[;&|])\s*<\s/.test(r)||/<<[-]?\s*['"]?[A-Za-z_]/.test(r))}function Vk(r,e){return`$'${r.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Fd(r){return process.platform!=="win32"?r:r.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function dr(r,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:r,detached:!0,async buildExecCommand(n,o){let s=process.platform==="win32",i=Bk(),a=s?Fd(i):i,c=o.useSandbox&&o.sandboxTmpDir?Wi.join(o.sandboxTmpDir,`cwd-${o.id}`):Wi.join(a,`qla-${o.id}-cwd`),d=o.useSandbox&&o.sandboxTmpDir?Wi.join(o.sandboxTmpDir,`cwd-${o.id}`):Wk(i,`qla-${o.id}-cwd`),l=Gk(n),u=Hk(l),p=Vk(l,u),m=[];if(t){let g=s?Fd(t):t;m.push(`source '${g}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${c}'`),{commandString:m.join(" && "),cwdFilePath:d}},getSpawnArgs(n){return["-c",...!!t?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as zk}from"node:os";import{join as Kk,posix as qk}from"node:path";function Bd(r){return Buffer.from(r,"utf16le").toString("base64")}function Xk(r){return["-NoProfile","-NonInteractive","-Command",r]}function Gi(r){return{type:"powershell",shellPath:r,detached:!1,async buildExecCommand(e,t){let n=t.useSandbox&&t.sandboxTmpDir?qk.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):Kk(zk(),`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(`
179
+ ; `),i=e+s;return{commandString:t.useSandbox?[`'${r.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Bd(i)].join(" "):i,cwdFilePath:n}},getSpawnArgs(e){return Xk(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var Yk=[{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"}],Jk=[{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 Hi(r){for(let{pattern:e,warning:t}of Yk)if(e.test(r))return t;return null}function Vi(r){for(let{pattern:e,warning:t}of Jk)if(e.test(r))return t;return null}var Qk="read",Zk={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 Wd(r){return{name:Qk,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:Zk,execute:async(n,o)=>{let s=r.resolvePath(o.path);if(r.validatePath){let g=r.validatePath(s);if(g)return{content:[{type:"text",text:`Access denied: ${g}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await r.readFile(s);if(i.type==="image")return{content:[{type:"text",text:`[Image: ${s}] (${i.mimeType})`}],details:{type:"read",path:s,isImage:!0},imageUrls:[i.localPath]};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(`
180
180
  `),c=Math.max(0,(o.offset??1)-1),d=Math.min(o.limit??2e3,2e3),l=a.slice(c,c+d),u=l.join(`
181
181
  `);u.length>5e4&&(u=u.slice(0,5e4)+`
182
- ... (truncated)`);let p=a.length,g=c+l.length,f=g<p;return{content:[{type:"text",text:u}],details:{type:"read",path:s,totalLines:p,startLine:c+1,endLine:g,hasMore:f}}}}}var Gk="write",Hk={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"]},$d=5e5;function Ud(r){return{name:Gk,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:Hk,execute:async(e,t)=>{let n=r.resolvePath(t.path);if(r.validatePath){let s=r.validatePath(n);if(s)return{content:[{type:"text",text:`Access denied: ${s}`}],details:{type:"write",path:n,error:"access_denied"}}}if(t.content.length>$d)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${$d}). Split into multiple writes or use a different approach.`}],details:{type:"write",path:n,error:"content_too_large"}};if(r.checkReadBeforeWrite){let s=r.checkReadBeforeWrite(n);if(s)return{content:[{type:"text",text:s}],details:{type:"write",path:n,error:"not_read_first"}}}if(r.checkConcurrentModification){let s=r.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 r.writeFile(n,t.content);let o=t.content.split(`
183
- `).length;return{content:[{type:"text",text:`Wrote ${o} lines to ${n}`}],details:{type:"write",path:n,lineCount:o}}}}}var Wk="edit",zk={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 Nd(r){return{name:Wk,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:zk,execute:async(e,t)=>{let n=r.resolvePath(t.path);if(r.checkConcurrentModification){let l=r.checkConcurrentModification(n);if(l)return{content:[{type:"text",text:`Concurrent modification detected: ${l}. Re-read the file first.`}],details:{type:"edit",path:n,success:!1,reason:"concurrent_modification"}}}let o=await r.readFile(n),s=o.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(o.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=o.slice(0,s)+t.newText+o.slice(s+t.oldText.length);await r.writeFile(n,a);let d=o.slice(0,s).split(`
184
- `).length;return{content:[{type:"text",text:`Edited ${n} (line ${d})`}],details:{type:"edit",path:n,success:!0,firstChangedLine:d}}}}}var Vk="search",qk={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"]},jd=100,Fd=250,Gi=1e5;function Bd(r){return{name:Vk,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:qk,execute:async(e,t)=>{let n=t.path?r.resolvePath?r.resolvePath(t.path):t.path:"",o=t.mode;return o==="filename"?Kk(r,t,n):o==="content"?Jk(r,t,n):Xk(r,t,n)}}}async function Kk(r,e,t){let n=e.headLimit??jd,{files:o,truncated:s}=await r.glob(e.pattern,{cwd:t,limit:n===0?1e4:n}),i=e.offset??0,a=i>0?o.slice(i):o,c=n===0?a.length:n,d=a.slice(0,c),l=s||a.length>c;if(d.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let u=d.join(`
182
+ ... (truncated)`);let p=a.length,m=c+l.length,f=m<p;return{content:[{type:"text",text:u}],details:{type:"read",path:s,totalLines:p,startLine:c+1,endLine:m,hasMore:f}}}}}var eT="write",tT={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"]},Gd=5e5;function Hd(r){return{name:eT,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:tT,execute:async(e,t)=>{let n=r.resolvePath(t.path);if(r.validatePath){let s=r.validatePath(n);if(s)return{content:[{type:"text",text:`Access denied: ${s}`}],details:{type:"write",path:n,error:"access_denied"}}}if(t.content.length>Gd)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${Gd}). Split into multiple writes or use a different approach.`}],details:{type:"write",path:n,error:"content_too_large"}};if(r.checkReadBeforeWrite){let s=r.checkReadBeforeWrite(n);if(s)return{content:[{type:"text",text:s}],details:{type:"write",path:n,error:"not_read_first"}}}if(r.checkConcurrentModification){let s=r.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 r.writeFile(n,t.content);let o=t.content.split(`
183
+ `).length;return{content:[{type:"text",text:`Wrote ${o} lines to ${n}`}],details:{type:"write",path:n,lineCount:o}}}}}var nT="edit",oT={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 Vd(r){return{name:nT,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:oT,execute:async(e,t)=>{let n=r.resolvePath(t.path);if(r.checkConcurrentModification){let l=r.checkConcurrentModification(n);if(l)return{content:[{type:"text",text:`Concurrent modification detected: ${l}. Re-read the file first.`}],details:{type:"edit",path:n,success:!1,reason:"concurrent_modification"}}}let o=await r.readFile(n),s=o.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(o.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=o.slice(0,s)+t.newText+o.slice(s+t.oldText.length);await r.writeFile(n,a);let d=o.slice(0,s).split(`
184
+ `).length;return{content:[{type:"text",text:`Edited ${n} (line ${d})`}],details:{type:"edit",path:n,success:!0,firstChangedLine:d}}}}}var rT="search",sT={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"]},zd=100,Kd=250,zi=1e5;function qd(r){return{name:rT,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:sT,execute:async(e,t)=>{let n=t.path?r.resolvePath?r.resolvePath(t.path):t.path:"",o=t.mode;return o==="filename"?iT(r,t,n):o==="content"?aT(r,t,n):cT(r,t,n)}}}async function iT(r,e,t){let n=e.headLimit??zd,{files:o,truncated:s}=await r.glob(e.pattern,{cwd:t,limit:n===0?1e4:n}),i=e.offset??0,a=i>0?o.slice(i):o,c=n===0?a.length:n,d=a.slice(0,c),l=s||a.length>c;if(d.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let u=d.join(`
185
185
  `);return l&&(u+=`
186
186
 
187
- (Results truncated. ${d.length} shown. Use a more specific pattern or increase headLimit.)`),u=Hi(u,Gi),{content:[{type:"text",text:u}],details:{mode:"filename",totalMatches:d.length,truncated:l}}}async function Jk(r,e,t){let n=e.headLimit??Fd,{matches:o,truncated:s}=await r.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:n===0?void 0:n,offset:e.offset});if(o.length===0)return{content:[{type:"text",text:"No matches found."}],details:{mode:"content",totalMatches:0,truncated:!1}};let i=[];for(let c of o){if(c.contextBefore&&c.contextBefore.length>0)for(let d of c.contextBefore)i.push(` ${d}`);if(i.push(`${c.path}:${c.line}: ${c.text}`),c.contextAfter&&c.contextAfter.length>0)for(let d of c.contextAfter)i.push(` ${d}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
187
+ (Results truncated. ${d.length} shown. Use a more specific pattern or increase headLimit.)`),u=Ki(u,zi),{content:[{type:"text",text:u}],details:{mode:"filename",totalMatches:d.length,truncated:l}}}async function aT(r,e,t){let n=e.headLimit??Kd,{matches:o,truncated:s}=await r.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:n===0?void 0:n,offset:e.offset});if(o.length===0)return{content:[{type:"text",text:"No matches found."}],details:{mode:"content",totalMatches:0,truncated:!1}};let i=[];for(let c of o){if(c.contextBefore&&c.contextBefore.length>0)for(let d of c.contextBefore)i.push(` ${d}`);if(i.push(`${c.path}:${c.line}: ${c.text}`),c.contextAfter&&c.contextAfter.length>0)for(let d of c.contextAfter)i.push(` ${d}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
188
188
  `);return s&&(a+=`
189
189
 
190
- (Results truncated at ${o.length} matches. Use offset/headLimit for pagination.)`),a=Hi(a,Gi),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:o.length,truncated:s}}}async function Xk(r,e,t){let[n,o]=await Promise.all([e.fileGlob?r.glob(e.fileGlob,{cwd:t,limit:jd}):Promise.resolve({files:[],truncated:!1}),r.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Fd,offset:e.offset})]),s=new Set(o.matches.map(l=>l.path)),i=n.files.filter(l=>!s.has(l)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
190
+ (Results truncated at ${o.length} matches. Use offset/headLimit for pagination.)`),a=Ki(a,zi),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:o.length,truncated:s}}}async function cT(r,e,t){let[n,o]=await Promise.all([e.fileGlob?r.glob(e.fileGlob,{cwd:t,limit:zd}):Promise.resolve({files:[],truncated:!1}),r.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Kd,offset:e.offset})]),s=new Set(o.matches.map(l=>l.path)),i=n.files.filter(l=>!s.has(l)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
191
191
  ${i.join(`
192
192
  `)}`),o.matches.length>0){let l=[];for(let u of o.matches)l.push(`${u.path}:${u.line}: ${u.text}`);a.push(`## Content matches (${o.matches.length}):
193
193
  ${l.join(`
@@ -195,113 +195,114 @@ ${l.join(`
195
195
 
196
196
  `);return c&&(d+=`
197
197
 
198
- (Some results truncated. Use more specific patterns.)`),d=Hi(d,Gi),{content:[{type:"text",text:d}],details:{mode:"both",totalMatches:i.length+o.matches.length,truncated:c}}}function Hi(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
198
+ (Some results truncated. Use more specific patterns.)`),d=Ki(d,zi),{content:[{type:"text",text:d}],details:{mode:"both",totalMatches:i.length+o.matches.length,truncated:c}}}function Ki(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
199
199
 
200
200
  ... [truncated ${r.length-e} chars] ...
201
201
 
202
- ${r.slice(-t)}`}var Yk="apply_patch",Qk={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function Zk(r){let e=r.split(`
203
- `),t=[],n=null,o=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:[]},o={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.hunks.push(o);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},o=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},o=null;else if(i.startsWith("*** Move to: ")&&n)n.moveTo=i.slice(13).trim();else if(i.startsWith("@@ ")&&n)o={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.hunks.push(o);else if(o)if(i.startsWith("+"))o.additions.push(i.slice(1));else if(i.startsWith("-"))o.removals.push(i.slice(1));else{let a=i.startsWith(" ")?i.slice(1):i;o.additions.length===0&&o.removals.length===0?o.contextBefore.push(a):o.contextAfter.push(a)}}}return n&&t.push(n),t}function eT(r,e){let n=[...r.split(`
202
+ ${r.slice(-t)}`}var lT="apply_patch",dT={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function uT(r){let e=r.split(`
203
+ `),t=[],n=null,o=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:[]},o={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.hunks.push(o);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},o=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},o=null;else if(i.startsWith("*** Move to: ")&&n)n.moveTo=i.slice(13).trim();else if(i.startsWith("@@ ")&&n)o={contextBefore:[],removals:[],additions:[],contextAfter:[]},n.hunks.push(o);else if(o)if(i.startsWith("+"))o.additions.push(i.slice(1));else if(i.startsWith("-"))o.removals.push(i.slice(1));else{let a=i.startsWith(" ")?i.slice(1):i;o.additions.length===0&&o.removals.length===0?o.contextBefore.push(a):o.contextAfter.push(a)}}}return n&&t.push(n),t}function pT(r,e){let n=[...r.split(`
204
204
  `)];for(let o of e){let s=-1;if(o.contextBefore.length>0)for(let i=0;i<=n.length-o.contextBefore.length;i++){let a=!0;for(let c=0;c<o.contextBefore.length;c++)if(n[i+c]!==o.contextBefore[c]){a=!1;break}if(a){s=i+o.contextBefore.length;break}}else s=0;s!==-1&&(o.removals.length>0?n.splice(s,o.removals.length,...o.additions):n.splice(s,0,...o.additions))}return n.join(`
205
- `)}function Gd(r){return{name:Yk,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:Qk,execute:async(e,t)=>{let n=Zk(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 o={added:[],modified:[],deleted:[]},s=[];for(let a of n){let c=r.resolvePath(a.path);try{switch(a.type){case"add":{let d=a.hunks.flatMap(l=>[...l.additions]).join(`
206
- `);await r.writeFile(c,d),o.added.push(a.path);break}case"update":{let d=await r.readFile(c),l=eT(d,a.hunks);if(a.moveTo){let u=r.resolvePath(a.moveTo);await r.writeFile(u,l),await r.deleteFile(c),o.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await r.writeFile(c,l),o.modified.push(a.path);break}case"delete":{await r.deleteFile(c),o.deleted.push(a.path);break}}}catch(d){s.push(`${a.type} ${a.path}: ${d instanceof Error?d.message:String(d)}`)}}let i=[];return o.added.length&&i.push(`Added: ${o.added.join(", ")}`),o.modified.length&&i.push(`Modified: ${o.modified.join(", ")}`),o.deleted.length&&i.push(`Deleted: ${o.deleted.join(", ")}`),s.length&&i.push(`Errors: ${s.join("; ")}`),{content:[{type:"text",text:i.join(`
207
- `)||"No changes applied."}],details:{type:"apply_patch",summary:o,errors:s}}}}}var tT="patch",nT={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
205
+ `)}function Xd(r){return{name:lT,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:dT,execute:async(e,t)=>{let n=uT(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 o={added:[],modified:[],deleted:[]},s=[];for(let a of n){let c=r.resolvePath(a.path);try{switch(a.type){case"add":{let d=a.hunks.flatMap(l=>[...l.additions]).join(`
206
+ `);await r.writeFile(c,d),o.added.push(a.path);break}case"update":{let d=await r.readFile(c),l=pT(d,a.hunks);if(a.moveTo){let u=r.resolvePath(a.moveTo);await r.writeFile(u,l),await r.deleteFile(c),o.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await r.writeFile(c,l),o.modified.push(a.path);break}case"delete":{await r.deleteFile(c),o.deleted.push(a.path);break}}}catch(d){s.push(`${a.type} ${a.path}: ${d instanceof Error?d.message:String(d)}`)}}let i=[];return o.added.length&&i.push(`Added: ${o.added.join(", ")}`),o.modified.length&&i.push(`Modified: ${o.modified.join(", ")}`),o.deleted.length&&i.push(`Deleted: ${o.deleted.join(", ")}`),s.length&&i.push(`Errors: ${s.join("; ")}`),{content:[{type:"text",text:i.join(`
207
+ `)||"No changes applied."}],details:{type:"apply_patch",summary:o,errors:s}}}}}var mT="patch",gT={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
208
208
  1) V4A unified diff (*** Begin Patch / *** End Patch markers)
209
209
  2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
210
- 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 oT(r){return r.replace(/\\n/g,`
211
- `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Hd(r){return r.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 Wd(r,e){if(r===e||Math.max(r.length,e.length)===0)return 1;let n=0,o=r.length,s=e.length,i=Math.max(o,s);for(let a=0;a<Math.min(o,s);a++)r[a]!==e[a]&&n++;return n+=Math.abs(o-s),1-n/i}function Xd(r,e,t){let n=[],o=r.indexOf(e);if(o!==-1){if(t){let m=0;for(;(o=r.indexOf(e,m))!==-1;)n.push({start:o,end:o+e.length,strategy:"exact"}),m=o+e.length}else n.push({start:o,end:o+e.length,strategy:"exact"});return n}let s=e.split(`
212
- `).map(m=>m.trim()),i=r.split(`
213
- `),a=zd(i,s,(m,y)=>m.trim()===y);if(a)return[{...Vd(r,i,a),strategy:"line_trimmed"}];let c=e.replace(/[ \t]+/g," "),d=r.replace(/[ \t]+/g," ");if(o=d.indexOf(c),o!==-1){let m=qd(r,d,o,c.length);if(m)return[{...m,strategy:"whitespace_normalized"}]}let l=zd(i,s,(m,y)=>m.trimStart()===y.trimStart());if(l)return[{...Vd(r,i,l),strategy:"indentation_flexible"}];let u=oT(e);if(u!==e&&(o=r.indexOf(u),o!==-1))return[{start:o,end:o+u.length,strategy:"escape_normalized"}];let p=e.split(`
214
- `);if(p.length>=3){let m=p.slice(1,-1).join(`
215
- `),y=p[0].trim(),k=p[p.length-1].trim();for(let b=0;b<i.length;b++)if(i[b].trim()===y){let x=i.slice(0,b+1).join(`
216
- `).length+1,S=r.indexOf(m,x);if(S!==-1){let A=S+m.length,$=r.indexOf(`
217
- `,A);if(($===-1?r.slice(A):r.slice(A,$)).trim()===k||$!==-1&&r.slice(A+1,r.indexOf(`
218
- `,A+1)===-1?void 0:r.indexOf(`
219
- `,A+1)).trim()===k){let B=i.slice(0,b).join(`
220
- `).length+(b>0?1:0),v=b,oe=p.length;if(b+oe<=i.length){v=b+oe;let T=i.slice(0,v).join(`
221
- `).length;return[{start:B,end:T,strategy:"trimmed_boundary"}]}}}}}let g=Hd(e),f=Hd(r);if((g!==e||f!==r)&&(o=f.indexOf(g),o!==-1)){let m=qd(r,f,o,g.length);if(m)return[{...m,strategy:"unicode_normalized"}]}if(p.length>=3){let m=p[0],y=p[p.length-1];for(let k=0;k<i.length;k++)if(i[k]===m){for(let b=k+p.length-1;b<Math.min(k+p.length+2,i.length);b++)if(i[b]===y){let x=b-k+1,S=i.slice(k+1,b),A=p.slice(1,-1),$=A.filter(B=>S.some(v=>Wd(v,B)>=.7)).length;if((A.length>0?$/A.length:1)>=.5&&x<=p.length+2){let B=i.slice(0,k).join(`
222
- `).length+(k>0?1:0),v=i.slice(0,b+1).join(`
223
- `).length;return[{start:B,end:v,strategy:"block_anchor"}]}}}}if(p.length>=2)for(let m=0;m<=i.length-p.length;m++){let y=i.slice(m,m+p.length);if(p.map((x,S)=>Wd(x,y[S])).filter(x=>x>=.8).length/p.length>=.5){let x=i.slice(0,m).join(`
224
- `).length+(m>0?1:0),S=i.slice(0,m+p.length).join(`
225
- `).length;return[{start:x,end:S,strategy:"context_aware"}]}}return[]}function zd(r,e,t){for(let n=0;n<=r.length-e.length;n++){let o=!0;for(let s=0;s<e.length;s++)if(!t(r[n+s],e[s])){o=!1;break}if(o)return{startIdx:n,endIdx:n+e.length}}return null}function Vd(r,e,t){let n=e.slice(0,t.startIdx).join(`
210
+ 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 fT(r){return r.replace(/\\n/g,`
211
+ `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Yd(r){return r.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 Jd(r,e){if(r===e||Math.max(r.length,e.length)===0)return 1;let n=0,o=r.length,s=e.length,i=Math.max(o,s);for(let a=0;a<Math.min(o,s);a++)r[a]!==e[a]&&n++;return n+=Math.abs(o-s),1-n/i}function ou(r,e,t){let n=[],o=r.indexOf(e);if(o!==-1){if(t){let g=0;for(;(o=r.indexOf(e,g))!==-1;)n.push({start:o,end:o+e.length,strategy:"exact"}),g=o+e.length}else n.push({start:o,end:o+e.length,strategy:"exact"});return n}let s=e.split(`
212
+ `).map(g=>g.trim()),i=r.split(`
213
+ `),a=Qd(i,s,(g,y)=>g.trim()===y);if(a)return[{...Zd(r,i,a),strategy:"line_trimmed"}];let c=e.replace(/[ \t]+/g," "),d=r.replace(/[ \t]+/g," ");if(o=d.indexOf(c),o!==-1){let g=eu(r,d,o,c.length);if(g)return[{...g,strategy:"whitespace_normalized"}]}let l=Qd(i,s,(g,y)=>g.trimStart()===y.trimStart());if(l)return[{...Zd(r,i,l),strategy:"indentation_flexible"}];let u=fT(e);if(u!==e&&(o=r.indexOf(u),o!==-1))return[{start:o,end:o+u.length,strategy:"escape_normalized"}];let p=e.split(`
214
+ `);if(p.length>=3){let g=p.slice(1,-1).join(`
215
+ `),y=p[0].trim(),b=p[p.length-1].trim();for(let k=0;k<i.length;k++)if(i[k].trim()===y){let S=i.slice(0,k+1).join(`
216
+ `).length+1,R=r.indexOf(g,S);if(R!==-1){let P=R+g.length,O=r.indexOf(`
217
+ `,P);if((O===-1?r.slice(P):r.slice(P,O)).trim()===b||O!==-1&&r.slice(P+1,r.indexOf(`
218
+ `,P+1)===-1?void 0:r.indexOf(`
219
+ `,P+1)).trim()===b){let B=i.slice(0,k).join(`
220
+ `).length+(k>0?1:0),v=k,ee=p.length;if(k+ee<=i.length){v=k+ee;let T=i.slice(0,v).join(`
221
+ `).length;return[{start:B,end:T,strategy:"trimmed_boundary"}]}}}}}let m=Yd(e),f=Yd(r);if((m!==e||f!==r)&&(o=f.indexOf(m),o!==-1)){let g=eu(r,f,o,m.length);if(g)return[{...g,strategy:"unicode_normalized"}]}if(p.length>=3){let g=p[0],y=p[p.length-1];for(let b=0;b<i.length;b++)if(i[b]===g){for(let k=b+p.length-1;k<Math.min(b+p.length+2,i.length);k++)if(i[k]===y){let S=k-b+1,R=i.slice(b+1,k),P=p.slice(1,-1),O=P.filter(B=>R.some(v=>Jd(v,B)>=.7)).length;if((P.length>0?O/P.length:1)>=.5&&S<=p.length+2){let B=i.slice(0,b).join(`
222
+ `).length+(b>0?1:0),v=i.slice(0,k+1).join(`
223
+ `).length;return[{start:B,end:v,strategy:"block_anchor"}]}}}}if(p.length>=2)for(let g=0;g<=i.length-p.length;g++){let y=i.slice(g,g+p.length);if(p.map((S,R)=>Jd(S,y[R])).filter(S=>S>=.8).length/p.length>=.5){let S=i.slice(0,g).join(`
224
+ `).length+(g>0?1:0),R=i.slice(0,g+p.length).join(`
225
+ `).length;return[{start:S,end:R,strategy:"context_aware"}]}}return[]}function Qd(r,e,t){for(let n=0;n<=r.length-e.length;n++){let o=!0;for(let s=0;s<e.length;s++)if(!t(r[n+s],e[s])){o=!1;break}if(o)return{startIdx:n,endIdx:n+e.length}}return null}function Zd(r,e,t){let n=e.slice(0,t.startIdx).join(`
226
226
  `).length+(t.startIdx>0?1:0),o=e.slice(0,t.endIdx).join(`
227
- `).length;return{start:n,end:o}}function qd(r,e,t,n){let o=0,s=0,i=-1,a=-1;for(;o<=r.length&&s<=e.length;){if(s===t&&i===-1&&(i=o),s===t+n){a=o;break}if(s>=e.length||o>=r.length)break;for(s++,o++;o<r.length&&s<e.length&&r[o]!==e[s];)o++}return i!==-1&&a===-1&&(a=r.length),i===-1?null:{start:i,end:a}}function Kd(r){let e=r.split(`
228
- `),t=[],n=null,o=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:[]},o={lines:[]},n.hunks.push(o);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},o=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},o=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:[]},o=null}else i.startsWith("@@ ")&&n?(o={contextHint:i.slice(3).replace(/ @@$/,"").trim()||void 0,lines:[]},n.hunks.push(o)):o&&(i.startsWith("+")?o.lines.push({prefix:"+",content:i.slice(1)}):i.startsWith("-")?o.lines.push({prefix:"-",content:i.slice(1)}):o.lines.push({prefix:" ",content:i.startsWith(" ")?i.slice(1):i}))}return n&&t.push(n),t}function rT(r){let e=[],t=r.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let n=t[0].trim().split(`
227
+ `).length;return{start:n,end:o}}function eu(r,e,t,n){let o=0,s=0,i=-1,a=-1;for(;o<=r.length&&s<=e.length;){if(s===t&&i===-1&&(i=o),s===t+n){a=o;break}if(s>=e.length||o>=r.length)break;for(s++,o++;o<r.length&&s<e.length&&r[o]!==e[s];)o++}return i!==-1&&a===-1&&(a=r.length),i===-1?null:{start:i,end:a}}function tu(r){let e=r.split(`
228
+ `),t=[],n=null,o=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:[]},o={lines:[]},n.hunks.push(o);else if(i.startsWith("*** Update File: "))n&&t.push(n),n={type:"update",path:i.slice(17).trim(),hunks:[]},o=null;else if(i.startsWith("*** Delete File: "))n&&t.push(n),n={type:"delete",path:i.slice(17).trim(),hunks:[]},o=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:[]},o=null}else i.startsWith("@@ ")&&n?(o={contextHint:i.slice(3).replace(/ @@$/,"").trim()||void 0,lines:[]},n.hunks.push(o)):o&&(i.startsWith("+")?o.lines.push({prefix:"+",content:i.slice(1)}):i.startsWith("-")?o.lines.push({prefix:"-",content:i.slice(1)}):o.lines.push({prefix:" ",content:i.startsWith(" ")?i.slice(1):i}))}return n&&t.push(n),t}function hT(r){let e=[],t=r.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let n=t[0].trim().split(`
229
229
  `).pop()?.trim();if(!n)return[];for(let o=1;o<t.length;o+=2){let s=t[o+1]||"",i=s.indexOf(`
230
230
  ====
231
231
  `);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),c=s.slice(i+6),d=c.indexOf(`
232
- >>>> REPLACE`),l=d===-1?c:c.slice(0,d);e.push({path:n,search:a,replace:l})}return e}function Jd(r,e,t){let n=e.lines.filter(f=>f.prefix===" ").map(f=>f.content),o=e.lines.filter(f=>f.prefix==="-").map(f=>f.content),s=e.lines.filter(f=>f.prefix==="+").map(f=>f.content),i=[],a="context";for(let f of e.lines)(f.prefix===" "||f.prefix==="-")&&i.push(f.content);let c=i.join(`
232
+ >>>> REPLACE`),l=d===-1?c:c.slice(0,d);e.push({path:n,search:a,replace:l})}return e}function nu(r,e,t){let n=e.lines.filter(f=>f.prefix===" ").map(f=>f.content),o=e.lines.filter(f=>f.prefix==="-").map(f=>f.content),s=e.lines.filter(f=>f.prefix==="+").map(f=>f.content),i=[],a="context";for(let f of e.lines)(f.prefix===" "||f.prefix==="-")&&i.push(f.content);let c=i.join(`
233
233
  `);if(!c)return{content:r+`
234
234
  `+s.join(`
235
- `),strategy:"exact"};let d=Xd(r,c,t);if(d.length===0)return null;let l=[];for(let f of e.lines)(f.prefix===" "||f.prefix==="+")&&l.push(f.content);let u=l.join(`
236
- `),p=d[0];return{content:r.slice(0,p.start)+u+r.slice(p.end),strategy:p.strategy}}function Wi(r){return{name:tT,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:nT,execute:async(e,t)=>{let n=t.replaceAll??!1,o={filesModified:[],filesAdded:[],filesDeleted:[],strategies:{},errors:[]},s=t.input.includes("*** Begin Patch"),i=t.input.includes("<<<< SEARCH");if(s){let d=Kd(t.input);if(d.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 l of d){let u=r.resolvePath(l.path);try{switch(l.type){case"add":{let p=l.hunks.flatMap(g=>g.lines.filter(f=>f.prefix==="+").map(f=>f.content)).join(`
237
- `);await r.writeFile(u,p),o.filesAdded.push(l.path),o.strategies[l.path]="exact";break}case"delete":{await r.deleteFile(u),o.filesDeleted.push(l.path);break}case"move":{let p=await r.readFile(u);if(l.newPath){let g=r.resolvePath(l.newPath),f=p;for(let m of l.hunks){let y=Jd(f,m,n);y&&(f=y.content,o.strategies[l.path]=y.strategy)}await r.writeFile(g,f),await r.deleteFile(u),o.filesModified.push(`${l.path} \u2192 ${l.newPath}`)}break}case"update":{let p=await r.readFile(u),g="exact",f=!0;for(let m of l.hunks){let y=Jd(p,m,n);if(y)p=y.content,g=y.strategy;else{f=!1;let k=m.lines.filter(b=>b.prefix===" "||b.prefix==="-").map(b=>b.content).slice(0,5).join(`
235
+ `),strategy:"exact"};let d=ou(r,c,t);if(d.length===0)return null;let l=[];for(let f of e.lines)(f.prefix===" "||f.prefix==="+")&&l.push(f.content);let u=l.join(`
236
+ `),p=d[0];return{content:r.slice(0,p.start)+u+r.slice(p.end),strategy:p.strategy}}function qi(r){return{name:mT,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:gT,execute:async(e,t)=>{let n=t.replaceAll??!1,o={filesModified:[],filesAdded:[],filesDeleted:[],strategies:{},errors:[]},s=t.input.includes("*** Begin Patch"),i=t.input.includes("<<<< SEARCH");if(s){let d=tu(t.input);if(d.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 l of d){let u=r.resolvePath(l.path);try{switch(l.type){case"add":{let p=l.hunks.flatMap(m=>m.lines.filter(f=>f.prefix==="+").map(f=>f.content)).join(`
237
+ `);await r.writeFile(u,p),o.filesAdded.push(l.path),o.strategies[l.path]="exact";break}case"delete":{await r.deleteFile(u),o.filesDeleted.push(l.path);break}case"move":{let p=await r.readFile(u);if(l.newPath){let m=r.resolvePath(l.newPath),f=p;for(let g of l.hunks){let y=nu(f,g,n);y&&(f=y.content,o.strategies[l.path]=y.strategy)}await r.writeFile(m,f),await r.deleteFile(u),o.filesModified.push(`${l.path} \u2192 ${l.newPath}`)}break}case"update":{let p=await r.readFile(u),m="exact",f=!0;for(let g of l.hunks){let y=nu(p,g,n);if(y)p=y.content,m=y.strategy;else{f=!1;let b=g.lines.filter(k=>k.prefix===" "||k.prefix==="-").map(k=>k.content).slice(0,5).join(`
238
238
  `);o.errors.push(`${l.path}: hunk not matched. Search begins with:
239
- ${k}`)}}(f||p!==await r.readFile(u))&&(await r.writeFile(u,p),o.filesModified.push(l.path),o.strategies[l.path]=g);break}}}catch(p){o.errors.push(`${l.type} ${l.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let d=rT(t.input);if(d.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let l of d){let u=r.resolvePath(l.path);try{let p=await r.readFile(u),g=Xd(p,l.search,n);if(g.length===0){o.errors.push(`${l.path}: search text not matched (tried all 9 strategies)`);continue}let f=[...g].sort((m,y)=>y.start-m.start);for(let m of f)p=p.slice(0,m.start)+l.replace+p.slice(m.end);await r.writeFile(u,p),o.filesModified.push(l.path),o.strategies[l.path]=g[0].strategy}catch(p){o.errors.push(`${l.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return Kd(`*** Begin Patch
239
+ ${b}`)}}(f||p!==await r.readFile(u))&&(await r.writeFile(u,p),o.filesModified.push(l.path),o.strategies[l.path]=m);break}}}catch(p){o.errors.push(`${l.type} ${l.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let d=hT(t.input);if(d.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let l of d){let u=r.resolvePath(l.path);try{let p=await r.readFile(u),m=ou(p,l.search,n);if(m.length===0){o.errors.push(`${l.path}: search text not matched (tried all 9 strategies)`);continue}let f=[...m].sort((g,y)=>y.start-g.start);for(let g of f)p=p.slice(0,g.start)+l.replace+p.slice(g.end);await r.writeFile(u,p),o.filesModified.push(l.path),o.strategies[l.path]=m[0].strategy}catch(p){o.errors.push(`${l.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return tu(`*** Begin Patch
240
240
  `+t.input+`
241
- *** End Patch`).length>0?Wi(r).execute(e,{input:`*** Begin Patch
241
+ *** End Patch`).length>0?qi(r).execute(e,{input:`*** Begin Patch
242
242
  `+t.input+`
243
243
  *** 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(o.filesAdded.length&&a.push(`Added: ${o.filesAdded.join(", ")}`),o.filesModified.length){let d=o.filesModified.map(l=>`${l} (${o.strategies[l]||"exact"})`).join(", ");a.push(`Modified: ${d}`)}o.filesDeleted.length&&a.push(`Deleted: ${o.filesDeleted.join(", ")}`),o.errors.length&&a.push(`
244
244
  Errors:
245
245
  ${o.errors.join(`
246
246
  `)}`);let c=o.errors.length===0;return{content:[{type:"text",text:a.join(`
247
- `)||"No changes applied."}],details:{type:"patch",...o,success:c}}}}}var sT="web_fetch",iT={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"]},aT=5e4;function Yd(r){return{name:sT,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:iT,execute:async(e,t)=>{let n=await r.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??aT,query:t.query,extract:t.extract});if(t.summarize&&r.summarizeContent&&n.content.length>1e3){let s=await r.summarizeContent(n.content,t.query);return{content:[{type:"text",text:n.title?`# ${n.title}
247
+ `)||"No changes applied."}],details:{type:"patch",...o,success:c}}}}}var yT="web_fetch",bT={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"]},kT=5e4;function ru(r){return{name:yT,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:bT,execute:async(e,t)=>{let n=await r.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??kT,query:t.query,extract:t.extract});if(t.summarize&&r.summarizeContent&&n.content.length>1e3){let s=await r.summarizeContent(n.content,t.query);return{content:[{type:"text",text:n.title?`# ${n.title}
248
248
 
249
249
  ${s}`:s}],details:{type:"web_fetch",url:t.url,summarized:!0,originalLength:n.content.length,summaryLength:s.length}}}let o=[];if(n.title&&o.push(`# ${n.title}
250
250
  `),o.push(n.content),n.relevantExcerpts?.length){o.push(`
251
251
  ---
252
252
  ## Relevant Excerpts
253
253
  `);for(let s of n.relevantExcerpts)o.push(`- ${s}`)}return{content:[{type:"text",text:o.join(`
254
- `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!n.extraction,extraction:n.extraction}}}}}var lT="web_search",cT={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"]},dT=10;function Qd(r){return{name:lT,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:cT,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 r.search(t.query.trim(),{allowedDomains:t.allowedDomains,blockedDomains:t.blockedDomains,maxResults:dT});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 o=[`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];o.push(`${s+1}. [${i.title}](${i.url})`),o.push(` ${i.snippet}`),o.push("")}return{content:[{type:"text",text:o.join(`
255
- `)}],details:{type:"web_search",query:n.query,resultCount:n.results.length}}}}}var uT="instructions",pT={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 Zd(r){return{name:uT,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:pT,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=r.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 o=n.map(s=>`- ${s.filename} (${s.size} bytes, updated ${s.updatedAt})`).join(`
254
+ `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!n.extraction,extraction:n.extraction}}}}}var TT="web_search",wT={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"]},vT=10;function su(r){return{name:TT,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:wT,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 r.search(t.query.trim(),{allowedDomains:t.allowedDomains,blockedDomains:t.blockedDomains,maxResults:vT});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 o=[`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];o.push(`${s+1}. [${i.title}](${i.url})`),o.push(` ${i.snippet}`),o.push("")}return{content:[{type:"text",text:o.join(`
255
+ `)}],details:{type:"web_search",query:n.query,resultCount:n.results.length}}}}}var ST="instructions",RT={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 iu(r){return{name:ST,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:RT,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=r.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 o=n.map(s=>`- ${s.filename} (${s.size} bytes, updated ${s.updatedAt})`).join(`
256
256
  `);return{content:[{type:"text",text:`Found ${n.length} instruction file(s):
257
- ${o}`}],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=r.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=r.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=r.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 o=n.content.split(t.old_text).length-1;if(o===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(o>1)return{content:[{type:"text",text:`old_text matches ${o} 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:o}};let s=n.content.replace(t.old_text,t.new_text),i=r.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"}}:r.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 mT="worktree",gT={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
257
+ ${o}`}],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=r.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=r.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=r.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 o=n.content.split(t.old_text).length-1;if(o===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(o>1)return{content:[{type:"text",text:`old_text matches ${o} 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:o}};let s=n.content.replace(t.old_text,t.new_text),i=r.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"}}:r.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 _T="worktree",xT={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
258
258
  exit: Leave worktree (keep or remove it).
259
- 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"]},fT=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function eu(r){return{name:mT,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:gT,execute:async(e,t)=>{switch(t.action){case"enter":{if(r.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&&!fT.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 r.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 o=n.worktree;return{content:[{type:"text",text:[`Entered worktree: ${o.name}`,` Branch: ${o.branch}`,` Path: ${o.path}`,"","Working in isolated branch. Changes here do not affect the main branch.","Use action='exit' when done (keep or remove)."].join(`
259
+ 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"]},AT=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function au(r){return{name:_T,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:xT,execute:async(e,t)=>{switch(t.action){case"enter":{if(r.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&&!AT.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 r.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 o=n.worktree;return{content:[{type:"text",text:[`Entered worktree: ${o.name}`,` Branch: ${o.branch}`,` Path: ${o.path}`,"","Working in isolated branch. Changes here do not affect the main branch.","Use action='exit' when done (keep or remove)."].join(`
260
260
  `)}],details:{type:"worktree",action:"enter",name:o.name,branch:o.branch,path:o.path}}}case"exit":{if(!r.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=r.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 o=await r.exitWorktree(n,t.discardChanges);return o.success?{content:[{type:"text",text:`Exited worktree. ${n==="keep"?"Worktree kept for later use.":"Worktree removed."}
261
261
  Restored to: ${o.previousCwd||"main workspace"}`}],details:{type:"worktree",action:"exit",exitAction:n,previousCwd:o.previousCwd}}:{content:[{type:"text",text:`Error: ${o.error||"failed to exit worktree"}`}],details:{type:"worktree",error:o.error}}}case"list":{let n=await r.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 o=[`Worktrees (${n.worktrees.length}):`,""];for(let s of n.worktrees){let i=s.isCurrent?" \u2190 current":"",a=s.hasChanges?" (has changes)":"";o.push(` ${s.name} [${s.branch}]${i}${a}`),o.push(` path: ${s.path}`)}return{content:[{type:"text",text:o.join(`
262
- `)}],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 hT}from"node:child_process";import{promisify as yT}from"node:util";import{join as Mt,resolve as tu,basename as zi}from"node:path";import{mkdir as au,rm as lu,symlink as bT,readdir as HP,stat as kT}from"node:fs/promises";var En=yT(hT),TT=/^[a-zA-Z0-9._-]+$/,nu=64;function cu(r){if(r.length>nu)throw new Error(`Invalid worktree name: must be ${nu} characters or fewer (got ${r.length})`);for(let e of r.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${r}": must not contain "." or ".." path segments`);if(!TT.test(e))throw new Error(`Invalid worktree name "${r}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function Vi(r){return r.replaceAll("/","+")}function du(r){return`worktree-${Vi(r)}`}var Ee=null;async function he(r,e){try{let{stdout:t,stderr:n}=await En("git",r,{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 Mn(r){let{stdout:e,code:t}=await he(["rev-parse","--show-toplevel"],r);return t===0?e.trim():null}async function ou(r){let{stdout:e,code:t}=await he(["status","--porcelain"],r);return t!==0?-1:e.trim().split(`
263
- `).filter(Boolean).length}async function ru(r,e){let{stdout:t,code:n}=await he(["rev-list",`origin/${e}..${e}`,"--count"],r);return n!==0?0:parseInt(t.trim(),10)||0}async function uu(r,e,t,n){for(let o of t){if(o.includes("..")||o.startsWith("/")||o.startsWith("\\")){n?.warn(`[worktree] skipping symlink for "${o}": path traversal detected`);continue}let s=Mt(r,o),i=Mt(e,o);try{await bT(s,i,"dir"),n?.info(`[worktree] symlinked ${o} from main repo to worktree`)}catch(a){let c=a.code;c!=="ENOENT"&&c!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${o} (${c??"unknown"}): ${a}`)}}}async function wT(r,e,t){let{code:n,stderr:o}=await he(["sparse-checkout","set","--cone","--",...t],r);if(n!==0)throw await he(["worktree","remove","--force",r],e),new Error(`Failed to configure sparse-checkout: ${o}`);let{code:s,stderr:i}=await he(["checkout","HEAD"],r);if(s!==0)throw await he(["worktree","remove","--force",r],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function vT(){try{return await En("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function ST(r,e){return`${zi(r)}_${e}`.replace(/[/.]/g,"_")}async function xT(r,e){if(!await vT())return null;try{return await En("tmux",["new-session","-d","-s",e,"-c",r],{timeout:1e4}),e}catch{return null}}async function su(r){try{return await En("tmux",["kill-session","-t",r],{timeout:5e3}),!0}catch{return!1}}async function iu(r,e,t,n){let o=Zl(e),s=Mt(o,r);try{if(!(await kT(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await En(s,[],{cwd:e,env:{...process.env,...t},timeout:3e4});return n?.info(`[worktree] hook ${r} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return n?.warn(`[worktree] hook ${r} failed: ${i}`),null}}async function pu(r,e,t){cu(e);let n=Vi(e),o=du(e),s=Mt(r,".worktrees"),i=Mt(s,n);await au(s,{recursive:!0});let{code:a,stderr:c}=await he(["worktree","add","-B",o,i,"HEAD"],r);return a!==0?(t?.warn(`[worktree] agent worktree creation failed: ${c}`),null):(await uu(r,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:o})}async function mu(r,e,t,n){let{code:o}=await he(["worktree","remove","--force",e],r);return o!==0&&(await lu(e,{recursive:!0,force:!0}).catch(()=>{}),await he(["worktree","prune"],r)),await he(["branch","-D",t],r),n?.info(`[worktree] agent worktree removed: ${e}`),!0}function gu(r){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:n}=r;return{async enterWorktree(o){try{let s=Date.now(),i=await Mn();if(!i)return{success:!1,error:"Not in a git repository"};let a=await iu("worktree-create",i,{WORKTREE_NAME:o??""},e);if(a){let D=process.cwd();return process.chdir(a),Ee={originalCwd:D,worktreePath:a,worktreeName:o??zi(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:Ee.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let c=o??`agent-${Date.now().toString(36)}`;cu(c);let d=Vi(c),l=du(c),u=Mt(i,".worktrees"),p=Mt(u,d);await au(u,{recursive:!0});let{stdout:g}=await he(["worktree","list","--porcelain"],i),f=g.split(`
264
- `).find(D=>D.startsWith("worktree ")&&D.includes(d));if(f){let D=f.replace("worktree ","").trim(),B=process.cwd();return process.chdir(D),Ee={originalCwd:B,worktreePath:D,worktreeName:c,worktreeBranch:l},e.info(`[worktree] resumed existing worktree: ${c} at ${D}`),{success:!0,worktree:{name:c,path:D,branch:l,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let m=n&&n.length>0,y=["worktree","add"];m&&y.push("--no-checkout"),y.push("-B",l,p,"HEAD");let{code:k,stderr:b}=await he(y,i);if(k!==0)return{success:!1,error:`git worktree add failed: ${b.trim()}`};let x=!1;m&&n&&(await wT(p,i,n),x=!0),await uu(i,p,t,e);let S=process.cwd();process.chdir(p);let A=ST(i,l),$=await xT(p,A);return Ee={originalCwd:S,worktreePath:p,worktreeName:c,worktreeBranch:l,tmuxSessionName:$??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:x},e.info(`[worktree] entered: ${c} at ${p}`),{success:!0,worktree:{name:c,path:p,branch:l,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(o,s){if(!Ee)return{success:!1,error:"Not in a worktree"};try{let i=Ee,a=await Mn(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(o==="remove"){let c=await ou(i.worktreePath),d=await ru(i.worktreePath,i.worktreeBranch);if((c>0||d>0)&&!s)return{success:!1,error:`Worktree has ${c} uncommitted change(s) and ${d} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),Ee=null,i.tmuxSessionName&&await su(i.tmuxSessionName),await iu("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let l=["worktree","remove"];s&&l.push("--force"),l.push(i.worktreePath);let{code:u,stderr:p}=await he(l,a);u!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await lu(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await he(["worktree","prune"],a)),await he(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await su(i.tmuxSessionName),Ee=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:o,code:s}=await he(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),c=o.split(`
262
+ `)}],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 CT}from"node:child_process";import{promisify as PT}from"node:util";import{join as Ot,resolve as cu,basename as Xi}from"node:path";import{mkdir as gu,rm as fu,symlink as IT,readdir as tM,stat as MT}from"node:fs/promises";var Ln=PT(CT),ET=/^[a-zA-Z0-9._-]+$/,lu=64;function hu(r){if(r.length>lu)throw new Error(`Invalid worktree name: must be ${lu} characters or fewer (got ${r.length})`);for(let e of r.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${r}": must not contain "." or ".." path segments`);if(!ET.test(e))throw new Error(`Invalid worktree name "${r}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function Yi(r){return r.replaceAll("/","+")}function yu(r){return`worktree-${Yi(r)}`}var De=null;async function be(r,e){try{let{stdout:t,stderr:n}=await Ln("git",r,{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 Dn(r){let{stdout:e,code:t}=await be(["rev-parse","--show-toplevel"],r);return t===0?e.trim():null}async function du(r){let{stdout:e,code:t}=await be(["status","--porcelain"],r);return t!==0?-1:e.trim().split(`
263
+ `).filter(Boolean).length}async function uu(r,e){let{stdout:t,code:n}=await be(["rev-list",`origin/${e}..${e}`,"--count"],r);return n!==0?0:parseInt(t.trim(),10)||0}async function bu(r,e,t,n){for(let o of t){if(o.includes("..")||o.startsWith("/")||o.startsWith("\\")){n?.warn(`[worktree] skipping symlink for "${o}": path traversal detected`);continue}let s=Ot(r,o),i=Ot(e,o);try{await IT(s,i,"dir"),n?.info(`[worktree] symlinked ${o} from main repo to worktree`)}catch(a){let c=a.code;c!=="ENOENT"&&c!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${o} (${c??"unknown"}): ${a}`)}}}async function OT(r,e,t){let{code:n,stderr:o}=await be(["sparse-checkout","set","--cone","--",...t],r);if(n!==0)throw await be(["worktree","remove","--force",r],e),new Error(`Failed to configure sparse-checkout: ${o}`);let{code:s,stderr:i}=await be(["checkout","HEAD"],r);if(s!==0)throw await be(["worktree","remove","--force",r],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function DT(){try{return await Ln("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function LT(r,e){return`${Xi(r)}_${e}`.replace(/[/.]/g,"_")}async function NT(r,e){if(!await DT())return null;try{return await Ln("tmux",["new-session","-d","-s",e,"-c",r],{timeout:1e4}),e}catch{return null}}async function pu(r){try{return await Ln("tmux",["kill-session","-t",r],{timeout:5e3}),!0}catch{return!1}}async function mu(r,e,t,n){let o=il(e),s=Ot(o,r);try{if(!(await MT(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await Ln(s,[],{cwd:e,env:{...process.env,...t},timeout:3e4});return n?.info(`[worktree] hook ${r} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return n?.warn(`[worktree] hook ${r} failed: ${i}`),null}}async function ku(r,e,t){hu(e);let n=Yi(e),o=yu(e),s=Ot(r,".worktrees"),i=Ot(s,n);await gu(s,{recursive:!0});let{code:a,stderr:c}=await be(["worktree","add","-B",o,i,"HEAD"],r);return a!==0?(t?.warn(`[worktree] agent worktree creation failed: ${c}`),null):(await bu(r,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:o})}async function Tu(r,e,t,n){let{code:o}=await be(["worktree","remove","--force",e],r);return o!==0&&(await fu(e,{recursive:!0,force:!0}).catch(()=>{}),await be(["worktree","prune"],r)),await be(["branch","-D",t],r),n?.info(`[worktree] agent worktree removed: ${e}`),!0}function wu(r){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:n}=r;return{async enterWorktree(o){try{let s=Date.now(),i=await Dn();if(!i)return{success:!1,error:"Not in a git repository"};let a=await mu("worktree-create",i,{WORKTREE_NAME:o??""},e);if(a){let L=process.cwd();return process.chdir(a),De={originalCwd:L,worktreePath:a,worktreeName:o??Xi(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:De.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let c=o??`agent-${Date.now().toString(36)}`;hu(c);let d=Yi(c),l=yu(c),u=Ot(i,".worktrees"),p=Ot(u,d);await gu(u,{recursive:!0});let{stdout:m}=await be(["worktree","list","--porcelain"],i),f=m.split(`
264
+ `).find(L=>L.startsWith("worktree ")&&L.includes(d));if(f){let L=f.replace("worktree ","").trim(),B=process.cwd();return process.chdir(L),De={originalCwd:B,worktreePath:L,worktreeName:c,worktreeBranch:l},e.info(`[worktree] resumed existing worktree: ${c} at ${L}`),{success:!0,worktree:{name:c,path:L,branch:l,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let g=n&&n.length>0,y=["worktree","add"];g&&y.push("--no-checkout"),y.push("-B",l,p,"HEAD");let{code:b,stderr:k}=await be(y,i);if(b!==0)return{success:!1,error:`git worktree add failed: ${k.trim()}`};let S=!1;g&&n&&(await OT(p,i,n),S=!0),await bu(i,p,t,e);let R=process.cwd();process.chdir(p);let P=LT(i,l),O=await NT(p,P);return De={originalCwd:R,worktreePath:p,worktreeName:c,worktreeBranch:l,tmuxSessionName:O??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:S},e.info(`[worktree] entered: ${c} at ${p}`),{success:!0,worktree:{name:c,path:p,branch:l,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(o,s){if(!De)return{success:!1,error:"Not in a worktree"};try{let i=De,a=await Dn(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(o==="remove"){let c=await du(i.worktreePath),d=await uu(i.worktreePath,i.worktreeBranch);if((c>0||d>0)&&!s)return{success:!1,error:`Worktree has ${c} uncommitted change(s) and ${d} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),De=null,i.tmuxSessionName&&await pu(i.tmuxSessionName),await mu("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let l=["worktree","remove"];s&&l.push("--force"),l.push(i.worktreePath);let{code:u,stderr:p}=await be(l,a);u!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await fu(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await be(["worktree","prune"],a)),await be(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await pu(i.tmuxSessionName),De=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:o,code:s}=await be(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),c=o.split(`
265
265
 
266
266
  `).filter(Boolean);for(let d of c){let l=d.split(`
267
- `),u="",p="";for(let y of l)y.startsWith("worktree ")&&(u=y.slice(9).trim()),y.startsWith("branch ")&&(p=y.slice(7).trim().replace("refs/heads/",""));if(!u)continue;let g=tu(u)===tu(a),f=await ou(u),m=await ru(u,p);i.push({name:p.startsWith("worktree-")?p.slice(9):zi(u),path:u,branch:p,isCurrent:g,hasChanges:f>0,unpushedCommits:m})}return{success:!0,worktrees:i}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}},isInWorktree(){return Ee!==null},currentWorktree(){return Ee?{name:Ee.worktreeName,path:Ee.worktreePath,branch:Ee.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as RT,writeFile as _T}from"node:fs/promises";import*as fu from"node:path";var CT={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 hu(r){let e=r.split(`
267
+ `),u="",p="";for(let y of l)y.startsWith("worktree ")&&(u=y.slice(9).trim()),y.startsWith("branch ")&&(p=y.slice(7).trim().replace("refs/heads/",""));if(!u)continue;let m=cu(u)===cu(a),f=await du(u),g=await uu(u,p);i.push({name:p.startsWith("worktree-")?p.slice(9):Xi(u),path:u,branch:p,isCurrent:m,hasChanges:f>0,unpushedCommits:g})}return{success:!0,worktrees:i}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}},isInWorktree(){return De!==null},currentWorktree(){return De?{name:De.worktreeName,path:De.worktreePath,branch:De.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as UT,writeFile as $T}from"node:fs/promises";import*as vu from"node:path";var jT={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 Su(r){let e=r.split(`
268
268
  `);return e.map((t,n)=>n<e.length-1?t+`
269
- `:t)}function yu(r){return r.join("")}function AT(r,e){let t=yu(r.source).trim(),n=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${r.cell_type}]: ${n}`}function IT(r,e){let t={cell_type:r,source:hu(e),metadata:{}};return r==="code"&&(t.execution_count=null,t.outputs=[]),t}function bu(){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:CT,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"jupyter notebook ipynb cell edit insert delete",execute:async(r,e)=>{let{notebook_path:t,cell_number:n,edit_mode:o="replace"}=e,s=fu.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 RT(t,"utf-8")}catch(g){return{content:[{type:"text",text:`Error reading notebook: ${g.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let c=a.cells.length,d=n-1;if(o==="insert"){if(n<0||n>c)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. For insert, use 0-${c}.`}],details:{error:"out_of_range"}}}else if(d<0||d>=c)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. Notebook has ${c} cell(s).`}],details:{error:"out_of_range"}};let l;switch(o){case"replace":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'replace' mode."}],details:{error:"missing_source"}};let g=a.cells[d],f=yu(g.source);g.source=hu(e.new_source),g.cell_type==="code"&&(g.execution_count=null,g.outputs=[]),l=`Replaced cell ${n} [${g.cell_type}].
269
+ `:t)}function Ru(r){return r.join("")}function FT(r,e){let t=Ru(r.source).trim(),n=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${r.cell_type}]: ${n}`}function BT(r,e){let t={cell_type:r,source:Su(e),metadata:{}};return r==="code"&&(t.execution_count=null,t.outputs=[]),t}function _u(){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:jT,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"jupyter notebook ipynb cell edit insert delete",execute:async(r,e)=>{let{notebook_path:t,cell_number:n,edit_mode:o="replace"}=e,s=vu.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 UT(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 c=a.cells.length,d=n-1;if(o==="insert"){if(n<0||n>c)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. For insert, use 0-${c}.`}],details:{error:"out_of_range"}}}else if(d<0||d>=c)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. Notebook has ${c} cell(s).`}],details:{error:"out_of_range"}};let l;switch(o){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[d],f=Ru(m.source);m.source=Su(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),l=`Replaced cell ${n} [${m.cell_type}].
270
270
  Old: ${f.slice(0,120)}${f.length>120?"...":""}
271
- New: ${e.new_source.slice(0,120)}${e.new_source.length>120?"...":""}`;break}case"insert":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'insert' mode."}],details:{error:"missing_source"}};let g=e.cell_type??"code",f=IT(g,e.new_source);a.cells.splice(n,0,f),l=`Inserted new ${g} cell after position ${n}. Total cells: ${a.cells.length}.`;break}case"delete":{let g=a.cells.splice(d,1)[0];l=`Deleted cell ${n} [${g.cell_type}]. Remaining: ${a.cells.length} cells.`;break}default:return{content:[{type:"text",text:`Error: unknown edit_mode "${o}". Use replace, insert, or delete.`}],details:{error:"unknown_mode"}}}try{let g=JSON.stringify(a,null,1)+`
272
- `;await _T(t,g,"utf-8")}catch(g){return{content:[{type:"text",text:`Error writing notebook: ${g.message}`}],details:{error:"write_failed"}}}let u=a.cells.slice(0,10).map((g,f)=>AT(g,f)).join(`
271
+ 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",f=BT(m,e.new_source);a.cells.splice(n,0,f),l=`Inserted new ${m} cell after position ${n}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(d,1)[0];l=`Deleted cell ${n} [${m.cell_type}]. Remaining: ${a.cells.length} cells.`;break}default:return{content:[{type:"text",text:`Error: unknown edit_mode "${o}". Use replace, insert, or delete.`}],details:{error:"unknown_mode"}}}try{let m=JSON.stringify(a,null,1)+`
272
+ `;await $T(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let u=a.cells.slice(0,10).map((m,f)=>FT(m,f)).join(`
273
273
  `),p=a.cells.length>10?`
274
274
  ... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${l}
275
275
 
276
276
  Current cells:
277
- ${u}${p}`}],details:{type:"notebook_edit",edit_mode:o,cell_number:n,total_cells:a.cells.length}}}}}import{readFile as PT,readdir as MT}from"node:fs/promises";import*as Tu from"node:path";import{existsSync as ET}from"node:fs";var OT={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
277
+ ${u}${p}`}],details:{type:"notebook_edit",edit_mode:o,cell_number:n,total_cells:a.cells.length}}}}}import{readFile as WT,readdir as GT}from"node:fs/promises";import*as Au from"node:path";import{existsSync as HT}from"node:fs";var VT={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
278
278
  run: Execute a workflow by name.
279
- 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 qi(r){let e=new Map,t=ql(r);await ku(t,e);let n=zl();return await ku(n,e),e}async function ku(r,e){if(ET(r))try{let t=await MT(r,{withFileTypes:!0});for(let n of t)if(n.isFile()&&n.name.endsWith(".json")){let o=n.name.replace(/\.json$/,"");e.has(o)||e.set(o,Tu.join(r,n.name))}}catch{}}async function Ki(r){let e=await PT(r,"utf-8");return JSON.parse(e)}function DT(r){let e=new Map(r.map(s=>[s.id,s])),t=new Set,n=[];function o(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 c of a.dependsOn??[])o(c,i);i.delete(s),t.add(s),n.push(a)}for(let s of r)o(s.id,new Set);return n}function LT(r,e,t){let n={};for(let[o,s]of Object.entries(r))if(typeof s=="string"){let i=s;i=i.replace(/\$\{var\.(\w+)\}/g,(a,c)=>e[c]??`\${var.${c}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,c)=>t.get(c)?.output??""),n[o]=i}else n[o]=s;return n}function wu(r){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:OT,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"workflow pipeline automation steps DAG",execute:async(e,t,n)=>{let o=r.getCwd();switch(t.action){case"list":{let s=await qi(o);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,c]of s)try{let d=await Ki(c);i.push(` - ${a}: ${d.description??"(no description)"} (${d.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
280
- `)}],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 qi(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Ki(i),c=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let d of a.steps){let l=d.dependsOn?.length?` (after: ${d.dependsOn.join(", ")})`:"";c.push(` ${d.id}: ${d.label??d.tool}${l}`),c.push(` tool: ${d.tool}`),c.push(` args: ${JSON.stringify(d.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){c.push("","Variables (defaults):");for(let[d,l]of Object.entries(a.variables))c.push(` ${d} = ${l}`)}return{content:[{type:"text",text:c.filter(Boolean).join(`
281
- `)}],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 qi(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Ki(i),c={...a.variables,...t.variables},d;try{d=DT(a.steps)}catch(g){return{content:[{type:"text",text:`Error: ${g.message}`}],details:{error:"dag_error"}}}let l=new Map,u=[`Running workflow: ${a.name}`,""],p=!0;for(let g of d){if(n?.aborted){u.push(`\u26A1 Aborted at step: ${g.id}`),p=!1;break}let f=(g.dependsOn??[]).some(k=>!l.get(k)?.success),m=g.condition??"on_success";if(m==="on_success"&&f){u.push(`\u23ED Skipped ${g.id} (dependency failed)`),l.set(g.id,{stepId:g.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(m==="on_failure"&&!f){u.push(`\u23ED Skipped ${g.id} (no failure to handle)`),l.set(g.id,{stepId:g.id,success:!0,output:""});continue}u.push(`\u25B6 ${g.id}: ${g.label??g.tool}`);let y=LT(g.args,c,l);try{let k=await r.invokeTool(g.tool,y,n),b=!k.error;if(l.set(g.id,{stepId:g.id,success:b,output:k.result,error:k.error}),b){let x=k.result.length>200?k.result.slice(0,200)+"...":k.result;u.push(` \u2705 ${x}`)}else u.push(` \u274C ${k.error}`),p=!1}catch(k){let b=k.message;l.set(g.id,{stepId:g.id,success:!1,output:"",error:b}),u.push(` \u274C ${b}`),p=!1}}return u.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:u.join(`
282
- `)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:l.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 $T="sleep",UT={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 vu(r){return{name:$T,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(`
283
- `),parameters:UT,execute:async(e,t,n)=>{let o=Math.max(1,Math.min(3600,Math.round(t.duration))),s=o*1e3,i=new AbortController,a=()=>i.abort();n?.addEventListener("abort",a,{once:!0}),n?.aborted&&i.abort();try{let c=await r.sleep(s,i.signal),d=[];return c.interrupted?(d.push(`Sleep interrupted after ${c.sleptSeconds}s.`),c.interruptReason&&d.push(`Reason: ${c.interruptReason}`),d.push("Check for new messages or tasks.")):d.push(`Slept for ${c.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:d.join(`
284
- `)}],details:{...c,requestedSeconds:o}}}finally{n?.removeEventListener("abort",a)}}}}var NT="tool_search",jT={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"]},FT=5;function xu(r){return{name:NT,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:jT,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(),o=t.maxResults??FT;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(l=>l.trim()).filter(Boolean),a=[],c=[];if(r.activateTool)for(let l of i)await r.activateTool(l)?a.push(l):c.push(l);else{let l=await r.searchTools(n,{maxResults:o});return Su(l)}let d=[];return a.length>0&&d.push(`Activated: ${a.join(", ")}. These tools are now available.`),c.length>0&&d.push(`Not found: ${c.join(", ")}.`),{content:[{type:"text",text:d.join(`
285
- `)}],details:{type:"tool_search",activated:a,notFound:c,mode:"select"}}}let s=await r.searchTools(n,{maxResults:o});return Su(s)}}}function Su(r){if(r.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${r.query}". Total deferred tools available: ${r.totalDeferred}.`}],details:{type:"tool_search",query:r.query,matchCount:0,totalDeferred:r.totalDeferred}};let e=[`Found ${r.matches.length} tool(s) matching "${r.query}" (${r.totalDeferred} total deferred):`,""];for(let t of r.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(`
286
- `)}],details:{type:"tool_search",query:r.query,matchCount:r.matches.length,totalDeferred:r.totalDeferred,matches:r.matches.map(t=>t.name)}}}var Ji="image_generate",BT={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. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."},quality:{type:"string",description:"Image quality level: 'auto', 'high', 'low', 'hd'. Provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation. Same seed + prompt = same result."}},required:["prompt"]};function Ru(r){return{name:Ji,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. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file. Local file paths and data: URIs are NOT supported by the generation API.",parameters:BT,execute:async(e,t)=>{let n=await r.generateImage({prompt:t.prompt,purpose:t.purpose,style:t.style,size:t.size,imageUrl:t.image_url,n:t.n,quality:t.quality,seed:t.seed}),o=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${o} image${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var GT={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)."},voice:{type:"string",description:"Voice name for TTS. Available voices depend on the provider. Common options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer."},speed:{type:"number",description:"Speech speed multiplier (0.25-4.0). Default is 1.0."}},required:["text"]};function _u(r){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:GT,execute:async(e,t)=>{let n=await r.textToSpeech({text:t.text,channel:t.channel,voice:t.voice,speed:t.speed});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 Xi="video_generate",HT={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 URL for image-to-video generation (first frame, style reference, or character reference). MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported. If the user provides a local file, use a file hosting service or the image_generate tool first."},reference_videos:{type:"array",items:{type:"string"},maxItems:3,description:"Reference video URLs for video-to-video or multimodal generation (Seedance 2.0). Max 3 videos, total duration \u226415s. Use for: (a) video-to-video: provide source video to restyle/transform with prompt guidance; (b) multimodal reference: combine with image_url and/or reference_audios for style/motion/audio-guided generation. Each URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_audios:{type:"array",items:{type:"string"},maxItems:3,description:"Reference audio URLs for audio-guided video generation (Seedance 2.0). Max 3 audio clips, total duration \u226415s. CANNOT be used alone \u2014 must be combined with at least one image_url or reference_video. Each URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},generate_audio:{type:"boolean",description:"Generate synchronized audio track for the video (Seedance 2.0/1.5 pro). When true, the output video includes AI-generated sound effects matching the visual content."},aspect_ratio:{type:"string",description:"Video aspect ratio: '9:16' (vertical), '16:9' (horizontal), '1:1' (square). Default: '16:9'."},duration:{type:"number",minimum:3,maximum:15,description:"Video duration in seconds. Seedance 2.0: 4-15s per shot. Seedance 1.0/1.5: 3-10s. For longer videos (>15s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation."},resolution:{type:"string",description:"Output resolution: '480p', '720p', '1080p'. Default: '720p'."},fps:{type:"number",description:"Frame rate: 24 or 30 fps. Default: provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation."},camera_fixed:{type:"boolean",description:"Lock camera position (Seedance 1.0/1.5 only, not supported for img2video)."},return_last_frame:{type:"boolean",description:"Return last frame URL for chaining continuous video segments."},draft:{type:"boolean",description:"Draft mode: low-cost preview (Seedance 1.5 pro only)."},service_tier:{type:"string",enum:["default","flex"],description:"'default' (online, fast) or 'flex' (offline, ~50% cost). Not all models support flex."},callback_url:{type:"string",description:"Webhook URL for async task completion notification."},safety_identifier:{type:"string",description:"End-user safety identifier for content moderation tracking."},execution_expires_after:{type:"number",description:"Task expiration in seconds (for offline/flex scheduling)."},video_tools:{type:"array",items:{type:"string"},description:"Video-level builtin tools, e.g. ['web_search'] (Seedance 2.0 online search)."}},required:["prompt"]};function Cu(r){return{name:Xi,label:"Video Generate",description:"Generate a short video clip from a text prompt, reference image, source video, or multimodal references. 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. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. 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:HT,execute:async(e,t)=>{let n=await r.generateVideo({prompt:t.prompt,purpose:t.purpose,style:t.style,imageUrl:t.image_url,referenceVideos:t.reference_videos,referenceAudios:t.reference_audios,generateAudio:t.generate_audio,aspectRatio:t.aspect_ratio,duration:t.duration,resolution:t.resolution,fps:t.fps,seed:t.seed,cameraFixed:t.camera_fixed,returnLastFrame:t.return_last_frame,draft:t.draft,serviceTier:t.service_tier,callbackUrl:t.callback_url,safetyIdentifier:t.safety_identifier,executionExpiresAfterSeconds:t.execution_expires_after,videoTools:t.video_tools}),o=n.mediaUrls.length,s=[`Generated ${o} video${o>1?"s":""}`];return n.model&&s.push(`model: ${n.model}`),n.lastFrameUrl&&s.push(`last_frame: ${n.lastFrameUrl}`),n.taskId&&s.push(`task_id: ${n.taskId}`),{content:[{type:"text",text:s.length>1?`${s[0]} (${s.slice(1).join(", ")})`:s[0]}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.taskId?{taskId:n.taskId}:{}}}}}}var Yi="music_generate",WT={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."},is_instrumental:{type:"boolean",description:"Set true for pure instrumental music without vocals. Defaults to true when no lyrics are provided."},cover_audio_url:{type:"string",description:"URL of an existing audio track to use as base for cover/remix. When provided, generates a cover version. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},audio_format:{type:"string",enum:["mp3","wav","flac"],description:"Output audio format. Defaults to mp3."}},required:["prompt"]};function Au(r){return{name:Yi,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:WT,execute:async(e,t)=>{let n=t.lyrics;if(!n&&!t.is_instrumental&&r.generateLyrics)try{n=await r.generateLyrics(t.prompt)}catch{}let o=await r.generateMusic({prompt:t.prompt,purpose:t.purpose,style:t.style,lyrics:n,duration:t.duration,isInstrumental:t.is_instrumental,audioUrl:t.cover_audio_url,audioFormat:t.audio_format}),s=o.mediaUrls.length;return{content:[{type:"text",text:`Generated ${s} audio track${s>1?"s":""}${o.model?` (model: ${o.model})`:""}`}],details:{type:"music_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var zT="video_edit",VT={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. All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_images:{type:"array",items:{type:"string"},maxItems:9,description:"Optional reference images for element replacement (up to 9). All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},duration:{type:"number",minimum:4,maximum:15,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 Iu(r){return{name:zT,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos (max 3). Max 9 reference images for element replacement. Max 720p. All video/image URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. For generating NEW videos from scratch, use video_generate instead.",parameters:VT,execute:async(e,t)=>{if(!t.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await r.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 qT="video_merge",KT={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video URL or file path. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if local file."},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 Pu(r){return{name:qT,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. All video/audio URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides local files. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:KT,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 r.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 JT="video_upscale",XT={type:"object",properties:{video:{type:"string",description:"Video URL to upscale. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},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 Mu(r){return{name:JT,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. Video URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. Best used as post-processing after video_merge.",parameters:XT,execute:async(e,t)=>{let n=await r.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 YT="three_d_generate",QT={type:"object",properties:{prompt:{type:"string",description:"3D model generation prompt. Describe the object's shape, material, texture, color, and pose. For text-to-3D, provide a detailed description. For image-to-3D, also provide image_url."},image_url:{type:"string",description:"Reference image URL for image-to-3D generation. The image should show the object clearly from a single viewpoint with clean background for best results. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},output_format:{type:"string",description:"3D model output format: 'glb' (default), 'obj', 'usd', 'usdz'."},seed:{type:"number",description:"Random seed for reproducible generation."}},required:["prompt"]};function Eu(r){return{name:YT,label:"3D Generate",description:"Generate a 3D model from a text prompt or reference image. Supports text-to-3D and image-to-3D workflows. Output formats include GLB, OBJ, USD. The generated model can be viewed in any 3D viewer or imported into game engines. IMPORTANT: Describe the object in detail \u2014 shape, size, material, texture, color, and pose.",parameters:QT,execute:async(e,t)=>{let n=await r.generate3D({prompt:t.prompt,imageUrl:t.image_url,outputFormat:t.output_format,seed:t.seed}),o=n.mediaUrls.length,s=`Generated ${o} 3D model${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`;return o===0&&n.metadata?.debugResponseKeys&&(s+=` [debug: response keys=${JSON.stringify(n.metadata.debugResponseKeys)}, content=${n.metadata.debugContentSample??"null"}]`),{content:[{type:"text",text:s}],details:{type:"three_d_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.metadata??{}}}}}}var ZT={type:"object",properties:{audio_url:{type:"string",description:"URL of the audio file to transcribe. Supports mp3, wav, m4a, ogg, flac formats. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},language:{type:"string",description:"Language hint for transcription: 'zh' (Chinese), 'en' (English), or auto-detect if omitted."}},required:["audio_url"]};function Ou(r){return{name:"stt",label:"STT",description:"Transcribe audio to text (Speech-to-Text). Provide an audio file URL and receive the spoken content as text. Supports Chinese and English. Use for meeting transcription, voice message reading, subtitle generation, or any audio-to-text conversion.",parameters:ZT,execute:async(e,t)=>{if(!t.audio_url)return{content:[{type:"text",text:"Error: audio_url parameter is required. Provide a publicly accessible HTTP/HTTPS URL to an audio file."}],details:{error:"audio_url parameter is required"}};let n=await r.speechToText({audioUrl:t.audio_url,language:t.language}),o=n.transcription.length>200?n.transcription.slice(0,200)+"\u2026":n.transcription;return{content:[{type:"text",text:n.transcription}],details:{type:"stt",model:n.model,durationMs:n.durationMs,transcriptionLength:n.transcription.length,preview:o}}}}}var ew="voice_clone",tw={type:"object",properties:{text:{type:"string",description:"Text to synthesize in the cloned voice."},sample_audio_url:{type:"string",description:"URL of an audio sample (5-30 seconds recommended) of the voice to clone. The sample should be clear speech with minimal background noise. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},speed:{type:"number",description:"Speech speed multiplier (0.5-2.0). Default is 1.0."}},required:["text","sample_audio_url"]};function Du(r){return{name:ew,label:"Voice Clone",description:"Clone a voice from an audio sample and synthesize new speech in that voice. Requires a clear audio sample (5-30s recommended) of the target voice. Use for personalized narration, character voices, or voice preservation. DO NOT use for impersonation or deception. For standard TTS with preset voices, use the tts tool instead.",parameters:tw,execute:async(e,t)=>{let n=await r.cloneVoice({text:t.text,sampleAudioUrl:t.sample_audio_url,speed:t.speed});return{content:[{type:"text",text:`Voice cloned and synthesized speech${n.model?` (model: ${n.model})`:""}`}],details:{type:"voice_clone",model:n.model,voiceId:n.voiceId,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var nw="media_cancel",ow={type:"object",properties:{task_id:{type:"string",description:"The task ID of the media generation to cancel (returned in previous generation results)."},provider:{type:"string",description:"Provider name (e.g. 'doubao', 'zhipu'). If omitted, auto-detects from task context."}},required:["task_id"]};function Lu(r){return{name:nw,label:"Media Cancel",description:"Cancel an in-progress media generation task (video, 3D, etc.). Provide the task_id from a previous generation result. Use this when a user wants to abort a long-running generation.",parameters:ow,execute:async(e,t)=>{if(!t.task_id)return{content:[{type:"text",text:"Error: task_id is required."}],details:{error:"task_id is required"}};let n=await r.cancelTask({taskId:t.task_id,provider:t.provider});return{content:[{type:"text",text:n.ok?`Task ${t.task_id} cancelled.`:`Cancel failed: ${n.message}`}],details:n.ok?void 0:{error:n.message}}}}}var rw="file_upload",sw={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the local file to upload. Supported: images (jpg/png/webp/gif), audio (mp3/wav/m4a/ogg/flac), video (mp4/mov/avi). The file will be uploaded to the configured provider's Files API and a file ID or public URL will be returned."},purpose:{type:"string",description:"Upload purpose hint: 'media_reference' (for image/video/audio generation), 'user_data' (general). Default: 'media_reference'."}},required:["file_path"]};function $u(r){return{name:rw,label:"File Upload",description:"Upload a local file to the cloud provider's Files API. Returns a file ID (or public URL) that can be used as input for media generation tools (image_generate, video_generate, video_edit, etc.). Use this when the user provides a local file that needs to be referenced by URL in media tools. IMPORTANT: Only call this tool for files that actually need to be uploaded for media generation. Not all providers support file upload \u2014 tool availability depends on the configured provider.",parameters:sw,execute:async(e,t)=>{let n=await r.uploadFile({filePath:t.file_path,purpose:t.purpose}),o=[`Uploaded "${n.filename}" (${Qi(n.bytes)}) via ${n.provider}`];return n.url&&o.push(`URL: ${n.url}`),o.push(`File ID: ${n.fileId}`),{content:[{type:"text",text:o.join(`
287
- `)}],details:{type:"file_upload",fileId:n.fileId,url:n.url,filename:n.filename,bytes:n.bytes,provider:n.provider}}}}}var iw="file_query",aw={type:"object",properties:{file_id:{type:"string",description:"Query a specific file by ID. If omitted, lists recent uploaded files."},limit:{type:"number",description:"Max number of files to list when file_id is omitted. Default: 10, max: 100."}},required:[]};function Uu(r){return{name:iw,label:"File Query",description:"Query or list uploaded files from the provider's Files API. Use file_id to get info on a specific file, or omit to list recent uploads. Returns file ID, name, size, status, and URL (if available).",parameters:aw,execute:async(e,t)=>{if(t.file_id){let i=await r.queryFile({fileId:t.file_id}),a=[`File: ${i.filename}`,`ID: ${i.id}`,`Size: ${Qi(i.bytes)}`,`Status: ${i.status}`];return i.url&&a.push(`URL: ${i.url}`),i.createdAt&&a.push(`Created: ${i.createdAt}`),{content:[{type:"text",text:a.join(`
279
+ 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 Ji(r){let e=new Map,t=el(r);await xu(t,e);let n=Qc();return await xu(n,e),e}async function xu(r,e){if(HT(r))try{let t=await GT(r,{withFileTypes:!0});for(let n of t)if(n.isFile()&&n.name.endsWith(".json")){let o=n.name.replace(/\.json$/,"");e.has(o)||e.set(o,Au.join(r,n.name))}}catch{}}async function Qi(r){let e=await WT(r,"utf-8");return JSON.parse(e)}function zT(r){let e=new Map(r.map(s=>[s.id,s])),t=new Set,n=[];function o(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 c of a.dependsOn??[])o(c,i);i.delete(s),t.add(s),n.push(a)}for(let s of r)o(s.id,new Set);return n}function KT(r,e,t){let n={};for(let[o,s]of Object.entries(r))if(typeof s=="string"){let i=s;i=i.replace(/\$\{var\.(\w+)\}/g,(a,c)=>e[c]??`\${var.${c}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,c)=>t.get(c)?.output??""),n[o]=i}else n[o]=s;return n}function Cu(r){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:VT,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"workflow pipeline automation steps DAG",execute:async(e,t,n)=>{let o=r.getCwd();switch(t.action){case"list":{let s=await Ji(o);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,c]of s)try{let d=await Qi(c);i.push(` - ${a}: ${d.description??"(no description)"} (${d.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
280
+ `)}],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 Ji(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Qi(i),c=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let d of a.steps){let l=d.dependsOn?.length?` (after: ${d.dependsOn.join(", ")})`:"";c.push(` ${d.id}: ${d.label??d.tool}${l}`),c.push(` tool: ${d.tool}`),c.push(` args: ${JSON.stringify(d.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){c.push("","Variables (defaults):");for(let[d,l]of Object.entries(a.variables))c.push(` ${d} = ${l}`)}return{content:[{type:"text",text:c.filter(Boolean).join(`
281
+ `)}],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 Ji(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Qi(i),c={...a.variables,...t.variables},d;try{d=zT(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let l=new Map,u=[`Running workflow: ${a.name}`,""],p=!0;for(let m of d){if(n?.aborted){u.push(`\u26A1 Aborted at step: ${m.id}`),p=!1;break}let f=(m.dependsOn??[]).some(b=>!l.get(b)?.success),g=m.condition??"on_success";if(g==="on_success"&&f){u.push(`\u23ED Skipped ${m.id} (dependency failed)`),l.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(g==="on_failure"&&!f){u.push(`\u23ED Skipped ${m.id} (no failure to handle)`),l.set(m.id,{stepId:m.id,success:!0,output:""});continue}u.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let y=KT(m.args,c,l);try{let b=await r.invokeTool(m.tool,y,n),k=!b.error;if(l.set(m.id,{stepId:m.id,success:k,output:b.result,error:b.error}),k){let S=b.result.length>200?b.result.slice(0,200)+"...":b.result;u.push(` \u2705 ${S}`)}else u.push(` \u274C ${b.error}`),p=!1}catch(b){let k=b.message;l.set(m.id,{stepId:m.id,success:!1,output:"",error:k}),u.push(` \u274C ${k}`),p=!1}}return u.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:u.join(`
282
+ `)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:l.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 qT="sleep",XT={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 Pu(r){return{name:qT,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(`
283
+ `),parameters:XT,execute:async(e,t,n)=>{let o=Math.max(1,Math.min(3600,Math.round(t.duration))),s=o*1e3,i=new AbortController,a=()=>i.abort();n?.addEventListener("abort",a,{once:!0}),n?.aborted&&i.abort();try{let c=await r.sleep(s,i.signal),d=[];return c.interrupted?(d.push(`Sleep interrupted after ${c.sleptSeconds}s.`),c.interruptReason&&d.push(`Reason: ${c.interruptReason}`),d.push("Check for new messages or tasks.")):d.push(`Slept for ${c.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:d.join(`
284
+ `)}],details:{...c,requestedSeconds:o}}}finally{n?.removeEventListener("abort",a)}}}}var YT="tool_search",JT={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"]},QT=5;function Mu(r){return{name:YT,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:JT,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(),o=t.maxResults??QT;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(l=>l.trim()).filter(Boolean),a=[],c=[];if(r.activateTool)for(let l of i)await r.activateTool(l)?a.push(l):c.push(l);else{let l=await r.searchTools(n,{maxResults:o});return Iu(l)}let d=[];return a.length>0&&d.push(`Activated: ${a.join(", ")}. These tools are now available.`),c.length>0&&d.push(`Not found: ${c.join(", ")}.`),{content:[{type:"text",text:d.join(`
285
+ `)}],details:{type:"tool_search",activated:a,notFound:c,mode:"select"}}}let s=await r.searchTools(n,{maxResults:o});return Iu(s)}}}function Iu(r){if(r.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${r.query}". Total deferred tools available: ${r.totalDeferred}.`}],details:{type:"tool_search",query:r.query,matchCount:0,totalDeferred:r.totalDeferred}};let e=[`Found ${r.matches.length} tool(s) matching "${r.query}" (${r.totalDeferred} total deferred):`,""];for(let t of r.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(`
286
+ `)}],details:{type:"tool_search",query:r.query,matchCount:r.matches.length,totalDeferred:r.totalDeferred,matches:r.matches.map(t=>t.name)}}}var Zi="image_generate",ZT={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. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."},quality:{type:"string",description:"Image quality level: 'auto', 'high', 'low', 'hd'. Provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation. Same seed + prompt = same result."}},required:["prompt"]};function Eu(r){return{name:Zi,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. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file. Local file paths and data: URIs are NOT supported by the generation API.",parameters:ZT,execute:async(e,t)=>{let n=await r.generateImage({prompt:t.prompt,purpose:t.purpose,style:t.style,size:t.size,imageUrl:t.image_url,n:t.n,quality:t.quality,seed:t.seed}),o=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${o} image${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var ew={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)."},voice:{type:"string",description:"Voice name for TTS. Available voices depend on the provider. Common options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer."},speed:{type:"number",description:"Speech speed multiplier (0.25-4.0). Default is 1.0."}},required:["text"]};function Ou(r){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:ew,execute:async(e,t)=>{let n=await r.textToSpeech({text:t.text,channel:t.channel,voice:t.voice,speed:t.speed});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 ea="video_generate",tw={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 URL for image-to-video generation (first frame, style reference, or character reference). MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported. If the user provides a local file, use a file hosting service or the image_generate tool first."},reference_videos:{type:"array",items:{type:"string"},maxItems:3,description:"Reference video URLs for video-to-video or multimodal generation (Seedance 2.0). Max 3 videos, total duration \u226415s. Use for: (a) video-to-video: provide source video to restyle/transform with prompt guidance; (b) multimodal reference: combine with image_url and/or reference_audios for style/motion/audio-guided generation. Each URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_audios:{type:"array",items:{type:"string"},maxItems:3,description:"Reference audio URLs for audio-guided video generation (Seedance 2.0). Max 3 audio clips, total duration \u226415s. CANNOT be used alone \u2014 must be combined with at least one image_url or reference_video. Each URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},generate_audio:{type:"boolean",description:"Generate synchronized audio track for the video (Seedance 2.0/1.5 pro). When true, the output video includes AI-generated sound effects matching the visual content."},aspect_ratio:{type:"string",description:"Video aspect ratio: '9:16' (vertical), '16:9' (horizontal), '1:1' (square). Default: '16:9'."},duration:{type:"number",minimum:3,maximum:15,description:"Video duration in seconds. Seedance 2.0: 4-15s per shot. Seedance 1.0/1.5: 3-10s. For longer videos (>15s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation."},resolution:{type:"string",description:"Output resolution: '480p', '720p', '1080p'. Default: '720p'."},fps:{type:"number",description:"Frame rate: 24 or 30 fps. Default: provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation."},camera_fixed:{type:"boolean",description:"Lock camera position (Seedance 1.0/1.5 only, not supported for img2video)."},return_last_frame:{type:"boolean",description:"Return last frame URL for chaining continuous video segments."},draft:{type:"boolean",description:"Draft mode: low-cost preview (Seedance 1.5 pro only)."},service_tier:{type:"string",enum:["default","flex"],description:"'default' (online, fast) or 'flex' (offline, ~50% cost). Not all models support flex."},callback_url:{type:"string",description:"Webhook URL for async task completion notification."},safety_identifier:{type:"string",description:"End-user safety identifier for content moderation tracking."},execution_expires_after:{type:"number",description:"Task expiration in seconds (for offline/flex scheduling)."},video_tools:{type:"array",items:{type:"string"},description:"Video-level builtin tools, e.g. ['web_search'] (Seedance 2.0 online search)."}},required:["prompt"]};function Du(r){return{name:ea,label:"Video Generate",description:"Generate a short video clip from a text prompt, reference image, source video, or multimodal references. 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. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. 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:tw,execute:async(e,t)=>{let n=await r.generateVideo({prompt:t.prompt,purpose:t.purpose,style:t.style,imageUrl:t.image_url,referenceVideos:t.reference_videos,referenceAudios:t.reference_audios,generateAudio:t.generate_audio,aspectRatio:t.aspect_ratio,duration:t.duration,resolution:t.resolution,fps:t.fps,seed:t.seed,cameraFixed:t.camera_fixed,returnLastFrame:t.return_last_frame,draft:t.draft,serviceTier:t.service_tier,callbackUrl:t.callback_url,safetyIdentifier:t.safety_identifier,executionExpiresAfterSeconds:t.execution_expires_after,videoTools:t.video_tools}),o=n.mediaUrls.length,s=[`Generated ${o} video${o>1?"s":""}`];return n.model&&s.push(`model: ${n.model}`),n.lastFrameUrl&&s.push(`last_frame: ${n.lastFrameUrl}`),n.taskId&&s.push(`task_id: ${n.taskId}`),{content:[{type:"text",text:s.length>1?`${s[0]} (${s.slice(1).join(", ")})`:s[0]}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.taskId?{taskId:n.taskId}:{}}}}}}var ta="music_generate",nw={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."},is_instrumental:{type:"boolean",description:"Set true for pure instrumental music without vocals. Defaults to true when no lyrics are provided."},cover_audio_url:{type:"string",description:"URL of an existing audio track to use as base for cover/remix. When provided, generates a cover version. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},audio_format:{type:"string",enum:["mp3","wav","flac"],description:"Output audio format. Defaults to mp3."}},required:["prompt"]};function Lu(r){return{name:ta,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:nw,execute:async(e,t)=>{let n=t.lyrics;if(!n&&!t.is_instrumental&&r.generateLyrics)try{n=await r.generateLyrics(t.prompt)}catch{}let o=await r.generateMusic({prompt:t.prompt,purpose:t.purpose,style:t.style,lyrics:n,duration:t.duration,isInstrumental:t.is_instrumental,audioUrl:t.cover_audio_url,audioFormat:t.audio_format}),s=o.mediaUrls.length;return{content:[{type:"text",text:`Generated ${s} audio track${s>1?"s":""}${o.model?` (model: ${o.model})`:""}`}],details:{type:"music_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var ow="video_edit",rw={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. All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_images:{type:"array",items:{type:"string"},maxItems:9,description:"Optional reference images for element replacement (up to 9). All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},duration:{type:"number",minimum:4,maximum:15,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 Nu(r){return{name:ow,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos (max 3). Max 9 reference images for element replacement. Max 720p. All video/image URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. For generating NEW videos from scratch, use video_generate instead.",parameters:rw,execute:async(e,t)=>{if(!t.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await r.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 sw="video_merge",iw={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video URL or file path. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if local file."},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 Uu(r){return{name:sw,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. All video/audio URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides local files. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:iw,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 r.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 aw="video_upscale",cw={type:"object",properties:{video:{type:"string",description:"Video URL to upscale. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},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 $u(r){return{name:aw,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. Video URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. Best used as post-processing after video_merge.",parameters:cw,execute:async(e,t)=>{let n=await r.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 lw="three_d_generate",dw={type:"object",properties:{prompt:{type:"string",description:"3D model generation prompt. Describe the object's shape, material, texture, color, and pose. For text-to-3D, provide a detailed description. For image-to-3D, also provide image_url."},image_url:{type:"string",description:"Reference image URL for image-to-3D generation. The image should show the object clearly from a single viewpoint with clean background for best results. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},output_format:{type:"string",description:"3D model output format: 'glb' (default), 'obj', 'usd', 'usdz'."},seed:{type:"number",description:"Random seed for reproducible generation."}},required:["prompt"]};function ju(r){return{name:lw,label:"3D Generate",description:"Generate a 3D model from a text prompt or reference image. Supports text-to-3D and image-to-3D workflows. Output formats include GLB, OBJ, USD. The generated model can be viewed in any 3D viewer or imported into game engines. IMPORTANT: Describe the object in detail \u2014 shape, size, material, texture, color, and pose.",parameters:dw,execute:async(e,t)=>{let n=await r.generate3D({prompt:t.prompt,imageUrl:t.image_url,outputFormat:t.output_format,seed:t.seed}),o=n.mediaUrls.length,s=`Generated ${o} 3D model${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`;return o===0&&n.metadata?.debugResponseKeys&&(s+=` [debug: response keys=${JSON.stringify(n.metadata.debugResponseKeys)}, content=${n.metadata.debugContentSample??"null"}]`),{content:[{type:"text",text:s}],details:{type:"three_d_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.metadata??{}}}}}}var uw={type:"object",properties:{audio_url:{type:"string",description:"URL of the audio file to transcribe. Supports mp3, wav, m4a, ogg, flac formats. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},language:{type:"string",description:"Language hint for transcription: 'zh' (Chinese), 'en' (English), or auto-detect if omitted."}},required:["audio_url"]};function Fu(r){return{name:"stt",label:"STT",description:"Transcribe audio to text (Speech-to-Text). Provide an audio file URL and receive the spoken content as text. Supports Chinese and English. Use for meeting transcription, voice message reading, subtitle generation, or any audio-to-text conversion.",parameters:uw,execute:async(e,t)=>{if(!t.audio_url)return{content:[{type:"text",text:"Error: audio_url parameter is required. Provide a publicly accessible HTTP/HTTPS URL to an audio file."}],details:{error:"audio_url parameter is required"}};let n=await r.speechToText({audioUrl:t.audio_url,language:t.language}),o=n.transcription.length>200?n.transcription.slice(0,200)+"\u2026":n.transcription;return{content:[{type:"text",text:n.transcription}],details:{type:"stt",model:n.model,durationMs:n.durationMs,transcriptionLength:n.transcription.length,preview:o}}}}}var pw="voice_clone",mw={type:"object",properties:{text:{type:"string",description:"Text to synthesize in the cloned voice."},sample_audio_url:{type:"string",description:"URL of an audio sample (5-30 seconds recommended) of the voice to clone. The sample should be clear speech with minimal background noise. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},speed:{type:"number",description:"Speech speed multiplier (0.5-2.0). Default is 1.0."}},required:["text","sample_audio_url"]};function Bu(r){return{name:pw,label:"Voice Clone",description:"Clone a voice from an audio sample and synthesize new speech in that voice. Requires a clear audio sample (5-30s recommended) of the target voice. Use for personalized narration, character voices, or voice preservation. DO NOT use for impersonation or deception. For standard TTS with preset voices, use the tts tool instead.",parameters:mw,execute:async(e,t)=>{let n=await r.cloneVoice({text:t.text,sampleAudioUrl:t.sample_audio_url,speed:t.speed});return{content:[{type:"text",text:`Voice cloned and synthesized speech${n.model?` (model: ${n.model})`:""}`}],details:{type:"voice_clone",model:n.model,voiceId:n.voiceId,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var gw="media_cancel",fw={type:"object",properties:{task_id:{type:"string",description:"The task ID of the media generation to cancel (returned in previous generation results)."},provider:{type:"string",description:"Provider name (e.g. 'doubao', 'zhipu'). If omitted, auto-detects from task context."}},required:["task_id"]};function Wu(r){return{name:gw,label:"Media Cancel",description:"Cancel an in-progress media generation task (video, 3D, etc.). Provide the task_id from a previous generation result. Use this when a user wants to abort a long-running generation.",parameters:fw,execute:async(e,t)=>{if(!t.task_id)return{content:[{type:"text",text:"Error: task_id is required."}],details:{error:"task_id is required"}};let n=await r.cancelTask({taskId:t.task_id,provider:t.provider});return{content:[{type:"text",text:n.ok?`Task ${t.task_id} cancelled.`:`Cancel failed: ${n.message}`}],details:n.ok?void 0:{error:n.message}}}}}var hw="file_upload",yw={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the local file to upload. Supported: images (jpg/png/webp/gif), audio (mp3/wav/m4a/ogg/flac), video (mp4/mov/avi). The file will be uploaded to the configured provider's Files API and a file ID or public URL will be returned."},purpose:{type:"string",description:"Upload purpose hint: 'media_reference' (for image/video/audio generation), 'user_data' (general). Default: 'media_reference'."}},required:["file_path"]};function Gu(r){return{name:hw,label:"File Upload",description:"Upload a local file to the cloud provider's Files API. Returns a file ID (or public URL) that can be used as input for media generation tools (image_generate, video_generate, video_edit, etc.). Use this when the user provides a local file that needs to be referenced by URL in media tools. IMPORTANT: Only call this tool for files that actually need to be uploaded for media generation. Not all providers support file upload \u2014 tool availability depends on the configured provider.",parameters:yw,execute:async(e,t)=>{let n=await r.uploadFile({filePath:t.file_path,purpose:t.purpose}),o=[`Uploaded "${n.filename}" (${na(n.bytes)}) via ${n.provider}`];return n.url&&o.push(`URL: ${n.url}`),o.push(`File ID: ${n.fileId}`),{content:[{type:"text",text:o.join(`
287
+ `)}],details:{type:"file_upload",fileId:n.fileId,url:n.url,filename:n.filename,bytes:n.bytes,provider:n.provider}}}}}var bw="file_query",kw={type:"object",properties:{file_id:{type:"string",description:"Query a specific file by ID. If omitted, lists recent uploaded files."},limit:{type:"number",description:"Max number of files to list when file_id is omitted. Default: 10, max: 100."}},required:[]};function Hu(r){return{name:bw,label:"File Query",description:"Query or list uploaded files from the provider's Files API. Use file_id to get info on a specific file, or omit to list recent uploads. Returns file ID, name, size, status, and URL (if available).",parameters:kw,execute:async(e,t)=>{if(t.file_id){let i=await r.queryFile({fileId:t.file_id}),a=[`File: ${i.filename}`,`ID: ${i.id}`,`Size: ${na(i.bytes)}`,`Status: ${i.status}`];return i.url&&a.push(`URL: ${i.url}`),i.createdAt&&a.push(`Created: ${i.createdAt}`),{content:[{type:"text",text:a.join(`
288
288
  `)}],details:{type:"file_query",fileId:i.id}}}let n=Math.min(Math.max(t.limit??10,1),100),o=await r.listFiles({limit:n});if(o.length===0)return{content:[{type:"text",text:"No uploaded files found."}],details:{type:"file_query",count:0}};let s=[`Found ${o.length} file(s):
289
- `];for(let i of o)s.push(`- ${i.filename} | ID: ${i.id} | ${Qi(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
290
- `)}],details:{type:"file_query",count:o.length}}}}}var lw="file_delete",cw={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function Nu(r){return{name:lw,label:"File Delete",description:"Delete a previously uploaded file from the provider's Files API. Use the file ID returned by file_upload or file_query.",parameters:cw,execute:async(e,t)=>(await r.deleteFile({fileId:t.file_id}),{content:[{type:"text",text:`Deleted file ${t.file_id}`}],details:{type:"file_delete",fileId:t.file_id}})}}function Qi(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}var dw="ask_user",uw={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:4,description:"1-4 clarifying questions to ask the user.",items:{type:"object",properties:{question:{type:"string",description:"The question text. Should end with '?'."},header:{type:"string",description:"Short identifier/tag for this question (max 50 chars)."},options:{type:"array",description:"2-4 options for the user to choose from. Omit for free text.",items:{type:"object",properties:{label:{type:"string",description:"Display label (1-5 words)."},description:{type:"string",description:"Brief explanation of this option."}},required:["label"]}},multiSelect:{type:"boolean",description:"Allow selecting multiple options (default: false)."}},required:["question","header"]}}},required:["questions"]};function ju(r){return{name:dw,label:"Ask User",description:"Ask the user clarifying questions when you need more information to proceed. Supports free text questions and multiple-choice options. Use this when the user's intent is ambiguous or you need confirmation.",parameters:uw,execute:async(e,t)=>{if(!t.questions||t.questions.length===0)return{content:[{type:"text",text:"Error: at least one question is required."}],details:{type:"ask_user",error:"no_questions"}};if(t.questions.length>4)return{content:[{type:"text",text:"Error: maximum 4 questions allowed."}],details:{type:"ask_user",error:"too_many_questions"}};let n=t.questions.map(i=>i.question);if(new Set(n).size!==n.length)return{content:[{type:"text",text:"Error: all questions must have unique text."}],details:{type:"ask_user",error:"duplicate_questions"}};for(let i of t.questions){if(i.options&&(i.options.length<2||i.options.length>4))return{content:[{type:"text",text:`Error: question "${i.header}" must have 2-4 options (got ${i.options.length}).`}],details:{type:"ask_user",error:"invalid_option_count"}};if(i.options){let a=i.options.map(c=>c.label);if(new Set(a).size!==a.length)return{content:[{type:"text",text:`Error: question "${i.header}" has duplicate option labels.`}],details:{type:"ask_user",error:"duplicate_option_labels"}}}}let o=await r.askUser(t.questions);if(o===null)return{content:[{type:"text",text:"User declined to answer questions."}],details:{type:"ask_user",declined:!0}};let s=["User answered:"];for(let i of t.questions){let a=o[i.question]??"(no answer)";s.push(`- ${i.header}: ${a}`)}return{content:[{type:"text",text:s.join(`
291
- `)}],details:{type:"ask_user",answers:o,questionCount:t.questions.length}}}}}function Fu(r,e){return!r?.webSearch||!r.capabilities.includes("web_search")?e:async(t,n)=>{try{let s=await r.webSearch(t,{maxResults:n?.maxResults});if(n?.allowedDomains?.length){let i=new Set(n.allowedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return i.has(new URL(a.url).hostname.toLowerCase())}catch{return!1}})}if(n?.blockedDomains?.length){let i=new Set(n.blockedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return!i.has(new URL(a.url).hostname.toLowerCase())}catch{return!0}})}if(s.length>0)return{query:t,results:s.map(i=>({title:i.title,url:i.url,snippet:i.snippet}))}}catch{}return e(t,n)}}var pw=[{pattern:"Bash",behavior:"ask",reason:"Group security: shell commands require approval in group chat",source:"group-policy"},{pattern:"computer",behavior:"deny",reason:"Group security: computer control blocked in group chat",source:"group-policy"}],mw=[/\.env($|\.)/i,/\.(key|pem|p12|pfx|jks)$/i,/id_rsa/i,/id_ed25519/i,/\.ssh\//i,/secret/i,/credential/i,/token/i,/password/i,/\.aws\//i,/\.gnupg\//i];function Bu(){return[...pw]}function Gu(r){return mw.some(e=>e.test(r))}var zu=!1;function oa(r){zu=r}var se,ye={},Vu,ta,gt={},qu;function Ku(r){qu=r}var Ju=null,na;function Xu(r){na=r}function Yu(r){Ju=r}function Qu(r,e,t,n,o){se=r,ye=e??{},Vu=t,ta=o,gt=n??{},hw()}function ra(r){let e=gt[r];if(!(!e||!se))return se.resolveModelById(e.provider,e.model,r)}function hw(){yw(),bw(),kw(),Tw()}function yw(){let r=Me(Xi);if(!r)return;let e=gt.video;if(!e||!se)return;let t=se.resolveModelById(e.provider,e.model,"video");if(!t)return;let n=t.modelInfo.mediaCapabilities;if(!n)return;let o=n.maxDurationSeconds??10,s=o>=10?4:3,i=n.resolutions?.join("/")||"720P",a=t.modelInfo.name||t.modelInfo.id;r.description=`Generate a short video clip from a text prompt, reference image, source video, or multimodal references. Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Current model: ${a}. Single-shot: ${s}\u2013${o}s. For longer videos (>${o}s), use multi-shot storyboard workflow. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. 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: ${s}-${o}s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).`;let c=r.parameters?.properties,d=c?.duration;d&&(d.minimum=s,d.maximum=o,d.description=`Video duration in seconds (${s}\u2013${o}s for ${a}). For longer videos (>${o}s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation.`);let l=c?.resolution;l&&n.resolutions&&(l.description=`Output resolution: ${i}. Default: '720p'.`)}function bw(){let r=Me(Ji);if(!r)return;let e=ra("image");if(!e)return;let t=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(t?.sizes?.length&&o.push(`Sizes: ${t.sizes.join(", ")}`),t?.transparentBackground&&o.push("Supports transparent background"),r.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. Current model: ${n}. ${o.join(". ")}${o.length?". ":""}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). Infer image size automatically from purpose. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file.`,t?.sizes?.length){let i=r.parameters?.properties?.size;i&&(i.description=`Dimensions: ${t.sizes.join(", ")}. Default: '1024x1024'. Auto-infer from purpose.`)}}function kw(){let r=Me("tts");if(!r)return;let e=ra("tts");if(!e)return;let t=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(t?.voices?.length&&o.push(`Voices: ${t.voices.join(", ")}`),t?.maxCharacters&&o.push(`Max: ${t.maxCharacters} characters per request`),t?.formats?.length&&o.push(`Formats: ${t.formats.join(", ")}`),r.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. Current model: ${n}. ${o.join(". ")}${o.length?".":""}`,t?.voices?.length){let i=r.parameters?.properties?.voice;i&&(i.description=`Voice name. Available: ${t.voices.join(", ")}.`)}}function Tw(){let r=Me(Yi);if(!r)return;let e=ra("music");if(!e)return;let t=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(t?.maxDurationSeconds&&o.push(`Max duration: ${t.maxDurationSeconds}s`),t?.formats?.length&&o.push(`Formats: ${t.formats.join(", ")}`),r.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. Current model: ${n}. ${o.join(". ")}${o.length?". ":""}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).`,t?.maxDurationSeconds){let i=r.parameters?.properties?.duration;i&&(i.maximum=t.maxDurationSeconds,i.description=`Duration in seconds (5\u2013${t.maxDurationSeconds}s for ${n}). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s.`)}}async function Ke(r){if(!se)throw new Error(`No media provider configured for ${r.mediaType}`);let e=gt[r.mediaType],t=e?.provider,n=e?.model||r.model;if(!t)throw new Error(`No provider configured for ${r.mediaType}. Please configure a provider in settings.`);let o={...r};ta&&!o.onProgress&&(o.onProgress=(c,d,l)=>{ta(l??"pending",r.mediaType,c,d,t)});let s=await Hu(t,n||r.model,o);if(s.ok)return s.result;let i=se.listMediaModels(r.mediaType),a=[`${t}: ${s.error}`];for(let c of i){if(c.providerId===t||!ye[c.providerId])continue;let l=await Hu(c.providerId,c.modelInfo.id,r);if(l.ok)return l.result;a.push(`${c.providerId}/${c.modelInfo.id}: ${l.error}`)}throw new Error(`All media providers failed for ${r.mediaType}:
289
+ `];for(let i of o)s.push(`- ${i.filename} | ID: ${i.id} | ${na(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
290
+ `)}],details:{type:"file_query",count:o.length}}}}}var Tw="file_delete",ww={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function Vu(r){return{name:Tw,label:"File Delete",description:"Delete a previously uploaded file from the provider's Files API. Use the file ID returned by file_upload or file_query.",parameters:ww,execute:async(e,t)=>(await r.deleteFile({fileId:t.file_id}),{content:[{type:"text",text:`Deleted file ${t.file_id}`}],details:{type:"file_delete",fileId:t.file_id}})}}function na(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}var vw="ask_user",Sw={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:4,description:"1-4 clarifying questions to ask the user.",items:{type:"object",properties:{question:{type:"string",description:"The question text. Should end with '?'."},header:{type:"string",description:"Short identifier/tag for this question (max 50 chars)."},options:{type:"array",description:"2-4 options for the user to choose from. Omit for free text.",items:{type:"object",properties:{label:{type:"string",description:"Display label (1-5 words)."},description:{type:"string",description:"Brief explanation of this option."}},required:["label"]}},multiSelect:{type:"boolean",description:"Allow selecting multiple options (default: false)."}},required:["question","header"]}}},required:["questions"]};function zu(r){return{name:vw,label:"Ask User",description:"Ask the user clarifying questions when you need more information to proceed. Supports free text questions and multiple-choice options. Use this when the user's intent is ambiguous or you need confirmation.",parameters:Sw,execute:async(e,t)=>{if(!t.questions||t.questions.length===0)return{content:[{type:"text",text:"Error: at least one question is required."}],details:{type:"ask_user",error:"no_questions"}};if(t.questions.length>4)return{content:[{type:"text",text:"Error: maximum 4 questions allowed."}],details:{type:"ask_user",error:"too_many_questions"}};let n=t.questions.map(i=>i.question);if(new Set(n).size!==n.length)return{content:[{type:"text",text:"Error: all questions must have unique text."}],details:{type:"ask_user",error:"duplicate_questions"}};for(let i of t.questions){if(i.options&&(i.options.length<2||i.options.length>4))return{content:[{type:"text",text:`Error: question "${i.header}" must have 2-4 options (got ${i.options.length}).`}],details:{type:"ask_user",error:"invalid_option_count"}};if(i.options){let a=i.options.map(c=>c.label);if(new Set(a).size!==a.length)return{content:[{type:"text",text:`Error: question "${i.header}" has duplicate option labels.`}],details:{type:"ask_user",error:"duplicate_option_labels"}}}}let o=await r.askUser(t.questions);if(o===null)return{content:[{type:"text",text:"User declined to answer questions."}],details:{type:"ask_user",declined:!0}};let s=["User answered:"];for(let i of t.questions){let a=o[i.question]??"(no answer)";s.push(`- ${i.header}: ${a}`)}return{content:[{type:"text",text:s.join(`
291
+ `)}],details:{type:"ask_user",answers:o,questionCount:t.questions.length}}}}}var Rw="project_switch",_w={type:"object",properties:{projectName:{type:"string",description:"The name of the project to switch to. Use the exact project name from the available project list."}},required:["projectName"]};function Ku(r){return{name:Rw,label:"Switch Project",description:["Switch the active project context. ONLY call this when the user EXPLICITLY asks to switch projects","(e.g. '\u5207\u6362\u5230XX\u9879\u76EE', 'switch to project X').","Do NOT call this if the user merely mentions a project name in conversation.","The projectName must be an EXACT match from the available project list.","If unsure which project the user means, ask them to clarify first."].join(`
292
+ `),parameters:_w,isReadOnly:!1,isConcurrencySafe:!1,shouldDefer:!0,searchHint:"switch project change workspace \u5207\u6362\u9879\u76EE",execute:async(e,t)=>{let n=r.listProjects();if(n.length===0)return{content:[{type:"text",text:"Error: No projects available."}]};let o=t.projectName.toLowerCase().trim(),s=n.find(a=>a.name.toLowerCase()===o);if(!s){let a=n.map(c=>`"${c.name}"`).join(", ");return{content:[{type:"text",text:`Error: No project with exact name "${t.projectName}". Available projects: ${a}. Please confirm the exact project name with the user before retrying.`}]}}let i=r.switchProject(s.id);return i?(r.onSwitched?.(i),{content:[{type:"text",text:`Switched to project "${i.name}" (workspace: ${i.workspaceDir}).`}]}):{content:[{type:"text",text:`Error: Failed to switch to project "${s.name}".`}]}}}}function qu(r,e){return!r?.webSearch||!r.capabilities.includes("web_search")?e:async(t,n)=>{try{let s=await r.webSearch(t,{maxResults:n?.maxResults});if(n?.allowedDomains?.length){let i=new Set(n.allowedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return i.has(new URL(a.url).hostname.toLowerCase())}catch{return!1}})}if(n?.blockedDomains?.length){let i=new Set(n.blockedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return!i.has(new URL(a.url).hostname.toLowerCase())}catch{return!0}})}if(s.length>0)return{query:t,results:s.map(i=>({title:i.title,url:i.url,snippet:i.snippet}))}}catch{}return e(t,n)}}var xw=[{pattern:"Bash",behavior:"ask",reason:"Group security: shell commands require approval in group chat",source:"group-policy"},{pattern:"computer",behavior:"deny",reason:"Group security: computer control blocked in group chat",source:"group-policy"}],Aw=[/\.env($|\.)/i,/\.(key|pem|p12|pfx|jks)$/i,/id_rsa/i,/id_ed25519/i,/\.ssh\//i,/secret/i,/credential/i,/token/i,/password/i,/\.aws\//i,/\.gnupg\//i];function Xu(){return[...xw]}function Yu(r){return Aw.some(e=>e.test(r))}import{existsSync as Ju,mkdirSync as Cw,readFileSync as Pw,writeFileSync as Iw}from"node:fs";import{join as Mw}from"node:path";import{randomUUID as Qu}from"node:crypto";function Zu(){return Mw(X(),"projects.json")}function Ue(){let r=Zu();if(!Ju(r))return{activeProjectId:null,projects:[]};try{let e=Pw(r,"utf-8");return JSON.parse(e)}catch{return{activeProjectId:null,projects:[]}}}function ft(r){let e=Zu(),t=X();Ju(t)||Cw(t,{recursive:!0}),Iw(e,JSON.stringify(r,null,2),"utf-8")}function oa(r){let e=Ue(),t=new Date().toISOString(),n={id:Qu(),name:r.name,workspaceDir:r.workspaceDir,type:r.type??"personal",status:"active",groupId:r.groupId,createdAt:t,updatedAt:t};return e.projects.push(n),e.activeProjectId=n.id,ft(e),n}function ht(){return Ue().projects.filter(e=>e.status==="active")}function Dt(){let r=Ue();if(!r.activeProjectId)return null;let e=r.projects.find(t=>t.id===r.activeProjectId)??null;return e&&e.status!=="active"?null:e}function ep(r){return Ue().projects.find(t=>t.id===r)??null}function Lt(r){let e=Ue(),t=e.projects.find(n=>n.id===r&&n.status==="active");return t?(e.activeProjectId=t.id,ft(e),t):null}function tp(r){let e=Ue(),t=e.projects.findIndex(s=>s.id===r);if(t===-1)return{deleted:!1};let n=e.projects[t];if(n.type==="default")return{deleted:!1};n.status="archived",n.updatedAt=new Date().toISOString();let o;if(e.activeProjectId===r){let s=e.projects.find(i=>i.type==="default"&&i.status==="active");if(s)e.activeProjectId=s.id,o=s;else{let i=e.projects.find(a=>a.status==="active"&&a.id!==r);e.activeProjectId=i?.id??null,o=i}}return ft(e),{deleted:!0,switchedTo:o}}function np(r){let e=Ue(),t=e.projects.find(s=>s.type==="default"&&s.status==="active");if(t)return t;let n=new Date().toISOString(),o={id:Qu(),name:"\u9ED8\u8BA4\u9879\u76EE",workspaceDir:r,type:"default",status:"active",createdAt:n,updatedAt:n};return e.projects.push(o),e.activeProjectId||(e.activeProjectId=o.id),ft(e),o}function op(r,e){let t=Ue(),n=t.projects.find(s=>s.id===r&&s.status==="active");return!n||n.type==="default"||t.projects.find(s=>s.name===e&&s.status==="active"&&s.id!==r)?null:(n.name=e,n.updatedAt=new Date().toISOString(),ft(t),n)}function rp(r){let e=Ue(),t=e.projects.find(o=>o.id===r&&o.status==="active");if(!t)return{archived:!1};if(t.type==="default")return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let n;if(e.activeProjectId===r){let o=e.projects.find(s=>s.type==="default"&&s.status==="active");if(o)e.activeProjectId=o.id,n=o;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==r);e.activeProjectId=s?.id??null,n=s}}return ft(e),{archived:!0,switchedTo:n}}function sp(r){let e=Ue(),t=e.projects.find(n=>n.id===r&&n.status==="archived");return t?(t.status="active",t.updatedAt=new Date().toISOString(),ft(e),t):null}function ra(r){return Ue().projects.find(t=>t.groupId===r&&t.status==="active")??null}function ip(r){let e=Ue(),t=e.projects.find(o=>o.groupId===r&&o.status==="active");if(!t)return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let n;if(e.activeProjectId===t.id){let o=e.projects.find(s=>s.type==="default"&&s.status==="active");if(o)e.activeProjectId=o.id,n=o;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==t.id);e.activeProjectId=s?.id??null,n=s}}return ft(e),{archived:!0,projectId:t.id,switchedTo:n}}var dp=!1;function la(r){dp=r}var ie,ke={},up,aa,yt={},pp;function mp(r){pp=r}var gp=null,Dw;var ca;function fp(r){ca=r}function hp(r){gp=r}function yp(r,e,t,n,o){ie=r,ke=e??{},up=t,aa=o,yt=n??{},Lw()}function da(r){let e=yt[r];if(!(!e||!ie))return ie.resolveModelById(e.provider,e.model,r)}function Lw(){Nw(),Uw(),$w(),jw()}function Nw(){let r=Oe(ea);if(!r)return;let e=yt.video;if(!e||!ie)return;let t=ie.resolveModelById(e.provider,e.model,"video");if(!t)return;let n=t.modelInfo.mediaCapabilities;if(!n)return;let o=n.maxDurationSeconds??10,s=o>=10?4:3,i=n.resolutions?.join("/")||"720P",a=t.modelInfo.name||t.modelInfo.id;r.description=`Generate a short video clip from a text prompt, reference image, source video, or multimodal references. Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Current model: ${a}. Single-shot: ${s}\u2013${o}s. For longer videos (>${o}s), use multi-shot storyboard workflow. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. 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: ${s}-${o}s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).`;let c=r.parameters?.properties,d=c?.duration;d&&(d.minimum=s,d.maximum=o,d.description=`Video duration in seconds (${s}\u2013${o}s for ${a}). For longer videos (>${o}s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation.`);let l=c?.resolution;l&&n.resolutions&&(l.description=`Output resolution: ${i}. Default: '720p'.`)}function Uw(){let r=Oe(Zi);if(!r)return;let e=da("image");if(!e)return;let t=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(t?.sizes?.length&&o.push(`Sizes: ${t.sizes.join(", ")}`),t?.transparentBackground&&o.push("Supports transparent background"),r.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. Current model: ${n}. ${o.join(". ")}${o.length?". ":""}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). Infer image size automatically from purpose. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file.`,t?.sizes?.length){let i=r.parameters?.properties?.size;i&&(i.description=`Dimensions: ${t.sizes.join(", ")}. Default: '1024x1024'. Auto-infer from purpose.`)}}function $w(){let r=Oe("tts");if(!r)return;let e=da("tts");if(!e)return;let t=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(t?.voices?.length&&o.push(`Voices: ${t.voices.join(", ")}`),t?.maxCharacters&&o.push(`Max: ${t.maxCharacters} characters per request`),t?.formats?.length&&o.push(`Formats: ${t.formats.join(", ")}`),r.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. Current model: ${n}. ${o.join(". ")}${o.length?".":""}`,t?.voices?.length){let i=r.parameters?.properties?.voice;i&&(i.description=`Voice name. Available: ${t.voices.join(", ")}.`)}}function jw(){let r=Oe(ta);if(!r)return;let e=da("music");if(!e)return;let t=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(t?.maxDurationSeconds&&o.push(`Max duration: ${t.maxDurationSeconds}s`),t?.formats?.length&&o.push(`Formats: ${t.formats.join(", ")}`),r.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. Current model: ${n}. ${o.join(". ")}${o.length?". ":""}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).`,t?.maxDurationSeconds){let i=r.parameters?.properties?.duration;i&&(i.maximum=t.maxDurationSeconds,i.description=`Duration in seconds (5\u2013${t.maxDurationSeconds}s for ${n}). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s.`)}}async function Ze(r){if(!ie)throw new Error(`No media provider configured for ${r.mediaType}`);let e=yt[r.mediaType],t=e?.provider,n=e?.model||r.model;if(!t)throw new Error(`No provider configured for ${r.mediaType}. Please configure a provider in settings.`);let o={...r};aa&&!o.onProgress&&(o.onProgress=(c,d,l)=>{aa(l??"pending",r.mediaType,c,d,t)});let s=await cp(t,n||r.model,o);if(s.ok)return s.result;let i=ie.listMediaModels(r.mediaType),a=[`${t}: ${s.error}`];for(let c of i){if(c.providerId===t||!ke[c.providerId])continue;let l=await cp(c.providerId,c.modelInfo.id,r);if(l.ok)return l.result;a.push(`${c.providerId}/${c.modelInfo.id}: ${l.error}`)}throw new Error(`All media providers failed for ${r.mediaType}:
292
293
  `+a.map(c=>` - ${c}`).join(`
293
- `))}async function Hu(r,e,t){let n=se.getTransport(r);if(!n)return{ok:!1,error:"transport not available"};let o=ye[r];if(!o)return{ok:!1,error:"no API key"};try{let s={...t,model:e},i=await n.generate(s,o);i.billingUnit||(t.mediaType==="tts"&&t.text?(i.billingUnit="per_character",i.billingQuantity=t.text.length):(t.mediaType==="video"||t.mediaType==="music")&&t.duration?(i.billingUnit="per_second",i.billingQuantity=t.duration):(i.billingUnit="per_call",i.billingQuantity=1));let a=i.model??s.model,c=i.billingUnit??"per_call",d=i.billingQuantity??1;return Vu?.(a,c,d),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Je(r){if(!se)return!1;let e=gt[r];if(!e)return!1;let t=se.getTransport(e.provider),n=ye[e.provider];return!!(t&&n)}function Zi(r,e){if(!Je(r))return!1;let t=gt[r],n=se.resolveModelById(t.provider,t.model,r);if(!n)return!1;let o=n.modelInfo.mediaCapabilities;return!o||!("operations"in o)||!o.operations?!0:o.operations.includes(e)}function ar(){if(!se)return;for(let[,e]of Object.entries(gt)){if(!e)continue;let t=se.getTransport(e.provider),n=ye[e.provider];if(t instanceof Ue&&n)return{id:e.provider,type:"volcengine"}}if(ye.google)return{id:"google",type:"gemini"}}var ea;function lr(){return ea||(ea=new wn({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),ea}var Et=process.cwd();function Se(r){return Z.isAbsolute(r)?Z.normalize(r):Z.resolve(Et,r)}var ww=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),Zu=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),vw={".pdf":"application/pdf",".txt":"text/plain",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/plain",".json":"application/json",".xml":"application/xml",".csv":"text/csv",".md":"text/markdown",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".mp4":"video/mp4",".webm":"video/webm",".avi":"video/x-msvideo",".mov":"video/quicktime",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Sw(){return{resolvePath:Se,async readFile(r){let e=Se(r),t=Z.extname(e).toLowerCase();return Zu.has(t)?{type:"binary",mimeType:"application/octet-stream"}:ww.has(t)?{type:"image",localPath:e,mimeType:t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg"}:{type:"text",text:await z.promises.readFile(e,"utf8")}},validatePath(r){let e=Se(r);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:zu&&Gu(e)?"Blocked: reading sensitive file in group chat mode":null}}}function xw(){return{resolvePath:Se,async writeFile(r,e){let t=Se(r);await z.promises.mkdir(Z.dirname(t),{recursive:!0}),await z.promises.writeFile(t,e,"utf8")}}}function Rw(){return{resolvePath:Se,async readFile(r){let e=Se(r);return z.promises.readFile(e,"utf8")},async writeFile(r,e){let t=Se(r);await z.promises.mkdir(Z.dirname(t),{recursive:!0}),await z.promises.writeFile(t,e,"utf8")}}}function _w(){return{resolvePath:Se,async readFile(r){let e=Se(r);return z.promises.readFile(e,"utf8")},async writeFile(r,e){let t=Se(r);await z.promises.mkdir(Z.dirname(t),{recursive:!0}),await z.promises.writeFile(t,e,"utf8")},async deleteFile(r){let e=Se(r);await z.promises.unlink(e)},async fileExists(r){let e=Se(r);try{return await z.promises.access(e),!0}catch{return!1}}}}function Cw(){return{resolvePath:Se,async glob(r,e){let t=e.cwd||Et,n=e.limit||1e3,o=[],s=!1,i=r.replace(/\\/g,"/").split("/"),a=i.some(l=>l==="**"),c=i[i.length-1]??"*",d=ep(c);try{await sa(t,async l=>{if(o.length>=n)return s=!0,!1;let u=Z.basename(l);return d.test(u)&&o.push(l),!0},a?1/0:1)}catch{}return{files:o,truncated:s}},async grep(r,e){let t=e.cwd||Et;try{return await Iw(r,t,e)}catch{return await Pw(r,t,e)}}}}function ep(r){let e=r.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(t,n)=>"("+n.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var Aw=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function sa(r,e,t,n=0,o=""){if(n>t)return;let s;try{s=await z.promises.readdir(r,{withFileTypes:!0})}catch{return}for(let i of s){let a=o?`${o}/${i.name}`:i.name;if(i.isDirectory()){if(Aw.has(i.name))continue;await sa(Z.join(r,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function Iw(r,e,t){return new Promise((n,o)=>{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(r),s.push("."),fw("rg",s,{cwd:e,maxBuffer:10*1024*1024,timeout:3e4},(i,a)=>{if(i&&!("killed"in i&&i.killed)&&i.code!==1){o(i);return}let c=[];for(let p of a.split(`
294
- `))if(p.trim())try{let g=JSON.parse(p);g.type==="match"&&g.data&&c.push({path:g.data.path?.text??"",line:g.data.line_number??0,text:(g.data.lines?.text??"").trimEnd()})}catch{}let d=t.headLimit??250,l=t.offset??0,u=c.slice(l,l+d);n({matches:u,truncated:c.length>l+d})})})}async function Pw(r,e,t){let n=new RegExp(r,t.caseInsensitive?"i":""),o=t.headLimit??250,s=t.offset??0,i=t.fileGlob?ep(t.fileGlob):null,a=[],c=!1;return await sa(e,async d=>{if(a.length>=s+o+1)return c=!0,!1;if(i&&!i.test(Z.basename(d)))return!0;let l=Z.extname(d).toLowerCase();if(Zu.has(l))return!0;try{let p=(await z.promises.readFile(Z.join(e,d),"utf8")).split(`
295
- `);for(let g=0;g<p.length;g++)if(n.test(p[g])&&(a.push({path:d,line:g+1,text:p[g].slice(0,500)}),a.length>=s+o+1))return c=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+o),truncated:c}}var Wu=!1;function Mw(){if(!Wu)if(Wu=!0,Yo()){let r=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";Pn(ji(r))}else if(process.platform==="win32"){let r=Ew();Pn(ir(r))}else{let r=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";Pn(ir(r))}}function Ew(){let r=process.env.QLOGICAGENT_BASH_PATH;if(r&&z.existsSync(r))return r;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],t=process.env.ProgramFiles?Z.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let n of e)if(z.existsSync(n))return n;return"bash"}function Ow(){return{async fetchUrl(r){let e=new AbortController,t=setTimeout(()=>e.abort(),3e4);try{let n=await fetch(r.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 o=n.headers.get("content-type")??"",s=await n.text();return r.maxChars&&s.length>r.maxChars&&(s=s.slice(0,r.maxChars)),o.includes("html")&&r.extractMode!=="json"&&(s=Dw(s)),{content:s,title:Lw(s)}}finally{clearTimeout(t)}}}}function Dw(r){return r.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 Lw(r){return r.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function $w(){let r=async(e,t)=>{let n=process.env.SEARXNG_BASE_URL?.trim();if(!n)return{query:e,results:[],totalResults:0};let o=t?.maxResults??10,s=new URL("/search",n);s.searchParams.set("q",e),s.searchParams.set("format","json"),s.searchParams.set("pageno","1");let i=new AbortController,a=setTimeout(()=>i.abort(),15e3);try{let c=await fetch(s.toString(),{signal:i.signal,headers:{Accept:"application/json"}});if(!c.ok)return{query:e,results:[]};let d=await c.json(),l=(d.results??[]).slice(0,o).map(u=>({title:u.title??"",url:u.url??"",snippet:u.content??""}));if(t?.allowedDomains?.length){let u=new Set(t.allowedDomains.map(p=>p.toLowerCase()));return{query:e,results:l.filter(p=>{try{return u.has(new URL(p.url).hostname.toLowerCase())}catch{return!1}})}}if(t?.blockedDomains?.length){let u=new Set(t.blockedDomains.map(p=>p.toLowerCase()));return{query:e,results:l.filter(p=>{try{return!u.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:l,totalResults:d.number_of_results}}finally{clearTimeout(a)}};return{search:(e,t)=>Fu(qu,r)(e,t)}}function Uw(){let r=Z.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(o){return Z.join(r,"projects",o,".instructions")}function t(o,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(o),a=Z.resolve(i,s);if(!a.startsWith(i+Z.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(o,s){if(!z.existsSync(o))return[];let i=[];for(let a of z.readdirSync(o,{withFileTypes:!0})){let c=Z.join(o,a.name);if(a.isDirectory())i.push(...n(c,s));else if(a.isFile()&&a.name.endsWith(".md")){let d=z.statSync(c);i.push({filename:Z.relative(s,c).replace(/\\/g,"/"),path:c,size:d.size,updatedAt:d.mtime.toISOString(),content:z.readFileSync(c,"utf-8")})}}return i}return{list(o){let s=e(o);return n(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(o,s){try{let i=t(o,s);if(!z.existsSync(i))return null;let a=z.statSync(i),c=z.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:c}}catch{return null}},write(o,s,i){let a=t(o,s);z.mkdirSync(Z.dirname(a),{recursive:!0}),z.writeFileSync(a,i,"utf-8");let c=z.statSync(a);return{filename:s,path:a,size:c.size,updatedAt:c.mtime.toISOString(),content:i}},remove(o,s){try{let i=t(o,s);return z.existsSync(i)?(z.unlinkSync(i),!0):!1}catch{return!1}}}}function Nw(r){r?.workdir&&(Et=r.workdir),Mw(),or(Et);let e=[];e.push(bd()),e.push(kd(void 0,{onTaskCreated:l=>na?.onTaskCreated?.(l),onTaskCompleted:l=>na?.onTaskCompleted?.(l)})),e.push(ju({askUser:async l=>Ju?.(l)??null})),e.push(Ed({onProgress:r?.onExecProgress,interpretExitCode:(l,u)=>{if(l===127)return"command not found";if(l===126)return"permission denied";if(l===137)return"killed (SIGKILL / OOM)";if(l===143)return"terminated (SIGTERM)";if(l===130)return"interrupted (Ctrl+C)"}}));let t=Sw(),n=xw(),o=Rw(),s=_w();e.push(Ld(t)),e.push(Ud(n)),e.push(Nd(o)),e.push(Wi(s)),e.push(Gd(s)),e.push(Bd(Cw())),e.push(Yd(Ow())),e.push(Qd($w()));let i=Uw();e.push(Zd(i));let a=r?.log??{info:()=>{},warn:()=>{}};e.push(eu(gu({log:a}))),e.push(bu());let c={invokeTool:async(l,u,p)=>{let g=Me(l);if(!g)return{result:"",error:`Unknown tool: ${l}`};try{let f=await g.execute(`wf_${Date.now()}`,u,p);return{result:f.content.map(y=>y.text??"").join(`
296
- `),error:f.details?.error}}catch(f){return{result:"",error:f.message}}},getCwd:()=>Et};e.push(wu(c)),e.push(vu({sleep:(l,u)=>new Promise(p=>{let g=Date.now(),f=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-g)/1e3),interrupted:!1})},l),m=()=>{clearTimeout(f),p({sleptSeconds:Math.round((Date.now()-g)/1e3),interrupted:!0,interruptReason:"aborted"})};u.addEventListener("abort",m,{once:!0}),u.aborted&&(clearTimeout(f),m())})})),e.push(xu({searchTools:async(l,u)=>{let p=u?.maxResults??5,g=pt(),f=l.toLowerCase().split(/\s+/).filter(Boolean),m=[],y=[];for(let A of f)A.startsWith("+")&&A.length>1?m.push(A.slice(1)):y.push(A);let k=[...m,...y],b=A=>A.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:g.map(A=>{let $=Me(A),D=b(A),B=($?.description??"").toLowerCase(),v=($?.searchHint??"").toLowerCase();if(m.length>0){let T=`${D.join(" ")} ${B} ${v}`;if(!m.every(V=>T.includes(V)))return null}let oe=0;for(let T of k){let E=0;D.some(V=>V===T)?E=10:D.some(V=>V.includes(T))?E=5:A.toLowerCase().includes(T)&&(E=3),v&&new RegExp(`\\b${T}`,"i").test(v)&&(E+=4),new RegExp(`\\b${T}`,"i").test(B)&&(E+=2),oe+=E}return{name:A,description:$?.description??"",searchHint:$?.searchHint,score:oe}}).filter(A=>A!==null&&A.score>0).sort((A,$)=>$.score-A.score).slice(0,p),query:l,totalDeferred:g.length}},activateTool:async l=>yd(l)})),e.push({...Ru({generateImage:async l=>{let u=await Ke({mediaType:"image",model:"",prompt:l.prompt,purpose:l.purpose,style:l.style,size:l.size,imageUrl:l.imageUrl,n:l.n,quality:l.quality,seed:l.seed});return{mediaUrls:u.mediaUrls,model:u.model,size:u.size,durationMs:u.durationMs}}}),isEnabled:()=>Je("image")}),e.push({..._u({textToSpeech:async l=>{let u=await Ke({mediaType:"tts",model:"",prompt:"",text:l.text,channel:l.channel,voice:l.voice,speed:l.speed});return{audioPath:"",provider:u.model,mediaUrls:u.mediaUrls}}}),isEnabled:()=>Je("tts")}),e.push({...Cu({generateVideo:async l=>{let u=await Ke({mediaType:"video",model:"",prompt:l.prompt,purpose:l.purpose,style:l.style,imageUrl:l.imageUrl,referenceVideos:l.referenceVideos,referenceAudios:l.referenceAudios,generateAudio:l.generateAudio,aspectRatio:l.aspectRatio,duration:l.duration,resolution:l.resolution,fps:l.fps,seed:l.seed,cameraFixed:l.cameraFixed,returnLastFrame:l.returnLastFrame,draft:l.draft,serviceTier:l.serviceTier,callbackUrl:l.callbackUrl,safetyIdentifier:l.safetyIdentifier,executionExpiresAfterSeconds:l.executionExpiresAfterSeconds,videoTools:l.videoTools});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs,lastFrameUrl:u.lastFrameUrl,taskId:u.taskId}}}),isEnabled:()=>Je("video")}),e.push({...Au({generateMusic:async l=>{let u=await Ke({mediaType:"music",model:"",prompt:l.prompt,purpose:l.purpose,style:l.style,lyrics:l.lyrics,duration:l.duration,isInstrumental:l.isInstrumental,audioUrl:l.audioUrl,audioFormat:l.audioFormat});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}},generateLyrics:async l=>{let u=gt.music;if(!u||!se)return"";let p=se.getTransport(u.provider);if(!(p instanceof Rt))return"";let g=ye[u.provider];return g?p.generateLyrics(l,g):""}}),isEnabled:()=>Je("music")}),e.push({...Iu({editVideo:async l=>{let u=await Ke({mediaType:"video",model:"",prompt:l.prompt,operation:"edit",sourceVideos:l.sourceVideos,referenceImages:l.referenceImages,duration:l.duration,aspectRatio:l.aspectRatio,resolution:l.resolution});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Zi("video","edit")}),e.push({...Pu({mergeVideos:async l=>{let u=[`merge ${l.clips.length} clips`];l.transition&&u.push(`transition: ${l.transition}${l.transitionDuration?` (${l.transitionDuration}s)`:""}`),l.subtitles&&u.push(`burn-in subtitles: ${l.subtitles}`),l.bgm&&u.push(`background music: ${l.bgm}${l.bgmVolume!==void 0?` at volume ${l.bgmVolume}`:""}`);let p=await Ke({mediaType:"video",model:"",prompt:u.join("; "),operation:"merge",sourceVideos:l.clips.map(g=>g.video),resolution:l.outputResolution,fps:l.outputFps});return{localPath:"",servePath:p.mediaUrls[0]??"",durationSec:(p.durationMs??0)/1e3,clipCount:l.clips.length,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>Zi("video","merge")}),e.push({...Mu({upscaleVideo:async l=>{let u=["upscale"];l.sharpness&&u.push(`sharpness: ${l.sharpness}`);let p=await Ke({mediaType:"video",model:"",prompt:u.join(", "),operation:"upscale",sourceVideos:[l.video],resolution:l.targetResolution??"1080p"});return{localPath:"",servePath:p.mediaUrls[0]??"",resolution:l.targetResolution??"1080p",durationSec:(p.durationMs??0)/1e3,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>Zi("video","upscale")}),e.push({...Eu({generate3D:async l=>{let u=await Ke({mediaType:"3d",model:"",prompt:l.prompt,imageUrl:l.imageUrl,outputFormat:l.outputFormat,seed:l.seed});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs,metadata:u.metadata}}}),shouldDefer:!0,isEnabled:()=>Je("3d")}),e.push({...Ou({speechToText:async l=>{let u=await Ke({mediaType:"stt",model:"",prompt:"",audioUrl:l.audioUrl,metadata:l.language?{language:l.language}:void 0});return{transcription:u.metadata?.transcription??"",model:u.model,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Je("stt")}),e.push({...Du({cloneVoice:async l=>{let u=await Ke({mediaType:"voice_clone",model:"",prompt:"",text:l.text,audioUrl:l.sampleAudioUrl,speed:l.speed});return{mediaUrls:u.mediaUrls,model:u.model,voiceId:u.metadata?.voiceId,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Je("voice_clone")}),e.push({...Lu({cancelTask:async l=>{let u=l.provider??"doubao";if(!se)return{ok:!1,message:"Media client not configured."};let p=se.getTransport(u);if(!p)return{ok:!1,message:`No transport for provider: ${u}`};let g=ye[u];if(!g)return{ok:!1,message:`No API key for provider: ${u}`};try{return"deleteVideoTask"in p&&typeof p.deleteVideoTask=="function"?(await p.deleteVideoTask(l.taskId,g),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${u} does not support task cancellation.`}}catch(f){return{ok:!1,message:f instanceof Error?f.message:String(f)}}}}),shouldDefer:!0,isEnabled:()=>Je("video")||Je("3d")});let d=ar();return e.push({...$u({uploadFile:async l=>{if(!d)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");let u=Se(l.filePath);if(!z.existsSync(u))throw new Error(`File not found: ${u}`);let p=z.statSync(u);if(p.size>100*1024*1024)throw new Error(`File too large (${(p.size/1024/1024).toFixed(1)} MB). Max: 100 MB.`);let g=await z.promises.readFile(u),f=Z.basename(u);if(d.type==="gemini"){let S=lr(),A=ye.google,$=Z.extname(u).toLowerCase(),D=vw[$]??"application/octet-stream",B=await S.uploadFile(Buffer.from(g),A,{mimeType:D,displayName:f});if(B.state==="PROCESSING"){let v=await S.waitForProcessing(B.name,A);return{fileId:v.name,url:v.uri,filename:f,bytes:p.size,provider:"google"}}return{fileId:B.name,url:B.uri,filename:f,bytes:p.size,provider:"google"}}let m=new Blob([g]),y=se.getTransport(d.id),k=ye[d.id];if(!(y instanceof Ue))throw new Error(`File upload only supported via Volcengine or Google provider. Current: ${d.id}`);let b=await y.uploadFile(m,k,{purpose:l.purpose??"media_reference",filename:f}),x;try{let S=await y.getFile(b.id,k);typeof S.url=="string"&&S.url&&(x=S.url)}catch{}return{fileId:b.id,url:x,filename:f,bytes:p.size,provider:d.id}}}),shouldDefer:!0,isEnabled:()=>!!ar()}),e.push({...Uu({queryFile:async l=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let f=lr(),m=ye.google,y=await f.getFile(l.fileId,m);return{id:y.name,filename:y.displayName??"",bytes:Number(y.sizeBytes??0),status:y.state?.toLowerCase()??"unknown",createdAt:y.createTime,url:y.uri}}let u=se.getTransport(d.id),p=ye[d.id];if(!(u instanceof Ue))throw new Error("File query only supported via Volcengine or Google provider.");let g=await u.getFile(l.fileId,p);return{id:String(g.id??l.fileId),filename:String(g.filename??""),bytes:Number(g.bytes??0),status:String(g.status??"unknown"),createdAt:g.created_at?String(g.created_at):void 0,url:g.url?String(g.url):void 0}},listFiles:async l=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let m=lr(),y=ye.google;return(await m.listFiles(y,{pageSize:l.limit??10})).files.map(b=>({id:b.name,filename:b.displayName??"",bytes:Number(b.sizeBytes??0),status:b.state?.toLowerCase()??"unknown",createdAt:b.createTime,url:b.uri}))}let u=se.getTransport(d.id),p=ye[d.id];if(!(u instanceof Ue))throw new Error("File list only supported via Volcengine or Google provider.");return((await u.listFiles(p,{limit:l.limit??10})).data??[]).map(m=>({id:String(m.id??""),filename:String(m.filename??""),bytes:Number(m.bytes??0),status:String(m.status??"unknown"),createdAt:m.created_at?String(m.created_at):void 0,url:m.url?String(m.url):void 0}))}}),shouldDefer:!0,isEnabled:()=>!!ar()}),e.push({...Nu({deleteFile:async l=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let g=lr(),f=ye.google;await g.deleteFile(l.fileId,f);return}let u=se.getTransport(d.id),p=ye[d.id];if(!(u instanceof Ue))throw new Error("File delete only supported via Volcengine or Google provider.");await u.deleteFile(l.fileId,p)}}),shouldDefer:!0,isEnabled:()=>!!ar()}),hd(e),r?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(l=>l.isEnabled?.()!==!1).length} enabled): ${pt().join(", ")}`),e}var tp=Nw;function Ot(r){Et=r,or(r)}import{spawn as jw}from"node:child_process";import{createInterface as Fw}from"node:readline";var cr=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=jw(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=Fw({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=Bw(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,o,s)=>this.executeAsTool(t.name,o,s)}))}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,t,n){try{let o=await this.callTool(e,t,n);return{content:[{type:"text",text:o.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
294
+ `))}async function cp(r,e,t){let n=ie.getTransport(r);if(!n)return{ok:!1,error:"transport not available"};let o=ke[r];if(!o)return{ok:!1,error:"no API key"};try{let s={...t,model:e},i=await n.generate(s,o);i.billingUnit||(t.mediaType==="tts"&&t.text?(i.billingUnit="per_character",i.billingQuantity=t.text.length):(t.mediaType==="video"||t.mediaType==="music")&&t.duration?(i.billingUnit="per_second",i.billingQuantity=t.duration):(i.billingUnit="per_call",i.billingQuantity=1));let a=i.model??s.model,c=i.billingUnit??"per_call",d=i.billingQuantity??1;return up?.(a,c,d),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function et(r){if(!ie)return!1;let e=yt[r];if(!e)return!1;let t=ie.getTransport(e.provider),n=ke[e.provider];return!!(t&&n)}function sa(r,e){if(!et(r))return!1;let t=yt[r],n=ie.resolveModelById(t.provider,t.model,r);if(!n)return!1;let o=n.modelInfo.mediaCapabilities;return!o||!("operations"in o)||!o.operations?!0:o.operations.includes(e)}function ur(){if(!ie)return;for(let[,e]of Object.entries(yt)){if(!e)continue;let t=ie.getTransport(e.provider),n=ke[e.provider];if(t instanceof je&&n)return{id:e.provider,type:"volcengine"}}if(ke.google)return{id:"google",type:"gemini"}}var ia;function pr(){return ia||(ia=new _n({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),ia}var Nt=process.cwd();function _e(r){return Z.isAbsolute(r)?Z.normalize(r):Z.resolve(Nt,r)}var Fw=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),bp=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),Bw={".pdf":"application/pdf",".txt":"text/plain",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/plain",".json":"application/json",".xml":"application/xml",".csv":"text/csv",".md":"text/markdown",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".mp4":"video/mp4",".webm":"video/webm",".avi":"video/x-msvideo",".mov":"video/quicktime",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Ww(){return{resolvePath:_e,async readFile(r){let e=_e(r),t=Z.extname(e).toLowerCase();return bp.has(t)?{type:"binary",mimeType:"application/octet-stream"}:Fw.has(t)?{type:"image",localPath:e,mimeType:t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg"}:{type:"text",text:await z.promises.readFile(e,"utf8")}},validatePath(r){let e=_e(r);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:dp&&Yu(e)?"Blocked: reading sensitive file in group chat mode":null}}}function Gw(){return{resolvePath:_e,async writeFile(r,e){let t=_e(r);await z.promises.mkdir(Z.dirname(t),{recursive:!0}),await z.promises.writeFile(t,e,"utf8")}}}function Hw(){return{resolvePath:_e,async readFile(r){let e=_e(r);return z.promises.readFile(e,"utf8")},async writeFile(r,e){let t=_e(r);await z.promises.mkdir(Z.dirname(t),{recursive:!0}),await z.promises.writeFile(t,e,"utf8")}}}function Vw(){return{resolvePath:_e,async readFile(r){let e=_e(r);return z.promises.readFile(e,"utf8")},async writeFile(r,e){let t=_e(r);await z.promises.mkdir(Z.dirname(t),{recursive:!0}),await z.promises.writeFile(t,e,"utf8")},async deleteFile(r){let e=_e(r);await z.promises.unlink(e)},async fileExists(r){let e=_e(r);try{return await z.promises.access(e),!0}catch{return!1}}}}function zw(){return{resolvePath:_e,async glob(r,e){let t=e.cwd||Nt,n=e.limit||1e3,o=[],s=!1,i=r.replace(/\\/g,"/").split("/"),a=i.some(l=>l==="**"),c=i[i.length-1]??"*",d=kp(c);try{await ua(t,async l=>{if(o.length>=n)return s=!0,!1;let u=Z.basename(l);return d.test(u)&&o.push(l),!0},a?1/0:1)}catch{}return{files:o,truncated:s}},async grep(r,e){let t=e.cwd||Nt;try{return await qw(r,t,e)}catch{return await Xw(r,t,e)}}}}function kp(r){let e=r.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(t,n)=>"("+n.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var Kw=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function ua(r,e,t,n=0,o=""){if(n>t)return;let s;try{s=await z.promises.readdir(r,{withFileTypes:!0})}catch{return}for(let i of s){let a=o?`${o}/${i.name}`:i.name;if(i.isDirectory()){if(Kw.has(i.name))continue;await ua(Z.join(r,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function qw(r,e,t){return new Promise((n,o)=>{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(r),s.push("."),Ow("rg",s,{cwd:e,maxBuffer:10*1024*1024,timeout:3e4},(i,a)=>{if(i&&!("killed"in i&&i.killed)&&i.code!==1){o(i);return}let c=[];for(let p of a.split(`
295
+ `))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&c.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let d=t.headLimit??250,l=t.offset??0,u=c.slice(l,l+d);n({matches:u,truncated:c.length>l+d})})})}async function Xw(r,e,t){let n=new RegExp(r,t.caseInsensitive?"i":""),o=t.headLimit??250,s=t.offset??0,i=t.fileGlob?kp(t.fileGlob):null,a=[],c=!1;return await ua(e,async d=>{if(a.length>=s+o+1)return c=!0,!1;if(i&&!i.test(Z.basename(d)))return!0;let l=Z.extname(d).toLowerCase();if(bp.has(l))return!0;try{let p=(await z.promises.readFile(Z.join(e,d),"utf8")).split(`
296
+ `);for(let m=0;m<p.length;m++)if(n.test(p[m])&&(a.push({path:d,line:m+1,text:p[m].slice(0,500)}),a.length>=s+o+1))return c=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+o),truncated:c}}var lp=!1;function Yw(){if(!lp)if(lp=!0,tr()){let r=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";On(Gi(r))}else if(process.platform==="win32"){let r=Jw();On(dr(r))}else{let r=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";On(dr(r))}}function Jw(){let r=process.env.QLOGICAGENT_BASH_PATH;if(r&&z.existsSync(r))return r;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],t=process.env.ProgramFiles?Z.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let n of e)if(z.existsSync(n))return n;return"bash"}function Qw(){return{async fetchUrl(r){let e=new AbortController,t=setTimeout(()=>e.abort(),3e4);try{let n=await fetch(r.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 o=n.headers.get("content-type")??"",s=await n.text();return r.maxChars&&s.length>r.maxChars&&(s=s.slice(0,r.maxChars)),o.includes("html")&&r.extractMode!=="json"&&(s=Zw(s)),{content:s,title:ev(s)}}finally{clearTimeout(t)}}}}function Zw(r){return r.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 ev(r){return r.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function tv(){let r=async(e,t)=>{let n=process.env.SEARXNG_BASE_URL?.trim();if(!n)return{query:e,results:[],totalResults:0};let o=t?.maxResults??10,s=new URL("/search",n);s.searchParams.set("q",e),s.searchParams.set("format","json"),s.searchParams.set("pageno","1");let i=new AbortController,a=setTimeout(()=>i.abort(),15e3);try{let c=await fetch(s.toString(),{signal:i.signal,headers:{Accept:"application/json"}});if(!c.ok)return{query:e,results:[]};let d=await c.json(),l=(d.results??[]).slice(0,o).map(u=>({title:u.title??"",url:u.url??"",snippet:u.content??""}));if(t?.allowedDomains?.length){let u=new Set(t.allowedDomains.map(p=>p.toLowerCase()));return{query:e,results:l.filter(p=>{try{return u.has(new URL(p.url).hostname.toLowerCase())}catch{return!1}})}}if(t?.blockedDomains?.length){let u=new Set(t.blockedDomains.map(p=>p.toLowerCase()));return{query:e,results:l.filter(p=>{try{return!u.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:l,totalResults:d.number_of_results}}finally{clearTimeout(a)}};return{search:(e,t)=>qu(pp,r)(e,t)}}function nv(){let r=Z.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(o){return Z.join(r,"projects",o,".instructions")}function t(o,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(o),a=Z.resolve(i,s);if(!a.startsWith(i+Z.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(o,s){if(!z.existsSync(o))return[];let i=[];for(let a of z.readdirSync(o,{withFileTypes:!0})){let c=Z.join(o,a.name);if(a.isDirectory())i.push(...n(c,s));else if(a.isFile()&&a.name.endsWith(".md")){let d=z.statSync(c);i.push({filename:Z.relative(s,c).replace(/\\/g,"/"),path:c,size:d.size,updatedAt:d.mtime.toISOString(),content:z.readFileSync(c,"utf-8")})}}return i}return{list(o){let s=e(o);return n(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(o,s){try{let i=t(o,s);if(!z.existsSync(i))return null;let a=z.statSync(i),c=z.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:c}}catch{return null}},write(o,s,i){let a=t(o,s);z.mkdirSync(Z.dirname(a),{recursive:!0}),z.writeFileSync(a,i,"utf-8");let c=z.statSync(a);return{filename:s,path:a,size:c.size,updatedAt:c.mtime.toISOString(),content:i}},remove(o,s){try{let i=t(o,s);return z.existsSync(i)?(z.unlinkSync(i),!0):!1}catch{return!1}}}}function ov(r){r?.workdir&&(Nt=r.workdir),Yw(),ar(Nt);let e=[];e.push(_d()),e.push(xd(void 0,{onTaskCreated:u=>ca?.onTaskCreated?.(u),onTaskCompleted:u=>ca?.onTaskCompleted?.(u)})),e.push(zu({askUser:async u=>gp?.(u)??null})),e.push(jd({onProgress:r?.onExecProgress,interpretExitCode:(u,p)=>{if(u===127)return"command not found";if(u===126)return"permission denied";if(u===137)return"killed (SIGKILL / OOM)";if(u===143)return"terminated (SIGTERM)";if(u===130)return"interrupted (Ctrl+C)"}}));let t=Ww(),n=Gw(),o=Hw(),s=Vw();e.push(Wd(t)),e.push(Hd(n)),e.push(Vd(o)),e.push(qi(s)),e.push(Xd(s)),e.push(qd(zw())),e.push(ru(Qw())),e.push(su(tv()));let i=nv();e.push(iu(i));let a=r?.log??{info:()=>{},warn:()=>{}};e.push(au(wu({log:a}))),e.push(_u());let c={invokeTool:async(u,p,m)=>{let f=Oe(u);if(!f)return{result:"",error:`Unknown tool: ${u}`};try{let g=await f.execute(`wf_${Date.now()}`,p,m);return{result:g.content.map(b=>b.text??"").join(`
297
+ `),error:g.details?.error}}catch(g){return{result:"",error:g.message}}},getCwd:()=>Nt};e.push(Cu(c)),e.push(Pu({sleep:(u,p)=>new Promise(m=>{let f=Date.now(),g=setTimeout(()=>{m({sleptSeconds:Math.round((Date.now()-f)/1e3),interrupted:!1})},u),y=()=>{clearTimeout(g),m({sleptSeconds:Math.round((Date.now()-f)/1e3),interrupted:!0,interruptReason:"aborted"})};p.addEventListener("abort",y,{once:!0}),p.aborted&&(clearTimeout(g),y())})}));let d={listProjects:()=>ht(),switchProject:u=>Lt(u),onSwitched:u=>Dw?.(u)};e.push(Ku(d)),e.push(Mu({searchTools:async(u,p)=>{let m=p?.maxResults??5,f=mt(),g=u.toLowerCase().split(/\s+/).filter(Boolean),y=[],b=[];for(let O of g)O.startsWith("+")&&O.length>1?y.push(O.slice(1)):b.push(O);let k=[...y,...b],S=O=>O.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:f.map(O=>{let L=Oe(O),B=S(O),v=(L?.description??"").toLowerCase(),ee=(L?.searchHint??"").toLowerCase();if(y.length>0){let E=`${B.join(" ")} ${v} ${ee}`;if(!y.every(re=>E.includes(re)))return null}let T=0;for(let E of k){let V=0;B.some(re=>re===E)?V=10:B.some(re=>re.includes(E))?V=5:O.toLowerCase().includes(E)&&(V=3),ee&&new RegExp(`\\b${E}`,"i").test(ee)&&(V+=4),new RegExp(`\\b${E}`,"i").test(v)&&(V+=2),T+=V}return{name:O,description:L?.description??"",searchHint:L?.searchHint,score:T}}).filter(O=>O!==null&&O.score>0).sort((O,L)=>L.score-O.score).slice(0,m),query:u,totalDeferred:f.length}},activateTool:async u=>Rd(u)})),e.push({...Eu({generateImage:async u=>{let p=await Ze({mediaType:"image",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,size:u.size,imageUrl:u.imageUrl,n:u.n,quality:u.quality,seed:u.seed});return{mediaUrls:p.mediaUrls,model:p.model,size:p.size,durationMs:p.durationMs}}}),isEnabled:()=>et("image")}),e.push({...Ou({textToSpeech:async u=>{let p=await Ze({mediaType:"tts",model:"",prompt:"",text:u.text,channel:u.channel,voice:u.voice,speed:u.speed});return{audioPath:"",provider:p.model,mediaUrls:p.mediaUrls}}}),isEnabled:()=>et("tts")}),e.push({...Du({generateVideo:async u=>{let p=await Ze({mediaType:"video",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,imageUrl:u.imageUrl,referenceVideos:u.referenceVideos,referenceAudios:u.referenceAudios,generateAudio:u.generateAudio,aspectRatio:u.aspectRatio,duration:u.duration,resolution:u.resolution,fps:u.fps,seed:u.seed,cameraFixed:u.cameraFixed,returnLastFrame:u.returnLastFrame,draft:u.draft,serviceTier:u.serviceTier,callbackUrl:u.callbackUrl,safetyIdentifier:u.safetyIdentifier,executionExpiresAfterSeconds:u.executionExpiresAfterSeconds,videoTools:u.videoTools});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs,lastFrameUrl:p.lastFrameUrl,taskId:p.taskId}}}),isEnabled:()=>et("video")}),e.push({...Lu({generateMusic:async u=>{let p=await Ze({mediaType:"music",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,lyrics:u.lyrics,duration:u.duration,isInstrumental:u.isInstrumental,audioUrl:u.audioUrl,audioFormat:u.audioFormat});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs}},generateLyrics:async u=>{let p=yt.music;if(!p||!ie)return"";let m=ie.getTransport(p.provider);if(!(m instanceof At))return"";let f=ke[p.provider];return f?m.generateLyrics(u,f):""}}),isEnabled:()=>et("music")}),e.push({...Nu({editVideo:async u=>{let p=await Ze({mediaType:"video",model:"",prompt:u.prompt,operation:"edit",sourceVideos:u.sourceVideos,referenceImages:u.referenceImages,duration:u.duration,aspectRatio:u.aspectRatio,resolution:u.resolution});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>sa("video","edit")}),e.push({...Uu({mergeVideos:async u=>{let p=[`merge ${u.clips.length} clips`];u.transition&&p.push(`transition: ${u.transition}${u.transitionDuration?` (${u.transitionDuration}s)`:""}`),u.subtitles&&p.push(`burn-in subtitles: ${u.subtitles}`),u.bgm&&p.push(`background music: ${u.bgm}${u.bgmVolume!==void 0?` at volume ${u.bgmVolume}`:""}`);let m=await Ze({mediaType:"video",model:"",prompt:p.join("; "),operation:"merge",sourceVideos:u.clips.map(f=>f.video),resolution:u.outputResolution,fps:u.outputFps});return{localPath:"",servePath:m.mediaUrls[0]??"",durationSec:(m.durationMs??0)/1e3,clipCount:u.clips.length,mediaUrls:m.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>sa("video","merge")}),e.push({...$u({upscaleVideo:async u=>{let p=["upscale"];u.sharpness&&p.push(`sharpness: ${u.sharpness}`);let m=await Ze({mediaType:"video",model:"",prompt:p.join(", "),operation:"upscale",sourceVideos:[u.video],resolution:u.targetResolution??"1080p"});return{localPath:"",servePath:m.mediaUrls[0]??"",resolution:u.targetResolution??"1080p",durationSec:(m.durationMs??0)/1e3,mediaUrls:m.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>sa("video","upscale")}),e.push({...ju({generate3D:async u=>{let p=await Ze({mediaType:"3d",model:"",prompt:u.prompt,imageUrl:u.imageUrl,outputFormat:u.outputFormat,seed:u.seed});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs,metadata:p.metadata}}}),shouldDefer:!0,isEnabled:()=>et("3d")}),e.push({...Fu({speechToText:async u=>{let p=await Ze({mediaType:"stt",model:"",prompt:"",audioUrl:u.audioUrl,metadata:u.language?{language:u.language}:void 0});return{transcription:p.metadata?.transcription??"",model:p.model,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>et("stt")}),e.push({...Bu({cloneVoice:async u=>{let p=await Ze({mediaType:"voice_clone",model:"",prompt:"",text:u.text,audioUrl:u.sampleAudioUrl,speed:u.speed});return{mediaUrls:p.mediaUrls,model:p.model,voiceId:p.metadata?.voiceId,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>et("voice_clone")}),e.push({...Wu({cancelTask:async u=>{let p=u.provider??"doubao";if(!ie)return{ok:!1,message:"Media client not configured."};let m=ie.getTransport(p);if(!m)return{ok:!1,message:`No transport for provider: ${p}`};let f=ke[p];if(!f)return{ok:!1,message:`No API key for provider: ${p}`};try{return"deleteVideoTask"in m&&typeof m.deleteVideoTask=="function"?(await m.deleteVideoTask(u.taskId,f),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${p} does not support task cancellation.`}}catch(g){return{ok:!1,message:g instanceof Error?g.message:String(g)}}}}),shouldDefer:!0,isEnabled:()=>et("video")||et("3d")});let l=ur();return e.push({...Gu({uploadFile:async u=>{if(!l)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");let p=_e(u.filePath);if(!z.existsSync(p))throw new Error(`File not found: ${p}`);let m=z.statSync(p);if(m.size>100*1024*1024)throw new Error(`File too large (${(m.size/1024/1024).toFixed(1)} MB). Max: 100 MB.`);let f=await z.promises.readFile(p),g=Z.basename(p);if(l.type==="gemini"){let P=pr(),O=ke.google,L=Z.extname(p).toLowerCase(),B=Bw[L]??"application/octet-stream",v=await P.uploadFile(Buffer.from(f),O,{mimeType:B,displayName:g});if(v.state==="PROCESSING"){let ee=await P.waitForProcessing(v.name,O);return{fileId:ee.name,url:ee.uri,filename:g,bytes:m.size,provider:"google"}}return{fileId:v.name,url:v.uri,filename:g,bytes:m.size,provider:"google"}}let y=new Blob([f]),b=ie.getTransport(l.id),k=ke[l.id];if(!(b instanceof je))throw new Error(`File upload only supported via Volcengine or Google provider. Current: ${l.id}`);let S=await b.uploadFile(y,k,{purpose:u.purpose??"media_reference",filename:g}),R;try{let P=await b.getFile(S.id,k);typeof P.url=="string"&&P.url&&(R=P.url)}catch{}return{fileId:S.id,url:R,filename:g,bytes:m.size,provider:l.id}}}),shouldDefer:!0,isEnabled:()=>!!ur()}),e.push({...Hu({queryFile:async u=>{if(!l)throw new Error("No file API provider available.");if(l.type==="gemini"){let g=pr(),y=ke.google,b=await g.getFile(u.fileId,y);return{id:b.name,filename:b.displayName??"",bytes:Number(b.sizeBytes??0),status:b.state?.toLowerCase()??"unknown",createdAt:b.createTime,url:b.uri}}let p=ie.getTransport(l.id),m=ke[l.id];if(!(p instanceof je))throw new Error("File query only supported via Volcengine or Google provider.");let f=await p.getFile(u.fileId,m);return{id:String(f.id??u.fileId),filename:String(f.filename??""),bytes:Number(f.bytes??0),status:String(f.status??"unknown"),createdAt:f.created_at?String(f.created_at):void 0,url:f.url?String(f.url):void 0}},listFiles:async u=>{if(!l)throw new Error("No file API provider available.");if(l.type==="gemini"){let y=pr(),b=ke.google;return(await y.listFiles(b,{pageSize:u.limit??10})).files.map(S=>({id:S.name,filename:S.displayName??"",bytes:Number(S.sizeBytes??0),status:S.state?.toLowerCase()??"unknown",createdAt:S.createTime,url:S.uri}))}let p=ie.getTransport(l.id),m=ke[l.id];if(!(p instanceof je))throw new Error("File list only supported via Volcengine or Google provider.");return((await p.listFiles(m,{limit:u.limit??10})).data??[]).map(y=>({id:String(y.id??""),filename:String(y.filename??""),bytes:Number(y.bytes??0),status:String(y.status??"unknown"),createdAt:y.created_at?String(y.created_at):void 0,url:y.url?String(y.url):void 0}))}}),shouldDefer:!0,isEnabled:()=>!!ur()}),e.push({...Vu({deleteFile:async u=>{if(!l)throw new Error("No file API provider available.");if(l.type==="gemini"){let f=pr(),g=ke.google;await f.deleteFile(u.fileId,g);return}let p=ie.getTransport(l.id),m=ke[l.id];if(!(p instanceof je))throw new Error("File delete only supported via Volcengine or Google provider.");await p.deleteFile(u.fileId,m)}}),shouldDefer:!0,isEnabled:()=>!!ur()}),Sd(e),r?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(u=>u.isEnabled?.()!==!1).length} enabled): ${mt().join(", ")}`),e}var Tp=ov;function Ut(r){Nt=r,ar(r)}import{spawn as rv}from"node:child_process";import{createInterface as sv}from"node:readline";var mr=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=rv(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=sv({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=iv(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,o,s)=>this.executeAsTool(t.name,o,s)}))}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,t,n){try{let o=await this.callTool(e,t,n);return{content:[{type:"text",text:o.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
297
298
  `)||"(no text output)"}],...o.isError?{details:{error:"mcp_tool_error"}}:{}}}catch(o){let s=o instanceof Error?o.message:String(o);return{content:[{type:"text",text:`MCP tool error: ${s}`}],details:{error:s}}}}sendRequest(e,t,n=3e4,o){return new Promise((s,i)=>{if(o?.aborted){i(new Error("Aborted"));return}let a=this.nextId++,c={jsonrpc:"2.0",id:a,method:e,params:t},d=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${n}ms`))},n),l=()=>{clearTimeout(d),this.pending.delete(a)};o?.addEventListener("abort",()=>{l(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:u=>{l(),u.error?i(new Error(`MCP error ${u.error.code}: ${u.error.message}`)):s(u.result)},reject:u=>{l(),i(u)}}),this.writeLine(JSON.stringify(c))})}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+`
298
- `)}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 o=n.id,s=this.pending.get(o);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 Bw(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as Gw}from"node:crypto";var dr=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,o){let s=Gw(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,c=setTimeout(()=>a.abort(),n);o&&o.addEventListener("abort",()=>a.abort(),{once:!0});try{let d={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(d["Mcp-Session-Id"]=this.sessionId);let l=await fetch(this.config.url,{method:"POST",headers:d,body:JSON.stringify(i),signal:a.signal}),u=l.headers.get("mcp-session-id");if(u&&(this.sessionId=u),!l.ok)throw new Error(`MCP HTTP error ${l.status}: ${l.statusText}`);if((l.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(l,s);let g=await l.json();if(g.error)throw new Error(`MCP error ${g.error.code}: ${g.error.message}`);return g.result}finally{clearTimeout(c)}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t},o={"Content-Type":"application/json",...this.config.headers};this.sessionId&&(o["Mcp-Session-Id"]=this.sessionId),await fetch(this.config.url,{method:"POST",headers:o,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 o=n.getReader(),s=new TextDecoder,i="";try{for(;;){let{done:a,value:c}=await o.read();if(a)break;i+=s.decode(c,{stream:!0});let d=i.split(`
299
- `);i=d.pop()??"";for(let l of d){if(!l.startsWith("data: "))continue;let u=l.slice(6).trim();if(u)try{let p=JSON.parse(u);if("method"in p&&p.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(p.id===t){if(p.error)throw new Error(`MCP error ${p.error.code}: ${p.error.message}`);return p.result}}catch(p){if(p instanceof Error&&p.message.startsWith("MCP error"))throw p}}}}finally{o.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${Hw(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(o,s,i)=>{try{let a=await t.callTool(e.name,s,i);return{content:[{type:"text",text:(a.content??[]).filter(l=>l.type==="text"&&l.text).map(l=>l.text).join(`
300
- `)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let c=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${c}`}],details:{type:"mcp",error:c}}}}}}};function Hw(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var ur=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 o={name:t.name,url:t.url,headers:t.headers,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new dr(o))}else{if(!t.command){this.log.warn(`[mcp] server "${t.name}" is type "stdio" but has no command, skipping`);continue}let o={name:t.name,command:t.command,args:t.args,env:t.env,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new cr(o))}}}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(o){this.log.warn(`[mcp] failed to connect to ${t}: ${o instanceof Error?o.message:o}`)}});await Promise.allSettled(e)}injectTools(){this.injected=!0;for(let[e,t]of this.clients){if(!t.isConnected)continue;let n=t.toPortableTools();vi(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(([,o])=>o):Array.from(this.clients.entries());return(await Promise.all(t.map(async([o,s])=>{if(!s?.isConnected||!s.listResources)return[];try{return(await s.listResources()).map(a=>({...a,server:o}))}catch{return this.log.warn(`[mcp] failed to list resources from ${o}`),[]}}))).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 pt())s.startsWith(n)&&Xo(s);let o=t.toPortableTools();vi(o),this.log.info(`[mcp] re-injected ${o.length} tools from ${e}`)}};function ia(r){if(!r||typeof r!="object")return[];let e=r,t=[],n=e.mcpServers??e.servers??e;for(let[o,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){t.push({name:o,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:o,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 Ww={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function np(r){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:Ww,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,t)=>{let n=r();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let o=await n.listResources(t.server);if(o.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 o){let c=s.get(a.server)??[];c.push(a),s.set(a.server,c)}let i=[];for(let[a,c]of s){i.push(`Server: ${a} (${c.length} resources)`);for(let d of c){let l=d.mimeType?` [${d.mimeType}]`:"",u=d.description?` \u2014 ${d.description}`:"";i.push(` ${d.name}: ${d.uri}${l}${u}`)}i.push("")}return{content:[{type:"text",text:i.join(`
301
- `).trim()}],details:{type:"list_mcp_resources",count:o.length}}}}}var zw={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 op(r){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:zw,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,t)=>{let n=r();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let o=await n.readResource(t.server,t.uri);if(o.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 o)if(i.text){let a=i.mimeType?` (${i.mimeType})`:"";s.push({type:"text",text:`--- ${i.uri}${a} ---
299
+ `)}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 o=n.id,s=this.pending.get(o);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 iv(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as av}from"node:crypto";var gr=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,o){let s=av(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,c=setTimeout(()=>a.abort(),n);o&&o.addEventListener("abort",()=>a.abort(),{once:!0});try{let d={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(d["Mcp-Session-Id"]=this.sessionId);let l=await fetch(this.config.url,{method:"POST",headers:d,body:JSON.stringify(i),signal:a.signal}),u=l.headers.get("mcp-session-id");if(u&&(this.sessionId=u),!l.ok)throw new Error(`MCP HTTP error ${l.status}: ${l.statusText}`);if((l.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(l,s);let m=await l.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(c)}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t},o={"Content-Type":"application/json",...this.config.headers};this.sessionId&&(o["Mcp-Session-Id"]=this.sessionId),await fetch(this.config.url,{method:"POST",headers:o,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 o=n.getReader(),s=new TextDecoder,i="";try{for(;;){let{done:a,value:c}=await o.read();if(a)break;i+=s.decode(c,{stream:!0});let d=i.split(`
300
+ `);i=d.pop()??"";for(let l of d){if(!l.startsWith("data: "))continue;let u=l.slice(6).trim();if(u)try{let p=JSON.parse(u);if("method"in p&&p.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(p.id===t){if(p.error)throw new Error(`MCP error ${p.error.code}: ${p.error.message}`);return p.result}}catch(p){if(p instanceof Error&&p.message.startsWith("MCP error"))throw p}}}}finally{o.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${cv(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(o,s,i)=>{try{let a=await t.callTool(e.name,s,i);return{content:[{type:"text",text:(a.content??[]).filter(l=>l.type==="text"&&l.text).map(l=>l.text).join(`
301
+ `)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let c=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${c}`}],details:{type:"mcp",error:c}}}}}}};function cv(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var fr=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 o={name:t.name,url:t.url,headers:t.headers,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new gr(o))}else{if(!t.command){this.log.warn(`[mcp] server "${t.name}" is type "stdio" but has no command, skipping`);continue}let o={name:t.name,command:t.command,args:t.args,env:t.env,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new mr(o))}}}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(o){this.log.warn(`[mcp] failed to connect to ${t}: ${o instanceof Error?o.message:o}`)}});await Promise.allSettled(e)}injectTools(){this.injected=!0;for(let[e,t]of this.clients){if(!t.isConnected)continue;let n=t.toPortableTools();xi(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(([,o])=>o):Array.from(this.clients.entries());return(await Promise.all(t.map(async([o,s])=>{if(!s?.isConnected||!s.listResources)return[];try{return(await s.listResources()).map(a=>({...a,server:o}))}catch{return this.log.warn(`[mcp] failed to list resources from ${o}`),[]}}))).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 mt())s.startsWith(n)&&er(s);let o=t.toPortableTools();xi(o),this.log.info(`[mcp] re-injected ${o.length} tools from ${e}`)}};function pa(r){if(!r||typeof r!="object")return[];let e=r,t=[],n=e.mcpServers??e.servers??e;for(let[o,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){t.push({name:o,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:o,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 lv={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function wp(r){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:lv,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,t)=>{let n=r();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let o=await n.listResources(t.server);if(o.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 o){let c=s.get(a.server)??[];c.push(a),s.set(a.server,c)}let i=[];for(let[a,c]of s){i.push(`Server: ${a} (${c.length} resources)`);for(let d of c){let l=d.mimeType?` [${d.mimeType}]`:"",u=d.description?` \u2014 ${d.description}`:"";i.push(` ${d.name}: ${d.uri}${l}${u}`)}i.push("")}return{content:[{type:"text",text:i.join(`
302
+ `).trim()}],details:{type:"list_mcp_resources",count:o.length}}}}}var dv={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 vp(r){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:dv,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,t)=>{let n=r();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let o=await n.readResource(t.server,t.uri);if(o.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 o)if(i.text){let a=i.mimeType?` (${i.mimeType})`:"";s.push({type:"text",text:`--- ${i.uri}${a} ---
302
303
  ${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"}) ---
303
- [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:o.length}}}catch(o){return{content:[{type:"text",text:`Error reading resource: ${o.message}`}],details:{error:o.message}}}}}}import*as Xe from"node:fs";import*as On from"node:path";import{pathToFileURL as Vw}from"node:url";var rp={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var pr=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(!Xe.existsSync(e))continue;let t;try{t=Xe.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let o=On.join(e,n.name);await this.loadPlugin(n.name,o)}}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 discoverNew(){let e=new Set(this.loaded.map(n=>n.name)),t=0;for(let n of this.config.pluginDirs){if(!Xe.existsSync(n))continue;let o;try{o=Xe.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let s of o){if(!s.isDirectory()||s.name.startsWith(".")||s.name.startsWith("_")||e.has(s.name))continue;let i=On.join(n,s.name);await this.loadPlugin(s.name,i),t++}}return t>0&&this.log.info(`[plugins] discovered ${t} new plugin(s)`),t}async refreshActivations(){let e=Date.now();for(let[t,n]of this.activations){if(e-n.lastCheckAt<n.ttlMs)continue;let o;try{o=await n.checkFn()}catch(s){this.log.warn(`[plugins] ${t}: check_fn error: ${s instanceof Error?s.message:s}`),o=n.lastResult}if(n.lastCheckAt=e,o!==n.lastResult){if(n.lastResult=o,o&&!n.active){for(let s of n.tools)ve(s);n.active=!0,this.log.info(`[plugins] ${t}: reactivated (${n.tools.length} tools)`)}else if(!o&&n.active){for(let s of n.tools)Xo(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"],o=null;for(let m of n){let y=On.join(t,m);if(Xe.existsSync(y)){o=y;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,c=[],d=[],l=null,u=6e4,p={},g=On.join(t,"config.json");if(Xe.existsSync(g))try{p=JSON.parse(Xe.readFileSync(g,"utf8"))}catch{}let f={pluginName:e,registerTool:m=>{ve(m),c.push(m),s++},registerHook:(m,y)=>{let k=rp[m];if(!k){this.log.warn(`[plugins] ${e}: unknown hook phase "${m}"`);return}let b=this.config.hookRegistry.register({point:k,handler:y,label:`plugin:${e}:${m}`,priority:200});d.push(b),i++},registerSkill:m=>{this.pluginSkills.push(m),a++},getConfig:()=>p,setActivationCheck:(m,y)=>{l=m,y!==void 0&&(u=y)}};try{let y=await import(Vw(o).href);if(typeof y.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await y.register(f),l&&this.activations.set(e,{checkFn:l,ttlMs:u,lastCheckAt:Date.now(),lastResult:!0,tools:c,hookUnregisterFns:d,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(m){this.log.warn(`[plugins] ${e}: load error: ${m instanceof Error?m.message:m}`)}}};import*as de from"node:fs";import*as Dn from"node:path";function aa(){return Gl()}function sp(){return Dn.join(aa(),"installed_plugins.json")}function ip(){let r=sp();if(!de.existsSync(r))return{version:1,plugins:[]};try{return JSON.parse(de.readFileSync(r,"utf-8"))}catch{return{version:1,plugins:[]}}}function qw(r){let e=aa();de.existsSync(e)||de.mkdirSync(e,{recursive:!0}),de.writeFileSync(sp(),JSON.stringify(r,null,2),"utf-8")}function Kw(r,e){return!(e.blocklist?.includes(r)||e.allowlist&&!e.allowlist.includes(r))}async function Jw(r,e,t){let{execFile:n}=await import("node:child_process"),{promisify:o}=await import("node:util"),s=o(n),i=aa(),a=e?`${r}@${e}`:r;try{let{stdout:c}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),d=c.trim().split(`
304
- `).pop()?.trim();if(!d)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let l=Dn.join(i,d),p=d.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",g=Dn.join(i,`${r}@${p}`);de.existsSync(g)||de.mkdirSync(g,{recursive:!0}),await s("tar",["xzf",l,"-C",g,"--strip-components=1"],{timeout:3e4});try{de.unlinkSync(l)}catch{}let f=Dn.join(g,"package.json");if(de.existsSync(f))try{await s("npm",["install","--production","--no-save"],{cwd:g,timeout:12e4})}catch(m){t.warn(`[marketplace] npm install for ${r} failed: ${m.message}`)}return t.info(`[marketplace] installed ${r}@${p} from npm`),{name:r,version:p,installPath:g}}catch(c){return t.warn(`[marketplace] failed to install ${a} from npm: ${c.message}`),null}}function Xw(){return ip().plugins.filter(e=>de.existsSync(e.installPath)).map(e=>e.installPath)}async function Yw(r,e){let t=ip(),n=[];for(let o of r.enabledPlugins){let s=o.specifier.split("/").pop()??o.specifier;if(!Kw(s,r)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(c=>c.source.specifier===o.specifier&&c.source.type===o.type);if(i&&de.existsSync(i.installPath)&&(!o.version||i.version===o.version)){n.push(i.installPath);continue}let a=null;switch(o.type){case"npm":a=await Jw(o.specifier,o.version,e);break;case"git":case"url":e.warn(`[marketplace] ${o.type} source not yet implemented for "${o.specifier}"`);break}if(a){let c={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};t.plugins=t.plugins.filter(d=>!(d.source.specifier===o.specifier&&d.source.type===o.type)),t.plugins.push(c),n.push(a.installPath)}}return qw(t),n}function Qw(){let r=Wl();if(!de.existsSync(r))return null;try{return JSON.parse(de.readFileSync(r,"utf-8"))}catch{return null}}async function ap(r,e){let t=[...r],n=Xw();t.push(...n);let o=Qw();if(o&&o.enabledPlugins.length>0)try{let s=await Yw(o,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 mr=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:o,regex:s}of this.compiledPatterns)if(s.test(t))return ev(o,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:Zw(t.pattern)}))}};function la(r){if(!r||typeof r!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=r,t=[];for(let a of["allow","deny","ask"]){let c=e[a];if(Array.isArray(c))for(let d of c)typeof d=="string"&&t.push({pattern:d,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let c=a,d=c.pattern,l=c.behavior??c.action;typeof d=="string"&&typeof l=="string"&&(l==="allow"||l==="deny"||l==="ask")&&t.push({pattern:d,behavior:l,reason:typeof c.reason=="string"?c.reason:void 0,source:typeof c.source=="string"?c.source:"config"})}}let n=e.mode,o=typeof n=="string"&&tv(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&nv(s)?s:"allow";return{mode:o,rules:t,defaultBehavior:i}}function Zw(r){let t=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function ev(r,e){let t={type:"rule",rule:r};return r.behavior==="allow"?{behavior:"allow",decisionReason:t}:r.behavior==="deny"?{behavior:"deny",message:r.reason??`Tool "${e.toolName}" denied by rule "${r.pattern}"`,decisionReason:t}:{behavior:"ask",message:r.reason??`Tool "${e.toolName}" requires approval (rule "${r.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:t}}function tv(r){return r==="default"||r==="bypassPermissions"||r==="acceptEdits"||r==="dontAsk"||r==="plan"}function nv(r){return r==="allow"||r==="deny"||r==="ask"}import{randomUUID as dv}from"node:crypto";var ov=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"]),lp=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"]),rv=[/\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],cp=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 dp(r,e,t){let n=r.trim();if(!n)return{decision:"allow",reason:"empty command"};let o=Fi(n)??Bi(n)??void 0;for(let d of rv)if(d.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${d.source}`,destructiveWarning:o};for(let d of ov)if(n===d||n.startsWith(d+" "))return{decision:"allow",reason:`known safe command: ${d}`,destructiveWarning:o};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return lp.has(i)||lp.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:o}:e&&t&&e.startsWith(t)&&(cp.has(i)||cp.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:o}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:o}}function sv(r){let e=Object.keys(r).sort(),t={};for(let n of e){let o=r[n];typeof o=="string"?t[n]=o.replace(/\s+/g," ").trim():t[n]=o}return JSON.stringify(t)}function ca(r,e){return`${r}::${sv(e)}`}var iv=500,gr=class{cache=new Map;get(e,t){let n=ca(e,t),o=this.cache.get(n);if(o)return o.hitCount++,o}set(e,t,n){if(this.cache.size>=iv){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let o=ca(e,t);this.cache.set(o,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(ca(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 av=new Set(["read","search","instructions","think","task","memory","skill","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function Ln(r){return av.has(r)}var up=`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.
304
+ [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:o.length}}}catch(o){return{content:[{type:"text",text:`Error reading resource: ${o.message}`}],details:{error:o.message}}}}}}import*as tt from"node:fs";import*as Nn from"node:path";import{pathToFileURL as uv}from"node:url";var Sp={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var hr=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(!tt.existsSync(e))continue;let t;try{t=tt.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let o=Nn.join(e,n.name);await this.loadPlugin(n.name,o)}}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 discoverNew(){let e=new Set(this.loaded.map(n=>n.name)),t=0;for(let n of this.config.pluginDirs){if(!tt.existsSync(n))continue;let o;try{o=tt.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let s of o){if(!s.isDirectory()||s.name.startsWith(".")||s.name.startsWith("_")||e.has(s.name))continue;let i=Nn.join(n,s.name);await this.loadPlugin(s.name,i),t++}}return t>0&&this.log.info(`[plugins] discovered ${t} new plugin(s)`),t}async refreshActivations(){let e=Date.now();for(let[t,n]of this.activations){if(e-n.lastCheckAt<n.ttlMs)continue;let o;try{o=await n.checkFn()}catch(s){this.log.warn(`[plugins] ${t}: check_fn error: ${s instanceof Error?s.message:s}`),o=n.lastResult}if(n.lastCheckAt=e,o!==n.lastResult){if(n.lastResult=o,o&&!n.active){for(let s of n.tools)Re(s);n.active=!0,this.log.info(`[plugins] ${t}: reactivated (${n.tools.length} tools)`)}else if(!o&&n.active){for(let s of n.tools)er(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"],o=null;for(let g of n){let y=Nn.join(t,g);if(tt.existsSync(y)){o=y;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,c=[],d=[],l=null,u=6e4,p={},m=Nn.join(t,"config.json");if(tt.existsSync(m))try{p=JSON.parse(tt.readFileSync(m,"utf8"))}catch{}let f={pluginName:e,registerTool:g=>{Re(g),c.push(g),s++},registerHook:(g,y)=>{let b=Sp[g];if(!b){this.log.warn(`[plugins] ${e}: unknown hook phase "${g}"`);return}let k=this.config.hookRegistry.register({point:b,handler:y,label:`plugin:${e}:${g}`,priority:200});d.push(k),i++},registerSkill:g=>{this.pluginSkills.push(g),a++},getConfig:()=>p,setActivationCheck:(g,y)=>{l=g,y!==void 0&&(u=y)}};try{let y=await import(uv(o).href);if(typeof y.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await y.register(f),l&&this.activations.set(e,{checkFn:l,ttlMs:u,lastCheckAt:Date.now(),lastResult:!0,tools:c,hookUnregisterFns:d,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(g){this.log.warn(`[plugins] ${e}: load error: ${g instanceof Error?g.message:g}`)}}};import*as pe from"node:fs";import*as Un from"node:path";function ma(){return Xc()}function Rp(){return Un.join(ma(),"installed_plugins.json")}function _p(){let r=Rp();if(!pe.existsSync(r))return{version:1,plugins:[]};try{return JSON.parse(pe.readFileSync(r,"utf-8"))}catch{return{version:1,plugins:[]}}}function pv(r){let e=ma();pe.existsSync(e)||pe.mkdirSync(e,{recursive:!0}),pe.writeFileSync(Rp(),JSON.stringify(r,null,2),"utf-8")}function mv(r,e){return!(e.blocklist?.includes(r)||e.allowlist&&!e.allowlist.includes(r))}async function gv(r,e,t){let{execFile:n}=await import("node:child_process"),{promisify:o}=await import("node:util"),s=o(n),i=ma(),a=e?`${r}@${e}`:r;try{let{stdout:c}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),d=c.trim().split(`
305
+ `).pop()?.trim();if(!d)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let l=Un.join(i,d),p=d.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=Un.join(i,`${r}@${p}`);pe.existsSync(m)||pe.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",l,"-C",m,"--strip-components=1"],{timeout:3e4});try{pe.unlinkSync(l)}catch{}let f=Un.join(m,"package.json");if(pe.existsSync(f))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(g){t.warn(`[marketplace] npm install for ${r} failed: ${g.message}`)}return t.info(`[marketplace] installed ${r}@${p} from npm`),{name:r,version:p,installPath:m}}catch(c){return t.warn(`[marketplace] failed to install ${a} from npm: ${c.message}`),null}}function fv(){return _p().plugins.filter(e=>pe.existsSync(e.installPath)).map(e=>e.installPath)}async function hv(r,e){let t=_p(),n=[];for(let o of r.enabledPlugins){let s=o.specifier.split("/").pop()??o.specifier;if(!mv(s,r)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(c=>c.source.specifier===o.specifier&&c.source.type===o.type);if(i&&pe.existsSync(i.installPath)&&(!o.version||i.version===o.version)){n.push(i.installPath);continue}let a=null;switch(o.type){case"npm":a=await gv(o.specifier,o.version,e);break;case"git":case"url":e.warn(`[marketplace] ${o.type} source not yet implemented for "${o.specifier}"`);break}if(a){let c={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};t.plugins=t.plugins.filter(d=>!(d.source.specifier===o.specifier&&d.source.type===o.type)),t.plugins.push(c),n.push(a.installPath)}}return pv(t),n}function yv(){let r=Jc();if(!pe.existsSync(r))return null;try{return JSON.parse(pe.readFileSync(r,"utf-8"))}catch{return null}}async function xp(r,e){let t=[...r],n=fv();t.push(...n);let o=yv();if(o&&o.enabledPlugins.length>0)try{let s=await hv(o,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 yr=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:o,regex:s}of this.compiledPatterns)if(s.test(t))return kv(o,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:bv(t.pattern)}))}};function ga(r){if(!r||typeof r!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=r,t=[];for(let a of["allow","deny","ask"]){let c=e[a];if(Array.isArray(c))for(let d of c)typeof d=="string"&&t.push({pattern:d,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let c=a,d=c.pattern,l=c.behavior??c.action;typeof d=="string"&&typeof l=="string"&&(l==="allow"||l==="deny"||l==="ask")&&t.push({pattern:d,behavior:l,reason:typeof c.reason=="string"?c.reason:void 0,source:typeof c.source=="string"?c.source:"config"})}}let n=e.mode,o=typeof n=="string"&&Tv(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&wv(s)?s:"allow";return{mode:o,rules:t,defaultBehavior:i}}function bv(r){let t=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function kv(r,e){let t={type:"rule",rule:r};return r.behavior==="allow"?{behavior:"allow",decisionReason:t}:r.behavior==="deny"?{behavior:"deny",message:r.reason??`Tool "${e.toolName}" denied by rule "${r.pattern}"`,decisionReason:t}:{behavior:"ask",message:r.reason??`Tool "${e.toolName}" requires approval (rule "${r.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:t}}function Tv(r){return r==="default"||r==="bypassPermissions"||r==="acceptEdits"||r==="dontAsk"||r==="plan"}function wv(r){return r==="allow"||r==="deny"||r==="ask"}import{randomUUID as Pv}from"node:crypto";var vv=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"]),Ap=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"]),Sv=[/\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],Cp=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 Pp(r,e,t){let n=r.trim();if(!n)return{decision:"allow",reason:"empty command"};let o=Hi(n)??Vi(n)??void 0;for(let d of Sv)if(d.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${d.source}`,destructiveWarning:o};for(let d of vv)if(n===d||n.startsWith(d+" "))return{decision:"allow",reason:`known safe command: ${d}`,destructiveWarning:o};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return Ap.has(i)||Ap.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:o}:e&&t&&e.startsWith(t)&&(Cp.has(i)||Cp.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:o}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:o}}function Rv(r){let e=Object.keys(r).sort(),t={};for(let n of e){let o=r[n];typeof o=="string"?t[n]=o.replace(/\s+/g," ").trim():t[n]=o}return JSON.stringify(t)}function fa(r,e){return`${r}::${Rv(e)}`}var _v=500,br=class{cache=new Map;get(e,t){let n=fa(e,t),o=this.cache.get(n);if(o)return o.hitCount++,o}set(e,t,n){if(this.cache.size>=_v){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let o=fa(e,t);this.cache.set(o,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(fa(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 xv=new Set(["read","search","instructions","think","task","memory","skill","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function $n(r){return xv.has(r)}var Ip=`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.
305
306
 
306
307
  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).
307
308
 
@@ -323,7 +324,7 @@ DANGEROUS operations (SHOULD be blocked):
323
324
  - Running commands with sudo/admin privileges
324
325
  - Downloading and executing unknown scripts
325
326
 
326
- Respond ONLY with XML. No other text.`;async function da(r,e,t,n){let o=Date.now();if(Ln(r))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-o};let s=lv(t),i=cv(r,e),a=`<transcript>
327
+ Respond ONLY with XML. No other text.`;async function ha(r,e,t,n){let o=Date.now();if($n(r))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-o};let s=Av(t),i=Cv(r,e),a=`<transcript>
327
328
  ${s}
328
329
  </transcript>
329
330
 
@@ -331,7 +332,7 @@ ${s}
331
332
  ${i}
332
333
  </action>
333
334
 
334
- Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let c=await n({system:up,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),d=gp(c.text);if(pp(d)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-o};let u=`<transcript>
335
+ Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let c=await n({system:Ip,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),d=Op(c.text);if(Mp(d)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-o};let u=`<transcript>
335
336
  ${s}
336
337
  </transcript>
337
338
 
@@ -339,57 +340,57 @@ ${s}
339
340
  ${i}
340
341
  </action>
341
342
 
342
- 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>.`,p=await n({system:up,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),g=gp(p.text),f=pp(g),m=mp(g)??mp(d)??"classifier decision";return{shouldBlock:f!==!1,reason:m,stage:"thinking",durationMs:Date.now()-o}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-o}}}function lv(r){return r.slice(-20).map(t=>{let n=t.role==="user"?"User":t.role==="assistant"?"Assistant":"System",o=typeof t.content=="string"?t.content.slice(0,500):JSON.stringify(t.content).slice(0,500);return`${n}: ${o}`}).join(`
343
- `)}function cv(r,e){let t=JSON.stringify(e,null,0),n=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${r}
344
- Arguments: ${n}`}function pp(r){let e=r.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function mp(r){let e=r.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function gp(r){return r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var fp={maxConsecutive:3,maxTotal:20};function hp(){return{consecutiveDenials:0,totalDenials:0}}function ua(r){return{consecutiveDenials:r.consecutiveDenials+1,totalDenials:r.totalDenials+1}}function pa(r){return r.consecutiveDenials===0?r:{...r,consecutiveDenials:0}}function yp(r){return r.consecutiveDenials>=fp.maxConsecutive||r.totalDenials>=fp.maxTotal}var uv=12e4,fr=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new gr;denialTracking=hp();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),o={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(o);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,o){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")&&o){let d=o.command??o.cmd??"";if(d){let l=dp(d);if(l.decision==="allow")return{action:"continue"};if(l.decision==="deny")return this.fireDenied(t,n,l.reason),{action:"abort",reason:l.reason}}}if(o){let d=this.classifierCache.get(n,o);if(d)return d.shouldBlock?(this.fireDenied(t,n,`cached: ${d.reason}`),{action:"abort",reason:d.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,n,o);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||Ln(n)?{action:"continue"}:this.handleWorkerAsk(t,n,o);if(this.ruleEngine.getMode()==="auto"){if(Ln(n))return{action:"continue"};let d=yp(this.denialTracking);if(this.classifierLLMCall&&!d)try{let l=this.getRecentMessages?.()??[],u=await da(n,o??{},l,this.classifierLLMCall);if(o&&this.classifierCache.set(n,o,{shouldBlock:u.shouldBlock,reason:u.reason}),!u.shouldBlock)return this.denialTracking=pa(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:u.reason}}};this.denialTracking=ua(this.denialTracking)}catch{}}let a=dv(),c={approvalId:a,callId:t,toolName:n,arguments:o,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n}).catch(()=>{});try{let d=await this.requestApproval(c);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n,decision:d.decision==="approved"?"approved":"denied"}).catch(()=>{}),d.permissionUpdate&&(this.ruleEngine.applyUpdate(d.permissionUpdate),this.onPermissionUpdate?.(d.permissionUpdate)),d.decision==="approved"?{action:"continue",context:d.updatedInput?{arguments:d.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(Ln(t))return{action:"continue"};if(this.classifierLLMCall)try{let o=this.getRecentMessages?.()??[],s=await da(t,n??{},o,this.classifierLLMCall);return n&&this.classifierCache.set(t,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=ua(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=pa(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 o=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),n(new Error("Approval timed out"))},uv);this.pendingApprovals.set(e.approvalId,{resolve:t,reject:n,timeoutId:o}),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 pv="skill",mv={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete","promote","install"],description:["The operation to perform:","\u2022 'invoke' \u2014 Run a skill by name (provide 'name', optional 'args')","\u2022 'list' \u2014 List all available skills (optional 'category' filter)","\u2022 'view' \u2014 View full skill content (provide 'name', optional 'filePath')","\u2022 'create' \u2014 Create a new skill (provide 'name', 'content')","\u2022 'edit' \u2014 Overwrite skill content (provide 'name', 'content')","\u2022 'patch' \u2014 Find/replace in skill (provide 'name', 'oldString', 'newString')","\u2022 'delete' \u2014 Remove a skill (provide 'name')","\u2022 'promote' \u2014 Promote a project-level skill to global/user-level (provide 'name')","\u2022 'install' \u2014 Download and install a skill from a URL (provide 'url', optional 'name')"].join(`
345
- `)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete/promote)."},args:{type:"string",description:"Arguments or context to pass when invoking a skill."},category:{type:"string",description:"Filter skills by category (for 'list' action)."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"View a specific file within the skill (for 'view' action)."},fileContent:{type:"string",description:"Content for writing supporting files."},oldString:{type:"string",description:"Text to find for patch action."},newString:{type:"string",description:"Replacement text for patch action."},url:{type:"string",description:"URL to download a skill from (for 'install' action). Supports skill stores (skillhub.cn, skill.io, GitHub raw links, etc.) and any direct .md URL."}},required:["action"]};function bp(r){return{name:pv,label:"Skill",description:Tv(r),parameters:mv,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke list view create edit delete command workflow",execute:async(e,t,n)=>{let{action:o}=t;switch(o){case"invoke":return gv(r,t,n);case"list":return fv(r,t);case"view":return hv(r,t);case"create":case"edit":case"patch":case"delete":return yv(r,t);case"promote":return bv(r,t);case"install":return kv(r,t);default:return{content:[{type:"text",text:`Unknown action: ${o}. Use invoke, list, view, create, edit, patch, delete, promote, or install.`}]}}}}}async function gv(r,e,t){let{name:n,args:o}=e;if(!n)return{content:[{type:"text",text:`Error: 'name' is required for invoke. Available skills: ${r.listSkills().map(d=>d.name).join(", ")||"(none)"}`}]};let s=await r.readSkillContent(n);if(!s){let c=r.listSkills().map(d=>d.name).join(", ");return{content:[{type:"text",text:`Skill "${n}" not found. Available skills: ${c||"(none)"}`}]}}if(r.executeSkillSubturn)try{return{content:[{type:"text",text:await r.executeSkillSubturn(n,s,o,t)}],details:{skillName:n,action:"invoke",mode:"subturn"}}}catch(c){let d=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`Skill execution error: ${d}`}],details:{error:d,skillName:n}}}let i=`## Skill: ${n}
343
+ The fast classifier flagged this action. Review carefully \u9225?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>.`,p=await n({system:Ip,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=Op(p.text),f=Mp(m),g=Ep(m)??Ep(d)??"classifier decision";return{shouldBlock:f!==!1,reason:g,stage:"thinking",durationMs:Date.now()-o}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-o}}}function Av(r){return r.slice(-20).map(t=>{let n=t.role==="user"?"User":t.role==="assistant"?"Assistant":"System",o=typeof t.content=="string"?t.content.slice(0,500):JSON.stringify(t.content).slice(0,500);return`${n}: ${o}`}).join(`
344
+ `)}function Cv(r,e){let t=JSON.stringify(e,null,0),n=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${r}
345
+ Arguments: ${n}`}function Mp(r){let e=r.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function Ep(r){let e=r.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function Op(r){return r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var Dp={maxConsecutive:3,maxTotal:20};function Lp(){return{consecutiveDenials:0,totalDenials:0}}function ya(r){return{consecutiveDenials:r.consecutiveDenials+1,totalDenials:r.totalDenials+1}}function ba(r){return r.consecutiveDenials===0?r:{...r,consecutiveDenials:0}}function Np(r){return r.consecutiveDenials>=Dp.maxConsecutive||r.totalDenials>=Dp.maxTotal}var Iv=12e4,kr=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new br;denialTracking=Lp();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),o={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(o);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,o){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")&&o){let d=o.command??o.cmd??"";if(d){let l=Pp(d);if(l.decision==="allow")return{action:"continue"};if(l.decision==="deny")return this.fireDenied(t,n,l.reason),{action:"abort",reason:l.reason}}}if(o){let d=this.classifierCache.get(n,o);if(d)return d.shouldBlock?(this.fireDenied(t,n,`cached: ${d.reason}`),{action:"abort",reason:d.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,n,o);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||$n(n)?{action:"continue"}:this.handleWorkerAsk(t,n,o);if(this.ruleEngine.getMode()==="auto"){if($n(n))return{action:"continue"};let d=Np(this.denialTracking);if(this.classifierLLMCall&&!d)try{let l=this.getRecentMessages?.()??[],u=await ha(n,o??{},l,this.classifierLLMCall);if(o&&this.classifierCache.set(n,o,{shouldBlock:u.shouldBlock,reason:u.reason}),!u.shouldBlock)return this.denialTracking=ba(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:u.reason}}};this.denialTracking=ya(this.denialTracking)}catch{}}let a=Pv(),c={approvalId:a,callId:t,toolName:n,arguments:o,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n}).catch(()=>{});try{let d=await this.requestApproval(c);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n,decision:d.decision==="approved"?"approved":"denied"}).catch(()=>{}),d.permissionUpdate&&(this.ruleEngine.applyUpdate(d.permissionUpdate),this.onPermissionUpdate?.(d.permissionUpdate)),d.decision==="approved"?{action:"continue",context:d.updatedInput?{arguments:d.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}" \u9225?approval timed out`}}}async handleWorkerAsk(e,t,n){if($n(t))return{action:"continue"};if(this.classifierLLMCall)try{let o=this.getRecentMessages?.()??[],s=await ha(t,n??{},o,this.classifierLLMCall);return n&&this.classifierCache.set(t,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=ya(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=ba(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 \u9225?no classifier for ${this.permissionRole} mode`}}requestApproval(e){return new Promise((t,n)=>{let o=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),n(new Error("Approval timed out"))},Iv);this.pendingApprovals.set(e.approvalId,{resolve:t,reject:n,timeoutId:o}),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 Mv="skill",Ev={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete","promote","install"],description:["The operation to perform:","\u2022 'invoke' \u2014 Run a skill by name (provide 'name', optional 'args')","\u2022 'list' \u2014 List all available skills (optional 'category' filter)","\u2022 'view' \u2014 View full skill content (provide 'name', optional 'filePath')","\u2022 'create' \u2014 Create a new skill (provide 'name', 'content')","\u2022 'edit' \u2014 Overwrite skill content (provide 'name', 'content')","\u2022 'patch' \u2014 Find/replace in skill (provide 'name', 'oldString', 'newString')","\u2022 'delete' \u2014 Remove a skill (provide 'name')","\u2022 'promote' \u2014 Promote a project-level skill to global/user-level (provide 'name')","\u2022 'install' \u2014 Download and install a skill from a URL (provide 'url', optional 'name')"].join(`
346
+ `)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete/promote)."},args:{type:"string",description:"Arguments or context to pass when invoking a skill."},category:{type:"string",description:"Filter skills by category (for 'list' action)."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"View a specific file within the skill (for 'view' action)."},fileContent:{type:"string",description:"Content for writing supporting files."},oldString:{type:"string",description:"Text to find for patch action."},newString:{type:"string",description:"Replacement text for patch action."},url:{type:"string",description:"URL to download a skill from (for 'install' action). Supports skill stores (skillhub.cn, skill.io, GitHub raw links, etc.) and any direct .md URL."}},required:["action"]};function Up(r){return{name:Mv,label:"Skill",description:jv(r),parameters:Ev,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke list view create edit delete command workflow",execute:async(e,t,n)=>{let{action:o}=t;switch(o){case"invoke":return Ov(r,t,n);case"list":return Dv(r,t);case"view":return Lv(r,t);case"create":case"edit":case"patch":case"delete":return Nv(r,t);case"promote":return Uv(r,t);case"install":return $v(r,t);default:return{content:[{type:"text",text:`Unknown action: ${o}. Use invoke, list, view, create, edit, patch, delete, promote, or install.`}]}}}}}async function Ov(r,e,t){let{name:n,args:o}=e;if(!n)return{content:[{type:"text",text:`Error: 'name' is required for invoke. Available skills: ${r.listSkills().map(d=>d.name).join(", ")||"(none)"}`}]};let s=await r.readSkillContent(n);if(!s){let c=r.listSkills().map(d=>d.name).join(", ");return{content:[{type:"text",text:`Skill "${n}" not found. Available skills: ${c||"(none)"}`}]}}if(r.executeSkillSubturn)try{return{content:[{type:"text",text:await r.executeSkillSubturn(n,s,o,t)}],details:{skillName:n,action:"invoke",mode:"subturn"}}}catch(c){let d=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`Skill execution error: ${d}`}],details:{error:d,skillName:n}}}let i=`## Skill: ${n}
346
347
 
347
348
  `,a=o?`
348
349
 
349
350
  ### User Context
350
351
  ${o}`:"";return{content:[{type:"text",text:`${i}Follow these instructions:
351
352
 
352
- ${s}${a}`}],details:{skillName:n,action:"invoke",mode:"inline"}}}async function fv(r,e){let t=await r.listSkillsFull(e.category);if(t.skills.length===0)return{content:[{type:"text",text:e.category?`No skills found in category "${e.category}".`:"No skills available."}],details:{action:"list",count:0}};let n=[`Available skills (${t.skills.length}):`];t.categories.length>0&&n.push(`Categories: ${t.categories.join(", ")}`),n.push("");for(let o of t.skills){let s=o.category?` [${o.category}]`:"",i=o.version?` (v${o.version})`:"",a=o.scope?` {${o.scope}}`:"";n.push(`- **${o.name}**${i}${s}${a}: ${o.description}`)}return{content:[{type:"text",text:n.join(`
353
- `)}],details:{action:"list",count:t.skills.length}}}async function hv(r,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for view."}]};let t=await r.viewSkill(e.name,e.filePath);if(!t)return{content:[{type:"text",text:`Skill "${e.name}" not found. Use action: "list" to see available skills.`}],details:{action:"view",error:"not_found"}};let n=[`## Skill: ${t.name}
353
+ ${s}${a}`}],details:{skillName:n,action:"invoke",mode:"inline"}}}async function Dv(r,e){let t=await r.listSkillsFull(e.category);if(t.skills.length===0)return{content:[{type:"text",text:e.category?`No skills found in category "${e.category}".`:"No skills available."}],details:{action:"list",count:0}};let n=[`Available skills (${t.skills.length}):`];t.categories.length>0&&n.push(`Categories: ${t.categories.join(", ")}`),n.push("");for(let o of t.skills){let s=o.category?` [${o.category}]`:"",i=o.version?` (v${o.version})`:"",a=o.scope?` {${o.scope}}`:"";n.push(`- **${o.name}**${i}${s}${a}: ${o.description}`)}return{content:[{type:"text",text:n.join(`
354
+ `)}],details:{action:"list",count:t.skills.length}}}async function Lv(r,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for view."}]};let t=await r.viewSkill(e.name,e.filePath);if(!t)return{content:[{type:"text",text:`Skill "${e.name}" not found. Use action: "list" to see available skills.`}],details:{action:"view",error:"not_found"}};let n=[`## Skill: ${t.name}
354
355
  `,t.content];return t.referenceFiles&&t.referenceFiles.length>0&&n.push(`
355
356
  ### Reference Files
356
357
  ${t.referenceFiles.map(o=>`- ${o}`).join(`
357
358
  `)}`),{content:[{type:"text",text:n.join(`
358
- `)}],details:{action:"view",name:t.name}}}async function yv(r,e){if(!e.name)return{content:[{type:"text",text:`Error: 'name' is required for ${e.action}.`}]};let t=await r.manageSkill({action:e.action,name:e.name,category:e.category,content:e.content,filePath:e.filePath,fileContent:e.fileContent,oldString:e.oldString,newString:e.newString});return{content:[{type:"text",text:t.message}],details:{action:e.action,success:t.success,path:t.path}}}async function bv(r,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for promote."}]};if(!r.promoteSkill)return{content:[{type:"text",text:"Promote is not available in this configuration. Skills may already be at user-level."}]};let t=await r.promoteSkill(e.name);return{content:[{type:"text",text:t.message}],details:{action:"promote",success:t.success,name:e.name}}}async function kv(r,e){if(!e.url)return{content:[{type:"text",text:"Error: 'url' is required for install. Provide a direct link to a .md skill file."}]};if(!r.installSkill)return{content:[{type:"text",text:"Install from URL is not available in this configuration."}]};let t=await r.installSkill(e.url,e.name);return{content:[{type:"text",text:t.message}],details:{action:"install",success:t.success,url:e.url,name:e.name}}}function Tv(r){let e=r.listSkills(),t=`Manage and invoke skills \u2014 reusable workflows and domain-specific knowledge packages. Use action: 'list' to discover skills, 'view' to read content, 'invoke' to run a skill. Skills can also be created, edited, patched, or deleted. Use 'promote' (with name) to copy a project skill to global (user-level) so it's available across all projects. Use 'install' (with url) to download a skill from a URL and save it globally.
359
+ `)}],details:{action:"view",name:t.name}}}async function Nv(r,e){if(!e.name)return{content:[{type:"text",text:`Error: 'name' is required for ${e.action}.`}]};let t=await r.manageSkill({action:e.action,name:e.name,category:e.category,content:e.content,filePath:e.filePath,fileContent:e.fileContent,oldString:e.oldString,newString:e.newString});return{content:[{type:"text",text:t.message}],details:{action:e.action,success:t.success,path:t.path}}}async function Uv(r,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for promote."}]};if(!r.promoteSkill)return{content:[{type:"text",text:"Promote is not available in this configuration. Skills may already be at user-level."}]};let t=await r.promoteSkill(e.name);return{content:[{type:"text",text:t.message}],details:{action:"promote",success:t.success,name:e.name}}}async function $v(r,e){if(!e.url)return{content:[{type:"text",text:"Error: 'url' is required for install. Provide a direct link to a .md skill file."}]};if(!r.installSkill)return{content:[{type:"text",text:"Install from URL is not available in this configuration."}]};let t=await r.installSkill(e.url,e.name);return{content:[{type:"text",text:t.message}],details:{action:"install",success:t.success,url:e.url,name:e.name}}}function jv(r){let e=r.listSkills(),t=`Manage and invoke skills \u2014 reusable workflows and domain-specific knowledge packages. Use action: 'list' to discover skills, 'view' to read content, 'invoke' to run a skill. Skills can also be created, edited, patched, or deleted. Use 'promote' (with name) to copy a project skill to global (user-level) so it's available across all projects. Use 'install' (with url) to download a skill from a URL and save it globally.
359
360
 
360
361
  CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled memories, it means a relevant skill exists in another project. You should proactively inform the user and offer to use it (invoke) or promote it to global. Do not wait for explicit instructions \u2014 the user may not know the skill exists. Typical user signals: '\u4E4B\u524D\u505A\u8FC7', '\u53C2\u8003XX\u9879\u76EE', 'didn't you do this before', 'same as the other project'.`;if(e.length===0)return t;let n=e.slice(0,50).map(o=>`- ${o.name}: ${o.description??"(no description)"}`).join(`
361
362
  `);return`${t}
362
363
 
363
364
  Available skills:
364
- ${n}`}var wv="agent",kp=["general","explore","plan","code","research","verify"],vv={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
365
+ ${n}`}var Fv="agent",$p=["general","explore","plan","code","research","verify"],Bv={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
365
366
  - general: Full tool access, any task
366
367
  - explore: Read-only codebase exploration (search, read, analyze)
367
368
  - plan: Planning mode (explore + produce plan, no writes)
368
369
  - code: Coding agent with full tool access
369
370
  - research: Web research and information gathering
370
- - 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},Tp=4;function wp(r){return{name:wv,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:vv,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(!kp.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${kp.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=r.currentForkDepth??0;if(n>=Tp)return{content:[{type:"text",text:`Error: maximum fork depth (${Tp}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:n}};try{let o=await r.forkAgent({agent:t.agent,prompt:t.prompt.trim(),description:t.description,maxTurns:t.maxTurns,background:t.background,abortSignal:r.abortSignal});if(t.background&&o.status==="running")return{content:[{type:"text",text:`Sub-agent "${t.agent}" started in background.
371
+ - 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},jp=4;function Fp(r){return{name:Fv,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:Bv,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(!$p.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${$p.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=r.currentForkDepth??0;if(n>=jp)return{content:[{type:"text",text:`Error: maximum fork depth (${jp}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:n}};try{let o=await r.forkAgent({agent:t.agent,prompt:t.prompt.trim(),description:t.description,maxTurns:t.maxTurns,background:t.background,abortSignal:r.abortSignal});if(t.background&&o.status==="running")return{content:[{type:"text",text:`Sub-agent "${t.agent}" started in background.
371
372
  Agent ID: ${o.agentId}
372
373
  Use task tool with this ID to check status and get output.`}],details:{type:"agent",agentId:o.agentId,status:"running",background:!0}};if(o.status==="failed")return{content:[{type:"text",text:`Sub-agent failed: ${o.error||"unknown error"}`}],details:{type:"agent",agentId:o.agentId,status:"failed",error:o.error}};let s=o.output||"(sub-agent returned no output)",i=o.maxTurnsReached?`
373
374
 
374
- [Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:o.agentId,status:"completed",tokensUsed:o.tokensUsed,maxTurnsReached:o.maxTurnsReached}}}catch(o){let s=o instanceof Error?o.message:String(o);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}var Sv="config",xv={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
375
+ [Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:o.agentId,status:"completed",tokensUsed:o.tokensUsed,maxTurnsReached:o.maxTurnsReached}}}catch(o){let s=o instanceof Error?o.message:String(o);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}var Wv="config",Gv={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
375
376
  - get: Read a config setting
376
377
  - set: Write a config setting
377
378
  - list: List all available settings
378
- - 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"]},$n=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function vp(r){return{name:Sv,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:xv,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(r.isValidKey&&!r.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 r.getConfig(t.key);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}};let o=n.setting,s=[`${o.key} = ${JSON.stringify(o.value)}`,` Type: ${o.type}${o.options?` (${o.options.join(" | ")})`:""}`,` ${o.description}`];return o.readOnly&&s.push(" \u26A0\uFE0F Read-only (cannot be changed)"),{content:[{type:"text",text:s.join(`
379
- `)}],details:{type:"config",action:"get",key:t.key,value:o.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($n.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(r.isValidKey&&!r.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}".`}],details:{type:"config",error:"unknown_key"}};let n=await r.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 r.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 o=[`Available settings (${n.settings.length}):`,""];for(let s of n.settings){let i=s.readOnly?" [read-only]":"",a=JSON.stringify(s.value);o.push(` ${s.key} = ${a}${i}`),o.push(` ${s.description}`)}return{content:[{type:"text",text:o.join(`
380
- `)}],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($n.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 r.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 Rv="cron",_v={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:
379
+ - 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"]},jn=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Bp(r){return{name:Wv,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:Gv,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(r.isValidKey&&!r.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 r.getConfig(t.key);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}};let o=n.setting,s=[`${o.key} = ${JSON.stringify(o.value)}`,` Type: ${o.type}${o.options?` (${o.options.join(" | ")})`:""}`,` ${o.description}`];return o.readOnly&&s.push(" \u26A0\uFE0F Read-only (cannot be changed)"),{content:[{type:"text",text:s.join(`
380
+ `)}],details:{type:"config",action:"get",key:t.key,value:o.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(jn.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(r.isValidKey&&!r.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}".`}],details:{type:"config",error:"unknown_key"}};let n=await r.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 r.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 o=[`Available settings (${n.settings.length}):`,""];for(let s of n.settings){let i=s.readOnly?" [read-only]":"",a=JSON.stringify(s.value);o.push(` ${s.key} = ${a}${i}`),o.push(` ${s.description}`)}return{content:[{type:"text",text:o.join(`
381
+ `)}],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(jn.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 r.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 Hv="cron",Vv={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:
381
382
  - Cron: '0 9 * * *' (every day at 9am)
382
383
  - Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
383
- 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"]},Sp=50;function xp(r){return{name:Rv,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:_v,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(r.validateSchedule){let s=r.validateSchedule(t.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let n=await r.listJobs();if(n.jobs&&n.jobs.length>=Sp)return{content:[{type:"text",text:`Error: maximum ${Sp} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let o=await r.createJob({prompt:t.prompt,schedule:t.schedule,name:t.name,repeat:t.repeat,allowedTools:t.allowedTools});return o.success?{content:[{type:"text",text:ma(o.job)}],details:{type:"cron",action:"create",jobId:o.job.id}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"list":{let n=await r.listJobs();if(!n.jobs||n.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let o=[`Scheduled jobs (${n.jobs.length}):`,""];for(let s of n.jobs)o.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:o.join(`
384
- `)}],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 r.getJob(t.jobId);return n.success?{content:[{type:"text",text:ma(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 o=await r.updateJob(t.jobId,n);return o.success?{content:[{type:"text",text:`Job updated.
385
- ${ma(o.job)}`}],details:{type:"cron",action:"update",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"delete":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await r.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 r.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 r.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 r.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 ma(r){let e=[`Job: ${r.name||r.id}`,`ID: ${r.id}`,`Schedule: ${r.scheduleDisplay} (${r.schedule})`,`State: ${r.state}`,`Repeat: ${r.repeat.times===null?"infinite":`${r.repeat.completed}/${r.repeat.times}`}`];return r.nextRunAt&&e.push(`Next run: ${r.nextRunAt}`),r.lastRunAt&&e.push(`Last run: ${r.lastRunAt} (${r.lastStatus||"unknown"})`),e.push(`Prompt: ${r.prompt.slice(0,100)}${r.prompt.length>100?"...":""}`),e.join(`
386
- `)}var Cv="monitor",Av={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 Rp(r){return{name:Cv,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(`
387
- `),parameters:Av,execute:async(e,t)=>{let{action:n}=t;if(n==="list"){let i=await r.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:n,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
384
+ 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"]},Wp=50;function Gp(r){return{name:Hv,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:Vv,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(r.validateSchedule){let s=r.validateSchedule(t.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let n=await r.listJobs();if(n.jobs&&n.jobs.length>=Wp)return{content:[{type:"text",text:`Error: maximum ${Wp} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let o=await r.createJob({prompt:t.prompt,schedule:t.schedule,name:t.name,repeat:t.repeat,allowedTools:t.allowedTools});return o.success?{content:[{type:"text",text:ka(o.job)}],details:{type:"cron",action:"create",jobId:o.job.id}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"list":{let n=await r.listJobs();if(!n.jobs||n.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let o=[`Scheduled jobs (${n.jobs.length}):`,""];for(let s of n.jobs)o.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:o.join(`
385
+ `)}],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 r.getJob(t.jobId);return n.success?{content:[{type:"text",text:ka(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 o=await r.updateJob(t.jobId,n);return o.success?{content:[{type:"text",text:`Job updated.
386
+ ${ka(o.job)}`}],details:{type:"cron",action:"update",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"delete":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await r.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 r.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 r.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 r.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 ka(r){let e=[`Job: ${r.name||r.id}`,`ID: ${r.id}`,`Schedule: ${r.scheduleDisplay} (${r.schedule})`,`State: ${r.state}`,`Repeat: ${r.repeat.times===null?"infinite":`${r.repeat.completed}/${r.repeat.times}`}`];return r.nextRunAt&&e.push(`Next run: ${r.nextRunAt}`),r.lastRunAt&&e.push(`Last run: ${r.lastRunAt} (${r.lastStatus||"unknown"})`),e.push(`Prompt: ${r.prompt.slice(0,100)}${r.prompt.length>100?"...":""}`),e.join(`
387
+ `)}var zv="monitor",Kv={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 Hp(r){return{name:zv,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(`
388
+ `),parameters:Kv,execute:async(e,t)=>{let{action:n}=t;if(n==="list"){let i=await r.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:n,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
388
389
  ${i.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.eventCount}, timeout: ${c.timeoutSeconds}s)`).join(`
389
- `)}`}],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 r.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 o=await r.startMonitor({monitorId:t.monitorId,source:t.source,target:t.target,conditions:t.conditions??[],timeoutSeconds:t.timeoutSeconds??3600});return{content:[{type:"text",text:o.success?`Monitor "${t.monitorId}" started: watching ${t.source} "${t.target}".`:`Failed to start monitor: ${o.error??"unknown"}`}],details:{...o}}}}}var Iv="team",Pv={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 _p(r){return{name:Iv,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:Pv,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 r.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 o=[`Team "${n.team.name}" created.`,`Lead: ${n.team.leadId}`,`Members: ${n.team.members.length}`];for(let s of n.team.members)o.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:o.join(`
390
+ `)}`}],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 r.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 o=await r.startMonitor({monitorId:t.monitorId,source:t.source,target:t.target,conditions:t.conditions??[],timeoutSeconds:t.timeoutSeconds??3600});return{content:[{type:"text",text:o.success?`Monitor "${t.monitorId}" started: watching ${t.source} "${t.target}".`:`Failed to start monitor: ${o.error??"unknown"}`}],details:{...o}}}}}var qv="team",Xv={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 Vp(r){return{name:qv,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:Xv,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 r.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 o=[`Team "${n.team.name}" created.`,`Lead: ${n.team.leadId}`,`Members: ${n.team.members.length}`];for(let s of n.team.members)o.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:o.join(`
390
391
  `)}],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 r.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 r.listTeams();if(!n.teams||n.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let o=[`Active teams (${n.teams.length}):`,""];for(let s of n.teams)o.push(`- **${s.name}**: ${s.description||"(no description)"} \u2014 ${s.members.length} members`);return{content:[{type:"text",text:o.join(`
391
- `)}],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 r.getTeamStatus(t.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=n.team,s=n.memberProgress??{},i=[`Team: ${o.name}`,`Description: ${o.description||"\u2014"}`,`Lead: ${o.leadId}`,`Created: ${o.createdAt}`,"",`Members (${o.members.length}):`];for(let a of o.members){let c=a.tools?` [tools: ${a.tools.join(", ")}]`:"",d=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",l=s[a.name],u=a.isActive===!1?" (idle)":" (active)";if(l){let p=[];if(l.runningFor&&p.push(`running ${Math.round(l.runningFor/1e3)}s`),l.lastToolCall&&p.push(`tool: ${l.lastToolCall}`),l.idleFor!==void 0&&l.idleFor>5&&p.push(`idle ${l.idleFor}s`),l.mediaProgress){let g=l.mediaProgress;p.push(`${g.mediaType} ${g.percent}% [${g.status}] taskId=${g.taskId}${g.provider?` provider=${g.provider}`:""}`)}p.length&&(u=` (${p.join(", ")})`)}i.push(` - ${a.name} (${a.role})${c}${d}${u}`)}return{content:[{type:"text",text:i.join(`
392
- `)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var Ev="mcp",Ov={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:
392
+ `)}],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 r.getTeamStatus(t.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=n.team,s=n.memberProgress??{},i=[`Team: ${o.name}`,`Description: ${o.description||"\u2014"}`,`Lead: ${o.leadId}`,`Created: ${o.createdAt}`,"",`Members (${o.members.length}):`];for(let a of o.members){let c=a.tools?` [tools: ${a.tools.join(", ")}]`:"",d=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",l=s[a.name],u=a.isActive===!1?" (idle)":" (active)";if(l){let p=[];if(l.runningFor&&p.push(`running ${Math.round(l.runningFor/1e3)}s`),l.lastToolCall&&p.push(`tool: ${l.lastToolCall}`),l.idleFor!==void 0&&l.idleFor>5&&p.push(`idle ${l.idleFor}s`),l.mediaProgress){let m=l.mediaProgress;p.push(`${m.mediaType} ${m.percent}% [${m.status}] taskId=${m.taskId}${m.provider?` provider=${m.provider}`:""}`)}p.length&&(u=` (${p.join(", ")})`)}i.push(` - ${a.name} (${a.role})${c}${d}${u}`)}return{content:[{type:"text",text:i.join(`
393
+ `)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var Jv="mcp",Qv={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:
393
394
  - list_servers: List configured MCP servers, their status and capabilities
394
395
  - list_tools: List tools provided by a specific server
395
396
  - call_tool: Execute a tool on an MCP server
@@ -398,14 +399,14 @@ ${i.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
398
399
  - list_prompts: List prompts available from a server
399
400
  - get_prompt: Get a specific prompt with arguments
400
401
  - authenticate: Initiate OAuth authentication with a server
401
- - 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 Cp(r){return{name:Ev,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).
402
+ - 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 zp(r){return{name:Jv,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).
402
403
 
403
- 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:Ov,shouldDefer:!0,execute:async(e,t,n)=>{switch(t.action){case"list_servers":{let o=await r.listServers();if(o.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 (${o.length}):`,""];for(let i of o){let a=Dv(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 c=[];i.capabilities.tools?.listChanged&&c.push("tools/listChanged"),i.capabilities.resources?.subscribe&&c.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&c.push("prompts/listChanged"),c.length>0&&s.push(` Capabilities: ${c.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(`
404
- `)}],details:{type:"mcp",action:"list_servers",count:o.length}}}case"list_tools":{if(!t.server)return ie("server is required for list_tools.");let o=await r.listTools(t.server);if(o.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}" (${o.length}):`,""];for(let i of o){let a=Lv(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(`
405
- `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:o.length}}}case"call_tool":{if(!t.server)return ie("server is required for call_tool.");if(!t.toolName)return ie("toolName is required for call_tool.");let o=await r.callTool(t.server,t.toolName,t.arguments,n);return!o.success||o.isError?{content:[{type:"text",text:`MCP tool error (${t.server}/${t.toolName}): ${o.error||o.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!1}}:o.contentBlocks&&o.contentBlocks.length>0?{content:o.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:o.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!0}}}case"list_resources":{let o=await r.listResources(t.server);if(o.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 (${o.length}):`,""];for(let i of o)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(`
406
- `)}],details:{type:"mcp",action:"list_resources",count:o.length,server:t.server}}}case"read_resource":{if(!t.server)return ie("server is required for read_resource.");if(!t.uri)return ie("uri is required for read_resource.");let o=await r.readResource(t.server,t.uri);if(o.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 o)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${$v(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 ie("server is required for list_prompts.");if(!r.listPrompts)return ie("Prompt listing not supported by the current MCP host.");let o=await r.listPrompts(t.server);if(o.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}" (${o.length}):`,""];for(let i of o)if(s.push(`- **${i.name}**${i.description?`: ${i.description}`:""}`),i.arguments&&i.arguments.length>0){let a=i.arguments.map(c=>`${c.name}${c.required?" (required)":""}${c.description?`: ${c.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
407
- `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:o.length}}}case"get_prompt":{if(!t.server)return ie("server is required for get_prompt.");if(!t.promptName)return ie("promptName is required for get_prompt.");if(!r.getPrompt)return ie("Prompt retrieval not supported by the current MCP host.");let o=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,c])=>[a,String(c)])):void 0,s=await r.getPrompt(t.server,t.promptName,o),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(`
408
- `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return ie("server is required for authenticate.");let o=await r.authenticate(t.server);switch(o.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
404
+ 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:Qv,shouldDefer:!0,execute:async(e,t,n)=>{switch(t.action){case"list_servers":{let o=await r.listServers();if(o.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 (${o.length}):`,""];for(let i of o){let a=Zv(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 c=[];i.capabilities.tools?.listChanged&&c.push("tools/listChanged"),i.capabilities.resources?.subscribe&&c.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&c.push("prompts/listChanged"),c.length>0&&s.push(` Capabilities: ${c.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(`
405
+ `)}],details:{type:"mcp",action:"list_servers",count:o.length}}}case"list_tools":{if(!t.server)return ae("server is required for list_tools.");let o=await r.listTools(t.server);if(o.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}" (${o.length}):`,""];for(let i of o){let a=eS(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(`
406
+ `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:o.length}}}case"call_tool":{if(!t.server)return ae("server is required for call_tool.");if(!t.toolName)return ae("toolName is required for call_tool.");let o=await r.callTool(t.server,t.toolName,t.arguments,n);return!o.success||o.isError?{content:[{type:"text",text:`MCP tool error (${t.server}/${t.toolName}): ${o.error||o.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!1}}:o.contentBlocks&&o.contentBlocks.length>0?{content:o.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:o.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!0}}}case"list_resources":{let o=await r.listResources(t.server);if(o.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 (${o.length}):`,""];for(let i of o)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(`
407
+ `)}],details:{type:"mcp",action:"list_resources",count:o.length,server:t.server}}}case"read_resource":{if(!t.server)return ae("server is required for read_resource.");if(!t.uri)return ae("uri is required for read_resource.");let o=await r.readResource(t.server,t.uri);if(o.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 o)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${tS(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 ae("server is required for list_prompts.");if(!r.listPrompts)return ae("Prompt listing not supported by the current MCP host.");let o=await r.listPrompts(t.server);if(o.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}" (${o.length}):`,""];for(let i of o)if(s.push(`- **${i.name}**${i.description?`: ${i.description}`:""}`),i.arguments&&i.arguments.length>0){let a=i.arguments.map(c=>`${c.name}${c.required?" (required)":""}${c.description?`: ${c.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
408
+ `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:o.length}}}case"get_prompt":{if(!t.server)return ae("server is required for get_prompt.");if(!t.promptName)return ae("promptName is required for get_prompt.");if(!r.getPrompt)return ae("Prompt retrieval not supported by the current MCP host.");let o=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,c])=>[a,String(c)])):void 0,s=await r.getPrompt(t.server,t.promptName,o),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(`
409
+ `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return ae("server is required for authenticate.");let o=await r.authenticate(t.server);switch(o.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
409
410
 
410
411
  Please open this URL in your browser:
411
412
  ${o.authUrl}
@@ -413,95 +414,95 @@ ${o.authUrl}
413
414
  ${o.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.
414
415
  Required scopes: ${o.requiredScopes?.join(", ")||"unknown"}
415
416
 
416
- `+(o.authUrl?`Re-authorize at: ${o.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}" (${o.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}": ${o.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"error"}}}}case"manage_server":{if(!t.server)return ie("server is required for manage_server.");if(!t.manageAction)return ie("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!r.addServer)return ie("Server addition not supported by the current MCP host.");if(!t.config)return ie("config is required for manage_server add.");let o=await r.addServer(t.server,t.config);return Un("add",t.server,o)}case"remove":{if(!r.removeServer)return ie("Server removal not supported by the current MCP host.");let o=await r.removeServer(t.server);return Un("remove",t.server,o)}case"restart":{if(!r.restartServer)return ie("Server restart not supported by the current MCP host.");let o=await r.restartServer(t.server);return Un("restart",t.server,o)}case"health_check":{if(!r.healthCheck)return ie("Health check not supported by the current MCP host.");let o=await r.healthCheck(t.server);return Un("health_check",t.server,o)}case"enable":case"disable":{if(!r.setServerEnabled)return ie("Server enable/disable not supported by the current MCP host.");let o=await r.setServerEnabled(t.server,t.manageAction==="enable");return Un(t.manageAction,t.server,o)}default:return ie(`Unknown manageAction: ${t.manageAction}`)}}default:return ie(`Unknown action: "${t.action}".`)}}}}function ie(r){return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"mcp",error:r}}}function Dv(r){switch(r){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 Lv(r){if(!r)return"";let e=[];return r.readOnlyHint&&e.push("\u{1F4D6}"),r.destructiveHint&&e.push("\u26A0\uFE0F"),r.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function $v(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function Un(r,e,t){let n=[];return n.push(`${t.success?"\u2705":"\u274C"} ${r} "${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(`
417
- `)}],details:{type:"mcp",action:"manage_server",manageAction:r,server:e,success:t.success}}}var Uv="checkpoint",Nv={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"]},Ap=/^[0-9a-fA-F]{4,64}$/;function Ip(r){return{name:Uv,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:Nv,execute:async(e,t)=>{switch(t.action){case"create":{let n=await r.createCheckpoint(t.message);return n.success?{content:[{type:"text",text:`Checkpoint created: ${n.checkpoint.id}
417
+ `+(o.authUrl?`Re-authorize at: ${o.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}" (${o.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}": ${o.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"error"}}}}case"manage_server":{if(!t.server)return ae("server is required for manage_server.");if(!t.manageAction)return ae("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!r.addServer)return ae("Server addition not supported by the current MCP host.");if(!t.config)return ae("config is required for manage_server add.");let o=await r.addServer(t.server,t.config);return Fn("add",t.server,o)}case"remove":{if(!r.removeServer)return ae("Server removal not supported by the current MCP host.");let o=await r.removeServer(t.server);return Fn("remove",t.server,o)}case"restart":{if(!r.restartServer)return ae("Server restart not supported by the current MCP host.");let o=await r.restartServer(t.server);return Fn("restart",t.server,o)}case"health_check":{if(!r.healthCheck)return ae("Health check not supported by the current MCP host.");let o=await r.healthCheck(t.server);return Fn("health_check",t.server,o)}case"enable":case"disable":{if(!r.setServerEnabled)return ae("Server enable/disable not supported by the current MCP host.");let o=await r.setServerEnabled(t.server,t.manageAction==="enable");return Fn(t.manageAction,t.server,o)}default:return ae(`Unknown manageAction: ${t.manageAction}`)}}default:return ae(`Unknown action: "${t.action}".`)}}}}function ae(r){return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"mcp",error:r}}}function Zv(r){switch(r){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 eS(r){if(!r)return"";let e=[];return r.readOnlyHint&&e.push("\u{1F4D6}"),r.destructiveHint&&e.push("\u26A0\uFE0F"),r.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function tS(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function Fn(r,e,t){let n=[];return n.push(`${t.success?"\u2705":"\u274C"} ${r} "${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(`
418
+ `)}],details:{type:"mcp",action:"manage_server",manageAction:r,server:e,success:t.success}}}var nS="checkpoint",oS={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"]},Kp=/^[0-9a-fA-F]{4,64}$/;function qp(r){return{name:nS,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:oS,execute:async(e,t)=>{switch(t.action){case"create":{let n=await r.createCheckpoint(t.message);return n.success?{content:[{type:"text",text:`Checkpoint created: ${n.checkpoint.id}
418
419
  Message: ${n.checkpoint.message}
419
420
  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 r.listCheckpoints();if(!n.checkpoints||n.checkpoints.length===0)return{content:[{type:"text",text:"No checkpoints available."}],details:{type:"checkpoint",action:"list",count:0}};let o=[`Checkpoints (${n.checkpoints.length}):`,""];for(let s of n.checkpoints)o.push(`- ${s.id.slice(0,8)} [${s.timestamp}] ${s.message} (${s.fileCount} files)`);return{content:[{type:"text",text:o.join(`
420
- `)}],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(!Ap.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await r.restoreCheckpoint(t.checkpointId,t.paths);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}};let o=t.paths?`(${t.paths.length} files)`:"(full workspace)";return{content:[{type:"text",text:`Restored to checkpoint ${t.checkpointId.slice(0,8)} ${o}`}],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(!Ap.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await r.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 _e from"node:fs";import*as qt from"node:path";function Pp(r,e){let t=Bl(e);return{createCheckpoint:async n=>{try{_e.mkdirSync(t,{recursive:!0});let{execSync:o}=await import("node:child_process"),s=qt.join(t,".git");_e.existsSync(s)||(o("git init",{cwd:t,stdio:"pipe"}),o('git config user.email "checkpoint@agent"',{cwd:t,stdio:"pipe"}),o('git config user.name "Checkpoint"',{cwd:t,stdio:"pipe"})),_e.cpSync(r,t,{recursive:!0,filter:d=>!d.includes(".git")&&!d.includes("node_modules")}),o("git add -A",{cwd:t,stdio:"pipe"});let i=n||`checkpoint ${new Date().toISOString()}`;o(`git commit --allow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:t,stdio:"pipe"});let a=o("git rev-parse HEAD",{cwd:t,stdio:"pipe"}).toString().trim(),c=parseInt(o("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:c}}}catch(o){return{success:!1,error:o.message}}},listCheckpoints:async()=>{try{let{execSync:n}=await import("node:child_process"),o=qt.join(t,".git");if(!_e.existsSync(o))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(`
421
- `).map(a=>{let[c="",d="",...l]=a.split("|");return{id:c,timestamp:d,message:l.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(n){return{success:!1,error:n.message}}},restoreCheckpoint:async(n,o)=>{try{let{execSync:s}=await import("node:child_process");if(o&&o.length>0){s(`git checkout ${n} -- ${o.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(" ")}`,{cwd:t,stdio:"pipe"});for(let i of o){let a=qt.join(t,i),c=qt.join(r,i);_e.existsSync(a)&&_e.cpSync(a,c,{recursive:!0})}}else{s(`git checkout ${n} -- .`,{cwd:t,stdio:"pipe"});let i=_e.readdirSync(r);for(let a of i){if(a===".git"||a==="node_modules")continue;let c=qt.join(r,a);_e.rmSync(c,{recursive:!0,force:!0})}_e.cpSync(t,r,{recursive:!0,filter:a=>!a.includes(".git")})}return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async n=>{try{let{execSync:o}=await import("node:child_process");return{success:!0,diff:o(`git diff ${n} HEAD`,{cwd:t,stdio:"pipe"}).toString()}}catch(o){return{success:!1,error:o.message}}}}}De();import{spawn as fa}from"node:child_process";import{createInterface as yr}from"node:readline";import{resolve as Jv,join as jn}from"node:path";import{createServer as Xv}from"node:net";import{createWriteStream as Yv,mkdirSync as Qv}from"node:fs";import{tmpdir as Zv}from"node:os";import{createInterface as jv}from"node:readline";var Fv=1,Bv=1,Be={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"},Gv=1e4,Dt=class{pendingRpcs=new Map;rl=null;child=null;onNotification=null;hostHandler=null;attach(e,t,n){this.onNotification=t??null,this.hostHandler=n??null,this.child=e,this.rl=jv({input:e.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.rl.on("line",o=>{let s=o.trim();if(!s)return;let i;try{i=JSON.parse(s)}catch{return}let a="id"in i&&(typeof i.id=="number"||typeof i.id=="string"),c="method"in i&&typeof i.method=="string";if(a&&!c){let d=this.pendingRpcs.get(i.id);if(d){clearTimeout(d.timer),this.pendingRpcs.delete(i.id);let l=i;l.error?d.reject(new Error(l.error.message)):d.resolve(l.result)}return}if(a&&c){this.handleAgentRequest(i.id,i.method,i.params);return}c&&!a&&this.onNotification?.(i.method,i.params)})}handleAgentRequest(e,t,n){let o=(c,d)=>{if(!this.child?.stdin?.writable)return;let l={jsonrpc:"2.0",id:e};d?l.error=d:l.result=c??{};try{this.child.stdin.write(`${JSON.stringify(l)}
422
- `)}catch{}},s=this.hostHandler,i=n;(async()=>{switch(t){case"fs/read_text_file":return s?.readTextFile?.(i)??{};case"fs/write_text_file":return s?.writeTextFile?.(i)??{};case"session/request_permission":return s?.requestPermission?.(i??{})??{outcome:"cancelled"};case"session/elicitation":case"session/elicitation/complete":return s?.elicitation?.(i??{})??{};case"terminal/create":return s?.createTerminal?.(i??{})??{};case"terminal/output":return s?.terminalOutput?.(i??{})??{};case"terminal/release":return s?.releaseTerminal?.(i??{})??{};case"terminal/wait_for_exit":return s?.waitForTerminalExit?.(i??{})??{};case"terminal/kill":return s?.killTerminal?.(i??{})??{};default:if(s?.extMethod)return s.extMethod(t,n);throw new Error(`Method not found: ${t}`)}})().then(c=>o(c)).catch(c=>o(null,{code:-32601,message:c instanceof Error?c.message:String(c)}))}detach(){this.rl?.close(),this.rl=null,this.child=null,this.hostHandler=null;for(let[e,t]of this.pendingRpcs)clearTimeout(t.timer),t.reject(new Error("ACP adapter detached")),this.pendingRpcs.delete(e)}sendRpc(e,t,n,o=3e4){let s=Fv++,i={jsonrpc:"2.0",id:s,method:t,params:n};return new Promise((a,c)=>{let d=setTimeout(()=>{this.pendingRpcs.delete(s),c(new Error(`ACP RPC timeout: ${t} (${o}ms)`))},o);this.pendingRpcs.set(s,{resolve:a,reject:c,timer:d});try{e.stdin.write(`${JSON.stringify(i)}
423
- `)}catch(l){clearTimeout(d),this.pendingRpcs.delete(s),c(l instanceof Error?l:new Error(String(l)))}})}async initialize(e){let t=await this.sendRpc(e,"initialize",{protocolVersion:Bv,clientInfo:{name:"qlogicagent",version:"1.0.0"},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,auth:{terminal:!1}}},Gv),n=t?.agentCapabilities??{};return{protocolVersion:typeof t?.protocolVersion=="number"?t.protocolVersion:0,agentCapabilities:{loadSession:n.loadSession===!0,mcpCapabilities:n.mcpCapabilities,promptCapabilities:n.promptCapabilities,sessionCapabilities:n.sessionCapabilities},agentInfo:t?.agentInfo,authMethods:t?.authMethods}}async createSession(e,t){let n={cwd:t.cwd,mcpServers:t.mcpServers??[]};t.additionalDirectories?.length&&(n.additionalDirectories=t.additionalDirectories),t.systemPrompt&&(n.systemPrompt=t.systemPrompt);let o=await this.sendRpc(e,"session/new",n);if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,t,n,o=3e5){let s=await this.sendRpc(e,"session/prompt",{sessionId:t,prompt:[{type:"text",text:n}]},o);return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:s?.userMessageId}}async resumeSession(e,t,n){let o={sessionId:t,cwd:n?.cwd??process.cwd(),mcpServers:n?.mcpServers??[]},s=await this.sendRpc(e,"session/load",o,3e4);if(typeof s?.sessionId!="string")throw new Error("ACP session/load: agent did not return sessionId");return{sessionId:s.sessionId}}async closeSession(e,t){try{await this.sendRpc(e,"session/close",{sessionId:t},5e3)}catch{}}static translateNotification(e,t){let n=t;if(e==="session/update"){if(!n)return null;let o=n.update;if(!o)return null;let s=o.sessionUpdate,i=n.sessionId;switch(s){case Be.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:i,messageId:o.messageId}}}case Be.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:i}};case Be.TOOL_CALL:return{method:"turn.tool_call",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"running",content:o.content,kind:o.kind,rawInput:o.rawInput,sessionId:i}};case Be.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"completed",content:o.content,rawOutput:o.rawOutput,sessionId:i}};case Be.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Be.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:i}};case Be.AVAILABLE_COMMANDS_UPDATE:case Be.CURRENT_MODE_UPDATE:case Be.CONFIG_OPTION_UPDATE:case Be.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:s,...o,sessionId:i}};case Be.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${s??"unknown"}`,params:{...o,sessionId:i}}}}return null}};var Nn=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{execSync as Ep}from"node:child_process";import{platform as Hv}from"node:os";var ga={claude:{id:"claude",name:"Claude Code",cliCommand:"claude",acpArgs:["--experimental-acp"],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:[],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen-code",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!1,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!0},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!1,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!1},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"ZHIPU_API_KEY"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}},Wv=["general","explore","plan","code","research","verify"];function zv(){return Wv.map(r=>({id:`qlogicagent-${r}`,name:`qlogicagent (${r})`,category:"sub-agent",protocol:"internal",status:"available",authRequired:!1,hasConfig:!0,supportsBaseUrlOverride:!0,capabilities:{supportsMcp:!1,supportsResume:!0,supportsUsageUpdate:!0}}))}var Vv=Hv()==="win32";function Mp(r){try{let e=Vv?`where ${r}`:`which ${r}`;return Ep(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function qv(r){try{return Ep(`"${r}" --version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var Kv=6e4,hr=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<Kv)return this.cache.agents;let t=[];t.push(...zv());for(let n of Object.values(ga))t.push(this.detectBackend(n));if(this.configStore?.customAgents)for(let n of Object.values(this.configStore.customAgents))t.push(this.detectCustomAgent(n));return this.cache={agents:t,timestamp:Date.now()},t}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let t=Mp(e.cliCommand),n=this.hasAgentConfig(e.id);if(!t)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let o=qv(t);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:t,version:o??void 0,authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose",supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){let t=Mp(e.cliCommand),n=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:t?"available":"not_installed",cliPath:t??void 0,authRequired:e.authRequired??!1,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let t=this.configStore.agents[e];return!!(t?.apiKey||t?.baseUrl||t?.customCliPath)}buildExternalDescriptor(e){let t=this.list().find(s=>s.id===e);if(!t||t.protocol!=="acp"||t.status!=="available"||!t.cliPath)return null;let n=ga[e],o=this.configStore?.agents[e];return{id:e,cliPath:o?.customCliPath??t.cliPath,acpArgs:o?.customArgs??n?.acpArgs??[],env:o?.env??n?.env,protocol:"acp"}}};var eS=1;function tS(r,e){return{jsonrpc:"2.0",id:eS++,method:r,params:e}}var nS=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function oS(r){let e={};for(let t of nS)process.env[t]&&(e[t]=process.env[t]);return r.apiKey&&(e.OPENAI_API_KEY=r.apiKey),r.baseUrl&&(e.OPENAI_BASE_URL=r.baseUrl),e.QLOGICAGENT_MEMBER_ID=r.memberId,e.QLOGICAGENT_MEMBER_NAME=r.name,r.agentType&&(e.QLOGICAGENT_AGENT_TYPE=r.agentType),r.model&&(e.QLOGICAGENT_MODEL=r.model),r.env&&Object.assign(e,r.env),e}var ha=us,rS=ps,Kt=ms,Op=gs;function sS(r){return new Promise(e=>setTimeout(e,r))}var Jt=class r{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=Jv(jn(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=jn(t,"dist","cli.js"),this.mcpBridgeScriptPath=jn(t,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,t,n,o){let i=`[${new Date().toISOString()}] [${e}] [agent:${t}] [${n}] ${o}`;e==="warn"?this.callbacks.log?.warn(i):this.callbacks.log?.info(i)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let t=this.callbacks.log,n=oS(e),o={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,o,n);let s=[this.cliBinaryPath];e.verbose&&s.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let i=fa(process.execPath,s,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});o.pid=i.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:o,child:i,pendingRpc:a}),yr({input:i.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{let l=d.trim();if(l)try{let u=JSON.parse(l);if("id"in u&&typeof u.id=="number"){let p=a.get(u.id);if(p){clearTimeout(p.timer),a.delete(u.id);let g=u;g.error?p.reject(new Error(g.error.message)):p.resolve(g.result)}}if("method"in u&&!("id"in u)){let p=u;this.captureChildProgress(e.memberId,p.method,p.params),this.callbacks.onNotification?.(e.memberId,p.method,p.params)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${l.slice(0,200)}`)}}),i.stderr&&yr({input:i.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",l=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${l}`)}),i.on("exit",(d,l)=>{o.state!=="killed"&&(o.state=d===0?"completed":"failed"),o.endedAt=Date.now(),d!==0&&!o.error&&(o.error=`Process exited with code ${d} (signal: ${l})`);for(let[p,g]of a)clearTimeout(g.timer),g.reject(new Error(`Agent process exited (code=${d})`)),a.delete(p);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,d,l),this.slog("info",e.memberId,"exit",`exited (code=${d}, signal=${l})`)}),i.on("error",d=>{o.state="failed",o.error=d.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",d.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let d=await this.sendRpc(e.memberId,"initialize",{protocolVersion:"1.0",clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"}},15e3);o.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${o.pid})`);let l=d;l&&typeof l.sessionId=="string"&&(o.sessionId=l.sessionId)}catch(d){throw o.state="failed",o.error=`Initialize handshake failed: ${d instanceof Error?d.message:String(d)}`,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(o.error)}return o}async sendTask(e,t,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let s;if(o.acpAdapter){let i=o.handle.sessionId??"default",a=await o.acpAdapter.sendPrompt(o.child,i,t,n?.timeout??3e5),c=o.handle.resultText??"";a.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(a.usage),s={content:c,stopReason:a.stopReason}}else{let i={content:t};n?.model&&(i.model=n.model),n?.apiKey&&(i.apiKey=n.apiKey),n?.baseUrl&&(i.baseUrl=n.baseUrl),n?.sessionId&&(i.sessionId=n.sessionId),s=await this.sendRpc(e,"thread.turn",i,n?.timeout??3e5);let a=s;a&&typeof a.content=="string"&&(o.handle.resultText=a.content)}return o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),s}catch(s){throw o.handle.state="failed",o.handle.error=s instanceof Error?s.message:String(s),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),s}}async sendRpc(e,t,n,o=3e4){let s=this.processes.get(e);if(!s)throw new Error(`No agent process: ${e}`);let i=tS(t,n);return new Promise((a,c)=>{let d=setTimeout(()=>{s.pendingRpc.delete(i.id),c(new Error(`RPC timeout: ${t} (${o}ms)`))},o);s.pendingRpc.set(i.id,{resolve:a,reject:c,timer:d});try{s.child.stdin.write(`${JSON.stringify(i)}
424
- `)}catch(l){clearTimeout(d),s.pendingRpc.delete(i.id),c(l instanceof Error?l:new Error(String(l)))}})}async sendTaskAsync(e,t,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.state="running",this.callbacks.onStateChange?.(e,"running");let s={content:t};n?.model&&(s.model=n.model),n?.apiKey&&(s.apiKey=n.apiKey),n?.baseUrl&&(s.baseUrl=n.baseUrl),n?.sessionId&&(s.sessionId=n.sessionId);let i=n?.pingInterval??6e4,a=n?.pingTimeout??1e4,c=n?.timeout??0,d=Date.now(),l=c>0?c:1440*60*1e3,u=this.sendRpc(e,"thread.turn",s,l),p=setInterval(async()=>{if(c>0&&Date.now()-d>c){clearInterval(p),o.handle.state="failed",o.handle.error="Task timed out",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed");return}try{await this.sendRpc(e,"ping",void 0,a)}catch{this.slog("warn",o.handle.memberId,"heartbeat","ping failed")}},i);try{let g=await u;clearInterval(p),o.handle.state="completed",o.handle.endedAt=Date.now();let f=g;return f&&typeof f.content=="string"&&(o.handle.resultText=f.content),this.callbacks.onStateChange?.(e,"completed"),g}catch(g){throw clearInterval(p),o.handle.state="failed",o.handle.error=g instanceof Error?g.message:String(g),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),g}}async ping(e,t=5e3){let n=this.processes.get(e);if(!n)return!1;if(n.acpAdapter){try{let i=JSON.stringify({jsonrpc:"2.0",method:"notifications/ping",params:{timestamp:Date.now()}})+`
425
- `;n.child.stdin?.write(i)}catch{return!1}let o=n.handle.lastActivityAt??0,s=Date.now()+t;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,500)),(n.handle.lastActivityAt??0)>o)return!0;try{return await this.sendRpc(e,"ping",void 0,Math.min(t,3e3)),!0}catch{return!1}}try{return await this.sendRpc(e,"ping",void 0,t),!0}catch{return!1}}getStatus(e){let t=this.processes.get(e);if(!t)return null;let{handle:n}=t,o=n.state==="starting"||n.state==="ready"||n.state==="running",s=o?Date.now()-n.startedAt:void 0,i=n.lastActivityAt&&o?Math.round((Date.now()-n.lastActivityAt)/1e3):void 0;return{alive:o,state:n.state,runningFor:s,resultText:n.resultText,error:n.error,mediaProgress:n.mediaProgress,lastToolCall:n.lastToolCall,idleFor:i}}captureChildProgress(e,t,n){let o=this.processes.get(e);if(!o)return;let{handle:s}=o;switch(s.lastActivityAt=Date.now(),t){case"turn.media_progress":{let i=n;i&&typeof i.taskId=="string"&&(s.mediaProgress={taskId:i.taskId,mediaType:i.mediaType??"unknown",percent:typeof i.percent=="number"?i.percent:0,status:i.status??"unknown",provider:i.provider,updatedAt:Date.now()});break}case"turn.tool_call":{let i=n;i&&typeof i.name=="string"&&(s.lastToolCall=i.name);break}case"turn.delta":{let i=n;i&&typeof i.text=="string"&&(s.lastDelta=i.text.slice(-200));break}case"turn.tool_result":{n&&s.mediaProgress&&s.mediaProgress.percent>=100&&(s.mediaProgress=void 0);break}}}async spawnAcpAgentWithRetry(e,t,n){let o=null;for(let s=0;s<=ha;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=rS*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${ha} after ${i}ms`),await sS(i)}return await this.spawnAcpAgent(e,t,n)}catch(i){o=i instanceof Error?i:new Error(String(i)),this.slog("warn",e.memberId,"spawn",`attempt ${s+1} failed: ${o.message}`)}throw t.state="failed",t.error=`ACP spawn failed after ${ha+1} attempts: ${o?.message}`,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),new Error(t.error)}async spawnAcpAgent(e,t,n){let o=this.callbacks.log,s=e.external;s.env&&Object.assign(n,s.env);let i=[...s.acpArgs];this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${s.cliPath} ${i.join(" ")}`);let a=fa(s.cliPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});t.pid=a.pid??-1;let c=new Map,d=new Dt,l=new Nn,{server:u,pipePath:p}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=p;let g;if(this.callbacks.sessionDir)try{Qv(this.callbacks.sessionDir,{recursive:!0}),g=Yv(jn(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}this.processes.set(e.memberId,{handle:t,child:a,pendingRpc:c,acpAdapter:d,usageTracker:l,ipcServer:u,ipcPath:p,stderrStream:g}),d.attach(a,(f,m)=>{f==="usage_update"&&l.onUsageUpdate(m);let y=Dt.translateNotification(f,m);y?(this.captureChildProgress(e.memberId,y.method,y.params),this.callbacks.onNotification?.(e.memberId,y.method,y.params)):(this.captureChildProgress(e.memberId,f,m),this.callbacks.onNotification?.(e.memberId,f,m))}),a.stderr&&yr({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",m=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${m}`),g?.write(`${new Date().toISOString()} ${m}
426
- `)}),a.on("exit",(f,m)=>{d.detach();let y=t.state;if(y!=="killed"&&y!=="completed"&&f!==0){let b=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(b<Kt){let x=Op*2**b;this.slog("warn",e.memberId,"crash",`crashed (code=${f}), restarting ${b+1}/${Kt} after ${x}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${f}, signal=${m}), restarting`,retriesLeft:Kt-b-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,n,b+1).catch(S=>{this.slog("warn",e.memberId,"restart",`failed: ${S instanceof Error?S.message:String(S)}`)})},x);return}}y!=="killed"&&(t.state=f===0?"completed":"failed"),t.endedAt=Date.now(),f!==0&&!t.error&&(t.error=`ACP process exited with code ${f} (signal: ${m})`),this.callbacks.onStateChange?.(e.memberId,t.state),this.callbacks.onExit?.(e.memberId,f,m),this.slog("info",e.memberId,"exit",`ACP exited (code=${f}, signal=${m})`)}),a.on("error",f=>{d.detach(),t.state="failed",t.error=f.message,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:f.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",f.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let f=await d.initialize(a);t.state="ready",t.supportsResume=f.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${f.protocolVersion}, loadSession=${t.supportsResume}, pid=${t.pid})`);try{let m={cwd:e.cwd},y=[...e.mcpServers??[]],k=this.processes.get(e.memberId);k?.ipcPath&&y.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:k.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),y.length>0&&(m.mcpServers=y),e.systemPrompt&&(m.systemPrompt=e.systemPrompt);let b=await d.createSession(a,m);t.sessionId=b.sessionId,this.slog("info",e.memberId,"session",`session created (id=${b.sessionId})`)}catch(m){this.slog("warn",e.memberId,"session",`session creation failed: ${m instanceof Error?m.message:String(m)}`)}this.startHeartbeat(e.memberId,m=>{this.slog("warn",m,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(m,"agents.error",{agentId:m,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${r.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(m)})}catch(f){throw t.state="failed",t.error=`ACP handshake failed: ${f instanceof Error?f.message:String(f)}`,t.endedAt=Date.now(),d.detach(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"handshake",error:t.error,retriesLeft:0}),this.kill(e.memberId),new Error(t.error)}return t}kill(e){let t=this.processes.get(e);if(t){this.stopHeartbeat(e),t.handle.state="killed",t.handle.endedAt=Date.now(),t.acpAdapter?.detach();try{t.ipcServer?.close()}catch{}try{t.stderrStream?.end()}catch{}try{t.child.kill("SIGTERM"),setTimeout(()=>{try{t.child.kill("SIGKILL")}catch{}},1e4)}catch{}this.callbacks.onStateChange?.(e,"killed"),this.slog("info",e,"kill",`killed (pid=${t.handle.pid})`)}}killAll(){for(let e of this.processes.keys())this.kill(e)}getHandle(e){return this.processes.get(e)?.handle}getAllHandles(){return[...this.processes.values()].map(e=>e.handle)}getUsageTracker(e){return this.processes.get(e)?.usageTracker??null}createMcpIpcServer(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"-"),n=process.platform==="win32"?`\\\\.\\pipe\\qlogicagent-mcp-${t}-${Date.now()}`:jn(Zv(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),o=Xv(s=>{let i="";s.on("data",a=>{i+=a.toString();let c;for(;(c=i.indexOf(`
421
+ `)}],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(!Kp.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await r.restoreCheckpoint(t.checkpointId,t.paths);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}};let o=t.paths?`(${t.paths.length} files)`:"(full workspace)";return{content:[{type:"text",text:`Restored to checkpoint ${t.checkpointId.slice(0,8)} ${o}`}],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(!Kp.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await r.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 Pe from"node:fs";import*as Jt from"node:path";function Xp(r,e){let t=qc(e);return{createCheckpoint:async n=>{try{Pe.mkdirSync(t,{recursive:!0});let{execSync:o}=await import("node:child_process"),s=Jt.join(t,".git");Pe.existsSync(s)||(o("git init",{cwd:t,stdio:"pipe"}),o('git config user.email "checkpoint@agent"',{cwd:t,stdio:"pipe"}),o('git config user.name "Checkpoint"',{cwd:t,stdio:"pipe"})),Pe.cpSync(r,t,{recursive:!0,filter:d=>!d.includes(".git")&&!d.includes("node_modules")}),o("git add -A",{cwd:t,stdio:"pipe"});let i=n||`checkpoint ${new Date().toISOString()}`;o(`git commit --allow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:t,stdio:"pipe"});let a=o("git rev-parse HEAD",{cwd:t,stdio:"pipe"}).toString().trim(),c=parseInt(o("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:c}}}catch(o){return{success:!1,error:o.message}}},listCheckpoints:async()=>{try{let{execSync:n}=await import("node:child_process"),o=Jt.join(t,".git");if(!Pe.existsSync(o))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(`
422
+ `).map(a=>{let[c="",d="",...l]=a.split("|");return{id:c,timestamp:d,message:l.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(n){return{success:!1,error:n.message}}},restoreCheckpoint:async(n,o)=>{try{let{execSync:s}=await import("node:child_process");if(o&&o.length>0){s(`git checkout ${n} -- ${o.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(" ")}`,{cwd:t,stdio:"pipe"});for(let i of o){let a=Jt.join(t,i),c=Jt.join(r,i);Pe.existsSync(a)&&Pe.cpSync(a,c,{recursive:!0})}}else{s(`git checkout ${n} -- .`,{cwd:t,stdio:"pipe"});let i=Pe.readdirSync(r);for(let a of i){if(a===".git"||a==="node_modules")continue;let c=Jt.join(r,a);Pe.rmSync(c,{recursive:!0,force:!0})}Pe.cpSync(t,r,{recursive:!0,filter:a=>!a.includes(".git")})}return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async n=>{try{let{execSync:o}=await import("node:child_process");return{success:!0,diff:o(`git diff ${n} HEAD`,{cwd:t,stdio:"pipe"}).toString()}}catch(o){return{success:!1,error:o.message}}}}}ye();import{spawn as wa}from"node:child_process";import{createInterface as wr}from"node:readline";import{resolve as gS,join as Wn}from"node:path";import{createServer as fS}from"node:net";import{createWriteStream as hS,mkdirSync as yS}from"node:fs";import{tmpdir as bS}from"node:os";import{createInterface as rS}from"node:readline";var sS=1,iS=1,Ge={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"},aS=1e4,$t=class{pendingRpcs=new Map;rl=null;child=null;onNotification=null;hostHandler=null;attach(e,t,n){this.onNotification=t??null,this.hostHandler=n??null,this.child=e,this.rl=rS({input:e.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.rl.on("line",o=>{let s=o.trim();if(!s)return;let i;try{i=JSON.parse(s)}catch{return}let a="id"in i&&(typeof i.id=="number"||typeof i.id=="string"),c="method"in i&&typeof i.method=="string";if(a&&!c){let d=this.pendingRpcs.get(i.id);if(d){clearTimeout(d.timer),this.pendingRpcs.delete(i.id);let l=i;l.error?d.reject(new Error(l.error.message)):d.resolve(l.result)}return}if(a&&c){this.handleAgentRequest(i.id,i.method,i.params);return}c&&!a&&this.onNotification?.(i.method,i.params)})}handleAgentRequest(e,t,n){let o=(c,d)=>{if(!this.child?.stdin?.writable)return;let l={jsonrpc:"2.0",id:e};d?l.error=d:l.result=c??{};try{this.child.stdin.write(`${JSON.stringify(l)}
423
+ `)}catch{}},s=this.hostHandler,i=n;(async()=>{switch(t){case"fs/read_text_file":return s?.readTextFile?.(i)??{};case"fs/write_text_file":return s?.writeTextFile?.(i)??{};case"session/request_permission":return s?.requestPermission?.(i??{})??{outcome:"cancelled"};case"session/elicitation":case"session/elicitation/complete":return s?.elicitation?.(i??{})??{};case"terminal/create":return s?.createTerminal?.(i??{})??{};case"terminal/output":return s?.terminalOutput?.(i??{})??{};case"terminal/release":return s?.releaseTerminal?.(i??{})??{};case"terminal/wait_for_exit":return s?.waitForTerminalExit?.(i??{})??{};case"terminal/kill":return s?.killTerminal?.(i??{})??{};default:if(s?.extMethod)return s.extMethod(t,n);throw new Error(`Method not found: ${t}`)}})().then(c=>o(c)).catch(c=>o(null,{code:-32601,message:c instanceof Error?c.message:String(c)}))}detach(){this.rl?.close(),this.rl=null,this.child=null,this.hostHandler=null;for(let[e,t]of this.pendingRpcs)clearTimeout(t.timer),t.reject(new Error("ACP adapter detached")),this.pendingRpcs.delete(e)}sendRpc(e,t,n,o=3e4){let s=sS++,i={jsonrpc:"2.0",id:s,method:t,params:n};return new Promise((a,c)=>{let d=setTimeout(()=>{this.pendingRpcs.delete(s),c(new Error(`ACP RPC timeout: ${t} (${o}ms)`))},o);this.pendingRpcs.set(s,{resolve:a,reject:c,timer:d});try{e.stdin.write(`${JSON.stringify(i)}
424
+ `)}catch(l){clearTimeout(d),this.pendingRpcs.delete(s),c(l instanceof Error?l:new Error(String(l)))}})}async initialize(e){let t=await this.sendRpc(e,"initialize",{protocolVersion:iS,clientInfo:{name:"qlogicagent",version:"1.0.0"},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,auth:{terminal:!1}}},aS),n=t?.agentCapabilities??{};return{protocolVersion:typeof t?.protocolVersion=="number"?t.protocolVersion:0,agentCapabilities:{loadSession:n.loadSession===!0,mcpCapabilities:n.mcpCapabilities,promptCapabilities:n.promptCapabilities,sessionCapabilities:n.sessionCapabilities},agentInfo:t?.agentInfo,authMethods:t?.authMethods}}async createSession(e,t){let n={cwd:t.cwd,mcpServers:t.mcpServers??[]};t.additionalDirectories?.length&&(n.additionalDirectories=t.additionalDirectories),t.systemPrompt&&(n.systemPrompt=t.systemPrompt);let o=await this.sendRpc(e,"session/new",n);if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,t,n,o=3e5){let s=await this.sendRpc(e,"session/prompt",{sessionId:t,prompt:[{type:"text",text:n}]},o);return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:s?.userMessageId}}async resumeSession(e,t,n){let o={sessionId:t,cwd:n?.cwd??process.cwd(),mcpServers:n?.mcpServers??[]},s=await this.sendRpc(e,"session/load",o,3e4);if(typeof s?.sessionId!="string")throw new Error("ACP session/load: agent did not return sessionId");return{sessionId:s.sessionId}}async closeSession(e,t){try{await this.sendRpc(e,"session/close",{sessionId:t},5e3)}catch{}}static translateNotification(e,t){let n=t;if(e==="session/update"){if(!n)return null;let o=n.update;if(!o)return null;let s=o.sessionUpdate,i=n.sessionId;switch(s){case Ge.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:i,messageId:o.messageId}}}case Ge.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:i}};case Ge.TOOL_CALL:return{method:"turn.tool_call",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"running",content:o.content,kind:o.kind,rawInput:o.rawInput,sessionId:i}};case Ge.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"completed",content:o.content,rawOutput:o.rawOutput,sessionId:i}};case Ge.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Ge.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:i}};case Ge.AVAILABLE_COMMANDS_UPDATE:case Ge.CURRENT_MODE_UPDATE:case Ge.CONFIG_OPTION_UPDATE:case Ge.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:s,...o,sessionId:i}};case Ge.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${s??"unknown"}`,params:{...o,sessionId:i}}}}return null}};var Bn=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{execSync as Jp}from"node:child_process";import{platform as cS}from"node:os";var Ta={claude:{id:"claude",name:"Claude Code",cliCommand:"claude",acpArgs:["--experimental-acp"],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:[],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen-code",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!1,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!0},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!1,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!1},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"ZHIPU_API_KEY"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}},lS=["general","explore","plan","code","research","verify"];function dS(){return lS.map(r=>({id:`qlogicagent-${r}`,name:`qlogicagent (${r})`,category:"sub-agent",protocol:"internal",status:"available",authRequired:!1,hasConfig:!0,supportsBaseUrlOverride:!0,capabilities:{supportsMcp:!1,supportsResume:!0,supportsUsageUpdate:!0}}))}var uS=cS()==="win32";function Yp(r){try{let e=uS?`where ${r}`:`which ${r}`;return Jp(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function pS(r){try{return Jp(`"${r}" --version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var mS=6e4,Tr=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<mS)return this.cache.agents;let t=[];t.push(...dS());for(let n of Object.values(Ta))t.push(this.detectBackend(n));if(this.configStore?.customAgents)for(let n of Object.values(this.configStore.customAgents))t.push(this.detectCustomAgent(n));return this.cache={agents:t,timestamp:Date.now()},t}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let t=Yp(e.cliCommand),n=this.hasAgentConfig(e.id);if(!t)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let o=pS(t);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:t,version:o??void 0,authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose",supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){let t=Yp(e.cliCommand),n=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:t?"available":"not_installed",cliPath:t??void 0,authRequired:e.authRequired??!1,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let t=this.configStore.agents[e];return!!(t?.apiKey||t?.baseUrl||t?.customCliPath)}buildExternalDescriptor(e){let t=this.list().find(s=>s.id===e);if(!t||t.protocol!=="acp"||t.status!=="available"||!t.cliPath)return null;let n=Ta[e],o=this.configStore?.agents[e];return{id:e,cliPath:o?.customCliPath??t.cliPath,acpArgs:o?.customArgs??n?.acpArgs??[],env:o?.env??n?.env,protocol:"acp"}}};var kS=1;function TS(r,e){return{jsonrpc:"2.0",id:kS++,method:r,params:e}}var wS=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function vS(r){let e={};for(let t of wS)process.env[t]&&(e[t]=process.env[t]);return r.apiKey&&(e.OPENAI_API_KEY=r.apiKey),r.baseUrl&&(e.OPENAI_BASE_URL=r.baseUrl),e.QLOGICAGENT_MEMBER_ID=r.memberId,e.QLOGICAGENT_MEMBER_NAME=r.name,r.agentType&&(e.QLOGICAGENT_AGENT_TYPE=r.agentType),r.model&&(e.QLOGICAGENT_MODEL=r.model),r.env&&Object.assign(e,r.env),e}var va=gs,SS=fs,Qt=hs,Qp=ys;function RS(r){return new Promise(e=>setTimeout(e,r))}var Zt=class r{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=gS(Wn(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Wn(t,"dist","cli.js"),this.mcpBridgeScriptPath=Wn(t,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,t,n,o){let i=`[${new Date().toISOString()}] [${e}] [agent:${t}] [${n}] ${o}`;e==="warn"?this.callbacks.log?.warn(i):this.callbacks.log?.info(i)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let t=this.callbacks.log,n=vS(e),o={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,o,n);let s=[this.cliBinaryPath];e.verbose&&s.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let i=wa(process.execPath,s,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});o.pid=i.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:o,child:i,pendingRpc:a}),wr({input:i.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{let l=d.trim();if(l)try{let u=JSON.parse(l);if("id"in u&&typeof u.id=="number"){let p=a.get(u.id);if(p){clearTimeout(p.timer),a.delete(u.id);let m=u;m.error?p.reject(new Error(m.error.message)):p.resolve(m.result)}}if("method"in u&&!("id"in u)){let p=u;this.captureChildProgress(e.memberId,p.method,p.params),this.callbacks.onNotification?.(e.memberId,p.method,p.params)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${l.slice(0,200)}`)}}),i.stderr&&wr({input:i.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",l=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${l}`)}),i.on("exit",(d,l)=>{o.state!=="killed"&&(o.state=d===0?"completed":"failed"),o.endedAt=Date.now(),d!==0&&!o.error&&(o.error=`Process exited with code ${d} (signal: ${l})`);for(let[p,m]of a)clearTimeout(m.timer),m.reject(new Error(`Agent process exited (code=${d})`)),a.delete(p);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,d,l),this.slog("info",e.memberId,"exit",`exited (code=${d}, signal=${l})`)}),i.on("error",d=>{o.state="failed",o.error=d.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",d.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let d=await this.sendRpc(e.memberId,"initialize",{protocolVersion:"1.0",clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"}},15e3);o.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${o.pid})`);let l=d;l&&typeof l.sessionId=="string"&&(o.sessionId=l.sessionId)}catch(d){throw o.state="failed",o.error=`Initialize handshake failed: ${d instanceof Error?d.message:String(d)}`,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(o.error)}return o}async sendTask(e,t,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let s;if(o.acpAdapter){let i=o.handle.sessionId??"default",a=await o.acpAdapter.sendPrompt(o.child,i,t,n?.timeout??3e5),c=o.handle.resultText??"";a.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(a.usage),s={content:c,stopReason:a.stopReason}}else{let i={content:t};n?.model&&(i.model=n.model),n?.apiKey&&(i.apiKey=n.apiKey),n?.baseUrl&&(i.baseUrl=n.baseUrl),n?.sessionId&&(i.sessionId=n.sessionId),s=await this.sendRpc(e,"thread.turn",i,n?.timeout??3e5);let a=s;a&&typeof a.content=="string"&&(o.handle.resultText=a.content)}return o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),s}catch(s){throw o.handle.state="failed",o.handle.error=s instanceof Error?s.message:String(s),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),s}}async sendRpc(e,t,n,o=3e4){let s=this.processes.get(e);if(!s)throw new Error(`No agent process: ${e}`);let i=TS(t,n);return new Promise((a,c)=>{let d=setTimeout(()=>{s.pendingRpc.delete(i.id),c(new Error(`RPC timeout: ${t} (${o}ms)`))},o);s.pendingRpc.set(i.id,{resolve:a,reject:c,timer:d});try{s.child.stdin.write(`${JSON.stringify(i)}
425
+ `)}catch(l){clearTimeout(d),s.pendingRpc.delete(i.id),c(l instanceof Error?l:new Error(String(l)))}})}async sendTaskAsync(e,t,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.state="running",this.callbacks.onStateChange?.(e,"running");let s={content:t};n?.model&&(s.model=n.model),n?.apiKey&&(s.apiKey=n.apiKey),n?.baseUrl&&(s.baseUrl=n.baseUrl),n?.sessionId&&(s.sessionId=n.sessionId);let i=n?.pingInterval??6e4,a=n?.pingTimeout??1e4,c=n?.timeout??0,d=Date.now(),l=c>0?c:1440*60*1e3,u=this.sendRpc(e,"thread.turn",s,l),p=setInterval(async()=>{if(c>0&&Date.now()-d>c){clearInterval(p),o.handle.state="failed",o.handle.error="Task timed out",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed");return}try{await this.sendRpc(e,"ping",void 0,a)}catch{this.slog("warn",o.handle.memberId,"heartbeat","ping failed")}},i);try{let m=await u;clearInterval(p),o.handle.state="completed",o.handle.endedAt=Date.now();let f=m;return f&&typeof f.content=="string"&&(o.handle.resultText=f.content),this.callbacks.onStateChange?.(e,"completed"),m}catch(m){throw clearInterval(p),o.handle.state="failed",o.handle.error=m instanceof Error?m.message:String(m),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),m}}async ping(e,t=5e3){let n=this.processes.get(e);if(!n)return!1;if(n.acpAdapter){try{let i=JSON.stringify({jsonrpc:"2.0",method:"notifications/ping",params:{timestamp:Date.now()}})+`
426
+ `;n.child.stdin?.write(i)}catch{return!1}let o=n.handle.lastActivityAt??0,s=Date.now()+t;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,500)),(n.handle.lastActivityAt??0)>o)return!0;try{return await this.sendRpc(e,"ping",void 0,Math.min(t,3e3)),!0}catch{return!1}}try{return await this.sendRpc(e,"ping",void 0,t),!0}catch{return!1}}getStatus(e){let t=this.processes.get(e);if(!t)return null;let{handle:n}=t,o=n.state==="starting"||n.state==="ready"||n.state==="running",s=o?Date.now()-n.startedAt:void 0,i=n.lastActivityAt&&o?Math.round((Date.now()-n.lastActivityAt)/1e3):void 0;return{alive:o,state:n.state,runningFor:s,resultText:n.resultText,error:n.error,mediaProgress:n.mediaProgress,lastToolCall:n.lastToolCall,idleFor:i}}captureChildProgress(e,t,n){let o=this.processes.get(e);if(!o)return;let{handle:s}=o;switch(s.lastActivityAt=Date.now(),t){case"turn.media_progress":{let i=n;i&&typeof i.taskId=="string"&&(s.mediaProgress={taskId:i.taskId,mediaType:i.mediaType??"unknown",percent:typeof i.percent=="number"?i.percent:0,status:i.status??"unknown",provider:i.provider,updatedAt:Date.now()});break}case"turn.tool_call":{let i=n;i&&typeof i.name=="string"&&(s.lastToolCall=i.name);break}case"turn.delta":{let i=n;i&&typeof i.text=="string"&&(s.lastDelta=i.text.slice(-200));break}case"turn.tool_result":{n&&s.mediaProgress&&s.mediaProgress.percent>=100&&(s.mediaProgress=void 0);break}}}async spawnAcpAgentWithRetry(e,t,n){let o=null;for(let s=0;s<=va;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=SS*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${va} after ${i}ms`),await RS(i)}return await this.spawnAcpAgent(e,t,n)}catch(i){o=i instanceof Error?i:new Error(String(i)),this.slog("warn",e.memberId,"spawn",`attempt ${s+1} failed: ${o.message}`)}throw t.state="failed",t.error=`ACP spawn failed after ${va+1} attempts: ${o?.message}`,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),new Error(t.error)}async spawnAcpAgent(e,t,n){let o=this.callbacks.log,s=e.external;s.env&&Object.assign(n,s.env);let i=[...s.acpArgs];this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${s.cliPath} ${i.join(" ")}`);let a=wa(s.cliPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});t.pid=a.pid??-1;let c=new Map,d=new $t,l=new Bn,{server:u,pipePath:p}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=p;let m;if(this.callbacks.sessionDir)try{yS(this.callbacks.sessionDir,{recursive:!0}),m=hS(Wn(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}this.processes.set(e.memberId,{handle:t,child:a,pendingRpc:c,acpAdapter:d,usageTracker:l,ipcServer:u,ipcPath:p,stderrStream:m}),d.attach(a,(f,g)=>{f==="usage_update"&&l.onUsageUpdate(g);let y=$t.translateNotification(f,g);y?(this.captureChildProgress(e.memberId,y.method,y.params),this.callbacks.onNotification?.(e.memberId,y.method,y.params)):(this.captureChildProgress(e.memberId,f,g),this.callbacks.onNotification?.(e.memberId,f,g))}),a.stderr&&wr({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",g=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${g}`),m?.write(`${new Date().toISOString()} ${g}
427
+ `)}),a.on("exit",(f,g)=>{d.detach();let y=t.state;if(y!=="killed"&&y!=="completed"&&f!==0){let k=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(k<Qt){let S=Qp*2**k;this.slog("warn",e.memberId,"crash",`crashed (code=${f}), restarting ${k+1}/${Qt} after ${S}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${f}, signal=${g}), restarting`,retriesLeft:Qt-k-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,n,k+1).catch(R=>{this.slog("warn",e.memberId,"restart",`failed: ${R instanceof Error?R.message:String(R)}`)})},S);return}}y!=="killed"&&(t.state=f===0?"completed":"failed"),t.endedAt=Date.now(),f!==0&&!t.error&&(t.error=`ACP process exited with code ${f} (signal: ${g})`),this.callbacks.onStateChange?.(e.memberId,t.state),this.callbacks.onExit?.(e.memberId,f,g),this.slog("info",e.memberId,"exit",`ACP exited (code=${f}, signal=${g})`)}),a.on("error",f=>{d.detach(),t.state="failed",t.error=f.message,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:f.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",f.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let f=await d.initialize(a);t.state="ready",t.supportsResume=f.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${f.protocolVersion}, loadSession=${t.supportsResume}, pid=${t.pid})`);try{let g={cwd:e.cwd},y=[...e.mcpServers??[]],b=this.processes.get(e.memberId);b?.ipcPath&&y.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:b.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),y.length>0&&(g.mcpServers=y),e.systemPrompt&&(g.systemPrompt=e.systemPrompt);let k=await d.createSession(a,g);t.sessionId=k.sessionId,this.slog("info",e.memberId,"session",`session created (id=${k.sessionId})`)}catch(g){this.slog("warn",e.memberId,"session",`session creation failed: ${g instanceof Error?g.message:String(g)}`)}this.startHeartbeat(e.memberId,g=>{this.slog("warn",g,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(g,"agents.error",{agentId:g,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${r.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(g)})}catch(f){throw t.state="failed",t.error=`ACP handshake failed: ${f instanceof Error?f.message:String(f)}`,t.endedAt=Date.now(),d.detach(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"handshake",error:t.error,retriesLeft:0}),this.kill(e.memberId),new Error(t.error)}return t}kill(e){let t=this.processes.get(e);if(t){this.stopHeartbeat(e),t.handle.state="killed",t.handle.endedAt=Date.now(),t.acpAdapter?.detach();try{t.ipcServer?.close()}catch{}try{t.stderrStream?.end()}catch{}try{t.child.kill("SIGTERM"),setTimeout(()=>{try{t.child.kill("SIGKILL")}catch{}},1e4)}catch{}this.callbacks.onStateChange?.(e,"killed"),this.slog("info",e,"kill",`killed (pid=${t.handle.pid})`)}}killAll(){for(let e of this.processes.keys())this.kill(e)}getHandle(e){return this.processes.get(e)?.handle}getAllHandles(){return[...this.processes.values()].map(e=>e.handle)}getUsageTracker(e){return this.processes.get(e)?.usageTracker??null}createMcpIpcServer(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"-"),n=process.platform==="win32"?`\\\\.\\pipe\\qlogicagent-mcp-${t}-${Date.now()}`:Wn(bS(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),o=fS(s=>{let i="";s.on("data",a=>{i+=a.toString();let c;for(;(c=i.indexOf(`
427
428
  `))!==-1;){let d=i.slice(0,c).trim();i=i.slice(c+1),d&&this.handleMcpIpcMessage(e,d,s)}})});return o.listen(n),o.on("error",s=>{this.slog("warn",e,"mcp-ipc",`server error: ${s.message}`)}),{server:o,pipePath:n}}handleMcpIpcMessage(e,t,n){let o;try{o=JSON.parse(t)}catch{return}if(o.method==="mcp.toolCall"&&o.id!==void 0){let s=typeof o.params?.tool=="string"?o.params.tool:"",i=o.params?.arguments??{};if(!this.callbacks.onMcpToolCall){let a=JSON.stringify({jsonrpc:"2.0",id:o.id,error:{code:-32601,message:"No onMcpToolCall handler"}})+`
428
429
  `;try{n.write(a)}catch{}return}this.callbacks.onMcpToolCall(e,s,i).then(a=>{let c=JSON.stringify({jsonrpc:"2.0",id:o.id,result:a})+`
429
430
  `;try{n.write(c)}catch{}}).catch(a=>{let c=JSON.stringify({jsonrpc:"2.0",id:o.id,error:{code:-32603,message:a instanceof Error?a.message:String(a)}})+`
430
431
  `;try{n.write(c)}catch{}})}else if(o.id!==void 0){let s=JSON.stringify({jsonrpc:"2.0",id:o.id,error:{code:-32601,message:`Unknown IPC method: ${o.method}`}})+`
431
- `;try{n.write(s)}catch{}}}async attemptRuntimeRestart(e,t,n){let o=this.callbacks.log,s=this.processes.get(e.memberId),i=s?.ipcServer,a=s?.ipcPath,c=s?.stderrStream;this.processes.delete(e.memberId);try{let d={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()},l=e.external,u=[...l.acpArgs];a&&(t.QLOGICAGENT_PARENT_RPC=a);let p=fa(l.cliPath,u,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!1});d.pid=p.pid??-1;let g=new Map,f=new Dt,m=new Nn;this.processes.set(e.memberId,{handle:d,child:p,pendingRpc:g,acpAdapter:f,usageTracker:m,ipcServer:i,ipcPath:a,stderrStream:c,runtimeRestartCount:n}),f.attach(p,(b,x)=>{b==="usage_update"&&m.onUsageUpdate(x);let S=Dt.translateNotification(b,x);S?(this.captureChildProgress(e.memberId,S.method,S.params),this.callbacks.onNotification?.(e.memberId,S.method,S.params)):(this.captureChildProgress(e.memberId,b,x),this.callbacks.onNotification?.(e.memberId,b,x))}),p.stderr&&yr({input:p.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",x=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${x}`),c?.write(`${new Date().toISOString()} ${x}
432
- `)}),p.on("exit",(b,x)=>{f.detach();let S=d.state;if(S!=="killed"&&S!=="completed"&&b!==0){let $=this.processes.get(e.memberId)?.runtimeRestartCount??n;if($<Kt){let D=Op*2**$;this.slog("warn",e.memberId,"crash",`crashed again (code=${b}), restart ${$+1}/${Kt}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${b}), restarting`,retriesLeft:Kt-$-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,t,$+1).catch(B=>{this.slog("warn",e.memberId,"restart",`failed: ${B instanceof Error?B.message:String(B)}`)})},D);return}}S!=="killed"&&(d.state=b===0?"completed":"failed"),d.endedAt=Date.now(),b!==0&&!d.error&&(d.error=`ACP process exited with code ${b} (signal: ${x})`),this.callbacks.onStateChange?.(e.memberId,d.state),this.callbacks.onExit?.(e.memberId,b,x)}),p.on("error",b=>{f.detach(),d.state="failed",d.error=b.message,d.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let y=await f.initialize(p);d.state="ready",d.supportsResume=y.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${n}, protocol=${y.protocolVersion}, loadSession=${d.supportsResume}, pid=${d.pid})`);let k=[...e.mcpServers??[]];a&&k.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(d.supportsResume&&d.sessionId){let b=await f.resumeSession(p,d.sessionId,{cwd:e.cwd,mcpServers:k.length>0?k:void 0});d.sessionId=b.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${d.sessionId})`)}else{let b={cwd:e.cwd};k.length>0&&(b.mcpServers=k),e.systemPrompt&&(b.systemPrompt=e.systemPrompt);let x=await f.createSession(p,b);d.sessionId=x.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${d.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,b=>{this.slog("warn",b,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(b,"agents.error",{agentId:b,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(b)})}catch(d){let l=this.processes.get(e.memberId);l&&(l.handle.state="failed",l.handle.error=`Runtime restart failed: ${d instanceof Error?d.message:String(d)}`,l.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${n} attempts: ${d instanceof Error?d.message:String(d)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,t){this.stopHeartbeat(e),this.missedBeats.set(e,0);let n=setInterval(async()=>{let o=this.processes.get(e);if(!o||o.handle.state==="completed"||o.handle.state==="failed"||o.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let i=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,i),this.slog("warn",e,"heartbeat",`missed (${i}/${r.MAX_MISSED_BEATS})`),i>=r.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),o.handle.error=`Hang detected: ${i} consecutive heartbeat failures`,this.kill(e),t?.(e))},r.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,n)}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let t=this.processes.get(e);t&&(this.stopHeartbeat(e),(t.handle.state==="running"||t.handle.state==="starting"||t.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};import{join as Lp}from"node:path";import{chmod as gS}from"node:fs/promises";import{readFile as iS,writeFile as aS,mkdir as lS,rename as cS,unlink as dS}from"node:fs/promises";import{dirname as uS,join as pS}from"node:path";import{randomUUID as mS}from"node:crypto";async function Xt(r,e){let t=uS(r);await lS(t,{recursive:!0});let n=pS(t,`.tmp-${mS()}`);try{await aS(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await cS(n,r);return}catch(i){if(o=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw o}catch(o){throw await dS(n).catch(()=>{}),o}}async function Fn(r){try{let e=await iS(r,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function br(r,e){await Xt(r,JSON.stringify(e,null,2)+`
433
- `)}var $p="agent-configs.json";function Dp(){return Lp(J(),$p)}function fS(r){return Lp(je(r),$p)}function hS(){return{agents:{}}}var kr=class{data=hS();cwd;constructor(e){this.cwd=e}async load(){let e=await Fn(Dp()),t=this.cwd?await Fn(fS(this.cwd)):void 0,n={gatewayUrl:e?.gatewayUrl,agents:{...e?.agents},customAgents:{...e?.customAgents}};if(t){t.gatewayUrl&&(n.gatewayUrl=t.gatewayUrl);for(let[o,s]of Object.entries(t.agents??{}))n.agents[o]={...n.agents[o],...s};for(let[o,s]of Object.entries(t.customAgents??{}))n.customAgents??={},n.customAgents[o]=s}this.data=n}getData(){return this.data}getAgentConfig(e){return this.data.agents[e]??null}async setAgentConfig(e,t){this.data.agents[e]={...this.data.agents[e],...t},await this.save()}async removeAgentConfig(e){delete this.data.agents[e],await this.save()}getGatewayUrl(){return this.data.gatewayUrl}async setGatewayUrl(e){this.data.gatewayUrl=e,await this.save()}registerCustomAgent(e){this.data.customAgents??={},this.data.customAgents[e.id]=e}unregisterCustomAgent(e){this.data.customAgents&&delete this.data.customAgents[e]}getCustomAgents(){return{...this.data.customAgents}}async save(){let e=Dp();await br(e,this.data);try{await gS(e,384)}catch{}}};import{randomUUID as wS}from"node:crypto";import{execFile as yS}from"node:child_process";import{promisify as bS}from"node:util";import{join as Up}from"node:path";import{mkdir as kS,rm as TS}from"node:fs/promises";var Yt=bS(yS);async function Bn(r){try{let{stdout:e}=await Yt("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return null}}async function Tr(r,e,t){let n=Up(r,".worktrees");await kS(n,{recursive:!0});let o=Up(n,e),i=["worktree","add","-B",`solo/${e}`,o];return t?i.push(t):i.push("HEAD"),await Yt("git",i,{cwd:r,encoding:"utf8"}),o}async function Np(r){try{await Yt("git",["add","-A"],{cwd:r});let{stdout:e}=await Yt("git",["diff","--cached","--stat"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return""}}async function jp(r,e){try{await Yt("git",["worktree","remove","--force",e],{cwd:r,encoding:"utf8"})}catch{try{await TS(e,{recursive:!0,force:!0})}catch{}}}async function Fp(r,e){let{stdout:t}=await Yt("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:r,encoding:"utf8"});return t.trim()}var wr=class{constructor(e,t,n,o={}){this.processManager=e;this.acpDetector=t;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;async start(e){let{task:t,agents:n,cwd:o}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let s=await Bn(o);if(!s)throw new Error("Solo Mode requires a git repository");let i=`solo-${wS().slice(0,8)}`,a={soloId:i,state:"running",task:t,cwd:o,gitRoot:s,agents:[],createdAt:Date.now()};this.sessions.set(i,a),this.callbacks.log?.info(`[solo] starting ${i} with ${n.length} agents`);let c=n.map(async(l,u)=>{let p=`${i}-${l}-${u}`,g=`solo/${p}`,f=`${i}:${l}:${u}`,m;try{m=await Tr(s,p)}catch(k){this.callbacks.log?.warn(`[solo] worktree creation failed for ${l}: ${k instanceof Error?k.message:String(k)}`);let b={agentId:l,memberId:f,worktreePath:"",worktreeBranch:g,state:"failed",error:`Worktree creation failed: ${k instanceof Error?k.message:String(k)}`};a.agents.push(b);return}let y={agentId:l,memberId:f,worktreePath:m,worktreeBranch:g,state:"pending"};a.agents.push(y);try{y.state="running",this.callbacks.onProgress?.(i,l,"running");let k=this.acpDetector.buildExternalDescriptor(l);if(!k)throw new Error(`Agent ${l} is not available or not ACP-compatible`);await this.processManager.spawn({memberId:f,name:`solo-${l}`,cwd:m,prompt:t,external:k});let b=this.processManager.getHandle(f);if(!b||b.state!=="ready")throw new Error(`Agent ${l} spawn did not reach ready state`);let x=await this.processManager.sendTask(f,t);y.state="completed",y.resultText=typeof x=="string"?x:JSON.stringify(x),y.diff=await Np(m);let S=this.processManager.getUsageTracker(f);if(S?.hasData()){let A=S.getUsage();y.usage={inputTokens:A.inputTokens,outputTokens:A.outputTokens}}this.callbacks.onProgress?.(i,l,"completed"),this.callbacks.log?.info(`[solo] ${l} completed (diff: ${y.diff?"yes":"none"})`)}catch(k){y.state="failed",y.error=k instanceof Error?k.message:String(k),this.callbacks.onProgress?.(i,l,"failed",y.error),this.callbacks.log?.warn(`[solo] ${l} failed: ${y.error}`)}});await Promise.allSettled(c);let d=a.agents.filter(l=>l.state==="completed");if(d.length===0)return a.state="failed",this.callbacks.log?.warn(`[solo] all agents failed for ${i}`),i;a.state="evaluating",this.callbacks.log?.info(`[solo] evaluating ${d.length} results for ${i}`);try{let l=await this.evaluate(a,d);a.evaluation=l,a.state="completed",this.callbacks.onEvaluation?.(i,l)}catch(l){a.state="completed",this.callbacks.log?.warn(`[solo] evaluation failed for ${i}: ${l instanceof Error?l.message:String(l)}`)}return i}getStatus(e){let t=this.sessions.get(e);return t?{soloId:t.soloId,state:t.state,agents:t.agents.map(n=>({id:n.agentId,state:n.state,progress:n.state==="running"?"Working...":void 0,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,worktreePath:n.worktreePath})),evaluation:t.evaluation}:null}async cancel(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state!=="running"&&t.state!=="evaluating")throw new Error(`Solo session ${e} is not running (state: ${t.state})`);t.state="cancelled";for(let n of t.agents)if(n.state==="running"||n.state==="pending"){n.state="failed",n.error="Cancelled by user";try{this.processManager.kill(n.memberId)}catch{}}await this.cleanupWorktrees(t),this.callbacks.log?.info(`[solo] cancelled ${e}`)}async select(e){let t=this.sessions.get(e.soloId);if(!t)throw new Error(`Solo session ${e.soloId} not found`);if(t.state!=="completed")throw new Error(`Solo session ${e.soloId} is not completed (state: ${t.state})`);let n=t.agents.find(s=>s.agentId===e.winnerId&&s.state==="completed");if(!n)throw new Error(`Agent ${e.winnerId} is not a completed participant in ${e.soloId}`);let o=await Fp(t.gitRoot,n.worktreeBranch);return this.callbacks.log?.info(`[solo] merged ${n.worktreeBranch}: ${o}`),await this.cleanupWorktrees(t),n.worktreeBranch}listSessions(){return[...this.sessions.values()].map(e=>this.getStatus(e.soloId))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state==="running"||t.state==="evaluating"){t.state="cancelled";for(let n of t.agents)if(n.state==="running"||n.state==="pending"){n.state="failed",n.error="Deleted";try{this.processManager.kill(n.memberId)}catch{}}await this.cleanupWorktrees(t)}this.sessions.delete(e),this.callbacks.log?.info(`[solo] deleted ${e}`)}async evaluate(e,t){if(t.length===1)return{winnerId:t[0].agentId,reasoning:`Only one agent (${t[0].agentId}) completed successfully.`};let n=["# Task Evaluation","","## Original Task",e.task,"","## Agent Results",""];for(let i of t)n.push(`### Agent: ${i.agentId}`,"","**Result:**",i.resultText??"(no output)","","**Changes (git diff stat):**",i.diff||"(no changes)","");n.push("## Instructions","","Review all agent results above. Select the best implementation and explain your reasoning.","Respond in this exact format:","","WINNER: <agent-id>","REASONING: <your explanation>");let o=n.join(`
434
- `),s=t[0].memberId;try{let i=await this.processManager.sendTask(s,o),a=typeof i=="string"?i:JSON.stringify(i);return this.parseEvaluationResponse(a,t)}catch{return{winnerId:t[0].agentId,reasoning:"Evaluation failed; defaulting to first completed agent."}}}parseEvaluationResponse(e,t){let n=e.match(/WINNER:\s*(\S+)/i),o=e.match(/REASONING:\s*(.+)/is),s=t.map(a=>a.agentId),i=n?.[1];if(i&&s.includes(i))return{winnerId:i,reasoning:o?.[1]?.trim()||"Selected by leader evaluation."};for(let a of s)if(e.includes(a))return{winnerId:a,reasoning:o?.[1]?.trim()||e.slice(0,500)};return{winnerId:t[0].agentId,reasoning:`Could not parse evaluation. Full response: ${e.slice(0,500)}`}}async cleanupWorktrees(e){for(let t of e.agents)if(t.worktreePath)try{try{this.processManager.kill(t.memberId)}catch{}this.processManager.remove(t.memberId),await jp(e.gitRoot,t.worktreePath)}catch(n){this.callbacks.log?.warn(`[solo] failed to clean worktree for ${t.agentId}: ${n instanceof Error?n.message:String(n)}`)}}};import{randomUUID as xS}from"node:crypto";var Gn=class{nodes=new Map;constructor(e){for(let t of e){if(this.nodes.has(t.taskId))throw new Error(`Duplicate task ID: ${t.taskId}`);this.nodes.set(t.taskId,{taskId:t.taskId,assignee:t.assignee,prompt:t.prompt,dependsOn:t.dependsOn??[],status:"pending"})}this.validateDag()}getAllTasks(){return[...this.nodes.values()]}getTask(e){return this.nodes.get(e)}getReadyTasks(){let e=[];for(let t of this.nodes.values()){if(t.status!=="pending")continue;t.dependsOn.every(o=>this.nodes.get(o)?.status==="completed")&&e.push(t)}return e}markRunning(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);if(t.status!=="pending")throw new Error(`Task ${e} is ${t.status}, cannot start`);t.status="running",t.startedAt=Date.now()}markCompleted(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Unknown task: ${e}`);if(n.status!=="running")throw new Error(`Task ${e} is ${n.status}, cannot complete`);n.status="completed",n.result=t,n.completedAt=Date.now()}markFailed(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Unknown task: ${e}`);n.status="failed",n.error=t,n.completedAt=Date.now()}markPaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="running"&&(t.status="paused")}resumePaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="paused"&&(t.status="pending")}isFinished(){for(let e of this.nodes.values())if(e.status==="running"||e.status==="paused"||e.status==="pending"&&!e.dependsOn.some(n=>this.nodes.get(n)?.status==="failed"))return!1;return!0}isAllCompleted(){return[...this.nodes.values()].every(e=>e.status==="completed")}getBlockedTasks(){return[...this.nodes.values()].filter(e=>e.status!=="pending"?!1:e.dependsOn.some(t=>this.nodes.get(t)?.status==="failed"))}pauseAll(){for(let e of this.nodes.values())e.status==="running"&&(e.status="paused")}resumeAll(){for(let e of this.nodes.values())e.status==="paused"&&(e.status="pending")}serialize(){return[...this.nodes.values()].map(e=>({taskId:e.taskId,assignee:e.assignee,prompt:e.prompt,dependsOn:e.dependsOn,status:e.status,result:e.result,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt}))}restore(e){for(let t of e){let n=this.nodes.get(t.taskId);n&&(n.status=t.status==="running"?"pending":t.status,n.result=t.result,n.error=t.error,n.startedAt=t.startedAt,n.completedAt=t.completedAt)}}validateDag(){for(let o of this.nodes.values())for(let s of o.dependsOn)if(!this.nodes.has(s))throw new Error(`Task "${o.taskId}" depends on unknown task "${s}"`);let e=new Set,t=new Set,n=o=>{if(t.has(o))throw new Error(`Cycle detected involving task "${o}"`);if(e.has(o))return;t.add(o);let s=this.nodes.get(o);for(let i of s.dependsOn)n(i);t.delete(o),e.add(o)};for(let o of this.nodes.keys())n(o)}};var Hn=class{maxTotalTokens;maxDuration;usedTokens=0;startedAt;warningEmitted=!1;constructor(e){this.maxTotalTokens=e?.maxTotalTokens,this.maxDuration=e?.maxDuration,this.startedAt=Date.now()}addUsage(e,t){this.usedTokens+=e+t}addFromTracker(e){if(!e.hasData())return;let t=e.getUsage();this.usedTokens+=t.totalTokens}getElapsed(){return Date.now()-this.startedAt}getBudget(){return{maxTotalTokens:this.maxTotalTokens,maxDuration:this.maxDuration,usedTokens:this.usedTokens,elapsed:this.getElapsed()}}check(){let e=this.getElapsed();if(this.maxDuration&&e>=this.maxDuration)return{action:"exceeded",percentage:Math.round(e/this.maxDuration*100),usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(this.maxTotalTokens){let n=Math.round(this.usedTokens/this.maxTotalTokens*100);if(this.usedTokens>=this.maxTotalTokens)return{action:"exceeded",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(n>=80&&!this.warningEmitted)return this.warningEmitted=!0,{action:"warning",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}return{action:"ok",percentage:this.maxTotalTokens?Math.round(this.usedTokens/this.maxTotalTokens*100):0,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}restore(e){this.usedTokens=e.usedTokens,this.startedAt=e.startedAt,this.warningEmitted=e.warningEmitted}serialize(){return{usedTokens:this.usedTokens,startedAt:this.startedAt,warningEmitted:this.warningEmitted}}};import{join as ya}from"node:path";import{mkdir as vS,readdir as SS}from"node:fs/promises";function Bp(r){return ya(je(r),"products")}function Gp(r,e){return ya(Bp(e),r)}function Hp(r,e){return ya(Gp(r,e),"product-state.json")}async function Wp(r,e){let t=Gp(r.productId,e);await vS(t,{recursive:!0}),await br(Hp(r.productId,e),r)}async function ba(r,e){return Fn(Hp(r,e))}async function zp(r){let e=Bp(r),t;try{t=await SS(e)}catch{return[]}let n=[];for(let o of t){let s=await ba(o,r);s&&n.push(s)}return n}var Wn=class r{constructor(e={}){this.callbacks=e}callbacks;static DEFAULT_INTERVAL=5*6e4;static LONG_RUNNING_INTERVAL=30*6e4;static LONG_RUNNING_THRESHOLD=2880*6e4;timer=null;lastCheckpointAt=0;cwd;start(e){this.cwd=e,this.stop(),this.timer=setInterval(()=>{let t=this.callbacks.getState?.();t&&this.checkpoint(t).catch(n=>{this.callbacks.log?.warn(`[checkpoint] periodic save failed: ${n instanceof Error?n.message:String(n)}`)})},r.DEFAULT_INTERVAL),this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getInterval(e){return e>r.LONG_RUNNING_THRESHOLD?r.LONG_RUNNING_INTERVAL:r.DEFAULT_INTERVAL}isDue(e){if(this.lastCheckpointAt===0)return!0;let t=this.getInterval(e);return Date.now()-this.lastCheckpointAt>=t}async checkpoint(e){let t=new Date().toISOString();e.lastCheckpointAt=t,await Wp(e,this.cwd),this.lastCheckpointAt=Date.now(),this.callbacks.onCheckpoint?.(e.productId,t),this.callbacks.log?.info(`[checkpoint] saved ${e.productId} at ${t}`)}getLastCheckpointAt(){return this.lastCheckpointAt}};var vr=class{constructor(e,t,n,o={}){this.processManager=e;this.acpDetector=t;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;async create(e){let{name:t,cwd:n,instances:o,tasks:s,budget:i}=e;if(o.length===0)throw new Error("Product requires at least 1 instance");if(s.length===0)throw new Error("Product requires at least 1 task");let a=new Set(o.map(m=>m.name));for(let m of s)if(!a.has(m.assignee))throw new Error(`Task "${m.taskId}" references unknown instance "${m.assignee}"`);let c=`product-${xS().slice(0,8)}`,d=new Gn(s),l=new Hn(i),u=new Wn({onCheckpoint:(m,y)=>this.callbacks.onCheckpointed?.(m,y),getState:()=>{let m=this.sessions.get(c);return m?this.buildPersistedState(m):null},log:this.callbacks.log}),p=await Bn(n),g=o.map((m,y)=>({instanceId:`${c}:${m.name}:${y}`,name:m.name,agentId:m.agentId,state:"idle"})),f={productId:c,name:t,cwd:n,phase:"active",instances:g,dag:d,budget:l,checkpoint:u,createdAt:new Date().toISOString(),gitRoot:p};return this.sessions.set(c,f),u.start(n),this.callbacks.log?.info(`[product] created ${c} "${t}" with ${o.length} instances, ${s.length} tasks`),this.scheduleNext(f),c}async resume(e,t){let n=await ba(e,t);if(!n)throw new Error(`Product ${e} not found on disk`);let o=new Gn(n.tasks);o.restore(n.tasks);let s=new Hn({maxTotalTokens:n.budget.maxTotalTokens,maxDuration:n.budget.maxDuration});s.restore(n.budget);let i=new Wn({onCheckpoint:(l,u)=>this.callbacks.onCheckpointed?.(l,u),getState:()=>{let l=this.sessions.get(e);return l?this.buildPersistedState(l):null},log:this.callbacks.log}),a=await Bn(n.cwd),c=n.instances.map((l,u)=>({instanceId:`${e}:${l.name}:${u}`,name:l.name,agentId:l.agentId,state:"idle"})),d={productId:n.productId,name:n.name,cwd:n.cwd,phase:"active",instances:c,dag:o,budget:s,checkpoint:i,createdAt:n.createdAt,gitRoot:a};this.sessions.set(e,d),i.start(n.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(d)}async pause(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase!=="active")throw new Error(`Product ${e} is not active`);t.phase="paused",t.dag.pauseAll();for(let n of t.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="paused"}await t.checkpoint.checkpoint(this.buildPersistedState(t)),t.checkpoint.stop(),this.callbacks.log?.info(`[product] paused ${e}`)}async checkpoint(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);await t.checkpoint.checkpoint(this.buildPersistedState(t))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase==="active"){t.phase="failed",t.dag.pauseAll();for(let n of t.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="failed"}}t.checkpoint.stop(),this.sessions.delete(e),this.callbacks.log?.info(`[product] deleted ${e}`)}getStatus(e){let t=this.sessions.get(e);return t?{productId:t.productId,name:t.name,phase:t.phase,instances:t.instances.map(n=>{let s=(n.memberId?this.processManager.getUsageTracker(n.memberId):null)?.getUsage();return{instanceId:n.instanceId,name:n.name,agentId:n.agentId,state:n.state,worktreePath:n.worktreePath,usage:s&&(s.inputTokens>0||s.outputTokens>0)?{inputTokens:s.inputTokens,outputTokens:s.outputTokens}:void 0}}),tasks:t.dag.getAllTasks().map(n=>({taskId:n.taskId,assignee:n.assignee,status:n.status,result:n.result,error:n.error,startedAt:n.startedAt?new Date(n.startedAt).toISOString():void 0,completedAt:n.completedAt?new Date(n.completedAt).toISOString():void 0})),budget:t.budget.getBudget(),lastCheckpointAt:new Date(t.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}:null}async list(e){let t=[];for(let o of this.sessions.values()){let s=o.dag.getAllTasks();t.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:s.length,completedTasks:s.filter(i=>i.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:new Date(o.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()})}let n=await zp(e);for(let o of n)this.sessions.has(o.productId)||t.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:o.tasks.length,completedTasks:o.tasks.filter(s=>s.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:o.lastCheckpointAt});return t}scheduleNext(e){if(e.phase!=="active")return;let t=e.budget.check();if(t.action==="exceeded"){this.callbacks.log?.warn(`[product] ${e.productId} budget exceeded, auto-pausing`),this.pause(e.productId).catch(o=>{this.callbacks.log?.warn(`[product] auto-pause failed: ${o instanceof Error?o.message:String(o)}`)});return}if(t.action==="warning"&&this.callbacks.onBudgetWarning?.(e.productId,t.usedTokens,t.maxTotalTokens,t.percentage),e.dag.isFinished()){this.finishProduct(e);return}let n=e.dag.getReadyTasks();for(let o of n)this.dispatchTask(e,o)}dispatchTask(e,t){let n=e.instances.find(o=>o.name===t.assignee);if(!n){e.dag.markFailed(t.taskId,`No instance found for assignee "${t.assignee}"`),this.callbacks.onTaskFailed?.(e.productId,t.taskId,`No instance for "${t.assignee}"`),this.scheduleNext(e);return}e.dag.markRunning(t.taskId),n.state="running",this.callbacks.onTaskStarted?.(e.productId,t.taskId,t.assignee),this.callbacks.log?.info(`[product] ${e.productId} dispatching task ${t.taskId} to ${t.assignee}`),this.runTask(e,n,t).catch(o=>{this.callbacks.log?.warn(`[product] task dispatch error: ${o instanceof Error?o.message:String(o)}`)})}async runTask(e,t,n){let o=`${e.productId}:${t.name}:${n.taskId}`;t.memberId=o;try{let s=this.acpDetector.buildExternalDescriptor(t.agentId);if(!s)throw new Error(`Agent ${t.agentId} is not available`);let i=e.cwd;if(e.gitRoot){let l=`${e.productId}-${t.name}-${n.taskId}`;try{i=await Tr(e.gitRoot,l),t.worktreePath=i}catch{this.callbacks.log?.warn(`[product] worktree creation failed for ${n.taskId}, using project cwd`)}}await this.processManager.spawn({memberId:o,name:`product-${t.name}`,cwd:i,prompt:n.prompt,external:s});let a=await this.processManager.sendTask(o,n.prompt),c=typeof a=="string"?a:JSON.stringify(a),d=this.processManager.getUsageTracker(o);if(d?.hasData()){let l=d.getUsage();e.budget.addUsage(l.inputTokens,l.outputTokens)}e.dag.markCompleted(n.taskId,c),t.state="completed",this.callbacks.onTaskCompleted?.(e.productId,n.taskId,c);try{this.processManager.kill(o)}catch{}this.processManager.remove(o)}catch(s){let i=s instanceof Error?s.message:String(s);e.dag.markFailed(n.taskId,i),t.state="failed",this.callbacks.onTaskFailed?.(e.productId,n.taskId,i);try{this.processManager.kill(o)}catch{}try{this.processManager.remove(o)}catch{}}try{await e.checkpoint.checkpoint(this.buildPersistedState(e))}catch(s){this.callbacks.log?.warn(`[product] checkpoint failed: ${s instanceof Error?s.message:String(s)}`)}this.scheduleNext(e)}finishProduct(e){if(e.dag.isAllCompleted()){e.phase="completed";let t=e.dag.getAllTasks(),n=`Product "${e.name}" completed: ${t.length} tasks all done.`;this.callbacks.onCompleted?.(e.productId,n)}else{e.phase="failed";let n=e.dag.getAllTasks().filter(i=>i.status==="failed").length,o=e.dag.getBlockedTasks().length,s=`Product "${e.name}" finished with ${n} failed, ${o} blocked tasks.`;this.callbacks.onCompleted?.(e.productId,s)}e.checkpoint.stop(),e.checkpoint.checkpoint(this.buildPersistedState(e)).catch(t=>{this.callbacks.log?.warn(`[product] final checkpoint failed: ${t instanceof Error?t.message:String(t)}`)}),this.callbacks.log?.info(`[product] ${e.productId} finished (phase=${e.phase})`)}buildPersistedState(e){return{productId:e.productId,name:e.name,phase:e.phase,cwd:e.cwd,instances:e.instances.map(t=>({name:t.name,role:"",agentId:t.agentId})),tasks:e.dag.serialize(),budget:e.budget.serialize(),createdAt:e.createdAt,lastCheckpointAt:new Date(e.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}}};var Vp="memory",qp="Memory",RS=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search"],Kp={type:"object",properties:{action:{type:"string",enum:RS,description:["Operation to perform:","","INDEX.md operations (always-visible notes in system prompt):","\u2022 'add' \u2014 Append a note to INDEX.md","\u2022 'replace' \u2014 Replace text in INDEX.md (str_replace semantics)","\u2022 'remove' \u2014 Remove text from INDEX.md","","Topic file operations (on-demand, for longer content):","\u2022 'create_file' \u2014 Create a new .md topic file","\u2022 'write_file' \u2014 Overwrite an existing topic file","\u2022 'read_file' \u2014 Read a topic file","\u2022 'delete_file' \u2014 Delete a topic file","\u2022 'list_files' \u2014 List all memory topic files","","Search:","\u2022 'search' \u2014 Search long-term memory (QMemory) + local keyword match"].join(`
432
+ `;try{n.write(s)}catch{}}}async attemptRuntimeRestart(e,t,n){let o=this.callbacks.log,s=this.processes.get(e.memberId),i=s?.ipcServer,a=s?.ipcPath,c=s?.stderrStream;this.processes.delete(e.memberId);try{let d={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()},l=e.external,u=[...l.acpArgs];a&&(t.QLOGICAGENT_PARENT_RPC=a);let p=wa(l.cliPath,u,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!1});d.pid=p.pid??-1;let m=new Map,f=new $t,g=new Bn;this.processes.set(e.memberId,{handle:d,child:p,pendingRpc:m,acpAdapter:f,usageTracker:g,ipcServer:i,ipcPath:a,stderrStream:c,runtimeRestartCount:n}),f.attach(p,(k,S)=>{k==="usage_update"&&g.onUsageUpdate(S);let R=$t.translateNotification(k,S);R?(this.captureChildProgress(e.memberId,R.method,R.params),this.callbacks.onNotification?.(e.memberId,R.method,R.params)):(this.captureChildProgress(e.memberId,k,S),this.callbacks.onNotification?.(e.memberId,k,S))}),p.stderr&&wr({input:p.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",S=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${S}`),c?.write(`${new Date().toISOString()} ${S}
433
+ `)}),p.on("exit",(k,S)=>{f.detach();let R=d.state;if(R!=="killed"&&R!=="completed"&&k!==0){let O=this.processes.get(e.memberId)?.runtimeRestartCount??n;if(O<Qt){let L=Qp*2**O;this.slog("warn",e.memberId,"crash",`crashed again (code=${k}), restart ${O+1}/${Qt}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${k}), restarting`,retriesLeft:Qt-O-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,t,O+1).catch(B=>{this.slog("warn",e.memberId,"restart",`failed: ${B instanceof Error?B.message:String(B)}`)})},L);return}}R!=="killed"&&(d.state=k===0?"completed":"failed"),d.endedAt=Date.now(),k!==0&&!d.error&&(d.error=`ACP process exited with code ${k} (signal: ${S})`),this.callbacks.onStateChange?.(e.memberId,d.state),this.callbacks.onExit?.(e.memberId,k,S)}),p.on("error",k=>{f.detach(),d.state="failed",d.error=k.message,d.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let y=await f.initialize(p);d.state="ready",d.supportsResume=y.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${n}, protocol=${y.protocolVersion}, loadSession=${d.supportsResume}, pid=${d.pid})`);let b=[...e.mcpServers??[]];a&&b.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(d.supportsResume&&d.sessionId){let k=await f.resumeSession(p,d.sessionId,{cwd:e.cwd,mcpServers:b.length>0?b:void 0});d.sessionId=k.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${d.sessionId})`)}else{let k={cwd:e.cwd};b.length>0&&(k.mcpServers=b),e.systemPrompt&&(k.systemPrompt=e.systemPrompt);let S=await f.createSession(p,k);d.sessionId=S.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${d.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,k=>{this.slog("warn",k,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(k,"agents.error",{agentId:k,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(k)})}catch(d){let l=this.processes.get(e.memberId);l&&(l.handle.state="failed",l.handle.error=`Runtime restart failed: ${d instanceof Error?d.message:String(d)}`,l.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${n} attempts: ${d instanceof Error?d.message:String(d)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,t){this.stopHeartbeat(e),this.missedBeats.set(e,0);let n=setInterval(async()=>{let o=this.processes.get(e);if(!o||o.handle.state==="completed"||o.handle.state==="failed"||o.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let i=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,i),this.slog("warn",e,"heartbeat",`missed (${i}/${r.MAX_MISSED_BEATS})`),i>=r.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),o.handle.error=`Hang detected: ${i} consecutive heartbeat failures`,this.kill(e),t?.(e))},r.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,n)}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let t=this.processes.get(e);t&&(this.stopHeartbeat(e),(t.handle.state==="running"||t.handle.state==="starting"||t.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};import{join as em}from"node:path";import{chmod as OS}from"node:fs/promises";import{readFile as _S,writeFile as xS,mkdir as AS,rename as CS,unlink as PS}from"node:fs/promises";import{dirname as IS,join as MS}from"node:path";import{randomUUID as ES}from"node:crypto";async function en(r,e){let t=IS(r);await AS(t,{recursive:!0});let n=MS(t,`.tmp-${ES()}`);try{await xS(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await CS(n,r);return}catch(i){if(o=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw o}catch(o){throw await PS(n).catch(()=>{}),o}}async function Gn(r){try{let e=await _S(r,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function vr(r,e){await en(r,JSON.stringify(e,null,2)+`
434
+ `)}var tm="agent-configs.json";function Zp(){return em(X(),tm)}function DS(r){return em(Be(r),tm)}function LS(){return{agents:{}}}var Sr=class{data=LS();cwd;constructor(e){this.cwd=e}async load(){let e=await Gn(Zp()),t=this.cwd?await Gn(DS(this.cwd)):void 0,n={gatewayUrl:e?.gatewayUrl,agents:{...e?.agents},customAgents:{...e?.customAgents}};if(t){t.gatewayUrl&&(n.gatewayUrl=t.gatewayUrl);for(let[o,s]of Object.entries(t.agents??{}))n.agents[o]={...n.agents[o],...s};for(let[o,s]of Object.entries(t.customAgents??{}))n.customAgents??={},n.customAgents[o]=s}this.data=n}getData(){return this.data}getAgentConfig(e){return this.data.agents[e]??null}async setAgentConfig(e,t){this.data.agents[e]={...this.data.agents[e],...t},await this.save()}async removeAgentConfig(e){delete this.data.agents[e],await this.save()}getGatewayUrl(){return this.data.gatewayUrl}async setGatewayUrl(e){this.data.gatewayUrl=e,await this.save()}registerCustomAgent(e){this.data.customAgents??={},this.data.customAgents[e.id]=e}unregisterCustomAgent(e){this.data.customAgents&&delete this.data.customAgents[e]}getCustomAgents(){return{...this.data.customAgents}}async save(){let e=Zp();await vr(e,this.data);try{await OS(e,384)}catch{}}};import{randomUUID as FS}from"node:crypto";import{execFile as NS}from"node:child_process";import{promisify as US}from"node:util";import{join as nm}from"node:path";import{mkdir as $S,rm as jS}from"node:fs/promises";var tn=US(NS);async function Hn(r){try{let{stdout:e}=await tn("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return null}}async function Rr(r,e,t){let n=nm(r,".worktrees");await $S(n,{recursive:!0});let o=nm(n,e),i=["worktree","add","-B",`solo/${e}`,o];return t?i.push(t):i.push("HEAD"),await tn("git",i,{cwd:r,encoding:"utf8"}),o}async function om(r){try{await tn("git",["add","-A"],{cwd:r});let{stdout:e}=await tn("git",["diff","--cached","--stat"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return""}}async function rm(r,e){try{await tn("git",["worktree","remove","--force",e],{cwd:r,encoding:"utf8"})}catch{try{await jS(e,{recursive:!0,force:!0})}catch{}}}async function sm(r,e){let{stdout:t}=await tn("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:r,encoding:"utf8"});return t.trim()}var _r=class{constructor(e,t,n,o={}){this.processManager=e;this.acpDetector=t;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;async start(e){let{task:t,agents:n,cwd:o}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let s=await Hn(o);if(!s)throw new Error("Solo Mode requires a git repository");let i=`solo-${FS().slice(0,8)}`,a={soloId:i,state:"running",task:t,cwd:o,gitRoot:s,agents:[],createdAt:Date.now()};this.sessions.set(i,a),this.callbacks.log?.info(`[solo] starting ${i} with ${n.length} agents`);let c=n.map(async(l,u)=>{let p=`${i}-${l}-${u}`,m=`solo/${p}`,f=`${i}:${l}:${u}`,g;try{g=await Rr(s,p)}catch(b){this.callbacks.log?.warn(`[solo] worktree creation failed for ${l}: ${b instanceof Error?b.message:String(b)}`);let k={agentId:l,memberId:f,worktreePath:"",worktreeBranch:m,state:"failed",error:`Worktree creation failed: ${b instanceof Error?b.message:String(b)}`};a.agents.push(k);return}let y={agentId:l,memberId:f,worktreePath:g,worktreeBranch:m,state:"pending"};a.agents.push(y);try{y.state="running",this.callbacks.onProgress?.(i,l,"running");let b=this.acpDetector.buildExternalDescriptor(l);if(!b)throw new Error(`Agent ${l} is not available or not ACP-compatible`);await this.processManager.spawn({memberId:f,name:`solo-${l}`,cwd:g,prompt:t,external:b});let k=this.processManager.getHandle(f);if(!k||k.state!=="ready")throw new Error(`Agent ${l} spawn did not reach ready state`);let S=await this.processManager.sendTask(f,t);y.state="completed",y.resultText=typeof S=="string"?S:JSON.stringify(S),y.diff=await om(g);let R=this.processManager.getUsageTracker(f);if(R?.hasData()){let P=R.getUsage();y.usage={inputTokens:P.inputTokens,outputTokens:P.outputTokens}}this.callbacks.onProgress?.(i,l,"completed"),y.diff&&this.callbacks.onAgentDiff?.(i,l,[{path:".",hunks:y.diff}]),y.usage&&this.callbacks.onAgentUsage?.(i,l,y.usage.inputTokens,y.usage.outputTokens),this.callbacks.log?.info(`[solo] ${l} completed (diff: ${y.diff?"yes":"none"})`)}catch(b){y.state="failed",y.error=b instanceof Error?b.message:String(b),this.callbacks.onProgress?.(i,l,"failed",y.error),this.callbacks.log?.warn(`[solo] ${l} failed: ${y.error}`)}});await Promise.allSettled(c);let d=a.agents.filter(l=>l.state==="completed");if(d.length===0)return a.state="failed",this.callbacks.log?.warn(`[solo] all agents failed for ${i}`),i;a.state="evaluating",this.callbacks.log?.info(`[solo] evaluating ${d.length} results for ${i}`);try{let l=await this.evaluate(a,d);a.evaluation=l,a.state="completed",this.callbacks.onEvaluation?.(i,l)}catch(l){a.state="completed",this.callbacks.log?.warn(`[solo] evaluation failed for ${i}: ${l instanceof Error?l.message:String(l)}`)}return i}getStatus(e){let t=this.sessions.get(e);return t?{soloId:t.soloId,state:t.state,agents:t.agents.map(n=>({id:n.agentId,state:n.state,progress:n.state==="running"?"Working...":void 0,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,worktreePath:n.worktreePath})),evaluation:t.evaluation}:null}async cancel(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state!=="running"&&t.state!=="evaluating")throw new Error(`Solo session ${e} is not running (state: ${t.state})`);t.state="cancelled";for(let n of t.agents)if(n.state==="running"||n.state==="pending"){n.state="failed",n.error="Cancelled by user";try{this.processManager.kill(n.memberId)}catch{}}await this.cleanupWorktrees(t),this.callbacks.log?.info(`[solo] cancelled ${e}`)}async select(e){let t=this.sessions.get(e.soloId);if(!t)throw new Error(`Solo session ${e.soloId} not found`);if(t.state!=="completed")throw new Error(`Solo session ${e.soloId} is not completed (state: ${t.state})`);let n=t.agents.find(s=>s.agentId===e.winnerId&&s.state==="completed");if(!n)throw new Error(`Agent ${e.winnerId} is not a completed participant in ${e.soloId}`);let o=await sm(t.gitRoot,n.worktreeBranch);return this.callbacks.log?.info(`[solo] merged ${n.worktreeBranch}: ${o}`),await this.cleanupWorktrees(t),n.worktreeBranch}listSessions(){return[...this.sessions.values()].map(e=>this.getStatus(e.soloId))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state==="running"||t.state==="evaluating"){t.state="cancelled";for(let n of t.agents)if(n.state==="running"||n.state==="pending"){n.state="failed",n.error="Deleted";try{this.processManager.kill(n.memberId)}catch{}}await this.cleanupWorktrees(t)}this.sessions.delete(e),this.callbacks.log?.info(`[solo] deleted ${e}`)}async evaluate(e,t){if(t.length===1)return{winnerId:t[0].agentId,reasoning:`Only one agent (${t[0].agentId}) completed successfully.`};let n=["# Task Evaluation","","## Original Task",e.task,"","## Agent Results",""];for(let i of t)n.push(`### Agent: ${i.agentId}`,"","**Result:**",i.resultText??"(no output)","","**Changes (git diff stat):**",i.diff||"(no changes)","");n.push("## Instructions","","Review all agent results above. Select the best implementation and explain your reasoning.","Respond in this exact format:","","WINNER: <agent-id>","REASONING: <your explanation>");let o=n.join(`
435
+ `),s=t[0].memberId;try{let i=await this.processManager.sendTask(s,o),a=typeof i=="string"?i:JSON.stringify(i);return this.parseEvaluationResponse(a,t)}catch{return{winnerId:t[0].agentId,reasoning:"Evaluation failed; defaulting to first completed agent."}}}parseEvaluationResponse(e,t){let n=e.match(/WINNER:\s*(\S+)/i),o=e.match(/REASONING:\s*(.+)/is),s=t.map(a=>a.agentId),i=n?.[1];if(i&&s.includes(i))return{winnerId:i,reasoning:o?.[1]?.trim()||"Selected by leader evaluation."};for(let a of s)if(e.includes(a))return{winnerId:a,reasoning:o?.[1]?.trim()||e.slice(0,500)};return{winnerId:t[0].agentId,reasoning:`Could not parse evaluation. Full response: ${e.slice(0,500)}`}}async cleanupWorktrees(e){for(let t of e.agents)if(t.worktreePath)try{try{this.processManager.kill(t.memberId)}catch{}this.processManager.remove(t.memberId),await rm(e.gitRoot,t.worktreePath)}catch(n){this.callbacks.log?.warn(`[solo] failed to clean worktree for ${t.agentId}: ${n instanceof Error?n.message:String(n)}`)}}};import{randomUUID as GS}from"node:crypto";var Vn=class{nodes=new Map;constructor(e){for(let t of e){if(this.nodes.has(t.taskId))throw new Error(`Duplicate task ID: ${t.taskId}`);this.nodes.set(t.taskId,{taskId:t.taskId,assignee:t.assignee,prompt:t.prompt,dependsOn:t.dependsOn??[],status:"pending"})}this.validateDag()}getAllTasks(){return[...this.nodes.values()]}getTask(e){return this.nodes.get(e)}getReadyTasks(){let e=[];for(let t of this.nodes.values()){if(t.status!=="pending")continue;t.dependsOn.every(o=>this.nodes.get(o)?.status==="completed")&&e.push(t)}return e}markRunning(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);if(t.status!=="pending")throw new Error(`Task ${e} is ${t.status}, cannot start`);t.status="running",t.startedAt=Date.now()}markCompleted(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Unknown task: ${e}`);if(n.status!=="running")throw new Error(`Task ${e} is ${n.status}, cannot complete`);n.status="completed",n.result=t,n.completedAt=Date.now()}markFailed(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Unknown task: ${e}`);n.status="failed",n.error=t,n.completedAt=Date.now()}markPaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="running"&&(t.status="paused")}resumePaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="paused"&&(t.status="pending")}isFinished(){for(let e of this.nodes.values())if(e.status==="running"||e.status==="paused"||e.status==="pending"&&!e.dependsOn.some(n=>this.nodes.get(n)?.status==="failed"))return!1;return!0}isAllCompleted(){return[...this.nodes.values()].every(e=>e.status==="completed")}getBlockedTasks(){return[...this.nodes.values()].filter(e=>e.status!=="pending"?!1:e.dependsOn.some(t=>this.nodes.get(t)?.status==="failed"))}pauseAll(){for(let e of this.nodes.values())e.status==="running"&&(e.status="paused")}resumeAll(){for(let e of this.nodes.values())e.status==="paused"&&(e.status="pending")}serialize(){return[...this.nodes.values()].map(e=>({taskId:e.taskId,assignee:e.assignee,prompt:e.prompt,dependsOn:e.dependsOn,status:e.status,result:e.result,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt}))}restore(e){for(let t of e){let n=this.nodes.get(t.taskId);n&&(n.status=t.status==="running"?"pending":t.status,n.result=t.result,n.error=t.error,n.startedAt=t.startedAt,n.completedAt=t.completedAt)}}validateDag(){for(let o of this.nodes.values())for(let s of o.dependsOn)if(!this.nodes.has(s))throw new Error(`Task "${o.taskId}" depends on unknown task "${s}"`);let e=new Set,t=new Set,n=o=>{if(t.has(o))throw new Error(`Cycle detected involving task "${o}"`);if(e.has(o))return;t.add(o);let s=this.nodes.get(o);for(let i of s.dependsOn)n(i);t.delete(o),e.add(o)};for(let o of this.nodes.keys())n(o)}};var zn=class{maxTotalTokens;maxDuration;usedTokens=0;startedAt;warningEmitted=!1;constructor(e){this.maxTotalTokens=e?.maxTotalTokens,this.maxDuration=e?.maxDuration,this.startedAt=Date.now()}addUsage(e,t){this.usedTokens+=e+t}addFromTracker(e){if(!e.hasData())return;let t=e.getUsage();this.usedTokens+=t.totalTokens}getElapsed(){return Date.now()-this.startedAt}getBudget(){return{maxTotalTokens:this.maxTotalTokens,maxDuration:this.maxDuration,usedTokens:this.usedTokens,elapsed:this.getElapsed()}}check(){let e=this.getElapsed();if(this.maxDuration&&e>=this.maxDuration)return{action:"exceeded",percentage:Math.round(e/this.maxDuration*100),usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(this.maxTotalTokens){let n=Math.round(this.usedTokens/this.maxTotalTokens*100);if(this.usedTokens>=this.maxTotalTokens)return{action:"exceeded",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(n>=80&&!this.warningEmitted)return this.warningEmitted=!0,{action:"warning",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}return{action:"ok",percentage:this.maxTotalTokens?Math.round(this.usedTokens/this.maxTotalTokens*100):0,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}restore(e){this.usedTokens=e.usedTokens,this.startedAt=e.startedAt,this.warningEmitted=e.warningEmitted}serialize(){return{usedTokens:this.usedTokens,startedAt:this.startedAt,warningEmitted:this.warningEmitted}}};import{join as Sa}from"node:path";import{mkdir as BS,readdir as WS}from"node:fs/promises";function im(r){return Sa(Be(r),"products")}function am(r,e){return Sa(im(e),r)}function cm(r,e){return Sa(am(r,e),"product-state.json")}async function lm(r,e){let t=am(r.productId,e);await BS(t,{recursive:!0}),await vr(cm(r.productId,e),r)}async function Ra(r,e){return Gn(cm(r,e))}async function dm(r){let e=im(r),t;try{t=await WS(e)}catch{return[]}let n=[];for(let o of t){let s=await Ra(o,r);s&&n.push(s)}return n}var Kn=class r{constructor(e={}){this.callbacks=e}callbacks;static DEFAULT_INTERVAL=5*6e4;static LONG_RUNNING_INTERVAL=30*6e4;static LONG_RUNNING_THRESHOLD=2880*6e4;timer=null;lastCheckpointAt=0;cwd;start(e){this.cwd=e,this.stop(),this.timer=setInterval(()=>{let t=this.callbacks.getState?.();t&&this.checkpoint(t).catch(n=>{this.callbacks.log?.warn(`[checkpoint] periodic save failed: ${n instanceof Error?n.message:String(n)}`)})},r.DEFAULT_INTERVAL),this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getInterval(e){return e>r.LONG_RUNNING_THRESHOLD?r.LONG_RUNNING_INTERVAL:r.DEFAULT_INTERVAL}isDue(e){if(this.lastCheckpointAt===0)return!0;let t=this.getInterval(e);return Date.now()-this.lastCheckpointAt>=t}async checkpoint(e){let t=new Date().toISOString();e.lastCheckpointAt=t,await lm(e,this.cwd),this.lastCheckpointAt=Date.now(),this.callbacks.onCheckpoint?.(e.productId,t),this.callbacks.log?.info(`[checkpoint] saved ${e.productId} at ${t}`)}getLastCheckpointAt(){return this.lastCheckpointAt}};var xr=class{constructor(e,t,n,o={}){this.processManager=e;this.acpDetector=t;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;async create(e){let{name:t,cwd:n,instances:o,tasks:s,budget:i}=e;if(o.length===0)throw new Error("Product requires at least 1 instance");if(s.length===0)throw new Error("Product requires at least 1 task");let a=new Set(o.map(b=>b.name));for(let b of s)if(!a.has(b.assignee))throw new Error(`Task "${b.taskId}" references unknown instance "${b.assignee}"`);let c=`product-${GS().slice(0,8)}`,d=new Vn(s),l=new zn(i),u=new Kn({onCheckpoint:(b,k)=>this.callbacks.onCheckpointed?.(b,k),getState:()=>{let b=this.sessions.get(c);return b?this.buildPersistedState(b):null},log:this.callbacks.log}),p=await Hn(n),m=o.map((b,k)=>({instanceId:`${c}:${b.name}:${k}`,name:b.name,agentId:b.agentId,state:"idle"})),f={productId:c,name:t,cwd:n,phase:"active",instances:m,dag:d,budget:l,checkpoint:u,createdAt:new Date().toISOString(),gitRoot:p};this.sessions.set(c,f),u.start(n),this.callbacks.log?.info(`[product] created ${c} "${t}" with ${o.length} instances, ${s.length} tasks`);let g=s.map(b=>({id:b.taskId,label:b.taskId,deps:b.dependsOn??[]})),y=[];for(let b of s)if(b.dependsOn)for(let k of b.dependsOn)y.push({from:k,to:b.taskId});return this.callbacks.onDagTopology?.(c,g,y),this.scheduleNext(f),c}async resume(e,t){let n=await Ra(e,t);if(!n)throw new Error(`Product ${e} not found on disk`);let o=new Vn(n.tasks);o.restore(n.tasks);let s=new zn({maxTotalTokens:n.budget.maxTotalTokens,maxDuration:n.budget.maxDuration});s.restore(n.budget);let i=new Kn({onCheckpoint:(l,u)=>this.callbacks.onCheckpointed?.(l,u),getState:()=>{let l=this.sessions.get(e);return l?this.buildPersistedState(l):null},log:this.callbacks.log}),a=await Hn(n.cwd),c=n.instances.map((l,u)=>({instanceId:`${e}:${l.name}:${u}`,name:l.name,agentId:l.agentId,state:"idle"})),d={productId:n.productId,name:n.name,cwd:n.cwd,phase:"active",instances:c,dag:o,budget:s,checkpoint:i,createdAt:n.createdAt,gitRoot:a};this.sessions.set(e,d),i.start(n.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(d)}async pause(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase!=="active")throw new Error(`Product ${e} is not active`);t.phase="paused",t.dag.pauseAll();for(let n of t.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="paused"}await t.checkpoint.checkpoint(this.buildPersistedState(t)),t.checkpoint.stop(),this.callbacks.log?.info(`[product] paused ${e}`)}async checkpoint(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);await t.checkpoint.checkpoint(this.buildPersistedState(t))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase==="active"){t.phase="failed",t.dag.pauseAll();for(let n of t.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="failed"}}t.checkpoint.stop(),this.sessions.delete(e),this.callbacks.log?.info(`[product] deleted ${e}`)}async rollback(e,t){let n=this.sessions.get(e);if(!n)throw new Error(`Product ${e} not found`);let o=n.cwd;await this.delete(e),await this.resume(e,o),this.callbacks.log?.info(`[product] rolled back ${e} to checkpoint ${t}`)}getStatus(e){let t=this.sessions.get(e);return t?{productId:t.productId,name:t.name,phase:t.phase,instances:t.instances.map(n=>{let s=(n.memberId?this.processManager.getUsageTracker(n.memberId):null)?.getUsage();return{instanceId:n.instanceId,name:n.name,agentId:n.agentId,state:n.state,worktreePath:n.worktreePath,usage:s&&(s.inputTokens>0||s.outputTokens>0)?{inputTokens:s.inputTokens,outputTokens:s.outputTokens}:void 0}}),tasks:t.dag.getAllTasks().map(n=>({taskId:n.taskId,assignee:n.assignee,status:n.status,result:n.result,error:n.error,startedAt:n.startedAt?new Date(n.startedAt).toISOString():void 0,completedAt:n.completedAt?new Date(n.completedAt).toISOString():void 0})),budget:t.budget.getBudget(),lastCheckpointAt:new Date(t.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}:null}async list(e){let t=[];for(let o of this.sessions.values()){let s=o.dag.getAllTasks();t.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:s.length,completedTasks:s.filter(i=>i.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:new Date(o.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()})}let n=await dm(e);for(let o of n)this.sessions.has(o.productId)||t.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:o.tasks.length,completedTasks:o.tasks.filter(s=>s.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:o.lastCheckpointAt});return t}scheduleNext(e){if(e.phase!=="active")return;let t=e.budget.check();if(t.action==="exceeded"){this.callbacks.log?.warn(`[product] ${e.productId} budget exceeded, auto-pausing`),this.pause(e.productId).catch(o=>{this.callbacks.log?.warn(`[product] auto-pause failed: ${o instanceof Error?o.message:String(o)}`)});return}if(t.action==="warning"&&this.callbacks.onBudgetWarning?.(e.productId,t.usedTokens,t.maxTotalTokens,t.percentage),e.dag.isFinished()){this.finishProduct(e);return}let n=e.dag.getReadyTasks();for(let o of n)this.dispatchTask(e,o)}dispatchTask(e,t){let n=e.instances.find(o=>o.name===t.assignee);if(!n){e.dag.markFailed(t.taskId,`No instance found for assignee "${t.assignee}"`),this.callbacks.onTaskFailed?.(e.productId,t.taskId,`No instance for "${t.assignee}"`),this.scheduleNext(e);return}e.dag.markRunning(t.taskId),n.state="running",this.callbacks.onTaskStarted?.(e.productId,t.taskId,t.assignee),this.callbacks.log?.info(`[product] ${e.productId} dispatching task ${t.taskId} to ${t.assignee}`),this.runTask(e,n,t).catch(o=>{this.callbacks.log?.warn(`[product] task dispatch error: ${o instanceof Error?o.message:String(o)}`)})}async runTask(e,t,n){let o=`${e.productId}:${t.name}:${n.taskId}`;t.memberId=o;try{let s=this.acpDetector.buildExternalDescriptor(t.agentId);if(!s)throw new Error(`Agent ${t.agentId} is not available`);let i=e.cwd;if(e.gitRoot){let l=`${e.productId}-${t.name}-${n.taskId}`;try{i=await Rr(e.gitRoot,l),t.worktreePath=i}catch{this.callbacks.log?.warn(`[product] worktree creation failed for ${n.taskId}, using project cwd`)}}await this.processManager.spawn({memberId:o,name:`product-${t.name}`,cwd:i,prompt:n.prompt,external:s});let a=await this.processManager.sendTask(o,n.prompt),c=typeof a=="string"?a:JSON.stringify(a),d=this.processManager.getUsageTracker(o);if(d?.hasData()){let l=d.getUsage();e.budget.addUsage(l.inputTokens,l.outputTokens);let u=e.budget.getBudget();this.callbacks.onBudgetUpdate?.(e.productId,u.usedTokens,0,u.elapsed,u.maxTotalTokens)}e.dag.markCompleted(n.taskId,c),t.state="completed",this.callbacks.onTaskCompleted?.(e.productId,n.taskId,c);try{this.processManager.kill(o)}catch{}this.processManager.remove(o)}catch(s){let i=s instanceof Error?s.message:String(s);e.dag.markFailed(n.taskId,i),t.state="failed",this.callbacks.onTaskFailed?.(e.productId,n.taskId,i);try{this.processManager.kill(o)}catch{}try{this.processManager.remove(o)}catch{}}try{await e.checkpoint.checkpoint(this.buildPersistedState(e))}catch(s){this.callbacks.log?.warn(`[product] checkpoint failed: ${s instanceof Error?s.message:String(s)}`)}this.scheduleNext(e)}finishProduct(e){if(e.dag.isAllCompleted()){e.phase="completed";let t=e.dag.getAllTasks(),n=`Product "${e.name}" completed: ${t.length} tasks all done.`;this.callbacks.onCompleted?.(e.productId,n)}else{e.phase="failed";let n=e.dag.getAllTasks().filter(i=>i.status==="failed").length,o=e.dag.getBlockedTasks().length,s=`Product "${e.name}" finished with ${n} failed, ${o} blocked tasks.`;this.callbacks.onCompleted?.(e.productId,s)}e.checkpoint.stop(),e.checkpoint.checkpoint(this.buildPersistedState(e)).catch(t=>{this.callbacks.log?.warn(`[product] final checkpoint failed: ${t instanceof Error?t.message:String(t)}`)}),this.callbacks.log?.info(`[product] ${e.productId} finished (phase=${e.phase})`)}buildPersistedState(e){return{productId:e.productId,name:e.name,phase:e.phase,cwd:e.cwd,instances:e.instances.map(t=>({name:t.name,role:"",agentId:t.agentId})),tasks:e.dag.serialize(),budget:e.budget.serialize(),createdAt:e.createdAt,lastCheckpointAt:new Date(e.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}}};var um="memory",pm="Memory",HS=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search"],mm={type:"object",properties:{action:{type:"string",enum:HS,description:["Operation to perform:","","INDEX.md operations (always-visible notes in system prompt):","\u9225?'add' \u9225?Append a note to INDEX.md","\u9225?'replace' \u9225?Replace text in INDEX.md (str_replace semantics)","\u9225?'remove' \u9225?Remove text from INDEX.md","","Topic file operations (on-demand, for longer content):","\u9225?'create_file' \u9225?Create a new .md topic file","\u9225?'write_file' \u9225?Overwrite an existing topic file","\u9225?'read_file' \u9225?Read a topic file","\u9225?'delete_file' \u9225?Delete a topic file","\u9225?'list_files' \u9225?List all memory topic files","","Search:","\u9225?'search' \u9225?Search long-term memory (QMemory) + local keyword match"].join(`
435
436
  `)},content:{type:"string",description:["Content for add/replace/create_file/write_file.","For INDEX.md notes: write concise, factual statements.","For topic files: can be longer (up to 8KB), use markdown formatting."].join(`
436
- `)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search': natural language query to find relevant memories."}},required:["action"]},Jp=["Manage persistent memory across sessions.","","Two storage tiers:","1. INDEX.md \u2014 always visible in system prompt (user preferences, key facts, file index)","2. Topic files \u2014 loaded on demand for longer notes (lessons, project context, task logs)","","Guidelines:","- Record important user preferences and facts to INDEX.md immediately","- Use topic files for detailed notes that don't need to be visible every turn","- Use 'search' to recall past conversations and long-term patterns from QMemory","- Keep INDEX.md concise (12KB limit) \u2014 move verbose content to topic files","- Name topic files descriptively: 'project-foo.md', 'lesson-deployment.md', 'task-2026-05-19.md'"].join(`
437
- `);async function Xp(r,e){let{action:t}=r,{memdir:n}=e;if(t==="add"){let o=r.content?.trim();if(!o)return{ok:!1,message:"content is required for 'add'.",action:t};let s=await n.addToIndex(o);return{ok:s.ok,message:s.message,action:t}}if(t==="replace"){let o=r.old_text?.trim(),s=r.new_text?.trim()||r.content?.trim();if(!o)return{ok:!1,message:"old_text is required for 'replace'.",action:t};if(!s)return{ok:!1,message:"new_text (or content) is required for 'replace'.",action:t};let i=await n.replaceInIndex(o,s);return{ok:i.ok,message:i.message,action:t}}if(t==="remove"){let o=r.old_text?.trim();if(!o)return{ok:!1,message:"old_text is required for 'remove'.",action:t};let s=await n.removeFromIndex(o);return{ok:s.ok,message:s.message,action:t}}if(t==="create_file"){let o=r.file?.trim(),s=r.content?.trim();if(!o)return{ok:!1,message:"file is required for 'create_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'create_file'.",action:t};let i=await n.createFile(o,s);return{ok:i.ok,message:i.message,action:t}}if(t==="write_file"){let o=r.file?.trim(),s=r.content?.trim();if(!o)return{ok:!1,message:"file is required for 'write_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'write_file'.",action:t};let i=await n.writeFile(o,s);return{ok:i.ok,message:i.message,action:t}}if(t==="read_file"){let o=r.file?.trim();if(!o)return{ok:!1,message:"file is required for 'read_file'.",action:t};let s=await n.readFile(o);return s.ok?{ok:!0,message:s.content,action:t}:{ok:!1,message:s.message,action:t}}if(t==="delete_file"){let o=r.file?.trim();if(!o)return{ok:!1,message:"file is required for 'delete_file'.",action:t};let s=await n.deleteFile(o);return{ok:s.ok,message:s.message,action:t}}if(t==="list_files"){let o=await n.listFiles();if(o.length===0)return{ok:!0,message:"No topic files yet. Use 'create_file' to create one.",action:t};let s=o.map(i=>{let a=(i.size/1024).toFixed(1),c=i.modifiedAt.slice(0,10);return`\u2022 ${i.name} (${a}KB, ${c})${i.preview?" \u2014 "+i.preview:""}`}).join(`
437
+ `)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search': natural language query to find relevant memories."}},required:["action"]},gm=["Manage persistent memory across sessions.","","Two storage tiers:","1. INDEX.md \u9225?always visible in system prompt (user preferences, key facts, file index)","2. Topic files \u9225?loaded on demand for longer notes (lessons, project context, task logs)","","Guidelines:","- Record important user preferences and facts to INDEX.md immediately","- Use topic files for detailed notes that don't need to be visible every turn","- Use 'search' to recall past conversations and long-term patterns from QMemory","- Keep INDEX.md concise (12KB limit) \u9225?move verbose content to topic files","- Name topic files descriptively: 'project-foo.md', 'lesson-deployment.md', 'task-2026-05-19.md'"].join(`
438
+ `);async function fm(r,e){let{action:t}=r,{memdir:n}=e;if(t==="add"){let o=r.content?.trim();if(!o)return{ok:!1,message:"content is required for 'add'.",action:t};let s=await n.addToIndex(o);return{ok:s.ok,message:s.message,action:t}}if(t==="replace"){let o=r.old_text?.trim(),s=r.new_text?.trim()||r.content?.trim();if(!o)return{ok:!1,message:"old_text is required for 'replace'.",action:t};if(!s)return{ok:!1,message:"new_text (or content) is required for 'replace'.",action:t};let i=await n.replaceInIndex(o,s);return{ok:i.ok,message:i.message,action:t}}if(t==="remove"){let o=r.old_text?.trim();if(!o)return{ok:!1,message:"old_text is required for 'remove'.",action:t};let s=await n.removeFromIndex(o);return{ok:s.ok,message:s.message,action:t}}if(t==="create_file"){let o=r.file?.trim(),s=r.content?.trim();if(!o)return{ok:!1,message:"file is required for 'create_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'create_file'.",action:t};let i=await n.createFile(o,s);return{ok:i.ok,message:i.message,action:t}}if(t==="write_file"){let o=r.file?.trim(),s=r.content?.trim();if(!o)return{ok:!1,message:"file is required for 'write_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'write_file'.",action:t};let i=await n.writeFile(o,s);return{ok:i.ok,message:i.message,action:t}}if(t==="read_file"){let o=r.file?.trim();if(!o)return{ok:!1,message:"file is required for 'read_file'.",action:t};let s=await n.readFile(o);return s.ok?{ok:!0,message:s.content,action:t}:{ok:!1,message:s.message,action:t}}if(t==="delete_file"){let o=r.file?.trim();if(!o)return{ok:!1,message:"file is required for 'delete_file'.",action:t};let s=await n.deleteFile(o);return{ok:s.ok,message:s.message,action:t}}if(t==="list_files"){let o=await n.listFiles();if(o.length===0)return{ok:!0,message:"No topic files yet. Use 'create_file' to create one.",action:t};let s=o.map(i=>{let a=(i.size/1024).toFixed(1),c=i.modifiedAt.slice(0,10);return`\u9225?${i.name} (${a}KB, ${c})${i.preview?" \u9225?"+i.preview:""}`}).join(`
438
439
  `);return{ok:!0,message:`Memory files (${o.length}):
439
440
  ${s}`,action:t}}if(t==="search"){let o=r.query?.trim();if(!o)return{ok:!1,message:"query is required for 'search'.",action:t};let s=[],i;try{let a=await n.searchLocal(o);a.length>0&&s.push(`## Local Memory
440
- `+a.map(c=>`\u2022 [${c.file}] ${c.snippet}`).join(`
441
+ `+a.map(c=>`\u9225?[${c.file}] ${c.snippet}`).join(`
441
442
  `))}catch{}if(e.provider)try{let a=await e.provider.search(o,e.userId,{limit:10});i=a,a.length>0&&s.push(`## Long-term Memory (QMemory)
442
443
  `+a.map((c,d)=>`${d+1}. ${c.text}`).join(`
443
444
  `))}catch{}return s.length===0?{ok:!0,message:"No matching memories found.",action:t,results:[]}:{ok:!0,message:s.join(`
444
445
 
445
- `),action:t,results:i}}return{ok:!1,message:`Unknown action: "${t}".`,action:t}}import{readFile as ka,readdir as Yp,unlink as _S,stat as CS,mkdir as AS}from"node:fs/promises";import{existsSync as Ge,readFileSync as Qp,mkdirSync as Zp,writeFileSync as IS}from"node:fs";import{join as Oe}from"node:path";var xe=12288,Ta=200,Sr=8192,PS="memory",ft="INDEX.md";function wa(){return Oe(J(),PS)}var MS=[/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 xr(r){return!MS.some(e=>e.test(r))}var ES=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function Rr(r){return!(!ES.test(r)||r===ft||r.includes("..")||r.includes("/")||r.includes("\\"))}var _r=class{root;indexCache=null;constructor(e){this.root=e??wa()}getRootPath(){return this.root}ensureInitialized(){Ge(this.root)||Zp(this.root,{recursive:!0});let e=Oe(this.root,ft);if(!Ge(e)){let t=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt. -->","<!-- Use memory tool to add notes, or create topic files for longer content. -->","","## User Profile","","## Notes",""].join(`
446
- `);OS(e,t)}}getIndexForPrompt(){let e=Oe(this.root,ft);if(!Ge(e))return"";let t;try{t=Qp(e,"utf-8")}catch{return""}this.indexCache=t;let n=t.split(`
447
- `);return n.length>Ta&&(t=n.slice(0,Ta).join(`
446
+ `),action:t,results:i}}return{ok:!1,message:`Unknown action: "${t}".`,action:t}}import{readFile as _a,readdir as hm,unlink as VS,stat as zS,mkdir as KS}from"node:fs/promises";import{existsSync as He,readFileSync as ym,mkdirSync as bm,writeFileSync as qS}from"node:fs";import{join as Le}from"node:path";var xe=12288,xa=200,Ar=8192,XS="memory",bt="INDEX.md";function Aa(){return Le(X(),XS)}var YS=[/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 Cr(r){return!YS.some(e=>e.test(r))}var JS=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function Pr(r){return!(!JS.test(r)||r===bt||r.includes("..")||r.includes("/")||r.includes("\\"))}var Ir=class{root;indexCache=null;constructor(e){this.root=e??Aa()}getRootPath(){return this.root}ensureInitialized(){He(this.root)||bm(this.root,{recursive:!0});let e=Le(this.root,bt);if(!He(e)){let t=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt. -->","<!-- Use memory tool to add notes, or create topic files for longer content. -->","","## User Profile","","## Notes",""].join(`
447
+ `);QS(e,t)}}getIndexForPrompt(){let e=Le(this.root,bt);if(!He(e))return"";let t;try{t=ym(e,"utf-8")}catch{return""}this.indexCache=t;let n=t.split(`
448
+ `);return n.length>xa&&(t=n.slice(0,xa).join(`
448
449
  `)+`
449
450
 
450
- <!-- INDEX.md truncated: ${n.length} lines total, showing first ${Ta} -->`),t.length>xe&&(t=t.slice(0,xe)+`
451
+ <!-- INDEX.md truncated: ${n.length} lines total, showing first ${xa} -->`),t.length>xe&&(t=t.slice(0,xe)+`
451
452
 
452
- <!-- INDEX.md truncated at ${xe} chars -->`),t}getIndexRaw(){let e=Oe(this.root,ft);if(!Ge(e))return"";try{return Qp(e,"utf-8")}catch{return""}}getIndexUsage(){let e=this.getIndexRaw(),t=e.length,n=e.split(`
453
- `).length;return{chars:t,lines:n,percent:Math.round(t/xe*100)}}async addToIndex(e){if(!e.trim())return{ok:!1,message:"Content cannot be empty."};if(!xr(e))return{ok:!1,message:"Content rejected: potential injection detected."};let t=this.getIndexRaw(),n=t.endsWith(`
453
+ <!-- INDEX.md truncated at ${xe} chars -->`),t}getIndexRaw(){let e=Le(this.root,bt);if(!He(e))return"";try{return ym(e,"utf-8")}catch{return""}}getIndexUsage(){let e=this.getIndexRaw(),t=e.length,n=e.split(`
454
+ `).length;return{chars:t,lines:n,percent:Math.round(t/xe*100)}}async addToIndex(e){if(!e.trim())return{ok:!1,message:"Content cannot be empty."};if(!Cr(e))return{ok:!1,message:"Content rejected: potential injection detected."};let t=this.getIndexRaw(),n=t.endsWith(`
454
455
  `)?t+e.trim()+`
455
456
  `:t+`
456
457
  `+e.trim()+`
457
- `;if(n.length>xe)return{ok:!1,message:`INDEX.md would exceed limit (${this.getIndexUsage().chars}/${xe} chars). Create a topic file instead, or remove old entries.`};await this.writeIndex(n);let o=this.getIndexUsage();return{ok:!0,message:`Added to INDEX.md. [${o.chars}/${xe} chars, ${o.percent}%]`,indexUsage:`${o.chars}/${xe}`}}async replaceInIndex(e,t){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};if(!t.trim())return{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."};if(!xr(t))return{ok:!1,message:"Content rejected: potential injection detected."};let n=this.getIndexRaw(),o=n.split(e).length-1;if(o===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(o>1)return{ok:!1,message:`Multiple matches (${o}) for: "${e.slice(0,80)}". Be more specific.`};let s=n.replace(e,t);if(s.length>xe)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${s.length}/${xe} chars).`};await this.writeIndex(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${xe} chars]`,indexUsage:`${i.chars}/${xe}`}}async removeFromIndex(e){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};let t=this.getIndexRaw();if(!t.includes(e))return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};let n=t.replace(e,"");n=n.replace(/\n{3,}/g,`
458
+ `;if(n.length>xe)return{ok:!1,message:`INDEX.md would exceed limit (${this.getIndexUsage().chars}/${xe} chars). Create a topic file instead, or remove old entries.`};await this.writeIndex(n);let o=this.getIndexUsage();return{ok:!0,message:`Added to INDEX.md. [${o.chars}/${xe} chars, ${o.percent}%]`,indexUsage:`${o.chars}/${xe}`}}async replaceInIndex(e,t){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};if(!t.trim())return{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."};if(!Cr(t))return{ok:!1,message:"Content rejected: potential injection detected."};let n=this.getIndexRaw(),o=n.split(e).length-1;if(o===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(o>1)return{ok:!1,message:`Multiple matches (${o}) for: "${e.slice(0,80)}". Be more specific.`};let s=n.replace(e,t);if(s.length>xe)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${s.length}/${xe} chars).`};await this.writeIndex(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${xe} chars]`,indexUsage:`${i.chars}/${xe}`}}async removeFromIndex(e){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};let t=this.getIndexRaw();if(!t.includes(e))return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};let n=t.replace(e,"");n=n.replace(/\n{3,}/g,`
458
459
 
459
- `),await this.writeIndex(n);let o=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${o.chars}/${xe} chars]`,indexUsage:`${o.chars}/${xe}`}}async listFiles(){if(!Ge(this.root))return[];let e=await Yp(this.root),t=[];for(let n of e){if(n===ft||!n.endsWith(".md"))continue;let o=Oe(this.root,n);try{let s=await CS(o);if(!s.isFile())continue;let a=(await ka(o,"utf-8")).split(`
460
- `).find(c=>c.trim()&&!c.startsWith("#"))?.trim();t.push({name:n,size:s.size,modifiedAt:s.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return t.sort((n,o)=>o.modifiedAt.localeCompare(n.modifiedAt))}async createFile(e,t){if(!Rr(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!xr(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>Sr)return{ok:!1,message:`Content too long (${t.length} chars, max ${Sr}).`};let n=Oe(this.root,e);if(Ge(n))return{ok:!1,message:`File already exists: "${e}". Use write_file to update.`};await this.ensureDir(),await Xt(n,t);let o=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return await this.appendIndexEntry(o),{ok:!0,message:`Created "${e}" (${t.length} chars). Entry added to INDEX.md.`,file:e}}async writeFile(e,t){if(!Rr(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files.`};if(!xr(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>Sr)return this.writeFileSplit(e,t);let n=Oe(this.root,e),o=!Ge(n);if(await this.ensureDir(),await Xt(n,t),o){let s=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(s)}return{ok:!0,message:`${o?"Created":"Updated"} "${e}" (${t.length} chars).`,file:e}}async writeFileSplit(e,t){let n=e.replace(/\.md$/,""),o=t.split(/\n{2,}/),s=[],i="";for(let d of o)i.length+d.length+2>Sr*.9&&i.length>0?(s.push(i),i=d):i=i?i+`
460
+ `),await this.writeIndex(n);let o=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${o.chars}/${xe} chars]`,indexUsage:`${o.chars}/${xe}`}}async listFiles(){if(!He(this.root))return[];let e=await hm(this.root),t=[];for(let n of e){if(n===bt||!n.endsWith(".md"))continue;let o=Le(this.root,n);try{let s=await zS(o);if(!s.isFile())continue;let a=(await _a(o,"utf-8")).split(`
461
+ `).find(c=>c.trim()&&!c.startsWith("#"))?.trim();t.push({name:n,size:s.size,modifiedAt:s.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return t.sort((n,o)=>o.modifiedAt.localeCompare(n.modifiedAt))}async createFile(e,t){if(!Pr(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!Cr(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>Ar)return{ok:!1,message:`Content too long (${t.length} chars, max ${Ar}).`};let n=Le(this.root,e);if(He(n))return{ok:!1,message:`File already exists: "${e}". Use write_file to update.`};await this.ensureDir(),await en(n,t);let o=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return await this.appendIndexEntry(o),{ok:!0,message:`Created "${e}" (${t.length} chars). Entry added to INDEX.md.`,file:e}}async writeFile(e,t){if(!Pr(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files.`};if(!Cr(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>Ar)return this.writeFileSplit(e,t);let n=Le(this.root,e),o=!He(n);if(await this.ensureDir(),await en(n,t),o){let s=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(s)}return{ok:!0,message:`${o?"Created":"Updated"} "${e}" (${t.length} chars).`,file:e}}async writeFileSplit(e,t){let n=e.replace(/\.md$/,""),o=t.split(/\n{2,}/),s=[],i="";for(let d of o)i.length+d.length+2>Ar*.9&&i.length>0?(s.push(i),i=d):i=i?i+`
461
462
 
462
- `+d:d;i&&s.push(i);let a=[];for(let d=0;d<s.length;d++){let l=`${n}-${d+1}.md`,u=Oe(this.root,l);await this.ensureDir(),await Xt(u,s[d]),a.push(l)}let c=this.getIndexRaw();for(let d of a)if(!c.includes(`[${d}]`)){let l=`- [${d}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(l)}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${t.length} chars total): ${a.join(", ")}`,file:a[0]}}async readFile(e){if(!Rr(e)&&e!==ft)return{ok:!1,message:`Invalid filename: "${e}".`};let t=Oe(this.root,e);try{let n=await ka(t,"utf-8");return{ok:!0,content:n,message:`Read "${e}" (${n.length} chars).`}}catch(n){return n.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${n.message}`}}}async deleteFile(e){if(e===ft)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!Rr(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=Oe(this.root,e);if(!Ge(t))return{ok:!1,message:`File not found: "${e}".`};await _S(t);let n=this.getIndexRaw(),o=new RegExp(`^.*\\[${DS(e)}\\].*$\\n?`,"m");if(o.test(n)){let s=n.replace(o,"").replace(/\n{3,}/g,`
463
+ `+d:d;i&&s.push(i);let a=[];for(let d=0;d<s.length;d++){let l=`${n}-${d+1}.md`,u=Le(this.root,l);await this.ensureDir(),await en(u,s[d]),a.push(l)}let c=this.getIndexRaw();for(let d of a)if(!c.includes(`[${d}]`)){let l=`- [${d}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(l)}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${t.length} chars total): ${a.join(", ")}`,file:a[0]}}async readFile(e){if(!Pr(e)&&e!==bt)return{ok:!1,message:`Invalid filename: "${e}".`};let t=Le(this.root,e);try{let n=await _a(t,"utf-8");return{ok:!0,content:n,message:`Read "${e}" (${n.length} chars).`}}catch(n){return n.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${n.message}`}}}async deleteFile(e){if(e===bt)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!Pr(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=Le(this.root,e);if(!He(t))return{ok:!1,message:`File not found: "${e}".`};await VS(t);let n=this.getIndexRaw(),o=new RegExp(`^.*\\[${ZS(e)}\\].*$\\n?`,"m");if(o.test(n)){let s=n.replace(o,"").replace(/\n{3,}/g,`
463
464
 
464
- `);await this.writeIndex(s)}return{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}}async searchLocal(e){if(!Ge(this.root))return[];let t=e.toLowerCase().split(/\s+/).filter(s=>s.length>1);if(t.length===0)return[];let n=await Yp(this.root),o=[];for(let s of n){if(!s.endsWith(".md"))continue;let i=Oe(this.root,s);try{let a=await ka(i,"utf-8"),c=a.toLowerCase(),d=t.filter(g=>c.includes(g)).length;if(d===0)continue;let l=a.split(`
465
- `),u="",p=0;for(let g of l){let f=g.toLowerCase(),m=t.filter(y=>f.includes(y)).length;m>p&&(p=m,u=g.trim())}o.push({file:s,snippet:u.slice(0,200),score:d/t.length})}catch{}}return o.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await this.ensureDir(),await Xt(Oe(this.root,ft),e),this.indexCache=e}async ensureDir(){Ge(this.root)||await AS(this.root,{recursive:!0})}async appendIndexEntry(e){let t=this.getIndexRaw();if(t.includes(e))return;let n=t.endsWith(`
465
+ `);await this.writeIndex(s)}return{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}}async searchLocal(e){if(!He(this.root))return[];let t=e.toLowerCase().split(/\s+/).filter(s=>s.length>1);if(t.length===0)return[];let n=await hm(this.root),o=[];for(let s of n){if(!s.endsWith(".md"))continue;let i=Le(this.root,s);try{let a=await _a(i,"utf-8"),c=a.toLowerCase(),d=t.filter(m=>c.includes(m)).length;if(d===0)continue;let l=a.split(`
466
+ `),u="",p=0;for(let m of l){let f=m.toLowerCase(),g=t.filter(y=>f.includes(y)).length;g>p&&(p=g,u=m.trim())}o.push({file:s,snippet:u.slice(0,200),score:d/t.length})}catch{}}return o.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await this.ensureDir(),await en(Le(this.root,bt),e),this.indexCache=e}async ensureDir(){He(this.root)||await KS(this.root,{recursive:!0})}async appendIndexEntry(e){let t=this.getIndexRaw();if(t.includes(e))return;let n=t.endsWith(`
466
467
  `)?t+e+`
467
468
  `:t+`
468
469
  `+e+`
469
- `;n.length<=xe&&await this.writeIndex(n)}};function OS(r,e){let t=Oe(r,"..");Ge(t)||Zp(t,{recursive:!0}),IS(r,e,"utf-8")}function DS(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Cr=Si;Es();Ms();De();import{readFile as LS}from"node:fs/promises";import{watch as $S}from"node:fs";import{join as US}from"node:path";var NS=we,jS="settings.json";function FS(r){return US(r,NS,jS)}async function BS(r){try{let e=await LS(r,"utf-8");return JSON.parse(e)}catch{return null}}function GS(r,e,t,n){let o=!1;r.permissionMode&&r.permissionMode!==e.getMode()&&(e.setMode(r.permissionMode),n?.(`settings: permission mode \u2192 ${r.permissionMode}`),o=!0),r.permissionRules&&(e.replaceRules(r.permissionRules),n?.(`settings: ${r.permissionRules.length} permission rules loaded`),o=!0),r.defaultBehavior&&(e.setDefaultBehavior(r.defaultBehavior),n?.(`settings: default behavior \u2192 ${r.defaultBehavior}`),o=!0),o&&t&&t.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:r}).catch(()=>{})}function em(r){let e=FS(r.projectRoot),t=null,n=null,o=async()=>{let s=await BS(e);s&&GS(s,r.ruleEngine,r.hooks,r.log)};o().catch(()=>{});try{t=$S(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{o().catch(()=>{})},200)}),t.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),t?.close(),t=null}}var va=new Set;function Lt(r){return va.add(r),()=>{va.delete(r)}}async function tm(){await Promise.all(Array.from(va).map(r=>r()))}import{join as zn}from"node:path";import{mkdirSync as HS,existsSync as WS,createWriteStream as zS}from"node:fs";import{pipeline as VS}from"node:stream/promises";import{Readable as qS}from"node:stream";De();var KS=cs,JS=ds,nm={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/mp4":".m4a","audio/flac":".flac","application/pdf":".pdf","model/gltf-binary":".glb","model/gltf+json":".gltf"},Ar=class{mediaDir;maxFileSize;timeoutMs;constructor(e){this.mediaDir=e?.projectDir?zn(e.projectDir,"media"):e?.mediaDir??zn(J(),"media"),this.maxFileSize=e?.maxFileSize??KS,this.timeoutMs=e?.timeoutMs??JS}setProjectDir(e){this.mediaDir=zn(e,"media")}async download(e,t){let n=t?.sessionId??XS(),o=zn(this.mediaDir,n);WS(o)||HS(o,{recursive:!0});let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeoutMs);try{let a=await fetch(e,{signal:s.signal});if(!a.ok)throw new Error(`Download failed: ${a.status} ${a.statusText}`);let c=parseInt(a.headers.get("content-length")??"0",10);if(c>this.maxFileSize)throw new Error(`File too large: ${c} bytes (max: ${this.maxFileSize})`);let d=a.headers.get("content-type")?.split(";")[0].trim()||"application/octet-stream",l=QS(e,d),u=YS(t?.type??ZS(d),l),p=zn(o,u),g=a.body;if(!g)throw new Error("No response body");let f=zS(p);await VS(qS.fromWeb(g),f);let{size:m}=await import("node:fs/promises").then(y=>y.stat(p));return{remoteUrl:e,localPath:p,bytes:m,mimeType:d}}finally{clearTimeout(i)}}async downloadAll(e,t,n){let o=[];for(let s of e)try{let i=await this.download(s,t);o.push(i)}catch(i){n?.warn(`media-persistence: failed to download ${s}: ${i.message}`)}return o}getMediaDir(){return this.mediaDir}};function XS(){let r=new Date;return`${r.getFullYear()}${String(r.getMonth()+1).padStart(2,"0")}${String(r.getDate()).padStart(2,"0")}`}function YS(r,e){let t=new Date,n=`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}${String(t.getMinutes()).padStart(2,"0")}${String(t.getSeconds()).padStart(2,"0")}`,o=Math.random().toString(36).slice(2,6);return`${r}_${n}_${o}${e}`}function QS(r,e){if(nm[e])return nm[e];try{let t=new URL(r).pathname,n=t.lastIndexOf(".");if(n>0){let o=t.slice(n).toLowerCase().split("?")[0];if(o.length<=5)return o}}catch{}return".bin"}function ZS(r){return r.startsWith("image/")?"image":r.startsWith("video/")?"video":r.startsWith("audio/")?"audio":r.startsWith("model/")?"3d":"file"}import{join as ex}from"node:path";import{readFileSync as tx,writeFileSync as nx,mkdirSync as ox}from"node:fs";var $t=null,Sa=!1;function om(r){return ex(r,"skill-stats.json")}function xa(r){if($t)return $t;try{$t=JSON.parse(tx(om(r),"utf8"))}catch{$t={}}return $t}function rx(r){if(!(!Sa||!$t))try{ox(r,{recursive:!0}),nx(om(r),JSON.stringify($t,null,2),"utf8"),Sa=!1}catch{}}function Ir(r,e,t){let n=xa(r);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),t?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Sa=!0,rx(r)}function rm(r,e){return xa(r)[e]}function sm(r){return xa(r)}import{existsSync as im,mkdirSync as sx,readFileSync as ix,writeFileSync as ax}from"node:fs";import{join as lx}from"node:path";import{randomUUID as am}from"node:crypto";function lm(){return lx(J(),"projects.json")}function $e(){let r=lm();if(!im(r))return{activeProjectId:null,projects:[]};try{let e=ix(r,"utf-8");return JSON.parse(e)}catch{return{activeProjectId:null,projects:[]}}}function ht(r){let e=lm(),t=J();im(t)||sx(t,{recursive:!0}),ax(e,JSON.stringify(r,null,2),"utf-8")}function Ra(r){let e=$e(),t=new Date().toISOString(),n={id:am(),name:r.name,workspaceDir:r.workspaceDir,type:r.type??"personal",status:"active",groupId:r.groupId,createdAt:t,updatedAt:t};return e.projects.push(n),e.activeProjectId=n.id,ht(e),n}function Qt(){return $e().projects.filter(e=>e.status==="active")}function Ut(){let r=$e();if(!r.activeProjectId)return null;let e=r.projects.find(t=>t.id===r.activeProjectId)??null;return e&&e.status!=="active"?null:e}function cm(r){return $e().projects.find(t=>t.id===r)??null}function Vn(r){let e=$e(),t=e.projects.find(n=>n.id===r&&n.status==="active");return t?(e.activeProjectId=t.id,ht(e),t):null}function dm(r){let e=$e(),t=e.projects.findIndex(s=>s.id===r);if(t===-1)return{deleted:!1};let n=e.projects[t];if(n.type==="default")return{deleted:!1};n.status="archived",n.updatedAt=new Date().toISOString();let o;if(e.activeProjectId===r){let s=e.projects.find(i=>i.type==="default"&&i.status==="active");if(s)e.activeProjectId=s.id,o=s;else{let i=e.projects.find(a=>a.status==="active"&&a.id!==r);e.activeProjectId=i?.id??null,o=i}}return ht(e),{deleted:!0,switchedTo:o}}function um(r){let e=$e(),t=e.projects.find(s=>s.type==="default"&&s.status==="active");if(t)return t;let n=new Date().toISOString(),o={id:am(),name:"\u9ED8\u8BA4\u9879\u76EE",workspaceDir:r,type:"default",status:"active",createdAt:n,updatedAt:n};return e.projects.push(o),e.activeProjectId||(e.activeProjectId=o.id),ht(e),o}function pm(r,e){let t=$e(),n=t.projects.find(s=>s.id===r&&s.status==="active");return!n||n.type==="default"||t.projects.find(s=>s.name===e&&s.status==="active"&&s.id!==r)?null:(n.name=e,n.updatedAt=new Date().toISOString(),ht(t),n)}function mm(r){let e=$e(),t=e.projects.find(o=>o.id===r&&o.status==="active");if(!t)return{archived:!1};if(t.type==="default")return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let n;if(e.activeProjectId===r){let o=e.projects.find(s=>s.type==="default"&&s.status==="active");if(o)e.activeProjectId=o.id,n=o;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==r);e.activeProjectId=s?.id??null,n=s}}return ht(e),{archived:!0,switchedTo:n}}function gm(r){let e=$e(),t=e.projects.find(n=>n.id===r&&n.status==="archived");return t?(t.status="active",t.updatedAt=new Date().toISOString(),ht(e),t):null}function _a(r){return $e().projects.find(t=>t.groupId===r&&t.status==="active")??null}function fm(r){let e=$e(),t=e.projects.find(o=>o.groupId===r&&o.status==="active");if(!t)return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let n;if(e.activeProjectId===t.id){let o=e.projects.find(s=>s.type==="default"&&s.status==="active");if(o)e.activeProjectId=o.id,n=o;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==t.id);e.activeProjectId=s?.id??null,n=s}}return ht(e),{archived:!0,projectId:t.id,switchedTo:n}}import Ce from"node:fs";import qn from"node:path";De();var hm=as,ym=ls,Kn=class{dir;constructor(e){this.dir=Jl(e)}list(){if(!Ce.existsSync(this.dir))return[];let e=[];for(let t of Ce.readdirSync(this.dir)){if(!t.endsWith(".md"))continue;let n=qn.join(this.dir,t);try{let o=Ce.statSync(n);if(!o.isFile())continue;let s=Ce.readFileSync(n,"utf8");e.push({filename:t,content:s,sizeBytes:o.size})}catch{}}return e}read(e){if(!this.isValidFilename(e))return null;let t=qn.join(this.dir,e);if(!Ce.existsSync(t))return null;try{let n=Ce.readFileSync(t,"utf8"),o=Ce.statSync(t);return{filename:e,content:n,sizeBytes:o.size}}catch{return null}}write(e,t){if(!this.isValidFilename(e))throw new Error("Invalid filename: must end with .md and contain no path separators");let n=Buffer.byteLength(t,"utf8");if(n>hm)throw new Error(`File too large: ${n} bytes exceeds ${hm} limit`);if(this.getDirSize(e)+n>ym)throw new Error(`Total instructions size would exceed ${ym} byte limit`);Ce.mkdirSync(this.dir,{recursive:!0});let s=qn.join(this.dir,e);return Ce.writeFileSync(s,t,"utf8"),{filename:e,content:t,sizeBytes:n}}remove(e){if(!this.isValidFilename(e))return!1;let t=qn.join(this.dir,e);return Ce.existsSync(t)?(Ce.unlinkSync(t),!0):!1}loadAll(){let e=this.list();return e.length===0?"":`<project-instructions>
470
+ `;n.length<=xe&&await this.writeIndex(n)}};function QS(r,e){let t=Le(r,"..");He(t)||bm(t,{recursive:!0}),qS(r,e,"utf-8")}function ZS(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Mr=Ai;Ns();Ds();ye();import{readFile as eR}from"node:fs/promises";import{watch as tR}from"node:fs";import{join as nR}from"node:path";var oR=Se,rR="settings.json";function sR(r){return nR(r,oR,rR)}async function iR(r){try{let e=await eR(r,"utf-8");return JSON.parse(e)}catch{return null}}function aR(r,e,t,n){let o=!1;r.permissionMode&&r.permissionMode!==e.getMode()&&(e.setMode(r.permissionMode),n?.(`settings: permission mode \u2192 ${r.permissionMode}`),o=!0),r.permissionRules&&(e.replaceRules(r.permissionRules),n?.(`settings: ${r.permissionRules.length} permission rules loaded`),o=!0),r.defaultBehavior&&(e.setDefaultBehavior(r.defaultBehavior),n?.(`settings: default behavior \u2192 ${r.defaultBehavior}`),o=!0),o&&t&&t.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:r}).catch(()=>{})}function km(r){let e=sR(r.projectRoot),t=null,n=null,o=async()=>{let s=await iR(e);s&&aR(s,r.ruleEngine,r.hooks,r.log)};o().catch(()=>{});try{t=tR(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{o().catch(()=>{})},200)}),t.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),t?.close(),t=null}}var Ca=new Set;function jt(r){return Ca.add(r),()=>{Ca.delete(r)}}async function Tm(){await Promise.all(Array.from(Ca).map(r=>r()))}import{join as qn}from"node:path";import{mkdirSync as cR,existsSync as lR,createWriteStream as dR}from"node:fs";import{pipeline as uR}from"node:stream/promises";import{Readable as pR}from"node:stream";ye();var mR=ps,gR=ms,wm={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/mp4":".m4a","audio/flac":".flac","application/pdf":".pdf","model/gltf-binary":".glb","model/gltf+json":".gltf"},Er=class{mediaDir;maxFileSize;timeoutMs;constructor(e){this.mediaDir=e?.projectDir?qn(e.projectDir,"media"):e?.mediaDir??qn(X(),"media"),this.maxFileSize=e?.maxFileSize??mR,this.timeoutMs=e?.timeoutMs??gR}setProjectDir(e){this.mediaDir=qn(e,"media")}async download(e,t){let n=t?.sessionId??fR(),o=qn(this.mediaDir,n);lR(o)||cR(o,{recursive:!0});let s=new AbortController,i=setTimeout(()=>s.abort(),this.timeoutMs);try{let a=await fetch(e,{signal:s.signal});if(!a.ok)throw new Error(`Download failed: ${a.status} ${a.statusText}`);let c=parseInt(a.headers.get("content-length")??"0",10);if(c>this.maxFileSize)throw new Error(`File too large: ${c} bytes (max: ${this.maxFileSize})`);let d=a.headers.get("content-type")?.split(";")[0].trim()||"application/octet-stream",l=yR(e,d),u=hR(t?.type??bR(d),l),p=qn(o,u),m=a.body;if(!m)throw new Error("No response body");let f=dR(p);await uR(pR.fromWeb(m),f);let{size:g}=await import("node:fs/promises").then(y=>y.stat(p));return{remoteUrl:e,localPath:p,bytes:g,mimeType:d}}finally{clearTimeout(i)}}async downloadAll(e,t,n){let o=[];for(let s of e)try{let i=await this.download(s,t);o.push(i)}catch(i){n?.warn(`media-persistence: failed to download ${s}: ${i.message}`)}return o}getMediaDir(){return this.mediaDir}};function fR(){let r=new Date;return`${r.getFullYear()}${String(r.getMonth()+1).padStart(2,"0")}${String(r.getDate()).padStart(2,"0")}`}function hR(r,e){let t=new Date,n=`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}${String(t.getMinutes()).padStart(2,"0")}${String(t.getSeconds()).padStart(2,"0")}`,o=Math.random().toString(36).slice(2,6);return`${r}_${n}_${o}${e}`}function yR(r,e){if(wm[e])return wm[e];try{let t=new URL(r).pathname,n=t.lastIndexOf(".");if(n>0){let o=t.slice(n).toLowerCase().split("?")[0];if(o.length<=5)return o}}catch{}return".bin"}function bR(r){return r.startsWith("image/")?"image":r.startsWith("video/")?"video":r.startsWith("audio/")?"audio":r.startsWith("model/")?"3d":"file"}import{join as kR}from"node:path";import{readFileSync as TR,writeFileSync as wR,mkdirSync as vR}from"node:fs";var Ft=null,Pa=!1;function vm(r){return kR(r,"skill-stats.json")}function Ia(r){if(Ft)return Ft;try{Ft=JSON.parse(TR(vm(r),"utf8"))}catch{Ft={}}return Ft}function SR(r){if(!(!Pa||!Ft))try{vR(r,{recursive:!0}),wR(vm(r),JSON.stringify(Ft,null,2),"utf8"),Pa=!1}catch{}}function Or(r,e,t){let n=Ia(r);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),t?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Pa=!0,SR(r)}function Sm(r,e){return Ia(r)[e]}function Rm(r){return Ia(r)}import Ie from"node:fs";import Xn from"node:path";ye();var _m=ds,xm=us,Yn=class{dir;constructor(e){this.dir=nl(e)}list(){if(!Ie.existsSync(this.dir))return[];let e=[];for(let t of Ie.readdirSync(this.dir)){if(!t.endsWith(".md"))continue;let n=Xn.join(this.dir,t);try{let o=Ie.statSync(n);if(!o.isFile())continue;let s=Ie.readFileSync(n,"utf8");e.push({filename:t,content:s,sizeBytes:o.size})}catch{}}return e}read(e){if(!this.isValidFilename(e))return null;let t=Xn.join(this.dir,e);if(!Ie.existsSync(t))return null;try{let n=Ie.readFileSync(t,"utf8"),o=Ie.statSync(t);return{filename:e,content:n,sizeBytes:o.size}}catch{return null}}write(e,t){if(!this.isValidFilename(e))throw new Error("Invalid filename: must end with .md and contain no path separators");let n=Buffer.byteLength(t,"utf8");if(n>_m)throw new Error(`File too large: ${n} bytes exceeds ${_m} limit`);if(this.getDirSize(e)+n>xm)throw new Error(`Total instructions size would exceed ${xm} byte limit`);Ie.mkdirSync(this.dir,{recursive:!0});let s=Xn.join(this.dir,e);return Ie.writeFileSync(s,t,"utf8"),{filename:e,content:t,sizeBytes:n}}remove(e){if(!this.isValidFilename(e))return!1;let t=Xn.join(this.dir,e);return Ie.existsSync(t)?(Ie.unlinkSync(t),!0):!1}loadAll(){let e=this.list();return e.length===0?"":`<project-instructions>
470
471
  ${e.map(n=>`<!-- file: ${n.filename} -->
471
472
  ${n.content}`).join(`
472
473
 
473
474
  `)}
474
- </project-instructions>`}isValidFilename(e){return!(!e.endsWith(".md")||e.includes("/")||e.includes("\\")||e.includes("..")||e.startsWith("."))}getDirSize(e){if(!Ce.existsSync(this.dir))return 0;let t=0;for(let n of Ce.readdirSync(this.dir)){if(n===e)continue;let o=qn.join(this.dir,n);try{let s=Ce.statSync(o);s.isFile()&&(t+=s.size)}catch{}}return t}};import yt from"node:fs";import Ca from"node:path";var Jn=class{dir;constructor(e){this.dir=Xl(e)}list(){if(!yt.existsSync(this.dir))return[];let e=[];for(let t of yt.readdirSync(this.dir)){if(!t.endsWith(".md"))continue;let n=this.load(t.replace(".md",""));n&&e.push(n)}return e}loadActive(){return this.list().filter(e=>e.status==="active")}load(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,""),n=Ca.join(this.dir,`${t}.md`);if(!yt.existsSync(n))return null;try{let o=yt.readFileSync(n,"utf8"),{frontmatter:s,body:i}=dx(o);return{slug:s.slug??t,status:s.status??"active",content:o,createdAt:s.created_at??"",updatedAt:s.updated_at??""}}catch{return null}}save(e,t){let n=e.replace(/[^a-zA-Z0-9_-]/g,"");yt.mkdirSync(this.dir,{recursive:!0});let o=Ca.join(this.dir,`${n}.md`);yt.writeFileSync(o,t,"utf8")}remove(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,""),n=Ca.join(this.dir,`${t}.md`);return yt.existsSync(n)?(yt.unlinkSync(n),!0):!1}};function dx(r){let e=r.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return{frontmatter:{},body:r};let t={};for(let n of e[1].split(`
475
- `)){let o=n.indexOf(":");if(o>0){let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();t[s]=i}}return{frontmatter:t,body:e[2]}}import*as M from"node:fs";import*as F from"node:path";import{homedir as yx}from"node:os";import{AGENT_RPC_ERROR_CODES as _,AGENT_RPC_PROTOCOL_VERSION as Er,isAgentRpcRequest as bx,isAcpJsonRpcRequest as kx,isAcpJsonRpcNotification as Tx,isAcpJsonRpcResponse as wx,ACP_PROTOCOL_VERSION as vx}from"qlogicagent-runtime-contracts";import{randomUUID as ux}from"node:crypto";import{ACP_METHODS as it,ACP_EXTENDED_METHODS as at,isAcpJsonRpcRequest as px,isAcpJsonRpcNotification as mx}from"qlogicagent-runtime-contracts";var Xn={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PROTOCOL_MISMATCH:-32001,SESSION_NOT_FOUND:-32002,AGENT_BUSY:-32003},Pr=class{transport;handler;verbose;hostCapabilities={};hostSupportsExtendedEvents=!1;hostSupportsExtendedMethods=!1;activeSessionId=null;pendingPermissions=new Map;outboundRequestMap=new Map;constructor(e,t,n){this.transport=e,this.handler=t,this.verbose=n?.verbose??!1}dispatchMessage(e){if(this.isJsonRpcResponse(e))return this.handleResponse(e),!0;if(px(e)){let t=e;return process.stderr.write(`[acp-server] \u2192 recv id=${String(t.id)} method=${t.method}
476
- `),this.handleRequest(t),!0}return mx(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,t,n){if(t.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let o={jsonrpc:"2.0",method:it.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:t,...n}}};this.transport.send(o)}async requestPermission(e){let t=`perm-${ux().slice(0,8)}`,n={jsonrpc:"2.0",method:it.SESSION_REQUEST_PERMISSION,params:e,id:t};return new Promise(o=>{this.outboundRequestMap.set(t,e.permissionId),this.pendingPermissions.set(e.permissionId,{resolve:s=>o({optionId:s})}),this.transport.send(n)})}get supportsExtendedEvents(){return this.hostSupportsExtendedEvents}get supportsExtendedMethods(){return this.hostSupportsExtendedMethods}get sessionId(){return this.activeSessionId}async handleRequest(e){let{method:t,params:n,id:o}=e,s=n??{};try{switch(t){case it.INITIALIZE:await this.onInitialize(o,s);break;case it.SESSION_NEW:await this.onSessionNew(o,s);break;case it.SESSION_PROMPT:await this.onSessionPrompt(o,s);break;case it.SESSION_END:await this.onSessionEnd(o,s);break;case it.SESSION_SET_CONFIG:await this.onSessionSetConfig(o,s);break;case it.SESSION_SET_MODEL:await this.handler.handleAcpSessionSetModel(s.sessionId??this.activeSessionId??"",s.modelId??s.model??""),this.sendResult(o,{});break;case it.SESSION_SET_MODE:await this.handler.handleAcpSessionSetMode(s.sessionId??this.activeSessionId??"",s.modeId??s.mode??""),this.sendResult(o,{});break;case at.ABORT:await this.onAbort(o,s);break;case at.DREAM:await this.onDream(o,s);break;case at.SOLO_START:{let i=await this.handler.handleAcpSoloStart(s);this.sendResult(o,i);break}case at.SOLO_STATUS:{let i=await this.handler.handleAcpSoloStatus(s);this.sendResult(o,i);break}case at.SOLO_SELECT:{let i=await this.handler.handleAcpSoloSelect(s);this.sendResult(o,i);break}case at.PRODUCT_CREATE:{let i=await this.handler.handleAcpProductCreate(s);this.sendResult(o,i);break}case at.PRODUCT_RESUME:{let i=await this.handler.handleAcpProductResume(s);this.sendResult(o,i);break}case at.PRODUCT_STATUS:{let i=await this.handler.handleAcpProductStatus(s);this.sendResult(o,i);break}case at.TEAM_DELEGATE:{let i=await this.handler.handleAcpTeamDelegate(s);this.sendResult(o,i);break}default:this.sendError(o,Xn.METHOD_NOT_FOUND,`Unknown method: ${t}`)}}catch(i){this.sendError(o,Xn.INTERNAL_ERROR,i.message)}}handleNotification(e){this.log(`received notification: ${e.method}`)}handleResponse(e){let t=this.outboundRequestMap.get(e.id);if(t){this.outboundRequestMap.delete(e.id);let n=this.pendingPermissions.get(t);if(n){this.pendingPermissions.delete(t);let o=e.result;n.resolve(o?.optionId??"deny")}}else this.log(`received response for id=${String(e.id)} (no matching outbound request)`)}async onInitialize(e,t){this.hostCapabilities=t.clientCapabilities??{},this.hostSupportsExtendedEvents=this.hostCapabilities.extendedEvents??!1,this.hostSupportsExtendedMethods=this.hostCapabilities.extendedMethods??!1;let n=t.clientInfo?.name??"unknown",o=t.clientInfo?.version??"unknown";this.log(`initialize: host=${n} v=${o}, proto=${String(t.protocolVersion)}, extendedEvents=${this.hostSupportsExtendedEvents}, extendedMethods=${this.hostSupportsExtendedMethods}`);let s=await this.handler.handleAcpInitialize(t);this.sendResult(e,s)}async onSessionNew(e,t){let n=await this.handler.handleAcpSessionNew(t);this.activeSessionId=n.sessionId,this.sendResult(e,n)}async onSessionPrompt(e,t){if(!this.activeSessionId||this.activeSessionId!==t.sessionId){this.sendError(e,Xn.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}let n=await this.handler.handleAcpSessionPrompt(t);this.sendResult(e,n)}async onSessionEnd(e,t){if(this.activeSessionId!==t.sessionId){this.sendError(e,Xn.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}await this.handler.handleAcpSessionEnd(t),this.activeSessionId=null,this.sendResult(e,{})}async onSessionSetConfig(e,t){if(this.activeSessionId!==t.sessionId){this.sendError(e,Xn.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}await this.handler.handleAcpSessionSetConfig(t),this.sendResult(e,{})}async onAbort(e,t){await this.handler.handleAcpAbort(t),this.sendResult(e,{aborted:!0})}async onDream(e,t){let n=await this.handler.handleAcpDream(t);this.sendResult(e,n)}sendResult(e,t){process.stderr.write(`[acp-server] \u2190 send id=${String(e)} result
477
- `);let n={jsonrpc:"2.0",id:e,result:t};this.transport.send(n)}sendError(e,t,n,o){process.stderr.write(`[acp-server] \u2190 send id=${String(e)} error=${n}
475
+ </project-instructions>`}isValidFilename(e){return!(!e.endsWith(".md")||e.includes("/")||e.includes("\\")||e.includes("..")||e.startsWith("."))}getDirSize(e){if(!Ie.existsSync(this.dir))return 0;let t=0;for(let n of Ie.readdirSync(this.dir)){if(n===e)continue;let o=Xn.join(this.dir,n);try{let s=Ie.statSync(o);s.isFile()&&(t+=s.size)}catch{}}return t}};import kt from"node:fs";import Ma from"node:path";var Jn=class{dir;constructor(e){this.dir=ol(e)}list(){if(!kt.existsSync(this.dir))return[];let e=[];for(let t of kt.readdirSync(this.dir)){if(!t.endsWith(".md"))continue;let n=this.load(t.replace(".md",""));n&&e.push(n)}return e}loadActive(){return this.list().filter(e=>e.status==="active")}load(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,""),n=Ma.join(this.dir,`${t}.md`);if(!kt.existsSync(n))return null;try{let o=kt.readFileSync(n,"utf8"),{frontmatter:s,body:i}=RR(o);return{slug:s.slug??t,status:s.status??"active",content:o,createdAt:s.created_at??"",updatedAt:s.updated_at??""}}catch{return null}}save(e,t){let n=e.replace(/[^a-zA-Z0-9_-]/g,"");kt.mkdirSync(this.dir,{recursive:!0});let o=Ma.join(this.dir,`${n}.md`);kt.writeFileSync(o,t,"utf8")}remove(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,""),n=Ma.join(this.dir,`${t}.md`);return kt.existsSync(n)?(kt.unlinkSync(n),!0):!1}};function RR(r){let e=r.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return{frontmatter:{},body:r};let t={};for(let n of e[1].split(`
476
+ `)){let o=n.indexOf(":");if(o>0){let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();t[s]=i}}return{frontmatter:t,body:e[2]}}import*as M from"node:fs";import*as F from"node:path";import{homedir as IR}from"node:os";var nn="1.0.0",x={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030};function Ea(r){if(!r||typeof r!="object")return!1;let e=r;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}var Am=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated"],Cm=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],_R=[...Am,...Cm];var Ve={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},me={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},ze={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},ce={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function Qn(r){if(!r||typeof r!="object")return!1;let e=r;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function Zn(r){if(!r||typeof r!="object")return!1;let e=r;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function Oa(r){if(!r||typeof r!="object")return!1;let e=r;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var Pm="openai-codex";var sD={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[Pm]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as xR}from"node:crypto";var eo={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PROTOCOL_MISMATCH:-32001,SESSION_NOT_FOUND:-32002,AGENT_BUSY:-32003},Dr=class{transport;handler;verbose;hostCapabilities={};hostSupportsExtendedEvents=!1;hostSupportsExtendedMethods=!1;activeSessionId=null;pendingPermissions=new Map;outboundRequestMap=new Map;constructor(e,t,n){this.transport=e,this.handler=t,this.verbose=n?.verbose??!1}dispatchMessage(e){if(this.isJsonRpcResponse(e))return this.handleResponse(e),!0;if(Qn(e)){let t=e;return process.stderr.write(`[acp-server] \u922B?recv id=${String(t.id)} method=${t.method}
477
+ `),this.handleRequest(t),!0}return Zn(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,t,n){if(t.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let o={jsonrpc:"2.0",method:Ve.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:t,...n}}};this.transport.send(o)}async requestPermission(e){let t=`perm-${xR().slice(0,8)}`,n={jsonrpc:"2.0",method:Ve.SESSION_REQUEST_PERMISSION,params:e,id:t};return new Promise(o=>{this.outboundRequestMap.set(t,e.permissionId),this.pendingPermissions.set(e.permissionId,{resolve:s=>o({optionId:s})}),this.transport.send(n)})}get supportsExtendedEvents(){return this.hostSupportsExtendedEvents}get supportsExtendedMethods(){return this.hostSupportsExtendedMethods}get sessionId(){return this.activeSessionId}async handleRequest(e){let{method:t,params:n,id:o}=e,s=n??{};try{switch(t){case Ve.INITIALIZE:await this.onInitialize(o,s);break;case Ve.SESSION_NEW:await this.onSessionNew(o,s);break;case Ve.SESSION_PROMPT:await this.onSessionPrompt(o,s);break;case Ve.SESSION_END:await this.onSessionEnd(o,s);break;case Ve.SESSION_SET_CONFIG:await this.onSessionSetConfig(o,s);break;case Ve.SESSION_SET_MODEL:await this.handler.handleAcpSessionSetModel(s.sessionId??this.activeSessionId??"",s.modelId??s.model??""),this.sendResult(o,{});break;case Ve.SESSION_SET_MODE:await this.handler.handleAcpSessionSetMode(s.sessionId??this.activeSessionId??"",s.modeId??s.mode??""),this.sendResult(o,{});break;case me.ABORT:await this.onAbort(o,s);break;case me.DREAM:await this.onDream(o,s);break;case me.AGENTS_LIST:{let i=await this.handler.handleAcpAgentsList();this.sendResult(o,i);break}case me.SOLO_START:{let i=await this.handler.handleAcpSoloStart(s);this.sendResult(o,i);break}case me.SOLO_STATUS:{let i=await this.handler.handleAcpSoloStatus(s);this.sendResult(o,i);break}case me.SOLO_SELECT:{let i=await this.handler.handleAcpSoloSelect(s);this.sendResult(o,i);break}case me.SOLO_CANCEL:{let i=await this.handler.handleAcpSoloCancel(s);this.sendResult(o,i);break}case me.SOLO_SUBSCRIBE:{let i=await this.handler.handleAcpSoloSubscribe(s);this.sendResult(o,i);break}case me.PRODUCT_CREATE:{let i=await this.handler.handleAcpProductCreate(s);this.sendResult(o,i);break}case me.PRODUCT_PAUSE:{let i=await this.handler.handleAcpProductPause(s);this.sendResult(o,i);break}case me.PRODUCT_RESUME:{let i=await this.handler.handleAcpProductResume(s);this.sendResult(o,i);break}case me.PRODUCT_CANCEL:{let i=await this.handler.handleAcpProductCancel(s);this.sendResult(o,i);break}case me.PRODUCT_ROLLBACK:{let i=await this.handler.handleAcpProductRollback(s);this.sendResult(o,i);break}case me.PRODUCT_STATUS:{let i=await this.handler.handleAcpProductStatus(s);this.sendResult(o,i);break}case me.PRODUCT_SUBSCRIBE:{let i=await this.handler.handleAcpProductSubscribe(s);this.sendResult(o,i);break}case me.TEAM_DELEGATE:{let i=await this.handler.handleAcpTeamDelegate(s);this.sendResult(o,i);break}default:this.sendError(o,eo.METHOD_NOT_FOUND,`Unknown method: ${t}`)}}catch(i){this.sendError(o,eo.INTERNAL_ERROR,i.message)}}handleNotification(e){this.log(`received notification: ${e.method}`)}handleResponse(e){let t=this.outboundRequestMap.get(e.id);if(t){this.outboundRequestMap.delete(e.id);let n=this.pendingPermissions.get(t);if(n){this.pendingPermissions.delete(t);let o=e.result;n.resolve(o?.optionId??"deny")}}else this.log(`received response for id=${String(e.id)} (no matching outbound request)`)}async onInitialize(e,t){this.hostCapabilities=t.clientCapabilities??{},this.hostSupportsExtendedEvents=this.hostCapabilities.extendedEvents??!1,this.hostSupportsExtendedMethods=this.hostCapabilities.extendedMethods??!1;let n=t.clientInfo?.name??"unknown",o=t.clientInfo?.version??"unknown";this.log(`initialize: host=${n} v=${o}, proto=${String(t.protocolVersion)}, extendedEvents=${this.hostSupportsExtendedEvents}, extendedMethods=${this.hostSupportsExtendedMethods}`);let s=await this.handler.handleAcpInitialize(t);this.sendResult(e,s)}async onSessionNew(e,t){let n=await this.handler.handleAcpSessionNew(t);this.activeSessionId=n.sessionId,this.sendResult(e,n)}async onSessionPrompt(e,t){if(!this.activeSessionId||this.activeSessionId!==t.sessionId){this.sendError(e,eo.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}let n=await this.handler.handleAcpSessionPrompt(t);this.sendResult(e,n)}async onSessionEnd(e,t){if(this.activeSessionId!==t.sessionId){this.sendError(e,eo.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}await this.handler.handleAcpSessionEnd(t),this.activeSessionId=null,this.sendResult(e,{})}async onSessionSetConfig(e,t){if(this.activeSessionId!==t.sessionId){this.sendError(e,eo.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}await this.handler.handleAcpSessionSetConfig(t),this.sendResult(e,{})}async onAbort(e,t){await this.handler.handleAcpAbort(t),this.sendResult(e,{aborted:!0})}async onDream(e,t){let n=await this.handler.handleAcpDream(t);this.sendResult(e,n)}sendResult(e,t){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} result
478
+ `);let n={jsonrpc:"2.0",id:e,result:t};this.transport.send(n)}sendError(e,t,n,o){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} error=${n}
478
479
  `);let s={jsonrpc:"2.0",id:e,error:{code:t,message:n,...o!==void 0?{data:o}:{}}};this.transport.send(s)}isJsonRpcResponse(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&("result"in t||"error"in t)&&!("method"in t)}log(e){this.verbose&&process.stderr.write(`[acp-server] ${e}
479
- `)}};import{ACP_SESSION_UPDATE_TYPES as lt,ACP_EXTENDED_SESSION_UPDATE_TYPES as ue}from"qlogicagent-runtime-contracts";function bm(r,e,t,n){let o=gx(t,n);o&&r.emitSessionUpdate(e,o.type,o.payload)}function gx(r,e){switch(r){case"turn.delta":return{type:lt.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:e.text}}};case"turn.reasoning_delta":return{type:lt.AGENT_THOUGHT_CHUNK,payload:{content:{type:"text",text:e.text}}};case"turn.tool_call":return{type:lt.TOOL_CALL,payload:{toolCallId:e.callId,status:"in_progress",title:e.name,kind:"execute",rawInput:fx(e.arguments)}};case"turn.tool_result":return{type:lt.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:e.ok?"completed":"failed",...e.outputPreview?{content:[{type:"content",content:{type:"text",text:e.outputPreview}}]}:{},...e.error?{content:[{type:"content",content:{type:"text",text:e.error}}]}:{}}};case"turn.tool_blocked":return{type:lt.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:"failed",content:[{type:"content",content:{type:"text",text:e.reason??"blocked"}}]}};case"turn.plan_update":return{type:lt.PLAN,payload:{entries:[{content:e.content,priority:"medium",status:"in_progress"}]}};case"turn.usage_update":{let t=e.usage,n=t?.inputTokens??t?.input_tokens??0,o=t?.outputTokens??t?.output_tokens??0;return{type:lt.USAGE_UPDATE,payload:{used:n+o,size:t?.contextWindow??2e5}}}case"turn.end":return null;case"turn.error":return{type:lt.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:`[Error] ${e.error??"Unknown error"}`}}};case"turn.suggestions":return{type:lt.AVAILABLE_COMMANDS_UPDATE,payload:{availableCommands:(e.items??[]).map(t=>({name:t.text,description:t.description??""}))}};case"turn.subagent_started":return{type:ue.X_SUBAGENT_STARTED,payload:{agentId:e.subagentId,agentName:e.agentType,task:e.prompt}};case"turn.subagent_delta":return{type:ue.X_SUBAGENT_DELTA,payload:{agentId:e.subagentId??e.agentType,text:e.text}};case"turn.subagent_ended":return{type:ue.X_SUBAGENT_ENDED,payload:{agentId:e.subagentId,result:e.outputPreview}};case"turn.media_result":return{type:ue.X_MEDIA_RESULT,payload:{mediaId:e.taskId??hx(),type:e.mediaType,url:e.url,metadata:{model:e.model,provider:e.provider}}};case"turn.media_progress":return{type:ue.X_MEDIA_PROGRESS,payload:{mediaId:e.taskId,progress:e.percent,stage:e.status}};case"turn.skill_instruction":return{type:ue.X_SKILL_INSTRUCTION,payload:{skillId:"unknown",instruction:String(e.instruction??"")}};case"turn.recovery":return{type:ue.X_RECOVERY,payload:{errorType:e.action,message:e.detail??"",action:"retry"}};case"turn.ask_user":return{type:ue.X_ASK_USER,payload:{question:(e.questions??[])[0]?.question??"",options:(e.questions??[])[0]?.options?.map(t=>t.label)}};case"session.info":return{type:ue.X_SESSION_INFO,payload:{sessionId:e.sessionId,model:e.model,metadata:{cwd:e.cwd,turnCount:e.turnCount}}};case"memory.updated":return{type:ue.X_MEMORY_UPDATED,payload:{memoryId:e.source,action:"updated",summary:e.summary}};case"team.member.notification":return{type:ue.X_TEAM_MEMBER_UPDATE,payload:{memberId:e.memberId,type:e.method,payload:e.params??{}}};case"solo.progress":return{type:ue.X_SOLO_STARTED,payload:{evaluationId:e.soloId,agents:[e.agentId],task:e.progress??""}};case"solo.agentDelta":return{type:ue.X_SUBAGENT_DELTA,payload:{agentId:e.agentId,text:e.text}};case"solo.evaluation":return{type:ue.X_SOLO_SELECTED,payload:{evaluationId:e.soloId,winnerId:e.winnerId,reason:e.reasoning}};case"product.taskStarted":return{type:ue.X_PRODUCT_TASK_STARTED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:e.assignee}};case"product.taskCompleted":return{type:ue.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",result:e.result,status:"completed"}};case"product.taskFailed":return{type:ue.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",status:"failed"}};case"product.checkpointed":return{type:ue.X_PRODUCT_CHECKPOINT,payload:{workflowId:e.productId,checkpointId:e.timestamp,completedTasks:[]}};case"turn.start":case"turn.todos_updated":case"task.updated":case"turn.exec_progress":case"turn.heartbeat":case"turn.tool_use_summary":case"turn.artifact":case"turn.annotations":case"tool.approval.request":case"permission.rule_updated":case"team.updated":case"team.member.state":case"pong":case"agents.status":case"agents.error":case"product.budgetWarning":case"product.completed":return null;default:return null}}function fx(r){if(r)try{return JSON.parse(r)}catch{return{raw:r}}}function hx(){return Math.random().toString(36).slice(2,10)}var km=["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","agents.scan","agents.list","agents.config","agents.setConfig","agents.getConfig","agents.removeConfig","agents.setGateway","solo.start","solo.status","solo.cancel","solo.select","product.create","product.resume","product.pause","product.checkpoint","product.status","product.list","project.create","project.list","project.delete","session.switchProject","session.getState"];var Mr=class{capabilities=["web_search","reader","tokenizer","moderations"];baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4}async webSearch(e,t){let n=`${this.baseUrl}/tools/web-search`,o={tool:"web-search-pro",messages:[{role:"user",content:e}],stream:!1},s=await this.postJSON(n,o),i=[],a=t?.maxResults??10;if(s.web_search){for(let c of s.web_search.slice(0,a))i.push({title:c.title??"",url:c.link??"",snippet:(c.content??"").slice(0,500),content:c.content});return i}for(let c of s.choices??[])for(let d of c.message?.tool_calls??[])for(let l of d.search_result??[]){if(i.length>=a)break;i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content})}return i}async reader(e){let t=`${this.baseUrl}/tools/reader`,n={tool:"reader",messages:[{role:"user",content:e}],stream:!1};return{title:"",content:(await this.postJSON(t,n)).choices?.[0]?.message?.content??"",url:e}}async tokenize(e,t){let n=`${this.baseUrl}/tokenizer`,o={model:t,messages:[{role:"user",content:e}]};return{tokenCount:(await this.postJSON(n,o)).usage?.total_tokens??0,model:t}}async moderate(e){let t=`${this.baseUrl}/moderations`,n={input:e},s=(await this.postJSON(t,n)).results?.[0];return{flagged:s?.flagged??!1,categories:s?.categories??{},scores:s?.category_scores}}async postJSON(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Zhipu Tool API error ${n.status}: ${o}`)}return n.json()}};var Sx=new Set(["zhipu","zhipu-openai","zhipu-coding"]),xx="https://open.bigmodel.cn/api/paas/v4";function Rx(r,e){if(!(!r||!e)&&Sx.has(r))return new Mr({baseUrl:xx,apiKey:e})}function _x(r){let e=r.pathname.split("/").filter(Boolean),n=(e[e.length-1]??"").replace(/\.md$/i,"").replace(/[^a-zA-Z0-9_-]/g,"-");return/^(skill|readme|index|install|main)$/i.test(n)&&e.length>=2?e[e.length-2].replace(/[^a-zA-Z0-9_-]/g,"-"):n||""}var Cx=[/继续(桌面|电脑|刚才|上次|之前)的/,/接着(桌面|电脑|刚才|上次|之前)的/,/刚才(那个|那件|说的|聊的|做的)/,/上次(说到|聊到|做到|讲到)/,/桌面(端|上)?(那个|那边|的任务|的对话|在做)/,/电脑(端|上)?(那个|那边|的任务|的对话|在做)/,/之前(那个|在做的|讨论的|说的)/,/帮我继续/,/接着(做|干|搞|写|改)/,/continue (from |where |the )?desktop/i,/pick up where/i,/what were we (doing|working on|talking about)/i,/continue (the |our )?(last |previous )?(task|conversation|chat)/i];function Ax(r){return!r||r.length<3?!1:Cx.some(e=>e.test(r))}var Aa=class r{running=!1;activeTurn=null;verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentProjectRoot;currentHooks=null;mcpManager=null;mcpReady=Promise.resolve();pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new zo;mediaPersistence=new Ar;memoryPrefetchState=Ct();qmemoryAdapter=null;qmemoryUserId="";memdir=null;fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;acpDetector=new hr;agentConfigStore=null;soloEvaluator=null;productOrchestrator=null;soloProcessManager=null;productProcessManager=null;acpServer=null;idleDreamTimer=null;idleDreamMinutes=30;idleDreamEnabled=!1;lastDreamAt=0;dreamCooldownMs=14400*1e3;dreamMaxDurationMs=300*1e3;constructor(e){this.verbose=e.verbose,this.registry=new Ht,this.mediaClient=new hn({registry:this.registry});let t=Number(process.env.QLOGICAGENT_IDLE_DREAM_MS);t>0&&(this.idleDreamMinutes=t/6e4);let n=Number(process.env.QLOGICAGENT_DREAM_COOLDOWN_MS);n>=0&&(this.dreamCooldownMs=n),this.transport=e.transport??new pn({verbose:e.verbose}),this.taskStore.onTaskChange((s,i)=>{i&&this.sendNotification("task.updated",{taskId:s,type:i.type,lifecycle:i.lifecycle,label:i.label})}),tp({log:{info:s=>this.log(s),warn:s=>this.log(`[warn] ${s}`),error:s=>this.log(`[error] ${s}`),debug:s=>{e.verbose&&this.log(`[debug] ${s}`)}},onExecProgress:s=>{this.sendNotification("turn.exec_progress",{output:s.output,elapsedTimeSeconds:s.elapsedTimeSeconds,totalLines:s.totalLines,totalBytes:s.totalBytes})}});let o=new _r;o.ensureInitialized(),this.memdir=o}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(wx(e)||Tx(e)){this.acpServer.dispatchMessage(e);return}if(kx(e)){let t=e.method;if(t==="initialize"||t.startsWith("session/")||t.startsWith("x/")||t.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!bx(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.cancelIdleDreamTimer(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{tm().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.user_response":this.handleUserResponse(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"media.listModels":this.handleMediaListModels(e);break;case"media.cancel":this.handleMediaCancel(e);break;case"media.status":this.handleMediaStatus(e);break;case"provider.list":this.handleProviderList(e);break;case"config.get":this.handleConfigGet(e);break;case"config.update":this.handleConfigUpdate(e);break;case"config.tunables":this.handleConfigTunables(e);break;case"config.updateTunable":this.handleConfigUpdateTunable(e);break;case"todos.list":this.handleTodosList(e);break;case"tasks.list":this.handleTasksList(e);break;case"tasks.cancel":this.handleTasksCancel(e);break;case"agents.scan":this.handleAgentsScan(e);break;case"agents.list":this.handleAgentsList(e);break;case"agents.config":this.handleAgentsConfig(e);break;case"agents.setConfig":this.handleAgentsSetConfig(e);break;case"agents.getConfig":this.handleAgentsGetConfig(e);break;case"agents.removeConfig":this.handleAgentsRemoveConfig(e);break;case"agents.setGateway":this.handleAgentsSetGateway(e);break;case"agents.getGateway":this.handleAgentsGetGateway(e);break;case"agents.processes":this.handleAgentsProcesses(e);break;case"agents.kill":this.handleAgentsKill(e);break;case"agents.listConfigured":this.handleAgentsListConfigured(e);break;case"agents.getLog":this.handleAgentsGetLog(e);break;case"agents.testConnection":this.handleAgentsTestConnection(e);break;case"solo.start":this.handleSoloStart(e);break;case"solo.status":this.handleSoloStatus(e);break;case"solo.cancel":this.handleSoloCancel(e);break;case"solo.select":this.handleSoloSelect(e);break;case"solo.list":this.handleSoloList(e);break;case"solo.delete":this.handleSoloDelete(e);break;case"product.create":this.handleProductCreate(e);break;case"product.resume":this.handleProductResume(e);break;case"product.pause":this.handleProductPause(e);break;case"product.checkpoint":this.handleProductCheckpoint(e);break;case"product.status":this.handleProductStatus(e);break;case"product.list":this.handleProductList(e);break;case"product.delete":this.handleProductDelete(e);break;case"project.create":this.handleProjectCreate(e);break;case"project.list":this.handleProjectList(e);break;case"project.delete":this.handleProjectDelete(e);break;case"project.rename":this.handleProjectRename(e);break;case"project.archive":this.handleProjectArchive(e);break;case"project.unarchive":this.handleProjectUnarchive(e);break;case"project.archiveByGroup":this.handleProjectArchiveByGroup(e);break;case"session.switchProject":this.handleSessionSwitchProject(e);break;case"session.getState":this.handleSessionGetState(e);break;case"instructions.list":this.handleInstructionsList(e);break;case"instructions.read":this.handleInstructionsRead(e);break;case"instructions.write":this.handleInstructionsWrite(e);break;case"instructions.delete":this.handleInstructionsDelete(e);break;case"skills.list":this.handleSkillsList(e);break;case"skills.activate":this.handleSkillsActivate(e);break;case"skills.deactivate":this.handleSkillsDeactivate(e);break;case"skills.delete":this.handleSkillsDelete(e);break;case"skills.promote":this.handleSkillsPromote(e);break;case"skills.stats":this.handleSkillsStats(e);break;case"plans.list":this.handlePlansList(e);break;case"plans.get":this.handlePlansGet(e);break;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleInitialize(e){let t=e.params,n=t?.protocolVersion??"unknown",o=t?.host?.name??t?.hostName??"unknown",s=t?.host?.version??t?.hostVersion??"?",i=n.split(".")[0],a=Er.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${Er}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${Er}`});return}this.log(`[initialize] host=${o} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:Er,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:rt().map(c=>c.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","turn.ask_user","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...km]}}),this.ensureDefaultProject()}ensureDefaultProject(){if(!Ut()){let t=F.join(process.env.HOME||process.env.USERPROFILE||yx(),"XiaozhiClaw");M.existsSync(t)||M.mkdirSync(t,{recursive:!0});let n=um(t);this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type})}}handleThreadCreate(e){let t=e.params,n=t?.id??pe();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&(Ot(t.cwd),this.currentProjectRoot=t.cwd,this.mediaPersistence.setProjectDir(t.cwd)),this.currentSessionId=n,this.sessionState=new Vt(n),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Ct(),this.enableIdleDream(),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 Jc(n,this.currentProjectRoot)).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(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Failed to list threads: ${o.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,o=t.decision;if(!n||!o){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:n,decision:o==="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})}handleUserResponse(e){let t=e.params,n=t?.requestId;if(!n){this.log("[warn] thread.user_response missing requestId"),e.id!==void 0&&this.sendResponse(e.id,{received:!1});return}let o=this.pendingAskUser.get(n);if(!o){this.log(`[warn] thread.user_response: no pending request ${n}`),e.id!==void 0&&this.sendResponse(e.id,{received:!1});return}if(this.pendingAskUser.delete(n),t?.declined===!0)o.resolve(null);else{let i=t?.answers??{};o.resolve(i)}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:_.INVALID_PARAMS,message:"sessionId is required"});return}try{let o=await Kc(n,this.currentProjectRoot);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:`Session not found: ${n}`});return}e.id!==void 0&&this.sendResponse(e.id,{metadata:o.metadata,messages:o.messages,costSnapshot:o.costSnapshot})}catch(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Failed to resume session: ${o.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??pe(),o=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;if(a?.workdir&&typeof a.workdir=="string"&&(Ot(a.workdir),this.currentProjectRoot=a.workdir,this.mediaPersistence.setProjectDir(a.workdir)),a?.sessionType==="group"&&typeof a?.groupKey=="string"){let g=a.groupKey,f=g.split(":"),m=f.length>=3?f.slice(1).join(":"):g,y=_a(m);if(y)Ot(y.workspaceDir),this.currentProjectRoot=y.workspaceDir,this.mediaPersistence.setProjectDir(y.workspaceDir),Ut()?.id!==y.id&&Vn(y.id);else{let k=a.groupName||m,b=f[1]??"unknown",x=f.slice(2).join(":")||m,S=process.env.HOME??process.env.USERPROFILE??".",A=k.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",$=F.join(S,"XiaozhiClaw","groups",A),D=Ra({name:k,workspaceDir:$,type:"group",groupId:m});D&&(Ot(D.workspaceDir),this.currentProjectRoot=D.workspaceDir,this.mediaPersistence.setProjectDir(D.workspaceDir),Vn(D.id),this.sendNotification("project.created",{id:D.id,name:D.name,type:"group",groupId:m,workspaceDir:D.workspaceDir}))}}let c=1800*1e3,d=!1,l=a?.projectHint,u=l&&typeof l=="object"&&"name"in l?l:typeof l=="string"?{name:l,updatedAt:Date.now()}:null;if(u&&a?.sessionType!=="group"){let g=Date.now()-u.updatedAt;if(g>c)d=!0,this.log(`[projectHint] stale (${Math.round(g/6e4)}min old), skipping auto-switch`);else{let f=u.name,m=Ut();if(!m||m.name.toLowerCase()!==f.toLowerCase()){let y=Qt(),k=f.toLowerCase(),b=y.find(x=>x.name.toLowerCase()===k)??y.find(x=>x.name.toLowerCase().includes(k));b&&b.status==="active"&&(Vn(b.id),Ot(b.workspaceDir),this.currentProjectRoot=b.workspaceDir,this.mediaPersistence.setProjectDir(b.workspaceDir))}}}{let g={},f=a?.provider,m=a?.apiKey;f&&m&&(g[f]=m);let y=a?.mediaApiKeys;y&&Object.assign(g,y),this.currentMediaApiKeys=g,Qu(this.mediaClient,g,(k,b,x)=>{this.sessionState?.addMediaUsage(k,b,x)},a?.mediaProviders,(k,b,x,S,A)=>{this.sendNotification("turn.media_progress",{turnId:n,taskId:k,mediaType:b,percent:x,status:S,...A?{provider:A}:{}})}),Ku(Rx(f,m))}Yu(async g=>{let f=`ask-${pe().slice(0,8)}`;return new Promise(m=>{this.pendingAskUser.set(f,{resolve:m}),this.sendNotification("turn.ask_user",{requestId:f,questions:g.map(y=>({header:y.header,question:y.question,options:y.options}))})})}),e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n}),o&&o!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),rd()),this.currentSessionId=o,this.sessionState=new Vt(o),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Ct(),this.enableIdleDream());let p=new AbortController;this.activeTurn&&this.activeTurn.abort(),this.activeTurn=p,this.log(`turn ${n} starting (session: ${o})`),this.sendNotification("turn.start",{turnId:n,model:a?.model??(this.currentModel||void 0),provider:a?.provider||void 0});try{let g={provider:a?.provider,model:a?.model,apiKey:a?.apiKey,baseUrl:a?.baseUrl,maxRounds:a?.maxRounds,temperature:a?.temperature,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,summaryModel:a?.summaryModel??process.env.QLOGICAGENT_SUMMARY_MODEL,maxConcurrentTools:a?.maxConcurrentTools,mediaProviders:a?.mediaProviders,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,mcpServers:a?.mcpServers};{let T=g.provider??"",E=g.model??"";T&&E&&this.registry.getModelInfo(T,E)?.streamRequired&&(g.streamRequired=!0)}let f=this.resolveAgent(g);if(this.permissionChecker&&a?.permissions){let T=a.permissions,E=la(T);this.permissionChecker.ruleEngineRef.setMode(E.mode),E.rules.length>0&&this.permissionChecker.ruleEngineRef.replaceRules(E.rules),E.defaultBehavior&&this.permissionChecker.ruleEngineRef.setDefaultBehavior(E.defaultBehavior)}if(!f){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 m,y=a?.workdir??process.cwd();try{let T=await nd(y,this.currentHooks??void 0);T.length>0&&(m=td(T))}catch{}try{let E=new Kn(y).loadAll();E&&(m=m?`${m}
480
+ `)}};function Mm(r,e,t,n){let o=AR(t,n);o&&r.emitSessionUpdate(e,o.type,o.payload)}function AR(r,e){switch(r){case"turn.delta":return{type:ze.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:e.text}}};case"turn.reasoning_delta":return{type:ze.AGENT_THOUGHT_CHUNK,payload:{content:{type:"text",text:e.delta}}};case"turn.tool_call":return{type:ze.TOOL_CALL,payload:{toolCallId:e.callId,status:"in_progress",title:e.name,kind:"execute",rawInput:CR(e.arguments)}};case"turn.tool_result":return{type:ze.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:e.ok?"completed":"failed",...e.outputPreview?{content:[{type:"content",content:{type:"text",text:e.outputPreview}}]}:{},...e.error?{content:[{type:"content",content:{type:"text",text:e.error}}]}:{}}};case"turn.tool_blocked":return{type:ze.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:"failed",content:[{type:"content",content:{type:"text",text:e.reason??"blocked"}}]}};case"turn.plan_update":return{type:ze.PLAN,payload:{entries:[{content:e.content,priority:"medium",status:"in_progress"}]}};case"turn.usage_update":{let t=e.usage,n=t?.inputTokens??t?.input_tokens??0,o=t?.outputTokens??t?.output_tokens??0;return{type:ze.USAGE_UPDATE,payload:{used:n+o,size:t?.contextWindow??2e5}}}case"turn.end":return null;case"turn.error":return{type:ze.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:`[Error] ${e.error??"Unknown error"}`}}};case"turn.suggestions":return{type:ze.AVAILABLE_COMMANDS_UPDATE,payload:{availableCommands:(e.items??[]).map(t=>({name:t.text,description:t.description??""}))}};case"turn.sidechain_started":return{type:ce.X_SUBAGENT_STARTED,payload:{agentId:String(e.depth??0),agentName:e.role,task:void 0}};case"turn.subagent_delta":return{type:ce.X_SUBAGENT_DELTA,payload:{agentId:e.subagentId??e.agentType,text:e.text}};case"turn.sidechain_completed":return{type:ce.X_SUBAGENT_ENDED,payload:{agentId:String(e.depth??0),result:void 0}};case"turn.media_result":return{type:ce.X_MEDIA_RESULT,payload:{mediaId:e.taskId??PR(),type:e.mediaType,url:e.url,metadata:{model:e.model,provider:e.provider}}};case"turn.media_progress":return{type:ce.X_MEDIA_PROGRESS,payload:{mediaId:e.taskId,progress:e.percent,stage:e.status}};case"turn.skill_instruction":return{type:ce.X_SKILL_INSTRUCTION,payload:{skillId:"unknown",instruction:String(e.instruction??"")}};case"turn.recovery":return{type:ce.X_RECOVERY,payload:{errorType:e.action,message:e.detail??"",action:"retry"}};case"turn.ask_user":return{type:ce.X_ASK_USER,payload:{question:(e.questions??[])[0]?.question??"",options:(e.questions??[])[0]?.options?.map(t=>t.label)}};case"session.info":return{type:ce.X_SESSION_INFO,payload:{sessionId:e.sessionId,model:e.model,metadata:{cwd:e.cwd,turnCount:e.turnCount}}};case"memory.updated":return{type:ce.X_MEMORY_UPDATED,payload:{memoryId:e.source,action:"updated",summary:e.summary}};case"team.member.notification":return{type:ce.X_TEAM_MEMBER_UPDATE,payload:{memberId:e.memberId,type:e.method,payload:e.params??{}}};case"solo.progress":return{type:ce.X_SOLO_STARTED,payload:{evaluationId:e.soloId,agents:[e.agentId],task:e.progress??""}};case"solo.agentDelta":return{type:ce.X_SUBAGENT_DELTA,payload:{agentId:e.agentId,text:e.text}};case"solo.evaluation":return{type:ce.X_SOLO_SELECTED,payload:{evaluationId:e.soloId,winnerId:e.winnerId,reason:e.reasoning}};case"product.taskStarted":return{type:ce.X_PRODUCT_TASK_STARTED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:e.assignee}};case"product.taskCompleted":return{type:ce.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",result:e.result,status:"completed"}};case"product.taskFailed":return{type:ce.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",status:"failed"}};case"product.checkpointed":return{type:ce.X_PRODUCT_CHECKPOINT,payload:{workflowId:e.productId,checkpointId:e.timestamp,completedTasks:[]}};case"turn.start":case"turn.task_updated":case"turn.exec_progress":case"turn.heartbeat":case"turn.tool_use_summary":case"turn.artifact":case"turn.annotations":case"tool.approval.request":case"permission.rule_updated":case"pong":case"agents.status":case"agents.error":case"product.budgetWarning":case"product.completed":return null;default:return null}}function CR(r){if(r)try{return JSON.parse(r)}catch{return{raw:r}}}function PR(){return Math.random().toString(36).slice(2,10)}var Em=["initialize","thread.create","thread.list","thread.turn","session.resume","session.getInfo","session.getMessages","memory.list","memory.read","memory.write","memory.search","memory.delete","memory.dream","tools.list","media.listModels","config.get","config.update","todos.list","tasks.list","tasks.cancel","agent.ping","agent.abort","tool.approval.response","agents.scan","agents.list","agents.config","agents.setConfig","agents.getConfig","agents.removeConfig","agents.setGateway","solo.start","solo.status","solo.cancel","solo.select","product.create","product.resume","product.pause","product.checkpoint","product.status","product.list","project.create","project.list","project.delete","project.rename","project.archive","project.unarchive","project.archiveByGroup","session.switchProject","session.getState","session.create","session.list","session.get","session.update","session.delete","session.archive","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus"];var Lr=class{capabilities=["web_search","reader","tokenizer","moderations"];baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??3e4}async webSearch(e,t){let n=`${this.baseUrl}/tools/web-search`,o={tool:"web-search-pro",messages:[{role:"user",content:e}],stream:!1},s=await this.postJSON(n,o),i=[],a=t?.maxResults??10;if(s.web_search){for(let c of s.web_search.slice(0,a))i.push({title:c.title??"",url:c.link??"",snippet:(c.content??"").slice(0,500),content:c.content});return i}for(let c of s.choices??[])for(let d of c.message?.tool_calls??[])for(let l of d.search_result??[]){if(i.length>=a)break;i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content})}return i}async reader(e){let t=`${this.baseUrl}/tools/reader`,n={tool:"reader",messages:[{role:"user",content:e}],stream:!1};return{title:"",content:(await this.postJSON(t,n)).choices?.[0]?.message?.content??"",url:e}}async tokenize(e,t){let n=`${this.baseUrl}/tokenizer`,o={model:t,messages:[{role:"user",content:e}]};return{tokenCount:(await this.postJSON(n,o)).usage?.total_tokens??0,model:t}}async moderate(e){let t=`${this.baseUrl}/moderations`,n={input:e},s=(await this.postJSON(t,n)).results?.[0];return{flagged:s?.flagged??!1,categories:s?.categories??{},scores:s?.category_scores}}async postJSON(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`Zhipu Tool API error ${n.status}: ${o}`)}return n.json()}};var MR=new Set(["zhipu","zhipu-openai","zhipu-coding"]),ER="https://open.bigmodel.cn/api/paas/v4";function OR(r,e){if(!(!r||!e)&&MR.has(r))return new Lr({baseUrl:ER,apiKey:e})}function DR(r){let e=r.pathname.split("/").filter(Boolean),n=(e[e.length-1]??"").replace(/\.md$/i,"").replace(/[^a-zA-Z0-9_-]/g,"-");return/^(skill|readme|index|install|main)$/i.test(n)&&e.length>=2?e[e.length-2].replace(/[^a-zA-Z0-9_-]/g,"-"):n||""}var LR=[/继续(桌面|电脑|刚才|上次|之前)的/,/接着(桌面|电脑|刚才|上次|之前)的/,/刚才(那个|那件|说的|聊的|做的)/,/上次(说到|聊到|做到|讲到)/,/桌面(端|上)?(那个|那边|的任务|的对话|在做)/,/电脑(端|上)?(那个|那边|的任务|的对话|在做)/,/之前(那个|在做的|讨论的|说的)/,/帮我继续/,/接着(做|干|搞|写|改)/,/continue (from |where |the )?desktop/i,/pick up where/i,/what were we (doing|working on|talking about)/i,/continue (the |our )?(last |previous )?(task|conversation|chat)/i];function NR(r){return!r||r.length<3?!1:LR.some(e=>e.test(r))}var Da=class r{running=!1;activeTurn=null;verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentProjectRoot;currentHooks=null;mcpManager=null;mcpReady=Promise.resolve();pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Xo;mediaPersistence=new Er;memoryPrefetchState=Pt();qmemoryAdapter=null;qmemoryUserId="";memdir=null;fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;acpDetector=new Tr;agentConfigStore=null;soloEvaluator=null;productOrchestrator=null;soloProcessManager=null;productProcessManager=null;acpServer=null;idleDreamTimer=null;idleDreamMinutes=30;idleDreamEnabled=!1;lastDreamAt=0;dreamCooldownMs=14400*1e3;dreamMaxDurationMs=300*1e3;constructor(e){this.verbose=e.verbose,this.registry=new zt,this.mediaClient=new Tn({registry:this.registry});let t=Number(process.env.QLOGICAGENT_IDLE_DREAM_MS);t>0&&(this.idleDreamMinutes=t/6e4);let n=Number(process.env.QLOGICAGENT_DREAM_COOLDOWN_MS);n>=0&&(this.dreamCooldownMs=n),this.transport=e.transport??new hn({verbose:e.verbose}),this.taskStore.onTaskChange((s,i)=>{i&&this.sendNotification("task.updated",{taskId:s,type:i.type,lifecycle:i.lifecycle,label:i.label})}),Tp({log:{info:s=>this.log(s),warn:s=>this.log(`[warn] ${s}`),error:s=>this.log(`[error] ${s}`),debug:s=>{e.verbose&&this.log(`[debug] ${s}`)}},onExecProgress:s=>{this.sendNotification("turn.exec_progress",{output:s.output,elapsedTimeSeconds:s.elapsedTimeSeconds,totalLines:s.totalLines,totalBytes:s.totalBytes})}});let o=new Ir;o.ensureInitialized(),this.memdir=o}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(Oa(e)||Zn(e)){this.acpServer.dispatchMessage(e);return}if(Qn(e)){let t=e.method;if(t==="initialize"||t.startsWith("session/")||t.startsWith("x/")||t.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Ea(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.cancelIdleDreamTimer(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{Tm().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.user_response":this.handleUserResponse(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"media.listModels":this.handleMediaListModels(e);break;case"media.cancel":this.handleMediaCancel(e);break;case"media.status":this.handleMediaStatus(e);break;case"provider.list":this.handleProviderList(e);break;case"config.get":this.handleConfigGet(e);break;case"config.update":this.handleConfigUpdate(e);break;case"config.tunables":this.handleConfigTunables(e);break;case"config.updateTunable":this.handleConfigUpdateTunable(e);break;case"todos.list":this.handleTodosList(e);break;case"tasks.list":this.handleTasksList(e);break;case"tasks.cancel":this.handleTasksCancel(e);break;case"agents.scan":this.handleAgentsScan(e);break;case"agents.list":this.handleAgentsList(e);break;case"agents.config":this.handleAgentsConfig(e);break;case"agents.setConfig":this.handleAgentsSetConfig(e);break;case"agents.getConfig":this.handleAgentsGetConfig(e);break;case"agents.removeConfig":this.handleAgentsRemoveConfig(e);break;case"agents.setGateway":this.handleAgentsSetGateway(e);break;case"agents.getGateway":this.handleAgentsGetGateway(e);break;case"agents.processes":this.handleAgentsProcesses(e);break;case"agents.kill":this.handleAgentsKill(e);break;case"agents.listConfigured":this.handleAgentsListConfigured(e);break;case"agents.getLog":this.handleAgentsGetLog(e);break;case"agents.testConnection":this.handleAgentsTestConnection(e);break;case"solo.start":this.handleSoloStart(e);break;case"solo.status":this.handleSoloStatus(e);break;case"solo.cancel":this.handleSoloCancel(e);break;case"solo.select":this.handleSoloSelect(e);break;case"solo.list":this.handleSoloList(e);break;case"solo.delete":this.handleSoloDelete(e);break;case"product.create":this.handleProductCreate(e);break;case"product.resume":this.handleProductResume(e);break;case"product.pause":this.handleProductPause(e);break;case"product.checkpoint":this.handleProductCheckpoint(e);break;case"product.status":this.handleProductStatus(e);break;case"product.list":this.handleProductList(e);break;case"product.delete":this.handleProductDelete(e);break;case"project.create":this.handleProjectCreate(e);break;case"project.list":this.handleProjectList(e);break;case"project.delete":this.handleProjectDelete(e);break;case"project.rename":this.handleProjectRename(e);break;case"project.archive":this.handleProjectArchive(e);break;case"project.unarchive":this.handleProjectUnarchive(e);break;case"project.archiveByGroup":this.handleProjectArchiveByGroup(e);break;case"session.switchProject":this.handleSessionSwitchProject(e);break;case"session.getState":this.handleSessionGetState(e);break;case"instructions.list":this.handleInstructionsList(e);break;case"instructions.read":this.handleInstructionsRead(e);break;case"instructions.write":this.handleInstructionsWrite(e);break;case"instructions.delete":this.handleInstructionsDelete(e);break;case"skills.list":this.handleSkillsList(e);break;case"skills.activate":this.handleSkillsActivate(e);break;case"skills.deactivate":this.handleSkillsDeactivate(e);break;case"skills.delete":this.handleSkillsDelete(e);break;case"skills.promote":this.handleSkillsPromote(e);break;case"skills.stats":this.handleSkillsStats(e);break;case"plans.list":this.handlePlansList(e);break;case"plans.get":this.handlePlansGet(e);break;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleInitialize(e){let t=e.params,n=t?.protocolVersion??"unknown",o=t?.host?.name??t?.hostName??"unknown",s=t?.host?.version??t?.hostVersion??"?",i=n.split(".")[0],a=nn.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${nn}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${nn}`});return}this.log(`[initialize] host=${o} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:nn,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:ct().map(c=>c.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","turn.ask_user","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...Em]}}),this.ensureDefaultProject()}ensureDefaultProject(){if(!Dt()){let t=F.join(process.env.HOME||process.env.USERPROFILE||IR(),"XiaozhiClaw");M.existsSync(t)||M.mkdirSync(t,{recursive:!0});let n=np(t);this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type})}}handleThreadCreate(e){let t=e.params,n=t?.id??ge();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&(Ut(t.cwd),this.currentProjectRoot=t.cwd,this.mediaPersistence.setProjectDir(t.cwd)),this.currentSessionId=n,this.sessionState=new Xt(n),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Pt(),this.enableIdleDream(),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 nd(n,this.currentProjectRoot)).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(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Failed to list threads: ${o.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,o=t.decision;if(!n||!o){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:n,decision:o==="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})}handleUserResponse(e){let t=e.params,n=t?.requestId;if(!n){this.log("[warn] thread.user_response missing requestId"),e.id!==void 0&&this.sendResponse(e.id,{received:!1});return}let o=this.pendingAskUser.get(n);if(!o){this.log(`[warn] thread.user_response: no pending request ${n}`),e.id!==void 0&&this.sendResponse(e.id,{received:!1});return}if(this.pendingAskUser.delete(n),t?.declined===!0)o.resolve(null);else{let i=t?.answers??{};o.resolve(i)}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:x.INVALID_PARAMS,message:"sessionId is required"});return}try{let o=await td(n,this.currentProjectRoot);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:`Session not found: ${n}`});return}e.id!==void 0&&this.sendResponse(e.id,{metadata:o.metadata,messages:o.messages,costSnapshot:o.costSnapshot})}catch(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Failed to resume session: ${o.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??ge(),o=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;if(a?.workdir&&typeof a.workdir=="string"&&(Ut(a.workdir),this.currentProjectRoot=a.workdir,this.mediaPersistence.setProjectDir(a.workdir)),a?.sessionType==="group"&&typeof a?.groupKey=="string"){let m=a.groupKey,f=m.split(":"),g=f.length>=3?f.slice(1).join(":"):m,y=ra(g);if(y)Ut(y.workspaceDir),this.currentProjectRoot=y.workspaceDir,this.mediaPersistence.setProjectDir(y.workspaceDir),Dt()?.id!==y.id&&Lt(y.id);else{let b=a.groupName||g,k=f[1]??"unknown",S=f.slice(2).join(":")||g,R=process.env.HOME??process.env.USERPROFILE??".",P=b.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",O=F.join(R,"XiaozhiClaw","groups",P),L=oa({name:b,workspaceDir:O,type:"group",groupId:g});L&&(Ut(L.workspaceDir),this.currentProjectRoot=L.workspaceDir,this.mediaPersistence.setProjectDir(L.workspaceDir),Lt(L.id),this.sendNotification("project.created",{id:L.id,name:L.name,type:"group",groupId:g,workspaceDir:L.workspaceDir}))}}let c=1800*1e3,d=!1,l=a?.projectHint,u=l&&typeof l=="object"&&"name"in l?l:typeof l=="string"?{name:l,updatedAt:Date.now()}:null;if(u&&a?.sessionType!=="group"){let m=Date.now()-u.updatedAt;if(m>c)d=!0,this.log(`[projectHint] stale (${Math.round(m/6e4)}min old), skipping auto-switch`);else{let f=u.name,g=Dt();if(!g||g.name.toLowerCase()!==f.toLowerCase()){let y=ht(),b=f.toLowerCase(),k=y.find(S=>S.name.toLowerCase()===b)??y.find(S=>S.name.toLowerCase().includes(b));k&&k.status==="active"&&(Lt(k.id),Ut(k.workspaceDir),this.currentProjectRoot=k.workspaceDir,this.mediaPersistence.setProjectDir(k.workspaceDir))}}}{let m={},f=a?.provider,g=a?.apiKey;f&&g&&(m[f]=g);let y=a?.mediaApiKeys;y&&Object.assign(m,y),this.currentMediaApiKeys=m,yp(this.mediaClient,m,(b,k,S)=>{this.sessionState?.addMediaUsage(b,k,S)},a?.mediaProviders,(b,k,S,R,P)=>{this.sendNotification("turn.media_progress",{turnId:n,taskId:b,mediaType:k,percent:S,status:R,...P?{provider:P}:{}})}),mp(OR(f,g))}hp(async m=>{let f=`ask-${ge().slice(0,8)}`;return new Promise(g=>{this.pendingAskUser.set(f,{resolve:g}),this.sendNotification("turn.ask_user",{requestId:f,questions:m.map(y=>({header:y.header,question:y.question,options:y.options}))})})}),e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n}),o&&o!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),ud()),this.currentSessionId=o,this.sessionState=new Xt(o),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Pt(),this.enableIdleDream());let p=new AbortController;this.activeTurn&&this.activeTurn.abort(),this.activeTurn=p,this.log(`turn ${n} starting (session: ${o})`),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,mediaProviders:a?.mediaProviders,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,mcpServers:a?.mcpServers};{let T=m.provider??"",E=m.model??"";T&&E&&this.registry.getModelInfo(T,E)?.streamRequired&&(m.streamRequired=!0)}let f=this.resolveAgent(m);if(this.permissionChecker&&a?.permissions){let T=a.permissions,E=ga(T);this.permissionChecker.ruleEngineRef.setMode(E.mode),E.rules.length>0&&this.permissionChecker.ruleEngineRef.replaceRules(E.rules),E.defaultBehavior&&this.permissionChecker.ruleEngineRef.setDefaultBehavior(E.defaultBehavior)}if(!f){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 g,y=a?.workdir??process.cwd();try{let T=await ld(y,this.currentHooks??void 0);T.length>0&&(g=cd(T))}catch{}try{let E=new Yn(y).loadAll();E&&(g=g?`${g}
480
481
 
481
- ${E}`:E)}catch{}let k=s.filter(T=>T.role==="user").map(T=>typeof T.content=="string"?T.content:"").join(" "),{domain:b,source:x}=pd({cwd:y,hostOverride:a?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:k});this.sessionTaskDomain=b,x==="auto-detect"&&gd(k,b)&&md(y,b);let S=this.memdir,A=await sd({basePrompt:a?.systemPrompt,instructionBlock:m,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[id(y),ad(b),ld(),_n("memory",()=>S&&S.getIndexForPrompt()||null,"memory INDEX.md may change between turns"),_n("plans",()=>{try{let E=new Jn(y).loadActive();return E.length===0?null:`## Active Plans
482
+ ${E}`:E)}catch{}let b=s.filter(T=>T.role==="user").map(T=>typeof T.content=="string"?T.content:"").join(" "),{domain:k,source:S}=kd({cwd:y,hostOverride:a?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:b});this.sessionTaskDomain=k,S==="auto-detect"&&wd(b,k)&&Td(y,k);let R=this.memdir,P=await pd({basePrompt:a?.systemPrompt,instructionBlock:g,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[md(y),gd(k),fd(),Pn("memory",()=>R&&R.getIndexForPrompt()||null,"memory INDEX.md may change between turns"),Pn("plans",()=>{try{let E=new Jn(y).loadActive();return E.length===0?null:`## Active Plans
482
483
 
483
484
  `+E.map(V=>V.content).join(`
484
485
  ---
485
- `)}catch{return null}},"plans may change between turns")]});for(let T of s)T.role==="user"&&pi(o,T,this.currentProjectRoot,n).catch(()=>{});await this.mcpReady;let $=rt(),D=new Set($.map(T=>T.function.name)),B=[...$,...i.filter(T=>!D.has(T.function.name))],v=s;if(d&&s.length>0){let T=Ut(),E=Qt().filter(me=>me.status==="active").map(me=>me.name).slice(0,10).join(", ");v=[{role:"system",content:`[\u6CE8\u610F\uFF1A\u7528\u6237\u4ECE IM \u7AEF\u53D1\u6765\u6D88\u606F\uFF0C\u4F46\u684C\u9762\u7AEF\u5DF2\u8D85\u8FC730\u5206\u949F\u672A\u6D3B\u8DC3\uFF0C\u65E0\u6CD5\u786E\u5B9A\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u5DE5\u4F5C\u3002\u5F53\u524D\u6D3B\u8DC3\u9879\u76EE\uFF1A${T?.name??"\u65E0"}\u3002\u53EF\u7528\u9879\u76EE\uFF1A${E||"\u65E0"}\u3002\u8BF7\u5728\u56DE\u590D\u5F00\u5934\u7B80\u77ED\u8BE2\u95EE\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u7EE7\u7EED\uFF0C\u4F8B\u5982\uFF1A"\u4F60\u60F3\u7EE7\u7EED\u5728\u300CXX\u300D\u9879\u76EE\u4E2D\u5DE5\u4F5C\u5417\uFF1F"]`},...s]}let oe=a?.desktopRecentContext;if(!d&&oe&&oe.length>0&&s.length>0){let T=s[s.length-1],E=T?.role==="user"&&typeof T.content=="string"?T.content:"";if(Ax(E)){let V={role:"system",content:"[\u4EE5\u4E0B\u662F\u7528\u6237\u5728\u684C\u9762\u7AEF\u7684\u8FD1\u671F\u5BF9\u8BDD\uFF0C\u4F9B\u4F60\u53C2\u8003\u4EE5\u4FDD\u6301\u4E0A\u4E0B\u6587\u8FDE\u8D2F]"},me={role:"system",content:"[\u684C\u9762\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u7ED3\u675F\uFF0C\u4EE5\u4E0B\u662F\u5F53\u524D IM \u7AEF\u7684\u5BF9\u8BDD]"};v=[V,...oe,me,...v],this.log(`[continuation] injected ${oe.length} desktop messages as reference`)}}for await(let T of f.run({turnId:n,sessionId:o,messages:v,tools:B,systemPrompt:A,config:g},p.signal)){let E=new Date().toISOString();switch(T.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:T.turnId,text:T.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:T.text,createdAt:E}});break;case"end":if(this.sendNotification("turn.end",{turnId:T.turnId,content:T.content,usage:T.usage,model:T.model,provider:T.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:T.content,createdAt:E}}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,T.model??this.currentModel);let V=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:T.model??this.currentModel,sessionCostUSD:V.totalInputTokens*3e-6+V.totalOutputTokens*15e-6})}T.content&&pi(o,{role:"assistant",content:T.content},this.currentProjectRoot,n).catch(()=>{});break;case"error":if(this.sendNotification("turn.error",{turnId:T.turnId,error:T.error,code:T.code}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,this.currentModel);let V=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:this.currentModel,sessionCostUSD:V.totalInputTokens*3e-6+V.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:T.turnId,instruction:T.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:T.turnId,callId:T.callId,name:T.name,arguments:T.arguments,item:{id:T.callId,type:"tool_call",role:"assistant",toolName:T.name,toolCallId:T.callId,arguments:T.arguments,createdAt:E}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:T.turnId,callId:T.callId,name:T.name,ok:T.ok,...T.error?{error:T.error}:{},...T.outputPreview?{outputPreview:T.outputPreview}:{},item:{id:`${T.callId}-result`,type:"tool_result",role:"assistant",toolName:T.name,toolCallId:T.callId,output:T.ok?T.outputPreview??"":T.error,approved:T.ok,createdAt:E}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:T.turnId,callId:T.callId,name:T.name,reason:T.reason,item:{id:`${T.callId}-blocked`,type:"tool_blocked",role:"system",toolName:T.name,toolCallId:T.callId,text:T.reason,approved:!1,createdAt:E}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:T.turnId,action:T.action,...T.detail?{detail:T.detail}:{},item:{id:`${n}-recovery-${pe().slice(0,8)}`,type:"recovery",role:"system",strategy:T.action,text:T.detail,createdAt:E}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:T.turnId,slug:T.slug,content:T.content,item:{id:`${n}-plan-${pe().slice(0,8)}`,type:"plan_update",role:"assistant",text:T.content,createdAt:E}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:T.turnId,text:T.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:T.turnId,items:T.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:T.turnId,mediaType:T.mediaType,url:T.url,...T.model?{model:T.model}:{},...T.provider?{provider:T.provider}:{},...T.taskId?{taskId:T.taskId}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:T.turnId,artifactId:T.artifactId,type:T.artifactType,title:T.title,...T.filePath?{filePath:T.filePath}:{},...T.language?{language:T.language}:{},...T.content?{content:T.content}:{},...T.mimeType?{mimeType:T.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:T.turnId,subagentId:T.subagentId,agentType:T.agentType,...T.prompt?{prompt:T.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:T.turnId,subagentId:T.subagentId,agentType:T.agentType,ok:T.ok,...T.outputPreview?{outputPreview:T.outputPreview}:{},...T.error?{error:T.error}:{}});break;case"annotations":this.sendNotification("turn.annotations",{turnId:T.turnId,annotations:T.annotations});break;case"heartbeat":this.sendNotification("turn.heartbeat",{turnId:T.turnId,message:T.message});break;case"tool_use_summary":this.sendNotification("turn.tool_use_summary",{turnId:T.turnId,summary:T.summary});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){qc(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:this.currentProjectRoot??process.cwd(),messageCount:s.length},this.currentProjectRoot).catch(()=>{});let T=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:this.currentProjectRoot??process.cwd(),turnCount:T.turnCount}),this.currentTransport&&this.currentApiKey&&g.summaryModel&&Xc(o,{sessionId:o,createdAt:0,lastActiveAt:0,turnCount:T.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:g.summaryModel},this.currentProjectRoot),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(n,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(g){if(p.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let f=g instanceof Error?g.message:String(g);this.sendNotification("turn.error",{turnId:n,error:f,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===p&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
486
+ `)}catch{return null}},"plans may change between turns")]});for(let T of s)T.role==="user"&&hi(o,T,this.currentProjectRoot,n).catch(()=>{});await this.mcpReady;let O=ct(),L=new Set(O.map(T=>T.function.name)),B=[...O,...i.filter(T=>!L.has(T.function.name))],v=s;if(d&&s.length>0){let T=Dt(),E=ht().filter(re=>re.status==="active").map(re=>re.name).slice(0,10).join(", ");v=[{role:"system",content:`[\u6CE8\u610F\uFF1A\u7528\u6237\u4ECE IM \u7AEF\u53D1\u6765\u6D88\u606F\uFF0C\u4F46\u684C\u9762\u7AEF\u5DF2\u8D85\u8FC730\u5206\u949F\u672A\u6D3B\u8DC3\uFF0C\u65E0\u6CD5\u786E\u5B9A\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u5DE5\u4F5C\u3002\u5F53\u524D\u6D3B\u8DC3\u9879\u76EE\uFF1A${T?.name??"\u65E0"}\u3002\u53EF\u7528\u9879\u76EE\uFF1A${E||"\u65E0"}\u3002\u8BF7\u5728\u56DE\u590D\u5F00\u5934\u7B80\u77ED\u8BE2\u95EE\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u7EE7\u7EED\uFF0C\u4F8B\u5982\uFF1A"\u4F60\u60F3\u7EE7\u7EED\u5728\u300CXX\u300D\u9879\u76EE\u4E2D\u5DE5\u4F5C\u5417\uFF1F"]`},...s]}let ee=a?.desktopRecentContext;if(!d&&ee&&ee.length>0&&s.length>0){let T=s[s.length-1],E=T?.role==="user"&&typeof T.content=="string"?T.content:"";if(NR(E)){let V={role:"system",content:"[\u4EE5\u4E0B\u662F\u7528\u6237\u5728\u684C\u9762\u7AEF\u7684\u8FD1\u671F\u5BF9\u8BDD\uFF0C\u4F9B\u4F60\u53C2\u8003\u4EE5\u4FDD\u6301\u4E0A\u4E0B\u6587\u8FDE\u8D2F]"},re={role:"system",content:"[\u684C\u9762\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u7ED3\u675F\uFF0C\u4EE5\u4E0B\u662F\u5F53\u524D IM \u7AEF\u7684\u5BF9\u8BDD]"};v=[V,...ee,re,...v],this.log(`[continuation] injected ${ee.length} desktop messages as reference`)}}for await(let T of f.run({turnId:n,sessionId:o,messages:v,tools:B,systemPrompt:P,config:m},p.signal)){let E=new Date().toISOString();switch(T.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:T.turnId,text:T.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:T.text,createdAt:E}});break;case"end":if(this.sendNotification("turn.end",{turnId:T.turnId,content:T.content,usage:T.usage,model:T.model,provider:T.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:T.content,createdAt:E}}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,T.model??this.currentModel);let V=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:T.model??this.currentModel,sessionCostUSD:V.totalInputTokens*3e-6+V.totalOutputTokens*15e-6})}T.content&&hi(o,{role:"assistant",content:T.content},this.currentProjectRoot,n).catch(()=>{});break;case"error":if(this.sendNotification("turn.error",{turnId:T.turnId,error:T.error,code:T.code}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,this.currentModel);let V=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:this.currentModel,sessionCostUSD:V.totalInputTokens*3e-6+V.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:T.turnId,instruction:T.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:T.turnId,callId:T.callId,name:T.name,arguments:T.arguments,item:{id:T.callId,type:"tool_call",role:"assistant",toolName:T.name,toolCallId:T.callId,arguments:T.arguments,createdAt:E}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:T.turnId,callId:T.callId,name:T.name,ok:T.ok,...T.error?{error:T.error}:{},...T.outputPreview?{outputPreview:T.outputPreview}:{},item:{id:`${T.callId}-result`,type:"tool_result",role:"assistant",toolName:T.name,toolCallId:T.callId,output:T.ok?T.outputPreview??"":T.error,approved:T.ok,createdAt:E}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:T.turnId,callId:T.callId,name:T.name,reason:T.reason,item:{id:`${T.callId}-blocked`,type:"tool_blocked",role:"system",toolName:T.name,toolCallId:T.callId,text:T.reason,approved:!1,createdAt:E}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:T.turnId,action:T.action,...T.detail?{detail:T.detail}:{},item:{id:`${n}-recovery-${ge().slice(0,8)}`,type:"recovery",role:"system",strategy:T.action,text:T.detail,createdAt:E}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:T.turnId,slug:T.slug,content:T.content,item:{id:`${n}-plan-${ge().slice(0,8)}`,type:"plan_update",role:"assistant",text:T.content,createdAt:E}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:T.turnId,text:T.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:T.turnId,items:T.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:T.turnId,mediaType:T.mediaType,url:T.url,...T.model?{model:T.model}:{},...T.provider?{provider:T.provider}:{},...T.taskId?{taskId:T.taskId}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:T.turnId,artifactId:T.artifactId,type:T.artifactType,title:T.title,...T.filePath?{filePath:T.filePath}:{},...T.language?{language:T.language}:{},...T.content?{content:T.content}:{},...T.mimeType?{mimeType:T.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:T.turnId,subagentId:T.subagentId,agentType:T.agentType,...T.prompt?{prompt:T.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:T.turnId,subagentId:T.subagentId,agentType:T.agentType,ok:T.ok,...T.outputPreview?{outputPreview:T.outputPreview}:{},...T.error?{error:T.error}:{}});break;case"annotations":this.sendNotification("turn.annotations",{turnId:T.turnId,annotations:T.annotations});break;case"heartbeat":this.sendNotification("turn.heartbeat",{turnId:T.turnId,message:T.message});break;case"tool_use_summary":this.sendNotification("turn.tool_use_summary",{turnId:T.turnId,summary:T.summary});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){ed(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:this.currentProjectRoot??process.cwd(),messageCount:s.length},this.currentProjectRoot).catch(()=>{});let T=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:this.currentProjectRoot??process.cwd(),turnCount:T.turnCount}),this.currentTransport&&this.currentApiKey&&m.summaryModel&&od(o,{sessionId:o,createdAt:0,lastActiveAt:0,turnCount:T.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:m.summaryModel},this.currentProjectRoot),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(n,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(m){if(p.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let f=m instanceof Error?m.message:String(m);this.sendNotification("turn.error",{turnId:n,error:f,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===p&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
486
487
  Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
487
488
  Be specific: "run the tests" beats "continue".
488
489
  Stay silent if the next step isn't obvious.
489
- Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,n,o,s){if(t.filter(d=>d.role==="assistant").length<1)return;let c=[...t.slice(-6),{role:"user",content:r.SUGGESTION_PROMPT}];try{let d="";for await(let u of n.stream({model:s,messages:c,temperature:.3,maxTokens:200},o))u.type==="delta"&&(d+=u.text);let l=d.match(/\[[\s\S]*\]/);if(l){let u=JSON.parse(l[0]),p=Array.isArray(u)?u.filter(g=>typeof g.text=="string"&&g.text.length>0).slice(0,5):[];p.length>0&&this.sendNotification("turn.suggestions",{turnId:e,items:p})}}catch{}}async handleDream(e){let t=e.params??{},n=t.turnId??pe(),o=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",c=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n});let d=new AbortController;this.activeTurn=d,this.log(`dream ${n} starting (session: ${o}, sessions reviewing: ${c.length})`);let l={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,reasoning:s?.reasoning,promptCacheKey:s?.promptCacheKey,promptCacheRetention:s?.promptCacheRetention,serviceTier:s?.serviceTier,openaiBuiltinTools:s?.openaiBuiltinTools,maxToolCalls:s?.maxToolCalls,parallelToolCalls:s?.parallelToolCalls,textVerbosity:s?.textVerbosity};{let p=l.provider??"",g=l.model??"";p&&g&&this.registry.getModelInfo(p,g)?.streamRequired&&(l.streamRequired=!0)}if(!this.resolveAgent(l)){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 p={context:{memoryRoot:i,transcriptDir:a,currentSessionId:o,listSessionsSince:async()=>c},triggerConfig:{force:s?.force!==!1},transport:this.currentTransport,toolInvoker:{invoke:async(f,m,y,k)=>{if(m.startsWith("$"))return{result:y};let b=Me(m);if(!b)return{result:"",error:`Unknown tool: ${m}`};let x=`tc_${pe().slice(0,8)}`;try{let S=JSON.parse(y),A=await b.execute(x,S,k);return{result:A.content.map(D=>D.text??"").join(`
490
- `),error:A.details?.error}}catch(S){return{result:"",error:S instanceof Error?S.message:String(S)}}}},tools:rt(),apiKey:this.currentApiKey,model:l.model??this.currentModel,log:{info:f=>this.log(f),warn:f=>this.log(`[warn] ${f}`),error:f=>this.log(`[error] ${f}`),debug:f=>{this.verbose&&this.log(`[debug] ${f}`)}},hooks:this.currentHooks??void 0,parentSignal:d.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},g=await Bc(p);if(g.ok){if(this.qmemoryAdapter&&this.qmemoryUserId)try{let f=await Wc({adapter:this.qmemoryAdapter,userId:this.qmemoryUserId,memoryRoot:i,log:{info:m=>this.log(m),debug:m=>{this.verbose&&this.log(m)}}});f.ran&&this.sendNotification("memory.decay.completed",{decayed:f.decayed,archived:f.archived,durationMs:f.durationMs})}catch(f){this.log(`[decay] post-dream decay error: ${f instanceof Error?f.message:String(f)}`)}this.sendNotification("turn.end",{turnId:n,content:`Dream consolidation completed. ${g.sessionsReviewed} sessions reviewed, ${g.filesTouched.length} files touched. Duration: ${g.durationMs}ms.`,usage:{prompt:0,completion:0}})}else this.sendNotification("turn.error",{turnId:n,error:g.error??"Dream consolidation failed",code:"DREAM_FAILED"});this.log(`dream ${n} completed`)}catch(p){if(d.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Dream aborted",code:"ABORTED"});else{let g=p instanceof Error?p.message:String(p);this.sendNotification("turn.error",{turnId:n,error:g,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===d&&(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,o=e.model,s=e.apiKey,i=e.baseUrl;if(!n||!s){let h=this.loadSettingsSync();h&&(n=n??h.provider,s=s??h.apiKey,o=o??h.model,i=i??h.baseUrl,n&&s&&this.log(`loaded provider from settings.json: ${n}, model: ${o}`))}if(!n||!s)return null;o=o??this.registry.getProvider(n)?.defaultModel??"",e.model=o,e.provider=n,e.apiKey=s,i&&(e.baseUrl=i);let a=$o({provider:n,model:o,apiKey:s,baseUrl:i},this.registry);oi()&&(a.transport=ri(a.transport,this.currentSessionId||"default"));let c={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}`)}},d={invoke:async(h,w,R,P)=>{if(w.startsWith("$"))return{result:R};let C=Me(w);if(!C)return{result:"",error:`Unknown tool: ${w}`};let j=`tc_${pe().slice(0,8)}`;try{let G=JSON.parse(R),L=await C.execute(j,G,P),U=[],ce=L.content.map(re=>{if(re.type==="image"&&re.data){let ct=re.mimeType||"image/png";return U.push(`data:${ct};base64,${re.data}`),"[Image]"}return re.text??""}).join(`
491
- `);U.length>0&&(L.imageUrls=[...U,...L.imageUrls??[]]);let Y=L.details?.error,ne=L.details?.type,ae=ne?.split("_")[0];if(ne==="three_d_generate"&&(ae="3d"),ae&&["image","tts","video","music","3d"].includes(ae)){let re=L.details?.mediaUrls??[],ct=ae;for(let He of re)this.sendNotification("turn.media_result",{turnId:h,mediaType:ct,url:He,model:L.details?.model,provider:L.details?.provider,...L.details?.durationMs?{durationSeconds:L.details.durationMs/1e3}:{},...L.details?.taskId?{taskId:L.details.taskId}:{}});if(re.length>0)try{let He=await this.mediaPersistence.downloadAll(re,{type:ae,sessionId:this.currentSessionId||void 0},{warn:Te=>this.log(Te)});if(He.length>0){for(let Te of He)ce=ce.replaceAll(Te.remoteUrl,Te.localPath);this.sendNotification("turn.media_persisted",{turnId:h,files:He.map(Te=>({remoteUrl:Te.remoteUrl,localPath:Te.localPath,bytes:Te.bytes,mimeType:Te.mimeType}))})}}catch{}}if(ne==="task"&&!Y&&L.details?.taskList)try{let re=L.details;re?.taskList&&this.sendNotification("turn.todos_updated",{turnId:h,items:re.taskList,summary:{total:re.total??re.taskList.length,completed:re.completed??0,inProgress:re.inProgress??0,notStarted:re.notStarted??0}})}catch{}let ke=Array.isArray(L.details?.matches)?L.details.matches:void 0,Yn=L.imageUrls;return{result:ce,error:Y,toolReferences:ke,imageUrls:Yn}}catch(G){return{result:"",error:G instanceof Error?G.message:String(G)}}}},l=ii(c);this.currentHooks=l,this.taskStore.setHooks(l,this.currentSessionId??""),Xu({onTaskCreated:h=>{l.invoke("task.created",{sessionId:this.currentSessionId??"",taskId:String(h.id),taskType:"planning",label:h.title}).catch(()=>{})},onTaskCompleted:h=>{l.invoke("task.completed",{sessionId:this.currentSessionId??"",taskId:String(h.id),taskType:"planning",label:h.title}).catch(()=>{})}});let u=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(u){let h=wc({baseUrl:u,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=h,this.qmemoryUserId=this.currentSessionId??"default",yc(l,{memoryProvider:h,userId:this.currentSessionId??"default",log:{debug:w=>c.debug(w),warn:w=>c.warn(w)}},this.memoryPrefetchState)}kc(l,{currentCwd:this.currentProjectRoot??void 0,log:{debug:h=>c.debug(h),warn:h=>c.warn(h)}}),Rl(l,c,{transport:a.transport,apiKey:a.apiKey});let p=e?.mcpServers,g=ia(p??{}),f=Hl();try{if(M.existsSync(f)){let h=JSON.parse(M.readFileSync(f,"utf8")),w=ia(h),R=new Set(g.map(P=>P.name));g=[...g,...w.filter(P=>!R.has(P.name))]}}catch{}if(g.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new ur({servers:g,log:c}),Lt(async()=>{await this.mcpManager?.disconnectAll()});let h=()=>this.mcpManager;ve(np(h)),ve(op(h)),ve(Cp({listServers:async()=>{let w=this.mcpManager;return w?w.getConnectedServers().map(P=>({name:P,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async w=>{if(!this.mcpManager)return[];let P=`mcp__${w.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return pt().filter(C=>C.startsWith(P)).map(C=>({name:C.slice(P.length),prefixedName:C}))},callTool:async(w,R,P,C)=>{let G=`mcp__${w.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+R,L=Me(G);if(!L)return{success:!1,error:`Tool not found: ${G}`};try{return{success:!0,content:(await L.execute(`mcp_${Date.now()}`,P??{},C)).content.map(Y=>Y.text??"").join(`
492
- `)}}catch(U){return{success:!1,error:U.message}}},listResources:async w=>{let R=this.mcpManager;return R?(await R.listResources(w)).map(C=>({uri:C.uri,name:C.name,mimeType:C.mimeType,description:C.description,server:C.server})):[]},readResource:async(w,R)=>{let P=this.mcpManager;if(!P)throw new Error("MCP not initialized");return(await P.readResource(w,R)).map(j=>({uri:j.uri,mimeType:j.mimeType,text:j.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpReady=this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),c.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(w=>{c.warn(`[mcp] connection error: ${w instanceof Error?w.message:w}`)})}let m=[],y=jl();M.existsSync(y)&&m.push(y);let k=e?.pluginPaths;if(Array.isArray(k))for(let h of k)typeof h=="string"&&M.existsSync(h)&&m.push(h);ap(m,c).then(h=>{if(h.length===0)return;this.pluginLoader=new pr({pluginDirs:h,hookRegistry:l,log:c}),this.pluginLoader.loadAll().then(R=>{c.info(`[plugins] ${R.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(R=>{c.warn(`[plugins] load error: ${R instanceof Error?R.message:R}`)});let w=this.pluginLoader;l.register({point:"turn.submitted",handler:async()=>(await w.discoverNew(),await w.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(h=>{c.warn(`[plugins] marketplace resolve error: ${h instanceof Error?h.message:h}`)});let b=e?.permissions,x=la(b),S=new mr(x);if(Ut()?.type==="group"){let h=Bu();for(let w of h)S.addRule(w);oa(!0),c.info(`[permissions] group security mode active: ${h.length} rules injected`)}else oa(!1);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new fr({ruleEngine:S,hookRegistry:l,onRequestApproval:async h=>{if(this.acpServer&&this.acpServer.sessionId)try{let w=await this.acpServer.requestPermission({sessionId:this.acpServer.sessionId,permissionId:h.approvalId,toolCall:{callId:h.callId,toolName:h.toolName,arguments:h.arguments?JSON.stringify(h.arguments):""},message:h.message,options:[{id:"allow",label:"Allow"},{id:"deny",label:"Deny"},{id:"allowAlways",label:"Always allow",persistent:!0}]});return{approvalId:h.approvalId,decision:w.optionId==="allow"||w.optionId==="allowAlways"?"approved":"denied"}}catch{return{approvalId:h.approvalId,decision:"denied"}}return this.sendNotification("tool.approval.request",{approvalId:h.approvalId,callId:h.callId,toolName:h.toolName,arguments:h.arguments?JSON.stringify(h.arguments):"",message:h.message,suggestions:h.suggestions?.map(w=>`${w.pattern}:${w.behavior}`)}),new Promise(()=>{})},onPermissionUpdate:h=>{c.info(`[permissions] rule saved: ${h.pattern} \u2192 ${h.behavior}`),this.sendNotification("permission.rule_updated",{pattern:h.pattern,behavior:h.behavior})},onDenied:(h,w)=>{c.warn(`[permissions] blocked "${h}": ${w}`)}});let $=rt();this.permissionChecker.setToolMeta($),this.permissionUnregister=this.permissionChecker.register();let D=this.currentProjectRoot?Ze(this.currentProjectRoot):void 0,B=[...D?[D]:[],Qe(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];ve(bp({listSkills:()=>{let h=[];this.pluginLoader&&h.push(...this.pluginLoader.getPluginSkills());let w=e?.skillPaths;if(Array.isArray(w)){for(let R of w)if(typeof R=="string"){let P=F.basename(R);h.some(C=>C.name===P)||h.push({name:P,source:"gateway",filePath:F.join(R,"SKILL.md"),baseDir:R})}}return h},listSkillsFull:async h=>{let w=[],R=new Set,P=Qe();for(let C of B)try{let j=await M.promises.readdir(C,{withFileTypes:!0});for(let G of j){if(!G.isDirectory())continue;let L=F.join(C,G.name,"SKILL.md");try{let U=await M.promises.readFile(L,"utf8"),ce=F.basename(C);if(h&&ce!==h)continue;R.add(ce);let Y=C===P?"global":C===D?"project":"config",ae=U.match(/^---\n[\s\S]*?^version:\s*(\S+)/m)?.[1],ke=U.startsWith(`---
493
- `)?U.indexOf("---",4):-1,ct=(ke>=0?U.slice(ke+3).trimStart():U).split(`
494
- `).find(He=>He.trim()&&!He.startsWith("#"))?.trim()??`Skill from ${ce}`;w.push({name:G.name,description:ct,category:ce,scope:Y,version:ae})}catch{}}}catch{}if(this.pluginLoader)for(let C of this.pluginLoader.getPluginSkills())h&&C.source!==h||(R.add(C.source??"plugin"),w.push({name:C.name,description:`Plugin skill (${C.source})`,category:C.source,scope:"plugin"}));return{skills:w,categories:[...R]}},readSkillContent:async h=>{for(let w of B){let R=F.join(w,h,"SKILL.md");try{return await M.promises.readFile(R,"utf8")}catch{}}return null},viewSkill:async(h,w)=>{for(let R of B){let P=w?F.join(R,h,w):F.join(R,h,"SKILL.md");try{let C=await M.promises.readFile(P,"utf8");return{name:h,content:C}}catch{}}return null},executeSkillSubturn:async(h,w,R,P)=>{let C=`skill_${h}_${pe().slice(0,8)}`,j=this.agent;if(!j)return"[skill] Cannot execute: no LLM provider configured";let G=J(),L=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:L,turnId:C,subagentId:C,agentType:`skill:${h}`}).catch(()=>{});let U=rt(),ce=R??`Execute skill "${h}" instructions.`,Y=[],ne;for await(let ae of j.run({turnId:C,sessionId:L,messages:[{role:"user",content:ce}],tools:U,systemPrompt:w,config:{parentDepth:1}},P)){if(ae.type==="end"&&ae.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:L,turnId:C,subagentId:C,agentType:`skill:${h}`,reason:"normal"}).catch(()=>{}),Ir(G,h,!0),ae.content;if(ae.type==="delta"&&ae.text&&Y.push(ae.text),ae.type==="error"){ne=ae.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:L,turnId:C,subagentId:C,agentType:`skill:${h}`,reason:ne?"error":"normal",error:ne}).catch(()=>{}),ne?(Ir(G,h,!1),`[skill "${h}"] error: ${ne}`):(Ir(G,h,!0),Y.join("")||`[skill "${h}"] completed (no output)`)},manageSkill:async h=>{let w=this.currentProjectRoot,R=w?Ze(w):B[0]??Qe(),P=F.join(R,h.name),C=F.join(P,"SKILL.md");switch(h.action){case"create":{if(await M.promises.mkdir(P,{recursive:!0}),await M.promises.writeFile(C,h.content??"","utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",content:h.content??"",scope:"project"}}),At(),this.qmemoryAdapter&&this.qmemoryUserId){let G=(h.content??"").split(`
495
- `).slice(0,3).join(" ").slice(0,200),L=w?F.basename(w):"unknown";this.qmemoryAdapter.ingestExtracted([{text:`Learned skill "${h.name}" in project "${L}": ${G}`,category:"skill-learning"}],this.qmemoryUserId).catch(()=>{})}let j=w?` (project-scoped). To make it available across all projects, use: skill promote name:"${h.name}"`:"";return{success:!0,message:`Skill "${h.name}" created${j}`,path:P}}case"edit":return await M.promises.writeFile(C,h.content??"","utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",content:h.content??"",scope:"project"}}),{success:!0,message:`Skill "${h.name}" updated`,path:C};case"patch":{let j=await M.promises.readFile(C,"utf8");if(!h.oldString||!j.includes(h.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let G=j.replace(h.oldString,h.newString??"");return await M.promises.writeFile(C,G,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",content:G,scope:"project"}}),{success:!0,message:`Skill "${h.name}" patched`,path:C}}case"delete":return await M.promises.rm(P,{recursive:!0,force:!0}),this.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",action:"delete",scope:"project"}}),At(),{success:!0,message:`Skill "${h.name}" deleted`};default:return{success:!1,message:`Unknown action: ${h.action}`}}},promoteSkill:async h=>{let w=Ze(this.currentProjectRoot??void 0),R=F.join(w,h,"SKILL.md");try{await M.promises.access(R)}catch{return{success:!1,message:`Skill "${h}" not found in project skills. Cannot promote.`}}let P=Qe(),C=F.join(P,h);await M.promises.mkdir(C,{recursive:!0});let j=F.join(w,h),G=await M.promises.readdir(j);for(let L of G){let U=await M.promises.readFile(F.join(j,L));await M.promises.writeFile(F.join(C,L),U)}return this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:h,category:"promoted",content:await M.promises.readFile(R,"utf8"),scope:"global"}}),await M.promises.rm(j,{recursive:!0,force:!0}),this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-cleanup-${Date.now()}`,instruction:{name:h,category:"learned",action:"delete",scope:"project"}}),At(),{success:!0,message:`Skill "${h}" promoted to global (user-level) and removed from project scope. It will now be available across all projects.`,path:C}},installSkill:async(h,w)=>{let R;try{if(R=new URL(h),!["http:","https:"].includes(R.protocol))return{success:!1,message:`Invalid URL scheme: ${R.protocol}. Only http/https allowed.`}}catch{return{success:!1,message:`Invalid URL: ${h}`}}let P=w??_x(R);if(!P)return{success:!1,message:"Cannot derive skill name from URL. Please provide 'name' parameter."};try{let C=await fetch(h,{signal:AbortSignal.timeout(3e4)});if(!C.ok)return{success:!1,message:`Download failed: HTTP ${C.status} ${C.statusText}`};let j=C.headers.get("content-length");if(j&&parseInt(j,10)>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};let G=await C.text();if(!G.trim())return{success:!1,message:"Downloaded content is empty."};if(G.length>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};if(G.trimStart().startsWith("<!DOCTYPE")||G.trimStart().startsWith("<html"))return{success:!1,message:"URL returned an HTML page, not a raw markdown file. Use a raw/direct download link."};let L=Qe(),U=F.join(L,P);return await M.promises.mkdir(U,{recursive:!0}),await M.promises.writeFile(F.join(U,"SKILL.md"),G,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-install-${Date.now()}`,instruction:{name:P,category:"installed",content:G,scope:"global"}}),At(),{success:!0,message:`Skill "${P}" installed from ${R.host}. Available globally across all projects.`,path:U}}catch(C){return{success:!1,message:`Install failed: ${C instanceof Error?C.message:String(C)}`}}}})),ve(wp({abortSignal:void 0,currentForkDepth:0,forkAgent:async h=>{let w=bo(h.agent);if(!w)return{agentId:"",status:"failed",error:`Unknown agent type: ${h.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let R=pt(),P=Ps(R,w),j=rt().filter(Y=>P.includes(Y.function.name)),G=Ti(j,!0),L=h.maxTurns??w.maxTurns??200,U=await Sn({promptMessages:[{role:"user",content:h.prompt}],tools:G,transport:this.currentTransport,toolInvoker:d,apiKey:this.currentApiKey,model:this.currentModel,log:c,hooks:l,forkLabel:`agent-${h.agent}`,maxTurns:L,parentSignal:h.abortSignal,parentDepth:0,onEvent:Y=>{Y.type==="delta"&&Y.text&&this.sendNotification("turn.subagent_delta",{agentType:h.agent,text:Y.text})}}),ce=U.events.filter(Y=>Y.type==="end"&&"content"in Y).map(Y=>Y.content??"").join("")||U.events.filter(Y=>Y.type==="delta"&&"text"in Y).map(Y=>Y.text).join("");return{agentId:`fork-${h.agent}-${pe().slice(0,8)}`,status:U.ok?"completed":"failed",output:ce||void 0,error:U.error,tokensUsed:U.totalUsage.prompt+U.totalUsage.completion}}}));let v=ut(),oe=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"]}]]),T=async()=>{try{return JSON.parse(await M.promises.readFile(v,"utf8"))}catch{return{}}},E=async h=>{await M.promises.mkdir(F.dirname(v),{recursive:!0}),await M.promises.writeFile(v,JSON.stringify(h,null,2),"utf8")};ve(vp({getConfig:async h=>{let w=oe.get(h);if(!w)return{success:!1,error:`Unknown key: ${h}`};let R=await T(),P=h in R?R[h]:w.value;return{success:!0,setting:{...w,value:P,readOnly:$n.includes(h)}}},setConfig:async(h,w)=>{let R=oe.get(h);if(!R)return{success:!1,error:`Unknown key: ${h}`};let P=await T(),C=h in P?P[h]:R.value;return P[h]=w,await E(P),{success:!0,previousValue:C,setting:{...R,value:w}}},listConfig:async()=>{let h=await T();return{success:!0,settings:[...oe.values()].map(R=>({...R,value:R.key in h?h[R.key]:R.value,readOnly:$n.includes(R.key)}))}},resetConfig:async h=>{let w=oe.get(h);if(!w)return{success:!1,error:`Unknown key: ${h}`};let R=await T();return delete R[h],await E(R),{success:!0,setting:w}},isValidKey:h=>oe.has(h)}));let V=new Map,me=h=>{let w=/^(\d+)([smhd])$/.exec(h.trim());if(!w)return null;let R=parseInt(w[1],10),P=w[2];return R*({s:1e3,m:6e4,h:36e5,d:864e5}[P]??6e4)},Ae=h=>{h.timerId&&clearTimeout(h.timerId);let w=me(h.schedule);if(!w)return;let R=Date.now(),P=w-R%w||w;h.timerId=setTimeout(()=>{h.lastRunAt=new Date().toISOString(),h.repeat.completed++,h.lastStatus="success",c.info(`[cron] triggered job ${h.id} (${h.name})`),h.repeat.times===null||h.repeat.completed<h.repeat.times?Ae(h):(h.state="paused",h.enabled=!1)},P),h.nextRunAt=new Date(R+P).toISOString()};Lt(async()=>{for(let h of V.values())h.timerId&&clearTimeout(h.timerId)}),ve(xp({createJob:async h=>{let w=`cron_${pe().slice(0,8)}`,R={id:w,name:h.name??`Job ${w}`,prompt:h.prompt,schedule:h.schedule,scheduleDisplay:h.schedule,state:"scheduled",enabled:!0,repeat:{times:h.repeat??null,completed:0},allowedTools:h.allowedTools};return V.set(w,R),Ae(R),{success:!0,job:{...R,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...V.values()].map(w=>({...w,timerId:void 0}))}),getJob:async h=>{let w=V.get(h);return w?{success:!0,job:{...w,timerId:void 0}}:{success:!1,error:`Job not found: ${h}`}},updateJob:async(h,w)=>{let R=V.get(h);return R?(w.prompt!==void 0&&(R.prompt=w.prompt),w.schedule!==void 0&&(R.schedule=w.schedule,R.scheduleDisplay=w.schedule),w.name!==void 0&&(R.name=w.name),w.enabled!==void 0&&(R.enabled=w.enabled,R.state=w.enabled?"scheduled":"paused"),w.repeat!==void 0&&(R.repeat.times=w.repeat),w.allowedTools!==void 0&&(R.allowedTools=w.allowedTools),R.enabled?Ae(R):R.timerId&&(clearTimeout(R.timerId),R.timerId=void 0),{success:!0,job:{...R,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},deleteJob:async h=>{let w=V.get(h);return w?(w.timerId&&clearTimeout(w.timerId),V.delete(h),{success:!0}):{success:!1,error:`Job not found: ${h}`}},pauseJob:async h=>{let w=V.get(h);return w?(w.state="paused",w.enabled=!1,w.timerId&&(clearTimeout(w.timerId),w.timerId=void 0),{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},resumeJob:async h=>{let w=V.get(h);return w?(w.state="scheduled",w.enabled=!0,Ae(w),{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},triggerJob:async h=>{let w=V.get(h);return w?(w.lastRunAt=new Date().toISOString(),w.repeat.completed++,w.lastStatus="success",{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},validateSchedule:h=>me(h)!==null||/^\d{1,2}\s/.test(h)?null:`Invalid schedule: ${h}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let q=new Map;Lt(async()=>{for(let h of q.values())h.cleanup();q.clear()}),ve(Rp({startMonitor:async h=>{if(q.has(h.monitorId))return{action:"start",success:!1,error:`Monitor "${h.monitorId}" already exists.`};let w={monitorId:h.monitorId,source:h.source,target:h.target,conditions:h.conditions,startedAt:Date.now(),timeoutSeconds:h.timeoutSeconds,eventCount:0},R=()=>{};if(h.source==="file")try{let P=M.watch(h.target,{persistent:!1},()=>{w.eventCount++,c.info(`[monitor] file change detected: ${h.target}`)});R=()=>P.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${h.target}`}}if(h.timeoutSeconds>0){let P=setTimeout(()=>{let j=q.get(h.monitorId);j&&(j.cleanup(),q.delete(h.monitorId))},h.timeoutSeconds*1e3),C=R;R=()=>{clearTimeout(P),C()}}return q.set(h.monitorId,{info:w,cleanup:R}),{action:"start",success:!0,monitorId:h.monitorId}},stopMonitor:async h=>{let w=q.get(h);return w?(w.cleanup(),q.delete(h),{action:"stop",success:!0,monitorId:h}):{action:"stop",success:!1,error:`Monitor "${h}" not found.`}},listMonitors:async()=>[...q.values()].map(h=>h.info)}));let X=new Map,be={info:h=>c.info(h),warn:h=>c.warn(h)},ge=new Jt({onNotification:(h,w,R)=>{this.sendNotification("team.member.notification",{memberId:h,method:w,params:R})},onStateChange:(h,w)=>{this.sendNotification("team.member.state",{memberId:h,state:w});let R=ge.getHandle(h),C=ge.getUsageTracker(h)?.getUsage();this.emitAgentStatus(h,w,{missedBeats:ge.getMissedBeats(h),lastActivityAt:R?.lastActivityAt,usage:C&&C.totalTokens>0?{inputTokens:C.inputTokens,outputTokens:C.outputTokens,totalTokens:C.totalTokens}:void 0})},onExit:(h,w,R)=>{for(let P of X.values()){let C=P.members.find(j=>j.cwd&&`team-${P.name}-${j.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()===h.replace(/^team-/,""));C&&(C.isActive=!1)}c.info(`[team] member ${h} exited (code=${w}, signal=${R})`)},onMcpToolCall:(h,w,R)=>this.handleMcpToolCall(h,w,R),log:{info:h=>c.info(h),warn:h=>c.warn(h),debug:h=>c.debug(h)},sessionDir:F.join(J(),"agent-logs")});Lt(async()=>{ge.dispose()}),ve(_p({createTeam:async h=>{if(X.has(h.teamName))return{success:!1,error:`Team "${h.teamName}" already exists.`};let w=await Mn(),R=[];for(let C of h.members??[]){let j={...C,isActive:!0};if(w){let G=`team-${h.teamName}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),L=await pu(w,G,be);L?(j.worktreePath=L.worktreePath,j.worktreeBranch=L.branch,j.cwd=L.worktreePath,c.info(`[team] provisioned worktree for ${C.name}: ${L.worktreePath}`)):(j.cwd=process.cwd(),c.warn(`[team] worktree provision failed for ${C.name}, using shared cwd`))}else j.cwd=process.cwd();R.push(j)}let P={name:h.teamName,description:h.description,leadId:this.currentSessionId??"default",members:R,createdAt:new Date().toISOString()};X.set(h.teamName,P);for(let C of R){if(!C.cwd)continue;let j=`team-${h.teamName}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();try{await ge.spawn({memberId:j,name:C.name,cwd:C.cwd,prompt:`You are the "${C.name}" team member. Role: ${C.role}.`,agentType:C.role,verbose:this.verbose}),c.info(`[team] spawned child process for ${C.name} in ${C.cwd}`)}catch(G){c.warn(`[team] failed to spawn child process for ${C.name}: ${G instanceof Error?G.message:String(G)}`),C.isActive=!1}}return this.sendNotification("team.updated",{teamName:h.teamName,action:"created",members:P.members.map(C=>({agentName:C.name,role:C.role,worktreePath:C.worktreePath,pid:ge.getHandle(`team-${h.teamName}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase())?.pid}))}),{success:!0,team:P}},deleteTeam:async h=>{let w=X.get(h);if(!w)return{success:!1,error:`Team "${h}" not found.`};for(let P of w.members){let C=`team-${h}-${P.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();ge.kill(C),ge.remove(C)}let R=await Mn();if(R)for(let P of w.members)P.worktreePath&&P.worktreeBranch&&(await mu(R,P.worktreePath,P.worktreeBranch,be),c.info(`[team] cleaned up worktree for ${P.name}: ${P.worktreePath}`));return X.delete(h),this.sendNotification("team.updated",{teamName:h,action:"destroyed",members:[]}),{success:!0}},listTeams:async()=>({success:!0,teams:[...X.values()]}),getTeamStatus:async h=>{let w=X.get(h);if(!w)return{success:!1,error:`Team "${h}" not found.`};let R={};for(let P of w.members){let C=`team-${h}-${P.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),j=ge.getStatus(C);j&&(P.isActive=j.alive,R[P.name]={mediaProgress:j.mediaProgress,lastToolCall:j.lastToolCall,idleFor:j.idleFor,runningFor:j.runningFor})}return{success:!0,team:w,memberProgress:R}}}));{let h=this.memdir;ve({name:Vp,label:qp,description:Jp,parameters:Kp,execute:async(w,R)=>{let P=await Xp(R,{memdir:h,provider:this.qmemoryAdapter??void 0,userId:this.qmemoryUserId||this.currentSessionId||"default"});return{content:[{type:"text",text:P.message}],details:{type:"memory",action:P.action,ok:P.ok}}}})}bc(l,{getMemdir:()=>this.memdir,log:{debug:h=>c.debug(h),warn:h=>c.warn(h)}},this.memoryPrefetchState);{let h=e?.workdir??process.cwd(),w=Pp(h,this.currentSessionId||"default");ve(Ip(w))}let Re=e?.workdir??process.cwd(),Ye=em({projectRoot:Re,ruleEngine:S,hooks:l,log:h=>c.info(`[settings] ${h}`)});Lt(async()=>{Ye()}),this.currentSessionId&&l.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let fe=e?.workdir??process.cwd();return Qc({projectRoot:fe,sessionId:this.currentSessionId,hooks:l,log:h=>c.debug(h),onInstructionCacheReset:od}).then(h=>{this.fileWatcher=h,Lt(async()=>{this.fileWatcher?.stop()})}).catch(h=>{c.warn(`[file-watcher] init error: ${h instanceof Error?h.message:h}`)}),this.agent=new Gt({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:d,log:c,hooks:l,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=t,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=o,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}loadSettingsSync(){try{let e=ut();if(!M.existsSync(e))return;let t=M.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(),o={sessionId:t,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:Nl(t),agentHome:J(),settings:ut()},usage:n?{turnCount:n.turnCount,inputTokens:n.totalInputTokens,outputTokens:n.totalOutputTokens}:void 0};e.id!==void 0&&this.sendResponse(e.id,o)}async handleMemoryList(e){let t=[];this.memdir&&t.push({id:"memdir",type:"file",path:wa()}),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??"memdir",o=t?.target??"index";if(n==="memdir"||n==="local"){if(!this.memdir){e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:o,content:""});return}try{if(o==="index"){let s=this.memdir.getIndexRaw();e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:"index",content:s})}else{let s=await this.memdir.readFile(o);e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:o,content:s.content??""})}}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:o,content:""})}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:`Unknown memory source: ${n}`})}async handleMemoryWrite(e){let t=e.params,n=t?.target??"index",o=t?.content;if(o==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"content is required."});return}if(!this.memdir){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Memory system not initialized."});return}try{if(n==="index"){let s=await this.memdir.addToIndex(o);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,target:"index",message:s.message})}else{let s=await this.memdir.writeFile(n,o);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,target:n,message:s.message})}this.sendNotification("memory.updated",{target:n,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,o=rt(t?.includeDeferred??!1).map(s=>({name:s.function.name,description:s.function.description??"",parameters:s.function.parameters,source:"builtin"}));if(t?.category){let s=o.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:o,total:o.length})}handleMediaListModels(e){let n=e.params?.mediaType,s=this.mediaClient.listMediaModels(n).map(i=>({providerId:i.providerId,providerName:i.providerDef.name,modelId:i.modelInfo.id,modelName:i.modelInfo.name,mediaType:i.mediaType,capabilities:i.modelInfo.mediaCapabilities}));e.id!==void 0&&this.sendResponse(e.id,{models:s})}async handleMediaCancel(e){let t=e.params;if(!t?.taskId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"taskId is required."});return}let n=t.provider??"doubao",o=this.mediaClient.getTransport(n);if(!o){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No transport for provider: ${n}`});return}if(!si(o)){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Provider ${n} does not support task cancellation.`});return}try{let s=this.resolveMediaApiKey(n);if(!s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No API key for provider: ${n}`});return}await o.deleteVideoTask(t.taskId,s),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,message:"Task cancelled."})}catch(s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:s instanceof Error?s.message:String(s)})}}async handleMediaStatus(e){let t=e.params;if(!t?.taskId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"taskId is required."});return}let n=t.provider??"doubao",o=this.mediaClient.getTransport(n);if(!o){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No transport for provider: ${n}`});return}if(!si(o)){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Provider ${n} does not support task status queries.`});return}try{let s=this.resolveMediaApiKey(n);if(!s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No API key for provider: ${n}`});return}if(o.getTaskStatus){let{status:d,task:l}=await o.getTaskStatus(t.taskId,s);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,status:d,task:l});return}let i=await o.listVideoTasks(s,{limit:100}),c=(i.data??i.tasks??[]).find(d=>d.id===t.taskId||d.task_id===t.taskId);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,...c?{status:c.status,task:c}:{status:"unknown",message:"Task not found in recent list."}})}catch(s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:s instanceof Error?s.message:String(s)})}}resolveMediaApiKey(e){return this.currentMediaApiKeys?.[e]}handleProviderList(e){let t=this.registry.listProviders(),n=new Map;for(let s of t){let i=s.group??s.id;n.has(i)||n.set(i,[]);let a=!!this.registry.resolveApiKey(s.id);n.get(i).push({id:s.id,name:s.name,transport:s.transport,baseUrl:s.baseUrl,defaultModel:s.defaultModel,modelCount:s.models?.length??0,available:a})}let o=[...n.entries()].map(([s,i])=>({group:s,variants:i}));e.id!==void 0&&this.sendResponse(e.id,{providers:o})}handleConfigGet(e){try{let t=ut(),n={};if(M.existsSync(t)){let o=M.readFileSync(t,"utf-8");n=JSON.parse(o)}e.id!==void 0&&this.sendResponse(e.id,{config:n,paths:{userSettings:t,agentHome:J()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.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:_.INVALID_PARAMS,message:"updates (object) is required."});return}try{let n=ut(),o={};try{let s=await M.promises.readFile(n,"utf-8");o=JSON.parse(s)}catch{}Object.assign(o,t.updates),await M.promises.mkdir(F.dirname(n),{recursive:!0}),await M.promises.writeFile(n,JSON.stringify(o,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:_.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}handleConfigTunables(e){try{let t=bs(),n=ut(),o={};try{let s=M.readFileSync(n,"utf-8"),i=JSON.parse(s);i.tunables&&typeof i.tunables=="object"&&(o=i.tunables)}catch{}e.id!==void 0&&this.sendResponse(e.id,{defaults:t,overrides:o})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleConfigUpdateTunable(e){let t=e.params,n=t?.key,o=t?.value;if(!n||typeof n!="string"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: key (string)"});return}let s=bs();if(!(n in s)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:`Unknown tunable key: "${n}". Valid keys: ${Object.keys(s).join(", ")}`});return}let i=typeof s[n];if(o==null||typeof o!==i){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:`Invalid value for "${n}": expected ${i}, got ${typeof o}`});return}try{let a=ut(),c={};try{let d=await M.promises.readFile(a,"utf-8");c=JSON.parse(d)}catch{}(!c.tunables||typeof c.tunables!="object")&&(c.tunables={}),c.tunables[n]=o,await M.promises.mkdir(F.dirname(a),{recursive:!0}),await M.promises.writeFile(a,JSON.stringify(c,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,key:n,value:o})}catch(a){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:a instanceof Error?a.message:String(a)})}}async handleTodosList(e){let t=Me("task");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:Cr([])});return}try{let s=(await t.execute("rpc-todos-list",{action:"list"},void 0)).details?.taskList??[];e.id!==void 0&&this.sendResponse(e.id,{items:s,summary:Cr(s)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:Cr([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){if(this.memdir)try{let n=await this.memdir.searchLocal(t.query);e.id!==void 0&&this.sendResponse(e.id,{results:n.slice(0,t.limit??10).map((o,s)=>({id:`memdir-${s}`,text:o.snippet,score:o.score,source:"memdir",metadata:{file:o.file}}))})}catch{e.id!==void 0&&this.sendResponse(e.id,{results:[]})}else e.id!==void 0&&this.sendResponse(e.id,{results:[]});return}try{let n=t.userId??(this.qmemoryUserId||"default"),o=await this.qmemoryAdapter.search(t.query,n,{limit:t.limit??10});e.id!==void 0&&this.sendResponse(e.id,{results:o.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:_.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:_.INVALID_PARAMS,message:"match is required."});return}let n=t.source??"memdir";if(n==="memdir"||n==="local"){if(!this.memdir){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Memory system not initialized."});return}let o=t.target??"index";try{if(o==="index"){let s=await this.memdir.removeFromIndex(t.match);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,removedCount:s.ok?1:0,message:s.message}),s.ok&&this.sendNotification("memory.updated",{source:"memdir",target:"index"})}else{let s=await this.memdir.deleteFile(o);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,removedCount:s.ok?1:0,message:s.message}),s.ok&&this.sendNotification("memory.updated",{source:"memdir",target:o})}}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.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(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:n==="qmemory"?"QMemory not configured.":`Unknown source: ${n}`})}handleTasksList(e){let n=e.params?.lifecycle??"all",o=this.taskStore.getAllTasks(),s=n==="all"?o:o.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:_.INVALID_PARAMS,message:"taskId is required."});return}let o=this.taskStore.getAllTasks().find(s=>s.taskId===t.taskId);if(!o){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} not found.`});return}if(o.lifecycle!=="running"&&o.lifecycle!=="pending"){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} is already ${o.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.`})}static STATE_TO_STATUS={starting:"spawning",ready:"available",running:"running",completed:"available",failed:"failed",killed:"unavailable"};emitAgentStatus(e,t,n){let o=r.STATE_TO_STATUS[t]??"unavailable",s={agentId:e,status:o};(n?.missedBeats!==void 0||n?.lastActivityAt!==void 0)&&(s.health={missedBeats:n.missedBeats??0,lastActiveAt:n.lastActivityAt?new Date(n.lastActivityAt).toISOString():new Date().toISOString()}),n?.usage&&(s.usage=n.usage),this.sendNotification("agents.status",s)}async handleMcpToolCall(e,t,n){let o=Me(t);if(!o)return`Error: Unknown tool "${t}"`;let s=`mcp_${e}_${pe().slice(0,8)}`;try{return(await o.execute(s,n)).content.map(a=>a.text??"").join(`
496
- `)||"OK"}catch(i){return`Error: ${i instanceof Error?i.message:String(i)}`}}async ensureAgentConfigStore(){return this.agentConfigStore||(this.agentConfigStore=new kr(this.currentProjectRoot),await this.agentConfigStore.load(),this.acpDetector.setConfigStore(this.agentConfigStore.getData())),this.agentConfigStore}async handleAgentsScan(e){try{let t=e.params,n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let o=this.acpDetector.scan(t?.force);e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsList(e){try{let t=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(t.getData());let n=this.acpDetector.list();e.id!==void 0&&this.sendResponse(e.id,n)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsConfig(e){try{let t=e.params;if(!t?.action||!t?.agent){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"action and agent are required."});return}let n=await this.ensureAgentConfigStore();switch(t.action){case"register":n.registerCustomAgent(t.agent);break;case"unregister":n.unregisterCustomAgent(t.agent.id);break;case"update":n.registerCustomAgent(t.agent);break}this.acpDetector.setConfigStore(n.getData()),this.acpDetector.clearCache(),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsSetConfig(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore(),{agentId:o,...s}=t;await n.setAgentConfig(o,s),this.acpDetector.setConfigStore(n.getData()),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsGetConfig(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"agentId is required."});return}let o=(await this.ensureAgentConfigStore()).getAgentConfig(t.agentId);e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsRemoveConfig(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();await n.removeAgentConfig(t.agentId),this.acpDetector.setConfigStore(n.getData()),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsSetGateway(e){try{let t=e.params;if(!t?.url){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"url is required."});return}await(await this.ensureAgentConfigStore()).setGatewayUrl(t.url),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureSoloEvaluator(){if(!this.soloEvaluator){let e=new Jt({log:{info:n=>process.stderr.write(`[solo:pm] ${n}
490
+ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,n,o,s){if(t.filter(d=>d.role==="assistant").length<1)return;let c=[...t.slice(-6),{role:"user",content:r.SUGGESTION_PROMPT}];try{let d="";for await(let u of n.stream({model:s,messages:c,temperature:.3,maxTokens:200},o))u.type==="delta"&&(d+=u.text);let l=d.match(/\[[\s\S]*\]/);if(l){let u=JSON.parse(l[0]),p=Array.isArray(u)?u.filter(m=>typeof m.text=="string"&&m.text.length>0).slice(0,5):[];p.length>0&&this.sendNotification("turn.suggestions",{turnId:e,items:p})}}catch{}}async handleDream(e){let t=e.params??{},n=t.turnId??ge(),o=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",c=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n});let d=new AbortController;this.activeTurn=d,this.log(`dream ${n} starting (session: ${o}, sessions reviewing: ${c.length})`);let l={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,reasoning:s?.reasoning,promptCacheKey:s?.promptCacheKey,promptCacheRetention:s?.promptCacheRetention,serviceTier:s?.serviceTier,openaiBuiltinTools:s?.openaiBuiltinTools,maxToolCalls:s?.maxToolCalls,parallelToolCalls:s?.parallelToolCalls,textVerbosity:s?.textVerbosity};{let p=l.provider??"",m=l.model??"";p&&m&&this.registry.getModelInfo(p,m)?.streamRequired&&(l.streamRequired=!0)}if(!this.resolveAgent(l)){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 p={context:{memoryRoot:i,transcriptDir:a,currentSessionId:o,listSessionsSince:async()=>c},triggerConfig:{force:s?.force!==!1},transport:this.currentTransport,toolInvoker:{invoke:async(f,g,y,b)=>{if(g.startsWith("$"))return{result:y};let k=Oe(g);if(!k)return{result:"",error:`Unknown tool: ${g}`};let S=`tc_${ge().slice(0,8)}`;try{let R=JSON.parse(y),P=await k.execute(S,R,b);return{result:P.content.map(L=>L.text??"").join(`
491
+ `),error:P.details?.error}}catch(R){return{result:"",error:R instanceof Error?R.message:String(R)}}}},tools:ct(),apiKey:this.currentApiKey,model:l.model??this.currentModel,log:{info:f=>this.log(f),warn:f=>this.log(`[warn] ${f}`),error:f=>this.log(`[error] ${f}`),debug:f=>{this.verbose&&this.log(`[debug] ${f}`)}},hooks:this.currentHooks??void 0,parentSignal:d.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},m=await ql(p);if(m.ok){if(this.qmemoryAdapter&&this.qmemoryUserId)try{let f=await Jl({adapter:this.qmemoryAdapter,userId:this.qmemoryUserId,memoryRoot:i,log:{info:g=>this.log(g),debug:g=>{this.verbose&&this.log(g)}}});f.ran&&this.sendNotification("memory.decay.completed",{decayed:f.decayed,archived:f.archived,durationMs:f.durationMs})}catch(f){this.log(`[decay] post-dream decay error: ${f instanceof Error?f.message:String(f)}`)}this.sendNotification("turn.end",{turnId:n,content:`Dream consolidation completed. ${m.sessionsReviewed} sessions reviewed, ${m.filesTouched.length} files touched. Duration: ${m.durationMs}ms.`,usage:{inputTokens:0,outputTokens:0}})}else this.sendNotification("turn.error",{turnId:n,error:m.error??"Dream consolidation failed",code:"DREAM_FAILED"});this.log(`dream ${n} completed`)}catch(p){if(d.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Dream aborted",code:"ABORTED"});else{let m=p instanceof Error?p.message:String(p);this.sendNotification("turn.error",{turnId:n,error:m,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===d&&(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,o=e.model,s=e.apiKey,i=e.baseUrl;if(!n||!s){let h=this.loadSettingsSync();h&&(n=n??h.provider,s=s??h.apiKey,o=o??h.model,i=i??h.baseUrl,n&&s&&this.log(`loaded provider from settings.json: ${n}, model: ${o}`))}if(!n||!s)return null;o=o??this.registry.getProvider(n)?.defaultModel??"",e.model=o,e.provider=n,e.apiKey=s,i&&(e.baseUrl=i);let a=Fo({provider:n,model:o,apiKey:s,baseUrl:i},this.registry);ai()&&(a.transport=ci(a.transport,this.currentSessionId||"default"));let c={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}`)}},d={invoke:async(h,w,_,I)=>{if(w.startsWith("$"))return{result:_};let A=Oe(w);if(!A)return{result:"",error:`Unknown tool: ${w}`};let j=`tc_${ge().slice(0,8)}`;try{let W=JSON.parse(_),N=await A.execute(j,W,I),U=[],ue=N.content.map(se=>{if(se.type==="image"&&se.data){let dt=se.mimeType||"image/png";return U.push(`data:${dt};base64,${se.data}`),"[Image]"}return se.text??""}).join(`
492
+ `);U.length>0&&(N.imageUrls=[...U,...N.imageUrls??[]]);let J=N.details?.error,oe=N.details?.type,le=oe?.split("_")[0];if(oe==="three_d_generate"&&(le="3d"),le&&["image","tts","video","music","3d"].includes(le)){let se=N.details?.mediaUrls??[],dt=le;for(let Ke of se)this.sendNotification("turn.media_result",{turnId:h,mediaType:dt,url:Ke,model:N.details?.model,provider:N.details?.provider,...N.details?.durationMs?{durationSeconds:N.details.durationMs/1e3}:{},...N.details?.taskId?{taskId:N.details.taskId}:{}});if(se.length>0)try{let Ke=await this.mediaPersistence.downloadAll(se,{type:le,sessionId:this.currentSessionId||void 0},{warn:ve=>this.log(ve)});if(Ke.length>0){for(let ve of Ke)ue=ue.replaceAll(ve.remoteUrl,ve.localPath);this.sendNotification("turn.media_persisted",{turnId:h,files:Ke.map(ve=>({remoteUrl:ve.remoteUrl,localPath:ve.localPath,bytes:ve.bytes,mimeType:ve.mimeType}))})}}catch{}}if(oe==="task"&&!J&&N.details?.taskList)try{let se=N.details;se?.taskList&&this.sendNotification("turn.todos_updated",{turnId:h,items:se.taskList,summary:{total:se.total??se.taskList.length,completed:se.completed??0,inProgress:se.inProgress??0,notStarted:se.notStarted??0}})}catch{}let we=Array.isArray(N.details?.matches)?N.details.matches:void 0,to=N.imageUrls;return{result:ue,error:J,toolReferences:we,imageUrls:to}}catch(W){return{result:"",error:W instanceof Error?W.message:String(W)}}}},l=di(c);this.currentHooks=l,this.taskStore.setHooks(l,this.currentSessionId??""),fp({onTaskCreated:h=>{l.invoke("task.created",{sessionId:this.currentSessionId??"",taskId:String(h.id),taskType:"planning",label:h.title}).catch(()=>{})},onTaskCompleted:h=>{l.invoke("task.completed",{sessionId:this.currentSessionId??"",taskId:String(h.id),taskType:"planning",label:h.title}).catch(()=>{})}});let u=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(u){let h=Cl({baseUrl:u,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=h,this.qmemoryUserId=this.currentSessionId??"default",Rl(l,{memoryProvider:h,userId:this.currentSessionId??"default",log:{debug:w=>c.debug(w),warn:w=>c.warn(w)}},this.memoryPrefetchState)}xl(l,{currentCwd:this.currentProjectRoot??void 0,log:{debug:h=>c.debug(h),warn:h=>c.warn(h)}}),Ec(l,c,{transport:a.transport,apiKey:a.apiKey});let p=e?.mcpServers,m=pa(p??{}),f=Yc();try{if(M.existsSync(f)){let h=JSON.parse(M.readFileSync(f,"utf8")),w=pa(h),_=new Set(m.map(I=>I.name));m=[...m,...w.filter(I=>!_.has(I.name))]}}catch{}if(m.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new fr({servers:m,log:c}),jt(async()=>{await this.mcpManager?.disconnectAll()});let h=()=>this.mcpManager;Re(wp(h)),Re(vp(h)),Re(zp({listServers:async()=>{let w=this.mcpManager;return w?w.getConnectedServers().map(I=>({name:I,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async w=>{if(!this.mcpManager)return[];let I=`mcp__${w.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return mt().filter(A=>A.startsWith(I)).map(A=>({name:A.slice(I.length),prefixedName:A}))},callTool:async(w,_,I,A)=>{let W=`mcp__${w.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+_,N=Oe(W);if(!N)return{success:!1,error:`Tool not found: ${W}`};try{return{success:!0,content:(await N.execute(`mcp_${Date.now()}`,I??{},A)).content.map(J=>J.text??"").join(`
493
+ `)}}catch(U){return{success:!1,error:U.message}}},listResources:async w=>{let _=this.mcpManager;return _?(await _.listResources(w)).map(A=>({uri:A.uri,name:A.name,mimeType:A.mimeType,description:A.description,server:A.server})):[]},readResource:async(w,_)=>{let I=this.mcpManager;if(!I)throw new Error("MCP not initialized");return(await I.readResource(w,_)).map(j=>({uri:j.uri,mimeType:j.mimeType,text:j.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpReady=this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),c.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(w=>{c.warn(`[mcp] connection error: ${w instanceof Error?w.message:w}`)})}let g=[],y=zc();M.existsSync(y)&&g.push(y);let b=e?.pluginPaths;if(Array.isArray(b))for(let h of b)typeof h=="string"&&M.existsSync(h)&&g.push(h);xp(g,c).then(h=>{if(h.length===0)return;this.pluginLoader=new hr({pluginDirs:h,hookRegistry:l,log:c}),this.pluginLoader.loadAll().then(_=>{c.info(`[plugins] ${_.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(_=>{c.warn(`[plugins] load error: ${_ instanceof Error?_.message:_}`)});let w=this.pluginLoader;l.register({point:"turn.submitted",handler:async()=>(await w.discoverNew(),await w.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(h=>{c.warn(`[plugins] marketplace resolve error: ${h instanceof Error?h.message:h}`)});let k=e?.permissions,S=ga(k),R=new yr(S);if(Dt()?.type==="group"){let h=Xu();for(let w of h)R.addRule(w);la(!0),c.info(`[permissions] group security mode active: ${h.length} rules injected`)}else la(!1);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new kr({ruleEngine:R,hookRegistry:l,onRequestApproval:async h=>{if(this.acpServer&&this.acpServer.sessionId)try{let w=await this.acpServer.requestPermission({sessionId:this.acpServer.sessionId,permissionId:h.approvalId,toolCall:{callId:h.callId,toolName:h.toolName,arguments:h.arguments?JSON.stringify(h.arguments):""},message:h.message,options:[{id:"allow",label:"Allow"},{id:"deny",label:"Deny"},{id:"allowAlways",label:"Always allow",persistent:!0}]});return{approvalId:h.approvalId,decision:w.optionId==="allow"||w.optionId==="allowAlways"?"approved":"denied"}}catch{return{approvalId:h.approvalId,decision:"denied"}}return this.sendNotification("tool.approval.request",{approvalId:h.approvalId,callId:h.callId,toolName:h.toolName,arguments:h.arguments?JSON.stringify(h.arguments):"",message:h.message,suggestions:h.suggestions?.map(w=>`${w.pattern}:${w.behavior}`)}),new Promise(()=>{})},onPermissionUpdate:h=>{c.info(`[permissions] rule saved: ${h.pattern} \u2192 ${h.behavior}`),this.sendNotification("permission.rule_updated",{pattern:h.pattern,behavior:h.behavior})},onDenied:(h,w)=>{c.warn(`[permissions] blocked "${h}": ${w}`)}});let O=ct();this.permissionChecker.setToolMeta(O),this.permissionUnregister=this.permissionChecker.register();let L=this.currentProjectRoot?rt(this.currentProjectRoot):void 0,B=[...L?[L]:[],ot(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];Re(Up({listSkills:()=>{let h=[];this.pluginLoader&&h.push(...this.pluginLoader.getPluginSkills());let w=e?.skillPaths;if(Array.isArray(w)){for(let _ of w)if(typeof _=="string"){let I=F.basename(_);h.some(A=>A.name===I)||h.push({name:I,source:"gateway",filePath:F.join(_,"SKILL.md"),baseDir:_})}}return h},listSkillsFull:async h=>{let w=[],_=new Set,I=ot();for(let A of B)try{let j=await M.promises.readdir(A,{withFileTypes:!0});for(let W of j){if(!W.isDirectory())continue;let N=F.join(A,W.name,"SKILL.md");try{let U=await M.promises.readFile(N,"utf8"),ue=F.basename(A);if(h&&ue!==h)continue;_.add(ue);let J=A===I?"global":A===L?"project":"config",le=U.match(/^---\n[\s\S]*?^version:\s*(\S+)/m)?.[1],we=U.startsWith(`---
494
+ `)?U.indexOf("---",4):-1,dt=(we>=0?U.slice(we+3).trimStart():U).split(`
495
+ `).find(Ke=>Ke.trim()&&!Ke.startsWith("#"))?.trim()??`Skill from ${ue}`;w.push({name:W.name,description:dt,category:ue,scope:J,version:le})}catch{}}}catch{}if(this.pluginLoader)for(let A of this.pluginLoader.getPluginSkills())h&&A.source!==h||(_.add(A.source??"plugin"),w.push({name:A.name,description:`Plugin skill (${A.source})`,category:A.source,scope:"plugin"}));return{skills:w,categories:[..._]}},readSkillContent:async h=>{for(let w of B){let _=F.join(w,h,"SKILL.md");try{return await M.promises.readFile(_,"utf8")}catch{}}return null},viewSkill:async(h,w)=>{for(let _ of B){let I=w?F.join(_,h,w):F.join(_,h,"SKILL.md");try{let A=await M.promises.readFile(I,"utf8");return{name:h,content:A}}catch{}}return null},executeSkillSubturn:async(h,w,_,I)=>{let A=`skill_${h}_${ge().slice(0,8)}`,j=this.agent;if(!j)return"[skill] Cannot execute: no LLM provider configured";let W=X(),N=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:N,turnId:A,subagentId:A,agentType:`skill:${h}`}).catch(()=>{});let U=ct(),ue=_??`Execute skill "${h}" instructions.`,J=[],oe;for await(let le of j.run({turnId:A,sessionId:N,messages:[{role:"user",content:ue}],tools:U,systemPrompt:w,config:{parentDepth:1}},I)){if(le.type==="end"&&le.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:N,turnId:A,subagentId:A,agentType:`skill:${h}`,reason:"normal"}).catch(()=>{}),Or(W,h,!0),le.content;if(le.type==="delta"&&le.text&&J.push(le.text),le.type==="error"){oe=le.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:N,turnId:A,subagentId:A,agentType:`skill:${h}`,reason:oe?"error":"normal",error:oe}).catch(()=>{}),oe?(Or(W,h,!1),`[skill "${h}"] error: ${oe}`):(Or(W,h,!0),J.join("")||`[skill "${h}"] completed (no output)`)},manageSkill:async h=>{let w=this.currentProjectRoot,_=w?rt(w):B[0]??ot(),I=F.join(_,h.name),A=F.join(I,"SKILL.md");switch(h.action){case"create":{if(await M.promises.mkdir(I,{recursive:!0}),await M.promises.writeFile(A,h.content??"","utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",content:h.content??"",scope:"project"}}),It(),this.qmemoryAdapter&&this.qmemoryUserId){let W=(h.content??"").split(`
496
+ `).slice(0,3).join(" ").slice(0,200),N=w?F.basename(w):"unknown";this.qmemoryAdapter.ingestExtracted([{text:`Learned skill "${h.name}" in project "${N}": ${W}`,category:"skill-learning"}],this.qmemoryUserId).catch(()=>{})}let j=w?` (project-scoped). To make it available across all projects, use: skill promote name:"${h.name}"`:"";return{success:!0,message:`Skill "${h.name}" created${j}`,path:I}}case"edit":return await M.promises.writeFile(A,h.content??"","utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",content:h.content??"",scope:"project"}}),{success:!0,message:`Skill "${h.name}" updated`,path:A};case"patch":{let j=await M.promises.readFile(A,"utf8");if(!h.oldString||!j.includes(h.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let W=j.replace(h.oldString,h.newString??"");return await M.promises.writeFile(A,W,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",content:W,scope:"project"}}),{success:!0,message:`Skill "${h.name}" patched`,path:A}}case"delete":return await M.promises.rm(I,{recursive:!0,force:!0}),this.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:h.name,category:h.category??"learned",action:"delete",scope:"project"}}),It(),{success:!0,message:`Skill "${h.name}" deleted`};default:return{success:!1,message:`Unknown action: ${h.action}`}}},promoteSkill:async h=>{let w=rt(this.currentProjectRoot??void 0),_=F.join(w,h,"SKILL.md");try{await M.promises.access(_)}catch{return{success:!1,message:`Skill "${h}" not found in project skills. Cannot promote.`}}let I=ot(),A=F.join(I,h);await M.promises.mkdir(A,{recursive:!0});let j=F.join(w,h),W=await M.promises.readdir(j);for(let N of W){let U=await M.promises.readFile(F.join(j,N));await M.promises.writeFile(F.join(A,N),U)}return this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:h,category:"promoted",content:await M.promises.readFile(_,"utf8"),scope:"global"}}),await M.promises.rm(j,{recursive:!0,force:!0}),this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-cleanup-${Date.now()}`,instruction:{name:h,category:"learned",action:"delete",scope:"project"}}),It(),{success:!0,message:`Skill "${h}" promoted to global (user-level) and removed from project scope. It will now be available across all projects.`,path:A}},installSkill:async(h,w)=>{let _;try{if(_=new URL(h),!["http:","https:"].includes(_.protocol))return{success:!1,message:`Invalid URL scheme: ${_.protocol}. Only http/https allowed.`}}catch{return{success:!1,message:`Invalid URL: ${h}`}}let I=w??DR(_);if(!I)return{success:!1,message:"Cannot derive skill name from URL. Please provide 'name' parameter."};try{let A=await fetch(h,{signal:AbortSignal.timeout(3e4)});if(!A.ok)return{success:!1,message:`Download failed: HTTP ${A.status} ${A.statusText}`};let j=A.headers.get("content-length");if(j&&parseInt(j,10)>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};let W=await A.text();if(!W.trim())return{success:!1,message:"Downloaded content is empty."};if(W.length>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};if(W.trimStart().startsWith("<!DOCTYPE")||W.trimStart().startsWith("<html"))return{success:!1,message:"URL returned an HTML page, not a raw markdown file. Use a raw/direct download link."};let N=ot(),U=F.join(N,I);return await M.promises.mkdir(U,{recursive:!0}),await M.promises.writeFile(F.join(U,"SKILL.md"),W,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-install-${Date.now()}`,instruction:{name:I,category:"installed",content:W,scope:"global"}}),It(),{success:!0,message:`Skill "${I}" installed from ${_.host}. Available globally across all projects.`,path:U}}catch(A){return{success:!1,message:`Install failed: ${A instanceof Error?A.message:String(A)}`}}}})),Re(Fp({abortSignal:void 0,currentForkDepth:0,forkAgent:async h=>{let w=vo(h.agent);if(!w)return{agentId:"",status:"failed",error:`Unknown agent type: ${h.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let _=mt(),I=Os(_,w),j=ct().filter(J=>I.includes(J.function.name)),W=Ri(j,!0),N=h.maxTurns??w.maxTurns??200,U=await An({promptMessages:[{role:"user",content:h.prompt}],tools:W,transport:this.currentTransport,toolInvoker:d,apiKey:this.currentApiKey,model:this.currentModel,log:c,hooks:l,forkLabel:`agent-${h.agent}`,maxTurns:N,parentSignal:h.abortSignal,parentDepth:0,onEvent:J=>{J.type==="delta"&&J.text&&this.sendNotification("turn.subagent_delta",{agentType:h.agent,text:J.text})}}),ue=U.events.filter(J=>J.type==="end"&&"content"in J).map(J=>J.content??"").join("")||U.events.filter(J=>J.type==="delta"&&"text"in J).map(J=>J.text).join("");return{agentId:`fork-${h.agent}-${ge().slice(0,8)}`,status:U.ok?"completed":"failed",output:ue||void 0,error:U.error,tokensUsed:U.totalUsage.inputTokens+U.totalUsage.outputTokens}}}));let v=pt(),ee=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"]}]]),T=async()=>{try{return JSON.parse(await M.promises.readFile(v,"utf8"))}catch{return{}}},E=async h=>{await M.promises.mkdir(F.dirname(v),{recursive:!0}),await M.promises.writeFile(v,JSON.stringify(h,null,2),"utf8")};Re(Bp({getConfig:async h=>{let w=ee.get(h);if(!w)return{success:!1,error:`Unknown key: ${h}`};let _=await T(),I=h in _?_[h]:w.value;return{success:!0,setting:{...w,value:I,readOnly:jn.includes(h)}}},setConfig:async(h,w)=>{let _=ee.get(h);if(!_)return{success:!1,error:`Unknown key: ${h}`};let I=await T(),A=h in I?I[h]:_.value;return I[h]=w,await E(I),{success:!0,previousValue:A,setting:{..._,value:w}}},listConfig:async()=>{let h=await T();return{success:!0,settings:[...ee.values()].map(_=>({..._,value:_.key in h?h[_.key]:_.value,readOnly:jn.includes(_.key)}))}},resetConfig:async h=>{let w=ee.get(h);if(!w)return{success:!1,error:`Unknown key: ${h}`};let _=await T();return delete _[h],await E(_),{success:!0,setting:w}},isValidKey:h=>ee.has(h)}));let V=new Map,re=h=>{let w=/^(\d+)([smhd])$/.exec(h.trim());if(!w)return null;let _=parseInt(w[1],10),I=w[2];return _*({s:1e3,m:6e4,h:36e5,d:864e5}[I]??6e4)},Me=h=>{h.timerId&&clearTimeout(h.timerId);let w=re(h.schedule);if(!w)return;let _=Date.now(),I=w-_%w||w;h.timerId=setTimeout(()=>{h.lastRunAt=new Date().toISOString(),h.repeat.completed++,h.lastStatus="success",c.info(`[cron] triggered job ${h.id} (${h.name})`),h.repeat.times===null||h.repeat.completed<h.repeat.times?Me(h):(h.state="paused",h.enabled=!1)},I),h.nextRunAt=new Date(_+I).toISOString()};jt(async()=>{for(let h of V.values())h.timerId&&clearTimeout(h.timerId)}),Re(Gp({createJob:async h=>{let w=`cron_${ge().slice(0,8)}`,_={id:w,name:h.name??`Job ${w}`,prompt:h.prompt,schedule:h.schedule,scheduleDisplay:h.schedule,state:"scheduled",enabled:!0,repeat:{times:h.repeat??null,completed:0},allowedTools:h.allowedTools};return V.set(w,_),Me(_),{success:!0,job:{..._,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...V.values()].map(w=>({...w,timerId:void 0}))}),getJob:async h=>{let w=V.get(h);return w?{success:!0,job:{...w,timerId:void 0}}:{success:!1,error:`Job not found: ${h}`}},updateJob:async(h,w)=>{let _=V.get(h);return _?(w.prompt!==void 0&&(_.prompt=w.prompt),w.schedule!==void 0&&(_.schedule=w.schedule,_.scheduleDisplay=w.schedule),w.name!==void 0&&(_.name=w.name),w.enabled!==void 0&&(_.enabled=w.enabled,_.state=w.enabled?"scheduled":"paused"),w.repeat!==void 0&&(_.repeat.times=w.repeat),w.allowedTools!==void 0&&(_.allowedTools=w.allowedTools),_.enabled?Me(_):_.timerId&&(clearTimeout(_.timerId),_.timerId=void 0),{success:!0,job:{..._,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},deleteJob:async h=>{let w=V.get(h);return w?(w.timerId&&clearTimeout(w.timerId),V.delete(h),{success:!0}):{success:!1,error:`Job not found: ${h}`}},pauseJob:async h=>{let w=V.get(h);return w?(w.state="paused",w.enabled=!1,w.timerId&&(clearTimeout(w.timerId),w.timerId=void 0),{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},resumeJob:async h=>{let w=V.get(h);return w?(w.state="scheduled",w.enabled=!0,Me(w),{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},triggerJob:async h=>{let w=V.get(h);return w?(w.lastRunAt=new Date().toISOString(),w.repeat.completed++,w.lastStatus="success",{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},validateSchedule:h=>re(h)!==null||/^\d{1,2}\s/.test(h)?null:`Invalid schedule: ${h}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let K=new Map;jt(async()=>{for(let h of K.values())h.cleanup();K.clear()}),Re(Hp({startMonitor:async h=>{if(K.has(h.monitorId))return{action:"start",success:!1,error:`Monitor "${h.monitorId}" already exists.`};let w={monitorId:h.monitorId,source:h.source,target:h.target,conditions:h.conditions,startedAt:Date.now(),timeoutSeconds:h.timeoutSeconds,eventCount:0},_=()=>{};if(h.source==="file")try{let I=M.watch(h.target,{persistent:!1},()=>{w.eventCount++,c.info(`[monitor] file change detected: ${h.target}`)});_=()=>I.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${h.target}`}}if(h.timeoutSeconds>0){let I=setTimeout(()=>{let j=K.get(h.monitorId);j&&(j.cleanup(),K.delete(h.monitorId))},h.timeoutSeconds*1e3),A=_;_=()=>{clearTimeout(I),A()}}return K.set(h.monitorId,{info:w,cleanup:_}),{action:"start",success:!0,monitorId:h.monitorId}},stopMonitor:async h=>{let w=K.get(h);return w?(w.cleanup(),K.delete(h),{action:"stop",success:!0,monitorId:h}):{action:"stop",success:!1,error:`Monitor "${h}" not found.`}},listMonitors:async()=>[...K.values()].map(h=>h.info)}));let Y=new Map,Te={info:h=>c.info(h),warn:h=>c.warn(h)},fe=new Zt({onNotification:(h,w,_)=>{this.sendNotification("team.member.notification",{memberId:h,method:w,params:_})},onStateChange:(h,w)=>{this.sendNotification("team.member.state",{memberId:h,state:w});let _=fe.getHandle(h),A=fe.getUsageTracker(h)?.getUsage();this.emitAgentStatus(h,w,{missedBeats:fe.getMissedBeats(h),lastActivityAt:_?.lastActivityAt,usage:A&&A.totalTokens>0?{inputTokens:A.inputTokens,outputTokens:A.outputTokens,totalTokens:A.totalTokens}:void 0})},onExit:(h,w,_)=>{for(let I of Y.values()){let A=I.members.find(j=>j.cwd&&`team-${I.name}-${j.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()===h.replace(/^team-/,""));A&&(A.isActive=!1)}c.info(`[team] member ${h} exited (code=${w}, signal=${_})`)},onMcpToolCall:(h,w,_)=>this.handleMcpToolCall(h,w,_),log:{info:h=>c.info(h),warn:h=>c.warn(h),debug:h=>c.debug(h)},sessionDir:F.join(X(),"agent-logs")});jt(async()=>{fe.dispose()}),Re(Vp({createTeam:async h=>{if(Y.has(h.teamName))return{success:!1,error:`Team "${h.teamName}" already exists.`};let w=await Dn(),_=[];for(let A of h.members??[]){let j={...A,isActive:!0};if(w){let W=`team-${h.teamName}-${A.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),N=await ku(w,W,Te);N?(j.worktreePath=N.worktreePath,j.worktreeBranch=N.branch,j.cwd=N.worktreePath,c.info(`[team] provisioned worktree for ${A.name}: ${N.worktreePath}`)):(j.cwd=process.cwd(),c.warn(`[team] worktree provision failed for ${A.name}, using shared cwd`))}else j.cwd=process.cwd();_.push(j)}let I={name:h.teamName,description:h.description,leadId:this.currentSessionId??"default",members:_,createdAt:new Date().toISOString()};Y.set(h.teamName,I);for(let A of _){if(!A.cwd)continue;let j=`team-${h.teamName}-${A.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();try{await fe.spawn({memberId:j,name:A.name,cwd:A.cwd,prompt:`You are the "${A.name}" team member. Role: ${A.role}.`,agentType:A.role,verbose:this.verbose}),c.info(`[team] spawned child process for ${A.name} in ${A.cwd}`)}catch(W){c.warn(`[team] failed to spawn child process for ${A.name}: ${W instanceof Error?W.message:String(W)}`),A.isActive=!1}}return this.sendNotification("team.updated",{teamName:h.teamName,action:"created",members:I.members.map(A=>({agentName:A.name,role:A.role,worktreePath:A.worktreePath,pid:fe.getHandle(`team-${h.teamName}-${A.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase())?.pid}))}),{success:!0,team:I}},deleteTeam:async h=>{let w=Y.get(h);if(!w)return{success:!1,error:`Team "${h}" not found.`};for(let I of w.members){let A=`team-${h}-${I.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();fe.kill(A),fe.remove(A)}let _=await Dn();if(_)for(let I of w.members)I.worktreePath&&I.worktreeBranch&&(await Tu(_,I.worktreePath,I.worktreeBranch,Te),c.info(`[team] cleaned up worktree for ${I.name}: ${I.worktreePath}`));return Y.delete(h),this.sendNotification("team.updated",{teamName:h,action:"destroyed",members:[]}),{success:!0}},listTeams:async()=>({success:!0,teams:[...Y.values()]}),getTeamStatus:async h=>{let w=Y.get(h);if(!w)return{success:!1,error:`Team "${h}" not found.`};let _={};for(let I of w.members){let A=`team-${h}-${I.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),j=fe.getStatus(A);j&&(I.isActive=j.alive,_[I.name]={mediaProgress:j.mediaProgress,lastToolCall:j.lastToolCall,idleFor:j.idleFor,runningFor:j.runningFor})}return{success:!0,team:w,memberProgress:_}}}));{let h=this.memdir;Re({name:um,label:pm,description:gm,parameters:mm,execute:async(w,_)=>{let I=await fm(_,{memdir:h,provider:this.qmemoryAdapter??void 0,userId:this.qmemoryUserId||this.currentSessionId||"default"});return{content:[{type:"text",text:I.message}],details:{type:"memory",action:I.action,ok:I.ok}}}})}_l(l,{getMemdir:()=>this.memdir,log:{debug:h=>c.debug(h),warn:h=>c.warn(h)}},this.memoryPrefetchState);{let h=e?.workdir??process.cwd(),w=Xp(h,this.currentSessionId||"default");Re(qp(w))}let Ae=e?.workdir??process.cwd(),nt=km({projectRoot:Ae,ruleEngine:R,hooks:l,log:h=>c.info(`[settings] ${h}`)});jt(async()=>{nt()}),this.currentSessionId&&l.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let he=e?.workdir??process.cwd();return sd({projectRoot:he,sessionId:this.currentSessionId,hooks:l,log:h=>c.debug(h),onInstructionCacheReset:dd}).then(h=>{this.fileWatcher=h,jt(async()=>{this.fileWatcher?.stop()})}).catch(h=>{c.warn(`[file-watcher] init error: ${h instanceof Error?h.message:h}`)}),this.agent=new Vt({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:d,log:c,hooks:l,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=t,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=o,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}loadSettingsSync(){try{let e=pt();if(!M.existsSync(e))return;let t=M.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(),o={sessionId:t,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:Vc(t),agentHome:X(),settings:pt()},usage:n?{turnCount:n.turnCount,inputTokens:n.totalInputTokens,outputTokens:n.totalOutputTokens}:void 0};e.id!==void 0&&this.sendResponse(e.id,o)}async handleMemoryList(e){let t=[];this.memdir&&t.push({id:"memdir",type:"file",path:Aa()}),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??"memdir",o=t?.target??"index";if(n==="memdir"||n==="local"){if(!this.memdir){e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:o,content:""});return}try{if(o==="index"){let s=this.memdir.getIndexRaw();e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:"index",content:s})}else{let s=await this.memdir.readFile(o);e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:o,content:s.content??""})}}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"memdir",target:o,content:""})}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:`Unknown memory source: ${n}`})}async handleMemoryWrite(e){let t=e.params,n=t?.target??"index",o=t?.content;if(o==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"content is required."});return}if(!this.memdir){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Memory system not initialized."});return}try{if(n==="index"){let s=await this.memdir.addToIndex(o);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,target:"index",message:s.message})}else{let s=await this.memdir.writeFile(n,o);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,target:n,message:s.message})}this.sendNotification("memory.updated",{target:n,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,o=ct(t?.includeDeferred??!1).map(s=>({name:s.function.name,description:s.function.description??"",parameters:s.function.parameters,source:"builtin"}));if(t?.category){let s=o.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:o,total:o.length})}handleMediaListModels(e){let n=e.params?.mediaType,s=this.mediaClient.listMediaModels(n).map(i=>({providerId:i.providerId,providerName:i.providerDef.name,modelId:i.modelInfo.id,modelName:i.modelInfo.name,mediaType:i.mediaType,capabilities:i.modelInfo.mediaCapabilities}));e.id!==void 0&&this.sendResponse(e.id,{models:s})}async handleMediaCancel(e){let t=e.params;if(!t?.taskId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"taskId is required."});return}let n=t.provider??"doubao",o=this.mediaClient.getTransport(n);if(!o){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No transport for provider: ${n}`});return}if(!li(o)){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Provider ${n} does not support task cancellation.`});return}try{let s=this.resolveMediaApiKey(n);if(!s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No API key for provider: ${n}`});return}await o.deleteVideoTask(t.taskId,s),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,message:"Task cancelled."})}catch(s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:s instanceof Error?s.message:String(s)})}}async handleMediaStatus(e){let t=e.params;if(!t?.taskId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"taskId is required."});return}let n=t.provider??"doubao",o=this.mediaClient.getTransport(n);if(!o){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No transport for provider: ${n}`});return}if(!li(o)){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Provider ${n} does not support task status queries.`});return}try{let s=this.resolveMediaApiKey(n);if(!s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`No API key for provider: ${n}`});return}if(o.getTaskStatus){let{status:d,task:l}=await o.getTaskStatus(t.taskId,s);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,status:d,task:l});return}let i=await o.listVideoTasks(s,{limit:100}),c=(i.data??i.tasks??[]).find(d=>d.id===t.taskId||d.task_id===t.taskId);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,...c?{status:c.status,task:c}:{status:"unknown",message:"Task not found in recent list."}})}catch(s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:s instanceof Error?s.message:String(s)})}}resolveMediaApiKey(e){return this.currentMediaApiKeys?.[e]}handleProviderList(e){let t=this.registry.listProviders(),n=new Map;for(let s of t){let i=s.group??s.id;n.has(i)||n.set(i,[]);let a=!!this.registry.resolveApiKey(s.id);n.get(i).push({id:s.id,name:s.name,transport:s.transport,baseUrl:s.baseUrl,defaultModel:s.defaultModel,modelCount:s.models?.length??0,available:a})}let o=[...n.entries()].map(([s,i])=>({group:s,variants:i}));e.id!==void 0&&this.sendResponse(e.id,{providers:o})}handleConfigGet(e){try{let t=pt(),n={};if(M.existsSync(t)){let o=M.readFileSync(t,"utf-8");n=JSON.parse(o)}e.id!==void 0&&this.sendResponse(e.id,{config:n,paths:{userSettings:t,agentHome:X()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.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:x.INVALID_PARAMS,message:"updates (object) is required."});return}try{let n=pt(),o={};try{let s=await M.promises.readFile(n,"utf-8");o=JSON.parse(s)}catch{}Object.assign(o,t.updates),await M.promises.mkdir(F.dirname(n),{recursive:!0}),await M.promises.writeFile(n,JSON.stringify(o,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:x.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}handleConfigTunables(e){try{let t=ws(),n=pt(),o={};try{let s=M.readFileSync(n,"utf-8"),i=JSON.parse(s);i.tunables&&typeof i.tunables=="object"&&(o=i.tunables)}catch{}e.id!==void 0&&this.sendResponse(e.id,{defaults:t,overrides:o})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleConfigUpdateTunable(e){let t=e.params,n=t?.key,o=t?.value;if(!n||typeof n!="string"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: key (string)"});return}let s=ws();if(!(n in s)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:`Unknown tunable key: "${n}". Valid keys: ${Object.keys(s).join(", ")}`});return}let i=typeof s[n];if(o==null||typeof o!==i){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:`Invalid value for "${n}": expected ${i}, got ${typeof o}`});return}try{let a=pt(),c={};try{let d=await M.promises.readFile(a,"utf-8");c=JSON.parse(d)}catch{}(!c.tunables||typeof c.tunables!="object")&&(c.tunables={}),c.tunables[n]=o,await M.promises.mkdir(F.dirname(a),{recursive:!0}),await M.promises.writeFile(a,JSON.stringify(c,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,key:n,value:o})}catch(a){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:a instanceof Error?a.message:String(a)})}}async handleTodosList(e){let t=Oe("task");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:Mr([])});return}try{let s=(await t.execute("rpc-todos-list",{action:"list"},void 0)).details?.taskList??[];e.id!==void 0&&this.sendResponse(e.id,{items:s,summary:Mr(s)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:Mr([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){if(this.memdir)try{let n=await this.memdir.searchLocal(t.query);e.id!==void 0&&this.sendResponse(e.id,{results:n.slice(0,t.limit??10).map((o,s)=>({id:`memdir-${s}`,text:o.snippet,score:o.score,source:"memdir",metadata:{file:o.file}}))})}catch{e.id!==void 0&&this.sendResponse(e.id,{results:[]})}else e.id!==void 0&&this.sendResponse(e.id,{results:[]});return}try{let n=t.userId??(this.qmemoryUserId||"default"),o=await this.qmemoryAdapter.search(t.query,n,{limit:t.limit??10});e.id!==void 0&&this.sendResponse(e.id,{results:o.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:x.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:x.INVALID_PARAMS,message:"match is required."});return}let n=t.source??"memdir";if(n==="memdir"||n==="local"){if(!this.memdir){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Memory system not initialized."});return}let o=t.target??"index";try{if(o==="index"){let s=await this.memdir.removeFromIndex(t.match);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,removedCount:s.ok?1:0,message:s.message}),s.ok&&this.sendNotification("memory.updated",{source:"memdir",target:"index"})}else{let s=await this.memdir.deleteFile(o);e.id!==void 0&&this.sendResponse(e.id,{ok:s.ok,removedCount:s.ok?1:0,message:s.message}),s.ok&&this.sendNotification("memory.updated",{source:"memdir",target:o})}}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.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(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:n==="qmemory"?"QMemory not configured.":`Unknown source: ${n}`})}handleTasksList(e){let n=e.params?.lifecycle??"all",o=this.taskStore.getAllTasks(),s=n==="all"?o:o.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:x.INVALID_PARAMS,message:"taskId is required."});return}let o=this.taskStore.getAllTasks().find(s=>s.taskId===t.taskId);if(!o){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} not found.`});return}if(o.lifecycle!=="running"&&o.lifecycle!=="pending"){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} is already ${o.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.`})}static STATE_TO_STATUS={starting:"spawning",ready:"available",running:"running",completed:"available",failed:"failed",killed:"unavailable"};emitAgentStatus(e,t,n){let o=r.STATE_TO_STATUS[t]??"unavailable",s={agentId:e,status:o};(n?.missedBeats!==void 0||n?.lastActivityAt!==void 0)&&(s.health={missedBeats:n.missedBeats??0,lastActiveAt:n.lastActivityAt?new Date(n.lastActivityAt).toISOString():new Date().toISOString()}),n?.usage&&(s.usage=n.usage),this.sendNotification("agents.status",s)}async handleMcpToolCall(e,t,n){let o=Oe(t);if(!o)return`Error: Unknown tool "${t}"`;let s=`mcp_${e}_${ge().slice(0,8)}`;try{return(await o.execute(s,n)).content.map(a=>a.text??"").join(`
497
+ `)||"OK"}catch(i){return`Error: ${i instanceof Error?i.message:String(i)}`}}async ensureAgentConfigStore(){return this.agentConfigStore||(this.agentConfigStore=new Sr(this.currentProjectRoot),await this.agentConfigStore.load(),this.acpDetector.setConfigStore(this.agentConfigStore.getData())),this.agentConfigStore}async handleAgentsScan(e){try{let t=e.params,n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let o=this.acpDetector.scan(t?.force);e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsList(e){try{let t=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(t.getData());let n=this.acpDetector.list();e.id!==void 0&&this.sendResponse(e.id,n)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsConfig(e){try{let t=e.params;if(!t?.action||!t?.agent){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"action and agent are required."});return}let n=await this.ensureAgentConfigStore();switch(t.action){case"register":n.registerCustomAgent(t.agent);break;case"unregister":n.unregisterCustomAgent(t.agent.id);break;case"update":n.registerCustomAgent(t.agent);break}this.acpDetector.setConfigStore(n.getData()),this.acpDetector.clearCache(),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsSetConfig(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore(),{agentId:o,...s}=t;await n.setAgentConfig(o,s),this.acpDetector.setConfigStore(n.getData()),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsGetConfig(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"agentId is required."});return}let o=(await this.ensureAgentConfigStore()).getAgentConfig(t.agentId);e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsRemoveConfig(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();await n.removeAgentConfig(t.agentId),this.acpDetector.setConfigStore(n.getData()),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsSetGateway(e){try{let t=e.params;if(!t?.url){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"url is required."});return}await(await this.ensureAgentConfigStore()).setGatewayUrl(t.url),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureSoloEvaluator(){if(!this.soloEvaluator){let e=new Zt({log:{info:n=>process.stderr.write(`[solo:pm] ${n}
497
498
  `),warn:n=>process.stderr.write(`[solo:pm] WARN ${n}
498
- `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,s),this.sendNotification("team.member.notification",{memberId:n,method:o,params:s})},onStateChange:(n,o)=>{let s=e.getHandle(n),a=e.getUsageTracker(n)?.getUsage();this.emitAgentStatus(n,o,{missedBeats:e.getMissedBeats(n),lastActivityAt:s?.lastActivityAt,usage:a&&a.totalTokens>0?{inputTokens:a.inputTokens,outputTokens:a.outputTokens,totalTokens:a.totalTokens}:void 0})},onMcpToolCall:(n,o,s)=>this.handleMcpToolCall(n,o,s),sessionDir:F.join(J(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
499
+ `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,s),this.sendNotification("team.member.notification",{memberId:n,method:o,params:s})},onStateChange:(n,o)=>{let s=e.getHandle(n),a=e.getUsageTracker(n)?.getUsage();this.emitAgentStatus(n,o,{missedBeats:e.getMissedBeats(n),lastActivityAt:s?.lastActivityAt,usage:a&&a.totalTokens>0?{inputTokens:a.inputTokens,outputTokens:a.outputTokens,totalTokens:a.totalTokens}:void 0})},onMcpToolCall:(n,o,s)=>this.handleMcpToolCall(n,o,s),sessionDir:F.join(X(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
499
500
  `),warn:n=>process.stderr.write(`${n}
500
- `)},onProgress:(n,o,s,i)=>{this.sendNotification("solo.progress",{soloId:n,agentId:o,state:s,progress:i})},onEvaluation:(n,o)=>{this.sendNotification("solo.evaluation",{soloId:n,winnerId:o.winnerId,reasoning:o.reasoning})},onAgentDelta:(n,o,s)=>{this.sendNotification("solo.agentDelta",{soloId:n,agentId:o,text:s})}};this.soloEvaluator=new wr(e,this.acpDetector,this.agentConfigStore,t),this.soloProcessManager=e}return this.soloEvaluator}async handleSoloStart(e){try{let t=e.params;if(!t?.task||!t?.agents||!t?.cwd){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"task, agents, and cwd are required."});return}let n=this.ensureSoloEvaluator(),o=await n.start(t),s=n.getStatus(o);e.id!==void 0&&this.sendResponse(e.id,s)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloStatus(e){try{let t=e.params;if(!t?.soloId){this.soloEvaluator?e.id!==void 0&&this.sendResponse(e.id,this.soloEvaluator.listSessions()):e.id!==void 0&&this.sendResponse(e.id,[]);return}let o=this.ensureSoloEvaluator().getStatus(t.soloId);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:`Solo session ${t.soloId} not found.`});return}e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloCancel(e){try{let t=e.params;if(!t?.soloId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"soloId is required."});return}await this.ensureSoloEvaluator().cancel(t.soloId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloSelect(e){try{let t=e.params;if(!t?.soloId||!t?.winnerId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"soloId and winnerId are required."});return}let o=await this.ensureSoloEvaluator().select(t);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,mergedBranch:o})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureProductOrchestrator(){if(!this.productOrchestrator){let e=new Jt({log:{info:n=>process.stderr.write(`[product:pm] ${n}
501
+ `)},onProgress:(n,o,s,i)=>{this.sendNotification("solo.progress",{soloId:n,agentId:o,state:s,progress:i})},onEvaluation:(n,o)=>{this.sendNotification("solo.evaluation",{soloId:n,winnerId:o.winnerId,reasoning:o.reasoning})},onAgentDelta:(n,o,s)=>{this.sendNotification("solo.agentDelta",{soloId:n,agentId:o,text:s})}};this.soloEvaluator=new _r(e,this.acpDetector,this.agentConfigStore,t),this.soloProcessManager=e}return this.soloEvaluator}async handleSoloStart(e){try{let t=e.params;if(!t?.task||!t?.agents||!t?.cwd){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"task, agents, and cwd are required."});return}let n=this.ensureSoloEvaluator(),o=await n.start(t),s=n.getStatus(o);e.id!==void 0&&this.sendResponse(e.id,s)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloStatus(e){try{let t=e.params;if(!t?.soloId){this.soloEvaluator?e.id!==void 0&&this.sendResponse(e.id,this.soloEvaluator.listSessions()):e.id!==void 0&&this.sendResponse(e.id,[]);return}let o=this.ensureSoloEvaluator().getStatus(t.soloId);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:`Solo session ${t.soloId} not found.`});return}e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloCancel(e){try{let t=e.params;if(!t?.soloId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"soloId is required."});return}await this.ensureSoloEvaluator().cancel(t.soloId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloSelect(e){try{let t=e.params;if(!t?.soloId||!t?.winnerId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"soloId and winnerId are required."});return}let o=await this.ensureSoloEvaluator().select(t);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,mergedBranch:o})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureProductOrchestrator(){if(!this.productOrchestrator){let e=new Zt({log:{info:n=>process.stderr.write(`[product:pm] ${n}
501
502
  `),warn:n=>process.stderr.write(`[product:pm] WARN ${n}
502
- `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,s),this.sendNotification("team.member.notification",{memberId:n,method:o,params:s})},onStateChange:(n,o)=>{let s=e.getHandle(n),a=e.getUsageTracker(n)?.getUsage();this.emitAgentStatus(n,o,{missedBeats:e.getMissedBeats(n),lastActivityAt:s?.lastActivityAt,usage:a&&a.totalTokens>0?{inputTokens:a.inputTokens,outputTokens:a.outputTokens,totalTokens:a.totalTokens}:void 0})},onMcpToolCall:(n,o,s)=>this.handleMcpToolCall(n,o,s),sessionDir:F.join(J(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
503
+ `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,s),this.sendNotification("team.member.notification",{memberId:n,method:o,params:s})},onStateChange:(n,o)=>{let s=e.getHandle(n),a=e.getUsageTracker(n)?.getUsage();this.emitAgentStatus(n,o,{missedBeats:e.getMissedBeats(n),lastActivityAt:s?.lastActivityAt,usage:a&&a.totalTokens>0?{inputTokens:a.inputTokens,outputTokens:a.outputTokens,totalTokens:a.totalTokens}:void 0})},onMcpToolCall:(n,o,s)=>this.handleMcpToolCall(n,o,s),sessionDir:F.join(X(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
503
504
  `),warn:n=>process.stderr.write(`${n}
504
- `)},onTaskStarted:(n,o,s)=>{this.sendNotification("product.taskStarted",{productId:n,taskId:o,assignee:s})},onTaskCompleted:(n,o,s)=>{this.sendNotification("product.taskCompleted",{productId:n,taskId:o,result:s})},onTaskFailed:(n,o,s)=>{this.sendNotification("product.taskFailed",{productId:n,taskId:o,error:s})},onCheckpointed:(n,o)=>{this.sendNotification("product.checkpointed",{productId:n,timestamp:o})},onBudgetWarning:(n,o,s,i)=>{this.sendNotification("product.budgetWarning",{productId:n,usedTokens:o,maxTotalTokens:s,percentage:i})},onCompleted:(n,o)=>{this.sendNotification("product.completed",{productId:n,summary:o})}};this.productOrchestrator=new vr(e,this.acpDetector,this.agentConfigStore,t),this.productProcessManager=e}return this.productOrchestrator}async handleProductCreate(e){try{let t=e.params;if(!t?.name||!t?.cwd||!t?.instances||!t?.tasks){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"name, cwd, instances, and tasks are required."});return}let o=await this.ensureProductOrchestrator().create(t);e.id!==void 0&&this.sendResponse(e.id,{productId:o})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductResume(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().resume(t.productId,this.currentProjectRoot),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductPause(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().pause(t.productId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductCheckpoint(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().checkpoint(t.productId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductStatus(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"productId is required."});return}let o=this.ensureProductOrchestrator().getStatus(t.productId);e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductList(e){try{let n=await this.ensureProductOrchestrator().list(this.currentProjectRoot);e.id!==void 0&&this.sendResponse(e.id,n)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsGetGateway(e){try{let n=(await this.ensureAgentConfigStore()).getGatewayUrl();e.id!==void 0&&this.sendResponse(e.id,{url:n})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsListConfigured(e){try{let n=(await this.ensureAgentConfigStore()).getData(),o=Object.entries(n.agents).map(([s,i])=>({agentId:s,hasApiKey:!!i.apiKey,hasBaseUrl:!!i.baseUrl,hasModel:!!i.model}));e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}handleAgentsProcesses(e){try{let t=[],n=(o,s)=>{if(o)for(let i of o.getAllHandles())t.push({memberId:i.memberId,name:i.name,pid:i.pid,state:i.state,startedAt:i.startedAt,endedAt:i.endedAt,source:s})};n(this.soloProcessManager,"solo"),n(this.productProcessManager,"product"),e.id!==void 0&&this.sendResponse(e.id,t)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}handleAgentsKill(e){try{let t=e.params;if(!t?.memberId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"memberId is required."});return}let n=!1;for(let o of[this.soloProcessManager,this.productProcessManager])if(o?.getHandle(t.memberId)){o.kill(t.memberId),n=!0;break}e.id!==void 0&&this.sendResponse(e.id,{ok:n})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsGetLog(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"agentId is required."});return}let n=F.join(J(),"agent-logs"),o=F.join(n,`${t.agentId}.stderr.log`),s="";try{s=M.readFileSync(o,"utf-8")}catch{}t.tail&&t.tail>0&&s&&(s=s.split(`
505
+ `)},onTaskStarted:(n,o,s)=>{this.sendNotification("product.taskStarted",{productId:n,taskId:o,assignee:s})},onTaskCompleted:(n,o,s)=>{this.sendNotification("product.taskCompleted",{productId:n,taskId:o,result:s})},onTaskFailed:(n,o,s)=>{this.sendNotification("product.taskFailed",{productId:n,taskId:o,error:s})},onCheckpointed:(n,o)=>{this.sendNotification("product.checkpointed",{productId:n,timestamp:o})},onBudgetWarning:(n,o,s,i)=>{this.sendNotification("product.budgetWarning",{productId:n,usedTokens:o,maxTotalTokens:s,percentage:i})},onCompleted:(n,o)=>{this.sendNotification("product.completed",{productId:n,summary:o})}};this.productOrchestrator=new xr(e,this.acpDetector,this.agentConfigStore,t),this.productProcessManager=e}return this.productOrchestrator}async handleProductCreate(e){try{let t=e.params;if(!t?.name||!t?.cwd||!t?.instances||!t?.tasks){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"name, cwd, instances, and tasks are required."});return}let o=await this.ensureProductOrchestrator().create(t);e.id!==void 0&&this.sendResponse(e.id,{productId:o})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductResume(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().resume(t.productId,this.currentProjectRoot),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductPause(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().pause(t.productId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductCheckpoint(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().checkpoint(t.productId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductStatus(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"productId is required."});return}let o=this.ensureProductOrchestrator().getStatus(t.productId);e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductList(e){try{let n=await this.ensureProductOrchestrator().list(this.currentProjectRoot);e.id!==void 0&&this.sendResponse(e.id,n)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsGetGateway(e){try{let n=(await this.ensureAgentConfigStore()).getGatewayUrl();e.id!==void 0&&this.sendResponse(e.id,{url:n})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsListConfigured(e){try{let n=(await this.ensureAgentConfigStore()).getData(),o=Object.entries(n.agents).map(([s,i])=>({agentId:s,hasApiKey:!!i.apiKey,hasBaseUrl:!!i.baseUrl,hasModel:!!i.model}));e.id!==void 0&&this.sendResponse(e.id,o)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}handleAgentsProcesses(e){try{let t=[],n=(o,s)=>{if(o)for(let i of o.getAllHandles())t.push({memberId:i.memberId,name:i.name,pid:i.pid,state:i.state,startedAt:i.startedAt,endedAt:i.endedAt,source:s})};n(this.soloProcessManager,"solo"),n(this.productProcessManager,"product"),e.id!==void 0&&this.sendResponse(e.id,t)}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}handleAgentsKill(e){try{let t=e.params;if(!t?.memberId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"memberId is required."});return}let n=!1;for(let o of[this.soloProcessManager,this.productProcessManager])if(o?.getHandle(t.memberId)){o.kill(t.memberId),n=!0;break}e.id!==void 0&&this.sendResponse(e.id,{ok:n})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsGetLog(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"agentId is required."});return}let n=F.join(X(),"agent-logs"),o=F.join(n,`${t.agentId}.stderr.log`),s="";try{s=M.readFileSync(o,"utf-8")}catch{}t.tail&&t.tail>0&&s&&(s=s.split(`
505
506
  `).slice(-t.tail).join(`
506
- `)),e.id!==void 0&&this.sendResponse(e.id,{log:s})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsTestConnection(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let s=this.acpDetector.list().find(a=>a.id===t.agentId);if(!s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,error:`Agent ${t.agentId} not found`,durationMs:0});return}if(s.status==="not_installed"){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,error:`Agent ${t.agentId} is not installed`,durationMs:0});return}let i=Date.now();e.id!==void 0&&this.sendResponse(e.id,{ok:s.status==="available",version:s.version,capabilities:s.capabilities,error:s.status!=="available"?`Agent status: ${s.status}`:void 0,durationMs:Date.now()-i})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}handleSoloList(e){try{this.soloEvaluator?e.id!==void 0&&this.sendResponse(e.id,this.soloEvaluator.listSessions()):e.id!==void 0&&this.sendResponse(e.id,[])}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloDelete(e){try{let t=e.params;if(!t?.soloId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"soloId is required."});return}await this.ensureSoloEvaluator().delete(t.soloId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductDelete(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().delete(t.productId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}sendResponse(e,t,n){let o={jsonrpc:"2.0",id:e};n?o.error=n:o.result=t,this.writeStdout(o)}sendNotification(e,t){if(this.acpServer&&this.acpServer.sessionId)bm(this.acpServer,this.acpServer.sessionId,e,t);else{let n={jsonrpc:"2.0",method:e,params:t};this.writeStdout(n)}e==="turn.end"&&this.resetIdleDreamTimer(),e==="turn.start"&&this.cancelIdleDreamTimer()}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
507
- `)}enableIdleDream(e){this.idleDreamEnabled=!0,e&&e>0&&(this.idleDreamMinutes=e),this.resetIdleDreamTimer()}resetIdleDreamTimer(){this.cancelIdleDreamTimer(),this.idleDreamEnabled&&this.currentSessionId&&(this.idleDreamTimer=setTimeout(()=>{this.triggerIdleDream()},this.idleDreamMinutes*6e4),this.idleDreamTimer.unref?.())}cancelIdleDreamTimer(){this.idleDreamTimer&&(clearTimeout(this.idleDreamTimer),this.idleDreamTimer=null)}async triggerIdleDream(){if(Date.now()-this.lastDreamAt<this.dreamCooldownMs){this.log("[dream:idle] Skipped \u2014 cooldown not elapsed");return}if(!this.currentTransport||!this.currentModel){this.log("[dream:idle] Skipped \u2014 no LLM transport configured");return}if(this.activeTurn){this.log("[dream:idle] Skipped \u2014 turn in progress");return}this.log("[dream:idle] Triggering idle dream consolidation"),this.lastDreamAt=Date.now();let e=setTimeout(()=>{this.activeTurn&&(this.log("[dream:idle] Aborting \u2014 max duration reached"),this.activeTurn.abort())},this.dreamMaxDurationMs);e.unref?.();let t=J(),n={jsonrpc:"2.0",id:void 0,method:"memory.dream",params:{turnId:`idle-dream-${pe().slice(0,8)}`,sessionId:this.currentSessionId,config:{memoryRoot:t,transcriptDir:F.join(t,"agent-logs"),model:this.currentModel,apiKey:this.currentApiKey,force:!1}}};try{await this.handleDream(n)}finally{clearTimeout(e)}this.resetIdleDreamTimer()}initAcpServer(){let e={handleAcpInitialize:t=>this.acpHandleInitialize(t),handleAcpSessionNew:t=>this.acpHandleSessionNew(t),handleAcpSessionPrompt:t=>this.acpHandleSessionPrompt(t),handleAcpSessionEnd:t=>this.acpHandleSessionEnd(t),handleAcpSessionSetConfig:t=>this.acpHandleSessionSetConfig(t),handleAcpSessionSetModel:(t,n)=>this.acpHandleSessionSetModel(t,n),handleAcpSessionSetMode:(t,n)=>this.acpHandleSessionSetMode(t,n),handleAcpPermissionResponse:(t,n)=>this.acpHandlePermissionResponse(t,n),handleAcpAbort:t=>this.acpHandleAbort(t),handleAcpDream:t=>this.acpHandleDream(t),handleAcpSoloStart:t=>this.acpHandleSoloStart(t),handleAcpSoloStatus:t=>this.acpHandleSoloStatus(t),handleAcpSoloSelect:t=>this.acpHandleSoloSelect(t),handleAcpProductCreate:t=>this.acpHandleProductCreate(t),handleAcpProductResume:t=>this.acpHandleProductResume(t),handleAcpProductStatus:t=>this.acpHandleProductStatus(t),handleAcpTeamDelegate:t=>this.acpHandleTeamDelegate(t)};this.acpServer=new Pr(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}async acpHandleInitialize(e){let t=e.clientInfo?.name??"unknown";this.log(`[acp] initialize: host=${t}`);let n={extendedEvents:!0,extendedMethods:!0,orchestration:!0,configOptions:[{name:"model",type:"string",description:"LLM model identifier"},{name:"provider",type:"string",description:"LLM provider identifier"},{name:"maxRounds",type:"number",description:"Max tool loop rounds"},{name:"temperature",type:"number",description:"Sampling temperature"}]};return this.ensureDefaultProject(),{protocolVersion:vx,agentInfo:{name:"qlogicagent",version:"0.1.0"},agentCapabilities:n}}async acpHandleSessionNew(e){let t=e.sessionId??pe();return this.log(`[acp] session/new: id=${t}`),this.currentSessionId=t,this.sessionState=new Vt(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Ct(),e.cwd&&typeof e.cwd=="string"&&(Ot(e.cwd),this.currentProjectRoot=e.cwd,this.mediaPersistence.setProjectDir(e.cwd)),this.enableIdleDream(),{sessionId:t}}async acpHandleSessionPrompt(e){let t=pe(),n=e.sessionId,s=[{role:"user",content:e.prompt.map(c=>c.type==="text"?c.text:`[${c.type}]`).join("")}],i={jsonrpc:"2.0",id:t,method:"thread.turn",params:{turnId:t,sessionId:n,messages:s,config:{}}};return await this.runAcpTurn(t,n,s)}async runAcpTurn(e,t,n){let o=new AbortController;this.activeTurn=o,this.sendNotification("turn.start",{turnId:e,model:this.currentModel||void 0});try{let s={model:this.currentModel||void 0,provider:this.currentProvider||void 0,apiKey:this.currentApiKey||void 0,baseUrl:this.currentBaseUrl||void 0},i=this.resolveAgent(s);if(!i)return this.sendNotification("turn.delta",{turnId:e,text:"Error: No LLM provider configured. Configure via ~/.qlogicagent/settings.json or pass provider/apiKey in session config.",item:{id:`${e}-err`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.sendNotification("turn.end",{turnId:e,content:"",item:{id:`${e}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.activeTurn=null,{stopReason:"end_turn"};await this.mcpReady;let a=rt(),c,d="end_turn";for await(let l of i.run({turnId:e,sessionId:t,messages:n,tools:a,config:s},o.signal)){let u=new Date().toISOString();switch(l.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:l.turnId,text:l.text,item:{id:`${e}-delta`,type:"message",role:"assistant",text:l.text,createdAt:u}});break;case"end":l.usage&&(c={inputTokens:l.usage.prompt??0,outputTokens:l.usage.completion??0,cacheReadTokens:l.usage.cacheRead,cacheWriteTokens:l.usage.cacheCreation}),this.sendNotification("turn.end",{turnId:l.turnId,content:l.content,usage:l.usage,model:l.model,provider:l.provider,item:{id:`${e}-end`,type:"message",role:"assistant",text:l.content,createdAt:u}});break;case"error":d="end_turn",this.sendNotification("turn.error",{turnId:l.turnId,error:l.error,code:l.code});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:l.turnId,callId:l.callId,name:l.name,arguments:l.arguments,item:{id:l.callId,type:"tool_call",role:"assistant",toolName:l.name,toolCallId:l.callId,arguments:l.arguments,createdAt:u}});break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:l.turnId,callId:l.callId,name:l.name,ok:l.ok,...l.error?{error:l.error}:{},...l.outputPreview?{outputPreview:l.outputPreview}:{},item:{id:`${l.callId}-result`,type:"tool_result",role:"assistant",toolName:l.name,toolCallId:l.callId,output:l.ok?l.outputPreview??"":l.error,approved:l.ok,createdAt:u}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:l.turnId,callId:l.callId,name:l.name,reason:l.reason,item:{id:`${l.callId}-blocked`,type:"tool_blocked",role:"system",toolName:l.name,toolCallId:l.callId,text:l.reason,approved:!1,createdAt:u}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:l.turnId,action:l.action,...l.detail?{detail:l.detail}:{},item:{id:`${e}-recovery-${pe().slice(0,8)}`,type:"recovery",role:"system",strategy:l.action,text:l.detail,createdAt:u}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:l.turnId,text:l.text});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:l.turnId,subagentId:l.subagentId,agentType:l.agentType,...l.prompt?{prompt:l.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:l.turnId,subagentId:l.subagentId,agentType:l.agentType,ok:l.ok,...l.outputPreview?{outputPreview:l.outputPreview}:{},...l.error?{error:l.error}:{}});break;case"media_result":this.sendNotification("turn.media_result",{turnId:l.turnId,mediaType:l.mediaType,url:l.url,...l.model?{model:l.model}:{},...l.provider?{provider:l.provider}:{},...l.taskId?{taskId:l.taskId}:{}});break}}return this.activeTurn=null,{stopReason:d,usage:c}}catch(s){this.activeTurn=null;let i=s instanceof Error?s.message:String(s);return this.log(`[acp] runAcpTurn error: ${i}`),this.sendNotification("turn.error",{turnId:e,error:i,code:"INTERNAL_ERROR"}),{stopReason:"end_turn"}}}async acpHandleSessionEnd(e){this.log(`[acp] session/end: id=${e.sessionId}`),this.currentSessionId===e.sessionId&&(this.cancelIdleDreamTimer(),this.currentHooks&&await this.currentHooks.invoke("session.ended",{sessionId:e.sessionId}).catch(()=>{}),this.currentSessionId="",this.sessionState=null)}async acpHandleSessionSetConfig(e){let t=e.configId??e.option;this.log(`[acp] session/set_config: ${t}=${JSON.stringify(e.value)}`);let n=typeof e.value=="string"?e.value:"";switch(t){case"model":this.currentModel=n;break;case"provider":this.currentProvider=n;break;case"apiKey":this.currentApiKey=n;break;case"baseUrl":this.currentBaseUrl=n;break}}async acpHandleSessionSetModel(e,t){this.log(`[acp] session/set_model: ${t}`),t&&(this.currentModel=t)}async acpHandleSessionSetMode(e,t){this.log(`[acp] session/set_mode: ${t}`)}acpHandlePermissionResponse(e,t){this.log(`[acp] permission response: ${e} \u2192 ${t}`),this.permissionChecker&&this.permissionChecker.resolveApproval({approvalId:e,decision:t==="allow"?"approved":"denied"})}async acpHandleAbort(e){this.log(`[acp] abort: session=${e.sessionId}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null)}async acpHandleDream(e){if(this.log(`[acp] x/dream: session=${e.sessionId}`),!this.currentTransport||!this.currentApiKey||!this.currentModel)return{ok:!1,summary:"No LLM transport configured for dream"};let t=J(),n={jsonrpc:"2.0",id:`acp-dream-${pe().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${pe().slice(0,8)}`,sessionId:e.sessionId||this.currentSessionId,config:{memoryRoot:e.config?.memoryRoot||t,transcriptDir:e.config?.transcriptDir||F.join(t,"agent-logs"),model:this.currentModel,apiKey:this.currentApiKey,...e.config}}};return await this.handleDream(n),{ok:!0,summary:"Dream consolidation triggered"}}async acpHandleSoloStart(e){this.log("[acp] x/solo.start");let t=this.ensureSoloEvaluator(),n=await t.start(e);return t.getStatus(n)}async acpHandleSoloStatus(e){this.log("[acp] x/solo.status");let t=e.soloId;if(!t)return this.soloEvaluator?this.soloEvaluator.listSessions():[];let o=this.ensureSoloEvaluator().getStatus(t);if(!o)throw new Error(`Solo session ${t} not found`);return o}async acpHandleSoloSelect(e){return this.log("[acp] x/solo.select"),{ok:!0,mergedBranch:await this.ensureSoloEvaluator().select(e)}}async acpHandleProductCreate(e){return this.log("[acp] x/product.create"),{productId:await this.ensureProductOrchestrator().create(e)}}async acpHandleProductResume(e){this.log("[acp] x/product.resume");let t=this.ensureProductOrchestrator(),n=e.productId;return await t.resume(n,this.currentProjectRoot),{ok:!0}}async acpHandleProductStatus(e){this.log("[acp] x/product.status");let t=e.productId;if(!this.productOrchestrator)return t?null:[];if(!t)return this.productOrchestrator.list(this.currentProjectRoot);let n=this.productOrchestrator.getStatus(t);if(!n)throw new Error(`Product session ${t} not found`);return n}async acpHandleTeamDelegate(e){let t=e.agentType,n=e.prompt,o=e.maxTurns;if(!n)throw new Error("Missing required param: prompt");if(!t)throw new Error("Missing required param: agentType");let s=bo(t);if(!s)throw new Error(`Unknown agent type: ${t}`);if(!this.currentTransport||!this.currentModel)throw new Error("No LLM provider configured \u2014 send a prompt first to configure the model");this.log(`[acp] x/team.delegate: agent=${t}, maxTurns=${o??s.maxTurns}`);let i={invoke:async()=>({result:"Tool execution not available in delegated mode"})},a={info:l=>this.log(`[delegate:${t}] ${l}`),warn:l=>this.log(`[delegate:${t}] WARN: ${l}`),error:l=>this.log(`[delegate:${t}] ERROR: ${l}`),debug:l=>this.log(`[delegate:${t}] ${l}`)},c=await Sn({promptMessages:[{role:"user",content:n}],tools:[],transport:this.currentTransport,toolInvoker:i,apiKey:this.currentApiKey,model:this.currentModel,log:a,forkLabel:`team-delegate-${t}`,maxTurns:o??s.maxTurns,parentSignal:this.activeTurn?.signal,parentDepth:0}),d=c.events.filter(l=>l.type==="end"&&"content"in l).map(l=>l.content??"").join("")||c.events.filter(l=>l.type==="delta"&&"text"in l).map(l=>l.text).join("");return{ok:c.ok,agentType:t,output:d||void 0,error:c.error,tokensUsed:c.totalUsage.prompt+c.totalUsage.completion}}handleProjectCreate(e){let t=e.params;if(!t?.name||!t?.workspaceDir){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required params: name, workspaceDir"});return}if(t.groupId){let o=_a(t.groupId);if(o){e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:o,deduplicated:!0});return}}if(!M.existsSync(t.workspaceDir))try{M.mkdirSync(t.workspaceDir,{recursive:!0})}catch{e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Cannot create workspace directory: ${t.workspaceDir}`});return}let n=Ra({name:t.name,workspaceDir:t.workspaceDir,type:t.type??"personal",groupId:t.groupId});this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type}),this.sendNotification("project.switched",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:n})}handleProjectList(e){let t=Qt();e.id!==void 0&&this.sendResponse(e.id,{projects:t})}handleProjectDelete(e){let t=e.params;if(!t?.projectId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: projectId"});return}let n=dm(t.projectId);if(!n.deleted){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}this.sendNotification("project.deleted",{id:t.projectId}),n.switchedTo&&this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,switchedTo:n.switchedTo})}handleProjectRename(e){let t=e.params;if(!t?.projectId||!t?.newName){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let n=pm(t.projectId,t.newName);if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}this.sendNotification("project.renamed",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:n})}handleProjectArchive(e){let t=e.params;if(!t?.projectId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: projectId"});return}let n=mm(t.projectId);if(!n.archived){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:t.projectId}),n.switchedTo&&this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,switchedTo:n.switchedTo})}handleProjectUnarchive(e){let t=e.params;if(!t?.projectId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: projectId"});return}let n=gm(t.projectId);if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:n})}handleProjectArchiveByGroup(e){let t=e.params;if(!t?.groupId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: groupId"});return}let n=fm(t.groupId);if(!n.archived){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:n.projectId}),n.switchedTo&&this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,projectId:n.projectId})}handleSessionSwitchProject(e){let t=e.params,n=null;if(t?.projectId)n=cm(t.projectId);else if(t?.projectName){let i=Qt(),a=t.projectName.toLowerCase();if(n=i.find(c=>c.name.toLowerCase()===a)??null,n||(n=i.find(c=>c.name.toLowerCase().includes(a))??null),!n){let c=i.map(d=>d.name).slice(0,10);e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`No project matching "${t.projectName}". Available: ${c.join(", ")||"(none)"}`});return}}else{e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!n||n.status!=="active"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Project not found or archived: ${t.projectId??t.projectName}`});return}let o=t.workspaceDir??n.workspaceDir;if(!M.existsSync(o)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Workspace directory does not exist: ${o}`});return}let s=Vn(n.id);if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Switch failed"});return}this.currentProjectRoot=s.workspaceDir,this.sendNotification("project.switched",{id:s.id,name:s.name,workspaceDir:s.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:s})}handleSessionGetState(e){let t=Ut(),n=Qt();e.id!==void 0&&this.sendResponse(e.id,{sessionId:this.currentSessionId,activeProject:t,projects:n})}getProjectInstructionsStore(){let e=this.currentProjectRoot;return e?new Kn(e):null}handleInstructionsList(e){let t=this.getProjectInstructionsStore();if(!t){e.id!==void 0&&this.sendResponse(e.id,{instructions:[]});return}let n=t.list();e.id!==void 0&&this.sendResponse(e.id,{instructions:n})}handleInstructionsRead(e){let t=e.params;if(!t?.path){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: path"});return}let n=this.getProjectInstructionsStore();if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}let o=n.read(t.path);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Instruction file not found"});return}e.id!==void 0&&this.sendResponse(e.id,{content:o.content,metadata:{filename:o.filename,sizeBytes:o.sizeBytes}})}handleInstructionsWrite(e){let t=e.params;if(!t?.path||typeof t?.content!="string"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required params: path, content"});return}let n=this.getProjectInstructionsStore();if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}try{n.write(t.path,t.content),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}handleInstructionsDelete(e){let t=e.params;if(!t?.path){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: path"});return}let n=this.getProjectInstructionsStore();if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}if(!n.remove(t.path)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Instruction file not found"});return}e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}handleSkillsList(e){let t=this.currentProjectRoot,n=t?Ze(t):void 0,o=Qe(),s=[];if(n&&M.existsSync(n))for(let i of M.readdirSync(n)){let a=F.join(n,i);if(!M.statSync(a).isDirectory())continue;let c=F.join(a,"SKILL.md"),d=F.join(a,"SKILL.md.disabled"),l=M.existsSync(c)?c:null;if(l||M.existsSync(d)){let u=l?this.extractSkillMeta(l):{};s.push({name:i,path:a,active:!!l,scope:"project",version:u.version,description:u.description})}}if(M.existsSync(o))for(let i of M.readdirSync(o)){let a=F.join(o,i);try{if(!M.statSync(a).isDirectory())continue}catch{continue}let c=F.join(a,"SKILL.md"),d=F.join(a,"SKILL.md.disabled"),l=M.existsSync(c)?c:null;if(l||M.existsSync(d)){let u=l?this.extractSkillMeta(l):{};s.push({name:i,path:a,active:!!l,scope:"global",version:u.version,description:u.description})}}e.id!==void 0&&this.sendResponse(e.id,{skills:s})}extractSkillMeta(e){try{let t=M.readFileSync(e,"utf8"),n=t.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),o=t.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:n?.[1],description:o?.[1]?.trim()}}catch{return{}}}handleSkillsActivate(e){let n=e.params?.name;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: name"});return}let o=this.currentProjectRoot,s=o?Ze(o):void 0;if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}let i=F.join(s,n),a=F.join(i,"SKILL.md.disabled"),c=F.join(i,"SKILL.md");if(M.existsSync(c)){e.id!==void 0&&this.sendResponse(e.id,{ok:!0,already:!0});return}if(M.existsSync(a))try{M.renameSync(a,c),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(d){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Failed to activate skill: ${d instanceof Error?d.message:d}`})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Skill "${n}" not found`})}handleSkillsDeactivate(e){let n=e.params?.name;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: name"});return}let o=this.currentProjectRoot,s=o?Ze(o):void 0;if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}let i=F.join(s,n),a=F.join(i,"SKILL.md"),c=F.join(i,"SKILL.md.disabled");if(!M.existsSync(a)){e.id!==void 0&&this.sendResponse(e.id,{ok:!0,already:!0});return}try{M.renameSync(a,c),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(d){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Failed to deactivate skill: ${d instanceof Error?d.message:d}`})}}handleSkillsDelete(e){let t=e.params,n=t?.name;if(!n||/[\/\\]|\.\./.test(n)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let o=t?.scope??"project",s;if(o==="global")s=F.join(Qe(),n);else{let i=this.currentProjectRoot,a=i?Ze(i):void 0;if(!a){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}s=F.join(a,n)}if(!M.existsSync(s)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Skill "${n}" not found in ${o} scope`});return}try{M.rmSync(s,{recursive:!0,force:!0}),At(),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,deleted:n,scope:o})}catch(i){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Failed to delete skill: ${i instanceof Error?i.message:i}`})}}handleSkillsPromote(e){let t=e.params,n=t?.name;if(!n||/[\/\\]|\.\./.test(n)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let o=this.currentProjectRoot,s=o?Ze(o):void 0;if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"No active project workspace"});return}let i=F.join(s,n),a=F.join(i,"SKILL.md");if(!M.existsSync(a)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Skill "${n}" not found in project scope`});return}let c=Qe(),d=F.join(c,n);try{M.mkdirSync(d,{recursive:!0});let l=M.readdirSync(i);for(let u of l){let p=M.readFileSync(F.join(i,u));M.writeFileSync(F.join(d,u),p)}t?.keepLocal||M.rmSync(i,{recursive:!0,force:!0}),At(),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,promoted:n,globalPath:d,removedFromProject:!t?.keepLocal})}catch(l){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}handleSkillsStats(e){let t=e.params,n=J();if(t?.name){let o=rm(n,t.name);e.id!==void 0&&this.sendResponse(e.id,{name:t.name,stats:o??null})}else{let o=sm(n);e.id!==void 0&&this.sendResponse(e.id,{stats:o})}}getProjectPlanStore(){let e=this.currentProjectRoot;return e?new Jn(e):null}handlePlansList(e){let n=this.getProjectPlanStore()?.list()??[];e.id!==void 0&&this.sendResponse(e.id,{plans:n})}handlePlansGet(e){let t=e.params;if(!t?.planId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INVALID_PARAMS,message:"Missing required param: planId"});return}let o=this.getProjectPlanStore()?.load(t.planId)??null;if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:_.INTERNAL_ERROR,message:"Plan not found"});return}e.id!==void 0&&this.sendResponse(e.id,{plan:o})}};Bt();export{Gt as Agent,Ht as ProviderRegistry,Aa as StdioServer,pn as StdioTransport,cn as buildSkillInstruction,ii as createHookRegistry,$o as createLLMClient,$f as parseCliArgs};
507
+ `)),e.id!==void 0&&this.sendResponse(e.id,{log:s})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleAgentsTestConnection(e){try{let t=e.params;if(!t?.agentId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let s=this.acpDetector.list().find(a=>a.id===t.agentId);if(!s){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,error:`Agent ${t.agentId} not found`,durationMs:0});return}if(s.status==="not_installed"){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,error:`Agent ${t.agentId} is not installed`,durationMs:0});return}let i=Date.now();e.id!==void 0&&this.sendResponse(e.id,{ok:s.status==="available",version:s.version,capabilities:s.capabilities,error:s.status!=="available"?`Agent status: ${s.status}`:void 0,durationMs:Date.now()-i})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}handleSoloList(e){try{this.soloEvaluator?e.id!==void 0&&this.sendResponse(e.id,this.soloEvaluator.listSessions()):e.id!==void 0&&this.sendResponse(e.id,[])}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleSoloDelete(e){try{let t=e.params;if(!t?.soloId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"soloId is required."});return}await this.ensureSoloEvaluator().delete(t.soloId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleProductDelete(e){try{let t=e.params;if(!t?.productId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"productId is required."});return}await this.ensureProductOrchestrator().delete(t.productId),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}sendResponse(e,t,n){let o={jsonrpc:"2.0",id:e};n?o.error=n:o.result=t,this.writeStdout(o)}sendNotification(e,t){if(this.acpServer&&this.acpServer.sessionId)Mm(this.acpServer,this.acpServer.sessionId,e,t);else{let n={jsonrpc:"2.0",method:e,params:t};this.writeStdout(n)}e==="turn.end"&&this.resetIdleDreamTimer(),e==="turn.start"&&this.cancelIdleDreamTimer()}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
508
+ `)}enableIdleDream(e){this.idleDreamEnabled=!0,e&&e>0&&(this.idleDreamMinutes=e),this.resetIdleDreamTimer()}resetIdleDreamTimer(){this.cancelIdleDreamTimer(),this.idleDreamEnabled&&this.currentSessionId&&(this.idleDreamTimer=setTimeout(()=>{this.triggerIdleDream()},this.idleDreamMinutes*6e4),this.idleDreamTimer.unref?.())}cancelIdleDreamTimer(){this.idleDreamTimer&&(clearTimeout(this.idleDreamTimer),this.idleDreamTimer=null)}async triggerIdleDream(){if(Date.now()-this.lastDreamAt<this.dreamCooldownMs){this.log("[dream:idle] Skipped \u2014 cooldown not elapsed");return}if(!this.currentTransport||!this.currentModel){this.log("[dream:idle] Skipped \u2014 no LLM transport configured");return}if(this.activeTurn){this.log("[dream:idle] Skipped \u2014 turn in progress");return}this.log("[dream:idle] Triggering idle dream consolidation"),this.lastDreamAt=Date.now();let e=setTimeout(()=>{this.activeTurn&&(this.log("[dream:idle] Aborting \u2014 max duration reached"),this.activeTurn.abort())},this.dreamMaxDurationMs);e.unref?.();let t=X(),n={jsonrpc:"2.0",id:void 0,method:"memory.dream",params:{turnId:`idle-dream-${ge().slice(0,8)}`,sessionId:this.currentSessionId,config:{memoryRoot:t,transcriptDir:F.join(t,"agent-logs"),model:this.currentModel,apiKey:this.currentApiKey,force:!1}}};try{await this.handleDream(n)}finally{clearTimeout(e)}this.resetIdleDreamTimer()}initAcpServer(){let e={handleAcpInitialize:t=>this.acpHandleInitialize(t),handleAcpSessionNew:t=>this.acpHandleSessionNew(t),handleAcpSessionPrompt:t=>this.acpHandleSessionPrompt(t),handleAcpSessionEnd:t=>this.acpHandleSessionEnd(t),handleAcpSessionSetConfig:t=>this.acpHandleSessionSetConfig(t),handleAcpSessionSetModel:(t,n)=>this.acpHandleSessionSetModel(t,n),handleAcpSessionSetMode:(t,n)=>this.acpHandleSessionSetMode(t,n),handleAcpPermissionResponse:(t,n)=>this.acpHandlePermissionResponse(t,n),handleAcpAbort:t=>this.acpHandleAbort(t),handleAcpDream:t=>this.acpHandleDream(t),handleAcpAgentsList:()=>this.acpHandleAgentsList(),handleAcpSoloStart:t=>this.acpHandleSoloStart(t),handleAcpSoloStatus:t=>this.acpHandleSoloStatus(t),handleAcpSoloSelect:t=>this.acpHandleSoloSelect(t),handleAcpSoloCancel:t=>this.acpHandleSoloCancel(t),handleAcpSoloSubscribe:t=>this.acpHandleSoloSubscribe(t),handleAcpProductCreate:t=>this.acpHandleProductCreate(t),handleAcpProductPause:t=>this.acpHandleProductPause(t),handleAcpProductResume:t=>this.acpHandleProductResume(t),handleAcpProductCancel:t=>this.acpHandleProductCancel(t),handleAcpProductRollback:t=>this.acpHandleProductRollback(t),handleAcpProductStatus:t=>this.acpHandleProductStatus(t),handleAcpProductSubscribe:t=>this.acpHandleProductSubscribe(t),handleAcpTeamDelegate:t=>this.acpHandleTeamDelegate(t)};this.acpServer=new Dr(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}async acpHandleInitialize(e){let t=e.clientInfo?.name??"unknown";this.log(`[acp] initialize: host=${t}`);let n={extendedEvents:!0,extendedMethods:!0,orchestration:!0,configOptions:[{name:"model",type:"string",description:"LLM model identifier"},{name:"provider",type:"string",description:"LLM provider identifier"},{name:"maxRounds",type:"number",description:"Max tool loop rounds"},{name:"temperature",type:"number",description:"Sampling temperature"}]};return this.ensureDefaultProject(),{protocolVersion:1,agentInfo:{name:"qlogicagent",version:"0.1.0"},agentCapabilities:n}}async acpHandleSessionNew(e){let t=e.sessionId??ge();return this.log(`[acp] session/new: id=${t}`),this.currentSessionId=t,this.sessionState=new Xt(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Pt(),e.cwd&&typeof e.cwd=="string"&&(Ut(e.cwd),this.currentProjectRoot=e.cwd,this.mediaPersistence.setProjectDir(e.cwd)),this.enableIdleDream(),{sessionId:t}}async acpHandleSessionPrompt(e){let t=ge(),n=e.sessionId,s=[{role:"user",content:e.prompt.map(c=>c.type==="text"?c.text:`[${c.type}]`).join("")}],i={jsonrpc:"2.0",id:t,method:"thread.turn",params:{turnId:t,sessionId:n,messages:s,config:{}}};return await this.runAcpTurn(t,n,s)}async runAcpTurn(e,t,n){let o=new AbortController;this.activeTurn=o,this.sendNotification("turn.start",{turnId:e,model:this.currentModel||void 0});try{let s={model:this.currentModel||void 0,provider:this.currentProvider||void 0,apiKey:this.currentApiKey||void 0,baseUrl:this.currentBaseUrl||void 0},i=this.resolveAgent(s);if(!i)return this.sendNotification("turn.delta",{turnId:e,text:"Error: No LLM provider configured. Configure via ~/.qlogicagent/settings.json or pass provider/apiKey in session config.",item:{id:`${e}-err`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.sendNotification("turn.end",{turnId:e,content:"",item:{id:`${e}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.activeTurn=null,{stopReason:"end_turn"};await this.mcpReady;let a=ct(),c,d="end_turn";for await(let l of i.run({turnId:e,sessionId:t,messages:n,tools:a,config:s},o.signal)){let u=new Date().toISOString();switch(l.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:l.turnId,text:l.text,item:{id:`${e}-delta`,type:"message",role:"assistant",text:l.text,createdAt:u}});break;case"end":l.usage&&(c={inputTokens:l.usage.inputTokens??0,outputTokens:l.usage.outputTokens??0,cacheReadTokens:l.usage.cacheRead,cacheWriteTokens:l.usage.cacheWrite}),this.sendNotification("turn.end",{turnId:l.turnId,content:l.content,usage:l.usage,model:l.model,provider:l.provider,item:{id:`${e}-end`,type:"message",role:"assistant",text:l.content,createdAt:u}});break;case"error":d="end_turn",this.sendNotification("turn.error",{turnId:l.turnId,error:l.error,code:l.code});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:l.turnId,callId:l.callId,name:l.name,arguments:l.arguments,item:{id:l.callId,type:"tool_call",role:"assistant",toolName:l.name,toolCallId:l.callId,arguments:l.arguments,createdAt:u}});break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:l.turnId,callId:l.callId,name:l.name,ok:l.ok,...l.error?{error:l.error}:{},...l.outputPreview?{outputPreview:l.outputPreview}:{},item:{id:`${l.callId}-result`,type:"tool_result",role:"assistant",toolName:l.name,toolCallId:l.callId,output:l.ok?l.outputPreview??"":l.error,approved:l.ok,createdAt:u}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:l.turnId,callId:l.callId,name:l.name,reason:l.reason,item:{id:`${l.callId}-blocked`,type:"tool_blocked",role:"system",toolName:l.name,toolCallId:l.callId,text:l.reason,approved:!1,createdAt:u}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:l.turnId,action:l.action,...l.detail?{detail:l.detail}:{},item:{id:`${e}-recovery-${ge().slice(0,8)}`,type:"recovery",role:"system",strategy:l.action,text:l.detail,createdAt:u}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:l.turnId,text:l.text});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:l.turnId,subagentId:l.subagentId,agentType:l.agentType,...l.prompt?{prompt:l.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:l.turnId,subagentId:l.subagentId,agentType:l.agentType,ok:l.ok,...l.outputPreview?{outputPreview:l.outputPreview}:{},...l.error?{error:l.error}:{}});break;case"media_result":this.sendNotification("turn.media_result",{turnId:l.turnId,mediaType:l.mediaType,url:l.url,...l.model?{model:l.model}:{},...l.provider?{provider:l.provider}:{},...l.taskId?{taskId:l.taskId}:{}});break}}return this.activeTurn=null,{stopReason:d,usage:c}}catch(s){this.activeTurn=null;let i=s instanceof Error?s.message:String(s);return this.log(`[acp] runAcpTurn error: ${i}`),this.sendNotification("turn.error",{turnId:e,error:i,code:"INTERNAL_ERROR"}),{stopReason:"end_turn"}}}async acpHandleSessionEnd(e){this.log(`[acp] session/end: id=${e.sessionId}`),this.currentSessionId===e.sessionId&&(this.cancelIdleDreamTimer(),this.currentHooks&&await this.currentHooks.invoke("session.ended",{sessionId:e.sessionId}).catch(()=>{}),this.currentSessionId="",this.sessionState=null)}async acpHandleSessionSetConfig(e){let t=e.configId??e.option;this.log(`[acp] session/set_config: ${t}=${JSON.stringify(e.value)}`);let n=typeof e.value=="string"?e.value:"";switch(t){case"model":this.currentModel=n;break;case"provider":this.currentProvider=n;break;case"apiKey":this.currentApiKey=n;break;case"baseUrl":this.currentBaseUrl=n;break}}async acpHandleSessionSetModel(e,t){this.log(`[acp] session/set_model: ${t}`),t&&(this.currentModel=t)}async acpHandleSessionSetMode(e,t){this.log(`[acp] session/set_mode: ${t}`)}acpHandlePermissionResponse(e,t){this.log(`[acp] permission response: ${e} \u2192 ${t}`),this.permissionChecker&&this.permissionChecker.resolveApproval({approvalId:e,decision:t==="allow"?"approved":"denied"})}async acpHandleAbort(e){this.log(`[acp] abort: session=${e.sessionId}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null)}async acpHandleDream(e){if(this.log(`[acp] x/dream: session=${e.sessionId}`),!this.currentTransport||!this.currentApiKey||!this.currentModel)return{ok:!1,summary:"No LLM transport configured for dream"};let t=X(),n={jsonrpc:"2.0",id:`acp-dream-${ge().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${ge().slice(0,8)}`,sessionId:e.sessionId||this.currentSessionId,config:{memoryRoot:e.config?.memoryRoot||t,transcriptDir:e.config?.transcriptDir||F.join(t,"agent-logs"),model:this.currentModel,apiKey:this.currentApiKey,...e.config}}};return await this.handleDream(n),{ok:!0,summary:"Dream consolidation triggered"}}async acpHandleSoloStart(e){this.log("[acp] x/solo.start");let t=this.ensureSoloEvaluator(),n=await t.start(e);return t.getStatus(n)}async acpHandleSoloStatus(e){this.log("[acp] x/solo.status");let t=e.soloId;if(!t)return this.soloEvaluator?this.soloEvaluator.listSessions():[];let o=this.ensureSoloEvaluator().getStatus(t);if(!o)throw new Error(`Solo session ${t} not found`);return o}async acpHandleSoloSelect(e){return this.log("[acp] x/solo.select"),{ok:!0,mergedBranch:await this.ensureSoloEvaluator().select(e)}}async acpHandleSoloCancel(e){this.log("[acp] x/solo.cancel");let t=this.ensureSoloEvaluator(),n=e.soloId;return await t.cancel(n),{ok:!0}}async acpHandleSoloSubscribe(e){return this.log("[acp] x/solo.subscribe"),{ok:!0,soloId:e.soloId}}async acpHandleAgentsList(){return this.log("[acp] x/agents.list"),Ls()}async acpHandleProductCreate(e){return this.log("[acp] x/product.create"),{productId:await this.ensureProductOrchestrator().create(e)}}async acpHandleProductResume(e){this.log("[acp] x/product.resume");let t=this.ensureProductOrchestrator(),n=e.productId;return await t.resume(n,this.currentProjectRoot),{ok:!0}}async acpHandleProductStatus(e){this.log("[acp] x/product.status");let t=e.productId;if(!this.productOrchestrator)return t?null:[];if(!t)return this.productOrchestrator.list(this.currentProjectRoot);let n=this.productOrchestrator.getStatus(t);if(!n)throw new Error(`Product session ${t} not found`);return n}async acpHandleProductPause(e){this.log("[acp] x/product.pause");let t=this.ensureProductOrchestrator(),n=e.productId;return await t.pause(n),{ok:!0}}async acpHandleProductCancel(e){this.log("[acp] x/product.cancel");let t=this.ensureProductOrchestrator(),n=e.productId;return await t.delete(n),{ok:!0}}async acpHandleProductRollback(e){this.log("[acp] x/product.rollback");let t=this.ensureProductOrchestrator(),n=e.productId,o=e.checkpointId??"latest";return await t.rollback(n,o),{ok:!0}}async acpHandleProductSubscribe(e){return this.log("[acp] x/product.subscribe"),{ok:!0,productId:e.productId}}async acpHandleTeamDelegate(e){let t=e.agentType,n=e.prompt,o=e.maxTurns;if(!n)throw new Error("Missing required param: prompt");if(!t)throw new Error("Missing required param: agentType");let s=vo(t);if(!s)throw new Error(`Unknown agent type: ${t}`);if(!this.currentTransport||!this.currentModel)throw new Error("No LLM provider configured \u2014 send a prompt first to configure the model");this.log(`[acp] x/team.delegate: agent=${t}, maxTurns=${o??s.maxTurns}`);let i={invoke:async()=>({result:"Tool execution not available in delegated mode"})},a={info:l=>this.log(`[delegate:${t}] ${l}`),warn:l=>this.log(`[delegate:${t}] WARN: ${l}`),error:l=>this.log(`[delegate:${t}] ERROR: ${l}`),debug:l=>this.log(`[delegate:${t}] ${l}`)},c=await An({promptMessages:[{role:"user",content:n}],tools:[],transport:this.currentTransport,toolInvoker:i,apiKey:this.currentApiKey,model:this.currentModel,log:a,forkLabel:`team-delegate-${t}`,maxTurns:o??s.maxTurns,parentSignal:this.activeTurn?.signal,parentDepth:0}),d=c.events.filter(l=>l.type==="end"&&"content"in l).map(l=>l.content??"").join("")||c.events.filter(l=>l.type==="delta"&&"text"in l).map(l=>l.text).join("");return{ok:c.ok,agentType:t,output:d||void 0,error:c.error,tokensUsed:c.totalUsage.inputTokens+c.totalUsage.outputTokens}}handleProjectCreate(e){let t=e.params;if(!t?.name||!t?.workspaceDir){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required params: name, workspaceDir"});return}if(t.groupId){let o=ra(t.groupId);if(o){e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:o,deduplicated:!0});return}}if(!M.existsSync(t.workspaceDir))try{M.mkdirSync(t.workspaceDir,{recursive:!0})}catch{e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Cannot create workspace directory: ${t.workspaceDir}`});return}let n=oa({name:t.name,workspaceDir:t.workspaceDir,type:t.type??"personal",groupId:t.groupId});this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type}),this.sendNotification("project.switched",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:n})}handleProjectList(e){let t=ht();e.id!==void 0&&this.sendResponse(e.id,{projects:t})}handleProjectDelete(e){let t=e.params;if(!t?.projectId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: projectId"});return}let n=tp(t.projectId);if(!n.deleted){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}this.sendNotification("project.deleted",{id:t.projectId}),n.switchedTo&&this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,switchedTo:n.switchedTo})}handleProjectRename(e){let t=e.params;if(!t?.projectId||!t?.newName){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let n=op(t.projectId,t.newName);if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}this.sendNotification("project.renamed",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:n})}handleProjectArchive(e){let t=e.params;if(!t?.projectId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: projectId"});return}let n=rp(t.projectId);if(!n.archived){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:t.projectId}),n.switchedTo&&this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,switchedTo:n.switchedTo})}handleProjectUnarchive(e){let t=e.params;if(!t?.projectId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: projectId"});return}let n=sp(t.projectId);if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:n})}handleProjectArchiveByGroup(e){let t=e.params;if(!t?.groupId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: groupId"});return}let n=ip(t.groupId);if(!n.archived){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:n.projectId}),n.switchedTo&&this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,projectId:n.projectId})}handleSessionSwitchProject(e){let t=e.params,n=null;if(t?.projectId)n=ep(t.projectId);else if(t?.projectName){let i=ht(),a=t.projectName.toLowerCase();if(n=i.find(c=>c.name.toLowerCase()===a)??null,n||(n=i.find(c=>c.name.toLowerCase().includes(a))??null),!n){let c=i.map(d=>d.name).slice(0,10);e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`No project matching "${t.projectName}". Available: ${c.join(", ")||"(none)"}`});return}}else{e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!n||n.status!=="active"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Project not found or archived: ${t.projectId??t.projectName}`});return}let o=t.workspaceDir??n.workspaceDir;if(!M.existsSync(o)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Workspace directory does not exist: ${o}`});return}let s=Lt(n.id);if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Switch failed"});return}this.currentProjectRoot=s.workspaceDir,this.sendNotification("project.switched",{id:s.id,name:s.name,workspaceDir:s.workspaceDir}),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,project:s})}handleSessionGetState(e){let t=Dt(),n=ht();e.id!==void 0&&this.sendResponse(e.id,{sessionId:this.currentSessionId,activeProject:t,projects:n})}getProjectInstructionsStore(){let e=this.currentProjectRoot;return e?new Yn(e):null}handleInstructionsList(e){let t=this.getProjectInstructionsStore();if(!t){e.id!==void 0&&this.sendResponse(e.id,{instructions:[]});return}let n=t.list();e.id!==void 0&&this.sendResponse(e.id,{instructions:n})}handleInstructionsRead(e){let t=e.params;if(!t?.path){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: path"});return}let n=this.getProjectInstructionsStore();if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}let o=n.read(t.path);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Instruction file not found"});return}e.id!==void 0&&this.sendResponse(e.id,{content:o.content,metadata:{filename:o.filename,sizeBytes:o.sizeBytes}})}handleInstructionsWrite(e){let t=e.params;if(!t?.path||typeof t?.content!="string"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required params: path, content"});return}let n=this.getProjectInstructionsStore();if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}try{n.write(t.path,t.content),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}handleInstructionsDelete(e){let t=e.params;if(!t?.path){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: path"});return}let n=this.getProjectInstructionsStore();if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}if(!n.remove(t.path)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Instruction file not found"});return}e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}handleSkillsList(e){let t=this.currentProjectRoot,n=t?rt(t):void 0,o=ot(),s=[];if(n&&M.existsSync(n))for(let i of M.readdirSync(n)){let a=F.join(n,i);if(!M.statSync(a).isDirectory())continue;let c=F.join(a,"SKILL.md"),d=F.join(a,"SKILL.md.disabled"),l=M.existsSync(c)?c:null;if(l||M.existsSync(d)){let u=l?this.extractSkillMeta(l):{};s.push({name:i,path:a,active:!!l,scope:"project",version:u.version,description:u.description})}}if(M.existsSync(o))for(let i of M.readdirSync(o)){let a=F.join(o,i);try{if(!M.statSync(a).isDirectory())continue}catch{continue}let c=F.join(a,"SKILL.md"),d=F.join(a,"SKILL.md.disabled"),l=M.existsSync(c)?c:null;if(l||M.existsSync(d)){let u=l?this.extractSkillMeta(l):{};s.push({name:i,path:a,active:!!l,scope:"global",version:u.version,description:u.description})}}e.id!==void 0&&this.sendResponse(e.id,{skills:s})}extractSkillMeta(e){try{let t=M.readFileSync(e,"utf8"),n=t.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),o=t.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:n?.[1],description:o?.[1]?.trim()}}catch{return{}}}handleSkillsActivate(e){let n=e.params?.name;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: name"});return}let o=this.currentProjectRoot,s=o?rt(o):void 0;if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}let i=F.join(s,n),a=F.join(i,"SKILL.md.disabled"),c=F.join(i,"SKILL.md");if(M.existsSync(c)){e.id!==void 0&&this.sendResponse(e.id,{ok:!0,already:!0});return}if(M.existsSync(a))try{M.renameSync(a,c),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(d){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Failed to activate skill: ${d instanceof Error?d.message:d}`})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Skill "${n}" not found`})}handleSkillsDeactivate(e){let n=e.params?.name;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: name"});return}let o=this.currentProjectRoot,s=o?rt(o):void 0;if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}let i=F.join(s,n),a=F.join(i,"SKILL.md"),c=F.join(i,"SKILL.md.disabled");if(!M.existsSync(a)){e.id!==void 0&&this.sendResponse(e.id,{ok:!0,already:!0});return}try{M.renameSync(a,c),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(d){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Failed to deactivate skill: ${d instanceof Error?d.message:d}`})}}handleSkillsDelete(e){let t=e.params,n=t?.name;if(!n||/[\/\\]|\.\./.test(n)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let o=t?.scope??"project",s;if(o==="global")s=F.join(ot(),n);else{let i=this.currentProjectRoot,a=i?rt(i):void 0;if(!a){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}s=F.join(a,n)}if(!M.existsSync(s)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Skill "${n}" not found in ${o} scope`});return}try{M.rmSync(s,{recursive:!0,force:!0}),It(),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,deleted:n,scope:o})}catch(i){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Failed to delete skill: ${i instanceof Error?i.message:i}`})}}handleSkillsPromote(e){let t=e.params,n=t?.name;if(!n||/[\/\\]|\.\./.test(n)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let o=this.currentProjectRoot,s=o?rt(o):void 0;if(!s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"No active project workspace"});return}let i=F.join(s,n),a=F.join(i,"SKILL.md");if(!M.existsSync(a)){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Skill "${n}" not found in project scope`});return}let c=ot(),d=F.join(c,n);try{M.mkdirSync(d,{recursive:!0});let l=M.readdirSync(i);for(let u of l){let p=M.readFileSync(F.join(i,u));M.writeFileSync(F.join(d,u),p)}t?.keepLocal||M.rmSync(i,{recursive:!0,force:!0}),It(),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,promoted:n,globalPath:d,removedFromProject:!t?.keepLocal})}catch(l){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}handleSkillsStats(e){let t=e.params,n=X();if(t?.name){let o=Sm(n,t.name);e.id!==void 0&&this.sendResponse(e.id,{name:t.name,stats:o??null})}else{let o=Rm(n);e.id!==void 0&&this.sendResponse(e.id,{stats:o})}}getProjectPlanStore(){let e=this.currentProjectRoot;return e?new Jn(e):null}handlePlansList(e){let n=this.getProjectPlanStore()?.list()??[];e.id!==void 0&&this.sendResponse(e.id,{plans:n})}handlePlansGet(e){let t=e.params;if(!t?.planId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INVALID_PARAMS,message:"Missing required param: planId"});return}let o=this.getProjectPlanStore()?.load(t.planId)??null;if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:x.INTERNAL_ERROR,message:"Plan not found"});return}e.id!==void 0&&this.sendResponse(e.id,{plan:o})}};Ht();export{Vt as Agent,zt as ProviderRegistry,Da as StdioServer,hn as StdioTransport,mn as buildSkillInstruction,di as createHookRegistry,Fo as createLLMClient,qf as parseCliArgs};