qlogicagent 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,42 +1,42 @@
1
1
  #!/usr/bin/env node
2
- var Lu=Object.defineProperty;var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var Rs=(r,e)=>{for(var t in e)Lu(r,t,{get:e[t],enumerable:!0})};function Re(r){if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(n=>Re(n));let e=r,t={};for(let[n,o]of Object.entries(e))if(!Du.has(n)){if(n==="properties"&&o&&typeof o=="object"&&!Array.isArray(o)){t[n]=Object.fromEntries(Object.entries(o).map(([s,i])=>[s,Re(i)]));continue}if(n==="items"&&o&&typeof o=="object"){t[n]=Array.isArray(o)?o.map(s=>Re(s)):Re(o);continue}if((n==="anyOf"||n==="oneOf"||n==="allOf")&&Array.isArray(o)){t[n]=o.map(s=>Re(s));continue}if(o&&typeof o=="object"&&!Array.isArray(o)){t[n]=Re(o);continue}if(Array.isArray(o)){t[n]=o.map(s=>Re(s));continue}t[n]=o}return t}var Du,mo=q(()=>{"use strict";Du=new Set(["patternProperties","additionalProperties","$schema","$id","$ref","$defs","definitions","examples","minLength","maxLength","minimum","maximum","multipleOf","pattern","format","minItems","maxItems","uniqueItems","minProperties","maxProperties","const"])});function go(r,e,t,n){return{role:"assistant",content:e||null,tool_calls:r,...t&&t.length>0?{thinkingBlocks:t}:{},...n?{reasoning_content:n}:{}}}function kt(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}}var _s=q(()=>{"use strict";mo()});function Je(r,e){if(!r)return!1;let t=r.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(t):t.includes(n))}function Qu(r){return Je(r,Ke.format)}function Cs(r){return Je(r,Ke.rateLimit)}function Zu(r){return Je(r,Ke.timeout)}function ed(r){return Uu.test(r)}function fo(r){let e=r.toLowerCase();return e?r.length>ju?Fu.test(e):Je(e,Ke.billing)?!0:Nu.test(r)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function As(r){return Je(r,Ke.authPermanent)}function td(r){return Je(r,Ke.auth)}function Ms(r){return Je(r,Ke.overloaded)}function qe(r,e){return e.some(t=>r.includes(t))}function nd(r){return qe(r,Gu)||qe(r,Hu)&&r.includes("limit")||r.includes("billing hard limit")||r.includes("hard limit reached")||r.includes("maximum allowed")&&r.includes("limit")}function od(r){let e=qe(r,zu),t=r.includes("spend limit")||r.includes("spending limit"),n=qe(r,Ku);return qe(r,Vu)&&qe(r,qu)||e&&(r.includes("usage limit")||t)||e&&r.includes("limit")&&r.includes("reset")||n&&r.includes("limit")&&(t||qe(r,Ju))}function rd(r){return r.trim().toLowerCase().replace(Xu,"").trim()}function Ps(r){let e=rd(r);return!e||nd(e)?"billing":Cs(e)||od(e)?"rate_limit":"billing"}function sd(r){return Yu.test(r)?Ps(r):null}function Is(r){let e=r.match(Bu);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function id(r){if(!r)return!1;let e=r.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function ad(r){let e=r.trim();if(!e)return!1;let t=Is(e);return t?Wu.has(t.code):!1}function Es(r,e){return typeof r!="number"||!Number.isFinite(r)?null:r===402?e?Ps(e):"billing":r===429?"rate_limit":r===401||r===403?e&&As(e)?"auth_permanent":"auth":r===408?"timeout":r===503?e&&Ms(e)?"overloaded":"timeout":r===502||r===504?"timeout":r===529?"overloaded":r===400?e&&fo(e)?"billing":"format":null}function ld(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 cd(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 Os(r){if(cd(r))return"session_expired";if(ld(r))return"model_not_found";let e=sd(r);return e||(ed(r)?fo(r)?"billing":"rate_limit":Cs(r)?"rate_limit":Ms(r)?"overloaded":ad(r)?Is(r.trim())?.code===529?"overloaded":"timeout":id(r)?"timeout":Qu(r)?"format":fo(r)?"billing":Zu(r)?"timeout":As(r)?"auth_permanent":td(r)?"auth":null)}var Uu,Ke,Nu,Fu,ju,Bu,Wu,Gu,Hu,zu,Vu,qu,Ku,Ju,Yu,Xu,Ls=q(()=>{"use strict";Uu=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Ke={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]},Nu=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Fu=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ju=512,Bu=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,Wu=new Set([500,502,503,504,521,522,523,524,529]),Gu=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Hu=["upgrade your plan","upgrade plan","current plan","subscription"],zu=["daily","weekly","monthly"],Vu=["try again","retry","temporary","cooldown"],qu=["usage limit","rate limit","organization usage"],Ku=["organization","workspace"],Ju=["billing period","exceeded","reached","exhausted"],Yu=/["']?(?: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,Xu=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function lt(r,e){let t=Es(r,e)??(e?Os(e):null);return t?ud[t]:typeof r=="number"&&r>=400&&r<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ho(r){return dd.has(r)}var ud,dd,$s=q(()=>{"use strict";Ls();ud={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"},dd=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"])});function St(r){return typeof r.compressAsync=="function"}function pd(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
+ var ed=Object.defineProperty;var K=(r,e)=>()=>(r&&(e=r(r=0)),e);var $s=(r,e)=>{for(var t in e)ed(r,t,{get:e[t],enumerable:!0})};function Ce(r){if(!r||typeof r!="object")return r;if(Array.isArray(r))return r.map(n=>Ce(n));let e=r,t={};for(let[n,o]of Object.entries(e))if(!nd.has(n)){if(n==="properties"&&o&&typeof o=="object"&&!Array.isArray(o)){t[n]=Object.fromEntries(Object.entries(o).map(([s,i])=>[s,Ce(i)]));continue}if(n==="items"&&o&&typeof o=="object"){t[n]=Array.isArray(o)?o.map(s=>Ce(s)):Ce(o);continue}if((n==="anyOf"||n==="oneOf"||n==="allOf")&&Array.isArray(o)){t[n]=o.map(s=>Ce(s));continue}if(o&&typeof o=="object"&&!Array.isArray(o)){t[n]=Ce(o);continue}if(Array.isArray(o)){t[n]=o.map(s=>Ce(s));continue}t[n]=o}return t}var nd,ko=K(()=>{"use strict";nd=new Set(["patternProperties","additionalProperties","$schema","$id","$ref","$defs","definitions","examples","minLength","maxLength","minimum","maximum","multipleOf","pattern","format","minItems","maxItems","uniqueItems","minProperties","maxProperties","const"])});function To(r,e,t,n){return{role:"assistant",content:e||null,tool_calls:r,...t&&t.length>0?{thinkingBlocks:t}:{},...n?{reasoning_content:n}:{}}}function Tt(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.toolReferences?.length?{toolReferences:e.toolReferences}:{}}}var Ds=K(()=>{"use strict";ko()});function Je(r,e){if(!r)return!1;let t=r.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(t):t.includes(n))}function bd(r){return Je(r,Ke.format)}function Us(r){return Je(r,Ke.rateLimit)}function kd(r){return Je(r,Ke.timeout)}function Td(r){return od.test(r)}function wo(r){let e=r.toLowerCase();return e?r.length>id?sd.test(e):Je(e,Ke.billing)?!0:rd.test(r)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function Ns(r){return Je(r,Ke.authPermanent)}function wd(r){return Je(r,Ke.auth)}function Fs(r){return Je(r,Ke.overloaded)}function qe(r,e){return e.some(t=>r.includes(t))}function vd(r){return qe(r,cd)||qe(r,ud)&&r.includes("limit")||r.includes("billing hard limit")||r.includes("hard limit reached")||r.includes("maximum allowed")&&r.includes("limit")}function xd(r){let e=qe(r,dd),t=r.includes("spend limit")||r.includes("spending limit"),n=qe(r,gd);return qe(r,pd)&&qe(r,md)||e&&(r.includes("usage limit")||t)||e&&r.includes("limit")&&r.includes("reset")||n&&r.includes("limit")&&(t||qe(r,fd))}function Sd(r){return r.trim().toLowerCase().replace(yd,"").trim()}function js(r){let e=Sd(r);return!e||vd(e)?"billing":Us(e)||xd(e)?"rate_limit":"billing"}function _d(r){return hd.test(r)?js(r):null}function Bs(r){let e=r.match(ad);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function Rd(r){if(!r)return!1;let e=r.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function Cd(r){let e=r.trim();if(!e)return!1;let t=Bs(e);return t?ld.has(t.code):!1}function Ws(r,e){return typeof r!="number"||!Number.isFinite(r)?null:r===402?e?js(e):"billing":r===429?"rate_limit":r===401||r===403?e&&Ns(e)?"auth_permanent":"auth":r===408?"timeout":r===503?e&&Fs(e)?"overloaded":"timeout":r===502||r===504?"timeout":r===529?"overloaded":r===400?e&&wo(e)?"billing":"format":null}function Ad(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 Md(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 Gs(r){if(Md(r))return"session_expired";if(Ad(r))return"model_not_found";let e=_d(r);return e||(Td(r)?wo(r)?"billing":"rate_limit":Us(r)?"rate_limit":Fs(r)?"overloaded":Cd(r)?Bs(r.trim())?.code===529?"overloaded":"timeout":Rd(r)?"timeout":bd(r)?"format":wo(r)?"billing":kd(r)?"timeout":Ns(r)?"auth_permanent":wd(r)?"auth":null)}var od,Ke,rd,sd,id,ad,ld,cd,ud,dd,pd,md,gd,fd,hd,yd,Hs=K(()=>{"use strict";od=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Ke={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]},rd=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,sd=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,id=512,ad=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,ld=new Set([500,502,503,504,521,522,523,524,529]),cd=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],ud=["upgrade your plan","upgrade plan","current plan","subscription"],dd=["daily","weekly","monthly"],pd=["try again","retry","temporary","cooldown"],md=["usage limit","rate limit","organization usage"],gd=["organization","workspace"],fd=["billing period","exceeded","reached","exhausted"],hd=/["']?(?: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,yd=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function lt(r,e){let t=Ws(r,e)??(e?Gs(e):null);return t?Pd[t]:typeof r=="number"&&r>=400&&r<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function vo(r){return Id.has(r)}var Pd,Id,Vs=K(()=>{"use strict";Hs();Pd={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"},Id=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"])});function _t(r){return typeof r.compressAsync=="function"}function Ed(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(`}
3
3
  `),t.lastIndexOf(`]
4
4
  `));if(s>e*.5)return t.slice(0,s+1)+`
5
5
  [...truncated: ${r.length-s-1} chars omitted]`}let o=t.lastIndexOf(`
6
6
  `);return o>e*.7?t.slice(0,o)+`
7
7
  [...truncated: ${r.length-o} chars omitted]`:t+`
8
- [...truncated: ${r.length-e} chars omitted]`}function yo(...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 bo(...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,l=!1;for(let u of r){let c=St(u)?await u.compressAsync(n,t):u.compress(n,t);n=c.messages,o+=c.droppedCount,c.droppedCount>0&&s.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,a=a||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages: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:l}:void 0}}}}function Us(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","Note any critical facts, constraints, or preferences the user mentioned that must be preserved.","","### 6. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 7. User Preferences Expressed",`The user sent ${t.length} messages. Note any stated preferences about style, approach, or constraints.`,"","### 8. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 9. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return e?.taskContext&&s.push("","## Additional Context",e.taskContext),s.push("","## Conversation to Summarize","",...r.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),s.join(`
9
- `)}function cn(r={}){let e={...Ns,...r},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function Rt(r,e){let t=r/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function md(r){let e=[],t=[];for(let n of r)n.role==="system"?e.push(n):t.push(n);return{system:e,nonSystem:t}}function ko(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function ln(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 fd(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 To(r,e,t){let n=t.estimateTokens??(p=>Math.ceil(p.length/4)),o=fd(e);if(o.length===0)return r;let s=r.map(p=>typeof p.content=="string"?p.content:"").join(`
8
+ [...truncated: ${r.length-e} chars omitted]`}function xo(...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 So(...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,l=!1;for(let u of r){let c=_t(u)?await u.compressAsync(n,t):u.compress(n,t);n=c.messages,o+=c.droppedCount,c.droppedCount>0&&s.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,a=a||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages: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:l}:void 0}}}}function qs(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??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),s.join(`
9
+ `)}function dn(r={}){let e={...Ks,...r},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function Rt(r,e){let t=r/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function Od(r){let e=[],t=[];for(let n of r)n.role==="system"?e.push(n):t.push(n);return{system:e,nonSystem:t}}function _o(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function un(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 $d(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 Ro(r,e,t){let n=t.estimateTokens??(p=>Math.ceil(p.length/4)),o=$d(e);if(o.length===0)return r;let s=r.map(p=>typeof p.content=="string"?p.content:"").join(`
10
10
  `),i=o.filter(p=>!s.includes(p));if(i.length===0)return r;let a=t.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=t.maxFiles||a<=0)break;let m=await t.readFile(p);if(!m)continue;let g=n(m);g>a||(a-=g,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
11
11
 
12
- ${m}`}))}if(l.length===0)return r;let c=[...r],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function wo(r,e,t=ko){if(e.size===0)return{messages:r,tokensFreed:0,removedCount:0};let n=0,o=0,s=[];for(let a of r){let l=a.tool_call_id??"";if(l&&e.has(l)){n+=t(a),o++,e.delete(l);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 Ds,ct,Ye,Tt,wt,Ns,vt,xt,gd,Ne,vo=q(()=>{"use strict";Ds=4,ct=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let n=[],o=[];for(let c of e)c.role==="system"?n.push(c):o.push(c);let s=t;for(let c of n)s-=this.estimateTokens(c);let i;for(let c of o)if(c.role==="user"){i=c;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=[],l=0;for(let c=o.length-1;c>=0;c--){let d=o[c];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=Ds)break;if(s-p<0&&l<Ds){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let u=[...n];return i&&!a.includes(i)&&u.push(i),u.push(...a),{messages:u,droppedCount:o.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},Ye=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:pd(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};Tt=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??ko,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}=md(e),i=e.reduce((x,R)=>x+this.config.estimateTokens(R),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let x=0;x<s.length&&(s[x].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));x++)a=x+1;let u=Math.max(a,s.length-this.config.protectedTailMessages);if(u<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let c=s.slice(0,a),d=s.slice(a,u),p=s.slice(u),m=Us(d,{taskContext:this.config.taskContext}),g=await this.config.summarize(d,m),f={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
12
+ ${m}`}))}if(l.length===0)return r;let c=[...r],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function Co(r,e,t=_o){if(e.size===0)return{messages:r,tokensFreed:0,removedCount:0};let n=0,o=0,s=[];for(let a of r){let l=a.tool_call_id??"";if(l&&e.has(l)){n+=t(a),o++,e.delete(l);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 zs,ct,Ye,wt,vt,Ks,xt,St,Ld,Fe,Ao=K(()=>{"use strict";zs=4,ct=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let n=[],o=[];for(let c of e)c.role==="system"?n.push(c):o.push(c);let s=t;for(let c of n)s-=this.estimateTokens(c);let i;for(let c of o)if(c.role==="user"){i=c;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=[],l=0;for(let c=o.length-1;c>=0;c--){let d=o[c];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=zs)break;if(s-p<0&&l<zs){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let u=[...n];return i&&!a.includes(i)&&u.push(i),u.push(...a),{messages:u,droppedCount:o.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},Ye=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:Ed(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};wt=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??_o,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}=Od(e),i=e.reduce((y,C)=>y+this.config.estimateTokens(C),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let y=0;y<s.length&&(s[y].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));y++)a=y+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),c=Math.max(a,s.length-u);if(c<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let d=s.slice(0,a),p=s.slice(a,c),m=s.slice(c),g=qs(p,{taskContext:this.config.taskContext}),f=await this.config.summarize(p,g),b={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
13
13
 
14
- ${g}`},b=[...o,...c,f,...p],h=Date.now()-n,k=b.reduce((x,R)=>x+this.config.estimateTokens(R),0);return{messages:b,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:k,compressionRatio:i>0?k/i:1,latencyMs:h,usedLlm:!0,cacheInvalidated:!0}}}},wt=class{config;constructor(e){this.config=e}compress(e,t){let n=ln(e),o=this.config.inner.compress(e,t),s=ln(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=ln(e),o=St(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=ln(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}}}},Ns={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};vt=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}},xt=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}))}};gd=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"]),Ne=class{constructor(e=20,t=ko){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,l)=>{if(l>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!gd.has(a.name)||a.content.length<=200)return a;let u=this.estimateTokens(a);return s+=u,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 xo(){return{stages:[]}}function So(r,e,t){let n=t?.thresholdMessages??40;if(r.filter(a=>a.role!=="system").length<=n)return{messages:r,stagedCount:0};let s=Fs(r,e),i=hd(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Fs(r,e),{messages:s,stagedCount:i.length}}function Ro(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:js(r,e),committed:t}}function Fs(r,e){return e.stages.filter(n=>n.committed).length===0?r:js(r,e)}function js(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),l={role:"system",content:o.summary};n.splice(s,a-s,l)}return n}function hd(r,e,t){let n=Math.max(0,r.length-Math.floor(t/2)),o=[],s=new Set(e.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<n;l++){let u=r[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||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 l=`${i}-${i+a}`;s.has(l)||o.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return o}var Bs=q(()=>{"use strict"});function yd(r){return!(!r.ok||r.existingSkillName||!r.multiStep||r.toolCallCount<3||r.distinctToolCount<2)}function bd(r){return r.existingSkillName?r.feedback==="negative":!1}function un(r,e){return bd(r)?{type:"skill.improve",skillName:r.existingSkillName,reason:"negative user feedback on existing skill execution"}:yd(r)?{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 Ws=q(()=>{"use strict"});function Gs(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 kd(r){return r==="enabled-eligible"||r==="installed-awaiting-approval"}function Td(r){return new Map((r??[]).map(e=>[e.toolName,e]))}function wd(r){if(!r.eligibility?.length)return[...r.tools];let e=Td(r.eligibility);return r.tools.filter(t=>{let n=Gs(t);if(!n)return!1;let o=e.get(n);return!o||kd(o.status)})}function vd(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 _o(r){let e=vd({toolChoice:r.toolChoice,thinkingEnabled:r.thinkingEnabled,compatibility:r.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],o=wd({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(l=>Gs(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:o,normalizedToolChoice:t,warnings:n}}var Hs=q(()=>{"use strict"});function zs(r){return r==null?[]:typeof r=="string"?r.length>0?[{type:"text",text:r}]:[]:Array.isArray(r)?r:[{type:"text",text:String(r)}]}function Rd(r,e){return{...r,content:[...zs(r.content),...zs(e.content)]}}function _d(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 Cd(r){return new Set((r??xd).map(e=>e.trim().toLowerCase()))}function Ad(r,e){return r?Cd(e).has(r.trim().toLowerCase()):!1}function Co(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 l=a.tool_calls.filter(u=>_d(u));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),t=new Set;for(let a of e)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let l of a.tool_calls)typeof l.id=="string"&&l.id&&t.add(l.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),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 l=a.tool_calls.filter(u=>typeof u.id=="string"&&o.has(u.id));if(l.length===0){let{tool_calls:u,...c}=a;c.content!=null&&c.content!==""&&s.push(c);continue}if(l.length<a.tool_calls.length){s.push({...a,tool_calls:l});continue}}s.push(a)}let i=[];for(let a of s){let l=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){i[i.length-1]=Rd(l,a);continue}i.push(a)}return i}function Ao(r,e){return Ad(e?.stopReason,e?.forcedStopReasons)?r.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let o of Sd)delete n[o];return n}):[...r]}function Mo(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 Po(r,e){let t=Co(r),n=Ao(t,e);return Mo(n,e)}var xd,Sd,Io=q(()=>{"use strict";xd=["stop","aborted","timeout","cancelled","interrupted","error"],Sd=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Md(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 Pd(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 Id(r){return{round:r.round??0,maxRounds:r.maxRounds,pendingToolCallIds:[...r.pendingToolCallIds??[]],completedToolCallIds:[...r.completedToolCallIds??[]],lastStopReason:r.lastStopReason,replayMessages:[...r.replayMessages??[]]}}function Eo(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 dn(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 pn(r){let e=[],t=Co(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=Ao(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=Mo(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:Id({maxRounds:r.maxRounds,round:r.round,lastStopReason:r.lastStopReason,replayMessages:o,pendingToolCallIds:Md(o),completedToolCallIds:Pd(o)}),recoveryActions:e}}var Vs=q(()=>{"use strict";Io()});function Oo(r){return r?Ed.has(r):!0}function Lo(r){return r===429||r===529}function mn(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 $o(){let r=process.env.QLOGICAGENT_PERSISTENT_RETRY;return r==="1"||r==="true"}var Ed,Gk,_t,qs=q(()=>{"use strict";Ed=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);Gk={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};_t=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Do(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 Uo=q(()=>{"use strict"});function No(r){return Fd.find(e=>e.name===r)}var Od,Ld,$d,Dd,Ud,Nd,Fd,Fo=q(()=>{"use strict";Od={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},Ld={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},$d={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","todo","tool_search"],canFork:!1},Dd={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Ud={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},Nd={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},Fd=[Od,Ld,$d,Dd,Ud,Nd]});var Ks=q(()=>{"use strict"});function jo(r){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:r.maxOutputTokens,consecutiveTruncations:0,aborted:r.abortSignal?.aborted??!1}}function Bo(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 Wo(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 Go(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 Ho(r,e){return r.aborted?!0:e.abortSignal?.aborted?(r.aborted=!0,!0):!1}var Js=q(()=>{"use strict"});function zo(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function ut(r,e=jd){return!(r.attemptedThisTurn||r.consecutiveFailures>=e.maxConsecutiveFailures)}var jd,Ys=q(()=>{"use strict";jd={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var Ct=q(()=>{"use strict";_s();$s();vo();vo();Bs();Ws();Hs();Io();Vs();qs();Uo();Fo();Ks();Js();Ys()});function Vo(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 qo=q(()=>{"use strict"});var Xs,Qs,Zs,ei,ti,ni,oi,ri,si,ii,At,ai,li,Ko,gn=q(()=>{"use strict";Xs=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Qs=3,Zs=128e3,ei=13e3,ti=16384,ni=65536,oi=3,ri=65536,si=3e4,ii=3,At=5,ai=5e4,li=2e5,Ko=2e3});import{mkdir as Wd,writeFile as Gd}from"fs/promises";import{join as ci}from"path";import{tmpdir as Hd}from"os";function di(){return{seenIds:new Set,replacements:new Map}}function pi(r){return ci(Hd(),"qlogicagent-sessions",r,zd)}async function qd(r){try{await Wd(pi(r),{recursive:!0})}catch{}}function Kd(r,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return ci(pi(r),`${t}.txt`)}function Jd(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 mi(r){return r.includes(ui)}async function gi(r,e,t){await qd(t);let n=Kd(t,e);try{await Gd(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:o,hasMore:s}=Jd(r,Ko);return{filepath:n,originalSize:r.length,preview:o,hasMore:s}}function fi(r){let e=`${ui}
14
+ ${f}`},T=[...o,...d,b,...m],w=Date.now()-n,_=T.reduce((y,C)=>y+this.config.estimateTokens(C),0);return{messages:T,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:_,compressionRatio:i>0?_/i:1,latencyMs:w,usedLlm:!0,cacheInvalidated:!0}}}},vt=class{config;constructor(e){this.config=e}compress(e,t){let n=un(e),o=this.config.inner.compress(e,t),s=un(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=un(e),o=_t(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=un(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}}}},Ks={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};xt=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}},St=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}))}};Ld=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),Fe=class{constructor(e=20,t=_o){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,l)=>{if(l>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!Ld.has(a.name)||a.content.length<=200)return a;let u=this.estimateTokens(a);return s+=u,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 Mo(){return{stages:[]}}function Po(r,e,t){let n=t?.thresholdMessages??40;if(r.filter(a=>a.role!=="system").length<=n)return{messages:r,stagedCount:0};let s=Js(r,e),i=Dd(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Js(r,e),{messages:s,stagedCount:i.length}}function Io(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:Ys(r,e),committed:t}}function Js(r,e){return e.stages.filter(n=>n.committed).length===0?r:Ys(r,e)}function Ys(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),l={role:"system",content:o.summary};n.splice(s,a-s,l)}return n}function Dd(r,e,t){let n=Math.max(0,r.length-Math.floor(t/2)),o=[],s=new Set(e.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<n;l++){let u=r[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||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 l=`${i}-${i+a}`;s.has(l)||o.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return o}var Xs=K(()=>{"use strict"});function Ud(r){return!(!r.ok||r.existingSkillName||!r.multiStep||r.toolCallCount<3||r.distinctToolCount<2)}function Nd(r){return r.existingSkillName?r.feedback==="negative":!1}function pn(r,e){return Nd(r)?{type:"skill.improve",skillName:r.existingSkillName,reason:"negative user feedback on existing skill execution"}:Ud(r)?{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 Qs=K(()=>{"use strict"});function Zs(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 Fd(r){return r==="enabled-eligible"||r==="installed-awaiting-approval"}function jd(r){return new Map((r??[]).map(e=>[e.toolName,e]))}function Bd(r){if(!r.eligibility?.length)return[...r.tools];let e=jd(r.eligibility);return r.tools.filter(t=>{let n=Zs(t);if(!n)return!1;let o=e.get(n);return!o||Fd(o.status)})}function Wd(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 Eo(r){let e=Wd({toolChoice:r.toolChoice,thinkingEnabled:r.thinkingEnabled,compatibility:r.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],o=Bd({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(l=>Zs(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:o,normalizedToolChoice:t,warnings:n}}var ei=K(()=>{"use strict"});function ti(r){return r==null?[]:typeof r=="string"?r.length>0?[{type:"text",text:r}]:[]:Array.isArray(r)?r:[{type:"text",text:String(r)}]}function Vd(r,e){return{...r,content:[...ti(r.content),...ti(e.content)]}}function zd(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 qd(r){return new Set((r??Gd).map(e=>e.trim().toLowerCase()))}function Kd(r,e){return r?qd(e).has(r.trim().toLowerCase()):!1}function Oo(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 l=a.tool_calls.filter(u=>zd(u));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),t=new Set;for(let a of e)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let l of a.tool_calls)typeof l.id=="string"&&l.id&&t.add(l.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),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 l=a.tool_calls.filter(u=>typeof u.id=="string"&&o.has(u.id));if(l.length===0){let{tool_calls:u,...c}=a;c.content!=null&&c.content!==""&&s.push(c);continue}if(l.length<a.tool_calls.length){s.push({...a,tool_calls:l});continue}}s.push(a)}let i=[];for(let a of s){let l=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){i[i.length-1]=Vd(l,a);continue}i.push(a)}return i}function Lo(r,e){return Kd(e?.stopReason,e?.forcedStopReasons)?r.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let o of Hd)delete n[o];return n}):[...r]}function $o(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 Do(r,e){let t=Oo(r),n=Lo(t,e);return $o(n,e)}var Gd,Hd,Uo=K(()=>{"use strict";Gd=["stop","aborted","timeout","cancelled","interrupted","error"],Hd=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Jd(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 Yd(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 Xd(r){return{round:r.round??0,maxRounds:r.maxRounds,pendingToolCallIds:[...r.pendingToolCallIds??[]],completedToolCallIds:[...r.completedToolCallIds??[]],lastStopReason:r.lastStopReason,replayMessages:[...r.replayMessages??[]]}}function No(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 mn(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 gn(r){let e=[],t=Oo(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=Lo(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=$o(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:Xd({maxRounds:r.maxRounds,round:r.round,lastStopReason:r.lastStopReason,replayMessages:o,pendingToolCallIds:Jd(o),completedToolCallIds:Yd(o)}),recoveryActions:e}}var ni=K(()=>{"use strict";Uo()});function Fo(r){return r?Qd.has(r):!0}function jo(r){return r===429||r===529}function fn(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 Bo(){let r=process.env.QLOGICAGENT_PERSISTENT_RETRY;return r==="1"||r==="true"}var Qd,AT,Ct,oi=K(()=>{"use strict";Qd=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);AT={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};Ct=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Wo(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 Go=K(()=>{"use strict"});function Ho(r){return sp.find(e=>e.name===r)}var Zd,ep,tp,np,op,rp,sp,Vo=K(()=>{"use strict";Zd={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},ep={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},tp={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","todo","tool_search"],canFork:!1},np={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},op={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},rp={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},sp=[Zd,ep,tp,np,op,rp]});var ri=K(()=>{"use strict"});function zo(r){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:r.maxOutputTokens,consecutiveTruncations:0,aborted:r.abortSignal?.aborted??!1}}function qo(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 Ko(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 Jo(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 Yo(r,e){return r.aborted?!0:e.abortSignal?.aborted?(r.aborted=!0,!0):!1}var si=K(()=>{"use strict"});function Xo(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function ut(r,e=ip){return!(r.attemptedThisTurn||r.consecutiveFailures>=e.maxConsecutiveFailures)}var ip,ii=K(()=>{"use strict";ip={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var At=K(()=>{"use strict";Ds();Vs();Ao();Ao();Xs();Qs();ei();Uo();ni();oi();Go();Vo();ri();si();ii()});function Qo(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 Zo=K(()=>{"use strict"});var ai,li,ci,ui,di,pi,mi,gi,fi,hi,Mt,er,yi,bi,ki,tr,hn=K(()=>{"use strict";ai=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),li=3,ci=128e3,ui=13e3,di=16384,pi=65536,mi=3,gi=65536,fi=3e4,hi=3,Mt=10,er=500,yi=3,bi=5e4,ki=2e5,tr=2e3});import{mkdir as lp,writeFile as cp}from"fs/promises";import{join as Ti}from"path";import{tmpdir as up}from"os";function vi(){return{seenIds:new Set,replacements:new Map}}function xi(r){return Ti(up(),"qlogicagent-sessions",r,dp)}async function mp(r){try{await lp(xi(r),{recursive:!0})}catch{}}function gp(r,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Ti(xi(r),`${t}.txt`)}function fp(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 Si(r){return r.includes(wi)}async function _i(r,e,t){await mp(t);let n=gp(t,e);try{await cp(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:o,hasMore:s}=fp(r,tr);return{filepath:n,originalSize:r.length,preview:o,hasMore:s}}function Ri(r){let e=`${wi}
16
16
  `;return e+=`Output too large (${r.originalSize} chars). Full output saved to: ${r.filepath}
17
17
 
18
- `,e+=`Preview (first ${Ko} bytes):
18
+ `,e+=`Preview (first ${tr} bytes):
19
19
  `,e+=r.preview,e+=r.hasMore?`
20
20
  ...
21
21
  `:`
22
- `,e+=Vd,e}async function hi(r,e,t,n=ai){if(r.length<=n||mi(r))return r;let o=await gi(r,e,t);return o?fi(o):r.slice(0,n)+`
23
- ...[truncated ${r.length-n} chars]`}function Yd(r){let e=[],t=[];for(let n of r)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?mi(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 Xd(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 Qd(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 yi(r,e,t,n=li){let o=Yd(r);if(o.length===0)return{messages:r,newlyReplacedCount:0};let s=new Map,i=[];for(let c of o){let{mustReapply:d,frozen:p,fresh:m}=Xd(c,e);for(let k of d)s.set(k.toolCallId,k.replacement);if(m.length===0){for(let k of c)e.seenIds.add(k.toolCallId);continue}let g=p.reduce((k,x)=>k+x.size,0),f=m.reduce((k,x)=>k+x.size,0),b=g+f>n?Qd(m,g,n):[],h=new Set(b.map(k=>k.toolCallId));for(let k of c)h.has(k.toolCallId)||e.seenIds.add(k.toolCallId);b.length>0&&i.push(...b)}if(s.size===0&&i.length===0)return{messages:r,newlyReplacedCount:0};let a=await Promise.all(i.map(async c=>{let d=await gi(c.content,c.toolCallId,t);return{candidate:c,result:d}})),l=0;for(let{candidate:c,result:d}of a){if(e.seenIds.add(c.toolCallId),!d)continue;let p=fi(d);s.set(c.toolCallId,p),e.replacements.set(c.toolCallId,p),l++}return s.size===0?{messages:r,newlyReplacedCount:0}:{messages:r.map(c=>{if(c.role!=="tool"||!c.tool_call_id)return c;let d=s.get(c.tool_call_id);return d===void 0?c:{...c,content:d}}),newlyReplacedCount:l}}var zd,ui,Vd,Jo=q(()=>{"use strict";gn();zd="tool-results",ui="<persisted-output>",Vd="</persisted-output>"});function tp(r){try{return JSON.parse(r)}catch{return}}var Zd,ep,fn,bi=q(()=>{"use strict";Ct();Jo();Zd=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),ep=new Set(["bash","execute_command","Bash","shell"]),fn=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??Zd,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:kt(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:l,log:u}=this.config,c=e.toolCall.function.name,d=!1,p=e.toolCall.function.arguments;if(i)try{let k=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:c,arguments:tp(p)});if(k.action==="abort"){let x=k.reason??"blocked by policy";u.info(`tool ${c} blocked: ${x}`),e.results.push({callId:e.id,toolName:c,ok:!1,error:x,blocked:!0,blockReason:x,message:kt(e.id,{ok:!1,error:x})}),e.status="completed";return}k.action==="continue"&&k.context?.arguments&&(p=JSON.stringify(k.context.arguments))}catch{}let m=await s.invoke(l,c,p,this.siblingAbortController.signal),g=this.getAbortReason();if(g&&!d){e.results.push(this.createSyntheticError(e,g)),e.status="completed";return}let f=!m.error,b=m.result;f&&b&&b.length>5e4&&(b=await hi(b,e.id,a));let h=kt(e.id,{ok:f,payload:b,error:m.error});f||(d=!0,ep.has(c)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(f?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:l,callId:e.id,toolName:c,ok:f,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:c,ok:f,error:m.error,message:h}),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 np}from"node:fs/promises";function Xe(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function Qe(r){let e=0;for(let t of r)e+=Xe(t);return e}function wi(r){if(!r)return 128e3;if(r in Yo)return Yo[r];let e=r.toLowerCase();for(let[t,n]of Object.entries(Yo))if(e.startsWith(t.toLowerCase()))return n;return 128e3}function rp(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"),Xo(t);try{let i="",a=e?.model??op;for await(let l 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)))l.type==="delta"&&(i+=l.text);return i||(r.warn("[context-compression] empty summary response"),Xo(t))}catch(i){return r.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),Xo(t)}}}function Xo(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+=pp,e}async function Ci(r,e,t,n=bi){if(r.length<=n||Si(r))return r;let o=await _i(r,e,t);return o?Ri(o):r.slice(0,n)+`
23
+ ...[truncated ${r.length-n} chars]`}function hp(r){let e=[],t=[];for(let n of r)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?Si(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 yp(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 bp(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 Ai(r,e,t,n=ki){let o=hp(r);if(o.length===0)return{messages:r,newlyReplacedCount:0};let s=new Map,i=[];for(let c of o){let{mustReapply:d,frozen:p,fresh:m}=yp(c,e);for(let w of d)s.set(w.toolCallId,w.replacement);if(m.length===0){for(let w of c)e.seenIds.add(w.toolCallId);continue}let g=p.reduce((w,_)=>w+_.size,0),f=m.reduce((w,_)=>w+_.size,0),b=g+f>n?bp(m,g,n):[],T=new Set(b.map(w=>w.toolCallId));for(let w of c)T.has(w.toolCallId)||e.seenIds.add(w.toolCallId);b.length>0&&i.push(...b)}if(s.size===0&&i.length===0)return{messages:r,newlyReplacedCount:0};let a=await Promise.all(i.map(async c=>{let d=await _i(c.content,c.toolCallId,t);return{candidate:c,result:d}})),l=0;for(let{candidate:c,result:d}of a){if(e.seenIds.add(c.toolCallId),!d)continue;let p=Ri(d);s.set(c.toolCallId,p),e.replacements.set(c.toolCallId,p),l++}return s.size===0?{messages:r,newlyReplacedCount:0}:{messages:r.map(c=>{if(c.role!=="tool"||!c.tool_call_id)return c;let d=s.get(c.tool_call_id);return d===void 0?c:{...c,content:d}}),newlyReplacedCount:l}}var dp,wi,pp,nr=K(()=>{"use strict";hn();dp="tool-results",wi="<persisted-output>",pp="</persisted-output>"});function wp(r){try{return JSON.parse(r)}catch{return}}var kp,Tp,yn,Mi=K(()=>{"use strict";At();nr();kp=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),Tp=new Set(["bash","execute_command","Bash","shell"]),yn=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??kp,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:Tt(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:l,log:u}=this.config,c=e.toolCall.function.name,d=!1,p=e.toolCall.function.arguments;if(i)try{let w=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:c,arguments:wp(p)});if(w.action==="abort"){let _=w.reason??"blocked by policy";u.info(`tool ${c} blocked: ${_}`),e.results.push({callId:e.id,toolName:c,ok:!1,error:_,blocked:!0,blockReason:_,message:Tt(e.id,{ok:!1,error:_})}),e.status="completed";return}w.action==="continue"&&w.context?.arguments&&(p=JSON.stringify(w.context.arguments))}catch{}let m=await s.invoke(l,c,p,this.siblingAbortController.signal),g=this.getAbortReason();if(g&&!d){e.results.push(this.createSyntheticError(e,g)),e.status="completed";return}let f=!m.error,b=m.result;f&&b&&b.length>5e4&&(b=await Ci(b,e.id,a));let T=Tt(e.id,{ok:f,payload:b,error:m.error,toolReferences:m.toolReferences});f||(d=!0,Tp.has(c)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(f?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:l,callId:e.id,toolName:c,ok:f,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:c,ok:f,error:m.error,message:T}),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 vp}from"node:fs/promises";function Xe(r){let e=typeof r.content=="string"?r.content:r.content!=null?JSON.stringify(r.content):"";return Math.ceil(e.length/4)}function Qe(r){let e=0;for(let t of r)e+=Xe(t);return e}function Ei(r){if(!r)return 128e3;if(r in or)return or[r];let e=r.toLowerCase();for(let[t,n]of Object.entries(or))if(e.startsWith(t.toLowerCase()))return n;return 128e3}function Sp(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"),rr(t);try{let i="",a=e?.model??xp;for await(let l 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)))l.type==="delta"&&(i+=l.text);return i||(r.warn("[context-compression] empty summary response"),rr(t))}catch(i){return r.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),rr(t)}}}function rr(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 sp(){return yo(new Ye(Qo),new Ne(20,Xe),new ct(Xe))}function Ti(r,e){let t=bo(new Ye(Qo),new Ne(20,Xe),new Tt({protectedHeadExchanges:1,protectedTailMessages:8,summarize:r,estimateTokens:Xe}),new ct(Xe));return new wt({inner:t,estimateTokens:Xe,onCacheInvalidated:e?.onCacheInvalidated})}function xi(r,e){let t=e?.budget??cn({modelContextWindow:wi(e?.model)}),o=(e?.pipeline??sp()).compress(r,t);if(o.droppedCount>0){let s=Qe(r),i=Qe(o.messages);vi.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:Rt(s,t)})}return o.droppedCount>0&&Zo?.(o.droppedCount,Qe(o.messages)),o}async function ip(r,e,t){let n=t??cn({modelContextWindow:wi(e.model)}),o=Qe(r),s=Rt(o,n),i;switch(s){case"none":i={messages:r,droppedCount:0,strategy:"none"};break;case"trim-only":i=new Ye(Qo).compress(r,n);break;case"sliding-window":{i=await Ti(e.summarize).compressAsync(r,n);break}case"llm-summarize":{let a=e.pipeline??Ti(e.summarize);i=St(a)?await a.compressAsync(r,n):a.compress(r,n);break}}return i.droppedCount>0&&(i={...i,messages:await To(i.messages,r,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await np(a,"utf-8")}catch{return null}}})}),ap(r,i,n),i}function ap(r,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||Qe(r),o=e.metrics?.tokensAfter||Qe(e.messages);vi.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:Rt(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||Qe(e.messages);Zo?.(e.droppedCount,n)}}function lp(r,e){let t=rp(r,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(o,s,i){return ip(o,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};ki.register(n),ki.activate(n.id),r.info(`[context-compression] registered context engine: ${n.id}`)}function Si(r,e,t){lp(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"}}}),Zo=(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 Yo,Qo,op,vi,ki,Zo,er=q(()=>{"use strict";Ct();Yo={"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};Qo=8e3,op="deepseek-v4-flash",vi=new vt(200),ki=new xt;Zo=null});function Ri(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 _i=q(()=>{"use strict"});var Ci={};Rs(Ci,{resolveToolEligibility:()=>mp});function up(r,e){if(cp.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 dp(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||up(t,e.dangerousPatterns)?(o.push("dangerous_tool"),{level:3,reasons:o}):{level:2,reasons:o}}function pp(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 mp(r,e={}){let t=new Map,n=[],o=[],s=[];for(let i of r){let a=i.function.name,{level:l,reasons:u}=dp(i,e),c=pp(l),d={toolName:a,status:c,permissionLevel:l,approvalRequired:l===4,reasonCodes:u};t.set(a,d),l===5?o.push(d):(n.push(i),l===4&&s.push(d))}return{eligibleTools:n,blockedTools:o,approvalRequiredTools:s,eligibilityByName:t}}var cp,Ai=q(()=>{"use strict";cp=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function hp(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 yp(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 bp(r){return typeof r=="number"&&Number.isFinite(r)&&r>=1?Math.min(Math.round(r),100):Xs}function Mi(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 kp(r){return r==="length"||r==="max_tokens"}function Pi(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 Tp(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 wp(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 vp(r){return r.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Ii(r,e,t,n){let{turnId:o,sessionId:s,messages:i,tools:a,model:l,apiKey:u,temperature:c,hooks:d,signal:p}=r,m={sessionId:s,turnId:o},g=r.maxTurns??0,f=r.querySource,{resolveToolEligibility:b}=await Promise.resolve().then(()=>(Ai(),Ci)),h=b(a,r.toolEligibilityContext),k=h.eligibleTools;for(let z of h.blockedTools)yield{type:"tool_blocked",turnId:o,callId:"",name:z.toolName,reason:"blocked-by-policy"};if(!k.length){yield*xp(o,l,i,u,c,p,e,n);return}let x=bp(r.maxRounds),R={contextWindowTokens:r.contextWindowTokens??Zs,responseBufferTokens:ei,maxOutputTokens:r.maxOutputTokens??ti,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},E=new Set,F=0,U=k,D,w={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:jo(R),reactiveCompactState:zo(),toolLoopState:pn({maxRounds:x,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:xo(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:di(),budgetContinuationCount:0},ge=Math.max(g*5,200),H=0;for(;;){if(H++,H>ge){n.info(`hard iteration cap reached (${ge}), forcing completion`);let S=w.finalText||tr(w.messages,n);yield{type:"end",turnId:o,content:S,usage:w.totalUsage,model:w.currentModel};return}let{messages:z,maxOutputTokensRecoveryCount:fe,hasAttemptedReactiveCompact:te,maxOutputTokensOverride:le,turnCount:G,guardState:N,reactiveCompactState:pe,collapseStore:Ee}=w,{toolLoopState:me}=w;if(D){try{let S=await D;S&&(yield{type:"tool_use_summary",turnId:o,summary:S})}catch{}D=void 0}if(r.refreshTools&&G>1){let S=r.refreshTools();S!==U&&(U=S,n.debug(`tools refreshed: ${S.length} tools`))}if(Ho(N,R)){n.info(`turn aborted by guard at turn ${G}`),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED",usage:w.totalUsage};return}let y=Bo(N,R);if(y.level==="blocking"){y.reason==="prompt_too_long"&&ut(pe)&&(pe.attemptedThisTurn=!0,N.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${y.reason}), reactive compact needed`),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${y.reason}), ending tool loop`);break}y.level==="warning"&&n.info(`token budget warning: ${y.usagePercent}% used, ${y.remainingTokens} remaining`);let T;{let S=await yi(z,w.contentReplacementState,s);T=S.messages,S.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${S.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:o,action:"tool_result_budget",detail:`${S.newlyReplacedCount} persisted`})}{let S=wo(T,w.snipRemovedIds);T=S.messages,S.removedCount>0&&(n.info(`snip: removed ${S.removedCount} messages, freed ~${S.tokensFreed} tokens`),yield{type:"recovery",turnId:o,action:"snip",detail:`${S.removedCount} messages`})}{let A=new Ne().compress(T,0);A.droppedCount>0&&(T=A.messages,n.info(`microcompact: cleared ${A.droppedCount} old tool results`))}if(T=So(T,Ee).messages,N.promptTokens>0){let S=xi(T,{budget:R.contextWindowTokens*.75,model:w.currentModel});S.droppedCount>0&&(T=S.messages,n.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield{type:"recovery",turnId:o,action:"autocompact",detail:`${S.strategy}: ${S.droppedCount} dropped`},w.hasAttemptedReactiveCompact=!1,d?.invoke("context.after_compact",{...m,removedCount:S.droppedCount}).catch(()=>{}))}T=vp(T);let v=_o({tools:U,toolChoice:r.toolChoice??"auto"}),_=pn({maxRounds:x,replayMessages:T,lastStopReason:me.lastStopReason,options:{stopReason:me.lastStopReason}}),C=v.extraSystemPrompt?[{role:"system",content:v.extraSystemPrompt},..._.state.replayMessages]:_.state.replayMessages;me=_.state,_.recoveryActions.length>0&&n.debug(`tool loop recovery: ${_.recoveryActions.map(S=>S.detail??S.kind).join("; ")}`),n.debug(`turn ${G}, messages: ${C.length}`),d?.invoke("turn.before_inference",{...m,model:w.currentModel}).catch(()=>{});let I=!1,V=[],j=new Map,re="stop",X,P=null,se=!1,ie=[],we=[];try{for await(let S of e.stream({model:w.currentModel,messages:C,tools:v.tools,toolChoice:v.normalizedToolChoice??"auto",temperature:c,maxTokens:(le??N.currentMaxOutputTokens)||void 0,streamRequired:r.streamRequired,previousResponseId:w.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},u,p))switch(S.type){case"delta":V.push(S.text),I||(yield{type:"delta",turnId:o,text:S.text});break;case"tool_call_delta":I=!0,Vo(j,S);break;case"reasoning_delta":ie.push(S.text);break;case"reasoning_block_complete":S.signature&&we.push({thinking:ie.join(""),signature:S.signature}),ie.length=0;break;case"usage":X={prompt:S.promptTokens,completion:S.completionTokens,reasoning:S.reasoningTokens,cacheRead:S.cacheReadTokens,cacheCreation:S.cacheCreationTokens};break;case"response_id":w.lastResponseId=S.id;break;case"annotations":yield{type:"annotations",turnId:o,annotations:S.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:o,message:`${S.toolType}: ${S.event}`};break;case"done":re=S.finishReason;break}if(I||d?.invoke("turn.after_inference",{...m,model:w.currentModel}).catch(()=>{}),r.postSamplingHooks&&r.postSamplingHooks.length>0){let S=w.currentModel;for(let A of r.postSamplingHooks)try{A({messages:[...T],model:S,sessionId:s})}catch{}}}catch(S){if(S instanceof _t&&r.fallbackModel){n.info(`model fallback triggered: ${S.originalModel} \u2192 ${S.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`${S.originalModel} \u2192 ${S.fallbackModel}`},w={...w,currentModel:S.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let A=S instanceof Error?S.message:String(S),O=typeof S?.status=="number"?S.status:void 0;if(!O&&A&&(A.includes("ECONNRESET")||A.includes("EPIPE"))){let ne=(w.consecutiveApiRetries??0)+1;if(ne>At){n.info(`stale connection retry limit reached (${At}), aborting`),yield{type:"error",turnId:o,error:A,code:"RETRIES_EXHAUSTED",usage:w.totalUsage};return}n.info(`stale connection (${A.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:o,action:"stale_connection_retry",detail:A.slice(0,80)},w={...w,consecutiveApiRetries:ne,transition:void 0};continue}let Y=wp({status:O,message:A});if(Y!==null){n.info(`max_tokens overflow: adjusting to ${Y}`),N.currentMaxOutputTokens=Y,w={...w,maxOutputTokensOverride:Y,transition:void 0};continue}if(Lo(O)){if(w.consecutive529Errors++,w.consecutive529Errors>=ii&&r.fallbackModel&&w.currentModel!==r.fallbackModel){n.info(`529 \xD7 ${w.consecutive529Errors}: triggering fallback to ${r.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`529 \xD7 ${w.consecutive529Errors}`},w={...w,currentModel:r.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if($o()){let ne=mn(w.consecutive529Errors);n.info(`persistent retry: waiting ${ne}ms (attempt ${w.consecutive529Errors})`);let K=ne;for(;K>0;){if(p?.aborted){yield{type:"error",turnId:o,error:"Aborted during retry wait",code:"ABORTED",usage:w.totalUsage};return}yield{type:"heartbeat",turnId:o,message:`Retrying in ${Math.ceil(K/1e3)}s (${O})`};let he=Math.min(K,si);await new Promise(Ou=>setTimeout(Ou,he)),K-=he}w={...w,transition:void 0};continue}if(Oo(f)){let K=Tp({status:O,message:A})??mn(w.consecutive529Errors);n.info(`transient ${O}: retry in ${K}ms`),yield{type:"recovery",turnId:o,action:"retry",detail:`${O} retry in ${K}ms`},await new Promise(he=>setTimeout(he,K)),w={...w,transition:void 0};continue}n.info(`background source ${f}: not retrying ${O}`)}P={status:O,message:A}}if(P&&d?.invoke("turn.after_inference",{...m,model:w.currentModel,response:{error:P.message}}).catch(()=>{}),P)if(Mi(P))se=!0,n.info(`withheld prompt_too_long error (status=${P.status})`);else if(Pi(P))se=!0,n.info(`withheld media_size error (status=${P.status})`);else{let S=Wo({status:P.status??500,message:P.message},N,R);if(S.action==="reactive_compact"&&ut(pe)&&(pe.attemptedThisTurn=!0,N.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:o,action:"reactive_compact",detail:`API ${P.status??500}: ${P.message}`}),S.action==="retry"){let O=(w.consecutiveApiRetries??0)+1;if(O>At){n.info(`API retry limit reached (${At}), aborting`);let Y=lt(P.status,P.message);yield{type:"error",turnId:o,error:P.message,code:Y,usage:w.totalUsage};return}yield{type:"recovery",turnId:o,action:"retry",detail:S.reason},w={...w,consecutiveApiRetries:O,transition:void 0};continue}let A=lt(P.status,P.message);d?.invoke("stop.failure",{sessionId:s,reason:A,error:P.message}).catch(()=>{}),yield{type:"error",turnId:o,error:P.message,code:A,usage:w.totalUsage};return}X&&(w.totalUsage.prompt+=X.prompt,w.totalUsage.completion+=X.completion,X.reasoning&&(w.totalUsage.reasoning=(w.totalUsage.reasoning??0)+X.reasoning),X.cacheRead&&(w.totalUsage.cacheRead=(w.totalUsage.cacheRead??0)+X.cacheRead),X.cacheCreation&&(w.totalUsage.cacheCreation=(w.totalUsage.cacheCreation??0)+X.cacheCreation)),X?.prompt&&(N.promptTokens=X.prompt);let an=V.join("");an&&(w.finalText=an);let Oe=[...j.values()].map(S=>({id:S.id||`tc_${o}_${G}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:S.name,arguments:S.arguments}}));if(Oe.length===0&&!I){if(se&&P&&Mi(P)){if(w.transition?.reason!=="collapse_drain_retry"){let A=Ro(T,Ee);if(A.committed>0){n.info(`collapse drain: committed ${A.committed} stages`),yield{type:"recovery",turnId:o,action:"collapse_drain",detail:`${A.committed} stages committed`},w={...w,messages:A.messages,transition:{reason:"collapse_drain_retry",committed:A.committed}};continue}}if(ut(pe)){pe.attemptedThisTurn=!0,N.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"withheld prompt_too_long"},w={...w,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),d?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:P.message}).catch(()=>{}),yield{type:"error",turnId:o,error:P.message,code:"PROMPT_TOO_LONG",usage:w.totalUsage};return}if(se&&P&&Pi(P)){if(ut(pe)){pe.attemptedThisTurn=!0,N.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"media error strip-retry"},w={...w,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),d?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:P.message}).catch(()=>{}),yield{type:"error",turnId:o,error:P.message,code:"IMAGE_ERROR",usage:w.totalUsage};return}if(kp(re)){N.consecutiveTruncations+=1;let A=r.modelMaxOutputTokens??ni,O=Go(N,R,A);if(O.shouldEscalate&&le===void 0){N.currentMaxOutputTokens=O.newMax,n.info(`max_output_tokens escalate: ${O.newMax} tokens`),yield{type:"recovery",turnId:o,action:"output_escalation",detail:`${O.newMax} tokens`},w={...w,maxOutputTokensOverride:ri,transition:{reason:"max_output_tokens_escalate"}};continue}if(fe<oi){let Y={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${fe+1}`),yield{type:"recovery",turnId:o,action:"max_output_tokens_recovery",detail:`attempt ${fe+1}`},w={...w,messages:[...T,Y],maxOutputTokensRecoveryCount:fe+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:fe+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else N.consecutiveTruncations=0;if(me=dn(me,{replayMessages:z,lastStopReason:"completed"}),d){let A=await d.invoke("stop",{sessionId:s,reason:"completed"});if(A.action==="prevent"){n.info(`stop hook prevented continuation: ${A.reason??"no reason"}`),yield{type:"end",turnId:o,content:w.finalText,usage:w.totalUsage,model:w.currentModel};return}if(A.action==="abort"){let O=A.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${O}`);let Y={role:"user",content:O},ne={role:"assistant",content:w.finalText,...we.length>0&&{thinkingBlocks:[...we]}};w={...w,messages:[...z,ne,Y],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(r.tokenBudget&&r.tokenBudget>0&&w.budgetContinuationCount<5){let A=w.totalUsage.prompt+w.totalUsage.completion+(w.totalUsage.reasoning??0),O=A/r.tokenBudget*100;if(O<90){let Y=w.budgetContinuationCount+1,ne={role:"user",content:Ri(O,A,r.tokenBudget)};n.info(`token budget continuation #${Y}: ${Math.round(O)}% used`),yield{type:"recovery",turnId:o,action:"budget_continuation",detail:`${Math.round(O)}% used (#${Y})`};let K={role:"assistant",content:w.finalText,...we.length>0&&{thinkingBlocks:[...we]}};w={...w,messages:[...z,K,ne],budgetContinuationCount:Y,transition:{reason:"token_budget_continuation"}};continue}}if(F>0){let A={ok:!0,toolCallCount:F,distinctToolCount:E.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},O=un(A,{tools:[...E]});O&&(yield{type:"skill_instruction",turnId:o,instruction:O})}yield{type:"end",turnId:o,content:w.finalText,usage:w.totalUsage,model:w.currentModel};return}for(let S of Oe){let A=S.function.arguments,O=U.find(Y=>Y.function.name===S.function.name);if(O?.backfillObservableInput)try{let Y=JSON.parse(S.function.arguments),ne={...Y};O.backfillObservableInput(ne),Object.keys(ne).some(he=>!(he in Y))&&(A=JSON.stringify(ne))}catch{}yield{type:"tool_call",turnId:o,callId:S.id,name:S.function.name,arguments:A}}let Iu=we.length===0&&ie.length>0?ie.join(""):void 0;z.push(go(Oe,w.finalText||void 0,we.length>0?we:void 0,Iu)),me=Eo(me,{replayMessages:z,pendingToolCallIds:Oe.map(S=>S.id),completedToolCallIds:me.completedToolCallIds,lastStopReason:"tool_calls"});let xs=[];try{let S=new fn({toolInvoker:t,hooks:d,sessionId:s,turnId:o,log:n,signal:p,maxConcurrentTools:r?.maxConcurrentTools});for(let A of Oe)S.addTool(A);for await(let A of S.getRemainingResults()){A.blocked&&(yield{type:"tool_blocked",turnId:o,callId:A.callId,name:A.toolName,reason:A.blockReason??"blocked"}),z.push(A.message),xs.push(A.callId),E.add(A.toolName),F++;let O=typeof A.message?.content=="string"?A.message.content:"",Y=A.ok&&O?O.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:o,callId:A.callId,name:A.toolName,ok:A.ok,error:A.error,outputPreview:Y},A.ok){let ne=Oe.find(K=>K.id===A.callId);if(ne){if(A.toolName==="plan_mode")try{let K=JSON.parse(ne.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(fp.has(A.toolName))try{let K=JSON.parse(ne.function.arguments),he=typeof K.file_path=="string"?K.file_path:typeof K.filePath=="string"?K.filePath:typeof K.path=="string"?K.path:void 0;he&&(yield{type:"artifact",turnId:o,artifactId:`artifact-${A.callId}`,artifactType:hp(he),title:he.split(/[\\/]/).pop()||he,filePath:he,language:yp(he)})}catch{}}}}}catch(S){let A=S instanceof Error?S.message:String(S);yield{type:"error",turnId:o,error:A,code:"TOOL_EXECUTION_ERROR",usage:w.totalUsage};return}if(me=dn(me,{replayMessages:z,completedToolCallIds:[...me.completedToolCallIds,...xs],lastStopReason:"tool_calls"}),r.generateToolUseSummary&&Oe.length>0){let S=Oe.map(A=>({name:A.function.name,arguments:A.function.arguments}));D=r.generateToolUseSummary(S).catch(()=>null)}let Ss=z.slice(-Oe.length),Eu=Ss.length>0&&Ss.every(S=>{let A=S?.content;return typeof A!="string"?!1:A.startsWith("Error: ")}),bt=w.consecutiveFailedRounds;if(Eu){if(bt+=1,bt>=Qs&&w.finalText){n.info(`early exit: ${bt} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:o,content:w.finalText,usage:w.totalUsage,model:w.currentModel};return}}else bt=0;let po=G+1;if(g>0&&po>g){if(n.info(`max turns reached (${g}), completing`),d){let A=await d.invoke("stop",{sessionId:s,reason:"max_turns"});if(A.action==="abort"){let O=A.reason??"Stop hook requested continuation after max_turns",Y={role:"assistant",content:w.finalText,...we.length>0&&{thinkingBlocks:[...we]}};w={...w,messages:[...z,Y,{role:"user",content:O}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let S=w.finalText||tr(z,n);yield{type:"end",turnId:o,content:S,usage:w.totalUsage,model:w.currentModel};return}if(po>x){if(n.info(`tool loop budget exhausted (${x} rounds), returning`),F>0){let A={ok:!0,toolCallCount:F,distinctToolCount:E.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},O=un(A,{tools:[...E]});O&&(yield{type:"skill_instruction",turnId:o,instruction:O})}let S=w.finalText||tr(z,n);yield{type:"end",turnId:o,content:S,usage:w.totalUsage,model:w.currentModel};return}w={messages:z,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:po,transition:{reason:"next_turn"},guardState:N,reactiveCompactState:pe,toolLoopState:me,consecutiveFailedRounds:bt,finalText:w.finalText,totalUsage:w.totalUsage,collapseStore:Ee,currentModel:w.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:w.stopHookActive,lastResponseId:w.lastResponseId,snipRemovedIds:w.snipRemovedIds,contentReplacementState:w.contentReplacementState,budgetContinuationCount:0}}}function tr(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 _p(){return xo(new Ye(sr),new Fe(20,Xe),new ct(Xe))}function Ii(r,e){let t=So(new Ye(sr),new Fe(20,Xe),new wt({protectedHeadExchanges:1,protectedTailMessages:8,summarize:r,estimateTokens:Xe}),new ct(Xe));return new vt({inner:t,estimateTokens:Xe,onCacheInvalidated:e?.onCacheInvalidated})}function Li(r,e){let t=e?.budget??dn({modelContextWindow:Ei(e?.model)}),o=(e?.pipeline??_p()).compress(r,t);if(o.droppedCount>0){let s=Qe(r),i=Qe(o.messages);Oi.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:Rt(s,t)})}return o.droppedCount>0&&ir?.(o.droppedCount,Qe(o.messages)),o}async function Rp(r,e,t){let n=t??dn({modelContextWindow:Ei(e.model)}),o=Qe(r),s=Rt(o,n),i;switch(s){case"none":i={messages:r,droppedCount:0,strategy:"none"};break;case"trim-only":i=new Ye(sr).compress(r,n);break;case"sliding-window":{i=await Ii(e.summarize).compressAsync(r,n);break}case"llm-summarize":{let a=e.pipeline??Ii(e.summarize);i=_t(a)?await a.compressAsync(r,n):a.compress(r,n);break}}return i.droppedCount>0&&(i={...i,messages:await Ro(i.messages,r,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await vp(a,"utf-8")}catch{return null}}})}),Cp(r,i,n),i}function Cp(r,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||Qe(r),o=e.metrics?.tokensAfter||Qe(e.messages);Oi.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:Rt(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||Qe(e.messages);ir?.(e.droppedCount,n)}}function Ap(r,e){let t=Sp(r,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(o,s,i){return Rp(o,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};Pi.register(n),Pi.activate(n.id),r.info(`[context-compression] registered context engine: ${n.id}`)}function $i(r,e,t){Ap(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"}}}),ir=(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 or,sr,xp,Oi,Pi,ir,ar=K(()=>{"use strict";At();or={"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};sr=8e3,xp="deepseek-v4-flash",Oi=new xt(200),Pi=new St;ir=null});function Di(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 Ui=K(()=>{"use strict"});var Ni={};$s(Ni,{resolveToolEligibility:()=>Op});function Pp(r,e){if(Mp.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 Ip(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||Pp(t,e.dangerousPatterns)?(o.push("dangerous_tool"),{level:3,reasons:o}):{level:2,reasons:o}}function Ep(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 Op(r,e={}){let t=new Map,n=[],o=[],s=[];for(let i of r){let a=i.function.name,{level:l,reasons:u}=Ip(i,e),c=Ep(l),d={toolName:a,status:c,permissionLevel:l,approvalRequired:l===4,reasonCodes:u};t.set(a,d),l===5?o.push(d):(n.push(i),l===4&&s.push(d))}return{eligibleTools:n,blockedTools:o,approvalRequiredTools:s,eligibilityByName:t}}var Mp,Fi=K(()=>{"use strict";Mp=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Up(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 Np(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 Fp(r){return typeof r=="number"&&Number.isFinite(r)&&r>=1?Math.min(Math.round(r),100):ai}function ji(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 jp(r){return r==="length"||r==="max_tokens"}function Bi(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 Bp(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 Wp(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 Gp(r){return r.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Wi(r,e,t,n){let{turnId:o,sessionId:s,messages:i,tools:a,model:l,apiKey:u,temperature:c=0,hooks:d,signal:p}=r,m={sessionId:s,turnId:o},g=r.maxTurns??0,f=r.querySource,{resolveToolEligibility:b}=await Promise.resolve().then(()=>(Fi(),Ni)),T=b(a,r.toolEligibilityContext),w=T.eligibleTools;for(let F of T.blockedTools)yield{type:"tool_blocked",turnId:o,callId:"",name:F.toolName,reason:"blocked-by-policy"};if(!w.length){yield*Hp(o,l,i,u,c,p,e,n);return}let _=Fp(r.maxRounds),y={contextWindowTokens:r.contextWindowTokens??ci,responseBufferTokens:ui,maxOutputTokens:r.maxOutputTokens??di,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},C=new Set,E=0,D=w,L,v={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:zo(y),reactiveCompactState:Xo(),toolLoopState:gn({maxRounds:_,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:Mo(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:vi(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0},ce=Math.max(g*5,200),j=0;for(;;){if(j++,j>ce){n.info(`hard iteration cap reached (${ce}), forcing completion`);let S=v.finalText||bn(v.messages,n);yield{type:"end",turnId:o,content:S,usage:v.totalUsage,model:v.currentModel};return}let{messages:F,maxOutputTokensRecoveryCount:ne,hasAttemptedReactiveCompact:re,maxOutputTokensOverride:ue,turnCount:V,guardState:B,reactiveCompactState:fe,collapseStore:Oe}=v,{toolLoopState:he}=v;if(L){try{let S=await L;S&&(yield{type:"tool_use_summary",turnId:o,summary:S})}catch{}L=void 0}if(r.refreshTools&&V>1){let S=r.refreshTools();S!==D&&(D=S,n.debug(`tools refreshed: ${S.length} tools`))}if(Yo(B,y)){n.info(`turn aborted by guard at turn ${V}`),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED",usage:v.totalUsage};return}let h=qo(B,y);if(h.level==="blocking"){h.reason==="prompt_too_long"&&ut(fe)&&(fe.attemptedThisTurn=!0,B.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${h.reason}), reactive compact needed`),yield{type:"recovery",turnId:o,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${h.reason}), ending tool loop`);break}h.level==="warning"&&n.info(`token budget warning: ${h.usagePercent}% used, ${h.remainingTokens} remaining`);let k;{let S=await Ai(F,v.contentReplacementState,s);k=S.messages,S.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${S.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:o,action:"tool_result_budget",detail:`${S.newlyReplacedCount} persisted`})}{let S=Co(k,v.snipRemovedIds);k=S.messages,S.removedCount>0&&(n.info(`snip: removed ${S.removedCount} messages, freed ~${S.tokensFreed} tokens`),yield{type:"recovery",turnId:o,action:"snip",detail:`${S.removedCount} messages`})}{let M=new Fe().compress(k,0);M.droppedCount>0&&(k=M.messages,n.info(`microcompact: cleared ${M.droppedCount} old tool results`))}if(k=Po(k,Oe).messages,B.promptTokens>0){let S=Li(k,{budget:y.contextWindowTokens*.75,model:v.currentModel});S.droppedCount>0&&(k=S.messages,n.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield{type:"recovery",turnId:o,action:"autocompact",detail:`${S.strategy}: ${S.droppedCount} dropped`},v.hasAttemptedReactiveCompact=!1,d?.invoke("context.after_compact",{...m,removedCount:S.droppedCount}).catch(()=>{}))}k=Gp(k);let x=Eo({tools:D,toolChoice:r.toolChoice??"auto"}),R=gn({maxRounds:_,replayMessages:k,lastStopReason:he.lastStopReason,options:{stopReason:he.lastStopReason}}),A=x.extraSystemPrompt?[{role:"system",content:x.extraSystemPrompt},...R.state.replayMessages]:R.state.replayMessages;he=R.state,R.recoveryActions.length>0&&n.debug(`tool loop recovery: ${R.recoveryActions.map(S=>S.detail??S.kind).join("; ")}`),n.debug(`turn ${V}, messages: ${A.length}`),d?.invoke("turn.before_inference",{...m,model:v.currentModel}).catch(()=>{});let O=!1,q=[],W=new Map,ae="stop",Q,I=null,se=!1,ze=[],X=[];try{for await(let S of e.stream({model:v.currentModel,messages:A,tools:x.tools,toolChoice:x.normalizedToolChoice??"auto",temperature:c,maxTokens:(ue??B.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},u,p))switch(S.type){case"delta":q.push(S.text),O||(yield{type:"delta",turnId:o,text:S.text});break;case"tool_call_delta":O=!0,Qo(W,S);break;case"reasoning_delta":ze.push(S.text);break;case"reasoning_block_complete":S.signature&&X.push({thinking:ze.join(""),signature:S.signature}),ze.length=0;break;case"usage":Q={prompt:S.promptTokens,completion:S.completionTokens,reasoning:S.reasoningTokens,cacheRead:S.cacheReadTokens,cacheCreation:S.cacheCreationTokens};break;case"response_id":v.lastResponseId=S.id;break;case"annotations":yield{type:"annotations",turnId:o,annotations:S.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:o,message:`${S.toolType}: ${S.event}`};break;case"done":ae=S.finishReason;break}if(O||d?.invoke("turn.after_inference",{...m,model:v.currentModel}).catch(()=>{}),r.postSamplingHooks&&r.postSamplingHooks.length>0){let S=v.currentModel;for(let M of r.postSamplingHooks)try{M({messages:[...k],model:S,sessionId:s})}catch{}}}catch(S){if(S instanceof Ct&&r.fallbackModel){n.info(`model fallback triggered: ${S.originalModel} \u2192 ${S.fallbackModel}`),yield{type:"recovery",turnId:o,action:"model_fallback",detail:`${S.originalModel} \u2192 ${S.fallbackModel}`},v={...v,currentModel:S.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let M=S instanceof Error?S.message:String(S),$=typeof S?.status=="number"?S.status:void 0;if(!$&&M&&(M.includes("ECONNRESET")||M.includes("EPIPE"))){let oe=(v.consecutiveApiRetries??0)+1;if(oe>Mt){n.info(`stale connection retry limit reached (${Mt}), aborting`),yield{type:"error",turnId:o,error:M,code:"RETRIES_EXHAUSTED",usage:v.totalUsage};return}n.info(`stale connection (${M.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:o,action:"stale_connection_retry",detail:M.slice(0,80)},v={...v,consecutiveApiRetries:oe,transition:void 0};continue}let Y=Wp({status:$,message:M});if(Y!==null){n.info(`max_tokens overflow: adjusting to ${Y}`),B.currentMaxOutputTokens=Y,v={...v,maxOutputTokensOverride:Y,transition:void 0};continue}if(jo($)){if(v.consecutive529Errors++,v.consecutive529Errors>=hi&&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(Bo()){let oe=fn(v.consecutive529Errors);n.info(`persistent retry: waiting ${oe}ms (attempt ${v.consecutive529Errors})`);let z=oe;for(;z>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(z/1e3)}s (${$})`};let pe=Math.min(z,fi);await new Promise(bo=>setTimeout(bo,pe)),z-=pe}v={...v,transition:void 0};continue}if(Fo(f)){let z=Bp({status:$,message:M})??fn(v.consecutive529Errors);n.info(`transient ${$}: retry in ${z}ms`),yield{type:"recovery",turnId:o,action:"retry",detail:`${$} retry in ${z}ms`},await new Promise(pe=>setTimeout(pe,z)),v={...v,transition:void 0};continue}n.info(`background source ${f}: not retrying ${$}`)}I={status:$,message:M}}if(I&&d?.invoke("turn.after_inference",{...m,model:v.currentModel,response:{error:I.message}}).catch(()=>{}),I)if(ji(I))se=!0,n.info(`withheld prompt_too_long error (status=${I.status})`);else if(Bi(I))se=!0,n.info(`withheld media_size error (status=${I.status})`);else{let S=Ko({status:I.status??500,message:I.message},B,y);if(S.action==="reactive_compact"&&ut(fe)&&(fe.attemptedThisTurn=!0,B.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:o,action:"reactive_compact",detail:`API ${I.status??500}: ${I.message}`}),S.action==="retry"){let $=(v.consecutiveApiRetries??0)+1;if($>Mt){n.info(`API retry limit reached (${Mt}), aborting`);let Y=lt(I.status,I.message);yield{type:"error",turnId:o,error:I.message,code:Y,usage:v.totalUsage};return}yield{type:"recovery",turnId:o,action:"retry",detail:S.reason},v={...v,consecutiveApiRetries:$,transition:void 0};continue}let M=lt(I.status,I.message);d?.invoke("stop.failure",{sessionId:s,reason:M,error:I.message}).catch(()=>{}),yield{type:"error",turnId:o,error:I.message,code:M,usage:v.totalUsage};return}Q&&(v.totalUsage.prompt+=Q.prompt,v.totalUsage.completion+=Q.completion,Q.reasoning&&(v.totalUsage.reasoning=(v.totalUsage.reasoning??0)+Q.reasoning),Q.cacheRead&&(v.totalUsage.cacheRead=(v.totalUsage.cacheRead??0)+Q.cacheRead),Q.cacheCreation&&(v.totalUsage.cacheCreation=(v.totalUsage.cacheCreation??0)+Q.cacheCreation)),Q?.prompt&&(B.promptTokens=Q.prompt);let cn=q.join("");cn&&(v.finalText=cn);let Se=[...W.values()].map(S=>({id:S.id||`tc_${o}_${V}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:S.name,arguments:S.arguments}}));if(Se.length===0&&!O){if(se&&I&&ji(I)){if(v.transition?.reason!=="collapse_drain_retry"){let M=Io(k,Oe);if(M.committed>0){n.info(`collapse drain: committed ${M.committed} stages`),yield{type:"recovery",turnId:o,action:"collapse_drain",detail:`${M.committed} stages committed`},v={...v,messages:M.messages,transition:{reason:"collapse_drain_retry",committed:M.committed}};continue}}if(ut(fe)){fe.attemptedThisTurn=!0,B.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"),d?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:I.message}).catch(()=>{}),yield{type:"error",turnId:o,error:I.message,code:"PROMPT_TOO_LONG",usage:v.totalUsage};return}if(se&&I&&Bi(I)){if(ut(fe)){fe.attemptedThisTurn=!0,B.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"),d?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:I.message}).catch(()=>{}),yield{type:"error",turnId:o,error:I.message,code:"IMAGE_ERROR",usage:v.totalUsage};return}if(jp(ae)){B.consecutiveTruncations+=1;let M=r.modelMaxOutputTokens??pi,$=Jo(B,y,M);if($.shouldEscalate&&ue===void 0){B.currentMaxOutputTokens=$.newMax,n.info(`max_output_tokens escalate: ${$.newMax} tokens`),yield{type:"recovery",turnId:o,action:"output_escalation",detail:`${$.newMax} tokens`},v={...v,maxOutputTokensOverride:gi,transition:{reason:"max_output_tokens_escalate"}};continue}if(ne<mi){let Y={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${ne+1}`),yield{type:"recovery",turnId:o,action:"max_output_tokens_recovery",detail:`attempt ${ne+1}`},v={...v,messages:[...k,Y],maxOutputTokensRecoveryCount:ne+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:ne+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else B.consecutiveTruncations=0;if(he=mn(he,{replayMessages:F,lastStopReason:"completed"}),d){let M=await d.invoke("stop",{sessionId:s,reason:"completed"});if(M.action==="prevent"){n.info(`stop hook prevented continuation: ${M.reason??"no reason"}`),yield{type:"end",turnId:o,content:v.finalText,usage:v.totalUsage,model:v.currentModel};return}if(M.action==="abort"){let $=M.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${$}`);let Y={role:"user",content:$},oe={role:"assistant",content:v.finalText,...X.length>0&&{thinkingBlocks:[...X]}};v={...v,messages:[...F,oe,Y],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(r.tokenBudget&&r.tokenBudget>0&&v.budgetContinuationCount<5){let M=v.totalUsage.prompt+v.totalUsage.completion+(v.totalUsage.reasoning??0),$=M/r.tokenBudget*100,Y=M-v.lastBudgetGlobalTokens,oe=v.budgetContinuationCount>=yi&&Y<er&&v.lastBudgetDeltaTokens<er;if(oe&&n.info(`token budget early stop: diminishing returns at ${Math.round($)}% (delta=${Y})`),!oe&&$<90){let z=v.budgetContinuationCount+1,pe={role:"user",content:Di($,M,r.tokenBudget)};n.info(`token budget continuation #${z}: ${Math.round($)}% used`),yield{type:"recovery",turnId:o,action:"budget_continuation",detail:`${Math.round($)}% used (#${z})`};let bo={role:"assistant",content:v.finalText,...X.length>0&&{thinkingBlocks:[...X]}};v={...v,messages:[...F,bo,pe],budgetContinuationCount:z,lastBudgetDeltaTokens:Y,lastBudgetGlobalTokens:M,transition:{reason:"token_budget_continuation"}};continue}}if(E>0){let M={ok:!0,toolCallCount:E,distinctToolCount:C.size,multiStep:E>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},$=pn(M,{tools:[...C]});$&&(yield{type:"skill_instruction",turnId:o,instruction:$})}yield{type:"end",turnId:o,content:v.finalText,usage:v.totalUsage,model:v.currentModel};return}for(let S of Se){let M=S.function.arguments,$=D.find(Y=>Y.function.name===S.function.name);if($?.backfillObservableInput)try{let Y=JSON.parse(S.function.arguments),oe={...Y};$.backfillObservableInput(oe),Object.keys(oe).some(pe=>!(pe in Y))&&(M=JSON.stringify(oe))}catch{}yield{type:"tool_call",turnId:o,callId:S.id,name:S.function.name,arguments:M}}let Qu=X.length===0&&ze.length>0?ze.join(""):void 0;F.push(To(Se,v.finalText||void 0,X.length>0?X:void 0,Qu)),he=No(he,{replayMessages:F,pendingToolCallIds:Se.map(S=>S.id),completedToolCallIds:he.completedToolCallIds,lastStopReason:"tool_calls"});let Os=[];try{let S=new yn({toolInvoker:t,hooks:d,sessionId:s,turnId:o,log:n,signal:p,maxConcurrentTools:r?.maxConcurrentTools});for(let M of Se)S.addTool(M);for await(let M of S.getRemainingResults()){M.blocked&&(yield{type:"tool_blocked",turnId:o,callId:M.callId,name:M.toolName,reason:M.blockReason??"blocked"}),F.push(M.message),Os.push(M.callId),C.add(M.toolName),E++;let $=typeof M.message?.content=="string"?M.message.content:"",Y=M.ok&&$?$.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:o,callId:M.callId,name:M.toolName,ok:M.ok,error:M.error,outputPreview:Y},M.ok){let oe=Se.find(z=>z.id===M.callId);if(oe){if(M.toolName==="plan_mode")try{let z=JSON.parse(oe.function.arguments);z.action==="exit"&&typeof z.plan=="string"&&z.plan.length>0&&(yield{type:"plan_update",turnId:o,slug:"approved-plan",content:z.plan})}catch{}if(Dp.has(M.toolName))try{let z=JSON.parse(oe.function.arguments),pe=typeof z.file_path=="string"?z.file_path:typeof z.filePath=="string"?z.filePath:typeof z.path=="string"?z.path:void 0;pe&&(yield{type:"artifact",turnId:o,artifactId:`artifact-${M.callId}`,artifactType:Up(pe),title:pe.split(/[\\/]/).pop()||pe,filePath:pe,language:Np(pe)})}catch{}}}}}catch(S){let M=S instanceof Error?S.message:String(S);yield{type:"error",turnId:o,error:M,code:"TOOL_EXECUTION_ERROR",usage:v.totalUsage};return}if(he=mn(he,{replayMessages:F,completedToolCallIds:[...he.completedToolCallIds,...Os],lastStopReason:"tool_calls"}),r.generateToolUseSummary&&Se.length>0){let S=Se.map(M=>({name:M.function.name,arguments:M.function.arguments}));L=r.generateToolUseSummary(S).catch(()=>null)}let Ls=F.slice(-Se.length),Zu=Ls.length>0&&Ls.every(S=>{let M=S?.content;return typeof M!="string"?!1:M.startsWith("Error: ")}),kt=v.consecutiveFailedRounds;if(Zu){if(kt+=1,kt>=li){let S=v.finalText||bn(F,n);n.info(`early exit: ${kt} consecutive failed rounds, returning ${v.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:o,content:S,usage:v.totalUsage,model:v.currentModel};return}}else kt=0;let yo=V+1;if(g>0&&yo>g){if(n.info(`max turns reached (${g}), completing`),d){let M=await d.invoke("stop",{sessionId:s,reason:"max_turns"});if(M.action==="abort"){let $=M.reason??"Stop hook requested continuation after max_turns",Y={role:"assistant",content:v.finalText,...X.length>0&&{thinkingBlocks:[...X]}};v={...v,messages:[...F,Y,{role:"user",content:$}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let S=v.finalText||bn(F,n);yield{type:"end",turnId:o,content:S,usage:v.totalUsage,model:v.currentModel};return}if(yo>_){if(n.info(`tool loop budget exhausted (${_} rounds), returning`),E>0){let M={ok:!0,toolCallCount:E,distinctToolCount:C.size,multiStep:E>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},$=pn(M,{tools:[...C]});$&&(yield{type:"skill_instruction",turnId:o,instruction:$})}let S=v.finalText||bn(F,n);yield{type:"end",turnId:o,content:S,usage:v.totalUsage,model:v.currentModel};return}v={messages:F,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:yo,transition:{reason:"next_turn"},guardState:B,reactiveCompactState:fe,toolLoopState:he,consecutiveFailedRounds:kt,finalText:v.finalText,totalUsage:v.totalUsage,collapseStore:Oe,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}}}function bn(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*xp(r,e,t,n,o,s,i,a){let l=[],u;a.debug(`single LLM round, messages: ${t.length}`);for await(let c of i.stream({model:e,messages:t,temperature:o},n,s))switch(c.type){case"delta":l.push(c.text),yield{type:"delta",turnId:r,text:c.text};break;case"usage":u={prompt:c.promptTokens,completion:c.completionTokens,reasoning:c.reasoningTokens,cacheRead:c.cacheReadTokens,cacheCreation:c.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:r,content:l.join(""),usage:u??{prompt:0,completion:0},model:e}}var fp,Ei=q(()=>{"use strict";qo();Ct();bi();er();_i();Jo();gn();fp=new Set(["write","edit","patch","apply_patch"])});var Li={};Rs(Li,{Agent:()=>Mt});var Mt,nr=q(()=>{"use strict";Ct();Ei();gn();Mt=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,l={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...l,prompt:o[o.length-1]?.content??void 0}).catch(()=>{});let u=Po(o),c=[];if(i&&c.push({role:"system",content:i}),c.push(...u),this.hooks){let m=u.filter(f=>f.role==="user").pop(),g=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(g)try{let f=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:g}),b=f?.context?.recalledMemories;if(b&&b.length>0){let h=b.map(k=>`- ${k.text}`).join(`
27
+ `)):""}async function*Hp(r,e,t,n,o,s,i,a){let l=[],u;a.debug(`single LLM round, messages: ${t.length}`);for await(let c of i.stream({model:e,messages:t,temperature:o},n,s))switch(c.type){case"delta":l.push(c.text),yield{type:"delta",turnId:r,text:c.text};break;case"usage":u={prompt:c.promptTokens,completion:c.completionTokens,reasoning:c.reasoningTokens,cacheRead:c.cacheReadTokens,cacheCreation:c.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:r,content:l.join(""),usage:u??{prompt:0,completion:0},model:e}}var Dp,Gi=K(()=>{"use strict";Zo();At();Mi();ar();Ui();nr();hn();Dp=new Set(["write","edit","patch","apply_patch"])});var Vi={};$s(Vi,{Agent:()=>Pt});var Pt,lr=K(()=>{"use strict";At();Gi();hn();Pt=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,l={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...l,prompt:o[o.length-1]?.content??void 0}).catch(()=>{});let u=Do(o),c=[];if(i&&c.push({role:"system",content:i}),c.push(...u),this.hooks){let m=u.filter(f=>f.role==="user").pop(),g=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(g)try{let f=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:g}),b=f?.context?.recalledMemories;if(b&&b.length>0){let T=b.map(w=>`- ${w.text}`).join(`
28
28
  `);c.splice(i?1:0,0,{role:"system",content:`[Recalled from long-term memory]
29
- ${h}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:f?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let d=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=a?.summaryModel?async b=>{try{let h=b.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:h}],tools:[],maxTokens:60},a.apiKey??this.apiKey),x="";for await(let R of k)R.type==="delta"&&(x+=R.text);return x.trim()||null}catch{return null}}:void 0,g={turnId:n,sessionId:e.sessionId,messages:c,tools:s,model:d,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},f;for await(let b of Ii(g,this.transport,this.toolInvoker,this.log))f=b,yield b;f?.type==="end"?this.hooks?.invoke("turn.completed",{...l}).catch(()=>{}):f?.type==="error"&&this.hooks?.invoke("turn.failed",{...l,code:f.code,error:f.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let g=m instanceof Error?m.message:String(m),f=typeof m?.status=="number"?m.status:void 0,b=lt(f,g);this.log.error(`turn ${n} error [${b}, retryable=${ho(b)}]: ${g}`),this.hooks?.invoke("turn.failed",{...l,code:b,error:g}).catch(()=>{}),yield{type:"error",turnId:n,error:g,code:b}}}}}});import{randomUUID as ve}from"node:crypto";import{createInterface as $u}from"node:readline";var at=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
- `)}start(){let e=$u({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let n=t.trim();if(n)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}
31
- `)}};nr();qo();var xe=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 c=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${c}`)}return e.streamImage&&a.body?this.parseStreamingImage(a.body,e,o):{mediaUrls:((await a.json()).data??[]).map(c=>c.url).filter(c=>!!c),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:l,value:u}=await a.read();if(l)break;s+=o.decode(u,{stream:!0});let c;for(;(c=s.indexOf(`
32
- `))!==-1;){let d=s.slice(0,c).trim();if(s=s.slice(c+1),!d||d.startsWith(":")||!d.startsWith("data:"))continue;let p=d.slice(5).trim();if(p==="[DONE]")break;try{let g=JSON.parse(p).data?.[0]?.url;g&&(i=g,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,l=e.referenceImages?.length??0,u=!!(e.imageUrl||l>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&&!u&&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"&&l>9)throw new Error(`Seedance 2.0 video edit: max 9 reference images (got ${l}).`);let c=[];switch(e.draftTaskId&&c.push({type:"draft_task",id:e.draftTaskId}),e.operation){case"multimodal_reference":{if(e.prompt&&c.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let h=0;h<e.referenceImages.length;h++){let k=e.imageRoles?.[h]??"reference_image";c.push({type:"image_url",image_url:{url:e.referenceImages[h]},role:k})}if(e.referenceVideos?.length)for(let h of e.referenceVideos)c.push({type:"video_url",video_url:{url:h},role:"reference_video"});if(e.referenceAudios?.length)for(let h of e.referenceAudios)c.push({type:"audio_url",audio_url:{url:h},role:"reference_audio"});break}case"extend":{if(e.sourceVideos?.length)for(let h of e.sourceVideos)c.push({type:"video_url",video_url:{url:h},role:"reference_video"});e.prompt&&c.push({type:"text",text:e.prompt});break}case"merge":for(let h of e.sourceVideos??[])c.push({type:"video_url",video_url:{url:h}});e.prompt&&c.push({type:"text",text:e.prompt});break;case"upscale":e.sourceVideos?.[0]&&c.push({type:"video_url",video_url:{url:e.sourceVideos[0]}}),c.push({type:"text",text:e.prompt||"upscale"});break;case"edit":for(let h of e.sourceVideos??[])c.push({type:"video_url",video_url:{url:h},role:"reference_video"});if(e.referenceImages?.length)for(let h of e.referenceImages)c.push({type:"image_url",image_url:{url:h},role:"reference_image"});e.prompt&&c.push({type:"text",text:e.prompt});break;default:{let h=(e.referenceVideos?.length??0)>0,k=(e.referenceAudios?.length??0)>0,x=(e.imageRoles?.length??0)>0;if(h||k||x){if(e.prompt&&c.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let R=0;R<e.referenceImages.length;R++){let E=e.imageRoles?.[R]??"reference_image";c.push({type:"image_url",image_url:{url:e.referenceImages[R]},role:E})}if(h)for(let R of e.referenceVideos)c.push({type:"video_url",video_url:{url:R},role:"reference_video"});if(k)for(let R of e.referenceAudios)c.push({type:"audio_url",audio_url:{url:R},role:"reference_audio"})}else if(e.referenceImages?.length){for(let R of e.referenceImages)c.push({type:"image_url",image_url:{url:R}});e.prompt&&c.push({type:"text",text:e.prompt})}else e.imageUrl?(c.push({type:"image_url",image_url:{url:e.imageUrl}}),e.prompt&&c.push({type:"text",text:e.prompt})):e.prompt&&c.push({type:"text",text:e.prompt});break}}let d={model:e.model,content:c};e.duration&&(d.duration=e.duration),e.aspectRatio&&(d.ratio=e.aspectRatio),e.resolution&&(d.resolution=e.resolution),e.seed!==void 0&&(d.seed=e.seed),e.fps&&(d.fps=e.fps),e.generateAudio!==void 0&&(d.generate_audio=e.generateAudio),e.watermark!==void 0&&(d.watermark=e.watermark),e.enhancePrompt!==void 0&&(d.enhance_prompt=e.enhancePrompt),e.cameraFixed!==void 0&&(d.camera_fixed=e.cameraFixed),e.returnLastFrame!==void 0&&(d.return_last_frame=e.returnLastFrame),e.serviceTier&&(d.service_tier=e.serviceTier),e.executionExpiresAfterSeconds!==void 0&&(d.execution_expires_after=e.executionExpiresAfterSeconds),e.draft!==void 0&&(d.draft=e.draft),e.safetyIdentifier&&(d.safety_identifier=e.safetyIdentifier),e.callbackUrl&&(d.callback_url=e.callbackUrl),e.videoTools?.length&&(d.tools=e.videoTools.map(h=>({type:h})));let p=await this.submitTask(s,d,t,n),m=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${p}`,t,n,e.onProgress,p),g=[],f=m.content;typeof f?.video_url=="string"&&g.push(f.video_url);let b=typeof f?.last_frame_url=="string"?f.last_frame_url:void 0;return{mediaUrls:g,model:e.model,durationMs:Date.now()-o,lastFrameUrl:b,taskId:p}}async generate3D(e,t,n){let o=Date.now(),s=`${this.baseUrl}/v3/3d-contents/generations/tasks`,i={model:e.model};e.imageUrl&&(i.image={url:e.imageUrl}),e.prompt&&(i.prompt=e.prompt),e.outputFormat&&(i.output_format=e.outputFormat);let a=await this.submitTask(s,i,t,n),l=await this.pollTask(`${this.baseUrl}/v3/3d-contents/generations/tasks/${a}`,t,n,e.onProgress,a),u=[],c=l.output;if(c?.model_urls){let d=c.model_urls;for(let p of Object.values(d))p&&u.push(p)}return{mediaUrls:u,model:e.model,durationMs:Date.now()-o}}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 l=await s.text().catch(()=>"");throw new Error(`Volcengine task status error ${s.status}: ${l}`)}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 l=await a.text().catch(()=>"");throw new Error(`Volcengine list tasks error ${a.status}: ${l}`)}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 u=await a.text().catch(()=>"");throw new Error(`Volcengine file upload error ${a.status}: ${u}`)}let l=await a.json();return{id:String(l.id??""),status:String(l.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 l=await a.text().catch(()=>"");throw new Error(`Volcengine list files error ${a.status}: ${l}`)}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 l=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${l}`)}let i=await s.json(),a=i.id??i.task_id;if(!a)throw new Error("Volcengine task submit: no task_id in response");return a}async pollTask(e,t,n,o,s){let i=Date.now()+6e5,a=0;for(;Date.now()<i;){n?.throwIfAborted();let l=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`Volcengine task poll error ${l.status}: ${m}`)}let u=await l.json(),c=u.status;if(c==="succeeded"||c==="complete")return o?.(100,"completed",s),u;if(c==="failed"||c==="cancelled"){let m=u.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${m}`)}a++;let d=Date.now()-(i-6e5),p=Math.min(95,Math.round(d/6e5*100));o?.(p,c??"running",s),await new Promise(m=>setTimeout(m,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as _p,mkdirSync as Cp}from"node:fs";import{join as Ji}from"node:path";import{randomUUID as Ap}from"node:crypto";import{homedir as Rp}from"node:os";import{join as Q}from"node:path";var _e=".qlogicagent";function B(){return Q(Rp(),_e)}function or(){return Q(B(),"sessions")}function $i(r){return Q(or(),r)}function Di(){return Q(B(),"plugins")}function rr(){return Q(B(),"skills")}function dt(){return Q(B(),"settings.json")}function Se(){return Q(B(),"cache")}function Ui(){return Q(B(),"debug-logs")}function Ni(r){let e=Q(B(),"checkpoints");return r?Q(e,r):e}function Fi(){return Q(B(),"plugin-cache")}function ji(){return Q(B(),"mcp.json")}function Bi(){return Q(B(),"marketplace.json")}function Wi(){return Q(B(),"workflows")}function Gi(){return Q(B(),"rules")}function Fe(r){return Q(r??process.cwd(),_e)}function Hi(r){return Q(Fe(r),"workflows")}function zi(r){return Q(Fe(r),"INSTRUCTIONS.md")}function Vi(r){return Q(Fe(r),"rules")}function qi(r){return Q(Fe(r),"sessions")}function Ki(r){return Q(r,_e,"hooks")}var Mp=18e4,Pt=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Mp}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 c=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${c}`)}return{mediaUrls:((await a.json()).data??[]).map(c=>c.url).filter(c=>!!c),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 l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${l.status}: ${m}`)}let u=Buffer.from(await l.arrayBuffer()),c=Ji(Se(),"tts");Cp(c,{recursive:!0});let d=`openai-tts-${Ap()}.mp3`,p=Ji(c,d);return _p(p,u),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-o,billingUnit:"per_character",billingQuantity:s.length}}};var Ze=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 l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax music rejected: ${l.base_resp.status_msg??"unknown"}`);let u=l.data?.audio??l.audio_file;if(u)return{mediaUrls:[u],model:e.model,durationMs:Date.now()-o};let c=l.task_id;if(!c)throw new Error("MiniMax music: no audio_file or task_id in response");let d=`${this.baseUrl}/v1/music_generation/${c}`;return{mediaUrls:(await this.pollTask(d,t,n,e.onProgress,c)).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 d=await a.text().catch(()=>"");throw new Error(`MiniMax music poll error ${a.status}: ${d}`)}let l=await a.json(),u=l.status;if(u==="Success"||u==="Finished"){o?.(100,"completed",s);let d=[];return l.audio_file&&d.push(l.audio_file),{audioUrls:d}}if(u==="Failed"||u==="Cancelled")throw new Error(`MiniMax music task failed: ${l.base_resp?.status_msg??"unknown"}`);let c=Date.now()-(i-6e5);o?.(Math.min(95,Math.round(c/6e5*100)),u??"running",s),await new Promise(d=>setTimeout(d,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 d=e.imageRoles.includes("first_frame"),p=e.imageRoles.includes("last_frame");if(d&&p){let m=e.imageRoles.indexOf("first_frame"),g=e.imageRoles.indexOf("last_frame");i.first_frame_image=e.referenceImages[m],i.last_frame_image=e.referenceImages[g]}else if(d){let m=e.imageRoles.indexOf("first_frame");i.first_frame_image=e.referenceImages[m]}else i.subject_reference=e.referenceImages.map((m,g)=>({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 d=await a.text().catch(()=>"");throw new Error(`MiniMax video submit error ${a.status}: ${d}`)}let l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax video rejected: ${l.base_resp.status_msg??"unknown"}`);let u=l.task_id;if(!u)throw new Error("MiniMax video: no task_id in response");let c=await this.pollVideoTask(u,t,n,e.onProgress);return{mediaUrls:c.downloadUrl?[c.downloadUrl]:[],model:e.model||"S2V-01",durationMs:Date.now()-o,taskId:u,metadata:{fileId:c.fileId,width:c.width,height:c.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 l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax video task error ${l.base_resp.status_code}: ${l.base_resp.status_msg??""}`);let u=l.status;if(u==="Success"){o?.(100,"completed",e);let m;if(l.file_id)try{m=await this.getFileDownloadUrl(l.file_id,t,n)}catch{}return{fileId:l.file_id,downloadUrl:m,width:l.video_width,height:l.video_height}}if(u==="Fail")throw new Error(`MiniMax video task failed: ${l.base_resp?.status_msg??"unknown"}`);let c=u??"running",d=Date.now()-(s-6e5),p=Math.min(95,Math.round(d/6e5*100));o?.(p,c,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 l=await s.text().catch(()=>"");throw new Error(`MiniMax file retrieve error ${s.status}: ${l}`)}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 u=await s.text().catch(()=>"");throw new Error(`MiniMax task status error ${s.status}: ${u}`)}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 Xi,mkdirSync as Qi}from"node:fs";import{join as yn}from"node:path";import{randomUUID as Zi}from"node:crypto";import{writeFileSync as Pp,mkdirSync as Ip}from"node:fs";import{join as Yi}from"node:path";import{randomUUID as Ep}from"node:crypto";var hn=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",l),s()},l=()=>{o.removeEventListener("open",a),i(new Error("Lyria RealTime WebSocket connection failed"))};o.addEventListener("open",a,{once:!0}),o.addEventListener("error",l,{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 sr(r,e,t){let n=t.durationSeconds??30,o=Date.now(),s=new hn(e),i=[];s.onAudioChunk=l=>{i.push(l.data)};let a=null;s.onError=l=>{a=l};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 l=Date.now()+n*1e3,u=500;for(;Date.now()<l;){if(t.signal?.throwIfAborted(),a)throw a;if(!s.connected)break;let f=Date.now()-o,b=n*1e3,h=Math.min(95,Math.round(10+f/b*85));t.onProgress?.(h,"streaming"),await new Promise(k=>setTimeout(k,u))}s.connected&&await s.stop(),t.onProgress?.(98,"assembling");let c=Buffer.concat(i),d=Op(c,48e3,2,16),p=Yi(Se(),"gemini-music-realtime");Ip(p,{recursive:!0});let m=`lyria-rt-${Ep()}.wav`,g=Yi(p,m);return Pp(g,d),t.onProgress?.(100,"completed"),{filePath:`file://${g}`,durationMs:Date.now()-o}}finally{s.close()}}function Op(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 Lp=18e4,$p=1e4,ir=6e5,It=class{supportedTypes=["image","video","music","music_realtime","tts","embedding"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Lp}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 l=await s.text().catch(()=>"");throw new Error(`Gemini operation query error ${s.status}: ${l}`)}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},l=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineImages(l),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 b=>({image:{inlineData:await this.resolveImageData(b)},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 l={instances:[i]};Object.keys(a).length>0&&(l.parameters=a);let c=(await this.postJson(s,l,t,n)).name;if(!c)throw new Error("Gemini video submit: no operation name in response");let d=c;e.onProgress?.(5,"submitted",d);let g=(await this.pollOperation(c,t,n,e.onProgress,d)).response?.generateVideoResponse?.generatedSamples??[],f=[];for(let b of g)b.video?.uri&&f.push(b.video.uri);return{mediaUrls:f,model:e.model,durationMs:Date.now()-o,taskId:d}}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 l={contents:[{parts:i}]};Object.keys(a).length>0&&(l.generationConfig=a);let u=await this.postJson(s,l,t,n);return{mediaUrls:this.extractInlineAudio(u,"gemini-music"),model:e.model,durationMs:Date.now()-o}}async generateMusicRealtime(e,t,n){let o=await sr(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},l=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineAudio(l,"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 u=(await this.postJson(s,i,t,n)).embeddings?.[0]?.values??[];return{mediaUrls:[],model:e.model,durationMs:Date.now()-o,metadata:{embedding:u,dimensions:u.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()+ir;for(;Date.now()<i;){n?.throwIfAborted();let a=`${this.apiBase}/${e}`,l=await fetch(a,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`Gemini operation poll error ${l.status}: ${p}`)}let u=await l.json();if(u.done===!0)return o?.(100,"completed",s),u;if(u.error){let p=u.error;throw new Error(`Gemini video generation failed: ${p.message??JSON.stringify(p)}`)}let c=Date.now()-(i-ir),d=Math.min(95,Math.round(c/ir*100));o?.(d,"running",s),await new Promise(p=>setTimeout(p,$p))}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"),l=i.split(".").pop()?.toLowerCase()??"png";return{mimeType:l==="jpg"||l==="jpeg"?"image/jpeg":l==="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=yn(Se(),"gemini-images");Qi(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-${Zi()}.${i}`,l=yn(n,a);Xi(l,Buffer.from(s.inlineData.data,"base64")),t.push(`file://${l}`)}return t}extractInlineAudio(e,t){let n=[],o=yn(Se(),t);Qi(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",l=Buffer.from(i.inlineData.data,"base64"),u=a==="pcm"?Dp(l,24e3,1,16):l,c=`gemini-${Zi()}.${a==="pcm"?"wav":a}`,d=yn(o,c);Xi(d,u),n.push(`file://${d}`)}return n}};function Dp(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 bn=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},l={text:s};e.voice&&(l.voice=e.voice),e.speed!==void 0&&(a.speech_rate=e.speed);let u={model:e.model||"qwen3-tts-voicedesign",input:l,parameters:a},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(u),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${c.status}: ${g}`)}let d=await c.json();if(d.code)throw new Error(`DashScope TTS submit rejected: ${d.code} \u2014 ${d.message??""}`);let p=d.output?.task_id;if(!p)throw new Error("DashScope TTS submit: no task_id in response");if(d.output?.task_status==="SUCCEEDED"){let g=this.extractMediaUrl(d);return{mediaUrls:g?[g]:[],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 Up(2e3);let l=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${l.status}: ${p}`)}let u=await l.json();if(u.code)throw new Error(`DashScope poll rejected: ${u.code} \u2014 ${u.message??""}`);let c=u.output?.task_status;if(c==="SUCCEEDED"){o?.(100,"completed",e);let p=this.extractMediaUrl(u);return p?[p]:[]}if(c==="FAILED")throw new Error(`DashScope task failed: ${u.message??"unknown error"}`);let d=Date.now()-(i-s);o?.(Math.min(95,Math.round(d/s*100)),c??"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 g=e.imageRoles.indexOf("first_frame"),f=e.imageRoles.indexOf("last_frame");g>=0&&(i.img_url=e.referenceImages[g]),f>=0&&(i.tail_image_url=e.referenceImages[f]);let b=e.imageRoles.map((h,k)=>h==="reference_image"?k:-1).filter(h=>h>=0);b.length>0&&(i.ref_image_url=e.referenceImages[b[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 l=`${this.baseUrl}/api/v1/services/aigc/generation/generation`,u={model:s,input:i};Object.keys(a).length>0&&(u.parameters=a);let c=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(u),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`DashScope video submit error ${c.status}: ${g}`)}let d=await c.json();if(d.code)throw new Error(`DashScope video submit rejected: ${d.code} \u2014 ${d.message??""}`);let p=d.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 c=await s.text().catch(()=>"");throw new Error(`DashScope task status error ${s.status}: ${c}`)}let i=await s.json(),l=i.output?.task_status??"unknown";return{status:l==="SUCCEEDED"?"succeeded":l==="FAILED"?"failed":l.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 Up(r){return new Promise(e=>setTimeout(e,r))}import{writeFileSync as Np,mkdirSync as Fp}from"node:fs";import{join as ea}from"node:path";import{randomUUID as jp}from"node:crypto";var Bp=18e4,Wp=3e3,kn=6e5,Gp=new Set(["glm-image"]),Et=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??Bp}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 Gp.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(c=>c.url).filter(c=>!!c),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 l=(await this.postJSON(s,i,t,n)).id;if(!l)throw new Error("Zhipu async image: no task id in response");return{mediaUrls:((await this.pollAsyncResult(l,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 l=(await this.postJSON(s,i,t,n)).id;if(!l)throw new Error("Zhipu video generation: no task id in response");return{mediaUrls:((await this.pollAsyncResult(l,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 l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let g=await l.text().catch(()=>"");throw new Error(`Zhipu TTS API error ${l.status}: ${g}`)}let u=Buffer.from(await l.arrayBuffer()),c=ea(Se(),"tts");Fp(c,{recursive:!0});let d=e.audioFormat??"wav",p=`zhipu-tts-${jp()}.${d}`,m=ea(c,p);return Np(m,u),{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,{signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok)throw new Error(`Failed to fetch audio from ${e.audioUrl}`);let a=await i.blob(),l=new FormData;l.append("model",e.model||"glm-asr-2512"),l.append("file",a,"audio.wav");let u=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:l,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`Zhipu STT API error ${u.status}: ${d}`)}let c=await u.json();return{mediaUrls:[],model:e.model||"glm-asr-2512",durationMs:Date.now()-o,metadata:{transcription:c.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},u=(await this.postJSON(i,a,t,n)).data??[];return{mediaUrls:[],model:e.model||"embedding-3",durationMs:Date.now()-o,metadata:{embeddings:u.map(c=>c.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 l=`${this.baseUrl}/voice/clone`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:a,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let p=await u.text().catch(()=>"");throw new Error(`Zhipu Voice Clone API error ${u.status}: ${p}`)}let c=await u.json();return{mediaUrls:(c.data??[]).map(p=>p.url).filter(p=>!!p),model:e.model||"glm-tts-clone",durationMs:Date.now()-o,metadata:{voiceId:c.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 c=(await this.postJSON(i,a,t,n)).pages??[];return{mediaUrls:[],model:e.model||"glm-ocr",durationMs:Date.now()-o,metadata:{pages:c.map(d=>({pageNum:d.page_num,content:d.content,layouts:d.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 l=await this.postJSON(i,a,t,n);return{mediaUrls:[],model:e.model||"rerank",durationMs:Date.now()-o,metadata:{results:(l.results??[]).map(u=>({index:u.index,relevanceScore:u.relevance_score,document:u.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()+kn,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 c=await a.text().catch(()=>"");throw new Error(`Zhipu async-result error ${a.status}: ${c}`)}let l=await a.json();if(l.task_status==="SUCCESS")return o?.(100,"completed",e),l;if(l.task_status==="FAIL")throw new Error("Zhipu async task failed");let u=Date.now()-(s-kn);o?.(Math.min(95,Math.round(u/kn*100)),l.task_status??"running",e),await new Promise(c=>setTimeout(c,Wp))}throw new Error(`Zhipu async task timed out after ${kn/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 u=await s.text().catch(()=>"");throw new Error(`Zhipu task query error ${s.status}: ${u}`)}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 Ot=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=Vp(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?Hp(n):void 0,a=s.find(l=>l.mediaType!==t?!1:!i||!l.mediaCapabilities?!0:zp(l.mediaCapabilities,i));if(a)return{providerId:e,providerDef:o,modelInfo:a,mediaType:t}}};function Hp(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 zp(r,e){return!("operations"in r)||!r.operations?!0:r.operations.includes(e)}function Vp(r){let e=r.baseUrl;switch(r.id){case"volcengine":return new xe({baseUrl:e});case"openai":return new Pt({baseUrl:e});case"minimax":return new Ze({baseUrl:e});case"google":return new It({baseUrl:e});case"qwen":return new bn({baseUrl:e});case"zhipu":return new Et({baseUrl:e.replace(/\/api\/anthropic\/?$/,"/api/paas/v4")});case"zhipu-openai":case"zhipu-coding":return new Et({baseUrl:e.replace(/\/api\/coding\/paas\/v4\/?$/,"/api/paas/v4")});default:return}}var ar=[{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 qp,mkdirSync as Kp,readFileSync as Jp,writeFileSync as Yp}from"node:fs";import{join as Xp}from"node:path";var Qp="https://models.dev/api.json",Zp=3e4,em=1440*60*1e3,tm=300*1e3,nm={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"},Lt=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??Se(),this.cacheFile=Xp(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??em}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(!qp(this.cacheFile))return;let e=Jp(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:ta(t.data)}}catch{}}saveToDisk(e){try{Kp(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);Yp(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<tm||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(Qp,{signal:AbortSignal.timeout(Zp),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=ta(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function ta(r){let e=new Map;if(!r||typeof r!="object")return e;for(let[t,n]of Object.entries(r)){let o=nm[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[l,u]of Object.entries(i)){if(!u||typeof u!="object"||a.models.has(l))continue;let c=u,d=c.cost??{},p=c.limit??{},m=c.modalities??{},g=Array.isArray(m.input)?m.input:[],f=Array.isArray(m.output)?m.output:[],b=om(f,g,l);a.models.set(l,{id:l,name:typeof c.name=="string"?c.name:l,contextWindow:typeof p.context=="number"?p.context:2e5,maxOutput:typeof p.output=="number"?p.output:8192,toolCall:c.tool_call===!0,reasoning:c.reasoning===!0,vision:c.attachment===!0||g.includes("image"),costInput:typeof d.input=="number"?d.input:void 0,costOutput:typeof d.output=="number"?d.output:void 0,costCacheRead:typeof d.cache_read=="number"?d.cache_read:void 0,costCacheWrite:typeof d.cache_write=="number"?d.cache_write:void 0,mediaType:b})}}return e}function om(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 rm={claude:"anthropic",gemini:"google",doubao:"volcengine"},$t=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of ar)this.builtins.set(t.id,t);this.catalog=e?.catalog??new Lt}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=rm[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 lr=new Set([429,529,502,503,504]),Ce=9e4;function Ae(r){let e=Math.min(1e3*Math.pow(2,r-1),3e4),t=Math.random()*.25*e;return e+t}function Le(r){return r!=null&&lr.has(r)}function Me(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 $e(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 Tn(r){return r.toLowerCase().startsWith("gpt-5")}function wn(r){return r.toLowerCase().includes("5.4-nano")}function Dt(r){return/^o[1-4](-|$)/.test(r.toLowerCase())}var pt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;quirks;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??{}}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:im(e.messages,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 l=!e.disableBuiltinTools,u=!1;if(l&&this.quirks.builtinWebSearch&&a.tools){let f=a.tools;this.quirks.builtinCodeInterpreter?f.push({type:"web_search",web_search:{enable:!0,search_result:!0}}):(f.push({type:"builtin_function",function:{name:"$web_search"}}),u=!0)}l&&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 c=this.quirks.useEffortInsteadOfBudget&&!!e.reasoning,d=e.model.startsWith("kimi-k2.6"),p=Tn(e.model);if(e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p||!Dt(e.model)&&!c&&!d)&&(a.temperature=e.temperature)),e.topP!==void 0&&(p||!Dt(e.model)&&!c&&!d)&&(a.top_p=e.topP),e.maxTokens!==void 0&&(p||Dt(e.model)||e.model.startsWith("kimi-k2")?a.max_completion_tokens=e.maxTokens:a.max_tokens=e.maxTokens),e.reasoning)if(p){let f=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;wn(e.model)&&(f==="high"||f==="xhigh")&&(f="medium"),a.reasoning={effort:f}}else if(Dt(e.model))a.reasoning_effort=e.reasoning.effort;else if(this.quirks.useEffortInsteadOfBudget){a.thinking={type:"enabled"};let f=this.quirks.maxReasoningEffort??"high",b=e.reasoning.effort??"high";a.reasoning_effort=b==="low"||b==="medium"?"high":f}else this.quirks.supportsThinkingParam?(u?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 u&&(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},g=null;for(let f=0;f<=3;f++){if(n?.aborted)throw new Error("Request aborted");f>0&&g&&await Me(Ae(f),n);try{yield*this.fetchAndStream(i,m,a,n);return}catch(b){g=b instanceof Error?b:new Error(String(b));let h=g.message.includes("Stream idle timeout");if(!Le($e(g))&&!h||f===3)throw g}}}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 u=await a.text().catch(()=>""),c=new Error(`LLM API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("LLM API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.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()},Ce)};try{i();let a=e.getReader();try{for(;;){let{done:l,value:u}=await a.read();if(l)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(u,{stream:!0});let c;for(;(c=n.indexOf(`
33
- `))!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),!d||d.startsWith(":")||!d.startsWith("data: "))continue;let p=d.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:sm(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},l=AbortSignal.timeout(this.timeoutMs),u=n?AbortSignal.any([n,l]):l,c=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(i),signal:u});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`FIM API error ${c.status}: ${g.slice(0,500)}`)}if(!c.body)throw new Error("FIM API returned no response body");let d=new TextDecoder,p="",m=c.body.getReader();try{for(;;){let{done:g,value:f}=await m.read();if(g)break;p+=d.decode(f,{stream:!0});let b;for(;(b=p.indexOf(`
34
- `))!==-1;){let h=p.slice(0,b).trim();if(p=p.slice(b+1),!h||h.startsWith(":")||!h.startsWith("data: "))continue;let k=h.slice(6);if(k==="[DONE]")return;let x;try{x=JSON.parse(k)}catch{continue}for(let R of x.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`,l=new FormData;l.append("file",e,t),l.append("purpose",n);let u=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`,...this.extraHeaders},body:l,signal:s??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`File upload error ${u.status}: ${d}`)}let c=await u.json();return{fileId:c.id??"",filename:c.filename??t,bytes:c.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 l=await i.text().catch(()=>"");throw new Error(`File info error ${i.status}: ${l}`)}let a=await i.json();return{id:a.id??e,filename:a.filename??"",bytes:a.bytes??0,status:a.status??"unknown"}}};function sm(r){switch(r){case"sensitive":return"content_filter";case"model_context_window_exceeded":return"length";case"network_error":return"error";default:return r}}function im(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 l=[];if(t.content&&l.push({type:"text",text:t.content}),n)for(let u of t.imageUrls){let c={url:u};t.imageDetail&&(c.detail=t.imageDetail),l.push({type:"image_url",image_url:c})}if(o)for(let u of t.videoUrls)l.push({type:"video_url",video_url:{url:u}});if(s)for(let u of t.audioUrls)l.push({type:"input_audio",input_audio:{data:u,format:t.audioFormat??"mp3"}});if(i)for(let u of t.fileIds)l.push({type:"file",file:{file_id:u.id}});return{role:"user",content:l}}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}return t.role==="tool"?{role:"tool",content:t.content??"",tool_call_id:t.tool_call_id??""}:{role:t.role,content:t.content??""}})}var vn=class{baseUrl;extraHeaders;timeoutMs;quirks;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??{}}async*stream(e,t,n){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/responses`:`${this.baseUrl}/v1/responses`,i=this.buildRequestBody(e),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},l=null;for(let u=0;u<=3;u++){if(n?.aborted)throw new Error("Request aborted");u>0&&l&&await Me(Ae(u),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(c){l=c instanceof Error?c:new Error(String(c));let d=l.message.includes("Stream idle timeout");if(!Le($e(l))&&!d||u===3)throw l}}}buildRequestBody(e){let t={model:e.model,input:am(e.messages),stream:!0};if(e.conversationId?t.conversation=e.conversationId:e.previousResponseId&&(t.previous_response_id=e.previousResponseId),e.store!==void 0&&(t.store=e.store),e.instructions&&(t.instructions=e.instructions),e.structuredOutput&&(e.structuredOutput.mode==="json_object"?t.text={format:{type:"json_object"}}:t.text={format:{type:"json_schema",name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}}),e.tools&&e.tools.length>0&&(t.tools=e.tools.map(n=>({type:"function",name:n.function.name,description:n.function.description,parameters:n.function.parameters,strict:!0}))),e.toolChoice!==void 0&&(typeof e.toolChoice=="string"?t.tool_choice=e.toolChoice:t.tool_choice={type:e.toolChoice.type,name:e.toolChoice.name}),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.top_p=e.topP),e.maxTokens!==void 0&&(t.max_output_tokens=e.maxTokens),e.reasoning){let n=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;wn(e.model)&&(n==="high"||n==="xhigh")&&(n="medium");let o={effort:n};o.summary="auto",o.generate_summary="auto",t.reasoning=o}if(e.prediction&&Tn(e.model)&&(t.prediction=e.prediction),t.truncation="auto",e.promptCacheKey&&(t.prompt_cache_key=e.promptCacheKey),e.promptCacheRetention&&(t.prompt_cache_retention=e.promptCacheRetention),e.serviceTier&&(t.service_tier=e.serviceTier),e.reasoning?.includeEncryptedReasoning&&(e.store===void 0&&(t.store=!1),t.include=["reasoning.encrypted_content"]),e.contextManagement&&(t.context_management=e.contextManagement.edits.map(n=>{let o={type:n.type};return n.type==="clear_thinking"&&n.keep!==void 0?o.keep=n.keep:n.type==="clear_tool_uses"&&(n.trigger&&(o.trigger=n.trigger),n.keep&&(o.keep=n.keep),n.excludeTools&&(o.exclude_tools=n.excludeTools),n.clearToolInput!==void 0&&(o.clear_tool_input=n.clearToolInput)),o})),!e.disableBuiltinTools){let n=t.tools??[],o=t.include??[];if(e.openaiBuiltinTools&&e.openaiBuiltinTools.length>0){for(let i of e.openaiBuiltinTools)n.push({...i});let s=new Set(e.openaiBuiltinTools.map(i=>i.type));s.has("web_search_preview")&&o.push("web_search_call.action.sources"),s.has("file_search")&&o.push("file_search_call.results"),s.has("code_interpreter")&&o.push("code_interpreter_call.outputs"),s.has("computer_use_preview")&&o.push("computer_call_output.output.image_url")}else this.quirks.builtinWebSearch&&(n.push({type:"web_search_preview"}),o.push("web_search_call.action.sources")),this.quirks.builtinCodeInterpreter&&(n.push({type:"code_interpreter"}),o.push("code_interpreter_call.outputs")),this.quirks.builtinFileSearch&&(n.push({type:"file_search"}),o.push("file_search_call.results"));n.length>0&&(t.tools=n),o.length>0&&(t.include=o)}if(e.maxToolCalls!==void 0&&(t.max_tool_calls=e.maxToolCalls),e.parallelToolCalls!==void 0&&(t.parallel_tool_calls=e.parallelToolCalls),e.textVerbosity){let n=t.text??{};n.verbosity=e.textVerbosity,t.text=n}return 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 u=await a.text().catch(()=>""),c=new Error(`OpenAI Responses API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("OpenAI Responses API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.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,l=new Map,u=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},Ce)};try{u();let c=e.getReader();try{for(;;){let{done:d,value:p}=await c.read();if(d)break;if(i.signal.aborted)throw new Error("Stream idle timeout");u(),n+=t.decode(p,{stream:!0});let m;for(;(m=n.indexOf(`
35
- `))!==-1;){let g=n.slice(0,m).trim();if(n=n.slice(m+1),!g){o="";continue}if(!g.startsWith(":")){if(g.startsWith("event:")){o=g.slice(6).trim();continue}if(g.startsWith("data:")){let f=g.slice(5).trim();if(f==="[DONE]")return;let b;try{b=JSON.parse(f)}catch{continue}yield*this.processEvent(o,b,l,()=>a++)}}}}}finally{c.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 l=n.get(i);l===void 0&&(l=o(),n.set(i,l)),yield{type:"tool_call_delta",index:l,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 l=o();n.set(i,l),yield{type:"tool_call_delta",index:l,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 l=a.annotations;l&&l.length>0&&(yield{type:"annotations",annotations:l.map(u=>({type:u.type??"url_citation",url:u.url,title:u.title,...u}))})}}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 u=a.input_tokens_details,c=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:c?.reasoning_tokens,cacheReadTokens:u?.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}}}};function am(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 l=[];if(n)for(let u of t.imageUrls){let c={type:"input_image",image_url:u};t.imageDetail&&(c.detail=t.imageDetail),l.push(c)}if(s)for(let u of t.audioUrls)l.push({type:"input_audio",data:u,format:t.audioFormat??"mp3"});if(i)for(let u of t.fileIds)l.push({type:"input_file",file_id:u.id});t.content&&l.push({type:"input_text",text:t.content}),e.push({role:"user",content:l})}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;e.push({type:"function_call_output",call_id:t.tool_call_id,output:t.content??""});continue}}return e}var lm=18e4,cm=3e5,um=64e3,dm="[Tool execution failed; output not available during conversation recovery]",pm="interleaved-thinking-2025-05-14",mm="context-1m-2025-08-07",gm="token-efficient-tools-2026-03-28",fm="prompt-caching-scope-2026-01-05",hm="pdfs-2024-09-25";function ym(r){let e=r.toLowerCase();return e.includes("opus-4-6")||e.includes("opus-4-7")||e.includes("sonnet-4-6")}function bm(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(mm),n.push(hm),e&&!o.includes("haiku")&&n.push(pm),t&&n.push(gm),n.push(fm);let i=process.env.ANTHROPIC_BETAS;if(i)for(let a of i.split(",").map(l=>l.trim()).filter(Boolean))n.includes(a)||n.push(a);return n}var Ut=class{baseUrl;apiVersion;timeoutMs;streamIdleTimeoutMs;enablePromptCaching;maxRetries;omitZeroTemperature;quirks;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??lm,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??Ce,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3,this.omitZeroTemperature=e.omitZeroTemperature??!1,this.quirks=e.quirks??{}}async*stream(e,t,n){let o=`${this.baseUrl}/v1/messages`,s=wm(e.messages),{system:i,messages:a}=vm(s,this.quirks),l=Tm(i,this.enablePromptCaching),u=!!e.reasoning,c=e.maxTokens??8192,d={model:e.model,messages:a,max_tokens:c,stream:!0};if(l&&(d.system=l),e.tools&&e.tools.length>0){let f=e.tools.map(xm);this.enablePromptCaching&&f.length>0&&(f[f.length-1].cache_control={type:"ephemeral",scope:"global"}),d.tools=f,e.toolChoice&&(d.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})}if(!u&&e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(d.temperature=e.temperature)),!u&&e.topP!==void 0&&(d.top_p=e.topP),u)if(this.quirks.useEffortInsteadOfBudget){d.thinking={type:"enabled"};let f=this.quirks.maxReasoningEffort??"high",b=e.reasoning?.effort??"high",h=b==="low"||b==="medium"?"high":f;if(d.output_config={effort:h},i){let k=2166136261;for(let x=0;x<i.length;x++)k^=i.charCodeAt(x),k=Math.imul(k,16777619);d.metadata={user_id:`qa-${(k>>>0).toString(36)}`}}}else if(ym(e.model))d.thinking={type:"adaptive"};else{let f=km(e.reasoning.effort,e.maxTokens);d.thinking={type:"enabled",budget_tokens:Math.min(c-1,f)}}let p=bm(e.model,u,(e.tools?.length??0)>0),m={"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion};p.length>0&&(m["anthropic-beta"]=p.join(","));let g=null;for(let f=0;f<=this.maxRetries;f++){if(n?.aborted)throw new Error("Request aborted");f>0&&g&&await Me(Ae(f),n);try{yield*this.streamWithWatchdog(o,m,d,n);return}catch(b){g=b instanceof Error?b:new Error(String(b));let h=Sm(g.message),k=h!==null&&lr.has(h),x=g.message.includes("Stream idle timeout");if(g.message.includes("model_context_window_exceeded")||g.message.includes("context_length_exceeded")||!k&&!x)throw g;if(f===this.maxRetries){if((x||k)&&!e.streamRequired)try{yield*this.nonStreamingFallback(o,m,d,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 l=null,u=!1,c=()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{u=!0},this.streamIdleTimeoutMs)},d=()=>{l!==null&&(clearTimeout(l),l=null)};c();try{yield*this.parseSSEStream(a.body,c,()=>u)}finally{d()}if(u)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,n,o){let s=Rm({...n,stream:!1}),i=AbortSignal.timeout(cm),a=o?AbortSignal.any([o,i]):i,l=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>""),d=new Error(`Anthropic API error ${l.status}: ${c.slice(0,500)}`);throw d.status=l.status,d}let u=await l.json();yield*this.mapNonStreamingResponse(u)}*mapNonStreamingResponse(e){let t=e.usage;t&&(yield{type:"usage",promptTokens:t.input_tokens??0,completionTokens:t.output_tokens??0,cacheReadTokens:t.cache_read_input_tokens>0?t.cache_read_input_tokens:void 0,cacheCreationTokens:t.cache_creation_input_tokens>0?t.cache_creation_input_tokens:void 0});let n=e.content;if(Array.isArray(n)){let s=0;for(let i of n){let a=i.type;a==="text"?yield{type:"delta",text:i.text}:a==="thinking"?yield{type:"reasoning_delta",text:i.thinking}:a==="tool_use"&&(yield{type:"tool_call_delta",index:s++,id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})})}}let o=e.stop_reason;o&&(yield{type:"done",finishReason:oa(o)})}async*parseSSEStream(e,t,n){let o=new TextDecoder,s="",i="",a=new Map,l={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};for await(let u of e){if(t(),n())break;s+=o.decode(u,{stream:!0});let c;for(;(c=s.indexOf(`
36
- `))!==-1;){let d=s.slice(0,c).trim();if(s=s.slice(c+1),!d){i="";continue}if(d.startsWith("event:")){i=d.slice(6).trimStart();continue}if(!d.startsWith("data:"))continue;let p=d.slice(5).trimStart(),m;try{m=JSON.parse(p)}catch{continue}yield*this.mapEvent(i,m,a,l)}}}*mapEvent(e,t,n,o){switch(e){case"message_start":{let i=t.message?.usage;i&&(na(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});break}case"content_block_start":{let s=t.index,i=t.content_block;if(!i)break;let a=i.type;n.set(s,{type:a,id:i.id,name:i.name,signature:a==="thinking"?"":void 0}),a==="tool_use"&&(yield{type:"tool_call_delta",index:s,id:i.id,name:i.name,arguments:""});break}case"content_block_delta":{let s=t.index,i=t.delta;if(!i)break;let a=i.type;if(a==="text_delta")yield{type:"delta",text:i.text};else if(a==="input_json_delta")yield{type:"tool_call_delta",index:s,arguments:i.partial_json};else if(a==="thinking_delta")yield{type:"reasoning_delta",text:i.thinking};else if(a==="signature_delta"){let l=n.get(s);l&&typeof i.signature=="string"&&(l.signature=i.signature)}break}case"content_block_stop":{let s=t.index,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&&(na(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}),s?.stop_reason&&(yield{type:"done",finishReason:oa(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 na(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)}function oa(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}}var cr={high:16e3,medium:8e3,low:4e3};function km(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 cr.high}return cr[r]??cr.high}function Tm(r,e){if(r)return e?[{type:"text",text:r,cache_control:{type:"ephemeral",scope:"global"}}]:r}function wm(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(c=>t.has(c.id)?!1:(t.add(c.id),!0)),i=new Set(s.map(c=>c.id)),a=new Set,l=r.slice(n+1);for(let c of l){if(c.role!=="tool")break;c.tool_call_id&&a.add(c.tool_call_id)}s.length!==o.tool_calls.length?e.push({...o,tool_calls:s}):e.push(o);let u=[...i].filter(c=>!a.has(c));for(let c of u){let d=s.find(p=>p.id===c);e.push({role:"tool",tool_call_id:c,name:d?.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}function vm(r,e={}){let t,n=[];for(let o of r){if(o.role==="system"){t=t?`${t}
37
-
38
- ${o.content??""}`:o.content??"";continue}if(o.role==="user")if(o.imageUrls&&o.imageUrls.length>0&&!e.filterImageBlocks){let i=[];o.content&&i.push({type:"text",text:o.content});for(let a of o.imageUrls)if(a.startsWith("data:")){let l=/^data:([^;]+);base64,(.+)$/.exec(a);if(l){let u=l[1];u==="application/pdf"?i.push({type:"document",source:{type:"base64",media_type:u,data:l[2]}}):i.push({type:"image",source:{type:"base64",media_type:u,data:l[2]}})}}else a.endsWith(".pdf")||a.includes(".pdf?")?i.push({type:"document",source:{type:"url",url:a}}):i.push({type:"image",source:{type:"url",url:a}});n.push({role:"user",content:i})}else n.push({role:"user",content:o.content??""});else if(o.role==="assistant"){let s=e.filterThinkingBlocks?void 0:o.thinkingBlocks;if(o.tool_calls&&o.tool_calls.length>0){let i=[];if(s)for(let a of s)a.signature&&i.push({type:"thinking",thinking:a.thinking,signature:a.signature});o.content&&i.push({type:"text",text:o.content});for(let a of o.tool_calls){let l;try{l=JSON.parse(a.function.arguments)}catch{l={}}i.push({type:"tool_use",id:a.id,name:a.function.name,input:l})}n.push({role:"assistant",content:i})}else if(s&&s.length>0){let i=[];for(let a of s)a.signature&&i.push({type:"thinking",thinking:a.thinking,signature:a.signature});o.content&&i.push({type:"text",text:o.content}),n.push({role:"assistant",content:i})}else n.push({role:"assistant",content:o.content??""})}else if(o.role==="tool"){let s=o.content??"",i=s.startsWith("Error:")||s===dm,a={type:"tool_result",tool_use_id:o.tool_call_id??"",content:s,...i&&{is_error:!0}},l=n[n.length-1];l&&l.role==="user"&&Array.isArray(l.content)?l.content.push(a):n.push({role:"user",content:[a]})}}return{system:t,messages:n}}function xm(r){return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters??{type:"object",properties:{}}}}function Sm(r){let e=/Anthropic API error (\d{3})/.exec(r);return e?parseInt(e[1],10):null}function Rm(r){let e=typeof r.max_tokens=="number"?r.max_tokens:8192,t=Math.min(e,um),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 xn=class{baseUrl;extraHeaders;timeoutMs;quirks;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??{}}async*stream(e,t,n){let s=`${this.baseUrl.replace(/\/v\d+$/,"")}/v3/responses`,i=this.buildRequestBody(e),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders};if(e.builtinTools&&!e.disableBuiltinTools&&e.builtinTools.length>0)for(let u of e.builtinTools)u.type==="builtin_web_search"?a["ark-beta-web-search"]="true":u.type==="builtin_image_process"?a["ark-beta-image-process"]="true":u.type==="builtin_knowledge_search"?a["ark-beta-knowledge-search"]="true":u.type==="builtin_doubao_app"&&(a["ark-beta-doubao-app"]="true");let l=null;for(let u=0;u<=3;u++){if(n?.aborted)throw new Error("Request aborted");u>0&&l&&await Me(Ae(u),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(c){l=c instanceof Error?c:new Error(String(c));let d=l.message.includes("Stream idle timeout");if(!Le($e(l))&&!d||u===3)throw l}}}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}buildRequestBody(e){let t=this.resolveConstraints(e),n={model:t.model,input:_m(t.messages),stream:!0};if(t.previousResponseId&&(n.previous_response_id=t.previousResponseId),t.store!==void 0&&(n.store=t.store),t.storeExpireAt!==void 0&&(n.expire_at=t.storeExpireAt),t.instructions&&(n.instructions=t.instructions),t.structuredOutput)if(t.structuredOutput.mode==="json_object")n.text={format:{type:"json_object"}};else{let s={type:"json_schema",name:t.structuredOutput.name,schema:t.structuredOutput.schema};t.structuredOutput.strict!==void 0&&(s.strict=t.structuredOutput.strict),n.text={format:s}}if(t.caching){let s={type:t.caching.type};t.caching.prefix!==void 0&&(s.prefix=t.caching.prefix),n.caching=s,t.caching.prefix&&(n.stream=!1)}if(t.contextManagement){let s=t.contextManagement.edits.map(i=>{let a={type:i.type};return i.type==="clear_thinking"&&i.keep!==void 0?a.keep=i.keep:i.type==="clear_tool_uses"&&(i.trigger&&(a.trigger=i.trigger),i.keep&&(a.keep=i.keep),i.excludeTools&&(a.exclude_tools=i.excludeTools),i.clearToolInput!==void 0&&(a.clear_tool_input=i.clearToolInput)),a});n.context_management={edits:s}}let o=[];if(t.tools&&t.tools.length>0)for(let s of t.tools)o.push({type:"function",name:s.function.name,description:s.function.description,parameters:s.function.parameters});if(t.builtinTools&&!t.disableBuiltinTools&&t.builtinTools.length>0)for(let s of t.builtinTools){let a={type:s.type.replace(/^builtin_/,"")};s.config&&Object.assign(a,s.config),o.push(a)}if(o.length>0&&(n.tools=o),t.maxToolCalls!==void 0&&(n.max_tool_calls=t.maxToolCalls),t.toolChoice!==void 0&&(typeof t.toolChoice=="string"?n.tool_choice=t.toolChoice:n.tool_choice={type:t.toolChoice.type,name:t.toolChoice.name}),t.temperature!==void 0&&(n.temperature=t.temperature),t.topP!==void 0&&(n.top_p=t.topP),t.maxTokens!==void 0&&(n.max_output_tokens=t.maxTokens),t.reasoning){let s=t.reasoning.effort??"high";s==="minimal"?n.thinking={type:"disabled"}:(n.thinking={type:"enabled"},n.reasoning={effort:s}),t.reasoning.includeEncryptedReasoning&&(n.include=["reasoning.encrypted_content"])}return t.prefixMessage&&n.input.push({role:"assistant",content:t.prefixMessage,partial:!0}),n}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 u=await a.text().catch(()=>""),c=new Error(`Volcengine Responses API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("Volcengine Responses API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.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,l=new Map,u=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},Ce)};try{u();let c=e.getReader();try{for(;;){let{done:d,value:p}=await c.read();if(d)break;if(i.signal.aborted)throw new Error("Stream idle timeout");u(),n+=t.decode(p,{stream:!0});let m;for(;(m=n.indexOf(`
39
- `))!==-1;){let g=n.slice(0,m).trim();if(n=n.slice(m+1),!g){o="";continue}if(!g.startsWith(":")){if(g.startsWith("event:")){o=g.slice(6).trim();continue}if(g.startsWith("data:")){let f=g.slice(5).trim();if(f==="[DONE]")return;let b;try{b=JSON.parse(f)}catch{continue}yield*this.processEvent(o,b,l,()=>a++)}}}}}finally{c.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 l=n.get(i);l===void 0&&(l=o(),n.set(i,l)),yield{type:"tool_call_delta",index:l,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 l=o();n.set(i,l),yield{type:"tool_call_delta",index:l,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 l=a.annotations;l&&l.length>0&&(yield{type:"annotations",annotations:l.map(u=>({type:u.type??"url_citation",url:u.url,title:u.title,...u}))})}}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 u=a.input_tokens_details,c=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:c?.reasoning_tokens,cacheReadTokens:u?.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}}}};function _m(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 l=[];if(n)for(let u of t.imageUrls){let c={type:"input_image",image_url:u};t.imageDetail&&(c.detail=t.imageDetail),t.imagePixelLimit&&(c.image_pixel_limit=t.imagePixelLimit),l.push(c)}if(o)for(let u of t.videoUrls){let c={type:"input_video",video_url:u};t.videoFps!==void 0&&(c.fps=t.videoFps),l.push(c)}if(s)for(let u of t.audioUrls){let c={type:"input_audio",audio_url:u};t.audioFormat&&(c.format=t.audioFormat),l.push(c)}if(i)for(let u of t.fileIds)l.push({type:"input_file",file_id:u.id});t.content&&l.push({type:"input_text",text:t.content}),e.push({role:"user",content:l})}else e.push({role:"user",content:t.content??""});continue}if(t.role==="assistant"){e.push({role:"assistant",content:t.content??""});continue}if(t.role==="tool"){if(!t.tool_call_id)continue;e.push({type:"function_call_output",call_id:t.tool_call_id,output:t.content??""});continue}}return e}mo();var Cm=[{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 Am(r){switch(r){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";default:return"HIGH"}}var Nt=class{baseUrl;timeoutMs;quirks;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??{}}async*stream(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:streamGenerateContent?alt=sse`,s=this.buildRequestBody(e),i={"Content-Type":"application/json","x-goog-api-key":t},a=null;for(let l=0;l<=3;l++){if(n?.aborted)throw new Error("Request aborted");l>0&&a&&await Me(Ae(l),n);try{yield*this.fetchAndStream(o,i,s,n);return}catch(u){a=u instanceof Error?u:new Error(String(u));let c=a.message.includes("Stream idle timeout");if(!Le($e(a))&&!c)throw a;if(l===3){if((c||Le($e(a)))&&!e.streamRequired)try{yield*this.nonStreamingFallback(e,t,n);return}catch{throw a}throw a}}}}buildRequestBody(e){let{systemInstruction:t,contents:n}=Mm(e.messages),o={contents:n};t&&(o.system_instruction=t);let s=this.buildTools(e);s.length>0&&(o.tools=s),e.tools&&e.tools.length>0&&e.toolChoice&&(o.toolConfig=this.buildToolConfig(e.toolChoice));let i=this.buildGenerationConfig(e);return Object.keys(i).length>0&&(o.generationConfig=i),o.safetySettings=Cm,e.cachedContent&&(o.cachedContent=e.cachedContent),o}buildTools(e){let t=[];if(e.tools&&e.tools.length>0){let n=e.tools.map(Pm);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=Am(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 u=await a.text().catch(()=>""),c=new Error(`Gemini API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("Gemini API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.includes("text/event-stream")){let u=await a.json();yield*this.processResponse(u);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()},Ce)};try{i();let a=e.getReader();try{for(;;){let{done:l,value:u}=await a.read();if(l)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(u,{stream:!0});let c;for(;(c=n.indexOf(`
29
+ ${T}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:n,blockCount:f?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let d=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=a?.summaryModel?async b=>{try{let T=b.map(y=>`${y.name}(${y.arguments.slice(0,200)})`).join(", "),w=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:T}],tools:[],maxTokens:60},a.apiKey??this.apiKey),_="";for await(let y of w)y.type==="delta"&&(_+=y.text);return _.trim()||null}catch{return null}}:void 0,g={turnId:n,sessionId:e.sessionId,messages:c,tools:s,model:d,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},f;for await(let b of Wi(g,this.transport,this.toolInvoker,this.log))f=b,yield b;f?.type==="end"?this.hooks?.invoke("turn.completed",{...l}).catch(()=>{}):f?.type==="error"&&this.hooks?.invoke("turn.failed",{...l,code:f.code,error:f.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let g=m instanceof Error?m.message:String(m),f=typeof m?.status=="number"?m.status:void 0,b=lt(f,g);this.log.error(`turn ${n} error [${b}, retryable=${vo(b)}]: ${g}`),this.hooks?.invoke("turn.failed",{...l,code:b,error:g}).catch(()=>{}),yield{type:"error",turnId:n,error:g,code:b}}}}}});import{randomUUID as xe}from"node:crypto";import{createInterface as td}from"node:readline";var at=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
+ `)}start(){let e=td({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let n=t.trim();if(n)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}
31
+ `)}};lr();Zo();var _e=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 c=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${c}`)}return e.streamImage&&a.body?this.parseStreamingImage(a.body,e,o):{mediaUrls:((await a.json()).data??[]).map(c=>c.url).filter(c=>!!c),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:l,value:u}=await a.read();if(l)break;s+=o.decode(u,{stream:!0});let c;for(;(c=s.indexOf(`
32
+ `))!==-1;){let d=s.slice(0,c).trim();if(s=s.slice(c+1),!d||d.startsWith(":")||!d.startsWith("data:"))continue;let p=d.slice(5).trim();if(p==="[DONE]")break;try{let g=JSON.parse(p).data?.[0]?.url;g&&(i=g,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,l=e.referenceImages?.length??0,u=!!(e.imageUrl||l>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&&!u&&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"&&l>9)throw new Error(`Seedance 2.0 video edit: max 9 reference images (got ${l}).`);let c=[];switch(e.draftTaskId&&c.push({type:"draft_task",id:e.draftTaskId}),e.operation){case"multimodal_reference":{if(e.prompt&&c.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let T=0;T<e.referenceImages.length;T++){let w=e.imageRoles?.[T]??"reference_image";c.push({type:"image_url",image_url:{url:e.referenceImages[T]},role:w})}if(e.referenceVideos?.length)for(let T of e.referenceVideos)c.push({type:"video_url",video_url:{url:T},role:"reference_video"});if(e.referenceAudios?.length)for(let T of e.referenceAudios)c.push({type:"audio_url",audio_url:{url:T},role:"reference_audio"});break}case"extend":{if(e.sourceVideos?.length)for(let T of e.sourceVideos)c.push({type:"video_url",video_url:{url:T},role:"reference_video"});e.prompt&&c.push({type:"text",text:e.prompt});break}case"merge":for(let T of e.sourceVideos??[])c.push({type:"video_url",video_url:{url:T}});e.prompt&&c.push({type:"text",text:e.prompt});break;case"upscale":e.sourceVideos?.[0]&&c.push({type:"video_url",video_url:{url:e.sourceVideos[0]}}),c.push({type:"text",text:e.prompt||"upscale"});break;case"edit":for(let T of e.sourceVideos??[])c.push({type:"video_url",video_url:{url:T},role:"reference_video"});if(e.referenceImages?.length)for(let T of e.referenceImages)c.push({type:"image_url",image_url:{url:T},role:"reference_image"});e.prompt&&c.push({type:"text",text:e.prompt});break;default:{let T=(e.referenceVideos?.length??0)>0,w=(e.referenceAudios?.length??0)>0,_=(e.imageRoles?.length??0)>0;if(T||w||_){if(e.prompt&&c.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let y=0;y<e.referenceImages.length;y++){let C=e.imageRoles?.[y]??"reference_image";c.push({type:"image_url",image_url:{url:e.referenceImages[y]},role:C})}if(T)for(let y of e.referenceVideos)c.push({type:"video_url",video_url:{url:y},role:"reference_video"});if(w)for(let y of e.referenceAudios)c.push({type:"audio_url",audio_url:{url:y},role:"reference_audio"})}else if(e.referenceImages?.length){for(let y of e.referenceImages)c.push({type:"image_url",image_url:{url:y}});e.prompt&&c.push({type:"text",text:e.prompt})}else e.imageUrl?(c.push({type:"image_url",image_url:{url:e.imageUrl}}),e.prompt&&c.push({type:"text",text:e.prompt})):e.prompt&&c.push({type:"text",text:e.prompt});break}}let d={model:e.model,content:c};e.duration&&(d.duration=e.duration),e.aspectRatio&&(d.ratio=e.aspectRatio),e.resolution&&(d.resolution=e.resolution),e.seed!==void 0&&(d.seed=e.seed),e.fps&&(d.fps=e.fps),e.generateAudio!==void 0&&(d.generate_audio=e.generateAudio),e.watermark!==void 0&&(d.watermark=e.watermark),e.enhancePrompt!==void 0&&(d.enhance_prompt=e.enhancePrompt),e.cameraFixed!==void 0&&(d.camera_fixed=e.cameraFixed),e.returnLastFrame!==void 0&&(d.return_last_frame=e.returnLastFrame),e.serviceTier&&(d.service_tier=e.serviceTier),e.executionExpiresAfterSeconds!==void 0&&(d.execution_expires_after=e.executionExpiresAfterSeconds),e.draft!==void 0&&(d.draft=e.draft),e.safetyIdentifier&&(d.safety_identifier=e.safetyIdentifier),e.callbackUrl&&(d.callback_url=e.callbackUrl),e.videoTools?.length&&(d.tools=e.videoTools.map(T=>({type:T})));let p=await this.submitTask(s,d,t,n),m=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${p}`,t,n,e.onProgress,p),g=[],f=m.content;typeof f?.video_url=="string"&&g.push(f.video_url);let b=typeof f?.last_frame_url=="string"?f.last_frame_url:void 0;return{mediaUrls:g,model:e.model,durationMs:Date.now()-o,lastFrameUrl:b,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 l={model:e.model,content:i},u=await this.submitTask(s,l,t,n),c=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${u}`,t,n,e.onProgress,u),d=[],p=c.content;if(typeof p?.video_url=="string"&&d.push(p.video_url),d.length===0&&p)for(let[,g]of Object.entries(p))typeof g=="string"&&/^https?:\/\//.test(g)&&d.push(g);let m=c.output;if(m?.model_urls){let g=m.model_urls;for(let f of Object.values(g))f&&!d.includes(f)&&d.push(f)}if(d.length===0){let g=Object.keys(c),f=p?Object.keys(p):[],b=m?Object.keys(m):[];console.error(`[volcengine-3d] No media URLs found. Response keys: [${g}], content keys: [${f}], output keys: [${b}]`);let T=c.data;if(T?.content){let w=T.content;for(let[,_]of Object.entries(w))typeof _=="string"&&/^https?:\/\//.test(_)&&d.push(_)}}return{mediaUrls:d,model:e.model,durationMs:Date.now()-o,metadata:d.length===0?{debugResponseKeys:Object.keys(c),debugContentKeys:p?Object.keys(p):null,debugContentSample:p?JSON.stringify(p).slice(0,500):null,debugOutputKeys:m?Object.keys(m):null,debugResultSample:JSON.stringify(c).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 l=await s.text().catch(()=>"");throw new Error(`Volcengine task status error ${s.status}: ${l}`)}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 l=await a.text().catch(()=>"");throw new Error(`Volcengine list tasks error ${a.status}: ${l}`)}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 u=await a.text().catch(()=>"");throw new Error(`Volcengine file upload error ${a.status}: ${u}`)}let l=await a.json();return{id:String(l.id??""),status:String(l.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 l=await a.text().catch(()=>"");throw new Error(`Volcengine list files error ${a.status}: ${l}`)}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 l=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${l}`)}let i=await s.json(),a=i.id??i.task_id;if(!a)throw new Error("Volcengine task submit: no task_id in response");return a}async pollTask(e,t,n,o,s){let i=Date.now()+6e5,a=0;for(;Date.now()<i;){n?.throwIfAborted();let l=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`Volcengine task poll error ${l.status}: ${m}`)}let u=await l.json(),c=u.status;if(c==="succeeded"||c==="complete")return o?.(100,"completed",s),u;if(c==="failed"||c==="cancelled"){let m=u.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${m}`)}a++;let d=Date.now()-(i-6e5),p=Math.min(95,Math.round(d/6e5*100));o?.(p,c??"running",s),await new Promise(m=>setTimeout(m,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as qp,mkdirSync as Kp}from"node:fs";import{join as ia}from"node:path";import{randomUUID as Jp}from"node:crypto";import{homedir as zp}from"node:os";import{join as Z}from"node:path";var ye=".qlogicagent";function G(){return Z(zp(),ye)}function cr(){return Z(G(),"sessions")}function zi(r){return Z(cr(),r)}function qi(){return Z(G(),"plugins")}function ur(){return Z(G(),"skills")}function dt(){return Z(G(),"settings.json")}function Re(){return Z(G(),"cache")}function Ki(){return Z(G(),"debug-logs")}function Ji(r){let e=Z(G(),"checkpoints");return r?Z(e,r):e}function Yi(){return Z(G(),"plugin-cache")}function Xi(){return Z(G(),"mcp.json")}function Qi(){return Z(G(),"marketplace.json")}function Zi(){return Z(G(),"workflows")}function ea(){return Z(G(),"rules")}function je(r){return Z(r??process.cwd(),ye)}function ta(r){return Z(je(r),"workflows")}function na(r){return Z(je(r),"INSTRUCTIONS.md")}function oa(r){return Z(je(r),"rules")}function ra(r){return Z(je(r),"sessions")}function sa(r){return Z(r,ye,"hooks")}var Yp=18e4,It=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Yp}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 c=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${c}`)}return{mediaUrls:((await a.json()).data??[]).map(c=>c.url).filter(c=>!!c),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 l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${l.status}: ${m}`)}let u=Buffer.from(await l.arrayBuffer()),c=ia(Re(),"tts");Kp(c,{recursive:!0});let d=`openai-tts-${Jp()}.mp3`,p=ia(c,d);return qp(p,u),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-o,billingUnit:"per_character",billingQuantity:s.length}}};var Ze=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 l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax music rejected: ${l.base_resp.status_msg??"unknown"}`);let u=l.data?.audio??l.audio_file;if(u)return{mediaUrls:[u],model:e.model,durationMs:Date.now()-o};let c=l.task_id;if(!c)throw new Error("MiniMax music: no audio_file or task_id in response");let d=`${this.baseUrl}/v1/music_generation/${c}`;return{mediaUrls:(await this.pollTask(d,t,n,e.onProgress,c)).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 d=await a.text().catch(()=>"");throw new Error(`MiniMax music poll error ${a.status}: ${d}`)}let l=await a.json(),u=l.status;if(u==="Success"||u==="Finished"){o?.(100,"completed",s);let d=[];return l.audio_file&&d.push(l.audio_file),{audioUrls:d}}if(u==="Failed"||u==="Cancelled")throw new Error(`MiniMax music task failed: ${l.base_resp?.status_msg??"unknown"}`);let c=Date.now()-(i-6e5);o?.(Math.min(95,Math.round(c/6e5*100)),u??"running",s),await new Promise(d=>setTimeout(d,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 d=e.imageRoles.includes("first_frame"),p=e.imageRoles.includes("last_frame");if(d&&p){let m=e.imageRoles.indexOf("first_frame"),g=e.imageRoles.indexOf("last_frame");i.first_frame_image=e.referenceImages[m],i.last_frame_image=e.referenceImages[g]}else if(d){let m=e.imageRoles.indexOf("first_frame");i.first_frame_image=e.referenceImages[m]}else i.subject_reference=e.referenceImages.map((m,g)=>({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 d=await a.text().catch(()=>"");throw new Error(`MiniMax video submit error ${a.status}: ${d}`)}let l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax video rejected: ${l.base_resp.status_msg??"unknown"}`);let u=l.task_id;if(!u)throw new Error("MiniMax video: no task_id in response");let c=await this.pollVideoTask(u,t,n,e.onProgress);return{mediaUrls:c.downloadUrl?[c.downloadUrl]:[],model:e.model||"S2V-01",durationMs:Date.now()-o,taskId:u,metadata:{fileId:c.fileId,width:c.width,height:c.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 l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax video task error ${l.base_resp.status_code}: ${l.base_resp.status_msg??""}`);let u=l.status;if(u==="Success"){o?.(100,"completed",e);let m;if(l.file_id)try{m=await this.getFileDownloadUrl(l.file_id,t,n)}catch{}return{fileId:l.file_id,downloadUrl:m,width:l.video_width,height:l.video_height}}if(u==="Fail")throw new Error(`MiniMax video task failed: ${l.base_resp?.status_msg??"unknown"}`);let c=u??"running",d=Date.now()-(s-6e5),p=Math.min(95,Math.round(d/6e5*100));o?.(p,c,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 l=await s.text().catch(()=>"");throw new Error(`MiniMax file retrieve error ${s.status}: ${l}`)}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 u=await s.text().catch(()=>"");throw new Error(`MiniMax task status error ${s.status}: ${u}`)}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 la,mkdirSync as ca}from"node:fs";import{join as Tn}from"node:path";import{randomUUID as ua}from"node:crypto";import{writeFileSync as Xp,mkdirSync as Qp}from"node:fs";import{join as aa}from"node:path";import{randomUUID as Zp}from"node:crypto";var kn=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",l),s()},l=()=>{o.removeEventListener("open",a),i(new Error("Lyria RealTime WebSocket connection failed"))};o.addEventListener("open",a,{once:!0}),o.addEventListener("error",l,{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 dr(r,e,t){let n=t.durationSeconds??30,o=Date.now(),s=new kn(e),i=[];s.onAudioChunk=l=>{i.push(l.data)};let a=null;s.onError=l=>{a=l};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 l=Date.now()+n*1e3,u=500;for(;Date.now()<l;){if(t.signal?.throwIfAborted(),a)throw a;if(!s.connected)break;let f=Date.now()-o,b=n*1e3,T=Math.min(95,Math.round(10+f/b*85));t.onProgress?.(T,"streaming"),await new Promise(w=>setTimeout(w,u))}s.connected&&await s.stop(),t.onProgress?.(98,"assembling");let c=Buffer.concat(i),d=em(c,48e3,2,16),p=aa(Re(),"gemini-music-realtime");Qp(p,{recursive:!0});let m=`lyria-rt-${Zp()}.wav`,g=aa(p,m);return Xp(g,d),t.onProgress?.(100,"completed"),{filePath:`file://${g}`,durationMs:Date.now()-o}}finally{s.close()}}function em(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 tm=18e4,nm=1e4,pr=6e5,Et=class{supportedTypes=["image","video","music","music_realtime","tts","embedding"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??tm}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 l=await s.text().catch(()=>"");throw new Error(`Gemini operation query error ${s.status}: ${l}`)}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},l=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineImages(l),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 b=>({image:{inlineData:await this.resolveImageData(b)},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 l={instances:[i]};Object.keys(a).length>0&&(l.parameters=a);let c=(await this.postJson(s,l,t,n)).name;if(!c)throw new Error("Gemini video submit: no operation name in response");let d=c;e.onProgress?.(5,"submitted",d);let g=(await this.pollOperation(c,t,n,e.onProgress,d)).response?.generateVideoResponse?.generatedSamples??[],f=[];for(let b of g)b.video?.uri&&f.push(b.video.uri);return{mediaUrls:f,model:e.model,durationMs:Date.now()-o,taskId:d}}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 l={contents:[{parts:i}]};Object.keys(a).length>0&&(l.generationConfig=a);let u=await this.postJson(s,l,t,n);return{mediaUrls:this.extractInlineAudio(u,"gemini-music"),model:e.model,durationMs:Date.now()-o}}async generateMusicRealtime(e,t,n){let o=await dr(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},l=await this.postJson(s,a,t,n);return{mediaUrls:this.extractInlineAudio(l,"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 u=(await this.postJson(s,i,t,n)).embeddings?.[0]?.values??[];return{mediaUrls:[],model:e.model,durationMs:Date.now()-o,metadata:{embedding:u,dimensions:u.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()+pr;for(;Date.now()<i;){n?.throwIfAborted();let a=`${this.apiBase}/${e}`,l=await fetch(a,{method:"GET",headers:{"x-goog-api-key":t},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`Gemini operation poll error ${l.status}: ${p}`)}let u=await l.json();if(u.done===!0)return o?.(100,"completed",s),u;if(u.error){let p=u.error;throw new Error(`Gemini video generation failed: ${p.message??JSON.stringify(p)}`)}let c=Date.now()-(i-pr),d=Math.min(95,Math.round(c/pr*100));o?.(d,"running",s),await new Promise(p=>setTimeout(p,nm))}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"),l=i.split(".").pop()?.toLowerCase()??"png";return{mimeType:l==="jpg"||l==="jpeg"?"image/jpeg":l==="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=Tn(Re(),"gemini-images");ca(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-${ua()}.${i}`,l=Tn(n,a);la(l,Buffer.from(s.inlineData.data,"base64")),t.push(`file://${l}`)}return t}extractInlineAudio(e,t){let n=[],o=Tn(Re(),t);ca(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",l=Buffer.from(i.inlineData.data,"base64"),u=a==="pcm"?om(l,24e3,1,16):l,c=`gemini-${ua()}.${a==="pcm"?"wav":a}`,d=Tn(o,c);la(d,u),n.push(`file://${d}`)}return n}};function om(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 wn=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},l={text:s};e.voice&&(l.voice=e.voice),e.speed!==void 0&&(a.speech_rate=e.speed);let u={model:e.model||"qwen3-tts-voicedesign",input:l,parameters:a},c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(u),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${c.status}: ${g}`)}let d=await c.json();if(d.code)throw new Error(`DashScope TTS submit rejected: ${d.code} \u2014 ${d.message??""}`);let p=d.output?.task_id;if(!p)throw new Error("DashScope TTS submit: no task_id in response");if(d.output?.task_status==="SUCCEEDED"){let g=this.extractMediaUrl(d);return{mediaUrls:g?[g]:[],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 rm(2e3);let l=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${l.status}: ${p}`)}let u=await l.json();if(u.code)throw new Error(`DashScope poll rejected: ${u.code} \u2014 ${u.message??""}`);let c=u.output?.task_status;if(c==="SUCCEEDED"){o?.(100,"completed",e);let p=this.extractMediaUrl(u);return p?[p]:[]}if(c==="FAILED")throw new Error(`DashScope task failed: ${u.message??"unknown error"}`);let d=Date.now()-(i-s);o?.(Math.min(95,Math.round(d/s*100)),c??"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 g=e.imageRoles.indexOf("first_frame"),f=e.imageRoles.indexOf("last_frame");g>=0&&(i.img_url=e.referenceImages[g]),f>=0&&(i.tail_image_url=e.referenceImages[f]);let b=e.imageRoles.map((T,w)=>T==="reference_image"?w:-1).filter(T=>T>=0);b.length>0&&(i.ref_image_url=e.referenceImages[b[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 l=`${this.baseUrl}/api/v1/services/aigc/generation/generation`,u={model:s,input:i};Object.keys(a).length>0&&(u.parameters=a);let c=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(u),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`DashScope video submit error ${c.status}: ${g}`)}let d=await c.json();if(d.code)throw new Error(`DashScope video submit rejected: ${d.code} \u2014 ${d.message??""}`);let p=d.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 c=await s.text().catch(()=>"");throw new Error(`DashScope task status error ${s.status}: ${c}`)}let i=await s.json(),l=i.output?.task_status??"unknown";return{status:l==="SUCCEEDED"?"succeeded":l==="FAILED"?"failed":l.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 rm(r){return new Promise(e=>setTimeout(e,r))}import{writeFileSync as sm,mkdirSync as im}from"node:fs";import{join as da}from"node:path";import{randomUUID as am}from"node:crypto";var lm=18e4,cm=3e3,vn=6e5,um=new Set(["glm-image"]),Ot=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??lm}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 um.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(c=>c.url).filter(c=>!!c),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 l=(await this.postJSON(s,i,t,n)).id;if(!l)throw new Error("Zhipu async image: no task id in response");return{mediaUrls:((await this.pollAsyncResult(l,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 l=(await this.postJSON(s,i,t,n)).id;if(!l)throw new Error("Zhipu video generation: no task id in response");return{mediaUrls:((await this.pollAsyncResult(l,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 l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let g=await l.text().catch(()=>"");throw new Error(`Zhipu TTS API error ${l.status}: ${g}`)}let u=Buffer.from(await l.arrayBuffer()),c=da(Re(),"tts");im(c,{recursive:!0});let d=e.audioFormat??"wav",p=`zhipu-tts-${am()}.${d}`,m=da(c,p);return sm(m,u),{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(),l=new FormData;l.append("model",e.model||"glm-asr-2512"),l.append("file",a,"audio.wav");let u=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:l,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`Zhipu STT API error ${u.status}: ${d}`)}let c=await u.json();return{mediaUrls:[],model:e.model||"glm-asr-2512",durationMs:Date.now()-o,metadata:{transcription:c.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},u=(await this.postJSON(i,a,t,n)).data??[];return{mediaUrls:[],model:e.model||"embedding-3",durationMs:Date.now()-o,metadata:{embeddings:u.map(c=>c.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 l=`${this.baseUrl}/voice/clone`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:a,signal:n??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let p=await u.text().catch(()=>"");throw new Error(`Zhipu Voice Clone API error ${u.status}: ${p}`)}let c=await u.json();return{mediaUrls:(c.data??[]).map(p=>p.url).filter(p=>!!p),model:e.model||"glm-tts-clone",durationMs:Date.now()-o,metadata:{voiceId:c.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 c=(await this.postJSON(i,a,t,n)).pages??[];return{mediaUrls:[],model:e.model||"glm-ocr",durationMs:Date.now()-o,metadata:{pages:c.map(d=>({pageNum:d.page_num,content:d.content,layouts:d.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 l=await this.postJSON(i,a,t,n);return{mediaUrls:[],model:e.model||"rerank",durationMs:Date.now()-o,metadata:{results:(l.results??[]).map(u=>({index:u.index,relevanceScore:u.relevance_score,document:u.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()+vn,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 c=await a.text().catch(()=>"");throw new Error(`Zhipu async-result error ${a.status}: ${c}`)}let l=await a.json();if(l.task_status==="SUCCESS")return o?.(100,"completed",e),l;if(l.task_status==="FAIL")throw new Error("Zhipu async task failed");let u=Date.now()-(s-vn);o?.(Math.min(95,Math.round(u/vn*100)),l.task_status??"running",e),await new Promise(c=>setTimeout(c,cm))}throw new Error(`Zhipu async task timed out after ${vn/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 u=await s.text().catch(()=>"");throw new Error(`Zhipu task query error ${s.status}: ${u}`)}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 Lt=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=mm(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?dm(n):void 0,a=s.find(l=>l.mediaType!==t?!1:!i||!l.mediaCapabilities?!0:pm(l.mediaCapabilities,i));if(a)return{providerId:e,providerDef:o,modelInfo:a,mediaType:t}}};function dm(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 pm(r,e){return!("operations"in r)||!r.operations?!0:r.operations.includes(e)}function mm(r){let e=r.baseUrl;switch(r.id){case"volcengine":return new _e({baseUrl:e});case"openai":return new It({baseUrl:e});case"minimax":return new Ze({baseUrl:e});case"google":return new Et({baseUrl:e});case"qwen":return new wn({baseUrl:e});case"zhipu":return new Ot({baseUrl:e.replace(/\/api\/anthropic\/?$/,"/api/paas/v4")});case"zhipu-openai":case"zhipu-coding":return new Ot({baseUrl:e.replace(/\/api\/coding\/paas\/v4\/?$/,"/api/paas/v4")});default:return}}var mr=[{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 gm,mkdirSync as fm,readFileSync as hm,writeFileSync as ym}from"node:fs";import{join as bm}from"node:path";var km="https://models.dev/api.json",Tm=3e4,wm=1440*60*1e3,vm=300*1e3,xm={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"},$t=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??Re(),this.cacheFile=bm(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??wm}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(!gm(this.cacheFile))return;let e=hm(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:pa(t.data)}}catch{}}saveToDisk(e){try{fm(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);ym(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<vm||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(km,{signal:AbortSignal.timeout(Tm),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=pa(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function pa(r){let e=new Map;if(!r||typeof r!="object")return e;for(let[t,n]of Object.entries(r)){let o=xm[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[l,u]of Object.entries(i)){if(!u||typeof u!="object"||a.models.has(l))continue;let c=u,d=c.cost??{},p=c.limit??{},m=c.modalities??{},g=Array.isArray(m.input)?m.input:[],f=Array.isArray(m.output)?m.output:[],b=Sm(f,g,l);a.models.set(l,{id:l,name:typeof c.name=="string"?c.name:l,contextWindow:typeof p.context=="number"?p.context:2e5,maxOutput:typeof p.output=="number"?p.output:8192,toolCall:c.tool_call===!0,reasoning:c.reasoning===!0,vision:c.attachment===!0||g.includes("image"),costInput:typeof d.input=="number"?d.input:void 0,costOutput:typeof d.output=="number"?d.output:void 0,costCacheRead:typeof d.cache_read=="number"?d.cache_read:void 0,costCacheWrite:typeof d.cache_write=="number"?d.cache_write:void 0,mediaType:b})}}return e}function Sm(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 _m={claude:"anthropic",gemini:"google",doubao:"volcengine"},Dt=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of mr)this.builtins.set(t.id,t);this.catalog=e?.catalog??new $t}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=_m[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 gr=new Set([429,529,502,503,504]),Ae=9e4;function Me(r){let e=Math.min(1e3*Math.pow(2,r-1),3e4),t=Math.random()*.25*e;return e+t}function Le(r){return r!=null&&gr.has(r)}function Pe(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 $e(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 xn(r){return r.toLowerCase().startsWith("gpt-5")}function Sn(r){return r.toLowerCase().includes("5.4-nano")}function Ut(r){return/^o[1-4](-|$)/.test(r.toLowerCase())}var pt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;quirks;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??{}}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:Cm(e.messages,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 l=!e.disableBuiltinTools,u=!1;if(l&&this.quirks.builtinWebSearch&&a.tools){let f=a.tools;this.quirks.builtinCodeInterpreter?f.push({type:"web_search",web_search:{enable:!0,search_result:!0}}):(f.push({type:"builtin_function",function:{name:"$web_search"}}),u=!0)}l&&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 c=this.quirks.useEffortInsteadOfBudget&&!!e.reasoning,d=e.model.startsWith("kimi-k2.6"),p=xn(e.model);if(e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p||!Ut(e.model)&&!c&&!d)&&(a.temperature=e.temperature)),e.topP!==void 0&&(p||!Ut(e.model)&&!c&&!d)&&(a.top_p=e.topP),e.maxTokens!==void 0&&(p||Ut(e.model)||e.model.startsWith("kimi-k2")?a.max_completion_tokens=e.maxTokens:a.max_tokens=e.maxTokens),e.reasoning)if(p){let f=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;Sn(e.model)&&(f==="high"||f==="xhigh")&&(f="medium"),a.reasoning={effort:f}}else if(Ut(e.model))a.reasoning_effort=e.reasoning.effort;else if(this.quirks.useEffortInsteadOfBudget){a.thinking={type:"enabled"};let f=this.quirks.maxReasoningEffort??"high",b=e.reasoning.effort??"high";a.reasoning_effort=b==="low"||b==="medium"?"high":f}else this.quirks.supportsThinkingParam?(u?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 u&&(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},g=null;for(let f=0;f<=3;f++){if(n?.aborted)throw new Error("Request aborted");f>0&&g&&await Pe(Me(f),n);try{yield*this.fetchAndStream(i,m,a,n);return}catch(b){g=b instanceof Error?b:new Error(String(b));let T=g.message.includes("Stream idle timeout");if(!Le($e(g))&&!T||f===3)throw g}}}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 u=await a.text().catch(()=>""),c=new Error(`LLM API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("LLM API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.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()},Ae)};try{i();let a=e.getReader();try{for(;;){let{done:l,value:u}=await a.read();if(l)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(u,{stream:!0});let c;for(;(c=n.indexOf(`
33
+ `))!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),!d||d.startsWith(":")||!d.startsWith("data: "))continue;let p=d.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:Rm(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},l=AbortSignal.timeout(this.timeoutMs),u=n?AbortSignal.any([n,l]):l,c=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(i),signal:u});if(!c.ok){let g=await c.text().catch(()=>"");throw new Error(`FIM API error ${c.status}: ${g.slice(0,500)}`)}if(!c.body)throw new Error("FIM API returned no response body");let d=new TextDecoder,p="",m=c.body.getReader();try{for(;;){let{done:g,value:f}=await m.read();if(g)break;p+=d.decode(f,{stream:!0});let b;for(;(b=p.indexOf(`
34
+ `))!==-1;){let T=p.slice(0,b).trim();if(p=p.slice(b+1),!T||T.startsWith(":")||!T.startsWith("data: "))continue;let w=T.slice(6);if(w==="[DONE]")return;let _;try{_=JSON.parse(w)}catch{continue}for(let y of _.choices??[])y.text&&(yield{type:"delta",text:y.text}),y.finish_reason&&(yield{type:"done",finishReason:y.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`,l=new FormData;l.append("file",e,t),l.append("purpose",n);let u=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`,...this.extraHeaders},body:l,signal:s??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`File upload error ${u.status}: ${d}`)}let c=await u.json();return{fileId:c.id??"",filename:c.filename??t,bytes:c.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 l=await i.text().catch(()=>"");throw new Error(`File info error ${i.status}: ${l}`)}let a=await i.json();return{id:a.id??e,filename:a.filename??"",bytes:a.bytes??0,status:a.status??"unknown"}}};function Rm(r){switch(r){case"sensitive":return"content_filter";case"model_context_window_exceeded":return"length";case"network_error":return"error";default:return r}}function Cm(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 l=[];if(t.content&&l.push({type:"text",text:t.content}),n)for(let u of t.imageUrls){let c={url:u};t.imageDetail&&(c.detail=t.imageDetail),l.push({type:"image_url",image_url:c})}if(o)for(let u of t.videoUrls)l.push({type:"video_url",video_url:{url:u}});if(s)for(let u of t.audioUrls)l.push({type:"input_audio",input_audio:{data:u,format:t.audioFormat??"mp3"}});if(i)for(let u of t.fileIds)l.push({type:"file",file:{file_id:u.id}});return{role:"user",content:l}}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}return t.role==="tool"?{role:"tool",content:t.content??"",tool_call_id:t.tool_call_id??""}:{role:t.role,content:t.content??""}})}var _n=class{baseUrl;extraHeaders;timeoutMs;quirks;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??{}}async*stream(e,t,n){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/responses`:`${this.baseUrl}/v1/responses`,i=this.buildRequestBody(e),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},l=null;for(let u=0;u<=3;u++){if(n?.aborted)throw new Error("Request aborted");u>0&&l&&await Pe(Me(u),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(c){l=c instanceof Error?c:new Error(String(c));let d=l.message.includes("Stream idle timeout");if(!Le($e(l))&&!d||u===3)throw l}}}buildRequestBody(e){let t={model:e.model,input:Am(e.messages),stream:!0};if(e.conversationId?t.conversation=e.conversationId:e.previousResponseId&&(t.previous_response_id=e.previousResponseId),e.store!==void 0&&(t.store=e.store),e.instructions&&(t.instructions=e.instructions),e.structuredOutput&&(e.structuredOutput.mode==="json_object"?t.text={format:{type:"json_object"}}:t.text={format:{type:"json_schema",name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}}),e.tools&&e.tools.length>0&&(t.tools=e.tools.map(n=>({type:"function",name:n.function.name,description:n.function.description,parameters:n.function.parameters,strict:!0}))),e.toolChoice!==void 0&&(typeof e.toolChoice=="string"?t.tool_choice=e.toolChoice:t.tool_choice={type:e.toolChoice.type,name:e.toolChoice.name}),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.top_p=e.topP),e.maxTokens!==void 0&&(t.max_output_tokens=e.maxTokens),e.reasoning){let n=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;Sn(e.model)&&(n==="high"||n==="xhigh")&&(n="medium");let o={effort:n};o.summary="auto",o.generate_summary="auto",t.reasoning=o}if(e.prediction&&xn(e.model)&&(t.prediction=e.prediction),t.truncation="auto",e.promptCacheKey&&(t.prompt_cache_key=e.promptCacheKey),e.promptCacheRetention&&(t.prompt_cache_retention=e.promptCacheRetention),e.serviceTier&&(t.service_tier=e.serviceTier),e.reasoning?.includeEncryptedReasoning&&(e.store===void 0&&(t.store=!1),t.include=["reasoning.encrypted_content"]),e.contextManagement&&(t.context_management=e.contextManagement.edits.map(n=>{let o={type:n.type};return n.type==="clear_thinking"&&n.keep!==void 0?o.keep=n.keep:n.type==="clear_tool_uses"&&(n.trigger&&(o.trigger=n.trigger),n.keep&&(o.keep=n.keep),n.excludeTools&&(o.exclude_tools=n.excludeTools),n.clearToolInput!==void 0&&(o.clear_tool_input=n.clearToolInput)),o})),!e.disableBuiltinTools){let n=t.tools??[],o=t.include??[];if(e.openaiBuiltinTools&&e.openaiBuiltinTools.length>0){for(let i of e.openaiBuiltinTools)n.push({...i});let s=new Set(e.openaiBuiltinTools.map(i=>i.type));s.has("web_search_preview")&&o.push("web_search_call.action.sources"),s.has("file_search")&&o.push("file_search_call.results"),s.has("code_interpreter")&&o.push("code_interpreter_call.outputs"),s.has("computer_use_preview")&&o.push("computer_call_output.output.image_url")}else this.quirks.builtinWebSearch&&(n.push({type:"web_search_preview"}),o.push("web_search_call.action.sources")),this.quirks.builtinCodeInterpreter&&(n.push({type:"code_interpreter"}),o.push("code_interpreter_call.outputs")),this.quirks.builtinFileSearch&&(n.push({type:"file_search"}),o.push("file_search_call.results"));n.length>0&&(t.tools=n),o.length>0&&(t.include=o)}if(e.maxToolCalls!==void 0&&(t.max_tool_calls=e.maxToolCalls),e.parallelToolCalls!==void 0&&(t.parallel_tool_calls=e.parallelToolCalls),e.textVerbosity){let n=t.text??{};n.verbosity=e.textVerbosity,t.text=n}return 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 u=await a.text().catch(()=>""),c=new Error(`OpenAI Responses API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("OpenAI Responses API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.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,l=new Map,u=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},Ae)};try{u();let c=e.getReader();try{for(;;){let{done:d,value:p}=await c.read();if(d)break;if(i.signal.aborted)throw new Error("Stream idle timeout");u(),n+=t.decode(p,{stream:!0});let m;for(;(m=n.indexOf(`
35
+ `))!==-1;){let g=n.slice(0,m).trim();if(n=n.slice(m+1),!g){o="";continue}if(!g.startsWith(":")){if(g.startsWith("event:")){o=g.slice(6).trim();continue}if(g.startsWith("data:")){let f=g.slice(5).trim();if(f==="[DONE]")return;let b;try{b=JSON.parse(f)}catch{continue}yield*this.processEvent(o,b,l,()=>a++)}}}}}finally{c.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 l=n.get(i);l===void 0&&(l=o(),n.set(i,l)),yield{type:"tool_call_delta",index:l,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 l=o();n.set(i,l),yield{type:"tool_call_delta",index:l,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 l=a.annotations;l&&l.length>0&&(yield{type:"annotations",annotations:l.map(u=>({type:u.type??"url_citation",url:u.url,title:u.title,...u}))})}}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 u=a.input_tokens_details,c=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:c?.reasoning_tokens,cacheReadTokens:u?.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}}}};function Am(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 l=[];if(n)for(let u of t.imageUrls){let c={type:"input_image",image_url:u};t.imageDetail&&(c.detail=t.imageDetail),l.push(c)}if(s)for(let u of t.audioUrls)l.push({type:"input_audio",data:u,format:t.audioFormat??"mp3"});if(i)for(let u of t.fileIds)l.push({type:"input_file",file_id:u.id});t.content&&l.push({type:"input_text",text:t.content}),e.push({role:"user",content:l})}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;e.push({type:"function_call_output",call_id:t.tool_call_id,output:t.content??""});continue}}return e}var Mm=18e4,Pm=3e5,Im=64e3,Em="[Tool execution failed; output not available during conversation recovery]",Om="interleaved-thinking-2025-05-14",Lm="context-1m-2025-08-07",$m="token-efficient-tools-2026-03-28",Dm="prompt-caching-scope-2026-01-05",Um="pdfs-2024-09-25";function Nm(r){let e=r.toLowerCase();return e.includes("opus-4-6")||e.includes("opus-4-7")||e.includes("sonnet-4-6")}function Fm(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(Lm),n.push(Um),e&&!o.includes("haiku")&&n.push(Om),t&&n.push($m),n.push(Dm);let i=process.env.ANTHROPIC_BETAS;if(i)for(let a of i.split(",").map(l=>l.trim()).filter(Boolean))n.includes(a)||n.push(a);return n}var Nt=class{baseUrl;apiVersion;timeoutMs;streamIdleTimeoutMs;enablePromptCaching;maxRetries;omitZeroTemperature;quirks;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??Mm,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??Ae,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3,this.omitZeroTemperature=e.omitZeroTemperature??!1,this.quirks=e.quirks??{}}async*stream(e,t,n){let o=`${this.baseUrl}/v1/messages`,s=Gm(e.messages),{system:i,messages:a}=Hm(s,this.quirks,e.model),l=Wm(i,this.enablePromptCaching),u=!!e.reasoning,c=e.maxTokens??8192,d={model:e.model,messages:a,max_tokens:c,stream:!0};if(l&&(d.system=l),e.tools&&e.tools.length>0){let f=e.tools.map(Vm);this.enablePromptCaching&&f.length>0&&(f[f.length-1].cache_control={type:"ephemeral"}),d.tools=f,e.toolChoice&&(d.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})}if(!u&&e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(d.temperature=e.temperature)),!u&&e.topP!==void 0&&(d.top_p=e.topP),u)if(this.quirks.useEffortInsteadOfBudget){d.thinking={type:"enabled"};let f=this.quirks.maxReasoningEffort??"high",b=e.reasoning?.effort??"high",T=b==="low"||b==="medium"?"high":f;if(d.output_config={effort:T},i){let w=2166136261;for(let _=0;_<i.length;_++)w^=i.charCodeAt(_),w=Math.imul(w,16777619);d.metadata={user_id:`qa-${(w>>>0).toString(36)}`}}}else if(Nm(e.model))d.thinking={type:"adaptive"};else{let f=Bm(e.reasoning.effort,e.maxTokens);d.thinking={type:"enabled",budget_tokens:Math.min(c-1,f)}}let p=Fm(e.model,u,(e.tools?.length??0)>0),m={"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion};p.length>0&&(m["anthropic-beta"]=p.join(","));let g=null;for(let f=0;f<=this.maxRetries;f++){if(n?.aborted)throw new Error("Request aborted");f>0&&g&&await Pe(Me(f),n);try{yield*this.streamWithWatchdog(o,m,d,n);return}catch(b){g=b instanceof Error?b:new Error(String(b));let T=zm(g.message),w=T!==null&&gr.has(T),_=g.message.includes("Stream idle timeout");if(g.message.includes("model_context_window_exceeded")||g.message.includes("context_length_exceeded")||!w&&!_)throw g;if(f===this.maxRetries){if((_||w)&&!e.streamRequired)try{yield*this.nonStreamingFallback(o,m,d,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 l=null,u=!1,c=()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{u=!0},this.streamIdleTimeoutMs)},d=()=>{l!==null&&(clearTimeout(l),l=null)};c();try{yield*this.parseSSEStream(a.body,c,()=>u)}finally{d()}if(u)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,n,o){let s=qm({...n,stream:!1}),i=AbortSignal.timeout(Pm),a=o?AbortSignal.any([o,i]):i,l=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>""),d=new Error(`Anthropic API error ${l.status}: ${c.slice(0,500)}`);throw d.status=l.status,d}let u=await l.json();yield*this.mapNonStreamingResponse(u)}*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:ga(o)})}async*parseSSEStream(e,t,n){let o=new TextDecoder,s="",i="",a=new Map,l={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,reasoningTokens:0};for await(let u of e){if(t(),n())break;s+=o.decode(u,{stream:!0});let c;for(;(c=s.indexOf(`
36
+ `))!==-1;){let d=s.slice(0,c).trim();if(s=s.slice(c+1),!d){i="";continue}if(d.startsWith("event:")){i=d.slice(6).trimStart();continue}if(!d.startsWith("data:"))continue;let p=d.slice(5).trimStart(),m;try{m=JSON.parse(p)}catch{continue}yield*this.mapEvent(i,m,a,l)}}}*mapEvent(e,t,n,o){switch(e){case"message_start":{let i=t.message?.usage;i&&(ma(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 l=n.get(s);l&&typeof i.signature=="string"&&(l.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&&(ma(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:ga(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 ma(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 ga(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 jm(r){return!/haiku/i.test(r)}var fr={high:16e3,medium:8e3,low:4e3};function Bm(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 fr.high}return fr[r]??fr.high}function Wm(r,e){if(r)return e?[{type:"text",text:r,cache_control:{type:"ephemeral"}}]:r}function Gm(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(c=>t.has(c.id)?!1:(t.add(c.id),!0)),i=new Set(s.map(c=>c.id)),a=new Set,l=r.slice(n+1);for(let c of l){if(c.role!=="tool")break;c.tool_call_id&&a.add(c.tool_call_id)}s.length!==o.tool_calls.length?e.push({...o,tool_calls:s}):e.push(o);let u=[...i].filter(c=>!a.has(c));for(let c of u){let d=s.find(p=>p.id===c);e.push({role:"tool",tool_call_id:c,name:d?.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}function Hm(r,e={},t){let n,o=[];for(let s of r){if(s.role==="system"){n=n?`${n}
37
+
38
+ ${s.content??""}`:s.content??"";continue}if(s.role==="user")if(s.imageUrls&&s.imageUrls.length>0&&!e.filterImageBlocks){let a=[];s.content&&a.push({type:"text",text:s.content});for(let l of s.imageUrls)if(l.startsWith("data:")){let u=/^data:([^;]+);base64,(.+)$/.exec(l);if(u){let c=u[1];c==="application/pdf"?a.push({type:"document",source:{type:"base64",media_type:c,data:u[2]}}):a.push({type:"image",source:{type:"base64",media_type:c,data:u[2]}})}}else l.endsWith(".pdf")||l.includes(".pdf?")?a.push({type:"document",source:{type:"url",url:l}}):a.push({type:"image",source:{type:"url",url:l}});o.push({role:"user",content:a})}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 l of i)l.signature&&a.push({type:"thinking",thinking:l.thinking,signature:l.signature});s.content&&a.push({type:"text",text:s.content});for(let l of s.tool_calls){let u;try{u=JSON.parse(l.function.arguments)}catch{u={}}a.push({type:"tool_use",id:l.id,name:l.function.name,input:u})}o.push({role:"assistant",content:a})}else if(i&&i.length>0){let a=[];for(let l of i)l.signature&&a.push({type:"thinking",thinking:l.thinking,signature:l.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=i.startsWith("Error:")||i===Em,l=s.toolReferences,c=l&&l.length>0&&!a&&(!t||jm(t))?l.map(m=>({type:"tool_reference",tool_name:m})):i,d={type:"tool_result",tool_use_id:s.tool_call_id??"",content:c,...a&&{is_error:!0}},p=o[o.length-1];p&&p.role==="user"&&Array.isArray(p.content)?p.content.push(d):o.push({role:"user",content:[d]})}}return{system:n,messages:o}}function Vm(r){return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters??{type:"object",properties:{}}}}function zm(r){let e=/Anthropic API error (\d{3})/.exec(r);return e?parseInt(e[1],10):null}function qm(r){let e=typeof r.max_tokens=="number"?r.max_tokens:8192,t=Math.min(e,Im),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 Rn=class{baseUrl;extraHeaders;timeoutMs;quirks;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??{}}async*stream(e,t,n){let s=`${this.baseUrl.replace(/\/v\d+$/,"")}/v3/responses`,i=this.buildRequestBody(e),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders};if(e.builtinTools&&!e.disableBuiltinTools&&e.builtinTools.length>0)for(let u of e.builtinTools)u.type==="builtin_web_search"?a["ark-beta-web-search"]="true":u.type==="builtin_image_process"?a["ark-beta-image-process"]="true":u.type==="builtin_knowledge_search"?a["ark-beta-knowledge-search"]="true":u.type==="builtin_doubao_app"&&(a["ark-beta-doubao-app"]="true");let l=null;for(let u=0;u<=3;u++){if(n?.aborted)throw new Error("Request aborted");u>0&&l&&await Pe(Me(u),n);try{yield*this.fetchAndStream(s,a,i,n);return}catch(c){l=c instanceof Error?c:new Error(String(c));let d=l.message.includes("Stream idle timeout");if(!Le($e(l))&&!d||u===3)throw l}}}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}buildRequestBody(e){let t=this.resolveConstraints(e),n={model:t.model,input:Km(t.messages),stream:!0};if(t.previousResponseId&&(n.previous_response_id=t.previousResponseId),t.store!==void 0&&(n.store=t.store),t.storeExpireAt!==void 0&&(n.expire_at=t.storeExpireAt),t.instructions&&(n.instructions=t.instructions),t.structuredOutput)if(t.structuredOutput.mode==="json_object")n.text={format:{type:"json_object"}};else{let s={type:"json_schema",name:t.structuredOutput.name,schema:t.structuredOutput.schema};t.structuredOutput.strict!==void 0&&(s.strict=t.structuredOutput.strict),n.text={format:s}}if(t.caching){let s={type:t.caching.type};t.caching.prefix!==void 0&&(s.prefix=t.caching.prefix),n.caching=s,t.caching.prefix&&(n.stream=!1)}if(t.contextManagement){let s=t.contextManagement.edits.map(i=>{let a={type:i.type};return i.type==="clear_thinking"&&i.keep!==void 0?a.keep=i.keep:i.type==="clear_tool_uses"&&(i.trigger&&(a.trigger=i.trigger),i.keep&&(a.keep=i.keep),i.excludeTools&&(a.exclude_tools=i.excludeTools),i.clearToolInput!==void 0&&(a.clear_tool_input=i.clearToolInput)),a});n.context_management={edits:s}}let o=[];if(t.tools&&t.tools.length>0)for(let s of t.tools)o.push({type:"function",name:s.function.name,description:s.function.description,parameters:s.function.parameters});if(t.builtinTools&&!t.disableBuiltinTools&&t.builtinTools.length>0)for(let s of t.builtinTools){let a={type:s.type.replace(/^builtin_/,"")};s.config&&Object.assign(a,s.config),o.push(a)}if(o.length>0&&(n.tools=o),t.maxToolCalls!==void 0&&(n.max_tool_calls=t.maxToolCalls),t.toolChoice!==void 0&&(typeof t.toolChoice=="string"?n.tool_choice=t.toolChoice:n.tool_choice={type:t.toolChoice.type,name:t.toolChoice.name}),t.temperature!==void 0&&(n.temperature=t.temperature),t.topP!==void 0&&(n.top_p=t.topP),t.maxTokens!==void 0&&(n.max_output_tokens=t.maxTokens),t.reasoning){let s=t.reasoning.effort??"high";s==="minimal"?n.thinking={type:"disabled"}:(n.thinking={type:"enabled"},n.reasoning={effort:s}),t.reasoning.includeEncryptedReasoning&&(n.include=["reasoning.encrypted_content"])}return t.prefixMessage&&n.input.push({role:"assistant",content:t.prefixMessage,partial:!0}),n}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 u=await a.text().catch(()=>""),c=new Error(`Volcengine Responses API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("Volcengine Responses API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.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,l=new Map,u=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},Ae)};try{u();let c=e.getReader();try{for(;;){let{done:d,value:p}=await c.read();if(d)break;if(i.signal.aborted)throw new Error("Stream idle timeout");u(),n+=t.decode(p,{stream:!0});let m;for(;(m=n.indexOf(`
39
+ `))!==-1;){let g=n.slice(0,m).trim();if(n=n.slice(m+1),!g){o="";continue}if(!g.startsWith(":")){if(g.startsWith("event:")){o=g.slice(6).trim();continue}if(g.startsWith("data:")){let f=g.slice(5).trim();if(f==="[DONE]")return;let b;try{b=JSON.parse(f)}catch{continue}yield*this.processEvent(o,b,l,()=>a++)}}}}}finally{c.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 l=n.get(i);l===void 0&&(l=o(),n.set(i,l)),yield{type:"tool_call_delta",index:l,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 l=o();n.set(i,l),yield{type:"tool_call_delta",index:l,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 l=a.annotations;l&&l.length>0&&(yield{type:"annotations",annotations:l.map(u=>({type:u.type??"url_citation",url:u.url,title:u.title,...u}))})}}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 u=a.input_tokens_details,c=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:c?.reasoning_tokens,cacheReadTokens:u?.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}}}};function Km(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 l=[];if(n)for(let u of t.imageUrls){let c={type:"input_image",image_url:u};t.imageDetail&&(c.detail=t.imageDetail),t.imagePixelLimit&&(c.image_pixel_limit=t.imagePixelLimit),l.push(c)}if(o)for(let u of t.videoUrls){let c={type:"input_video",video_url:u};t.videoFps!==void 0&&(c.fps=t.videoFps),l.push(c)}if(s)for(let u of t.audioUrls){let c={type:"input_audio",audio_url:u};t.audioFormat&&(c.format=t.audioFormat),l.push(c)}if(i)for(let u of t.fileIds)l.push({type:"input_file",file_id:u.id});t.content&&l.push({type:"input_text",text:t.content}),e.push({role:"user",content:l})}else e.push({role:"user",content:t.content??""});continue}if(t.role==="assistant"){e.push({role:"assistant",content:t.content??""});continue}if(t.role==="tool"){if(!t.tool_call_id)continue;e.push({type:"function_call_output",call_id:t.tool_call_id,output:t.content??""});continue}}return e}ko();var Jm=[{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 Ym(r){switch(r){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";default:return"HIGH"}}var Ft=class{baseUrl;timeoutMs;quirks;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??{}}async*stream(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:streamGenerateContent?alt=sse`,s=this.buildRequestBody(e),i={"Content-Type":"application/json","x-goog-api-key":t},a=null;for(let l=0;l<=3;l++){if(n?.aborted)throw new Error("Request aborted");l>0&&a&&await Pe(Me(l),n);try{yield*this.fetchAndStream(o,i,s,n);return}catch(u){a=u instanceof Error?u:new Error(String(u));let c=a.message.includes("Stream idle timeout");if(!Le($e(a))&&!c)throw a;if(l===3){if((c||Le($e(a)))&&!e.streamRequired)try{yield*this.nonStreamingFallback(e,t,n);return}catch{throw a}throw a}}}}buildRequestBody(e){let{systemInstruction:t,contents:n}=Xm(e.messages),o={contents:n};t&&(o.system_instruction=t);let s=this.buildTools(e);s.length>0&&(o.tools=s),e.tools&&e.tools.length>0&&e.toolChoice&&(o.toolConfig=this.buildToolConfig(e.toolChoice));let i=this.buildGenerationConfig(e);return Object.keys(i).length>0&&(o.generationConfig=i),o.safetySettings=Jm,e.cachedContent&&(o.cachedContent=e.cachedContent),o}buildTools(e){let t=[];if(e.tools&&e.tools.length>0){let n=e.tools.map(Qm);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=Ym(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 u=await a.text().catch(()=>""),c=new Error(`Gemini API error ${a.status}: ${u.slice(0,500)}`);throw c.status=a.status,c}if(!a.body)throw new Error("Gemini API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.includes("text/event-stream")){let u=await a.json();yield*this.processResponse(u);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()},Ae)};try{i();let a=e.getReader();try{for(;;){let{done:l,value:u}=await a.read();if(l)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),n+=t.decode(u,{stream:!0});let c;for(;(c=n.indexOf(`
40
40
  `))!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),!d||d.startsWith(":")||!d.startsWith("data: "))continue;let p=d.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:`
41
41
  \`\`\`output
42
42
  ${s.codeExecutionResult.output??""}
@@ -45,8 +45,8 @@ ${s.codeExecutionResult.output??""}
45
45
  \`\`\`${s.executableCode.language??"python"}
46
46
  ${s.executableCode.code}
47
47
  \`\`\`
48
- `};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:Im(t.finishReason)})}}async*nonStreamingFallback(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:generateContent`,s=this.buildRequestBody(e),i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`Gemini API error ${l.status}: ${c.slice(0,500)}`)}let u=await l.json();yield*this.processResponse(u)}};function Mm(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 l=a.match(/^data:([^;]+);base64,(.+)$/);l&&i.push({inlineData:{mimeType:l[1],data:l[2]}})}else i.push({fileData:{mimeType:"image/jpeg",fileUri:a}});if(s.audioUrls&&s.audioUrls.length>0)for(let a of s.audioUrls){let l=s.audioFormat?`audio/${s.audioFormat==="m4a"?"mp4":s.audioFormat}`:"audio/mp3";i.push({fileData:{mimeType:l,fileUri:a}})}if(s.videoUrls&&s.videoUrls.length>0)for(let a of s.videoUrls)i.push({fileData:{mimeType:"video/mp4",fileUri:a}});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 l={text:a.thinking,thought:!0};a.signature&&(l.thoughtSignature=a.signature),i.push(l)}if(s.content&&i.push({text:s.content}),s.tool_calls&&s.tool_calls.length>0)for(let a of s.tool_calls){let l={};try{l=JSON.parse(a.function.arguments)}catch{}i.push({functionCall:{name:a.function.name,args:l,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??""}}n.push({functionResponse:{name:s.name??"",response:i,id:s.tool_call_id??""}});break}}return o(),{systemInstruction:e,contents:t}}function Pm(r){let e={name:r.function.name,description:r.function.description};return r.function.parameters&&(e.parameters=Re(r.function.parameters)),e}function Im(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()}}function dr(r,e){r.baseUrl&&e.applyOverride(r.provider,{baseUrl:r.baseUrl});let t=e.getProvider(r.provider);if(!t)throw new Error(`Unknown LLM provider: "${r.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let n=r.baseUrl||t.baseUrl;return{transport:Em(t,n),apiKey:r.apiKey,resolvedModel:r.model,providerDef:t}}function pr(r){for(let e of r.listProviders()){let t=r.resolveApiKey(e.id);if(t)return{providerId:e.id,apiKey:t,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function Em(r,e){let t;switch(r.transport){case"openai-chat":t=new pt({baseUrl:e,extraHeaders:r.extraHeaders,supportsStreamOptions:r.supportsStreamOptions,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks});break;case"openai-responses":t=new vn({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks});break;case"anthropic-messages":t=new Ut({baseUrl:e,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks});break;case"volcengine-responses":t=new xn({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks});break;case"gemini-generatecontent":t=new Nt({baseUrl:e,quirks:r.quirks});break;default:throw new Error(`Unsupported transport type: "${r.transport}" for provider "${r.id}"`)}if(r.transport==="anthropic-messages"&&r.quirks?.supportsPrefixCompletion){let n=e.replace(/\/anthropic\/?$/,""),o=new pt({baseUrl:n,quirks:r.quirks});return new ur(t,o)}return t}var ur=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 Ft=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",l=this.baseUrl.replace(/(\/v1beta)$/,"/upload$1/files"),u=await fetch(l,{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(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Gemini file upload init error ${u.status}: ${m.slice(0,500)}`)}let c=u.headers.get("x-goog-upload-url");if(!c)throw new Error("Gemini file upload: missing x-goog-upload-url in response headers");let d=await fetch(c,{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(!d.ok){let m=await d.text().catch(()=>"");throw new Error(`Gemini file upload error ${d.status}: ${m.slice(0,500)}`)}return(await d.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(l=>setTimeout(l,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 l=await i.text().catch(()=>"");throw new Error(`Gemini file list error ${i.status}: ${l.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 Om}from"node:path";import{mkdirSync as Lm,appendFileSync as $m}from"node:fs";var ra=Ui();function mr(){return process.env.QLOGICAGENT_DEBUG==="1"}function gr(r,e){let t=Om(ra,`${e}.jsonl`),n=!1;function o(){n||(Lm(ra,{recursive:!0}),n=!0)}function s(i){try{o(),$m(t,JSON.stringify(i)+`
49
- `,"utf8")}catch{}}return{async*stream(i,a,l){let u=Date.now();s({type:"request",timestamp:new Date(u).toISOString(),model:i.model,messageCount:i.messages.length,toolCount:i.tools?.length??0,toolChoice:i.toolChoice,temperature:i.temperature,maxTokens:i.maxTokens,reasoning:i.reasoning});let c=0,d=0,p=0,m="",g;try{for await(let f of r.stream(i,a,l))f.type==="usage"?(c=f.promptTokens,d=f.completionTokens,p=f.reasoningTokens??0):f.type==="done"&&(m=f.finishReason),yield f}catch(f){throw g=f instanceof Error?f.message:String(f),f}finally{let f=Date.now()-u;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:f,promptTokens:c,completionTokens:d,reasoningTokens:p,finishReason:m,...g?{error:g}:{}})}}}}function fr(r){return typeof r.deleteVideoTask=="function"&&typeof r.listVideoTasks=="function"}function sa(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}}}}var Sn={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function jt(){return{surfacedPaths:new Set,sessionBytes:0}}function ia(r,e,t){let n=[],o=t??jt(),s,i=[];return n.push(r.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,l)=>{if(!e.memoryProvider||!l.query)return{action:"continue",context:l};if(o.sessionBytes>=Sn.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:l};try{let u=await e.memoryProvider.search(l.query,e.userId,{limit:Sn.LIMIT_PER_RECALL}),c=u.filter(p=>{let m=p,g=m.path??m.id??"";if(!g)return!0;if(o.surfacedPaths.has(g))return!1;let f=(m.content?.length??0)*2;if(o.sessionBytes+f>Sn.MAX_SESSION_BYTES)return!1;if(o.surfacedPaths.add(g),o.sessionBytes+=f,o.surfacedPaths.size>Sn.MAX_SURFACED_ENTRIES){let b=o.surfacedPaths.values().next().value;b!==void 0&&o.surfacedPaths.delete(b)}return!0});s=l.turnId,i=c,e.log.debug(`memory.before_recall: prefetched ${u.length} \u2192 ${c.length} after dedup (${o.sessionBytes} bytes used)`);let d=c.map(p=>{let m=p;return{text:m.text??m.content??"",score:m.score}}).filter(p=>p.text);return{action:"continue",context:{...l,recalledMemories:d}}}catch(u){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${u instanceof Error?u.message:String(u)}`),i=[]}return{action:"continue",context:l}}})),n.push(r.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,l)=>{let u=s===l.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${l.blockCount??0} blocks assembled, ${u} qmemory results (session: ${o.sessionBytes} bytes)`),{action:"continue",context:l}}})),()=>{for(let a of n)a();i=[]}}import{ClawQMemoryAdapter as Dm}from"qlogicagent-adapter-claw";var aa="qmemory";function la(r){let e=new Dm({baseUrl:r.baseUrl,apiKey:r.apiKey,timeout:r.timeoutMs??5e3});function t(n){return r.userIdPrefix?`${r.userIdPrefix}:${n}`:n}return{providerId:aa,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:aa,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(u=>e.dispatch("memory.addFact",{user_id:i,text:u.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...u.category?{category:u.category}:{},...typeof u.importance=="number"?{importance:u.importance}:{},...u.speaker?{speaker:u.speaker}:{},...u.event_date?{event_date:u.event_date}:{},...u.tags?.length?{tags:u.tags}:{}}}))),l=0;for(let u of a)u.status==="fulfilled"&&(l+=u.value.memories_added??1);return{memoriesAdded:l}},async remove(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}:{}})}}}import{readFile as ga,writeFile as yr,stat as wa,unlink as Wm,mkdir as Gm}from"node:fs/promises";import{join as _n,resolve as fa,isAbsolute as ha,normalize as ya}from"node:path";import{randomUUID as Hm}from"node:crypto";function ca(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function Um(r){return r.latestInputTokens+r.cumulativeOutputTokens}var Nm=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),ua=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function Fm(r){return{isSearch:Nm.has(r)||void 0,isRead:ua.has(r)||void 0}}function jm(r,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${ua.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 da(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 pa(r,e,t,n){r.toolUseCount++;let o=Fm(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??jm(e,t),isSearch:o.isSearch,isRead:o.isRead};for(r.recentActivities.push(s);r.recentActivities.length>5;)r.recentActivities.shift()}function hr(r){return{toolUseCount:r.toolUseCount,tokenCount:Um(r),lastActivity:r.recentActivities.length>0?r.recentActivities[r.recentActivities.length-1]:void 0,recentActivities:[...r.recentActivities]}}import{randomUUID as ma}from"node:crypto";function Bm(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 Rn(r){let e=Date.now(),t=[],n={prompt:0,completion:0},o=ca(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:u,toolInvoker:c,apiKey:d,model:p,log:m,hooks:g,forkLabel:f,maxTurns:b,temperature:h,parentSignal:k,onEvent:x,onProgress:R,budgetTokens:E,parentDepth:F}=r,U=Bm(k),D=`fork-${f}-${ma().slice(0,8)}`,w=`fork-session-${ma().slice(0,8)}`;m.info(`[fork:${f}] starting \u2014 ${s.length} initial messages, model=${p}`);let ge=l?{invoke:async(te,le,G,N)=>{let pe={};try{pe=JSON.parse(G)}catch{}let Ee=l(le,pe);return Ee.allowed?c.invoke(te,le,G,N):(m.info(`[fork:${f}] tool ${le} denied: ${Ee.reason}`),{result:"",error:Ee.reason})}}:c,H=!0,z;try{let{Agent:te}=await Promise.resolve().then(()=>(nr(),Li)),le=new te({llmTransport:u,apiKey:d,toolInvoker:ge,log:m,hooks:g,maxRounds:b});for await(let G of le.run({turnId:D,sessionId:w,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:d,temperature:h,maxOutputTokens:r.maxOutputTokens,parentDepth:F}},U.signal)){if(t.push(G),x?.(G),G.type==="end"&&G.usage&&(da(o,{input_tokens:G.usage.prompt,output_tokens:G.usage.completion}),n.prompt+=G.usage.prompt,n.completion+=G.usage.completion,G.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+G.usage.cacheRead),G.usage.cacheCreation&&(n.cacheCreation=(n.cacheCreation??0)+G.usage.cacheCreation),E&&E>0)){let N=n.prompt+n.completion+(n.reasoning??0);N>=E&&(m.info(`[fork:${f}] budget exceeded (${N} / ${E} tokens), aborting`),U.abort("budget_exceeded"))}if(G.type==="tool_call"){let N={};try{N=JSON.parse(G.arguments??"{}")}catch{}pa(o,G.name,N),R?.(hr(o))}G.type==="error"&&(H=!1,z=G.error)}}catch(te){H=!1,z=te instanceof Error?te.message:String(te),m.warn(`[fork:${f}] error: ${z}`)}finally{U.signal.aborted||U.abort("fork_complete")}let fe=Date.now()-e;return m.info(`[fork:${f}] finished in ${fe}ms \u2014 ${t.length} events, usage: prompt=${n.prompt} completion=${n.completion}, ok=${H}`),{events:t,totalUsage:n,progress:hr(o),durationMs:fe,ok:H,error:z}}var va={minHours:24,minSessions:5,scanIntervalMs:6e5},Cn=".consolidate-lock",zm=3600*1e3,ba="CLAUDE.md",Vm=100,qm=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"]),Km=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),Jm=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function Ym(r){let e=r.trim();if(!e||Jm.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!qm.has(n))return!1;if(n==="git"){let o=t[1];if(!o||!Km.has(o))return!1}return!0}function Xm(r,e){let{toolName:t,input:n}=e;if(new Set(["read_file","grep","glob","search","list_dir","file_read","Grep","Glob"]).has(t))return{allowed:!0};if(new Set(["qmemory_search","qmemory_store","qmemory_feedback"]).has(t))return{allowed:!0};if(t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return Ym(i)?{allowed:!0}:{allowed:!1,reason:"Only read-only shell commands are permitted during dream consolidation (ls, find, grep, cat, stat, wc, head, tail, and similar)"}}if(t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??"";return typeof i=="string"&&xa(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_file, grep, glob, read-only bash, and memory-scoped file_edit/file_write are allowed.`}}function xa(r,e){let t=ha(r)?r:fa(r),n=ha(e)?e:fa(e),o=ya(t),s=ya(n);return o.startsWith(s)}function Sa(r,e,t,n){let o=n?.hasQMemory?`
48
+ `};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:Zm(t.finishReason)})}}async*nonStreamingFallback(e,t,n){let o=`${this.baseUrl}/models/${encodeURIComponent(e.model)}:generateContent`,s=this.buildRequestBody(e),i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`Gemini API error ${l.status}: ${c.slice(0,500)}`)}let u=await l.json();yield*this.processResponse(u)}};function Xm(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 l=a.match(/^data:([^;]+);base64,(.+)$/);l&&i.push({inlineData:{mimeType:l[1],data:l[2]}})}else i.push({fileData:{mimeType:"image/jpeg",fileUri:a}});if(s.audioUrls&&s.audioUrls.length>0)for(let a of s.audioUrls){let l=s.audioFormat?`audio/${s.audioFormat==="m4a"?"mp4":s.audioFormat}`:"audio/mp3";i.push({fileData:{mimeType:l,fileUri:a}})}if(s.videoUrls&&s.videoUrls.length>0)for(let a of s.videoUrls)i.push({fileData:{mimeType:"video/mp4",fileUri:a}});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 l={text:a.thinking,thought:!0};a.signature&&(l.thoughtSignature=a.signature),i.push(l)}if(s.content&&i.push({text:s.content}),s.tool_calls&&s.tool_calls.length>0)for(let a of s.tool_calls){let l={};try{l=JSON.parse(a.function.arguments)}catch{}i.push({functionCall:{name:a.function.name,args:l,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??""}}n.push({functionResponse:{name:s.name??"",response:i,id:s.tool_call_id??""}});break}}return o(),{systemInstruction:e,contents:t}}function Qm(r){let e={name:r.function.name,description:r.function.description};return r.function.parameters&&(e.parameters=Ce(r.function.parameters)),e}function Zm(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()}}function yr(r,e){r.baseUrl&&e.applyOverride(r.provider,{baseUrl:r.baseUrl});let t=e.getProvider(r.provider);if(!t)throw new Error(`Unknown LLM provider: "${r.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let n=r.baseUrl||t.baseUrl;return{transport:eg(t,n),apiKey:r.apiKey,resolvedModel:r.model,providerDef:t}}function br(r){for(let e of r.listProviders()){let t=r.resolveApiKey(e.id);if(t)return{providerId:e.id,apiKey:t,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function eg(r,e){let t;switch(r.transport){case"openai-chat":t=new pt({baseUrl:e,extraHeaders:r.extraHeaders,supportsStreamOptions:r.supportsStreamOptions,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks});break;case"openai-responses":t=new _n({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks});break;case"anthropic-messages":t=new Nt({baseUrl:e,omitZeroTemperature:r.omitZeroTemperature,quirks:r.quirks});break;case"volcengine-responses":t=new Rn({baseUrl:e,extraHeaders:r.extraHeaders,quirks:r.quirks});break;case"gemini-generatecontent":t=new Ft({baseUrl:e,quirks:r.quirks});break;default:throw new Error(`Unsupported transport type: "${r.transport}" for provider "${r.id}"`)}if(r.transport==="anthropic-messages"&&r.quirks?.supportsPrefixCompletion){let n=e.replace(/\/anthropic\/?$/,""),o=new pt({baseUrl:n,quirks:r.quirks});return new hr(t,o)}return t}var hr=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 jt=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",l=this.baseUrl.replace(/(\/v1beta)$/,"/upload$1/files"),u=await fetch(l,{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(!u.ok){let m=await u.text().catch(()=>"");throw new Error(`Gemini file upload init error ${u.status}: ${m.slice(0,500)}`)}let c=u.headers.get("x-goog-upload-url");if(!c)throw new Error("Gemini file upload: missing x-goog-upload-url in response headers");let d=await fetch(c,{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(!d.ok){let m=await d.text().catch(()=>"");throw new Error(`Gemini file upload error ${d.status}: ${m.slice(0,500)}`)}return(await d.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(l=>setTimeout(l,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 l=await i.text().catch(()=>"");throw new Error(`Gemini file list error ${i.status}: ${l.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 tg}from"node:path";import{mkdirSync as ng,appendFileSync as og}from"node:fs";var fa=Ki();function kr(){return process.env.QLOGICAGENT_DEBUG==="1"}function Tr(r,e){let t=tg(fa,`${e}.jsonl`),n=!1;function o(){n||(ng(fa,{recursive:!0}),n=!0)}function s(i){try{o(),og(t,JSON.stringify(i)+`
49
+ `,"utf8")}catch{}}return{async*stream(i,a,l){let u=Date.now();s({type:"request",timestamp:new Date(u).toISOString(),model:i.model,messageCount:i.messages.length,toolCount:i.tools?.length??0,toolChoice:i.toolChoice,temperature:i.temperature,maxTokens:i.maxTokens,reasoning:i.reasoning});let c=0,d=0,p=0,m="",g;try{for await(let f of r.stream(i,a,l))f.type==="usage"?(c=f.promptTokens,d=f.completionTokens,p=f.reasoningTokens??0):f.type==="done"&&(m=f.finishReason),yield f}catch(f){throw g=f instanceof Error?f.message:String(f),f}finally{let f=Date.now()-u;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:f,promptTokens:c,completionTokens:d,reasoningTokens:p,finishReason:m,...g?{error:g}:{}})}}}}function wr(r){return typeof r.deleteVideoTask=="function"&&typeof r.listVideoTasks=="function"}function ha(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}}}}var Cn={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function Bt(){return{surfacedPaths:new Set,sessionBytes:0}}function ya(r,e,t){let n=[],o=t??Bt(),s,i=[];return n.push(r.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,l)=>{if(!e.memoryProvider||!l.query)return{action:"continue",context:l};if(o.sessionBytes>=Cn.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:l};try{let u=await e.memoryProvider.search(l.query,e.userId,{limit:Cn.LIMIT_PER_RECALL}),c=u.filter(p=>{let m=p,g=m.path??m.id??"";if(!g)return!0;if(o.surfacedPaths.has(g))return!1;let f=(m.content?.length??0)*2;if(o.sessionBytes+f>Cn.MAX_SESSION_BYTES)return!1;if(o.surfacedPaths.add(g),o.sessionBytes+=f,o.surfacedPaths.size>Cn.MAX_SURFACED_ENTRIES){let b=o.surfacedPaths.values().next().value;b!==void 0&&o.surfacedPaths.delete(b)}return!0});s=l.turnId,i=c,e.log.debug(`memory.before_recall: prefetched ${u.length} \u2192 ${c.length} after dedup (${o.sessionBytes} bytes used)`);let d=c.map(p=>{let m=p;return{text:m.text??m.content??"",score:m.score}}).filter(p=>p.text);return{action:"continue",context:{...l,recalledMemories:d}}}catch(u){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${u instanceof Error?u.message:String(u)}`),i=[]}return{action:"continue",context:l}}})),n.push(r.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,l)=>{let u=s===l.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${l.blockCount??0} blocks assembled, ${u} qmemory results (session: ${o.sessionBytes} bytes)`),{action:"continue",context:l}}})),()=>{for(let a of n)a();i=[]}}import{ClawQMemoryAdapter as rg}from"qlogicagent-adapter-claw";var ba="qmemory";function ka(r){let e=new rg({baseUrl:r.baseUrl,apiKey:r.apiKey,timeout:r.timeoutMs??5e3});function t(n){return r.userIdPrefix?`${r.userIdPrefix}:${n}`:n}return{providerId:ba,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:ba,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(u=>e.dispatch("memory.addFact",{user_id:i,text:u.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...u.category?{category:u.category}:{},...typeof u.importance=="number"?{importance:u.importance}:{},...u.speaker?{speaker:u.speaker}:{},...u.event_date?{event_date:u.event_date}:{},...u.tags?.length?{tags:u.tags}:{}}}))),l=0;for(let u of a)u.status==="fulfilled"&&(l+=u.value.memories_added??1);return{memoriesAdded:l}},async remove(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}:{}})}}}import{readFile as _a,writeFile as xr,stat as Ea,unlink as ug,mkdir as dg}from"node:fs/promises";import{join as Mn,resolve as Ra,isAbsolute as Ca,normalize as Aa}from"node:path";import{randomUUID as pg}from"node:crypto";function Ta(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function sg(r){return r.latestInputTokens+r.cumulativeOutputTokens}var ig=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),wa=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function ag(r){return{isSearch:ig.has(r)||void 0,isRead:wa.has(r)||void 0}}function lg(r,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${wa.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 va(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 xa(r,e,t,n){r.toolUseCount++;let o=ag(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??lg(e,t),isSearch:o.isSearch,isRead:o.isRead};for(r.recentActivities.push(s);r.recentActivities.length>5;)r.recentActivities.shift()}function vr(r){return{toolUseCount:r.toolUseCount,tokenCount:sg(r),lastActivity:r.recentActivities.length>0?r.recentActivities[r.recentActivities.length-1]:void 0,recentActivities:[...r.recentActivities]}}import{randomUUID as Sa}from"node:crypto";function cg(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={prompt:0,completion:0},o=Ta(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:u,toolInvoker:c,apiKey:d,model:p,log:m,hooks:g,forkLabel:f,maxTurns:b,temperature:T,parentSignal:w,onEvent:_,onProgress:y,budgetTokens:C,parentDepth:E}=r,D=cg(w),L=`fork-${f}-${Sa().slice(0,8)}`,v=`fork-session-${Sa().slice(0,8)}`;m.info(`[fork:${f}] starting \u2014 ${s.length} initial messages, model=${p}`);let ce=l?{invoke:async(re,ue,V,B)=>{let fe={};try{fe=JSON.parse(V)}catch{}let Oe=l(ue,fe);return Oe.allowed?c.invoke(re,ue,V,B):(m.info(`[fork:${f}] tool ${ue} denied: ${Oe.reason}`),{result:"",error:Oe.reason})}}:c,j=!0,F;try{let{Agent:re}=await Promise.resolve().then(()=>(lr(),Vi)),ue=new re({llmTransport:u,apiKey:d,toolInvoker:ce,log:m,hooks:g,maxRounds:b});for await(let V of ue.run({turnId:L,sessionId:v,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:d,temperature:T,maxOutputTokens:r.maxOutputTokens,parentDepth:E}},D.signal)){if(t.push(V),_?.(V),V.type==="end"&&V.usage&&(va(o,{input_tokens:V.usage.prompt,output_tokens:V.usage.completion}),n.prompt+=V.usage.prompt,n.completion+=V.usage.completion,V.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+V.usage.cacheRead),V.usage.cacheCreation&&(n.cacheCreation=(n.cacheCreation??0)+V.usage.cacheCreation),C&&C>0)){let B=n.prompt+n.completion+(n.reasoning??0);B>=C&&(m.info(`[fork:${f}] budget exceeded (${B} / ${C} tokens), aborting`),D.abort("budget_exceeded"))}if(V.type==="tool_call"){let B={};try{B=JSON.parse(V.arguments??"{}")}catch{}xa(o,V.name,B),y?.(vr(o))}V.type==="error"&&(j=!1,F=V.error)}}catch(re){j=!1,F=re instanceof Error?re.message:String(re),m.warn(`[fork:${f}] error: ${F}`)}finally{D.signal.aborted||D.abort("fork_complete")}let ne=Date.now()-e;return m.info(`[fork:${f}] finished in ${ne}ms \u2014 ${t.length} events, usage: prompt=${n.prompt} completion=${n.completion}, ok=${j}`),{events:t,totalUsage:n,progress:vr(o),durationMs:ne,ok:j,error:F}}var Oa={minHours:24,minSessions:5,scanIntervalMs:6e5},Pn=".consolidate-lock",mg=3600*1e3,Ma="CLAUDE.md",gg=100,fg=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"]),hg=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),yg=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function bg(r){let e=r.trim();if(!e||yg.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!fg.has(n))return!1;if(n==="git"){let o=t[1];if(!o||!hg.has(o))return!1}return!0}function kg(r,e){let{toolName:t,input:n}=e;if(new Set(["read_file","grep","glob","search","list_dir","file_read","Grep","Glob"]).has(t))return{allowed:!0};if(new Set(["qmemory_search","qmemory_store","qmemory_feedback"]).has(t))return{allowed:!0};if(t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return bg(i)?{allowed:!0}:{allowed:!1,reason:"Only read-only shell commands are permitted during dream consolidation (ls, find, grep, cat, stat, wc, head, tail, and similar)"}}if(t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??"";return typeof i=="string"&&La(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_file, grep, glob, read-only bash, and memory-scoped file_edit/file_write are allowed.`}}function La(r,e){let t=Ca(r)?r:Ra(r),n=Ca(e)?e:Ra(e),o=Aa(t),s=Aa(n);return o.startsWith(s)}function $a(r,e,t,n){let o=n?.hasQMemory?`
50
50
 
51
51
  ## Phase 2.5 \u2014 Long-term memory triage (QMemory)
52
52
 
@@ -81,7 +81,7 @@ Session transcripts: \`${e}\` (large JSONL files \u2014 grep narrowly, don't rea
81
81
  ## Phase 1 \u2014 Orient
82
82
 
83
83
  - \`ls\` the memory directory to see what already exists
84
- - Read \`${ba}\` to understand the current index
84
+ - Read \`${Ma}\` to understand the current index
85
85
  - Skim existing topic files so you improve them rather than creating duplicates
86
86
  - If \`logs/\` or \`sessions/\` subdirectories exist, review recent entries there
87
87
 
@@ -107,7 +107,7 @@ Focus on:
107
107
 
108
108
  ## Phase 4 \u2014 Prune and index
109
109
 
110
- Update \`${ba}\` so it stays under ${Vm} 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.
110
+ Update \`${Ma}\` so it stays under ${gg} 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.
111
111
 
112
112
  - Remove pointers to memories that are now stale, wrong, or superseded
113
113
  - 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
@@ -122,41 +122,48 @@ Sessions since last consolidation (${t.length}):
122
122
  ${t.map(s=>`- ${s}`).join(`
123
123
  `)}
124
124
 
125
- Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var ka=0;async function Qm(r,e={}){let t={...va,...e},n;try{n=await Ra(r.memoryRoot)}catch{n=0}let o=(Date.now()-n)/36e5;if(!t.force&&o<t.minHours)return null;let s=Date.now()-ka;if(!t.force&&s<t.scanIntervalMs)return null;ka=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 Ra(r){let e=_n(r,Cn);return(await wa(e)).mtimeMs}function Zm(r){try{return process.kill(r,0),!0}catch{return!1}}async function eg(r){let e=_n(r,Cn),t,n;try{let[s,i]=await Promise.all([wa(e),ga(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<zm&&n!==void 0&&Zm(n))return null;await Gm(r,{recursive:!0}),await yr(e,String(process.pid));let o;try{o=await ga(e,"utf8")}catch{return null}return parseInt(o.trim(),10)!==process.pid?null:t??0}async function Ta(r,e){let t=_n(r,Cn);try{if(e===0){await Wm(t);return}await yr(t,"");let{utimes:n}=await import("node:fs/promises"),o=e/1e3;await n(t,o,o)}catch{}}async function tg(r){let e=_n(r,Cn);await yr(e,String(process.pid))}function ng(r){return{taskId:`dream-${Hm().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 og(r,e={}){let t={...va,...e},n=await Qm(r,t);if(!n)return null;let o;if(t.force)try{o=await Ra(r.memoryRoot)}catch{o=0}else if(o=await eg(r.memoryRoot),o===null)return null;let s=Sa(r.memoryRoot,r.transcriptDir,n.sessionIds),i=ng({sessionId:r.currentSessionId,sessionsReviewing:n.sessionIds.length,priorLockMtime:o});return{prompt:s,taskState:i,sessionIds:n.sessionIds}}async function _a(r){let e=Date.now(),t=await og(r.context,r.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:n,sessionIds:o}=t,s=!!(r.qmemoryAdapter&&r.qmemoryUserId),i=s?Sa(r.context.memoryRoot,r.context.transcriptDir,o,{hasQMemory:!0}):t.prompt;r.log.info(`[dream] starting consolidation \u2014 ${o.length} sessions, memoryRoot=${r.context.memoryRoot}`+(s?", qmemory=enabled":"")),r.hooks?.invoke("subagent.started",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let a=(d,p)=>Xm(r.context.memoryRoot,{toolName:d,input:p}),l=s?[{type:"function",function:{name:"qmemory_search",description:"Search the user's long-term memory (QMemory). Returns relevant memories sorted by relevance.",parameters:{type:"object",properties:{query:{type:"string",description:"Semantic search query"},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"qmemory_store",description:"Store a memory to the user's long-term memory (QMemory). Use for user preferences, facts, and cross-project knowledge.",parameters:{type:"object",properties:{text:{type:"string",description:"The memory text to store"},source:{type:"string",description:"Source label (e.g. 'dream-consolidation')"}},required:["text"]}}},{type:"function",function:{name:"qmemory_feedback",description:"Submit feedback on recalled memories (e.g. mark as outdated or wrong).",parameters:{type:"object",properties:{memoryIds:{type:"array",items:{type:"string"},description:"IDs of memories to give feedback on"},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"Feedback signal"}},required:["memoryIds","signal"]}}}]:[],u=s?{invoke:async(d,p,m,g)=>{let f=r.qmemoryAdapter,b=r.qmemoryUserId;if(p==="qmemory_search"){let{query:h,limit:k}=JSON.parse(m),x=await f.search(h,b,{limit:k??10});return{result:JSON.stringify(x)}}if(p==="qmemory_store"){if(!f.addText)return{result:"",error:"addText not supported"};let{text:h,source:k}=JSON.parse(m),x=await f.addText(h,b,{sessionId:r.context.currentSessionId,source:k??"dream-consolidation"});return{result:JSON.stringify(x)}}if(p==="qmemory_feedback"){let{memoryIds:h,signal:k}=JSON.parse(m);return f.feedback&&await f.feedback(h,k,r.context.currentSessionId),{result:"Feedback recorded successfully."}}return r.toolInvoker.invoke(d,p,m,g)}}:r.toolInvoker,c=[...r.tools,...l];try{let d=await Rn({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:i,tools:c,canUseTool:a,transport:r.transport,toolInvoker:u,apiKey:r.apiKey,model:r.model,log:r.log,hooks:r.hooks,forkLabel:"dream-consolidation",parentSignal:r.parentSignal,skipTranscript:!0}),p=[];for(let m of d.events)if(m.type==="tool_call")try{let g=JSON.parse(m.arguments),f=g.file_path??g.path??g.filePath;f&&xa(f,r.context.memoryRoot)&&p.push(f)}catch{}return d.ok?(await tg(r.context.memoryRoot),r.log.info(`[dream] consolidation complete \u2014 ${p.length} files touched, ${d.durationMs}ms`)):(await Ta(r.context.memoryRoot,n.priorLockMtime),r.log.warn(`[dream] consolidation failed: ${d.error}`)),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:d.ok?"normal":"error",error:d.error}).catch(()=>{}),{ok:d.ok,sessionsReviewed:o.length,filesTouched:[...new Set(p)],turns:[],durationMs:Date.now()-e,error:d.error}}catch(d){await Ta(r.context.memoryRoot,n.priorLockMtime).catch(()=>{});let p=d instanceof Error?d.message:String(d);return r.log.warn(`[dream] consolidation error: ${p}`),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:p}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:p}}}var Bt=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 be from"node:fs";import*as De from"node:path";var Ca="transcript.jsonl",Wt="state.json",rg=50,sg=50,ig=30;function Aa(r){return r?qi(r):or()}function An(r,e){let t=r.replace(/[^a-zA-Z0-9_-]/g,"_");return De.join(Aa(e),t)}async function br(r,e,t){let n=An(r,t);await be.promises.mkdir(n,{recursive:!0});let o=JSON.stringify({role:e.role,content:e.content,ts:Date.now()})+`
126
- `;await be.promises.appendFile(De.join(n,Ca),o,"utf8")}async function Ma(r,e,t,n){let o=An(r,n);await be.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=De.join(o,Wt+".tmp");await be.promises.writeFile(i,JSON.stringify(s,null,2),"utf8"),await be.promises.rename(i,De.join(o,Wt))}async function Pa(r,e){let t=An(r,e),n=De.join(t,Ca),o=De.join(t,Wt),s=[];try{s=(await be.promises.readFile(n,"utf8")).split(`
127
- `).filter(Boolean).map(c=>{let d=JSON.parse(c);return{role:d.role,content:d.content??null}})}catch{return null}let i={sessionId:r,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:s.length},a;try{let u=await be.promises.readFile(o,"utf8"),c=JSON.parse(u);i=c.metadata,a=c.costSnapshot}catch{}let l=s.filter(u=>u.role!=="system");return{metadata:i,messages:l,costSnapshot:a}}async function Ia(r=rg,e){let t=Aa(e),n;try{n=await be.promises.readdir(t)}catch{return[]}let o=[];for(let s of n){let i=De.join(t,s,Wt);try{let a=await be.promises.readFile(i,"utf8"),l=JSON.parse(a);o.push({sessionId:l.metadata.sessionId,title:l.metadata.title,lastActiveAt:l.metadata.lastActiveAt,messageCount:l.metadata.messageCount,model:l.metadata.model})}catch{}}return o.sort((s,i)=>i.lastActiveAt-s.lastActiveAt),o.slice(0,r)}function ag(r){return r.turnCount<sg?!1:r.taskSummaryGeneratedAt?r.turnCount-(r.taskSummaryGeneratedAt??0)>=ig:!0}async function Ea(r,e,t,n,o){if(!ag(e))return null;try{let i=t.slice(-20).map(d=>`[${d.role}]: ${typeof d.content=="string"?d.content.slice(0,500):JSON.stringify(d.content).slice(0,500)}`).join(`
128
- `),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),l="";for await(let d of a)d.type==="delta"&&(l+=d.text);if(l=l.trim(),!l)return null;let u=An(r,o),c=De.join(u,Wt);try{let d=await be.promises.readFile(c,"utf8"),p=JSON.parse(d);p.metadata.taskSummary=l,p.metadata.taskSummaryGeneratedAt=e.turnCount;let m=c+".tmp";await be.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await be.promises.rename(m,c)}catch{}return l}catch{return null}}er();import{randomUUID as tx}from"node:crypto";var lg=3e4;var Pn=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),!Mn(n.lifecycle)&&Mn(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&&Mn(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=lg){let t=Date.now();for(let[n,o]of this.tasks)Mn(o.lifecycle)&&o.endedAt&&t-o.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function Mn(r){return r==="completed"||r==="failed"||r==="cancelled"||r==="timeout"}import{watch as cg}from"node:fs";import{stat as ug}from"node:fs/promises";import{join as Oa,relative as dg,resolve as pg}from"node:path";var mg=[`${_e}/settings.json`,"INSTRUCTIONS.md",`${_e}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${_e}/rules`],gg=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${_e}/rules`],kr=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 mg){let t=Oa(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=cg(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(o,s)=>{let i=s?Oa(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 ug(e)}catch{o="deleted"}let s=dg(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(()=>{}),gg.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=pg(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 La(r){let e=new kr(r);return await e.start(),e}import{readFile as fg,readdir as hg,stat as yg}from"node:fs/promises";import{dirname as In,extname as bg,isAbsolute as kg,join as tt,parse as Da,resolve as $a}from"node:path";import{homedir as Tg}from"node:os";var wg=5;var vg="INSTRUCTIONS.md",xg="INSTRUCTIONS.local.md",Sg="INSTRUCTIONS.md",Rg=[".instructions.md"],_g=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 Cg(r){try{return await fg(r,"utf-8")}catch{return null}}function Ag(r){return r.includes("<!--")?r.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):r}function Mg(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(l=>l.trim()).filter(Boolean);let a=s.map(l=>l.endsWith("/**")?l.slice(0,-3):l).filter(l=>l.length>0&&l!=="**");return{content:n,globs:a.length>0?a:void 0}}function Pg(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 l=a.indexOf("#");if(l!==-1&&(a=a.substring(0,l)),!a)continue;a=a.replace(/\\ /g," ");let u;if(a.startsWith("~/"))u=tt(Tg(),a.slice(2));else if(kg(a))u=a;else if(a.startsWith("./"))u=$a(In(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))u=$a(In(e),a);else continue;t.add(u)}return[...t]}async function et(r,e,t,n=0,o){let s=r.toLowerCase();if(t.has(s)||n>=wg)return[];let i=bg(r).toLowerCase();if(i&&!_g.has(i))return[];t.add(s);let a=await Cg(r);if(!a?.trim())return[];let{content:l,globs:u}=Mg(a),c=Ag(l);if(!c.trim())return[];let d=[],p={path:r,type:e,content:c.trim()};o&&(p.parent=o),u&&(p.globs=u),d.push(p);let m=Pg(l,r);for(let g of m){let f=await et(g,e,t,n+1,r);d.push(...f)}return d}async function Tr(r,e,t,n,o=new Set){if(o.has(r))return[];o.add(r);let s=[];try{let i=await hg(r,{withFileTypes:!0});for(let a of i){let l=tt(r,a.name);if(a.isDirectory())s.push(...await Tr(l,e,t,n,o));else if(a.isFile()&&a.name.endsWith(".md")){let u=await et(l,e,t);s.push(...u.filter(c=>n?!!c.globs:!c.globs))}}}catch{}return s}async function Ig(r){let e=r,t=Da(e).root;for(;e!==t;){try{let n=tt(e,".git"),o=await yg(n);if(o.isDirectory()||o.isFile())return e}catch{}e=In(e)}return null}async function Eg(r,e){let t=[],n=new Set,o=B(),s=tt(o,Sg);t.push(...await et(s,"User",n));let i=Gi();t.push(...await Tr(i,"User",n,!1));let l=await Ig(r)??Da(r).root,u=[],c=r;for(;u.push(c),!(c===l&&c!==r);){let d=In(c);if(d===c)break;c=d}for(let d of u.reverse()){t.push(...await et(tt(d,vg),"Project",n));for(let p of Rg)t.push(...await et(tt(d,p),"Project",n));t.push(...await et(zi(d),"Project",n)),t.push(...await Tr(Vi(d),"Project",n,!1)),t.push(...await et(tt(d,xg),"Local",n))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:r,fileCount:t.length}).catch(()=>{}),t}function Ua(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}:
125
+ Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var Pa=0;async function Tg(r,e={}){let t={...Oa,...e},n;try{n=await Da(r.memoryRoot)}catch{n=0}let o=(Date.now()-n)/36e5;if(!t.force&&o<t.minHours)return null;let s=Date.now()-Pa;if(!t.force&&s<t.scanIntervalMs)return null;Pa=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 Da(r){let e=Mn(r,Pn);return(await Ea(e)).mtimeMs}function wg(r){try{return process.kill(r,0),!0}catch{return!1}}async function vg(r){let e=Mn(r,Pn),t,n;try{let[s,i]=await Promise.all([Ea(e),_a(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<mg&&n!==void 0&&wg(n))return null;await dg(r,{recursive:!0}),await xr(e,String(process.pid));let o;try{o=await _a(e,"utf8")}catch{return null}return parseInt(o.trim(),10)!==process.pid?null:t??0}async function Ia(r,e){let t=Mn(r,Pn);try{if(e===0){await ug(t);return}await xr(t,"");let{utimes:n}=await import("node:fs/promises"),o=e/1e3;await n(t,o,o)}catch{}}async function xg(r){let e=Mn(r,Pn);await xr(e,String(process.pid))}function Sg(r){return{taskId:`dream-${pg().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 _g(r,e={}){let t={...Oa,...e},n=await Tg(r,t);if(!n)return null;let o;if(t.force)try{o=await Da(r.memoryRoot)}catch{o=0}else if(o=await vg(r.memoryRoot),o===null)return null;let s=$a(r.memoryRoot,r.transcriptDir,n.sessionIds),i=Sg({sessionId:r.currentSessionId,sessionsReviewing:n.sessionIds.length,priorLockMtime:o});return{prompt:s,taskState:i,sessionIds:n.sessionIds}}async function Ua(r){let e=Date.now(),t=await _g(r.context,r.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:n,sessionIds:o}=t,s=!!(r.qmemoryAdapter&&r.qmemoryUserId),i=s?$a(r.context.memoryRoot,r.context.transcriptDir,o,{hasQMemory:!0}):t.prompt;r.log.info(`[dream] starting consolidation \u2014 ${o.length} sessions, memoryRoot=${r.context.memoryRoot}`+(s?", qmemory=enabled":"")),r.hooks?.invoke("subagent.started",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let a=(d,p)=>kg(r.context.memoryRoot,{toolName:d,input:p}),l=s?[{type:"function",function:{name:"qmemory_search",description:"Search the user's long-term memory (QMemory). Returns relevant memories sorted by relevance.",parameters:{type:"object",properties:{query:{type:"string",description:"Semantic search query"},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"qmemory_store",description:"Store a memory to the user's long-term memory (QMemory). Use for user preferences, facts, and cross-project knowledge.",parameters:{type:"object",properties:{text:{type:"string",description:"The memory text to store"},source:{type:"string",description:"Source label (e.g. 'dream-consolidation')"}},required:["text"]}}},{type:"function",function:{name:"qmemory_feedback",description:"Submit feedback on recalled memories (e.g. mark as outdated or wrong).",parameters:{type:"object",properties:{memoryIds:{type:"array",items:{type:"string"},description:"IDs of memories to give feedback on"},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"Feedback signal"}},required:["memoryIds","signal"]}}}]:[],u=s?{invoke:async(d,p,m,g)=>{let f=r.qmemoryAdapter,b=r.qmemoryUserId;if(p==="qmemory_search"){let{query:T,limit:w}=JSON.parse(m),_=await f.search(T,b,{limit:w??10});return{result:JSON.stringify(_)}}if(p==="qmemory_store"){if(!f.addText)return{result:"",error:"addText not supported"};let{text:T,source:w}=JSON.parse(m),_=await f.addText(T,b,{sessionId:r.context.currentSessionId,source:w??"dream-consolidation"});return{result:JSON.stringify(_)}}if(p==="qmemory_feedback"){let{memoryIds:T,signal:w}=JSON.parse(m);return f.feedback&&await f.feedback(T,w,r.context.currentSessionId),{result:"Feedback recorded successfully."}}return r.toolInvoker.invoke(d,p,m,g)}}:r.toolInvoker,c=[...r.tools,...l];try{let d=await An({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:i,tools:c,canUseTool:a,transport:r.transport,toolInvoker:u,apiKey:r.apiKey,model:r.model,log:r.log,hooks:r.hooks,forkLabel:"dream-consolidation",parentSignal:r.parentSignal,skipTranscript:!0}),p=[];for(let m of d.events)if(m.type==="tool_call")try{let g=JSON.parse(m.arguments),f=g.file_path??g.path??g.filePath;f&&La(f,r.context.memoryRoot)&&p.push(f)}catch{}return d.ok?(await xg(r.context.memoryRoot),r.log.info(`[dream] consolidation complete \u2014 ${p.length} files touched, ${d.durationMs}ms`)):(await Ia(r.context.memoryRoot,n.priorLockMtime),r.log.warn(`[dream] consolidation failed: ${d.error}`)),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:d.ok?"normal":"error",error:d.error}).catch(()=>{}),{ok:d.ok,sessionsReviewed:o.length,filesTouched:[...new Set(p)],turns:[],durationMs:Date.now()-e,error:d.error}}catch(d){await Ia(r.context.memoryRoot,n.priorLockMtime).catch(()=>{});let p=d instanceof Error?d.message:String(d);return r.log.warn(`[dream] consolidation error: ${p}`),r.hooks?.invoke("subagent.stopped",{sessionId:r.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:p}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:p}}}var Wt=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 Te from"node:fs";import*as De from"node:path";var Na="transcript.jsonl",Gt="state.json",Rg=50,Cg=50,Ag=30;function Fa(r){return r?ra(r):cr()}function In(r,e){let t=r.replace(/[^a-zA-Z0-9_-]/g,"_");return De.join(Fa(e),t)}async function Sr(r,e,t){let n=In(r,t);await Te.promises.mkdir(n,{recursive:!0});let o=JSON.stringify({role:e.role,content:e.content,ts:Date.now()})+`
126
+ `;await Te.promises.appendFile(De.join(n,Na),o,"utf8")}async function ja(r,e,t,n){let o=In(r,n);await Te.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=De.join(o,Gt+".tmp");await Te.promises.writeFile(i,JSON.stringify(s,null,2),"utf8"),await Te.promises.rename(i,De.join(o,Gt))}async function Ba(r,e){let t=In(r,e),n=De.join(t,Na),o=De.join(t,Gt),s=[];try{s=(await Te.promises.readFile(n,"utf8")).split(`
127
+ `).filter(Boolean).map(c=>{let d=JSON.parse(c);return{role:d.role,content:d.content??null}})}catch{return null}let i={sessionId:r,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:s.length},a;try{let u=await Te.promises.readFile(o,"utf8"),c=JSON.parse(u);i=c.metadata,a=c.costSnapshot}catch{}let l=s.filter(u=>u.role!=="system");return{metadata:i,messages:l,costSnapshot:a}}async function Wa(r=Rg,e){let t=Fa(e),n;try{n=await Te.promises.readdir(t)}catch{return[]}let o=[];for(let s of n){let i=De.join(t,s,Gt);try{let a=await Te.promises.readFile(i,"utf8"),l=JSON.parse(a);o.push({sessionId:l.metadata.sessionId,title:l.metadata.title,lastActiveAt:l.metadata.lastActiveAt,messageCount:l.metadata.messageCount,model:l.metadata.model})}catch{}}return o.sort((s,i)=>i.lastActiveAt-s.lastActiveAt),o.slice(0,r)}function Mg(r){return r.turnCount<Cg?!1:r.taskSummaryGeneratedAt?r.turnCount-(r.taskSummaryGeneratedAt??0)>=Ag:!0}async function Ga(r,e,t,n,o){if(!Mg(e))return null;try{let i=t.slice(-20).map(d=>`[${d.role}]: ${typeof d.content=="string"?d.content.slice(0,500):JSON.stringify(d.content).slice(0,500)}`).join(`
128
+ `),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),l="";for await(let d of a)d.type==="delta"&&(l+=d.text);if(l=l.trim(),!l)return null;let u=In(r,o),c=De.join(u,Gt);try{let d=await Te.promises.readFile(c,"utf8"),p=JSON.parse(d);p.metadata.taskSummary=l,p.metadata.taskSummaryGeneratedAt=e.turnCount;let m=c+".tmp";await Te.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await Te.promises.rename(m,c)}catch{}return l}catch{return null}}ar();import{randomUUID as jx}from"node:crypto";var Pg=3e4;var On=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),!En(n.lifecycle)&&En(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&&En(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=Pg){let t=Date.now();for(let[n,o]of this.tasks)En(o.lifecycle)&&o.endedAt&&t-o.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function En(r){return r==="completed"||r==="failed"||r==="cancelled"||r==="timeout"}import{watch as Ig}from"node:fs";import{stat as Eg}from"node:fs/promises";import{join as Ha,relative as Og,resolve as Lg}from"node:path";var $g=[`${ye}/settings.json`,"INSTRUCTIONS.md",`${ye}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${ye}/rules`],Dg=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${ye}/rules`],_r=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 $g){let t=Ha(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=Ig(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(o,s)=>{let i=s?Ha(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 Eg(e)}catch{o="deleted"}let s=Og(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(()=>{}),Dg.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=Lg(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 Va(r){let e=new _r(r);return await e.start(),e}import{readFile as Ug,readdir as Ng,stat as Fg}from"node:fs/promises";import{dirname as Ln,extname as jg,isAbsolute as Bg,join as tt,parse as qa,resolve as za}from"node:path";import{homedir as Wg}from"node:os";var Gg=5;var Hg="INSTRUCTIONS.md",Vg="INSTRUCTIONS.local.md",zg="INSTRUCTIONS.md",qg=[".instructions.md"],Kg=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 Jg(r){try{return await Ug(r,"utf-8")}catch{return null}}function Yg(r){return r.includes("<!--")?r.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):r}function Xg(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(l=>l.trim()).filter(Boolean);let a=s.map(l=>l.endsWith("/**")?l.slice(0,-3):l).filter(l=>l.length>0&&l!=="**");return{content:n,globs:a.length>0?a:void 0}}function Qg(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 l=a.indexOf("#");if(l!==-1&&(a=a.substring(0,l)),!a)continue;a=a.replace(/\\ /g," ");let u;if(a.startsWith("~/"))u=tt(Wg(),a.slice(2));else if(Bg(a))u=a;else if(a.startsWith("./"))u=za(Ln(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))u=za(Ln(e),a);else continue;t.add(u)}return[...t]}async function et(r,e,t,n=0,o){let s=r.toLowerCase();if(t.has(s)||n>=Gg)return[];let i=jg(r).toLowerCase();if(i&&!Kg.has(i))return[];t.add(s);let a=await Jg(r);if(!a?.trim())return[];let{content:l,globs:u}=Xg(a),c=Yg(l);if(!c.trim())return[];let d=[],p={path:r,type:e,content:c.trim()};o&&(p.parent=o),u&&(p.globs=u),d.push(p);let m=Qg(l,r);for(let g of m){let f=await et(g,e,t,n+1,r);d.push(...f)}return d}async function Rr(r,e,t,n,o=new Set){if(o.has(r))return[];o.add(r);let s=[];try{let i=await Ng(r,{withFileTypes:!0});for(let a of i){let l=tt(r,a.name);if(a.isDirectory())s.push(...await Rr(l,e,t,n,o));else if(a.isFile()&&a.name.endsWith(".md")){let u=await et(l,e,t);s.push(...u.filter(c=>n?!!c.globs:!c.globs))}}}catch{}return s}async function Zg(r){let e=r,t=qa(e).root;for(;e!==t;){try{let n=tt(e,".git"),o=await Fg(n);if(o.isDirectory()||o.isFile())return e}catch{}e=Ln(e)}return null}async function ef(r,e){let t=[],n=new Set,o=G(),s=tt(o,zg);t.push(...await et(s,"User",n));let i=ea();t.push(...await Rr(i,"User",n,!1));let l=await Zg(r)??qa(r).root,u=[],c=r;for(;u.push(c),!(c===l&&c!==r);){let d=Ln(c);if(d===c)break;c=d}for(let d of u.reverse()){t.push(...await et(tt(d,Hg),"Project",n));for(let p of qg)t.push(...await et(tt(d,p),"Project",n));t.push(...await et(na(d),"Project",n)),t.push(...await Rr(oa(d),"Project",n,!1)),t.push(...await et(tt(d,Vg),"Local",n))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:r,fileCount:t.length}).catch(()=>{}),t}function Ka(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}:
129
129
 
130
130
  ${n.content.trim()}`)}return t.length>0?`${e}
131
131
 
132
132
  ${t.join(`
133
133
 
134
- `)}`:""}var Gt=null,wr=null;async function Na(r,e){return Gt&&wr===r||(Gt=await Eg(r,e),wr=r),Gt}function Fa(){Gt=null,wr=null}function vr(r,e){return{name:r,compute:e,cacheBreak:!1}}var En=new Map;async function Og(r){return(await Promise.all(r.map(async t=>{if(!t.cacheBreak&&En.has(t.name))return En.get(t.name)??null;let n=await t.compute();return En.set(t.name,n),n}))).filter(t=>t!=null)}function ja(){En.clear()}async function Ba(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 Og(r.sections);e.push(...t)}return r.appendSystemPrompt&&e.push(r.appendSystemPrompt),e.filter(Boolean).join(`
134
+ `)}`:""}var Ht=null,Cr=null;async function Ja(r,e){return Ht&&Cr===r||(Ht=await ef(r,e),Cr=r),Ht}function Ya(){Ht=null,Cr=null}function Ar(r,e){return{name:r,compute:e,cacheBreak:!1}}function Xa(r,e,t){return{name:r,compute:e,cacheBreak:!0}}var $n=new Map;async function tf(r){return(await Promise.all(r.map(async t=>{if(!t.cacheBreak&&$n.has(t.name))return $n.get(t.name)??null;let n=await t.compute();return $n.set(t.name,n),n}))).filter(t=>t!=null)}function Qa(){$n.clear()}async function Za(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 tf(r.sections);e.push(...t)}return r.appendSystemPrompt&&e.push(r.appendSystemPrompt),e.filter(Boolean).join(`
135
135
 
136
- `)}import{release as Lg,homedir as $g}from"node:os";import{resolve as Dg}from"node:path";function Ug(){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 Ng(){let r=process.platform,e=Lg();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 Wa(r){return vr("environment_context",()=>{let e=Ug(),t=Ng(),n=r??process.cwd(),o=process.version,s=$g(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${Dg(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(`
137
- `)})}function Ga(){return vr("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 `skill_invoke` to run installed skills by name when:","- The user asks to run, invoke, or execute a specific skill","- A matching skill exists in the configured skill paths","- The task matches a skill's trigger pattern","Do NOT search manually for skills \u2014 use `skill_invoke` directly.","","## 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(`
138
- `))}import*as L from"node:fs";import*as W from"node:path";import{execFile as Zh}from"node:child_process";var xr=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),Ha=new Set([...xr,"agent"]);function Sr(r,e){let t=e?xr:Ha;return r.filter(n=>n.function.name.startsWith("mcp__")?!0:!t.has(n.function.name))}var je=new Map;function za(r){je.clear();for(let e of r)je.set(e.name,e)}function ce(r){je.set(r.name,r)}function Rr(r){for(let e of r)je.set(e.name,e)}function On(r){return je.delete(r)}function ke(r){return je.get(r)}function Be(){return Array.from(je.keys())}function We(r=!1){let e=[];for(let t of je.values())t.isEnabled?.()!==!1&&(!r&&t.shouldDefer||e.push({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters},meta:{parallelSafe:t.isConcurrencySafe??!1,isReadOnly:t.isReadOnly??!1,isDangerous:!(t.isReadOnly??!1)&&!(t.isConcurrencySafe??!1)}}));return e}var Fg="think",jg={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(`
139
- `)}},required:["thought"]};function Va(){return{name:Fg,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(`
140
- `),parameters:jg,execute:async(r,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function mt(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}}var Bg="todo",Wg=["create","update","delete","list"],Gg={type:"object",properties:{action:{type:"string",enum:[...Wg],description:"create \u2014 add a single new task (auto-assigns id). update \u2014 modify a single task by id (partial). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list."},id:{type:"number",description:"[update|delete] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task."}},required:["action"]};function qa(r){let e=[],t=0,n=r??{};function o(){let p=e.reduce((m,g)=>Math.max(m,g.id),0);return t=Math.max(t,p)+1,t}function s(p){return{content:[{type:"text",text:JSON.stringify({error:p,todoList:e})}],details:{type:"todo",error:p}}}function i(p){let m=mt(e),g=new Set(e.filter(h=>h.status==="completed").map(h=>h.id)),f=e.map(h=>{let k=h.blockedBy?.filter(x=>!g.has(x));return{...h,...k?.length?{blockedBy:k}:{blockedBy:void 0}}}),b={...m,todoList:f,...p};return{content:[{type:"text",text:JSON.stringify(b)}],details:{type:"todo",...m,agentId:n.agentId}}}function a(p,m,g){let f=e.find(b=>b.id===p);if(f){if(m?.length){f.blocks=[...new Set([...f.blocks??[],...m])];for(let b of m){let h=e.find(k=>k.id===b);h&&(h.blockedBy=[...new Set([...h.blockedBy??[],p])])}}if(g?.length){f.blockedBy=[...new Set([...f.blockedBy??[],...g])];for(let b of g){let h=e.find(k=>k.id===b);h&&(h.blocks=[...new Set([...h.blocks??[],p])])}}}}function l(p){for(let m of e)m.blocks&&(m.blocks=m.blocks.filter(g=>g!==p)),m.blockedBy&&(m.blockedBy=m.blockedBy.filter(g=>g!==p))}function u(p){if(!p.title)return s("title is required for create action.");let m={id:o(),title:p.title,status:"not-started",...p.description!=null&&{description:p.description},...p.owner!=null&&{owner:p.owner}};return e.push(m),a(m.id,void 0,p.addBlockedBy),i({created:{id:m.id,title:m.title}})}function c(p){if(p.id==null)return s("id is required for update action.");let m=e.find(g=>g.id===p.id);if(!m)return s(`Task #${p.id} not found.`);if(p.status==="in-progress"){let g=e.find(f=>f.status==="in-progress"&&f.id!==p.id);if(g)return s(`Cannot set #${p.id} to in-progress: #${g.id} already is.`)}return p.title!=null&&(m.title=p.title),p.description!=null&&(m.description=p.description),p.owner!=null&&(m.owner=p.owner),p.status!=null&&(m.status=p.status),a(m.id,p.addBlocks,p.addBlockedBy),i({updated:{id:m.id,title:m.title}})}function d(p){if(p.id==null)return s("id is required for delete action.");let m=e.findIndex(g=>g.id===p.id);return m===-1?s(`Task #${p.id} not found.`):(t=Math.max(t,p.id),e.splice(m,1),l(p.id),i({deleted:p.id}))}return{name:Bg,label:"Todo",description:"Manage a structured todo list to track multi-step task progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all). Supports dependency tracking (blocks/blockedBy). Use frequently during complex work to plan steps and show progress.",parameters:Gg,searchHint:"manage session task checklist progress tracking dependencies",maxResultSizeChars:1e5,execute:async(p,m)=>{let g=m.action;switch(g){case"create":return u(m);case"update":return c(m);case"delete":return d(m);case"list":return i();default:return s(`Unknown action: ${g}. Valid: create, update, delete, list.`)}}}}import{isAbsolute as cf,resolve as uf}from"node:path";var Ka=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Ja=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Ya=new Set(["ls","tree","du"]);var Xa=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Hg(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 l=n[o];if(s.test(l)){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 Qa(r){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(r)}function _r(r){let e=Hg(r),t=e!==null&&Ka.has(e),n=e!==null&&Ja.has(e),o=e!==null&&Ya.has(e),s=e!==null&&Xa.has(e),i=/(?:[^2]>|^>|\|>)/.test(r),a=Qa(r),l=(t||n||o)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:o,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}function Cr(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 ef}from"node:child_process";import{constants as Un,readFileSync as tf,unlinkSync as nf}from"node:fs";import{mkdir as of,open as rf,realpath as nl}from"node:fs/promises";import{isAbsolute as sf,resolve as af}from"node:path";function Ln(){if(process.platform!=="win32")return!1;let r=process.env.QLOGICAGENT_USE_POWERSHELL;return r==="1"||r==="true"}function Ar(){return Ln()?"powershell":"bash"}function Mr(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as zg,readFile as Vg,writeFile as qg,unlink as Kg}from"node:fs/promises";import{join as Za}from"node:path";import{tmpdir as Jg}from"node:os";var Yg=8*1024*1024,Xg=5*1024*1024*1024;var Pr;function Ht(){if(!Pr){let r=Math.random().toString(36).slice(2,10);Pr=Za(Jg(),"qla-tasks",r)}return Pr}function el(r){return Za(Ht(),`${r}.output`)}function Ue(r="local_bash"){return`${r}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Ge=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,n=!1,o=Yg){this.taskId=e,this.path=el(e),this.stdoutToFile=n,this.#t=o,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=Qg(e),this.#u()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await Vg(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&zg(Ht(),{recursive:!0}).then(()=>qg(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await Kg(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function Qg(r){let e=0;for(let t=0;t<r.length;t++)r.charCodeAt(t)===10&&e++;return e}var Ir=137,tl=143,Zg=5e3,Er=5*1024*1024*1024,$n=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)}},Or=class r{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,n,o,s=!1,i=Er){this.#t=e,this.#l=t,this.#g=n,this.#b=s,this.#u=i,this.taskOutput=o,this.#s=e.stderr?new $n(e.stderr,o,!0):null,this.#r=e.stdout?new $n(e.stdout,o,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#R()}get status(){return this.#e}static#T(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(tl)}#w(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#x(){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)}#S(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#u&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(Ir))},()=>{}))},Zg),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.#x.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===Ir,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 ${Er} bytes. ${n.stderr}`:e===tl&&(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??Ir)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#S():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#d=void 0}};function Lr(r,e,t,n,o=!1,s=Er){return new Or(r,e,t,n,o,s)}function Dn(r,e){let t=new Ge(Ue("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 $r(r){let e=new Ge(Ue("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 lf=1800*1e3,Nn=process.cwd(),ol=process.cwd();function Fn(){return Nn}function Dr(r,e){Nn=sf(r)?r:af(e||Nn,r)}function rl(){return ol}function jn(r){Nn=r,ol=r}var Ur=null;function zt(r){Ur={provider:r}}function sl(){if(!Ur)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return Ur.provider}async function Bn(r,e,t,n){let{timeout:o,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:u}=n??{},c=o||lf,d=t??Ar(),p=sl(),m=Mr(),{commandString:g,cwdFilePath:f}=await p.buildExecCommand(r,{id:m,useSandbox:!1}),b=g,h=u??Fn();try{await nl(h)}catch{let w=rl();try{await nl(w),Dr(w),h=w}catch{return $r(`Working directory "${h}" no longer exists.`)}}if(e.aborted)return Dn();let k=p.shellPath,x=p.getSpawnArgs(b),R=await p.getEnvironmentOverrides(r),E=!!l,F=Ue("local_bash"),U=new Ge(F,s??null,!E);await of(Ht(),{recursive:!0});let D;if(!E){let w=Un.O_NOFOLLOW??0;D=await rf(U.path,process.platform==="win32"?"w":Un.O_WRONLY|Un.O_CREAT|Un.O_APPEND|w)}try{let w=ef(k,x,{env:{...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...R},cwd:h,stdio:E?["pipe","pipe","pipe"]:["pipe",D?.fd,D?.fd],detached:p.detached,windowsHide:!0}),ge=Lr(w,e,c,U,a);if(D!==void 0)try{await D.close()}catch{}return w.stdout&&l&&w.stdout.on("data",H=>{l(typeof H=="string"?H:H.toString())}),f&&ge.result.then(H=>{if(H&&!i&&!H.backgroundTaskId){try{let z=tf(f,{encoding:"utf8"}).trim();z&&z.normalize("NFC")!==h&&Dr(z,h)}catch{}try{nf(f)}catch{}}}),ge}catch(w){if(D!==void 0)try{await D.close()}catch{}return U.clear(),Dn(void 0,{code:126,stderr:w instanceof Error?w.message:String(w)})}}var df="exec",pf={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"]},mf=12e4,gf=6e5,Wn=3e4;function Nr(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
136
+ `)}import{release as nf,homedir as of}from"node:os";import{resolve as rf}from"node:path";function sf(){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 af(){let r=process.platform,e=nf();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 el(r){return Ar("environment_context",()=>{let e=sf(),t=af(),n=r??process.cwd(),o=process.version,s=of(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${rf(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(`
137
+ `)})}function Dn(){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 lf(){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.)."]}function cf(){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 uf(){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 tl(r="general"){return Xa("task_guidance",()=>{let e;switch(r){case"coding":e=[...lf(),"",...Dn()];break;case"office":e=[...cf(),"",...Dn()];break;case"creative":e=[...uf(),"",...Dn()];break;default:e=["# Doing Tasks","","You are a versatile assistant that handles software engineering, office, and creative tasks.","",...Dn(),"","## 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 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(`
138
+ `)})}function nl(){return Ar("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 `skill_invoke` to run installed skills by name when:","- The user asks to run, invoke, or execute a specific skill","- A matching skill exists in the configured skill paths","- The task matches a skill's trigger pattern","Do NOT search manually for skills \u2014 use `skill_invoke` directly.","","## 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(`
139
+ `))}import{existsSync as ol,mkdirSync as df,readFileSync as Vt,writeFileSync as rl}from"node:fs";import{join as zt}from"node:path";var Un=new Set(["coding","office","creative","general"]),sl="settings.yaml";function pf(r){try{let e=zt(r,ye,sl),n=Vt(e,"utf-8").match(/^taskDomain\s*:\s*(\w+)/m);if(n){let o=n[1].toLowerCase();if(Un.has(o))return o}}catch{}try{let e=zt(r,ye,"INSTRUCTIONS.md"),n=Vt(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(Un.has(s))return s}}}catch{}try{let e=zt(r,"INSTRUCTIONS.md"),n=Vt(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(Un.has(s))return s}}}catch{}}var mf=3;function gf(r,e){let t=bf(r);return e?t===e||t==="general"?e:(Pr(r)[t]??0)>=mf?t:e:t}var ff=/\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,hf=/\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,yf=/\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 bf(r){if(!r||r.trim().length===0)return"general";let e=Pr(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 Pr(r){return{coding:Mr(r,ff),office:Mr(r,hf),creative:Mr(r,yf),general:0}}function Mr(r,e){let t=new RegExp(e.source,"gi"),n=r.match(t);return n?n.length:0}function il(r){let e=pf(r.cwd);if(e)return{domain:e,source:"project-file"};if(r.hostOverride&&Un.has(r.hostOverride))return{domain:r.hostOverride,source:"host-override"};let t=gf(r.userText,r.sessionDomain);return r.sessionDomain&&t===r.sessionDomain?{domain:t,source:"session-sticky"}:{domain:t,source:"auto-detect"}}var kf=3;function al(r,e){if(e==="general")return!1;try{let t=zt(r,ye),n=zt(t,sl);if(ol(n)){let s=Vt(n,"utf-8");if(/^taskDomain\s*:/m.test(s))return!1}df(t,{recursive:!0});let o=`# Auto-detected task domain for this workspace.
140
+ # Values: coding | office | creative | general
141
+ `;if(ol(n)){let s=Vt(n,"utf-8");rl(n,s.trimEnd()+`
142
+
143
+ `+o+`taskDomain: ${e}
144
+ `,"utf-8")}else rl(n,o+`taskDomain: ${e}
145
+ `,"utf-8");return!0}catch{return!1}}function ll(r,e){return e==="general"?!1:(Pr(r)[e]??0)>=kf}import*as U from"node:fs";import*as H from"node:path";import{execFile as Ny}from"node:child_process";var Ir=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),cl=new Set([...Ir,"agent"]);function Er(r,e){let t=e?Ir:cl;return r.filter(n=>n.function.name.startsWith("mcp__")?!0:!t.has(n.function.name))}var Ue=new Map,Or=new Set;function ul(r){Ue.clear(),Or.clear();for(let e of r)Ue.set(e.name,e)}function me(r){Ue.set(r.name,r)}function Lr(r){for(let e of r)Ue.set(e.name,e)}function Nn(r){return Ue.delete(r)}function we(r){return Ue.get(r)}function Be(){return Array.from(Ue.keys())}function dl(r){let e=Ue.get(r);return!e||e.isEnabled?.()===!1?!1:(Or.add(r),!0)}function We(r=!1){let e=[];for(let t of Ue.values())t.isEnabled?.()!==!1&&(!r&&t.shouldDefer&&!Or.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 Tf="think",wf={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(`
146
+ `)}},required:["thought"]};function pl(){return{name:Tf,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(`
147
+ `),parameters:wf,execute:async(r,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function mt(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}}var vf="todo",xf=["create","update","delete","list"],Sf={type:"object",properties:{action:{type:"string",enum:[...xf],description:"create \u2014 add a single new task (auto-assigns id). update \u2014 modify a single task by id (partial). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list."},id:{type:"number",description:"[update|delete] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task."}},required:["action"]};function ml(r){let e=[],t=0,n=r??{};function o(){let p=e.reduce((m,g)=>Math.max(m,g.id),0);return t=Math.max(t,p)+1,t}function s(p){return{content:[{type:"text",text:JSON.stringify({error:p,todoList:e})}],details:{type:"todo",error:p}}}function i(p){let m=mt(e),g=new Set(e.filter(T=>T.status==="completed").map(T=>T.id)),f=e.map(T=>{let w=T.blockedBy?.filter(_=>!g.has(_));return{...T,...w?.length?{blockedBy:w}:{blockedBy:void 0}}}),b={...m,todoList:f,...p};return{content:[{type:"text",text:JSON.stringify(b)}],details:{type:"todo",...m,agentId:n.agentId}}}function a(p,m,g){let f=e.find(b=>b.id===p);if(f){if(m?.length){f.blocks=[...new Set([...f.blocks??[],...m])];for(let b of m){let T=e.find(w=>w.id===b);T&&(T.blockedBy=[...new Set([...T.blockedBy??[],p])])}}if(g?.length){f.blockedBy=[...new Set([...f.blockedBy??[],...g])];for(let b of g){let T=e.find(w=>w.id===b);T&&(T.blocks=[...new Set([...T.blocks??[],p])])}}}}function l(p){for(let m of e)m.blocks&&(m.blocks=m.blocks.filter(g=>g!==p)),m.blockedBy&&(m.blockedBy=m.blockedBy.filter(g=>g!==p))}function u(p){if(!p.title)return s("title is required for create action.");let m={id:o(),title:p.title,status:"not-started",...p.description!=null&&{description:p.description},...p.owner!=null&&{owner:p.owner}};return e.push(m),a(m.id,void 0,p.addBlockedBy),i({created:{id:m.id,title:m.title}})}function c(p){if(p.id==null)return s("id is required for update action.");let m=e.find(g=>g.id===p.id);if(!m)return s(`Task #${p.id} not found.`);if(p.status==="in-progress"){let g=e.find(f=>f.status==="in-progress"&&f.id!==p.id);if(g)return s(`Cannot set #${p.id} to in-progress: #${g.id} already is.`)}return p.title!=null&&(m.title=p.title),p.description!=null&&(m.description=p.description),p.owner!=null&&(m.owner=p.owner),p.status!=null&&(m.status=p.status),a(m.id,p.addBlocks,p.addBlockedBy),i({updated:{id:m.id,title:m.title}})}function d(p){if(p.id==null)return s("id is required for delete action.");let m=e.findIndex(g=>g.id===p.id);return m===-1?s(`Task #${p.id} not found.`):(t=Math.max(t,p.id),e.splice(m,1),l(p.id),i({deleted:p.id}))}return{name:vf,label:"Todo",description:"Manage a structured todo list to track multi-step task progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all). Supports dependency tracking (blocks/blockedBy). Use frequently during complex work to plan steps and show progress.",parameters:Sf,searchHint:"manage session task checklist progress tracking dependencies",maxResultSizeChars:1e5,execute:async(p,m)=>{let g=m.action;switch(g){case"create":return u(m);case"update":return c(m);case"delete":return d(m);case"list":return i();default:return s(`Unknown action: ${g}. Valid: create, update, delete, list.`)}}}}import{isAbsolute as zf,resolve as qf}from"node:path";var gl=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),fl=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),hl=new Set(["ls","tree","du"]);var yl=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function _f(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 l=n[o];if(s.test(l)){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 bl(r){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(r)}function $r(r){let e=_f(r),t=e!==null&&gl.has(e),n=e!==null&&fl.has(e),o=e!==null&&hl.has(e),s=e!==null&&yl.has(e),i=/(?:[^2]>|^>|\|>)/.test(r),a=bl(r),l=(t||n||o)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:o,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}function Dr(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 Nf}from"node:child_process";import{constants as Wn,readFileSync as Ff,unlinkSync as jf}from"node:fs";import{mkdir as Bf,open as Wf,realpath as vl}from"node:fs/promises";import{isAbsolute as Gf,resolve as Hf}from"node:path";function Fn(){if(process.platform!=="win32")return!1;let r=process.env.QLOGICAGENT_USE_POWERSHELL;return r==="1"||r==="true"}function Ur(){return Fn()?"powershell":"bash"}function Nr(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as Rf,readFile as Cf,writeFile as Af,unlink as Mf}from"node:fs/promises";import{join as kl}from"node:path";import{tmpdir as Pf}from"node:os";var If=8*1024*1024,Ef=5*1024*1024*1024;var Fr;function qt(){if(!Fr){let r=Math.random().toString(36).slice(2,10);Fr=kl(Pf(),"qla-tasks",r)}return Fr}function Tl(r){return kl(qt(),`${r}.output`)}function Ne(r="local_bash"){return`${r}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Ge=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,n=!1,o=If){this.taskId=e,this.path=Tl(e),this.stdoutToFile=n,this.#t=o,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=Of(e),this.#u()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await Cf(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&Rf(qt(),{recursive:!0}).then(()=>Af(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await Mf(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function Of(r){let e=0;for(let t=0;t<r.length;t++)r.charCodeAt(t)===10&&e++;return e}var jr=137,wl=143,Lf=5e3,Br=5*1024*1024*1024,jn=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)}},Wr=class r{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,n,o,s=!1,i=Br){this.#t=e,this.#l=t,this.#g=n,this.#b=s,this.#u=i,this.taskOutput=o,this.#s=e.stderr?new jn(e.stderr,o,!0):null,this.#r=e.stdout?new jn(e.stdout,o,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#_()}get status(){return this.#e}static#T(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(wl)}#w(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#x(){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)}#S(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#u&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(jr))},()=>{}))},Lf),this.#o.unref?.()}#_(){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.#x.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.#R.bind(this))})}async#R(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===jr,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 ${Br} bytes. ${n.stderr}`:e===wl&&(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??jr)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#S():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#d=void 0}};function Gr(r,e,t,n,o=!1,s=Br){return new Wr(r,e,t,n,o,s)}function Bn(r,e){let t=new Ge(Ne("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 Hr(r){let e=new Ge(Ne("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 $f=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"]),Df=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function Vr(){let r={...process.env};for(let e of Object.keys(r))Uf(e)&&delete r[e];return r}function Uf(r){if($f.has(r))return!0;let e=r.toUpperCase();for(let t of Df)if(e.includes(t))return!0;return!1}var Vf=1800*1e3,Gn=process.cwd(),xl=process.cwd();function Hn(){return Gn}function zr(r,e){Gn=Gf(r)?r:Hf(e||Gn,r)}function Sl(){return xl}function Vn(r){Gn=r,xl=r}var qr=null;function Kt(r){qr={provider:r}}function _l(){if(!qr)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return qr.provider}async function zn(r,e,t,n){let{timeout:o,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:u}=n??{},c=o||Vf,d=t??Ur(),p=_l(),m=Nr(),{commandString:g,cwdFilePath:f}=await p.buildExecCommand(r,{id:m,useSandbox:!1}),b=g,T=u??Hn();try{await vl(T)}catch{let v=Sl();try{await vl(v),zr(v),T=v}catch{return Hr(`Working directory "${T}" no longer exists.`)}}if(e.aborted)return Bn();let w=p.shellPath,_=p.getSpawnArgs(b),y=await p.getEnvironmentOverrides(r),C=!!l,E=Ne("local_bash"),D=new Ge(E,s??null,!C);await Bf(qt(),{recursive:!0});let L;if(!C){let v=Wn.O_NOFOLLOW??0;L=await Wf(D.path,process.platform==="win32"?"w":Wn.O_WRONLY|Wn.O_CREAT|Wn.O_APPEND|v)}try{let v=Nf(w,_,{env:{...Vr(),GIT_EDITOR:"true",QLOGICAGENT:"1",...y},cwd:T,stdio:C?["pipe","pipe","pipe"]:["pipe",L?.fd,L?.fd],detached:p.detached,windowsHide:!0}),ce=Gr(v,e,c,D,a);if(L!==void 0)try{await L.close()}catch{}return v.stdout&&l&&v.stdout.on("data",j=>{l(typeof j=="string"?j:j.toString())}),f&&ce.result.then(j=>{if(j&&!i&&!j.backgroundTaskId){try{let F=Ff(f,{encoding:"utf8"}).trim();F&&F.normalize("NFC")!==T&&zr(F,T)}catch{}try{jf(f)}catch{}}}),ce}catch(v){if(L!==void 0)try{await L.close()}catch{}return D.clear(),Bn(void 0,{code:126,stderr:v instanceof Error?v.message:String(v)})}}var Kf="exec",Jf={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"]},Yf=12e4,Xf=6e5,qn=3e4;function Kr(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
141
148
 
142
149
  ... [truncated ${r.length-e} chars] ...
143
150
 
144
- ${r.slice(-t)}`}function ff(r){return r==null||r<=0?mf:Math.min(r,gf)}async function*hf(r){let{command:e,abortController:t,timeout:n,shouldAutoBackground:o,cwd:s}=r,i="",a=0,l=0,u=Date.now(),c=null;function d(){return new Promise(g=>{c=()=>g(null)})}let p=await Bn(e,t.signal,void 0,{timeout:n,onProgress(g,f,b,h,k){i=f,a=b,l=h,c&&(c(),c=null)},shouldAutoBackground:o,cwd:s});for(p.onTimeout&&o&&p.onTimeout(g=>{let f=Ue("bg");g(f)});p.status==="running"&&await Promise.race([d(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-u)/1e3,totalLines:a,totalBytes:l};let m=await p.result;return p.cleanup(),m}function il(r={}){return{name:df,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:pf,maxResultSizeChars:Wn,execute:async(e,t)=>{let n=_r(t.command);if(!t.background){let p=Cr(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=ff(t.timeout),i=t.workdir?cf(t.workdir)?t.workdir:uf(Fn(),t.workdir):void 0;if(t.background){let p=await Bn(t.command,o.signal,void 0,{shouldAutoBackground:!1,cwd:i}),m=Ue("bg");if(p.background(m))return{content:[{type:"text",text:`Background task started (id: ${m}).
145
- Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:t.description,classification:n}}}let a=hf({command:t.command,abortController:o,timeout:s,shouldAutoBackground:!0,cwd:i}),l;do l=await a.next(),!l.done&&r.onProgress&&r.onProgress(l.value);while(!l.done);let u=l.value,c=[];if(u.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${u.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:u.backgroundTaskId,assistantAutoBackgrounded:u.assistantAutoBackgrounded,classification:n}};u.outputFilePath?(c.push(Nr(u.stdout,Wn)),c.push(`[full output: ${u.outputFilePath} (${u.outputFileSize} bytes)]`)):u.stdout&&c.push(Nr(u.stdout,Wn)),u.stderr&&c.push(`[stderr]
146
- ${Nr(u.stderr,Math.floor(Wn/4))}`),u.interrupted&&c.push(`[interrupted \u2014 exit code ${u.code}]`);let d;return u.code!==0&&r.interpretExitCode&&(d=r.interpretExitCode(u.code,u.stderr),d&&c.push(`[exit ${u.code}: ${d}]`)),c.length===0&&c.push(n.isSilent&&u.code===0?"Done":`(exit code ${u.code}, no output)`),{content:[{type:"text",text:c.join(`
147
- `)}],details:{type:"exec",exitCode:u.code,interrupted:u.interrupted,description:t.description,returnCodeInterpretation:d,noOutputExpected:n.isSilent,outputFilePath:u.outputFilePath,classification:n}}}}}import{tmpdir as yf}from"node:os";import{join as bf,posix as Fr}from"node:path";function kf(r){return r.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function Tf(r){return!(/(?:^|[;&|])\s*<\s/.test(r)||/<<[-]?\s*['"]?[A-Za-z_]/.test(r))}function wf(r,e){return`$'${r.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function al(r){return process.platform!=="win32"?r:r.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function Gn(r,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:r,detached:!0,async buildExecCommand(n,o){let s=process.platform==="win32",i=yf(),a=s?al(i):i,l=o.useSandbox&&o.sandboxTmpDir?Fr.join(o.sandboxTmpDir,`cwd-${o.id}`):Fr.join(a,`qla-${o.id}-cwd`),u=o.useSandbox&&o.sandboxTmpDir?Fr.join(o.sandboxTmpDir,`cwd-${o.id}`):bf(i,`qla-${o.id}-cwd`),c=kf(n),d=Tf(c),p=wf(c,d),m=[];if(t){let f=s?al(t):t;m.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${l}'`),{commandString:m.join(" && "),cwdFilePath:u}},getSpawnArgs(n){return["-c",...!!t?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as vf}from"node:os";import{join as xf,posix as Sf}from"node:path";function ll(r){return Buffer.from(r,"utf16le").toString("base64")}function Rf(r){return["-NoProfile","-NonInteractive","-Command",r]}function jr(r){return{type:"powershell",shellPath:r,detached:!1,async buildExecCommand(e,t){let n=t.useSandbox&&t.sandboxTmpDir?Sf.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):xf(vf(),`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(`
148
- ; `),i=e+s;return{commandString:t.useSandbox?[`'${r.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",ll(i)].join(" "):i,cwdFilePath:n}},getSpawnArgs(e){return Rf(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var _f=[{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"}],Cf=[{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 Br(r){for(let{pattern:e,warning:t}of _f)if(e.test(r))return t;return null}function Wr(r){for(let{pattern:e,warning:t}of Cf)if(e.test(r))return t;return null}var Af="read",Mf={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 cl(r){return{name:Af,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:Mf,execute:async(n,o)=>{let s=r.resolvePath(o.path);if(r.validatePath){let f=r.validatePath(s);if(f)return{content:[{type:"text",text:`Access denied: ${f}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await r.readFile(s);if(i.type==="image")return{content:[{type:"image",data:i.base64,mimeType:i.mimeType}],details:{type:"read",path:s,isImage:!0}};if(i.type==="binary")return{content:[{type:"text",text:`Cannot read binary file (${i.mimeType}). Use a specific tool for this file type (e.g. pdf tool for PDFs).`}],details:{type:"read",path:s,error:"binary_file",mimeType:i.mimeType}};let a=i.text.split(`
151
+ ${r.slice(-t)}`}function Qf(r){return r==null||r<=0?Yf:Math.min(r,Xf)}async function*Zf(r){let{command:e,abortController:t,timeout:n,shouldAutoBackground:o,cwd:s}=r,i="",a=0,l=0,u=Date.now(),c=null;function d(){return new Promise(g=>{c=()=>g(null)})}let p=await zn(e,t.signal,void 0,{timeout:n,onProgress(g,f,b,T,w){i=f,a=b,l=T,c&&(c(),c=null)},shouldAutoBackground:o,cwd:s});for(p.onTimeout&&o&&p.onTimeout(g=>{let f=Ne("bg");g(f)});p.status==="running"&&await Promise.race([d(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-u)/1e3,totalLines:a,totalBytes:l};let m=await p.result;return p.cleanup(),m}function Rl(r={}){return{name:Kf,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:Jf,maxResultSizeChars:qn,execute:async(e,t)=>{let n=$r(t.command);if(!t.background){let p=Dr(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=Qf(t.timeout),i=t.workdir?zf(t.workdir)?t.workdir:qf(Hn(),t.workdir):void 0;if(t.background){let p=await zn(t.command,o.signal,void 0,{shouldAutoBackground:!1,cwd:i}),m=Ne("bg");if(p.background(m))return{content:[{type:"text",text:`Background task started (id: ${m}).
152
+ Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:t.description,classification:n}}}let a=Zf({command:t.command,abortController:o,timeout:s,shouldAutoBackground:!0,cwd:i}),l;do l=await a.next(),!l.done&&r.onProgress&&r.onProgress(l.value);while(!l.done);let u=l.value,c=[];if(u.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${u.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:u.backgroundTaskId,assistantAutoBackgrounded:u.assistantAutoBackgrounded,classification:n}};u.outputFilePath?(c.push(Kr(u.stdout,qn)),c.push(`[full output: ${u.outputFilePath} (${u.outputFileSize} bytes)]`)):u.stdout&&c.push(Kr(u.stdout,qn)),u.stderr&&c.push(`[stderr]
153
+ ${Kr(u.stderr,Math.floor(qn/4))}`),u.interrupted&&c.push(`[interrupted \u2014 exit code ${u.code}]`);let d;return u.code!==0&&r.interpretExitCode&&(d=r.interpretExitCode(u.code,u.stderr),d&&c.push(`[exit ${u.code}: ${d}]`)),c.length===0&&c.push(n.isSilent&&u.code===0?"Done":`(exit code ${u.code}, no output)`),{content:[{type:"text",text:c.join(`
154
+ `)}],details:{type:"exec",exitCode:u.code,interrupted:u.interrupted,description:t.description,returnCodeInterpretation:d,noOutputExpected:n.isSilent,outputFilePath:u.outputFilePath,classification:n}}}}}import{tmpdir as eh}from"node:os";import{join as th,posix as Jr}from"node:path";function nh(r){return r.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function oh(r){return!(/(?:^|[;&|])\s*<\s/.test(r)||/<<[-]?\s*['"]?[A-Za-z_]/.test(r))}function rh(r,e){return`$'${r.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Cl(r){return process.platform!=="win32"?r:r.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function Kn(r,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:r,detached:!0,async buildExecCommand(n,o){let s=process.platform==="win32",i=eh(),a=s?Cl(i):i,l=o.useSandbox&&o.sandboxTmpDir?Jr.join(o.sandboxTmpDir,`cwd-${o.id}`):Jr.join(a,`qla-${o.id}-cwd`),u=o.useSandbox&&o.sandboxTmpDir?Jr.join(o.sandboxTmpDir,`cwd-${o.id}`):th(i,`qla-${o.id}-cwd`),c=nh(n),d=oh(c),p=rh(c,d),m=[];if(t){let f=s?Cl(t):t;m.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${l}'`),{commandString:m.join(" && "),cwdFilePath:u}},getSpawnArgs(n){return["-c",...!!t?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as sh}from"node:os";import{join as ih,posix as ah}from"node:path";function Al(r){return Buffer.from(r,"utf16le").toString("base64")}function lh(r){return["-NoProfile","-NonInteractive","-Command",r]}function Yr(r){return{type:"powershell",shellPath:r,detached:!1,async buildExecCommand(e,t){let n=t.useSandbox&&t.sandboxTmpDir?ah.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):ih(sh(),`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(`
155
+ ; `),i=e+s;return{commandString:t.useSandbox?[`'${r.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Al(i)].join(" "):i,cwdFilePath:n}},getSpawnArgs(e){return lh(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var ch=[{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"}],uh=[{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 Xr(r){for(let{pattern:e,warning:t}of ch)if(e.test(r))return t;return null}function Qr(r){for(let{pattern:e,warning:t}of uh)if(e.test(r))return t;return null}var dh="read",ph={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 Ml(r){return{name:dh,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:ph,execute:async(n,o)=>{let s=r.resolvePath(o.path);if(r.validatePath){let f=r.validatePath(s);if(f)return{content:[{type:"text",text:`Access denied: ${f}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await r.readFile(s);if(i.type==="image")return{content:[{type:"image",data:i.base64,mimeType:i.mimeType}],details:{type:"read",path:s,isImage:!0}};if(i.type==="binary")return{content:[{type:"text",text:`Cannot read binary file (${i.mimeType}). Use a specific tool for this file type (e.g. pdf tool for PDFs).`}],details:{type:"read",path:s,error:"binary_file",mimeType:i.mimeType}};let a=i.text.split(`
149
156
  `),l=Math.max(0,(o.offset??1)-1),u=Math.min(o.limit??2e3,2e3),c=a.slice(l,l+u),d=c.join(`
150
157
  `);d.length>5e4&&(d=d.slice(0,5e4)+`
151
- ... (truncated)`);let p=a.length,m=l+c.length,g=m<p;return{content:[{type:"text",text:d}],details:{type:"read",path:s,totalLines:p,startLine:l+1,endLine:m,hasMore:g}}}}}var Pf="write",If={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"]},ul=5e5;function dl(r){return{name:Pf,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:If,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>ul)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${ul}). 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(`
152
- `).length;return{content:[{type:"text",text:`Wrote ${o} lines to ${n}`}],details:{type:"write",path:n,lineCount:o}}}}}var Ef="edit",Of={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 pl(r){return{name:Ef,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:Of,execute:async(e,t)=>{let n=r.resolvePath(t.path);if(r.checkConcurrentModification){let c=r.checkConcurrentModification(n);if(c)return{content:[{type:"text",text:`Concurrent modification detected: ${c}. 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 u=o.slice(0,s).split(`
153
- `).length;return{content:[{type:"text",text:`Edited ${n} (line ${u})`}],details:{type:"edit",path:n,success:!0,firstChangedLine:u}}}}}var Lf="search",$f={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"]},ml=100,gl=250,Gr=1e5;function fl(r){return{name:Lf,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:$f,execute:async(e,t)=>{let n=t.path?r.resolvePath?r.resolvePath(t.path):t.path:"",o=t.mode;return o==="filename"?Df(r,t,n):o==="content"?Uf(r,t,n):Nf(r,t,n)}}}async function Df(r,e,t){let n=e.headLimit??ml,{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,l=n===0?a.length:n,u=a.slice(0,l),c=s||a.length>l;if(u.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let d=u.join(`
158
+ ... (truncated)`);let p=a.length,m=l+c.length,g=m<p;return{content:[{type:"text",text:d}],details:{type:"read",path:s,totalLines:p,startLine:l+1,endLine:m,hasMore:g}}}}}var mh="write",gh={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"]},Pl=5e5;function Il(r){return{name:mh,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:gh,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>Pl)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${Pl}). 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(`
159
+ `).length;return{content:[{type:"text",text:`Wrote ${o} lines to ${n}`}],details:{type:"write",path:n,lineCount:o}}}}}var fh="edit",hh={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 El(r){return{name:fh,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:hh,execute:async(e,t)=>{let n=r.resolvePath(t.path);if(r.checkConcurrentModification){let c=r.checkConcurrentModification(n);if(c)return{content:[{type:"text",text:`Concurrent modification detected: ${c}. 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 u=o.slice(0,s).split(`
160
+ `).length;return{content:[{type:"text",text:`Edited ${n} (line ${u})`}],details:{type:"edit",path:n,success:!0,firstChangedLine:u}}}}}var yh="search",bh={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"]},Ol=100,Ll=250,Zr=1e5;function $l(r){return{name:yh,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:bh,execute:async(e,t)=>{let n=t.path?r.resolvePath?r.resolvePath(t.path):t.path:"",o=t.mode;return o==="filename"?kh(r,t,n):o==="content"?Th(r,t,n):wh(r,t,n)}}}async function kh(r,e,t){let n=e.headLimit??Ol,{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,l=n===0?a.length:n,u=a.slice(0,l),c=s||a.length>l;if(u.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let d=u.join(`
154
161
  `);return c&&(d+=`
155
162
 
156
- (Results truncated. ${u.length} shown. Use a more specific pattern or increase headLimit.)`),d=Hr(d,Gr),{content:[{type:"text",text:d}],details:{mode:"filename",totalMatches:u.length,truncated:c}}}async function Uf(r,e,t){let n=e.headLimit??gl,{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 l of o){if(l.contextBefore&&l.contextBefore.length>0)for(let u of l.contextBefore)i.push(` ${u}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let u of l.contextAfter)i.push(` ${u}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
163
+ (Results truncated. ${u.length} shown. Use a more specific pattern or increase headLimit.)`),d=es(d,Zr),{content:[{type:"text",text:d}],details:{mode:"filename",totalMatches:u.length,truncated:c}}}async function Th(r,e,t){let n=e.headLimit??Ll,{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 l of o){if(l.contextBefore&&l.contextBefore.length>0)for(let u of l.contextBefore)i.push(` ${u}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let u of l.contextAfter)i.push(` ${u}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
157
164
  `);return s&&(a+=`
158
165
 
159
- (Results truncated at ${o.length} matches. Use offset/headLimit for pagination.)`),a=Hr(a,Gr),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:o.length,truncated:s}}}async function Nf(r,e,t){let[n,o]=await Promise.all([e.fileGlob?r.glob(e.fileGlob,{cwd:t,limit:ml}):Promise.resolve({files:[],truncated:!1}),r.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??gl,offset:e.offset})]),s=new Set(o.matches.map(c=>c.path)),i=n.files.filter(c=>!s.has(c)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
166
+ (Results truncated at ${o.length} matches. Use offset/headLimit for pagination.)`),a=es(a,Zr),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:o.length,truncated:s}}}async function wh(r,e,t){let[n,o]=await Promise.all([e.fileGlob?r.glob(e.fileGlob,{cwd:t,limit:Ol}):Promise.resolve({files:[],truncated:!1}),r.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Ll,offset:e.offset})]),s=new Set(o.matches.map(c=>c.path)),i=n.files.filter(c=>!s.has(c)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
160
167
  ${i.join(`
161
168
  `)}`),o.matches.length>0){let c=[];for(let d of o.matches)c.push(`${d.path}:${d.line}: ${d.text}`);a.push(`## Content matches (${o.matches.length}):
162
169
  ${c.join(`
@@ -164,113 +171,113 @@ ${c.join(`
164
171
 
165
172
  `);return l&&(u+=`
166
173
 
167
- (Some results truncated. Use more specific patterns.)`),u=Hr(u,Gr),{content:[{type:"text",text:u}],details:{mode:"both",totalMatches:i.length+o.matches.length,truncated:l}}}function Hr(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
174
+ (Some results truncated. Use more specific patterns.)`),u=es(u,Zr),{content:[{type:"text",text:u}],details:{mode:"both",totalMatches:i.length+o.matches.length,truncated:l}}}function es(r,e){if(r.length<=e)return r;let t=Math.floor(e/2)-50;return`${r.slice(0,t)}
168
175
 
169
176
  ... [truncated ${r.length-e} chars] ...
170
177
 
171
- ${r.slice(-t)}`}var Ff="apply_patch",jf={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function Bf(r){let e=r.split(`
172
- `),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 Wf(r,e){let n=[...r.split(`
178
+ ${r.slice(-t)}`}var vh="apply_patch",xh={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function Sh(r){let e=r.split(`
179
+ `),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 _h(r,e){let n=[...r.split(`
173
180
  `)];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 l=0;l<o.contextBefore.length;l++)if(n[i+l]!==o.contextBefore[l]){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(`
174
- `)}function hl(r){return{name:Ff,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:jf,execute:async(e,t)=>{let n=Bf(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 l=r.resolvePath(a.path);try{switch(a.type){case"add":{let u=a.hunks.flatMap(c=>[...c.additions]).join(`
175
- `);await r.writeFile(l,u),o.added.push(a.path);break}case"update":{let u=await r.readFile(l),c=Wf(u,a.hunks);if(a.moveTo){let d=r.resolvePath(a.moveTo);await r.writeFile(d,c),await r.deleteFile(l),o.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await r.writeFile(l,c),o.modified.push(a.path);break}case"delete":{await r.deleteFile(l),o.deleted.push(a.path);break}}}catch(u){s.push(`${a.type} ${a.path}: ${u instanceof Error?u.message:String(u)}`)}}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(`
176
- `)||"No changes applied."}],details:{type:"apply_patch",summary:o,errors:s}}}}}var Gf="patch",Hf={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
181
+ `)}function Dl(r){return{name:vh,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:xh,execute:async(e,t)=>{let n=Sh(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 l=r.resolvePath(a.path);try{switch(a.type){case"add":{let u=a.hunks.flatMap(c=>[...c.additions]).join(`
182
+ `);await r.writeFile(l,u),o.added.push(a.path);break}case"update":{let u=await r.readFile(l),c=_h(u,a.hunks);if(a.moveTo){let d=r.resolvePath(a.moveTo);await r.writeFile(d,c),await r.deleteFile(l),o.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await r.writeFile(l,c),o.modified.push(a.path);break}case"delete":{await r.deleteFile(l),o.deleted.push(a.path);break}}}catch(u){s.push(`${a.type} ${a.path}: ${u instanceof Error?u.message:String(u)}`)}}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(`
183
+ `)||"No changes applied."}],details:{type:"apply_patch",summary:o,errors:s}}}}}var Rh="patch",Ch={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
177
184
  1) V4A unified diff (*** Begin Patch / *** End Patch markers)
178
185
  2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
179
- 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 zf(r){return r.replace(/\\n/g,`
180
- `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function yl(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 bl(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 Sl(r,e,t){let n=[],o=r.indexOf(e);if(o!==-1){if(t){let f=0;for(;(o=r.indexOf(e,f))!==-1;)n.push({start:o,end:o+e.length,strategy:"exact"}),f=o+e.length}else n.push({start:o,end:o+e.length,strategy:"exact"});return n}let s=e.split(`
186
+ 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 Ah(r){return r.replace(/\\n/g,`
187
+ `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Ul(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 Nl(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 Hl(r,e,t){let n=[],o=r.indexOf(e);if(o!==-1){if(t){let f=0;for(;(o=r.indexOf(e,f))!==-1;)n.push({start:o,end:o+e.length,strategy:"exact"}),f=o+e.length}else n.push({start:o,end:o+e.length,strategy:"exact"});return n}let s=e.split(`
181
188
  `).map(f=>f.trim()),i=r.split(`
182
- `),a=kl(i,s,(f,b)=>f.trim()===b);if(a)return[{...Tl(r,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),u=r.replace(/[ \t]+/g," ");if(o=u.indexOf(l),o!==-1){let f=wl(r,u,o,l.length);if(f)return[{...f,strategy:"whitespace_normalized"}]}let c=kl(i,s,(f,b)=>f.trimStart()===b.trimStart());if(c)return[{...Tl(r,i,c),strategy:"indentation_flexible"}];let d=zf(e);if(d!==e&&(o=r.indexOf(d),o!==-1))return[{start:o,end:o+d.length,strategy:"escape_normalized"}];let p=e.split(`
189
+ `),a=Fl(i,s,(f,b)=>f.trim()===b);if(a)return[{...jl(r,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),u=r.replace(/[ \t]+/g," ");if(o=u.indexOf(l),o!==-1){let f=Bl(r,u,o,l.length);if(f)return[{...f,strategy:"whitespace_normalized"}]}let c=Fl(i,s,(f,b)=>f.trimStart()===b.trimStart());if(c)return[{...jl(r,i,c),strategy:"indentation_flexible"}];let d=Ah(e);if(d!==e&&(o=r.indexOf(d),o!==-1))return[{start:o,end:o+d.length,strategy:"escape_normalized"}];let p=e.split(`
183
190
  `);if(p.length>=3){let f=p.slice(1,-1).join(`
184
- `),b=p[0].trim(),h=p[p.length-1].trim();for(let k=0;k<i.length;k++)if(i[k].trim()===b){let x=i.slice(0,k+1).join(`
185
- `).length+1,R=r.indexOf(f,x);if(R!==-1){let E=R+f.length,F=r.indexOf(`
186
- `,E);if((F===-1?r.slice(E):r.slice(E,F)).trim()===h||F!==-1&&r.slice(E+1,r.indexOf(`
187
- `,E+1)===-1?void 0:r.indexOf(`
188
- `,E+1)).trim()===h){let D=i.slice(0,k).join(`
189
- `).length+(k>0?1:0),w=k,ge=p.length;if(k+ge<=i.length){w=k+ge;let H=i.slice(0,w).join(`
190
- `).length;return[{start:D,end:H,strategy:"trimmed_boundary"}]}}}}}let m=yl(e),g=yl(r);if((m!==e||g!==r)&&(o=g.indexOf(m),o!==-1)){let f=wl(r,g,o,m.length);if(f)return[{...f,strategy:"unicode_normalized"}]}if(p.length>=3){let f=p[0],b=p[p.length-1];for(let h=0;h<i.length;h++)if(i[h]===f){for(let k=h+p.length-1;k<Math.min(h+p.length+2,i.length);k++)if(i[k]===b){let x=k-h+1,R=i.slice(h+1,k),E=p.slice(1,-1),F=E.filter(D=>R.some(w=>bl(w,D)>=.7)).length;if((E.length>0?F/E.length:1)>=.5&&x<=p.length+2){let D=i.slice(0,h).join(`
191
- `).length+(h>0?1:0),w=i.slice(0,k+1).join(`
192
- `).length;return[{start:D,end:w,strategy:"block_anchor"}]}}}}if(p.length>=2)for(let f=0;f<=i.length-p.length;f++){let b=i.slice(f,f+p.length);if(p.map((x,R)=>bl(x,b[R])).filter(x=>x>=.8).length/p.length>=.5){let x=i.slice(0,f).join(`
193
- `).length+(f>0?1:0),R=i.slice(0,f+p.length).join(`
194
- `).length;return[{start:x,end:R,strategy:"context_aware"}]}}return[]}function kl(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 Tl(r,e,t){let n=e.slice(0,t.startIdx).join(`
191
+ `),b=p[0].trim(),T=p[p.length-1].trim();for(let w=0;w<i.length;w++)if(i[w].trim()===b){let _=i.slice(0,w+1).join(`
192
+ `).length+1,y=r.indexOf(f,_);if(y!==-1){let C=y+f.length,E=r.indexOf(`
193
+ `,C);if((E===-1?r.slice(C):r.slice(C,E)).trim()===T||E!==-1&&r.slice(C+1,r.indexOf(`
194
+ `,C+1)===-1?void 0:r.indexOf(`
195
+ `,C+1)).trim()===T){let L=i.slice(0,w).join(`
196
+ `).length+(w>0?1:0),v=w,ce=p.length;if(w+ce<=i.length){v=w+ce;let j=i.slice(0,v).join(`
197
+ `).length;return[{start:L,end:j,strategy:"trimmed_boundary"}]}}}}}let m=Ul(e),g=Ul(r);if((m!==e||g!==r)&&(o=g.indexOf(m),o!==-1)){let f=Bl(r,g,o,m.length);if(f)return[{...f,strategy:"unicode_normalized"}]}if(p.length>=3){let f=p[0],b=p[p.length-1];for(let T=0;T<i.length;T++)if(i[T]===f){for(let w=T+p.length-1;w<Math.min(T+p.length+2,i.length);w++)if(i[w]===b){let _=w-T+1,y=i.slice(T+1,w),C=p.slice(1,-1),E=C.filter(L=>y.some(v=>Nl(v,L)>=.7)).length;if((C.length>0?E/C.length:1)>=.5&&_<=p.length+2){let L=i.slice(0,T).join(`
198
+ `).length+(T>0?1:0),v=i.slice(0,w+1).join(`
199
+ `).length;return[{start:L,end:v,strategy:"block_anchor"}]}}}}if(p.length>=2)for(let f=0;f<=i.length-p.length;f++){let b=i.slice(f,f+p.length);if(p.map((_,y)=>Nl(_,b[y])).filter(_=>_>=.8).length/p.length>=.5){let _=i.slice(0,f).join(`
200
+ `).length+(f>0?1:0),y=i.slice(0,f+p.length).join(`
201
+ `).length;return[{start:_,end:y,strategy:"context_aware"}]}}return[]}function Fl(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 jl(r,e,t){let n=e.slice(0,t.startIdx).join(`
195
202
  `).length+(t.startIdx>0?1:0),o=e.slice(0,t.endIdx).join(`
196
- `).length;return{start:n,end:o}}function wl(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 vl(r){let e=r.split(`
197
- `),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 Vf(r){let e=[],t=r.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let n=t[0].trim().split(`
203
+ `).length;return{start:n,end:o}}function Bl(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 Wl(r){let e=r.split(`
204
+ `),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 Mh(r){let e=[],t=r.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let n=t[0].trim().split(`
198
205
  `).pop()?.trim();if(!n)return[];for(let o=1;o<t.length;o+=2){let s=t[o+1]||"",i=s.indexOf(`
199
206
  ====
200
207
  `);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),l=s.slice(i+6),u=l.indexOf(`
201
- >>>> REPLACE`),c=u===-1?l:l.slice(0,u);e.push({path:n,search:a,replace:c})}return e}function xl(r,e,t){let n=e.lines.filter(g=>g.prefix===" ").map(g=>g.content),o=e.lines.filter(g=>g.prefix==="-").map(g=>g.content),s=e.lines.filter(g=>g.prefix==="+").map(g=>g.content),i=[],a="context";for(let g of e.lines)(g.prefix===" "||g.prefix==="-")&&i.push(g.content);let l=i.join(`
208
+ >>>> REPLACE`),c=u===-1?l:l.slice(0,u);e.push({path:n,search:a,replace:c})}return e}function Gl(r,e,t){let n=e.lines.filter(g=>g.prefix===" ").map(g=>g.content),o=e.lines.filter(g=>g.prefix==="-").map(g=>g.content),s=e.lines.filter(g=>g.prefix==="+").map(g=>g.content),i=[],a="context";for(let g of e.lines)(g.prefix===" "||g.prefix==="-")&&i.push(g.content);let l=i.join(`
202
209
  `);if(!l)return{content:r+`
203
210
  `+s.join(`
204
- `),strategy:"exact"};let u=Sl(r,l,t);if(u.length===0)return null;let c=[];for(let g of e.lines)(g.prefix===" "||g.prefix==="+")&&c.push(g.content);let d=c.join(`
205
- `),p=u[0];return{content:r.slice(0,p.start)+d+r.slice(p.end),strategy:p.strategy}}function zr(r){return{name:Gf,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:Hf,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 u=vl(t.input);if(u.length===0)return{content:[{type:"text",text:"Error: No valid V4A operations found. Ensure *** Begin Patch / *** End Patch markers are present."}],details:{type:"patch",error:"parse_failed"}};for(let c of u){let d=r.resolvePath(c.path);try{switch(c.type){case"add":{let p=c.hunks.flatMap(m=>m.lines.filter(g=>g.prefix==="+").map(g=>g.content)).join(`
206
- `);await r.writeFile(d,p),o.filesAdded.push(c.path),o.strategies[c.path]="exact";break}case"delete":{await r.deleteFile(d),o.filesDeleted.push(c.path);break}case"move":{let p=await r.readFile(d);if(c.newPath){let m=r.resolvePath(c.newPath),g=p;for(let f of c.hunks){let b=xl(g,f,n);b&&(g=b.content,o.strategies[c.path]=b.strategy)}await r.writeFile(m,g),await r.deleteFile(d),o.filesModified.push(`${c.path} \u2192 ${c.newPath}`)}break}case"update":{let p=await r.readFile(d),m="exact",g=!0;for(let f of c.hunks){let b=xl(p,f,n);if(b)p=b.content,m=b.strategy;else{g=!1;let h=f.lines.filter(k=>k.prefix===" "||k.prefix==="-").map(k=>k.content).slice(0,5).join(`
211
+ `),strategy:"exact"};let u=Hl(r,l,t);if(u.length===0)return null;let c=[];for(let g of e.lines)(g.prefix===" "||g.prefix==="+")&&c.push(g.content);let d=c.join(`
212
+ `),p=u[0];return{content:r.slice(0,p.start)+d+r.slice(p.end),strategy:p.strategy}}function ts(r){return{name:Rh,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:Ch,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 u=Wl(t.input);if(u.length===0)return{content:[{type:"text",text:"Error: No valid V4A operations found. Ensure *** Begin Patch / *** End Patch markers are present."}],details:{type:"patch",error:"parse_failed"}};for(let c of u){let d=r.resolvePath(c.path);try{switch(c.type){case"add":{let p=c.hunks.flatMap(m=>m.lines.filter(g=>g.prefix==="+").map(g=>g.content)).join(`
213
+ `);await r.writeFile(d,p),o.filesAdded.push(c.path),o.strategies[c.path]="exact";break}case"delete":{await r.deleteFile(d),o.filesDeleted.push(c.path);break}case"move":{let p=await r.readFile(d);if(c.newPath){let m=r.resolvePath(c.newPath),g=p;for(let f of c.hunks){let b=Gl(g,f,n);b&&(g=b.content,o.strategies[c.path]=b.strategy)}await r.writeFile(m,g),await r.deleteFile(d),o.filesModified.push(`${c.path} \u2192 ${c.newPath}`)}break}case"update":{let p=await r.readFile(d),m="exact",g=!0;for(let f of c.hunks){let b=Gl(p,f,n);if(b)p=b.content,m=b.strategy;else{g=!1;let T=f.lines.filter(w=>w.prefix===" "||w.prefix==="-").map(w=>w.content).slice(0,5).join(`
207
214
  `);o.errors.push(`${c.path}: hunk not matched. Search begins with:
208
- ${h}`)}}(g||p!==await r.readFile(d))&&(await r.writeFile(d,p),o.filesModified.push(c.path),o.strategies[c.path]=m);break}}}catch(p){o.errors.push(`${c.type} ${c.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let u=Vf(t.input);if(u.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let c of u){let d=r.resolvePath(c.path);try{let p=await r.readFile(d),m=Sl(p,c.search,n);if(m.length===0){o.errors.push(`${c.path}: search text not matched (tried all 9 strategies)`);continue}let g=[...m].sort((f,b)=>b.start-f.start);for(let f of g)p=p.slice(0,f.start)+c.replace+p.slice(f.end);await r.writeFile(d,p),o.filesModified.push(c.path),o.strategies[c.path]=m[0].strategy}catch(p){o.errors.push(`${c.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return vl(`*** Begin Patch
215
+ ${T}`)}}(g||p!==await r.readFile(d))&&(await r.writeFile(d,p),o.filesModified.push(c.path),o.strategies[c.path]=m);break}}}catch(p){o.errors.push(`${c.type} ${c.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let u=Mh(t.input);if(u.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let c of u){let d=r.resolvePath(c.path);try{let p=await r.readFile(d),m=Hl(p,c.search,n);if(m.length===0){o.errors.push(`${c.path}: search text not matched (tried all 9 strategies)`);continue}let g=[...m].sort((f,b)=>b.start-f.start);for(let f of g)p=p.slice(0,f.start)+c.replace+p.slice(f.end);await r.writeFile(d,p),o.filesModified.push(c.path),o.strategies[c.path]=m[0].strategy}catch(p){o.errors.push(`${c.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return Wl(`*** Begin Patch
209
216
  `+t.input+`
210
- *** End Patch`).length>0?zr(r).execute(e,{input:`*** Begin Patch
217
+ *** End Patch`).length>0?ts(r).execute(e,{input:`*** Begin Patch
211
218
  `+t.input+`
212
219
  *** 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 u=o.filesModified.map(c=>`${c} (${o.strategies[c]||"exact"})`).join(", ");a.push(`Modified: ${u}`)}o.filesDeleted.length&&a.push(`Deleted: ${o.filesDeleted.join(", ")}`),o.errors.length&&a.push(`
213
220
  Errors:
214
221
  ${o.errors.join(`
215
222
  `)}`);let l=o.errors.length===0;return{content:[{type:"text",text:a.join(`
216
- `)||"No changes applied."}],details:{type:"patch",...o,success:l}}}}}var qf="web_fetch",Kf={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"]},Jf=5e4;function Rl(r){return{name:qf,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:Kf,execute:async(e,t)=>{let n=await r.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??Jf,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}
223
+ `)||"No changes applied."}],details:{type:"patch",...o,success:l}}}}}var Ph="web_fetch",Ih={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"]},Eh=5e4;function Vl(r){return{name:Ph,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:Ih,execute:async(e,t)=>{let n=await r.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??Eh,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}
217
224
 
218
225
  ${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}
219
226
  `),o.push(n.content),n.relevantExcerpts?.length){o.push(`
220
227
  ---
221
228
  ## Relevant Excerpts
222
229
  `);for(let s of n.relevantExcerpts)o.push(`- ${s}`)}return{content:[{type:"text",text:o.join(`
223
- `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!n.extraction,extraction:n.extraction}}}}}var Yf="web_search",Xf={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"]},Qf=10;function _l(r){return{name:Yf,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:Xf,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:Qf});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(`
224
- `)}],details:{type:"web_search",query:n.query,resultCount:n.results.length}}}}}var Zf="instructions",eh={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 Cl(r){return{name:Zf,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:eh,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(`
230
+ `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!n.extraction,extraction:n.extraction}}}}}var Oh="web_search",Lh={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"]},$h=10;function zl(r){return{name:Oh,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:Lh,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:$h});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(`
231
+ `)}],details:{type:"web_search",query:n.query,resultCount:n.results.length}}}}}var Dh="instructions",Uh={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 ql(r){return{name:Dh,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:Uh,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(`
225
232
  `);return{content:[{type:"text",text:`Found ${n.length} instruction file(s):
226
- ${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 th="worktree",nh={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
233
+ ${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 Nh="worktree",Fh={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
227
234
  exit: Leave worktree (keep or remove it).
228
- 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"]},oh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function Al(r){return{name:th,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:nh,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&&!oh.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(`
235
+ 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"]},jh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function Kl(r){return{name:Nh,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:Fh,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&&!jh.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(`
229
236
  `)}],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."}
230
237
  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(`
231
- `)}],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 rh}from"node:child_process";import{promisify as sh}from"node:util";import{join as nt,resolve as Ml,basename as Vr}from"node:path";import{mkdir as $l,rm as Dl,symlink as ih,readdir as BS,stat as ah}from"node:fs/promises";var qt=sh(rh),lh=/^[a-zA-Z0-9._-]+$/,Pl=64;function Ul(r){if(r.length>Pl)throw new Error(`Invalid worktree name: must be ${Pl} 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(!lh.test(e))throw new Error(`Invalid worktree name "${r}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function qr(r){return r.replaceAll("/","+")}function Nl(r){return`worktree-${qr(r)}`}var Te=null;async function ae(r,e){try{let{stdout:t,stderr:n}=await qt("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 Vt(r){let{stdout:e,code:t}=await ae(["rev-parse","--show-toplevel"],r);return t===0?e.trim():null}async function Il(r){let{stdout:e,code:t}=await ae(["status","--porcelain"],r);return t!==0?-1:e.trim().split(`
232
- `).filter(Boolean).length}async function El(r,e){let{stdout:t,code:n}=await ae(["rev-list",`origin/${e}..${e}`,"--count"],r);return n!==0?0:parseInt(t.trim(),10)||0}async function Fl(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=nt(r,o),i=nt(e,o);try{await ih(s,i,"dir"),n?.info(`[worktree] symlinked ${o} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${o} (${l??"unknown"}): ${a}`)}}}async function ch(r,e,t){let{code:n,stderr:o}=await ae(["sparse-checkout","set","--cone","--",...t],r);if(n!==0)throw await ae(["worktree","remove","--force",r],e),new Error(`Failed to configure sparse-checkout: ${o}`);let{code:s,stderr:i}=await ae(["checkout","HEAD"],r);if(s!==0)throw await ae(["worktree","remove","--force",r],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function uh(){try{return await qt("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function dh(r,e){return`${Vr(r)}_${e}`.replace(/[/.]/g,"_")}async function ph(r,e){if(!await uh())return null;try{return await qt("tmux",["new-session","-d","-s",e,"-c",r],{timeout:1e4}),e}catch{return null}}async function Ol(r){try{return await qt("tmux",["kill-session","-t",r],{timeout:5e3}),!0}catch{return!1}}async function Ll(r,e,t,n){let o=Ki(e),s=nt(o,r);try{if(!(await ah(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await qt(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 jl(r,e,t){Ul(e);let n=qr(e),o=Nl(e),s=nt(r,".worktrees"),i=nt(s,n);await $l(s,{recursive:!0});let{code:a,stderr:l}=await ae(["worktree","add","-B",o,i,"HEAD"],r);return a!==0?(t?.warn(`[worktree] agent worktree creation failed: ${l}`),null):(await Fl(r,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:o})}async function Bl(r,e,t,n){let{code:o}=await ae(["worktree","remove","--force",e],r);return o!==0&&(await Dl(e,{recursive:!0,force:!0}).catch(()=>{}),await ae(["worktree","prune"],r)),await ae(["branch","-D",t],r),n?.info(`[worktree] agent worktree removed: ${e}`),!0}function Wl(r){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:n}=r;return{async enterWorktree(o){try{let s=Date.now(),i=await Vt();if(!i)return{success:!1,error:"Not in a git repository"};let a=await Ll("worktree-create",i,{WORKTREE_NAME:o??""},e);if(a){let U=process.cwd();return process.chdir(a),Te={originalCwd:U,worktreePath:a,worktreeName:o??Vr(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:Te.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=o??`agent-${Date.now().toString(36)}`;Ul(l);let u=qr(l),c=Nl(l),d=nt(i,".worktrees"),p=nt(d,u);await $l(d,{recursive:!0});let{stdout:m}=await ae(["worktree","list","--porcelain"],i),g=m.split(`
233
- `).find(U=>U.startsWith("worktree ")&&U.includes(u));if(g){let U=g.replace("worktree ","").trim(),D=process.cwd();return process.chdir(U),Te={originalCwd:D,worktreePath:U,worktreeName:l,worktreeBranch:c},e.info(`[worktree] resumed existing worktree: ${l} at ${U}`),{success:!0,worktree:{name:l,path:U,branch:c,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=n&&n.length>0,b=["worktree","add"];f&&b.push("--no-checkout"),b.push("-B",c,p,"HEAD");let{code:h,stderr:k}=await ae(b,i);if(h!==0)return{success:!1,error:`git worktree add failed: ${k.trim()}`};let x=!1;f&&n&&(await ch(p,i,n),x=!0),await Fl(i,p,t,e);let R=process.cwd();process.chdir(p);let E=dh(i,c),F=await ph(p,E);return Te={originalCwd:R,worktreePath:p,worktreeName:l,worktreeBranch:c,tmuxSessionName:F??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:x},e.info(`[worktree] entered: ${l} at ${p}`),{success:!0,worktree:{name:l,path:p,branch:c,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(o,s){if(!Te)return{success:!1,error:"Not in a worktree"};try{let i=Te,a=await Vt(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(o==="remove"){let l=await Il(i.worktreePath),u=await El(i.worktreePath,i.worktreeBranch);if((l>0||u>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${u} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),Te=null,i.tmuxSessionName&&await Ol(i.tmuxSessionName),await Ll("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let c=["worktree","remove"];s&&c.push("--force"),c.push(i.worktreePath);let{code:d,stderr:p}=await ae(c,a);d!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await Dl(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await ae(["worktree","prune"],a)),await ae(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await Ol(i.tmuxSessionName),Te=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 ae(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=o.split(`
238
+ `)}],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 Bh}from"node:child_process";import{promisify as Wh}from"node:util";import{join as nt,resolve as Jl,basename as ns}from"node:path";import{mkdir as tc,rm as nc,symlink as Gh,readdir as O_,stat as Hh}from"node:fs/promises";var Yt=Wh(Bh),Vh=/^[a-zA-Z0-9._-]+$/,Yl=64;function oc(r){if(r.length>Yl)throw new Error(`Invalid worktree name: must be ${Yl} 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(!Vh.test(e))throw new Error(`Invalid worktree name "${r}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function os(r){return r.replaceAll("/","+")}function rc(r){return`worktree-${os(r)}`}var ve=null;async function le(r,e){try{let{stdout:t,stderr:n}=await Yt("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 Jt(r){let{stdout:e,code:t}=await le(["rev-parse","--show-toplevel"],r);return t===0?e.trim():null}async function Xl(r){let{stdout:e,code:t}=await le(["status","--porcelain"],r);return t!==0?-1:e.trim().split(`
239
+ `).filter(Boolean).length}async function Ql(r,e){let{stdout:t,code:n}=await le(["rev-list",`origin/${e}..${e}`,"--count"],r);return n!==0?0:parseInt(t.trim(),10)||0}async function sc(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=nt(r,o),i=nt(e,o);try{await Gh(s,i,"dir"),n?.info(`[worktree] symlinked ${o} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${o} (${l??"unknown"}): ${a}`)}}}async function zh(r,e,t){let{code:n,stderr:o}=await le(["sparse-checkout","set","--cone","--",...t],r);if(n!==0)throw await le(["worktree","remove","--force",r],e),new Error(`Failed to configure sparse-checkout: ${o}`);let{code:s,stderr:i}=await le(["checkout","HEAD"],r);if(s!==0)throw await le(["worktree","remove","--force",r],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function qh(){try{return await Yt("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function Kh(r,e){return`${ns(r)}_${e}`.replace(/[/.]/g,"_")}async function Jh(r,e){if(!await qh())return null;try{return await Yt("tmux",["new-session","-d","-s",e,"-c",r],{timeout:1e4}),e}catch{return null}}async function Zl(r){try{return await Yt("tmux",["kill-session","-t",r],{timeout:5e3}),!0}catch{return!1}}async function ec(r,e,t,n){let o=sa(e),s=nt(o,r);try{if(!(await Hh(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await Yt(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 ic(r,e,t){oc(e);let n=os(e),o=rc(e),s=nt(r,".worktrees"),i=nt(s,n);await tc(s,{recursive:!0});let{code:a,stderr:l}=await le(["worktree","add","-B",o,i,"HEAD"],r);return a!==0?(t?.warn(`[worktree] agent worktree creation failed: ${l}`),null):(await sc(r,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:o})}async function ac(r,e,t,n){let{code:o}=await le(["worktree","remove","--force",e],r);return o!==0&&(await nc(e,{recursive:!0,force:!0}).catch(()=>{}),await le(["worktree","prune"],r)),await le(["branch","-D",t],r),n?.info(`[worktree] agent worktree removed: ${e}`),!0}function lc(r){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:n}=r;return{async enterWorktree(o){try{let s=Date.now(),i=await Jt();if(!i)return{success:!1,error:"Not in a git repository"};let a=await ec("worktree-create",i,{WORKTREE_NAME:o??""},e);if(a){let D=process.cwd();return process.chdir(a),ve={originalCwd:D,worktreePath:a,worktreeName:o??ns(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:ve.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=o??`agent-${Date.now().toString(36)}`;oc(l);let u=os(l),c=rc(l),d=nt(i,".worktrees"),p=nt(d,u);await tc(d,{recursive:!0});let{stdout:m}=await le(["worktree","list","--porcelain"],i),g=m.split(`
240
+ `).find(D=>D.startsWith("worktree ")&&D.includes(u));if(g){let D=g.replace("worktree ","").trim(),L=process.cwd();return process.chdir(D),ve={originalCwd:L,worktreePath:D,worktreeName:l,worktreeBranch:c},e.info(`[worktree] resumed existing worktree: ${l} at ${D}`),{success:!0,worktree:{name:l,path:D,branch:c,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=n&&n.length>0,b=["worktree","add"];f&&b.push("--no-checkout"),b.push("-B",c,p,"HEAD");let{code:T,stderr:w}=await le(b,i);if(T!==0)return{success:!1,error:`git worktree add failed: ${w.trim()}`};let _=!1;f&&n&&(await zh(p,i,n),_=!0),await sc(i,p,t,e);let y=process.cwd();process.chdir(p);let C=Kh(i,c),E=await Jh(p,C);return ve={originalCwd:y,worktreePath:p,worktreeName:l,worktreeBranch:c,tmuxSessionName:E??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:_},e.info(`[worktree] entered: ${l} at ${p}`),{success:!0,worktree:{name:l,path:p,branch:c,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(o,s){if(!ve)return{success:!1,error:"Not in a worktree"};try{let i=ve,a=await Jt(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(o==="remove"){let l=await Xl(i.worktreePath),u=await Ql(i.worktreePath,i.worktreeBranch);if((l>0||u>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${u} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),ve=null,i.tmuxSessionName&&await Zl(i.tmuxSessionName),await ec("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let c=["worktree","remove"];s&&c.push("--force"),c.push(i.worktreePath);let{code:d,stderr:p}=await le(c,a);d!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await nc(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await le(["worktree","prune"],a)),await le(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await Zl(i.tmuxSessionName),ve=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 le(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=o.split(`
234
241
 
235
242
  `).filter(Boolean);for(let u of l){let c=u.split(`
236
- `),d="",p="";for(let b of c)b.startsWith("worktree ")&&(d=b.slice(9).trim()),b.startsWith("branch ")&&(p=b.slice(7).trim().replace("refs/heads/",""));if(!d)continue;let m=Ml(d)===Ml(a),g=await Il(d),f=await El(d,p);i.push({name:p.startsWith("worktree-")?p.slice(9):Vr(d),path:d,branch:p,isCurrent:m,hasChanges:g>0,unpushedCommits:f})}return{success:!0,worktrees:i}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}},isInWorktree(){return Te!==null},currentWorktree(){return Te?{name:Te.worktreeName,path:Te.worktreePath,branch:Te.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as mh,writeFile as gh}from"node:fs/promises";import*as Gl from"node:path";var fh={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 Hl(r){let e=r.split(`
243
+ `),d="",p="";for(let b of c)b.startsWith("worktree ")&&(d=b.slice(9).trim()),b.startsWith("branch ")&&(p=b.slice(7).trim().replace("refs/heads/",""));if(!d)continue;let m=Jl(d)===Jl(a),g=await Xl(d),f=await Ql(d,p);i.push({name:p.startsWith("worktree-")?p.slice(9):ns(d),path:d,branch:p,isCurrent:m,hasChanges:g>0,unpushedCommits:f})}return{success:!0,worktrees:i}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}},isInWorktree(){return ve!==null},currentWorktree(){return ve?{name:ve.worktreeName,path:ve.worktreePath,branch:ve.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as Yh,writeFile as Xh}from"node:fs/promises";import*as cc from"node:path";var Qh={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 uc(r){let e=r.split(`
237
244
  `);return e.map((t,n)=>n<e.length-1?t+`
238
- `:t)}function zl(r){return r.join("")}function hh(r,e){let t=zl(r.source).trim(),n=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${r.cell_type}]: ${n}`}function yh(r,e){let t={cell_type:r,source:Hl(e),metadata:{}};return r==="code"&&(t.execution_count=null,t.outputs=[]),t}function Vl(){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:fh,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=Gl.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 mh(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let l=a.cells.length,u=n-1;if(o==="insert"){if(n<0||n>l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(u<0||u>=l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let c;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[u],g=zl(m.source);m.source=Hl(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),c=`Replaced cell ${n} [${m.cell_type}].
245
+ `:t)}function dc(r){return r.join("")}function Zh(r,e){let t=dc(r.source).trim(),n=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${r.cell_type}]: ${n}`}function ey(r,e){let t={cell_type:r,source:uc(e),metadata:{}};return r==="code"&&(t.execution_count=null,t.outputs=[]),t}function pc(){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:Qh,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=cc.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 Yh(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let l=a.cells.length,u=n-1;if(o==="insert"){if(n<0||n>l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(u<0||u>=l)return{content:[{type:"text",text:`Error: cell_number ${n} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let c;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[u],g=dc(m.source);m.source=uc(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),c=`Replaced cell ${n} [${m.cell_type}].
239
246
  Old: ${g.slice(0,120)}${g.length>120?"...":""}
240
- 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",g=yh(m,e.new_source);a.cells.splice(n,0,g),c=`Inserted new ${m} cell after position ${n}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(u,1)[0];c=`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)+`
241
- `;await gh(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let d=a.cells.slice(0,10).map((m,g)=>hh(m,g)).join(`
247
+ 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",g=ey(m,e.new_source);a.cells.splice(n,0,g),c=`Inserted new ${m} cell after position ${n}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(u,1)[0];c=`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)+`
248
+ `;await Xh(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let d=a.cells.slice(0,10).map((m,g)=>Zh(m,g)).join(`
242
249
  `),p=a.cells.length>10?`
243
250
  ... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${c}
244
251
 
245
252
  Current cells:
246
- ${d}${p}`}],details:{type:"notebook_edit",edit_mode:o,cell_number:n,total_cells:a.cells.length}}}}}import{readFile as bh,readdir as kh}from"node:fs/promises";import*as Kl from"node:path";import{existsSync as Th}from"node:fs";var wh={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
253
+ ${d}${p}`}],details:{type:"notebook_edit",edit_mode:o,cell_number:n,total_cells:a.cells.length}}}}}import{readFile as ty,readdir as ny}from"node:fs/promises";import*as gc from"node:path";import{existsSync as oy}from"node:fs";var ry={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
247
254
  run: Execute a workflow by name.
248
- 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 Kr(r){let e=new Map,t=Hi(r);await ql(t,e);let n=Wi();return await ql(n,e),e}async function ql(r,e){if(Th(r))try{let t=await kh(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,Kl.join(r,n.name))}}catch{}}async function Jr(r){let e=await bh(r,"utf-8");return JSON.parse(e)}function vh(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 l of a.dependsOn??[])o(l,i);i.delete(s),t.add(s),n.push(a)}for(let s of r)o(s.id,new Set);return n}function xh(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,l)=>e[l]??`\${var.${l}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,l)=>t.get(l)?.output??""),n[o]=i}else n[o]=s;return n}function Jl(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:wh,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 Kr(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,l]of s)try{let u=await Jr(l);i.push(` - ${a}: ${u.description??"(no description)"} (${u.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
249
- `)}],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 Kr(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Jr(i),l=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let u of a.steps){let c=u.dependsOn?.length?` (after: ${u.dependsOn.join(", ")})`:"";l.push(` ${u.id}: ${u.label??u.tool}${c}`),l.push(` tool: ${u.tool}`),l.push(` args: ${JSON.stringify(u.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){l.push("","Variables (defaults):");for(let[u,c]of Object.entries(a.variables))l.push(` ${u} = ${c}`)}return{content:[{type:"text",text:l.filter(Boolean).join(`
250
- `)}],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 Kr(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await Jr(i),l={...a.variables,...t.variables},u;try{u=vh(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let c=new Map,d=[`Running workflow: ${a.name}`,""],p=!0;for(let m of u){if(n?.aborted){d.push(`\u26A1 Aborted at step: ${m.id}`),p=!1;break}let g=(m.dependsOn??[]).some(h=>!c.get(h)?.success),f=m.condition??"on_success";if(f==="on_success"&&g){d.push(`\u23ED Skipped ${m.id} (dependency failed)`),c.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(f==="on_failure"&&!g){d.push(`\u23ED Skipped ${m.id} (no failure to handle)`),c.set(m.id,{stepId:m.id,success:!0,output:""});continue}d.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let b=xh(m.args,l,c);try{let h=await r.invokeTool(m.tool,b,n),k=!h.error;if(c.set(m.id,{stepId:m.id,success:k,output:h.result,error:h.error}),k){let x=h.result.length>200?h.result.slice(0,200)+"...":h.result;d.push(` \u2705 ${x}`)}else d.push(` \u274C ${h.error}`),p=!1}catch(h){let k=h.message;c.set(m.id,{stepId:m.id,success:!1,output:"",error:k}),d.push(` \u274C ${k}`),p=!1}}return d.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:d.join(`
251
- `)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:c.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 Sh="sleep",Rh={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 Yl(r){return{name:Sh,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(`
252
- `),parameters:Rh,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 l=await r.sleep(s,i.signal),u=[];return l.interrupted?(u.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&u.push(`Reason: ${l.interruptReason}`),u.push("Check for new messages or tasks.")):u.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:u.join(`
253
- `)}],details:{...l,requestedSeconds:o}}}finally{n?.removeEventListener("abort",a)}}}}var _h="tool_search",Ch={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"]},Ah=5;function Ql(r){return{name:_h,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:Ch,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??Ah;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(c=>c.trim()).filter(Boolean),a=[],l=[];if(r.activateTool)for(let c of i)await r.activateTool(c)?a.push(c):l.push(c);else{let c=await r.searchTools(n,{maxResults:o});return Xl(c)}let u=[];return a.length>0&&u.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&u.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:u.join(`
254
- `)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await r.searchTools(n,{maxResults:o});return Xl(s)}}}function Xl(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(`
255
- `)}],details:{type:"tool_search",query:r.query,matchCount:r.matches.length,totalDeferred:r.totalDeferred,matches:r.matches.map(t=>t.name)}}}var Yr="image_generate",Mh={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 Zl(r){return{name:Yr,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:Mh,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 Ph={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 ec(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:Ph,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 Xr="video_generate",Ih={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 tc(r){return{name:Xr,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:Ih,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 Qr="music_generate",Eh={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 nc(r){return{name:Qr,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:Eh,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 Oh="video_edit",Lh={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 oc(r){return{name:Oh,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:Lh,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 $h="video_merge",Dh={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 rc(r){return{name:$h,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:Dh,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 Uh="video_upscale",Nh={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 sc(r){return{name:Uh,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:Nh,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 Fh="three_d_generate",jh={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 ic(r){return{name:Fh,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:jh,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;return{content:[{type:"text",text:`Generated ${o} 3D model${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"three_d_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var Bh={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 ac(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:Bh,execute:async(e,t)=>{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 Wh="voice_clone",Gh={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 lc(r){return{name:Wh,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:Gh,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 Hh="file_upload",zh={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 cc(r){return{name:Hh,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:zh,execute:async(e,t)=>{let n=await r.uploadFile({filePath:t.file_path,purpose:t.purpose}),o=[`Uploaded "${n.filename}" (${Zr(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(`
256
- `)}],details:{type:"file_upload",fileId:n.fileId,url:n.url,filename:n.filename,bytes:n.bytes,provider:n.provider}}}}}var Vh="file_query",qh={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 uc(r){return{name:Vh,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:qh,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: ${Zr(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(`
255
+ 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 rs(r){let e=new Map,t=ta(r);await mc(t,e);let n=Zi();return await mc(n,e),e}async function mc(r,e){if(oy(r))try{let t=await ny(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,gc.join(r,n.name))}}catch{}}async function ss(r){let e=await ty(r,"utf-8");return JSON.parse(e)}function sy(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 l of a.dependsOn??[])o(l,i);i.delete(s),t.add(s),n.push(a)}for(let s of r)o(s.id,new Set);return n}function iy(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,l)=>e[l]??`\${var.${l}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,l)=>t.get(l)?.output??""),n[o]=i}else n[o]=s;return n}function fc(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:ry,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 rs(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,l]of s)try{let u=await ss(l);i.push(` - ${a}: ${u.description??"(no description)"} (${u.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
256
+ `)}],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 rs(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await ss(i),l=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let u of a.steps){let c=u.dependsOn?.length?` (after: ${u.dependsOn.join(", ")})`:"";l.push(` ${u.id}: ${u.label??u.tool}${c}`),l.push(` tool: ${u.tool}`),l.push(` args: ${JSON.stringify(u.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){l.push("","Variables (defaults):");for(let[u,c]of Object.entries(a.variables))l.push(` ${u} = ${c}`)}return{content:[{type:"text",text:l.filter(Boolean).join(`
257
+ `)}],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 rs(o)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await ss(i),l={...a.variables,...t.variables},u;try{u=sy(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let c=new Map,d=[`Running workflow: ${a.name}`,""],p=!0;for(let m of u){if(n?.aborted){d.push(`\u26A1 Aborted at step: ${m.id}`),p=!1;break}let g=(m.dependsOn??[]).some(T=>!c.get(T)?.success),f=m.condition??"on_success";if(f==="on_success"&&g){d.push(`\u23ED Skipped ${m.id} (dependency failed)`),c.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(f==="on_failure"&&!g){d.push(`\u23ED Skipped ${m.id} (no failure to handle)`),c.set(m.id,{stepId:m.id,success:!0,output:""});continue}d.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let b=iy(m.args,l,c);try{let T=await r.invokeTool(m.tool,b,n),w=!T.error;if(c.set(m.id,{stepId:m.id,success:w,output:T.result,error:T.error}),w){let _=T.result.length>200?T.result.slice(0,200)+"...":T.result;d.push(` \u2705 ${_}`)}else d.push(` \u274C ${T.error}`),p=!1}catch(T){let w=T.message;c.set(m.id,{stepId:m.id,success:!1,output:"",error:w}),d.push(` \u274C ${w}`),p=!1}}return d.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:d.join(`
258
+ `)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:c.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 ay="sleep",ly={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 hc(r){return{name:ay,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(`
259
+ `),parameters:ly,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 l=await r.sleep(s,i.signal),u=[];return l.interrupted?(u.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&u.push(`Reason: ${l.interruptReason}`),u.push("Check for new messages or tasks.")):u.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:u.join(`
260
+ `)}],details:{...l,requestedSeconds:o}}}finally{n?.removeEventListener("abort",a)}}}}var cy="tool_search",uy={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"]},dy=5;function bc(r){return{name:cy,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:uy,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??dy;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(c=>c.trim()).filter(Boolean),a=[],l=[];if(r.activateTool)for(let c of i)await r.activateTool(c)?a.push(c):l.push(c);else{let c=await r.searchTools(n,{maxResults:o});return yc(c)}let u=[];return a.length>0&&u.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&u.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:u.join(`
261
+ `)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await r.searchTools(n,{maxResults:o});return yc(s)}}}function yc(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(`
262
+ `)}],details:{type:"tool_search",query:r.query,matchCount:r.matches.length,totalDeferred:r.totalDeferred,matches:r.matches.map(t=>t.name)}}}var is="image_generate",py={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 kc(r){return{name:is,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:py,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 my={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 Tc(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:my,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 as="video_generate",gy={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 wc(r){return{name:as,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:gy,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 ls="music_generate",fy={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 vc(r){return{name:ls,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:fy,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 hy="video_edit",yy={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 xc(r){return{name:hy,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:yy,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 by="video_merge",ky={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 Sc(r){return{name:by,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:ky,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 Ty="video_upscale",wy={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 _c(r){return{name:Ty,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:wy,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 vy="three_d_generate",xy={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 Rc(r){return{name:vy,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:xy,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 Sy={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 Cc(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:Sy,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 _y="voice_clone",Ry={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 Ac(r){return{name:_y,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:Ry,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 Cy="media_cancel",Ay={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 Mc(r){return{name:Cy,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:Ay,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 My="file_upload",Py={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 Pc(r){return{name:My,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:Py,execute:async(e,t)=>{let n=await r.uploadFile({filePath:t.file_path,purpose:t.purpose}),o=[`Uploaded "${n.filename}" (${cs(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(`
263
+ `)}],details:{type:"file_upload",fileId:n.fileId,url:n.url,filename:n.filename,bytes:n.bytes,provider:n.provider}}}}}var Iy="file_query",Ey={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 Ic(r){return{name:Iy,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:Ey,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: ${cs(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(`
257
264
  `)}],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):
258
- `];for(let i of o)s.push(`- ${i.filename} | ID: ${i.id} | ${Zr(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
259
- `)}],details:{type:"file_query",count:o.length}}}}}var Kh="file_delete",Jh={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function dc(r){return{name:Kh,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:Jh,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 Zr(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}var Yh="ask_user",Xh={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 pc(r){return{name:Yh,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:Xh,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(l=>l.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(`
260
- `)}],details:{type:"ask_user",answers:o,questionCount:t.questions.length}}}}}function mc(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 ee,ue={},hc,ns,ze={},yc;function bc(r){yc=r}var kc=null;function Tc(r){kc=r}function wc(r,e,t,n,o){ee=r,ue=e??{},hc=t,ns=o,ze=n??{},ey()}function os(r){let e=ze[r];if(!(!e||!ee))return ee.resolveModelById(e.provider,e.model,r)}function ey(){ty(),ny(),oy(),ry()}function ty(){let r=ke(Xr);if(!r)return;let e=ze.video;if(!e||!ee)return;let t=ee.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 l=r.parameters?.properties,u=l?.duration;u&&(u.minimum=s,u.maximum=o,u.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 c=l?.resolution;c&&n.resolutions&&(c.description=`Output resolution: ${i}. Default: '720p'.`)}function ny(){let r=ke(Yr);if(!r)return;let e=os("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 oy(){let r=ke("tts");if(!r)return;let e=os("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 ry(){let r=ke(Qr);if(!r)return;let e=os("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 Pe(r){if(!ee)throw new Error(`No media provider configured for ${r.mediaType}`);let e=ze[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};ns&&!o.onProgress&&(o.onProgress=(l,u,c)=>{ns(c??"pending",r.mediaType,l,u,t)});let s=await gc(t,n||r.model,o);if(s.ok)return s.result;let i=ee.listMediaModels(r.mediaType),a=[`${t}: ${s.error}`];for(let l of i){if(l.providerId===t||!ue[l.providerId])continue;let c=await gc(l.providerId,l.modelInfo.id,r);if(c.ok)return c.result;a.push(`${l.providerId}/${l.modelInfo.id}: ${c.error}`)}throw new Error(`All media providers failed for ${r.mediaType}:
265
+ `];for(let i of o)s.push(`- ${i.filename} | ID: ${i.id} | ${cs(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
266
+ `)}],details:{type:"file_query",count:o.length}}}}}var Oy="file_delete",Ly={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function Ec(r){return{name:Oy,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:Ly,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 cs(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}var $y="ask_user",Dy={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 Oc(r){return{name:$y,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:Dy,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(l=>l.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(`
267
+ `)}],details:{type:"ask_user",answers:o,questionCount:t.questions.length}}}}}function Lc(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 ee,de={},Uc,ps,He={},Nc;function Fc(r){Nc=r}var jc=null;function Bc(r){jc=r}function Wc(r,e,t,n,o){ee=r,de=e??{},Uc=t,ps=o,He=n??{},Fy()}function ms(r){let e=He[r];if(!(!e||!ee))return ee.resolveModelById(e.provider,e.model,r)}function Fy(){jy(),By(),Wy(),Gy()}function jy(){let r=we(as);if(!r)return;let e=He.video;if(!e||!ee)return;let t=ee.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 l=r.parameters?.properties,u=l?.duration;u&&(u.minimum=s,u.maximum=o,u.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 c=l?.resolution;c&&n.resolutions&&(c.description=`Output resolution: ${i}. Default: '720p'.`)}function By(){let r=we(is);if(!r)return;let e=ms("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 Wy(){let r=we("tts");if(!r)return;let e=ms("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 Gy(){let r=we(ls);if(!r)return;let e=ms("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 Ie(r){if(!ee)throw new Error(`No media provider configured for ${r.mediaType}`);let e=He[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};ps&&!o.onProgress&&(o.onProgress=(l,u,c)=>{ps(c??"pending",r.mediaType,l,u,t)});let s=await $c(t,n||r.model,o);if(s.ok)return s.result;let i=ee.listMediaModels(r.mediaType),a=[`${t}: ${s.error}`];for(let l of i){if(l.providerId===t||!de[l.providerId])continue;let c=await $c(l.providerId,l.modelInfo.id,r);if(c.ok)return c.result;a.push(`${l.providerId}/${l.modelInfo.id}: ${c.error}`)}throw new Error(`All media providers failed for ${r.mediaType}:
261
268
  `+a.map(l=>` - ${l}`).join(`
262
- `))}async function gc(r,e,t){let n=ee.getTransport(r);if(!n)return{ok:!1,error:"transport not available"};let o=ue[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,l=i.billingUnit??"per_call",u=i.billingQuantity??1;return hc?.(a,l,u),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function He(r){if(!ee)return!1;let e=ze[r];if(!e)return!1;let t=ee.getTransport(e.provider),n=ue[e.provider];return!!(t&&n)}function es(r,e){if(!He(r))return!1;let t=ze[r],n=ee.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 Hn(){if(!ee)return;for(let[,e]of Object.entries(ze)){if(!e)continue;let t=ee.getTransport(e.provider),n=ue[e.provider];if(t instanceof xe&&n)return{id:e.provider,type:"volcengine"}}if(ue.google)return{id:"google",type:"gemini"}}var ts;function zn(){return ts||(ts=new Ft({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),ts}var ot=process.cwd();function de(r){return W.isAbsolute(r)?W.normalize(r):W.resolve(ot,r)}var sy=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),vc=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),iy={".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 ay(){return{resolvePath:de,async readFile(r){let e=de(r),t=W.extname(e).toLowerCase();if(vc.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(sy.has(t)){let o=await L.promises.readFile(e),s=t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg";return{type:"image",base64:o.toString("base64"),mimeType:s}}return{type:"text",text:await L.promises.readFile(e,"utf8")}},validatePath(r){let e=de(r);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function ly(){return{resolvePath:de,async writeFile(r,e){let t=de(r);await L.promises.mkdir(W.dirname(t),{recursive:!0}),await L.promises.writeFile(t,e,"utf8")}}}function cy(){return{resolvePath:de,async readFile(r){let e=de(r);return L.promises.readFile(e,"utf8")},async writeFile(r,e){let t=de(r);await L.promises.mkdir(W.dirname(t),{recursive:!0}),await L.promises.writeFile(t,e,"utf8")}}}function uy(){return{resolvePath:de,async readFile(r){let e=de(r);return L.promises.readFile(e,"utf8")},async writeFile(r,e){let t=de(r);await L.promises.mkdir(W.dirname(t),{recursive:!0}),await L.promises.writeFile(t,e,"utf8")},async deleteFile(r){let e=de(r);await L.promises.unlink(e)},async fileExists(r){let e=de(r);try{return await L.promises.access(e),!0}catch{return!1}}}}function dy(){return{resolvePath:de,async glob(r,e){let t=e.cwd||ot,n=e.limit||1e3,o=[],s=!1,i=r.replace(/\\/g,"/").split("/"),a=i.some(c=>c==="**"),l=i[i.length-1]??"*",u=xc(l);try{await rs(t,async c=>{if(o.length>=n)return s=!0,!1;let d=W.basename(c);return u.test(d)&&o.push(c),!0},a?1/0:1)}catch{}return{files:o,truncated:s}},async grep(r,e){let t=e.cwd||ot;try{return await my(r,t,e)}catch{return await gy(r,t,e)}}}}function xc(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 py=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function rs(r,e,t,n=0,o=""){if(n>t)return;let s;try{s=await L.promises.readdir(r,{withFileTypes:!0})}catch{return}for(let i of s){let a=o?`${o}/${i.name}`:i.name;if(i.isDirectory()){if(py.has(i.name))continue;await rs(W.join(r,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function my(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("."),Zh("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 l=[];for(let p of a.split(`
263
- `))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&l.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let u=t.headLimit??250,c=t.offset??0,d=l.slice(c,c+u);n({matches:d,truncated:l.length>c+u})})})}async function gy(r,e,t){let n=new RegExp(r,t.caseInsensitive?"i":""),o=t.headLimit??250,s=t.offset??0,i=t.fileGlob?xc(t.fileGlob):null,a=[],l=!1;return await rs(e,async u=>{if(a.length>=s+o+1)return l=!0,!1;if(i&&!i.test(W.basename(u)))return!0;let c=W.extname(u).toLowerCase();if(vc.has(c))return!0;try{let p=(await L.promises.readFile(W.join(e,u),"utf8")).split(`
264
- `);for(let m=0;m<p.length;m++)if(n.test(p[m])&&(a.push({path:u,line:m+1,text:p[m].slice(0,500)}),a.length>=s+o+1))return l=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+o),truncated:l}}var fc=!1;function fy(){if(!fc)if(fc=!0,Ln()){let r=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";zt(jr(r))}else if(process.platform==="win32"){let r=hy();zt(Gn(r))}else{let r=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";zt(Gn(r))}}function hy(){let r=process.env.QLOGICAGENT_BASH_PATH;if(r&&L.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?W.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let n of e)if(L.existsSync(n))return n;return"bash"}function yy(){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=by(s)),{content:s,title:ky(s)}}finally{clearTimeout(t)}}}}function by(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 ky(r){return r.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function Ty(){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 l=await fetch(s.toString(),{signal:i.signal,headers:{Accept:"application/json"}});if(!l.ok)return{query:e,results:[]};let u=await l.json(),c=(u.results??[]).slice(0,o).map(d=>({title:d.title??"",url:d.url??"",snippet:d.content??""}));if(t?.allowedDomains?.length){let d=new Set(t.allowedDomains.map(p=>p.toLowerCase()));return{query:e,results:c.filter(p=>{try{return d.has(new URL(p.url).hostname.toLowerCase())}catch{return!1}})}}if(t?.blockedDomains?.length){let d=new Set(t.blockedDomains.map(p=>p.toLowerCase()));return{query:e,results:c.filter(p=>{try{return!d.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:c,totalResults:u.number_of_results}}finally{clearTimeout(a)}};return{search:(e,t)=>mc(yc,r)(e,t)}}function wy(){let r=W.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(o){return W.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=W.resolve(i,s);if(!a.startsWith(i+W.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(o,s){if(!L.existsSync(o))return[];let i=[];for(let a of L.readdirSync(o,{withFileTypes:!0})){let l=W.join(o,a.name);if(a.isDirectory())i.push(...n(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let u=L.statSync(l);i.push({filename:W.relative(s,l).replace(/\\/g,"/"),path:l,size:u.size,updatedAt:u.mtime.toISOString(),content:L.readFileSync(l,"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(!L.existsSync(i))return null;let a=L.statSync(i),l=L.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:l}}catch{return null}},write(o,s,i){let a=t(o,s);L.mkdirSync(W.dirname(a),{recursive:!0}),L.writeFileSync(a,i,"utf-8");let l=L.statSync(a);return{filename:s,path:a,size:l.size,updatedAt:l.mtime.toISOString(),content:i}},remove(o,s){try{let i=t(o,s);return L.existsSync(i)?(L.unlinkSync(i),!0):!1}catch{return!1}}}}function vy(r){r?.workdir&&(ot=r.workdir),fy(),jn(ot);let e=[];e.push(Va()),e.push(qa()),e.push(pc({askUser:async c=>kc?.(c)??null})),e.push(il({onProgress:r?.onExecProgress,interpretExitCode:(c,d)=>{if(c===127)return"command not found";if(c===126)return"permission denied";if(c===137)return"killed (SIGKILL / OOM)";if(c===143)return"terminated (SIGTERM)";if(c===130)return"interrupted (Ctrl+C)"}}));let t=ay(),n=ly(),o=cy(),s=uy();e.push(cl(t)),e.push(dl(n)),e.push(pl(o)),e.push(zr(s)),e.push(hl(s)),e.push(fl(dy())),e.push(Rl(yy())),e.push(_l(Ty()));let i=wy();e.push(Cl(i));let a=r?.log??{info:()=>{},warn:()=>{}};e.push(Al(Wl({log:a}))),e.push(Vl());let l={invokeTool:async(c,d,p)=>{let m=ke(c);if(!m)return{result:"",error:`Unknown tool: ${c}`};try{let g=await m.execute(`wf_${Date.now()}`,d,p);return{result:g.content.map(b=>b.text??"").join(`
265
- `),error:g.details?.error}}catch(g){return{result:"",error:g.message}}},getCwd:()=>ot};e.push(Jl(l)),e.push(Yl({sleep:(c,d)=>new Promise(p=>{let m=Date.now(),g=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!1})},c),f=()=>{clearTimeout(g),p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!0,interruptReason:"aborted"})};d.addEventListener("abort",f,{once:!0}),d.aborted&&(clearTimeout(g),f())})})),e.push(Ql({searchTools:async(c,d)=>{let p=d?.maxResults??5,m=c.toLowerCase(),g=Be();return{matches:g.map(b=>{let h=ke(b),k=`${b} ${h?.description??""} ${h?.searchHint??""}`.toLowerCase();return{name:b,description:h?.description??"",searchHint:h?.searchHint,score:k.includes(m)?1:0}}).filter(b=>b.score>0).slice(0,p),query:c,totalDeferred:g.length}}})),e.push({...Zl({generateImage:async c=>{let d=await Pe({mediaType:"image",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,size:c.size,imageUrl:c.imageUrl,n:c.n,quality:c.quality,seed:c.seed});return{mediaUrls:d.mediaUrls,model:d.model,size:d.size,durationMs:d.durationMs}}}),isEnabled:()=>He("image")}),e.push({...ec({textToSpeech:async c=>{let d=await Pe({mediaType:"tts",model:"",prompt:"",text:c.text,channel:c.channel,voice:c.voice,speed:c.speed});return{audioPath:"",provider:d.model,mediaUrls:d.mediaUrls}}}),isEnabled:()=>He("tts")}),e.push({...tc({generateVideo:async c=>{let d=await Pe({mediaType:"video",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,imageUrl:c.imageUrl,referenceVideos:c.referenceVideos,referenceAudios:c.referenceAudios,generateAudio:c.generateAudio,aspectRatio:c.aspectRatio,duration:c.duration,resolution:c.resolution,fps:c.fps,seed:c.seed,cameraFixed:c.cameraFixed,returnLastFrame:c.returnLastFrame,draft:c.draft,serviceTier:c.serviceTier,callbackUrl:c.callbackUrl,safetyIdentifier:c.safetyIdentifier,executionExpiresAfterSeconds:c.executionExpiresAfterSeconds,videoTools:c.videoTools});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs,lastFrameUrl:d.lastFrameUrl,taskId:d.taskId}}}),isEnabled:()=>He("video")}),e.push({...nc({generateMusic:async c=>{let d=await Pe({mediaType:"music",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,lyrics:c.lyrics,duration:c.duration,isInstrumental:c.isInstrumental,audioUrl:c.audioUrl,audioFormat:c.audioFormat});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}},generateLyrics:async c=>{let d=ze.music;if(!d||!ee)return"";let p=ee.getTransport(d.provider);if(!(p instanceof Ze))return"";let m=ue[d.provider];return m?p.generateLyrics(c,m):""}}),isEnabled:()=>He("music")}),e.push({...oc({editVideo:async c=>{let d=await Pe({mediaType:"video",model:"",prompt:c.prompt,operation:"edit",sourceVideos:c.sourceVideos,referenceImages:c.referenceImages,duration:c.duration,aspectRatio:c.aspectRatio,resolution:c.resolution});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>es("video","edit")}),e.push({...rc({mergeVideos:async c=>{let d=[`merge ${c.clips.length} clips`];c.transition&&d.push(`transition: ${c.transition}${c.transitionDuration?` (${c.transitionDuration}s)`:""}`),c.subtitles&&d.push(`burn-in subtitles: ${c.subtitles}`),c.bgm&&d.push(`background music: ${c.bgm}${c.bgmVolume!==void 0?` at volume ${c.bgmVolume}`:""}`);let p=await Pe({mediaType:"video",model:"",prompt:d.join("; "),operation:"merge",sourceVideos:c.clips.map(m=>m.video),resolution:c.outputResolution,fps:c.outputFps});return{localPath:"",servePath:p.mediaUrls[0]??"",durationSec:(p.durationMs??0)/1e3,clipCount:c.clips.length,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>es("video","merge")}),e.push({...sc({upscaleVideo:async c=>{let d=["upscale"];c.sharpness&&d.push(`sharpness: ${c.sharpness}`);let p=await Pe({mediaType:"video",model:"",prompt:d.join(", "),operation:"upscale",sourceVideos:[c.video],resolution:c.targetResolution??"1080p"});return{localPath:"",servePath:p.mediaUrls[0]??"",resolution:c.targetResolution??"1080p",durationSec:(p.durationMs??0)/1e3,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>es("video","upscale")}),e.push({...ic({generate3D:async c=>{let d=await Pe({mediaType:"3d",model:"",prompt:c.prompt,imageUrl:c.imageUrl,outputFormat:c.outputFormat,seed:c.seed});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>He("3d")}),e.push({...ac({speechToText:async c=>{let d=await Pe({mediaType:"stt",model:"",prompt:"",audioUrl:c.audioUrl,metadata:c.language?{language:c.language}:void 0});return{transcription:d.metadata?.transcription??"",model:d.model,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>He("stt")}),e.push({...lc({cloneVoice:async c=>{let d=await Pe({mediaType:"voice_clone",model:"",prompt:"",text:c.text,audioUrl:c.sampleAudioUrl,speed:c.speed});return{mediaUrls:d.mediaUrls,model:d.model,voiceId:d.metadata?.voiceId,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>He("voice_clone")});let u=Hn();return e.push({...cc({uploadFile:async c=>{if(!u)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");let d=de(c.filePath);if(!L.existsSync(d))throw new Error(`File not found: ${d}`);let p=L.statSync(d);if(p.size>100*1024*1024)throw new Error(`File too large (${(p.size/1024/1024).toFixed(1)} MB). Max: 100 MB.`);let m=await L.promises.readFile(d),g=W.basename(d);if(u.type==="gemini"){let R=zn(),E=ue.google,F=W.extname(d).toLowerCase(),U=iy[F]??"application/octet-stream",D=await R.uploadFile(Buffer.from(m),E,{mimeType:U,displayName:g});if(D.state==="PROCESSING"){let w=await R.waitForProcessing(D.name,E);return{fileId:w.name,url:w.uri,filename:g,bytes:p.size,provider:"google"}}return{fileId:D.name,url:D.uri,filename:g,bytes:p.size,provider:"google"}}let f=new Blob([m]),b=ee.getTransport(u.id),h=ue[u.id];if(!(b instanceof xe))throw new Error(`File upload only supported via Volcengine or Google provider. Current: ${u.id}`);let k=await b.uploadFile(f,h,{purpose:c.purpose??"media_reference",filename:g}),x;try{let R=await b.getFile(k.id,h);typeof R.url=="string"&&R.url&&(x=R.url)}catch{}return{fileId:k.id,url:x,filename:g,bytes:p.size,provider:u.id}}}),shouldDefer:!0,isEnabled:()=>!!Hn()}),e.push({...uc({queryFile:async c=>{if(!u)throw new Error("No file API provider available.");if(u.type==="gemini"){let g=zn(),f=ue.google,b=await g.getFile(c.fileId,f);return{id:b.name,filename:b.displayName??"",bytes:Number(b.sizeBytes??0),status:b.state?.toLowerCase()??"unknown",createdAt:b.createTime,url:b.uri}}let d=ee.getTransport(u.id),p=ue[u.id];if(!(d instanceof xe))throw new Error("File query only supported via Volcengine or Google provider.");let m=await d.getFile(c.fileId,p);return{id:String(m.id??c.fileId),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}},listFiles:async c=>{if(!u)throw new Error("No file API provider available.");if(u.type==="gemini"){let f=zn(),b=ue.google;return(await f.listFiles(b,{pageSize:c.limit??10})).files.map(k=>({id:k.name,filename:k.displayName??"",bytes:Number(k.sizeBytes??0),status:k.state?.toLowerCase()??"unknown",createdAt:k.createTime,url:k.uri}))}let d=ee.getTransport(u.id),p=ue[u.id];if(!(d instanceof xe))throw new Error("File list only supported via Volcengine or Google provider.");return((await d.listFiles(p,{limit:c.limit??10})).data??[]).map(f=>({id:String(f.id??""),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}))}}),shouldDefer:!0,isEnabled:()=>!!Hn()}),e.push({...dc({deleteFile:async c=>{if(!u)throw new Error("No file API provider available.");if(u.type==="gemini"){let m=zn(),g=ue.google;await m.deleteFile(c.fileId,g);return}let d=ee.getTransport(u.id),p=ue[u.id];if(!(d instanceof xe))throw new Error("File delete only supported via Volcengine or Google provider.");await d.deleteFile(c.fileId,p)}}),shouldDefer:!0,isEnabled:()=>!!Hn()}),za(e),r?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(c=>c.isEnabled?.()!==!1).length} enabled): ${Be().join(", ")}`),e}var Sc=vy;function ss(r){ot=r,jn(r)}import{spawn as xy}from"node:child_process";import{createInterface as Sy}from"node:readline";var Vn=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=xy(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=Sy({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=Ry(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(`
269
+ `))}async function $c(r,e,t){let n=ee.getTransport(r);if(!n)return{ok:!1,error:"transport not available"};let o=de[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,l=i.billingUnit??"per_call",u=i.billingQuantity??1;return Uc?.(a,l,u),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Ee(r){if(!ee)return!1;let e=He[r];if(!e)return!1;let t=ee.getTransport(e.provider),n=de[e.provider];return!!(t&&n)}function us(r,e){if(!Ee(r))return!1;let t=He[r],n=ee.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 Jn(){if(!ee)return;for(let[,e]of Object.entries(He)){if(!e)continue;let t=ee.getTransport(e.provider),n=de[e.provider];if(t instanceof _e&&n)return{id:e.provider,type:"volcengine"}}if(de.google)return{id:"google",type:"gemini"}}var ds;function Yn(){return ds||(ds=new jt({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),ds}var ot=process.cwd();function ge(r){return H.isAbsolute(r)?H.normalize(r):H.resolve(ot,r)}var Hy=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),Gc=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),Vy={".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 zy(){return{resolvePath:ge,async readFile(r){let e=ge(r),t=H.extname(e).toLowerCase();if(Gc.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(Hy.has(t)){let o=await U.promises.readFile(e),s=t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg";return{type:"image",base64:o.toString("base64"),mimeType:s}}return{type:"text",text:await U.promises.readFile(e,"utf8")}},validatePath(r){let e=ge(r);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function qy(){return{resolvePath:ge,async writeFile(r,e){let t=ge(r);await U.promises.mkdir(H.dirname(t),{recursive:!0}),await U.promises.writeFile(t,e,"utf8")}}}function Ky(){return{resolvePath:ge,async readFile(r){let e=ge(r);return U.promises.readFile(e,"utf8")},async writeFile(r,e){let t=ge(r);await U.promises.mkdir(H.dirname(t),{recursive:!0}),await U.promises.writeFile(t,e,"utf8")}}}function Jy(){return{resolvePath:ge,async readFile(r){let e=ge(r);return U.promises.readFile(e,"utf8")},async writeFile(r,e){let t=ge(r);await U.promises.mkdir(H.dirname(t),{recursive:!0}),await U.promises.writeFile(t,e,"utf8")},async deleteFile(r){let e=ge(r);await U.promises.unlink(e)},async fileExists(r){let e=ge(r);try{return await U.promises.access(e),!0}catch{return!1}}}}function Yy(){return{resolvePath:ge,async glob(r,e){let t=e.cwd||ot,n=e.limit||1e3,o=[],s=!1,i=r.replace(/\\/g,"/").split("/"),a=i.some(c=>c==="**"),l=i[i.length-1]??"*",u=Hc(l);try{await gs(t,async c=>{if(o.length>=n)return s=!0,!1;let d=H.basename(c);return u.test(d)&&o.push(c),!0},a?1/0:1)}catch{}return{files:o,truncated:s}},async grep(r,e){let t=e.cwd||ot;try{return await Qy(r,t,e)}catch{return await Zy(r,t,e)}}}}function Hc(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 Xy=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function gs(r,e,t,n=0,o=""){if(n>t)return;let s;try{s=await U.promises.readdir(r,{withFileTypes:!0})}catch{return}for(let i of s){let a=o?`${o}/${i.name}`:i.name;if(i.isDirectory()){if(Xy.has(i.name))continue;await gs(H.join(r,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function Qy(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("."),Ny("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 l=[];for(let p of a.split(`
270
+ `))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&l.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let u=t.headLimit??250,c=t.offset??0,d=l.slice(c,c+u);n({matches:d,truncated:l.length>c+u})})})}async function Zy(r,e,t){let n=new RegExp(r,t.caseInsensitive?"i":""),o=t.headLimit??250,s=t.offset??0,i=t.fileGlob?Hc(t.fileGlob):null,a=[],l=!1;return await gs(e,async u=>{if(a.length>=s+o+1)return l=!0,!1;if(i&&!i.test(H.basename(u)))return!0;let c=H.extname(u).toLowerCase();if(Gc.has(c))return!0;try{let p=(await U.promises.readFile(H.join(e,u),"utf8")).split(`
271
+ `);for(let m=0;m<p.length;m++)if(n.test(p[m])&&(a.push({path:u,line:m+1,text:p[m].slice(0,500)}),a.length>=s+o+1))return l=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+o),truncated:l}}var Dc=!1;function eb(){if(!Dc)if(Dc=!0,Fn()){let r=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";Kt(Yr(r))}else if(process.platform==="win32"){let r=tb();Kt(Kn(r))}else{let r=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";Kt(Kn(r))}}function tb(){let r=process.env.QLOGICAGENT_BASH_PATH;if(r&&U.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?H.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let n of e)if(U.existsSync(n))return n;return"bash"}function nb(){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=ob(s)),{content:s,title:rb(s)}}finally{clearTimeout(t)}}}}function ob(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 rb(r){return r.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function sb(){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 l=await fetch(s.toString(),{signal:i.signal,headers:{Accept:"application/json"}});if(!l.ok)return{query:e,results:[]};let u=await l.json(),c=(u.results??[]).slice(0,o).map(d=>({title:d.title??"",url:d.url??"",snippet:d.content??""}));if(t?.allowedDomains?.length){let d=new Set(t.allowedDomains.map(p=>p.toLowerCase()));return{query:e,results:c.filter(p=>{try{return d.has(new URL(p.url).hostname.toLowerCase())}catch{return!1}})}}if(t?.blockedDomains?.length){let d=new Set(t.blockedDomains.map(p=>p.toLowerCase()));return{query:e,results:c.filter(p=>{try{return!d.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:c,totalResults:u.number_of_results}}finally{clearTimeout(a)}};return{search:(e,t)=>Lc(Nc,r)(e,t)}}function ib(){let r=H.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(o){return H.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=H.resolve(i,s);if(!a.startsWith(i+H.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(o,s){if(!U.existsSync(o))return[];let i=[];for(let a of U.readdirSync(o,{withFileTypes:!0})){let l=H.join(o,a.name);if(a.isDirectory())i.push(...n(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let u=U.statSync(l);i.push({filename:H.relative(s,l).replace(/\\/g,"/"),path:l,size:u.size,updatedAt:u.mtime.toISOString(),content:U.readFileSync(l,"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(!U.existsSync(i))return null;let a=U.statSync(i),l=U.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:l}}catch{return null}},write(o,s,i){let a=t(o,s);U.mkdirSync(H.dirname(a),{recursive:!0}),U.writeFileSync(a,i,"utf-8");let l=U.statSync(a);return{filename:s,path:a,size:l.size,updatedAt:l.mtime.toISOString(),content:i}},remove(o,s){try{let i=t(o,s);return U.existsSync(i)?(U.unlinkSync(i),!0):!1}catch{return!1}}}}function ab(r){r?.workdir&&(ot=r.workdir),eb(),Vn(ot);let e=[];e.push(pl()),e.push(ml()),e.push(Oc({askUser:async c=>jc?.(c)??null})),e.push(Rl({onProgress:r?.onExecProgress,interpretExitCode:(c,d)=>{if(c===127)return"command not found";if(c===126)return"permission denied";if(c===137)return"killed (SIGKILL / OOM)";if(c===143)return"terminated (SIGTERM)";if(c===130)return"interrupted (Ctrl+C)"}}));let t=zy(),n=qy(),o=Ky(),s=Jy();e.push(Ml(t)),e.push(Il(n)),e.push(El(o)),e.push(ts(s)),e.push(Dl(s)),e.push($l(Yy())),e.push(Vl(nb())),e.push(zl(sb()));let i=ib();e.push(ql(i));let a=r?.log??{info:()=>{},warn:()=>{}};e.push(Kl(lc({log:a}))),e.push(pc());let l={invokeTool:async(c,d,p)=>{let m=we(c);if(!m)return{result:"",error:`Unknown tool: ${c}`};try{let g=await m.execute(`wf_${Date.now()}`,d,p);return{result:g.content.map(b=>b.text??"").join(`
272
+ `),error:g.details?.error}}catch(g){return{result:"",error:g.message}}},getCwd:()=>ot};e.push(fc(l)),e.push(hc({sleep:(c,d)=>new Promise(p=>{let m=Date.now(),g=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!1})},c),f=()=>{clearTimeout(g),p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!0,interruptReason:"aborted"})};d.addEventListener("abort",f,{once:!0}),d.aborted&&(clearTimeout(g),f())})})),e.push(bc({searchTools:async(c,d)=>{let p=d?.maxResults??5,m=Be(),g=c.toLowerCase().split(/\s+/).filter(Boolean),f=[],b=[];for(let C of g)C.startsWith("+")&&C.length>1?f.push(C.slice(1)):b.push(C);let T=[...f,...b],w=C=>C.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:m.map(C=>{let E=we(C),D=w(C),L=(E?.description??"").toLowerCase(),v=(E?.searchHint??"").toLowerCase();if(f.length>0){let j=`${D.join(" ")} ${L} ${v}`;if(!f.every(ne=>j.includes(ne)))return null}let ce=0;for(let j of T){let F=0;D.some(ne=>ne===j)?F=10:D.some(ne=>ne.includes(j))?F=5:C.toLowerCase().includes(j)&&(F=3),v&&new RegExp(`\\b${j}`,"i").test(v)&&(F+=4),new RegExp(`\\b${j}`,"i").test(L)&&(F+=2),ce+=F}return{name:C,description:E?.description??"",searchHint:E?.searchHint,score:ce}}).filter(C=>C!==null&&C.score>0).sort((C,E)=>E.score-C.score).slice(0,p),query:c,totalDeferred:m.length}},activateTool:async c=>dl(c)})),e.push({...kc({generateImage:async c=>{let d=await Ie({mediaType:"image",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,size:c.size,imageUrl:c.imageUrl,n:c.n,quality:c.quality,seed:c.seed});return{mediaUrls:d.mediaUrls,model:d.model,size:d.size,durationMs:d.durationMs}}}),isEnabled:()=>Ee("image")}),e.push({...Tc({textToSpeech:async c=>{let d=await Ie({mediaType:"tts",model:"",prompt:"",text:c.text,channel:c.channel,voice:c.voice,speed:c.speed});return{audioPath:"",provider:d.model,mediaUrls:d.mediaUrls}}}),isEnabled:()=>Ee("tts")}),e.push({...wc({generateVideo:async c=>{let d=await Ie({mediaType:"video",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,imageUrl:c.imageUrl,referenceVideos:c.referenceVideos,referenceAudios:c.referenceAudios,generateAudio:c.generateAudio,aspectRatio:c.aspectRatio,duration:c.duration,resolution:c.resolution,fps:c.fps,seed:c.seed,cameraFixed:c.cameraFixed,returnLastFrame:c.returnLastFrame,draft:c.draft,serviceTier:c.serviceTier,callbackUrl:c.callbackUrl,safetyIdentifier:c.safetyIdentifier,executionExpiresAfterSeconds:c.executionExpiresAfterSeconds,videoTools:c.videoTools});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs,lastFrameUrl:d.lastFrameUrl,taskId:d.taskId}}}),isEnabled:()=>Ee("video")}),e.push({...vc({generateMusic:async c=>{let d=await Ie({mediaType:"music",model:"",prompt:c.prompt,purpose:c.purpose,style:c.style,lyrics:c.lyrics,duration:c.duration,isInstrumental:c.isInstrumental,audioUrl:c.audioUrl,audioFormat:c.audioFormat});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}},generateLyrics:async c=>{let d=He.music;if(!d||!ee)return"";let p=ee.getTransport(d.provider);if(!(p instanceof Ze))return"";let m=de[d.provider];return m?p.generateLyrics(c,m):""}}),isEnabled:()=>Ee("music")}),e.push({...xc({editVideo:async c=>{let d=await Ie({mediaType:"video",model:"",prompt:c.prompt,operation:"edit",sourceVideos:c.sourceVideos,referenceImages:c.referenceImages,duration:c.duration,aspectRatio:c.aspectRatio,resolution:c.resolution});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>us("video","edit")}),e.push({...Sc({mergeVideos:async c=>{let d=[`merge ${c.clips.length} clips`];c.transition&&d.push(`transition: ${c.transition}${c.transitionDuration?` (${c.transitionDuration}s)`:""}`),c.subtitles&&d.push(`burn-in subtitles: ${c.subtitles}`),c.bgm&&d.push(`background music: ${c.bgm}${c.bgmVolume!==void 0?` at volume ${c.bgmVolume}`:""}`);let p=await Ie({mediaType:"video",model:"",prompt:d.join("; "),operation:"merge",sourceVideos:c.clips.map(m=>m.video),resolution:c.outputResolution,fps:c.outputFps});return{localPath:"",servePath:p.mediaUrls[0]??"",durationSec:(p.durationMs??0)/1e3,clipCount:c.clips.length,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>us("video","merge")}),e.push({..._c({upscaleVideo:async c=>{let d=["upscale"];c.sharpness&&d.push(`sharpness: ${c.sharpness}`);let p=await Ie({mediaType:"video",model:"",prompt:d.join(", "),operation:"upscale",sourceVideos:[c.video],resolution:c.targetResolution??"1080p"});return{localPath:"",servePath:p.mediaUrls[0]??"",resolution:c.targetResolution??"1080p",durationSec:(p.durationMs??0)/1e3,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>us("video","upscale")}),e.push({...Rc({generate3D:async c=>{let d=await Ie({mediaType:"3d",model:"",prompt:c.prompt,imageUrl:c.imageUrl,outputFormat:c.outputFormat,seed:c.seed});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs,metadata:d.metadata}}}),shouldDefer:!0,isEnabled:()=>Ee("3d")}),e.push({...Cc({speechToText:async c=>{let d=await Ie({mediaType:"stt",model:"",prompt:"",audioUrl:c.audioUrl,metadata:c.language?{language:c.language}:void 0});return{transcription:d.metadata?.transcription??"",model:d.model,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>Ee("stt")}),e.push({...Ac({cloneVoice:async c=>{let d=await Ie({mediaType:"voice_clone",model:"",prompt:"",text:c.text,audioUrl:c.sampleAudioUrl,speed:c.speed});return{mediaUrls:d.mediaUrls,model:d.model,voiceId:d.metadata?.voiceId,durationMs:d.durationMs}}}),shouldDefer:!0,isEnabled:()=>Ee("voice_clone")}),e.push({...Mc({cancelTask:async c=>{let d=c.provider??"doubao";if(!ee)return{ok:!1,message:"Media client not configured."};let p=ee.getTransport(d);if(!p)return{ok:!1,message:`No transport for provider: ${d}`};let m=de[d];if(!m)return{ok:!1,message:`No API key for provider: ${d}`};try{return"deleteVideoTask"in p&&typeof p.deleteVideoTask=="function"?(await p.deleteVideoTask(c.taskId,m),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${d} does not support task cancellation.`}}catch(g){return{ok:!1,message:g instanceof Error?g.message:String(g)}}}}),shouldDefer:!0,isEnabled:()=>Ee("video")||Ee("3d")});let u=Jn();return e.push({...Pc({uploadFile:async c=>{if(!u)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");let d=ge(c.filePath);if(!U.existsSync(d))throw new Error(`File not found: ${d}`);let p=U.statSync(d);if(p.size>100*1024*1024)throw new Error(`File too large (${(p.size/1024/1024).toFixed(1)} MB). Max: 100 MB.`);let m=await U.promises.readFile(d),g=H.basename(d);if(u.type==="gemini"){let y=Yn(),C=de.google,E=H.extname(d).toLowerCase(),D=Vy[E]??"application/octet-stream",L=await y.uploadFile(Buffer.from(m),C,{mimeType:D,displayName:g});if(L.state==="PROCESSING"){let v=await y.waitForProcessing(L.name,C);return{fileId:v.name,url:v.uri,filename:g,bytes:p.size,provider:"google"}}return{fileId:L.name,url:L.uri,filename:g,bytes:p.size,provider:"google"}}let f=new Blob([m]),b=ee.getTransport(u.id),T=de[u.id];if(!(b instanceof _e))throw new Error(`File upload only supported via Volcengine or Google provider. Current: ${u.id}`);let w=await b.uploadFile(f,T,{purpose:c.purpose??"media_reference",filename:g}),_;try{let y=await b.getFile(w.id,T);typeof y.url=="string"&&y.url&&(_=y.url)}catch{}return{fileId:w.id,url:_,filename:g,bytes:p.size,provider:u.id}}}),shouldDefer:!0,isEnabled:()=>!!Jn()}),e.push({...Ic({queryFile:async c=>{if(!u)throw new Error("No file API provider available.");if(u.type==="gemini"){let g=Yn(),f=de.google,b=await g.getFile(c.fileId,f);return{id:b.name,filename:b.displayName??"",bytes:Number(b.sizeBytes??0),status:b.state?.toLowerCase()??"unknown",createdAt:b.createTime,url:b.uri}}let d=ee.getTransport(u.id),p=de[u.id];if(!(d instanceof _e))throw new Error("File query only supported via Volcengine or Google provider.");let m=await d.getFile(c.fileId,p);return{id:String(m.id??c.fileId),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}},listFiles:async c=>{if(!u)throw new Error("No file API provider available.");if(u.type==="gemini"){let f=Yn(),b=de.google;return(await f.listFiles(b,{pageSize:c.limit??10})).files.map(w=>({id:w.name,filename:w.displayName??"",bytes:Number(w.sizeBytes??0),status:w.state?.toLowerCase()??"unknown",createdAt:w.createTime,url:w.uri}))}let d=ee.getTransport(u.id),p=de[u.id];if(!(d instanceof _e))throw new Error("File list only supported via Volcengine or Google provider.");return((await d.listFiles(p,{limit:c.limit??10})).data??[]).map(f=>({id:String(f.id??""),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}))}}),shouldDefer:!0,isEnabled:()=>!!Jn()}),e.push({...Ec({deleteFile:async c=>{if(!u)throw new Error("No file API provider available.");if(u.type==="gemini"){let m=Yn(),g=de.google;await m.deleteFile(c.fileId,g);return}let d=ee.getTransport(u.id),p=de[u.id];if(!(d instanceof _e))throw new Error("File delete only supported via Volcengine or Google provider.");await d.deleteFile(c.fileId,p)}}),shouldDefer:!0,isEnabled:()=>!!Jn()}),ul(e),r?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(c=>c.isEnabled?.()!==!1).length} enabled): ${Be().join(", ")}`),e}var Vc=ab;function fs(r){ot=r,Vn(r)}import{spawn as lb}from"node:child_process";import{createInterface as cb}from"node:readline";var Xn=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=lb(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=cb({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=ub(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(`
266
273
  `)||"(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++,l={jsonrpc:"2.0",id:a,method:e,params:t},u=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${n}ms`))},n),c=()=>{clearTimeout(u),this.pending.delete(a)};o?.addEventListener("abort",()=>{c(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:d=>{c(),d.error?i(new Error(`MCP error ${d.error.code}: ${d.error.message}`)):s(d.result)},reject:d=>{c(),i(d)}}),this.writeLine(JSON.stringify(l))})}sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t};this.writeLine(JSON.stringify(n))}writeLine(e){this.process?.stdin?.writable&&this.process.stdin.write(e+`
267
- `)}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 Ry(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as _y}from"node:crypto";var qn=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=_y(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,l=setTimeout(()=>a.abort(),n);o&&o.addEventListener("abort",()=>a.abort(),{once:!0});try{let u={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(u["Mcp-Session-Id"]=this.sessionId);let c=await fetch(this.config.url,{method:"POST",headers:u,body:JSON.stringify(i),signal:a.signal}),d=c.headers.get("mcp-session-id");if(d&&(this.sessionId=d),!c.ok)throw new Error(`MCP HTTP error ${c.status}: ${c.statusText}`);if((c.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(c,s);let m=await c.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(l)}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t},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:l}=await o.read();if(a)break;i+=s.decode(l,{stream:!0});let u=i.split(`
268
- `);i=u.pop()??"";for(let c of u){if(!c.startsWith("data: "))continue;let d=c.slice(6).trim();if(d)try{let p=JSON.parse(d);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__${Cy(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(c=>c.type==="text"&&c.text).map(c=>c.text).join(`
269
- `)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function Cy(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Kn=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 qn(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 Vn(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();Rr(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 Be())s.startsWith(n)&&On(s);let o=t.toPortableTools();Rr(o),this.log.info(`[mcp] re-injected ${o.length} tools from ${e}`)}};function is(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 Ay={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function Rc(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:Ay,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 l=s.get(a.server)??[];l.push(a),s.set(a.server,l)}let i=[];for(let[a,l]of s){i.push(`Server: ${a} (${l.length} resources)`);for(let u of l){let c=u.mimeType?` [${u.mimeType}]`:"",d=u.description?` \u2014 ${u.description}`:"";i.push(` ${u.name}: ${u.uri}${c}${d}`)}i.push("")}return{content:[{type:"text",text:i.join(`
270
- `).trim()}],details:{type:"list_mcp_resources",count:o.length}}}}}var My={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 _c(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:My,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} ---
274
+ `)}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 ub(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as db}from"node:crypto";var Qn=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=db(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,l=setTimeout(()=>a.abort(),n);o&&o.addEventListener("abort",()=>a.abort(),{once:!0});try{let u={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(u["Mcp-Session-Id"]=this.sessionId);let c=await fetch(this.config.url,{method:"POST",headers:u,body:JSON.stringify(i),signal:a.signal}),d=c.headers.get("mcp-session-id");if(d&&(this.sessionId=d),!c.ok)throw new Error(`MCP HTTP error ${c.status}: ${c.statusText}`);if((c.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(c,s);let m=await c.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(l)}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t},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:l}=await o.read();if(a)break;i+=s.decode(l,{stream:!0});let u=i.split(`
275
+ `);i=u.pop()??"";for(let c of u){if(!c.startsWith("data: "))continue;let d=c.slice(6).trim();if(d)try{let p=JSON.parse(d);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__${pb(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(c=>c.type==="text"&&c.text).map(c=>c.text).join(`
276
+ `)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function pb(r){return r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Zn=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 Qn(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 Xn(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();Lr(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 Be())s.startsWith(n)&&Nn(s);let o=t.toPortableTools();Lr(o),this.log.info(`[mcp] re-injected ${o.length} tools from ${e}`)}};function hs(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 mb={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function zc(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:mb,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 l=s.get(a.server)??[];l.push(a),s.set(a.server,l)}let i=[];for(let[a,l]of s){i.push(`Server: ${a} (${l.length} resources)`);for(let u of l){let c=u.mimeType?` [${u.mimeType}]`:"",d=u.description?` \u2014 ${u.description}`:"";i.push(` ${u.name}: ${u.uri}${c}${d}`)}i.push("")}return{content:[{type:"text",text:i.join(`
277
+ `).trim()}],details:{type:"list_mcp_resources",count:o.length}}}}}var gb={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 qc(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:gb,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} ---
271
278
  ${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"}) ---
272
- [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 Ve from"node:fs";import*as Jn from"node:path";import{pathToFileURL as Py}from"node:url";var Cc={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var Yn=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(!Ve.existsSync(e))continue;let t;try{t=Ve.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let o=Jn.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 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)ce(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)On(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 f of n){let b=Jn.join(t,f);if(Ve.existsSync(b)){o=b;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],u=[],c=null,d=6e4,p={},m=Jn.join(t,"config.json");if(Ve.existsSync(m))try{p=JSON.parse(Ve.readFileSync(m,"utf8"))}catch{}let g={pluginName:e,registerTool:f=>{ce(f),l.push(f),s++},registerHook:(f,b)=>{let h=Cc[f];if(!h){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let k=this.config.hookRegistry.register({point:h,handler:b,label:`plugin:${e}:${f}`,priority:200});u.push(k),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>p,setActivationCheck:(f,b)=>{c=f,b!==void 0&&(d=b)}};try{let b=await import(Py(o).href);if(typeof b.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await b.register(g),c&&this.activations.set(e,{checkFn:c,ttlMs:d,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:u,active:!0}),this.loaded.push({name:e,directory:t,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(f){this.log.warn(`[plugins] ${e}: load error: ${f instanceof Error?f.message:f}`)}}};import*as oe from"node:fs";import*as Kt from"node:path";function as(){return Fi()}function Ac(){return Kt.join(as(),"installed_plugins.json")}function Mc(){let r=Ac();if(!oe.existsSync(r))return{version:1,plugins:[]};try{return JSON.parse(oe.readFileSync(r,"utf-8"))}catch{return{version:1,plugins:[]}}}function Iy(r){let e=as();oe.existsSync(e)||oe.mkdirSync(e,{recursive:!0}),oe.writeFileSync(Ac(),JSON.stringify(r,null,2),"utf-8")}function Ey(r,e){return!(e.blocklist?.includes(r)||e.allowlist&&!e.allowlist.includes(r))}async function Oy(r,e,t){let{execFile:n}=await import("node:child_process"),{promisify:o}=await import("node:util"),s=o(n),i=as(),a=e?`${r}@${e}`:r;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),u=l.trim().split(`
273
- `).pop()?.trim();if(!u)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let c=Kt.join(i,u),p=u.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=Kt.join(i,`${r}@${p}`);oe.existsSync(m)||oe.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",c,"-C",m,"--strip-components=1"],{timeout:3e4});try{oe.unlinkSync(c)}catch{}let g=Kt.join(m,"package.json");if(oe.existsSync(g))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){t.warn(`[marketplace] npm install for ${r} failed: ${f.message}`)}return t.info(`[marketplace] installed ${r}@${p} from npm`),{name:r,version:p,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function Ly(){return Mc().plugins.filter(e=>oe.existsSync(e.installPath)).map(e=>e.installPath)}async function $y(r,e){let t=Mc(),n=[];for(let o of r.enabledPlugins){let s=o.specifier.split("/").pop()??o.specifier;if(!Ey(s,r)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(l=>l.source.specifier===o.specifier&&l.source.type===o.type);if(i&&oe.existsSync(i.installPath)&&(!o.version||i.version===o.version)){n.push(i.installPath);continue}let a=null;switch(o.type){case"npm":a=await Oy(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 l={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};t.plugins=t.plugins.filter(u=>!(u.source.specifier===o.specifier&&u.source.type===o.type)),t.plugins.push(l),n.push(a.installPath)}}return Iy(t),n}function Dy(){let r=Bi();if(!oe.existsSync(r))return null;try{return JSON.parse(oe.readFileSync(r,"utf-8"))}catch{return null}}async function Pc(r,e){let t=[...r],n=Ly();t.push(...n);let o=Dy();if(o&&o.enabledPlugins.length>0)try{let s=await $y(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 Xn=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 Ny(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:Uy(t.pattern)}))}};function ls(r){if(!r||typeof r!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=r,t=[];for(let a of["allow","deny","ask"]){let l=e[a];if(Array.isArray(l))for(let u of l)typeof u=="string"&&t.push({pattern:u,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let l=a,u=l.pattern,c=l.behavior??l.action;typeof u=="string"&&typeof c=="string"&&(c==="allow"||c==="deny"||c==="ask")&&t.push({pattern:u,behavior:c,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let n=e.mode,o=typeof n=="string"&&Fy(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&jy(s)?s:"allow";return{mode:o,rules:t,defaultBehavior:i}}function Uy(r){let t=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function Ny(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 Fy(r){return r==="default"||r==="bypassPermissions"||r==="acceptEdits"||r==="dontAsk"||r==="plan"}function jy(r){return r==="allow"||r==="deny"||r==="ask"}import{randomUUID as Ky}from"node:crypto";var By=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"]),Ic=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"]),Wy=[/\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],Ec=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 Oc(r,e,t){let n=r.trim();if(!n)return{decision:"allow",reason:"empty command"};let o=Br(n)??Wr(n)??void 0;for(let u of Wy)if(u.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${u.source}`,destructiveWarning:o};for(let u of By)if(n===u||n.startsWith(u+" "))return{decision:"allow",reason:`known safe command: ${u}`,destructiveWarning:o};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return Ic.has(i)||Ic.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:o}:e&&t&&e.startsWith(t)&&(Ec.has(i)||Ec.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:o}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:o}}function Gy(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 cs(r,e){return`${r}::${Gy(e)}`}var Hy=500,Qn=class{cache=new Map;get(e,t){let n=cs(e,t),o=this.cache.get(n);if(o)return o.hitCount++,o}set(e,t,n){if(this.cache.size>=Hy){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let o=cs(e,t);this.cache.set(o,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(cs(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 zy=new Set(["read","search","instructions","think","todo","memory","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function Jt(r){return zy.has(r)}var Lc=`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.
279
+ [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 Ve from"node:fs";import*as eo from"node:path";import{pathToFileURL as fb}from"node:url";var Kc={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var to=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(!Ve.existsSync(e))continue;let t;try{t=Ve.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let o=eo.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 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)me(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)Nn(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 f of n){let b=eo.join(t,f);if(Ve.existsSync(b)){o=b;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],u=[],c=null,d=6e4,p={},m=eo.join(t,"config.json");if(Ve.existsSync(m))try{p=JSON.parse(Ve.readFileSync(m,"utf8"))}catch{}let g={pluginName:e,registerTool:f=>{me(f),l.push(f),s++},registerHook:(f,b)=>{let T=Kc[f];if(!T){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let w=this.config.hookRegistry.register({point:T,handler:b,label:`plugin:${e}:${f}`,priority:200});u.push(w),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>p,setActivationCheck:(f,b)=>{c=f,b!==void 0&&(d=b)}};try{let b=await import(fb(o).href);if(typeof b.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await b.register(g),c&&this.activations.set(e,{checkFn:c,ttlMs:d,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:u,active:!0}),this.loaded.push({name:e,directory:t,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(f){this.log.warn(`[plugins] ${e}: load error: ${f instanceof Error?f.message:f}`)}}};import*as ie from"node:fs";import*as Xt from"node:path";function ys(){return Yi()}function Jc(){return Xt.join(ys(),"installed_plugins.json")}function Yc(){let r=Jc();if(!ie.existsSync(r))return{version:1,plugins:[]};try{return JSON.parse(ie.readFileSync(r,"utf-8"))}catch{return{version:1,plugins:[]}}}function hb(r){let e=ys();ie.existsSync(e)||ie.mkdirSync(e,{recursive:!0}),ie.writeFileSync(Jc(),JSON.stringify(r,null,2),"utf-8")}function yb(r,e){return!(e.blocklist?.includes(r)||e.allowlist&&!e.allowlist.includes(r))}async function bb(r,e,t){let{execFile:n}=await import("node:child_process"),{promisify:o}=await import("node:util"),s=o(n),i=ys(),a=e?`${r}@${e}`:r;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),u=l.trim().split(`
280
+ `).pop()?.trim();if(!u)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let c=Xt.join(i,u),p=u.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=Xt.join(i,`${r}@${p}`);ie.existsSync(m)||ie.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",c,"-C",m,"--strip-components=1"],{timeout:3e4});try{ie.unlinkSync(c)}catch{}let g=Xt.join(m,"package.json");if(ie.existsSync(g))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){t.warn(`[marketplace] npm install for ${r} failed: ${f.message}`)}return t.info(`[marketplace] installed ${r}@${p} from npm`),{name:r,version:p,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function kb(){return Yc().plugins.filter(e=>ie.existsSync(e.installPath)).map(e=>e.installPath)}async function Tb(r,e){let t=Yc(),n=[];for(let o of r.enabledPlugins){let s=o.specifier.split("/").pop()??o.specifier;if(!yb(s,r)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(l=>l.source.specifier===o.specifier&&l.source.type===o.type);if(i&&ie.existsSync(i.installPath)&&(!o.version||i.version===o.version)){n.push(i.installPath);continue}let a=null;switch(o.type){case"npm":a=await bb(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 l={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};t.plugins=t.plugins.filter(u=>!(u.source.specifier===o.specifier&&u.source.type===o.type)),t.plugins.push(l),n.push(a.installPath)}}return hb(t),n}function wb(){let r=Qi();if(!ie.existsSync(r))return null;try{return JSON.parse(ie.readFileSync(r,"utf-8"))}catch{return null}}async function Xc(r,e){let t=[...r],n=kb();t.push(...n);let o=wb();if(o&&o.enabledPlugins.length>0)try{let s=await Tb(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 no=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 xb(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:vb(t.pattern)}))}};function bs(r){if(!r||typeof r!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=r,t=[];for(let a of["allow","deny","ask"]){let l=e[a];if(Array.isArray(l))for(let u of l)typeof u=="string"&&t.push({pattern:u,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let l=a,u=l.pattern,c=l.behavior??l.action;typeof u=="string"&&typeof c=="string"&&(c==="allow"||c==="deny"||c==="ask")&&t.push({pattern:u,behavior:c,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let n=e.mode,o=typeof n=="string"&&Sb(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&_b(s)?s:"allow";return{mode:o,rules:t,defaultBehavior:i}}function vb(r){let t=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function xb(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 Sb(r){return r==="default"||r==="bypassPermissions"||r==="acceptEdits"||r==="dontAsk"||r==="plan"}function _b(r){return r==="allow"||r==="deny"||r==="ask"}import{randomUUID as Ob}from"node:crypto";var Rb=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"]),Qc=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"]),Cb=[/\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],Zc=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 eu(r,e,t){let n=r.trim();if(!n)return{decision:"allow",reason:"empty command"};let o=Xr(n)??Qr(n)??void 0;for(let u of Cb)if(u.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${u.source}`,destructiveWarning:o};for(let u of Rb)if(n===u||n.startsWith(u+" "))return{decision:"allow",reason:`known safe command: ${u}`,destructiveWarning:o};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return Qc.has(i)||Qc.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:o}:e&&t&&e.startsWith(t)&&(Zc.has(i)||Zc.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:o}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:o}}function Ab(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 ks(r,e){return`${r}::${Ab(e)}`}var Mb=500,oo=class{cache=new Map;get(e,t){let n=ks(e,t),o=this.cache.get(n);if(o)return o.hitCount++,o}set(e,t,n){if(this.cache.size>=Mb){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let o=ks(e,t);this.cache.set(o,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(ks(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 Pb=new Set(["read","search","instructions","think","todo","memory","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function Qt(r){return Pb.has(r)}var tu=`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.
274
281
 
275
282
  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).
276
283
 
@@ -292,7 +299,7 @@ DANGEROUS operations (SHOULD be blocked):
292
299
  - Running commands with sudo/admin privileges
293
300
  - Downloading and executing unknown scripts
294
301
 
295
- Respond ONLY with XML. No other text.`;async function us(r,e,t,n){let o=Date.now();if(Jt(r))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-o};let s=Vy(t),i=qy(r,e),a=`<transcript>
302
+ Respond ONLY with XML. No other text.`;async function Ts(r,e,t,n){let o=Date.now();if(Qt(r))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-o};let s=Ib(t),i=Eb(r,e),a=`<transcript>
296
303
  ${s}
297
304
  </transcript>
298
305
 
@@ -300,7 +307,7 @@ ${s}
300
307
  ${i}
301
308
  </action>
302
309
 
303
- Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let l=await n({system:Lc,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),u=Uc(l.text);if($c(u)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-o};let d=`<transcript>
310
+ Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let l=await n({system:tu,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),u=ru(l.text);if(nu(u)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-o};let d=`<transcript>
304
311
  ${s}
305
312
  </transcript>
306
313
 
@@ -308,55 +315,55 @@ ${s}
308
315
  ${i}
309
316
  </action>
310
317
 
311
- 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:Lc,messages:[{role:"user",content:d}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=Uc(p.text),g=$c(m),f=Dc(m)??Dc(u)??"classifier decision";return{shouldBlock:g!==!1,reason:f,stage:"thinking",durationMs:Date.now()-o}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-o}}}function Vy(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(`
312
- `)}function qy(r,e){let t=JSON.stringify(e,null,0),n=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${r}
313
- Arguments: ${n}`}function $c(r){let e=r.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function Dc(r){let e=r.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function Uc(r){return r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var Nc={maxConsecutive:3,maxTotal:20};function Fc(){return{consecutiveDenials:0,totalDenials:0}}function ds(r){return{consecutiveDenials:r.consecutiveDenials+1,totalDenials:r.totalDenials+1}}function ps(r){return r.consecutiveDenials===0?r:{...r,consecutiveDenials:0}}function jc(r){return r.consecutiveDenials>=Nc.maxConsecutive||r.totalDenials>=Nc.maxTotal}var Jy=12e4,Zn=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new Qn;denialTracking=Fc();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 u=o.command??o.cmd??"";if(u){let c=Oc(u);if(c.decision==="allow")return{action:"continue"};if(c.decision==="deny")return this.fireDenied(t,n,c.reason),{action:"abort",reason:c.reason}}}if(o){let u=this.classifierCache.get(n,o);if(u)return u.shouldBlock?(this.fireDenied(t,n,`cached: ${u.reason}`),{action:"abort",reason:u.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,n,o);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||Jt(n)?{action:"continue"}:this.handleWorkerAsk(t,n,o);if(this.ruleEngine.getMode()==="auto"){if(Jt(n))return{action:"continue"};let u=jc(this.denialTracking);if(this.classifierLLMCall&&!u)try{let c=this.getRecentMessages?.()??[],d=await us(n,o??{},c,this.classifierLLMCall);if(o&&this.classifierCache.set(n,o,{shouldBlock:d.shouldBlock,reason:d.reason}),!d.shouldBlock)return this.denialTracking=ps(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:d.reason}}};this.denialTracking=ds(this.denialTracking)}catch{}}let a=Ky(),l={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 u=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n,decision:u.decision==="approved"?"approved":"denied"}).catch(()=>{}),u.permissionUpdate&&(this.ruleEngine.applyUpdate(u.permissionUpdate),this.onPermissionUpdate?.(u.permissionUpdate)),u.decision==="approved"?{action:"continue",context:u.updatedInput?{arguments:u.updatedInput}:void 0}:(this.fireDenied(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(Jt(t))return{action:"continue"};if(this.classifierLLMCall)try{let o=this.getRecentMessages?.()??[],s=await us(t,n??{},o,this.classifierLLMCall);return n&&this.classifierCache.set(t,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=ds(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=ps(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"))},Jy);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 Yy="skill",Xy={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete"],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')"].join(`
314
- `)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete)."},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."}},required:["action"]};function Bc(r){return{name:Yy,label:"Skill",description:nb(r),parameters:Xy,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 Qy(r,t,n);case"list":return Zy(r,t);case"view":return eb(r,t);case"create":case"edit":case"patch":case"delete":return tb(r,t);default:return{content:[{type:"text",text:`Unknown action: ${o}. Use invoke, list, view, create, edit, patch, or delete.`}]}}}}}async function Qy(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(u=>u.name).join(", ")||"(none)"}`}]};let s=await r.readSkillContent(n);if(!s){let l=r.listSkills().map(u=>u.name).join(", ");return{content:[{type:"text",text:`Skill "${n}" not found. Available skills: ${l||"(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(l){let u=l instanceof Error?l.message:String(l);return{content:[{type:"text",text:`Skill execution error: ${u}`}],details:{error:u,skillName:n}}}let i=`## Skill: ${n}
318
+ 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:tu,messages:[{role:"user",content:d}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=ru(p.text),g=nu(m),f=ou(m)??ou(u)??"classifier decision";return{shouldBlock:g!==!1,reason:f,stage:"thinking",durationMs:Date.now()-o}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-o}}}function Ib(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(`
319
+ `)}function Eb(r,e){let t=JSON.stringify(e,null,0),n=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${r}
320
+ Arguments: ${n}`}function nu(r){let e=r.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function ou(r){let e=r.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function ru(r){return r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var su={maxConsecutive:3,maxTotal:20};function iu(){return{consecutiveDenials:0,totalDenials:0}}function ws(r){return{consecutiveDenials:r.consecutiveDenials+1,totalDenials:r.totalDenials+1}}function vs(r){return r.consecutiveDenials===0?r:{...r,consecutiveDenials:0}}function au(r){return r.consecutiveDenials>=su.maxConsecutive||r.totalDenials>=su.maxTotal}var Lb=12e4,ro=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new oo;denialTracking=iu();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 u=o.command??o.cmd??"";if(u){let c=eu(u);if(c.decision==="allow")return{action:"continue"};if(c.decision==="deny")return this.fireDenied(t,n,c.reason),{action:"abort",reason:c.reason}}}if(o){let u=this.classifierCache.get(n,o);if(u)return u.shouldBlock?(this.fireDenied(t,n,`cached: ${u.reason}`),{action:"abort",reason:u.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,n,o);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||Qt(n)?{action:"continue"}:this.handleWorkerAsk(t,n,o);if(this.ruleEngine.getMode()==="auto"){if(Qt(n))return{action:"continue"};let u=au(this.denialTracking);if(this.classifierLLMCall&&!u)try{let c=this.getRecentMessages?.()??[],d=await Ts(n,o??{},c,this.classifierLLMCall);if(o&&this.classifierCache.set(n,o,{shouldBlock:d.shouldBlock,reason:d.reason}),!d.shouldBlock)return this.denialTracking=vs(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:d.reason}}};this.denialTracking=ws(this.denialTracking)}catch{}}let a=Ob(),l={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 u=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:n,decision:u.decision==="approved"?"approved":"denied"}).catch(()=>{}),u.permissionUpdate&&(this.ruleEngine.applyUpdate(u.permissionUpdate),this.onPermissionUpdate?.(u.permissionUpdate)),u.decision==="approved"?{action:"continue",context:u.updatedInput?{arguments:u.updatedInput}:void 0}:(this.fireDenied(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(Qt(t))return{action:"continue"};if(this.classifierLLMCall)try{let o=this.getRecentMessages?.()??[],s=await Ts(t,n??{},o,this.classifierLLMCall);return n&&this.classifierCache.set(t,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=ws(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=vs(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"))},Lb);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 $b="skill",Db={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete"],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')"].join(`
321
+ `)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete)."},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."}},required:["action"]};function lu(r){return{name:$b,label:"Skill",description:Bb(r),parameters:Db,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 Ub(r,t,n);case"list":return Nb(r,t);case"view":return Fb(r,t);case"create":case"edit":case"patch":case"delete":return jb(r,t);default:return{content:[{type:"text",text:`Unknown action: ${o}. Use invoke, list, view, create, edit, patch, or delete.`}]}}}}}async function Ub(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(u=>u.name).join(", ")||"(none)"}`}]};let s=await r.readSkillContent(n);if(!s){let l=r.listSkills().map(u=>u.name).join(", ");return{content:[{type:"text",text:`Skill "${n}" not found. Available skills: ${l||"(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(l){let u=l instanceof Error?l.message:String(l);return{content:[{type:"text",text:`Skill execution error: ${u}`}],details:{error:u,skillName:n}}}let i=`## Skill: ${n}
315
322
 
316
323
  `,a=o?`
317
324
 
318
325
  ### User Context
319
326
  ${o}`:"";return{content:[{type:"text",text:`${i}Follow these instructions:
320
327
 
321
- ${s}${a}`}],details:{skillName:n,action:"invoke",mode:"inline"}}}async function Zy(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})`:"";n.push(`- **${o.name}**${i}${s}: ${o.description}`)}return{content:[{type:"text",text:n.join(`
322
- `)}],details:{action:"list",count:t.skills.length}}}async function eb(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}
328
+ ${s}${a}`}],details:{skillName:n,action:"invoke",mode:"inline"}}}async function Nb(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})`:"";n.push(`- **${o.name}**${i}${s}: ${o.description}`)}return{content:[{type:"text",text:n.join(`
329
+ `)}],details:{action:"list",count:t.skills.length}}}async function Fb(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}
323
330
  `,t.content];return t.referenceFiles&&t.referenceFiles.length>0&&n.push(`
324
331
  ### Reference Files
325
332
  ${t.referenceFiles.map(o=>`- ${o}`).join(`
326
333
  `)}`),{content:[{type:"text",text:n.join(`
327
- `)}],details:{action:"view",name:t.name}}}async function tb(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,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}}}function nb(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.";if(e.length===0)return t;let n=e.slice(0,50).map(o=>`- ${o.name}: ${o.description??"(no description)"}`).join(`
334
+ `)}],details:{action:"view",name:t.name}}}async function jb(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,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}}}function Bb(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.";if(e.length===0)return t;let n=e.slice(0,50).map(o=>`- ${o.name}: ${o.description??"(no description)"}`).join(`
328
335
  `);return`${t}
329
336
 
330
337
  Available skills:
331
- ${n}`}var ob="agent",Wc=["general","explore","plan","code","research","verify"],rb={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
338
+ ${n}`}var Wb="agent",cu=["general","explore","plan","code","research","verify"],Gb={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
332
339
  - general: Full tool access, any task
333
340
  - explore: Read-only codebase exploration (search, read, analyze)
334
341
  - plan: Planning mode (explore + produce plan, no writes)
335
342
  - code: Coding agent with full tool access
336
343
  - research: Web research and information gathering
337
- - 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},Gc=4;function Hc(r){return{name:ob,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:rb,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(!Wc.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${Wc.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=r.currentForkDepth??0;if(n>=Gc)return{content:[{type:"text",text:`Error: maximum fork depth (${Gc}) 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.
344
+ - 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},uu=4;function du(r){return{name:Wb,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:Gb,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(!cu.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${cu.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=r.currentForkDepth??0;if(n>=uu)return{content:[{type:"text",text:`Error: maximum fork depth (${uu}) 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.
338
345
  Agent ID: ${o.agentId}
339
346
  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?`
340
347
 
341
- [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 sb="config",ib={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
348
+ [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 Hb="config",Vb={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
342
349
  - get: Read a config setting
343
350
  - set: Write a config setting
344
351
  - list: List all available settings
345
- - 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"]},Yt=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function zc(r){return{name:sb,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:ib,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(`
346
- `)}],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(Yt.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(`
347
- `)}],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(Yt.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 ab="cron",lb={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:
352
+ - 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"]},Zt=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function pu(r){return{name:Hb,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:Vb,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(`
353
+ `)}],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(Zt.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(`
354
+ `)}],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(Zt.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 zb="cron",qb={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:
348
355
  - Cron: '0 9 * * *' (every day at 9am)
349
356
  - Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
350
- 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"]},Vc=50;function qc(r){return{name:ab,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:lb,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>=Vc)return{content:[{type:"text",text:`Error: maximum ${Vc} 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:ms(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(`
351
- `)}],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:ms(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.
352
- ${ms(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 ms(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(`
353
- `)}var cb="monitor",ub={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 Kc(r){return{name:cb,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(`
354
- `),parameters:ub,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:
357
+ 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"]},mu=50;function gu(r){return{name:zb,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:qb,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>=mu)return{content:[{type:"text",text:`Error: maximum ${mu} 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:xs(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(`
358
+ `)}],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:xs(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.
359
+ ${xs(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 xs(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(`
360
+ `)}var Kb="monitor",Jb={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 fu(r){return{name:Kb,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(`
361
+ `),parameters:Jb,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:
355
362
  ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.eventCount}, timeout: ${l.timeoutSeconds}s)`).join(`
356
- `)}`}],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 db="team",pb={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 Jc(r){return{name:db,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:pb,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(`
363
+ `)}`}],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 Yb="team",Xb={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 hu(r){return{name:Yb,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:Xb,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(`
357
364
  `)}],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(`
358
365
  `)}],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 l=a.tools?` [tools: ${a.tools.join(", ")}]`:"",u=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",c=s[a.name],d=a.isActive===!1?" (idle)":" (active)";if(c){let p=[];if(c.runningFor&&p.push(`running ${Math.round(c.runningFor/1e3)}s`),c.lastToolCall&&p.push(`tool: ${c.lastToolCall}`),c.idleFor!==void 0&&c.idleFor>5&&p.push(`idle ${c.idleFor}s`),c.mediaProgress){let m=c.mediaProgress;p.push(`${m.mediaType} ${m.percent}% [${m.status}] taskId=${m.taskId}${m.provider?` provider=${m.provider}`:""}`)}p.length&&(d=` (${p.join(", ")})`)}i.push(` - ${a.name} (${a.role})${l}${u}${d}`)}return{content:[{type:"text",text:i.join(`
359
- `)}],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 gb="mcp",fb={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:
366
+ `)}],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 Zb="mcp",ek={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:
360
367
  - list_servers: List configured MCP servers, their status and capabilities
361
368
  - list_tools: List tools provided by a specific server
362
369
  - call_tool: Execute a tool on an MCP server
@@ -365,14 +372,14 @@ ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.
365
372
  - list_prompts: List prompts available from a server
366
373
  - get_prompt: Get a specific prompt with arguments
367
374
  - authenticate: Initiate OAuth authentication with a server
368
- - 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 Yc(r){return{name:gb,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).
375
+ - 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 yu(r){return{name:Zb,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).
369
376
 
370
- 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:fb,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=hb(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let l=[];i.capabilities.tools?.listChanged&&l.push("tools/listChanged"),i.capabilities.resources?.subscribe&&l.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&l.push("prompts/listChanged"),l.length>0&&s.push(` Capabilities: ${l.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
371
- `)}],details:{type:"mcp",action:"list_servers",count:o.length}}}case"list_tools":{if(!t.server)return Z("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=yb(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(`
372
- `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:o.length}}}case"call_tool":{if(!t.server)return Z("server is required for call_tool.");if(!t.toolName)return Z("toolName is required for call_tool.");let 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(`
373
- `)}],details:{type:"mcp",action:"list_resources",count:o.length,server:t.server}}}case"read_resource":{if(!t.server)return Z("server is required for read_resource.");if(!t.uri)return Z("uri is required for read_resource.");let 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?` (${bb(i.blobSize)})`:""}]`}):i.text&&s.push({type:"text",text:i.text});return s.length===0&&s.push({type:"text",text:"(empty content)"}),{content:s,details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}}}case"list_prompts":{if(!t.server)return Z("server is required for list_prompts.");if(!r.listPrompts)return Z("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(l=>`${l.name}${l.required?" (required)":""}${l.description?`: ${l.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
374
- `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:o.length}}}case"get_prompt":{if(!t.server)return Z("server is required for get_prompt.");if(!t.promptName)return Z("promptName is required for get_prompt.");if(!r.getPrompt)return Z("Prompt retrieval not supported by the current MCP host.");let o=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,l])=>[a,String(l)])):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(`
375
- `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return Z("server is required for authenticate.");let o=await r.authenticate(t.server);switch(o.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
377
+ 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:ek,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=tk(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let l=[];i.capabilities.tools?.listChanged&&l.push("tools/listChanged"),i.capabilities.resources?.subscribe&&l.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&l.push("prompts/listChanged"),l.length>0&&s.push(` Capabilities: ${l.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
378
+ `)}],details:{type:"mcp",action:"list_servers",count:o.length}}}case"list_tools":{if(!t.server)return te("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=nk(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(`
379
+ `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:o.length}}}case"call_tool":{if(!t.server)return te("server is required for call_tool.");if(!t.toolName)return te("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(`
380
+ `)}],details:{type:"mcp",action:"list_resources",count:o.length,server:t.server}}}case"read_resource":{if(!t.server)return te("server is required for read_resource.");if(!t.uri)return te("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?` (${ok(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 te("server is required for list_prompts.");if(!r.listPrompts)return te("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(l=>`${l.name}${l.required?" (required)":""}${l.description?`: ${l.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
381
+ `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:o.length}}}case"get_prompt":{if(!t.server)return te("server is required for get_prompt.");if(!t.promptName)return te("promptName is required for get_prompt.");if(!r.getPrompt)return te("Prompt retrieval not supported by the current MCP host.");let o=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,l])=>[a,String(l)])):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(`
382
+ `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return te("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}".
376
383
 
377
384
  Please open this URL in your browser:
378
385
  ${o.authUrl}
@@ -380,30 +387,30 @@ ${o.authUrl}
380
387
  ${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.
381
388
  Required scopes: ${o.requiredScopes?.join(", ")||"unknown"}
382
389
 
383
- `+(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 Z("server is required for manage_server.");if(!t.manageAction)return Z("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!r.addServer)return Z("Server addition not supported by the current MCP host.");if(!t.config)return Z("config is required for manage_server add.");let o=await r.addServer(t.server,t.config);return Xt("add",t.server,o)}case"remove":{if(!r.removeServer)return Z("Server removal not supported by the current MCP host.");let o=await r.removeServer(t.server);return Xt("remove",t.server,o)}case"restart":{if(!r.restartServer)return Z("Server restart not supported by the current MCP host.");let o=await r.restartServer(t.server);return Xt("restart",t.server,o)}case"health_check":{if(!r.healthCheck)return Z("Health check not supported by the current MCP host.");let o=await r.healthCheck(t.server);return Xt("health_check",t.server,o)}case"enable":case"disable":{if(!r.setServerEnabled)return Z("Server enable/disable not supported by the current MCP host.");let o=await r.setServerEnabled(t.server,t.manageAction==="enable");return Xt(t.manageAction,t.server,o)}default:return Z(`Unknown manageAction: ${t.manageAction}`)}}default:return Z(`Unknown action: "${t.action}".`)}}}}function Z(r){return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"mcp",error:r}}}function hb(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 yb(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 bb(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function Xt(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(`
384
- `)}],details:{type:"mcp",action:"manage_server",manageAction:r,server:e,success:t.success}}}var kb="checkpoint",Tb={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"]},Xc=/^[0-9a-fA-F]{4,64}$/;function Qc(r){return{name:kb,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:Tb,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}
390
+ `+(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 te("server is required for manage_server.");if(!t.manageAction)return te("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!r.addServer)return te("Server addition not supported by the current MCP host.");if(!t.config)return te("config is required for manage_server add.");let o=await r.addServer(t.server,t.config);return en("add",t.server,o)}case"remove":{if(!r.removeServer)return te("Server removal not supported by the current MCP host.");let o=await r.removeServer(t.server);return en("remove",t.server,o)}case"restart":{if(!r.restartServer)return te("Server restart not supported by the current MCP host.");let o=await r.restartServer(t.server);return en("restart",t.server,o)}case"health_check":{if(!r.healthCheck)return te("Health check not supported by the current MCP host.");let o=await r.healthCheck(t.server);return en("health_check",t.server,o)}case"enable":case"disable":{if(!r.setServerEnabled)return te("Server enable/disable not supported by the current MCP host.");let o=await r.setServerEnabled(t.server,t.manageAction==="enable");return en(t.manageAction,t.server,o)}default:return te(`Unknown manageAction: ${t.manageAction}`)}}default:return te(`Unknown action: "${t.action}".`)}}}}function te(r){return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"mcp",error:r}}}function tk(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 nk(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 ok(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function en(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(`
391
+ `)}],details:{type:"mcp",action:"manage_server",manageAction:r,server:e,success:t.success}}}var rk="checkpoint",sk={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"]},bu=/^[0-9a-fA-F]{4,64}$/;function ku(r){return{name:rk,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:sk,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}
385
392
  Message: ${n.checkpoint.message}
386
393
  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(`
387
- `)}],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(!Xc.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(!Xc.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 Ie from"node:fs";import*as Qt from"node:path";function Zc(r,e){let t=Ni(e);return{createCheckpoint:async n=>{try{Ie.mkdirSync(t,{recursive:!0});let{execSync:o}=await import("node:child_process"),s=Qt.join(t,".git");Ie.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"})),Ie.cpSync(r,t,{recursive:!0,filter:u=>!u.includes(".git")&&!u.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(),l=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:l}}}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(!Ie.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(`
388
- `).map(a=>{let[l="",u="",...c]=a.split("|");return{id:l,timestamp:u,message:c.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)for(let i of o){s(`git checkout ${n} -- "${i}"`,{cwd:t,stdio:"pipe"});let a=Qt.join(t,i),l=Qt.join(r,i);Ie.existsSync(a)&&Ie.cpSync(a,l,{recursive:!0})}else s(`git checkout ${n} -- .`,{cwd:t,stdio:"pipe"}),Ie.cpSync(t,r,{recursive:!0,filter:i=>!i.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}}}}}import{spawn as fs}from"node:child_process";import{createInterface as to}from"node:readline";import{resolve as Pb,join as en}from"node:path";import{createServer as Ib}from"node:net";import{createWriteStream as Eb,mkdirSync as Ob}from"node:fs";import{tmpdir as Lb}from"node:os";import{createInterface as wb}from"node:readline";var vb=1,xb=1e4,rt=class{pendingRpcs=new Map;rl=null;onNotification=null;attach(e,t){this.onNotification=t??null,this.rl=wb({input:e.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.rl.on("line",n=>{let o=n.trim();if(!o)return;let s;try{s=JSON.parse(o)}catch{return}if("id"in s&&typeof s.id=="number"){let i=this.pendingRpcs.get(s.id);if(i){clearTimeout(i.timer),this.pendingRpcs.delete(s.id);let a=s;a.error?i.reject(new Error(a.error.message)):i.resolve(a.result)}return}"method"in s&&!("id"in s)&&this.onNotification?.(s.method,s.params)})}detach(){this.rl?.close(),this.rl=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=vb++,i={jsonrpc:"2.0",id:s,method:t,params:n};return new Promise((a,l)=>{let u=setTimeout(()=>{this.pendingRpcs.delete(s),l(new Error(`ACP RPC timeout: ${t} (${o}ms)`))},o);this.pendingRpcs.set(s,{resolve:a,reject:l,timer:u});try{e.stdin.write(`${JSON.stringify(i)}
389
- `)}catch(c){clearTimeout(u),this.pendingRpcs.delete(s),l(c instanceof Error?c:new Error(String(c)))}})}async initialize(e){let t=await this.sendRpc(e,"initialize",{protocolVersion:1,clientInfo:{name:"qlogicagent",version:"1.0.0"}},xb),n=t?.capabilities??{};return{protocolVersion:typeof t?.protocolVersion=="number"?t.protocolVersion:0,capabilities:{prompts:n.prompts!==!1,supportsResume:n.supportsResume===!0||n.resume===!0},serverInfo:t?.serverInfo}}async createSession(e,t){let n={workspaceRoot:t.workspaceRoot};t.mcpServers?.length&&(n.mcpServers=t.mcpServers),t.systemPrompt&&(n.systemPrompt=t.systemPrompt);let o=await this.sendRpc(e,"session/new",n);return{id:typeof o?.id=="string"?o.id:"unknown"}}async sendPrompt(e,t,n,o=3e5){let s=await this.sendRpc(e,"prompt",{sessionId:t,content:[{type:"text",text:n}]},o);return{content:Array.isArray(s?.content)?s.content:[{type:"text",text:String(s??"")}],usage:s?.usage}}async resumeSession(e,t,n){let o={sessionId:t};n?.workspaceRoot&&(o.workspaceRoot=n.workspaceRoot),n?.mcpServers?.length&&(o.mcpServers=n.mcpServers);let s=await this.sendRpc(e,"session/resume",o,3e4);return{id:typeof s?.id=="string"?s.id:t}}async closeSession(e,t){try{await this.sendRpc(e,"session/close",{sessionId:t},5e3)}catch{}}static translateNotification(e,t){let n=t;switch(e){case"message":{if(!n)return null;let o=n.type;return o==="text"||!o?{method:"turn.delta",params:{text:n.content??n.text??""}}:o==="finish"||o==="end"?{method:"turn.end",params:{content:n.content??n.text??"",usage:n.usage}}:null}case"usage_update":return{method:"turn.usage_update",params:n??{}};case"notifications/progress":case"progress":return{method:"turn.exec_progress",params:{status:n?.message??n?.status??"working",percent:n?.percent}};default:return null}}};var Zt=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 tu}from"node:child_process";import{platform as Sb}from"node:os";var gs={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",acpArgs:["--acp"],defaultCliPath:"npx @anthropic-ai/claude-code@qwen",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},goose:{id:"goose",name:"Goose",cliCommand:"goose",acpArgs:["acp"],authRequired:!1,skillsDirs:[".goose/skills"],supportsBaseUrlOverride:!0},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:"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","--stdio"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},auggie:{id:"auggie",name:"Auggie",cliCommand:"auggie",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},droid:{id:"droid",name:"Droid",cliCommand:"droid",acpArgs:["exec","--output-format","acp"],authRequired:!0,skillsDirs:[".factory/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},vibe:{id:"vibe",name:"Vibe (Mistral)",cliCommand:"vibe-acp",acpArgs:[],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0}},Rb=["general","explore","plan","code","research","verify"];function _b(){return Rb.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 Cb=Sb()==="win32";function eu(r){try{let e=Cb?`where ${r}`:`which ${r}`;return tu(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function Ab(r){try{return tu(`"${r}" --version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var Mb=6e4,eo=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<Mb)return this.cache.agents;let t=[];t.push(..._b());for(let n of Object.values(gs))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=eu(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=Ab(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=eu(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=gs[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 $b=1;function Db(r,e){return{jsonrpc:"2.0",id:$b++,method:r,params:e}}var Ub=["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 Nb(r){let e={};for(let t of Ub)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 hs=2,Fb=3e3,gt=3,nu=5e3;function jb(r){return new Promise(e=>setTimeout(e,r))}var ft=class r{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=Pb(en(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=en(t,"dist","cli.js"),this.mcpBridgeScriptPath=en(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=Nb(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=fs(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}),to({input:i.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",u=>{let c=u.trim();if(c)try{let d=JSON.parse(c);if("id"in d&&typeof d.id=="number"){let p=a.get(d.id);if(p){clearTimeout(p.timer),a.delete(d.id);let m=d;m.error?p.reject(new Error(m.error.message)):p.resolve(m.result)}}if("method"in d&&!("id"in d)){let p=d;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: ${c.slice(0,200)}`)}}),i.stderr&&to({input:i.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",c=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${c}`)}),i.on("exit",(u,c)=>{o.state!=="killed"&&(o.state=u===0?"completed":"failed"),o.endedAt=Date.now(),u!==0&&!o.error&&(o.error=`Process exited with code ${u} (signal: ${c})`);for(let[p,m]of a)clearTimeout(m.timer),m.reject(new Error(`Agent process exited (code=${u})`)),a.delete(p);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,u,c),this.slog("info",e.memberId,"exit",`exited (code=${u}, signal=${c})`)}),i.on("error",u=>{o.state="failed",o.error=u.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",u.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let u=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 c=u;c&&typeof c.sessionId=="string"&&(o.sessionId=c.sessionId)}catch(u){throw o.state="failed",o.error=`Initialize handshake failed: ${u instanceof Error?u.message:String(u)}`,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),u=(a.content?.map(c=>c.text).filter(Boolean)??[]).join(`
390
- `);o.handle.resultText=u,a.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(a.usage),s={content:u}}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=Db(t,n);return new Promise((a,l)=>{let u=setTimeout(()=>{s.pendingRpc.delete(i.id),l(new Error(`RPC timeout: ${t} (${o}ms)`))},o);s.pendingRpc.set(i.id,{resolve:a,reject:l,timer:u});try{s.child.stdin.write(`${JSON.stringify(i)}
394
+ `)}],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(!bu.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(!bu.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 be from"node:fs";import*as gt from"node:path";function Tu(r,e){let t=Ji(e);return{createCheckpoint:async n=>{try{be.mkdirSync(t,{recursive:!0});let{execSync:o}=await import("node:child_process"),s=gt.join(t,".git");be.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"})),be.cpSync(r,t,{recursive:!0,filter:u=>!u.includes(".git")&&!u.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(),l=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:l}}}catch(o){return{success:!1,error:o.message}}},listCheckpoints:async()=>{try{let{execSync:n}=await import("node:child_process"),o=gt.join(t,".git");if(!be.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(`
395
+ `).map(a=>{let[l="",u="",...c]=a.split("|");return{id:l,timestamp:u,message:c.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=gt.join(t,i),l=gt.join(r,i);be.existsSync(a)&&be.cpSync(a,l,{recursive:!0})}}else{s(`git checkout ${n} -- .`,{cwd:t,stdio:"pipe"});let i=be.readdirSync(r);for(let a of i){if(a===".git"||a==="node_modules")continue;let l=gt.join(r,a);be.rmSync(l,{recursive:!0,force:!0})}be.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}}}}}import{spawn as _s}from"node:child_process";import{createInterface as io}from"node:readline";import{resolve as fk,join as nn}from"node:path";import{createServer as hk}from"node:net";import{createWriteStream as yk,mkdirSync as bk}from"node:fs";import{tmpdir as kk}from"node:os";import{createInterface as ik}from"node:readline";var ak=1,lk=1e4,rt=class{pendingRpcs=new Map;rl=null;onNotification=null;attach(e,t){this.onNotification=t??null,this.rl=ik({input:e.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.rl.on("line",n=>{let o=n.trim();if(!o)return;let s;try{s=JSON.parse(o)}catch{return}if("id"in s&&typeof s.id=="number"){let i=this.pendingRpcs.get(s.id);if(i){clearTimeout(i.timer),this.pendingRpcs.delete(s.id);let a=s;a.error?i.reject(new Error(a.error.message)):i.resolve(a.result)}return}"method"in s&&!("id"in s)&&this.onNotification?.(s.method,s.params)})}detach(){this.rl?.close(),this.rl=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=ak++,i={jsonrpc:"2.0",id:s,method:t,params:n};return new Promise((a,l)=>{let u=setTimeout(()=>{this.pendingRpcs.delete(s),l(new Error(`ACP RPC timeout: ${t} (${o}ms)`))},o);this.pendingRpcs.set(s,{resolve:a,reject:l,timer:u});try{e.stdin.write(`${JSON.stringify(i)}
396
+ `)}catch(c){clearTimeout(u),this.pendingRpcs.delete(s),l(c instanceof Error?c:new Error(String(c)))}})}async initialize(e){let t=await this.sendRpc(e,"initialize",{protocolVersion:1,clientInfo:{name:"qlogicagent",version:"1.0.0"}},lk),n=t?.capabilities??{};return{protocolVersion:typeof t?.protocolVersion=="number"?t.protocolVersion:0,capabilities:{prompts:n.prompts!==!1,supportsResume:n.supportsResume===!0||n.resume===!0},serverInfo:t?.serverInfo}}async createSession(e,t){let n={workspaceRoot:t.workspaceRoot};t.mcpServers?.length&&(n.mcpServers=t.mcpServers),t.systemPrompt&&(n.systemPrompt=t.systemPrompt);let o=await this.sendRpc(e,"session/new",n);return{id:typeof o?.id=="string"?o.id:"unknown"}}async sendPrompt(e,t,n,o=3e5){let s=await this.sendRpc(e,"prompt",{sessionId:t,content:[{type:"text",text:n}]},o);return{content:Array.isArray(s?.content)?s.content:[{type:"text",text:String(s??"")}],usage:s?.usage}}async resumeSession(e,t,n){let o={sessionId:t};n?.workspaceRoot&&(o.workspaceRoot=n.workspaceRoot),n?.mcpServers?.length&&(o.mcpServers=n.mcpServers);let s=await this.sendRpc(e,"session/resume",o,3e4);return{id:typeof s?.id=="string"?s.id:t}}async closeSession(e,t){try{await this.sendRpc(e,"session/close",{sessionId:t},5e3)}catch{}}static translateNotification(e,t){let n=t;switch(e){case"message":{if(!n)return null;let o=n.type;return o==="text"||!o?{method:"turn.delta",params:{text:n.content??n.text??""}}:o==="finish"||o==="end"?{method:"turn.end",params:{content:n.content??n.text??"",usage:n.usage}}:null}case"usage_update":return{method:"turn.usage_update",params:n??{}};case"notifications/progress":case"progress":return{method:"turn.exec_progress",params:{status:n?.message??n?.status??"working",percent:n?.percent}};default:return null}}};var tn=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 vu}from"node:child_process";import{platform as ck}from"node:os";var Ss={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",acpArgs:["--acp"],defaultCliPath:"npx @anthropic-ai/claude-code@qwen",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},goose:{id:"goose",name:"Goose",cliCommand:"goose",acpArgs:["acp"],authRequired:!1,skillsDirs:[".goose/skills"],supportsBaseUrlOverride:!0},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:"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","--stdio"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},auggie:{id:"auggie",name:"Auggie",cliCommand:"auggie",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},droid:{id:"droid",name:"Droid",cliCommand:"droid",acpArgs:["exec","--output-format","acp"],authRequired:!0,skillsDirs:[".factory/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},vibe:{id:"vibe",name:"Vibe (Mistral)",cliCommand:"vibe-acp",acpArgs:[],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0}},uk=["general","explore","plan","code","research","verify"];function dk(){return uk.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 pk=ck()==="win32";function wu(r){try{let e=pk?`where ${r}`:`which ${r}`;return vu(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function mk(r){try{return vu(`"${r}" --version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var gk=6e4,so=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<gk)return this.cache.agents;let t=[];t.push(...dk());for(let n of Object.values(Ss))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=wu(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=mk(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=wu(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=Ss[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 Tk=1;function wk(r,e){return{jsonrpc:"2.0",id:Tk++,method:r,params:e}}var vk=["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 xk(r){let e={};for(let t of vk)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 Rs=2,Sk=3e3,ft=3,xu=5e3;function _k(r){return new Promise(e=>setTimeout(e,r))}var ht=class r{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=fk(nn(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=nn(t,"dist","cli.js"),this.mcpBridgeScriptPath=nn(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=xk(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=_s(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}),io({input:i.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",u=>{let c=u.trim();if(c)try{let d=JSON.parse(c);if("id"in d&&typeof d.id=="number"){let p=a.get(d.id);if(p){clearTimeout(p.timer),a.delete(d.id);let m=d;m.error?p.reject(new Error(m.error.message)):p.resolve(m.result)}}if("method"in d&&!("id"in d)){let p=d;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: ${c.slice(0,200)}`)}}),i.stderr&&io({input:i.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",c=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${c}`)}),i.on("exit",(u,c)=>{o.state!=="killed"&&(o.state=u===0?"completed":"failed"),o.endedAt=Date.now(),u!==0&&!o.error&&(o.error=`Process exited with code ${u} (signal: ${c})`);for(let[p,m]of a)clearTimeout(m.timer),m.reject(new Error(`Agent process exited (code=${u})`)),a.delete(p);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,u,c),this.slog("info",e.memberId,"exit",`exited (code=${u}, signal=${c})`)}),i.on("error",u=>{o.state="failed",o.error=u.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",u.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let u=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 c=u;c&&typeof c.sessionId=="string"&&(o.sessionId=c.sessionId)}catch(u){throw o.state="failed",o.error=`Initialize handshake failed: ${u instanceof Error?u.message:String(u)}`,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),u=(a.content?.map(c=>c.text).filter(Boolean)??[]).join(`
397
+ `);o.handle.resultText=u,a.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(a.usage),s={content:u}}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=wk(t,n);return new Promise((a,l)=>{let u=setTimeout(()=>{s.pendingRpc.delete(i.id),l(new Error(`RPC timeout: ${t} (${o}ms)`))},o);s.pendingRpc.set(i.id,{resolve:a,reject:l,timer:u});try{s.child.stdin.write(`${JSON.stringify(i)}
391
398
  `)}catch(c){clearTimeout(u),s.pendingRpc.delete(i.id),l(c instanceof Error?c:new Error(String(c)))}})}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,l=n?.timeout??0,u=Date.now(),c=l>0?l:1440*60*1e3,d=this.sendRpc(e,"thread.turn",s,c),p=setInterval(async()=>{if(l>0&&Date.now()-u>l){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 d;clearInterval(p),o.handle.state="completed",o.handle.endedAt=Date.now();let g=m;return g&&typeof g.content=="string"&&(o.handle.resultText=g.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()}})+`
392
- `;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<=hs;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=Fb*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${hs} after ${i}ms`),await jb(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 ${hs+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=fs(s.cliPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});t.pid=a.pid??-1;let l=new Map,u=new rt,c=new Zt,{server:d,pipePath:p}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=p;let m;if(this.callbacks.sessionDir)try{Ob(this.callbacks.sessionDir,{recursive:!0}),m=Eb(en(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}this.processes.set(e.memberId,{handle:t,child:a,pendingRpc:l,acpAdapter:u,usageTracker:c,ipcServer:d,ipcPath:p,stderrStream:m}),u.attach(a,(g,f)=>{g==="usage_update"&&c.onUsageUpdate(f);let b=rt.translateNotification(g,f);b?(this.captureChildProgress(e.memberId,b.method,b.params),this.callbacks.onNotification?.(e.memberId,b.method,b.params)):(this.captureChildProgress(e.memberId,g,f),this.callbacks.onNotification?.(e.memberId,g,f))}),a.stderr&&to({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",f=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${f}`),m?.write(`${new Date().toISOString()} ${f}
393
- `)}),a.on("exit",(g,f)=>{u.detach();let b=t.state;if(b!=="killed"&&b!=="completed"&&g!==0){let k=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(k<gt){let x=nu*2**k;this.slog("warn",e.memberId,"crash",`crashed (code=${g}), restarting ${k+1}/${gt} after ${x}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${g}, signal=${f}), restarting`,retriesLeft:gt-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)}`)})},x);return}}b!=="killed"&&(t.state=g===0?"completed":"failed"),t.endedAt=Date.now(),g!==0&&!t.error&&(t.error=`ACP process exited with code ${g} (signal: ${f})`),this.callbacks.onStateChange?.(e.memberId,t.state),this.callbacks.onExit?.(e.memberId,g,f),this.slog("info",e.memberId,"exit",`ACP exited (code=${g}, signal=${f})`)}),a.on("error",g=>{u.detach(),t.state="failed",t.error=g.message,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:g.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",g.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let g=await u.initialize(a);t.state="ready",t.supportsResume=g.capabilities.supportsResume===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${g.protocolVersion}, resume=${t.supportsResume}, pid=${t.pid})`);try{let f={workspaceRoot:e.cwd},b=[...e.mcpServers??[]],h=this.processes.get(e.memberId);h?.ipcPath&&b.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:h.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),b.length>0&&(f.mcpServers=b),e.systemPrompt&&(f.systemPrompt=e.systemPrompt);let k=await u.createSession(a,f);t.sessionId=k.id,this.slog("info",e.memberId,"session",`session created (id=${k.id})`)}catch(f){this.slog("warn",e.memberId,"session",`session creation failed: ${f instanceof Error?f.message:String(f)}`)}this.startHeartbeat(e.memberId,f=>{this.slog("warn",f,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(f,"agents.error",{agentId:f,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${r.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(f)})}catch(g){throw t.state="failed",t.error=`ACP handshake failed: ${g instanceof Error?g.message:String(g)}`,t.endedAt=Date.now(),u.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()}`:en(Lb(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),o=Ib(s=>{let i="";s.on("data",a=>{i+=a.toString();let l;for(;(l=i.indexOf(`
399
+ `;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<=Rs;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=Sk*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${Rs} after ${i}ms`),await _k(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 ${Rs+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=_s(s.cliPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});t.pid=a.pid??-1;let l=new Map,u=new rt,c=new tn,{server:d,pipePath:p}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=p;let m;if(this.callbacks.sessionDir)try{bk(this.callbacks.sessionDir,{recursive:!0}),m=yk(nn(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}this.processes.set(e.memberId,{handle:t,child:a,pendingRpc:l,acpAdapter:u,usageTracker:c,ipcServer:d,ipcPath:p,stderrStream:m}),u.attach(a,(g,f)=>{g==="usage_update"&&c.onUsageUpdate(f);let b=rt.translateNotification(g,f);b?(this.captureChildProgress(e.memberId,b.method,b.params),this.callbacks.onNotification?.(e.memberId,b.method,b.params)):(this.captureChildProgress(e.memberId,g,f),this.callbacks.onNotification?.(e.memberId,g,f))}),a.stderr&&io({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",f=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${f}`),m?.write(`${new Date().toISOString()} ${f}
400
+ `)}),a.on("exit",(g,f)=>{u.detach();let b=t.state;if(b!=="killed"&&b!=="completed"&&g!==0){let w=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(w<ft){let _=xu*2**w;this.slog("warn",e.memberId,"crash",`crashed (code=${g}), restarting ${w+1}/${ft} after ${_}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${g}, signal=${f}), restarting`,retriesLeft:ft-w-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,n,w+1).catch(y=>{this.slog("warn",e.memberId,"restart",`failed: ${y instanceof Error?y.message:String(y)}`)})},_);return}}b!=="killed"&&(t.state=g===0?"completed":"failed"),t.endedAt=Date.now(),g!==0&&!t.error&&(t.error=`ACP process exited with code ${g} (signal: ${f})`),this.callbacks.onStateChange?.(e.memberId,t.state),this.callbacks.onExit?.(e.memberId,g,f),this.slog("info",e.memberId,"exit",`ACP exited (code=${g}, signal=${f})`)}),a.on("error",g=>{u.detach(),t.state="failed",t.error=g.message,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:g.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",g.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let g=await u.initialize(a);t.state="ready",t.supportsResume=g.capabilities.supportsResume===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${g.protocolVersion}, resume=${t.supportsResume}, pid=${t.pid})`);try{let f={workspaceRoot:e.cwd},b=[...e.mcpServers??[]],T=this.processes.get(e.memberId);T?.ipcPath&&b.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:T.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),b.length>0&&(f.mcpServers=b),e.systemPrompt&&(f.systemPrompt=e.systemPrompt);let w=await u.createSession(a,f);t.sessionId=w.id,this.slog("info",e.memberId,"session",`session created (id=${w.id})`)}catch(f){this.slog("warn",e.memberId,"session",`session creation failed: ${f instanceof Error?f.message:String(f)}`)}this.startHeartbeat(e.memberId,f=>{this.slog("warn",f,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(f,"agents.error",{agentId:f,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${r.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(f)})}catch(g){throw t.state="failed",t.error=`ACP handshake failed: ${g instanceof Error?g.message:String(g)}`,t.endedAt=Date.now(),u.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()}`:nn(kk(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),o=hk(s=>{let i="";s.on("data",a=>{i+=a.toString();let l;for(;(l=i.indexOf(`
394
401
  `))!==-1;){let u=i.slice(0,l).trim();i=i.slice(l+1),u&&this.handleMcpIpcMessage(e,u,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"}})+`
395
402
  `;try{n.write(a)}catch{}return}this.callbacks.onMcpToolCall(e,s,i).then(a=>{let l=JSON.stringify({jsonrpc:"2.0",id:o.id,result:a})+`
396
403
  `;try{n.write(l)}catch{}}).catch(a=>{let l=JSON.stringify({jsonrpc:"2.0",id:o.id,error:{code:-32603,message:a instanceof Error?a.message:String(a)}})+`
397
404
  `;try{n.write(l)}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}`}})+`
398
- `;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,l=s?.stderrStream;this.processes.delete(e.memberId);try{let u={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()},c=e.external,d=[...c.acpArgs];a&&(t.QLOGICAGENT_PARENT_RPC=a);let p=fs(c.cliPath,d,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!1});u.pid=p.pid??-1;let m=new Map,g=new rt,f=new Zt;this.processes.set(e.memberId,{handle:u,child:p,pendingRpc:m,acpAdapter:g,usageTracker:f,ipcServer:i,ipcPath:a,stderrStream:l,runtimeRestartCount:n}),g.attach(p,(k,x)=>{k==="usage_update"&&f.onUsageUpdate(x);let R=rt.translateNotification(k,x);R?(this.captureChildProgress(e.memberId,R.method,R.params),this.callbacks.onNotification?.(e.memberId,R.method,R.params)):(this.captureChildProgress(e.memberId,k,x),this.callbacks.onNotification?.(e.memberId,k,x))}),p.stderr&&to({input:p.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",x=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${x}`),l?.write(`${new Date().toISOString()} ${x}
399
- `)}),p.on("exit",(k,x)=>{g.detach();let R=u.state;if(R!=="killed"&&R!=="completed"&&k!==0){let F=this.processes.get(e.memberId)?.runtimeRestartCount??n;if(F<gt){let U=nu*2**F;this.slog("warn",e.memberId,"crash",`crashed again (code=${k}), restart ${F+1}/${gt}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${k}), restarting`,retriesLeft:gt-F-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,t,F+1).catch(D=>{this.slog("warn",e.memberId,"restart",`failed: ${D instanceof Error?D.message:String(D)}`)})},U);return}}R!=="killed"&&(u.state=k===0?"completed":"failed"),u.endedAt=Date.now(),k!==0&&!u.error&&(u.error=`ACP process exited with code ${k} (signal: ${x})`),this.callbacks.onStateChange?.(e.memberId,u.state),this.callbacks.onExit?.(e.memberId,k,x)}),p.on("error",k=>{g.detach(),u.state="failed",u.error=k.message,u.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let b=await g.initialize(p);u.state="ready",u.supportsResume=b.capabilities.supportsResume===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${n}, protocol=${b.protocolVersion}, resume=${u.supportsResume}, pid=${u.pid})`);let h=[...e.mcpServers??[]];a&&h.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(u.supportsResume&&u.sessionId){let k=await g.resumeSession(p,u.sessionId,{workspaceRoot:e.cwd,mcpServers:h.length>0?h:void 0});u.sessionId=k.id,this.slog("info",e.memberId,"session",`session resumed (id=${u.sessionId})`)}else{let k={workspaceRoot:e.cwd};h.length>0&&(k.mcpServers=h),e.systemPrompt&&(k.systemPrompt=e.systemPrompt);let x=await g.createSession(p,k);u.sessionId=x.id,this.slog("info",e.memberId,"session",`new session on restart (id=${u.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(u){let c=this.processes.get(e.memberId);c&&(c.handle.state="failed",c.handle.error=`Runtime restart failed: ${u instanceof Error?u.message:String(u)}`,c.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: ${u instanceof Error?u.message:String(u)}`,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 iu}from"node:path";import{chmod as Yb}from"node:fs/promises";import{readFile as Bb,writeFile as Wb,mkdir as Gb,rename as Hb,unlink as zb}from"node:fs/promises";import{dirname as Vb,join as ou}from"node:path";import{randomUUID as qb}from"node:crypto";async function Kb(r,e){let t=Vb(r);await Gb(t,{recursive:!0});let n=ou(t,`.tmp-${qb()}`);try{await Wb(n,e,"utf-8"),await Hb(n,r)}catch(o){throw await zb(n).catch(()=>{}),o}}async function ht(r){try{let e=await Bb(r,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function tn(r,e){await Kb(r,JSON.stringify(e,null,2)+`
400
- `)}var Jb="memory.json";function no(){return ou(B(),Jb)}async function ru(){return ht(no())}async function ys(r){let e={...r,savedAt:new Date().toISOString()};await tn(no(),e)}var au="agent-configs.json";function su(){return iu(B(),au)}function Xb(r){return iu(Fe(r),au)}function Qb(){return{agents:{}}}var oo=class{data=Qb();cwd;constructor(e){this.cwd=e}async load(){let e=await ht(su()),t=this.cwd?await ht(Xb(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=su();await tn(e,this.data);try{await Yb(e,384)}catch{}}};import{randomUUID as ok}from"node:crypto";import{execFile as Zb}from"node:child_process";import{promisify as ek}from"node:util";import{join as lu}from"node:path";import{mkdir as tk,rm as nk}from"node:fs/promises";var yt=ek(Zb);async function nn(r){try{let{stdout:e}=await yt("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return null}}async function ro(r,e,t){let n=lu(r,".worktrees");await tk(n,{recursive:!0});let o=lu(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 cu(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 uu(r,e){try{await yt("git",["worktree","remove","--force",e],{cwd:r,encoding:"utf8"})}catch{try{await nk(e,{recursive:!0,force:!0})}catch{}}}async function du(r,e){let{stdout:t}=await yt("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:r,encoding:"utf8"});return t.trim()}var so=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 nn(o);if(!s)throw new Error("Solo Mode requires a git repository");let i=`solo-${ok().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 l=n.map(async(c,d)=>{let p=`${i}-${c}-${d}`,m=`solo/${p}`,g=`${i}:${c}:${d}`,f;try{f=await ro(s,p)}catch(h){this.callbacks.log?.warn(`[solo] worktree creation failed for ${c}: ${h instanceof Error?h.message:String(h)}`);let k={agentId:c,memberId:g,worktreePath:"",worktreeBranch:m,state:"failed",error:`Worktree creation failed: ${h instanceof Error?h.message:String(h)}`};a.agents.push(k);return}let b={agentId:c,memberId:g,worktreePath:f,worktreeBranch:m,state:"pending"};a.agents.push(b);try{b.state="running",this.callbacks.onProgress?.(i,c,"running");let h=this.acpDetector.buildExternalDescriptor(c);if(!h)throw new Error(`Agent ${c} is not available or not ACP-compatible`);await this.processManager.spawn({memberId:g,name:`solo-${c}`,cwd:f,prompt:t,external:h});let k=this.processManager.getHandle(g);if(!k||k.state!=="ready")throw new Error(`Agent ${c} spawn did not reach ready state`);let x=await this.processManager.sendTask(g,t);b.state="completed",b.resultText=typeof x=="string"?x:JSON.stringify(x),b.diff=await cu(f);let R=this.processManager.getUsageTracker(g);if(R?.hasData()){let E=R.getUsage();b.usage={inputTokens:E.inputTokens,outputTokens:E.outputTokens}}this.callbacks.onProgress?.(i,c,"completed"),this.callbacks.log?.info(`[solo] ${c} completed (diff: ${b.diff?"yes":"none"})`)}catch(h){b.state="failed",b.error=h instanceof Error?h.message:String(h),this.callbacks.onProgress?.(i,c,"failed",b.error),this.callbacks.log?.warn(`[solo] ${c} failed: ${b.error}`)}});await Promise.allSettled(l);let u=a.agents.filter(c=>c.state==="completed");if(u.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 ${u.length} results for ${i}`);try{let c=await this.evaluate(a,u);a.evaluation=c,a.state="completed",this.callbacks.onEvaluation?.(i,c)}catch(c){a.state="completed",this.callbacks.log?.warn(`[solo] evaluation failed for ${i}: ${c instanceof Error?c.message:String(c)}`)}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 du(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(`
401
- `),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 uu(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 ik}from"node:crypto";var on=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 rn=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 bs}from"node:path";import{mkdir as rk,readdir as sk}from"node:fs/promises";function pu(r){return bs(Fe(r),"products")}function mu(r,e){return bs(pu(e),r)}function gu(r,e){return bs(mu(r,e),"product-state.json")}async function fu(r,e){let t=mu(r.productId,e);await rk(t,{recursive:!0}),await tn(gu(r.productId,e),r)}async function ks(r,e){return ht(gu(r,e))}async function hu(r){let e=pu(r),t;try{t=await sk(e)}catch{return[]}let n=[];for(let o of t){let s=await ks(o,r);s&&n.push(s)}return n}var sn=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 fu(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 io=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(f=>f.name));for(let f of s)if(!a.has(f.assignee))throw new Error(`Task "${f.taskId}" references unknown instance "${f.assignee}"`);let l=`product-${ik().slice(0,8)}`,u=new on(s),c=new rn(i),d=new sn({onCheckpoint:(f,b)=>this.callbacks.onCheckpointed?.(f,b),getState:()=>{let f=this.sessions.get(l);return f?this.buildPersistedState(f):null},log:this.callbacks.log}),p=await nn(n),m=o.map((f,b)=>({instanceId:`${l}:${f.name}:${b}`,name:f.name,agentId:f.agentId,state:"idle"})),g={productId:l,name:t,cwd:n,phase:"active",instances:m,dag:u,budget:c,checkpoint:d,createdAt:new Date().toISOString(),gitRoot:p};return this.sessions.set(l,g),d.start(n),this.callbacks.log?.info(`[product] created ${l} "${t}" with ${o.length} instances, ${s.length} tasks`),this.scheduleNext(g),l}async resume(e,t){let n=await ks(e,t);if(!n)throw new Error(`Product ${e} not found on disk`);let o=new on(n.tasks);o.restore(n.tasks);let s=new rn({maxTotalTokens:n.budget.maxTotalTokens,maxDuration:n.budget.maxDuration});s.restore(n.budget);let i=new sn({onCheckpoint:(c,d)=>this.callbacks.onCheckpointed?.(c,d),getState:()=>{let c=this.sessions.get(e);return c?this.buildPersistedState(c):null},log:this.callbacks.log}),a=await nn(n.cwd),l=n.instances.map((c,d)=>({instanceId:`${e}:${c.name}:${d}`,name:c.name,agentId:c.agentId,state:"idle"})),u={productId:n.productId,name:n.name,cwd:n.cwd,phase:"active",instances:l,dag:o,budget:s,checkpoint:i,createdAt:n.createdAt,gitRoot:a};this.sessions.set(e,u),i.start(n.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(u)}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 hu(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 c=`${e.productId}-${t.name}-${n.taskId}`;try{i=await ro(e.gitRoot,c),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),l=typeof a=="string"?a:JSON.stringify(a),u=this.processManager.getUsageTracker(o);if(u?.hasData()){let c=u.getUsage();e.budget.addUsage(c.inputTokens,c.outputTokens)}e.dag.markCompleted(n.taskId,l),t.state="completed",this.callbacks.onTaskCompleted?.(e.productId,n.taskId,l);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 yu="memory";var ak=["add","replace","remove","search"],bu={type:"object",properties:{action:{type:"string",enum:ak,description:["The operation to perform:","\u2022 'add' \u2014 Save a concise note about this user (\u2192 local notes, always visible)","\u2022 'replace' \u2014 Update an existing note by matching a substring (\u2192 local notes)","\u2022 'remove' \u2014 Delete a note by matching a substring (\u2192 local notes)","\u2022 'search' \u2014 Search across long-term memory, recalled facts, user profile, and media preferences"].join(`
405
+ `;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,l=s?.stderrStream;this.processes.delete(e.memberId);try{let u={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()},c=e.external,d=[...c.acpArgs];a&&(t.QLOGICAGENT_PARENT_RPC=a);let p=_s(c.cliPath,d,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!1});u.pid=p.pid??-1;let m=new Map,g=new rt,f=new tn;this.processes.set(e.memberId,{handle:u,child:p,pendingRpc:m,acpAdapter:g,usageTracker:f,ipcServer:i,ipcPath:a,stderrStream:l,runtimeRestartCount:n}),g.attach(p,(w,_)=>{w==="usage_update"&&f.onUsageUpdate(_);let y=rt.translateNotification(w,_);y?(this.captureChildProgress(e.memberId,y.method,y.params),this.callbacks.onNotification?.(e.memberId,y.method,y.params)):(this.captureChildProgress(e.memberId,w,_),this.callbacks.onNotification?.(e.memberId,w,_))}),p.stderr&&io({input:p.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",_=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${_}`),l?.write(`${new Date().toISOString()} ${_}
406
+ `)}),p.on("exit",(w,_)=>{g.detach();let y=u.state;if(y!=="killed"&&y!=="completed"&&w!==0){let E=this.processes.get(e.memberId)?.runtimeRestartCount??n;if(E<ft){let D=xu*2**E;this.slog("warn",e.memberId,"crash",`crashed again (code=${w}), restart ${E+1}/${ft}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${w}), restarting`,retriesLeft:ft-E-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,t,E+1).catch(L=>{this.slog("warn",e.memberId,"restart",`failed: ${L instanceof Error?L.message:String(L)}`)})},D);return}}y!=="killed"&&(u.state=w===0?"completed":"failed"),u.endedAt=Date.now(),w!==0&&!u.error&&(u.error=`ACP process exited with code ${w} (signal: ${_})`),this.callbacks.onStateChange?.(e.memberId,u.state),this.callbacks.onExit?.(e.memberId,w,_)}),p.on("error",w=>{g.detach(),u.state="failed",u.error=w.message,u.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let b=await g.initialize(p);u.state="ready",u.supportsResume=b.capabilities.supportsResume===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${n}, protocol=${b.protocolVersion}, resume=${u.supportsResume}, pid=${u.pid})`);let T=[...e.mcpServers??[]];a&&T.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(u.supportsResume&&u.sessionId){let w=await g.resumeSession(p,u.sessionId,{workspaceRoot:e.cwd,mcpServers:T.length>0?T:void 0});u.sessionId=w.id,this.slog("info",e.memberId,"session",`session resumed (id=${u.sessionId})`)}else{let w={workspaceRoot:e.cwd};T.length>0&&(w.mcpServers=T),e.systemPrompt&&(w.systemPrompt=e.systemPrompt);let _=await g.createSession(p,w);u.sessionId=_.id,this.slog("info",e.memberId,"session",`new session on restart (id=${u.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,w=>{this.slog("warn",w,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(w,"agents.error",{agentId:w,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(w)})}catch(u){let c=this.processes.get(e.memberId);c&&(c.handle.state="failed",c.handle.error=`Runtime restart failed: ${u instanceof Error?u.message:String(u)}`,c.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: ${u instanceof Error?u.message:String(u)}`,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 Cu}from"node:path";import{chmod as $k}from"node:fs/promises";import{readFile as Rk,writeFile as Ck,mkdir as Ak,rename as Mk,unlink as Pk}from"node:fs/promises";import{dirname as Ik,join as Su}from"node:path";import{randomUUID as Ek}from"node:crypto";async function Ok(r,e){let t=Ik(r);await Ak(t,{recursive:!0});let n=Su(t,`.tmp-${Ek()}`);try{await Ck(n,e,"utf-8"),await Mk(n,r)}catch(o){throw await Pk(n).catch(()=>{}),o}}async function yt(r){try{let e=await Rk(r,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function on(r,e){await Ok(r,JSON.stringify(e,null,2)+`
407
+ `)}var Lk="memory.json";function ao(){return Su(G(),Lk)}async function _u(){return yt(ao())}async function Cs(r){let e={...r,savedAt:new Date().toISOString()};await on(ao(),e)}var Au="agent-configs.json";function Ru(){return Cu(G(),Au)}function Dk(r){return Cu(je(r),Au)}function Uk(){return{agents:{}}}var lo=class{data=Uk();cwd;constructor(e){this.cwd=e}async load(){let e=await yt(Ru()),t=this.cwd?await yt(Dk(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=Ru();await on(e,this.data);try{await $k(e,384)}catch{}}};import{randomUUID as Wk}from"node:crypto";import{execFile as Nk}from"node:child_process";import{promisify as Fk}from"node:util";import{join as Mu}from"node:path";import{mkdir as jk,rm as Bk}from"node:fs/promises";var bt=Fk(Nk);async function rn(r){try{let{stdout:e}=await bt("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return null}}async function co(r,e,t){let n=Mu(r,".worktrees");await jk(n,{recursive:!0});let o=Mu(n,e),i=["worktree","add","-B",`solo/${e}`,o];return t?i.push(t):i.push("HEAD"),await bt("git",i,{cwd:r,encoding:"utf8"}),o}async function Pu(r){try{await bt("git",["add","-A"],{cwd:r});let{stdout:e}=await bt("git",["diff","--cached","--stat"],{cwd:r,encoding:"utf8"});return e.trim()}catch{return""}}async function Iu(r,e){try{await bt("git",["worktree","remove","--force",e],{cwd:r,encoding:"utf8"})}catch{try{await Bk(e,{recursive:!0,force:!0})}catch{}}}async function Eu(r,e){let{stdout:t}=await bt("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:r,encoding:"utf8"});return t.trim()}var uo=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 rn(o);if(!s)throw new Error("Solo Mode requires a git repository");let i=`solo-${Wk().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 l=n.map(async(c,d)=>{let p=`${i}-${c}-${d}`,m=`solo/${p}`,g=`${i}:${c}:${d}`,f;try{f=await co(s,p)}catch(T){this.callbacks.log?.warn(`[solo] worktree creation failed for ${c}: ${T instanceof Error?T.message:String(T)}`);let w={agentId:c,memberId:g,worktreePath:"",worktreeBranch:m,state:"failed",error:`Worktree creation failed: ${T instanceof Error?T.message:String(T)}`};a.agents.push(w);return}let b={agentId:c,memberId:g,worktreePath:f,worktreeBranch:m,state:"pending"};a.agents.push(b);try{b.state="running",this.callbacks.onProgress?.(i,c,"running");let T=this.acpDetector.buildExternalDescriptor(c);if(!T)throw new Error(`Agent ${c} is not available or not ACP-compatible`);await this.processManager.spawn({memberId:g,name:`solo-${c}`,cwd:f,prompt:t,external:T});let w=this.processManager.getHandle(g);if(!w||w.state!=="ready")throw new Error(`Agent ${c} spawn did not reach ready state`);let _=await this.processManager.sendTask(g,t);b.state="completed",b.resultText=typeof _=="string"?_:JSON.stringify(_),b.diff=await Pu(f);let y=this.processManager.getUsageTracker(g);if(y?.hasData()){let C=y.getUsage();b.usage={inputTokens:C.inputTokens,outputTokens:C.outputTokens}}this.callbacks.onProgress?.(i,c,"completed"),this.callbacks.log?.info(`[solo] ${c} completed (diff: ${b.diff?"yes":"none"})`)}catch(T){b.state="failed",b.error=T instanceof Error?T.message:String(T),this.callbacks.onProgress?.(i,c,"failed",b.error),this.callbacks.log?.warn(`[solo] ${c} failed: ${b.error}`)}});await Promise.allSettled(l);let u=a.agents.filter(c=>c.state==="completed");if(u.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 ${u.length} results for ${i}`);try{let c=await this.evaluate(a,u);a.evaluation=c,a.state="completed",this.callbacks.onEvaluation?.(i,c)}catch(c){a.state="completed",this.callbacks.log?.warn(`[solo] evaluation failed for ${i}: ${c instanceof Error?c.message:String(c)}`)}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 Eu(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(`
408
+ `),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 Iu(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 Vk}from"node:crypto";var sn=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 an=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 As}from"node:path";import{mkdir as Gk,readdir as Hk}from"node:fs/promises";function Ou(r){return As(je(r),"products")}function Lu(r,e){return As(Ou(e),r)}function $u(r,e){return As(Lu(r,e),"product-state.json")}async function Du(r,e){let t=Lu(r.productId,e);await Gk(t,{recursive:!0}),await on($u(r.productId,e),r)}async function Ms(r,e){return yt($u(r,e))}async function Uu(r){let e=Ou(r),t;try{t=await Hk(e)}catch{return[]}let n=[];for(let o of t){let s=await Ms(o,r);s&&n.push(s)}return n}var ln=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 Du(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 po=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(f=>f.name));for(let f of s)if(!a.has(f.assignee))throw new Error(`Task "${f.taskId}" references unknown instance "${f.assignee}"`);let l=`product-${Vk().slice(0,8)}`,u=new sn(s),c=new an(i),d=new ln({onCheckpoint:(f,b)=>this.callbacks.onCheckpointed?.(f,b),getState:()=>{let f=this.sessions.get(l);return f?this.buildPersistedState(f):null},log:this.callbacks.log}),p=await rn(n),m=o.map((f,b)=>({instanceId:`${l}:${f.name}:${b}`,name:f.name,agentId:f.agentId,state:"idle"})),g={productId:l,name:t,cwd:n,phase:"active",instances:m,dag:u,budget:c,checkpoint:d,createdAt:new Date().toISOString(),gitRoot:p};return this.sessions.set(l,g),d.start(n),this.callbacks.log?.info(`[product] created ${l} "${t}" with ${o.length} instances, ${s.length} tasks`),this.scheduleNext(g),l}async resume(e,t){let n=await Ms(e,t);if(!n)throw new Error(`Product ${e} not found on disk`);let o=new sn(n.tasks);o.restore(n.tasks);let s=new an({maxTotalTokens:n.budget.maxTotalTokens,maxDuration:n.budget.maxDuration});s.restore(n.budget);let i=new ln({onCheckpoint:(c,d)=>this.callbacks.onCheckpointed?.(c,d),getState:()=>{let c=this.sessions.get(e);return c?this.buildPersistedState(c):null},log:this.callbacks.log}),a=await rn(n.cwd),l=n.instances.map((c,d)=>({instanceId:`${e}:${c.name}:${d}`,name:c.name,agentId:c.agentId,state:"idle"})),u={productId:n.productId,name:n.name,cwd:n.cwd,phase:"active",instances:l,dag:o,budget:s,checkpoint:i,createdAt:n.createdAt,gitRoot:a};this.sessions.set(e,u),i.start(n.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(u)}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 Uu(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 c=`${e.productId}-${t.name}-${n.taskId}`;try{i=await co(e.gitRoot,c),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),l=typeof a=="string"?a:JSON.stringify(a),u=this.processManager.getUsageTracker(o);if(u?.hasData()){let c=u.getUsage();e.budget.addUsage(c.inputTokens,c.outputTokens)}e.dag.markCompleted(n.taskId,l),t.state="completed",this.callbacks.onTaskCompleted?.(e.productId,n.taskId,l);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 Nu="memory";var zk=["add","replace","remove","search"],Fu={type:"object",properties:{action:{type:"string",enum:zk,description:["The operation to perform:","\u2022 'add' \u2014 Save a concise note about this user (\u2192 local notes, always visible)","\u2022 'replace' \u2014 Update an existing note by matching a substring (\u2192 local notes)","\u2022 'remove' \u2014 Delete a note by matching a substring (\u2192 local notes)","\u2022 'search' \u2014 Search across long-term memory, recalled facts, user profile, and media preferences"].join(`
402
409
  `)},target:{type:"string",enum:["memory","user"],description:["Which note target to operate on (for add/replace/remove):","\u2022 'memory' \u2014 Your personal observations/notes about this user (default)","\u2022 'user' \u2014 User profile facts (preferences, timezone, etc.)"].join(`
403
410
  `)},content:{type:"string",description:["Required for 'add' and 'replace'. The note content to store.","Write a concise, factual statement.","Good: '\u7528\u6237\u662F\u540E\u7AEF\u5DE5\u7A0B\u5E08\uFF0C\u4E3B\u8981\u4F7F\u7528 TypeScript \u548C Go'","Good: 'User prefers dark UI themes and minimalist design'","Bad: '\u7528\u6237\u8BF4\u4E86\u5F88\u591A\u8BDD' (too vague)","Bad: entire conversation transcripts (too long)"].join(`
404
411
  `)},old_text:{type:"string",description:"Required for 'replace' and 'remove'. A substring that uniquely identifies the note entry to modify."},query:{type:"string",description:"Required for 'search'. Natural language query to find relevant memories."},category:{type:"string",enum:["profile","facts","media","projects"],description:["Optional for 'search': narrow the search to a specific category.","\u2022 'profile' \u2014 user preferences, expertise, communication style","\u2022 'facts' \u2014 recalled long-term memories","\u2022 'media' \u2014 media generation preferences (image style, music genre, etc.)","\u2022 'projects' \u2014 project context and tech stack","If omitted, searches across all sources."].join(`
405
- `)}},required:["action"]},ku=["Manage your notes about this user and search long-term memory.","","Your notes (add/replace/remove) are always visible in the system prompt.","Long-term memories are automatically extracted from every conversation","and searchable via 'search'.","","Guidelines:","- Use 'add' to record important user preferences, facts, or context","- Use 'replace' to update outdated notes (match by substring)","- Use 'remove' to delete incorrect notes (match by substring)","- Use 'search' to recall conversation history, user profile, and media preferences","- Keep notes concise \u2014 there's a character limit"].join(`
406
- `),Tu="Memory",lk=[/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 Ts(r){return!lk.some(e=>e.test(r))}async function wu(r,e){let{action:t}=r,n=r.target??"memory";if(t==="add"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let o=r.content?.trim();if(!o)return{ok:!1,message:"content is required for 'add' action.",action:t,errorCode:"empty_content"};if(o.length>2e3)return{ok:!1,message:`Content too long (${o.length} chars, max 2000).`,action:t,errorCode:"too_long"};let s=e.store.add(n,o);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="replace"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let o=r.old_text?.trim(),s=r.content?.trim();if(!o)return{ok:!1,message:"old_text is required for 'replace' action.",action:t,errorCode:"empty_old_text"};if(!s)return{ok:!1,message:"content is required for 'replace' action.",action:t,errorCode:"empty_content"};if(s.length>2e3)return{ok:!1,message:`Content too long (${s.length} chars, max 2000).`,action:t,errorCode:"too_long"};let i=e.store.replace(n,o,s);return{ok:i.ok,message:i.ok?`${i.message} [${i.usage}]`:i.message,action:t,entryCount:i.entryCount,usage:i.usage,storeModified:i.ok,errorCode:i.errorCode}}if(t==="remove"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let o=r.old_text?.trim();if(!o)return{ok:!1,message:"old_text is required for 'remove' action.",action:t,errorCode:"empty_old_text"};let s=e.store.remove(n,o);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="search"){let o=r.query?.trim();if(!o)return{ok:!1,message:"query is required for 'search' action.",action:t,errorCode:"empty_query"};let s=r.category,i=[],a;if(e.store&&(!s||s==="facts"||s==="profile")){let l=o.toLowerCase(),u=l.split(/\s+/).filter(d=>d.length>2),c=[];for(let d of["memory","user"])for(let p of e.store.getEntries(d)){let m=p.toLowerCase();(m.includes(l)||u.some(g=>m.includes(g)))&&c.push(`[${d}] ${p}`)}c.length>0&&i.push(`## Local Notes
412
+ `)}},required:["action"]},ju=["Manage your notes about this user and search long-term memory.","","Your notes (add/replace/remove) are always visible in the system prompt.","Long-term memories are automatically extracted from every conversation","and searchable via 'search'.","","Guidelines:","- Use 'add' to record important user preferences, facts, or context","- Use 'replace' to update outdated notes (match by substring)","- Use 'remove' to delete incorrect notes (match by substring)","- Use 'search' to recall conversation history, user profile, and media preferences","- Keep notes concise \u2014 there's a character limit"].join(`
413
+ `),Bu="Memory",qk=[/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 Ps(r){return!qk.some(e=>e.test(r))}async function Wu(r,e){let{action:t}=r,n=r.target??"memory";if(t==="add"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let o=r.content?.trim();if(!o)return{ok:!1,message:"content is required for 'add' action.",action:t,errorCode:"empty_content"};if(o.length>2e3)return{ok:!1,message:`Content too long (${o.length} chars, max 2000).`,action:t,errorCode:"too_long"};let s=e.store.add(n,o);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="replace"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let o=r.old_text?.trim(),s=r.content?.trim();if(!o)return{ok:!1,message:"old_text is required for 'replace' action.",action:t,errorCode:"empty_old_text"};if(!s)return{ok:!1,message:"content is required for 'replace' action.",action:t,errorCode:"empty_content"};if(s.length>2e3)return{ok:!1,message:`Content too long (${s.length} chars, max 2000).`,action:t,errorCode:"too_long"};let i=e.store.replace(n,o,s);return{ok:i.ok,message:i.ok?`${i.message} [${i.usage}]`:i.message,action:t,entryCount:i.entryCount,usage:i.usage,storeModified:i.ok,errorCode:i.errorCode}}if(t==="remove"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let o=r.old_text?.trim();if(!o)return{ok:!1,message:"old_text is required for 'remove' action.",action:t,errorCode:"empty_old_text"};let s=e.store.remove(n,o);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="search"){let o=r.query?.trim();if(!o)return{ok:!1,message:"query is required for 'search' action.",action:t,errorCode:"empty_query"};let s=r.category,i=[],a;if(e.store&&(!s||s==="facts"||s==="profile")){let l=o.toLowerCase(),u=l.split(/\s+/).filter(d=>d.length>2),c=[];for(let d of["memory","user"])for(let p of e.store.getEntries(d)){let m=p.toLowerCase();(m.includes(l)||u.some(g=>m.includes(g)))&&c.push(`[${d}] ${p}`)}c.length>0&&i.push(`## Local Notes
407
414
  `+c.map(d=>`\u2022 ${d}`).join(`
408
415
  `))}if(!s||s==="facts"||s==="projects")try{let l=await e.provider.search(o,e.userId,{limit:10});a=l,l.length>0&&i.push(`## Long-term Memory
409
416
  `+l.map((u,c)=>`${c+1}. [${u.blockId}] ${u.text}`).join(`
@@ -414,34 +421,34 @@ Files: ${n.checkpoint.fileCount}`}],details:{type:"checkpoint",action:"create",c
414
421
  `+u.join(`
415
422
  `))}}catch{}return i.length===0?{ok:!0,message:"No matching memories found.",action:t,results:[]}:{ok:!0,message:i.join(`
416
423
 
417
- `),action:t,results:a}}return{ok:!1,message:`Unknown action: ${t}. Use 'add', 'replace', 'remove', or 'search'.`,action:t,errorCode:"unknown_action"}}import{readFileSync as ck,existsSync as uk}from"node:fs";var st=`
424
+ `),action:t,results:a}}return{ok:!1,message:`Unknown action: ${t}. Use 'add', 'replace', 'remove', or 'search'.`,action:t,errorCode:"unknown_action"}}import{readFileSync as Kk,existsSync as Jk}from"node:fs";var st=`
418
425
  \xA7
419
- `,dk=2200,pk=1375,ao=class{memoryEntries=[];userEntries=[];frozenSnapshot={memory:"",user:""};snapshotFrozen=!1;saveTimer=null;memoryCharLimit;userCharLimit;persistToDisk;constructor(e){this.memoryCharLimit=e?.memoryCharLimit??dk,this.userCharLimit=e?.userCharLimit??pk,this.persistToDisk=e?.persistToDisk??!1}loadFromSerialized(e){this.memoryEntries=xu(vu(e.memory??"")),this.userEntries=xu(vu(e.user??""))}serialize(){return{memory:this.memoryEntries.join(st),user:this.userEntries.join(st)}}async loadFromDisk(){let e=await ru();e&&this.loadFromSerialized(e)}loadFromDiskSync(){let e=no();try{if(!uk(e))return;let t=ck(e,"utf-8"),n=JSON.parse(t);this.loadFromSerialized(n)}catch{}}scheduleSave(){this.persistToDisk&&(this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(()=>{this.saveTimer=null,ys(this.serialize()).catch(()=>{})},500))}async flush(){this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.persistToDisk&&await ys(this.serialize())}freezeSnapshot(){this.frozenSnapshot={memory:this.renderBlock("memory",this.memoryEntries),user:this.renderBlock("user",this.userEntries)},this.snapshotFrozen=!0}getSystemPromptBlock(e){return this.snapshotFrozen||this.freezeSnapshot(),this.frozenSnapshot[e]}add(e,t){let n=t.trim();if(!n)return this.errorResult(e,"Content cannot be empty.","empty_content");if(!Ts(n))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let o=this.entriesFor(e);if(o.includes(n))return this.successResult(e,"Entry already exists (no change).");if([...o,n].join(st).length>this.charLimitFor(e)){let a=this.formatUsage(e);return this.errorResult(e,`Memory full (${a}). Remove old entries first.`,"over_limit")}return o.push(n),this.scheduleSave(),this.successResult(e,"Entry added.")}replace(e,t,n){let o=t.trim(),s=n.trim();if(!o)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");if(!s)return this.errorResult(e,"content cannot be empty.","empty_content");if(!Ts(s))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let i=this.entriesFor(e),a=i.map((d,p)=>d.includes(o)?p:-1).filter(d=>d>=0);if(a.length===0)return this.errorResult(e,`No entry contains: "${ws(o)}"`,"not_found");if(a.length>1&&new Set(a.map(p=>i[p])).size>1)return this.errorResult(e,`Multiple entries match: "${ws(o)}" (${a.length} matches). Be more specific.`,"ambiguous_match");let l=a[0],u=[...i];if(u[l]=s,u.join(st).length>this.charLimitFor(e)){let d=this.formatUsage(e);return this.errorResult(e,`Replacement would exceed limit (${d}).`,"over_limit")}return i[l]=s,this.scheduleSave(),this.successResult(e,"Entry replaced.")}remove(e,t){let n=t.trim();if(!n)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");let o=this.entriesFor(e),s=o.map((i,a)=>i.includes(n)?a:-1).filter(i=>i>=0);if(s.length===0)return this.errorResult(e,`No entry contains: "${ws(n)}"`,"not_found");for(let i=s.length-1;i>=0;i--)o.splice(s[i],1);return this.scheduleSave(),this.successResult(e,s.length===1?"Entry removed.":`${s.length} entries removed.`)}getEntries(e){return this.entriesFor(e)}getUsage(e){let t=this.entriesFor(e),n=t.length>0?t.join(st).length:0,o=this.charLimitFor(e);return{used:n,limit:o,percent:o>0?Math.round(n/o*100):0}}isEmpty(){return this.memoryEntries.length===0&&this.userEntries.length===0}entriesFor(e){return e==="user"?this.userEntries:this.memoryEntries}charLimitFor(e){return e==="user"?this.userCharLimit:this.memoryCharLimit}formatUsage(e){let{used:t,limit:n,percent:o}=this.getUsage(e);return`${o}% \u2014 ${t}/${n} chars`}renderBlock(e,t){if(t.length===0)return"";let n=e==="user"?"USER PROFILE":"MEMORY",o=this.formatUsage(e),s="\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",i=t.join(st);return`${s}
426
+ `,Yk=2200,Xk=1375,mo=class{memoryEntries=[];userEntries=[];frozenSnapshot={memory:"",user:""};snapshotFrozen=!1;saveTimer=null;memoryCharLimit;userCharLimit;persistToDisk;constructor(e){this.memoryCharLimit=e?.memoryCharLimit??Yk,this.userCharLimit=e?.userCharLimit??Xk,this.persistToDisk=e?.persistToDisk??!1}loadFromSerialized(e){this.memoryEntries=Hu(Gu(e.memory??"")),this.userEntries=Hu(Gu(e.user??""))}serialize(){return{memory:this.memoryEntries.join(st),user:this.userEntries.join(st)}}async loadFromDisk(){let e=await _u();e&&this.loadFromSerialized(e)}loadFromDiskSync(){let e=ao();try{if(!Jk(e))return;let t=Kk(e,"utf-8"),n=JSON.parse(t);this.loadFromSerialized(n)}catch{}}scheduleSave(){this.persistToDisk&&(this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(()=>{this.saveTimer=null,Cs(this.serialize()).catch(()=>{})},500))}async flush(){this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.persistToDisk&&await Cs(this.serialize())}freezeSnapshot(){this.frozenSnapshot={memory:this.renderBlock("memory",this.memoryEntries),user:this.renderBlock("user",this.userEntries)},this.snapshotFrozen=!0}getSystemPromptBlock(e){return this.snapshotFrozen||this.freezeSnapshot(),this.frozenSnapshot[e]}add(e,t){let n=t.trim();if(!n)return this.errorResult(e,"Content cannot be empty.","empty_content");if(!Ps(n))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let o=this.entriesFor(e);if(o.includes(n))return this.successResult(e,"Entry already exists (no change).");if([...o,n].join(st).length>this.charLimitFor(e)){let a=this.formatUsage(e);return this.errorResult(e,`Memory full (${a}). Remove old entries first.`,"over_limit")}return o.push(n),this.scheduleSave(),this.successResult(e,"Entry added.")}replace(e,t,n){let o=t.trim(),s=n.trim();if(!o)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");if(!s)return this.errorResult(e,"content cannot be empty.","empty_content");if(!Ps(s))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let i=this.entriesFor(e),a=i.map((d,p)=>d.includes(o)?p:-1).filter(d=>d>=0);if(a.length===0)return this.errorResult(e,`No entry contains: "${Is(o)}"`,"not_found");if(a.length>1&&new Set(a.map(p=>i[p])).size>1)return this.errorResult(e,`Multiple entries match: "${Is(o)}" (${a.length} matches). Be more specific.`,"ambiguous_match");let l=a[0],u=[...i];if(u[l]=s,u.join(st).length>this.charLimitFor(e)){let d=this.formatUsage(e);return this.errorResult(e,`Replacement would exceed limit (${d}).`,"over_limit")}return i[l]=s,this.scheduleSave(),this.successResult(e,"Entry replaced.")}remove(e,t){let n=t.trim();if(!n)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");let o=this.entriesFor(e),s=o.map((i,a)=>i.includes(n)?a:-1).filter(i=>i>=0);if(s.length===0)return this.errorResult(e,`No entry contains: "${Is(n)}"`,"not_found");for(let i=s.length-1;i>=0;i--)o.splice(s[i],1);return this.scheduleSave(),this.successResult(e,s.length===1?"Entry removed.":`${s.length} entries removed.`)}getEntries(e){return this.entriesFor(e)}getUsage(e){let t=this.entriesFor(e),n=t.length>0?t.join(st).length:0,o=this.charLimitFor(e);return{used:n,limit:o,percent:o>0?Math.round(n/o*100):0}}isEmpty(){return this.memoryEntries.length===0&&this.userEntries.length===0}entriesFor(e){return e==="user"?this.userEntries:this.memoryEntries}charLimitFor(e){return e==="user"?this.userCharLimit:this.memoryCharLimit}formatUsage(e){let{used:t,limit:n,percent:o}=this.getUsage(e);return`${o}% \u2014 ${t}/${n} chars`}renderBlock(e,t){if(t.length===0)return"";let n=e==="user"?"USER PROFILE":"MEMORY",o=this.formatUsage(e),s="\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",i=t.join(st);return`${s}
420
427
  ${n} (your personal notes) [${o}]
421
428
  ${s}
422
- ${i}`}successResult(e,t){let n=this.entriesFor(e);return{ok:!0,message:t,target:e,entries:n,entryCount:n.length,usage:this.formatUsage(e)}}errorResult(e,t,n){let o=this.entriesFor(e);return{ok:!1,message:t,target:e,entries:o,entryCount:o.length,usage:this.formatUsage(e),errorCode:n}}};function vu(r){return r.trim()?r.split(st).map(e=>e.trim()).filter(Boolean):[]}function xu(r){let e=new Set;return r.filter(t=>e.has(t)?!1:(e.add(t),!0))}function ws(r,e=60){return r.length<=e?r:`${r.slice(0,e-1).trimEnd()}\u2026`}Fo();Uo();import{readFile as mk}from"node:fs/promises";import{watch as gk}from"node:fs";import{join as fk}from"node:path";var hk=_e,yk="settings.json";function bk(r){return fk(r,hk,yk)}async function kk(r){try{let e=await mk(r,"utf-8");return JSON.parse(e)}catch{return null}}function Tk(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 Su(r){let e=bk(r.projectRoot),t=null,n=null,o=async()=>{let s=await kk(e);s&&Tk(s,r.ruleEngine,r.hooks,r.log)};o().catch(()=>{});try{t=gk(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 vs=new Set;function it(r){return vs.add(r),()=>{vs.delete(r)}}async function Ru(){await Promise.all(Array.from(vs).map(r=>r()))}import*as $ from"node:fs";import*as J from"node:path";import{AGENT_RPC_ERROR_CODES as M,AGENT_RPC_PROTOCOL_VERSION as co,isAgentRpcRequest as wk}from"qlogicagent-runtime-contracts";var _u=["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"];var lo=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 l of s.web_search.slice(0,a))i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content});return i}for(let l of s.choices??[])for(let u of l.message?.tool_calls??[])for(let c of u.search_result??[]){if(i.length>=a)break;i.push({title:c.title??"",url:c.link??"",snippet:(c.content??"").slice(0,500),content:c.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 vk=new Set(["zhipu","zhipu-openai","zhipu-coding"]),xk="https://open.bigmodel.cn/api/paas/v4";function Sk(r,e){if(!(!r||!e)&&vk.has(r))return new lo({baseUrl:xk,apiKey:e})}var uo=class r{running=!1;activeTurn=null;verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentProjectRoot;currentHooks=null;mcpManager=null;pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";sessionState=null;currentMediaApiKeys=null;taskStore=new Pn;memoryPrefetchState=jt();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;pendingAskUser=new Map;acpDetector=new eo;agentConfigStore=null;soloEvaluator=null;productOrchestrator=null;soloProcessManager=null;productProcessManager=null;constructor(e){this.verbose=e.verbose,this.registry=new $t,this.mediaClient=new Ot({registry:this.registry}),this.transport=e.transport??new at({verbose:e.verbose}),this.taskStore.onTaskChange((t,n)=>{n&&this.sendNotification("task.updated",{taskId:t,type:n.type,lifecycle:n.lifecycle,label:n.label})}),Sc({log:{info:t=>this.log(t),warn:t=>this.log(`[warn] ${t}`),error:t=>this.log(`[error] ${t}`),debug:t=>{e.verbose&&this.log(`[debug] ${t}`)}},onExecProgress:t=>{this.sendNotification("turn.exec_progress",{output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,totalBytes:t.totalBytes})}})}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(!wk(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}stop(){if(this.running){this.running=!1,this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{Ru().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"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;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.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=co.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${co}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${co}`});return}this.log(`[initialize] host=${o} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:co,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:We().map(l=>l.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","turn.ask_user","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[..._u]}})}handleThreadCreate(e){let t=e.params,n=t?.id??ve();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&(ss(t.cwd),this.currentProjectRoot=t.cwd),this.currentSessionId=n,this.sessionState=new Bt(n),this.memoryPrefetchState=jt(),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 Ia(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:M.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:M.INVALID_PARAMS,message:"sessionId is required"});return}try{let o=await Pa(n,this.currentProjectRoot);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.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:M.INTERNAL_ERROR,message:`Failed to resume session: ${o.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??ve(),o=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;a?.workdir&&typeof a.workdir=="string"&&(ss(a.workdir),this.currentProjectRoot=a.workdir);{let u={},c=a?.provider,d=a?.apiKey;c&&d&&(u[c]=d);let p=a?.mediaApiKeys;p&&Object.assign(u,p),this.currentMediaApiKeys=u,wc(this.mediaClient,u,(m,g,f)=>{this.sessionState?.addMediaUsage(m,g,f)},a?.mediaProviders,(m,g,f,b,h)=>{this.sendNotification("turn.media_progress",{turnId:n,taskId:m,mediaType:g,percent:f,status:b,...h?{provider:h}:{}})}),bc(Sk(c,d))}Tc(async u=>{let c=`ask-${ve().slice(0,8)}`;return new Promise(d=>{this.pendingAskUser.set(c,{resolve:d}),this.sendNotification("turn.ask_user",{requestId:c,questions:u.map(p=>({header:p.header,question:p.question,options:p.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(()=>{}),ja()),this.currentSessionId=o,this.sessionState=new Bt(o),this.memoryPrefetchState=jt());let l=new AbortController;this.activeTurn=l,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 u={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};{let h=u.provider??"",k=u.model??"";h&&k&&this.registry.getModelInfo(h,k)?.streamRequired&&(u.streamRequired=!0)}let c=this.resolveAgent(u);if(this.permissionChecker&&a?.permissions){let h=a.permissions,k=ls(h);this.permissionChecker.ruleEngineRef.setMode(k.mode),k.rules.length>0&&this.permissionChecker.ruleEngineRef.replaceRules(k.rules),k.defaultBehavior&&this.permissionChecker.ruleEngineRef.setDefaultBehavior(k.defaultBehavior)}if(!c){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 d,p=a?.workdir??process.cwd();try{let h=await Na(p,this.currentHooks??void 0);h.length>0&&(d=Ua(h))}catch{}let m=await Ba({basePrompt:a?.systemPrompt,instructionBlock:d,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[Wa(p),Ga()]});for(let h of s)h.role==="user"&&br(o,h,this.currentProjectRoot).catch(()=>{});let g=We(),f=new Set(g.map(h=>h.function.name)),b=[...g,...i.filter(h=>!f.has(h.function.name))];for await(let h of c.run({turnId:n,sessionId:o,messages:s,tools:b,systemPrompt:m,config:u},l.signal)){let k=new Date().toISOString();switch(h.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:h.turnId,text:h.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:h.text,createdAt:k}});break;case"end":if(this.sendNotification("turn.end",{turnId:h.turnId,content:h.content,usage:h.usage,model:h.model,provider:h.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:h.content,createdAt:k}}),h.usage&&this.sessionState){this.sessionState.addUsage(h.usage,h.model??this.currentModel);let x=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:h.turnId,usage:h.usage,model:h.model??this.currentModel,sessionCostUSD:x.totalInputTokens*3e-6+x.totalOutputTokens*15e-6})}h.content&&br(o,{role:"assistant",content:h.content},this.currentProjectRoot).catch(()=>{});break;case"error":if(this.sendNotification("turn.error",{turnId:h.turnId,error:h.error,code:h.code}),h.usage&&this.sessionState){this.sessionState.addUsage(h.usage,this.currentModel);let x=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:h.turnId,usage:h.usage,model:this.currentModel,sessionCostUSD:x.totalInputTokens*3e-6+x.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:h.turnId,instruction:h.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:h.turnId,callId:h.callId,name:h.name,arguments:h.arguments,item:{id:h.callId,type:"tool_call",role:"assistant",toolName:h.name,toolCallId:h.callId,arguments:h.arguments,createdAt:k}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:h.turnId,callId:h.callId,name:h.name,ok:h.ok,...h.error?{error:h.error}:{},...h.outputPreview?{outputPreview:h.outputPreview}:{},item:{id:`${h.callId}-result`,type:"tool_result",role:"assistant",toolName:h.name,toolCallId:h.callId,output:h.ok?h.outputPreview??"":h.error,approved:h.ok,createdAt:k}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:h.turnId,callId:h.callId,name:h.name,reason:h.reason,item:{id:`${h.callId}-blocked`,type:"tool_blocked",role:"system",toolName:h.name,toolCallId:h.callId,text:h.reason,approved:!1,createdAt:k}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:h.turnId,action:h.action,...h.detail?{detail:h.detail}:{},item:{id:`${n}-recovery-${ve().slice(0,8)}`,type:"recovery",role:"system",strategy:h.action,text:h.detail,createdAt:k}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:h.turnId,slug:h.slug,content:h.content,item:{id:`${n}-plan-${ve().slice(0,8)}`,type:"plan_update",role:"assistant",text:h.content,createdAt:k}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:h.turnId,text:h.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:h.turnId,items:h.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:h.turnId,mediaType:h.mediaType,url:h.url,...h.model?{model:h.model}:{},...h.provider?{provider:h.provider}:{},...h.taskId?{taskId:h.taskId}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:h.turnId,artifactId:h.artifactId,type:h.artifactType,title:h.title,...h.filePath?{filePath:h.filePath}:{},...h.language?{language:h.language}:{},...h.content?{content:h.content}:{},...h.mimeType?{mimeType:h.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:h.turnId,subagentId:h.subagentId,agentType:h.agentType,...h.prompt?{prompt:h.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:h.turnId,subagentId:h.subagentId,agentType:h.agentType,ok:h.ok,...h.outputPreview?{outputPreview:h.outputPreview}:{},...h.error?{error:h.error}:{}});break;case"annotations":this.sendNotification("turn.annotations",{turnId:h.turnId,annotations:h.annotations});break;case"heartbeat":this.sendNotification("turn.heartbeat",{turnId:h.turnId,message:h.message});break;case"tool_use_summary":this.sendNotification("turn.tool_use_summary",{turnId:h.turnId,summary:h.summary});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){Ma(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:this.currentProjectRoot??process.cwd(),messageCount:s.length},this.currentProjectRoot).catch(()=>{});let h=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:this.currentProjectRoot??process.cwd(),turnCount:h.turnCount}),this.currentTransport&&this.currentApiKey&&u.summaryModel&&Ea(o,{sessionId:o,createdAt:0,lastActiveAt:0,turnCount:h.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:u.summaryModel},this.currentProjectRoot),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(n,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(u){if(l.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let c=u instanceof Error?u.message:String(u);this.sendNotification("turn.error",{turnId:n,error:c,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===l&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
429
+ ${i}`}successResult(e,t){let n=this.entriesFor(e);return{ok:!0,message:t,target:e,entries:n,entryCount:n.length,usage:this.formatUsage(e)}}errorResult(e,t,n){let o=this.entriesFor(e);return{ok:!1,message:t,target:e,entries:o,entryCount:o.length,usage:this.formatUsage(e),errorCode:n}}};function Gu(r){return r.trim()?r.split(st).map(e=>e.trim()).filter(Boolean):[]}function Hu(r){let e=new Set;return r.filter(t=>e.has(t)?!1:(e.add(t),!0))}function Is(r,e=60){return r.length<=e?r:`${r.slice(0,e-1).trimEnd()}\u2026`}Vo();Go();import{readFile as Qk}from"node:fs/promises";import{watch as Zk}from"node:fs";import{join as eT}from"node:path";var tT=ye,nT="settings.json";function oT(r){return eT(r,tT,nT)}async function rT(r){try{let e=await Qk(r,"utf-8");return JSON.parse(e)}catch{return null}}function sT(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 Vu(r){let e=oT(r.projectRoot),t=null,n=null,o=async()=>{let s=await rT(e);s&&sT(s,r.ruleEngine,r.hooks,r.log)};o().catch(()=>{});try{t=Zk(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 Es=new Set;function it(r){return Es.add(r),()=>{Es.delete(r)}}async function zu(){await Promise.all(Array.from(Es).map(r=>r()))}import*as N from"node:fs";import*as J from"node:path";import{AGENT_RPC_ERROR_CODES as P,AGENT_RPC_PROTOCOL_VERSION as fo,isAgentRpcRequest as iT}from"qlogicagent-runtime-contracts";var qu=["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"];var go=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 l of s.web_search.slice(0,a))i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content});return i}for(let l of s.choices??[])for(let u of l.message?.tool_calls??[])for(let c of u.search_result??[]){if(i.length>=a)break;i.push({title:c.title??"",url:c.link??"",snippet:(c.content??"").slice(0,500),content:c.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 aT=new Set(["zhipu","zhipu-openai","zhipu-coding"]),lT="https://open.bigmodel.cn/api/paas/v4";function cT(r,e){if(!(!r||!e)&&aT.has(r))return new go({baseUrl:lT,apiKey:e})}var ho=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="";sessionState=null;currentMediaApiKeys=null;taskStore=new On;memoryPrefetchState=Bt();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;acpDetector=new so;agentConfigStore=null;soloEvaluator=null;productOrchestrator=null;soloProcessManager=null;productProcessManager=null;constructor(e){this.verbose=e.verbose,this.registry=new Dt,this.mediaClient=new Lt({registry:this.registry}),this.transport=e.transport??new at({verbose:e.verbose}),this.taskStore.onTaskChange((t,n)=>{n&&this.sendNotification("task.updated",{taskId:t,type:n.type,lifecycle:n.lifecycle,label:n.label})}),Vc({log:{info:t=>this.log(t),warn:t=>this.log(`[warn] ${t}`),error:t=>this.log(`[error] ${t}`),debug:t=>{e.verbose&&this.log(`[debug] ${t}`)}},onExecProgress:t=>{this.sendNotification("turn.exec_progress",{output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,totalBytes:t.totalBytes})}})}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(!iT(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}stop(){if(this.running){this.running=!1,this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{zu().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"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;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.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=fo.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${fo}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${fo}`});return}this.log(`[initialize] host=${o} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:fo,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:We().map(l=>l.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","turn.ask_user","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...qu]}})}handleThreadCreate(e){let t=e.params,n=t?.id??xe();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&(fs(t.cwd),this.currentProjectRoot=t.cwd),this.currentSessionId=n,this.sessionState=new Wt(n),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Bt(),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 Wa(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:P.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:P.INVALID_PARAMS,message:"sessionId is required"});return}try{let o=await Ba(n,this.currentProjectRoot);if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.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:P.INTERNAL_ERROR,message:`Failed to resume session: ${o.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??xe(),o=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;a?.workdir&&typeof a.workdir=="string"&&(fs(a.workdir),this.currentProjectRoot=a.workdir);{let u={},c=a?.provider,d=a?.apiKey;c&&d&&(u[c]=d);let p=a?.mediaApiKeys;p&&Object.assign(u,p),this.currentMediaApiKeys=u,Wc(this.mediaClient,u,(m,g,f)=>{this.sessionState?.addMediaUsage(m,g,f)},a?.mediaProviders,(m,g,f,b,T)=>{this.sendNotification("turn.media_progress",{turnId:n,taskId:m,mediaType:g,percent:f,status:b,...T?{provider:T}:{}})}),Fc(cT(c,d))}Bc(async u=>{let c=`ask-${xe().slice(0,8)}`;return new Promise(d=>{this.pendingAskUser.set(c,{resolve:d}),this.sendNotification("turn.ask_user",{requestId:c,questions:u.map(p=>({header:p.header,question:p.question,options:p.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(()=>{}),Qa()),this.currentSessionId=o,this.sessionState=new Wt(o),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Bt());let l=new AbortController;this.activeTurn=l,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 u={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 y=u.provider??"",C=u.model??"";y&&C&&this.registry.getModelInfo(y,C)?.streamRequired&&(u.streamRequired=!0)}let c=this.resolveAgent(u);if(this.permissionChecker&&a?.permissions){let y=a.permissions,C=bs(y);this.permissionChecker.ruleEngineRef.setMode(C.mode),C.rules.length>0&&this.permissionChecker.ruleEngineRef.replaceRules(C.rules),C.defaultBehavior&&this.permissionChecker.ruleEngineRef.setDefaultBehavior(C.defaultBehavior)}if(!c){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 d,p=a?.workdir??process.cwd();try{let y=await Ja(p,this.currentHooks??void 0);y.length>0&&(d=Ka(y))}catch{}let m=s.filter(y=>y.role==="user").map(y=>typeof y.content=="string"?y.content:"").join(" "),{domain:g,source:f}=il({cwd:p,hostOverride:a?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:m});this.sessionTaskDomain=g,f==="auto-detect"&&ll(m,g)&&al(p,g);let b=await Za({basePrompt:a?.systemPrompt,instructionBlock:d,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[el(p),tl(g),nl()]});for(let y of s)y.role==="user"&&Sr(o,y,this.currentProjectRoot).catch(()=>{});await this.mcpReady;let T=We(),w=new Set(T.map(y=>y.function.name)),_=[...T,...i.filter(y=>!w.has(y.function.name))];for await(let y of c.run({turnId:n,sessionId:o,messages:s,tools:_,systemPrompt:b,config:u},l.signal)){let C=new Date().toISOString();switch(y.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:y.turnId,text:y.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:y.text,createdAt:C}});break;case"end":if(this.sendNotification("turn.end",{turnId:y.turnId,content:y.content,usage:y.usage,model:y.model,provider:y.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:y.content,createdAt:C}}),y.usage&&this.sessionState){this.sessionState.addUsage(y.usage,y.model??this.currentModel);let E=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:y.turnId,usage:y.usage,model:y.model??this.currentModel,sessionCostUSD:E.totalInputTokens*3e-6+E.totalOutputTokens*15e-6})}y.content&&Sr(o,{role:"assistant",content:y.content},this.currentProjectRoot).catch(()=>{});break;case"error":if(this.sendNotification("turn.error",{turnId:y.turnId,error:y.error,code:y.code}),y.usage&&this.sessionState){this.sessionState.addUsage(y.usage,this.currentModel);let E=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:y.turnId,usage:y.usage,model:this.currentModel,sessionCostUSD:E.totalInputTokens*3e-6+E.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:y.turnId,instruction:y.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:y.turnId,callId:y.callId,name:y.name,arguments:y.arguments,item:{id:y.callId,type:"tool_call",role:"assistant",toolName:y.name,toolCallId:y.callId,arguments:y.arguments,createdAt:C}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:y.turnId,callId:y.callId,name:y.name,ok:y.ok,...y.error?{error:y.error}:{},...y.outputPreview?{outputPreview:y.outputPreview}:{},item:{id:`${y.callId}-result`,type:"tool_result",role:"assistant",toolName:y.name,toolCallId:y.callId,output:y.ok?y.outputPreview??"":y.error,approved:y.ok,createdAt:C}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:y.turnId,callId:y.callId,name:y.name,reason:y.reason,item:{id:`${y.callId}-blocked`,type:"tool_blocked",role:"system",toolName:y.name,toolCallId:y.callId,text:y.reason,approved:!1,createdAt:C}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:y.turnId,action:y.action,...y.detail?{detail:y.detail}:{},item:{id:`${n}-recovery-${xe().slice(0,8)}`,type:"recovery",role:"system",strategy:y.action,text:y.detail,createdAt:C}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:y.turnId,slug:y.slug,content:y.content,item:{id:`${n}-plan-${xe().slice(0,8)}`,type:"plan_update",role:"assistant",text:y.content,createdAt:C}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:y.turnId,text:y.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:y.turnId,items:y.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:y.turnId,mediaType:y.mediaType,url:y.url,...y.model?{model:y.model}:{},...y.provider?{provider:y.provider}:{},...y.taskId?{taskId:y.taskId}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:y.turnId,artifactId:y.artifactId,type:y.artifactType,title:y.title,...y.filePath?{filePath:y.filePath}:{},...y.language?{language:y.language}:{},...y.content?{content:y.content}:{},...y.mimeType?{mimeType:y.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:y.turnId,subagentId:y.subagentId,agentType:y.agentType,...y.prompt?{prompt:y.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:y.turnId,subagentId:y.subagentId,agentType:y.agentType,ok:y.ok,...y.outputPreview?{outputPreview:y.outputPreview}:{},...y.error?{error:y.error}:{}});break;case"annotations":this.sendNotification("turn.annotations",{turnId:y.turnId,annotations:y.annotations});break;case"heartbeat":this.sendNotification("turn.heartbeat",{turnId:y.turnId,message:y.message});break;case"tool_use_summary":this.sendNotification("turn.tool_use_summary",{turnId:y.turnId,summary:y.summary});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){ja(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:this.currentProjectRoot??process.cwd(),messageCount:s.length},this.currentProjectRoot).catch(()=>{});let y=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:this.currentProjectRoot??process.cwd(),turnCount:y.turnCount}),this.currentTransport&&this.currentApiKey&&u.summaryModel&&Ga(o,{sessionId:o,createdAt:0,lastActiveAt:0,turnCount:y.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:u.summaryModel},this.currentProjectRoot),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(n,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(u){if(l.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let c=u instanceof Error?u.message:String(u);this.sendNotification("turn.error",{turnId:n,error:c,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===l&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
423
430
  Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
424
431
  Be specific: "run the tests" beats "continue".
425
432
  Stay silent if the next step isn't obvious.
426
- Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,n,o,s){if(t.filter(u=>u.role==="assistant").length<1)return;let l=[...t.slice(-6),{role:"user",content:r.SUGGESTION_PROMPT}];try{let u="";for await(let d of n.stream({model:s,messages:l,temperature:.3,maxTokens:200},o))d.type==="delta"&&(u+=d.text);let c=u.match(/\[[\s\S]*\]/);if(c){let d=JSON.parse(c[0]),p=Array.isArray(d)?d.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??ve(),o=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",l=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n});let u=new AbortController;this.activeTurn=u,this.log(`dream ${n} starting (session: ${o}, sessions reviewing: ${l.length})`);let c={provider:s?.provider,model:s?.model,apiKey:s?.apiKey,baseUrl:s?.baseUrl,maxRounds:s?.maxRounds,temperature:s?.temperature,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,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=c.provider??"",m=c.model??"";p&&m&&this.registry.getModelInfo(p,m)?.streamRequired&&(c.streamRequired=!0)}if(!this.resolveAgent(c)){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()=>l},triggerConfig:{force:!0},transport:this.currentTransport,toolInvoker:{invoke:async(g,f,b,h)=>{if(f.startsWith("$"))return{result:b};let k=ke(f);if(!k)return{result:"",error:`Unknown tool: ${f}`};let x=`tc_${ve().slice(0,8)}`;try{let R=JSON.parse(b),E=await k.execute(x,R,h);return{result:E.content.map(U=>U.text??"").join(`
427
- `),error:E.details?.error}}catch(R){return{result:"",error:R instanceof Error?R.message:String(R)}}}},tools:We(),apiKey:this.currentApiKey,model:c.model??this.currentModel,log:{info:g=>this.log(g),warn:g=>this.log(`[warn] ${g}`),error:g=>this.log(`[error] ${g}`),debug:g=>{this.verbose&&this.log(`[debug] ${g}`)}},hooks:this.currentHooks??void 0,parentSignal:u.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},m=await _a(p);m.ok?this.sendNotification("turn.end",{turnId:n,content:`Dream consolidation completed. ${m.sessionsReviewed} sessions reviewed, ${m.filesTouched.length} files touched. Duration: ${m.durationMs}ms.`,usage:{prompt:0,completion:0}}):this.sendNotification("turn.error",{turnId:n,error:m.error??"Dream consolidation failed",code:"DREAM_FAILED"}),this.log(`dream ${n} completed`)}catch(p){if(u.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===u&&(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 y=pr(this.registry);y&&(n=n??y.providerId,s=s??y.apiKey,o=o??y.defaultModel,this.log(`auto-detected provider: ${n}, model: ${o}`))}if(!n||!s){let y=this.loadSettingsSync();y&&(n=n??y.provider,s=s??y.apiKey,o=o??y.model,n&&s&&this.log(`loaded provider from settings.json: ${n}, model: ${o}`))}if(!n||!s)return null;o=o??this.registry.getProvider(n)?.defaultModel??"";let a=dr({provider:n,model:o,apiKey:s,baseUrl:i},this.registry);mr()&&(a.transport=gr(a.transport,this.currentSessionId||"default"));let l={info:y=>this.log(y),warn:y=>this.log(`[warn] ${y}`),error:y=>this.log(`[error] ${y}`),debug:y=>{this.verbose&&this.log(`[debug] ${y}`)}},u={invoke:async(y,T,v,_)=>{if(T.startsWith("$"))return{result:v};let C=ke(T);if(!C)return{result:"",error:`Unknown tool: ${T}`};let I=`tc_${ve().slice(0,8)}`;try{let V=JSON.parse(v),j=await C.execute(I,V,_),re=j.content.map(ie=>ie.text??"").join(`
428
- `),X=j.details?.error,P=j.details?.type,se=P?.split("_")[0];if(se&&["image","tts","video","music"].includes(se)){let ie=j.details?.mediaUrls??[],we=se;for(let an of ie)this.sendNotification("turn.media_result",{turnId:y,mediaType:we,url:an,model:j.details?.model,provider:j.details?.provider,...j.details?.durationMs?{durationSeconds:j.details.durationMs/1e3}:{},...j.details?.taskId?{taskId:j.details.taskId}:{}})}if(P==="todo"&&!X)try{let ie=JSON.parse(re);ie.todoList&&this.sendNotification("turn.todos_updated",{turnId:y,items:ie.todoList,summary:{total:ie.total??ie.todoList.length,completed:ie.completed??0,inProgress:ie.inProgress??0,notStarted:ie.notStarted??0}})}catch{}return{result:re,error:X}}catch(V){return{result:"",error:V instanceof Error?V.message:String(V)}}}},c=sa(l);this.currentHooks=c,this.taskStore.setHooks(c,this.currentSessionId??"");let d=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(d){let y=la({baseUrl:d,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=y,this.qmemoryUserId=this.currentSessionId??"default",ia(c,{memoryProvider:y,userId:this.currentSessionId??"default",log:{debug:T=>l.debug(T),warn:T=>l.warn(T)}},this.memoryPrefetchState)}Si(c,l,{transport:a.transport,apiKey:a.apiKey});let p=e?.mcpServers,m=is(p??{}),g=ji();try{if($.existsSync(g)){let y=JSON.parse($.readFileSync(g,"utf8")),T=is(y),v=new Set(m.map(_=>_.name));m=[...m,...T.filter(_=>!v.has(_.name))]}}catch{}if(m.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new Kn({servers:m,log:l}),it(async()=>{await this.mcpManager?.disconnectAll()});let y=()=>this.mcpManager;ce(Rc(y)),ce(_c(y)),ce(Yc({listServers:async()=>{let T=this.mcpManager;return T?T.getConnectedServers().map(_=>({name:_,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async T=>{if(!this.mcpManager)return[];let _=`mcp__${T.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return Be().filter(C=>C.startsWith(_)).map(C=>({name:C.slice(_.length),prefixedName:C}))},callTool:async(T,v,_,C)=>{let V=`mcp__${T.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+v,j=ke(V);if(!j)return{success:!1,error:`Tool not found: ${V}`};try{return{success:!0,content:(await j.execute(`mcp_${Date.now()}`,_??{},C)).content.map(P=>P.text??"").join(`
429
- `)}}catch(re){return{success:!1,error:re.message}}},listResources:async T=>{let v=this.mcpManager;return v?(await v.listResources(T)).map(C=>({uri:C.uri,name:C.name,mimeType:C.mimeType,description:C.description,server:C.server})):[]},readResource:async(T,v)=>{let _=this.mcpManager;if(!_)throw new Error("MCP not initialized");return(await _.readResource(T,v)).map(I=>({uri:I.uri,mimeType:I.mimeType,text:I.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(T=>{l.warn(`[mcp] connection error: ${T instanceof Error?T.message:T}`)})}let f=[],b=Di();$.existsSync(b)&&f.push(b);let h=e?.pluginPaths;if(Array.isArray(h))for(let y of h)typeof y=="string"&&$.existsSync(y)&&f.push(y);Pc(f,l).then(y=>{if(y.length===0)return;this.pluginLoader=new Yn({pluginDirs:y,hookRegistry:c,log:l}),this.pluginLoader.loadAll().then(v=>{l.info(`[plugins] ${v.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(v=>{l.warn(`[plugins] load error: ${v instanceof Error?v.message:v}`)});let T=this.pluginLoader;c.register({point:"turn.submitted",handler:async()=>(await T.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(y=>{l.warn(`[plugins] marketplace resolve error: ${y instanceof Error?y.message:y}`)});let k=e?.permissions,x=ls(k),R=new Xn(x);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new Zn({ruleEngine:R,hookRegistry:c,onRequestApproval:async y=>(this.sendNotification("tool.approval.request",{approvalId:y.approvalId,callId:y.callId,toolName:y.toolName,arguments:y.arguments?JSON.stringify(y.arguments):"",message:y.message,suggestions:y.suggestions?.map(T=>`${T.pattern}:${T.behavior}`)}),new Promise(()=>{})),onPermissionUpdate:y=>{l.info(`[permissions] rule saved: ${y.pattern} \u2192 ${y.behavior}`),this.sendNotification("permission.rule_updated",{pattern:y.pattern,behavior:y.behavior})},onDenied:(y,T)=>{l.warn(`[permissions] blocked "${y}": ${T}`)}});let E=We();this.permissionChecker.setToolMeta(E),this.permissionUnregister=this.permissionChecker.register();let F=[rr(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];ce(Bc({listSkills:()=>{let y=[];this.pluginLoader&&y.push(...this.pluginLoader.getPluginSkills());let T=e?.skillPaths;if(Array.isArray(T)){for(let v of T)if(typeof v=="string"){let _=J.basename(v);y.some(C=>C.name===_)||y.push({name:_,source:"gateway",filePath:J.join(v,"SKILL.md"),baseDir:v})}}return y},listSkillsFull:async y=>{let T=[],v=new Set;for(let _ of F)try{let C=await $.promises.readdir(_,{withFileTypes:!0});for(let I of C){if(!I.isDirectory())continue;let V=J.join(_,I.name,"SKILL.md");try{await $.promises.access(V);let j=J.basename(_);if(y&&j!==y)continue;v.add(j),T.push({name:I.name,description:`Skill from ${_}`,category:j})}catch{}}}catch{}if(this.pluginLoader)for(let _ of this.pluginLoader.getPluginSkills())y&&_.source!==y||(v.add(_.source??"plugin"),T.push({name:_.name,description:`Plugin skill (${_.source})`,category:_.source}));return{skills:T,categories:[...v]}},readSkillContent:async y=>{for(let T of F){let v=J.join(T,y,"SKILL.md");try{return await $.promises.readFile(v,"utf8")}catch{}}return null},viewSkill:async(y,T)=>{for(let v of F){let _=T?J.join(v,y,T):J.join(v,y,"SKILL.md");try{let C=await $.promises.readFile(_,"utf8");return{name:y,content:C}}catch{}}return null},executeSkillSubturn:async(y,T,v,_)=>{let C=`skill_${y}_${ve().slice(0,8)}`,I=this.agent;if(!I)return"[skill] Cannot execute: no LLM provider configured";let V=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:V,turnId:C,subagentId:C,agentType:`skill:${y}`}).catch(()=>{});let j=We(),re=v??`Execute skill "${y}" instructions.`,X=[],P;for await(let se of I.run({turnId:C,sessionId:V,messages:[{role:"user",content:re}],tools:j,systemPrompt:T,config:{parentDepth:1}},_)){if(se.type==="end"&&se.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:V,turnId:C,subagentId:C,agentType:`skill:${y}`,reason:"normal"}).catch(()=>{}),se.content;if(se.type==="delta"&&se.text&&X.push(se.text),se.type==="error"){P=se.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:V,turnId:C,subagentId:C,agentType:`skill:${y}`,reason:P?"error":"normal",error:P}).catch(()=>{}),P?`[skill "${y}"] error: ${P}`:X.join("")||`[skill "${y}"] completed (no output)`},manageSkill:async y=>{let T=J.join(F[0]??rr(),y.name),v=J.join(T,"SKILL.md");switch(y.action){case"create":return await $.promises.mkdir(T,{recursive:!0}),await $.promises.writeFile(v,y.content??"","utf8"),{success:!0,message:`Skill "${y.name}" created`,path:T};case"edit":return await $.promises.writeFile(v,y.content??"","utf8"),{success:!0,message:`Skill "${y.name}" updated`,path:v};case"patch":{let _=await $.promises.readFile(v,"utf8");return!y.oldString||!_.includes(y.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await $.promises.writeFile(v,_.replace(y.oldString,y.newString??""),"utf8"),{success:!0,message:`Skill "${y.name}" patched`,path:v})}case"delete":return await $.promises.rm(T,{recursive:!0,force:!0}),{success:!0,message:`Skill "${y.name}" deleted`};default:return{success:!1,message:`Unknown action: ${y.action}`}}}})),ce(Hc({abortSignal:void 0,currentForkDepth:0,forkAgent:async y=>{let T=No(y.agent);if(!T)return{agentId:"",status:"failed",error:`Unknown agent type: ${y.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let v=Be(),_=Do(v,T),I=We().filter(P=>_.includes(P.function.name)),V=Sr(I,!0),j=y.maxTurns??T.maxTurns??200,re=await Rn({promptMessages:[{role:"user",content:y.prompt}],tools:V,transport:this.currentTransport,toolInvoker:u,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:c,forkLabel:`agent-${y.agent}`,maxTurns:j,parentSignal:y.abortSignal,parentDepth:0,onEvent:P=>{P.type==="delta"&&P.text&&this.sendNotification("turn.subagent_delta",{agentType:y.agent,text:P.text})}}),X=re.events.filter(P=>P.type==="end"&&"content"in P).map(P=>P.content??"").join("")||re.events.filter(P=>P.type==="delta"&&"text"in P).map(P=>P.text).join("");return{agentId:`fork-${y.agent}-${ve().slice(0,8)}`,status:re.ok?"completed":"failed",output:X||void 0,error:re.error,tokensUsed:re.totalUsage.prompt+re.totalUsage.completion}}}));let U=dt(),D=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"]}]]),w=async()=>{try{return JSON.parse(await $.promises.readFile(U,"utf8"))}catch{return{}}},ge=async y=>{await $.promises.mkdir(J.dirname(U),{recursive:!0}),await $.promises.writeFile(U,JSON.stringify(y,null,2),"utf8")};ce(zc({getConfig:async y=>{let T=D.get(y);if(!T)return{success:!1,error:`Unknown key: ${y}`};let v=await w(),_=y in v?v[y]:T.value;return{success:!0,setting:{...T,value:_,readOnly:Yt.includes(y)}}},setConfig:async(y,T)=>{let v=D.get(y);if(!v)return{success:!1,error:`Unknown key: ${y}`};let _=await w(),C=y in _?_[y]:v.value;return _[y]=T,await ge(_),{success:!0,previousValue:C,setting:{...v,value:T}}},listConfig:async()=>{let y=await w();return{success:!0,settings:[...D.values()].map(v=>({...v,value:v.key in y?y[v.key]:v.value,readOnly:Yt.includes(v.key)}))}},resetConfig:async y=>{let T=D.get(y);if(!T)return{success:!1,error:`Unknown key: ${y}`};let v=await w();return delete v[y],await ge(v),{success:!0,setting:T}},isValidKey:y=>D.has(y)}));let H=new Map,z=y=>{let T=/^(\d+)([smhd])$/.exec(y.trim());if(!T)return null;let v=parseInt(T[1],10),_=T[2];return v*({s:1e3,m:6e4,h:36e5,d:864e5}[_]??6e4)},fe=y=>{y.timerId&&clearTimeout(y.timerId);let T=z(y.schedule);T&&(y.timerId=setTimeout(()=>{y.lastRunAt=new Date().toISOString(),y.repeat.completed++,y.lastStatus="success",l.info(`[cron] triggered job ${y.id} (${y.name})`),y.repeat.times===null||y.repeat.completed<y.repeat.times?fe(y):(y.state="paused",y.enabled=!1)},T),y.nextRunAt=new Date(Date.now()+T).toISOString())};it(async()=>{for(let y of H.values())y.timerId&&clearTimeout(y.timerId)}),ce(qc({createJob:async y=>{let T=`cron_${ve().slice(0,8)}`,v={id:T,name:y.name??`Job ${T}`,prompt:y.prompt,schedule:y.schedule,scheduleDisplay:y.schedule,state:"scheduled",enabled:!0,repeat:{times:y.repeat??null,completed:0},allowedTools:y.allowedTools};return H.set(T,v),fe(v),{success:!0,job:{...v,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...H.values()].map(T=>({...T,timerId:void 0}))}),getJob:async y=>{let T=H.get(y);return T?{success:!0,job:{...T,timerId:void 0}}:{success:!1,error:`Job not found: ${y}`}},updateJob:async(y,T)=>{let v=H.get(y);return v?(T.prompt!==void 0&&(v.prompt=T.prompt),T.schedule!==void 0&&(v.schedule=T.schedule,v.scheduleDisplay=T.schedule),T.name!==void 0&&(v.name=T.name),T.enabled!==void 0&&(v.enabled=T.enabled,v.state=T.enabled?"scheduled":"paused"),T.repeat!==void 0&&(v.repeat.times=T.repeat),T.allowedTools!==void 0&&(v.allowedTools=T.allowedTools),v.enabled?fe(v):v.timerId&&(clearTimeout(v.timerId),v.timerId=void 0),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${y}`}},deleteJob:async y=>{let T=H.get(y);return T?(T.timerId&&clearTimeout(T.timerId),H.delete(y),{success:!0}):{success:!1,error:`Job not found: ${y}`}},pauseJob:async y=>{let T=H.get(y);return T?(T.state="paused",T.enabled=!1,T.timerId&&(clearTimeout(T.timerId),T.timerId=void 0),{success:!0,job:{...T,timerId:void 0}}):{success:!1,error:`Job not found: ${y}`}},resumeJob:async y=>{let T=H.get(y);return T?(T.state="scheduled",T.enabled=!0,fe(T),{success:!0,job:{...T,timerId:void 0}}):{success:!1,error:`Job not found: ${y}`}},triggerJob:async y=>{let T=H.get(y);return T?(T.lastRunAt=new Date().toISOString(),T.repeat.completed++,T.lastStatus="success",{success:!0,job:{...T,timerId:void 0}}):{success:!1,error:`Job not found: ${y}`}},validateSchedule:y=>z(y)!==null||/^\d{1,2}\s/.test(y)?null:`Invalid schedule: ${y}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let te=new Map;it(async()=>{for(let y of te.values())y.cleanup();te.clear()}),ce(Kc({startMonitor:async y=>{if(te.has(y.monitorId))return{action:"start",success:!1,error:`Monitor "${y.monitorId}" already exists.`};let T={monitorId:y.monitorId,source:y.source,target:y.target,conditions:y.conditions,startedAt:Date.now(),timeoutSeconds:y.timeoutSeconds,eventCount:0},v=()=>{};if(y.source==="file")try{let _=$.watch(y.target,{persistent:!1},()=>{T.eventCount++,l.info(`[monitor] file change detected: ${y.target}`)});v=()=>_.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${y.target}`}}if(y.timeoutSeconds>0){let _=setTimeout(()=>{let I=te.get(y.monitorId);I&&(I.cleanup(),te.delete(y.monitorId))},y.timeoutSeconds*1e3),C=v;v=()=>{clearTimeout(_),C()}}return te.set(y.monitorId,{info:T,cleanup:v}),{action:"start",success:!0,monitorId:y.monitorId}},stopMonitor:async y=>{let T=te.get(y);return T?(T.cleanup(),te.delete(y),{action:"stop",success:!0,monitorId:y}):{action:"stop",success:!1,error:`Monitor "${y}" not found.`}},listMonitors:async()=>[...te.values()].map(y=>y.info)}));let le=new Map,G={info:y=>l.info(y),warn:y=>l.warn(y)},N=new ft({onNotification:(y,T,v)=>{this.sendNotification("team.member.notification",{memberId:y,method:T,params:v})},onStateChange:(y,T)=>{this.sendNotification("team.member.state",{memberId:y,state:T});let v=N.getHandle(y),C=N.getUsageTracker(y)?.getUsage();this.emitAgentStatus(y,T,{missedBeats:N.getMissedBeats(y),lastActivityAt:v?.lastActivityAt,usage:C&&C.totalTokens>0?{inputTokens:C.inputTokens,outputTokens:C.outputTokens,totalTokens:C.totalTokens}:void 0})},onExit:(y,T,v)=>{for(let _ of le.values()){let C=_.members.find(I=>I.cwd&&`team-${_.name}-${I.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()===y.replace(/^team-/,""));C&&(C.isActive=!1)}l.info(`[team] member ${y} exited (code=${T}, signal=${v})`)},onMcpToolCall:(y,T,v)=>this.handleMcpToolCall(y,T,v),log:{info:y=>l.info(y),warn:y=>l.warn(y),debug:y=>l.debug(y)},sessionDir:J.join(B(),"agent-logs")});it(async()=>{N.dispose()}),ce(Jc({createTeam:async y=>{if(le.has(y.teamName))return{success:!1,error:`Team "${y.teamName}" already exists.`};let T=await Vt(),v=[];for(let C of y.members??[]){let I={...C,isActive:!0};if(T){let V=`team-${y.teamName}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),j=await jl(T,V,G);j?(I.worktreePath=j.worktreePath,I.worktreeBranch=j.branch,I.cwd=j.worktreePath,l.info(`[team] provisioned worktree for ${C.name}: ${j.worktreePath}`)):(I.cwd=process.cwd(),l.warn(`[team] worktree provision failed for ${C.name}, using shared cwd`))}else I.cwd=process.cwd();v.push(I)}let _={name:y.teamName,description:y.description,leadId:this.currentSessionId??"default",members:v,createdAt:new Date().toISOString()};le.set(y.teamName,_);for(let C of v){if(!C.cwd)continue;let I=`team-${y.teamName}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();try{await N.spawn({memberId:I,name:C.name,cwd:C.cwd,prompt:`You are the "${C.name}" team member. Role: ${C.role}.`,agentType:C.role,verbose:this.verbose}),l.info(`[team] spawned child process for ${C.name} in ${C.cwd}`)}catch(V){l.warn(`[team] failed to spawn child process for ${C.name}: ${V instanceof Error?V.message:String(V)}`),C.isActive=!1}}return this.sendNotification("team.updated",{teamName:y.teamName,action:"created",members:_.members.map(C=>({agentName:C.name,role:C.role,worktreePath:C.worktreePath,pid:N.getHandle(`team-${y.teamName}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase())?.pid}))}),{success:!0,team:_}},deleteTeam:async y=>{let T=le.get(y);if(!T)return{success:!1,error:`Team "${y}" not found.`};for(let _ of T.members){let C=`team-${y}-${_.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();N.kill(C),N.remove(C)}let v=await Vt();if(v)for(let _ of T.members)_.worktreePath&&_.worktreeBranch&&(await Bl(v,_.worktreePath,_.worktreeBranch,G),l.info(`[team] cleaned up worktree for ${_.name}: ${_.worktreePath}`));return le.delete(y),this.sendNotification("team.updated",{teamName:y,action:"destroyed",members:[]}),{success:!0}},listTeams:async()=>({success:!0,teams:[...le.values()]}),getTeamStatus:async y=>{let T=le.get(y);if(!T)return{success:!1,error:`Team "${y}" not found.`};let v={};for(let _ of T.members){let C=`team-${y}-${_.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),I=N.getStatus(C);I&&(_.isActive=I.alive,v[_.name]={mediaProgress:I.mediaProgress,lastToolCall:I.lastToolCall,idleFor:I.idleFor,runningFor:I.runningFor})}return{success:!0,team:T,memberProgress:v}}}));{let y=new ao({persistToDisk:!0});y.loadFromDiskSync();let T={providerId:"null",search:async()=>[],ingest:async()=>{}},v=this.qmemoryAdapter??T;ce({name:yu,label:Tu,description:ku,parameters:bu,execute:async(_,C)=>{let I=await wu(C,{provider:v,store:y,userId:this.qmemoryUserId||this.currentSessionId||"default",sessionId:this.currentSessionId});return{content:[{type:"text",text:I.message}],details:{type:"memory",action:I.action,ok:I.ok}}}})}{let y=e?.workdir??process.cwd(),T=Zc(y,this.currentSessionId||"default");ce(Qc(T))}let pe=e?.workdir??process.cwd(),Ee=Su({projectRoot:pe,ruleEngine:R,hooks:c,log:y=>l.info(`[settings] ${y}`)});it(async()=>{Ee()}),this.currentSessionId&&c.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let me=e?.workdir??process.cwd();return La({projectRoot:me,sessionId:this.currentSessionId,hooks:c,log:y=>l.debug(y),onInstructionCacheReset:Fa}).then(y=>{this.fileWatcher=y,it(async()=>{this.fileWatcher?.stop()})}).catch(y=>{l.warn(`[file-watcher] init error: ${y instanceof Error?y.message:y}`)}),this.agent=new Mt({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:u,log:l,hooks:c,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=dt();if(!$.existsSync(e))return;let t=$.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:$i(t),agentHome:B(),settings:dt()},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=[],n=J.join(B(),"memory.json");$.existsSync(n)&&t.push({id:"local",type:"json",path:n}),this.qmemoryAdapter&&t.push({id:"qmemory",type:"vector"}),e.id!==void 0&&this.sendResponse(e.id,{sources:t})}async handleMemoryRead(e){let t=e.params,n=t?.source??"local",o=t?.target??"memory";if(n==="local")try{let s=J.join(B(),"memory.json"),i=await $.promises.readFile(s,"utf-8"),a=JSON.parse(i);e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:o,content:a[o]??""})}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:o,content:""})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.INVALID_PARAMS,message:`Unknown memory source: ${n}`})}async handleMemoryWrite(e){let t=e.params,n=t?.target??"memory",o=t?.content;if(n!=="memory"&&n!=="user"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.INVALID_PARAMS,message:`Invalid memory target: ${n}. Must be "memory" or "user".`});return}if(o==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.INVALID_PARAMS,message:"content is required."});return}try{let s=J.join(B(),"memory.json"),i={};try{let a=await $.promises.readFile(s,"utf-8");i=JSON.parse(a)}catch{}i[n]=o,i.savedAt=new Date().toISOString(),await $.promises.mkdir(B(),{recursive:!0}),await $.promises.writeFile(s,JSON.stringify(i,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,target:n}),this.sendNotification("memory.updated",{target:n,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,o=We(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:M.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(!fr(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:M.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(!fr(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:u,task:c}=await o.getTaskStatus(t.taskId,s);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,status:u,task:c});return}let i=await o.listVideoTasks(s,{limit:100}),l=(i.data??i.tasks??[]).find(u=>u.id===t.taskId||u.task_id===t.taskId);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,...l?{status:l.status,task:l}:{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=dt(),n={};if($.existsSync(t)){let o=$.readFileSync(t,"utf-8");n=JSON.parse(o)}e.id!==void 0&&this.sendResponse(e.id,{config:n,paths:{userSettings:t,agentHome:B()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.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:M.INVALID_PARAMS,message:"updates (object) is required."});return}try{let n=dt(),o={};try{let s=await $.promises.readFile(n,"utf-8");o=JSON.parse(s)}catch{}Object.assign(o,t.updates),await $.promises.mkdir(J.dirname(n),{recursive:!0}),await $.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:M.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}async handleTodosList(e){let t=ke("todo");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:mt([])});return}try{let o=(await t.execute("rpc-todos-list",{action:"list"},void 0)).content.map(a=>a.text??"").join(""),i=JSON.parse(o).todoList??[];e.id!==void 0&&this.sendResponse(e.id,{items:i,summary:mt(i)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:mt([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){try{let n=J.join(B(),"memory.json"),o=await $.promises.readFile(n,"utf-8"),s=JSON.parse(o),i=[],a=t.query.toLowerCase();for(let[l,u]of Object.entries(s)){if(typeof u!="string")continue;let c=u.split(`
433
+ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,n,o,s){if(t.filter(u=>u.role==="assistant").length<1)return;let l=[...t.slice(-6),{role:"user",content:r.SUGGESTION_PROMPT}];try{let u="";for await(let d of n.stream({model:s,messages:l,temperature:.3,maxTokens:200},o))d.type==="delta"&&(u+=d.text);let c=u.match(/\[[\s\S]*\]/);if(c){let d=JSON.parse(c[0]),p=Array.isArray(d)?d.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??xe(),o=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",l=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n});let u=new AbortController;this.activeTurn=u,this.log(`dream ${n} starting (session: ${o}, sessions reviewing: ${l.length})`);let c={provider:s?.provider,model:s?.model,apiKey:s?.apiKey,baseUrl:s?.baseUrl,maxRounds:s?.maxRounds,temperature:s?.temperature,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,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=c.provider??"",m=c.model??"";p&&m&&this.registry.getModelInfo(p,m)?.streamRequired&&(c.streamRequired=!0)}if(!this.resolveAgent(c)){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()=>l},triggerConfig:{force:!0},transport:this.currentTransport,toolInvoker:{invoke:async(g,f,b,T)=>{if(f.startsWith("$"))return{result:b};let w=we(f);if(!w)return{result:"",error:`Unknown tool: ${f}`};let _=`tc_${xe().slice(0,8)}`;try{let y=JSON.parse(b),C=await w.execute(_,y,T);return{result:C.content.map(D=>D.text??"").join(`
434
+ `),error:C.details?.error}}catch(y){return{result:"",error:y instanceof Error?y.message:String(y)}}}},tools:We(),apiKey:this.currentApiKey,model:c.model??this.currentModel,log:{info:g=>this.log(g),warn:g=>this.log(`[warn] ${g}`),error:g=>this.log(`[error] ${g}`),debug:g=>{this.verbose&&this.log(`[debug] ${g}`)}},hooks:this.currentHooks??void 0,parentSignal:u.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},m=await Ua(p);m.ok?this.sendNotification("turn.end",{turnId:n,content:`Dream consolidation completed. ${m.sessionsReviewed} sessions reviewed, ${m.filesTouched.length} files touched. Duration: ${m.durationMs}ms.`,usage:{prompt:0,completion:0}}):this.sendNotification("turn.error",{turnId:n,error:m.error??"Dream consolidation failed",code:"DREAM_FAILED"}),this.log(`dream ${n} completed`)}catch(p){if(u.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===u&&(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=br(this.registry);h&&(n=n??h.providerId,s=s??h.apiKey,o=o??h.defaultModel,this.log(`auto-detected provider: ${n}, model: ${o}`))}if(!n||!s){let h=this.loadSettingsSync();h&&(n=n??h.provider,s=s??h.apiKey,o=o??h.model,n&&s&&this.log(`loaded provider from settings.json: ${n}, model: ${o}`))}if(!n||!s)return null;o=o??this.registry.getProvider(n)?.defaultModel??"";let a=yr({provider:n,model:o,apiKey:s,baseUrl:i},this.registry);kr()&&(a.transport=Tr(a.transport,this.currentSessionId||"default"));let l={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}`)}},u={invoke:async(h,k,x,R)=>{if(k.startsWith("$"))return{result:x};let A=we(k);if(!A)return{result:"",error:`Unknown tool: ${k}`};let O=`tc_${xe().slice(0,8)}`;try{let q=JSON.parse(x),W=await A.execute(O,q,R),ae=W.content.map(X=>X.text??"").join(`
435
+ `),Q=W.details?.error,I=W.details?.type,se=I?.split("_")[0];if(I==="three_d_generate"&&(se="3d"),se&&["image","tts","video","music","3d"].includes(se)){let X=W.details?.mediaUrls??[],cn=se;for(let Se of X)this.sendNotification("turn.media_result",{turnId:h,mediaType:cn,url:Se,model:W.details?.model,provider:W.details?.provider,...W.details?.durationMs?{durationSeconds:W.details.durationMs/1e3}:{},...W.details?.taskId?{taskId:W.details.taskId}:{}})}if(I==="todo"&&!Q)try{let X=JSON.parse(ae);X.todoList&&this.sendNotification("turn.todos_updated",{turnId:h,items:X.todoList,summary:{total:X.total??X.todoList.length,completed:X.completed??0,inProgress:X.inProgress??0,notStarted:X.notStarted??0}})}catch{}let ze=Array.isArray(W.details?.matches)?W.details.matches:void 0;return{result:ae,error:Q,toolReferences:ze}}catch(q){return{result:"",error:q instanceof Error?q.message:String(q)}}}},c=ha(l);this.currentHooks=c,this.taskStore.setHooks(c,this.currentSessionId??"");let d=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(d){let h=ka({baseUrl:d,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=h,this.qmemoryUserId=this.currentSessionId??"default",ya(c,{memoryProvider:h,userId:this.currentSessionId??"default",log:{debug:k=>l.debug(k),warn:k=>l.warn(k)}},this.memoryPrefetchState)}$i(c,l,{transport:a.transport,apiKey:a.apiKey});let p=e?.mcpServers,m=hs(p??{}),g=Xi();try{if(N.existsSync(g)){let h=JSON.parse(N.readFileSync(g,"utf8")),k=hs(h),x=new Set(m.map(R=>R.name));m=[...m,...k.filter(R=>!x.has(R.name))]}}catch{}if(m.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new Zn({servers:m,log:l}),it(async()=>{await this.mcpManager?.disconnectAll()});let h=()=>this.mcpManager;me(zc(h)),me(qc(h)),me(yu({listServers:async()=>{let k=this.mcpManager;return k?k.getConnectedServers().map(R=>({name:R,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async k=>{if(!this.mcpManager)return[];let R=`mcp__${k.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return Be().filter(A=>A.startsWith(R)).map(A=>({name:A.slice(R.length),prefixedName:A}))},callTool:async(k,x,R,A)=>{let q=`mcp__${k.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+x,W=we(q);if(!W)return{success:!1,error:`Tool not found: ${q}`};try{return{success:!0,content:(await W.execute(`mcp_${Date.now()}`,R??{},A)).content.map(I=>I.text??"").join(`
436
+ `)}}catch(ae){return{success:!1,error:ae.message}}},listResources:async k=>{let x=this.mcpManager;return x?(await x.listResources(k)).map(A=>({uri:A.uri,name:A.name,mimeType:A.mimeType,description:A.description,server:A.server})):[]},readResource:async(k,x)=>{let R=this.mcpManager;if(!R)throw new Error("MCP not initialized");return(await R.readResource(k,x)).map(O=>({uri:O.uri,mimeType:O.mimeType,text:O.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpReady=this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(k=>{l.warn(`[mcp] connection error: ${k instanceof Error?k.message:k}`)})}let f=[],b=qi();N.existsSync(b)&&f.push(b);let T=e?.pluginPaths;if(Array.isArray(T))for(let h of T)typeof h=="string"&&N.existsSync(h)&&f.push(h);Xc(f,l).then(h=>{if(h.length===0)return;this.pluginLoader=new to({pluginDirs:h,hookRegistry:c,log:l}),this.pluginLoader.loadAll().then(x=>{l.info(`[plugins] ${x.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(x=>{l.warn(`[plugins] load error: ${x instanceof Error?x.message:x}`)});let k=this.pluginLoader;c.register({point:"turn.submitted",handler:async()=>(await k.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(h=>{l.warn(`[plugins] marketplace resolve error: ${h instanceof Error?h.message:h}`)});let w=e?.permissions,_=bs(w),y=new no(_);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new ro({ruleEngine:y,hookRegistry:c,onRequestApproval:async h=>(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(k=>`${k.pattern}:${k.behavior}`)}),new Promise(()=>{})),onPermissionUpdate:h=>{l.info(`[permissions] rule saved: ${h.pattern} \u2192 ${h.behavior}`),this.sendNotification("permission.rule_updated",{pattern:h.pattern,behavior:h.behavior})},onDenied:(h,k)=>{l.warn(`[permissions] blocked "${h}": ${k}`)}});let C=We();this.permissionChecker.setToolMeta(C),this.permissionUnregister=this.permissionChecker.register();let E=[ur(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];me(lu({listSkills:()=>{let h=[];this.pluginLoader&&h.push(...this.pluginLoader.getPluginSkills());let k=e?.skillPaths;if(Array.isArray(k)){for(let x of k)if(typeof x=="string"){let R=J.basename(x);h.some(A=>A.name===R)||h.push({name:R,source:"gateway",filePath:J.join(x,"SKILL.md"),baseDir:x})}}return h},listSkillsFull:async h=>{let k=[],x=new Set;for(let R of E)try{let A=await N.promises.readdir(R,{withFileTypes:!0});for(let O of A){if(!O.isDirectory())continue;let q=J.join(R,O.name,"SKILL.md");try{await N.promises.access(q);let W=J.basename(R);if(h&&W!==h)continue;x.add(W),k.push({name:O.name,description:`Skill from ${R}`,category:W})}catch{}}}catch{}if(this.pluginLoader)for(let R of this.pluginLoader.getPluginSkills())h&&R.source!==h||(x.add(R.source??"plugin"),k.push({name:R.name,description:`Plugin skill (${R.source})`,category:R.source}));return{skills:k,categories:[...x]}},readSkillContent:async h=>{for(let k of E){let x=J.join(k,h,"SKILL.md");try{return await N.promises.readFile(x,"utf8")}catch{}}return null},viewSkill:async(h,k)=>{for(let x of E){let R=k?J.join(x,h,k):J.join(x,h,"SKILL.md");try{let A=await N.promises.readFile(R,"utf8");return{name:h,content:A}}catch{}}return null},executeSkillSubturn:async(h,k,x,R)=>{let A=`skill_${h}_${xe().slice(0,8)}`,O=this.agent;if(!O)return"[skill] Cannot execute: no LLM provider configured";let q=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:q,turnId:A,subagentId:A,agentType:`skill:${h}`}).catch(()=>{});let W=We(),ae=x??`Execute skill "${h}" instructions.`,Q=[],I;for await(let se of O.run({turnId:A,sessionId:q,messages:[{role:"user",content:ae}],tools:W,systemPrompt:k,config:{parentDepth:1}},R)){if(se.type==="end"&&se.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:q,turnId:A,subagentId:A,agentType:`skill:${h}`,reason:"normal"}).catch(()=>{}),se.content;if(se.type==="delta"&&se.text&&Q.push(se.text),se.type==="error"){I=se.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:q,turnId:A,subagentId:A,agentType:`skill:${h}`,reason:I?"error":"normal",error:I}).catch(()=>{}),I?`[skill "${h}"] error: ${I}`:Q.join("")||`[skill "${h}"] completed (no output)`},manageSkill:async h=>{let k=J.join(E[0]??ur(),h.name),x=J.join(k,"SKILL.md");switch(h.action){case"create":return await N.promises.mkdir(k,{recursive:!0}),await N.promises.writeFile(x,h.content??"","utf8"),{success:!0,message:`Skill "${h.name}" created`,path:k};case"edit":return await N.promises.writeFile(x,h.content??"","utf8"),{success:!0,message:`Skill "${h.name}" updated`,path:x};case"patch":{let R=await N.promises.readFile(x,"utf8");return!h.oldString||!R.includes(h.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await N.promises.writeFile(x,R.replace(h.oldString,h.newString??""),"utf8"),{success:!0,message:`Skill "${h.name}" patched`,path:x})}case"delete":return await N.promises.rm(k,{recursive:!0,force:!0}),{success:!0,message:`Skill "${h.name}" deleted`};default:return{success:!1,message:`Unknown action: ${h.action}`}}}})),me(du({abortSignal:void 0,currentForkDepth:0,forkAgent:async h=>{let k=Ho(h.agent);if(!k)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 x=Be(),R=Wo(x,k),O=We().filter(I=>R.includes(I.function.name)),q=Er(O,!0),W=h.maxTurns??k.maxTurns??200,ae=await An({promptMessages:[{role:"user",content:h.prompt}],tools:q,transport:this.currentTransport,toolInvoker:u,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:c,forkLabel:`agent-${h.agent}`,maxTurns:W,parentSignal:h.abortSignal,parentDepth:0,onEvent:I=>{I.type==="delta"&&I.text&&this.sendNotification("turn.subagent_delta",{agentType:h.agent,text:I.text})}}),Q=ae.events.filter(I=>I.type==="end"&&"content"in I).map(I=>I.content??"").join("")||ae.events.filter(I=>I.type==="delta"&&"text"in I).map(I=>I.text).join("");return{agentId:`fork-${h.agent}-${xe().slice(0,8)}`,status:ae.ok?"completed":"failed",output:Q||void 0,error:ae.error,tokensUsed:ae.totalUsage.prompt+ae.totalUsage.completion}}}));let D=dt(),L=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"]}]]),v=async()=>{try{return JSON.parse(await N.promises.readFile(D,"utf8"))}catch{return{}}},ce=async h=>{await N.promises.mkdir(J.dirname(D),{recursive:!0}),await N.promises.writeFile(D,JSON.stringify(h,null,2),"utf8")};me(pu({getConfig:async h=>{let k=L.get(h);if(!k)return{success:!1,error:`Unknown key: ${h}`};let x=await v(),R=h in x?x[h]:k.value;return{success:!0,setting:{...k,value:R,readOnly:Zt.includes(h)}}},setConfig:async(h,k)=>{let x=L.get(h);if(!x)return{success:!1,error:`Unknown key: ${h}`};let R=await v(),A=h in R?R[h]:x.value;return R[h]=k,await ce(R),{success:!0,previousValue:A,setting:{...x,value:k}}},listConfig:async()=>{let h=await v();return{success:!0,settings:[...L.values()].map(x=>({...x,value:x.key in h?h[x.key]:x.value,readOnly:Zt.includes(x.key)}))}},resetConfig:async h=>{let k=L.get(h);if(!k)return{success:!1,error:`Unknown key: ${h}`};let x=await v();return delete x[h],await ce(x),{success:!0,setting:k}},isValidKey:h=>L.has(h)}));let j=new Map,F=h=>{let k=/^(\d+)([smhd])$/.exec(h.trim());if(!k)return null;let x=parseInt(k[1],10),R=k[2];return x*({s:1e3,m:6e4,h:36e5,d:864e5}[R]??6e4)},ne=h=>{h.timerId&&clearTimeout(h.timerId);let k=F(h.schedule);if(!k)return;let x=Date.now(),R=k-x%k||k;h.timerId=setTimeout(()=>{h.lastRunAt=new Date().toISOString(),h.repeat.completed++,h.lastStatus="success",l.info(`[cron] triggered job ${h.id} (${h.name})`),h.repeat.times===null||h.repeat.completed<h.repeat.times?ne(h):(h.state="paused",h.enabled=!1)},R),h.nextRunAt=new Date(x+R).toISOString()};it(async()=>{for(let h of j.values())h.timerId&&clearTimeout(h.timerId)}),me(gu({createJob:async h=>{let k=`cron_${xe().slice(0,8)}`,x={id:k,name:h.name??`Job ${k}`,prompt:h.prompt,schedule:h.schedule,scheduleDisplay:h.schedule,state:"scheduled",enabled:!0,repeat:{times:h.repeat??null,completed:0},allowedTools:h.allowedTools};return j.set(k,x),ne(x),{success:!0,job:{...x,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...j.values()].map(k=>({...k,timerId:void 0}))}),getJob:async h=>{let k=j.get(h);return k?{success:!0,job:{...k,timerId:void 0}}:{success:!1,error:`Job not found: ${h}`}},updateJob:async(h,k)=>{let x=j.get(h);return x?(k.prompt!==void 0&&(x.prompt=k.prompt),k.schedule!==void 0&&(x.schedule=k.schedule,x.scheduleDisplay=k.schedule),k.name!==void 0&&(x.name=k.name),k.enabled!==void 0&&(x.enabled=k.enabled,x.state=k.enabled?"scheduled":"paused"),k.repeat!==void 0&&(x.repeat.times=k.repeat),k.allowedTools!==void 0&&(x.allowedTools=k.allowedTools),x.enabled?ne(x):x.timerId&&(clearTimeout(x.timerId),x.timerId=void 0),{success:!0,job:{...x,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},deleteJob:async h=>{let k=j.get(h);return k?(k.timerId&&clearTimeout(k.timerId),j.delete(h),{success:!0}):{success:!1,error:`Job not found: ${h}`}},pauseJob:async h=>{let k=j.get(h);return k?(k.state="paused",k.enabled=!1,k.timerId&&(clearTimeout(k.timerId),k.timerId=void 0),{success:!0,job:{...k,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},resumeJob:async h=>{let k=j.get(h);return k?(k.state="scheduled",k.enabled=!0,ne(k),{success:!0,job:{...k,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},triggerJob:async h=>{let k=j.get(h);return k?(k.lastRunAt=new Date().toISOString(),k.repeat.completed++,k.lastStatus="success",{success:!0,job:{...k,timerId:void 0}}):{success:!1,error:`Job not found: ${h}`}},validateSchedule:h=>F(h)!==null||/^\d{1,2}\s/.test(h)?null:`Invalid schedule: ${h}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let re=new Map;it(async()=>{for(let h of re.values())h.cleanup();re.clear()}),me(fu({startMonitor:async h=>{if(re.has(h.monitorId))return{action:"start",success:!1,error:`Monitor "${h.monitorId}" already exists.`};let k={monitorId:h.monitorId,source:h.source,target:h.target,conditions:h.conditions,startedAt:Date.now(),timeoutSeconds:h.timeoutSeconds,eventCount:0},x=()=>{};if(h.source==="file")try{let R=N.watch(h.target,{persistent:!1},()=>{k.eventCount++,l.info(`[monitor] file change detected: ${h.target}`)});x=()=>R.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${h.target}`}}if(h.timeoutSeconds>0){let R=setTimeout(()=>{let O=re.get(h.monitorId);O&&(O.cleanup(),re.delete(h.monitorId))},h.timeoutSeconds*1e3),A=x;x=()=>{clearTimeout(R),A()}}return re.set(h.monitorId,{info:k,cleanup:x}),{action:"start",success:!0,monitorId:h.monitorId}},stopMonitor:async h=>{let k=re.get(h);return k?(k.cleanup(),re.delete(h),{action:"stop",success:!0,monitorId:h}):{action:"stop",success:!1,error:`Monitor "${h}" not found.`}},listMonitors:async()=>[...re.values()].map(h=>h.info)}));let ue=new Map,V={info:h=>l.info(h),warn:h=>l.warn(h)},B=new ht({onNotification:(h,k,x)=>{this.sendNotification("team.member.notification",{memberId:h,method:k,params:x})},onStateChange:(h,k)=>{this.sendNotification("team.member.state",{memberId:h,state:k});let x=B.getHandle(h),A=B.getUsageTracker(h)?.getUsage();this.emitAgentStatus(h,k,{missedBeats:B.getMissedBeats(h),lastActivityAt:x?.lastActivityAt,usage:A&&A.totalTokens>0?{inputTokens:A.inputTokens,outputTokens:A.outputTokens,totalTokens:A.totalTokens}:void 0})},onExit:(h,k,x)=>{for(let R of ue.values()){let A=R.members.find(O=>O.cwd&&`team-${R.name}-${O.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()===h.replace(/^team-/,""));A&&(A.isActive=!1)}l.info(`[team] member ${h} exited (code=${k}, signal=${x})`)},onMcpToolCall:(h,k,x)=>this.handleMcpToolCall(h,k,x),log:{info:h=>l.info(h),warn:h=>l.warn(h),debug:h=>l.debug(h)},sessionDir:J.join(G(),"agent-logs")});it(async()=>{B.dispose()}),me(hu({createTeam:async h=>{if(ue.has(h.teamName))return{success:!1,error:`Team "${h.teamName}" already exists.`};let k=await Jt(),x=[];for(let A of h.members??[]){let O={...A,isActive:!0};if(k){let q=`team-${h.teamName}-${A.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),W=await ic(k,q,V);W?(O.worktreePath=W.worktreePath,O.worktreeBranch=W.branch,O.cwd=W.worktreePath,l.info(`[team] provisioned worktree for ${A.name}: ${W.worktreePath}`)):(O.cwd=process.cwd(),l.warn(`[team] worktree provision failed for ${A.name}, using shared cwd`))}else O.cwd=process.cwd();x.push(O)}let R={name:h.teamName,description:h.description,leadId:this.currentSessionId??"default",members:x,createdAt:new Date().toISOString()};ue.set(h.teamName,R);for(let A of x){if(!A.cwd)continue;let O=`team-${h.teamName}-${A.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();try{await B.spawn({memberId:O,name:A.name,cwd:A.cwd,prompt:`You are the "${A.name}" team member. Role: ${A.role}.`,agentType:A.role,verbose:this.verbose}),l.info(`[team] spawned child process for ${A.name} in ${A.cwd}`)}catch(q){l.warn(`[team] failed to spawn child process for ${A.name}: ${q instanceof Error?q.message:String(q)}`),A.isActive=!1}}return this.sendNotification("team.updated",{teamName:h.teamName,action:"created",members:R.members.map(A=>({agentName:A.name,role:A.role,worktreePath:A.worktreePath,pid:B.getHandle(`team-${h.teamName}-${A.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase())?.pid}))}),{success:!0,team:R}},deleteTeam:async h=>{let k=ue.get(h);if(!k)return{success:!1,error:`Team "${h}" not found.`};for(let R of k.members){let A=`team-${h}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();B.kill(A),B.remove(A)}let x=await Jt();if(x)for(let R of k.members)R.worktreePath&&R.worktreeBranch&&(await ac(x,R.worktreePath,R.worktreeBranch,V),l.info(`[team] cleaned up worktree for ${R.name}: ${R.worktreePath}`));return ue.delete(h),this.sendNotification("team.updated",{teamName:h,action:"destroyed",members:[]}),{success:!0}},listTeams:async()=>({success:!0,teams:[...ue.values()]}),getTeamStatus:async h=>{let k=ue.get(h);if(!k)return{success:!1,error:`Team "${h}" not found.`};let x={};for(let R of k.members){let A=`team-${h}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),O=B.getStatus(A);O&&(R.isActive=O.alive,x[R.name]={mediaProgress:O.mediaProgress,lastToolCall:O.lastToolCall,idleFor:O.idleFor,runningFor:O.runningFor})}return{success:!0,team:k,memberProgress:x}}}));{let h=new mo({persistToDisk:!0});h.loadFromDiskSync();let k={providerId:"null",search:async()=>[],ingest:async()=>{}},x=this.qmemoryAdapter??k;me({name:Nu,label:Bu,description:ju,parameters:Fu,execute:async(R,A)=>{let O=await Wu(A,{provider:x,store:h,userId:this.qmemoryUserId||this.currentSessionId||"default",sessionId:this.currentSessionId});return{content:[{type:"text",text:O.message}],details:{type:"memory",action:O.action,ok:O.ok}}}})}{let h=e?.workdir??process.cwd(),k=Tu(h,this.currentSessionId||"default");me(ku(k))}let fe=e?.workdir??process.cwd(),Oe=Vu({projectRoot:fe,ruleEngine:y,hooks:c,log:h=>l.info(`[settings] ${h}`)});it(async()=>{Oe()}),this.currentSessionId&&c.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let he=e?.workdir??process.cwd();return Va({projectRoot:he,sessionId:this.currentSessionId,hooks:c,log:h=>l.debug(h),onInstructionCacheReset:Ya}).then(h=>{this.fileWatcher=h,it(async()=>{this.fileWatcher?.stop()})}).catch(h=>{l.warn(`[file-watcher] init error: ${h instanceof Error?h.message:h}`)}),this.agent=new Pt({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:u,log:l,hooks:c,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=dt();if(!N.existsSync(e))return;let t=N.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:zi(t),agentHome:G(),settings:dt()},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=[],n=J.join(G(),"memory.json");N.existsSync(n)&&t.push({id:"local",type:"json",path:n}),this.qmemoryAdapter&&t.push({id:"qmemory",type:"vector"}),e.id!==void 0&&this.sendResponse(e.id,{sources:t})}async handleMemoryRead(e){let t=e.params,n=t?.source??"local",o=t?.target??"memory";if(n==="local")try{let s=J.join(G(),"memory.json"),i=await N.promises.readFile(s,"utf-8"),a=JSON.parse(i);e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:o,content:a[o]??""})}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:o,content:""})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.INVALID_PARAMS,message:`Unknown memory source: ${n}`})}async handleMemoryWrite(e){let t=e.params,n=t?.target??"memory",o=t?.content;if(n!=="memory"&&n!=="user"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.INVALID_PARAMS,message:`Invalid memory target: ${n}. Must be "memory" or "user".`});return}if(o==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.INVALID_PARAMS,message:"content is required."});return}try{let s=J.join(G(),"memory.json"),i={};try{let a=await N.promises.readFile(s,"utf-8");i=JSON.parse(a)}catch{}i[n]=o,i.savedAt=new Date().toISOString(),await N.promises.mkdir(G(),{recursive:!0}),await N.promises.writeFile(s,JSON.stringify(i,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,target:n}),this.sendNotification("memory.updated",{target:n,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,o=We(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:P.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(!wr(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:P.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(!wr(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:u,task:c}=await o.getTaskStatus(t.taskId,s);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,status:u,task:c});return}let i=await o.listVideoTasks(s,{limit:100}),l=(i.data??i.tasks??[]).find(u=>u.id===t.taskId||u.task_id===t.taskId);e.id!==void 0&&this.sendResponse(e.id,{ok:!0,taskId:t.taskId,...l?{status:l.status,task:l}:{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=dt(),n={};if(N.existsSync(t)){let o=N.readFileSync(t,"utf-8");n=JSON.parse(o)}e.id!==void 0&&this.sendResponse(e.id,{config:n,paths:{userSettings:t,agentHome:G()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.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:P.INVALID_PARAMS,message:"updates (object) is required."});return}try{let n=dt(),o={};try{let s=await N.promises.readFile(n,"utf-8");o=JSON.parse(s)}catch{}Object.assign(o,t.updates),await N.promises.mkdir(J.dirname(n),{recursive:!0}),await N.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:P.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}async handleTodosList(e){let t=we("todo");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:mt([])});return}try{let o=(await t.execute("rpc-todos-list",{action:"list"},void 0)).content.map(a=>a.text??"").join(""),i=JSON.parse(o).todoList??[];e.id!==void 0&&this.sendResponse(e.id,{items:i,summary:mt(i)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:mt([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){try{let n=J.join(G(),"memory.json"),o=await N.promises.readFile(n,"utf-8"),s=JSON.parse(o),i=[],a=t.query.toLowerCase();for(let[l,u]of Object.entries(s)){if(typeof u!="string")continue;let c=u.split(`
430
437
  \xA7
431
- `).filter(d=>d.trim());for(let d=0;d<c.length;d++)c[d].toLowerCase().includes(a)&&i.push({id:`local-${l}-${d}`,text:c[d],score:1,source:"local"})}e.id!==void 0&&this.sendResponse(e.id,{results:i.slice(0,t.limit??10)})}catch{e.id!==void 0&&this.sendResponse(e.id,{results:[]})}return}try{let n=t.userId??(this.qmemoryUserId||"default"),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:M.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:M.INVALID_PARAMS,message:"match is required."});return}let n=t.source??"local";if(n==="local"){let o=t.target??"memory";try{let s=J.join(B(),"memory.json"),i=await $.promises.readFile(s,"utf-8"),a=JSON.parse(i),u=(a[o]??"").split(`
438
+ `).filter(d=>d.trim());for(let d=0;d<c.length;d++)c[d].toLowerCase().includes(a)&&i.push({id:`local-${l}-${d}`,text:c[d],score:1,source:"local"})}e.id!==void 0&&this.sendResponse(e.id,{results:i.slice(0,t.limit??10)})}catch{e.id!==void 0&&this.sendResponse(e.id,{results:[]})}return}try{let n=t.userId??(this.qmemoryUserId||"default"),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:P.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:P.INVALID_PARAMS,message:"match is required."});return}let n=t.source??"local";if(n==="local"){let o=t.target??"memory";try{let s=J.join(G(),"memory.json"),i=await N.promises.readFile(s,"utf-8"),a=JSON.parse(i),u=(a[o]??"").split(`
432
439
  \xA7
433
440
  `).filter(m=>m.trim()),c=u.length,d=u.filter(m=>!m.includes(t.match));a[o]=d.join(`
434
441
  \xA7
435
- `),a.savedAt=new Date().toISOString(),await $.promises.writeFile(s,JSON.stringify(a,null,2),"utf-8");let p=c-d.length;e.id!==void 0&&this.sendResponse(e.id,{ok:!0,removedCount:p,message:`Removed ${p} entries.`}),p>0&&this.sendNotification("memory.updated",{source:"local",target:o})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.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:M.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.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:M.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=ke(t);if(!o)return`Error: Unknown tool "${t}"`;let s=`mcp_${e}_${ve().slice(0,8)}`;try{return(await o.execute(s,n)).content.map(a=>a.text??"").join(`
436
- `)||"OK"}catch(i){return`Error: ${i instanceof Error?i.message:String(i)}`}}async ensureAgentConfigStore(){return this.agentConfigStore||(this.agentConfigStore=new oo(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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureSoloEvaluator(){if(!this.soloEvaluator){let e=new ft({log:{info:n=>process.stderr.write(`[solo:pm] ${n}
442
+ `),a.savedAt=new Date().toISOString(),await N.promises.writeFile(s,JSON.stringify(a,null,2),"utf-8");let p=c-d.length;e.id!==void 0&&this.sendResponse(e.id,{ok:!0,removedCount:p,message:`Removed ${p} entries.`}),p>0&&this.sendNotification("memory.updated",{source:"local",target:o})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.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:P.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.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:P.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=we(t);if(!o)return`Error: Unknown tool "${t}"`;let s=`mcp_${e}_${xe().slice(0,8)}`;try{return(await o.execute(s,n)).content.map(a=>a.text??"").join(`
443
+ `)||"OK"}catch(i){return`Error: ${i instanceof Error?i.message:String(i)}`}}async ensureAgentConfigStore(){return this.agentConfigStore||(this.agentConfigStore=new lo(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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureSoloEvaluator(){if(!this.soloEvaluator){let e=new ht({log:{info:n=>process.stderr.write(`[solo:pm] ${n}
437
444
  `),warn:n=>process.stderr.write(`[solo:pm] WARN ${n}
438
- `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,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:J.join(B(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
445
+ `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,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:J.join(G(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
439
446
  `),warn:n=>process.stderr.write(`${n}
440
- `)},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 so(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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureProductOrchestrator(){if(!this.productOrchestrator){let e=new ft({log:{info:n=>process.stderr.write(`[product:pm] ${n}
447
+ `)},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 uo(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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}ensureProductOrchestrator(){if(!this.productOrchestrator){let e=new ht({log:{info:n=>process.stderr.write(`[product:pm] ${n}
441
448
  `),warn:n=>process.stderr.write(`[product:pm] WARN ${n}
442
- `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,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:J.join(B(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
449
+ `)},onNotification:(n,o,s)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,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:J.join(G(),"agent-logs")}),t={log:{info:n=>process.stderr.write(`${n}
443
450
  `),warn:n=>process.stderr.write(`${n}
444
- `)},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 io(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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.INVALID_PARAMS,message:"agentId is required."});return}let n=J.join(B(),"agent-logs"),o=J.join(n,`${t.agentId}.stderr.log`),s="";try{s=$.readFileSync(o,"utf-8")}catch{}t.tail&&t.tail>0&&s&&(s=s.split(`
451
+ `)},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 po(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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.INVALID_PARAMS,message:"agentId is required."});return}let n=J.join(G(),"agent-logs"),o=J.join(n,`${t.agentId}.stderr.log`),s="";try{s=N.readFileSync(o,"utf-8")}catch{}t.tail&&t.tail>0&&s&&(s=s.split(`
445
452
  `).slice(-t.tail).join(`
446
- `)),e.id!==void 0&&this.sendResponse(e.id,{log:s})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:M.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:M.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:M.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:M.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:M.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:M.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:M.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:M.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){let n={jsonrpc:"2.0",method:e,params:t};this.writeStdout(n)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
447
- `)}};function Cu(r){let e={verbose:!1};for(let t of r.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}var Au=Cu(process.argv),Rk=new at({verbose:Au.verbose}),Mu=new uo({verbose:Au.verbose,transport:Rk}),Pu=()=>{Mu.stop(),process.exit(0)};process.on("SIGTERM",Pu);process.on("SIGINT",Pu);Mu.start();
453
+ `)),e.id!==void 0&&this.sendResponse(e.id,{log:s})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:P.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:P.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:P.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:P.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:P.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:P.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:P.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:P.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){let n={jsonrpc:"2.0",method:e,params:t};this.writeStdout(n)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
454
+ `)}};function Ku(r){let e={verbose:!1};for(let t of r.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}var Ju=Ku(process.argv),uT=new at({verbose:Ju.verbose}),Yu=new ho({verbose:Ju.verbose,transport:uT}),Xu=()=>{Yu.stop(),process.exit(0)};process.on("SIGTERM",Xu);process.on("SIGINT",Xu);Yu.start();