qlogicagent 1.0.0 → 1.1.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/agent.js +7 -7
- package/dist/cli.js +204 -195
- package/dist/index.js +204 -195
- package/dist/orchestration.js +10 -10
- package/dist/types/agent/tool-loop.d.ts +2 -0
- package/dist/types/agent/types.d.ts +54 -1
- package/dist/types/cli/stdio-server.d.ts +10 -0
- package/dist/types/cli/tool-bootstrap.d.ts +13 -1
- package/dist/types/llm/index.d.ts +1 -1
- package/dist/types/llm/llm-client.d.ts +1 -1
- package/dist/types/llm/media-client.d.ts +3 -4
- package/dist/types/llm/media-transport.d.ts +75 -4
- package/dist/types/llm/provider-def.d.ts +124 -3
- package/dist/types/llm/provider-registry.d.ts +5 -0
- package/dist/types/llm/provider-tool-api.d.ts +44 -0
- package/dist/types/llm/retry.d.ts +37 -0
- package/dist/types/llm/transport.d.ts +161 -2
- package/dist/types/llm/transports/anthropic-messages.d.ts +7 -0
- package/dist/types/llm/transports/minimax-media.d.ts +5 -0
- package/dist/types/llm/transports/openai-chat.d.ts +44 -3
- package/dist/types/llm/transports/realtime-transport.d.ts +183 -0
- package/dist/types/llm/transports/volcengine-grounding.d.ts +58 -0
- package/dist/types/llm/transports/volcengine-media.d.ts +50 -0
- package/dist/types/llm/transports/volcengine-responses.d.ts +60 -0
- package/dist/types/llm/transports/zhipu-media.d.ts +60 -0
- package/dist/types/llm/transports/zhipu-tool-api.d.ts +35 -0
- package/dist/types/orchestration/error-handling/error-classification.d.ts +1 -10
- package/dist/types/orchestration/index.d.ts +1 -1
- package/dist/types/orchestration/tool-cascade.d.ts +40 -0
- package/dist/types/orchestration/tool-loop/tool-schema.d.ts +4 -1
- package/dist/types/protocol/methods.d.ts +19 -0
- package/dist/types/skills/memory/memory-extractor.d.ts +1 -1
- package/dist/types/skills/tools/file-management-tool.d.ts +90 -0
- package/dist/types/skills/tools/image-generate-tool.d.ts +13 -1
- package/dist/types/skills/tools/music-generate-tool.d.ts +25 -0
- package/dist/types/skills/tools/stt-tool.d.ts +33 -0
- package/dist/types/skills/tools/three-d-generate-tool.d.ts +45 -0
- package/dist/types/skills/tools/tts-tool.d.ts +12 -0
- package/dist/types/skills/tools/video-edit-tool.d.ts +5 -2
- package/dist/types/skills/tools/video-generate-tool.d.ts +102 -2
- package/dist/types/skills/tools/video-merge-tool.d.ts +1 -1
- package/dist/types/skills/tools/video-upscale-tool.d.ts +1 -1
- package/dist/types/skills/tools/voice-clone-tool.d.ts +40 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,36 +1,39 @@
|
|
|
1
|
-
var
|
|
1
|
+
var mc=Object.defineProperty;var z=(n,e)=>()=>(n&&(e=n(n=0)),e);var Er=(n,e)=>{for(var t in e)mc(n,t,{get:e[t],enumerable:!0})};function No(n,e,t,o){return{role:"assistant",content:e||null,tool_calls:n,...t&&t.length>0?{thinkingBlocks:t}:{},...o?{reasoning_content:o}:{}}}function ct(n,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:n,content:t}}var Or=z(()=>{"use strict"});function Ne(n,e){if(!n)return!1;let t=n.toLowerCase();return e.some(o=>o instanceof RegExp?o.test(t):t.includes(o))}function Pc(n){return Ne(n,Ue.format)}function Lr(n){return Ne(n,Ue.rateLimit)}function Ac(n){return Ne(n,Ue.timeout)}function Ic(n){return gc.test(n)}function Fo(n){let e=n.toLowerCase();return e?n.length>yc?hc.test(e):Ne(e,Ue.billing)?!0:fc.test(n)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function $r(n){return Ne(n,Ue.authPermanent)}function Ec(n){return Ne(n,Ue.auth)}function Dr(n){return Ne(n,Ue.overloaded)}function De(n,e){return e.some(t=>n.includes(t))}function Oc(n){return De(n,kc)||De(n,xc)&&n.includes("limit")||n.includes("billing hard limit")||n.includes("hard limit reached")||n.includes("maximum allowed")&&n.includes("limit")}function Lc(n){let e=De(n,vc),t=n.includes("spend limit")||n.includes("spending limit"),o=De(n,Cc);return De(n,wc)&&De(n,_c)||e&&(n.includes("usage limit")||t)||e&&n.includes("limit")&&n.includes("reset")||o&&n.includes("limit")&&(t||De(n,Sc))}function $c(n){return n.trim().toLowerCase().replace(Mc,"").trim()}function Ur(n){let e=$c(n);return!e||Oc(e)?"billing":Lr(e)||Lc(e)?"rate_limit":"billing"}function Dc(n){return Rc.test(n)?Ur(n):null}function Nr(n){let e=n.match(bc);if(!e)return null;let t=Number(e[1]);return Number.isFinite(t)?{code:t,rest:(e[2]??"").trim()}:null}function Uc(n){if(!n)return!1;let e=n.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function Nc(n){let e=n.trim();if(!e)return!1;let t=Nr(e);return t?Tc.has(t.code):!1}function Fr(n,e){return typeof n!="number"||!Number.isFinite(n)?null:n===402?e?Ur(e):"billing":n===429?"rate_limit":n===401||n===403?e&&$r(e)?"auth_permanent":"auth":n===408?"timeout":n===503?e&&Dr(e)?"overloaded":"timeout":n===502||n===504?"timeout":n===529?"overloaded":n===400?e&&Fo(e)?"billing":"format":null}function Fc(n){if(!n)return!1;let e=n.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(n)||/\b404\b/.test(n)&&/not[-_ ]?found/i.test(n))}function jc(n){if(!n)return!1;let e=n.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 jr(n){if(jc(n))return"session_expired";if(Fc(n))return"model_not_found";let e=Dc(n);return e||(Ic(n)?Fo(n)?"billing":"rate_limit":Lr(n)?"rate_limit":Dr(n)?"overloaded":Nc(n)?Nr(n.trim())?.code===529?"overloaded":"timeout":Uc(n)?"timeout":Pc(n)?"format":Fo(n)?"billing":Ac(n)?"timeout":$r(n)?"auth_permanent":Ec(n)?"auth":null)}var gc,Ue,fc,hc,yc,bc,Tc,kc,xc,vc,wc,_c,Cc,Sc,Rc,Mc,Br=z(()=>{"use strict";gc=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Ue={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]},fc=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,hc=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,yc=512,bc=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i,Tc=new Set([500,502,503,504,521,522,523,524,529]),kc=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],xc=["upgrade your plan","upgrade plan","current plan","subscription"],vc=["daily","weekly","monthly"],wc=["try again","retry","temporary","cooldown"],_c=["usage limit","rate limit","organization usage"],Cc=["organization","workspace"],Sc=["billing period","exceeded","reached","exhausted"],Rc=/["']?(?: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,Mc=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i});function Ke(n,e){let t=Fr(n,e)??(e?jr(e):null);return t?Bc[t]:typeof n=="number"&&n>=400&&n<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function jo(n){return Wc.has(n)}var Bc,Wc,Wr=z(()=>{"use strict";Br();Bc={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"},Wc=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"])});function gt(n){return typeof n.compressAsync=="function"}function Hc(n,e){if(n.length<=e)return n;let t=n.slice(0,e);if(n.trimStart().startsWith("{")||n.trimStart().startsWith("[")){let s=Math.max(t.lastIndexOf("},"),t.lastIndexOf("],"),t.lastIndexOf(`}
|
|
2
2
|
`),t.lastIndexOf(`]
|
|
3
3
|
`));if(s>e*.5)return t.slice(0,s+1)+`
|
|
4
|
-
[...truncated: ${
|
|
4
|
+
[...truncated: ${n.length-s-1} chars omitted]`}let r=t.lastIndexOf(`
|
|
5
5
|
`);return r>e*.7?t.slice(0,r)+`
|
|
6
|
-
[...truncated: ${
|
|
7
|
-
[...truncated: ${
|
|
8
|
-
`)}function
|
|
9
|
-
`),i=r.filter(
|
|
6
|
+
[...truncated: ${n.length-r} chars omitted]`:t+`
|
|
7
|
+
[...truncated: ${n.length-e} chars omitted]`}function Bo(...n){return{compress(e,t){let o=e,r=0,s=[];for(let i of n){let a=i.compress(o,t);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function Wo(...n){return{compress(e,t){let o=e,r=0,s=[];for(let i of n){let a=i.compress(o,t);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(e,t){let o=e,r=0,s=[],i=0,a=!1,c=!1;for(let u of n){let l=gt(u)?await u.compressAsync(o,t):u.compress(o,t);o=l.messages,r+=l.droppedCount,l.droppedCount>0&&s.push(l.strategy),l.metrics&&(i+=l.metrics.latencyMs,a=a||l.metrics.usedLlm,c=c||!!l.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:c}:void 0}}}}function zr(n,e){let t=n.filter(i=>i.role==="user"),o=n.filter(i=>i.tool_calls!=null),r=n.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Note any critical facts, constraints, or preferences the user mentioned that must be preserved.","","### 6. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 7. User Preferences Expressed",`The user sent ${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","",...n.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),c=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${c}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),s.join(`
|
|
8
|
+
`)}function jt(n={}){let e={...Gr,...n},t=Math.floor(e.modelContextWindow*e.targetUsageRatio);return Math.max(e.minBudget,Math.min(t,e.maxBudget))}function ft(n,e){let t=n/e;return t<=.8?"none":t<=1?"trim-only":t<=1.5?"sliding-window":"llm-summarize"}function zc(n){let e=[],t=[];for(let o of n)o.role==="system"?e.push(o):t.push(o);return{system:e,nonSystem:t}}function Ho(n){let e=typeof n.content=="string"?n.content:n.content!=null?JSON.stringify(n.content):"";return Math.ceil(e.length/4)}function Ft(n){let e=Math.min(n.length,5),t=[];for(let o=0;o<e;o++){let r=n[o],s=typeof r.content=="string"?r.content.slice(0,200):"";t.push(`${r.role}:${s}`)}return t.join("|")}function Vc(n){let e=new Map;for(let t=0;t<n.length;t++){let o=n[t];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&e.set(a,t)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...e.entries()].sort((t,o)=>o[1]-t[1]).map(([t])=>t)}async function zo(n,e,t){let o=t.estimateTokens??(p=>Math.ceil(p.length/4)),r=Vc(e);if(r.length===0)return n;let s=n.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
9
|
+
`),i=r.filter(p=>!s.includes(p));if(i.length===0)return n;let a=t.maxTokenBudget,c=[],u=0;for(let p of i){if(u>=t.maxFiles||a<=0)break;let m=await t.readFile(p);if(!m)continue;let h=o(m);h>a||(a-=h,u++,c.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
10
10
|
|
|
11
|
-
${m}`}))}if(
|
|
11
|
+
${m}`}))}if(c.length===0)return n;let l=[...n],d=-1;for(let p=0;p<l.length;p++)l[p].role==="system"&&(d=p);return l.splice(d+1,0,...c),l}function Go(n,e,t=Ho){if(e.size===0)return{messages:n,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of n){let c=a.tool_call_id??"";if(c&&e.has(c)){o+=t(a),r++,e.delete(c);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}var Hr,Je,Fe,ut,dt,Gr,pt,mt,Gc,Re,Vo=z(()=>{"use strict";Hr=4,Je=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let o=[],r=[];for(let l of e)l.role==="system"?o.push(l):r.push(l);let s=t;for(let l of o)s-=this.estimateTokens(l);let i;for(let l of r)if(l.role==="user"){i=l;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],c=0;for(let l=r.length-1;l>=0;l--){let d=r[l];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&c>=Hr)break;if(s-p<0&&c<Hr){a.unshift(d),c++;continue}s-=p,a.unshift(d),c++}let u=[...o];return i&&!a.includes(i)&&u.push(i),u.push(...a),{messages:u,droppedCount:r.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},Fe=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,t){let o=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:Hc(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};ut=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??Ho,taskContext:e.taskContext}}compress(e,t){return{messages:e,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(e,t){let o=Date.now(),{system:r,nonSystem:s}=zc(e),i=e.reduce((_,S)=>_+this.config.estimateTokens(S),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,c=0;for(let _=0;_<s.length&&(s[_].role==="user"&&c++,!(c>this.config.protectedHeadExchanges));_++)a=_+1;let u=Math.max(a,s.length-this.config.protectedTailMessages);if(u<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let l=s.slice(0,a),d=s.slice(a,u),p=s.slice(u),m=zr(d,{taskContext:this.config.taskContext}),h=await this.config.summarize(d,m),y={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
12
12
|
|
|
13
|
-
${y}`},k=[...r,...u,h,...d],w=Date.now()-n,f=k.reduce((C,R)=>C+this.config.estimateTokens(R),0);return{messages:k,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:f,compressionRatio:i>0?f/i:1,latencyMs:w,usedLlm:!0,cacheInvalidated:!0}}}},Ze=class{config;constructor(e){this.config=e}compress(e,t){let n=Et(e),r=this.config.inner.compress(e,t),s=Et(r.messages),i=n!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(e,t){let n=Et(e),r=ot(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=Et(r.messages),i=n!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},_r={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};et=class{events=[];maxEvents;constructor(e=100){this.maxEvents=e}record(e){this.events.push(e),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let e=this.events.length;if(e===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let t=0,n=0,r=0,s=0,i=0;for(let a of this.events)t+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,n+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:e,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:t/e,averageLatencyMs:n/e,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},tt=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}))}};gc=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),xe=class{constructor(e=20,t=Po){this.preserveRecentCount=e;this.estimateTokens=t}preserveRecentCount;estimateTokens;compress(e,t){if(e.length<=this.preserveRecentCount)return{messages:e,droppedCount:0,strategy:"micro-compact"};let n=e.length-this.preserveRecentCount,r=0,s=0;return{messages:e.map((a,l)=>{if(l>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!gc.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return s+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function Oo(){return{stages:[]}}function Lo(o,e,t){let n=t?.thresholdMessages??40;if(o.filter(a=>a.role!=="system").length<=n)return{messages:o,stagedCount:0};let s=Rr(o,e),i=hc(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Rr(o,e),{messages:s,stagedCount:i.length}}function $o(o,e){let t=0;for(let n of e.stages)n.committed||(n.committed=!0,t++);return t===0?{messages:o,committed:0}:{messages:Mr(o,e),committed:t}}function Rr(o,e){return e.stages.filter(n=>n.committed).length===0?o:Mr(o,e)}function Mr(o,e){let t=e.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...o];for(let r of t){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),l={role:"system",content:r.summary};n.splice(s,a-s,l)}return n}function hc(o,e,t){let n=Math.max(0,o.length-Math.floor(t/2)),r=[],s=new Set(e.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<n;l++){let c=o[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}var Pr=q(()=>{"use strict"});function yc(o){return!(!o.ok||o.existingSkillName||!o.multiStep||o.toolCallCount<3||o.distinctToolCount<2)}function bc(o){return o.existingSkillName?o.feedback==="negative":!1}function rt(o,e){return bc(o)?{type:"skill.improve",skillName:o.existingSkillName,reason:"negative user feedback on existing skill execution"}:yc(o)?{type:"skill.create",suggestedName:e.suggestedName??`auto-skill-${e.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${e.tools.join(", ")}`,tools:e.tools,stepCount:o.toolCallCount}:null}var Ar=q(()=>{"use strict"});function Er(o){return o.function&&typeof o.function=="object"&&typeof o.function.name=="string"?o.function.name.trim():typeof o.name=="string"?o.name.trim():""}function Tc(o){return o==="enabled-eligible"||o==="installed-awaiting-approval"}function kc(o){return new Map((o??[]).map(e=>[e.toolName,e]))}function xc(o){if(!o.eligibility?.length)return[...o.tools];let e=kc(o.eligibility);return o.tools.filter(t=>{let n=Er(t);if(!n)return!1;let r=e.get(n);return!r||Tc(r.status)})}function vc(o){let e=[],t=o.compatibility??{},n=o.toolChoice;if(o.thinkingEnabled&&t.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&t.allowRequiredToolChoice===!1){let r=t.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&t.allowNamedToolChoice===!1){let r=t.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:e}}function Do(o){let e=vc({toolChoice:o.toolChoice,thinkingEnabled:o.thinkingEnabled,compatibility:o.compatibility}),t=e.normalizedToolChoice,n=[...e.warnings],r=xc({tools:o.tools,eligibility:o.eligibility});if(!t||t==="auto")return{tools:r,normalizedToolChoice:t,warnings:n};if(t==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(t==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof t=="object"&&!Array.isArray(t)&&t.type==="function"){let s=t.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>Er(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:t,warnings:n}}var Ir=q(()=>{"use strict"});function Or(o){return o==null?[]:typeof o=="string"?o.length>0?[{type:"text",text:o}]:[]:Array.isArray(o)?o:[{type:"text",text:String(o)}]}function Cc(o,e){return{...o,content:[...Or(o.content),...Or(e.content)]}}function _c(o){if(!o||typeof o!="object")return!1;if(o.function&&typeof o.function=="object"){let e=o.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof o.name=="string"&&o.name.length>0}function Rc(o){return new Set((o??wc).map(e=>e.trim().toLowerCase()))}function Mc(o,e){return o?Rc(e).has(o.trim().toLowerCase()):!1}function No(o){if(!Array.isArray(o)||o.length===0)return[...o];let e=o.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let l=a.tool_calls.filter(c=>_c(c));return{...a,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...a}}),t=new Set;for(let a of e)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let l of a.tool_calls)typeof l.id=="string"&&l.id&&t.add(l.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),r=new Set;for(let a of n)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&r.add(a.tool_call_id);let s=[];for(let a of n){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...u}=a;u.content!=null&&u.content!==""&&s.push(u);continue}if(l.length<a.tool_calls.length){s.push({...a,tool_calls:l});continue}}s.push(a)}let i=[];for(let a of s){let l=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&l?.role==="user"){i[i.length-1]=Cc(l,a);continue}i.push(a)}return i}function Uo(o,e){return Mc(e?.stopReason,e?.forcedStopReasons)?o.map(t=>{if(t.role!=="assistant")return{...t};let n={...t};for(let r of Sc)delete n[r];return n}):[...o]}function jo(o,e){let t=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of o)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:t}));return r}function Fo(o,e){let t=No(o),n=Uo(t,e);return jo(n,e)}var wc,Sc,Bo=q(()=>{"use strict";wc=["stop","aborted","timeout","cancelled","interrupted","error"],Sc=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function Pc(o){let e=new Set,t=new Set;for(let n of o){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&e.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id)}return[...e].filter(n=>!t.has(n))}function Ac(o){let e=new Set;for(let t of o)t.role==="tool"&&typeof t.tool_call_id=="string"&&t.tool_call_id&&e.add(t.tool_call_id);return[...e]}function Ec(o){return{round:o.round??0,maxRounds:o.maxRounds,pendingToolCallIds:[...o.pendingToolCallIds??[]],completedToolCallIds:[...o.completedToolCallIds??[]],lastStopReason:o.lastStopReason,replayMessages:[...o.replayMessages??[]]}}function Wo(o,e){return{round:o.round+1,maxRounds:o.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??o.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??o.completedToolCallIds],lastStopReason:e.lastStopReason??o.lastStopReason,replayMessages:[...e.replayMessages??o.replayMessages]}}function Ot(o,e){return{round:o.round,maxRounds:o.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??o.completedToolCallIds],lastStopReason:e.lastStopReason??o.lastStopReason,replayMessages:[...e.replayMessages??o.replayMessages]}}function Lt(o){let e=[],t=No(o.replayMessages);t.length!==o.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=Uo(t,o.options);n.some((s,i)=>s!==t[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=jo(n,o.options);return r.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Ec({maxRounds:o.maxRounds,round:o.round,lastStopReason:o.lastStopReason,replayMessages:r,pendingToolCallIds:Pc(r),completedToolCallIds:Ac(r)}),recoveryActions:e}}var Lr=q(()=>{"use strict";Bo()});function qo(o){return o?Ic.has(o):!0}function Ho(o){return o===429||o===529}function $t(o,e=500,t=32e3){let n=Math.min(e*Math.pow(2,o-1),t);return n+Math.floor(Math.random()*n*.25)}function Go(){let o=process.env.QLOGICAGENT_PERSISTENT_RETRY;return o==="1"||o==="true"}var Ic,Ph,st,$r=q(()=>{"use strict";Ic=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);Ph={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};st=class extends Error{constructor(t,n){super(`Model fallback triggered: ${t} -> ${n}`);this.originalModel=t;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function zo(o,e){if(e.allowedTools&&e.allowedTools.length>0){let t=new Set(e.allowedTools);return o.filter(n=>t.has(n))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let t=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return o.filter(n=>!t.has(n))}return e.canFork?[...o]:o.filter(t=>t!=="agent")}var Vo=q(()=>{"use strict"});function Ko(o){return jc.find(e=>e.name===o)}var Oc,Lc,$c,Dc,Nc,Uc,jc,Jo=q(()=>{"use strict";Oc={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},Lc={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},$c={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},Dc={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},Nc={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},Uc={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},jc=[Oc,Lc,$c,Dc,Nc,Uc]});var Dr=q(()=>{"use strict"});function Yo(o){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:o.maxOutputTokens,consecutiveTruncations:0,aborted:o.abortSignal?.aborted??!1}}function Xo(o,e){if(o.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let t=e.contextWindowTokens-e.responseBufferTokens-o.currentMaxOutputTokens,n=t>0?o.promptTokens/t*100:100;return o.promptTokens>=t?o.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:t-o.promptTokens}:{level:"ok"}}function Qo(o,e,t){let n=o.message?.toLowerCase()??"",r=o.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&t.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:{action:"abort",reason:n||"unknown_error"}}function Zo(o,e,t){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:o.currentMaxOutputTokens};if(o.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:o.currentMaxOutputTokens};let n=Math.min(o.currentMaxOutputTokens*2,t);return n<=o.currentMaxOutputTokens?{shouldEscalate:!1,newMax:o.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function en(o,e){return o.aborted?!0:e.abortSignal?.aborted?(o.aborted=!0,!0):!1}var Nr=q(()=>{"use strict"});function tn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function qe(o,e=Fc){return!(o.attemptedThisTurn||o.consecutiveFailures>=e.maxConsecutiveFailures)}var Fc,Ur=q(()=>{"use strict";Fc={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var He=q(()=>{"use strict";gr();wr();Io();Io();Pr();Ar();Ir();Bo();Lr();$r();Vo();Jo();Dr();Nr();Ur()});function on(o,e){let t=o.get(e.index);t||(t={id:"",name:"",arguments:""},o.set(e.index,t)),e.id&&(t.id=e.id),e.name&&(t.name+=e.name),t.arguments+=e.arguments}var nn=q(()=>{"use strict"});var jr,Fr,Br,Wr,qr,Hr,Gr,zr,Vr,Kr,it,Jr,Yr,rn,Dt=q(()=>{"use strict";jr=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Fr=3,Br=128e3,Wr=13e3,qr=16384,Hr=65536,Gr=3,zr=65536,Vr=3e4,Kr=3,it=5,Jr=5e4,Yr=2e5,rn=2e3});import{mkdir as Wc,writeFile as qc}from"fs/promises";import{join as Xr}from"path";import{tmpdir as Hc}from"os";function Zr(){return{seenIds:new Set,replacements:new Map}}function es(o){return Xr(Hc(),"qlogicagent-sessions",o,Gc)}async function Vc(o){try{await Wc(es(o),{recursive:!0})}catch{}}function Kc(o,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Xr(es(o),`${t}.txt`)}function Jc(o,e){if(o.length<=e)return{preview:o,hasMore:!1};let n=o.slice(0,e).lastIndexOf(`
|
|
14
|
-
`),r=
|
|
15
|
-
`;return e+=`Output too large (${
|
|
13
|
+
${h}`},T=[...r,...l,y,...p],x=Date.now()-o,f=T.reduce((_,S)=>_+this.config.estimateTokens(S),0);return{messages:T,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:f,compressionRatio:i>0?f/i:1,latencyMs:x,usedLlm:!0,cacheInvalidated:!0}}}},dt=class{config;constructor(e){this.config=e}compress(e,t){let o=Ft(e),r=this.config.inner.compress(e,t),s=Ft(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(e,t){let o=Ft(e),r=gt(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=Ft(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Gr={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};pt=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,o=0,r=0,s=0,i=0;for(let a of this.events)t+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:e,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:t/e,averageLatencyMs:o/e,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},mt=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}))}};Gc=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"]),Re=class{constructor(e=20,t=Ho){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 o=e.length-this.preserveRecentCount,r=0,s=0;return{messages:e.map((a,c)=>{if(c>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!Gc.has(a.name)||a.content.length<=200)return a;let u=this.estimateTokens(a);return s+=u,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}}});function qo(){return{stages:[]}}function Ko(n,e,t){let o=t?.thresholdMessages??40;if(n.filter(a=>a.role!=="system").length<=o)return{messages:n,stagedCount:0};let s=Vr(n,e),i=qc(s,e,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Vr(n,e),{messages:s,stagedCount:i.length}}function Jo(n,e){let t=0;for(let o of e.stages)o.committed||(o.committed=!0,t++);return t===0?{messages:n,committed:0}:{messages:qr(n,e),committed:t}}function Vr(n,e){return e.stages.filter(o=>o.committed).length===0?n:qr(n,e)}function qr(n,e){let t=e.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...n];for(let r of t){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),c={role:"system",content:r.summary};o.splice(s,a-s,c)}return o}function qc(n,e,t){let o=Math.max(0,n.length-Math.floor(t/2)),r=[],s=new Set(e.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<o;c++){let u=n[c];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=c),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let c=`${i}-${i+a}`;s.has(c)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}var Kr=z(()=>{"use strict"});function Kc(n){return!(!n.ok||n.existingSkillName||!n.multiStep||n.toolCallCount<3||n.distinctToolCount<2)}function Jc(n){return n.existingSkillName?n.feedback==="negative":!1}function ht(n,e){return Jc(n)?{type:"skill.improve",skillName:n.existingSkillName,reason:"negative user feedback on existing skill execution"}:Kc(n)?{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:n.toolCallCount}:null}var Jr=z(()=>{"use strict"});function Yr(n){return n.function&&typeof n.function=="object"&&typeof n.function.name=="string"?n.function.name.trim():typeof n.name=="string"?n.name.trim():""}function Yc(n){return n==="enabled-eligible"||n==="installed-awaiting-approval"}function Xc(n){return new Map((n??[]).map(e=>[e.toolName,e]))}function Qc(n){if(!n.eligibility?.length)return[...n.tools];let e=Xc(n.eligibility);return n.tools.filter(t=>{let o=Yr(t);if(!o)return!1;let r=e.get(o);return!r||Yc(r.status)})}function Zc(n){let e=[],t=n.compatibility??{},o=n.toolChoice;if(n.thinkingEnabled&&t.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&t.allowRequiredToolChoice===!1){let r=t.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&t.allowNamedToolChoice===!1){let r=t.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:e}}function Yo(n){let e=Zc({toolChoice:n.toolChoice,thinkingEnabled:n.thinkingEnabled,compatibility:n.compatibility}),t=e.normalizedToolChoice,o=[...e.warnings],r=Qc({tools:n.tools,eligibility:n.eligibility});if(!t||t==="auto")return{tools:r,normalizedToolChoice:t,warnings:o};if(t==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(t==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof t=="object"&&!Array.isArray(t)&&t.type==="function"){let s=t.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(c=>Yr(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:t,warnings:o}}var Xr=z(()=>{"use strict"});function Qr(n){return n==null?[]:typeof n=="string"?n.length>0?[{type:"text",text:n}]:[]:Array.isArray(n)?n:[{type:"text",text:String(n)}]}function ou(n,e){return{...n,content:[...Qr(n.content),...Qr(e.content)]}}function nu(n){if(!n||typeof n!="object")return!1;if(n.function&&typeof n.function=="object"){let e=n.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof n.name=="string"&&n.name.length>0}function ru(n){return new Set((n??eu).map(e=>e.trim().toLowerCase()))}function su(n,e){return n?ru(e).has(n.trim().toLowerCase()):!1}function Xo(n){if(!Array.isArray(n)||n.length===0)return[...n];let e=n.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(u=>nu(u));return{...a,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...a}}),t=new Set;for(let a of e)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let c of a.tool_calls)typeof c.id=="string"&&c.id&&t.add(c.id);let o=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&t.has(a.tool_call_id))),r=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&r.add(a.tool_call_id);let s=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let c=a.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...l}=a;l.content!=null&&l.content!==""&&s.push(l);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=[];for(let a of s){let c=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){i[i.length-1]=ou(c,a);continue}i.push(a)}return i}function Qo(n,e){return su(e?.stopReason,e?.forcedStopReasons)?n.map(t=>{if(t.role!=="assistant")return{...t};let o={...t};for(let r of tu)delete o[r];return o}):[...n]}function Zo(n,e){let t=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of n)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of n)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:t}));return r}function en(n,e){let t=Xo(n),o=Qo(t,e);return Zo(o,e)}var eu,tu,tn=z(()=>{"use strict";eu=["stop","aborted","timeout","cancelled","interrupted","error"],tu=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function iu(n){let e=new Set,t=new Set;for(let o of n){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&e.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id)}return[...e].filter(o=>!t.has(o))}function au(n){let e=new Set;for(let t of n)t.role==="tool"&&typeof t.tool_call_id=="string"&&t.tool_call_id&&e.add(t.tool_call_id);return[...e]}function lu(n){return{round:n.round??0,maxRounds:n.maxRounds,pendingToolCallIds:[...n.pendingToolCallIds??[]],completedToolCallIds:[...n.completedToolCallIds??[]],lastStopReason:n.lastStopReason,replayMessages:[...n.replayMessages??[]]}}function on(n,e){return{round:n.round+1,maxRounds:n.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??n.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??n.completedToolCallIds],lastStopReason:e.lastStopReason??n.lastStopReason,replayMessages:[...e.replayMessages??n.replayMessages]}}function Bt(n,e){return{round:n.round,maxRounds:n.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??n.completedToolCallIds],lastStopReason:e.lastStopReason??n.lastStopReason,replayMessages:[...e.replayMessages??n.replayMessages]}}function Wt(n){let e=[],t=Xo(n.replayMessages);t.length!==n.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=Qo(t,n.options);o.some((s,i)=>s!==t[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Zo(o,n.options);return r.length>o.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:lu({maxRounds:n.maxRounds,round:n.round,lastStopReason:n.lastStopReason,replayMessages:r,pendingToolCallIds:iu(r),completedToolCallIds:au(r)}),recoveryActions:e}}var Zr=z(()=>{"use strict";tn()});function nn(n){return n?cu.has(n):!0}function rn(n){return n===429||n===529}function Ht(n,e=500,t=32e3){let o=Math.min(e*Math.pow(2,n-1),t);return o+Math.floor(Math.random()*o*.25)}function sn(){let n=process.env.QLOGICAGENT_PERSISTENT_RETRY;return n==="1"||n==="true"}var cu,Dy,yt,es=z(()=>{"use strict";cu=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);Dy={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};yt=class extends Error{constructor(t,o){super(`Model fallback triggered: ${t} -> ${o}`);this.originalModel=t;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function an(n,e){if(e.allowedTools&&e.allowedTools.length>0){let t=new Set(e.allowedTools);return n.filter(o=>t.has(o))}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 n.filter(o=>!t.has(o))}return e.canFork?[...n]:n.filter(t=>t!=="agent")}var ln=z(()=>{"use strict"});function cn(n){return hu.find(e=>e.name===n)}var uu,du,pu,mu,gu,fu,hu,un=z(()=>{"use strict";uu={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},du={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},pu={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},mu={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},gu={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},fu={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},hu=[uu,du,pu,mu,gu,fu]});var ts=z(()=>{"use strict"});function dn(n){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:n.maxOutputTokens,consecutiveTruncations:0,aborted:n.abortSignal?.aborted??!1}}function pn(n,e){if(n.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let t=e.contextWindowTokens-e.responseBufferTokens-n.currentMaxOutputTokens,o=t>0?n.promptTokens/t*100:100;return n.promptTokens>=t?n.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:t-n.promptTokens}:{level:"ok"}}function mn(n,e,t){let o=n.message?.toLowerCase()??"",r=n.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&t.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function gn(n,e,t){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:n.currentMaxOutputTokens};if(n.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:n.currentMaxOutputTokens};let o=Math.min(n.currentMaxOutputTokens*2,t);return o<=n.currentMaxOutputTokens?{shouldEscalate:!1,newMax:n.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function fn(n,e){return n.aborted?!0:e.abortSignal?.aborted?(n.aborted=!0,!0):!1}var os=z(()=>{"use strict"});function hn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Ye(n,e=yu){return!(n.attemptedThisTurn||n.consecutiveFailures>=e.maxConsecutiveFailures)}var yu,ns=z(()=>{"use strict";yu={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var Xe=z(()=>{"use strict";Or();Wr();Vo();Vo();Kr();Jr();Xr();tn();Zr();es();ln();un();ts();os();ns()});function yn(n,e){let t=n.get(e.index);t||(t={id:"",name:"",arguments:""},n.set(e.index,t)),e.id&&(t.id=e.id),e.name&&(t.name+=e.name),t.arguments+=e.arguments}var bn=z(()=>{"use strict"});var rs,ss,is,as,ls,cs,us,ds,ps,ms,bt,gs,fs,Tn,zt=z(()=>{"use strict";rs=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),ss=3,is=128e3,as=13e3,ls=16384,cs=65536,us=3,ds=65536,ps=3e4,ms=3,bt=5,gs=5e4,fs=2e5,Tn=2e3});import{mkdir as Tu,writeFile as ku}from"fs/promises";import{join as hs}from"path";import{tmpdir as xu}from"os";function bs(){return{seenIds:new Set,replacements:new Map}}function Ts(n){return hs(xu(),"qlogicagent-sessions",n,vu)}async function _u(n){try{await Tu(Ts(n),{recursive:!0})}catch{}}function Cu(n,e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return hs(Ts(n),`${t}.txt`)}function Su(n,e){if(n.length<=e)return{preview:n,hasMore:!1};let o=n.slice(0,e).lastIndexOf(`
|
|
14
|
+
`),r=o>e*.5?o:e;return{preview:n.slice(0,r),hasMore:!0}}function ks(n){return n.includes(ys)}async function xs(n,e,t){await _u(t);let o=Cu(t,e);try{await ku(o,n,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:r,hasMore:s}=Su(n,Tn);return{filepath:o,originalSize:n.length,preview:r,hasMore:s}}function vs(n){let e=`${ys}
|
|
15
|
+
`;return e+=`Output too large (${n.originalSize} chars). Full output saved to: ${n.filepath}
|
|
16
16
|
|
|
17
|
-
`,e+=`Preview (first ${
|
|
18
|
-
`,e+=
|
|
17
|
+
`,e+=`Preview (first ${Tn} bytes):
|
|
18
|
+
`,e+=n.preview,e+=n.hasMore?`
|
|
19
19
|
...
|
|
20
20
|
`:`
|
|
21
|
-
`,e+=
|
|
22
|
-
...[truncated ${
|
|
21
|
+
`,e+=wu,e}async function ws(n,e,t,o=gs){if(n.length<=o||ks(n))return n;let r=await xs(n,e,t);return r?vs(r):n.slice(0,o)+`
|
|
22
|
+
...[truncated ${n.length-o} chars]`}function Ru(n){let e=[],t=[];for(let o of n)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?ks(o.content)||t.push({toolCallId:o.tool_call_id,content:o.content,size:o.content.length}):o.role==="assistant"&&t.length>0&&(e.push(t),t=[]);return t.length>0&&e.push(t),e}function Mu(n,e){let t=[],o=[],r=[];for(let s of n){let i=e.replacements.get(s.toolCallId);i!==void 0?t.push({...s,replacement:i}):e.seenIds.has(s.toolCallId)?o.push(s):r.push(s)}return{mustReapply:t,frozen:o,fresh:r}}function Pu(n,e,t){let o=[...n].sort((i,a)=>a.size-i.size),r=[],s=e+n.reduce((i,a)=>i+a.size,0);for(let i of o){if(s<=t)break;r.push(i),s-=i.size}return r}async function _s(n,e,t,o=fs){let r=Ru(n);if(r.length===0)return{messages:n,newlyReplacedCount:0};let s=new Map,i=[];for(let l of r){let{mustReapply:d,frozen:p,fresh:m}=Mu(l,e);for(let f of d)s.set(f.toolCallId,f.replacement);if(m.length===0){for(let f of l)e.seenIds.add(f.toolCallId);continue}let h=p.reduce((f,_)=>f+_.size,0),y=m.reduce((f,_)=>f+_.size,0),T=h+y>o?Pu(m,h,o):[],x=new Set(T.map(f=>f.toolCallId));for(let f of l)x.has(f.toolCallId)||e.seenIds.add(f.toolCallId);T.length>0&&i.push(...T)}if(s.size===0&&i.length===0)return{messages:n,newlyReplacedCount:0};let a=await Promise.all(i.map(async l=>{let d=await xs(l.content,l.toolCallId,t);return{candidate:l,result:d}})),c=0;for(let{candidate:l,result:d}of a){if(e.seenIds.add(l.toolCallId),!d)continue;let p=vs(d);s.set(l.toolCallId,p),e.replacements.set(l.toolCallId,p),c++}return s.size===0?{messages:n,newlyReplacedCount:0}:{messages:n.map(l=>{if(l.role!=="tool"||!l.tool_call_id)return l;let d=s.get(l.tool_call_id);return d===void 0?l:{...l,content:d}}),newlyReplacedCount:c}}var vu,ys,wu,kn=z(()=>{"use strict";zt();vu="tool-results",ys="<persisted-output>",wu="</persisted-output>"});function Eu(n){try{return JSON.parse(n)}catch{return}}var Au,Iu,Gt,Cs=z(()=>{"use strict";Xe();kn();Au=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),Iu=new Set(["bash","execute_command","Bash","shell"]),Gt=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??Au,this.siblingAbortController=new AbortController,e.signal&&e.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(e){let t=this.concurrencySafe.has(e.function.name);this.tools.push({id:e.id,toolCall:e,status:"queued",isConcurrencySafe:t,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(r=>r.status==="executing"),o=this.config.maxConcurrentTools;return o&&o>0&&t.length>=o?!1:t.length===0||e&&t.every(r=>r.isConcurrencySafe)}async processQueue(){for(let e of this.tools)if(e.status==="queued"){if(this.canExecuteTool(e.isConcurrencySafe))await this.executeTool(e);else if(!e.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(e){let t;try{t=JSON.parse(e.toolCall.function.arguments)}catch{}let o=t?.command??t?.file_path??t?.pattern??"";if(typeof o=="string"&&o.length>0){let r=o.length>40?o.slice(0,40)+"\u2026":o;return`${e.toolCall.function.name}(${r})`}return e.toolCall.function.name}createSyntheticError(e,t){let o=this.erroredToolDescription,r=t==="user_interrupted"?"User rejected tool use":t==="discarded"?"Streaming fallback - tool execution discarded":o?`Cancelled: parallel tool call ${o} errored`:"Cancelled: parallel tool call errored";return{callId:e.id,toolName:e.toolCall.function.name,ok:!1,error:r,message:ct(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:c,log:u}=this.config,l=e.toolCall.function.name,d=!1,p=e.toolCall.function.arguments;if(i)try{let f=await i.invoke("tool.before_invoke",{sessionId:a,turnId:c,callId:e.id,toolName:l,arguments:Eu(p)});if(f.action==="abort"){let _=f.reason??"blocked by policy";u.info(`tool ${l} blocked: ${_}`),e.results.push({callId:e.id,toolName:l,ok:!1,error:_,blocked:!0,blockReason:_,message:ct(e.id,{ok:!1,error:_})}),e.status="completed";return}f.action==="continue"&&f.context?.arguments&&(p=JSON.stringify(f.context.arguments))}catch{}let m=await s.invoke(c,l,p,this.siblingAbortController.signal),h=this.getAbortReason();if(h&&!d){e.results.push(this.createSyntheticError(e,h)),e.status="completed";return}let y=!m.error,T=m.result;y&&T&&T.length>5e4&&(T=await ws(T,e.id,a));let x=ct(e.id,{ok:y,payload:T,error:m.error});y||(d=!0,Iu.has(l)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(y?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:c,callId:e.id,toolName:l,ok:y,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:l,ok:y,error:m.error,message:x}),e.status="completed"})();e.promise=o,o.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let e of this.tools)if(e.status!=="yielded"){if(e.status==="completed"&&e.results.length>0){e.status="yielded";for(let 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(o=>o.status==="executing"&&o.promise).map(o=>o.promise),t=new Promise(o=>{this.progressResolve=o});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 Ou}from"node:fs/promises";function je(n){let e=typeof n.content=="string"?n.content:n.content!=null?JSON.stringify(n.content):"";return Math.ceil(e.length/4)}function Be(n){let e=0;for(let t of n)e+=je(t);return e}function Ms(n){if(!n)return 128e3;if(n in xn)return xn[n];let e=n.toLowerCase();for(let[t,o]of Object.entries(xn))if(e.startsWith(t.toLowerCase()))return o;return 128e3}function $u(n,e){return async(t,o)=>{let r=e?.transport,s=e?.apiKey;if(!r||!s)return n.debug("[context-compression] no LLM transport for summarization \u2014 using sync fallback"),vn(t);try{let i="",a=e?.model??Lu;for await(let c of r.stream({model:a,messages:[{role:"system",content:"You are a precise conversation summarizer."},{role:"user",content:o}],maxTokens:2e3,temperature:.3},s,AbortSignal.timeout(3e4)))c.type==="delta"&&(i+=c.text);return i||(n.warn("[context-compression] empty summary response"),vn(t))}catch(i){return n.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),vn(t)}}}function vn(n){let e=n.filter(o=>o.role==="user"),t=e.slice(0,10).map(o=>{let r=typeof o.content=="string"?o.content:JSON.stringify(o.content??"");return`- ${r.slice(0,200)}${r.length>200?"...":""}`});return`User requests (${e.length} messages):
|
|
23
23
|
${t.join(`
|
|
24
|
-
`)}`}function su(){return Ro(new Ee(cn),new xe(20,Ie),new We(Ie))}function ls(o,e){let t=Mo(new Ee(cn),new xe(20,Ie),new Qe({protectedHeadExchanges:1,protectedTailMessages:8,summarize:o,estimateTokens:Ie}),new We(Ie));return new Ze({inner:t,estimateTokens:Ie,onCacheInvalidated:e?.onCacheInvalidated})}function ds(o,e){let t=e?.budget??It({modelContextWindow:cs(e?.model)}),r=(e?.pipeline??su()).compress(o,t);if(r.droppedCount>0){let s=Oe(o),i=Oe(r.messages);us.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:s,tokensAfter:i,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:nt(s,t)})}return r.droppedCount>0&&un?.(r.droppedCount,Oe(r.messages)),r}async function iu(o,e,t){let n=t??It({modelContextWindow:cs(e.model)}),r=Oe(o),s=nt(r,n),i;switch(s){case"none":i={messages:o,droppedCount:0,strategy:"none"};break;case"trim-only":i=new Ee(cn).compress(o,n);break;case"sliding-window":{i=await ls(e.summarize).compressAsync(o,n);break}case"llm-summarize":{let a=e.pipeline??ls(e.summarize);i=ot(a)?await a.compressAsync(o,n):a.compress(o,n);break}}return i.droppedCount>0&&(i={...i,messages:await Ao(i.messages,o,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await ou(a,"utf-8")}catch{return null}}})}),au(o,i,n),i}function au(o,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let n=e.metrics?.tokensBefore||Oe(o),r=e.metrics?.tokensAfter||Oe(e.messages);us.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:n,tokensAfter:r,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:nt(n,t)})}if(e.droppedCount>0){let n=e.metrics?.tokensAfter||Oe(e.messages);un?.(e.droppedCount,n)}}function lu(o,e){let t=ru(o,e),n={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return iu(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};as.register(n),as.activate(n.id),o.info(`[context-compression] registered context engine: ${n.id}`)}function ps(o,e,t){lu(e,t),o.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(n,r)=>{let s=r.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),un=(n,r)=>{e.debug(`[context-compression] after_compact: removed ${n}, ${r} tokens remaining`),o.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:n,tokenCount:r}).catch(()=>{})}}var an,cn,nu,us,as,un,dn=q(()=>{"use strict";He();an={"deepseek-chat":64e3,"deepseek-reasoner":64e3,"deepseek-v4-flash":64e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};cn=8e3,nu="deepseek-chat",us=new et(200),as=new tt;un=null});function ms(o,e,t){let n=t-e;return`[Budget] ${Math.round(o)}% used (${e.toLocaleString()} / ${t.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(o>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var gs=q(()=>{"use strict"});var fs={};mr(fs,{resolveToolEligibility:()=>mu});function uu(o,e){if(cu.some(t=>t.test(o)))return!0;if(e)for(let t of e)try{if(new RegExp(t,"i").test(o))return!0}catch{}return!1}function du(o,e){let t=o.function.name,n=o.meta,r=[];return e.blockedToolNames?.includes(t)?(r.push("policy_blocked"),{level:5,reasons:r}):n?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):n?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):n?.isDangerous||uu(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function pu(o){switch(o){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function mu(o,e={}){let t=new Map,n=[],r=[],s=[];for(let i of o){let a=i.function.name,{level:l,reasons:c}=du(i,e),u=pu(l),p={toolName:a,status:u,permissionLevel:l,approvalRequired:l===4,reasonCodes:c};t.set(a,p),l===5?r.push(p):(n.push(i),l===4&&s.push(p))}return{eligibleTools:n,blockedTools:r,approvalRequiredTools:s,eligibilityByName:t}}var cu,hs=q(()=>{"use strict";cu=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function hu(o){let e=o.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(e)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(e)?"diagram":["csv","tsv","xlsx","xls"].includes(e)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(e)?"code":"file"}function yu(o){let e=o.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[e]}function bu(o){return typeof o=="number"&&Number.isFinite(o)&&o>=1?Math.min(Math.round(o),100):jr}function ys(o){let e=o.message.toLowerCase();return o.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function Tu(o){return o==="length"||o==="max_tokens"}function bs(o){let e=o.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(o.status===413||e.includes("too large")||e.includes("size"))}function ku(o){let e=o.headers;if(!e)return null;let t=e["retry-after"]??e["Retry-After"];if(!t)return null;let n=parseInt(t,10);return!isNaN(n)&&n>0?n*1e3:null}function xu(o){if(o.status!==400)return null;let e=o.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!e?.[1]||!e?.[3])return null;let t=parseInt(e[1],10),n=parseInt(e[3],10);if(isNaN(t)||isNaN(n))return null;let r=n-t-1e3;return r>=3e3?r:null}function vu(o){return o.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Ts(o,e,t,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:l,apiKey:c,temperature:u,hooks:p,signal:d}=o,m={sessionId:s,turnId:r},y=o.maxTurns??0,h=o.querySource,{resolveToolEligibility:k}=await Promise.resolve().then(()=>(hs(),fs)),w=k(a,o.toolEligibilityContext),f=w.eligibleTools;for(let B of w.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:B.toolName,reason:"blocked-by-policy"};if(!f.length){yield*wu(r,l,i,c,u,d,e,n);return}let C=bu(o.maxRounds),R={contextWindowTokens:o.contextWindowTokens??Br,responseBufferTokens:Wr,maxOutputTokens:o.maxOutputTokens??qr,abortSignal:d,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,K=0,D=f,F,T={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Yo(R),reactiveCompactState:tn(),toolLoopState:Lt({maxRounds:C,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:Oo(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:Zr()};for(;;){let{messages:B,maxOutputTokensRecoveryCount:J,hasAttemptedReactiveCompact:Q,maxOutputTokensOverride:ke,turnCount:oe,guardState:$,reactiveCompactState:A,collapseStore:le}=T,{toolLoopState:se}=T;if(F){try{let x=await F;x&&(yield{type:"tool_use_summary",turnId:r,summary:x})}catch{}F=void 0}if(o.refreshTools&&oe>1){let x=o.refreshTools();x!==D&&(D=x,n.debug(`tools refreshed: ${x.length} tools`))}if(en($,R)){n.info(`turn aborted by guard at turn ${oe}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let ce=Xo($,R);if(ce.level==="blocking"){ce.reason==="prompt_too_long"&&qe(A)&&(A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ce.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${ce.reason}), ending tool loop`);break}ce.level==="warning"&&n.info(`token budget warning: ${ce.usagePercent}% used, ${ce.remainingTokens} remaining`);let g;{let x=await ss(B,T.contentReplacementState,s);g=x.messages,x.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${x.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${x.newlyReplacedCount} persisted`})}{let x=Eo(g,T.snipRemovedIds);g=x.messages,x.removedCount>0&&(n.info(`snip: removed ${x.removedCount} messages, freed ~${x.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${x.removedCount} messages`})}{let S=new xe().compress(g,0);S.droppedCount>0&&(g=S.messages,n.info(`microcompact: cleared ${S.droppedCount} old tool results`))}if(g=Lo(g,le).messages,$.promptTokens>0){let x=ds(g,{budget:R.contextWindowTokens*.75,model:T.currentModel});x.droppedCount>0&&(g=x.messages,n.info(`autocompact: ${x.strategy}, dropped ${x.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${x.strategy}: ${x.droppedCount} dropped`},T.hasAttemptedReactiveCompact=!1,p?.invoke("context.after_compact",{...m,removedCount:x.droppedCount}).catch(()=>{}))}g=vu(g);let b=Do({tools:D,toolChoice:o.toolChoice??"auto"}),v=Lt({maxRounds:C,replayMessages:g,lastStopReason:se.lastStopReason,options:{stopReason:se.lastStopReason}}),_=b.extraSystemPrompt?[{role:"system",content:b.extraSystemPrompt},...v.state.replayMessages]:v.state.replayMessages;se=v.state,v.recoveryActions.length>0&&n.debug(`tool loop recovery: ${v.recoveryActions.map(x=>x.detail??x.kind).join("; ")}`),n.debug(`turn ${oe}, messages: ${_.length}`),p?.invoke("turn.before_inference",{...m,model:T.currentModel}).catch(()=>{});let M=!1,W=[],Z=new Map,z="stop",j,E=null,O=!1;try{for await(let x of e.stream({model:T.currentModel,messages:_,tools:b.tools,toolChoice:b.normalizedToolChoice??"auto",temperature:u,maxTokens:(ke??$.currentMaxOutputTokens)||void 0},c,d))switch(x.type){case"delta":W.push(x.text),M||(yield{type:"delta",turnId:r,text:x.text});break;case"tool_call_delta":M=!0,on(Z,x);break;case"reasoning_delta":break;case"usage":j={prompt:x.promptTokens,completion:x.completionTokens,reasoning:x.reasoningTokens,cacheRead:x.cacheReadTokens,cacheCreation:x.cacheCreationTokens};break;case"done":z=x.finishReason;break}if(M||p?.invoke("turn.after_inference",{...m,model:T.currentModel}).catch(()=>{}),o.postSamplingHooks&&o.postSamplingHooks.length>0){let x=T.currentModel;for(let S of o.postSamplingHooks)try{S({messages:[...g],model:x,sessionId:s})}catch{}}}catch(x){if(x instanceof st&&o.fallbackModel){n.info(`model fallback triggered: ${x.originalModel} \u2192 ${x.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${x.originalModel} \u2192 ${x.fallbackModel}`},T={...T,currentModel:x.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let S=x instanceof Error?x.message:String(x),G=typeof x?.status=="number"?x.status:void 0;if(!G&&S&&(S.includes("ECONNRESET")||S.includes("EPIPE"))){let ie=(T.consecutiveApiRetries??0)+1;if(ie>it){n.info(`stale connection retry limit reached (${it}), aborting`),yield{type:"error",turnId:r,error:S,code:"RETRIES_EXHAUSTED"};return}n.info(`stale connection (${S.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:S.slice(0,80)},T={...T,consecutiveApiRetries:ie,transition:void 0};continue}let ue=xu({status:G,message:S});if(ue!==null){n.info(`max_tokens overflow: adjusting to ${ue}`),$.currentMaxOutputTokens=ue,T={...T,maxOutputTokensOverride:ue,transition:void 0};continue}if(Ho(G)){if(T.consecutive529Errors++,T.consecutive529Errors>=Kr&&o.fallbackModel&&T.currentModel!==o.fallbackModel){n.info(`529 \xD7 ${T.consecutive529Errors}: triggering fallback to ${o.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${T.consecutive529Errors}`},T={...T,currentModel:o.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Go()){let ie=$t(T.consecutive529Errors);n.info(`persistent retry: waiting ${ie}ms (attempt ${T.consecutive529Errors})`);let V=ie;for(;V>0;){if(d?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(V/1e3)}s (${G})`};let de=Math.min(V,Vr);await new Promise($l=>setTimeout($l,de)),V-=de}T={...T,transition:void 0};continue}if(qo(h)){let V=ku({status:G,message:S})??$t(T.consecutive529Errors);n.info(`transient ${G}: retry in ${V}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${G} retry in ${V}ms`},await new Promise(de=>setTimeout(de,V)),T={...T,transition:void 0};continue}n.info(`background source ${h}: not retrying ${G}`)}E={status:G,message:S}}if(E&&p?.invoke("turn.after_inference",{...m,model:T.currentModel,response:{error:E.message}}).catch(()=>{}),E)if(ys(E))O=!0,n.info(`withheld prompt_too_long error (status=${E.status})`);else if(bs(E))O=!0,n.info(`withheld media_size error (status=${E.status})`);else{let x=Qo({status:E.status??500,message:E.message},$,R);if(x.action==="reactive_compact"&&qe(A)&&(A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${E.status??500}: ${E.message}`}),x.action==="retry"){let G=(T.consecutiveApiRetries??0)+1;if(G>it){n.info(`API retry limit reached (${it}), aborting`);let ue=Be(E.status,E.message);yield{type:"error",turnId:r,error:E.message,code:ue};return}yield{type:"recovery",turnId:r,action:"retry",detail:x.reason},T={...T,consecutiveApiRetries:G,transition:void 0};continue}let S=Be(E.status,E.message);p?.invoke("stop.failure",{sessionId:s,reason:S,error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:S};return}j&&(T.totalUsage.prompt+=j.prompt,T.totalUsage.completion+=j.completion,j.reasoning&&(T.totalUsage.reasoning=(T.totalUsage.reasoning??0)+j.reasoning),j.cacheRead&&(T.totalUsage.cacheRead=(T.totalUsage.cacheRead??0)+j.cacheRead),j.cacheCreation&&(T.totalUsage.cacheCreation=(T.totalUsage.cacheCreation??0)+j.cacheCreation)),j?.prompt&&($.promptTokens=j.prompt),T.finalText=W.join("");let N=[...Z.values()].map(x=>({id:x.id||`tc_${r}_${oe}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:x.name,arguments:x.arguments}}));if(N.length===0&&!M){if(O&&E&&ys(E)){if(T.transition?.reason!=="collapse_drain_retry"){let x=$o(g,le);if(x.committed>0){n.info(`collapse drain: committed ${x.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${x.committed} stages committed`},T={...T,messages:x.messages,transition:{reason:"collapse_drain_retry",committed:x.committed}};continue}}if(qe(A)){A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},T={...T,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),p?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:"PROMPT_TOO_LONG"};return}if(O&&E&&bs(E)){if(qe(A)){A.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},T={...T,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),p?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:"IMAGE_ERROR"};return}if(Tu(z)){$.consecutiveTruncations+=1;let x=o.modelMaxOutputTokens??Hr,S=Zo($,R,x);if(S.shouldEscalate&&ke===void 0){$.currentMaxOutputTokens=S.newMax,n.info(`max_output_tokens escalate: ${S.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${S.newMax} tokens`},T={...T,maxOutputTokensOverride:zr,transition:{reason:"max_output_tokens_escalate"}};continue}if(J<Gr){let G={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${J+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${J+1}`},T={...T,messages:[...g,G],maxOutputTokensRecoveryCount:J+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:J+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else $.consecutiveTruncations=0;if(se=Ot(se,{replayMessages:B,lastStopReason:"completed"}),p){let x=await p.invoke("stop",{sessionId:s,reason:"completed"});if(x.action==="prevent"){n.info(`stop hook prevented continuation: ${x.reason??"no reason"}`),yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}if(x.action==="abort"){let S=x.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${S}`);let G={role:"user",content:S};T={...T,messages:[...B,{role:"assistant",content:T.finalText},G],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(o.tokenBudget&&o.tokenBudget>0){let x=T.totalUsage.prompt+T.totalUsage.completion+(T.totalUsage.reasoning??0),S=x/o.tokenBudget*100;if(S<90){let G={role:"user",content:ms(S,x,o.tokenBudget)};n.info(`token budget continuation: ${Math.round(S)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(S)}% used`},T={...T,messages:[...B,{role:"assistant",content:T.finalText},G],transition:{reason:"token_budget_continuation"}};continue}}if(K>0){let x={ok:!0,toolCallCount:K,distinctToolCount:L.size,multiStep:K>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},S=rt(x,{tools:[...L]});S&&(yield{type:"skill_instruction",turnId:r,instruction:S})}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}for(let x of N){let S=x.function.arguments,G=D.find(ue=>ue.function.name===x.function.name);if(G?.backfillObservableInput)try{let ue=JSON.parse(x.function.arguments),ie={...ue};G.backfillObservableInput(ie),Object.keys(ie).some(de=>!(de in ue))&&(S=JSON.stringify(ie))}catch{}yield{type:"tool_call",turnId:r,callId:x.id,name:x.function.name,arguments:S}}B.push(So(N,T.finalText||void 0)),se=Wo(se,{replayMessages:B,pendingToolCallIds:N.map(x=>x.id),completedToolCallIds:se.completedToolCallIds,lastStopReason:"tool_calls"});let Pt=[];try{let x=new Nt({toolInvoker:t,hooks:p,sessionId:s,turnId:r,log:n,signal:d,maxConcurrentTools:o?.maxConcurrentTools});for(let S of N)x.addTool(S);for await(let S of x.getRemainingResults()){S.blocked&&(yield{type:"tool_blocked",turnId:r,callId:S.callId,name:S.toolName,reason:S.blockReason??"blocked"}),B.push(S.message),Pt.push(S.callId),L.add(S.toolName),K++;let G=typeof S.message?.content=="string"?S.message.content:"",ue=S.ok&&G?G.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:S.callId,name:S.toolName,ok:S.ok,error:S.error,outputPreview:ue},S.ok){let ie=N.find(V=>V.id===S.callId);if(ie){if(S.toolName==="plan_mode")try{let V=JSON.parse(ie.function.arguments);V.action==="exit"&&typeof V.plan=="string"&&V.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:V.plan})}catch{}if(fu.has(S.toolName))try{let V=JSON.parse(ie.function.arguments),de=typeof V.file_path=="string"?V.file_path:typeof V.filePath=="string"?V.filePath:typeof V.path=="string"?V.path:void 0;de&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${S.callId}`,artifactType:hu(de),title:de.split(/[\\/]/).pop()||de,filePath:de,language:yu(de)})}catch{}}}}}catch(x){let S=x instanceof Error?x.message:String(x);yield{type:"error",turnId:r,error:S,code:"TOOL_EXECUTION_ERROR"};return}if(se=Ot(se,{replayMessages:B,completedToolCallIds:[...se.completedToolCallIds,...Pt],lastStopReason:"tool_calls"}),o.generateToolUseSummary&&N.length>0){let x=N.map(S=>({name:S.function.name,arguments:S.function.arguments}));F=o.generateToolUseSummary(x).catch(()=>null)}let At=B.slice(-N.length),Ll=At.length>0&&At.every(x=>{let S=x?.content;return typeof S!="string"?!1:S.startsWith("Error: ")}),Ye=T.consecutiveFailedRounds;if(Ll){if(Ye+=1,Ye>=Fr&&T.finalText){n.info(`early exit: ${Ye} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}}else Ye=0;let wo=oe+1;if(y>0&&wo>y){if(n.info(`max turns reached (${y}), completing`),p){let x=await p.invoke("stop",{sessionId:s,reason:"max_turns"});if(x.action==="abort"){let S=x.reason??"Stop hook requested continuation after max_turns";T={...T,messages:[...B,{role:"assistant",content:T.finalText},{role:"user",content:S}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}if(wo>C){if(n.info(`tool loop budget exhausted (${C} rounds), returning`),K>0){let x={ok:!0,toolCallCount:K,distinctToolCount:L.size,multiStep:K>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},S=rt(x,{tools:[...L]});S&&(yield{type:"skill_instruction",turnId:r,instruction:S})}yield{type:"end",turnId:r,content:T.finalText,usage:T.totalUsage,model:T.currentModel};return}T={messages:B,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:wo,transition:{reason:"next_turn"},guardState:$,reactiveCompactState:A,toolLoopState:se,consecutiveFailedRounds:Ye,finalText:T.finalText,totalUsage:T.totalUsage,collapseStore:le,currentModel:T.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:T.stopHookActive,snipRemovedIds:T.snipRemovedIds,contentReplacementState:T.contentReplacementState}}}async function*wu(o,e,t,n,r,s,i,a){let l=[],c;a.debug(`single LLM round, messages: ${t.length}`);for await(let u of i.stream({model:e,messages:t,temperature:r},n,s))switch(u.type){case"delta":l.push(u.text),yield{type:"delta",turnId:o,text:u.text};break;case"usage":c={prompt:u.promptTokens,completion:u.completionTokens,reasoning:u.reasoningTokens,cacheRead:u.cacheReadTokens,cacheCreation:u.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:o,content:l.join(""),usage:c??{prompt:0,completion:0},model:e}}var fu,ks=q(()=>{"use strict";nn();He();is();dn();gs();sn();Dt();fu=new Set(["write","edit","patch","apply_patch"])});var vs={};mr(vs,{Agent:()=>Ge});var Ge,Ut=q(()=>{"use strict";He();ks();Dt();Ge=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(e){this.transport=e.llmTransport,this.apiKey=e.apiKey,this.toolInvoker=e.toolInvoker,this.log=e.log,this.hooks=e.hooks,this.maxRounds=Math.min(e.maxRounds??25,100)}async*run(e,t){let{turnId:n,messages:r,tools:s,systemPrompt:i,config:a}=e,l={sessionId:e.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let c=Fo(r),u=[];if(i&&u.push({role:"system",content:i}),u.push(...c),this.hooks){let m=c.filter(h=>h.role==="user").pop(),y=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(y)try{let h=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:n,query:y}),k=h?.context?.recalledMemories;if(k&&k.length>0){let w=k.map(f=>`- ${f.text}`).join(`
|
|
25
|
-
`);
|
|
26
|
-
${
|
|
27
|
-
`)}start(){let e=
|
|
28
|
-
`)}};import{randomUUID as ye}from"node:crypto";Ut();nn();var lt=class{supportedTypes=["image","video","3d"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4}async generate(e,t,n){switch(e.mediaType){case"image":return this.generateImage(e,t,n);case"video":return this.generateVideo(e,t,n);case"3d":return this.generate3D(e,t,n);default:throw new Error(`VolcengineMediaTransport: unsupported mediaType "${e.mediaType}"`)}}canHandle(e){return!!this.supportedTypes.includes(e.mediaType)}async generateImage(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v3/images/generations`,i={model:e.model,prompt:e.prompt,size:e.size??"1024x1024",n:e.n??1,response_format:"url"};e.imageUrl&&(i.image=e.imageUrl);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${u}`)}return{mediaUrls:((await a.json()).data??[]).map(u=>u.url).filter(u=>!!u),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r}}async generateVideo(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=[];if(e.sourceVideos?.length)for(let p of e.sourceVideos)i.push({type:"video_url",video_url:{url:p}});if(e.referenceImages?.length)for(let p of e.referenceImages)i.push({type:"image_url",image_url:{url:p}});else e.imageUrl&&i.push({type:"image_url",image_url:{url:e.imageUrl}});e.prompt&&i.push({type:"text",text:e.prompt});let a={model:e.model,content:i};e.duration&&(a.duration=e.duration),e.aspectRatio&&(a.aspect_ratio=e.aspectRatio),e.resolution&&(a.resolution=e.resolution);let l=await this.submitTask(s,a,t,n),c=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${l}`,t,n),u=[];if(Array.isArray(c.content))for(let p of c.content)p?.type==="video_url"&&p.video_url?.url&&u.push(p.video_url.url);return{mediaUrls:u,model:e.model,durationMs:Date.now()-r}}async generate3D(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v3/3d-contents/generations/tasks`,i={model:e.model};e.imageUrl&&(i.image={url:e.imageUrl}),e.prompt&&(i.prompt=e.prompt);let a=await this.submitTask(s,i,t,n),l=await this.pollTask(`${this.baseUrl}/v3/3d-contents/generations/tasks/${a}`,t,n),c=[],u=l.output;if(u?.model_urls){let p=u.model_urls;for(let d of Object.values(p))d&&c.push(d)}return{mediaUrls:c,model:e.model,durationMs:Date.now()-r}}async submitTask(e,t,n,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(t),signal:r??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${l}`)}let i=await s.json(),a=i.id??i.task_id;if(!a)throw new Error("Volcengine task submit: no task_id in response");return a}async pollTask(e,t,n){let r=Date.now()+6e5;for(;Date.now()<r;){n?.throwIfAborted();let s=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Volcengine task poll error ${s.status}: ${l}`)}let i=await s.json(),a=i.status;if(a==="succeeded"||a==="complete")return i;if(a==="failed"||a==="cancelled"){let l=i.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${l}`)}await new Promise(l=>setTimeout(l,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as Mu,mkdirSync as Pu}from"node:fs";import{join as Ds}from"node:path";import{randomUUID as Au}from"node:crypto";import{homedir as Ru}from"node:os";import{join as ee}from"node:path";var fe=".qlogicagent";function H(){return ee(Ru(),fe)}function pn(){return ee(H(),"sessions")}function ws(o){return ee(pn(),o)}function Ss(){return ee(H(),"plugins")}function jt(){return ee(H(),"skills")}function ze(){return ee(H(),"settings.json")}function Ft(){return ee(H(),"cache")}function Cs(){return ee(H(),"debug-logs")}function _s(o){let e=ee(H(),"checkpoints");return o?ee(e,o):e}function Rs(){return ee(H(),"plugin-cache")}function Ms(){return ee(H(),"mcp.json")}function Ps(){return ee(H(),"marketplace.json")}function As(){return ee(H(),"workflows")}function Es(){return ee(H(),"rules")}function mn(o){return ee(o??process.cwd(),fe)}function Is(o){return ee(mn(o),"workflows")}function Os(o){return ee(mn(o),"INSTRUCTIONS.md")}function Ls(o){return ee(mn(o),"rules")}function $s(o){return ee(o,fe,"hooks")}var Eu=18e4,ct=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??Eu}async generate(e,t,n){switch(e.mediaType){case"image":return this.generateImage(e,t,n);case"tts":return this.generateTTS(e,t,n);default:throw new Error(`OpenAIMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateImage(e,t,n){let r=Date.now(),s=`${this.baseUrl}/v1/images/generations`,i={model:e.model,prompt:e.prompt,n:e.n??1,size:e.size??"1024x1024",response_format:"url"},a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${u}`)}return{mediaUrls:((await a.json()).data??[]).map(u=>u.url).filter(u=>!!u),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r}}async generateTTS(e,t,n){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("OpenAIMediaTransport: text or prompt is required for TTS");let i=`${this.baseUrl}/v1/audio/speech`,a={model:e.model||"tts-1",input:s,voice:"alloy",response_format:"mp3"},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${l.status}: ${m}`)}let c=Buffer.from(await l.arrayBuffer()),u=Ds(Ft(),"tts");Pu(u,{recursive:!0});let p=`openai-tts-${Au()}.mp3`,d=Ds(u,p);return Mu(d,c),{mediaUrls:[`file://${d}`],model:e.model||"tts-1",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:s.length}}};var ut=class{supportedTypes=["music"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??6e4}async generate(e,t,n){if(e.mediaType!=="music")throw new Error(`MiniMaxMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=`${this.baseUrl}/v1/music_generation`,i={model:e.model,prompt:e.prompt};e.lyrics&&(i.lyrics=e.lyrics),e.duration&&(i.duration=e.duration);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`MiniMax music submit error ${a.status}: ${d}`)}let l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax music submit rejected: ${l.base_resp.status_msg??"unknown"}`);let c=l.task_id;if(!c)throw new Error("MiniMax music submit: no task_id in response");let u=`${this.baseUrl}/v1/music_generation/${c}`;return{mediaUrls:(await this.pollTask(u,t,n)).audioUrls,model:e.model,durationMs:Date.now()-r}}async pollTask(e,t,n){let r=Date.now()+6e5;for(;Date.now()<r;){n?.throwIfAborted();let s=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`MiniMax music poll error ${s.status}: ${l}`)}let i=await s.json(),a=i.status;if(a==="Success"||a==="Finished"){let l=[];return i.audio_file&&l.push(i.audio_file),{audioUrls:l}}if(a==="Failed"||a==="Cancelled")throw new Error(`MiniMax music task failed: ${i.base_resp?.status_msg??"unknown"}`);await new Promise(l=>setTimeout(l,3e3))}throw new Error("MiniMax music task timed out after polling")}};var dt=class{supportedTypes=["image"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4}async generate(e,t,n){if(e.mediaType!=="image")throw new Error(`GeminiMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={contents:[{parts:[{text:e.prompt}]}],generationConfig:{responseModalities:["TEXT","IMAGE"]}},a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(i),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Gemini image API error ${a.status}: ${u}`)}let l=await a.json(),c=[];for(let u of l.candidates??[])for(let p of u.content?.parts??[])if(p.inlineData?.data){let d=`data:${p.inlineData.mimeType};base64,${p.inlineData.data}`;c.push(d)}return{mediaUrls:c,model:e.model,durationMs:Date.now()-r}}};var Bt=class{supportedTypes=["tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/apps\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??3e4}async generate(e,t,n){if(e.mediaType!=="tts")throw new Error(`QwenMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("QwenMediaTransport: text or prompt is required for TTS");let i=`${this.baseUrl}/api/v1/services/aigc/text2audio/generation`,a={model:e.model||"qwen3-tts-voicedesign",input:{text:s},parameters:{format:"mp3",sample_rate:24e3}},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(a),signal:n??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let d=await l.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${l.status}: ${d}`)}let c=await l.json();if(c.code)throw new Error(`DashScope TTS submit rejected: ${c.code} \u2014 ${c.message??""}`);let u=c.output?.task_id;if(!u)throw new Error("DashScope TTS submit: no task_id in response");if(c.output?.task_status==="SUCCEEDED"){let d=this.extractAudioUrl(c);return{mediaUrls:d?[d]:[],model:e.model,durationMs:Date.now()-r}}return{mediaUrls:await this.pollTask(u,t,n),model:e.model,durationMs:Date.now()-r}}async pollTask(e,t,n){let r=Date.now()+12e4,s=`${this.baseUrl}/api/v1/tasks/${e}`;for(;Date.now()<r;){n?.throwIfAborted(),await Iu(2e3);let i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:n??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${i.status}: ${c}`)}let a=await i.json();if(a.code)throw new Error(`DashScope TTS poll rejected: ${a.code} \u2014 ${a.message??""}`);let l=a.output?.task_status;if(l==="SUCCEEDED"){let c=this.extractAudioUrl(a);return c?[c]:[]}if(l==="FAILED")throw new Error(`DashScope TTS task failed: ${a.message??"unknown error"}`)}throw new Error("DashScope TTS task timed out")}extractAudioUrl(e){if(e.output?.audio_url)return e.output.audio_url;if(e.output?.results?.[0]?.url)return e.output.results[0].url}};function Iu(o){return new Promise(e=>setTimeout(e,o))}var pt=class{registry;transports=new Map;constructor(e){this.registry=e.registry}resolveModel(e,t){if(t){let n=this.findModelInProvider(t,e);if(n)return n}for(let n of this.registry.listProviders()){let r=this.findModelInProvider(n.id,e);if(r)return r}}getTransport(e){let t=this.transports.get(e);if(t)return t;let n=this.registry.getProvider(e);if(!n)return;let r=Ou(n);if(r)return this.transports.set(e,r),r}listMediaModels(e){let t=[];for(let n of this.registry.listProviders()){let r=this.registry.listModels(n.id);for(let s of r)s.mediaType&&(!e||s.mediaType===e)&&t.push({providerId:n.id,providerDef:n,modelInfo:s,mediaType:s.mediaType})}return t}findModelInProvider(e,t){let n=this.registry.getProvider(e);if(!n)return;let s=this.registry.listModels(e).find(i=>i.mediaType===t);if(s)return{providerId:e,providerDef:n,modelInfo:s,mediaType:t}}};function Ou(o){let e=o.baseUrl;switch(o.id){case"doubao":return new lt({baseUrl:e});case"openai":return new ct({baseUrl:e});case"minimax":return new ut({baseUrl:e});case"google":return new dt({baseUrl:e});case"qwen":return new Bt({baseUrl:e});default:return}}var gn=[{id:"deepseek",name:"DeepSeek",transport:"anthropic-messages",baseUrl:"https://api.deepseek.com/anthropic",apiKeyEnvVars:["DEEPSEEK_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"deepseek-v4-flash",models:[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",contextWindow:1e6,maxOutput:384e3,toolCall:!0,reasoning:!0,vision:!1,costInput:1.74,costOutput:3.48}]},{id:"qwen",name:"Alibaba Qwen (DashScope)",transport:"anthropic-messages",baseUrl:"https://dashscope.aliyuncs.com/apps/anthropic",apiKeyEnvVars:["DASHSCOPE_API_KEY","QWEN_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"qwen3.6-plus",models:[{id:"qwen3.6-plus",name:"Qwen3.6 Plus",contextWindow:1e6,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:3,costCacheRead:.05,costCacheWrite:.625},{id:"qwen3-tts-voicedesign",name:"Qwen3 TTS VoiceDesign",contextWindow:32768,maxOutput:16384,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts"}]},{id:"zhipu",name:"\u667A\u8C31 GLM (Zhipu)",transport:"anthropic-messages",baseUrl:"https://open.bigmodel.cn/api/anthropic",apiKeyEnvVars:["ZHIPU_API_KEY","GLM_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"glm-5",models:[{id:"glm-5",name:"GLM-5",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:1,costOutput:3.2,costCacheRead:.2},{id:"glm-5.1",name:"GLM-5.1",contextWindow:2e5,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:6,costOutput:24,costCacheRead:1.3}]},{id:"minimax",name:"MiniMax",transport:"anthropic-messages",baseUrl:"https://api.minimaxi.com/anthropic",apiKeyEnvVars:["MINIMAX_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"MiniMax-M2.7",models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7",contextWindow:204800,maxOutput:131072,toolCall:!0,reasoning:!0,vision:!1,costInput:.3,costOutput:1.2,costCacheRead:.06,costCacheWrite:.375},{id:"music-2.6",name:"MiniMax Music 2.6",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"music"},{id:"music-cover",name:"MiniMax Music Cover",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"music"}]},{id:"moonshot",name:"Moonshot (Kimi)",transport:"openai-chat",baseUrl:"https://api.moonshot.cn",apiKeyEnvVars:["MOONSHOT_API_KEY"],authType:"bearer",isAggregator:!1,omitZeroTemperature:!0,defaultModel:"kimi-k2.6",models:[{id:"kimi-k2.6",name:"Kimi K2.6",contextWindow:262144,maxOutput:262144,toolCall:!0,reasoning:!0,vision:!0,costInput:.95,costOutput:4,costCacheRead:.16}]},{id:"doubao",name:"\u8C46\u5305 (Doubao/Volcengine)",transport:"openai-chat",baseUrl:"https://ark.cn-beijing.volces.com/api",apiKeyEnvVars:["ARK_API_KEY","DOUBAO_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"doubao-seedream-5-0-260128",models:[{id:"doubao-seedance-2-0-260128",name:"Doubao Seedance 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"video"},{id:"doubao-seedance-2-0-fast-260128",name:"Doubao Seedance 2.0 Fast",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"video"},{id:"doubao-seedream-5-0-260128",name:"Doubao Seedream 5.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"},{id:"doubao-seedream-4-5-251128",name:"Doubao Seedream 4.5",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"},{id:"doubao-seed3d-2-0-260328",name:"Doubao Seed3D 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d"},{id:"hyper3d-gen2-260112",name:"Hyper3D Gen2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d"},{id:"hitem3d-2-0-251223",name:"HiTem3D 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d"}]},{id:"openai",name:"OpenAI",transport:"openai-chat",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-5.5",models:[{id:"gpt-5.5",name:"GPT-5.5",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:30,costCacheRead:.5},{id:"gpt-5.4",name:"GPT-5.4",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:2.5,costOutput:15,costCacheRead:.25},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.75,costOutput:4.5,costCacheRead:.075},{id:"o3",name:"o3",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!0,costInput:2,costOutput:8,costCacheRead:.5},{id:"o4-mini",name:"o4-mini",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!0,costInput:1.1,costOutput:4.4,costCacheRead:.28},{id:"gpt-image-2",name:"GPT Image 2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"},{id:"tts-1",name:"OpenAI TTS-1",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts"},{id:"tts-1-hd",name:"OpenAI TTS-1 HD",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts"}]},{id:"anthropic",name:"Anthropic",transport:"anthropic-messages",baseUrl:"https://api.anthropic.com",apiKeyEnvVars:["ANTHROPIC_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"claude-opus-4-7",models:[{id:"claude-opus-4-7",name:"Claude Opus 4.7",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-opus-4-6",name:"Claude Opus 4.6",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindow:1e6,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:5,costCacheRead:.1,costCacheWrite:1.25}]},{id:"google",name:"Google Gemini",transport:"openai-chat",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",apiKeyEnvVars:["GOOGLE_API_KEY","GEMINI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gemini-2.5-pro",models:[{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:1.25,costOutput:10,costCacheRead:.125},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.15,costOutput:.6,costCacheRead:.0375},{id:"gemini-3.1-flash-image-preview",name:"Gemini 3.1 Flash Image",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image"}]},{id:"openrouter",name:"OpenRouter",transport:"openai-chat",baseUrl:"https://openrouter.ai/api",apiKeyEnvVars:["OPENROUTER_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"anthropic/claude-opus-4.7",extraHeaders:{"HTTP-Referer":"https://claw.bot","X-Title":"XiaozhiClaw"},models:[{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7 (via OpenRouter)",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5},{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6 (via OpenRouter)",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5},{id:"deepseek/deepseek-v4-flash",name:"DeepSeek V4 Flash (via OpenRouter)",contextWindow:1048576,maxOutput:393216,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28,costCacheRead:.028}]},{id:"qwen-coding",name:"Alibaba Qwen (Coding Plan)",transport:"anthropic-messages",baseUrl:"https://coding.dashscope.aliyuncs.com/apps/anthropic",apiKeyEnvVars:["DASHSCOPE_API_KEY","QWEN_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"qwen3-coder-plus",models:[{id:"qwen3-coder-plus",name:"Qwen3 Coder Plus (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1},{id:"qwen3-coder-flash",name:"Qwen3 Coder Flash (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1}]},{id:"doubao-coding",name:"\u8C46\u5305 Doubao (Coding Plan)",transport:"anthropic-messages",baseUrl:"https://ark.cn-beijing.volces.com/api/coding",apiKeyEnvVars:["ARK_API_KEY","DOUBAO_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"doubao-pro-256k",models:[{id:"doubao-pro-256k",name:"Doubao Pro 256K (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1}]}];import{existsSync as Lu,mkdirSync as $u,readFileSync as Du,writeFileSync as Nu}from"node:fs";import{join as Uu}from"node:path";var ju="https://models.dev/api.json",Fu=3e4,Bu=1440*60*1e3,Wu=300*1e3,qu={deepseek:"deepseek",qwen:"qwen","qwen-coding-plan":"qwen-coding","alibaba-cn":"qwen",zhipuai:"zhipu",minimax:"minimax",moonshot:"moonshot",moonshotai:"moonshot",doubao:"doubao","doubao-coding-plan":"doubao-coding","bytedance-seed":"doubao",volcengine:"doubao","volcengine-coding-plan":"doubao-coding",openai:"openai",anthropic:"anthropic",google:"google",openrouter:"openrouter"},mt=class{cache=null;cacheDir;cacheFile;ttlMs;fetching=!1;lastFetchAttempt=0;constructor(e){this.cacheDir=e?.cacheDir??Ft(),this.cacheFile=Uu(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??Bu}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(!Lu(this.cacheFile))return;let e=Du(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:Ns(t.data)}}catch{}}saveToDisk(e){try{$u(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);Nu(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<Wu||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(ju,{signal:AbortSignal.timeout(Fu),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),n=Ns(t);return n.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:n},this.saveToDisk(t),!0)}catch{return!1}}};function Ns(o){let e=new Map;if(!o||typeof o!="object")return e;for(let[t,n]of Object.entries(o)){let r=qu[t];if(!r||!n||typeof n!="object")continue;let i=n.models;if(!i||typeof i!="object")continue;let a=e.get(r);a||(a={models:new Map},e.set(r,a));for(let[l,c]of Object.entries(i)){if(!c||typeof c!="object"||a.models.has(l))continue;let u=c,p=u.cost??{},d=u.limit??{},m=u.modalities??{},y=Array.isArray(m.input)?m.input:[],h=Array.isArray(m.output)?m.output:[],k=Hu(h,y,l);a.models.set(l,{id:l,name:typeof u.name=="string"?u.name:l,contextWindow:typeof d.context=="number"?d.context:2e5,maxOutput:typeof d.output=="number"?d.output:8192,toolCall:u.tool_call===!0,reasoning:u.reasoning===!0,vision:u.attachment===!0||y.includes("image"),costInput:typeof p.input=="number"?p.input:void 0,costOutput:typeof p.output=="number"?p.output:void 0,costCacheRead:typeof p.cache_read=="number"?p.cache_read:void 0,costCacheWrite:typeof p.cache_write=="number"?p.cache_write:void 0,mediaType:k})}}return e}function Hu(o,e,t){if(o.includes("video"))return"video";if(o.includes("image")&&!o.includes("text"))return"image";if(o.includes("audio")&&!o.includes("text"))return"tts";if(o.includes("3d"))return"3d";let n=t.toLowerCase();if(n.includes("tts")||n.includes("speech")||n.includes("cosyvoice"))return"tts";if(n.includes("music")||n.includes("suno"))return"music";if(n.includes("seedream")||n.includes("image")||n.includes("dall"))return"image";if(n.includes("seedance")||n.includes("video"))return"video"}var Gu={claude:"anthropic",gemini:"google"},Ve=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of gn)this.builtins.set(t.id,t);this.catalog=e?.catalog??new mt}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=Gu[e]??e,n=this.builtins.get(t),r=this.overrides.get(t);if(!(!n&&!r))return!n&&r?!r.id||!r.transport||!r.baseUrl?void 0:{id:r.id,name:r.name??r.id,transport:r.transport,baseUrl:r.baseUrl,apiKeyEnvVars:r.apiKeyEnvVars??[],authType:r.authType??"bearer",isAggregator:r.isAggregator??!1,defaultModel:r.defaultModel,models:r.models}:n&&!r?n:{...n,...r,models:r.models??n.models}}listProviders(){let e=new Map;for(let[t,n]of this.builtins)e.set(t,n);for(let[t]of this.overrides){let n=this.getProvider(t);n&&e.set(t,n)}return[...e.values()]}listModels(e){let n=this.getProvider(e)?.models??[],r=this.catalog.getModels(e);if(r.length===0)return n;let s=new Map;for(let i of r)s.set(i.id,i);for(let i of n)s.set(i.id,i);return[...s.values()]}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,t){if(t)return t;let n=this.getProvider(e);if(n)for(let r of n.apiKeyEnvVars){let s=process.env[r];if(s?.trim())return s.trim()}}};var gt=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;constructor(e){if(!e.baseUrl)throw new Error("OpenAIChatTransport: baseUrl is required (got empty or undefined)");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.supportsStreamOptions=e.supportsStreamOptions??!0,this.omitZeroTemperature=e.omitZeroTemperature??!1}async*stream(e,t,n){let r=`${this.baseUrl}/v1/chat/completions`,s={model:e.model,messages:e.messages,stream:!0};this.supportsStreamOptions&&(s.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(s.tools=e.tools,e.toolChoice&&(s.tool_choice=e.toolChoice)),e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||fn(e.model)||(s.temperature=e.temperature)),e.maxTokens!==void 0&&(fn(e.model)?s.max_completion_tokens=e.maxTokens:s.max_tokens=e.maxTokens),e.reasoning&&(fn(e.model)?s.reasoning_effort=e.reasoning.effort:s.reasoning=e.reasoning);let i=AbortSignal.timeout(this.timeoutMs),a=n?AbortSignal.any([n,i]):i,l=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},body:JSON.stringify(s),signal:a});if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`LLM API error ${l.status}: ${c.slice(0,500)}`)}if(!l.body)throw new Error("LLM API returned no response body");yield*this.parseSSEStream(l.body)}async*parseSSEStream(e){let t=new TextDecoder,n="";for await(let r of e){n+=t.decode(r,{stream:!0});let s;for(;(s=n.indexOf(`
|
|
29
|
-
`))!==-1;){let i=n.slice(0,s).trim();if(n=n.slice(s+1),!i||i.startsWith(":")||!i.startsWith("data: "))continue;let a=i.slice(6);if(a==="[DONE]")return;let l;try{l=JSON.parse(a)}catch{continue}yield*this.mapChunk(l)}}if(n.trim()){let r=n.trim();if(r.startsWith("data: ")&&r.slice(6)!=="[DONE]")try{let s=JSON.parse(r.slice(6));yield*this.mapChunk(s)}catch{}}}*mapChunk(e){if(e.usage&&(yield{type:"usage",promptTokens:e.usage.prompt_tokens??0,completionTokens:e.usage.completion_tokens??0,reasoningTokens:e.usage.completion_tokens_details?.reasoning_tokens}),!(!e.choices||e.choices.length===0))for(let t of e.choices){let n=t.delta;if(n){if(n.reasoning_content&&(yield{type:"reasoning_delta",text:n.reasoning_content}),n.content&&(yield{type:"delta",text:n.content}),n.tool_calls)for(let r of n.tool_calls)yield{type:"tool_call_delta",index:r.index,id:r.id,name:r.function?.name,arguments:r.function?.arguments??""};t.finish_reason&&(yield{type:"done",finishReason:t.finish_reason})}}}};function fn(o){let e=o.toLowerCase();return/^o[1-9]/.test(e)}var zu=new Set([429,529,502,503,504]),Vu="[Tool execution failed; output not available during conversation recovery]",Ku="interleaved-thinking-2025-05-14",Ju="context-1m-2025-08-07",Yu="token-efficient-tools-2026-03-28",Xu="prompt-caching-scope-2026-01-05";function Qu(o,e,t){let n=[],r=o.toLowerCase();(r.includes("opus-4-6")||r.includes("opus-4-7")||r.includes("sonnet-4-6"))&&n.push(Ju),e&&!r.includes("haiku")&&n.push(Ku),t&&n.push(Yu),n.push(Xu);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 ft=class{baseUrl;apiVersion;timeoutMs;streamIdleTimeoutMs;enablePromptCaching;maxRetries;constructor(e){if(!e.baseUrl)throw new Error("AnthropicMessagesTransport: baseUrl is required (got empty or undefined)");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiVersion=e.apiVersion??"2023-06-01",this.timeoutMs=e.timeoutMs??18e4,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??9e4,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3}async*stream(e,t,n){let r=`${this.baseUrl}/v1/messages`,s=td(e.messages),{system:i,messages:a}=od(s),l=ed(i,this.enablePromptCaching),c=!!e.reasoning,u=e.maxTokens??8192,p={model:e.model,messages:a,max_tokens:u,stream:!0};if(l&&(p.system=l),e.tools&&e.tools.length>0&&(p.tools=e.tools.map(nd),e.toolChoice&&(p.tool_choice=e.toolChoice==="auto"?{type:"auto"}:e.toolChoice==="required"?{type:"any"}:{type:"none"})),!c&&e.temperature!==void 0&&(p.temperature=e.temperature),c){let h=Zu(e.reasoning.effort);p.thinking={type:"enabled",budget_tokens:Math.min(u-1,h)}}let d=Qu(e.model,c,(e.tools?.length??0)>0),m={"Content-Type":"application/json","x-api-key":t,"anthropic-version":this.apiVersion};d.length>0&&(m["anthropic-beta"]=d.join(","));let y=null;for(let h=0;h<=this.maxRetries;h++){if(n?.aborted)throw new Error("Request aborted");if(h>0&&y){let k=Math.min(1e3*Math.pow(2,h-1),3e4),w=Math.random()*.25*k;await sd(k+w,n)}try{yield*this.streamWithWatchdog(r,m,p,n);return}catch(k){y=k instanceof Error?k:new Error(String(k));let w=rd(y.message),f=w!==null&&zu.has(w),C=y.message.includes("Stream idle timeout");if(y.message.includes("model_context_window_exceeded")||y.message.includes("context_length_exceeded")||!f&&!C)throw y;if(h===this.maxRetries){if(C||f)try{yield*this.nonStreamingFallback(r,m,p,n);return}catch{throw y}throw y}}}if(y)throw y}async*streamWithWatchdog(e,t,n,r){let s=AbortSignal.timeout(this.timeoutMs),i=r?AbortSignal.any([r,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(n),signal:i});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Anthropic API error ${a.status}: ${d.slice(0,500)}`)}if(!a.body)throw new Error("Anthropic API returned no response body");let l=null,c=!1,u=()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{c=!0},this.streamIdleTimeoutMs)},p=()=>{l!==null&&(clearTimeout(l),l=null)};u();try{yield*this.parseSSEStream(a.body,u,()=>c)}finally{p()}if(c)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,n,r){let s=id({...n,stream:!1}),i=AbortSignal.timeout(3e5),a=r?AbortSignal.any([r,i]):i,l=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!l.ok){let u=await l.text().catch(()=>"");throw new Error(`Anthropic API error ${l.status}: ${u.slice(0,500)}`)}let c=await l.json();yield*this.mapNonStreamingResponse(c)}*mapNonStreamingResponse(e){let t=e.usage;t&&(yield{type:"usage",promptTokens:t.input_tokens??0,completionTokens:t.output_tokens??0,cacheReadTokens:t.cache_read_input_tokens>0?t.cache_read_input_tokens:void 0,cacheCreationTokens:t.cache_creation_input_tokens>0?t.cache_creation_input_tokens:void 0});let n=e.content;if(Array.isArray(n)){let s=0;for(let i of n){let a=i.type;a==="text"?yield{type:"delta",text:i.text}:a==="thinking"?yield{type:"reasoning_delta",text:i.thinking}:a==="tool_use"&&(yield{type:"tool_call_delta",index:s++,id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})})}}let r=e.stop_reason;r&&(yield{type:"done",finishReason:js(r)})}async*parseSSEStream(e,t,n){let r=new TextDecoder,s="",i="",a=new Map,l={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};for await(let c of e){if(t(),n())break;s+=r.decode(c,{stream:!0});let u;for(;(u=s.indexOf(`
|
|
30
|
-
`))!==-1;){let
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
`,"utf8")}catch{}}return{async*stream(i,a,l){let c=Date.now();s({type:"request",timestamp:new Date(c).toISOString(),model:i.model,messageCount:i.messages.length,toolCount:i.tools?.length??0,toolChoice:i.toolChoice,temperature:i.temperature,maxTokens:i.maxTokens,reasoning:i.reasoning});let u=0,p=0,d=0,m="",y;try{for await(let h of o.stream(i,a,l))h.type==="usage"?(u=h.promptTokens,p=h.completionTokens,d=h.reasoningTokens??0):h.type==="done"&&(m=h.finishReason),yield h}catch(h){throw y=h instanceof Error?h.message:String(h),h}finally{let h=Date.now()-c;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:h,promptTokens:u,completionTokens:p,reasoningTokens:d,finishReason:m,...y?{error:y}:{}})}}}}function bn(o){let e=new Map;return{register(t){let n=e.get(t.point)??[],r={handler:t.handler,priority:t.priority??100,label:t.label};return n.push(r),n.sort((s,i)=>s.priority-i.priority),e.set(t.point,n),()=>{let s=n.indexOf(r);s>=0&&n.splice(s,1)}},async invoke(t,n){let r=e.get(t);if(!r||r.length===0)return{action:"continue",context:n};let s=n;for(let i of r)try{let a=await i.handler(t,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return o.info({hook:t,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){o.warn({hook:t,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}var Ht={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function ht(){return{surfacedPaths:new Set,sessionBytes:0}}function Ws(o,e,t){let n=[],r=t??ht(),s,i=[];return n.push(o.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,l)=>{if(!e.memoryProvider||!l.query)return{action:"continue",context:l};if(r.sessionBytes>=Ht.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:l};try{let c=await e.memoryProvider.search(l.query,e.userId,{limit:Ht.LIMIT_PER_RECALL}),u=c.filter(d=>{let m=d,y=m.path??m.id??"";if(!y)return!0;if(r.surfacedPaths.has(y))return!1;let h=(m.content?.length??0)*2;if(r.sessionBytes+h>Ht.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(y),r.sessionBytes+=h,r.surfacedPaths.size>Ht.MAX_SURFACED_ENTRIES){let k=r.surfacedPaths.values().next().value;k!==void 0&&r.surfacedPaths.delete(k)}return!0});s=l.turnId,i=u,e.log.debug(`memory.before_recall: prefetched ${c.length} \u2192 ${u.length} after dedup (${r.sessionBytes} bytes used)`);let p=u.map(d=>{let m=d;return{text:m.text??m.content??"",score:m.score}}).filter(d=>d.text);return{action:"continue",context:{...l,recalledMemories:p}}}catch(c){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${c instanceof Error?c.message:String(c)}`),i=[]}return{action:"continue",context:l}}})),n.push(o.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,l)=>{let c=s===l.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${l.blockCount??0} blocks assembled, ${c} qmemory results (session: ${r.sessionBytes} bytes)`),{action:"continue",context:l}}})),()=>{for(let a of n)a();i=[]}}import{ClawQMemoryAdapter as dd}from"qlogicagent-adapter-claw";var qs="qmemory";function Hs(o){let e=new dd({baseUrl:o.baseUrl,apiKey:o.apiKey,timeout:o.timeoutMs??5e3});function t(n){return o.userIdPrefix?`${o.userIdPrefix}:${n}`:n}return{providerId:qs,async search(n,r,s){return((await e.dispatch("memory.search",{q:n,user_id:t(r),limit:s?.limit??10})).memories??[]).filter(a=>a.id&&a.text).map(a=>({blockId:a.id,text:a.text,score:typeof a.importance=="number"?a.importance:0,source:qs,metadata:a.metadata}))},async ingest(n,r,s){await e.dispatch("memory.addKnowledge",{user_id:t(r),messages:n.map(i=>({role:i.role,content:i.content,...i.timestamp?{timestamp:i.timestamp}:{}})),extraction_mode:"none",run_async:!0,...s?.sessionId?{session_id:s.sessionId}:{},...s?.source?{metadata:{source:s.source}}:{}})},async health(){let n=await e.dispatch("memory.health",{});return{status:n.status??"unknown",version:n.version??"",memoryCount:n.memory_count??0,dbSizeBytes:n.db_size_bytes??0,embeddingModel:n.embedding_model??"",uptimeSeconds:n.uptime_seconds??0}},async addText(n,r,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:t(r),text:n,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(n,r,s){if(n.length===0)return{memoriesAdded:0};let i=t(r),a=await Promise.allSettled(n.map(c=>e.dispatch("memory.addFact",{user_id:i,text:c.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...c.category?{category:c.category}:{},...typeof c.importance=="number"?{importance:c.importance}:{},...c.speaker?{speaker:c.speaker}:{},...c.event_date?{event_date:c.event_date}:{},...c.tags?.length?{tags:c.tags}:{}}}))),l=0;for(let c of a)c.status==="fulfilled"&&(l+=c.value.memories_added??1);return{memoriesAdded:l}},async remove(n){try{return await e.dispatch("memory.forget",{id:n}),!0}catch{return!1}},async feedback(n,r,s){await e.dispatch("memory.feedback",{memory_ids:n,signal:r,...s?{session_id:s}:{}})}}}import{readFile as Ys,writeFile as kn,stat as ni,unlink as yd,mkdir as bd}from"node:fs/promises";import{join as zt,resolve as Xs,isAbsolute as Qs,normalize as Zs}from"node:path";import{randomUUID as Td}from"node:crypto";function Gs(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function pd(o){return o.latestInputTokens+o.cumulativeOutputTokens}var md=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),zs=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function gd(o){return{isSearch:md.has(o)||void 0,isRead:zs.has(o)||void 0}}function fd(o,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${zs.has(o)?"Reading":o.includes("write")||o.includes("edit")?"Editing":"Using"} ${t}`;let n=e.command??e.cmd;if(typeof n=="string")return`Running: ${n.length>60?n.slice(0,60)+"\u2026":n}`;let r=e.query??e.pattern??e.search;if(typeof r=="string")return`Searching: ${r}`}function Vs(o,e){o.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),o.cumulativeOutputTokens+=e.output_tokens??0}function Ks(o,e,t,n){o.toolUseCount++;let r=gd(e),s={toolName:e,input:t,activityDescription:n?.(e,t)??fd(e,t),isSearch:r.isSearch,isRead:r.isRead};for(o.recentActivities.push(s);o.recentActivities.length>5;)o.recentActivities.shift()}function Tn(o){return{toolUseCount:o.toolUseCount,tokenCount:pd(o),lastActivity:o.recentActivities.length>0?o.recentActivities[o.recentActivities.length-1]:void 0,recentActivities:[...o.recentActivities]}}import{randomUUID as Js}from"node:crypto";function hd(o){let e=new AbortController;return o&&(o.aborted?e.abort(o.reason):o.addEventListener("abort",()=>{e.abort(o.reason)},{once:!0})),e}async function Gt(o){let e=Date.now(),t=[],n={prompt:0,completion:0},r=Gs(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:c,toolInvoker:u,apiKey:p,model:d,log:m,hooks:y,forkLabel:h,maxTurns:k,temperature:w,parentSignal:f,onEvent:C,onProgress:R,budgetTokens:L,parentDepth:K}=o,D=hd(f),F=`fork-${h}-${Js().slice(0,8)}`,T=`fork-session-${Js().slice(0,8)}`;m.info(`[fork:${h}] starting \u2014 ${s.length} initial messages, model=${d}`);let B=l?{invoke:async(oe,$,A,le)=>{let se={};try{se=JSON.parse(A)}catch{}let ce=l($,se);return ce.allowed?u.invoke(oe,$,A,le):(m.info(`[fork:${h}] tool ${$} denied: ${ce.reason}`),{result:"",error:ce.reason})}}:u,J=!0,Q;try{let{Agent:oe}=await Promise.resolve().then(()=>(Ut(),vs)),$=new oe({llmTransport:c,apiKey:p,toolInvoker:B,log:m,hooks:y,maxRounds:k});for await(let A of $.run({turnId:F,sessionId:T,messages:s,tools:a,systemPrompt:i,config:{model:d,apiKey:p,temperature:w,maxOutputTokens:o.maxOutputTokens,parentDepth:K}},D.signal)){if(t.push(A),C?.(A),A.type==="end"&&A.usage&&(Vs(r,{input_tokens:A.usage.prompt,output_tokens:A.usage.completion}),n.prompt+=A.usage.prompt,n.completion+=A.usage.completion,A.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+A.usage.cacheRead),A.usage.cacheCreation&&(n.cacheCreation=(n.cacheCreation??0)+A.usage.cacheCreation),L&&L>0)){let le=n.prompt+n.completion+(n.reasoning??0);le>=L&&(m.info(`[fork:${h}] budget exceeded (${le} / ${L} tokens), aborting`),D.abort("budget_exceeded"))}if(A.type==="tool_call"){let le={};try{le=JSON.parse(A.arguments??"{}")}catch{}Ks(r,A.name,le),R?.(Tn(r))}A.type==="error"&&(J=!1,Q=A.error)}}catch(oe){J=!1,Q=oe instanceof Error?oe.message:String(oe),m.warn(`[fork:${h}] error: ${Q}`)}finally{D.signal.aborted||D.abort("fork_complete")}let ke=Date.now()-e;return m.info(`[fork:${h}] finished in ${ke}ms \u2014 ${t.length} events, usage: prompt=${n.prompt} completion=${n.completion}, ok=${J}`),{events:t,totalUsage:n,progress:Tn(r),durationMs:ke,ok:J,error:Q}}var ri={minHours:24,minSessions:5,scanIntervalMs:6e5},Vt=".consolidate-lock",kd=3600*1e3,ei="CLAUDE.md",xd=100,vd=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"]),wd=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),Sd=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function Cd(o){let e=o.trim();if(!e||Sd.test(e))return!1;let t=e.split(/\s+/),n=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!vd.has(n))return!1;if(n==="git"){let r=t[1];if(!r||!wd.has(r))return!1}return!0}function _d(o,e){let{toolName:t,input:n}=e;if(new Set(["read_file","grep","glob","search","list_dir","file_read","Grep","Glob"]).has(t))return{allowed:!0};if(new Set(["qmemory_search","qmemory_store","qmemory_feedback"]).has(t))return{allowed:!0};if(t==="bash"||t==="execute_command"||t==="Bash"){let i=n.command??n.cmd??"";return Cd(i)?{allowed:!0}:{allowed:!1,reason:"Only read-only shell commands are permitted during dream consolidation (ls, find, grep, cat, stat, wc, head, tail, and similar)"}}if(t==="file_edit"||t==="file_write"||t==="FileEdit"||t==="FileWrite"){let i=n.file_path??n.path??"";return typeof i=="string"&&si(i,o)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${o}`}}return{allowed:!1,reason:`Tool "${t}" is not permitted during dream consolidation. Only read_file, grep, glob, read-only bash, and memory-scoped file_edit/file_write are allowed.`}}function si(o,e){let t=Qs(o)?o:Xs(o),n=Qs(e)?e:Xs(e),r=Zs(t),s=Zs(n);return r.startsWith(s)}function ii(o,e,t,n){let r=n?.hasQMemory?`
|
|
24
|
+
`)}`}function Du(){return Bo(new Fe(wn),new Re(20,je),new Je(je))}function Rs(n,e){let t=Wo(new Fe(wn),new Re(20,je),new ut({protectedHeadExchanges:1,protectedTailMessages:8,summarize:n,estimateTokens:je}),new Je(je));return new dt({inner:t,estimateTokens:je,onCacheInvalidated:e?.onCacheInvalidated})}function As(n,e){let t=e?.budget??jt({modelContextWindow:Ms(e?.model)}),r=(e?.pipeline??Du()).compress(n,t);if(r.droppedCount>0){let s=Be(n),i=Be(r.messages);Ps.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:s,tokensAfter:i,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:ft(s,t)})}return r.droppedCount>0&&_n?.(r.droppedCount,Be(r.messages)),r}async function Uu(n,e,t){let o=t??jt({modelContextWindow:Ms(e.model)}),r=Be(n),s=ft(r,o),i;switch(s){case"none":i={messages:n,droppedCount:0,strategy:"none"};break;case"trim-only":i=new Fe(wn).compress(n,o);break;case"sliding-window":{i=await Rs(e.summarize).compressAsync(n,o);break}case"llm-summarize":{let a=e.pipeline??Rs(e.summarize);i=gt(a)?await a.compressAsync(n,o):a.compress(n,o);break}}return i.droppedCount>0&&(i={...i,messages:await zo(i.messages,n,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await Ou(a,"utf-8")}catch{return null}}})}),Nu(n,i,o),i}function Nu(n,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let o=e.metrics?.tokensBefore||Be(n),r=e.metrics?.tokensAfter||Be(e.messages);Ps.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:o,tokensAfter:r,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:ft(o,t)})}if(e.droppedCount>0){let o=e.metrics?.tokensAfter||Be(e.messages);_n?.(e.droppedCount,o)}}function Fu(n,e){let t=$u(n,e),o={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return Uu(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};Ss.register(o),Ss.activate(o.id),n.info(`[context-compression] registered context engine: ${o.id}`)}function Is(n,e,t){Fu(e,t),n.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(o,r)=>{let s=r.messageCount;return s&&s>0&&e.debug(`[context-compression] before_compact: ${s} messages entering compression`),{action:"continue"}}}),_n=(o,r)=>{e.debug(`[context-compression] after_compact: removed ${o}, ${r} tokens remaining`),n.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:o,tokenCount:r}).catch(()=>{})}}var xn,wn,Lu,Ps,Ss,_n,Cn=z(()=>{"use strict";Xe();xn={"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-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};wn=8e3,Lu="deepseek-v4-flash",Ps=new pt(200),Ss=new mt;_n=null});function Es(n,e,t){let o=t-e;return`[Budget] ${Math.round(n)}% used (${e.toLocaleString()} / ${t.toLocaleString()} tokens). ${o.toLocaleString()} tokens remaining. `+(n>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var Os=z(()=>{"use strict"});var Ls={};Er(Ls,{resolveToolEligibility:()=>zu});function Bu(n,e){if(ju.some(t=>t.test(n)))return!0;if(e)for(let t of e)try{if(new RegExp(t,"i").test(n))return!0}catch{}return!1}function Wu(n,e){let t=n.function.name,o=n.meta,r=[];return e.blockedToolNames?.includes(t)?(r.push("policy_blocked"),{level:5,reasons:r}):o?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):o?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):o?.isDangerous||Bu(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function Hu(n){switch(n){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 zu(n,e={}){let t=new Map,o=[],r=[],s=[];for(let i of n){let a=i.function.name,{level:c,reasons:u}=Wu(i,e),l=Hu(c),d={toolName:a,status:l,permissionLevel:c,approvalRequired:c===4,reasonCodes:u};t.set(a,d),c===5?r.push(d):(o.push(i),c===4&&s.push(d))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:s,eligibilityByName:t}}var ju,$s=z(()=>{"use strict";ju=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function qu(n){let e=n.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 Ku(n){let e=n.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 Ju(n){return typeof n=="number"&&Number.isFinite(n)&&n>=1?Math.min(Math.round(n),100):rs}function Ds(n){let e=n.message.toLowerCase();return n.status===413||e.includes("prompt_too_long")||e.includes("context_length_exceeded")||e.includes("maximum context length")}function Yu(n){return n==="length"||n==="max_tokens"}function Us(n){let e=n.message.toLowerCase();return(e.includes("image")||e.includes("media")||e.includes("file too large")||e.includes("payload too large"))&&(n.status===413||e.includes("too large")||e.includes("size"))}function Xu(n){let e=n.headers;if(!e)return null;let t=e["retry-after"]??e["Retry-After"];if(!t)return null;let o=parseInt(t,10);return!isNaN(o)&&o>0?o*1e3:null}function Qu(n){if(n.status!==400)return null;let e=n.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),o=parseInt(e[3],10);if(isNaN(t)||isNaN(o))return null;let r=o-t-1e3;return r>=3e3?r:null}function Zu(n){return n.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Ns(n,e,t,o){let{turnId:r,sessionId:s,messages:i,tools:a,model:c,apiKey:u,temperature:l,hooks:d,signal:p}=n,m={sessionId:s,turnId:r},h=n.maxTurns??0,y=n.querySource,{resolveToolEligibility:T}=await Promise.resolve().then(()=>($s(),Ls)),x=T(a,n.toolEligibilityContext),f=x.eligibleTools;for(let j of x.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:j.toolName,reason:"blocked-by-policy"};if(!f.length){yield*ed(r,c,i,u,l,p,e,o);return}let _=Ju(n.maxRounds),S={contextWindowTokens:n.contextWindowTokens??is,responseBufferTokens:as,maxOutputTokens:n.maxOutputTokens??ls,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},O=new Set,K=0,D=f,F,k={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:dn(S),reactiveCompactState:hn(),toolLoopState:Wt({maxRounds:_,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:qo(),currentModel:c,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:bs()};for(;;){let{messages:j,maxOutputTokensRecoveryCount:J,hasAttemptedReactiveCompact:Q,maxOutputTokensOverride:Se,turnCount:oe,guardState:$,reactiveCompactState:I,collapseStore:ue}=k,{toolLoopState:se}=k;if(F){try{let v=await F;v&&(yield{type:"tool_use_summary",turnId:r,summary:v})}catch{}F=void 0}if(n.refreshTools&&oe>1){let v=n.refreshTools();v!==D&&(D=v,o.debug(`tools refreshed: ${v.length} tools`))}if(fn($,S)){o.info(`turn aborted by guard at turn ${oe}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:k.totalUsage};return}let de=pn($,S);if(de.level==="blocking"){de.reason==="prompt_too_long"&&Ye(I)&&(I.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${de.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${de.reason}), ending tool loop`);break}de.level==="warning"&&o.info(`token budget warning: ${de.usagePercent}% used, ${de.remainingTokens} remaining`);let g;{let v=await _s(j,k.contentReplacementState,s);g=v.messages,v.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${v.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${v.newlyReplacedCount} persisted`})}{let v=Go(g,k.snipRemovedIds);g=v.messages,v.removedCount>0&&(o.info(`snip: removed ${v.removedCount} messages, freed ~${v.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${v.removedCount} messages`})}{let C=new Re().compress(g,0);C.droppedCount>0&&(g=C.messages,o.info(`microcompact: cleared ${C.droppedCount} old tool results`))}if(g=Ko(g,ue).messages,$.promptTokens>0){let v=As(g,{budget:S.contextWindowTokens*.75,model:k.currentModel});v.droppedCount>0&&(g=v.messages,o.info(`autocompact: ${v.strategy}, dropped ${v.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${v.strategy}: ${v.droppedCount} dropped`},k.hasAttemptedReactiveCompact=!1,d?.invoke("context.after_compact",{...m,removedCount:v.droppedCount}).catch(()=>{}))}g=Zu(g);let b=Yo({tools:D,toolChoice:n.toolChoice??"auto"}),w=Wt({maxRounds:_,replayMessages:g,lastStopReason:se.lastStopReason,options:{stopReason:se.lastStopReason}}),R=b.extraSystemPrompt?[{role:"system",content:b.extraSystemPrompt},...w.state.replayMessages]:w.state.replayMessages;se=w.state,w.recoveryActions.length>0&&o.debug(`tool loop recovery: ${w.recoveryActions.map(v=>v.detail??v.kind).join("; ")}`),o.debug(`turn ${oe}, messages: ${R.length}`),d?.invoke("turn.before_inference",{...m,model:k.currentModel}).catch(()=>{});let M=!1,H=[],Z=new Map,V="stop",N,E=null,L=!1,B=[],he=[];try{for await(let v of e.stream({model:k.currentModel,messages:R,tools:b.tools,toolChoice:b.normalizedToolChoice??"auto",temperature:l,maxTokens:(Se??$.currentMaxOutputTokens)||void 0,streamRequired:n.streamRequired},u,p))switch(v.type){case"delta":H.push(v.text),M||(yield{type:"delta",turnId:r,text:v.text});break;case"tool_call_delta":M=!0,yn(Z,v);break;case"reasoning_delta":B.push(v.text);break;case"reasoning_block_complete":v.signature&&he.push({thinking:B.join(""),signature:v.signature}),B.length=0;break;case"usage":N={prompt:v.promptTokens,completion:v.completionTokens,reasoning:v.reasoningTokens,cacheRead:v.cacheReadTokens,cacheCreation:v.cacheCreationTokens};break;case"done":V=v.finishReason;break}if(M||d?.invoke("turn.after_inference",{...m,model:k.currentModel}).catch(()=>{}),n.postSamplingHooks&&n.postSamplingHooks.length>0){let v=k.currentModel;for(let C of n.postSamplingHooks)try{C({messages:[...g],model:v,sessionId:s})}catch{}}}catch(v){if(v instanceof yt&&n.fallbackModel){o.info(`model fallback triggered: ${v.originalModel} \u2192 ${v.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${v.originalModel} \u2192 ${v.fallbackModel}`},k={...k,currentModel:v.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let C=v instanceof Error?v.message:String(v),W=typeof v?.status=="number"?v.status:void 0;if(!W&&C&&(C.includes("ECONNRESET")||C.includes("EPIPE"))){let ce=(k.consecutiveApiRetries??0)+1;if(ce>bt){o.info(`stale connection retry limit reached (${bt}), aborting`),yield{type:"error",turnId:r,error:C,code:"RETRIES_EXHAUSTED",usage:k.totalUsage};return}o.info(`stale connection (${C.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:C.slice(0,80)},k={...k,consecutiveApiRetries:ce,transition:void 0};continue}let ie=Qu({status:W,message:C});if(ie!==null){o.info(`max_tokens overflow: adjusting to ${ie}`),$.currentMaxOutputTokens=ie,k={...k,maxOutputTokensOverride:ie,transition:void 0};continue}if(rn(W)){if(k.consecutive529Errors++,k.consecutive529Errors>=ms&&n.fallbackModel&&k.currentModel!==n.fallbackModel){o.info(`529 \xD7 ${k.consecutive529Errors}: triggering fallback to ${n.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${k.consecutive529Errors}`},k={...k,currentModel:n.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(sn()){let ce=Ht(k.consecutive529Errors);o.info(`persistent retry: waiting ${ce}ms (attempt ${k.consecutive529Errors})`);let q=ce;for(;q>0;){if(p?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED",usage:k.totalUsage};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(q/1e3)}s (${W})`};let pe=Math.min(q,ps);await new Promise(pc=>setTimeout(pc,pe)),q-=pe}k={...k,transition:void 0};continue}if(nn(y)){let q=Xu({status:W,message:C})??Ht(k.consecutive529Errors);o.info(`transient ${W}: retry in ${q}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${W} retry in ${q}ms`},await new Promise(pe=>setTimeout(pe,q)),k={...k,transition:void 0};continue}o.info(`background source ${y}: not retrying ${W}`)}E={status:W,message:C}}if(E&&d?.invoke("turn.after_inference",{...m,model:k.currentModel,response:{error:E.message}}).catch(()=>{}),E)if(Ds(E))L=!0,o.info(`withheld prompt_too_long error (status=${E.status})`);else if(Us(E))L=!0,o.info(`withheld media_size error (status=${E.status})`);else{let v=mn({status:E.status??500,message:E.message},$,S);if(v.action==="reactive_compact"&&Ye(I)&&(I.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${E.status??500}: ${E.message}`}),v.action==="retry"){let W=(k.consecutiveApiRetries??0)+1;if(W>bt){o.info(`API retry limit reached (${bt}), aborting`);let ie=Ke(E.status,E.message);yield{type:"error",turnId:r,error:E.message,code:ie,usage:k.totalUsage};return}yield{type:"recovery",turnId:r,action:"retry",detail:v.reason},k={...k,consecutiveApiRetries:W,transition:void 0};continue}let C=Ke(E.status,E.message);d?.invoke("stop.failure",{sessionId:s,reason:C,error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:C,usage:k.totalUsage};return}N&&(k.totalUsage.prompt+=N.prompt,k.totalUsage.completion+=N.completion,N.reasoning&&(k.totalUsage.reasoning=(k.totalUsage.reasoning??0)+N.reasoning),N.cacheRead&&(k.totalUsage.cacheRead=(k.totalUsage.cacheRead??0)+N.cacheRead),N.cacheCreation&&(k.totalUsage.cacheCreation=(k.totalUsage.cacheCreation??0)+N.cacheCreation)),N?.prompt&&($.promptTokens=N.prompt),k.finalText=H.join("");let ye=[...Z.values()].map(v=>({id:v.id||`tc_${r}_${oe}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:v.name,arguments:v.arguments}}));if(ye.length===0&&!M){if(L&&E&&Ds(E)){if(k.transition?.reason!=="collapse_drain_retry"){let v=Jo(g,ue);if(v.committed>0){o.info(`collapse drain: committed ${v.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${v.committed} stages committed`},k={...k,messages:v.messages,transition:{reason:"collapse_drain_retry",committed:v.committed}};continue}}if(Ye(I)){I.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},k={...k,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),d?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:"PROMPT_TOO_LONG",usage:k.totalUsage};return}if(L&&E&&Us(E)){if(Ye(I)){I.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},k={...k,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),d?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:E.message}).catch(()=>{}),yield{type:"error",turnId:r,error:E.message,code:"IMAGE_ERROR",usage:k.totalUsage};return}if(Yu(V)){$.consecutiveTruncations+=1;let v=n.modelMaxOutputTokens??cs,C=gn($,S,v);if(C.shouldEscalate&&Se===void 0){$.currentMaxOutputTokens=C.newMax,o.info(`max_output_tokens escalate: ${C.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${C.newMax} tokens`},k={...k,maxOutputTokensOverride:ds,transition:{reason:"max_output_tokens_escalate"}};continue}if(J<us){let W={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${J+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${J+1}`},k={...k,messages:[...g,W],maxOutputTokensRecoveryCount:J+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:J+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else $.consecutiveTruncations=0;if(se=Bt(se,{replayMessages:j,lastStopReason:"completed"}),d){let v=await d.invoke("stop",{sessionId:s,reason:"completed"});if(v.action==="prevent"){o.info(`stop hook prevented continuation: ${v.reason??"no reason"}`),yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}if(v.action==="abort"){let C=v.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${C}`);let W={role:"user",content:C},ie={role:"assistant",content:k.finalText,...he.length>0&&{thinkingBlocks:[...he]}};k={...k,messages:[...j,ie,W],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(n.tokenBudget&&n.tokenBudget>0){let v=k.totalUsage.prompt+k.totalUsage.completion+(k.totalUsage.reasoning??0),C=v/n.tokenBudget*100;if(C<90){let W={role:"user",content:Es(C,v,n.tokenBudget)};o.info(`token budget continuation: ${Math.round(C)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(C)}% used`};let ie={role:"assistant",content:k.finalText,...he.length>0&&{thinkingBlocks:[...he]}};k={...k,messages:[...j,ie,W],transition:{reason:"token_budget_continuation"}};continue}}if(K>0){let v={ok:!0,toolCallCount:K,distinctToolCount:O.size,multiStep:K>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},C=ht(v,{tools:[...O]});C&&(yield{type:"skill_instruction",turnId:r,instruction:C})}yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}for(let v of ye){let C=v.function.arguments,W=D.find(ie=>ie.function.name===v.function.name);if(W?.backfillObservableInput)try{let ie=JSON.parse(v.function.arguments),ce={...ie};W.backfillObservableInput(ce),Object.keys(ce).some(pe=>!(pe in ie))&&(C=JSON.stringify(ce))}catch{}yield{type:"tool_call",turnId:r,callId:v.id,name:v.function.name,arguments:C}}let uc=he.length===0&&B.length>0?B.join(""):void 0;j.push(No(ye,k.finalText||void 0,he.length>0?he:void 0,uc)),se=on(se,{replayMessages:j,pendingToolCallIds:ye.map(v=>v.id),completedToolCallIds:se.completedToolCallIds,lastStopReason:"tool_calls"});let Ar=[];try{let v=new Gt({toolInvoker:t,hooks:d,sessionId:s,turnId:r,log:o,signal:p,maxConcurrentTools:n?.maxConcurrentTools});for(let C of ye)v.addTool(C);for await(let C of v.getRemainingResults()){C.blocked&&(yield{type:"tool_blocked",turnId:r,callId:C.callId,name:C.toolName,reason:C.blockReason??"blocked"}),j.push(C.message),Ar.push(C.callId),O.add(C.toolName),K++;let W=typeof C.message?.content=="string"?C.message.content:"",ie=C.ok&&W?W.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:C.callId,name:C.toolName,ok:C.ok,error:C.error,outputPreview:ie},C.ok){let ce=ye.find(q=>q.id===C.callId);if(ce){if(C.toolName==="plan_mode")try{let q=JSON.parse(ce.function.arguments);q.action==="exit"&&typeof q.plan=="string"&&q.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:q.plan})}catch{}if(Vu.has(C.toolName))try{let q=JSON.parse(ce.function.arguments),pe=typeof q.file_path=="string"?q.file_path:typeof q.filePath=="string"?q.filePath:typeof q.path=="string"?q.path:void 0;pe&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${C.callId}`,artifactType:qu(pe),title:pe.split(/[\\/]/).pop()||pe,filePath:pe,language:Ku(pe)})}catch{}}}}}catch(v){let C=v instanceof Error?v.message:String(v);yield{type:"error",turnId:r,error:C,code:"TOOL_EXECUTION_ERROR",usage:k.totalUsage};return}if(se=Bt(se,{replayMessages:j,completedToolCallIds:[...se.completedToolCallIds,...Ar],lastStopReason:"tool_calls"}),n.generateToolUseSummary&&ye.length>0){let v=ye.map(C=>({name:C.function.name,arguments:C.function.arguments}));F=n.generateToolUseSummary(v).catch(()=>null)}let Ir=j.slice(-ye.length),dc=Ir.length>0&&Ir.every(v=>{let C=v?.content;return typeof C!="string"?!1:C.startsWith("Error: ")}),lt=k.consecutiveFailedRounds;if(dc){if(lt+=1,lt>=ss&&k.finalText){o.info(`early exit: ${lt} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}}else lt=0;let Uo=oe+1;if(h>0&&Uo>h){if(o.info(`max turns reached (${h}), completing`),d){let v=await d.invoke("stop",{sessionId:s,reason:"max_turns"});if(v.action==="abort"){let C=v.reason??"Stop hook requested continuation after max_turns",W={role:"assistant",content:k.finalText,...he.length>0&&{thinkingBlocks:[...he]}};k={...k,messages:[...j,W,{role:"user",content:C}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}if(Uo>_){if(o.info(`tool loop budget exhausted (${_} rounds), returning`),K>0){let v={ok:!0,toolCallCount:K,distinctToolCount:O.size,multiStep:K>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},C=ht(v,{tools:[...O]});C&&(yield{type:"skill_instruction",turnId:r,instruction:C})}yield{type:"end",turnId:r,content:k.finalText,usage:k.totalUsage,model:k.currentModel};return}k={messages:j,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Uo,transition:{reason:"next_turn"},guardState:$,reactiveCompactState:I,toolLoopState:se,consecutiveFailedRounds:lt,finalText:k.finalText,totalUsage:k.totalUsage,collapseStore:ue,currentModel:k.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:k.stopHookActive,snipRemovedIds:k.snipRemovedIds,contentReplacementState:k.contentReplacementState}}}async function*ed(n,e,t,o,r,s,i,a){let c=[],u;a.debug(`single LLM round, messages: ${t.length}`);for await(let l of i.stream({model:e,messages:t,temperature:r},o,s))switch(l.type){case"delta":c.push(l.text),yield{type:"delta",turnId:n,text:l.text};break;case"usage":u={prompt:l.promptTokens,completion:l.completionTokens,reasoning:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheCreation:l.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:n,content:c.join(""),usage:u??{prompt:0,completion:0},model:e}}var Vu,Fs=z(()=>{"use strict";bn();Xe();Cs();Cn();Os();kn();zt();Vu=new Set(["write","edit","patch","apply_patch"])});var Bs={};Er(Bs,{Agent:()=>Qe});var Qe,Vt=z(()=>{"use strict";Xe();Fs();zt();Qe=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:o,messages:r,tools:s,systemPrompt:i,config:a}=e,c={sessionId:e.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...c,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let u=en(r),l=[];if(i&&l.push({role:"system",content:i}),l.push(...u),this.hooks){let m=u.filter(y=>y.role==="user").pop(),h=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(h)try{let y=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:o,query:h}),T=y?.context?.recalledMemories;if(T&&T.length>0){let x=T.map(f=>`- ${f.text}`).join(`
|
|
25
|
+
`);l.splice(i?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
26
|
+
${x}`})}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o,blockCount:y?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let d=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=a?.summaryModel?async T=>{try{let x=T.map(S=>`${S.name}(${S.arguments.slice(0,200)})`).join(", "),f=this.transport.stream({model:a.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:x}],tools:[],maxTokens:60},a.apiKey??this.apiKey),_="";for await(let S of f)S.type==="delta"&&(_+=S.text);return _.trim()||null}catch{return null}}:void 0,h={turnId:o,sessionId:e.sessionId,messages:l,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,generateToolUseSummary:m,signal:t},y;for await(let T of Ns(h,this.transport,this.toolInvoker,this.log))y=T,yield T;y?.type==="end"?this.hooks?.invoke("turn.completed",{...c}).catch(()=>{}):y?.type==="error"&&this.hooks?.invoke("turn.failed",{...c,code:y.code,error:y.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...c,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let h=m instanceof Error?m.message:String(m),y=typeof m?.status=="number"?m.status:void 0,T=Ke(y,h);this.log.error(`turn ${o} error [${T}, retryable=${jo(T)}]: ${h}`),this.hooks?.invoke("turn.failed",{...c,code:T,error:h}).catch(()=>{}),yield{type:"error",turnId:o,error:h,code:T}}}}}});Vt();function od(n){let e={verbose:!1};for(let t of n.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{createInterface as nd}from"node:readline";var Tt=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)}
|
|
27
|
+
`)}start(){let e=nd({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let o=t.trim();if(o)try{let r=JSON.parse(o);this.messageHandler?.(r)}catch{this.log(`invalid JSON on stdin: ${o.slice(0,200)}`)}}),e.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
|
|
28
|
+
`)}};import{randomUUID as we}from"node:crypto";Vt();bn();var be=class{supportedTypes=["image","video","3d"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??18e4}async generate(e,t,o){switch(e.mediaType){case"image":return this.generateImage(e,t,o);case"video":return this.generateVideo(e,t,o);case"3d":return this.generate3D(e,t,o);default:throw new Error(`VolcengineMediaTransport: unsupported mediaType "${e.mediaType}"`)}}canHandle(e){return!!this.supportedTypes.includes(e.mediaType)}async generateImage(e,t,o){let r=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"};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:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${l}`)}return e.streamImage&&a.body?this.parseStreamingImage(a.body,e,r):{mediaUrls:((await a.json()).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r}}async parseStreamingImage(e,t,o){let r=new TextDecoder,s="",i="",a=e.getReader();try{for(;;){let{done:c,value:u}=await a.read();if(c)break;s+=r.decode(u,{stream:!0});let l;for(;(l=s.indexOf(`
|
|
29
|
+
`))!==-1;){let d=s.slice(0,l).trim();if(s=s.slice(l+1),!d||d.startsWith(":")||!d.startsWith("data:"))continue;let p=d.slice(5).trim();if(p==="[DONE]")break;try{let h=JSON.parse(p).data?.[0]?.url;h&&(i=h,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()-o}}async generateVideo(e,t,o){let r=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=e.referenceVideos?.length??0,a=e.referenceAudios?.length??0,c=e.referenceImages?.length??0,u=!!(e.imageUrl||c>0);if(i>3)throw new Error(`Seedance 2.0: max 3 reference videos (got ${i}). Total duration must be \u226415s.`);if(a>3)throw new Error(`Seedance 2.0: max 3 reference audios (got ${a}). Total duration must be \u226415s.`);if(a>0&&!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"&&c>9)throw new Error(`Seedance 2.0 video edit: max 9 reference images (got ${c}).`);let l=[];switch(e.draftTaskId&&l.push({type:"draft_task",id:e.draftTaskId}),e.operation){case"multimodal_reference":{if(e.prompt&&l.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let x=0;x<e.referenceImages.length;x++){let f=e.imageRoles?.[x]??"reference_image";l.push({type:"image_url",image_url:{url:e.referenceImages[x]},role:f})}if(e.referenceVideos?.length)for(let x of e.referenceVideos)l.push({type:"video_url",video_url:{url:x},role:"reference_video"});if(e.referenceAudios?.length)for(let x of e.referenceAudios)l.push({type:"audio_url",audio_url:{url:x},role:"reference_audio"});break}case"extend":{if(e.sourceVideos?.length)for(let x of e.sourceVideos)l.push({type:"video_url",video_url:{url:x},role:"reference_video"});e.prompt&&l.push({type:"text",text:e.prompt});break}case"merge":for(let x of e.sourceVideos??[])l.push({type:"video_url",video_url:{url:x}});e.prompt&&l.push({type:"text",text:e.prompt});break;case"upscale":e.sourceVideos?.[0]&&l.push({type:"video_url",video_url:{url:e.sourceVideos[0]}}),l.push({type:"text",text:e.prompt||"upscale"});break;case"edit":for(let x of e.sourceVideos??[])l.push({type:"video_url",video_url:{url:x},role:"reference_video"});if(e.referenceImages?.length)for(let x of e.referenceImages)l.push({type:"image_url",image_url:{url:x},role:"reference_image"});e.prompt&&l.push({type:"text",text:e.prompt});break;default:{let x=(e.referenceVideos?.length??0)>0,f=(e.referenceAudios?.length??0)>0,_=(e.imageRoles?.length??0)>0;if(x||f||_){if(e.prompt&&l.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let S=0;S<e.referenceImages.length;S++){let O=e.imageRoles?.[S]??"reference_image";l.push({type:"image_url",image_url:{url:e.referenceImages[S]},role:O})}if(x)for(let S of e.referenceVideos)l.push({type:"video_url",video_url:{url:S},role:"reference_video"});if(f)for(let S of e.referenceAudios)l.push({type:"audio_url",audio_url:{url:S},role:"reference_audio"})}else if(e.referenceImages?.length){for(let S of e.referenceImages)l.push({type:"image_url",image_url:{url:S}});e.prompt&&l.push({type:"text",text:e.prompt})}else e.imageUrl?(l.push({type:"image_url",image_url:{url:e.imageUrl}}),e.prompt&&l.push({type:"text",text:e.prompt})):e.prompt&&l.push({type:"text",text:e.prompt});break}}let d={model:e.model,content:l};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(x=>({type:x})));let p=await this.submitTask(s,d,t,o),m=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${p}`,t,o,e.onProgress),h=[],y=m.content;typeof y?.video_url=="string"&&h.push(y.video_url);let T=typeof y?.last_frame_url=="string"?y.last_frame_url:void 0;return{mediaUrls:h,model:e.model,durationMs:Date.now()-r,lastFrameUrl:T,taskId:p}}async generate3D(e,t,o){let r=Date.now(),s=`${this.baseUrl}/v3/3d-contents/generations/tasks`,i={model:e.model};e.imageUrl&&(i.image={url:e.imageUrl}),e.prompt&&(i.prompt=e.prompt),e.outputFormat&&(i.output_format=e.outputFormat);let a=await this.submitTask(s,i,t,o),c=await this.pollTask(`${this.baseUrl}/v3/3d-contents/generations/tasks/${a}`,t,o,e.onProgress),u=[],l=c.output;if(l?.model_urls){let d=l.model_urls;for(let p of Object.values(d))p&&u.push(p)}return{mediaUrls:u,model:e.model,durationMs:Date.now()-r}}async listVideoTasks(e,t,o){let r=new URLSearchParams;t?.after&&r.set("after",t.after),t?.limit&&r.set("limit",String(t.limit)),t?.status&&r.set("status",t.status);let s=r.toString(),i=`${this.baseUrl}/v3/contents/generations/tasks${s?`?${s}`:""}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Volcengine list tasks error ${a.status}: ${c}`)}return await a.json()}async deleteVideoTask(e,t,o){let r=`${this.baseUrl}/v3/contents/generations/tasks/${e}`,s=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:o??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,o,r){let s=`${this.baseUrl}/v3/files`,i=new FormData;i.append("file",e instanceof Blob?e:new Blob([e]),o?.filename??"upload"),i.append("purpose",o?.purpose??"user_data");let a=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:i,signal:r??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Volcengine file upload error ${a.status}: ${u}`)}let c=await a.json();return{id:String(c.id??""),status:String(c.status??"")}}async getFile(e,t,o){let r=`${this.baseUrl}/v3/files/${e}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??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,o){let r=new URLSearchParams;t?.after&&r.set("after",t.after),t?.limit&&r.set("limit",String(t.limit)),t?.purpose&&r.set("purpose",t.purpose),t?.order&&r.set("order",t.order);let s=r.toString(),i=`${this.baseUrl}/v3/files${s?`?${s}`:""}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Volcengine list files error ${a.status}: ${c}`)}return await a.json()}async deleteFile(e,t,o){let r=`${this.baseUrl}/v3/files/${e}`,s=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:o??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,o,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(t),signal:r??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Volcengine task submit error ${s.status}: ${c}`)}let i=await s.json(),a=i.id??i.task_id;if(!a)throw new Error("Volcengine task submit: no task_id in response");return a}async pollTask(e,t,o,r){let s=Date.now()+6e5,i=0;for(;Date.now()<s;){o?.throwIfAborted();let a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let p=await a.text().catch(()=>"");throw new Error(`Volcengine task poll error ${a.status}: ${p}`)}let c=await a.json(),u=c.status;if(u==="succeeded"||u==="complete")return r?.(100,"completed"),c;if(u==="failed"||u==="cancelled"){let p=c.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${p}`)}i++;let l=Date.now()-(s-6e5),d=Math.min(95,Math.round(l/6e5*100));r?.(d,u??"running"),await new Promise(p=>setTimeout(p,3e3))}throw new Error("Volcengine task timed out after polling")}};import{writeFileSync as sd,mkdirSync as id}from"node:fs";import{join as ti}from"node:path";import{randomUUID as ad}from"node:crypto";import{homedir as rd}from"node:os";import{join as ee}from"node:path";var Te=".qlogicagent";function G(){return ee(rd(),Te)}function Sn(){return ee(G(),"sessions")}function Ws(n){return ee(Sn(),n)}function Hs(){return ee(G(),"plugins")}function qt(){return ee(G(),"skills")}function Ze(){return ee(G(),"settings.json")}function Me(){return ee(G(),"cache")}function zs(){return ee(G(),"debug-logs")}function Gs(n){let e=ee(G(),"checkpoints");return n?ee(e,n):e}function Vs(){return ee(G(),"plugin-cache")}function qs(){return ee(G(),"mcp.json")}function Ks(){return ee(G(),"marketplace.json")}function Js(){return ee(G(),"workflows")}function Ys(){return ee(G(),"rules")}function Rn(n){return ee(n??process.cwd(),Te)}function Xs(n){return ee(Rn(n),"workflows")}function Qs(n){return ee(Rn(n),"INSTRUCTIONS.md")}function Zs(n){return ee(Rn(n),"rules")}function ei(n){return ee(n,Te,"hooks")}var ld=18e4,kt=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??ld}async generate(e,t,o){switch(e.mediaType){case"image":return this.generateImage(e,t,o);case"tts":return this.generateTTS(e,t,o);default:throw new Error(`OpenAIMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateImage(e,t,o){let r=Date.now(),s=`${this.baseUrl}/v1/images/generations`,i={model:e.model,prompt:e.prompt,n:e.n??1,size:e.size??"1024x1024",response_format:"url"};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:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${l}`)}return{mediaUrls:((await a.json()).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r}}async generateTTS(e,t,o){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("OpenAIMediaTransport: text or prompt is required for TTS");let i=`${this.baseUrl}/v1/audio/speech`,a={model:e.model||"tts-1",input:s,voice:e.voice??"alloy",response_format:e.audioFormat??"mp3"};e.speed!==void 0&&(a.speed=e.speed);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`OpenAI TTS API error ${c.status}: ${m}`)}let u=Buffer.from(await c.arrayBuffer()),l=ti(Me(),"tts");id(l,{recursive:!0});let d=`openai-tts-${ad()}.mp3`,p=ti(l,d);return sd(p,u),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:s.length}}};var We=class{supportedTypes=["music"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??6e4}async generate(e,t,o){if(e.mediaType!=="music")throw new Error(`MiniMaxMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=`${this.baseUrl}/v1/music_generation`,i={model:e.model,prompt:e.prompt,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:o??AbortSignal.timeout(6e5)});if(!a.ok){let m=await a.text().catch(()=>"");throw new Error(`MiniMax music error ${a.status}: ${m}`)}let c=await a.json();if(c.base_resp?.status_code&&c.base_resp.status_code!==0)throw new Error(`MiniMax music rejected: ${c.base_resp.status_msg??"unknown"}`);let u=c.data?.audio??c.audio_file;if(u)return{mediaUrls:[u],model:e.model,durationMs:Date.now()-r};let l=c.task_id;if(!l)throw new Error("MiniMax music: no audio_file or task_id in response");let d=`${this.baseUrl}/v1/music_generation/${l}`;return{mediaUrls:(await this.pollTask(d,t,o,e.onProgress)).audioUrls,model:e.model,durationMs:Date.now()-r}}async pollTask(e,t,o,r){let s=Date.now()+6e5;for(;Date.now()<s;){o?.throwIfAborted();let i=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let l=await i.text().catch(()=>"");throw new Error(`MiniMax music poll error ${i.status}: ${l}`)}let a=await i.json(),c=a.status;if(c==="Success"||c==="Finished"){r?.(100,"completed");let l=[];return a.audio_file&&l.push(a.audio_file),{audioUrls:l}}if(c==="Failed"||c==="Cancelled")throw new Error(`MiniMax music task failed: ${a.base_resp?.status_msg??"unknown"}`);let u=Date.now()-(s-6e5);r?.(Math.min(95,Math.round(u/6e5*100)),c??"running"),await new Promise(l=>setTimeout(l,3e3))}throw new Error("MiniMax music task timed out after polling")}async generateLyrics(e,t,o){let r=`${this.baseUrl}/v1/lyrics_generation`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({prompt:e}),signal:o??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??""}};import{writeFileSync as cd,mkdirSync as ud}from"node:fs";import{join as oi}from"node:path";import{randomUUID as dd}from"node:crypto";var pd=18e4,xt=class{supportedTypes=["image"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??pd}async generate(e,t,o){if(e.mediaType!=="image")throw new Error(`GeminiMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={responseModalities:["TEXT","IMAGE"]};e.aspectRatio&&(i.aspectRatio=e.aspectRatio);let a={contents:[{parts:[{text:e.prompt}]}],generationConfig:i},c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":t},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`Gemini image API error ${c.status}: ${p}`)}let u=await c.json(),l=[],d=oi(Me(),"gemini-images");ud(d,{recursive:!0});for(let p of u.candidates??[])for(let m of p.content?.parts??[])if(m.inlineData?.data){let h=m.inlineData.mimeType==="image/png"?"png":m.inlineData.mimeType==="image/webp"?"webp":"jpg",y=`gemini-${dd()}.${h}`,T=oi(d,y);cd(T,Buffer.from(m.inlineData.data,"base64")),l.push(`file://${T}`)}return{mediaUrls:l,model:e.model,durationMs:Date.now()-r}}};var Kt=class{supportedTypes=["tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/apps\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??3e4}async generate(e,t,o){if(e.mediaType!=="tts")throw new Error(`QwenMediaTransport: unsupported mediaType "${e.mediaType}"`);let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("QwenMediaTransport: text or prompt is required for TTS");let i=`${this.baseUrl}/api/v1/services/aigc/text2audio/generation`,a={format:e.audioFormat??"mp3",sample_rate:24e3},c={text:s};e.voice&&(c.voice=e.voice),e.speed!==void 0&&(a.speech_rate=e.speed);let u={model:e.model||"qwen3-tts-voicedesign",input:c,parameters:a},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(u),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let h=await l.text().catch(()=>"");throw new Error(`DashScope TTS submit error ${l.status}: ${h}`)}let d=await l.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 h=this.extractAudioUrl(d);return{mediaUrls:h?[h]:[],model:e.model,durationMs:Date.now()-r}}return{mediaUrls:await this.pollTask(p,t,o,e.onProgress),model:e.model,durationMs:Date.now()-r}}async pollTask(e,t,o,r){let s=Date.now()+12e4,i=`${this.baseUrl}/api/v1/tasks/${e}`;for(;Date.now()<s;){o?.throwIfAborted(),await md(2e3);let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${a.status}: ${d}`)}let c=await a.json();if(c.code)throw new Error(`DashScope TTS poll rejected: ${c.code} \u2014 ${c.message??""}`);let u=c.output?.task_status;if(u==="SUCCEEDED"){r?.(100,"completed");let d=this.extractAudioUrl(c);return d?[d]:[]}if(u==="FAILED")throw new Error(`DashScope TTS task failed: ${c.message??"unknown error"}`);let l=Date.now()-(s-12e4);r?.(Math.min(95,Math.round(l/12e4*100)),u??"running")}throw new Error("DashScope TTS task timed out")}extractAudioUrl(e){if(e.output?.audio_url)return e.output.audio_url;if(e.output?.results?.[0]?.url)return e.output.results[0].url}};function md(n){return new Promise(e=>setTimeout(e,n))}import{writeFileSync as gd,mkdirSync as fd}from"node:fs";import{join as ni}from"node:path";import{randomUUID as hd}from"node:crypto";var yd=18e4,bd=3e3,Jt=6e5,Td=new Set(["glm-image"]),vt=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??yd}async generate(e,t,o){switch(e.mediaType){case"image":return this.generateImage(e,t,o);case"video":return this.generateVideo(e,t,o);case"tts":return this.generateTTS(e,t,o);case"stt":return this.generateSTT(e,t,o);case"embedding":return this.generateEmbedding(e,t,o);case"voice_clone":return this.generateVoiceClone(e,t,o);case"document_parsing":return this.generateDocumentParsing(e,t,o);case"rerank":return this.generateRerank(e,t,o);default:throw new Error(`ZhipuMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateImage(e,t,o){return Td.has(e.model)?this.generateImageAsync(e,t,o):this.generateImageSync(e,t,o)}async generateImageSync(e,t,o){let r=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,o)).data??[]).map(l=>l.url).filter(l=>!!l),model:e.model,size:e.size,durationMs:Date.now()-r}}async generateImageAsync(e,t,o){let r=Date.now(),s=`${this.baseUrl}/async/images/generations`,i={model:e.model,prompt:e.prompt};e.size&&(i.size=e.size),e.quality&&(i.quality=e.quality);let c=(await this.postJSON(s,i,t,o)).id;if(!c)throw new Error("Zhipu async image: no task id in response");return{mediaUrls:((await this.pollAsyncResult(c,t,o,e.onProgress)).data??[]).map(p=>p.url).filter(p=>!!p),model:e.model,size:e.size,durationMs:Date.now()-r}}async generateVideo(e,t,o){let r=Date.now(),s=`${this.baseUrl}/videos/generations`,i={model:e.model,prompt:e.prompt};e.imageUrl&&(i.image_url=e.imageUrl),e.size&&(i.size=e.size),e.duration&&(i.duration=e.duration);let c=(await this.postJSON(s,i,t,o)).id;if(!c)throw new Error("Zhipu video generation: no task id in response");return{mediaUrls:((await this.pollAsyncResult(c,t,o,e.onProgress)).video_result??[]).map(p=>p.url).filter(p=>!!p),model:e.model,durationMs:Date.now()-r}}async generateTTS(e,t,o){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: text or prompt required for TTS");let i=`${this.baseUrl}/audio/speech`,a={model:e.model||"glm-tts",input:s};e.voice&&(a.voice=e.voice),e.speed!==void 0&&(a.speed=e.speed),e.audioFormat&&(a.response_format=e.audioFormat);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let h=await c.text().catch(()=>"");throw new Error(`Zhipu TTS API error ${c.status}: ${h}`)}let u=Buffer.from(await c.arrayBuffer()),l=ni(Me(),"tts");fd(l,{recursive:!0});let d=e.audioFormat??"wav",p=`zhipu-tts-${hd()}.${d}`,m=ni(l,p);return gd(m,u),{mediaUrls:[`file://${m}`],model:e.model||"glm-tts",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:s.length}}async generateSTT(e,t,o){let r=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:o??AbortSignal.timeout(this.timeoutMs)});if(!i.ok)throw new Error(`Failed to fetch audio from ${e.audioUrl}`);let a=await i.blob(),c=new FormData;c.append("model",e.model||"glm-asr-2512"),c.append("file",a,"audio.wav");let u=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:c,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!u.ok){let d=await u.text().catch(()=>"");throw new Error(`Zhipu STT API error ${u.status}: ${d}`)}let l=await u.json();return{mediaUrls:[],model:e.model||"glm-asr-2512",durationMs:Date.now()-r,metadata:{transcription:l.text??""}}}async generateEmbedding(e,t,o){let r=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,o)).data??[];return{mediaUrls:[],model:e.model||"embedding-3",durationMs:Date.now()-r,metadata:{embeddings:u.map(l=>l.embedding).filter(Boolean)}}}async generateVoiceClone(e,t,o){let r=Date.now();if(!e.audioUrl)throw new Error("ZhipuMediaTransport: audioUrl required for voice_clone (sample audio)");let s=await fetch(e.audioUrl,{signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`Failed to fetch audio sample from ${e.audioUrl}`);let i=await s.blob(),a=new FormData;a.append("model",e.model||"glm-tts-clone"),a.append("file",i,"sample.wav"),(e.text||e.prompt)&&a.append("text",e.text||e.prompt||"");let c=`${this.baseUrl}/voice/clone`,u=await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:a,signal:o??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 l=await u.json();return{mediaUrls:(l.data??[]).map(p=>p.url).filter(p=>!!p),model:e.model||"glm-tts-clone",durationMs:Date.now()-r,metadata:{voiceId:l.voice_id}}}async generateDocumentParsing(e,t,o){let r=Date.now(),s=e.imageUrl||e.audioUrl;if(!s&&!e.prompt)throw new Error("ZhipuMediaTransport: imageUrl/audioUrl (file URL) or prompt (base64) required for document_parsing");let i=`${this.baseUrl}/layout_parsing`,a={model:e.model||"glm-ocr"};s?a.file_url=s:e.prompt&&(a.content=e.prompt);let l=(await this.postJSON(i,a,t,o)).pages??[];return{mediaUrls:[],model:e.model||"glm-ocr",durationMs:Date.now()-r,metadata:{pages:l.map(d=>({pageNum:d.page_num,content:d.content,layouts:d.layouts}))}}}async generateRerank(e,t,o){let r=Date.now(),s=e.prompt;if(!s)throw new Error("ZhipuMediaTransport: prompt (query) required for rerank");if(!e.metadata?.documents)throw new Error("ZhipuMediaTransport: metadata.documents required for rerank");let i=`${this.baseUrl}/rerank`,a={model:e.model||"rerank",query:s,documents:e.metadata.documents};e.metadata.topN!==void 0&&(a.top_n=e.metadata.topN);let c=await this.postJSON(i,a,t,o);return{mediaUrls:[],model:e.model||"rerank",durationMs:Date.now()-r,metadata:{results:(c.results??[]).map(u=>({index:u.index,relevanceScore:u.relevance_score,document:u.document}))}}}async postJSON(e,t,o,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(t),signal:r??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,o,r){let s=Date.now()+Jt,i=`${this.baseUrl}/async-result/${encodeURIComponent(e)}`;for(;Date.now()<s;){o?.throwIfAborted();let a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`Zhipu async-result error ${a.status}: ${l}`)}let c=await a.json();if(c.task_status==="SUCCESS")return r?.(100,"completed"),c;if(c.task_status==="FAIL")throw new Error("Zhipu async task failed");let u=Date.now()-(s-Jt);r?.(Math.min(95,Math.round(u/Jt*100)),c.task_status??"running"),await new Promise(l=>setTimeout(l,bd))}throw new Error(`Zhipu async task timed out after ${Jt/1e3}s`)}async listVoices(e,t){let o=`${this.baseUrl}/voice/`,r=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:t??AbortSignal.timeout(this.timeoutMs)});if(!r.ok){let i=await r.text().catch(()=>"");throw new Error(`Zhipu voice list error ${r.status}: ${i}`)}return(await r.json()).data??[]}async deleteVoice(e,t,o){let r=`${this.baseUrl}/voice/${encodeURIComponent(e)}`,s=await fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Zhipu voice delete error ${s.status}: ${i}`)}}};var wt=class{registry;transports=new Map;constructor(e){this.registry=e.registry}resolveModelById(e,t,o){let r=this.registry.getProvider(e);if(!r)return;let i=this.registry.listModels(e).find(a=>a.id===t&&a.mediaType===o);if(i)return{providerId:e,providerDef:r,modelInfo:i,mediaType:o}}getTransport(e){let t=this.transports.get(e);if(t)return t;let o=this.registry.getProvider(e);if(!o)return;let r=vd(o);if(r)return this.transports.set(e,r),r}listMediaModels(e){let t=[];for(let o of this.registry.listProviders()){let r=this.registry.listModels(o.id);for(let s of r)s.mediaType&&(!e||s.mediaType===e)&&t.push({providerId:o.id,providerDef:o,modelInfo:s,mediaType:s.mediaType})}return t}findModelInProvider(e,t,o){let r=this.registry.getProvider(e);if(!r)return;let s=this.registry.listModels(e),i=o?kd(o):void 0,a=s.find(c=>c.mediaType!==t?!1:!i||!c.mediaCapabilities?!0:xd(c.mediaCapabilities,i));if(a)return{providerId:e,providerDef:r,modelInfo:a,mediaType:t}}};function kd(n){switch(n.mediaType){case"video":return n.operation==="merge"?"merge":n.operation==="upscale"?"upscale":n.operation==="edit"?"edit":n.imageUrl?"img2video":"text2video";case"image":return n.operation==="edit"?"inpainting":n.imageUrl?"img2img":"text2image";case"music":return n.audioUrl?"cover":"text2music";case"tts":return"text2speech";case"3d":return n.imageUrl?"img2_3d":"text2_3d";default:return}}function xd(n,e){return!("operations"in n)||!n.operations?!0:n.operations.includes(e)}function vd(n){let e=n.baseUrl;switch(n.id){case"volcengine":return new be({baseUrl:e});case"openai":return new kt({baseUrl:e});case"minimax":return new We({baseUrl:e});case"google":return new xt({baseUrl:e});case"qwen":return new Kt({baseUrl:e});case"zhipu":return new vt({baseUrl:e.replace(/\/api\/anthropic\/?$/,"/api/paas/v4")});case"zhipu-openai":case"zhipu-coding":return new vt({baseUrl:e.replace(/\/api\/coding\/paas\/v4\/?$/,"/api/paas/v4")});default:return}}var Mn=[{id:"deepseek",name:"DeepSeek",transport:"anthropic-messages",baseUrl:"https://api.deepseek.com/anthropic",apiKeyEnvVars:["DEEPSEEK_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"deepseek-v4-flash",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-chat",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-5.5",models:[{id:"gpt-5.5",name:"GPT-5.5",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:30,costCacheRead:.5},{id:"gpt-5.4",name:"GPT-5.4",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:2.5,costOutput:15,costCacheRead:.25},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.75,costOutput:4.5,costCacheRead:.075},{id:"o3",name:"o3",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!0,costInput:2,costOutput:8,costCacheRead:.5},{id:"o4-mini",name:"o4-mini",contextWindow:2e5,maxOutput:1e5,toolCall:!0,reasoning:!0,vision:!0,costInput:1.1,costOutput:4.4,costCacheRead:.28},{id:"gpt-image-2",name:"GPT Image 2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img","inpainting"],sizes:["1024x1024","1536x1024","1024x1536","auto"],transparentBackground:!0}},{id:"tts-1",name:"OpenAI TTS-1",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],voices:["alloy","ash","coral","echo","fable","onyx","nova","sage","shimmer"],maxCharacters:4096,formats:["mp3","opus","aac","flac","wav","pcm"]}},{id:"tts-1-hd",name:"OpenAI TTS-1 HD",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],voices:["alloy","ash","coral","echo","fable","onyx","nova","sage","shimmer"],maxCharacters:4096,formats:["mp3","opus","aac","flac","wav","pcm"]}}]},{id:"anthropic",name:"Anthropic",transport:"anthropic-messages",baseUrl:"https://api.anthropic.com",apiKeyEnvVars:["ANTHROPIC_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"claude-opus-4-7",models:[{id:"claude-opus-4-7",name:"Claude Opus 4.7",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-opus-4-6",name:"Claude Opus 4.6",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindow:1e6,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:5,costCacheRead:.1,costCacheWrite:1.25}]},{id:"google",name:"Google Gemini",transport:"openai-chat",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",apiKeyEnvVars:["GOOGLE_API_KEY","GEMINI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gemini-2.5-pro",models:[{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:1.25,costOutput:10,costCacheRead:.125},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.15,costOutput:.6,costCacheRead:.0375},{id:"gemini-3.1-flash-image-preview",name:"Gemini 3.1 Flash Image",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}}]},{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 wd,mkdirSync as _d,readFileSync as Cd,writeFileSync as Sd}from"node:fs";import{join as Rd}from"node:path";var Md="https://models.dev/api.json",Pd=3e4,Ad=1440*60*1e3,Id=300*1e3,Ed={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??Me(),this.cacheFile=Rd(this.cacheDir,"model_catalog.json"),this.ttlMs=e?.ttlMs??Ad}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(!wd(this.cacheFile))return;let e=Cd(this.cacheFile,"utf8"),t=JSON.parse(e);if(!t.fetchedAt||!t.data)return;this.cache={fetchedAt:t.fetchedAt,providers:ri(t.data)}}catch{}}saveToDisk(e){try{_d(this.cacheDir,{recursive:!0});let t=JSON.stringify({fetchedAt:Date.now(),data:e},null,0);Sd(this.cacheFile,t,"utf8")}catch{}}backgroundFetch(){this.fetching||Date.now()-this.lastFetchAttempt<Id||(this.fetching=!0,this.fetchRemote().finally(()=>{this.fetching=!1}))}async fetchRemote(){this.lastFetchAttempt=Date.now();try{let e=await fetch(Md,{signal:AbortSignal.timeout(Pd),headers:{Accept:"application/json"}});if(!e.ok)return!1;let t=await e.json(),o=ri(t);return o.size===0?!1:(this.cache={fetchedAt:Date.now(),providers:o},this.saveToDisk(t),!0)}catch{return!1}}};function ri(n){let e=new Map;if(!n||typeof n!="object")return e;for(let[t,o]of Object.entries(n)){let r=Ed[t];if(!r||!o||typeof o!="object")continue;let i=o.models;if(!i||typeof i!="object")continue;let a=e.get(r);a||(a={models:new Map},e.set(r,a));for(let[c,u]of Object.entries(i)){if(!u||typeof u!="object"||a.models.has(c))continue;let l=u,d=l.cost??{},p=l.limit??{},m=l.modalities??{},h=Array.isArray(m.input)?m.input:[],y=Array.isArray(m.output)?m.output:[],T=Od(y,h,c);a.models.set(c,{id:c,name:typeof l.name=="string"?l.name:c,contextWindow:typeof p.context=="number"?p.context:2e5,maxOutput:typeof p.output=="number"?p.output:8192,toolCall:l.tool_call===!0,reasoning:l.reasoning===!0,vision:l.attachment===!0||h.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:T})}}return e}function Od(n,e,t){if(n.includes("video"))return"video";if(n.includes("image")&&!n.includes("text"))return"image";if(n.includes("audio")&&!n.includes("text"))return"tts";if(n.includes("3d"))return"3d";let o=t.toLowerCase();if(o.includes("tts")||o.includes("speech")||o.includes("cosyvoice"))return"tts";if(o.includes("music")||o.includes("suno"))return"music";if(o.includes("seedream")||o.includes("image")||o.includes("dall"))return"image";if(o.includes("seedance")||o.includes("video"))return"video"}var Ld={claude:"anthropic",gemini:"google",doubao:"volcengine"},et=class{builtins=new Map;catalog;overrides=new Map;constructor(e){for(let t of Mn)this.builtins.set(t.id,t);this.catalog=e?.catalog??new _t}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=Ld[e]??e,o=this.builtins.get(t),r=this.overrides.get(t);if(!(!o&&!r))return!o&&r?!r.id||!r.transport||!r.baseUrl?void 0:{id:r.id,name:r.name??r.id,transport:r.transport,baseUrl:r.baseUrl,apiKeyEnvVars:r.apiKeyEnvVars??[],authType:r.authType??"bearer",isAggregator:r.isAggregator??!1,defaultModel:r.defaultModel,models:r.models}:o&&!r?o:{...o,...r,models:r.models??o.models}}listProviders(){let e=new Map;for(let[t,o]of this.builtins)e.set(t,o);for(let[t]of this.overrides){let o=this.getProvider(t);o&&e.set(t,o)}return[...e.values()]}listModels(e){let o=this.getProvider(e)?.models??[],r=this.catalog.getModels(e);if(r.length===0)return o;let s=new Map;for(let i of r)s.set(i.id,i);for(let i of o)s.set(i.id,i);return[...s.values()]}getModelInfo(e,t){return this.listModels(e).find(o=>o.id===t)}async refreshCatalog(){return this.catalog.refreshCatalog()}resolveApiKey(e,t){if(t)return t;let o=this.getProvider(e);if(o)for(let r of o.apiKeyEnvVars){let s=process.env[r];if(s?.trim())return s.trim()}}};var Pn=new Set([429,529,502,503,504]),tt=9e4;function ot(n){let e=Math.min(1e3*Math.pow(2,n-1),3e4),t=Math.random()*.25*e;return e+t}function Yt(n){return n!=null&&Pn.has(n)}function nt(n,e){return new Promise((t,o)=>{if(e?.aborted){o(new Error("Request aborted"));return}let r=setTimeout(t,n);e&&e.addEventListener("abort",()=>{clearTimeout(r),o(new Error("Request aborted"))},{once:!0})})}function Xt(n){if(n&&typeof n=="object"){let e=n;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}var rt=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,o){this.cumulativeReasoningLen=0,this.cumulativeContentLen=0;let r=e.prefixMessage&&this.quirks.supportsPrefixCompletion,s=/\/v\d+$/.test(this.baseUrl),i;r?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:Dd(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 c=!e.disableBuiltinTools,u=!1;if(c&&this.quirks.builtinWebSearch&&a.tools){let h=a.tools;this.quirks.builtinCodeInterpreter?h.push({type:"web_search",web_search:{enable:!0,search_result:!0}}):(h.push({type:"builtin_function",function:{name:"$web_search"}}),u=!0)}c&&this.quirks.builtinCodeInterpreter&&a.tools&&a.tools.push({type:"code_interpreter",code_interpreter:{sandbox:"none"}}),this.quirks.supportsToolStream&&a.tools&&(a.tool_stream=!0);let l=this.quirks.useEffortInsteadOfBudget&&!!e.reasoning,d=e.model.startsWith("kimi-k2.6");if(e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||!Qt(e.model)&&!l&&!d&&(a.temperature=e.temperature)),e.topP!==void 0&&!Qt(e.model)&&!l&&!d&&(a.top_p=e.topP),e.maxTokens!==void 0&&(Qt(e.model)||e.model.startsWith("kimi-k2")?a.max_completion_tokens=e.maxTokens:a.max_tokens=e.maxTokens),e.reasoning)if(Qt(e.model))a.reasoning_effort=e.reasoning.effort;else if(this.quirks.useEffortInsteadOfBudget){a.thinking={type:"enabled"};let h=this.quirks.maxReasoningEffort??"high",y=e.reasoning.effort??"high";a.reasoning_effort=y==="low"||y==="medium"?"high":h}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),r&&e.prefixMessage&&a.messages.push({role:"assistant",content:e.prefixMessage,prefix:!0});let p={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},m=null;for(let h=0;h<=3;h++){if(o?.aborted)throw new Error("Request aborted");h>0&&m&&await nt(ot(h),o);try{yield*this.fetchAndStream(i,p,a,o);return}catch(y){m=y instanceof Error?y:new Error(String(y));let T=m.message.includes("Stream idle timeout");if(!Yt(Xt(m))&&!T||h===3)throw m}}}async*fetchAndStream(e,t,o,r){let s=AbortSignal.timeout(this.timeoutMs),i=r?AbortSignal.any([r,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(o),signal:i});if(!a.ok){let u=await a.text().catch(()=>""),l=new Error(`LLM API error ${a.status}: ${u.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("LLM API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStreamWithWatchdog(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();t.usage&&(yield{type:"usage",promptTokens:t.usage.prompt_tokens??0,completionTokens:t.usage.completion_tokens??0,reasoningTokens:t.usage.completion_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.prompt_tokens_details?.cached_tokens});for(let o of t.choices??[]){let r=o.message;if(r){if(r.reasoning_content&&(yield{type:"reasoning_delta",text:r.reasoning_content}),r.content&&(yield{type:"delta",text:r.content}),r.tool_calls)for(let s=0;s<r.tool_calls.length;s++){let i=r.tool_calls[s];yield{type:"tool_call_delta",index:s,id:i.id,name:i.function.name,arguments:i.function.arguments}}o.finish_reason&&(yield{type:"done",finishReason:o.finish_reason})}}}async*parseSSEStreamWithWatchdog(e){let t=new TextDecoder,o="",r=null,s=new AbortController,i=()=>{r&&clearTimeout(r),r=setTimeout(()=>{s.abort()},tt)};try{i();let a=e.getReader();try{for(;;){let{done:c,value:u}=await a.read();if(c)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),o+=t.decode(u,{stream:!0});let l;for(;(l=o.indexOf(`
|
|
30
|
+
`))!==-1;){let d=o.slice(0,l).trim();if(o=o.slice(l+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{r&&clearTimeout(r)}}*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 o=t.delta;if(o){if(o.reasoning_content&&(yield{type:"reasoning_delta",text:o.reasoning_content}),o.reasoning_details){let r=o.reasoning_details.slice(this.cumulativeReasoningLen);r&&(this.cumulativeReasoningLen=o.reasoning_details.length,yield{type:"reasoning_delta",text:r})}if(o.content)if(this.quirks.supportsReasoningSplit){let r=o.content.slice(this.cumulativeContentLen);r&&(this.cumulativeContentLen=o.content.length,yield{type:"delta",text:r})}else yield{type:"delta",text:o.content};if(o.tool_calls)for(let r of o.tool_calls)yield{type:"tool_call_delta",index:r.index,id:r.id,name:r.function?.name,arguments:r.function?.arguments??""};t.finish_reason&&(yield{type:"done",finishReason:$d(t.finish_reason)})}}}async*complete(e,t,o){if(!this.quirks.supportsPrefixCompletion)throw new Error("FIM completion is not supported by this provider");let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/beta/completions`:`${this.baseUrl}/beta/v1/completions`,i={model:e.model,prompt:e.prompt,stream:!0,max_tokens:e.maxTokens??4096};e.suffix&&(i.suffix=e.suffix),e.temperature!==void 0&&(i.temperature=e.temperature),e.stop&&(i.stop=e.stop);let a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},c=AbortSignal.timeout(this.timeoutMs),u=o?AbortSignal.any([o,c]):c,l=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(i),signal:u});if(!l.ok){let h=await l.text().catch(()=>"");throw new Error(`FIM API error ${l.status}: ${h.slice(0,500)}`)}if(!l.body)throw new Error("FIM API returned no response body");let d=new TextDecoder,p="",m=l.body.getReader();try{for(;;){let{done:h,value:y}=await m.read();if(h)break;p+=d.decode(y,{stream:!0});let T;for(;(T=p.indexOf(`
|
|
31
|
+
`))!==-1;){let x=p.slice(0,T).trim();if(p=p.slice(T+1),!x||x.startsWith(":")||!x.startsWith("data: "))continue;let f=x.slice(6);if(f==="[DONE]")return;let _;try{_=JSON.parse(f)}catch{continue}for(let S of _.choices??[])S.text&&(yield{type:"delta",text:S.text}),S.finish_reason&&(yield{type:"done",finishReason:S.finish_reason})}}}finally{m.releaseLock()}}async uploadFile(e,t,o,r,s){let a=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/files`:`${this.baseUrl}/v1/files`,c=new FormData;c.append("file",e,t),c.append("purpose",o);let u=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${r}`,...this.extraHeaders},body:c,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 l=await u.json();return{fileId:l.id??"",filename:l.filename??t,bytes:l.bytes??0}}async getFileInfo(e,t,o){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:o??AbortSignal.timeout(this.timeoutMs)});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`File info error ${i.status}: ${c}`)}let a=await i.json();return{id:a.id??e,filename:a.filename??"",bytes:a.bytes??0,status:a.status??"unknown"}}};function Qt(n){let e=n.toLowerCase();return/^o[1-4](-|$)/.test(e)}function $d(n){switch(n){case"sensitive":return"content_filter";case"model_context_window_exceeded":return"length";case"network_error":return"error";default:return n}}function Dd(n,e){return n.map(t=>{if(t.role==="user"){let o=t.imageUrls&&t.imageUrls.length>0&&!e.filterImageBlocks,r=t.videoUrls&&t.videoUrls.length>0,s=t.audioUrls&&t.audioUrls.length>0,i=t.fileIds&&t.fileIds.length>0;if(o||r||s||i){let c=[];if(t.content&&c.push({type:"text",text:t.content}),o)for(let u of t.imageUrls){let l={url:u};t.imageDetail&&(l.detail=t.imageDetail),c.push({type:"image_url",image_url:l})}if(r)for(let u of t.videoUrls)c.push({type:"video_url",video_url:{url:u}});if(s)for(let u of t.audioUrls)c.push({type:"input_audio",input_audio:{data:u,format:t.audioFormat??"mp3"}});if(i)for(let u of t.fileIds)c.push({type:"file",file:{file_id:u.id}});return{role:"user",content:c}}return{role:"user",content:t.content??""}}if(t.role==="assistant"){let o={role:"assistant"};return t.thinkingBlocks&&t.thinkingBlocks.length>0&&(o.reasoning_content=t.thinkingBlocks.map(r=>r.thinking).join("")),o.content=t.content??null,t.tool_calls&&t.tool_calls.length>0&&(o.tool_calls=t.tool_calls.map(r=>({id:r.id,type:r.type,function:{name:r.function.name,arguments:r.function.arguments}}))),o}return t.role==="tool"?{role:"tool",content:t.content??"",tool_call_id:t.tool_call_id??""}:{role:t.role,content:t.content??""}})}var Ud=18e4,Nd=3e5,Fd=64e3,jd="[Tool execution failed; output not available during conversation recovery]",Bd="interleaved-thinking-2025-05-14",Wd="context-1m-2025-08-07",Hd="token-efficient-tools-2026-03-28",zd="prompt-caching-scope-2026-01-05";function Gd(n,e,t){let o=[],r=n.toLowerCase();(r.includes("opus-4-6")||r.includes("opus-4-7")||r.includes("sonnet-4-6"))&&o.push(Wd),e&&!r.includes("haiku")&&o.push(Bd),t&&o.push(Hd),o.push(zd);let i=process.env.ANTHROPIC_BETAS;if(i)for(let a of i.split(",").map(c=>c.trim()).filter(Boolean))o.includes(a)||o.push(a);return o}var Ct=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??Ud,this.streamIdleTimeoutMs=e.streamIdleTimeoutMs??tt,this.enablePromptCaching=e.enablePromptCaching??!0,this.maxRetries=e.maxRetries??3,this.omitZeroTemperature=e.omitZeroTemperature??!1,this.quirks=e.quirks??{}}async*stream(e,t,o){let r=`${this.baseUrl}/v1/messages`,s=Kd(e.messages),{system:i,messages:a}=Jd(s,this.quirks),c=qd(i,this.enablePromptCaching),u=!!e.reasoning,l=e.maxTokens??8192,d={model:e.model,messages:a,max_tokens:l,stream:!0};if(c&&(d.system=c),e.tools&&e.tools.length>0){let y=e.tools.map(Yd);this.enablePromptCaching&&y.length>0&&(y[y.length-1].cache_control={type:"ephemeral"}),d.tools=y,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 y=this.quirks.maxReasoningEffort??"high",T=e.reasoning?.effort??"high",x=T==="low"||T==="medium"?"high":y;if(d.output_config={effort:x},i){let f=2166136261;for(let _=0;_<i.length;_++)f^=i.charCodeAt(_),f=Math.imul(f,16777619);d.metadata={user_id:`qa-${(f>>>0).toString(36)}`}}}else{let y=Vd(e.reasoning.effort,e.maxTokens);d.thinking={type:"enabled",budget_tokens:Math.min(l-1,y)}}let p=Gd(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 h=null;for(let y=0;y<=this.maxRetries;y++){if(o?.aborted)throw new Error("Request aborted");y>0&&h&&await nt(ot(y),o);try{yield*this.streamWithWatchdog(r,m,d,o);return}catch(T){h=T instanceof Error?T:new Error(String(T));let x=Xd(h.message),f=x!==null&&Pn.has(x),_=h.message.includes("Stream idle timeout");if(h.message.includes("model_context_window_exceeded")||h.message.includes("context_length_exceeded")||!f&&!_)throw h;if(y===this.maxRetries){if((_||f)&&!e.streamRequired)try{yield*this.nonStreamingFallback(r,m,d,o);return}catch{throw h}throw h}}}if(h)throw h}async*streamWithWatchdog(e,t,o,r){let s=AbortSignal.timeout(this.timeoutMs),i=r?AbortSignal.any([r,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(o),signal:i});if(!a.ok){let p=await a.text().catch(()=>""),m=new Error(`Anthropic API error ${a.status}: ${p.slice(0,500)}`);throw m.status=a.status,m}if(!a.body)throw new Error("Anthropic API returned no response body");let c=null,u=!1,l=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{u=!0},this.streamIdleTimeoutMs)},d=()=>{c!==null&&(clearTimeout(c),c=null)};l();try{yield*this.parseSSEStream(a.body,l,()=>u)}finally{d()}if(u)throw new Error("Stream idle timeout - no chunks received")}async*nonStreamingFallback(e,t,o,r){let s=Qd({...o,stream:!1}),i=AbortSignal.timeout(Nd),a=r?AbortSignal.any([r,i]):i,c=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(s),signal:a});if(!c.ok){let l=await c.text().catch(()=>""),d=new Error(`Anthropic API error ${c.status}: ${l.slice(0,500)}`);throw d.status=c.status,d}let u=await c.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 o=e.content;if(Array.isArray(o)){let s=0;for(let i of o){let a=i.type;a==="text"?yield{type:"delta",text:i.text}:a==="thinking"?yield{type:"reasoning_delta",text:i.thinking}:a==="tool_use"&&(yield{type:"tool_call_delta",index:s++,id:i.id,name:i.name,arguments:JSON.stringify(i.input??{})})}}let r=e.stop_reason;r&&(yield{type:"done",finishReason:ii(r)})}async*parseSSEStream(e,t,o){let r=new TextDecoder,s="",i="",a=new Map,c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};for await(let u of e){if(t(),o())break;s+=r.decode(u,{stream:!0});let l;for(;(l=s.indexOf(`
|
|
32
|
+
`))!==-1;){let d=s.slice(0,l).trim();if(s=s.slice(l+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,c)}}}*mapEvent(e,t,o,r){switch(e){case"message_start":{let i=t.message?.usage;i&&(si(r,i),yield{type:"usage",promptTokens:r.inputTokens,completionTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens>0?r.cacheReadTokens:void 0,cacheCreationTokens:r.cacheCreationTokens>0?r.cacheCreationTokens:void 0});break}case"content_block_start":{let s=t.index,i=t.content_block;if(!i)break;let a=i.type;o.set(s,{type:a,id:i.id,name:i.name,signature:a==="thinking"?"":void 0}),a==="tool_use"&&(yield{type:"tool_call_delta",index:s,id:i.id,name:i.name,arguments:""});break}case"content_block_delta":{let s=t.index,i=t.delta;if(!i)break;let a=i.type;if(a==="text_delta")yield{type:"delta",text:i.text};else if(a==="input_json_delta")yield{type:"tool_call_delta",index:s,arguments:i.partial_json};else if(a==="thinking_delta")yield{type:"reasoning_delta",text:i.thinking};else if(a==="signature_delta"){let c=o.get(s);c&&typeof i.signature=="string"&&(c.signature=i.signature)}break}case"content_block_stop":{let s=t.index,i=o.get(s);i?.type==="thinking"&&typeof i.signature=="string"&&(yield{type:"reasoning_block_complete",thinking:"",signature:i.signature}),o.delete(s);break}case"message_delta":{let s=t.delta,i=t.usage;i&&(si(r,i),yield{type:"usage",promptTokens:r.inputTokens,completionTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens>0?r.cacheReadTokens:void 0,cacheCreationTokens:r.cacheCreationTokens>0?r.cacheCreationTokens:void 0}),s?.stop_reason&&(yield{type:"done",finishReason:ii(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 si(n,e){e.input_tokens>0&&(n.inputTokens=e.input_tokens),n.outputTokens=e.output_tokens??n.outputTokens,e.cache_read_input_tokens>0&&(n.cacheReadTokens=e.cache_read_input_tokens),e.cache_creation_input_tokens>0&&(n.cacheCreationTokens=e.cache_creation_input_tokens)}function ii(n){switch(n){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_calls";case"max_tokens":return"length";default:return n}}var An={high:16e3,medium:8e3,low:4e3};function Vd(n,e){if(e&&e>16384)switch(n){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 An.high}return An[n]??An.high}function qd(n,e){if(n)return e?[{type:"text",text:n,cache_control:{type:"ephemeral"}}]:n}function Kd(n){let e=[],t=new Set;for(let o=0;o<n.length;o++){let r=n[o];if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){let s=r.tool_calls.filter(l=>t.has(l.id)?!1:(t.add(l.id),!0)),i=new Set(s.map(l=>l.id)),a=new Set,c=n.slice(o+1);for(let l of c){if(l.role!=="tool")break;l.tool_call_id&&a.add(l.tool_call_id)}s.length!==r.tool_calls.length?e.push({...r,tool_calls:s}):e.push(r);let u=[...i].filter(l=>!a.has(l));for(let l of u){let d=s.find(p=>p.id===l);e.push({role:"tool",tool_call_id:l,name:d?.function.name,content:"[Tool execution failed; output not available during conversation recovery]"})}}else r.role==="tool"?t.has(r.tool_call_id??"")&&e.push(r):e.push(r)}return e}function Jd(n,e={}){let t,o=[];for(let r of n){if(r.role==="system"){t=t?`${t}
|
|
33
|
+
|
|
34
|
+
${r.content??""}`:r.content??"";continue}if(r.role==="user")if(r.imageUrls&&r.imageUrls.length>0&&!e.filterImageBlocks){let i=[];r.content&&i.push({type:"text",text:r.content});for(let a of r.imageUrls)if(a.startsWith("data:")){let c=/^data:(image\/\w+);base64,(.+)$/.exec(a);c&&i.push({type:"image",source:{type:"base64",media_type:c[1],data:c[2]}})}else i.push({type:"image",source:{type:"url",url:a}});o.push({role:"user",content:i})}else o.push({role:"user",content:r.content??""});else if(r.role==="assistant"){let s=e.filterThinkingBlocks?void 0:r.thinkingBlocks;if(r.tool_calls&&r.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});r.content&&i.push({type:"text",text:r.content});for(let a of r.tool_calls){let c;try{c=JSON.parse(a.function.arguments)}catch{c={}}i.push({type:"tool_use",id:a.id,name:a.function.name,input:c})}o.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});r.content&&i.push({type:"text",text:r.content}),o.push({role:"assistant",content:i})}else o.push({role:"assistant",content:r.content??""})}else if(r.role==="tool"){let s=r.content??"",i=s.startsWith("Error:")||s===jd,a={type:"tool_result",tool_use_id:r.tool_call_id??"",content:s,...i&&{is_error:!0}},c=o[o.length-1];c&&c.role==="user"&&Array.isArray(c.content)?c.content.push(a):o.push({role:"user",content:[a]})}}return{system:t,messages:o}}function Yd(n){return{name:n.function.name,description:n.function.description,input_schema:n.function.parameters??{type:"object",properties:{}}}}function Xd(n){let e=/Anthropic API error (\d{3})/.exec(n);return e?parseInt(e[1],10):null}function Qd(n){let e=typeof n.max_tokens=="number"?n.max_tokens:8192,t=Math.min(e,Fd),o={...n,max_tokens:t},r=o.thinking;return r?.type==="enabled"&&r.budget_tokens&&(o.thinking={...r,budget_tokens:Math.min(r.budget_tokens,t-1)}),o}var Zt=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,o){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 c=null;for(let u=0;u<=3;u++){if(o?.aborted)throw new Error("Request aborted");u>0&&c&&await nt(ot(u),o);try{yield*this.fetchAndStream(s,a,i,o);return}catch(l){c=l instanceof Error?l:new Error(String(l));let d=c.message.includes("Stream idle timeout");if(!Yt(Xt(c))&&!d||u===3)throw c}}}resolveConstraints(e){let t=e;if(t.caching&&t.caching.type==="enabled"){if(t.instructions)return t={...t,caching:void 0},t;if(t.structuredOutput&&t.structuredOutput.mode==="json_schema"&&(t={...t,structuredOutput:{mode:"json_object"}}),t.builtinTools&&t.builtinTools.length>0){let r=t.builtinTools.filter(s=>s.type!=="builtin_web_search"&&s.type!=="builtin_image_process");r.length!==t.builtinTools.length&&(t={...t,builtinTools:r.length>0?r:void 0})}}return t}buildRequestBody(e){let t=this.resolveConstraints(e),o={model:t.model,input:Zd(t.messages),stream:!0};if(t.previousResponseId&&(o.previous_response_id=t.previousResponseId),t.store!==void 0&&(o.store=t.store),t.storeExpireAt!==void 0&&(o.expire_at=t.storeExpireAt),t.instructions&&(o.instructions=t.instructions),t.structuredOutput)if(t.structuredOutput.mode==="json_object")o.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),o.text={format:s}}if(t.caching){let s={type:t.caching.type};t.caching.prefix!==void 0&&(s.prefix=t.caching.prefix),o.caching=s,t.caching.prefix&&(o.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});o.context_management={edits:s}}let r=[];if(t.tools&&t.tools.length>0)for(let s of t.tools)r.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),r.push(a)}if(r.length>0&&(o.tools=r),t.maxToolCalls!==void 0&&(o.max_tool_calls=t.maxToolCalls),t.toolChoice!==void 0&&(typeof t.toolChoice=="string"?o.tool_choice=t.toolChoice:o.tool_choice={type:t.toolChoice.type,name:t.toolChoice.name}),t.temperature!==void 0&&(o.temperature=t.temperature),t.topP!==void 0&&(o.top_p=t.topP),t.maxTokens!==void 0&&(o.max_output_tokens=t.maxTokens),t.reasoning){let s=t.reasoning.effort??"high";s==="minimal"?o.thinking={type:"disabled"}:(o.thinking={type:"enabled"},o.reasoning={effort:s}),t.reasoning.includeEncryptedReasoning&&(o.include=["reasoning.encrypted_content"])}return t.prefixMessage&&o.input.push({role:"assistant",content:t.prefixMessage,partial:!0}),o}async*fetchAndStream(e,t,o,r){let s=AbortSignal.timeout(this.timeoutMs),i=r?AbortSignal.any([r,s]):s,a=await fetch(e,{method:"POST",headers:t,body:JSON.stringify(o),signal:i});if(!a.ok){let u=await a.text().catch(()=>""),l=new Error(`Volcengine Responses API error ${a.status}: ${u.slice(0,500)}`);throw l.status=a.status,l}if(!a.body)throw new Error("Volcengine Responses API returned no response body");let c=a.headers.get("content-type")??"";if(c.includes("application/json")&&!c.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStream(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();if(t.id&&(yield{type:"response_id",id:t.id}),t.usage&&(yield{type:"usage",promptTokens:t.usage.input_tokens??0,completionTokens:t.usage.output_tokens??0,reasoningTokens:t.usage.output_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.input_tokens_details?.cached_tokens}),t.output)for(let o of t.output){if(o.type==="message"&&o.content)for(let r of o.content)r.type==="output_text"&&(yield{type:"delta",text:r.text??""});if(o.type==="reasoning"&&o.summary)for(let r of o.summary)r.type==="summary_text"&&(yield{type:"reasoning_delta",text:r.text??""});o.type==="function_call"&&(yield{type:"tool_call_delta",index:0,id:o.call_id,name:o.name,arguments:o.arguments??""})}yield{type:"done",finishReason:t.status==="completed"?"stop":t.status??"stop"}}async*parseSSEStream(e){let t=new TextDecoder,o="",r="",s=null,i=new AbortController,a=0,c=new Map,u=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},tt)};try{u();let l=e.getReader();try{for(;;){let{done:d,value:p}=await l.read();if(d)break;if(i.signal.aborted)throw new Error("Stream idle timeout");u(),o+=t.decode(p,{stream:!0});let m;for(;(m=o.indexOf(`
|
|
35
|
+
`))!==-1;){let h=o.slice(0,m).trim();if(o=o.slice(m+1),!h){r="";continue}if(!h.startsWith(":")){if(h.startsWith("event:")){r=h.slice(6).trim();continue}if(h.startsWith("data:")){let y=h.slice(5).trim();if(y==="[DONE]")return;let T;try{T=JSON.parse(y)}catch{continue}yield*this.processEvent(r,T,c,()=>a++)}}}}}finally{l.releaseLock()}}finally{s&&clearTimeout(s)}}*processEvent(e,t,o,r){switch(e){case"response.output_text.delta":{let s=t.delta;s&&(yield{type:"delta",text:s});break}case"response.reasoning_summary_text.delta":{let s=t.delta;s&&(yield{type:"reasoning_delta",text:s});break}case"response.function_call_arguments.delta":{let s=t.delta,i=t.call_id,a=t.name;if(s!==void 0&&i){let c=o.get(i);c===void 0&&(c=r(),o.set(i,c)),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:s}}break}case"response.output_item.added":{let s=t.item;if(s&&s.type==="function_call"){let i=s.call_id,a=s.name;if(i&&!o.has(i)){let c=r();o.set(i,c),yield{type:"tool_call_delta",index:c,id:i,name:a,arguments:""}}}break}case"response.function_call_arguments.done":break;case"response.output_item.done":{let s=t.item;if(s?.type==="message"){let i=s.content;if(i)for(let a of i){let c=a.annotations;c&&c.length>0&&(yield{type:"annotations",annotations:c.map(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,l=a.output_tokens_details;yield{type:"usage",promptTokens:a.input_tokens??0,completionTokens:a.output_tokens??0,reasoningTokens:l?.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 Zd(n){let e=[];for(let t of n){if(t.role==="system"){e.push({role:"system",content:t.content??""});continue}if(t.role==="user"){let o=t.imageUrls&&t.imageUrls.length>0,r=t.videoUrls&&t.videoUrls.length>0,s=t.audioUrls&&t.audioUrls.length>0,i=t.fileIds&&t.fileIds.length>0;if(o||r||s||i){let c=[];if(o)for(let u of t.imageUrls){let l={type:"input_image",image_url:u};t.imageDetail&&(l.detail=t.imageDetail),t.imagePixelLimit&&(l.image_pixel_limit=t.imagePixelLimit),c.push(l)}if(r)for(let u of t.videoUrls){let l={type:"input_video",video_url:u};t.videoFps!==void 0&&(l.fps=t.videoFps),c.push(l)}if(s)for(let u of t.audioUrls){let l={type:"input_audio",audio_url:u};t.audioFormat&&(l.format=t.audioFormat),c.push(l)}if(i)for(let u of t.fileIds)c.push({type:"input_file",file_id:u.id});t.content&&c.push({type:"input_text",text:t.content}),e.push({role:"user",content:c})}else e.push({role:"user",content:t.content??""});continue}if(t.role==="assistant"){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}function eo(n,e){n.baseUrl&&e.applyOverride(n.provider,{baseUrl:n.baseUrl});let t=e.getProvider(n.provider);if(!t)throw new Error(`Unknown LLM provider: "${n.provider}". Available: ${e.listProviders().map(s=>s.id).join(", ")}`);let o=n.baseUrl||t.baseUrl;return{transport:ep(t,o),apiKey:n.apiKey,resolvedModel:n.model,providerDef:t}}function to(n){for(let e of n.listProviders()){let t=n.resolveApiKey(e.id);if(t)return{providerId:e.id,apiKey:t,defaultModel:e.defaultModel??e.models?.[0]?.id??""}}}function ep(n,e){let t;switch(n.transport){case"openai-chat":t=new rt({baseUrl:e,extraHeaders:n.extraHeaders,supportsStreamOptions:n.supportsStreamOptions,omitZeroTemperature:n.omitZeroTemperature,quirks:n.quirks});break;case"anthropic-messages":t=new Ct({baseUrl:e,omitZeroTemperature:n.omitZeroTemperature,quirks:n.quirks});break;case"volcengine-responses":t=new Zt({baseUrl:e,extraHeaders:n.extraHeaders,quirks:n.quirks});break;default:throw new Error(`Unsupported transport type: "${n.transport}" for provider "${n.id}"`)}if(n.transport==="anthropic-messages"&&n.quirks?.supportsPrefixCompletion){let o=e.replace(/\/anthropic\/?$/,""),r=new rt({baseUrl:o,quirks:n.quirks});return new In(t,r)}return t}var In=class{constructor(e,t){this.primary=e;this.prefixTransport=t}primary;prefixTransport;async*stream(e,t,o){yield*(e.prefixMessage?this.prefixTransport:this.primary).stream(e,t,o)}async*complete(e,t,o){if(this.prefixTransport.complete)yield*this.prefixTransport.complete(e,t,o);else throw new Error("FIM completion is not supported by this transport")}};import{join as tp}from"node:path";import{mkdirSync as op,appendFileSync as np}from"node:fs";var ai=zs();function En(){return process.env.QLOGICAGENT_DEBUG==="1"}function On(n,e){let t=tp(ai,`${e}.jsonl`),o=!1;function r(){o||(op(ai,{recursive:!0}),o=!0)}function s(i){try{r(),np(t,JSON.stringify(i)+`
|
|
36
|
+
`,"utf8")}catch{}}return{async*stream(i,a,c){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 l=0,d=0,p=0,m="",h;try{for await(let y of n.stream(i,a,c))y.type==="usage"?(l=y.promptTokens,d=y.completionTokens,p=y.reasoningTokens??0):y.type==="done"&&(m=y.finishReason),yield y}catch(y){throw h=y instanceof Error?y.message:String(y),y}finally{let y=Date.now()-u;s({type:"response",timestamp:new Date().toISOString(),model:i.model,elapsedMs:y,promptTokens:l,completionTokens:d,reasoningTokens:p,finishReason:m,...h?{error:h}:{}})}}}}function Ln(n){let e=new Map;return{register(t){let o=e.get(t.point)??[],r={handler:t.handler,priority:t.priority??100,label:t.label};return o.push(r),o.sort((s,i)=>s.priority-i.priority),e.set(t.point,o),()=>{let s=o.indexOf(r);s>=0&&o.splice(s,1)}},async invoke(t,o){let r=e.get(t);if(!r||r.length===0)return{action:"continue",context:o};let s=o;for(let i of r)try{let a=await i.handler(t,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return n.info({hook:t,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){n.warn({hook:t,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}var oo={MAX_SESSION_BYTES:61440,LIMIT_PER_RECALL:10,MAX_SURFACED_ENTRIES:100};function St(){return{surfacedPaths:new Set,sessionBytes:0}}function li(n,e,t){let o=[],r=t??St(),s,i=[];return o.push(n.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,c)=>{if(!e.memoryProvider||!c.query)return{action:"continue",context:c};if(r.sessionBytes>=oo.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:c};try{let u=await e.memoryProvider.search(c.query,e.userId,{limit:oo.LIMIT_PER_RECALL}),l=u.filter(p=>{let m=p,h=m.path??m.id??"";if(!h)return!0;if(r.surfacedPaths.has(h))return!1;let y=(m.content?.length??0)*2;if(r.sessionBytes+y>oo.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(h),r.sessionBytes+=y,r.surfacedPaths.size>oo.MAX_SURFACED_ENTRIES){let T=r.surfacedPaths.values().next().value;T!==void 0&&r.surfacedPaths.delete(T)}return!0});s=c.turnId,i=l,e.log.debug(`memory.before_recall: prefetched ${u.length} \u2192 ${l.length} after dedup (${r.sessionBytes} bytes used)`);let d=l.map(p=>{let m=p;return{text:m.text??m.content??"",score:m.score}}).filter(p=>p.text);return{action:"continue",context:{...c,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:c}}})),o.push(n.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,c)=>{let u=s===c.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${c.blockCount??0} blocks assembled, ${u} qmemory results (session: ${r.sessionBytes} bytes)`),{action:"continue",context:c}}})),()=>{for(let a of o)a();i=[]}}import{ClawQMemoryAdapter as rp}from"qlogicagent-adapter-claw";var ci="qmemory";function ui(n){let e=new rp({baseUrl:n.baseUrl,apiKey:n.apiKey,timeout:n.timeoutMs??5e3});function t(o){return n.userIdPrefix?`${n.userIdPrefix}:${o}`:o}return{providerId:ci,async search(o,r,s){return((await e.dispatch("memory.search",{q:o,user_id:t(r),limit:s?.limit??10})).memories??[]).filter(a=>a.id&&a.text).map(a=>({blockId:a.id,text:a.text,score:typeof a.importance=="number"?a.importance:0,source:ci,metadata:a.metadata}))},async ingest(o,r,s){await e.dispatch("memory.addKnowledge",{user_id:t(r),messages:o.map(i=>({role:i.role,content:i.content,...i.timestamp?{timestamp:i.timestamp}:{}})),extraction_mode:"none",run_async:!0,...s?.sessionId?{session_id:s.sessionId}:{},...s?.source?{metadata:{source:s.source}}:{}})},async health(){let o=await e.dispatch("memory.health",{});return{status:o.status??"unknown",version:o.version??"",memoryCount:o.memory_count??0,dbSizeBytes:o.db_size_bytes??0,embeddingModel:o.embedding_model??"",uptimeSeconds:o.uptime_seconds??0}},async addText(o,r,s){return{memoriesAdded:(await e.dispatch("memory.addFact",{user_id:t(r),text:o,extraction_mode:"none",...s?.sessionId?{metadata:{session_id:s.sessionId,...s.source?{source:s.source}:{}}}:{}})).memories_added??0}},async ingestExtracted(o,r,s){if(o.length===0)return{memoriesAdded:0};let i=t(r),a=await Promise.allSettled(o.map(u=>e.dispatch("memory.addFact",{user_id:i,text:u.text,extraction_mode:"none",...s?.sessionId?{session_id:s.sessionId}:{},metadata:{...s?.source?{source:s.source}:{},...u.category?{category:u.category}:{},...typeof u.importance=="number"?{importance:u.importance}:{},...u.speaker?{speaker:u.speaker}:{},...u.event_date?{event_date:u.event_date}:{},...u.tags?.length?{tags:u.tags}:{}}}))),c=0;for(let u of a)u.status==="fulfilled"&&(c+=u.value.memories_added??1);return{memoriesAdded:c}},async remove(o){try{return await e.dispatch("memory.forget",{id:o}),!0}catch{return!1}},async feedback(o,r,s){await e.dispatch("memory.feedback",{memory_ids:o,signal:r,...s?{session_id:s}:{}})}}}import{readFile as hi,writeFile as Dn,stat as wi,unlink as up,mkdir as dp}from"node:fs/promises";import{join as ro,resolve as yi,isAbsolute as bi,normalize as Ti}from"node:path";import{randomUUID as pp}from"node:crypto";function di(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function sp(n){return n.latestInputTokens+n.cumulativeOutputTokens}var ip=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),pi=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function ap(n){return{isSearch:ip.has(n)||void 0,isRead:pi.has(n)||void 0}}function lp(n,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${pi.has(n)?"Reading":n.includes("write")||n.includes("edit")?"Editing":"Using"} ${t}`;let o=e.command??e.cmd;if(typeof o=="string")return`Running: ${o.length>60?o.slice(0,60)+"\u2026":o}`;let r=e.query??e.pattern??e.search;if(typeof r=="string")return`Searching: ${r}`}function mi(n,e){n.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),n.cumulativeOutputTokens+=e.output_tokens??0}function gi(n,e,t,o){n.toolUseCount++;let r=ap(e),s={toolName:e,input:t,activityDescription:o?.(e,t)??lp(e,t),isSearch:r.isSearch,isRead:r.isRead};for(n.recentActivities.push(s);n.recentActivities.length>5;)n.recentActivities.shift()}function $n(n){return{toolUseCount:n.toolUseCount,tokenCount:sp(n),lastActivity:n.recentActivities.length>0?n.recentActivities[n.recentActivities.length-1]:void 0,recentActivities:[...n.recentActivities]}}import{randomUUID as fi}from"node:crypto";function cp(n){let e=new AbortController;return n&&(n.aborted?e.abort(n.reason):n.addEventListener("abort",()=>{e.abort(n.reason)},{once:!0})),e}async function no(n){let e=Date.now(),t=[],o={prompt:0,completion:0},r=di(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:c,transport:u,toolInvoker:l,apiKey:d,model:p,log:m,hooks:h,forkLabel:y,maxTurns:T,temperature:x,parentSignal:f,onEvent:_,onProgress:S,budgetTokens:O,parentDepth:K}=n,D=cp(f),F=`fork-${y}-${fi().slice(0,8)}`,k=`fork-session-${fi().slice(0,8)}`;m.info(`[fork:${y}] starting \u2014 ${s.length} initial messages, model=${p}`);let j=c?{invoke:async(oe,$,I,ue)=>{let se={};try{se=JSON.parse(I)}catch{}let de=c($,se);return de.allowed?l.invoke(oe,$,I,ue):(m.info(`[fork:${y}] tool ${$} denied: ${de.reason}`),{result:"",error:de.reason})}}:l,J=!0,Q;try{let{Agent:oe}=await Promise.resolve().then(()=>(Vt(),Bs)),$=new oe({llmTransport:u,apiKey:d,toolInvoker:j,log:m,hooks:h,maxRounds:T});for await(let I of $.run({turnId:F,sessionId:k,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:d,temperature:x,maxOutputTokens:n.maxOutputTokens,parentDepth:K}},D.signal)){if(t.push(I),_?.(I),I.type==="end"&&I.usage&&(mi(r,{input_tokens:I.usage.prompt,output_tokens:I.usage.completion}),o.prompt+=I.usage.prompt,o.completion+=I.usage.completion,I.usage.cacheRead&&(o.cacheRead=(o.cacheRead??0)+I.usage.cacheRead),I.usage.cacheCreation&&(o.cacheCreation=(o.cacheCreation??0)+I.usage.cacheCreation),O&&O>0)){let ue=o.prompt+o.completion+(o.reasoning??0);ue>=O&&(m.info(`[fork:${y}] budget exceeded (${ue} / ${O} tokens), aborting`),D.abort("budget_exceeded"))}if(I.type==="tool_call"){let ue={};try{ue=JSON.parse(I.arguments??"{}")}catch{}gi(r,I.name,ue),S?.($n(r))}I.type==="error"&&(J=!1,Q=I.error)}}catch(oe){J=!1,Q=oe instanceof Error?oe.message:String(oe),m.warn(`[fork:${y}] error: ${Q}`)}finally{D.signal.aborted||D.abort("fork_complete")}let Se=Date.now()-e;return m.info(`[fork:${y}] finished in ${Se}ms \u2014 ${t.length} events, usage: prompt=${o.prompt} completion=${o.completion}, ok=${J}`),{events:t,totalUsage:o,progress:$n(r),durationMs:Se,ok:J,error:Q}}var _i={minHours:24,minSessions:5,scanIntervalMs:6e5},so=".consolidate-lock",mp=3600*1e3,ki="CLAUDE.md",gp=100,fp=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"]),hp=new Set(["log","show","diff","status","branch","tag","remote","rev-parse","rev-list","ls-files","ls-tree","describe","blame","shortlog","name-rev","cat-file"]),yp=/[|>&]|>>|>\s|rm\s|mv\s|cp\s|chmod\s|chown\s|mkdir\s|touch\s/;function bp(n){let e=n.trim();if(!e||yp.test(e))return!1;let t=e.split(/\s+/),o=t[0]?.replace(/^(\/usr\/bin\/|\/bin\/|\/usr\/local\/bin\/)/,"")??"";if(!fp.has(o))return!1;if(o==="git"){let r=t[1];if(!r||!hp.has(r))return!1}return!0}function Tp(n,e){let{toolName:t,input:o}=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=o.command??o.cmd??"";return bp(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=o.file_path??o.path??"";return typeof i=="string"&&Ci(i,n)?{allowed:!0}:{allowed:!1,reason:`File writes are only allowed within the memory directory: ${n}`}}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 Ci(n,e){let t=bi(n)?n:yi(n),o=bi(e)?e:yi(e),r=Ti(t),s=Ti(o);return r.startsWith(s)}function Si(n,e,t,o){let r=o?.hasQMemory?`
|
|
34
37
|
|
|
35
38
|
## Phase 2.5 \u2014 Long-term memory triage (QMemory)
|
|
36
39
|
|
|
@@ -55,7 +58,7 @@ Examples of project memories: architecture decisions, file conventions, build pa
|
|
|
55
58
|
|
|
56
59
|
You are performing a dream \u2014 a reflective pass over your memory files. Synthesize what you've learned recently into durable, well-organized memories so that future sessions can orient quickly.
|
|
57
60
|
|
|
58
|
-
Memory directory: \`${
|
|
61
|
+
Memory directory: \`${n}\`
|
|
59
62
|
If the directory doesn't exist yet, create it with the necessary structure.
|
|
60
63
|
|
|
61
64
|
Session transcripts: \`${e}\` (large JSONL files \u2014 grep narrowly, don't read whole files)
|
|
@@ -65,7 +68,7 @@ Session transcripts: \`${e}\` (large JSONL files \u2014 grep narrowly, don't rea
|
|
|
65
68
|
## Phase 1 \u2014 Orient
|
|
66
69
|
|
|
67
70
|
- \`ls\` the memory directory to see what already exists
|
|
68
|
-
- Read \`${
|
|
71
|
+
- Read \`${ki}\` to understand the current index
|
|
69
72
|
- Skim existing topic files so you improve them rather than creating duplicates
|
|
70
73
|
- If \`logs/\` or \`sessions/\` subdirectories exist, review recent entries there
|
|
71
74
|
|
|
@@ -91,7 +94,7 @@ Focus on:
|
|
|
91
94
|
|
|
92
95
|
## Phase 4 \u2014 Prune and index
|
|
93
96
|
|
|
94
|
-
Update \`${
|
|
97
|
+
Update \`${ki}\` so it stays under ${gp} lines AND under ~25KB. It's an **index**, not a dump \u2014 each entry should be one line under ~150 characters: \`- [Title](file.md) \u2014 one-line hook\`. Never write memory content directly into it.
|
|
95
98
|
|
|
96
99
|
- Remove pointers to memories that are now stale, wrong, or superseded
|
|
97
100
|
- 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
|
|
@@ -106,147 +109,153 @@ Sessions since last consolidation (${t.length}):
|
|
|
106
109
|
${t.map(s=>`- ${s}`).join(`
|
|
107
110
|
`)}
|
|
108
111
|
|
|
109
|
-
Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var
|
|
110
|
-
`;await
|
|
111
|
-
`).filter(Boolean).map(
|
|
112
|
-
`),i=
|
|
112
|
+
Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so.`}var xi=0;async function kp(n,e={}){let t={..._i,...e},o;try{o=await Ri(n.memoryRoot)}catch{o=0}let r=(Date.now()-o)/36e5;if(!t.force&&r<t.minHours)return null;let s=Date.now()-xi;if(!t.force&&s<t.scanIntervalMs)return null;xi=Date.now();let i;try{i=await n.listSessionsSince(o)}catch{return null}return i=i.filter(a=>a!==n.currentSessionId),!t.force&&i.length<t.minSessions?null:{sessionIds:i}}async function Ri(n){let e=ro(n,so);return(await wi(e)).mtimeMs}function xp(n){try{return process.kill(n,0),!0}catch{return!1}}async function vp(n){let e=ro(n,so),t,o;try{let[s,i]=await Promise.all([wi(e),hi(e,"utf8")]);t=s.mtimeMs;let a=parseInt(i.trim(),10);o=Number.isFinite(a)?a:void 0}catch{}if(t!==void 0&&Date.now()-t<mp&&o!==void 0&&xp(o))return null;await dp(n,{recursive:!0}),await Dn(e,String(process.pid));let r;try{r=await hi(e,"utf8")}catch{return null}return parseInt(r.trim(),10)!==process.pid?null:t??0}async function vi(n,e){let t=ro(n,so);try{if(e===0){await up(t);return}await Dn(t,"");let{utimes:o}=await import("node:fs/promises"),r=e/1e3;await o(t,r,r)}catch{}}async function wp(n){let e=ro(n,so);await Dn(e,String(process.pid))}function _p(n){return{taskId:`dream-${pp().slice(0,8)}`,type:"dream",label:"Memory consolidation",permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:1,maxTurns:0,tokenBudget:0,startedAt:Date.now(),parentTaskId:n.parentTaskId,sessionId:n.sessionId,phase:"starting",sessionsReviewing:n.sessionsReviewing,filesTouched:[],turns:[],priorLockMtime:n.priorLockMtime}}async function Cp(n,e={}){let t={..._i,...e},o=await kp(n,t);if(!o)return null;let r;if(t.force)try{r=await Ri(n.memoryRoot)}catch{r=0}else if(r=await vp(n.memoryRoot),r===null)return null;let s=Si(n.memoryRoot,n.transcriptDir,o.sessionIds),i=_p({sessionId:n.currentSessionId,sessionsReviewing:o.sessionIds.length,priorLockMtime:r});return{prompt:s,taskState:i,sessionIds:o.sessionIds}}async function Mi(n){let e=Date.now(),t=await Cp(n.context,n.triggerConfig);if(!t)return{ok:!0,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e};let{taskState:o,sessionIds:r}=t,s=!!(n.qmemoryAdapter&&n.qmemoryUserId),i=s?Si(n.context.memoryRoot,n.context.transcriptDir,r,{hasQMemory:!0}):t.prompt;n.log.info(`[dream] starting consolidation \u2014 ${r.length} sessions, memoryRoot=${n.context.memoryRoot}`+(s?", qmemory=enabled":"")),n.hooks?.invoke("subagent.started",{sessionId:n.context.currentSessionId,turnId:o.taskId,subagentId:o.taskId,agentType:"dream"}).catch(()=>{});let a=(d,p)=>Tp(n.context.memoryRoot,{toolName:d,input:p}),c=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,h)=>{let y=n.qmemoryAdapter,T=n.qmemoryUserId;if(p==="qmemory_search"){let{query:x,limit:f}=JSON.parse(m),_=await y.search(x,T,{limit:f??10});return{result:JSON.stringify(_)}}if(p==="qmemory_store"){if(!y.addText)return{result:"",error:"addText not supported"};let{text:x,source:f}=JSON.parse(m),_=await y.addText(x,T,{sessionId:n.context.currentSessionId,source:f??"dream-consolidation"});return{result:JSON.stringify(_)}}if(p==="qmemory_feedback"){let{memoryIds:x,signal:f}=JSON.parse(m);return y.feedback&&await y.feedback(x,f,n.context.currentSessionId),{result:"Feedback recorded successfully."}}return n.toolInvoker.invoke(d,p,m,h)}}:n.toolInvoker,l=[...n.tools,...c];try{let d=await no({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:i,tools:l,canUseTool:a,transport:n.transport,toolInvoker:u,apiKey:n.apiKey,model:n.model,log:n.log,hooks:n.hooks,forkLabel:"dream-consolidation",parentSignal:n.parentSignal,skipTranscript:!0}),p=[];for(let m of d.events)if(m.type==="tool_call")try{let h=JSON.parse(m.arguments),y=h.file_path??h.path??h.filePath;y&&Ci(y,n.context.memoryRoot)&&p.push(y)}catch{}return d.ok?(await wp(n.context.memoryRoot),n.log.info(`[dream] consolidation complete \u2014 ${p.length} files touched, ${d.durationMs}ms`)):(await vi(n.context.memoryRoot,o.priorLockMtime),n.log.warn(`[dream] consolidation failed: ${d.error}`)),n.hooks?.invoke("subagent.stopped",{sessionId:n.context.currentSessionId,turnId:o.taskId,subagentId:o.taskId,agentType:"dream",reason:d.ok?"normal":"error",error:d.error}).catch(()=>{}),{ok:d.ok,sessionsReviewed:r.length,filesTouched:[...new Set(p)],turns:[],durationMs:Date.now()-e,error:d.error}}catch(d){await vi(n.context.memoryRoot,o.priorLockMtime).catch(()=>{});let p=d instanceof Error?d.message:String(d);return n.log.warn(`[dream] consolidation error: ${p}`),n.hooks?.invoke("subagent.stopped",{sessionId:n.context.currentSessionId,turnId:o.taskId,subagentId:o.taskId,agentType:"dream",reason:"error",error:p}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:p}}}var Rt=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_tokensSinceLastExtraction=0;_toolCallsSinceLastExtraction=0;_hasExtractedOnce=!1;_listeners=new Set;extractionThresholds;constructor(e,t){this.sessionId=e,this.extractionThresholds={initialTokenThreshold:t?.initialTokenThreshold??1e4,updateTokenThreshold:t?.updateTokenThreshold??5e3,toolCallThreshold:t?.toolCallThreshold??3}}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}get turnCount(){return this._turnCount}get toolCallCount(){return this._toolCallCount}getModelUsage(e){return this._modelUsage.get(e)}getAllModelUsage(){let e={};for(let[t,o]of this._modelUsage)e[t]={...o};return e}addUsage(e,t){this._totalInputTokens+=e.prompt,this._totalOutputTokens+=e.completion;let o=this._modelUsage.get(t);o?(o.inputTokens+=e.prompt,o.outputTokens+=e.completion,o.cacheRead+=e.cacheRead??0,o.cacheCreation+=e.cacheCreation??0):this._modelUsage.set(t,{inputTokens:e.prompt,outputTokens:e.completion,cacheRead:e.cacheRead??0,cacheCreation:e.cacheCreation??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this._tokensSinceLastExtraction+=e.prompt+e.completion,this.notifyListeners()}addMediaUsage(e,t,o){let r=this._modelUsage.get(e),s=r??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(r||this._modelUsage.set(e,s),s.mediaCalls+=1,t){case"per_second":s.mediaDurationSeconds+=o;break;case"per_character":s.mediaCharacters+=o;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++,this._toolCallsSinceLastExtraction++}recordTurnCompleted(){this._turnCount++}shouldExtractMemory(){let e=this._hasExtractedOnce?this.extractionThresholds.updateTokenThreshold:this.extractionThresholds.initialTokenThreshold,t=this._tokensSinceLastExtraction>=e,o=this._toolCallsSinceLastExtraction>=this.extractionThresholds.toolCallThreshold;return t&&o}markExtractionDone(){this._tokensSinceLastExtraction=0,this._toolCallsSinceLastExtraction=0,this._hasExtractedOnce=!0}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[t,o]of Object.entries(e.modelUsage))this._modelUsage.set(t,{...o});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as me from"node:fs";import*as _e from"node:path";var Pi="transcript.jsonl",Mt="state.json",Sp=50,Rp=50,Mp=30;function Ai(){return Sn()}function io(n){let e=n.replace(/[^a-zA-Z0-9_-]/g,"_");return _e.join(Ai(),e)}async function Un(n,e){let t=io(n);await me.promises.mkdir(t,{recursive:!0});let o=JSON.stringify({role:e.role,content:e.content,ts:Date.now()})+`
|
|
113
|
+
`;await me.promises.appendFile(_e.join(t,Pi),o,"utf8")}async function Ii(n,e,t){let o=io(n);await me.promises.mkdir(o,{recursive:!0});let r={metadata:{sessionId:n,createdAt:t.createdAt??Date.now(),lastActiveAt:Date.now(),model:t.model,cwd:t.cwd,turnCount:e.turnCount,messageCount:t.messageCount??0,title:t.title},costSnapshot:e},s=_e.join(o,Mt+".tmp");await me.promises.writeFile(s,JSON.stringify(r,null,2),"utf8"),await me.promises.rename(s,_e.join(o,Mt))}async function Ei(n){let e=io(n),t=_e.join(e,Pi),o=_e.join(e,Mt),r=[];try{r=(await me.promises.readFile(t,"utf8")).split(`
|
|
114
|
+
`).filter(Boolean).map(u=>{let l=JSON.parse(u);return{role:l.role,content:l.content??null}})}catch{return null}let s={sessionId:n,createdAt:Date.now(),lastActiveAt:Date.now(),turnCount:0,messageCount:r.length},i;try{let c=await me.promises.readFile(o,"utf8"),u=JSON.parse(c);s=u.metadata,i=u.costSnapshot}catch{}let a=r.filter(c=>c.role!=="system");return{metadata:s,messages:a,costSnapshot:i}}async function Oi(n=Sp){let e=Ai(),t;try{t=await me.promises.readdir(e)}catch{return[]}let o=[];for(let r of t){let s=_e.join(e,r,Mt);try{let i=await me.promises.readFile(s,"utf8"),a=JSON.parse(i);o.push({sessionId:a.metadata.sessionId,title:a.metadata.title,lastActiveAt:a.metadata.lastActiveAt,messageCount:a.metadata.messageCount,model:a.metadata.model})}catch{}}return o.sort((r,s)=>s.lastActiveAt-r.lastActiveAt),o.slice(0,n)}function Pp(n){return n.turnCount<Rp?!1:n.taskSummaryGeneratedAt?n.turnCount-(n.taskSummaryGeneratedAt??0)>=Mp:!0}async function Li(n,e,t,o){if(!Pp(e))return null;try{let s=t.slice(-20).map(l=>`[${l.role}]: ${typeof l.content=="string"?l.content.slice(0,500):JSON.stringify(l.content).slice(0,500)}`).join(`
|
|
115
|
+
`),i=o.transport.stream({model:o.model,messages:[{role:"system",content:"Generate a concise task summary (~100 words) of what the user is working on in this session. Focus on the goal, key decisions, and current progress. Reply with ONLY the summary."},{role:"user",content:s}],tools:[],maxTokens:200},o.apiKey),a="";for await(let l of i)l.type==="delta"&&(a+=l.text);if(a=a.trim(),!a)return null;let c=io(n),u=_e.join(c,Mt);try{let l=await me.promises.readFile(u,"utf8"),d=JSON.parse(l);d.metadata.taskSummary=a,d.metadata.taskSummaryGeneratedAt=e.turnCount;let p=u+".tmp";await me.promises.writeFile(p,JSON.stringify(d,null,2),"utf8"),await me.promises.rename(p,u)}catch{}return a}catch{return null}}Cn();import{randomUUID as _k}from"node:crypto";var Ap=3e4;var lo=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 o of this.listeners)try{o(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 o=this.tasks.get(e);if(!o)return;let r=t(o);r!==o&&(this.tasks.set(e,r),this.notify(e,r),!ao(o.lifecycle)&&ao(r.lifecycle)&&this.hooks?.invoke("task.completed",{sessionId:this.sessionId,taskId:r.taskId,taskType:r.type,label:r.label}).catch(()=>{}))}getTask(e){return this.tasks.get(e)}getRunningTasks(){return[...this.tasks.values()].filter(e=>e.lifecycle==="running")}getAllTasks(){return[...this.tasks.values()]}evictTask(e){let t=this.tasks.get(e);t&&ao(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=Ap){let t=Date.now();for(let[o,r]of this.tasks)ao(r.lifecycle)&&r.endedAt&&t-r.endedAt>e&&(this.tasks.delete(o),this.notify(o,null))}};function ao(n){return n==="completed"||n==="failed"||n==="cancelled"||n==="timeout"}import{watch as Ip}from"node:fs";import{stat as Ep}from"node:fs/promises";import{join as $i,relative as Op,resolve as Lp}from"node:path";var $p=[`${Te}/settings.json`,"INSTRUCTIONS.md",`${Te}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${Te}/rules`],Dp=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${Te}/rules`],Nn=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 $p){let t=$i(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 o=Ip(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(r,s)=>{let i=s?$i(e,s):e;this.handleChange(i,r==="rename"?"created":"modified")});o.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,o)}catch{}}handleChange(e,t){let o=this.debounceTimers.get(e);o&&clearTimeout(o),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let r=t;try{await Ep(e)}catch{r="deleted"}let s=Op(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${r} ${s}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:r}).catch(()=>{}),Dp.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=Lp(e);if(t===this._cwd)return;let o=this._cwd;this._cwd=t,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:o,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 Di(n){let e=new Nn(n);return await e.start(),e}import{readFile as Up,readdir as Np,stat as Fp}from"node:fs/promises";import{dirname as co,extname as jp,isAbsolute as Bp,join as Ge,parse as Ni,resolve as Ui}from"node:path";import{homedir as Wp}from"node:os";var Hp=5;var zp="INSTRUCTIONS.md",Gp="INSTRUCTIONS.local.md",Vp="INSTRUCTIONS.md",qp=[".instructions.md"],Kp=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 Jp(n){try{return await Up(n,"utf-8")}catch{return null}}function Yp(n){return n.includes("<!--")?n.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):n}function Xp(n){let e=n.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:n};let t=e[1],o=n.slice(e[0].length),r=t.match(/^paths:\s*(.+)$/m);if(!r)return{content:o};let s=[],i=r[1].trim();if(i.startsWith("["))try{s=JSON.parse(i)}catch{}else s=i.split(",").map(c=>c.trim()).filter(Boolean);let a=s.map(c=>c.endsWith("/**")?c.slice(0,-3):c).filter(c=>c.length>0&&c!=="**");return{content:o,globs:a.length>0?a:void 0}}function Qp(n,e){let t=new Set,o=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=n.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=o.exec(s))!==null;){let a=i[1];if(!a)continue;let c=a.indexOf("#");if(c!==-1&&(a=a.substring(0,c)),!a)continue;a=a.replace(/\\ /g," ");let u;if(a.startsWith("~/"))u=Ge(Wp(),a.slice(2));else if(Bp(a))u=a;else if(a.startsWith("./"))u=Ui(co(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))u=Ui(co(e),a);else continue;t.add(u)}return[...t]}async function ze(n,e,t,o=0,r){let s=n.toLowerCase();if(t.has(s)||o>=Hp)return[];let i=jp(n).toLowerCase();if(i&&!Kp.has(i))return[];t.add(s);let a=await Jp(n);if(!a?.trim())return[];let{content:c,globs:u}=Xp(a),l=Yp(c);if(!l.trim())return[];let d=[],p={path:n,type:e,content:l.trim()};r&&(p.parent=r),u&&(p.globs=u),d.push(p);let m=Qp(c,n);for(let h of m){let y=await ze(h,e,t,o+1,n);d.push(...y)}return d}async function Fn(n,e,t,o,r=new Set){if(r.has(n))return[];r.add(n);let s=[];try{let i=await Np(n,{withFileTypes:!0});for(let a of i){let c=Ge(n,a.name);if(a.isDirectory())s.push(...await Fn(c,e,t,o,r));else if(a.isFile()&&a.name.endsWith(".md")){let u=await ze(c,e,t);s.push(...u.filter(l=>o?!!l.globs:!l.globs))}}}catch{}return s}async function Zp(n){let e=n,t=Ni(e).root;for(;e!==t;){try{let o=Ge(e,".git"),r=await Fp(o);if(r.isDirectory()||r.isFile())return e}catch{}e=co(e)}return null}async function em(n,e){let t=[],o=new Set,r=G(),s=Ge(r,Vp);t.push(...await ze(s,"User",o));let i=Ys();t.push(...await Fn(i,"User",o,!1));let c=await Zp(n)??Ni(n).root,u=[],l=n;for(;u.push(l),!(l===c&&l!==n);){let d=co(l);if(d===l)break;l=d}for(let d of u.reverse()){t.push(...await ze(Ge(d,zp),"Project",o));for(let p of qp)t.push(...await ze(Ge(d,p),"Project",o));t.push(...await ze(Qs(d),"Project",o)),t.push(...await Fn(Zs(d),"Project",o,!1)),t.push(...await ze(Ge(d,Gp),"Local",o))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:n,fileCount:t.length}).catch(()=>{}),t}function Fi(n){if(n.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 o of n){if(!o.content)continue;let r=o.type==="Project"?" (project instructions, checked into the codebase)":o.type==="Local"?" (user's private project instructions, not checked in)":" (user's private global instructions for all projects)";t.push(`Contents of ${o.path}${r}:
|
|
113
116
|
|
|
114
|
-
${
|
|
117
|
+
${o.content.trim()}`)}return t.length>0?`${e}
|
|
115
118
|
|
|
116
119
|
${t.join(`
|
|
117
120
|
|
|
118
|
-
`)}`:""}var
|
|
121
|
+
`)}`:""}var Pt=null,jn=null;async function ji(n,e){return Pt&&jn===n||(Pt=await em(n,e),jn=n),Pt}function Bi(){Pt=null,jn=null}function Wi(n,e){return{name:n,compute:e,cacheBreak:!1}}var uo=new Map;async function tm(n){return(await Promise.all(n.map(async t=>{if(!t.cacheBreak&&uo.has(t.name))return uo.get(t.name)??null;let o=await t.compute();return uo.set(t.name,o),o}))).filter(t=>t!=null)}function Hi(){uo.clear()}async function zi(n){let e=[];if(n.instructionBlock&&e.push(n.instructionBlock),n.customSystemPrompt?e.push(n.customSystemPrompt):n.basePrompt&&e.push(n.basePrompt),n.sections?.length){let t=await tm(n.sections);e.push(...t)}return n.appendSystemPrompt&&e.push(n.appendSystemPrompt),e.filter(Boolean).join(`
|
|
119
122
|
|
|
120
|
-
`)}import{release as
|
|
121
|
-
`)})}import*as
|
|
122
|
-
`)}},required:["thought"]};function
|
|
123
|
-
`),parameters:fp,execute:async(o,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function Ke(o){let e=new Set(o.filter(t=>t.status==="completed").map(t=>t.id));return{total:o.length,completed:o.filter(t=>t.status==="completed").length,inProgress:o.filter(t=>t.status==="in-progress").length,notStarted:o.filter(t=>t.status==="not-started").length,blocked:o.filter(t=>t.status!=="completed"&&t.blockedBy?.some(n=>!e.has(n))).length}}var hp="todo",yp=["create","update","delete","list"],bp={type:"object",properties:{action:{type:"string",enum:[...yp],description:"create \u2014 add a single new task (auto-assigns id). update \u2014 modify a single task by id (partial). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list."},id:{type:"number",description:"[update|delete] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task."}},required:["action"]};function Pi(o){let e=[],t=0,n=o??{};function r(){let d=e.reduce((m,y)=>Math.max(m,y.id),0);return t=Math.max(t,d)+1,t}function s(d){return{content:[{type:"text",text:JSON.stringify({error:d,todoList:e})}],details:{type:"todo",error:d}}}function i(d){let m=Ke(e),y=new Set(e.filter(w=>w.status==="completed").map(w=>w.id)),h=e.map(w=>{let f=w.blockedBy?.filter(C=>!y.has(C));return{...w,...f?.length?{blockedBy:f}:{blockedBy:void 0}}}),k={...m,todoList:h,...d};return{content:[{type:"text",text:JSON.stringify(k)}],details:{type:"todo",...m,agentId:n.agentId}}}function a(d,m,y){let h=e.find(k=>k.id===d);if(h){if(m?.length){h.blocks=[...new Set([...h.blocks??[],...m])];for(let k of m){let w=e.find(f=>f.id===k);w&&(w.blockedBy=[...new Set([...w.blockedBy??[],d])])}}if(y?.length){h.blockedBy=[...new Set([...h.blockedBy??[],...y])];for(let k of y){let w=e.find(f=>f.id===k);w&&(w.blocks=[...new Set([...w.blocks??[],d])])}}}}function l(d){for(let m of e)m.blocks&&(m.blocks=m.blocks.filter(y=>y!==d)),m.blockedBy&&(m.blockedBy=m.blockedBy.filter(y=>y!==d))}function c(d){if(!d.title)return s("title is required for create action.");let m={id:r(),title:d.title,status:"not-started",...d.description!=null&&{description:d.description},...d.owner!=null&&{owner:d.owner}};return e.push(m),a(m.id,void 0,d.addBlockedBy),i({created:{id:m.id,title:m.title}})}function u(d){if(d.id==null)return s("id is required for update action.");let m=e.find(y=>y.id===d.id);if(!m)return s(`Task #${d.id} not found.`);if(d.status==="in-progress"){let y=e.find(h=>h.status==="in-progress"&&h.id!==d.id);if(y)return s(`Cannot set #${d.id} to in-progress: #${y.id} already is.`)}return d.title!=null&&(m.title=d.title),d.description!=null&&(m.description=d.description),d.owner!=null&&(m.owner=d.owner),d.status!=null&&(m.status=d.status),a(m.id,d.addBlocks,d.addBlockedBy),i({updated:{id:m.id,title:m.title}})}function p(d){if(d.id==null)return s("id is required for delete action.");let m=e.findIndex(y=>y.id===d.id);return m===-1?s(`Task #${d.id} not found.`):(t=Math.max(t,d.id),e.splice(m,1),l(d.id),i({deleted:d.id}))}return{name:hp,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:bp,searchHint:"manage session task checklist progress tracking dependencies",maxResultSizeChars:1e5,execute:async(d,m)=>{let y=m.action;switch(y){case"create":return c(m);case"update":return u(m);case"delete":return p(m);case"list":return i();default:return s(`Unknown action: ${y}. Valid: create, update, delete, list.`)}}}}import{isAbsolute as Np,resolve as Up}from"node:path";var Ai=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Ei=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Ii=new Set(["ls","tree","du"]);var Oi=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Tp(o){let t=o.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!t)return null;let n=t.split(/\s+/),r=0;for(;r<n.length&&/^[A-Za-z_]\w*=/.test(n[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<n.length;){let l=n[r];if(s.test(l)){for(r++;r<n.length&&/^[-+]/.test(n[r]);)r++;r<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[r])&&r++;continue}break}if(r>=n.length)return null;let i=n[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Li(o){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(o)}function Mn(o){let e=Tp(o),t=e!==null&&Ai.has(e),n=e!==null&&Ei.has(e),r=e!==null&&Ii.has(e),s=e!==null&&Oi.has(e),i=/(?:[^2]>|^>|\|>)/.test(o),a=Li(o),l=(t||n||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:n,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}function Pn(o){return/(?:^|[;&|])\s*sleep\s+\d/i.test(o)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(o)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as Pp}from"node:child_process";import{constants as no,readFileSync as Ap,unlinkSync as Ep}from"node:fs";import{mkdir as Ip,open as Op,realpath as Ui}from"node:fs/promises";import{isAbsolute as Lp,resolve as $p}from"node:path";function eo(){if(process.platform!=="win32")return!1;let o=process.env.QLOGICAGENT_USE_POWERSHELL;return o==="1"||o==="true"}function An(){return eo()?"powershell":"bash"}function En(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as kp,readFile as xp,writeFile as vp,unlink as wp}from"node:fs/promises";import{join as $i}from"node:path";import{tmpdir as Sp}from"node:os";var Cp=8*1024*1024,_p=5*1024*1024*1024;var In;function kt(){if(!In){let o=Math.random().toString(36).slice(2,10);In=$i(Sp(),"qla-tasks",o)}return In}function Di(o){return $i(kt(),`${o}.output`)}function Te(o="local_bash"){return`${o}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var _e=class{taskId;path;stdoutToFile;#e="";#o="";#r=0;#s=0;#t;#i;#n=0;#a=!1;constructor(e,t,n=!1,r=Cp){this.taskId=e,this.path=Di(e),this.stdoutToFile=n,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=Rp(e),this.#u()}writeStderr(e){this.#o+=e}async getStdout(){if(this.stdoutToFile)try{let e=await xp(this.path,"utf-8");return this.#n=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#o}get outputFileSize(){return this.#n}get outputFileRedundant(){return this.#n<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&kp(kt(),{recursive:!0}).then(()=>vp(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await wp(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#o="",this.#i=null,this.deleteOutputFile())}};function Rp(o){let e=0;for(let t=0;t<o.length;t++)o.charCodeAt(t)===10&&e++;return e}var On=137,Ni=143,Mp=5e3,Ln=5*1024*1024*1024,to=class{#e;#o;#r;#s=!1;constructor(e,t,n){this.#e=e,this.#o=t,this.#r=n,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let t=typeof e=="string"?e:e.toString();this.#r?this.#o.writeStderr(t):this.#o.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#o=null)}},$n=class o{#e="running";#o;#r;#s;#t;#i=null;#n=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,n,r,s=!1,i=Ln){this.#t=e,this.#l=t,this.#g=n,this.#b=s,this.#u=i,this.taskOutput=r,this.#s=e.stderr?new to(e.stderr,r,!0):null,this.#r=e.stdout?new to(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#C()}get status(){return this.#e}static#k(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(Ni)}#x(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let n=e??(t==="SIGTERM"?144:1);this.#f(n)}#w(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#T(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#T(){this.#n&&(clearInterval(this.#n),this.#n=null)}#S(){this.#n=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#u&&this.#e==="backgrounded"&&this.#n!==null&&(this.#a=!0,this.#T(),this.#y(On))},()=>{}))},Mp),this.#n.unref?.()}#C(){this.#c=this.#x.bind(this),this.#l.addEventListener("abort",this.#c,{once:!0}),this.#t.once("exit",this.#v.bind(this)),this.#t.once("error",this.#w.bind(this)),this.#i=setTimeout(o.#k,this.#g,this);let e=new Promise(t=>{this.#m=t});return new Promise(t=>{this.#p=t,e.then(this.#_.bind(this))})}async#_(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let t=await this.taskOutput.getStdout(),n={code:e,stdout:t,stderr:this.taskOutput.getStderr(),interrupted:e===On,backgroundTaskId:this.#o};this.taskOutput.stdoutToFile&&!this.#o&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(n.outputFilePath=this.taskOutput.path,n.outputFileSize=this.taskOutput.outputFileSize)),this.#a?n.stderr=`Background command killed: output file exceeded ${Ln} bytes. ${n.stderr}`:e===Ni&&(n.stderr=`Command timed out after ${this.#g}ms. ${n.stderr}`),this.#p&&(this.#p(n),this.#p=null)}#y(e){this.#e="killed";let t=this.#t.pid;if(t)try{if(process.platform==="win32")import("node:child_process").then(({execSync:n})=>{try{n(`taskkill /PID ${t} /T /F`,{stdio:"ignore"})}catch{}});else try{process.kill(-t,"SIGKILL")}catch{try{process.kill(t,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#f(e??On)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#o=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#S():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#d=void 0}};function Dn(o,e,t,n,r=!1,s=Ln){return new $n(o,e,t,n,r,s)}function oo(o,e){let t=new _e(Te("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:o}),taskOutput:t,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function Nn(o){let e=new _e(Te("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:o,interrupted:!1,preSpawnError:o}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var Dp=1800*1e3,ro=process.cwd(),ji=process.cwd();function so(){return ro}function Un(o,e){ro=Lp(o)?o:$p(e||ro,o)}function Fi(){return ji}function io(o){ro=o,ji=o}var jn=null;function xt(o){jn={provider:o}}function Bi(){if(!jn)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return jn.provider}async function ao(o,e,t,n){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:c}=n??{},u=r||Dp,p=t??An(),d=Bi(),m=En(),{commandString:y,cwdFilePath:h}=await d.buildExecCommand(o,{id:m,useSandbox:!1}),k=y,w=c??so();try{await Ui(w)}catch{let T=Fi();try{await Ui(T),Un(T),w=T}catch{return Nn(`Working directory "${w}" no longer exists.`)}}if(e.aborted)return oo();let f=d.shellPath,C=d.getSpawnArgs(k),R=await d.getEnvironmentOverrides(o),L=!!l,K=Te("local_bash"),D=new _e(K,s??null,!L);await Ip(kt(),{recursive:!0});let F;if(!L){let T=no.O_NOFOLLOW??0;F=await Op(D.path,process.platform==="win32"?"w":no.O_WRONLY|no.O_CREAT|no.O_APPEND|T)}try{let T=Pp(f,C,{env:{...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...R},cwd:w,stdio:L?["pipe","pipe","pipe"]:["pipe",F?.fd,F?.fd],detached:d.detached,windowsHide:!0}),B=Dn(T,e,u,D,a);if(F!==void 0)try{await F.close()}catch{}return T.stdout&&l&&T.stdout.on("data",J=>{l(typeof J=="string"?J:J.toString())}),h&&B.result.then(J=>{if(J&&!i&&!J.backgroundTaskId){try{let Q=Ap(h,{encoding:"utf8"}).trim();Q&&Q.normalize("NFC")!==w&&Un(Q,w)}catch{}try{Ep(h)}catch{}}}),B}catch(T){if(F!==void 0)try{await F.close()}catch{}return D.clear(),oo(void 0,{code:126,stderr:T instanceof Error?T.message:String(T)})}}var jp="exec",Fp={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"]},Bp=12e4,Wp=6e5,lo=3e4;function Fn(o,e){if(o.length<=e)return o;let t=Math.floor(e/2)-50;return`${o.slice(0,t)}
|
|
123
|
+
`)}import{release as om,homedir as nm}from"node:os";import{resolve as rm}from"node:path";function sm(){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 im(){let n=process.platform,e=om();return n==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():n==="darwin"?"macOS":n==="linux"?"Linux":n}function Gi(n){return Wi("environment_context",()=>{let e=sm(),t=im(),o=n??process.cwd(),r=process.version,s=nm(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${rm(o)}`,`- Home directory: ${s}`,`- Node.js: ${r}`];return e==="powershell"?i.push("- Note: Use PowerShell syntax (semicolons, not &&; use $env: for env vars)"):e==="cmd"&&i.push("- Note: Use CMD syntax (%VAR%, not $VAR)"),i.join(`
|
|
124
|
+
`)})}import*as A from"node:fs";import*as U from"node:path";import{execFile as Sf}from"node:child_process";var Bn=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),Vi=new Set([...Bn,"agent"]);function Wn(n,e){let t=e?Bn:Vi;return n.filter(o=>o.function.name.startsWith("mcp__")?!0:!t.has(o.function.name))}var Pe=new Map;function qi(n){Pe.clear();for(let e of n)Pe.set(e.name,e)}function ne(n){Pe.set(n.name,n)}function Hn(n){for(let e of n)Pe.set(e.name,e)}function po(n){return Pe.delete(n)}function Ae(n){return Pe.get(n)}function Ie(){return Array.from(Pe.keys())}function Ee(n=!1){let e=[];for(let t of Pe.values())t.isEnabled?.()!==!1&&(!n&&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 am="think",lm={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(`
|
|
125
|
+
`)}},required:["thought"]};function Ki(){return{name:am,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(`
|
|
126
|
+
`),parameters:lm,execute:async(n,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}function st(n){let e=new Set(n.filter(t=>t.status==="completed").map(t=>t.id));return{total:n.length,completed:n.filter(t=>t.status==="completed").length,inProgress:n.filter(t=>t.status==="in-progress").length,notStarted:n.filter(t=>t.status==="not-started").length,blocked:n.filter(t=>t.status!=="completed"&&t.blockedBy?.some(o=>!e.has(o))).length}}var cm="todo",um=["create","update","delete","list"],dm={type:"object",properties:{action:{type:"string",enum:[...um],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 Ji(n){let e=[],t=0,o=n??{};function r(){let p=e.reduce((m,h)=>Math.max(m,h.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=st(e),h=new Set(e.filter(x=>x.status==="completed").map(x=>x.id)),y=e.map(x=>{let f=x.blockedBy?.filter(_=>!h.has(_));return{...x,...f?.length?{blockedBy:f}:{blockedBy:void 0}}}),T={...m,todoList:y,...p};return{content:[{type:"text",text:JSON.stringify(T)}],details:{type:"todo",...m,agentId:o.agentId}}}function a(p,m,h){let y=e.find(T=>T.id===p);if(y){if(m?.length){y.blocks=[...new Set([...y.blocks??[],...m])];for(let T of m){let x=e.find(f=>f.id===T);x&&(x.blockedBy=[...new Set([...x.blockedBy??[],p])])}}if(h?.length){y.blockedBy=[...new Set([...y.blockedBy??[],...h])];for(let T of h){let x=e.find(f=>f.id===T);x&&(x.blocks=[...new Set([...x.blocks??[],p])])}}}}function c(p){for(let m of e)m.blocks&&(m.blocks=m.blocks.filter(h=>h!==p)),m.blockedBy&&(m.blockedBy=m.blockedBy.filter(h=>h!==p))}function u(p){if(!p.title)return s("title is required for create action.");let m={id:r(),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 l(p){if(p.id==null)return s("id is required for update action.");let m=e.find(h=>h.id===p.id);if(!m)return s(`Task #${p.id} not found.`);if(p.status==="in-progress"){let h=e.find(y=>y.status==="in-progress"&&y.id!==p.id);if(h)return s(`Cannot set #${p.id} to in-progress: #${h.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(h=>h.id===p.id);return m===-1?s(`Task #${p.id} not found.`):(t=Math.max(t,p.id),e.splice(m,1),c(p.id),i({deleted:p.id}))}return{name:cm,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:dm,searchHint:"manage session task checklist progress tracking dependencies",maxResultSizeChars:1e5,execute:async(p,m)=>{let h=m.action;switch(h){case"create":return u(m);case"update":return l(m);case"delete":return d(m);case"list":return i();default:return s(`Unknown action: ${h}. Valid: create, update, delete, list.`)}}}}import{isAbsolute as Am,resolve as Im}from"node:path";var Yi=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Xi=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Qi=new Set(["ls","tree","du"]);var Zi=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function pm(n){let t=n.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!t)return null;let o=t.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let c=o[r];if(s.test(c)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function ea(n){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(n)}function zn(n){let e=pm(n),t=e!==null&&Yi.has(e),o=e!==null&&Xi.has(e),r=e!==null&&Qi.has(e),s=e!==null&&Zi.has(e),i=/(?:[^2]>|^>|\|>)/.test(n),a=ea(n),c=(t||o||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:o,isList:r,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}function Gn(n){return/(?:^|[;&|])\s*sleep\s+\d/i.test(n)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(n)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}import{spawn as vm}from"node:child_process";import{constants as ho,readFileSync as wm,unlinkSync as _m}from"node:fs";import{mkdir as Cm,open as Sm,realpath as ra}from"node:fs/promises";import{isAbsolute as Rm,resolve as Mm}from"node:path";function mo(){if(process.platform!=="win32")return!1;let n=process.env.QLOGICAGENT_USE_POWERSHELL;return n==="1"||n==="true"}function Vn(){return mo()?"powershell":"bash"}function qn(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as mm,readFile as gm,writeFile as fm,unlink as hm}from"node:fs/promises";import{join as ta}from"node:path";import{tmpdir as ym}from"node:os";var bm=8*1024*1024,Tm=5*1024*1024*1024;var Kn;function At(){if(!Kn){let n=Math.random().toString(36).slice(2,10);Kn=ta(ym(),"qla-tasks",n)}return Kn}function oa(n){return ta(At(),`${n}.output`)}function Ce(n="local_bash"){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Oe=class{taskId;path;stdoutToFile;#e="";#o="";#r=0;#s=0;#t;#i;#n=0;#a=!1;constructor(e,t,o=!1,r=bm){this.taskId=e,this.path=oa(e),this.stdoutToFile=o,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=km(e),this.#u()}writeStderr(e){this.#o+=e}async getStdout(){if(this.stdoutToFile)try{let e=await gm(this.path,"utf-8");return this.#n=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#o}get outputFileSize(){return this.#n}get outputFileRedundant(){return this.#n<=this.#t}#u(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&mm(At(),{recursive:!0}).then(()=>fm(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await hm(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#o="",this.#i=null,this.deleteOutputFile())}};function km(n){let e=0;for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&e++;return e}var Jn=137,na=143,xm=5e3,Yn=5*1024*1024*1024,go=class{#e;#o;#r;#s=!1;constructor(e,t,o){this.#e=e,this.#o=t,this.#r=o,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let t=typeof e=="string"?e:e.toString();this.#r?this.#o.writeStderr(t):this.#o.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#o=null)}},Xn=class n{#e="running";#o;#r;#s;#t;#i=null;#n=null;#a=!1;#u;#l;#d;#g;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,o,r,s=!1,i=Yn){this.#t=e,this.#l=t,this.#g=o,this.#b=s,this.#u=i,this.taskOutput=r,this.#s=e.stderr?new go(e.stderr,r,!0):null,this.#r=e.stdout?new go(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#d=a}),this.result=this.#C()}get status(){return this.#e}static#k(e){e.#b&&e.#d?e.#d(e.background.bind(e)):e.#y(na)}#x(){this.#l.reason!=="interrupt"&&this.kill()}#v(e,t){let o=e??(t==="SIGTERM"?144:1);this.#f(o)}#w(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#T(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#T(){this.#n&&(clearInterval(this.#n),this.#n=null)}#_(){this.#n=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#u&&this.#e==="backgrounded"&&this.#n!==null&&(this.#a=!0,this.#T(),this.#y(Jn))},()=>{}))},xm),this.#n.unref?.()}#C(){this.#c=this.#x.bind(this),this.#l.addEventListener("abort",this.#c,{once:!0}),this.#t.once("exit",this.#v.bind(this)),this.#t.once("error",this.#w.bind(this)),this.#i=setTimeout(n.#k,this.#g,this);let e=new Promise(t=>{this.#m=t});return new Promise(t=>{this.#p=t,e.then(this.#S.bind(this))})}async#S(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let t=await this.taskOutput.getStdout(),o={code:e,stdout:t,stderr:this.taskOutput.getStderr(),interrupted:e===Jn,backgroundTaskId:this.#o};this.taskOutput.stdoutToFile&&!this.#o&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(o.outputFilePath=this.taskOutput.path,o.outputFileSize=this.taskOutput.outputFileSize)),this.#a?o.stderr=`Background command killed: output file exceeded ${Yn} bytes. ${o.stderr}`:e===na&&(o.stderr=`Command timed out after ${this.#g}ms. ${o.stderr}`),this.#p&&(this.#p(o),this.#p=null)}#y(e){this.#e="killed";let t=this.#t.pid;if(t)try{if(process.platform==="win32")import("node:child_process").then(({execSync:o})=>{try{o(`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??Jn)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#o=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#_():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 Qn(n,e,t,o,r=!1,s=Yn){return new Xn(n,e,t,o,r,s)}function fo(n,e){let t=new Oe(Ce("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:n}),taskOutput:t,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function Zn(n){let e=new Oe(Ce("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:n,interrupted:!1,preSpawnError:n}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var Pm=1800*1e3,yo=process.cwd(),sa=process.cwd();function bo(){return yo}function er(n,e){yo=Rm(n)?n:Mm(e||yo,n)}function ia(){return sa}function To(n){yo=n,sa=n}var tr=null;function It(n){tr={provider:n}}function aa(){if(!tr)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return tr.provider}async function ko(n,e,t,o){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:c,cwd:u}=o??{},l=r||Pm,d=t??Vn(),p=aa(),m=qn(),{commandString:h,cwdFilePath:y}=await p.buildExecCommand(n,{id:m,useSandbox:!1}),T=h,x=u??bo();try{await ra(x)}catch{let k=ia();try{await ra(k),er(k),x=k}catch{return Zn(`Working directory "${x}" no longer exists.`)}}if(e.aborted)return fo();let f=p.shellPath,_=p.getSpawnArgs(T),S=await p.getEnvironmentOverrides(n),O=!!c,K=Ce("local_bash"),D=new Oe(K,s??null,!O);await Cm(At(),{recursive:!0});let F;if(!O){let k=ho.O_NOFOLLOW??0;F=await Sm(D.path,process.platform==="win32"?"w":ho.O_WRONLY|ho.O_CREAT|ho.O_APPEND|k)}try{let k=vm(f,_,{env:{...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...S},cwd:x,stdio:O?["pipe","pipe","pipe"]:["pipe",F?.fd,F?.fd],detached:p.detached,windowsHide:!0}),j=Qn(k,e,l,D,a);if(F!==void 0)try{await F.close()}catch{}return k.stdout&&c&&k.stdout.on("data",J=>{c(typeof J=="string"?J:J.toString())}),y&&j.result.then(J=>{if(J&&!i&&!J.backgroundTaskId){try{let Q=wm(y,{encoding:"utf8"}).trim();Q&&Q.normalize("NFC")!==x&&er(Q,x)}catch{}try{_m(y)}catch{}}}),j}catch(k){if(F!==void 0)try{await F.close()}catch{}return D.clear(),fo(void 0,{code:126,stderr:k instanceof Error?k.message:String(k)})}}var Em="exec",Om={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"]},Lm=12e4,$m=6e5,xo=3e4;function or(n,e){if(n.length<=e)return n;let t=Math.floor(e/2)-50;return`${n.slice(0,t)}
|
|
124
127
|
|
|
125
|
-
... [truncated ${
|
|
128
|
+
... [truncated ${n.length-e} chars] ...
|
|
126
129
|
|
|
127
|
-
${
|
|
128
|
-
Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:t.description,classification:
|
|
129
|
-
${
|
|
130
|
-
`)}],details:{type:"exec",exitCode:
|
|
131
|
-
; `),i=e+s;return{commandString:t.useSandbox?[`'${
|
|
132
|
-
`),
|
|
133
|
-
`);
|
|
134
|
-
... (truncated)`);let
|
|
135
|
-
`).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${
|
|
136
|
-
`).length;return{content:[{type:"text",text:`Edited ${
|
|
137
|
-
`);return
|
|
130
|
+
${n.slice(-t)}`}function Dm(n){return n==null||n<=0?Lm:Math.min(n,$m)}async function*Um(n){let{command:e,abortController:t,timeout:o,shouldAutoBackground:r,cwd:s}=n,i="",a=0,c=0,u=Date.now(),l=null;function d(){return new Promise(h=>{l=()=>h(null)})}let p=await ko(e,t.signal,void 0,{timeout:o,onProgress(h,y,T,x,f){i=y,a=T,c=x,l&&(l(),l=null)},shouldAutoBackground:r,cwd:s});for(p.onTimeout&&r&&p.onTimeout(h=>{let y=Ce("bg");h(y)});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:c};let m=await p.result;return p.cleanup(),m}function la(n={}){return{name:Em,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:Om,maxResultSizeChars:xo,execute:async(e,t)=>{let o=zn(t.command);if(!t.background){let p=Gn(t.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:o}}}if(n.validateCommand){let p=await n.validateCommand(t.command);if(p)return{content:[{type:"text",text:`Command blocked: ${p}`}],details:{type:"exec",error:"blocked_by_guard",reason:p,classification:o}}}let r=new AbortController,s=Dm(t.timeout),i=t.workdir?Am(t.workdir)?t.workdir:Im(bo(),t.workdir):void 0;if(t.background){let p=await ko(t.command,r.signal,void 0,{shouldAutoBackground:!1,cwd:i}),m=Ce("bg");if(p.background(m))return{content:[{type:"text",text:`Background task started (id: ${m}).
|
|
131
|
+
Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:m,description:t.description,classification:o}}}let a=Um({command:t.command,abortController:r,timeout:s,shouldAutoBackground:!0,cwd:i}),c;do c=await a.next(),!c.done&&n.onProgress&&n.onProgress(c.value);while(!c.done);let u=c.value,l=[];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:o}};u.outputFilePath?(l.push(or(u.stdout,xo)),l.push(`[full output: ${u.outputFilePath} (${u.outputFileSize} bytes)]`)):u.stdout&&l.push(or(u.stdout,xo)),u.stderr&&l.push(`[stderr]
|
|
132
|
+
${or(u.stderr,Math.floor(xo/4))}`),u.interrupted&&l.push(`[interrupted \u2014 exit code ${u.code}]`);let d;return u.code!==0&&n.interpretExitCode&&(d=n.interpretExitCode(u.code,u.stderr),d&&l.push(`[exit ${u.code}: ${d}]`)),l.length===0&&l.push(o.isSilent&&u.code===0?"Done":`(exit code ${u.code}, no output)`),{content:[{type:"text",text:l.join(`
|
|
133
|
+
`)}],details:{type:"exec",exitCode:u.code,interrupted:u.interrupted,description:t.description,returnCodeInterpretation:d,noOutputExpected:o.isSilent,outputFilePath:u.outputFilePath,classification:o}}}}}import{tmpdir as Nm}from"node:os";import{join as Fm,posix as nr}from"node:path";function jm(n){return n.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function Bm(n){return!(/(?:^|[;&|])\s*<\s/.test(n)||/<<[-]?\s*['"]?[A-Za-z_]/.test(n))}function Wm(n,e){return`$'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function ca(n){return process.platform!=="win32"?n:n.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function vo(n,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:n,detached:!0,async buildExecCommand(o,r){let s=process.platform==="win32",i=Nm(),a=s?ca(i):i,c=r.useSandbox&&r.sandboxTmpDir?nr.join(r.sandboxTmpDir,`cwd-${r.id}`):nr.join(a,`qla-${r.id}-cwd`),u=r.useSandbox&&r.sandboxTmpDir?nr.join(r.sandboxTmpDir,`cwd-${r.id}`):Fm(i,`qla-${r.id}-cwd`),l=jm(o),d=Bm(l),p=Wm(l,d),m=[];if(t){let y=s?ca(t):t;m.push(`source '${y}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${c}'`),{commandString:m.join(" && "),cwdFilePath:u}},getSpawnArgs(o){return["-c",...!!t?[]:["-l"],o]},async getEnvironmentOverrides(o){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as Hm}from"node:os";import{join as zm,posix as Gm}from"node:path";function ua(n){return Buffer.from(n,"utf16le").toString("base64")}function Vm(n){return["-NoProfile","-NonInteractive","-Command",n]}function rr(n){return{type:"powershell",shellPath:n,detached:!1,async buildExecCommand(e,t){let o=t.useSandbox&&t.sandboxTmpDir?Gm.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):zm(Hm(),`qla-pwd-ps-${t.id}`),s=["","$_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }",`(Get-Location).Path | Out-File -FilePath '${o.replace(/'/g,"''")}' -Encoding utf8 -NoNewline`,"exit $_ec"].join(`
|
|
134
|
+
; `),i=e+s;return{commandString:t.useSandbox?[`'${n.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",ua(i)].join(" "):i,cwdFilePath:o}},getSpawnArgs(e){return Vm(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var qm=[{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"}],Km=[{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 sr(n){for(let{pattern:e,warning:t}of qm)if(e.test(n))return t;return null}function ir(n){for(let{pattern:e,warning:t}of Km)if(e.test(n))return t;return null}var Jm="read",Ym={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 da(n){return{name:Jm,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:Ym,execute:async(o,r)=>{let s=n.resolvePath(r.path);if(n.validatePath){let y=n.validatePath(s);if(y)return{content:[{type:"text",text:`Access denied: ${y}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await n.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(`
|
|
135
|
+
`),c=Math.max(0,(r.offset??1)-1),u=Math.min(r.limit??2e3,2e3),l=a.slice(c,c+u),d=l.join(`
|
|
136
|
+
`);d.length>5e4&&(d=d.slice(0,5e4)+`
|
|
137
|
+
... (truncated)`);let p=a.length,m=c+l.length,h=m<p;return{content:[{type:"text",text:d}],details:{type:"read",path:s,totalLines:p,startLine:c+1,endLine:m,hasMore:h}}}}}var Xm="write",Qm={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"]},pa=5e5;function ma(n){return{name:Xm,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:Qm,execute:async(e,t)=>{let o=n.resolvePath(t.path);if(n.validatePath){let s=n.validatePath(o);if(s)return{content:[{type:"text",text:`Access denied: ${s}`}],details:{type:"write",path:o,error:"access_denied"}}}if(t.content.length>pa)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${pa}). Split into multiple writes or use a different approach.`}],details:{type:"write",path:o,error:"content_too_large"}};if(n.checkReadBeforeWrite){let s=n.checkReadBeforeWrite(o);if(s)return{content:[{type:"text",text:s}],details:{type:"write",path:o,error:"not_read_first"}}}if(n.checkConcurrentModification){let s=n.checkConcurrentModification(o);if(s)return{content:[{type:"text",text:`Concurrent modification detected: ${s}. Re-read the file first.`}],details:{type:"write",path:o,error:"concurrent_modification"}}}await n.writeFile(o,t.content);let r=t.content.split(`
|
|
138
|
+
`).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${o}`}],details:{type:"write",path:o,lineCount:r}}}}}var Zm="edit",eg={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 ga(n){return{name:Zm,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:eg,execute:async(e,t)=>{let o=n.resolvePath(t.path);if(n.checkConcurrentModification){let l=n.checkConcurrentModification(o);if(l)return{content:[{type:"text",text:`Concurrent modification detected: ${l}. Re-read the file first.`}],details:{type:"edit",path:o,success:!1,reason:"concurrent_modification"}}}let r=await n.readFile(o),s=r.indexOf(t.oldText);if(s===-1)return{content:[{type:"text",text:`Error: oldText not found in ${o}. Ensure it matches exactly.`}],details:{type:"edit",path:o,success:!1,reason:"not_found"}};if(r.indexOf(t.oldText,s+1)!==-1)return{content:[{type:"text",text:`Error: oldText matches multiple locations in ${o}. Include more context to make the match unique.`}],details:{type:"edit",path:o,success:!1,reason:"ambiguous"}};let a=r.slice(0,s)+t.newText+r.slice(s+t.oldText.length);await n.writeFile(o,a);let u=r.slice(0,s).split(`
|
|
139
|
+
`).length;return{content:[{type:"text",text:`Edited ${o} (line ${u})`}],details:{type:"edit",path:o,success:!0,firstChangedLine:u}}}}}var tg="search",og={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"]},fa=100,ha=250,ar=1e5;function ya(n){return{name:tg,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:og,execute:async(e,t)=>{let o=t.path?n.resolvePath?n.resolvePath(t.path):t.path:"",r=t.mode;return r==="filename"?ng(n,t,o):r==="content"?rg(n,t,o):sg(n,t,o)}}}async function ng(n,e,t){let o=e.headLimit??fa,{files:r,truncated:s}=await n.glob(e.pattern,{cwd:t,limit:o===0?1e4:o}),i=e.offset??0,a=i>0?r.slice(i):r,c=o===0?a.length:o,u=a.slice(0,c),l=s||a.length>c;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(`
|
|
140
|
+
`);return l&&(d+=`
|
|
138
141
|
|
|
139
|
-
(Results truncated. ${
|
|
142
|
+
(Results truncated. ${u.length} shown. Use a more specific pattern or increase headLimit.)`),d=lr(d,ar),{content:[{type:"text",text:d}],details:{mode:"filename",totalMatches:u.length,truncated:l}}}async function rg(n,e,t){let o=e.headLimit??ha,{matches:r,truncated:s}=await n.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:o===0?void 0:o,offset:e.offset});if(r.length===0)return{content:[{type:"text",text:"No matches found."}],details:{mode:"content",totalMatches:0,truncated:!1}};let i=[];for(let c of r){if(c.contextBefore&&c.contextBefore.length>0)for(let u of c.contextBefore)i.push(` ${u}`);if(i.push(`${c.path}:${c.line}: ${c.text}`),c.contextAfter&&c.contextAfter.length>0)for(let u of c.contextAfter)i.push(` ${u}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
|
|
140
143
|
`);return s&&(a+=`
|
|
141
144
|
|
|
142
|
-
(Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=
|
|
145
|
+
(Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=lr(a,ar),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function sg(n,e,t){let[o,r]=await Promise.all([e.fileGlob?n.glob(e.fileGlob,{cwd:t,limit:fa}):Promise.resolve({files:[],truncated:!1}),n.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??ha,offset:e.offset})]),s=new Set(r.matches.map(l=>l.path)),i=o.files.filter(l=>!s.has(l)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
|
|
143
146
|
${i.join(`
|
|
144
|
-
`)}`),r.matches.length>0){let
|
|
145
|
-
${
|
|
146
|
-
`)}`)}if(a.length===0)return{content:[{type:"text",text:"No matches found in either filename or content."}],details:{mode:"both",totalMatches:0,truncated:!1}};let
|
|
147
|
+
`)}`),r.matches.length>0){let l=[];for(let d of r.matches)l.push(`${d.path}:${d.line}: ${d.text}`);a.push(`## Content matches (${r.matches.length}):
|
|
148
|
+
${l.join(`
|
|
149
|
+
`)}`)}if(a.length===0)return{content:[{type:"text",text:"No matches found in either filename or content."}],details:{mode:"both",totalMatches:0,truncated:!1}};let c=o.truncated||r.truncated,u=a.join(`
|
|
147
150
|
|
|
148
|
-
`);return
|
|
151
|
+
`);return c&&(u+=`
|
|
149
152
|
|
|
150
|
-
(Some results truncated. Use more specific patterns.)`),
|
|
153
|
+
(Some results truncated. Use more specific patterns.)`),u=lr(u,ar),{content:[{type:"text",text:u}],details:{mode:"both",totalMatches:i.length+r.matches.length,truncated:c}}}function lr(n,e){if(n.length<=e)return n;let t=Math.floor(e/2)-50;return`${n.slice(0,t)}
|
|
151
154
|
|
|
152
|
-
... [truncated ${
|
|
155
|
+
... [truncated ${n.length-e} chars] ...
|
|
153
156
|
|
|
154
|
-
${
|
|
155
|
-
`),t=[],
|
|
156
|
-
`)];for(let r of e){let s=-1;if(r.contextBefore.length>0)for(let i=0;i<=
|
|
157
|
-
`)}function
|
|
158
|
-
`);await
|
|
159
|
-
`)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var
|
|
157
|
+
${n.slice(-t)}`}var ig="apply_patch",ag={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function lg(n){let e=n.split(`
|
|
158
|
+
`),t=[],o=null,r=null,s=!1;for(let i of e){if(i.startsWith("*** Begin Patch")){s=!0;continue}if(i.startsWith("*** End Patch"))break;if(s){if(i.startsWith("*** Add File: "))o&&t.push(o),o={type:"add",path:i.slice(14).trim(),hunks:[]},r={contextBefore:[],removals:[],additions:[],contextAfter:[]},o.hunks.push(r);else if(i.startsWith("*** Update File: "))o&&t.push(o),o={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))o&&t.push(o),o={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move to: ")&&o)o.moveTo=i.slice(13).trim();else if(i.startsWith("@@ ")&&o)r={contextBefore:[],removals:[],additions:[],contextAfter:[]},o.hunks.push(r);else if(r)if(i.startsWith("+"))r.additions.push(i.slice(1));else if(i.startsWith("-"))r.removals.push(i.slice(1));else{let a=i.startsWith(" ")?i.slice(1):i;r.additions.length===0&&r.removals.length===0?r.contextBefore.push(a):r.contextAfter.push(a)}}}return o&&t.push(o),t}function cg(n,e){let o=[...n.split(`
|
|
159
|
+
`)];for(let r of e){let s=-1;if(r.contextBefore.length>0)for(let i=0;i<=o.length-r.contextBefore.length;i++){let a=!0;for(let c=0;c<r.contextBefore.length;c++)if(o[i+c]!==r.contextBefore[c]){a=!1;break}if(a){s=i+r.contextBefore.length;break}}else s=0;s!==-1&&(r.removals.length>0?o.splice(s,r.removals.length,...r.additions):o.splice(s,0,...r.additions))}return o.join(`
|
|
160
|
+
`)}function ba(n){return{name:ig,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:ag,execute:async(e,t)=>{let o=lg(t.input);if(o.length===0)return{content:[{type:"text",text:"Error: No valid patch operations found. Ensure *** Begin Patch / *** End Patch markers are present."}]};let r={added:[],modified:[],deleted:[]},s=[];for(let a of o){let c=n.resolvePath(a.path);try{switch(a.type){case"add":{let u=a.hunks.flatMap(l=>[...l.additions]).join(`
|
|
161
|
+
`);await n.writeFile(c,u),r.added.push(a.path);break}case"update":{let u=await n.readFile(c),l=cg(u,a.hunks);if(a.moveTo){let d=n.resolvePath(a.moveTo);await n.writeFile(d,l),await n.deleteFile(c),r.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await n.writeFile(c,l),r.modified.push(a.path);break}case"delete":{await n.deleteFile(c),r.deleted.push(a.path);break}}}catch(u){s.push(`${a.type} ${a.path}: ${u instanceof Error?u.message:String(u)}`)}}let i=[];return r.added.length&&i.push(`Added: ${r.added.join(", ")}`),r.modified.length&&i.push(`Modified: ${r.modified.join(", ")}`),r.deleted.length&&i.push(`Deleted: ${r.deleted.join(", ")}`),s.length&&i.push(`Errors: ${s.join("; ")}`),{content:[{type:"text",text:i.join(`
|
|
162
|
+
`)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var ug="patch",dg={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
|
|
160
163
|
1) V4A unified diff (*** Begin Patch / *** End Patch markers)
|
|
161
164
|
2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
|
|
162
|
-
Fuzzy matching automatically handles whitespace/indent/unicode drift in the search text.`},replaceAll:{type:"boolean",description:"Replace all occurrences instead of first only (default: false)."}},required:["input"]};function
|
|
163
|
-
`).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function
|
|
164
|
-
`).map(
|
|
165
|
-
`),a=
|
|
166
|
-
`);if(
|
|
167
|
-
`),
|
|
168
|
-
`).length+1,
|
|
169
|
-
`,
|
|
170
|
-
`,
|
|
171
|
-
`,
|
|
172
|
-
`).length+(f>0?1:0),
|
|
173
|
-
`).length;return[{start:F,end:J,strategy:"trimmed_boundary"}]}}}}}let m=
|
|
174
|
-
`).length+(
|
|
175
|
-
`).length;return[{start:F,end:
|
|
176
|
-
`).length+(
|
|
177
|
-
`).length;return[{start:
|
|
165
|
+
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 pg(n){return n.replace(/\\n/g,`
|
|
166
|
+
`).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Ta(n){return n.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 ka(n,e){if(n===e||Math.max(n.length,e.length)===0)return 1;let o=0,r=n.length,s=e.length,i=Math.max(r,s);for(let a=0;a<Math.min(r,s);a++)n[a]!==e[a]&&o++;return o+=Math.abs(r-s),1-o/i}function Sa(n,e,t){let o=[],r=n.indexOf(e);if(r!==-1){if(t){let y=0;for(;(r=n.indexOf(e,y))!==-1;)o.push({start:r,end:r+e.length,strategy:"exact"}),y=r+e.length}else o.push({start:r,end:r+e.length,strategy:"exact"});return o}let s=e.split(`
|
|
167
|
+
`).map(y=>y.trim()),i=n.split(`
|
|
168
|
+
`),a=xa(i,s,(y,T)=>y.trim()===T);if(a)return[{...va(n,i,a),strategy:"line_trimmed"}];let c=e.replace(/[ \t]+/g," "),u=n.replace(/[ \t]+/g," ");if(r=u.indexOf(c),r!==-1){let y=wa(n,u,r,c.length);if(y)return[{...y,strategy:"whitespace_normalized"}]}let l=xa(i,s,(y,T)=>y.trimStart()===T.trimStart());if(l)return[{...va(n,i,l),strategy:"indentation_flexible"}];let d=pg(e);if(d!==e&&(r=n.indexOf(d),r!==-1))return[{start:r,end:r+d.length,strategy:"escape_normalized"}];let p=e.split(`
|
|
169
|
+
`);if(p.length>=3){let y=p.slice(1,-1).join(`
|
|
170
|
+
`),T=p[0].trim(),x=p[p.length-1].trim();for(let f=0;f<i.length;f++)if(i[f].trim()===T){let _=i.slice(0,f+1).join(`
|
|
171
|
+
`).length+1,S=n.indexOf(y,_);if(S!==-1){let O=S+y.length,K=n.indexOf(`
|
|
172
|
+
`,O);if((K===-1?n.slice(O):n.slice(O,K)).trim()===x||K!==-1&&n.slice(O+1,n.indexOf(`
|
|
173
|
+
`,O+1)===-1?void 0:n.indexOf(`
|
|
174
|
+
`,O+1)).trim()===x){let F=i.slice(0,f).join(`
|
|
175
|
+
`).length+(f>0?1:0),k=f,j=p.length;if(f+j<=i.length){k=f+j;let J=i.slice(0,k).join(`
|
|
176
|
+
`).length;return[{start:F,end:J,strategy:"trimmed_boundary"}]}}}}}let m=Ta(e),h=Ta(n);if((m!==e||h!==n)&&(r=h.indexOf(m),r!==-1)){let y=wa(n,h,r,m.length);if(y)return[{...y,strategy:"unicode_normalized"}]}if(p.length>=3){let y=p[0],T=p[p.length-1];for(let x=0;x<i.length;x++)if(i[x]===y){for(let f=x+p.length-1;f<Math.min(x+p.length+2,i.length);f++)if(i[f]===T){let _=f-x+1,S=i.slice(x+1,f),O=p.slice(1,-1),K=O.filter(F=>S.some(k=>ka(k,F)>=.7)).length;if((O.length>0?K/O.length:1)>=.5&&_<=p.length+2){let F=i.slice(0,x).join(`
|
|
177
|
+
`).length+(x>0?1:0),k=i.slice(0,f+1).join(`
|
|
178
|
+
`).length;return[{start:F,end:k,strategy:"block_anchor"}]}}}}if(p.length>=2)for(let y=0;y<=i.length-p.length;y++){let T=i.slice(y,y+p.length);if(p.map((_,S)=>ka(_,T[S])).filter(_=>_>=.8).length/p.length>=.5){let _=i.slice(0,y).join(`
|
|
179
|
+
`).length+(y>0?1:0),S=i.slice(0,y+p.length).join(`
|
|
180
|
+
`).length;return[{start:_,end:S,strategy:"context_aware"}]}}return[]}function xa(n,e,t){for(let o=0;o<=n.length-e.length;o++){let r=!0;for(let s=0;s<e.length;s++)if(!t(n[o+s],e[s])){r=!1;break}if(r)return{startIdx:o,endIdx:o+e.length}}return null}function va(n,e,t){let o=e.slice(0,t.startIdx).join(`
|
|
178
181
|
`).length+(t.startIdx>0?1:0),r=e.slice(0,t.endIdx).join(`
|
|
179
|
-
`).length;return{start:
|
|
180
|
-
`),t=[],
|
|
181
|
-
`).pop()?.trim();if(!
|
|
182
|
+
`).length;return{start:o,end:r}}function wa(n,e,t,o){let r=0,s=0,i=-1,a=-1;for(;r<=n.length&&s<=e.length;){if(s===t&&i===-1&&(i=r),s===t+o){a=r;break}if(s>=e.length||r>=n.length)break;for(s++,r++;r<n.length&&s<e.length&&n[r]!==e[s];)r++}return i!==-1&&a===-1&&(a=n.length),i===-1?null:{start:i,end:a}}function _a(n){let e=n.split(`
|
|
183
|
+
`),t=[],o=null,r=null,s=!1;for(let i of e){if(i.startsWith("*** Begin Patch")){s=!0;continue}if(i.startsWith("*** End Patch"))break;if(s)if(i.startsWith("*** Add File: "))o&&t.push(o),o={type:"add",path:i.slice(14).trim(),hunks:[]},r={lines:[]},o.hunks.push(r);else if(i.startsWith("*** Update File: "))o&&t.push(o),o={type:"update",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Delete File: "))o&&t.push(o),o={type:"delete",path:i.slice(17).trim(),hunks:[]},r=null;else if(i.startsWith("*** Move File: ")){o&&t.push(o);let a=i.slice(15).trim().split(" -> ");o={type:"move",path:a[0].trim(),newPath:a[1]?.trim(),hunks:[]},r=null}else i.startsWith("@@ ")&&o?(r={contextHint:i.slice(3).replace(/ @@$/,"").trim()||void 0,lines:[]},o.hunks.push(r)):r&&(i.startsWith("+")?r.lines.push({prefix:"+",content:i.slice(1)}):i.startsWith("-")?r.lines.push({prefix:"-",content:i.slice(1)}):r.lines.push({prefix:" ",content:i.startsWith(" ")?i.slice(1):i}))}return o&&t.push(o),t}function mg(n){let e=[],t=n.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let o=t[0].trim().split(`
|
|
184
|
+
`).pop()?.trim();if(!o)return[];for(let r=1;r<t.length;r+=2){let s=t[r+1]||"",i=s.indexOf(`
|
|
182
185
|
====
|
|
183
|
-
`);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),
|
|
184
|
-
>>>> REPLACE`),u
|
|
185
|
-
`);if(!
|
|
186
|
+
`);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),c=s.slice(i+6),u=c.indexOf(`
|
|
187
|
+
>>>> REPLACE`),l=u===-1?c:c.slice(0,u);e.push({path:o,search:a,replace:l})}return e}function Ca(n,e,t){let o=e.lines.filter(h=>h.prefix===" ").map(h=>h.content),r=e.lines.filter(h=>h.prefix==="-").map(h=>h.content),s=e.lines.filter(h=>h.prefix==="+").map(h=>h.content),i=[],a="context";for(let h of e.lines)(h.prefix===" "||h.prefix==="-")&&i.push(h.content);let c=i.join(`
|
|
188
|
+
`);if(!c)return{content:n+`
|
|
186
189
|
`+s.join(`
|
|
187
|
-
`),strategy:"exact"};let
|
|
188
|
-
`),
|
|
189
|
-
`);await
|
|
190
|
-
`);r.errors.push(`${
|
|
191
|
-
${
|
|
190
|
+
`),strategy:"exact"};let u=Sa(n,c,t);if(u.length===0)return null;let l=[];for(let h of e.lines)(h.prefix===" "||h.prefix==="+")&&l.push(h.content);let d=l.join(`
|
|
191
|
+
`),p=u[0];return{content:n.slice(0,p.start)+d+n.slice(p.end),strategy:p.strategy}}function cr(n){return{name:ug,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:dg,execute:async(e,t)=>{let o=t.replaceAll??!1,r={filesModified:[],filesAdded:[],filesDeleted:[],strategies:{},errors:[]},s=t.input.includes("*** Begin Patch"),i=t.input.includes("<<<< SEARCH");if(s){let u=_a(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 l of u){let d=n.resolvePath(l.path);try{switch(l.type){case"add":{let p=l.hunks.flatMap(m=>m.lines.filter(h=>h.prefix==="+").map(h=>h.content)).join(`
|
|
192
|
+
`);await n.writeFile(d,p),r.filesAdded.push(l.path),r.strategies[l.path]="exact";break}case"delete":{await n.deleteFile(d),r.filesDeleted.push(l.path);break}case"move":{let p=await n.readFile(d);if(l.newPath){let m=n.resolvePath(l.newPath),h=p;for(let y of l.hunks){let T=Ca(h,y,o);T&&(h=T.content,r.strategies[l.path]=T.strategy)}await n.writeFile(m,h),await n.deleteFile(d),r.filesModified.push(`${l.path} \u2192 ${l.newPath}`)}break}case"update":{let p=await n.readFile(d),m="exact",h=!0;for(let y of l.hunks){let T=Ca(p,y,o);if(T)p=T.content,m=T.strategy;else{h=!1;let x=y.lines.filter(f=>f.prefix===" "||f.prefix==="-").map(f=>f.content).slice(0,5).join(`
|
|
193
|
+
`);r.errors.push(`${l.path}: hunk not matched. Search begins with:
|
|
194
|
+
${x}`)}}(h||p!==await n.readFile(d))&&(await n.writeFile(d,p),r.filesModified.push(l.path),r.strategies[l.path]=m);break}}}catch(p){r.errors.push(`${l.type} ${l.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let u=mg(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 l of u){let d=n.resolvePath(l.path);try{let p=await n.readFile(d),m=Sa(p,l.search,o);if(m.length===0){r.errors.push(`${l.path}: search text not matched (tried all 9 strategies)`);continue}let h=[...m].sort((y,T)=>T.start-y.start);for(let y of h)p=p.slice(0,y.start)+l.replace+p.slice(y.end);await n.writeFile(d,p),r.filesModified.push(l.path),r.strategies[l.path]=m[0].strategy}catch(p){r.errors.push(`${l.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return _a(`*** Begin Patch
|
|
192
195
|
`+t.input+`
|
|
193
|
-
*** End Patch`).length>0?
|
|
196
|
+
*** End Patch`).length>0?cr(n).execute(e,{input:`*** Begin Patch
|
|
194
197
|
`+t.input+`
|
|
195
|
-
*** End Patch`,replaceAll:
|
|
198
|
+
*** End Patch`,replaceAll:o}):{content:[{type:"text",text:"Error: Unrecognized patch format. Use V4A (*** Begin Patch) or search/replace (<<<< SEARCH / ==== / >>>> REPLACE)."}],details:{type:"patch",error:"unknown_format"}};let a=[];if(r.filesAdded.length&&a.push(`Added: ${r.filesAdded.join(", ")}`),r.filesModified.length){let u=r.filesModified.map(l=>`${l} (${r.strategies[l]||"exact"})`).join(", ");a.push(`Modified: ${u}`)}r.filesDeleted.length&&a.push(`Deleted: ${r.filesDeleted.join(", ")}`),r.errors.length&&a.push(`
|
|
196
199
|
Errors:
|
|
197
200
|
${r.errors.join(`
|
|
198
|
-
`)}`);let
|
|
199
|
-
`)||"No changes applied."}],details:{type:"patch",...r,success:
|
|
201
|
+
`)}`);let c=r.errors.length===0;return{content:[{type:"text",text:a.join(`
|
|
202
|
+
`)||"No changes applied."}],details:{type:"patch",...r,success:c}}}}}var gg="web_fetch",fg={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"]},hg=5e4;function Ra(n){return{name:gg,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:fg,execute:async(e,t)=>{let o=await n.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??hg,query:t.query,extract:t.extract});if(t.summarize&&n.summarizeContent&&o.content.length>1e3){let s=await n.summarizeContent(o.content,t.query);return{content:[{type:"text",text:o.title?`# ${o.title}
|
|
200
203
|
|
|
201
|
-
${s}`:s}],details:{type:"web_fetch",url:t.url,summarized:!0,originalLength:
|
|
202
|
-
`),r.push(
|
|
204
|
+
${s}`:s}],details:{type:"web_fetch",url:t.url,summarized:!0,originalLength:o.content.length,summaryLength:s.length}}}let r=[];if(o.title&&r.push(`# ${o.title}
|
|
205
|
+
`),r.push(o.content),o.relevantExcerpts?.length){r.push(`
|
|
203
206
|
---
|
|
204
207
|
## Relevant Excerpts
|
|
205
|
-
`);for(let s of
|
|
206
|
-
`)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!
|
|
207
|
-
`)}],details:{type:"web_search",query:
|
|
208
|
-
`);return{content:[{type:"text",text:`Found ${
|
|
209
|
-
${r}`}],details:{projectId:t.project_id,count:
|
|
208
|
+
`);for(let s of o.relevantExcerpts)r.push(`- ${s}`)}return{content:[{type:"text",text:r.join(`
|
|
209
|
+
`)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!o.extraction,extraction:o.extraction}}}}}var yg="web_search",bg={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"]},Tg=10;function Ma(n){return{name:yg,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:bg,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 o=await n.search(t.query.trim(),{allowedDomains:t.allowedDomains,blockedDomains:t.blockedDomains,maxResults:Tg});if(o.results.length===0)return{content:[{type:"text",text:`No results found for: "${t.query}"`}],details:{type:"web_search",query:t.query,resultCount:0}};let r=[`Web search results for: "${o.query}"`,"","REMINDER: You MUST include source URLs as markdown links when referencing these results.",""];for(let s=0;s<o.results.length;s++){let i=o.results[s];r.push(`${s+1}. [${i.title}](${i.url})`),r.push(` ${i.snippet}`),r.push("")}return{content:[{type:"text",text:r.join(`
|
|
210
|
+
`)}],details:{type:"web_search",query:o.query,resultCount:o.results.length}}}}}var kg="instructions",xg={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 Pa(n){return{name:kg,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:xg,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 o=n.list(t.project_id);if(o.length===0)return{content:[{type:"text",text:"No instruction files found for this project."}],details:{projectId:t.project_id,count:0}};let r=o.map(s=>`- ${s.filename} (${s.size} bytes, updated ${s.updatedAt})`).join(`
|
|
211
|
+
`);return{content:[{type:"text",text:`Found ${o.length} instruction file(s):
|
|
212
|
+
${r}`}],details:{projectId:t.project_id,count:o.length,files:o}}}case"read":{if(!t.filename)return{content:[{type:"text",text:"filename is required for read action"}],details:{error:"missing_filename"}};let o=n.read(t.project_id,t.filename);return o?{content:[{type:"text",text:o.content}],details:{projectId:t.project_id,filename:o.filename,size:o.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 o=n.write(t.project_id,t.filename,t.content);return{content:[{type:"text",text:`Instruction file written: ${o.filename} (${o.size} bytes)`}],details:{projectId:t.project_id,filename:o.filename,size:o.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 o=n.read(t.project_id,t.filename);if(!o)return{content:[{type:"text",text:`Instruction file not found: ${t.filename}`}],details:{projectId:t.project_id,filename:t.filename,error:"not_found"}};let r=o.content.split(t.old_text).length-1;if(r===0)return{content:[{type:"text",text:"old_text not found in the file"}],details:{projectId:t.project_id,filename:t.filename,error:"old_text_not_found"}};if(r>1)return{content:[{type:"text",text:`old_text matches ${r} locations \u2014 must match exactly once. Add more surrounding context to make it unique.`}],details:{projectId:t.project_id,filename:t.filename,error:"ambiguous_match",occurrences:r}};let s=o.content.replace(t.old_text,t.new_text),i=n.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"}}:n.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 vg="worktree",wg={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
|
|
210
213
|
exit: Leave worktree (keep or remove it).
|
|
211
|
-
list: Show all active worktrees.`},name:{type:"string",description:"Worktree/branch name (for enter). Must be kebab-case, max 64 characters. If omitted, auto-generated from task context."},exitAction:{type:"string",enum:["keep","remove"],description:"For exit: 'keep' retains the worktree for later use; 'remove' deletes it."},discardChanges:{type:"boolean",description:"Required true to confirm discarding uncommitted changes when exitAction='remove'. Safety mechanism to prevent data loss."}},required:["action"]},
|
|
212
|
-
`)}],details:{type:"worktree",action:"enter",name:r.name,branch:r.branch,path:r.path}}}case"exit":{if(!
|
|
213
|
-
Restored to: ${r.previousCwd||"main workspace"}`}],details:{type:"worktree",action:"exit",exitAction:
|
|
214
|
-
`)}],details:{type:"worktree",action:"list",count:
|
|
215
|
-
`).filter(Boolean).length}async function
|
|
216
|
-
`).find(D=>D.startsWith("worktree ")&&D.includes(
|
|
217
|
-
|
|
218
|
-
`).filter(Boolean);for(let
|
|
219
|
-
`),
|
|
220
|
-
`);return e.map((t,
|
|
221
|
-
`:t)}function
|
|
222
|
-
Old: ${
|
|
223
|
-
New: ${e.new_source.slice(0,120)}${e.new_source.length>120?"...":""}`;break}case"insert":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'insert' mode."}],details:{error:"missing_source"}};let m=e.cell_type??"code",
|
|
224
|
-
`;await
|
|
225
|
-
`),
|
|
226
|
-
... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${
|
|
214
|
+
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"]},_g=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function Aa(n){return{name:vg,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:wg,execute:async(e,t)=>{switch(t.action){case"enter":{if(n.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&&!_g.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 o=await n.enterWorktree(t.name);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error||"failed to create worktree"}`}],details:{type:"worktree",error:o.error}};let r=o.worktree;return{content:[{type:"text",text:[`Entered worktree: ${r.name}`,` Branch: ${r.branch}`,` Path: ${r.path}`,"","Working in isolated branch. Changes here do not affect the main branch.","Use action='exit' when done (keep or remove)."].join(`
|
|
215
|
+
`)}],details:{type:"worktree",action:"enter",name:r.name,branch:r.branch,path:r.path}}}case"exit":{if(!n.isInWorktree())return{content:[{type:"text",text:"Error: not in a worktree."}],details:{type:"worktree",error:"not_in_worktree"}};let o=t.exitAction||"keep";if(o==="remove"){let i=n.currentWorktree?.();if(i&&(i.hasChanges||i.unpushedCommits>0)&&!t.discardChanges){let a=[];return i.hasChanges&&a.push("uncommitted changes"),i.unpushedCommits>0&&a.push(`${i.unpushedCommits} unpushed commit(s)`),{content:[{type:"text",text:`Error: worktree has ${a.join(" and ")}. Set discardChanges=true to confirm removal, or use exitAction='keep'.`}],details:{type:"worktree",error:"has_changes",hasChanges:i.hasChanges,unpushedCommits:i.unpushedCommits}}}}let r=await n.exitWorktree(o,t.discardChanges);return r.success?{content:[{type:"text",text:`Exited worktree. ${o==="keep"?"Worktree kept for later use.":"Worktree removed."}
|
|
216
|
+
Restored to: ${r.previousCwd||"main workspace"}`}],details:{type:"worktree",action:"exit",exitAction:o,previousCwd:r.previousCwd}}:{content:[{type:"text",text:`Error: ${r.error||"failed to exit worktree"}`}],details:{type:"worktree",error:r.error}}}case"list":{let o=await n.listWorktrees();if(!o.worktrees||o.worktrees.length===0)return{content:[{type:"text",text:"No worktrees (only the main working tree)."}],details:{type:"worktree",action:"list",count:0}};let r=[`Worktrees (${o.worktrees.length}):`,""];for(let s of o.worktrees){let i=s.isCurrent?" \u2190 current":"",a=s.hasChanges?" (has changes)":"";r.push(` ${s.name} [${s.branch}]${i}${a}`),r.push(` path: ${s.path}`)}return{content:[{type:"text",text:r.join(`
|
|
217
|
+
`)}],details:{type:"worktree",action:"list",count:o.worktrees.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"worktree",error:"unknown_action"}}}}}}import{execFile as Cg}from"node:child_process";import{promisify as Sg}from"node:util";import{join as Et,resolve as Ia,basename as ur}from"node:path";import{mkdir as Rg,rm as Mg,symlink as Pg,readdir as uv,stat as Ag}from"node:fs/promises";var Ot=Sg(Cg),Ig=/^[a-zA-Z0-9._-]+$/,Ea=64;function Eg(n){if(n.length>Ea)throw new Error(`Invalid worktree name: must be ${Ea} characters or fewer (got ${n.length})`);for(let e of n.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${n}": must not contain "." or ".." path segments`);if(!Ig.test(e))throw new Error(`Invalid worktree name "${n}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function Na(n){return n.replaceAll("/","+")}function Og(n){return`worktree-${Na(n)}`}var ge=null;async function fe(n,e){try{let{stdout:t,stderr:o}=await Ot("git",n,{cwd:e??process.cwd(),env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""},timeout:3e4});return{stdout:t,stderr:o,code:0}}catch(t){let o=t;return{stdout:o.stdout??"",stderr:o.stderr??String(t),code:o.code??1}}}async function Oa(n){let{stdout:e,code:t}=await fe(["rev-parse","--show-toplevel"],n);return t===0?e.trim():null}async function La(n){let{stdout:e,code:t}=await fe(["status","--porcelain"],n);return t!==0?-1:e.trim().split(`
|
|
218
|
+
`).filter(Boolean).length}async function $a(n,e){let{stdout:t,code:o}=await fe(["rev-list",`origin/${e}..${e}`,"--count"],n);return o!==0?0:parseInt(t.trim(),10)||0}async function Lg(n,e,t,o){for(let r of t){if(r.includes("..")||r.startsWith("/")||r.startsWith("\\")){o?.warn(`[worktree] skipping symlink for "${r}": path traversal detected`);continue}let s=Et(n,r),i=Et(e,r);try{await Pg(s,i,"dir"),o?.info(`[worktree] symlinked ${r} from main repo to worktree`)}catch(a){let c=a.code;c!=="ENOENT"&&c!=="EEXIST"&&o?.warn(`[worktree] failed to symlink ${r} (${c??"unknown"}): ${a}`)}}}async function $g(n,e,t){let{code:o,stderr:r}=await fe(["sparse-checkout","set","--cone","--",...t],n);if(o!==0)throw await fe(["worktree","remove","--force",n],e),new Error(`Failed to configure sparse-checkout: ${r}`);let{code:s,stderr:i}=await fe(["checkout","HEAD"],n);if(s!==0)throw await fe(["worktree","remove","--force",n],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function Dg(){try{return await Ot("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function Ug(n,e){return`${ur(n)}_${e}`.replace(/[/.]/g,"_")}async function Ng(n,e){if(!await Dg())return null;try{return await Ot("tmux",["new-session","-d","-s",e,"-c",n],{timeout:1e4}),e}catch{return null}}async function Da(n){try{return await Ot("tmux",["kill-session","-t",n],{timeout:5e3}),!0}catch{return!1}}async function Ua(n,e,t,o){let r=ei(e),s=Et(r,n);try{if(!(await Ag(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await Ot(s,[],{cwd:e,env:{...process.env,...t},timeout:3e4});return o?.info(`[worktree] hook ${n} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return o?.warn(`[worktree] hook ${n} failed: ${i}`),null}}function Fa(n){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:o}=n;return{async enterWorktree(r){try{let s=Date.now(),i=await Oa();if(!i)return{success:!1,error:"Not in a git repository"};let a=await Ua("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let D=process.cwd();return process.chdir(a),ge={originalCwd:D,worktreePath:a,worktreeName:r??ur(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:ge.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let c=r??`agent-${Date.now().toString(36)}`;Eg(c);let u=Na(c),l=Og(c),d=Et(i,".worktrees"),p=Et(d,u);await Rg(d,{recursive:!0});let{stdout:m}=await fe(["worktree","list","--porcelain"],i),h=m.split(`
|
|
219
|
+
`).find(D=>D.startsWith("worktree ")&&D.includes(u));if(h){let D=h.replace("worktree ","").trim(),F=process.cwd();return process.chdir(D),ge={originalCwd:F,worktreePath:D,worktreeName:c,worktreeBranch:l},e.info(`[worktree] resumed existing worktree: ${c} at ${D}`),{success:!0,worktree:{name:c,path:D,branch:l,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let y=o&&o.length>0,T=["worktree","add"];y&&T.push("--no-checkout"),T.push("-B",l,p,"HEAD");let{code:x,stderr:f}=await fe(T,i);if(x!==0)return{success:!1,error:`git worktree add failed: ${f.trim()}`};let _=!1;y&&o&&(await $g(p,i,o),_=!0),await Lg(i,p,t,e);let S=process.cwd();process.chdir(p);let O=Ug(i,l),K=await Ng(p,O);return ge={originalCwd:S,worktreePath:p,worktreeName:c,worktreeBranch:l,tmuxSessionName:K??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:_},e.info(`[worktree] entered: ${c} at ${p}`),{success:!0,worktree:{name:c,path:p,branch:l,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(r,s){if(!ge)return{success:!1,error:"Not in a worktree"};try{let i=ge,a=await Oa(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let c=await La(i.worktreePath),u=await $a(i.worktreePath,i.worktreeBranch);if((c>0||u>0)&&!s)return{success:!1,error:`Worktree has ${c} uncommitted change(s) and ${u} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),ge=null,i.tmuxSessionName&&await Da(i.tmuxSessionName),await Ua("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let l=["worktree","remove"];s&&l.push("--force"),l.push(i.worktreePath);let{code:d,stderr:p}=await fe(l,a);d!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await Mg(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await fe(["worktree","prune"],a)),await fe(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await Da(i.tmuxSessionName),ge=null,e.info(`[worktree] exited (kept): ${i.worktreeName}`);return{success:!0,previousCwd:i.originalCwd}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}},async listWorktrees(){try{let{stdout:r,code:s}=await fe(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),c=r.split(`
|
|
220
|
+
|
|
221
|
+
`).filter(Boolean);for(let u of c){let l=u.split(`
|
|
222
|
+
`),d="",p="";for(let T of l)T.startsWith("worktree ")&&(d=T.slice(9).trim()),T.startsWith("branch ")&&(p=T.slice(7).trim().replace("refs/heads/",""));if(!d)continue;let m=Ia(d)===Ia(a),h=await La(d),y=await $a(d,p);i.push({name:p.startsWith("worktree-")?p.slice(9):ur(d),path:d,branch:p,isCurrent:m,hasChanges:h>0,unpushedCommits:y})}return{success:!0,worktrees:i}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}},isInWorktree(){return ge!==null},currentWorktree(){return ge?{name:ge.worktreeName,path:ge.worktreePath,branch:ge.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as Fg,writeFile as jg}from"node:fs/promises";import*as ja from"node:path";var Bg={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 Ba(n){let e=n.split(`
|
|
223
|
+
`);return e.map((t,o)=>o<e.length-1?t+`
|
|
224
|
+
`:t)}function Wa(n){return n.join("")}function Wg(n,e){let t=Wa(n.source).trim(),o=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${n.cell_type}]: ${o}`}function Hg(n,e){let t={cell_type:n,source:Ba(e),metadata:{}};return n==="code"&&(t.execution_count=null,t.outputs=[]),t}function Ha(){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:Bg,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"jupyter notebook ipynb cell edit insert delete",execute:async(n,e)=>{let{notebook_path:t,cell_number:o,edit_mode:r="replace"}=e,s=ja.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 Fg(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let c=a.cells.length,u=o-1;if(r==="insert"){if(o<0||o>c)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. For insert, use 0-${c}.`}],details:{error:"out_of_range"}}}else if(u<0||u>=c)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. Notebook has ${c} cell(s).`}],details:{error:"out_of_range"}};let l;switch(r){case"replace":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'replace' mode."}],details:{error:"missing_source"}};let m=a.cells[u],h=Wa(m.source);m.source=Ba(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),l=`Replaced cell ${o} [${m.cell_type}].
|
|
225
|
+
Old: ${h.slice(0,120)}${h.length>120?"...":""}
|
|
226
|
+
New: ${e.new_source.slice(0,120)}${e.new_source.length>120?"...":""}`;break}case"insert":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'insert' mode."}],details:{error:"missing_source"}};let m=e.cell_type??"code",h=Hg(m,e.new_source);a.cells.splice(o,0,h),l=`Inserted new ${m} cell after position ${o}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(u,1)[0];l=`Deleted cell ${o} [${m.cell_type}]. Remaining: ${a.cells.length} cells.`;break}default:return{content:[{type:"text",text:`Error: unknown edit_mode "${r}". Use replace, insert, or delete.`}],details:{error:"unknown_mode"}}}try{let m=JSON.stringify(a,null,1)+`
|
|
227
|
+
`;await jg(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,h)=>Wg(m,h)).join(`
|
|
228
|
+
`),p=a.cells.length>10?`
|
|
229
|
+
... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${l}
|
|
227
230
|
|
|
228
231
|
Current cells:
|
|
229
|
-
${
|
|
232
|
+
${d}${p}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:o,total_cells:a.cells.length}}}}}import{readFile as zg,readdir as Gg}from"node:fs/promises";import*as Ga from"node:path";import{existsSync as Vg}from"node:fs";var qg={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
|
|
230
233
|
run: Execute a workflow by name.
|
|
231
|
-
describe: Show workflow steps and variables.`},workflow:{type:"string",description:"Workflow name (required for 'run' and 'describe')."},variables:{type:"object",description:"Variable overrides (key-value pairs) for the workflow run.",additionalProperties:{type:"string"}}},required:["action"]};async function
|
|
232
|
-
`)}],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
|
|
233
|
-
`)}],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
|
|
234
|
-
`)}],details:{type:"workflow",action:"run",workflow:a.name,success:
|
|
235
|
-
`),parameters:
|
|
236
|
-
`)}],details:{...
|
|
237
|
-
`)}],details:{type:"tool_search",activated:a,notFound:
|
|
238
|
-
`)}],details:{type:"tool_search",query:o.query,matchCount:o.matches.length,totalDeferred:o.totalDeferred,matches:o.matches.map(t=>t.name)}}}var lg="image_generate",cg={type:"object",properties:{prompt:{type:"string",description:"Image generation prompt. Enrich vague requests with style, lighting, composition, color, mood details."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video-cover', 'phone-wallpaper', 'avatar', 'poster', etc."},style:{type:"string",description:"Visual art style: 'photorealistic', 'anime', 'watercolor', 'oil-painting', '3d-render', etc."},size:{type:"string",description:"Dimensions: e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Default: '1024x1024'."},image_url:{type:"string",description:"Reference image URL for image-to-image generation (img2img). Character reference sheet or style transfer."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."}},required:["prompt"]};function Aa(o){return{name:lg,label:"Image Generate",description:"Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately. IMPORTANT: If the user has not specified purpose or preferred style, use ask_user to clarify (e.g. purpose: social-media / wallpaper / poster; style: photorealistic / anime / watercolor) before calling this tool. Infer image size automatically from purpose (e.g. 1024x1792 for phone wallpaper, 1792x1024 for landscape poster, 1024x1024 for avatar/social). Do NOT expose size as a raw number to the user.",parameters:cg,execute:async(e,t)=>{let n=await o.generateImage({prompt:t.prompt,purpose:t.purpose,style:t.style,size:t.size,imageUrl:t.image_url,n:t.n}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} image${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var ug={type:"object",properties:{text:{type:"string",description:"Text to convert to speech."},channel:{type:"string",description:"Optional channel id to pick output format (e.g. telegram)."}},required:["text"]};function Ea(o){return{name:"tts",label:"TTS",description:"Convert text to speech (TTS) \u2014 read text aloud as spoken audio. Use for narration, voice messages, or any spoken-word output. DO NOT use for music, songs, or melodies \u2014 use music_generate instead.",parameters:ug,execute:async(e,t)=>{let n=await o.textToSpeech({text:t.text,channel:t.channel});return{content:[{type:"text",text:"\u5DF2\u6210\u529F\u751F\u6210\u8BED\u97F3\u3002"}],details:{type:"tts",audioPath:n.audioPath,provider:n.provider,voiceCompatible:n.voiceCompatible,mediaUrls:n.mediaUrls}}}}}var dg="video_generate",pg={type:"object",properties:{prompt:{type:"string",description:"Video generation prompt. MUST be in English. Include scene, movement, camera motion, lighting, style."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video', 'presentation', etc."},style:{type:"string",description:"Visual style: 'cinematic', 'anime', 'watercolor', etc."},image_url:{type:"string",description:"Reference image for image-to-video. Preview image from storyboard Step 3, or user-uploaded image."},aspect_ratio:{type:"string",description:"Video aspect ratio: '9:16' (vertical), '16:9' (horizontal), '1:1' (square). Default: '16:9'."},duration:{type:"number",description:"Video duration in seconds (3-10s single-shot, >10s requires multi-shot workflow). Must be confirmed by user."}},required:["prompt"]};function Ia(o){return{name:dg,label:"Video Generate",description:"Generate a short video clip from a text prompt (and optional reference image). Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Single-shot: 3\u201310s. For longer videos (>10s), use multi-shot storyboard workflow. IMPORTANT: If the user has not specified aspect ratio or duration, use ask_user to clarify (e.g. aspect: 16:9 for landscape / 9:16 for vertical / 1:1 for square; duration: 3-10s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).",parameters:pg,execute:async(e,t)=>{let n=await o.generateVideo({prompt:t.prompt,purpose:t.purpose,style:t.style,imageUrl:t.image_url,aspectRatio:t.aspect_ratio,duration:t.duration}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} video${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var mg="music_generate",gg={type:"object",properties:{prompt:{type:"string",description:"Music generation prompt. MUST be in English. Include genre, mood, tempo, instruments, and atmosphere details."},purpose:{type:"string",description:"Intended use: 'background-music', 'ringtone', 'short-video-bgm', 'full-song', 'notification-sound', etc."},style:{type:"string",description:"Musical style/genre: 'lo-fi', 'pop', 'rock', 'jazz', 'classical', 'electronic', 'ambient', etc."},lyrics:{type:"string",description:"Optional lyrics for vocal music. Structure with [verse], [chorus], [bridge] tags if desired."},duration:{type:"number",description:"Duration in seconds (5-300). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s."}},required:["prompt"]};function Oa(o){return{name:mg,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:gg,execute:async(e,t)=>{let n=await o.generateMusic({prompt:t.prompt,purpose:t.purpose,style:t.style,lyrics:t.lyrics,duration:t.duration}),r=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} audio track${r>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"music_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var fg="video_edit",hg={type:"object",properties:{prompt:{type:"string",description:"Edit instruction. Reference videos as \u89C6\u98911, \u89C6\u98912, \u89C6\u98913. Reference images as \u56FE\u72471, \u56FE\u72472. Operations: add/remove/modify elements, extend, track fill."},source_videos:{type:"array",items:{type:"string"},minItems:1,maxItems:3,description:"Video(s) to edit (1-3 URLs). Order: [0]=\u89C6\u98911, [1]=\u89C6\u98912, [2]=\u89C6\u98913."},reference_images:{type:"array",items:{type:"string"},description:"Optional reference images for element replacement (up to 9)."},duration:{type:"number",description:"Output duration in seconds (4-15s). Default: same as source."},aspect_ratio:{type:"string",description:"Output aspect ratio: 16:9, 9:16, 1:1, 4:3, 3:4, 21:9. Default: same as source."},resolution:{type:"string",description:"Output resolution: '480p' or '720p'. Default: '720p'."}},required:["prompt","source_videos"]};function La(o){return{name:fg,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos. Max 3 source videos, max 720p. For generating NEW videos from scratch, use video_generate instead.",parameters:hg,execute:async(e,t)=>{if(!t.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await o.editVideo({prompt:t.prompt,sourceVideos:t.source_videos,referenceImages:t.reference_images,duration:t.duration,aspectRatio:t.aspect_ratio,resolution:t.resolution});return{content:[{type:"text",text:`Video edited successfully${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_edit",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var yg="video_merge",bg={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video file path."},audio:{type:"string",description:"Narration audio file path (from TTS)."},trimStart:{type:"number",description:"Trim start in seconds (default 0)."},trimEnd:{type:"number",description:"Trim end in seconds (default: full)."}},required:["video"]},minItems:2,description:"Array of video clips to merge, in order."},transition:{type:"string",description:"Transition effect: 'crossfade' (default), 'fade', 'wipeleft', 'cut', 'dissolve', etc."},transitionDuration:{type:"number",description:"Transition duration in seconds (0.1-2.0, default 0.5)."},subtitles:{type:"string",description:"Path to SRT subtitle file to burn-in."},bgm:{type:"string",description:"Background music file path."},bgmVolume:{type:"number",description:"BGM volume (0.0-1.0, default 0.15)."},outputResolution:{type:"string",description:"Output resolution: '1920x1080', '1080x1920', etc. Default: auto."},outputFps:{type:"number",description:"Output FPS (default 30)."}},required:["clips"]};function $a(o){return{name:yg,label:"Video Merge",description:"Merge multiple video clips into a single video with transitions, subtitles, and background music. Requires at least 2 clips. Supports crossfade, fade, wipe, dissolve, and cut transitions. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:bg,execute:async(e,t)=>{if(!t.clips||t.clips.length<2)return{content:[{type:"text",text:"Error: at least 2 clips are required for merging."}]};let n=await o.mergeVideos({clips:t.clips,transition:t.transition,transitionDuration:t.transitionDuration,subtitles:t.subtitles,bgm:t.bgm,bgmVolume:t.bgmVolume,outputResolution:t.outputResolution,outputFps:t.outputFps});return{content:[{type:"text",text:`Merged ${n.clipCount} clips \u2192 ${n.durationSec.toFixed(1)}s video`+(t.transition?` (transition: ${t.transition})`:"")}],details:{type:"video_merge",localPath:n.localPath,servePath:n.servePath,durationSec:n.durationSec,clipCount:n.clipCount,mediaUrls:n.mediaUrls}}}}}var Tg="video_upscale",kg={type:"object",properties:{video:{type:"string",description:"Video file path (local or serve path)."},targetResolution:{type:"string",description:"Target resolution: '1080p' (default, 1920x1080/1080x1920), '2k' (2560x1440/1440x2560)."},sharpness:{type:"string",description:"Sharpening intensity: 'light' (default), 'medium', 'strong'."}},required:["video"]};function Da(o){return{name:Tg,label:"Video Upscale",description:"Upscale a video to higher resolution with optional sharpening. Auto-detects orientation (landscape/portrait). Uses Lanczos interpolation + unsharp mask. Supports 1080p and 2K targets. Best used as post-processing after video_merge.",parameters:kg,execute:async(e,t)=>{let n=await o.upscaleVideo({video:t.video,targetResolution:t.targetResolution,sharpness:t.sharpness});return{content:[{type:"text",text:`Upscaled to ${n.resolution}${t.sharpness?` (sharpness: ${t.sharpness})`:""}`}],details:{type:"video_upscale",localPath:n.localPath,servePath:n.servePath,resolution:n.resolution,durationSec:n.durationSec,mediaUrls:n.mediaUrls}}}}}var Ue,Xn={},Ua;function ja(o,e,t){Ue=o,Xn=e??{},Ua=t}async function De(o){if(Ue){let e=Ue.resolveModel(o.mediaType);if(e){let t=Ue.getTransport(e.providerId),n=Xn[e.providerId];if(t&&n){let r={...o,model:o.model||e.modelInfo.id},s=await t.generate(r,n);s.billingUnit||(o.mediaType==="tts"&&o.text?(s.billingUnit="per_character",s.billingQuantity=o.text.length):(o.mediaType==="video"||o.mediaType==="music")&&o.duration?(s.billingUnit="per_second",s.billingQuantity=o.duration):(s.billingUnit="per_call",s.billingQuantity=1));let i=s.model??r.model,a=s.billingUnit??"per_call",l=s.billingQuantity??1;return Ua?.(i,a,l),s}}}throw new Error(`No media provider configured for ${o.mediaType}`)}function Ne(o){if(Ue){let e=Ue.resolveModel(o);if(e){let t=Ue.getTransport(e.providerId),n=Xn[e.providerId];if(t&&n)return!0}}return!1}var je=process.cwd();function ae(o){return U.isAbsolute(o)?U.normalize(o):U.resolve(je,o)}var vg=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),Fa=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]);function wg(){return{resolvePath:ae,async readFile(o){let e=ae(o),t=U.extname(e).toLowerCase();if(Fa.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(vg.has(t)){let r=await I.promises.readFile(e),s=t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg";return{type:"image",base64:r.toString("base64"),mimeType:s}}return{type:"text",text:await I.promises.readFile(e,"utf8")}},validatePath(o){let e=ae(o);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function Sg(){return{resolvePath:ae,async writeFile(o,e){let t=ae(o);await I.promises.mkdir(U.dirname(t),{recursive:!0}),await I.promises.writeFile(t,e,"utf8")}}}function Cg(){return{resolvePath:ae,async readFile(o){let e=ae(o);return I.promises.readFile(e,"utf8")},async writeFile(o,e){let t=ae(o);await I.promises.mkdir(U.dirname(t),{recursive:!0}),await I.promises.writeFile(t,e,"utf8")}}}function _g(){return{resolvePath:ae,async readFile(o){let e=ae(o);return I.promises.readFile(e,"utf8")},async writeFile(o,e){let t=ae(o);await I.promises.mkdir(U.dirname(t),{recursive:!0}),await I.promises.writeFile(t,e,"utf8")},async deleteFile(o){let e=ae(o);await I.promises.unlink(e)},async fileExists(o){let e=ae(o);try{return await I.promises.access(e),!0}catch{return!1}}}}function Rg(){return{resolvePath:ae,async glob(o,e){let t=e.cwd||je,n=e.limit||1e3,r=[],s=!1,i=o.replace(/\\/g,"/").split("/"),a=i.some(u=>u==="**"),l=i[i.length-1]??"*",c=Ba(l);try{await Qn(t,async u=>{if(r.length>=n)return s=!0,!1;let p=U.basename(u);return c.test(p)&&r.push(u),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(o,e){let t=e.cwd||je;try{return await Pg(o,t,e)}catch{return await Ag(o,t,e)}}}}function Ba(o){let e=o.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(t,n)=>"("+n.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var Mg=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function Qn(o,e,t,n=0,r=""){if(n>t)return;let s;try{s=await I.promises.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(Mg.has(i.name))continue;await Qn(U.join(o,i.name),e,t,n+1,a)}else if(i.isFile()&&!await e(a))return}}function Pg(o,e,t){return new Promise((n,r)=>{let s=["--json","--no-heading","--max-columns","500"];t.caseInsensitive&&s.push("-i"),t.contextLines&&s.push("-C",String(t.contextLines)),t.fileGlob&&s.push("-g",t.fileGlob),s.push("--max-count",String(t.headLimit??250)),s.push(o),s.push("."),xg("rg",s,{cwd:e,maxBuffer:10*1024*1024,timeout:3e4},(i,a)=>{if(i&&!("killed"in i&&i.killed)&&i.code!==1){r(i);return}let l=[];for(let d of a.split(`
|
|
239
|
-
`)
|
|
240
|
-
`)
|
|
241
|
-
`
|
|
242
|
-
`)
|
|
243
|
-
|
|
244
|
-
`);i=
|
|
245
|
-
`)
|
|
246
|
-
`).
|
|
234
|
+
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 dr(n){let e=new Map,t=Xs(n);await za(t,e);let o=Js();return await za(o,e),e}async function za(n,e){if(Vg(n))try{let t=await Gg(n,{withFileTypes:!0});for(let o of t)if(o.isFile()&&o.name.endsWith(".json")){let r=o.name.replace(/\.json$/,"");e.has(r)||e.set(r,Ga.join(n,o.name))}}catch{}}async function pr(n){let e=await zg(n,"utf-8");return JSON.parse(e)}function Kg(n){let e=new Map(n.map(s=>[s.id,s])),t=new Set,o=[];function r(s,i){if(t.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected at step: ${s}`);i.add(s);let a=e.get(s);if(!a)throw new Error(`Unknown step dependency: ${s}`);for(let c of a.dependsOn??[])r(c,i);i.delete(s),t.add(s),o.push(a)}for(let s of n)r(s.id,new Set);return o}function Jg(n,e,t){let o={};for(let[r,s]of Object.entries(n))if(typeof s=="string"){let i=s;i=i.replace(/\$\{var\.(\w+)\}/g,(a,c)=>e[c]??`\${var.${c}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,c)=>t.get(c)?.output??""),o[r]=i}else o[r]=s;return o}function Va(n){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:qg,shouldDefer:!0,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"workflow pipeline automation steps DAG",execute:async(e,t,o)=>{let r=n.getCwd();switch(t.action){case"list":{let s=await dr(r);if(s.size===0)return{content:[{type:"text",text:"No workflows found. Create .json files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/."}],details:{type:"workflow",action:"list",count:0}};let i=["Available workflows:"];for(let[a,c]of s)try{let u=await pr(c);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(`
|
|
235
|
+
`)}],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 dr(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await pr(i),c=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let u of a.steps){let l=u.dependsOn?.length?` (after: ${u.dependsOn.join(", ")})`:"";c.push(` ${u.id}: ${u.label??u.tool}${l}`),c.push(` tool: ${u.tool}`),c.push(` args: ${JSON.stringify(u.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){c.push("","Variables (defaults):");for(let[u,l]of Object.entries(a.variables))c.push(` ${u} = ${l}`)}return{content:[{type:"text",text:c.filter(Boolean).join(`
|
|
236
|
+
`)}],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 dr(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await pr(i),c={...a.variables,...t.variables},u;try{u=Kg(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let l=new Map,d=[`Running workflow: ${a.name}`,""],p=!0;for(let m of u){if(o?.aborted){d.push(`\u26A1 Aborted at step: ${m.id}`),p=!1;break}let h=(m.dependsOn??[]).some(x=>!l.get(x)?.success),y=m.condition??"on_success";if(y==="on_success"&&h){d.push(`\u23ED Skipped ${m.id} (dependency failed)`),l.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(y==="on_failure"&&!h){d.push(`\u23ED Skipped ${m.id} (no failure to handle)`),l.set(m.id,{stepId:m.id,success:!0,output:""});continue}d.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let T=Jg(m.args,c,l);try{let x=await n.invokeTool(m.tool,T,o),f=!x.error;if(l.set(m.id,{stepId:m.id,success:f,output:x.result,error:x.error}),f){let _=x.result.length>200?x.result.slice(0,200)+"...":x.result;d.push(` \u2705 ${_}`)}else d.push(` \u274C ${x.error}`),p=!1}catch(x){let f=x.message;l.set(m.id,{stepId:m.id,success:!1,output:"",error:f}),d.push(` \u274C ${f}`),p=!1}}return d.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:d.join(`
|
|
237
|
+
`)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:l.size,totalSteps:a.steps.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}". Use list, run, or describe.`}],details:{error:"unknown_action"}}}}}}var Yg="sleep",Xg={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 qa(n){return{name:Yg,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(`
|
|
238
|
+
`),parameters:Xg,execute:async(e,t,o)=>{let r=Math.max(1,Math.min(3600,Math.round(t.duration))),s=r*1e3,i=new AbortController,a=()=>i.abort();o?.addEventListener("abort",a,{once:!0}),o?.aborted&&i.abort();try{let c=await n.sleep(s,i.signal),u=[];return c.interrupted?(u.push(`Sleep interrupted after ${c.sleptSeconds}s.`),c.interruptReason&&u.push(`Reason: ${c.interruptReason}`),u.push("Check for new messages or tasks.")):u.push(`Slept for ${c.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:u.join(`
|
|
239
|
+
`)}],details:{...c,requestedSeconds:r}}}finally{o?.removeEventListener("abort",a)}}}}var Qg="tool_search",Zg={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"]},ef=5;function Ja(n){return{name:Qg,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:Zg,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 o=t.query.trim(),r=t.maxResults??ef;if(o.startsWith("select:")){let i=o.slice(7).split(",").map(l=>l.trim()).filter(Boolean),a=[],c=[];if(n.activateTool)for(let l of i)await n.activateTool(l)?a.push(l):c.push(l);else{let l=await n.searchTools(o,{maxResults:r});return Ka(l)}let u=[];return a.length>0&&u.push(`Activated: ${a.join(", ")}. These tools are now available.`),c.length>0&&u.push(`Not found: ${c.join(", ")}.`),{content:[{type:"text",text:u.join(`
|
|
240
|
+
`)}],details:{type:"tool_search",activated:a,notFound:c,mode:"select"}}}let s=await n.searchTools(o,{maxResults:r});return Ka(s)}}}function Ka(n){if(n.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${n.query}". Total deferred tools available: ${n.totalDeferred}.`}],details:{type:"tool_search",query:n.query,matchCount:0,totalDeferred:n.totalDeferred}};let e=[`Found ${n.matches.length} tool(s) matching "${n.query}" (${n.totalDeferred} total deferred):`,""];for(let t of n.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(`
|
|
241
|
+
`)}],details:{type:"tool_search",query:n.query,matchCount:n.matches.length,totalDeferred:n.totalDeferred,matches:n.matches.map(t=>t.name)}}}var tf="image_generate",of={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 Ya(n){return{name:tf,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:of,execute:async(e,t)=>{let o=await n.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}),r=o.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} image${r>1?"s":""}${o.model?` (model: ${o.model})`:""}`}],details:{type:"image_generate",model:o.model,size:o.size,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var nf={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 Xa(n){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:nf,execute:async(e,t)=>{let o=await n.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:o.audioPath,provider:o.provider,voiceCompatible:o.voiceCompatible,mediaUrls:o.mediaUrls}}}}}var rf="video_generate",sf={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 Qa(n){return{name:rf,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:sf,execute:async(e,t)=>{let o=await n.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}),r=o.mediaUrls.length,s=[`Generated ${r} video${r>1?"s":""}`];return o.model&&s.push(`model: ${o.model}`),o.lastFrameUrl&&s.push(`last_frame: ${o.lastFrameUrl}`),o.taskId&&s.push(`task_id: ${o.taskId}`),{content:[{type:"text",text:s.length>1?`${s[0]} (${s.slice(1).join(", ")})`:s[0]}],details:{type:"video_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var af="music_generate",lf={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 Za(n){return{name:af,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:lf,execute:async(e,t)=>{let o=t.lyrics;if(!o&&!t.is_instrumental&&n.generateLyrics)try{o=await n.generateLyrics(t.prompt)}catch{}let r=await n.generateMusic({prompt:t.prompt,purpose:t.purpose,style:t.style,lyrics:o,duration:t.duration,isInstrumental:t.is_instrumental,audioUrl:t.cover_audio_url,audioFormat:t.audio_format}),s=r.mediaUrls.length;return{content:[{type:"text",text:`Generated ${s} audio track${s>1?"s":""}${r.model?` (model: ${r.model})`:""}`}],details:{type:"music_generate",model:r.model,durationMs:r.durationMs,mediaUrls:r.mediaUrls}}}}}var cf="video_edit",uf={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 el(n){return{name:cf,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:uf,execute:async(e,t)=>{if(!t.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let o=await n.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${o.model?` (model: ${o.model})`:""}`}],details:{type:"video_edit",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var df="video_merge",pf={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 tl(n){return{name:df,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:pf,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 o=await n.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 ${o.clipCount} clips \u2192 ${o.durationSec.toFixed(1)}s video`+(t.transition?` (transition: ${t.transition})`:"")}],details:{type:"video_merge",localPath:o.localPath,servePath:o.servePath,durationSec:o.durationSec,clipCount:o.clipCount,mediaUrls:o.mediaUrls}}}}}var mf="video_upscale",gf={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 ol(n){return{name:mf,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:gf,execute:async(e,t)=>{let o=await n.upscaleVideo({video:t.video,targetResolution:t.targetResolution,sharpness:t.sharpness});return{content:[{type:"text",text:`Upscaled to ${o.resolution}${t.sharpness?` (sharpness: ${t.sharpness})`:""}`}],details:{type:"video_upscale",localPath:o.localPath,servePath:o.servePath,resolution:o.resolution,durationSec:o.durationSec,mediaUrls:o.mediaUrls}}}}}var ff="three_d_generate",hf={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 nl(n){return{name:ff,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:hf,execute:async(e,t)=>{let o=await n.generate3D({prompt:t.prompt,imageUrl:t.image_url,outputFormat:t.output_format,seed:t.seed}),r=o.mediaUrls.length;return{content:[{type:"text",text:`Generated ${r} 3D model${r>1?"s":""}${o.model?` (model: ${o.model})`:""}`}],details:{type:"three_d_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var yf={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 rl(n){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:yf,execute:async(e,t)=>{let o=await n.speechToText({audioUrl:t.audio_url,language:t.language}),r=o.transcription.length>200?o.transcription.slice(0,200)+"\u2026":o.transcription;return{content:[{type:"text",text:o.transcription}],details:{type:"stt",model:o.model,durationMs:o.durationMs,transcriptionLength:o.transcription.length,preview:r}}}}}var bf="voice_clone",Tf={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 sl(n){return{name:bf,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:Tf,execute:async(e,t)=>{let o=await n.cloneVoice({text:t.text,sampleAudioUrl:t.sample_audio_url,speed:t.speed});return{content:[{type:"text",text:`Voice cloned and synthesized speech${o.model?` (model: ${o.model})`:""}`}],details:{type:"voice_clone",model:o.model,voiceId:o.voiceId,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var kf="file_upload",xf={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 il(n){return{name:kf,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:xf,execute:async(e,t)=>{let o=await n.uploadFile({filePath:t.file_path,purpose:t.purpose}),r=[`Uploaded "${o.filename}" (${mr(o.bytes)}) via ${o.provider}`];return o.url&&r.push(`URL: ${o.url}`),r.push(`File ID: ${o.fileId}`),{content:[{type:"text",text:r.join(`
|
|
242
|
+
`)}],details:{type:"file_upload",fileId:o.fileId,url:o.url,filename:o.filename,bytes:o.bytes,provider:o.provider}}}}}var vf="file_query",wf={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 al(n){return{name:vf,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:wf,execute:async(e,t)=>{if(t.file_id){let i=await n.queryFile({fileId:t.file_id}),a=[`File: ${i.filename}`,`ID: ${i.id}`,`Size: ${mr(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(`
|
|
243
|
+
`)}],details:{type:"file_query",fileId:i.id}}}let o=Math.min(Math.max(t.limit??10,1),100),r=await n.listFiles({limit:o});if(r.length===0)return{content:[{type:"text",text:"No uploaded files found."}],details:{type:"file_query",count:0}};let s=[`Found ${r.length} file(s):
|
|
244
|
+
`];for(let i of r)s.push(`- ${i.filename} | ID: ${i.id} | ${mr(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
|
|
245
|
+
`)}],details:{type:"file_query",count:r.length}}}}}var _f="file_delete",Cf={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function ll(n){return{name:_f,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:Cf,execute:async(e,t)=>(await n.deleteFile({fileId:t.file_id}),{content:[{type:"text",text:`Deleted file ${t.file_id}`}],details:{type:"file_delete",fileId:t.file_id}})}}function mr(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function cl(n,e){return!n?.webSearch||!n.capabilities.includes("web_search")?e:async(t,o)=>{try{let s=await n.webSearch(t,{maxResults:o?.maxResults});if(o?.allowedDomains?.length){let i=new Set(o.allowedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return i.has(new URL(a.url).hostname.toLowerCase())}catch{return!1}})}if(o?.blockedDomains?.length){let i=new Set(o.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,o)}}var ae,xe={},pl,it={},ml;function gl(n){ml=n}function fl(n,e,t,o){ae=n,xe=e??{},pl=t,it=o??{}}async function ke(n){if(!ae)throw new Error(`No media provider configured for ${n.mediaType}`);let e=it[n.mediaType],t=e?.provider,o=e?.model||n.model;if(!t)throw new Error(`No provider configured for ${n.mediaType}. Please configure a provider in settings.`);let r=await ul(t,o||n.model,n);if(r.ok)return r.result;let s=ae.listMediaModels(n.mediaType),i=[`${t}: ${r.error}`];for(let a of s){if(a.providerId===t||!xe[a.providerId])continue;let u=await ul(a.providerId,a.modelInfo.id,n);if(u.ok)return u.result;i.push(`${a.providerId}/${a.modelInfo.id}: ${u.error}`)}throw new Error(`All media providers failed for ${n.mediaType}:
|
|
246
|
+
`+i.map(a=>` - ${a}`).join(`
|
|
247
|
+
`))}async function ul(n,e,t){let o=ae.getTransport(n);if(!o)return{ok:!1,error:"transport not available"};let r=xe[n];if(!r)return{ok:!1,error:"no API key"};try{let s={...t,model:e},i=await o.generate(s,r);i.billingUnit||(t.mediaType==="tts"&&t.text?(i.billingUnit="per_character",i.billingQuantity=t.text.length):(t.mediaType==="video"||t.mediaType==="music")&&t.duration?(i.billingUnit="per_second",i.billingQuantity=t.duration):(i.billingUnit="per_call",i.billingQuantity=1));let a=i.model??s.model,c=i.billingUnit??"per_call",u=i.billingQuantity??1;return pl?.(a,c,u),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Le(n){if(!ae)return!1;let e=it[n];if(!e)return!1;let t=ae.getTransport(e.provider),o=xe[e.provider];return!!(t&&o)}function gr(n,e){if(!Le(n))return!1;let t=it[n],o=ae.resolveModelById(t.provider,t.model,n);if(!o)return!1;let r=o.modelInfo.mediaCapabilities;return!r||!("operations"in r)||!r.operations?!0:r.operations.includes(e)}function wo(){if(ae)for(let[,n]of Object.entries(it)){if(!n)continue;let e=ae.getTransport(n.provider),t=xe[n.provider];if(e instanceof be&&t)return{id:n.provider}}}var Ve=process.cwd();function le(n){return U.isAbsolute(n)?U.normalize(n):U.resolve(Ve,n)}var Rf=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),hl=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]);function Mf(){return{resolvePath:le,async readFile(n){let e=le(n),t=U.extname(e).toLowerCase();if(hl.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(Rf.has(t)){let r=await A.promises.readFile(e),s=t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg";return{type:"image",base64:r.toString("base64"),mimeType:s}}return{type:"text",text:await A.promises.readFile(e,"utf8")}},validatePath(n){let e=le(n);return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:null}}}function Pf(){return{resolvePath:le,async writeFile(n,e){let t=le(n);await A.promises.mkdir(U.dirname(t),{recursive:!0}),await A.promises.writeFile(t,e,"utf8")}}}function Af(){return{resolvePath:le,async readFile(n){let e=le(n);return A.promises.readFile(e,"utf8")},async writeFile(n,e){let t=le(n);await A.promises.mkdir(U.dirname(t),{recursive:!0}),await A.promises.writeFile(t,e,"utf8")}}}function If(){return{resolvePath:le,async readFile(n){let e=le(n);return A.promises.readFile(e,"utf8")},async writeFile(n,e){let t=le(n);await A.promises.mkdir(U.dirname(t),{recursive:!0}),await A.promises.writeFile(t,e,"utf8")},async deleteFile(n){let e=le(n);await A.promises.unlink(e)},async fileExists(n){let e=le(n);try{return await A.promises.access(e),!0}catch{return!1}}}}function Ef(){return{resolvePath:le,async glob(n,e){let t=e.cwd||Ve,o=e.limit||1e3,r=[],s=!1,i=n.replace(/\\/g,"/").split("/"),a=i.some(l=>l==="**"),c=i[i.length-1]??"*",u=yl(c);try{await fr(t,async l=>{if(r.length>=o)return s=!0,!1;let d=U.basename(l);return u.test(d)&&r.push(l),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(n,e){let t=e.cwd||Ve;try{return await Lf(n,t,e)}catch{return await $f(n,t,e)}}}}function yl(n){let e=n.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(t,o)=>"("+o.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var Of=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function fr(n,e,t,o=0,r=""){if(o>t)return;let s;try{s=await A.promises.readdir(n,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(Of.has(i.name))continue;await fr(U.join(n,i.name),e,t,o+1,a)}else if(i.isFile()&&!await e(a))return}}function Lf(n,e,t){return new Promise((o,r)=>{let s=["--json","--no-heading","--max-columns","500"];t.caseInsensitive&&s.push("-i"),t.contextLines&&s.push("-C",String(t.contextLines)),t.fileGlob&&s.push("-g",t.fileGlob),s.push("--max-count",String(t.headLimit??250)),s.push(n),s.push("."),Sf("rg",s,{cwd:e,maxBuffer:10*1024*1024,timeout:3e4},(i,a)=>{if(i&&!("killed"in i&&i.killed)&&i.code!==1){r(i);return}let c=[];for(let p of a.split(`
|
|
248
|
+
`))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&c.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let u=t.headLimit??250,l=t.offset??0,d=c.slice(l,l+u);o({matches:d,truncated:c.length>l+u})})})}async function $f(n,e,t){let o=new RegExp(n,t.caseInsensitive?"i":""),r=t.headLimit??250,s=t.offset??0,i=t.fileGlob?yl(t.fileGlob):null,a=[],c=!1;return await fr(e,async u=>{if(a.length>=s+r+1)return c=!0,!1;if(i&&!i.test(U.basename(u)))return!0;let l=U.extname(u).toLowerCase();if(hl.has(l))return!0;try{let p=(await A.promises.readFile(U.join(e,u),"utf8")).split(`
|
|
249
|
+
`);for(let m=0;m<p.length;m++)if(o.test(p[m])&&(a.push({path:u,line:m+1,text:p[m].slice(0,500)}),a.length>=s+r+1))return c=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+r),truncated:c}}var dl=!1;function Df(){if(!dl)if(dl=!0,mo()){let n=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";It(rr(n))}else if(process.platform==="win32"){let n=Uf();It(vo(n))}else{let n=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";It(vo(n))}}function Uf(){let n=process.env.QLOGICAGENT_BASH_PATH;if(n&&A.existsSync(n))return n;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],t=process.env.ProgramFiles?U.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let o of e)if(A.existsSync(o))return o;return"bash"}function Nf(){return{async fetchUrl(n){let e=new AbortController,t=setTimeout(()=>e.abort(),3e4);try{let o=await fetch(n.url,{signal:e.signal,headers:{"User-Agent":"Mozilla/5.0 (compatible; QLogicAgent/1.0)",Accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow"});if(!o.ok)return{content:`HTTP ${o.status} ${o.statusText}`};let r=o.headers.get("content-type")??"",s=await o.text();return n.maxChars&&s.length>n.maxChars&&(s=s.slice(0,n.maxChars)),r.includes("html")&&n.extractMode!=="json"&&(s=Ff(s)),{content:s,title:jf(s)}}finally{clearTimeout(t)}}}}function Ff(n){return n.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s{2,}/g," ").trim()}function jf(n){return n.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function Bf(){let n=async(e,t)=>{let o=process.env.SEARXNG_BASE_URL?.trim();if(!o)return{query:e,results:[],totalResults:0};let r=t?.maxResults??10,s=new URL("/search",o);s.searchParams.set("q",e),s.searchParams.set("format","json"),s.searchParams.set("pageno","1");let i=new AbortController,a=setTimeout(()=>i.abort(),15e3);try{let c=await fetch(s.toString(),{signal:i.signal,headers:{Accept:"application/json"}});if(!c.ok)return{query:e,results:[]};let u=await c.json(),l=(u.results??[]).slice(0,r).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:l.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:l.filter(p=>{try{return!d.has(new URL(p.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:l,totalResults:u.number_of_results}}finally{clearTimeout(a)}};return{search:(e,t)=>cl(ml,n)(e,t)}}function Wf(){let n=U.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(r){return U.join(n,"projects",r,".instructions")}function t(r,s){if(!s.endsWith(".md"))throw new Error("Filename must end with .md");if(s.includes(".."))throw new Error("Path traversal not allowed");let i=e(r),a=U.resolve(i,s);if(!a.startsWith(i+U.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function o(r,s){if(!A.existsSync(r))return[];let i=[];for(let a of A.readdirSync(r,{withFileTypes:!0})){let c=U.join(r,a.name);if(a.isDirectory())i.push(...o(c,s));else if(a.isFile()&&a.name.endsWith(".md")){let u=A.statSync(c);i.push({filename:U.relative(s,c).replace(/\\/g,"/"),path:c,size:u.size,updatedAt:u.mtime.toISOString(),content:A.readFileSync(c,"utf-8")})}}return i}return{list(r){let s=e(r);return o(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(r,s){try{let i=t(r,s);if(!A.existsSync(i))return null;let a=A.statSync(i),c=A.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:c}}catch{return null}},write(r,s,i){let a=t(r,s);A.mkdirSync(U.dirname(a),{recursive:!0}),A.writeFileSync(a,i,"utf-8");let c=A.statSync(a);return{filename:s,path:a,size:c.size,updatedAt:c.mtime.toISOString(),content:i}},remove(r,s){try{let i=t(r,s);return A.existsSync(i)?(A.unlinkSync(i),!0):!1}catch{return!1}}}}function Hf(n){n?.workdir&&(Ve=n.workdir),Df(),To(Ve);let e=[];e.push(Ki()),e.push(Ji()),e.push(la({onProgress:n?.onExecProgress,interpretExitCode:(l,d)=>{if(l===127)return"command not found";if(l===126)return"permission denied";if(l===137)return"killed (SIGKILL / OOM)";if(l===143)return"terminated (SIGTERM)";if(l===130)return"interrupted (Ctrl+C)"}}));let t=Mf(),o=Pf(),r=Af(),s=If();e.push(da(t)),e.push(ma(o)),e.push(ga(r)),e.push(cr(s)),e.push(ba(s)),e.push(ya(Ef())),e.push(Ra(Nf())),e.push(Ma(Bf()));let i=Wf();e.push(Pa(i));let a=n?.log??{info:()=>{},warn:()=>{}};e.push(Aa(Fa({log:a}))),e.push(Ha());let c={invokeTool:async(l,d,p)=>{let m=Ae(l);if(!m)return{result:"",error:`Unknown tool: ${l}`};try{let h=await m.execute(`wf_${Date.now()}`,d,p);return{result:h.content.map(T=>T.text??"").join(`
|
|
250
|
+
`),error:h.details?.error}}catch(h){return{result:"",error:h.message}}},getCwd:()=>Ve};e.push(Va(c)),e.push(qa({sleep:(l,d)=>new Promise(p=>{let m=Date.now(),h=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!1})},l),y=()=>{clearTimeout(h),p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!0,interruptReason:"aborted"})};d.addEventListener("abort",y,{once:!0}),d.aborted&&(clearTimeout(h),y())})})),e.push(Ja({searchTools:async(l,d)=>{let p=d?.maxResults??5,m=l.toLowerCase(),h=Ie();return{matches:h.map(T=>{let x=Ae(T),f=`${T} ${x?.description??""} ${x?.searchHint??""}`.toLowerCase();return{name:T,description:x?.description??"",searchHint:x?.searchHint,score:f.includes(m)?1:0}}).filter(T=>T.score>0).slice(0,p),query:l,totalDeferred:h.length}}})),e.push({...Ya({generateImage:async l=>{let d=await ke({mediaType:"image",model:"",prompt:l.prompt,purpose:l.purpose,style:l.style,size:l.size,imageUrl:l.imageUrl,n:l.n,quality:l.quality,seed:l.seed});return{mediaUrls:d.mediaUrls,model:d.model,size:d.size,durationMs:d.durationMs}}}),isEnabled:()=>Le("image")}),e.push({...Xa({textToSpeech:async l=>{let d=await ke({mediaType:"tts",model:"",prompt:"",text:l.text,channel:l.channel,voice:l.voice,speed:l.speed});return{audioPath:"",provider:d.model,mediaUrls:d.mediaUrls}}}),isEnabled:()=>Le("tts")}),e.push({...Qa({generateVideo:async l=>{let d=await ke({mediaType:"video",model:"",prompt:l.prompt,purpose:l.purpose,style:l.style,imageUrl:l.imageUrl,referenceVideos:l.referenceVideos,referenceAudios:l.referenceAudios,generateAudio:l.generateAudio,aspectRatio:l.aspectRatio,duration:l.duration,resolution:l.resolution,fps:l.fps,seed:l.seed,cameraFixed:l.cameraFixed,returnLastFrame:l.returnLastFrame,draft:l.draft,serviceTier:l.serviceTier,callbackUrl:l.callbackUrl,safetyIdentifier:l.safetyIdentifier,executionExpiresAfterSeconds:l.executionExpiresAfterSeconds,videoTools:l.videoTools});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs,lastFrameUrl:d.lastFrameUrl,taskId:d.taskId}}}),isEnabled:()=>Le("video")}),e.push({...Za({generateMusic:async l=>{let d=await ke({mediaType:"music",model:"",prompt:l.prompt,purpose:l.purpose,style:l.style,lyrics:l.lyrics,duration:l.duration,isInstrumental:l.isInstrumental,audioUrl:l.audioUrl,audioFormat:l.audioFormat});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}},generateLyrics:async l=>{let d=it.music;if(!d||!ae)return"";let p=ae.getTransport(d.provider);if(!(p instanceof We))return"";let m=xe[d.provider];return m?p.generateLyrics(l,m):""}}),isEnabled:()=>Le("music")}),e.push({...el({editVideo:async l=>{let d=await ke({mediaType:"video",model:"",prompt:l.prompt,operation:"edit",sourceVideos:l.sourceVideos,referenceImages:l.referenceImages,duration:l.duration,aspectRatio:l.aspectRatio,resolution:l.resolution});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}}}),isEnabled:()=>gr("video","edit")}),e.push({...tl({mergeVideos:async l=>{let d=[`merge ${l.clips.length} clips`];l.transition&&d.push(`transition: ${l.transition}${l.transitionDuration?` (${l.transitionDuration}s)`:""}`),l.subtitles&&d.push(`burn-in subtitles: ${l.subtitles}`),l.bgm&&d.push(`background music: ${l.bgm}${l.bgmVolume!==void 0?` at volume ${l.bgmVolume}`:""}`);let p=await ke({mediaType:"video",model:"",prompt:d.join("; "),operation:"merge",sourceVideos:l.clips.map(m=>m.video),resolution:l.outputResolution,fps:l.outputFps});return{localPath:"",servePath:p.mediaUrls[0]??"",durationSec:(p.durationMs??0)/1e3,clipCount:l.clips.length,mediaUrls:p.mediaUrls}}}),isEnabled:()=>gr("video","merge")}),e.push({...ol({upscaleVideo:async l=>{let d=["upscale"];l.sharpness&&d.push(`sharpness: ${l.sharpness}`);let p=await ke({mediaType:"video",model:"",prompt:d.join(", "),operation:"upscale",sourceVideos:[l.video],resolution:l.targetResolution??"1080p"});return{localPath:"",servePath:p.mediaUrls[0]??"",resolution:l.targetResolution??"1080p",durationSec:(p.durationMs??0)/1e3,mediaUrls:p.mediaUrls}}}),isEnabled:()=>gr("video","upscale")}),e.push({...nl({generate3D:async l=>{let d=await ke({mediaType:"3d",model:"",prompt:l.prompt,imageUrl:l.imageUrl,outputFormat:l.outputFormat,seed:l.seed});return{mediaUrls:d.mediaUrls,model:d.model,durationMs:d.durationMs}}}),isEnabled:()=>Le("3d")}),e.push({...rl({speechToText:async l=>{let d=await ke({mediaType:"stt",model:"",prompt:"",audioUrl:l.audioUrl,metadata:l.language?{language:l.language}:void 0});return{transcription:d.metadata?.transcription??"",model:d.model,durationMs:d.durationMs}}}),isEnabled:()=>Le("stt")}),e.push({...sl({cloneVoice:async l=>{let d=await ke({mediaType:"voice_clone",model:"",prompt:"",text:l.text,audioUrl:l.sampleAudioUrl,speed:l.speed});return{mediaUrls:d.mediaUrls,model:d.model,voiceId:d.metadata?.voiceId,durationMs:d.durationMs}}}),isEnabled:()=>Le("voice_clone")});let u=wo();return e.push({...il({uploadFile:async l=>{if(!u)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine).");let d=le(l.filePath);if(!A.existsSync(d))throw new Error(`File not found: ${d}`);let p=A.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 A.promises.readFile(d),h=U.basename(d),y=new Blob([m]),T=ae.getTransport(u.id),x=xe[u.id];if(!(T instanceof be))throw new Error(`File upload only supported via Volcengine provider. Current: ${u.id}`);let f=await T.uploadFile(y,x,{purpose:l.purpose??"media_reference",filename:h}),_;try{let S=await T.getFile(f.id,x);typeof S.url=="string"&&S.url&&(_=S.url)}catch{}return{fileId:f.id,url:_,filename:h,bytes:p.size,provider:u.id}}}),isEnabled:()=>!!wo()}),e.push({...al({queryFile:async l=>{if(!u)throw new Error("No file API provider available.");let d=ae.getTransport(u.id),p=xe[u.id];if(!(d instanceof be))throw new Error("File query only supported via Volcengine provider.");let m=await d.getFile(l.fileId,p);return{id:String(m.id??l.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 l=>{if(!u)throw new Error("No file API provider available.");let d=ae.getTransport(u.id),p=xe[u.id];if(!(d instanceof be))throw new Error("File list only supported via Volcengine provider.");return((await d.listFiles(p,{limit:l.limit??10})).data??[]).map(y=>({id:String(y.id??""),filename:String(y.filename??""),bytes:Number(y.bytes??0),status:String(y.status??"unknown"),createdAt:y.created_at?String(y.created_at):void 0,url:y.url?String(y.url):void 0}))}}),isEnabled:()=>!!wo()}),e.push({...ll({deleteFile:async l=>{if(!u)throw new Error("No file API provider available.");let d=ae.getTransport(u.id),p=xe[u.id];if(!(d instanceof be))throw new Error("File delete only supported via Volcengine provider.");await d.deleteFile(l.fileId,p)}}),isEnabled:()=>!!wo()}),qi(e),n?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(l=>l.isEnabled?.()!==!1).length} enabled): ${Ie().join(", ")}`),e}var bl=Hf;function hr(n){Ve=n,To(n)}import{spawn as zf}from"node:child_process";import{createInterface as Gf}from"node:readline";var _o=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=zf(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:e,cwd:this.config.cwd,windowsHide:!0}),this.process.on("error",o=>{this.handleProcessError(o)}),this.process.on("exit",o=>{this.handleProcessExit(o)}),this.process.stderr?.on("data",o=>{this.stderrBuffer+=o.toString(),this.stderrBuffer.length>4096&&(this.stderrBuffer=this.stderrBuffer.slice(-4096))}),this.readline=Gf({input:this.process.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.readline.on("line",o=>this.handleLine(o));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,o){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:t??{}},12e4,o)}async listResources(){if(!this.connected)return[];try{return(await this.sendRequest("resources/list",{})).resources??[]}catch{return[]}}async readResource(e){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return(await this.sendRequest("resources/read",{uri:e})).contents??[]}toPortableTools(){let e=Vf(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(o,r,s)=>this.executeAsTool(t.name,r,s)}))}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,t,o){try{let r=await this.callTool(e,t,o);return{content:[{type:"text",text:r.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
|
|
251
|
+
`)||"(no text output)"}],...r.isError?{details:{error:"mcp_tool_error"}}:{}}}catch(r){let s=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`MCP tool error: ${s}`}],details:{error:s}}}}sendRequest(e,t,o=3e4,r){return new Promise((s,i)=>{if(r?.aborted){i(new Error("Aborted"));return}let a=this.nextId++,c={jsonrpc:"2.0",id:a,method:e,params:t},u=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${o}ms`))},o),l=()=>{clearTimeout(u),this.pending.delete(a)};r?.addEventListener("abort",()=>{l(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:d=>{l(),d.error?i(new Error(`MCP error ${d.error.code}: ${d.error.message}`)):s(d.result)},reject:d=>{l(),i(d)}}),this.writeLine(JSON.stringify(c))})}sendNotification(e,t){let o={jsonrpc:"2.0",method:e,params:t};this.writeLine(JSON.stringify(o))}writeLine(e){this.process?.stdin?.writable&&this.process.stdin.write(e+`
|
|
252
|
+
`)}handleLine(e){let t=e.trim();if(!t)return;let o;try{o=JSON.parse(t)}catch{return}if("id"in o&&("result"in o||"error"in o)){let r=o.id,s=this.pending.get(r);s&&s.resolve(o)}else"method"in o&&!("id"in o)&&this.handleNotification(o)}handleNotification(e){e.method==="notifications/tools/list_changed"&&this.refreshTools().then(()=>{this.onToolsChanged?.()}).catch(()=>{})}handleProcessError(e){this.connected=!1;for(let[,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 Vf(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as qf}from"node:crypto";var Co=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,o){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,o)}async listResources(){if(!this.connected)return[];try{return(await this.sendRequest("resources/list",{})).resources??[]}catch{return[]}}async readResource(e){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return(await this.sendRequest("resources/read",{uri:e})).contents??[]}toPortableTools(){return this.toolsCache.map(e=>this.schemaToPortableTool(e))}getCachedTools(){return[...this.toolsCache]}get isConnected(){return this.connected}get info(){return{name:this.serverName,version:this.serverVersion}}setOnToolsChanged(e){this.onToolsChanged=e}async refreshTools(){let e=await this.sendRequest("tools/list",{});this.toolsCache=e.tools??[]}async sendRequest(e,t,o=3e4,r){let s=qf(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,c=setTimeout(()=>a.abort(),o);r&&r.addEventListener("abort",()=>a.abort(),{once:!0});try{let u={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(u["Mcp-Session-Id"]=this.sessionId);let l=await fetch(this.config.url,{method:"POST",headers:u,body:JSON.stringify(i),signal:a.signal}),d=l.headers.get("mcp-session-id");if(d&&(this.sessionId=d),!l.ok)throw new Error(`MCP HTTP error ${l.status}: ${l.statusText}`);if((l.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(l,s);let m=await l.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(c)}}async sendNotification(e,t){let o={jsonrpc:"2.0",method:e,params:t},r={"Content-Type":"application/json",...this.config.headers};this.sessionId&&(r["Mcp-Session-Id"]=this.sessionId),await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(o)}).catch(()=>{})}async parseSSEResponse(e,t){let o=e.body;if(!o)throw new Error("MCP SSE response has no body");let r=o.getReader(),s=new TextDecoder,i="";try{for(;;){let{done:a,value:c}=await r.read();if(a)break;i+=s.decode(c,{stream:!0});let u=i.split(`
|
|
253
|
+
`);i=u.pop()??"";for(let l of u){if(!l.startsWith("data: "))continue;let d=l.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{r.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${Kf(this.config.name)}__${e.name}`,label:`[${this.config.name}] ${e.name}`,description:e.description??`MCP tool from ${this.config.name}`,parameters:e.inputSchema??{type:"object",properties:{}},isConcurrencySafe:!0,isReadOnly:!1,searchHint:`mcp ${this.config.name} ${e.name}`,execute:async(r,s,i)=>{try{let a=await t.callTool(e.name,s,i);return{content:[{type:"text",text:(a.content??[]).filter(l=>l.type==="text"&&l.text).map(l=>l.text).join(`
|
|
254
|
+
`)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let c=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${c}`}],details:{type:"mcp",error:c}}}}}}};function Kf(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var So=class{clients=new Map;injected=!1;log;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}};for(let t of e.servers){if(t.disabled)continue;if((t.type??(t.url?"http":"stdio"))==="http"){if(!t.url){this.log.warn(`[mcp] server "${t.name}" is type "http" but has no url, skipping`);continue}let r={name:t.name,url:t.url,headers:t.headers,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new Co(r))}else{if(!t.command){this.log.warn(`[mcp] server "${t.name}" is type "stdio" but has no command, skipping`);continue}let r={name:t.name,command:t.command,args:t.args,env:t.env,initTimeoutMs:t.initTimeoutMs};this.clients.set(t.name,new _o(r))}}}async connectAll(){let e=Array.from(this.clients.entries()).map(async([t,o])=>{try{await o.connect(),this.log.info(`[mcp] connected to ${t} (${o.info.name} v${o.info.version})`),o.setOnToolsChanged(()=>{this.log.info(`[mcp] tools changed on ${t}, re-injecting`),this.injected&&this.reinjectTools(t,o)})}catch(r){this.log.warn(`[mcp] failed to connect to ${t}: ${r instanceof Error?r.message:r}`)}});await Promise.allSettled(e)}injectTools(){this.injected=!0;for(let[e,t]of this.clients){if(!t.isConnected)continue;let o=t.toPortableTools();Hn(o),this.log.info(`[mcp] injected ${o.length} tools from ${e}`)}}getConnectedServers(){return Array.from(this.clients.entries()).filter(([,e])=>e.isConnected).map(([e])=>e)}getToolCount(){let e=0;for(let t of this.clients.values())t.isConnected&&(e+=t.getCachedTools().length);return e}async disconnectAll(){let e=Array.from(this.clients.values()).map(async t=>{try{await t.disconnect()}catch{}});await Promise.allSettled(e),this.clients.clear(),this.injected=!1}async listResources(e){let t=e?[[e,this.clients.get(e)]].filter(([,r])=>r):Array.from(this.clients.entries());return(await Promise.all(t.map(async([r,s])=>{if(!s?.isConnected||!s.listResources)return[];try{return(await s.listResources()).map(a=>({...a,server:r}))}catch{return this.log.warn(`[mcp] failed to list resources from ${r}`),[]}}))).flat()}async readResource(e,t){let o=this.clients.get(e);if(!o?.isConnected)throw new Error(`MCP server "${e}" is not connected`);if(!o.readResource)throw new Error(`MCP server "${e}" does not support resources`);return o.readResource(t)}reinjectTools(e,t){if(!this.injected)return;let o=`mcp__${e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;for(let s of Ie())s.startsWith(o)&&po(s);let r=t.toPortableTools();Hn(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function yr(n){if(!n||typeof n!="object")return[];let e=n,t=[],o=e.mcpServers??e.servers??e;for(let[r,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){t.push({name:r,type:"http",url:i.url,headers:i.headers&&typeof i.headers=="object"?i.headers:void 0,disabled:i.disabled===!0,initTimeoutMs:typeof i.initTimeoutMs=="number"?i.initTimeoutMs:void 0});continue}typeof i.command=="string"&&t.push({name:r,type:"stdio",command:i.command,args:Array.isArray(i.args)?i.args:void 0,env:i.env&&typeof i.env=="object"?i.env:void 0,disabled:i.disabled===!0})}return t}var Jf={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function Tl(n){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:Jf,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,t)=>{let o=n();if(!o)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let r=await o.listResources(t.server);if(r.length===0)return{content:[{type:"text",text:t.server?`No resources found from MCP server "${t.server}".`:"No resources found from any connected MCP server."}],details:{type:"list_mcp_resources",count:0}};let s=new Map;for(let a of r){let c=s.get(a.server)??[];c.push(a),s.set(a.server,c)}let i=[];for(let[a,c]of s){i.push(`Server: ${a} (${c.length} resources)`);for(let u of c){let l=u.mimeType?` [${u.mimeType}]`:"",d=u.description?` \u2014 ${u.description}`:"";i.push(` ${u.name}: ${u.uri}${l}${d}`)}i.push("")}return{content:[{type:"text",text:i.join(`
|
|
255
|
+
`).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var Yf={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 kl(n){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:Yf,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,t)=>{let o=n();if(!o)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let r=await o.readResource(t.server,t.uri);if(r.length===0)return{content:[{type:"text",text:`Resource "${t.uri}" returned no content.`}],details:{type:"read_mcp_resource",empty:!0}};let s=[];for(let i of r)if(i.text){let a=i.mimeType?` (${i.mimeType})`:"";s.push({type:"text",text:`--- ${i.uri}${a} ---
|
|
247
256
|
${i.text}`})}else if(i.blob){let a=Math.ceil(i.blob.length*3/4/1024);s.push({type:"text",text:`--- ${i.uri} (binary, ~${a}KB, ${i.mimeType??"unknown"}) ---
|
|
248
|
-
[Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${t.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:t.uri,server:t.server,contentCount:r.length}}}catch(r){return{content:[{type:"text",text:`Error reading resource: ${r.message}`}],details:{error:r.message}}}}}}import*as
|
|
249
|
-
`).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let u=St.join(i,c),d=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=St.join(i,`${o}@${d}`);re.existsSync(m)||re.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",u,"-C",m,"--strip-components=1"],{timeout:3e4});try{re.unlinkSync(u)}catch{}let y=St.join(m,"package.json");if(re.existsSync(y))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(h){t.warn(`[marketplace] npm install for ${o} failed: ${h.message}`)}return t.info(`[marketplace] installed ${o}@${d} from npm`),{name:o,version:d,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function Yg(){return Va().plugins.filter(e=>re.existsSync(e.installPath)).map(e=>e.installPath)}async function Xg(o,e){let t=Va(),n=[];for(let r of o.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!Kg(s,o)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(l=>l.source.specifier===r.specifier&&l.source.type===r.type);if(i&&re.existsSync(i.installPath)&&(!r.version||i.version===r.version)){n.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await Jg(r.specifier,r.version,e);break;case"git":case"url":e.warn(`[marketplace] ${r.type} source not yet implemented for "${r.specifier}"`);break}if(a){let l={name:a.name,version:a.version,source:r,installPath:a.installPath,installedAt:new Date().toISOString()};t.plugins=t.plugins.filter(c=>!(c.source.specifier===r.specifier&&c.source.type===r.type)),t.plugins.push(l),n.push(a.installPath)}}return Vg(t),n}function Qg(){let o=Ps();if(!re.existsSync(o))return null;try{return JSON.parse(re.readFileSync(o,"utf-8"))}catch{return null}}async function Ka(o,e){let t=[...o],n=Yg();t.push(...n);let r=Qg();if(r&&r.enabledPlugins.length>0)try{let s=await Xg(r,e),i=new Set(t);for(let a of s)i.has(a)||t.push(a)}catch(s){e.warn(`[marketplace] failed to update plugins: ${s.message}`)}return t}var ho=class{mode;rules;defaultBehavior;compiledPatterns;constructor(e){this.mode=e.mode,this.rules=[...e.rules],this.defaultBehavior=e.defaultBehavior,this.compiledPatterns=this.compileRules(this.rules)}getMode(){return this.mode}setMode(e){this.mode=e}getRules(){return this.rules}getDefaultBehavior(){return this.defaultBehavior}replaceRules(e){this.rules=[...e],this.compiledPatterns=this.compileRules(this.rules)}setDefaultBehavior(e){this.defaultBehavior=e}addRule(e){this.rules.push(e),this.compiledPatterns=this.compileRules(this.rules)}applyUpdate(e){this.addRule({pattern:e.pattern,behavior:e.behavior,reason:e.description,source:"user"})}check(e){let{toolName:t,meta:n}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return{behavior:"deny",message:`Tool "${t}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${t}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:r,regex:s}of this.compiledPatterns)if(s.test(t))return ef(r,e);return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:n?.requiresApproval?{behavior:"ask",message:`Tool "${t}" requires approval`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:n?.isDangerous?{behavior:"ask",message:`Tool "${t}" is marked dangerous`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}:this.mode==="acceptEdits"?/write|edit|create|delete|move|rename|patch/i.test(t)?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:{behavior:"ask",message:`Tool "${t}" needs approval in acceptEdits mode`,toolName:t,input:e.arguments,decisionReason:{type:"mode",mode:"acceptEdits"}}:this.defaultBehavior==="allow"?{behavior:"allow"}:this.defaultBehavior==="deny"?{behavior:"deny",message:`Tool "${t}" denied by default policy`,decisionReason:{type:"other",reason:"default_deny"}}:{behavior:"ask",message:`Tool "${t}" requires approval (default policy)`,toolName:t,input:e.arguments}}compileRules(e){return e.map(t=>({rule:t,regex:Zg(t.pattern)}))}};function or(o){if(!o||typeof o!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=o,t=[];for(let a of["allow","deny","ask"]){let l=e[a];if(Array.isArray(l))for(let c of l)typeof c=="string"&&t.push({pattern:c,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let l=a,c=l.pattern,u=l.behavior??l.action;typeof c=="string"&&typeof u=="string"&&(u==="allow"||u==="deny"||u==="ask")&&t.push({pattern:c,behavior:u,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let n=e.mode,r=typeof n=="string"&&tf(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&of(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function Zg(o){let t=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function ef(o,e){let t={type:"rule",rule:o};return o.behavior==="allow"?{behavior:"allow",decisionReason:t}:o.behavior==="deny"?{behavior:"deny",message:o.reason??`Tool "${e.toolName}" denied by rule "${o.pattern}"`,decisionReason:t}:{behavior:"ask",message:o.reason??`Tool "${e.toolName}" requires approval (rule "${o.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:t}}function tf(o){return o==="default"||o==="bypassPermissions"||o==="acceptEdits"||o==="dontAsk"||o==="plan"}function of(o){return o==="allow"||o==="deny"||o==="ask"}import{randomUUID as df}from"node:crypto";var nf=new Set(["node --version","npm --version","npx --version","pnpm --version","yarn --version","bun --version","deno --version","python --version","python3 --version","pip --version","ruby --version","go version","rustc --version","cargo --version","java -version","javac -version","dotnet --version","gcc --version","g++ --version","clang --version","git --version","docker --version","--help","-h"]),Ja=new Set(["ls","dir","find","fd","locate","which","where","type","cat","head","tail","less","more","bat","wc","file","stat","du","df","tree","exa","eza","grep","rg","ripgrep","ag","ack","fgrep","egrep","git status","git log","git diff","git show","git branch","git tag","git remote","git stash list","git blame","git shortlog","git describe","git rev-parse","git ls-files","git ls-tree","git cat-file","git reflog","ps","top","htop","uptime","uname","hostname","whoami","id","env","printenv","echo","ping","nslookup","dig","host","ifconfig","ip","netstat","ss","npm list","npm ls","npm info","npm view","npm outdated","npm audit","pnpm list","pnpm ls","pnpm outdated","pip list","pip show","pip freeze","cargo tree","npm test","npm run test","npm run build","npm run lint","pnpm test","pnpm run test","pnpm run build","pnpm run lint","yarn test","yarn build","yarn lint","cargo test","cargo build","cargo check","cargo clippy","go test","go build","go vet","make","cmake","pytest","python -m pytest","python3 -m pytest","jest","vitest","mocha","tsc","tsc --noEmit","eslint","prettier","oxlint"]),rf=[/\brm\s+-rf?\s+[/~]/,/\brm\s+-rf?\s+\.\.\//,/\bsudo\b/,/\bsu\s/,/\bchmod\s+777\b/,/\bmkfs\b/,/\bfdisk\b/,/\bdd\s+if=/,/\bsystemctl\s+(start|stop|restart|enable|disable)\b/,/\bservice\s+\S+\s+(start|stop|restart)\b/,/\breg\s+(add|delete)\b/i,/\\Windows\\System32/i,/\/etc\/(passwd|shadow|sudoers|fstab)/,/\bgit\s+push\s+.*--force\b/,/\bgit\s+push\s+-f\b/,/\bcurl\b.*(-H|--header)\s+.*[Aa]uthorization/,/\bwget\b.*--header.*[Aa]uthorization/,/\bcurl\b.*\|\s*(sh|bash|zsh)\b/,/\bwget\b.*-O\s*-\s*\|\s*(sh|bash|zsh)\b/,/\bnpm\s+install\s+-g\b/,/\bpip\s+install\b(?!.*-r\b)(?!.*requirements)/,/\bDROP\s+(DATABASE|TABLE|SCHEMA)\b/i,/\bTRUNCATE\s+TABLE\b/i],Ya=new Set(["npm install","npm i","npm ci","pnpm install","pnpm i","yarn install","yarn","pip install -r","pip install -e","cargo build","cargo install","go mod download","go get","bundle install","composer install","git add","git commit","git stash","git checkout","git switch","git merge","git rebase","git cherry-pick","git pull","git fetch","docker build","docker compose","mkdir","touch","cp"]);function Xa(o,e,t){let n=o.trim();if(!n)return{decision:"allow",reason:"empty command"};let r=qn(n)??Hn(n)??void 0;for(let c of rf)if(c.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${c.source}`,destructiveWarning:r};for(let c of nf)if(n===c||n.startsWith(c+" "))return{decision:"allow",reason:`known safe command: ${c}`,destructiveWarning:r};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return Ja.has(i)||Ja.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&(Ya.has(i)||Ya.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function sf(o){let e=Object.keys(o).sort(),t={};for(let n of e){let r=o[n];typeof r=="string"?t[n]=r.replace(/\s+/g," ").trim():t[n]=r}return JSON.stringify(t)}function nr(o,e){return`${o}::${sf(e)}`}var af=500,yo=class{cache=new Map;get(e,t){let n=nr(e,t),r=this.cache.get(n);if(r)return r.hitCount++,r}set(e,t,n){if(this.cache.size>=af){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=nr(e,t);this.cache.set(r,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(nr(e,t))}clear(){this.cache.clear()}get size(){return this.cache.size}get totalHits(){let e=0;for(let t of this.cache.values())e+=t.hitCount;return e}};var lf=new Set(["read","search","instructions","think","todo","memory","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function Ct(o){return lf.has(o)}var Qa=`You are a security classifier for an AI coding agent. Your job is to decide whether a tool invocation is safe to execute without user confirmation.
|
|
257
|
+
[Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${t.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:t.uri,server:t.server,contentCount:r.length}}}catch(r){return{content:[{type:"text",text:`Error reading resource: ${r.message}`}],details:{error:r.message}}}}}}import*as $e from"node:fs";import*as Ro from"node:path";import{pathToFileURL as Xf}from"node:url";var xl={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var Mo=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(!$e.existsSync(e))continue;let t;try{t=$e.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let o of t){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let r=Ro.join(e,o.name);await this.loadPlugin(o.name,r)}}return this.log.info(`[plugins] loaded ${this.loaded.length} plugin(s): ${this.loaded.map(e=>e.name).join(", ")||"(none)"}`),this.loaded}getPluginSkills(){return this.pluginSkills}getLoaded(){return this.loaded}async refreshActivations(){let e=Date.now();for(let[t,o]of this.activations){if(e-o.lastCheckAt<o.ttlMs)continue;let r;try{r=await o.checkFn()}catch(s){this.log.warn(`[plugins] ${t}: check_fn error: ${s instanceof Error?s.message:s}`),r=o.lastResult}if(o.lastCheckAt=e,r!==o.lastResult){if(o.lastResult=r,r&&!o.active){for(let s of o.tools)ne(s);o.active=!0,this.log.info(`[plugins] ${t}: reactivated (${o.tools.length} tools)`)}else if(!r&&o.active){for(let s of o.tools)po(s.name);for(let s of o.hookUnregisterFns)s();o.active=!1,this.log.info(`[plugins] ${t}: deactivated`)}}}}async loadPlugin(e,t){let o=["index.js","index.mjs"],r=null;for(let y of o){let T=Ro.join(t,y);if($e.existsSync(T)){r=T;break}}if(!r){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,c=[],u=[],l=null,d=6e4,p={},m=Ro.join(t,"config.json");if($e.existsSync(m))try{p=JSON.parse($e.readFileSync(m,"utf8"))}catch{}let h={pluginName:e,registerTool:y=>{ne(y),c.push(y),s++},registerHook:(y,T)=>{let x=xl[y];if(!x){this.log.warn(`[plugins] ${e}: unknown hook phase "${y}"`);return}let f=this.config.hookRegistry.register({point:x,handler:T,label:`plugin:${e}:${y}`,priority:200});u.push(f),i++},registerSkill:y=>{this.pluginSkills.push(y),a++},getConfig:()=>p,setActivationCheck:(y,T)=>{l=y,T!==void 0&&(d=T)}};try{let T=await import(Xf(r).href);if(typeof T.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await T.register(h),l&&this.activations.set(e,{checkFn:l,ttlMs:d,lastCheckAt:Date.now(),lastResult:!0,tools:c,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(y){this.log.warn(`[plugins] ${e}: load error: ${y instanceof Error?y.message:y}`)}}};import*as re from"node:fs";import*as Lt from"node:path";function br(){return Vs()}function vl(){return Lt.join(br(),"installed_plugins.json")}function wl(){let n=vl();if(!re.existsSync(n))return{version:1,plugins:[]};try{return JSON.parse(re.readFileSync(n,"utf-8"))}catch{return{version:1,plugins:[]}}}function Qf(n){let e=br();re.existsSync(e)||re.mkdirSync(e,{recursive:!0}),re.writeFileSync(vl(),JSON.stringify(n,null,2),"utf-8")}function Zf(n,e){return!(e.blocklist?.includes(n)||e.allowlist&&!e.allowlist.includes(n))}async function eh(n,e,t){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(o),i=br(),a=e?`${n}@${e}`:n;try{let{stdout:c}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),u=c.trim().split(`
|
|
258
|
+
`).pop()?.trim();if(!u)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let l=Lt.join(i,u),p=u.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=Lt.join(i,`${n}@${p}`);re.existsSync(m)||re.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",l,"-C",m,"--strip-components=1"],{timeout:3e4});try{re.unlinkSync(l)}catch{}let h=Lt.join(m,"package.json");if(re.existsSync(h))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(y){t.warn(`[marketplace] npm install for ${n} failed: ${y.message}`)}return t.info(`[marketplace] installed ${n}@${p} from npm`),{name:n,version:p,installPath:m}}catch(c){return t.warn(`[marketplace] failed to install ${a} from npm: ${c.message}`),null}}function th(){return wl().plugins.filter(e=>re.existsSync(e.installPath)).map(e=>e.installPath)}async function oh(n,e){let t=wl(),o=[];for(let r of n.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!Zf(s,n)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=t.plugins.find(c=>c.source.specifier===r.specifier&&c.source.type===r.type);if(i&&re.existsSync(i.installPath)&&(!r.version||i.version===r.version)){o.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await eh(r.specifier,r.version,e);break;case"git":case"url":e.warn(`[marketplace] ${r.type} source not yet implemented for "${r.specifier}"`);break}if(a){let c={name:a.name,version:a.version,source:r,installPath:a.installPath,installedAt:new Date().toISOString()};t.plugins=t.plugins.filter(u=>!(u.source.specifier===r.specifier&&u.source.type===r.type)),t.plugins.push(c),o.push(a.installPath)}}return Qf(t),o}function nh(){let n=Ks();if(!re.existsSync(n))return null;try{return JSON.parse(re.readFileSync(n,"utf-8"))}catch{return null}}async function _l(n,e){let t=[...n],o=th();t.push(...o);let r=nh();if(r&&r.enabledPlugins.length>0)try{let s=await oh(r,e),i=new Set(t);for(let a of s)i.has(a)||t.push(a)}catch(s){e.warn(`[marketplace] failed to update plugins: ${s.message}`)}return t}var Po=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:o}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return{behavior:"deny",message:`Tool "${t}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${t}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:r,regex:s}of this.compiledPatterns)if(s.test(t))return sh(r,e);return o?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:o?.requiresApproval?{behavior:"ask",message:`Tool "${t}" requires approval`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:o?.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:rh(t.pattern)}))}};function Tr(n){if(!n||typeof n!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=n,t=[];for(let a of["allow","deny","ask"]){let c=e[a];if(Array.isArray(c))for(let u of c)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 c=a,u=c.pattern,l=c.behavior??c.action;typeof u=="string"&&typeof l=="string"&&(l==="allow"||l==="deny"||l==="ask")&&t.push({pattern:u,behavior:l,reason:typeof c.reason=="string"?c.reason:void 0,source:typeof c.source=="string"?c.source:"config"})}}let o=e.mode,r=typeof o=="string"&&ih(o)?o:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&ah(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function rh(n){let t=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function sh(n,e){let t={type:"rule",rule:n};return n.behavior==="allow"?{behavior:"allow",decisionReason:t}:n.behavior==="deny"?{behavior:"deny",message:n.reason??`Tool "${e.toolName}" denied by rule "${n.pattern}"`,decisionReason:t}:{behavior:"ask",message:n.reason??`Tool "${e.toolName}" requires approval (rule "${n.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:t}}function ih(n){return n==="default"||n==="bypassPermissions"||n==="acceptEdits"||n==="dontAsk"||n==="plan"}function ah(n){return n==="allow"||n==="deny"||n==="ask"}import{randomUUID as fh}from"node:crypto";var lh=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"]),Cl=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"]),ch=[/\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],Sl=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 Rl(n,e,t){let o=n.trim();if(!o)return{decision:"allow",reason:"empty command"};let r=sr(o)??ir(o)??void 0;for(let u of ch)if(u.test(o))return{decision:"deny",reason:`matches dangerous pattern: ${u.source}`,destructiveWarning:r};for(let u of lh)if(o===u||o.startsWith(u+" "))return{decision:"allow",reason:`known safe command: ${u}`,destructiveWarning:r};let s=o.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return Cl.has(i)||Cl.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&(Sl.has(i)||Sl.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function uh(n){let e=Object.keys(n).sort(),t={};for(let o of e){let r=n[o];typeof r=="string"?t[o]=r.replace(/\s+/g," ").trim():t[o]=r}return JSON.stringify(t)}function kr(n,e){return`${n}::${uh(e)}`}var dh=500,Ao=class{cache=new Map;get(e,t){let o=kr(e,t),r=this.cache.get(o);if(r)return r.hitCount++,r}set(e,t,o){if(this.cache.size>=dh){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=kr(e,t);this.cache.set(r,{shouldBlock:o.shouldBlock,reason:o.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(kr(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 ph=new Set(["read","search","instructions","think","todo","memory","skill_list","skill_view","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function $t(n){return ph.has(n)}var Ml=`You are a security classifier for an AI coding agent. Your job is to decide whether a tool invocation is safe to execute without user confirmation.
|
|
250
259
|
|
|
251
260
|
The agent operates in a workspace and has been given permission to use tools autonomously. You must decide if each tool call is SAFE (routine development work) or DANGEROUS (could cause harm, data loss, or unexpected side effects).
|
|
252
261
|
|
|
@@ -268,7 +277,7 @@ DANGEROUS operations (SHOULD be blocked):
|
|
|
268
277
|
- Running commands with sudo/admin privileges
|
|
269
278
|
- Downloading and executing unknown scripts
|
|
270
279
|
|
|
271
|
-
Respond ONLY with XML. No other text.`;async function
|
|
280
|
+
Respond ONLY with XML. No other text.`;async function xr(n,e,t,o){let r=Date.now();if($t(n))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=mh(t),i=gh(n,e),a=`<transcript>
|
|
272
281
|
${s}
|
|
273
282
|
</transcript>
|
|
274
283
|
|
|
@@ -276,7 +285,7 @@ ${s}
|
|
|
276
285
|
${i}
|
|
277
286
|
</action>
|
|
278
287
|
|
|
279
|
-
Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let
|
|
288
|
+
Should this action be blocked? Respond with <block>yes</block> or <block>no</block>. If blocking, add <reason>explanation</reason>.`;try{let c=await o({system:Ml,messages:[{role:"user",content:a}],maxTokens:64,temperature:0,stop:["</reason>"],cacheSystemPrompt:!0}),u=Il(c.text);if(Pl(u)===!1)return{shouldBlock:!1,reason:"classifier: safe",stage:"fast",durationMs:Date.now()-r};let d=`<transcript>
|
|
280
289
|
${s}
|
|
281
290
|
</transcript>
|
|
282
291
|
|
|
@@ -284,50 +293,50 @@ ${s}
|
|
|
284
293
|
${i}
|
|
285
294
|
</action>
|
|
286
295
|
|
|
287
|
-
The fast classifier flagged this action. Review carefully \u2014 is it actually dangerous, or is it safe development work? Consider the project context. Use <thinking> tags to reason, then respond with <block>yes</block> or <block>no</block> and <reason>explanation</reason>.`,
|
|
288
|
-
`)}function
|
|
289
|
-
Arguments: ${
|
|
296
|
+
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 o({system:Ml,messages:[{role:"user",content:d}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=Il(p.text),h=Pl(m),y=Al(m)??Al(u)??"classifier decision";return{shouldBlock:h!==!1,reason:y,stage:"thinking",durationMs:Date.now()-r}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-r}}}function mh(n){return n.slice(-20).map(t=>{let o=t.role==="user"?"User":t.role==="assistant"?"Assistant":"System",r=typeof t.content=="string"?t.content.slice(0,500):JSON.stringify(t.content).slice(0,500);return`${o}: ${r}`}).join(`
|
|
297
|
+
`)}function gh(n,e){let t=JSON.stringify(e,null,0),o=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${n}
|
|
298
|
+
Arguments: ${o}`}function Pl(n){let e=n.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function Al(n){let e=n.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function Il(n){return n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var El={maxConsecutive:3,maxTotal:20};function Ol(){return{consecutiveDenials:0,totalDenials:0}}function vr(n){return{consecutiveDenials:n.consecutiveDenials+1,totalDenials:n.totalDenials+1}}function wr(n){return n.consecutiveDenials===0?n:{...n,consecutiveDenials:0}}function Ll(n){return n.consecutiveDenials>=El.maxConsecutive||n.totalDenials>=El.maxTotal}var hh=12e4,Io=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;unregisterHook=null;toolMetaCache=new Map;classifierCache=new Ao;denialTracking=Ol();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 o=this.toolMetaCache.get(t.toolName),r={toolName:t.toolName,arguments:t.arguments,meta:o?{isReadOnly:o.isReadOnly,isDangerous:o.isDangerous,requiresApproval:o.requiresApproval,parallelSafe:o.parallelSafe}:void 0},s=this.ruleEngine.check(r);return this.handleResult(s,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,o){this.onDenied?.(t,o),this.hookRegistry.invoke("permission.denied",{sessionId:"",turnId:"",approvalId:e,callId:e,toolName:t,decision:"denied",reason:o}).catch(()=>{})}async handleResult(e,t,o,r){if(e.behavior==="allow")return{action:"continue",context:e.updatedInput?{arguments:e.updatedInput}:void 0};if(e.behavior==="deny")return this.fireDenied(t,o,e.message),{action:"abort",reason:e.message};if(e.decisionReason?.type==="tool_check"&&(e.decisionReason.reason==="isDangerous"||e.decisionReason.reason==="requiresApproval")&&this.permissionRole!=="interactive")return this.fireDenied(t,o,`safety check: ${e.message} (${this.permissionRole} cannot override)`),{action:"abort",reason:`Tool "${o}" blocked by safety check (${this.permissionRole} agents cannot override dangerous tool restrictions)`};if((o==="bash"||o==="execute_command"||o==="Bash"||o==="shell")&&r){let u=r.command??r.cmd??"";if(u){let l=Rl(u);if(l.decision==="allow")return{action:"continue"};if(l.decision==="deny")return this.fireDenied(t,o,l.reason),{action:"abort",reason:l.reason}}}if(r){let u=this.classifierCache.get(o,r);if(u)return u.shouldBlock?(this.fireDenied(t,o,`cached: ${u.reason}`),{action:"abort",reason:u.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,o,r);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(o)?.isReadOnly||$t(o)?{action:"continue"}:this.handleWorkerAsk(t,o,r);if(this.ruleEngine.getMode()==="auto"){if($t(o))return{action:"continue"};let u=Ll(this.denialTracking);if(this.classifierLLMCall&&!u)try{let l=this.getRecentMessages?.()??[],d=await xr(o,r??{},l,this.classifierLLMCall);if(r&&this.classifierCache.set(o,r,{shouldBlock:d.shouldBlock,reason:d.reason}),!d.shouldBlock)return this.denialTracking=wr(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:d.reason}}};this.denialTracking=vr(this.denialTracking)}catch{}}let a=fh(),c={approvalId:a,callId:t,toolName:o,arguments:r,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:o}).catch(()=>{});try{let u=await this.requestApproval(c);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:o,decision:u.decision==="approved"?"approved":"denied"}).catch(()=>{}),u.permissionUpdate&&(this.ruleEngine.applyUpdate(u.permissionUpdate),this.onPermissionUpdate?.(u.permissionUpdate)),u.decision==="approved"?{action:"continue",context:u.updatedInput?{arguments:u.updatedInput}:void 0}:(this.fireDenied(t,o,`denied by user (approval ${a})`),{action:"abort",reason:`Tool "${o}" denied by user`})}catch{return this.fireDenied(t,o,`approval timeout or error (approval ${a})`),{action:"abort",reason:`Tool "${o}" \u2014 approval timed out`}}}async handleWorkerAsk(e,t,o){if($t(t))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await xr(t,o??{},r,this.classifierLLMCall);return o&&this.classifierCache.set(t,o,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=vr(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=wr(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,o)=>{let r=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),o(new Error("Approval timed out"))},hh);this.pendingApprovals.set(e.approvalId,{resolve:t,reject:o,timeoutId:r}),this.onRequestApproval(e).then(s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),t(s))},s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),o(s))})})}clearClassifierCache(){this.classifierCache.clear(),this.denialTracking={consecutiveDenials:0,totalDenials:0}}cancelAllPending(){this.classifierCache.clear();for(let[e,t]of this.pendingApprovals)clearTimeout(t.timeoutId),t.reject(new Error("Permission checker destroyed")),this.pendingApprovals.delete(e)}};var yh="skill_invoke",bh={type:"object",properties:{skill:{type:"string",description:"Name of the skill to invoke. Use skill_list to see available skills."},args:{type:"string",description:"Optional arguments or context to pass to the skill. This is included in the skill's system prompt."}},required:["skill"]};function $l(n){return{name:yh,label:"Invoke Skill",description:Th(n),parameters:bh,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke run execute command",execute:async(e,t,o)=>{let{skill:r,args:s}=t,i=await n.readSkillContent(r);if(!i){let u=n.listSkills().map(l=>l.name).join(", ");return{content:[{type:"text",text:`Skill "${r}" not found. Available skills: ${u||"(none)"}`}]}}if(n.executeSkillSubturn)try{return{content:[{type:"text",text:await n.executeSkillSubturn(r,i,s,o)}],details:{skillName:r,mode:"subturn"}}}catch(u){let l=u instanceof Error?u.message:String(u);return{content:[{type:"text",text:`Skill execution error: ${l}`}],details:{error:l,skillName:r}}}let a=`## Skill: ${r}
|
|
290
299
|
|
|
291
|
-
`,
|
|
300
|
+
`,c=s?`
|
|
292
301
|
|
|
293
302
|
### User Context
|
|
294
303
|
${s}`:"";return{content:[{type:"text",text:`${a}Follow these instructions:
|
|
295
304
|
|
|
296
|
-
${i}${
|
|
305
|
+
${i}${c}`}],details:{skillName:r,mode:"inline"}}}}}function Th(n){let e=n.listSkills(),t="Invoke a specialized skill to handle a specific task. Skills provide domain-specific instructions and workflows.";if(e.length===0)return t;let o=e.slice(0,50).map(r=>`- ${r.name}: ${r.description??"(no description)"}`).join(`
|
|
297
306
|
`);return`${t}
|
|
298
307
|
|
|
299
308
|
Available skills:
|
|
300
|
-
${
|
|
301
|
-
`)}],details:{type:"skill_list",count:
|
|
302
|
-
`)}],details:{type:"skill_view",name:
|
|
309
|
+
${o}`}var kh="skill_list",xh={type:"object",properties:{category:{type:"string",description:"Filter skills by category (e.g. 'devops', 'mlops'). Omit to list all."}},required:[]};function Dl(n){return{name:kh,label:"List Skills",description:"List all available skills (reusable workflows/knowledge packages). Returns skill names, descriptions, and categories. Use skill_view to see full skill content.",parameters:xh,execute:async(e,t)=>{let o=await n.listSkills(t.category);if(o.skills.length===0)return{content:[{type:"text",text:t.category?`No skills found in category "${t.category}".`:"No skills available."}],details:{type:"skill_list",count:0}};let r=[`Available skills (${o.skills.length}):`];o.categories.length>0&&r.push(`Categories: ${o.categories.join(", ")}`),r.push("");for(let s of o.skills){let i=s.category?` [${s.category}]`:"",a=s.version?` (v${s.version})`:"";r.push(`- **${s.name}**${a}${i}: ${s.description}`)}return r.push(""),r.push("Use skill_view(name) to see full skill content."),{content:[{type:"text",text:r.join(`
|
|
310
|
+
`)}],details:{type:"skill_list",count:o.skills.length,categories:o.categories}}}}}var vh="skill_view",wh={type:"object",properties:{name:{type:"string",description:"Skill name to view (e.g. 'code-review', 'deploy-ecs')."},filePath:{type:"string",description:"Optional: view a specific file within the skill (e.g. 'references/api.md'). Omit to view the main SKILL.md."}},required:["name"]};function Ul(n){return{name:vh,label:"View Skill",description:"View the full content of a skill (instructions, configuration, reference files). Use skill_list to discover available skills first.",parameters:wh,execute:async(e,t)=>{if(!t.name||t.name.trim().length===0)return{content:[{type:"text",text:"Error: skill name is required."}],details:{type:"skill_view",error:"empty_name"}};let o=await n.viewSkill(t.name.trim(),t.filePath);if(!o)return{content:[{type:"text",text:`Skill "${t.name}" not found. Use skill_list to see available skills.`}],details:{type:"skill_view",error:"not_found",name:t.name}};let r=[];return t.filePath?r.push(`## ${o.name} / ${t.filePath}`):(r.push(`## Skill: ${o.name}`),o.tags&&o.tags.length>0&&r.push(`Tags: ${o.tags.join(", ")}`),o.referenceFiles&&o.referenceFiles.length>0&&r.push(`Reference files: ${o.referenceFiles.join(", ")}`)),r.push(""),r.push(o.content),{content:[{type:"text",text:r.join(`
|
|
311
|
+
`)}],details:{type:"skill_view",name:o.name,filePath:t.filePath,referenceFiles:o.referenceFiles}}}}}var _h="skill_manage",Ch={type:"object",properties:{action:{type:"string",enum:["create","edit","patch","delete","write_file","remove_file"],description:"Action to perform: create (new skill), edit (overwrite SKILL.md), patch (find/replace in SKILL.md), delete (remove skill), write_file (add/overwrite supporting file), remove_file (delete supporting file)."},name:{type:"string",description:"Skill name (lowercase, max 64 chars, kebab-case: letters, digits, hyphens)."},content:{type:"string",description:"Full SKILL.md content (YAML frontmatter + body). Required for create/edit. Max 100,000 chars. Must include ---\\nname: ...\\ndescription: ...\\n--- header."},category:{type:"string",description:"Category/domain (e.g. 'devops', 'mlops'). Used by create to organize skills."},filePath:{type:"string",description:"Path within the skill for write_file/remove_file. Must be in references/, templates/, scripts/, or assets/ subdirectory."},fileContent:{type:"string",description:"Content for write_file action. Max 1 MiB."},oldString:{type:"string",description:"Text to find for patch action (must match uniquely in SKILL.md)."},newString:{type:"string",description:"Replacement text for patch action (can be empty to delete)."}},required:["action","name"]},Sh=/^[a-z0-9][a-z0-9._-]{0,63}$/,Nl=1e5,Rh=1048576,Eo=["references/","templates/","scripts/","assets/"];function Fl(n){return{name:_h,label:"Manage Skills",description:"Create, edit, patch, or delete skills. Skills are reusable workflows/knowledge packages that can be discovered and invoked. Supports managing supporting files (references, templates).",parameters:Ch,execute:async(e,t)=>{let o=n.validateName?n.validateName(t.name):Mh(t.name);if(o)return{content:[{type:"text",text:`Error: ${o}`}],details:{type:"skill_manage",error:"invalid_name"}};let r=Ph(t);if(r)return{content:[{type:"text",text:`Error: ${r}`}],details:{type:"skill_manage",error:"validation_failed"}};let s=await n.manageSkill(t);return{content:[{type:"text",text:s.message}],details:{type:"skill_manage",action:t.action,name:t.name,success:s.success,path:s.path}}}}}function Mh(n){return n?Sh.test(n)?null:"name must be lowercase, start with letter/digit, contain only letters, digits, hyphens, dots, underscores (max 64 chars).":"name is required."}function Ph(n){switch(n.action){case"create":case"edit":if(!n.content)return`content is required for ${n.action}.`;if(n.content.length>Nl)return`content exceeds max length (${Nl} chars).`;if(!n.content.includes("---"))return"content must include YAML frontmatter (--- delimiters).";break;case"patch":if(!n.oldString)return"oldString is required for patch.";if(n.newString===void 0)return"newString is required for patch (can be empty to delete).";break;case"write_file":if(!n.filePath)return"filePath is required for write_file.";if(!n.fileContent)return"fileContent is required for write_file.";if(n.fileContent.length>Rh)return"fileContent exceeds max length (1 MiB).";if(!Eo.some(e=>n.filePath.startsWith(e)))return`filePath must be in one of: ${Eo.join(", ")}`;if(n.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"remove_file":if(!n.filePath)return"filePath is required for remove_file.";if(!Eo.some(e=>n.filePath.startsWith(e)))return`filePath must be in one of: ${Eo.join(", ")}`;if(n.filePath.includes(".."))return"filePath must not contain path traversal (..).";break;case"delete":break;default:return`unknown action: ${n.action}`}return null}var Ah="agent",jl=["general","explore","plan","code","research","verify"],Ih={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
|
|
303
312
|
- general: Full tool access, any task
|
|
304
313
|
- explore: Read-only codebase exploration (search, read, analyze)
|
|
305
314
|
- plan: Planning mode (explore + produce plan, no writes)
|
|
306
315
|
- code: Coding agent with full tool access
|
|
307
316
|
- research: Web research and information gathering
|
|
308
|
-
- verify: Run tests, check builds, validate changes`},prompt:{type:"string",description:"Detailed task for the sub-agent. The sub-agent shares your conversation history as context (prompt cache shared). Be specific about what information to return in the final response."},description:{type:"string",description:"Short description (3-7 words) for status tracking."},maxTurns:{type:"number",description:"Max turns for the sub-agent. Defaults: general=200, explore=50, plan=80, code=200, research=30, verify=40."},background:{type:"boolean",description:"If true, runs in background and returns a task_id. Poll with task tool. Default: false."}},required:["agent","prompt"],additionalProperties:!1},
|
|
317
|
+
- 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},Bl=4;function Wl(n){return{name:Ah,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:Ih,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(!jl.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${jl.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let o=n.currentForkDepth??0;if(o>=Bl)return{content:[{type:"text",text:`Error: maximum fork depth (${Bl}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:o}};try{let r=await n.forkAgent({agent:t.agent,prompt:t.prompt.trim(),description:t.description,maxTurns:t.maxTurns,background:t.background,abortSignal:n.abortSignal});if(t.background&&r.status==="running")return{content:[{type:"text",text:`Sub-agent "${t.agent}" started in background.
|
|
309
318
|
Agent ID: ${r.agentId}
|
|
310
319
|
Use task tool with this ID to check status and get output.`}],details:{type:"agent",agentId:r.agentId,status:"running",background:!0}};if(r.status==="failed")return{content:[{type:"text",text:`Sub-agent failed: ${r.error||"unknown error"}`}],details:{type:"agent",agentId:r.agentId,status:"failed",error:r.error}};let s=r.output||"(sub-agent returned no output)",i=r.maxTurnsReached?`
|
|
311
320
|
|
|
312
|
-
[Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:r.agentId,status:"completed",tokensUsed:r.tokensUsed,maxTurnsReached:r.maxTurnsReached}}}catch(r){let s=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}var
|
|
321
|
+
[Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:r.agentId,status:"completed",tokensUsed:r.tokensUsed,maxTurnsReached:r.maxTurnsReached}}}catch(r){let s=r instanceof Error?r.message:String(r);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}var Eh="config",Oh={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
|
|
313
322
|
- get: Read a config setting
|
|
314
323
|
- set: Write a config setting
|
|
315
324
|
- list: List all available settings
|
|
316
|
-
- reset: Reset a setting to default`},key:{type:"string",description:"Config key path (e.g. 'model', 'language', 'theme', 'permissions.defaultMode'). Required for get/set/reset."},value:{description:"Value to set. Type depends on the setting. Required for 'set' action."}},required:["action"]},
|
|
317
|
-
`)}],details:{type:"config",action:"get",key:t.key,value:r.value}}}case"set":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for set."}],details:{type:"config",error:"missing_key"}};if(t.value===void 0)return{content:[{type:"text",text:"Error: value is required for set."}],details:{type:"config",error:"missing_value"}};if(
|
|
318
|
-
`)}],details:{type:"config",action:"list",count:
|
|
325
|
+
- 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"]},Dt=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Hl(n){return{name:Eh,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:Oh,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(n.isValidKey&&!n.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 o=await n.getConfig(t.key);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"config",error:o.error}};let r=o.setting,s=[`${r.key} = ${JSON.stringify(r.value)}`,` Type: ${r.type}${r.options?` (${r.options.join(" | ")})`:""}`,` ${r.description}`];return r.readOnly&&s.push(" \u26A0\uFE0F Read-only (cannot be changed)"),{content:[{type:"text",text:s.join(`
|
|
326
|
+
`)}],details:{type:"config",action:"get",key:t.key,value:r.value}}}case"set":{if(!t.key)return{content:[{type:"text",text:"Error: key is required for set."}],details:{type:"config",error:"missing_key"}};if(t.value===void 0)return{content:[{type:"text",text:"Error: value is required for set."}],details:{type:"config",error:"missing_value"}};if(Dt.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(n.isValidKey&&!n.isValidKey(t.key))return{content:[{type:"text",text:`Error: unknown config key "${t.key}".`}],details:{type:"config",error:"unknown_key"}};let o=await n.setConfig(t.key,t.value);return o.success?{content:[{type:"text",text:`Updated "${t.key}": ${JSON.stringify(o.previousValue)} \u2192 ${JSON.stringify(t.value)}`}],details:{type:"config",action:"set",key:t.key,previousValue:o.previousValue,newValue:t.value}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"config",error:o.error}}}case"list":{let o=await n.listConfig();if(!o.settings||o.settings.length===0)return{content:[{type:"text",text:"No config settings available."}],details:{type:"config",action:"list",count:0}};let r=[`Available settings (${o.settings.length}):`,""];for(let s of o.settings){let i=s.readOnly?" [read-only]":"",a=JSON.stringify(s.value);r.push(` ${s.key} = ${a}${i}`),r.push(` ${s.description}`)}return{content:[{type:"text",text:r.join(`
|
|
327
|
+
`)}],details:{type:"config",action:"list",count:o.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(Dt.includes(t.key))return{content:[{type:"text",text:`Error: "${t.key}" cannot be reset (security-critical).`}],details:{type:"config",error:"readonly_key"}};let o=await n.resetConfig(t.key);return o.success?{content:[{type:"text",text:`Reset "${t.key}" to default: ${JSON.stringify(o.setting?.value)}`}],details:{type:"config",action:"reset",key:t.key,value:o.setting?.value}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"config",error:o.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"config",error:"unknown_action"}}}}}}var Lh="cron",$h={type:"object",properties:{action:{type:"string",enum:["create","list","get","update","delete","pause","resume","trigger"],description:"CRUD action: create/list/get/update/delete/pause/resume/trigger."},jobId:{type:"string",description:"Job ID. Required for get/update/delete/pause/resume/trigger."},prompt:{type:"string",description:"Task prompt to execute on schedule. Required for create."},schedule:{type:"string",description:`Schedule expression. Supports:
|
|
319
328
|
- Cron: '0 9 * * *' (every day at 9am)
|
|
320
329
|
- Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
|
|
321
|
-
Required for create.`},name:{type:"string",description:"Human-readable job name."},repeat:{type:"number",description:"Number of times to repeat (null = infinite). Default: null."},allowedTools:{type:"array",items:{type:"string"},description:"Tools the scheduled task is allowed to use."},enabled:{type:"boolean",description:"Whether the job is enabled (for update)."}},required:["action"]},
|
|
322
|
-
`)}],details:{type:"cron",action:"list",count:
|
|
323
|
-
${
|
|
324
|
-
`)}var
|
|
325
|
-
`),parameters:
|
|
326
|
-
${i.map(
|
|
327
|
-
`)}`}],details:{action:
|
|
328
|
-
`)}],details:{type:"team",action:"create",teamName:
|
|
329
|
-
`)}],details:{type:"team",action:"list",count:
|
|
330
|
-
`)}],details:{type:"team",action:"status",teamName:r.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var
|
|
330
|
+
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"]},zl=50;function Gl(n){return{name:Lh,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:$h,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(n.validateSchedule){let s=n.validateSchedule(t.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let o=await n.listJobs();if(o.jobs&&o.jobs.length>=zl)return{content:[{type:"text",text:`Error: maximum ${zl} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let r=await n.createJob({prompt:t.prompt,schedule:t.schedule,name:t.name,repeat:t.repeat,allowedTools:t.allowedTools});return r.success?{content:[{type:"text",text:_r(r.job)}],details:{type:"cron",action:"create",jobId:r.job.id}}:{content:[{type:"text",text:`Error: ${r.error}`}],details:{type:"cron",error:r.error}}}case"list":{let o=await n.listJobs();if(!o.jobs||o.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let r=[`Scheduled jobs (${o.jobs.length}):`,""];for(let s of o.jobs)r.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:r.join(`
|
|
331
|
+
`)}],details:{type:"cron",action:"list",count:o.jobs.length}}}case"get":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await n.getJob(t.jobId);return o.success?{content:[{type:"text",text:_r(o.job)}],details:{type:"cron",action:"get",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"update":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o={};t.prompt!==void 0&&(o.prompt=t.prompt),t.schedule!==void 0&&(o.schedule=t.schedule),t.name!==void 0&&(o.name=t.name),t.enabled!==void 0&&(o.enabled=t.enabled),t.repeat!==void 0&&(o.repeat=t.repeat),t.allowedTools!==void 0&&(o.allowedTools=t.allowedTools);let r=await n.updateJob(t.jobId,o);return r.success?{content:[{type:"text",text:`Job updated.
|
|
332
|
+
${_r(r.job)}`}],details:{type:"cron",action:"update",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${r.error}`}],details:{type:"cron",error:r.error}}}case"delete":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await n.deleteJob(t.jobId);return o.success?{content:[{type:"text",text:`Job ${t.jobId} deleted.`}],details:{type:"cron",action:"delete",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"pause":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await n.pauseJob(t.jobId);return o.success?{content:[{type:"text",text:`Job ${t.jobId} paused.`}],details:{type:"cron",action:"pause",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"resume":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await n.resumeJob(t.jobId);return o.success?{content:[{type:"text",text:`Job ${t.jobId} resumed.`}],details:{type:"cron",action:"resume",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"trigger":{if(!t.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let o=await n.triggerJob(t.jobId);return o.success?{content:[{type:"text",text:`Job ${t.jobId} triggered (running now).`}],details:{type:"cron",action:"trigger",jobId:t.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"cron",error:"unknown_action"}}}}}}function _r(n){let e=[`Job: ${n.name||n.id}`,`ID: ${n.id}`,`Schedule: ${n.scheduleDisplay} (${n.schedule})`,`State: ${n.state}`,`Repeat: ${n.repeat.times===null?"infinite":`${n.repeat.completed}/${n.repeat.times}`}`];return n.nextRunAt&&e.push(`Next run: ${n.nextRunAt}`),n.lastRunAt&&e.push(`Last run: ${n.lastRunAt} (${n.lastStatus||"unknown"})`),e.push(`Prompt: ${n.prompt.slice(0,100)}${n.prompt.length>100?"...":""}`),e.join(`
|
|
333
|
+
`)}var Dh="monitor",Uh={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 Vl(n){return{name:Dh,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(`
|
|
334
|
+
`),parameters:Uh,execute:async(e,t)=>{let{action:o}=t;if(o==="list"){let i=await n.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:o,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
|
|
335
|
+
${i.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.eventCount}, timeout: ${c.timeoutSeconds}s)`).join(`
|
|
336
|
+
`)}`}],details:{action:o,monitors:i}}}if(!t.monitorId)return{content:[{type:"text",text:"Error: monitorId is required for start/stop."}],details:{action:o,success:!1,error:"missing_monitor_id"}};if(o==="stop"){let i=await n.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:o,success:!1,error:"missing_source_or_target"}};let r=await n.startMonitor({monitorId:t.monitorId,source:t.source,target:t.target,conditions:t.conditions??[],timeoutSeconds:t.timeoutSeconds??3600});return{content:[{type:"text",text:r.success?`Monitor "${t.monitorId}" started: watching ${t.source} "${t.target}".`:`Failed to start monitor: ${r.error??"unknown"}`}],details:{...r}}}}}var Nh="team",Fh={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 ql(n){return{name:Nh,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:Fh,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 o=await n.createTeam({teamName:t.teamName,description:t.description,members:t.members});if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"team",error:o.error}};let r=[`Team "${o.team.name}" created.`,`Lead: ${o.team.leadId}`,`Members: ${o.team.members.length}`];for(let s of o.team.members)r.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:r.join(`
|
|
337
|
+
`)}],details:{type:"team",action:"create",teamName:o.team.name}}}case"delete":{if(!t.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let o=await n.deleteTeam(t.teamName);return o.success?{content:[{type:"text",text:`Team "${t.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:t.teamName}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"team",error:o.error}}}case"list":{let o=await n.listTeams();if(!o.teams||o.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let r=[`Active teams (${o.teams.length}):`,""];for(let s of o.teams)r.push(`- **${s.name}**: ${s.description||"(no description)"} \u2014 ${s.members.length} members`);return{content:[{type:"text",text:r.join(`
|
|
338
|
+
`)}],details:{type:"team",action:"list",count:o.teams.length}}}case"status":{if(!t.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let o=await n.getTeamStatus(t.teamName);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"team",error:o.error}};let r=o.team,s=[`Team: ${r.name}`,`Description: ${r.description||"\u2014"}`,`Lead: ${r.leadId}`,`Created: ${r.createdAt}`,"",`Members (${r.members.length}):`];for(let i of r.members){let a=i.tools?` [tools: ${i.tools.join(", ")}]`:"";s.push(` - ${i.name} (${i.role})${a}`)}return{content:[{type:"text",text:s.join(`
|
|
339
|
+
`)}],details:{type:"team",action:"status",teamName:r.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}var Bh="mcp",Wh={type:"object",properties:{action:{type:"string",enum:["list_servers","list_tools","call_tool","list_resources","read_resource","list_prompts","get_prompt","authenticate","manage_server"],description:`MCP action:
|
|
331
340
|
- list_servers: List configured MCP servers, their status and capabilities
|
|
332
341
|
- list_tools: List tools provided by a specific server
|
|
333
342
|
- call_tool: Execute a tool on an MCP server
|
|
@@ -336,14 +345,14 @@ ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.
|
|
|
336
345
|
- list_prompts: List prompts available from a server
|
|
337
346
|
- get_prompt: Get a specific prompt with arguments
|
|
338
347
|
- authenticate: Initiate OAuth authentication with a server
|
|
339
|
-
- manage_server: Add, remove, restart, or check server status`},server:{type:"string",description:"MCP server name. Required for all actions except list_servers."},toolName:{type:"string",description:"Tool name on the MCP server. Required for call_tool."},arguments:{type:"object",description:"Arguments for the tool call or prompt. Used with call_tool and get_prompt."},uri:{type:"string",description:"Resource URI. Required for read_resource."},promptName:{type:"string",description:"Prompt name. Required for get_prompt."},manageAction:{type:"string",enum:["add","remove","restart","health_check","enable","disable"],description:"Sub-action for manage_server."},config:{type:"object",description:"Server configuration. Required for manage_server add."}},required:["action"]};function
|
|
348
|
+
- 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 Kl(n){return{name:Bh,label:"MCP",description:`Interact with external MCP (Model Context Protocol) servers. Discover and call tools, read resources, get prompts, manage servers, and handle authentication. MCP servers extend agent capabilities with external integrations (databases, APIs, code analysis, custom tools).
|
|
340
349
|
|
|
341
|
-
Dynamic tools: When MCP servers are connected, their tools also appear as individual entries in the tool list (prefixed mcp__server__tool) for direct invocation without going through this management tool.`,parameters:
|
|
342
|
-
`)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!t.server)return X("server is required for list_tools.");let r=await
|
|
343
|
-
`)}],details:{type:"mcp",action:"list_tools",server:t.server,count:r.length}}}case"call_tool":{if(!t.server)return X("server is required for call_tool.");if(!t.toolName)return X("toolName is required for call_tool.");let r=await
|
|
344
|
-
`)}],details:{type:"mcp",action:"list_resources",count:r.length,server:t.server}}}case"read_resource":{if(!t.server)return X("server is required for read_resource.");if(!t.uri)return X("uri is required for read_resource.");let r=await
|
|
345
|
-
`)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:r.length}}}case"get_prompt":{if(!t.server)return X("server is required for get_prompt.");if(!t.promptName)return X("promptName is required for get_prompt.");if(!
|
|
346
|
-
`)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return X("server is required for authenticate.");let r=await
|
|
350
|
+
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:Wh,shouldDefer:!0,execute:async(e,t,o)=>{switch(t.action){case"list_servers":{let r=await n.listServers();if(r.length===0)return{content:[{type:"text",text:"No MCP servers configured. Use manage_server action to add one."}],details:{type:"mcp",action:"list_servers",count:0}};let s=[`MCP Servers (${r.length}):`,""];for(let i of r){let a=Hh(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let c=[];i.capabilities.tools?.listChanged&&c.push("tools/listChanged"),i.capabilities.resources?.subscribe&&c.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&c.push("prompts/listChanged"),c.length>0&&s.push(` Capabilities: ${c.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
|
|
351
|
+
`)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!t.server)return X("server is required for list_tools.");let r=await n.listTools(t.server);if(r.length===0)return{content:[{type:"text",text:`No tools available from server "${t.server}".`}],details:{type:"mcp",action:"list_tools",server:t.server,count:0}};let s=[`Tools from "${t.server}" (${r.length}):`,""];for(let i of r){let a=zh(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(`
|
|
352
|
+
`)}],details:{type:"mcp",action:"list_tools",server:t.server,count:r.length}}}case"call_tool":{if(!t.server)return X("server is required for call_tool.");if(!t.toolName)return X("toolName is required for call_tool.");let r=await n.callTool(t.server,t.toolName,t.arguments,o);return!r.success||r.isError?{content:[{type:"text",text:`MCP tool error (${t.server}/${t.toolName}): ${r.error||r.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!1}}:r.contentBlocks&&r.contentBlocks.length>0?{content:r.contentBlocks.map(i=>i.type==="image"&&i.data?{type:"image",data:i.data,mimeType:i.mimeType}:{type:"text",text:i.text||""}),details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!0}}:{content:[{type:"text",text:r.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:t.server,toolName:t.toolName,success:!0}}}case"list_resources":{let r=await n.listResources(t.server);if(r.length===0)return{content:[{type:"text",text:t.server?`No resources from "${t.server}".`:"No MCP resources available."}],details:{type:"mcp",action:"list_resources",count:0}};let s=[`MCP Resources (${r.length}):`,""];for(let i of r)s.push(`- **${i.name}** \`${i.uri}\`${i.mimeType?` [${i.mimeType}]`:""}`),i.description&&s.push(` ${i.description}`),i.server&&s.push(` Server: ${i.server}`);return{content:[{type:"text",text:s.join(`
|
|
353
|
+
`)}],details:{type:"mcp",action:"list_resources",count:r.length,server:t.server}}}case"read_resource":{if(!t.server)return X("server is required for read_resource.");if(!t.uri)return X("uri is required for read_resource.");let r=await n.readResource(t.server,t.uri);if(r.length===0)return{content:[{type:"text",text:"Resource returned no content."}],details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}};let s=[];for(let i of r)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${Gh(i.blobSize)})`:""}]`}):i.text&&s.push({type:"text",text:i.text});return s.length===0&&s.push({type:"text",text:"(empty content)"}),{content:s,details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}}}case"list_prompts":{if(!t.server)return X("server is required for list_prompts.");if(!n.listPrompts)return X("Prompt listing not supported by the current MCP host.");let r=await n.listPrompts(t.server);if(r.length===0)return{content:[{type:"text",text:`No prompts available from "${t.server}".`}],details:{type:"mcp",action:"list_prompts",server:t.server,count:0}};let s=[`Prompts from "${t.server}" (${r.length}):`,""];for(let i of r)if(s.push(`- **${i.name}**${i.description?`: ${i.description}`:""}`),i.arguments&&i.arguments.length>0){let a=i.arguments.map(c=>`${c.name}${c.required?" (required)":""}${c.description?`: ${c.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
|
|
354
|
+
`)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:r.length}}}case"get_prompt":{if(!t.server)return X("server is required for get_prompt.");if(!t.promptName)return X("promptName is required for get_prompt.");if(!n.getPrompt)return X("Prompt retrieval not supported by the current MCP host.");let r=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,c])=>[a,String(c)])):void 0,s=await n.getPrompt(t.server,t.promptName,r),i=[];s.description&&i.push(`> ${s.description}`,"");for(let a of s.messages)i.push(`**[${a.role}]:**`),a.content.type==="text"?i.push(a.content.text):a.content.type==="resource"?(i.push(`[Resource: ${a.content.resource.uri}]`),a.content.resource.text&&i.push(a.content.resource.text)):a.content.type==="image"&&i.push("[Image content]"),i.push("");return{content:[{type:"text",text:i.join(`
|
|
355
|
+
`)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return X("server is required for authenticate.");let r=await n.authenticate(t.server);switch(r.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
|
|
347
356
|
|
|
348
357
|
Please open this URL in your browser:
|
|
349
358
|
${r.authUrl}
|
|
@@ -351,43 +360,43 @@ ${r.authUrl}
|
|
|
351
360
|
${r.message||"Once you complete authentication, the server's tools will become available automatically."}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"auth_url"}};case"already_authenticated":return{content:[{type:"text",text:`Server "${t.server}" is already authenticated.`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"already_authenticated"}};case"step_up_required":return{content:[{type:"text",text:`Server "${t.server}" requires elevated permissions.
|
|
352
361
|
Required scopes: ${r.requiredScopes?.join(", ")||"unknown"}
|
|
353
362
|
|
|
354
|
-
`+(r.authUrl?`Re-authorize at: ${r.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:t.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${t.server}" (${r.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${t.server}": ${r.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"error"}}}}case"manage_server":{if(!t.server)return X("server is required for manage_server.");if(!t.manageAction)return X("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!
|
|
355
|
-
`)}],details:{type:"mcp",action:"manage_server",manageAction:
|
|
356
|
-
Message: ${
|
|
357
|
-
Files: ${
|
|
358
|
-
`)}],details:{type:"checkpoint",action:"list",count:
|
|
359
|
-
`).map(a=>{let[
|
|
363
|
+
`+(r.authUrl?`Re-authorize at: ${r.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:t.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${t.server}" (${r.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${t.server}": ${r.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:t.server,status:"error"}}}}case"manage_server":{if(!t.server)return X("server is required for manage_server.");if(!t.manageAction)return X("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!n.addServer)return X("Server addition not supported by the current MCP host.");if(!t.config)return X("config is required for manage_server add.");let r=await n.addServer(t.server,t.config);return Ut("add",t.server,r)}case"remove":{if(!n.removeServer)return X("Server removal not supported by the current MCP host.");let r=await n.removeServer(t.server);return Ut("remove",t.server,r)}case"restart":{if(!n.restartServer)return X("Server restart not supported by the current MCP host.");let r=await n.restartServer(t.server);return Ut("restart",t.server,r)}case"health_check":{if(!n.healthCheck)return X("Health check not supported by the current MCP host.");let r=await n.healthCheck(t.server);return Ut("health_check",t.server,r)}case"enable":case"disable":{if(!n.setServerEnabled)return X("Server enable/disable not supported by the current MCP host.");let r=await n.setServerEnabled(t.server,t.manageAction==="enable");return Ut(t.manageAction,t.server,r)}default:return X(`Unknown manageAction: ${t.manageAction}`)}}default:return X(`Unknown action: "${t.action}".`)}}}}function X(n){return{content:[{type:"text",text:`Error: ${n}`}],details:{type:"mcp",error:n}}}function Hh(n){switch(n){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 zh(n){if(!n)return"";let e=[];return n.readOnlyHint&&e.push("\u{1F4D6}"),n.destructiveHint&&e.push("\u26A0\uFE0F"),n.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function Gh(n){return n<1024?`${n}B`:n<1024*1024?`${(n/1024).toFixed(1)}KB`:`${(n/(1024*1024)).toFixed(1)}MB`}function Ut(n,e,t){let o=[];return o.push(`${t.success?"\u2705":"\u274C"} ${n} "${e}": ${t.message}`),t.serverState&&(o.push(""),o.push(` Status: ${t.serverState.status}`),o.push(` Tools: ${t.serverState.toolCount} | Resources: ${t.serverState.resourceCount}`)),{content:[{type:"text",text:o.join(`
|
|
364
|
+
`)}],details:{type:"mcp",action:"manage_server",manageAction:n,server:e,success:t.success}}}var Vh="checkpoint",qh={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"]},Jl=/^[0-9a-fA-F]{4,64}$/;function Yl(n){return{name:Vh,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:qh,execute:async(e,t)=>{switch(t.action){case"create":{let o=await n.createCheckpoint(t.message);return o.success?{content:[{type:"text",text:`Checkpoint created: ${o.checkpoint.id}
|
|
365
|
+
Message: ${o.checkpoint.message}
|
|
366
|
+
Files: ${o.checkpoint.fileCount}`}],details:{type:"checkpoint",action:"create",checkpointId:o.checkpoint.id}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"checkpoint",error:o.error}}}case"list":{let o=await n.listCheckpoints();if(!o.checkpoints||o.checkpoints.length===0)return{content:[{type:"text",text:"No checkpoints available."}],details:{type:"checkpoint",action:"list",count:0}};let r=[`Checkpoints (${o.checkpoints.length}):`,""];for(let s of o.checkpoints)r.push(`- ${s.id.slice(0,8)} [${s.timestamp}] ${s.message} (${s.fileCount} files)`);return{content:[{type:"text",text:r.join(`
|
|
367
|
+
`)}],details:{type:"checkpoint",action:"list",count:o.checkpoints.length}}}case"restore":{if(!t.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for restore."}],details:{type:"checkpoint",error:"missing_id"}};if(!Jl.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let o=await n.restoreCheckpoint(t.checkpointId,t.paths);if(!o.success)return{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"checkpoint",error:o.error}};let r=t.paths?`(${t.paths.length} files)`:"(full workspace)";return{content:[{type:"text",text:`Restored to checkpoint ${t.checkpointId.slice(0,8)} ${r}`}],details:{type:"checkpoint",action:"restore",checkpointId:t.checkpointId}}}case"diff":{if(!t.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for diff."}],details:{type:"checkpoint",error:"missing_id"}};if(!Jl.test(t.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let o=await n.diffCheckpoint(t.checkpointId);return o.success?{content:[{type:"text",text:o.diff||"(no changes since checkpoint)"}],details:{type:"checkpoint",action:"diff",checkpointId:t.checkpointId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"checkpoint",error:o.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${t.action}".`}],details:{type:"checkpoint",error:"unknown_action"}}}}}}import*as ve from"node:fs";import*as Nt from"node:path";function Xl(n,e){let t=Gs(e);return{createCheckpoint:async o=>{try{ve.mkdirSync(t,{recursive:!0});let{execSync:r}=await import("node:child_process"),s=Nt.join(t,".git");ve.existsSync(s)||(r("git init",{cwd:t,stdio:"pipe"}),r('git config user.email "checkpoint@agent"',{cwd:t,stdio:"pipe"}),r('git config user.name "Checkpoint"',{cwd:t,stdio:"pipe"})),ve.cpSync(n,t,{recursive:!0,filter:u=>!u.includes(".git")&&!u.includes("node_modules")}),r("git add -A",{cwd:t,stdio:"pipe"});let i=o||`checkpoint ${new Date().toISOString()}`;r(`git commit --allow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:t,stdio:"pipe"});let a=r("git rev-parse HEAD",{cwd:t,stdio:"pipe"}).toString().trim(),c=parseInt(r("git ls-files | wc -l",{cwd:t,stdio:"pipe"}).toString().trim(),10)||0;return{success:!0,checkpoint:{id:a,message:i,timestamp:new Date().toISOString(),fileCount:c}}}catch(r){return{success:!1,error:r.message}}},listCheckpoints:async()=>{try{let{execSync:o}=await import("node:child_process"),r=Nt.join(t,".git");if(!ve.existsSync(r))return{success:!0,checkpoints:[]};let s=o('git log --format="%H|%aI|%s" --max-count=20',{cwd:t,stdio:"pipe"}).toString().trim();return s?{success:!0,checkpoints:s.split(`
|
|
368
|
+
`).map(a=>{let[c="",u="",...l]=a.split("|");return{id:c,timestamp:u,message:l.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(o){return{success:!1,error:o.message}}},restoreCheckpoint:async(o,r)=>{try{let{execSync:s}=await import("node:child_process");if(r&&r.length>0)for(let i of r){s(`git checkout ${o} -- "${i}"`,{cwd:t,stdio:"pipe"});let a=Nt.join(t,i),c=Nt.join(n,i);ve.existsSync(a)&&ve.cpSync(a,c,{recursive:!0})}else s(`git checkout ${o} -- .`,{cwd:t,stdio:"pipe"}),ve.cpSync(t,n,{recursive:!0,filter:i=>!i.includes(".git")});return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async o=>{try{let{execSync:r}=await import("node:child_process");return{success:!0,diff:r(`git diff ${o} HEAD`,{cwd:t,stdio:"pipe"}).toString()}}catch(r){return{success:!1,error:r.message}}}}}var Ql="memory";var Kh=["add","replace","remove","search"],Zl={type:"object",properties:{action:{type:"string",enum:Kh,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(`
|
|
360
369
|
`)},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(`
|
|
361
370
|
`)},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(`
|
|
362
371
|
`)},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(`
|
|
363
|
-
`)}},required:["action"]},
|
|
364
|
-
`),
|
|
365
|
-
`+
|
|
366
|
-
`))}catch{}if((!s||s==="facts"||s==="projects")&&e.queryGraph)try{let
|
|
367
|
-
`+
|
|
368
|
-
`))}catch{}if((!s||s==="profile"||s==="projects")&&e.getProfileSummary)try{let
|
|
369
|
-
`+
|
|
370
|
-
`+
|
|
372
|
+
`)}},required:["action"]},ec=["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(`
|
|
373
|
+
`),tc="Memory",Jh=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i];function Cr(n){return!Jh.some(e=>e.test(n))}async function oc(n,e){let{action:t}=n,o=n.target??"memory";if(t==="add"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=n.content?.trim();if(!r)return{ok:!1,message:"content is required for 'add' action.",action:t,errorCode:"empty_content"};if(r.length>2e3)return{ok:!1,message:`Content too long (${r.length} chars, max 2000).`,action:t,errorCode:"too_long"};let s=e.store.add(o,r);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="replace"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=n.old_text?.trim(),s=n.content?.trim();if(!r)return{ok:!1,message:"old_text is required for 'replace' action.",action:t,errorCode:"empty_old_text"};if(!s)return{ok:!1,message:"content is required for 'replace' action.",action:t,errorCode:"empty_content"};if(s.length>2e3)return{ok:!1,message:`Content too long (${s.length} chars, max 2000).`,action:t,errorCode:"too_long"};let i=e.store.replace(o,r,s);return{ok:i.ok,message:i.ok?`${i.message} [${i.usage}]`:i.message,action:t,entryCount:i.entryCount,usage:i.usage,storeModified:i.ok,errorCode:i.errorCode}}if(t==="remove"){if(!e.store)return{ok:!1,message:"Local memory store is not available.",action:t,errorCode:"no_store"};let r=n.old_text?.trim();if(!r)return{ok:!1,message:"old_text is required for 'remove' action.",action:t,errorCode:"empty_old_text"};let s=e.store.remove(o,r);return{ok:s.ok,message:s.ok?`${s.message} [${s.usage}]`:s.message,action:t,entryCount:s.entryCount,usage:s.usage,storeModified:s.ok,errorCode:s.errorCode}}if(t==="search"){let r=n.query?.trim();if(!r)return{ok:!1,message:"query is required for 'search' action.",action:t,errorCode:"empty_query"};let s=n.category,i=[],a;if(!s||s==="facts"||s==="projects")try{let c=await e.provider.search(r,e.userId,{limit:10});a=c,c.length>0&&i.push(`## Long-term Memory
|
|
374
|
+
`+c.map((u,l)=>`${l+1}. [${u.blockId}] ${u.text}`).join(`
|
|
375
|
+
`))}catch{}if((!s||s==="facts"||s==="projects")&&e.queryGraph)try{let c=e.queryGraph(r,e.userId);c.length>0&&i.push(`## Recalled Facts
|
|
376
|
+
`+c.map(u=>`\u2022 ${u}`).join(`
|
|
377
|
+
`))}catch{}if((!s||s==="profile"||s==="projects")&&e.getProfileSummary)try{let c=e.getProfileSummary(e.userId);c&&i.push(`## User Profile
|
|
378
|
+
`+c)}catch{}if((!s||s==="media")&&e.getMediaPreferences)try{let c=e.getMediaPreferences(e.userId);if(c){let u=[];c.imageStyle&&u.push(`\u2022 Image style: ${c.imageStyle}`),c.videoStyle&&u.push(`\u2022 Video style: ${c.videoStyle}`),c.musicGenre&&u.push(`\u2022 Music genre: ${c.musicGenre}`),c.musicMood&&u.push(`\u2022 Music mood: ${c.musicMood}`),c.primaryPurpose&&u.push(`\u2022 Primary purpose: ${c.primaryPurpose}`),c.colorPreference&&u.push(`\u2022 Color preference: ${c.colorPreference}`),u.length>0&&i.push(`## Media Preferences
|
|
379
|
+
`+u.join(`
|
|
371
380
|
`))}}catch{}return i.length===0?{ok:!0,message:"No matching memories found.",action:t,results:[]}:{ok:!0,message:i.join(`
|
|
372
381
|
|
|
373
|
-
`),action:t,results:a}}return{ok:!1,message:`Unknown action: ${t}. Use 'add', 'replace', 'remove', or 'search'.`,action:t,errorCode:"unknown_action"}}import{readFile as
|
|
374
|
-
`)}var
|
|
382
|
+
`),action:t,results:a}}return{ok:!1,message:`Unknown action: ${t}. Use 'add', 'replace', 'remove', or 'search'.`,action:t,errorCode:"unknown_action"}}import{readFile as Yh,writeFile as Xh,mkdir as Qh,rename as Zh,unlink as ey}from"node:fs/promises";import{dirname as ty,join as nc}from"node:path";import{randomUUID as oy}from"node:crypto";async function ny(n,e){let t=ty(n);await Qh(t,{recursive:!0});let o=nc(t,`.tmp-${oy()}`);try{await Xh(o,e,"utf-8"),await Zh(o,n)}catch(r){throw await ey(o).catch(()=>{}),r}}async function ry(n){try{let e=await Yh(n,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function sy(n,e){await ny(n,JSON.stringify(e,null,2)+`
|
|
383
|
+
`)}var iy="memory.json";function Oo(){return nc(G(),iy)}async function rc(){return ry(Oo())}async function Sr(n){let e={...n,savedAt:new Date().toISOString()};await sy(Oo(),e)}import{readFileSync as ay,existsSync as ly}from"node:fs";var qe=`
|
|
375
384
|
\xA7
|
|
376
|
-
`,
|
|
377
|
-
${
|
|
385
|
+
`,cy=2200,uy=1375,Lo=class{memoryEntries=[];userEntries=[];frozenSnapshot={memory:"",user:""};snapshotFrozen=!1;saveTimer=null;memoryCharLimit;userCharLimit;persistToDisk;constructor(e){this.memoryCharLimit=e?.memoryCharLimit??cy,this.userCharLimit=e?.userCharLimit??uy,this.persistToDisk=e?.persistToDisk??!1}loadFromSerialized(e){this.memoryEntries=ic(sc(e.memory??"")),this.userEntries=ic(sc(e.user??""))}serialize(){return{memory:this.memoryEntries.join(qe),user:this.userEntries.join(qe)}}async loadFromDisk(){let e=await rc();e&&this.loadFromSerialized(e)}loadFromDiskSync(){let e=Oo();try{if(!ly(e))return;let t=ay(e,"utf-8"),o=JSON.parse(t);this.loadFromSerialized(o)}catch{}}scheduleSave(){this.persistToDisk&&(this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(()=>{this.saveTimer=null,Sr(this.serialize()).catch(()=>{})},500))}async flush(){this.saveTimer&&(clearTimeout(this.saveTimer),this.saveTimer=null),this.persistToDisk&&await Sr(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 o=t.trim();if(!o)return this.errorResult(e,"Content cannot be empty.","empty_content");if(!Cr(o))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let r=this.entriesFor(e);if(r.includes(o))return this.successResult(e,"Entry already exists (no change).");if([...r,o].join(qe).length>this.charLimitFor(e)){let a=this.formatUsage(e);return this.errorResult(e,`Memory full (${a}). Remove old entries first.`,"over_limit")}return r.push(o),this.scheduleSave(),this.successResult(e,"Entry added.")}replace(e,t,o){let r=t.trim(),s=o.trim();if(!r)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");if(!s)return this.errorResult(e,"content cannot be empty.","empty_content");if(!Cr(s))return this.errorResult(e,"Content rejected: potential injection detected.","unsafe_content");let i=this.entriesFor(e),a=i.map((d,p)=>d.includes(r)?p:-1).filter(d=>d>=0);if(a.length===0)return this.errorResult(e,`No entry contains: "${Rr(r)}"`,"not_found");if(a.length>1&&new Set(a.map(p=>i[p])).size>1)return this.errorResult(e,`Multiple entries match: "${Rr(r)}" (${a.length} matches). Be more specific.`,"ambiguous_match");let c=a[0],u=[...i];if(u[c]=s,u.join(qe).length>this.charLimitFor(e)){let d=this.formatUsage(e);return this.errorResult(e,`Replacement would exceed limit (${d}).`,"over_limit")}return i[c]=s,this.scheduleSave(),this.successResult(e,"Entry replaced.")}remove(e,t){let o=t.trim();if(!o)return this.errorResult(e,"old_text cannot be empty.","empty_old_text");let r=this.entriesFor(e),s=r.map((i,a)=>i.includes(o)?a:-1).filter(i=>i>=0);if(s.length===0)return this.errorResult(e,`No entry contains: "${Rr(o)}"`,"not_found");for(let i=s.length-1;i>=0;i--)r.splice(s[i],1);return this.scheduleSave(),this.successResult(e,s.length===1?"Entry removed.":`${s.length} entries removed.`)}getEntries(e){return this.entriesFor(e)}getUsage(e){let t=this.entriesFor(e),o=t.length>0?t.join(qe).length:0,r=this.charLimitFor(e);return{used:o,limit:r,percent:r>0?Math.round(o/r*100):0}}isEmpty(){return this.memoryEntries.length===0&&this.userEntries.length===0}entriesFor(e){return e==="user"?this.userEntries:this.memoryEntries}charLimitFor(e){return e==="user"?this.userCharLimit:this.memoryCharLimit}formatUsage(e){let{used:t,limit:o,percent:r}=this.getUsage(e);return`${r}% \u2014 ${t}/${o} chars`}renderBlock(e,t){if(t.length===0)return"";let o=e==="user"?"USER PROFILE":"MEMORY",r=this.formatUsage(e),s="\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",i=t.join(qe);return`${s}
|
|
386
|
+
${o} (your personal notes) [${r}]
|
|
378
387
|
${s}
|
|
379
|
-
${i}`}successResult(e,t){let n=this.entriesFor(e);return{ok:!0,message:t,target:e,entries:n,entryCount:n.length,usage:this.formatUsage(e)}}errorResult(e,t,n){let r=this.entriesFor(e);return{ok:!1,message:t,target:e,entries:r,entryCount:r.length,usage:this.formatUsage(e),errorCode:n}}};function Pl(o){return o.trim()?o.split(Fe).map(e=>e.trim()).filter(Boolean):[]}function Al(o){let e=new Set;return o.filter(t=>e.has(t)?!1:(e.add(t),!0))}function ur(o,e=60){return o.length<=e?o:`${o.slice(0,e-1).trimEnd()}\u2026`}Jo();Vo();import{readFile as ah}from"node:fs/promises";import{watch as lh}from"node:fs";import{join as ch}from"node:path";var uh=fe,dh="settings.json";function ph(o){return ch(o,uh,dh)}async function mh(o){try{let e=await ah(o,"utf-8");return JSON.parse(e)}catch{return null}}function gh(o,e,t,n){let r=!1;o.permissionMode&&o.permissionMode!==e.getMode()&&(e.setMode(o.permissionMode),n?.(`settings: permission mode \u2192 ${o.permissionMode}`),r=!0),o.permissionRules&&(e.replaceRules(o.permissionRules),n?.(`settings: ${o.permissionRules.length} permission rules loaded`),r=!0),o.defaultBehavior&&(e.setDefaultBehavior(o.defaultBehavior),n?.(`settings: default behavior \u2192 ${o.defaultBehavior}`),r=!0),r&&t&&t.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:o}).catch(()=>{})}function El(o){let e=ph(o.projectRoot),t=null,n=null,r=async()=>{let s=await mh(e);s&&gh(s,o.ruleEngine,o.hooks,o.log)};r().catch(()=>{});try{t=lh(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{r().catch(()=>{})},200)}),t.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),t?.close(),t=null}}var dr=new Set;function Je(o){return dr.add(o),()=>{dr.delete(o)}}async function Il(){await Promise.all(Array.from(dr).map(o=>o()))}import*as P from"node:fs";import*as Y from"node:path";import{AGENT_RPC_ERROR_CODES as te,AGENT_RPC_PROTOCOL_VERSION as vo,isAgentRpcRequest as fh}from"qlogicagent-runtime-contracts";var Ol=["initialize","thread.create","thread.list","thread.turn","session.resume","session.getInfo","memory.list","memory.read","memory.write","memory.search","memory.delete","memory.dream","tools.list","config.get","config.update","todos.list","tasks.list","tasks.cancel","agent.ping","agent.abort","tool.approval.response"];var pr=class o{running=!1;activeTurn=null;verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentHooks=null;mcpManager=null;pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";sessionState=null;taskStore=new Yt;memoryPrefetchState=ht();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;constructor(e){this.verbose=e.verbose,this.registry=new Ve,this.mediaClient=new pt({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})}),Wa({log:{info:t=>this.log(t),warn:t=>this.log(`[warn] ${t}`),error:t=>this.log(`[error] ${t}`),debug:t=>{e.verbose&&this.log(`[debug] ${t}`)}},onExecProgress:t=>{this.sendNotification("turn.exec_progress",{output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,totalBytes:t.totalBytes})}})}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(!fh(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}stop(){if(this.running){this.running=!1,this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{Il().catch(()=>{}),this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null),this.mcpManager&&(this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=null),this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}handleMessage(e){switch(e.method){case"initialize":this.handleInitialize(e);break;case"agent.ping":this.handlePing(e);break;case"thread.turn":this.handleTurn(e);break;case"memory.dream":this.handleDream(e);break;case"agent.abort":this.handleAbort(e);break;case"tool.approval.response":this.handleApprovalResponse(e);break;case"thread.list":this.handleThreadList(e);break;case"session.resume":this.handleSessionResume(e);break;case"thread.create":this.handleThreadCreate(e);break;case"session.getInfo":this.handleSessionGetInfo(e);break;case"memory.list":this.handleMemoryList(e);break;case"memory.read":this.handleMemoryRead(e);break;case"memory.write":this.handleMemoryWrite(e);break;case"memory.search":this.handleMemorySearch(e);break;case"memory.delete":this.handleMemoryDelete(e);break;case"tools.list":this.handleToolsList(e);break;case"config.get":this.handleConfigGet(e);break;case"config.update":this.handleConfigUpdate(e);break;case"todos.list":this.handleTodosList(e);break;case"tasks.list":this.handleTasksList(e);break;case"tasks.cancel":this.handleTasksCancel(e);break;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleInitialize(e){let t=e.params,n=t?.protocolVersion??"unknown",r=t?.host?.name??t?.hostName??"unknown",s=t?.host?.version??t?.hostVersion??"?",i=n.split(".")[0],a=vo.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${n} agent=${vo}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${n}, agent=${vo}`});return}this.log(`[initialize] host=${r} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:vo,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:Ce().map(l=>l.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...Ol]}})}handleThreadCreate(e){let t=e.params,n=t?.id??ye();this.log(`[thread.create] id=${n} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&Zn(t.cwd),this.currentSessionId=n,this.sessionState=new yt(n),this.memoryPrefetchState=ht(),e.id!==void 0&&this.sendResponse(e.id,{id:n,title:t?.title,status:"active",createdAt:new Date().toISOString()})}async handleThreadList(e){let n=e.params?.limit??20;try{let s=(await mi(n)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:new Date(i.lastActiveAt).toISOString(),lastActiveAt:new Date(i.lastActiveAt).toISOString()}));e.id!==void 0&&this.sendResponse(e.id,{threads:s})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:`Failed to list threads: ${r.message}`})}}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}handleAbort(e){let t=e.params?.turnId??"";this.log(`abort requested for turn ${t}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),e.id!==void 0&&this.sendResponse(e.id,{aborted:!0})}handleApprovalResponse(e){let t=e.params;if(!t)return;let n=t.approvalId,r=t.decision;if(!n||!r){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:n,decision:r==="approved"?"approved":"denied",updatedInput:t.updatedInput,permissionUpdate:t.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(s),e.id!==void 0&&this.sendResponse(e.id,{received:!0})}async handleSessionResume(e){let n=e.params?.sessionId;if(!n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"sessionId is required"});return}try{let r=await pi(n);if(!r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Session not found: ${n}`});return}e.id!==void 0&&this.sendResponse(e.id,{metadata:r.metadata,messages:r.messages,costSnapshot:r.costSnapshot})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:`Failed to resume session: ${r.message}`})}}async handleTurn(e){let t=e.params??{},n=t.turnId??ye(),r=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;a?.workdir&&typeof a.workdir=="string"&&Zn(a.workdir);{let m={},y=a?.provider,h=a?.apiKey;y&&h&&(m[y]=h);let k=a?.mediaApiKeys;k&&Object.assign(m,k),ja(this.mediaClient,m,(w,f,C)=>{this.sessionState?.addMediaUsage(w,f,C)})}let l=Ce(),c=new Set(l.map(m=>m.function.name)),p=[...l,...i.filter(m=>!c.has(m.function.name))];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:n}),r&&r!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),wi()),this.currentSessionId=r,this.sessionState=new yt(r),this.memoryPrefetchState=ht());let d=new AbortController;this.activeTurn=d,this.log(`turn ${n} starting (session: ${r})`),this.sendNotification("turn.start",{turnId:n,model:a?.model??(this.currentModel||void 0),provider:a?.provider||void 0});try{let m={provider:a?.provider,model:a?.model,apiKey:a?.apiKey,baseUrl:a?.baseUrl,maxRounds:a?.maxRounds,temperature:a?.temperature,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,summaryModel:a?.summaryModel??process.env.QLOGICAGENT_SUMMARY_MODEL,maxConcurrentTools:a?.maxConcurrentTools},y=this.resolveAgent(m);if(this.permissionChecker&&a?.permissions){let f=a.permissions;if(typeof f?.mode=="string"){let C=or(f);this.permissionChecker.ruleEngineRef.setMode(C.mode)}}if(!y){this.sendNotification("turn.error",{turnId:n,error:"No LLM provider configured. Provide provider/model/apiKey in agent.turn config, or set DEEPSEEK_API_KEY / OPENAI_API_KEY / ANTHROPIC_API_KEY environment variable.",code:"NO_PROVIDER"});return}let h,k=a?.workdir??process.cwd();try{let f=await ki(k,this.currentHooks??void 0);f.length>0&&(h=Ti(f))}catch{}let w=await Si({basePrompt:a?.systemPrompt,instructionBlock:h,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[Ci(k)]});for(let f of s)f.role==="user"&&xn(r,f).catch(()=>{});for await(let f of y.run({turnId:n,sessionId:r,messages:s,tools:p,systemPrompt:w,config:m},d.signal)){let C=new Date().toISOString();switch(f.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:f.turnId,text:f.text,item:{id:`${n}-delta`,type:"message",role:"assistant",text:f.text,createdAt:C}});break;case"end":if(this.sendNotification("turn.end",{turnId:f.turnId,content:f.content,usage:f.usage,model:f.model,provider:f.provider,item:{id:`${n}-end`,type:"message",role:"assistant",text:f.content,createdAt:C}}),f.usage&&this.sessionState){this.sessionState.addUsage(f.usage,f.model??this.currentModel);let R=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:f.turnId,usage:f.usage,model:f.model??this.currentModel,sessionCostUSD:R.totalInputTokens*3e-6+R.totalOutputTokens*15e-6})}f.content&&xn(r,{role:"assistant",content:f.content}).catch(()=>{});break;case"error":this.sendNotification("turn.error",{turnId:f.turnId,error:f.error,code:f.code});break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:f.turnId,instruction:f.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:f.turnId,callId:f.callId,name:f.name,arguments:f.arguments,item:{id:f.callId,type:"tool_call",role:"assistant",toolName:f.name,toolCallId:f.callId,arguments:f.arguments,createdAt:C}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:f.turnId,callId:f.callId,name:f.name,ok:f.ok,...f.error?{error:f.error}:{},...f.outputPreview?{outputPreview:f.outputPreview}:{},item:{id:`${f.callId}-result`,type:"tool_result",role:"assistant",toolName:f.name,toolCallId:f.callId,output:f.ok?f.outputPreview??"":f.error,approved:f.ok,createdAt:C}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:f.turnId,callId:f.callId,name:f.name,reason:f.reason,item:{id:`${f.callId}-blocked`,type:"tool_blocked",role:"system",toolName:f.name,toolCallId:f.callId,text:f.reason,approved:!1,createdAt:C}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:f.turnId,action:f.action,...f.detail?{detail:f.detail}:{},item:{id:`${n}-recovery-${ye().slice(0,8)}`,type:"recovery",role:"system",strategy:f.action,text:f.detail,createdAt:C}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:f.turnId,slug:f.slug,content:f.content,item:{id:`${n}-plan-${ye().slice(0,8)}`,type:"plan_update",role:"assistant",text:f.content,createdAt:C}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:f.turnId,text:f.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:f.turnId,items:f.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:f.turnId,mediaType:f.mediaType,url:f.url,...f.model?{model:f.model}:{},...f.provider?{provider:f.provider}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:f.turnId,artifactId:f.artifactId,type:f.artifactType,title:f.title,...f.filePath?{filePath:f.filePath}:{},...f.language?{language:f.language}:{},...f.content?{content:f.content}:{},...f.mimeType?{mimeType:f.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:f.turnId,subagentId:f.subagentId,agentType:f.agentType,...f.prompt?{prompt:f.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:f.turnId,subagentId:f.subagentId,agentType:f.agentType,ok:f.ok,...f.outputPreview?{outputPreview:f.outputPreview}:{},...f.error?{error:f.error}:{}});break}}if(this.log(`turn ${n} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){di(r,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:process.cwd(),messageCount:s.length}).catch(()=>{});let f=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:r,model:this.currentModel||void 0,cwd:process.cwd(),turnCount:f.turnCount}),this.currentTransport&&this.currentApiKey&&m.summaryModel&&gi(r,{sessionId:r,createdAt:0,lastActiveAt:0,turnCount:f.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:m.summaryModel}),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(n,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(m){if(d.signal.aborted)this.sendNotification("turn.error",{turnId:n,error:"Turn aborted",code:"ABORTED"});else{let y=m instanceof Error?m.message:String(m);this.sendNotification("turn.error",{turnId:n,error:y,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===d&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
|
|
388
|
+
${i}`}successResult(e,t){let o=this.entriesFor(e);return{ok:!0,message:t,target:e,entries:o,entryCount:o.length,usage:this.formatUsage(e)}}errorResult(e,t,o){let r=this.entriesFor(e);return{ok:!1,message:t,target:e,entries:r,entryCount:r.length,usage:this.formatUsage(e),errorCode:o}}};function sc(n){return n.trim()?n.split(qe).map(e=>e.trim()).filter(Boolean):[]}function ic(n){let e=new Set;return n.filter(t=>e.has(t)?!1:(e.add(t),!0))}function Rr(n,e=60){return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}un();ln();import{readFile as dy}from"node:fs/promises";import{watch as py}from"node:fs";import{join as my}from"node:path";var gy=Te,fy="settings.json";function hy(n){return my(n,gy,fy)}async function yy(n){try{let e=await dy(n,"utf-8");return JSON.parse(e)}catch{return null}}function by(n,e,t,o){let r=!1;n.permissionMode&&n.permissionMode!==e.getMode()&&(e.setMode(n.permissionMode),o?.(`settings: permission mode \u2192 ${n.permissionMode}`),r=!0),n.permissionRules&&(e.replaceRules(n.permissionRules),o?.(`settings: ${n.permissionRules.length} permission rules loaded`),r=!0),n.defaultBehavior&&(e.setDefaultBehavior(n.defaultBehavior),o?.(`settings: default behavior \u2192 ${n.defaultBehavior}`),r=!0),r&&t&&t.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:n}).catch(()=>{})}function ac(n){let e=hy(n.projectRoot),t=null,o=null,r=async()=>{let s=await yy(e);s&&by(s,n.ruleEngine,n.hooks,n.log)};r().catch(()=>{});try{t=py(e,{persistent:!1},s=>{o&&clearTimeout(o),o=setTimeout(()=>{r().catch(()=>{})},200)}),t.on("error",()=>{})}catch{}return()=>{o&&clearTimeout(o),t?.close(),t=null}}var Mr=new Set;function at(n){return Mr.add(n),()=>{Mr.delete(n)}}async function lc(){await Promise.all(Array.from(Mr).map(n=>n()))}import*as P from"node:fs";import*as Y from"node:path";import{AGENT_RPC_ERROR_CODES as te,AGENT_RPC_PROTOCOL_VERSION as Do,isAgentRpcRequest as Ty}from"qlogicagent-runtime-contracts";var cc=["initialize","thread.create","thread.list","thread.turn","session.resume","session.getInfo","memory.list","memory.read","memory.write","memory.search","memory.delete","memory.dream","tools.list","config.get","config.update","todos.list","tasks.list","tasks.cancel","agent.ping","agent.abort","tool.approval.response"];var $o=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 o=`${this.baseUrl}/tools/web-search`,r={tool:"web-search-pro",messages:[{role:"user",content:e}],stream:!1},s=await this.postJSON(o,r),i=[],a=t?.maxResults??10;if(s.web_search){for(let c of s.web_search.slice(0,a))i.push({title:c.title??"",url:c.link??"",snippet:(c.content??"").slice(0,500),content:c.content});return i}for(let c of s.choices??[])for(let u of c.message?.tool_calls??[])for(let l of u.search_result??[]){if(i.length>=a)break;i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content})}return i}async reader(e){let t=`${this.baseUrl}/tools/reader`,o={tool:"reader",messages:[{role:"user",content:e}],stream:!1};return{title:"",content:(await this.postJSON(t,o)).choices?.[0]?.message?.content??"",url:e}}async tokenize(e,t){let o=`${this.baseUrl}/tokenizer`,r={model:t,messages:[{role:"user",content:e}]};return{tokenCount:(await this.postJSON(o,r)).usage?.total_tokens??0,model:t}}async moderate(e){let t=`${this.baseUrl}/moderations`,o={input:e},s=(await this.postJSON(t,o)).results?.[0];return{flagged:s?.flagged??!1,categories:s?.categories??{},scores:s?.category_scores}}async postJSON(e,t){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let r=await o.text().catch(()=>"");throw new Error(`Zhipu Tool API error ${o.status}: ${r}`)}return o.json()}};var ky=new Set(["zhipu","zhipu-openai","zhipu-coding"]),xy="https://open.bigmodel.cn/api/paas/v4";function vy(n,e){if(!(!n||!e)&&ky.has(n))return new $o({baseUrl:xy,apiKey:e})}var Pr=class n{running=!1;activeTurn=null;verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentHooks=null;mcpManager=null;pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";sessionState=null;taskStore=new lo;memoryPrefetchState=St();qmemoryAdapter=null;qmemoryUserId="";fileWatcher=null;constructor(e){this.verbose=e.verbose,this.registry=new et,this.mediaClient=new wt({registry:this.registry}),this.transport=e.transport??new Tt({verbose:e.verbose}),this.taskStore.onTaskChange((t,o)=>{o&&this.sendNotification("task.updated",{taskId:t,type:o.type,lifecycle:o.lifecycle,label:o.label})}),bl({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(!Ty(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{lc().catch(()=>{}),this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null),this.mcpManager&&(this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=null),this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}handleMessage(e){switch(e.method){case"initialize":this.handleInitialize(e);break;case"agent.ping":this.handlePing(e);break;case"thread.turn":this.handleTurn(e);break;case"memory.dream":this.handleDream(e);break;case"agent.abort":this.handleAbort(e);break;case"tool.approval.response":this.handleApprovalResponse(e);break;case"thread.list":this.handleThreadList(e);break;case"session.resume":this.handleSessionResume(e);break;case"thread.create":this.handleThreadCreate(e);break;case"session.getInfo":this.handleSessionGetInfo(e);break;case"memory.list":this.handleMemoryList(e);break;case"memory.read":this.handleMemoryRead(e);break;case"memory.write":this.handleMemoryWrite(e);break;case"memory.search":this.handleMemorySearch(e);break;case"memory.delete":this.handleMemoryDelete(e);break;case"tools.list":this.handleToolsList(e);break;case"media.listModels":this.handleMediaListModels(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;default:e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}}handleInitialize(e){let t=e.params,o=t?.protocolVersion??"unknown",r=t?.host?.name??t?.hostName??"unknown",s=t?.host?.version??t?.hostVersion??"?",i=o.split(".")[0],a=Do.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${o} agent=${Do}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${o}, agent=${Do}`});return}this.log(`[initialize] host=${r} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:Do,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:Ee().map(c=>c.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...cc]}})}handleThreadCreate(e){let t=e.params,o=t?.id??we();this.log(`[thread.create] id=${o} title=${t?.title??"(none)"}`),t?.cwd&&typeof t.cwd=="string"&&hr(t.cwd),this.currentSessionId=o,this.sessionState=new Rt(o),this.memoryPrefetchState=St(),e.id!==void 0&&this.sendResponse(e.id,{id:o,title:t?.title,status:"active",createdAt:new Date().toISOString()})}async handleThreadList(e){let o=e.params?.limit??20;try{let s=(await Oi(o)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:new Date(i.lastActiveAt).toISOString(),lastActiveAt:new Date(i.lastActiveAt).toISOString()}));e.id!==void 0&&this.sendResponse(e.id,{threads:s})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:`Failed to list threads: ${r.message}`})}}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}handleAbort(e){let t=e.params?.turnId??"";this.log(`abort requested for turn ${t}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),e.id!==void 0&&this.sendResponse(e.id,{aborted:!0})}handleApprovalResponse(e){let t=e.params;if(!t)return;let o=t.approvalId,r=t.decision;if(!o||!r){this.log("[warn] tool.approval.response missing approvalId or decision");return}let s={approvalId:o,decision:r==="approved"?"approved":"denied",updatedInput:t.updatedInput,permissionUpdate:t.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(s),e.id!==void 0&&this.sendResponse(e.id,{received:!0})}async handleSessionResume(e){let o=e.params?.sessionId;if(!o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"sessionId is required"});return}try{let r=await Ei(o);if(!r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Session not found: ${o}`});return}e.id!==void 0&&this.sendResponse(e.id,{metadata:r.metadata,messages:r.messages,costSnapshot:r.costSnapshot})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:`Failed to resume session: ${r.message}`})}}async handleTurn(e){let t=e.params??{},o=t.turnId??we(),r=t.sessionId,s=t.messages??[],i=t.tools??[],a=t.config;a?.workdir&&typeof a.workdir=="string"&&hr(a.workdir);{let m={},h=a?.provider,y=a?.apiKey;h&&y&&(m[h]=y);let T=a?.mediaApiKeys;T&&Object.assign(m,T),fl(this.mediaClient,m,(x,f,_)=>{this.sessionState?.addMediaUsage(x,f,_)},a?.mediaProviders),gl(vy(h,y))}let c=Ee(),u=new Set(c.map(m=>m.function.name)),d=[...c,...i.filter(m=>!u.has(m.function.name))];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:o}),r&&r!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),Hi()),this.currentSessionId=r,this.sessionState=new Rt(r),this.memoryPrefetchState=St());let p=new AbortController;this.activeTurn=p,this.log(`turn ${o} starting (session: ${r})`),this.sendNotification("turn.start",{turnId:o,model:a?.model??(this.currentModel||void 0),provider:a?.provider||void 0});try{let m={provider:a?.provider,model:a?.model,apiKey:a?.apiKey,baseUrl:a?.baseUrl,maxRounds:a?.maxRounds,temperature:a?.temperature,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,summaryModel:a?.summaryModel??process.env.QLOGICAGENT_SUMMARY_MODEL,maxConcurrentTools:a?.maxConcurrentTools,mediaProviders:a?.mediaProviders};{let f=m.provider??"",_=m.model??"";f&&_&&this.registry.getModelInfo(f,_)?.streamRequired&&(m.streamRequired=!0)}let h=this.resolveAgent(m);if(this.permissionChecker&&a?.permissions){let f=a.permissions;if(typeof f?.mode=="string"){let _=Tr(f);this.permissionChecker.ruleEngineRef.setMode(_.mode)}}if(!h){this.sendNotification("turn.error",{turnId:o,error:"No LLM provider configured. Provide provider/model/apiKey in agent.turn config, or set DEEPSEEK_API_KEY / OPENAI_API_KEY / ANTHROPIC_API_KEY environment variable.",code:"NO_PROVIDER"});return}let y,T=a?.workdir??process.cwd();try{let f=await ji(T,this.currentHooks??void 0);f.length>0&&(y=Fi(f))}catch{}let x=await zi({basePrompt:a?.systemPrompt,instructionBlock:y,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[Gi(T)]});for(let f of s)f.role==="user"&&Un(r,f).catch(()=>{});for await(let f of h.run({turnId:o,sessionId:r,messages:s,tools:d,systemPrompt:x,config:m},p.signal)){let _=new Date().toISOString();switch(f.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:f.turnId,text:f.text,item:{id:`${o}-delta`,type:"message",role:"assistant",text:f.text,createdAt:_}});break;case"end":if(this.sendNotification("turn.end",{turnId:f.turnId,content:f.content,usage:f.usage,model:f.model,provider:f.provider,item:{id:`${o}-end`,type:"message",role:"assistant",text:f.content,createdAt:_}}),f.usage&&this.sessionState){this.sessionState.addUsage(f.usage,f.model??this.currentModel);let S=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:f.turnId,usage:f.usage,model:f.model??this.currentModel,sessionCostUSD:S.totalInputTokens*3e-6+S.totalOutputTokens*15e-6})}f.content&&Un(r,{role:"assistant",content:f.content}).catch(()=>{});break;case"error":if(this.sendNotification("turn.error",{turnId:f.turnId,error:f.error,code:f.code}),f.usage&&this.sessionState){this.sessionState.addUsage(f.usage,this.currentModel);let S=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:f.turnId,usage:f.usage,model:this.currentModel,sessionCostUSD:S.totalInputTokens*3e-6+S.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:f.turnId,instruction:f.instruction});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:f.turnId,callId:f.callId,name:f.name,arguments:f.arguments,item:{id:f.callId,type:"tool_call",role:"assistant",toolName:f.name,toolCallId:f.callId,arguments:f.arguments,createdAt:_}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:f.turnId,callId:f.callId,name:f.name,ok:f.ok,...f.error?{error:f.error}:{},...f.outputPreview?{outputPreview:f.outputPreview}:{},item:{id:`${f.callId}-result`,type:"tool_result",role:"assistant",toolName:f.name,toolCallId:f.callId,output:f.ok?f.outputPreview??"":f.error,approved:f.ok,createdAt:_}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:f.turnId,callId:f.callId,name:f.name,reason:f.reason,item:{id:`${f.callId}-blocked`,type:"tool_blocked",role:"system",toolName:f.name,toolCallId:f.callId,text:f.reason,approved:!1,createdAt:_}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:f.turnId,action:f.action,...f.detail?{detail:f.detail}:{},item:{id:`${o}-recovery-${we().slice(0,8)}`,type:"recovery",role:"system",strategy:f.action,text:f.detail,createdAt:_}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:f.turnId,slug:f.slug,content:f.content,item:{id:`${o}-plan-${we().slice(0,8)}`,type:"plan_update",role:"assistant",text:f.content,createdAt:_}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:f.turnId,text:f.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:f.turnId,items:f.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:f.turnId,mediaType:f.mediaType,url:f.url,...f.model?{model:f.model}:{},...f.provider?{provider:f.provider}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:f.turnId,artifactId:f.artifactId,type:f.artifactType,title:f.title,...f.filePath?{filePath:f.filePath}:{},...f.language?{language:f.language}:{},...f.content?{content:f.content}:{},...f.mimeType?{mimeType:f.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:f.turnId,subagentId:f.subagentId,agentType:f.agentType,...f.prompt?{prompt:f.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:f.turnId,subagentId:f.subagentId,agentType:f.agentType,ok:f.ok,...f.outputPreview?{outputPreview:f.outputPreview}:{},...f.error?{error:f.error}:{}});break}}if(this.log(`turn ${o} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){Ii(r,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:process.cwd(),messageCount:s.length}).catch(()=>{});let f=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:r,model:this.currentModel||void 0,cwd:process.cwd(),turnCount:f.turnCount}),this.currentTransport&&this.currentApiKey&&m.summaryModel&&Li(r,{sessionId:r,createdAt:0,lastActiveAt:0,turnCount:f.turnCount,messageCount:s.length},s,{transport:this.currentTransport,apiKey:this.currentApiKey,model:m.summaryModel}),this.currentTransport&&this.currentApiKey&&this.currentModel&&this.generateSuggestions(o,s,this.currentTransport,this.currentApiKey,this.currentModel)}}catch(m){if(p.signal.aborted)this.sendNotification("turn.error",{turnId:o,error:"Turn aborted",code:"ABORTED"});else{let h=m instanceof Error?m.message:String(m);this.sendNotification("turn.error",{turnId:o,error:h,code:"INTERNAL_ERROR"})}}finally{this.activeTurn===p&&(this.activeTurn=null)}}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
|
|
380
389
|
Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
|
|
381
390
|
Be specific: "run the tests" beats "continue".
|
|
382
391
|
Stay silent if the next step isn't obvious.
|
|
383
|
-
Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,
|
|
384
|
-
`),error:
|
|
385
|
-
`),E=
|
|
386
|
-
`)}}catch(j){return{success:!1,error:j.message}}},listResources:async b=>{let v=this.mcpManager;return v?(await v.listResources(b)).map(M=>({uri:M.uri,name:M.name,mimeType:M.mimeType,description:M.description,server:M.server})):[]},readResource:async(b,v)=>{let _=this.mcpManager;if(!_)throw new Error("MCP not initialized");return(await _.readResource(b,v)).map(W=>({uri:W.uri,mimeType:W.mimeType,text:W.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(b=>{l.warn(`[mcp] connection error: ${b instanceof Error?b.message:b}`)})}let h=[],k=Ss();P.existsSync(k)&&h.push(k);let w=e?.pluginPaths;if(Array.isArray(w))for(let g of w)typeof g=="string"&&P.existsSync(g)&&h.push(g);Ka(h,l).then(g=>{if(g.length===0)return;this.pluginLoader=new fo({pluginDirs:g,hookRegistry:u,log:l}),this.pluginLoader.loadAll().then(v=>{l.info(`[plugins] ${v.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(v=>{l.warn(`[plugins] load error: ${v instanceof Error?v.message:v}`)});let b=this.pluginLoader;u.register({point:"turn.submitted",handler:async()=>(await b.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(g=>{l.warn(`[plugins] marketplace resolve error: ${g instanceof Error?g.message:g}`)});let f=e?.permissions,C=or(f),R=new ho(C);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new bo({ruleEngine:R,hookRegistry:u,onRequestApproval:async g=>(this.sendNotification("tool.approval.request",{approvalId:g.approvalId,callId:g.callId,toolName:g.toolName,arguments:g.arguments?JSON.stringify(g.arguments):"",message:g.message,suggestions:g.suggestions?.map(b=>`${b.pattern}:${b.behavior}`)}),new Promise(()=>{})),onPermissionUpdate:g=>{l.info(`[permissions] rule saved: ${g.pattern} \u2192 ${g.behavior}`),this.sendNotification("permission.rule_updated",{pattern:g.pattern,behavior:g.behavior})},onDenied:(g,b)=>{l.warn(`[permissions] blocked "${g}": ${b}`)}});let L=Ce();this.permissionChecker.setToolMeta(L),this.permissionUnregister=this.permissionChecker.register();let K=sl({listSkills:()=>{let g=[];this.pluginLoader&&g.push(...this.pluginLoader.getPluginSkills());let b=e?.skillPaths;if(Array.isArray(b)){for(let v of b)if(typeof v=="string"){let _=Y.basename(v);g.some(M=>M.name===_)||g.push({name:_,source:"gateway",filePath:Y.join(v,"SKILL.md"),baseDir:v})}}return g},readSkillContent:async g=>{let b=[jt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];for(let v of b){let _=Y.join(v,g,"SKILL.md");try{return await P.promises.readFile(_,"utf8")}catch{}}return null},executeSkillSubturn:async(g,b,v,_)=>{let M=`skill_${g}_${ye().slice(0,8)}`,W=this.agent;if(!W)return"[skill] Cannot execute: no LLM provider configured";let Z=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`}).catch(()=>{});let z=Ce(),j=v??`Execute skill "${g}" instructions.`,E=[],O;for await(let N of W.run({turnId:M,sessionId:Z,messages:[{role:"user",content:j}],tools:z,systemPrompt:b,config:{parentDepth:1}},_)){if(N.type==="end"&&N.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`,reason:"normal"}).catch(()=>{}),N.content;if(N.type==="delta"&&N.text&&E.push(N.text),N.type==="error"){O=N.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`,reason:O?"error":"normal",error:O}).catch(()=>{}),O?`[skill "${g}"] error: ${O}`:E.join("")||`[skill "${g}"] completed (no output)`}});ne(K);let D=[jt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];ne(il({listSkills:async g=>{let b=[],v=new Set;for(let _ of D)try{let M=await P.promises.readdir(_,{withFileTypes:!0});for(let W of M){if(!W.isDirectory())continue;let Z=Y.join(_,W.name,"SKILL.md");try{await P.promises.access(Z);let z=Y.basename(_);if(g&&z!==g)continue;v.add(z),b.push({name:W.name,description:`Skill from ${_}`,category:z})}catch{}}}catch{}if(this.pluginLoader)for(let _ of this.pluginLoader.getPluginSkills())g&&_.source!==g||(v.add(_.source??"plugin"),b.push({name:_.name,description:`Plugin skill (${_.source})`,category:_.source}));return{skills:b,categories:[...v]}}})),ne(al({viewSkill:async(g,b)=>{for(let v of D){let _=b?Y.join(v,g,b):Y.join(v,g,"SKILL.md");try{let M=await P.promises.readFile(_,"utf8");return{name:g,content:M}}catch{}}return null}})),ne(cl({manageSkill:async g=>{let b=Y.join(D[0]??jt(),g.name),v=Y.join(b,"SKILL.md");switch(g.action){case"create":return await P.promises.mkdir(b,{recursive:!0}),await P.promises.writeFile(v,g.content??"","utf8"),{success:!0,message:`Skill "${g.name}" created`,path:b};case"edit":return await P.promises.writeFile(v,g.content??"","utf8"),{success:!0,message:`Skill "${g.name}" updated`,path:v};case"patch":{let _=await P.promises.readFile(v,"utf8");return!g.oldString||!_.includes(g.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await P.promises.writeFile(v,_.replace(g.oldString,g.newString??""),"utf8"),{success:!0,message:`Skill "${g.name}" patched`,path:v})}case"delete":return await P.promises.rm(b,{recursive:!0,force:!0}),{success:!0,message:`Skill "${g.name}" deleted`};case"write_file":{if(!g.filePath)return{success:!1,message:"filePath required for write_file"};let _=Y.join(b,g.filePath);return await P.promises.mkdir(Y.dirname(_),{recursive:!0}),await P.promises.writeFile(_,g.fileContent??"","utf8"),{success:!0,message:`File written: ${g.filePath}`,path:_}}case"remove_file":{if(!g.filePath)return{success:!1,message:"filePath required for remove_file"};let _=Y.join(b,g.filePath);return await P.promises.unlink(_).catch(()=>{}),{success:!0,message:`File removed: ${g.filePath}`}}default:return{success:!1,message:`Unknown action: ${g.action}`}}}})),ne(pl({abortSignal:void 0,currentForkDepth:0,forkAgent:async g=>{let b=Ko(g.agent);if(!b)return{agentId:"",status:"failed",error:`Unknown agent type: ${g.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let v=Se(),_=zo(v,b),W=Ce().filter(O=>_.includes(O.function.name)),Z=_n(W,!0),z=g.maxTurns??b.maxTurns??200,j=await Gt({promptMessages:[{role:"user",content:g.prompt}],tools:Z,transport:this.currentTransport,toolInvoker:c,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:u,forkLabel:`agent-${g.agent}`,maxTurns:z,parentSignal:g.abortSignal,parentDepth:0,onEvent:O=>{O.type==="delta"&&O.text&&this.sendNotification("turn.subagent_delta",{agentType:g.agent,text:O.text})}}),E=j.events.filter(O=>O.type==="end"&&"content"in O).map(O=>O.content??"").join("")||j.events.filter(O=>O.type==="delta"&&"text"in O).map(O=>O.text).join("");return{agentId:`fork-${g.agent}-${ye().slice(0,8)}`,status:j.ok?"completed":"failed",output:E||void 0,error:j.error,tokensUsed:j.totalUsage.prompt+j.totalUsage.completion}}}));let F=ze(),T=new Map([["model",{key:"model",value:this.currentModel??"",type:"string",description:"Default LLM model"}],["language",{key:"language",value:"zh-cn",type:"string",description:"UI / response language"}],["verbose",{key:"verbose",value:this.verbose,type:"boolean",description:"Enable verbose logging"}],["maxRounds",{key:"maxRounds",value:25,type:"number",description:"Default max tool-call rounds per turn"}],["theme",{key:"theme",value:"auto",type:"enum",description:"Color theme",options:["auto","light","dark"]}]]),B=async()=>{try{return JSON.parse(await P.promises.readFile(F,"utf8"))}catch{return{}}},J=async g=>{await P.promises.mkdir(Y.dirname(F),{recursive:!0}),await P.promises.writeFile(F,JSON.stringify(g,null,2),"utf8")};ne(ml({getConfig:async g=>{let b=T.get(g);if(!b)return{success:!1,error:`Unknown key: ${g}`};let v=await B(),_=g in v?v[g]:b.value;return{success:!0,setting:{...b,value:_,readOnly:_t.includes(g)}}},setConfig:async(g,b)=>{let v=T.get(g);if(!v)return{success:!1,error:`Unknown key: ${g}`};let _=await B(),M=g in _?_[g]:v.value;return _[g]=b,await J(_),{success:!0,previousValue:M,setting:{...v,value:b}}},listConfig:async()=>{let g=await B();return{success:!0,settings:[...T.values()].map(v=>({...v,value:v.key in g?g[v.key]:v.value,readOnly:_t.includes(v.key)}))}},resetConfig:async g=>{let b=T.get(g);if(!b)return{success:!1,error:`Unknown key: ${g}`};let v=await B();return delete v[g],await J(v),{success:!0,setting:b}},isValidKey:g=>T.has(g)}));let Q=new Map,ke=g=>{let b=/^(\d+)([smhd])$/.exec(g.trim());if(!b)return null;let v=parseInt(b[1],10),_=b[2];return v*({s:1e3,m:6e4,h:36e5,d:864e5}[_]??6e4)},oe=g=>{g.timerId&&clearTimeout(g.timerId);let b=ke(g.schedule);b&&(g.timerId=setTimeout(()=>{g.lastRunAt=new Date().toISOString(),g.repeat.completed++,g.lastStatus="success",l.info(`[cron] triggered job ${g.id} (${g.name})`),g.repeat.times===null||g.repeat.completed<g.repeat.times?oe(g):(g.state="paused",g.enabled=!1)},b),g.nextRunAt=new Date(Date.now()+b).toISOString())};Je(async()=>{for(let g of Q.values())g.timerId&&clearTimeout(g.timerId)}),ne(fl({createJob:async g=>{let b=`cron_${ye().slice(0,8)}`,v={id:b,name:g.name??`Job ${b}`,prompt:g.prompt,schedule:g.schedule,scheduleDisplay:g.schedule,state:"scheduled",enabled:!0,repeat:{times:g.repeat??null,completed:0},allowedTools:g.allowedTools};return Q.set(b,v),oe(v),{success:!0,job:{...v,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...Q.values()].map(b=>({...b,timerId:void 0}))}),getJob:async g=>{let b=Q.get(g);return b?{success:!0,job:{...b,timerId:void 0}}:{success:!1,error:`Job not found: ${g}`}},updateJob:async(g,b)=>{let v=Q.get(g);return v?(b.prompt!==void 0&&(v.prompt=b.prompt),b.schedule!==void 0&&(v.schedule=b.schedule,v.scheduleDisplay=b.schedule),b.name!==void 0&&(v.name=b.name),b.enabled!==void 0&&(v.enabled=b.enabled,v.state=b.enabled?"scheduled":"paused"),b.repeat!==void 0&&(v.repeat.times=b.repeat),b.allowedTools!==void 0&&(v.allowedTools=b.allowedTools),v.enabled?oe(v):v.timerId&&(clearTimeout(v.timerId),v.timerId=void 0),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},deleteJob:async g=>{let b=Q.get(g);return b?(b.timerId&&clearTimeout(b.timerId),Q.delete(g),{success:!0}):{success:!1,error:`Job not found: ${g}`}},pauseJob:async g=>{let b=Q.get(g);return b?(b.state="paused",b.enabled=!1,b.timerId&&(clearTimeout(b.timerId),b.timerId=void 0),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},resumeJob:async g=>{let b=Q.get(g);return b?(b.state="scheduled",b.enabled=!0,oe(b),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},triggerJob:async g=>{let b=Q.get(g);return b?(b.lastRunAt=new Date().toISOString(),b.repeat.completed++,b.lastStatus="success",{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},validateSchedule:g=>ke(g)!==null||/^\d{1,2}\s/.test(g)?null:`Invalid schedule: ${g}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let $=new Map;Je(async()=>{for(let g of $.values())g.cleanup();$.clear()}),ne(hl({startMonitor:async g=>{if($.has(g.monitorId))return{action:"start",success:!1,error:`Monitor "${g.monitorId}" already exists.`};let b={monitorId:g.monitorId,source:g.source,target:g.target,conditions:g.conditions,startedAt:Date.now(),timeoutSeconds:g.timeoutSeconds,eventCount:0},v=()=>{};if(g.source==="file")try{let _=P.watch(g.target,{persistent:!1},()=>{b.eventCount++,l.info(`[monitor] file change detected: ${g.target}`)});v=()=>_.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${g.target}`}}if(g.timeoutSeconds>0){let _=setTimeout(()=>{let W=$.get(g.monitorId);W&&(W.cleanup(),$.delete(g.monitorId))},g.timeoutSeconds*1e3),M=v;v=()=>{clearTimeout(_),M()}}return $.set(g.monitorId,{info:b,cleanup:v}),{action:"start",success:!0,monitorId:g.monitorId}},stopMonitor:async g=>{let b=$.get(g);return b?(b.cleanup(),$.delete(g),{action:"stop",success:!0,monitorId:g}):{action:"stop",success:!1,error:`Monitor "${g}" not found.`}},listMonitors:async()=>[...$.values()].map(g=>g.info)}));let A=new Map;ne(yl({createTeam:async g=>{if(A.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let b={name:g.teamName,description:g.description,leadId:this.currentSessionId??"default",members:g.members??[],createdAt:new Date().toISOString()};return A.set(g.teamName,b),this.sendNotification("team.updated",{teamName:g.teamName,action:"created",members:b.members.map(v=>({agentName:v.name,role:v.role}))}),{success:!0,team:b}},deleteTeam:async g=>A.has(g)?(A.delete(g),this.sendNotification("team.updated",{teamName:g,action:"destroyed",members:[]}),{success:!0}):{success:!1,error:`Team "${g}" not found.`},listTeams:async()=>({success:!0,teams:[...A.values()]}),getTeamStatus:async g=>{let b=A.get(g);return b?{success:!0,team:b}:{success:!1,error:`Team "${g}" not found.`}}}));{let g=new xo({persistToDisk:!0});g.loadFromDiskSync();let b={providerId:"null",search:async()=>[],ingest:async()=>{}},v=this.qmemoryAdapter??b;ne({name:vl,label:Cl,description:Sl,parameters:wl,execute:async(_,M)=>{let W=await _l(M,{provider:v,store:g,userId:this.qmemoryUserId||this.currentSessionId||"default",sessionId:this.currentSessionId});return{content:[{type:"text",text:W.message}],details:{type:"memory",action:W.action,ok:W.ok}}}})}{let g=e?.workdir??process.cwd(),b=xl(g,this.currentSessionId||"default");ne(kl(b))}let le=e?.workdir??process.cwd(),se=El({projectRoot:le,ruleEngine:R,hooks:u,log:g=>l.info(`[settings] ${g}`)});Je(async()=>{se()}),this.currentSessionId&&u.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let ce=e?.workdir??process.cwd();return hi({projectRoot:ce,sessionId:this.currentSessionId,hooks:u,log:g=>l.debug(g),onInstructionCacheReset:xi}).then(g=>{this.fileWatcher=g,Je(async()=>{this.fileWatcher?.stop()})}).catch(g=>{l.warn(`[file-watcher] init error: ${g instanceof Error?g.message:g}`)}),this.agent=new Ge({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:c,log:l,hooks:u,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=t,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=r,this.log(`created Agent (provider: ${n}, model: ${r})`),this.agent}loadSettingsSync(){try{let e=ze();if(!P.existsSync(e))return;let t=P.readFileSync(e,"utf-8"),n=JSON.parse(t);return{provider:n.provider,model:n.model,apiKey:n.apiKey,baseUrl:n.baseUrl}}catch{return}}handleSessionGetInfo(e){let t=this.currentSessionId||"default",n=this.sessionState?.createSnapshot(),r={sessionId:t,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:ws(t),agentHome:H(),settings:ze()},usage:n?{turnCount:n.turnCount,inputTokens:n.totalInputTokens,outputTokens:n.totalOutputTokens}:void 0};e.id!==void 0&&this.sendResponse(e.id,r)}async handleMemoryList(e){let t=[],n=Y.join(H(),"memory.json");P.existsSync(n)&&t.push({id:"local",type:"json",path:n}),this.qmemoryAdapter&&t.push({id:"qmemory",type:"vector"}),e.id!==void 0&&this.sendResponse(e.id,{sources:t})}async handleMemoryRead(e){let t=e.params,n=t?.source??"local",r=t?.target??"memory";if(n==="local")try{let s=Y.join(H(),"memory.json"),i=await P.promises.readFile(s,"utf-8"),a=JSON.parse(i);e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:r,content:a[r]??""})}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:r,content:""})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Unknown memory source: ${n}`})}async handleMemoryWrite(e){let t=e.params,n=t?.target??"memory",r=t?.content;if(n!=="memory"&&n!=="user"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Invalid memory target: ${n}. Must be "memory" or "user".`});return}if(r==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"content is required."});return}try{let s=Y.join(H(),"memory.json"),i={};try{let a=await P.promises.readFile(s,"utf-8");i=JSON.parse(a)}catch{}i[n]=r,i.savedAt=new Date().toISOString(),await P.promises.mkdir(H(),{recursive:!0}),await P.promises.writeFile(s,JSON.stringify(i,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,target:n}),this.sendNotification("memory.updated",{target:n,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,r=Ce().map(s=>({name:s.function.name,description:s.function.description??"",parameters:s.function.parameters,source:"builtin"}));if(t?.category){let s=r.filter(i=>i.name.startsWith(t.category)||i.description.toLowerCase().includes(t.category.toLowerCase()));e.id!==void 0&&this.sendResponse(e.id,{tools:s,total:s.length})}else e.id!==void 0&&this.sendResponse(e.id,{tools:r,total:r.length})}handleConfigGet(e){try{let t=ze(),n={};if(P.existsSync(t)){let r=P.readFileSync(t,"utf-8");n=JSON.parse(r)}e.id!==void 0&&this.sendResponse(e.id,{config:n,paths:{userSettings:t,agentHome:H()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleConfigUpdate(e){let t=e.params;if(!t?.updates||typeof t.updates!="object"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"updates (object) is required."});return}try{let n=ze(),r={};try{let s=await P.promises.readFile(n,"utf-8");r=JSON.parse(s)}catch{}Object.assign(r,t.updates),await P.promises.mkdir(Y.dirname(n),{recursive:!0}),await P.promises.writeFile(n,JSON.stringify(r,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(n){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)})}}async handleTodosList(e){let t=we("todo");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:Ke([])});return}try{let r=(await t.execute("rpc-todos-list",{action:"list"},void 0)).content.map(a=>a.text??"").join(""),i=JSON.parse(r).todoList??[];e.id!==void 0&&this.sendResponse(e.id,{items:i,summary:Ke(i)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:Ke([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){try{let n=Y.join(H(),"memory.json"),r=await P.promises.readFile(n,"utf-8"),s=JSON.parse(r),i=[],a=t.query.toLowerCase();for(let[l,c]of Object.entries(s)){if(typeof c!="string")continue;let u=c.split(`
|
|
392
|
+
Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;async generateSuggestions(e,t,o,r,s){if(t.filter(u=>u.role==="assistant").length<1)return;let c=[...t.slice(-6),{role:"user",content:n.SUGGESTION_PROMPT}];try{let u="";for await(let d of o.stream({model:s,messages:c,temperature:.3,maxTokens:200},r))d.type==="delta"&&(u+=d.text);let l=u.match(/\[[\s\S]*\]/);if(l){let d=JSON.parse(l[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??{},o=t.turnId??we(),r=t.sessionId,s=t.config,i=s?.memoryRoot??"",a=s?.transcriptDir??"",c=s?.dreamSessionIds??[];e.id!==void 0&&this.sendResponse(e.id,{accepted:!0,turnId:o});let u=new AbortController;this.activeTurn=u,this.log(`dream ${o} starting (session: ${r}, sessions reviewing: ${c.length})`);let l={provider:s?.provider,model:s?.model,apiKey:s?.apiKey,baseUrl:s?.baseUrl,maxRounds:s?.maxRounds,temperature:s?.temperature,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens};{let p=l.provider??"",m=l.model??"";p&&m&&this.registry.getModelInfo(p,m)?.streamRequired&&(l.streamRequired=!0)}if(!this.resolveAgent(l)){this.sendNotification("turn.start",{turnId:o}),this.sendNotification("turn.error",{turnId:o,error:"No LLM provider configured for dream.",code:"NO_PROVIDER"});return}this.sendNotification("turn.start",{turnId:o});try{let p={context:{memoryRoot:i,transcriptDir:a,currentSessionId:r,listSessionsSince:async()=>c},triggerConfig:{force:!0},transport:this.currentTransport,toolInvoker:{invoke:async(h,y,T,x)=>{if(y.startsWith("$"))return{result:T};let f=Ae(y);if(!f)return{result:"",error:`Unknown tool: ${y}`};let _=`tc_${we().slice(0,8)}`;try{let S=JSON.parse(T),O=await f.execute(_,S,x);return{result:O.content.map(D=>D.text??"").join(`
|
|
393
|
+
`),error:O.details?.error}}catch(S){return{result:"",error:S instanceof Error?S.message:String(S)}}}},tools:Ee(),apiKey:this.currentApiKey,model:l.model??this.currentModel,log:{info:h=>this.log(h),warn:h=>this.log(`[warn] ${h}`),error:h=>this.log(`[error] ${h}`),debug:h=>{this.verbose&&this.log(`[debug] ${h}`)}},hooks:this.currentHooks??void 0,parentSignal:u.signal,qmemoryAdapter:this.qmemoryAdapter??void 0,qmemoryUserId:this.qmemoryUserId||void 0},m=await Mi(p);m.ok?this.sendNotification("turn.end",{turnId:o,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:o,error:m.error??"Dream consolidation failed",code:"DREAM_FAILED"}),this.log(`dream ${o} completed`)}catch(p){if(u.signal.aborted)this.sendNotification("turn.error",{turnId:o,error:"Dream aborted",code:"ABORTED"});else{let m=p instanceof Error?p.message:String(p);this.sendNotification("turn.error",{turnId:o,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 o=e.provider,r=e.model,s=e.apiKey,i=e.baseUrl;if(!o||!s){let g=to(this.registry);g&&(o=o??g.providerId,s=s??g.apiKey,r=r??g.defaultModel,this.log(`auto-detected provider: ${o}, model: ${r}`))}if(!o||!s){let g=this.loadSettingsSync();g&&(o=o??g.provider,s=s??g.apiKey,r=r??g.model,o&&s&&this.log(`loaded provider from settings.json: ${o}, model: ${r}`))}if(!o||!s)return null;r=r??this.registry.getProvider(o)?.defaultModel??"";let a=eo({provider:o,model:r,apiKey:s,baseUrl:i},this.registry);En()&&(a.transport=On(a.transport,this.currentSessionId||"default"));let c={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}`)}},u={invoke:async(g,b,w,R)=>{if(b.startsWith("$"))return{result:w};let M=Ae(b);if(!M)return{result:"",error:`Unknown tool: ${b}`};let H=`tc_${we().slice(0,8)}`;try{let Z=JSON.parse(w),V=await M.execute(H,Z,R),N=V.content.map(B=>B.text??"").join(`
|
|
394
|
+
`),E=V.details?.error,L=V.details?.type;if(L&&["image","tts","video","music"].includes(L)){let B=V.details?.mediaUrls??[],he=L==="music"?"tts":L;for(let ye of B)this.sendNotification("turn.media_result",{turnId:g,mediaType:he,url:ye,model:V.details?.model,provider:V.details?.provider,...V.details?.durationMs?{durationSeconds:V.details.durationMs/1e3}:{}})}if(L==="todo"&&!E)try{let B=JSON.parse(N);B.todoList&&this.sendNotification("turn.todos_updated",{turnId:g,items:B.todoList,summary:{total:B.total??B.todoList.length,completed:B.completed??0,inProgress:B.inProgress??0,notStarted:B.notStarted??0}})}catch{}return{result:N,error:E}}catch(Z){return{result:"",error:Z instanceof Error?Z.message:String(Z)}}}},l=Ln(c);this.currentHooks=l,this.taskStore.setHooks(l,this.currentSessionId??"");let d=(process.env.QMEMORY_BASE_URL??process.env.QLOGICAGENT_QMEMORY_BASE_URL??"").trim().replace(/\/+$/,"");if(d){let g=ui({baseUrl:d,apiKey:(process.env.QMEMORY_API_KEY??"").trim()||void 0,timeoutMs:5e3});this.qmemoryAdapter=g,this.qmemoryUserId=this.currentSessionId??"default",li(l,{memoryProvider:g,userId:this.currentSessionId??"default",log:{debug:b=>c.debug(b),warn:b=>c.warn(b)}},this.memoryPrefetchState)}Is(l,c,{transport:a.transport,apiKey:a.apiKey});let p=e?.mcpServers,m=yr(p??{}),h=qs();try{if(P.existsSync(h)){let g=JSON.parse(P.readFileSync(h,"utf8")),b=yr(g),w=new Set(m.map(R=>R.name));m=[...m,...b.filter(R=>!w.has(R.name))]}}catch{}if(m.length>0){this.mcpManager&&this.mcpManager.disconnectAll().catch(()=>{}),this.mcpManager=new So({servers:m,log:c}),at(async()=>{await this.mcpManager?.disconnectAll()});let g=()=>this.mcpManager;ne(Tl(g)),ne(kl(g)),ne(Kl({listServers:async()=>{let b=this.mcpManager;return b?b.getConnectedServers().map(R=>({name:R,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})):[]},listTools:async b=>{if(!this.mcpManager)return[];let R=`mcp__${b.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return Ie().filter(M=>M.startsWith(R)).map(M=>({name:M.slice(R.length),prefixedName:M}))},callTool:async(b,w,R,M)=>{let Z=`mcp__${b.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+w,V=Ae(Z);if(!V)return{success:!1,error:`Tool not found: ${Z}`};try{return{success:!0,content:(await V.execute(`mcp_${Date.now()}`,R??{},M)).content.map(L=>L.text??"").join(`
|
|
395
|
+
`)}}catch(N){return{success:!1,error:N.message}}},listResources:async b=>{let w=this.mcpManager;return w?(await w.listResources(b)).map(M=>({uri:M.uri,name:M.name,mimeType:M.mimeType,description:M.description,server:M.server})):[]},readResource:async(b,w)=>{let R=this.mcpManager;if(!R)throw new Error("MCP not initialized");return(await R.readResource(b,w)).map(H=>({uri:H.uri,mimeType:H.mimeType,text:H.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),c.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(b=>{c.warn(`[mcp] connection error: ${b instanceof Error?b.message:b}`)})}let y=[],T=Hs();P.existsSync(T)&&y.push(T);let x=e?.pluginPaths;if(Array.isArray(x))for(let g of x)typeof g=="string"&&P.existsSync(g)&&y.push(g);_l(y,c).then(g=>{if(g.length===0)return;this.pluginLoader=new Mo({pluginDirs:g,hookRegistry:l,log:c}),this.pluginLoader.loadAll().then(w=>{c.info(`[plugins] ${w.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(w=>{c.warn(`[plugins] load error: ${w instanceof Error?w.message:w}`)});let b=this.pluginLoader;l.register({point:"turn.submitted",handler:async()=>(await b.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(g=>{c.warn(`[plugins] marketplace resolve error: ${g instanceof Error?g.message:g}`)});let f=e?.permissions,_=Tr(f),S=new Po(_);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new Io({ruleEngine:S,hookRegistry:l,onRequestApproval:async g=>(this.sendNotification("tool.approval.request",{approvalId:g.approvalId,callId:g.callId,toolName:g.toolName,arguments:g.arguments?JSON.stringify(g.arguments):"",message:g.message,suggestions:g.suggestions?.map(b=>`${b.pattern}:${b.behavior}`)}),new Promise(()=>{})),onPermissionUpdate:g=>{c.info(`[permissions] rule saved: ${g.pattern} \u2192 ${g.behavior}`),this.sendNotification("permission.rule_updated",{pattern:g.pattern,behavior:g.behavior})},onDenied:(g,b)=>{c.warn(`[permissions] blocked "${g}": ${b}`)}});let O=Ee();this.permissionChecker.setToolMeta(O),this.permissionUnregister=this.permissionChecker.register();let K=$l({listSkills:()=>{let g=[];this.pluginLoader&&g.push(...this.pluginLoader.getPluginSkills());let b=e?.skillPaths;if(Array.isArray(b)){for(let w of b)if(typeof w=="string"){let R=Y.basename(w);g.some(M=>M.name===R)||g.push({name:R,source:"gateway",filePath:Y.join(w,"SKILL.md"),baseDir:w})}}return g},readSkillContent:async g=>{let b=[qt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];for(let w of b){let R=Y.join(w,g,"SKILL.md");try{return await P.promises.readFile(R,"utf8")}catch{}}return null},executeSkillSubturn:async(g,b,w,R)=>{let M=`skill_${g}_${we().slice(0,8)}`,H=this.agent;if(!H)return"[skill] Cannot execute: no LLM provider configured";let Z=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`}).catch(()=>{});let V=Ee(),N=w??`Execute skill "${g}" instructions.`,E=[],L;for await(let B of H.run({turnId:M,sessionId:Z,messages:[{role:"user",content:N}],tools:V,systemPrompt:b,config:{parentDepth:1}},R)){if(B.type==="end"&&B.content)return this.currentHooks?.invoke("subagent.stopped",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`,reason:"normal"}).catch(()=>{}),B.content;if(B.type==="delta"&&B.text&&E.push(B.text),B.type==="error"){L=B.error;break}}return this.currentHooks?.invoke("subagent.stopped",{sessionId:Z,turnId:M,subagentId:M,agentType:`skill:${g}`,reason:L?"error":"normal",error:L}).catch(()=>{}),L?`[skill "${g}"] error: ${L}`:E.join("")||`[skill "${g}"] completed (no output)`}});ne(K);let D=[qt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];ne(Dl({listSkills:async g=>{let b=[],w=new Set;for(let R of D)try{let M=await P.promises.readdir(R,{withFileTypes:!0});for(let H of M){if(!H.isDirectory())continue;let Z=Y.join(R,H.name,"SKILL.md");try{await P.promises.access(Z);let V=Y.basename(R);if(g&&V!==g)continue;w.add(V),b.push({name:H.name,description:`Skill from ${R}`,category:V})}catch{}}}catch{}if(this.pluginLoader)for(let R of this.pluginLoader.getPluginSkills())g&&R.source!==g||(w.add(R.source??"plugin"),b.push({name:R.name,description:`Plugin skill (${R.source})`,category:R.source}));return{skills:b,categories:[...w]}}})),ne(Ul({viewSkill:async(g,b)=>{for(let w of D){let R=b?Y.join(w,g,b):Y.join(w,g,"SKILL.md");try{let M=await P.promises.readFile(R,"utf8");return{name:g,content:M}}catch{}}return null}})),ne(Fl({manageSkill:async g=>{let b=Y.join(D[0]??qt(),g.name),w=Y.join(b,"SKILL.md");switch(g.action){case"create":return await P.promises.mkdir(b,{recursive:!0}),await P.promises.writeFile(w,g.content??"","utf8"),{success:!0,message:`Skill "${g.name}" created`,path:b};case"edit":return await P.promises.writeFile(w,g.content??"","utf8"),{success:!0,message:`Skill "${g.name}" updated`,path:w};case"patch":{let R=await P.promises.readFile(w,"utf8");return!g.oldString||!R.includes(g.oldString)?{success:!1,message:"oldString not found in SKILL.md"}:(await P.promises.writeFile(w,R.replace(g.oldString,g.newString??""),"utf8"),{success:!0,message:`Skill "${g.name}" patched`,path:w})}case"delete":return await P.promises.rm(b,{recursive:!0,force:!0}),{success:!0,message:`Skill "${g.name}" deleted`};case"write_file":{if(!g.filePath)return{success:!1,message:"filePath required for write_file"};let R=Y.join(b,g.filePath);return await P.promises.mkdir(Y.dirname(R),{recursive:!0}),await P.promises.writeFile(R,g.fileContent??"","utf8"),{success:!0,message:`File written: ${g.filePath}`,path:R}}case"remove_file":{if(!g.filePath)return{success:!1,message:"filePath required for remove_file"};let R=Y.join(b,g.filePath);return await P.promises.unlink(R).catch(()=>{}),{success:!0,message:`File removed: ${g.filePath}`}}default:return{success:!1,message:`Unknown action: ${g.action}`}}}})),ne(Wl({abortSignal:void 0,currentForkDepth:0,forkAgent:async g=>{let b=cn(g.agent);if(!b)return{agentId:"",status:"failed",error:`Unknown agent type: ${g.agent}`};if(!this.agent||!this.currentTransport||!this.currentApiKey||!this.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let w=Ie(),R=an(w,b),H=Ee().filter(L=>R.includes(L.function.name)),Z=Wn(H,!0),V=g.maxTurns??b.maxTurns??200,N=await no({promptMessages:[{role:"user",content:g.prompt}],tools:Z,transport:this.currentTransport,toolInvoker:u,apiKey:this.currentApiKey,model:this.currentModel,log:c,hooks:l,forkLabel:`agent-${g.agent}`,maxTurns:V,parentSignal:g.abortSignal,parentDepth:0,onEvent:L=>{L.type==="delta"&&L.text&&this.sendNotification("turn.subagent_delta",{agentType:g.agent,text:L.text})}}),E=N.events.filter(L=>L.type==="end"&&"content"in L).map(L=>L.content??"").join("")||N.events.filter(L=>L.type==="delta"&&"text"in L).map(L=>L.text).join("");return{agentId:`fork-${g.agent}-${we().slice(0,8)}`,status:N.ok?"completed":"failed",output:E||void 0,error:N.error,tokensUsed:N.totalUsage.prompt+N.totalUsage.completion}}}));let F=Ze(),k=new Map([["model",{key:"model",value:this.currentModel??"",type:"string",description:"Default LLM model"}],["language",{key:"language",value:"zh-cn",type:"string",description:"UI / response language"}],["verbose",{key:"verbose",value:this.verbose,type:"boolean",description:"Enable verbose logging"}],["maxRounds",{key:"maxRounds",value:25,type:"number",description:"Default max tool-call rounds per turn"}],["theme",{key:"theme",value:"auto",type:"enum",description:"Color theme",options:["auto","light","dark"]}]]),j=async()=>{try{return JSON.parse(await P.promises.readFile(F,"utf8"))}catch{return{}}},J=async g=>{await P.promises.mkdir(Y.dirname(F),{recursive:!0}),await P.promises.writeFile(F,JSON.stringify(g,null,2),"utf8")};ne(Hl({getConfig:async g=>{let b=k.get(g);if(!b)return{success:!1,error:`Unknown key: ${g}`};let w=await j(),R=g in w?w[g]:b.value;return{success:!0,setting:{...b,value:R,readOnly:Dt.includes(g)}}},setConfig:async(g,b)=>{let w=k.get(g);if(!w)return{success:!1,error:`Unknown key: ${g}`};let R=await j(),M=g in R?R[g]:w.value;return R[g]=b,await J(R),{success:!0,previousValue:M,setting:{...w,value:b}}},listConfig:async()=>{let g=await j();return{success:!0,settings:[...k.values()].map(w=>({...w,value:w.key in g?g[w.key]:w.value,readOnly:Dt.includes(w.key)}))}},resetConfig:async g=>{let b=k.get(g);if(!b)return{success:!1,error:`Unknown key: ${g}`};let w=await j();return delete w[g],await J(w),{success:!0,setting:b}},isValidKey:g=>k.has(g)}));let Q=new Map,Se=g=>{let b=/^(\d+)([smhd])$/.exec(g.trim());if(!b)return null;let w=parseInt(b[1],10),R=b[2];return w*({s:1e3,m:6e4,h:36e5,d:864e5}[R]??6e4)},oe=g=>{g.timerId&&clearTimeout(g.timerId);let b=Se(g.schedule);b&&(g.timerId=setTimeout(()=>{g.lastRunAt=new Date().toISOString(),g.repeat.completed++,g.lastStatus="success",c.info(`[cron] triggered job ${g.id} (${g.name})`),g.repeat.times===null||g.repeat.completed<g.repeat.times?oe(g):(g.state="paused",g.enabled=!1)},b),g.nextRunAt=new Date(Date.now()+b).toISOString())};at(async()=>{for(let g of Q.values())g.timerId&&clearTimeout(g.timerId)}),ne(Gl({createJob:async g=>{let b=`cron_${we().slice(0,8)}`,w={id:b,name:g.name??`Job ${b}`,prompt:g.prompt,schedule:g.schedule,scheduleDisplay:g.schedule,state:"scheduled",enabled:!0,repeat:{times:g.repeat??null,completed:0},allowedTools:g.allowedTools};return Q.set(b,w),oe(w),{success:!0,job:{...w,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...Q.values()].map(b=>({...b,timerId:void 0}))}),getJob:async g=>{let b=Q.get(g);return b?{success:!0,job:{...b,timerId:void 0}}:{success:!1,error:`Job not found: ${g}`}},updateJob:async(g,b)=>{let w=Q.get(g);return w?(b.prompt!==void 0&&(w.prompt=b.prompt),b.schedule!==void 0&&(w.schedule=b.schedule,w.scheduleDisplay=b.schedule),b.name!==void 0&&(w.name=b.name),b.enabled!==void 0&&(w.enabled=b.enabled,w.state=b.enabled?"scheduled":"paused"),b.repeat!==void 0&&(w.repeat.times=b.repeat),b.allowedTools!==void 0&&(w.allowedTools=b.allowedTools),w.enabled?oe(w):w.timerId&&(clearTimeout(w.timerId),w.timerId=void 0),{success:!0,job:{...w,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},deleteJob:async g=>{let b=Q.get(g);return b?(b.timerId&&clearTimeout(b.timerId),Q.delete(g),{success:!0}):{success:!1,error:`Job not found: ${g}`}},pauseJob:async g=>{let b=Q.get(g);return b?(b.state="paused",b.enabled=!1,b.timerId&&(clearTimeout(b.timerId),b.timerId=void 0),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},resumeJob:async g=>{let b=Q.get(g);return b?(b.state="scheduled",b.enabled=!0,oe(b),{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},triggerJob:async g=>{let b=Q.get(g);return b?(b.lastRunAt=new Date().toISOString(),b.repeat.completed++,b.lastStatus="success",{success:!0,job:{...b,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},validateSchedule:g=>Se(g)!==null||/^\d{1,2}\s/.test(g)?null:`Invalid schedule: ${g}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let $=new Map;at(async()=>{for(let g of $.values())g.cleanup();$.clear()}),ne(Vl({startMonitor:async g=>{if($.has(g.monitorId))return{action:"start",success:!1,error:`Monitor "${g.monitorId}" already exists.`};let b={monitorId:g.monitorId,source:g.source,target:g.target,conditions:g.conditions,startedAt:Date.now(),timeoutSeconds:g.timeoutSeconds,eventCount:0},w=()=>{};if(g.source==="file")try{let R=P.watch(g.target,{persistent:!1},()=>{b.eventCount++,c.info(`[monitor] file change detected: ${g.target}`)});w=()=>R.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${g.target}`}}if(g.timeoutSeconds>0){let R=setTimeout(()=>{let H=$.get(g.monitorId);H&&(H.cleanup(),$.delete(g.monitorId))},g.timeoutSeconds*1e3),M=w;w=()=>{clearTimeout(R),M()}}return $.set(g.monitorId,{info:b,cleanup:w}),{action:"start",success:!0,monitorId:g.monitorId}},stopMonitor:async g=>{let b=$.get(g);return b?(b.cleanup(),$.delete(g),{action:"stop",success:!0,monitorId:g}):{action:"stop",success:!1,error:`Monitor "${g}" not found.`}},listMonitors:async()=>[...$.values()].map(g=>g.info)}));let I=new Map;ne(ql({createTeam:async g=>{if(I.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let b={name:g.teamName,description:g.description,leadId:this.currentSessionId??"default",members:g.members??[],createdAt:new Date().toISOString()};return I.set(g.teamName,b),this.sendNotification("team.updated",{teamName:g.teamName,action:"created",members:b.members.map(w=>({agentName:w.name,role:w.role}))}),{success:!0,team:b}},deleteTeam:async g=>I.has(g)?(I.delete(g),this.sendNotification("team.updated",{teamName:g,action:"destroyed",members:[]}),{success:!0}):{success:!1,error:`Team "${g}" not found.`},listTeams:async()=>({success:!0,teams:[...I.values()]}),getTeamStatus:async g=>{let b=I.get(g);return b?{success:!0,team:b}:{success:!1,error:`Team "${g}" not found.`}}}));{let g=new Lo({persistToDisk:!0});g.loadFromDiskSync();let b={providerId:"null",search:async()=>[],ingest:async()=>{}},w=this.qmemoryAdapter??b;ne({name:Ql,label:tc,description:ec,parameters:Zl,execute:async(R,M)=>{let H=await oc(M,{provider:w,store:g,userId:this.qmemoryUserId||this.currentSessionId||"default",sessionId:this.currentSessionId});return{content:[{type:"text",text:H.message}],details:{type:"memory",action:H.action,ok:H.ok}}}})}{let g=e?.workdir??process.cwd(),b=Xl(g,this.currentSessionId||"default");ne(Yl(b))}let ue=e?.workdir??process.cwd(),se=ac({projectRoot:ue,ruleEngine:S,hooks:l,log:g=>c.info(`[settings] ${g}`)});at(async()=>{se()}),this.currentSessionId&&l.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let de=e?.workdir??process.cwd();return Di({projectRoot:de,sessionId:this.currentSessionId,hooks:l,log:g=>c.debug(g),onInstructionCacheReset:Bi}).then(g=>{this.fileWatcher=g,at(async()=>{this.fileWatcher?.stop()})}).catch(g=>{c.warn(`[file-watcher] init error: ${g instanceof Error?g.message:g}`)}),this.agent=new Qe({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:u,log:c,hooks:l,maxRounds:e.maxRounds,verbose:this.verbose}),this.lastLlmConfigKey=t,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=r,this.log(`created Agent (provider: ${o}, model: ${r})`),this.agent}loadSettingsSync(){try{let e=Ze();if(!P.existsSync(e))return;let t=P.readFileSync(e,"utf-8"),o=JSON.parse(t);return{provider:o.provider,model:o.model,apiKey:o.apiKey,baseUrl:o.baseUrl}}catch{return}}handleSessionGetInfo(e){let t=this.currentSessionId||"default",o=this.sessionState?.createSnapshot(),r={sessionId:t,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:Ws(t),agentHome:G(),settings:Ze()},usage:o?{turnCount:o.turnCount,inputTokens:o.totalInputTokens,outputTokens:o.totalOutputTokens}:void 0};e.id!==void 0&&this.sendResponse(e.id,r)}async handleMemoryList(e){let t=[],o=Y.join(G(),"memory.json");P.existsSync(o)&&t.push({id:"local",type:"json",path:o}),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,o=t?.source??"local",r=t?.target??"memory";if(o==="local")try{let s=Y.join(G(),"memory.json"),i=await P.promises.readFile(s,"utf-8"),a=JSON.parse(i);e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:r,content:a[r]??""})}catch{e.id!==void 0&&this.sendResponse(e.id,{source:"local",target:r,content:""})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Unknown memory source: ${o}`})}async handleMemoryWrite(e){let t=e.params,o=t?.target??"memory",r=t?.content;if(o!=="memory"&&o!=="user"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:`Invalid memory target: ${o}. Must be "memory" or "user".`});return}if(r==null){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"content is required."});return}try{let s=Y.join(G(),"memory.json"),i={};try{let a=await P.promises.readFile(s,"utf-8");i=JSON.parse(a)}catch{}i[o]=r,i.savedAt=new Date().toISOString(),await P.promises.mkdir(G(),{recursive:!0}),await P.promises.writeFile(s,JSON.stringify(i,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,target:o}),this.sendNotification("memory.updated",{target:o,source:"rpc"})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}handleToolsList(e){let t=e.params,r=Ee().map(s=>({name:s.function.name,description:s.function.description??"",parameters:s.function.parameters,source:"builtin"}));if(t?.category){let s=r.filter(i=>i.name.startsWith(t.category)||i.description.toLowerCase().includes(t.category.toLowerCase()));e.id!==void 0&&this.sendResponse(e.id,{tools:s,total:s.length})}else e.id!==void 0&&this.sendResponse(e.id,{tools:r,total:r.length})}handleMediaListModels(e){let o=e.params?.mediaType,s=this.mediaClient.listMediaModels(o).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})}handleProviderList(e){let t=this.registry.listProviders(),o=new Map;for(let s of t){let i=s.group??s.id;o.has(i)||o.set(i,[]);let a=!!this.registry.resolveApiKey(s.id);o.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 r=[...o.entries()].map(([s,i])=>({group:s,variants:i}));e.id!==void 0&&this.sendResponse(e.id,{providers:r})}handleConfigGet(e){try{let t=Ze(),o={};if(P.existsSync(t)){let r=P.readFileSync(t,"utf-8");o=JSON.parse(r)}e.id!==void 0&&this.sendResponse(e.id,{config:o,paths:{userSettings:t,agentHome:G()}})}catch(t){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async handleConfigUpdate(e){let t=e.params;if(!t?.updates||typeof t.updates!="object"){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"updates (object) is required."});return}try{let o=Ze(),r={};try{let s=await P.promises.readFile(o,"utf-8");r=JSON.parse(s)}catch{}Object.assign(r,t.updates),await P.promises.mkdir(Y.dirname(o),{recursive:!0}),await P.promises.writeFile(o,JSON.stringify(r,null,2),"utf-8"),e.id!==void 0&&this.sendResponse(e.id,{ok:!0})}catch(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}async handleTodosList(e){let t=Ae("todo");if(!t){e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:st([])});return}try{let r=(await t.execute("rpc-todos-list",{action:"list"},void 0)).content.map(a=>a.text??"").join(""),i=JSON.parse(r).todoList??[];e.id!==void 0&&this.sendResponse(e.id,{items:i,summary:st(i)})}catch{e.id!==void 0&&this.sendResponse(e.id,{items:[],summary:st([])})}}async handleMemorySearch(e){let t=e.params;if(!t?.query){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"query is required."});return}if(!this.qmemoryAdapter){try{let o=Y.join(G(),"memory.json"),r=await P.promises.readFile(o,"utf-8"),s=JSON.parse(r),i=[],a=t.query.toLowerCase();for(let[c,u]of Object.entries(s)){if(typeof u!="string")continue;let l=u.split(`
|
|
387
396
|
\xA7
|
|
388
|
-
`).filter(
|
|
397
|
+
`).filter(d=>d.trim());for(let d=0;d<l.length;d++)l[d].toLowerCase().includes(a)&&i.push({id:`local-${c}-${d}`,text:l[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 o=t.userId??(this.qmemoryUserId||"default"),r=await this.qmemoryAdapter.search(t.query,o,{limit:t.limit??10});e.id!==void 0&&this.sendResponse(e.id,{results:r.map(s=>({id:s.blockId??"",text:s.text,score:s.score,source:"qmemory",metadata:s.metadata}))})}catch(o){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}async handleMemoryDelete(e){let t=e.params;if(!t?.match){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"match is required."});return}let o=t.source??"local";if(o==="local"){let r=t.target??"memory";try{let s=Y.join(G(),"memory.json"),i=await P.promises.readFile(s,"utf-8"),a=JSON.parse(i),u=(a[r]??"").split(`
|
|
389
398
|
\xA7
|
|
390
|
-
`).filter(m=>m.trim()),u
|
|
399
|
+
`).filter(m=>m.trim()),l=u.length,d=u.filter(m=>!m.includes(t.match));a[r]=d.join(`
|
|
391
400
|
\xA7
|
|
392
|
-
`),a.savedAt=new Date().toISOString(),await P.promises.writeFile(s,JSON.stringify(a,null,2),"utf-8");let
|
|
393
|
-
`)}};
|
|
401
|
+
`),a.savedAt=new Date().toISOString(),await P.promises.writeFile(s,JSON.stringify(a,null,2),"utf-8");let p=l-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:r})}catch(s){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:s instanceof Error?s.message:String(s)})}}else if(o==="qmemory"&&this.qmemoryAdapter)try{await this.qmemoryAdapter.remove(t.match),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,removedCount:1,message:"Removed from QMemory."}),this.sendNotification("memory.updated",{source:"qmemory"})}catch(r){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:o==="qmemory"?"QMemory not configured.":`Unknown source: ${o}`})}handleTasksList(e){let o=e.params?.lifecycle??"all",r=this.taskStore.getAllTasks(),s=o==="all"?r:r.filter(i=>i.lifecycle===o);e.id!==void 0&&this.sendResponse(e.id,{tasks:s.map(i=>({taskId:i.taskId,type:i.type,lifecycle:i.lifecycle,label:i.label}))})}handleTasksCancel(e){let t=e.params;if(!t?.taskId){e.id!==void 0&&this.sendResponse(e.id,void 0,{code:te.INVALID_PARAMS,message:"taskId is required."});return}let r=this.taskStore.getAllTasks().find(s=>s.taskId===t.taskId);if(!r){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} not found.`});return}if(r.lifecycle!=="running"&&r.lifecycle!=="pending"){e.id!==void 0&&this.sendResponse(e.id,{ok:!1,message:`Task ${t.taskId} is already ${r.lifecycle}.`});return}this.taskStore.updateTask(t.taskId,s=>(s.lifecycle="cancelled",s)),e.id!==void 0&&this.sendResponse(e.id,{ok:!0,message:`Task ${t.taskId} cancelled.`})}sendResponse(e,t,o){let r={jsonrpc:"2.0",id:e};o?r.error=o:r.result=t,this.writeStdout(r)}sendNotification(e,t){let o={jsonrpc:"2.0",method:e,params:t};this.writeStdout(o)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
|
|
402
|
+
`)}};Xe();export{Qe as Agent,et as ProviderRegistry,Pr as StdioServer,Tt as StdioTransport,to as autoDetectProvider,ht as buildSkillInstruction,Ln as createHookRegistry,eo as createLLMClient,od as parseCliArgs};
|