qlogicagent 2.10.9 → 2.10.11

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/index.js CHANGED
@@ -11,7 +11,7 @@ var Uk=Object.defineProperty;var gi=(n=>typeof require<"u"?require:typeof Proxy<
11
11
  ${m}`}))}if(l.length===0)return n;let d=[...n],u=-1;for(let p=0;p<d.length;p++)d[p].role==="system"&&(u=p);return d.splice(u+1,0,...l),d}function xi(n,e,t=Ti){if(e.size===0)return{messages:n,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of n){let l=a.tool_call_id??"";if(l&&e.has(l)){o+=t(a),r++,e.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}var Ld,Dn,bn,fo,go,$d,ho,yo,yv,on,Ri=N(()=>{"use strict";Ld=4,Dn=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,t){let o=[],r=[];for(let d of e)d.role==="system"?o.push(d):r.push(d);let s=t;for(let d of o)s-=this.estimateTokens(d);let i;for(let d of r)if(d.role==="user"){i=d;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let d=r.length-1;d>=0;d--){let u=r[d];if(u===i)continue;let p=this.estimateTokens(u);if(s-p<0&&l>=Ld)break;if(s-p<0&&l<Ld){a.unshift(u),l++;continue}s-=p,a.unshift(u),l++}let c=[...o];return i&&!a.includes(i)&&c.push(i),c.push(...a),{messages:c,droppedCount:r.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},bn=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:gv(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};fo=class{config;constructor(e){this.config={protectedHeadExchanges:e.protectedHeadExchanges,protectedTailMessages:e.protectedTailMessages,summarize:e.summarize,estimateTokens:e.estimateTokens??Ti,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}=hv(e),i=e.reduce((I,P)=>I+this.config.estimateTokens(P),0);if(i<=t)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let I=0;I<s.length&&(s[I].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));I++)a=I+1;let c=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),d=Math.max(a,s.length-c);if(d<=a)return{messages:e,droppedCount:0,strategy:"head-tail-protected"};let u=s.slice(0,a),p=s.slice(a,d),m=s.slice(d),h=Nd(p,{taskContext:this.config.taskContext}),f=await this.config.summarize(p,h),y={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
12
12
 
13
13
  ${f}`},b=[...r,...u,y,...m],k=Date.now()-o,x=b.reduce((I,P)=>I+this.config.estimateTokens(P),0);return{messages:b,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:x,compressionRatio:i>0?x/i:1,latencyMs:k,usedLlm:!0,cacheInvalidated:!0}}}},go=class{config;constructor(e){this.config=e}compress(e,t){let o=vr(e),r=this.config.inner.compress(e,t),s=vr(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=vr(e),r=bo(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=vr(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}}}},$d={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};ho=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}},yo=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}))}};yv=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"]),on=class{constructor(e=20,t=Ti){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,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!yv.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 _i(){return{stages:[]}}function Ai(n,e,t){let o=t?.thresholdMessages??40;if(n.filter(a=>a.role!=="system").length<=o)return{messages:n,stagedCount:0};let s=Ud(n,e),i=kv(s,e,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Ud(n,e),{messages:s,stagedCount:i.length}}function Pi(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:jd(n,e),committed:t}}function Ud(n,e){return e.stages.filter(o=>o.committed).length===0?n:jd(n,e)}function jd(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),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function kv(n,e,t){let o=Math.max(0,n.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<o;l++){let c=n[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let u=`${i}-${i+a}`;s.has(u)||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 Fd=N(()=>{"use strict"});function ma(){return{maxRoundsLimit:100,defaultMaxRounds:25,defaultTemperature:0,maxToolBudgetCap:100,defaultToolBudget:Ii,maxConsecutiveFailures:Ci,maxIdenticalCallRepeats:Ei,defaultContextWindowTokens:Mi,responseBufferTokens:Oi,defaultMaxOutputTokens:Di,defaultModelMaxOutputTokens:Li,maxOutputTokensRecoveryLimit:Ni,escalatedMaxOutputTokens:$i,diminishingReturnsThreshold:wr,diminishingReturnsMinContinuations:Ui,defaultMaxResultSizeChars:ji,maxToolResultsPerMessageChars:Fi,toolResultPreviewBytes:xr,heartbeatIntervalMs:Bi,max529Retries:Wi,maxApiRetries:Ln,persistentRetryMaxBackoffMs:vv,persistentRetryResetCapMs:Sv,compressionTargetUsageRatio:Tv,compressionMinBudget:wv,compressionMaxBudget:xv,reactiveCompactMaxFailures:Rv,reactiveCompactMinMessages:_v,reactiveCompactTargetPercent:Av,maxSkillsPerProject:Gi,maxSkillsGlobal:Bd,minToolCallsForSkill:Hi,minDistinctToolsForSkill:Vi,skillCreationCooldownMs:Ki,skillInjectionMaxChars:Pv,skillInjectionMaxCount:Iv,skillRecallMaxSkills:zi,skillRecallMaxContentChars:qi,skillRecallCacheTtlMs:Yi,maxForkDepth:Xi,maxSessions:Qi,taskSummaryTurnThreshold:Zi,taskSummaryRegenInterval:ea,maxIncludeDepth:ta,maxInstructionChars:Cv,instructionsMaxFileSize:na,instructionsMaxDirSize:oa,mediaMaxDownloadSize:ra,mediaMaxUploadSize:Ev,mediaDownloadTimeoutMs:sa,acpMaxSpawnRetries:ia,acpRetryBackoffBase:aa,acpRuntimeRestartMax:la,acpRuntimeRestartBackoffBase:ca,taskPollIntervalMs:Mv,taskStoppedDisplayMs:Ov,taskPanelGraceMs:Dv,memoryPrefetchMaxSessionBytes:da,memoryPrefetchLimitPerRecall:ua,memoryMaxSurfacedEntries:pa,dreamMinIntervalHours:Lv,dreamMinSessions:Nv,dreamScanIntervalMs:$v,idleDreamMinutes:Uv,dreamCooldownMs:jv,dreamMaxDurationMs:Fv,teamBudgetTokens:Ji}}var Ii,Ci,Ei,Tr,Mi,Oi,Di,Li,Ni,$i,wr,Ui,ji,Fi,xr,Bi,Wi,Ln,vv,Sv,Tv,wv,xv,Rv,_v,Av,Gi,Bd,Hi,Vi,Ki,Wd,Gd,Pv,Iv,zi,qi,Yi,Xi,Ji,Qi,Zi,ea,Hd,Vd,ta,Cv,na,oa,ra,Ev,sa,ia,aa,la,ca,Mv,Ov,Dv,da,ua,pa,Lv,Nv,$v,Uv,jv,Fv,je=N(()=>{"use strict";Ii=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ci=3,Ei=2,Tr=2,Mi=128e3,Oi=13e3,Di=16384,Li=65536,Ni=3,$i=65536,wr=500,Ui=3,ji=5e4,Fi=2e5,xr=2e3,Bi=3e4,Wi=3,Ln=2,vv=3e5,Sv=216e5,Tv=.75,wv=16e3,xv=12e4,Rv=3,_v=4,Av=50,Gi=20,Bd=50,Hi=3,Vi=2,Ki=300*1e3,Wd=3,Gd=720*60*60*1e3,Pv=4e3,Iv=5,zi=3,qi=800,Yi=300*1e3,Xi=4,Ji=0,Qi=50,Zi=50,ea=30,Hd=3600*1e3,Vd=200,ta=5,Cv=4e4,na=50*1024,oa=500*1024,ra=500*1024*1024,Ev=50*1024*1024,sa=3e5,ia=2,aa=3e3,la=3,ca=5e3,Mv=1e3,Ov=3e3,Dv=3e4,da=60*1024,ua=10,pa=100,Lv=24,Nv=5,$v=6e5,Uv=30,jv=144e5,Fv=3e5});import{existsSync as fa,readFileSync as zd,writeFileSync as Bv,readdirSync as qd,mkdirSync as Wv}from"node:fs";import{join as ga,dirname as Gv}from"node:path";function Xd(n){return ga(n,".qlogicagent",Hv)}function Vv(n){let e=Xd(n);try{return JSON.parse(zd(e,"utf8"))}catch{return{version:1,patterns:{}}}}function Kd(n,e){let t=Xd(n);Wv(Gv(t),{recursive:!0}),Bv(t,JSON.stringify(e,null,2),"utf8")}function Kv(n){let e=Date.now()-Gd;for(let[t,o]of Object.entries(n.patterns))new Date(o.lastSeen).getTime()<e&&delete n.patterns[t]}function Jd(n,e){if(e.length===0)return!1;let t=Rr(e),o=Vv(n);Kv(o);let r=new Date().toISOString(),s=o.patterns[t];if(s||(s={signature:t,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[t]=s),s.promoted)return Kd(n,o),!1;s.count++,s.lastSeen=r;let i=s.count>=Wd;return i&&(s.promoted=!0),Kd(n,o),i}function Rr(n){return[...n].sort().join("+")}function zv(n,e){if(!fa(e))return null;let t=Rr(n);try{let o=qd(e,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=ga(e,r.name,"SKILL.md");try{let a=zd(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let l=a[1].split(`
14
- `).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Rr(l)===t)return r.name}}catch{}}}catch{}return null}function qv(n){if(!fa(n))return 0;try{return qd(n,{withFileTypes:!0}).filter(e=>e.isDirectory()&&fa(ga(n,e.name,"SKILL.md"))).length}catch{return 0}}function Yv(n,e){return!(!n.ok||n.existingSkillName||!n.multiStep||n.toolCallCount<Hi||n.distinctToolCount<Vi||Date.now()-Yd<Ki||e?.projectSkillsDir&&(qv(e.projectSkillsDir)>=Gi||e.tools.length>0&&zv(e.tools,e.projectSkillsDir))||e?.projectRoot&&e.tools.length>0&&!Jd(e.projectRoot,e.tools))}function Xv(n){return n.existingSkillName?n.feedback==="negative":!1}function vo(n,e){return Xv(n)?{type:"skill.improve",skillName:n.existingSkillName,reason:"negative user feedback on existing skill execution"}:Yv(n,e)?(Yd=Date.now(),{type:"skill.create",suggestedName:e.suggestedName??`auto-skill-${e.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${e.tools.join(", ")}`,tools:e.tools,stepCount:n.toolCallCount}):null}var Yd,Hv,Qd=N(()=>{"use strict";je();Yd=0,Hv="skill-patterns.json"});function Zd(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 Jv(n){return n==="enabled-eligible"||n==="installed-awaiting-approval"}function Qv(n){return new Map((n??[]).map(e=>[e.toolName,e]))}function Zv(n){if(!n.eligibility?.length)return[...n.tools];let e=Qv(n.eligibility);return n.tools.filter(t=>{let o=Zd(t);if(!o)return!1;let r=e.get(o);return!r||Jv(r.status)})}function eS(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 ha(n){let e=eS({toolChoice:n.toolChoice,thinkingEnabled:n.thinkingEnabled,compatibility:n.compatibility}),t=e.normalizedToolChoice,o=[...e.warnings],r=Zv({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(l=>Zd(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:t,warnings:o}}var eu=N(()=>{"use strict"});function tu(n){return n==null?[]:typeof n=="string"?n.length>0?[{type:"text",text:n}]:[]:Array.isArray(n)?n:[{type:"text",text:String(n)}]}function oS(n,e){return{...n,content:[...tu(n.content),...tu(e.content)]}}function rS(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 sS(n){return new Set((n??tS).map(e=>e.trim().toLowerCase()))}function iS(n,e){return n?sS(e).has(n.trim().toLowerCase()):!1}function ya(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 l=a.tool_calls.filter(c=>rS(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 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 l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...d}=a;d.content!=null&&d.content!==""&&s.push(d);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]=oS(l,a);continue}i.push(a)}return i}function ba(n,e){return iS(e?.stopReason,e?.forcedStopReasons)?n.map(t=>{if(t.role!=="assistant")return{...t};let o={...t};for(let r of nS)delete o[r];return o}):[...n]}function ka(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 va(n,e){let t=ya(n),o=ba(t,e);return ka(o,e)}var tS,nS,Sa=N(()=>{"use strict";tS=["stop","aborted","timeout","cancelled","interrupted","error"],nS=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function aS(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 lS(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 cS(n){return{round:n.round??0,maxRounds:n.maxRounds,pendingToolCallIds:[...n.pendingToolCallIds??[]],completedToolCallIds:[...n.completedToolCallIds??[]],lastStopReason:n.lastStopReason,replayMessages:[...n.replayMessages??[]]}}function Ta(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 _r(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 Ar(n){let e=[],t=ya(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=ba(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=ka(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:cS({maxRounds:n.maxRounds,round:n.round,lastStopReason:n.lastStopReason,replayMessages:r,pendingToolCallIds:aS(r),completedToolCallIds:lS(r)}),recoveryActions:e}}var nu=N(()=>{"use strict";Sa()});function wa(n){return n?dS.has(n):!0}function xa(n){return n===429||n===529}function Pr(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 Ir(){let n=process.env.QLOGICAGENT_PERSISTENT_RETRY;return n==="1"||n==="true"}var dS,mM,So,ou=N(()=>{"use strict";dS=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);mM={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};So=class extends Error{constructor(t,o){super(`Model fallback triggered: ${t} -> ${o}`);this.originalModel=t;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Ra(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 _a=N(()=>{"use strict";je()});function Aa(){return[...ru]}function Cr(n){return ru.find(e=>e.name===n)}var uS,pS,mS,fS,gS,hS,ru,Pa=N(()=>{"use strict";uS={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},pS={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},mS={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},fS={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},gS={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},hS={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},ru=[uS,pS,mS,fS,gS,hS]});var su=N(()=>{"use strict"});function Ia(n){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:n.maxOutputTokens,consecutiveTruncations:0,aborted:n.abortSignal?.aborted??!1}}function Ca(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 Ea(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 Ma(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 Oa(n,e){return n.aborted?!0:e.abortSignal?.aborted?(n.aborted=!0,!0):!1}var iu=N(()=>{"use strict"});function Da(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Nn(n,e=yS){return!(n.attemptedThisTurn||n.consecutiveFailures>=e.maxConsecutiveFailures)}var yS,au=N(()=>{"use strict";yS={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var $n=N(()=>{"use strict";Rd();Dd();Ri();Ri();Fd();Qd();eu();Sa();nu();ou();_a();Pa();su();iu();au()});function La(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 lu=N(()=>{"use strict"});var cu=N(()=>{"use strict"});var du=N(()=>{"use strict"});function Er(n){return typeof n.deleteVideoTask=="function"&&typeof n.listVideoTasks=="function"}var uu=N(()=>{"use strict"});function pu(n){let e=n.usage??n.data?.usage,t=rn(e?.completion_tokens)??rn(e?.completionTokens)??rn(e?.output_tokens)??rn(e?.outputTokens)??rn(e?.total_tokens)??rn(e?.totalTokens)??0,o=rn(e?.total_tokens)??rn(e?.totalTokens)??t;return{completionTokens:t,totalTokens:o,hasUsage:!!e,rawUsage:e}}function rn(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()){let e=Number(n);if(Number.isFinite(e))return e}}var dt,Mr=N(()=>{"use strict";dt=class{supportedTypes=["image","video","3d","embedding"];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);case"embedding":return this.generateEmbedding(e,t,o);default:throw new Error(`VolcengineMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateEmbedding(e,t,o){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("VolcengineMediaTransport: text or prompt is required for embedding");let i=`${this.baseUrl}/embeddings/multimodal`,a={model:e.model||"doubao-embedding-vision-251215",input:[{type:"text",text:s}]},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`Volcengine embedding error ${l.status}: ${m}`)}let c=await l.json(),u=(Array.isArray(c.data)?c.data:c.data?[c.data]:[]).map(m=>m.embedding).filter(m=>Array.isArray(m)),p=c.usage?.total_tokens??c.usage?.prompt_tokens;return{mediaUrls:[],model:c.model??e.model??"doubao-embedding-vision-251215",durationMs:Date.now()-r,billingUnit:p!==void 0?"per_token":void 0,billingQuantity:p,metadata:{embeddings:u,dimensions:u[0]?.length??0,usage:c.usage}}}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",sequential_image_generation:"disabled",watermark:!0};e.imageUrl&&(i.image=e.imageUrl),e.referenceImages&&e.referenceImages.length>0&&(i.image_urls=e.referenceImages),e.style&&(i.style=e.style),e.quality&&(i.quality=e.quality),e.seed!==void 0&&(i.seed=e.seed),e.guidanceScale!==void 0&&(i.guidance_scale=e.guidanceScale),e.enhancePrompt!==void 0&&(i.enhance_prompt=e.enhancePrompt),e.streamImage&&(i.stream=!0);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${d}`)}if(e.streamImage&&a.body)return this.parseStreamingImage(a.body,e,r);let c=((await a.json()).data??[]).map(d=>d.url).filter(d=>!!d);return{mediaUrls:c,model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r,billingUnit:"per_call",billingQuantity:e.n??Math.max(c.length,1),metadata:{billableUnits:{images:e.n??Math.max(c.length,1)},pricingSpec:e.size??"1024x1024"}}}async parseStreamingImage(e,t,o){let r=new TextDecoder,s="",i="",a=e.getReader();try{for(;;){let{done:l,value:c}=await a.read();if(l)break;s+=r.decode(c,{stream:!0});let d;for(;(d=s.indexOf(`
14
+ `).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Rr(l)===t)return r.name}}catch{}}}catch{}return null}function qv(n){if(!fa(n))return 0;try{return qd(n,{withFileTypes:!0}).filter(e=>e.isDirectory()&&fa(ga(n,e.name,"SKILL.md"))).length}catch{return 0}}function Yv(n,e){return!(!n.ok||n.existingSkillName||!n.multiStep||n.toolCallCount<Hi||n.distinctToolCount<Vi||Date.now()-Yd<Ki||e?.projectSkillsDir&&(qv(e.projectSkillsDir)>=Gi||e.tools.length>0&&zv(e.tools,e.projectSkillsDir))||e?.projectRoot&&e.tools.length>0&&!Jd(e.projectRoot,e.tools))}function Xv(n){return n.existingSkillName?n.feedback==="negative":!1}function vo(n,e){return Xv(n)?{type:"skill.improve",skillName:n.existingSkillName,reason:"negative user feedback on existing skill execution"}:Yv(n,e)?(Yd=Date.now(),{type:"skill.create",suggestedName:e.suggestedName??`auto-skill-${e.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${e.tools.join(", ")}`,tools:e.tools,stepCount:n.toolCallCount}):null}var Yd,Hv,Qd=N(()=>{"use strict";je();Yd=0,Hv="skill-patterns.json"});function Zd(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 Jv(n){return n==="enabled-eligible"||n==="installed-awaiting-approval"}function Qv(n){return new Map((n??[]).map(e=>[e.toolName,e]))}function Zv(n){if(!n.eligibility?.length)return[...n.tools];let e=Qv(n.eligibility);return n.tools.filter(t=>{let o=Zd(t);if(!o)return!1;let r=e.get(o);return!r||Jv(r.status)})}function eS(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 ha(n){let e=eS({toolChoice:n.toolChoice,thinkingEnabled:n.thinkingEnabled,compatibility:n.compatibility}),t=e.normalizedToolChoice,o=[...e.warnings],r=Zv({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(l=>Zd(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:t,warnings:o}}var eu=N(()=>{"use strict"});function tu(n){return n==null?[]:typeof n=="string"?n.length>0?[{type:"text",text:n}]:[]:Array.isArray(n)?n:[{type:"text",text:String(n)}]}function oS(n,e){return{...n,content:[...tu(n.content),...tu(e.content)]}}function rS(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 sS(n){return new Set((n??tS).map(e=>e.trim().toLowerCase()))}function iS(n,e){return n?sS(e).has(n.trim().toLowerCase()):!1}function ya(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 l=a.tool_calls.filter(c=>rS(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 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 l=a.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(l.length===0){let{tool_calls:c,...d}=a;d.content!=null&&d.content!==""&&s.push(d);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]=oS(l,a);continue}i.push(a)}return i}function ba(n,e){return iS(e?.stopReason,e?.forcedStopReasons)?n.map(t=>{if(t.role!=="assistant")return{...t};let o={...t};for(let r of nS)delete o[r];return o}):[...n]}function ka(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 va(n,e){let t=ya(n),o=ba(t,e);return ka(o,e)}var tS,nS,Sa=N(()=>{"use strict";tS=["stop","aborted","timeout","cancelled","interrupted","error"],nS=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function aS(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 lS(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 cS(n){return{round:n.round??0,maxRounds:n.maxRounds,pendingToolCallIds:[...n.pendingToolCallIds??[]],completedToolCallIds:[...n.completedToolCallIds??[]],lastStopReason:n.lastStopReason,replayMessages:[...n.replayMessages??[]]}}function Ta(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 _r(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 Ar(n){let e=[],t=ya(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=ba(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=ka(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:cS({maxRounds:n.maxRounds,round:n.round,lastStopReason:n.lastStopReason,replayMessages:r,pendingToolCallIds:aS(r),completedToolCallIds:lS(r)}),recoveryActions:e}}var nu=N(()=>{"use strict";Sa()});function wa(n){return n?dS.has(n):!0}function xa(n){return n===429||n===529}function Pr(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 Ir(){let n=process.env.QLOGICAGENT_PERSISTENT_RETRY;return n==="1"||n==="true"}var dS,gM,So,ou=N(()=>{"use strict";dS=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);gM={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};So=class extends Error{constructor(t,o){super(`Model fallback triggered: ${t} -> ${o}`);this.originalModel=t;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Ra(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 _a=N(()=>{"use strict";je()});function Aa(){return[...ru]}function Cr(n){return ru.find(e=>e.name===n)}var uS,pS,mS,fS,gS,hS,ru,Pa=N(()=>{"use strict";uS={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},pS={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},mS={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},fS={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},gS={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},hS={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},ru=[uS,pS,mS,fS,gS,hS]});var su=N(()=>{"use strict"});function Ia(n){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:n.maxOutputTokens,consecutiveTruncations:0,aborted:n.abortSignal?.aborted??!1}}function Ca(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 Ea(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 Ma(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 Oa(n,e){return n.aborted?!0:e.abortSignal?.aborted?(n.aborted=!0,!0):!1}var iu=N(()=>{"use strict"});function Da(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Nn(n,e=yS){return!(n.attemptedThisTurn||n.consecutiveFailures>=e.maxConsecutiveFailures)}var yS,au=N(()=>{"use strict";yS={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var $n=N(()=>{"use strict";Rd();Dd();Ri();Ri();Fd();Qd();eu();Sa();nu();ou();_a();Pa();su();iu();au()});function La(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 lu=N(()=>{"use strict"});var cu=N(()=>{"use strict"});var du=N(()=>{"use strict"});function Er(n){return typeof n.deleteVideoTask=="function"&&typeof n.listVideoTasks=="function"}var uu=N(()=>{"use strict"});function pu(n){let e=n.usage??n.data?.usage,t=rn(e?.completion_tokens)??rn(e?.completionTokens)??rn(e?.output_tokens)??rn(e?.outputTokens)??rn(e?.total_tokens)??rn(e?.totalTokens)??0,o=rn(e?.total_tokens)??rn(e?.totalTokens)??t;return{completionTokens:t,totalTokens:o,hasUsage:!!e,rawUsage:e}}function rn(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()){let e=Number(n);if(Number.isFinite(e))return e}}var dt,Mr=N(()=>{"use strict";dt=class{supportedTypes=["image","video","3d","embedding"];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);case"embedding":return this.generateEmbedding(e,t,o);default:throw new Error(`VolcengineMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateEmbedding(e,t,o){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("VolcengineMediaTransport: text or prompt is required for embedding");let i=`${this.baseUrl}/embeddings/multimodal`,a={model:e.model||"doubao-embedding-vision-251215",input:[{type:"text",text:s}]},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`Volcengine embedding error ${l.status}: ${m}`)}let c=await l.json(),u=(Array.isArray(c.data)?c.data:c.data?[c.data]:[]).map(m=>m.embedding).filter(m=>Array.isArray(m)),p=c.usage?.total_tokens??c.usage?.prompt_tokens;return{mediaUrls:[],model:c.model??e.model??"doubao-embedding-vision-251215",durationMs:Date.now()-r,billingUnit:p!==void 0?"per_token":void 0,billingQuantity:p,metadata:{embeddings:u,dimensions:u[0]?.length??0,usage:c.usage}}}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",sequential_image_generation:"disabled",watermark:!0};e.imageUrl&&(i.image=e.imageUrl),e.referenceImages&&e.referenceImages.length>0&&(i.image_urls=e.referenceImages),e.style&&(i.style=e.style),e.quality&&(i.quality=e.quality),e.seed!==void 0&&(i.seed=e.seed),e.guidanceScale!==void 0&&(i.guidance_scale=e.guidanceScale),e.enhancePrompt!==void 0&&(i.enhance_prompt=e.enhancePrompt),e.streamImage&&(i.stream=!0);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`Volcengine image API error ${a.status}: ${d}`)}if(e.streamImage&&a.body)return this.parseStreamingImage(a.body,e,r);let c=((await a.json()).data??[]).map(d=>d.url).filter(d=>!!d);return{mediaUrls:c,model:e.model,size:e.size??"1024x1024",durationMs:Date.now()-r,billingUnit:"per_call",billingQuantity:e.n??Math.max(c.length,1),metadata:{billableUnits:{images:e.n??Math.max(c.length,1)},pricingSpec:e.size??"1024x1024"}}}async parseStreamingImage(e,t,o){let r=new TextDecoder,s="",i="",a=e.getReader();try{for(;;){let{done:l,value:c}=await a.read();if(l)break;s+=r.decode(c,{stream:!0});let d;for(;(d=s.indexOf(`
15
15
  `))!==-1;){let u=s.slice(0,d).trim();if(s=s.slice(d+1),!u||u.startsWith(":")||!u.startsWith("data:"))continue;let p=u.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,billingUnit:"per_call",billingQuantity:1,metadata:{billableUnits:{images:1},pricingSpec:t.size??"1024x1024"}}}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,l=e.referenceImages?.length??0,c=!!(e.imageUrl||l>0);if(i>3)throw new Error(`Seedance 2.0: max 3 reference videos (got ${i}). Total duration must be \u922E?5s.`);if(a>3)throw new Error(`Seedance 2.0: max 3 reference audios (got ${a}). Total duration must be \u922E?5s.`);if(a>0&&!c&&i===0)throw new Error("Seedance 2.0: reference audio cannot be used alone. Provide at least one reference image or video.");if(e.operation==="edit"&&l>9)throw new Error(`Seedance 2.0 video edit: max 9 reference images (got ${l}).`);let d=[];switch(e.draftTaskId&&d.push({type:"draft_task",id:e.draftTaskId}),e.operation){case"multimodal_reference":{if(e.prompt&&d.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let k=0;k<e.referenceImages.length;k++){let x=e.imageRoles?.[k]??"reference_image";d.push({type:"image_url",image_url:{url:e.referenceImages[k]},role:x})}if(e.referenceVideos?.length)for(let k of e.referenceVideos)d.push({type:"video_url",video_url:{url:k},role:"reference_video"});if(e.referenceAudios?.length)for(let k of e.referenceAudios)d.push({type:"audio_url",audio_url:{url:k},role:"reference_audio"});break}case"extend":{if(e.sourceVideos?.length)for(let k of e.sourceVideos)d.push({type:"video_url",video_url:{url:k},role:"reference_video"});e.prompt&&d.push({type:"text",text:e.prompt});break}case"merge":for(let k of e.sourceVideos??[])d.push({type:"video_url",video_url:{url:k}});e.prompt&&d.push({type:"text",text:e.prompt});break;case"upscale":e.sourceVideos?.[0]&&d.push({type:"video_url",video_url:{url:e.sourceVideos[0]}}),d.push({type:"text",text:e.prompt||"upscale"});break;case"edit":for(let k of e.sourceVideos??[])d.push({type:"video_url",video_url:{url:k},role:"reference_video"});if(e.referenceImages?.length)for(let k of e.referenceImages)d.push({type:"image_url",image_url:{url:k},role:"reference_image"});e.prompt&&d.push({type:"text",text:e.prompt});break;default:{let k=(e.referenceVideos?.length??0)>0,x=(e.referenceAudios?.length??0)>0,I=(e.imageRoles?.length??0)>0;if(k||x||I){if(e.prompt&&d.push({type:"text",text:e.prompt}),e.referenceImages?.length)for(let P=0;P<e.referenceImages.length;P++){let O=e.imageRoles?.[P]??"reference_image";d.push({type:"image_url",image_url:{url:e.referenceImages[P]},role:O})}if(k)for(let P of e.referenceVideos)d.push({type:"video_url",video_url:{url:P},role:"reference_video"});if(x)for(let P of e.referenceAudios)d.push({type:"audio_url",audio_url:{url:P},role:"reference_audio"})}else if(e.referenceImages?.length){for(let P of e.referenceImages)d.push({type:"image_url",image_url:{url:P}});e.prompt&&d.push({type:"text",text:e.prompt})}else e.imageUrl?(d.push({type:"image_url",image_url:{url:e.imageUrl}}),e.prompt&&d.push({type:"text",text:e.prompt})):e.prompt&&d.push({type:"text",text:e.prompt});break}}let u={model:e.model,content:d};e.duration&&(u.duration=e.duration),e.aspectRatio&&(u.ratio=e.aspectRatio),e.resolution&&(u.resolution=e.resolution),e.seed!==void 0&&(u.seed=e.seed),e.fps&&(u.fps=e.fps),e.generateAudio!==void 0&&(u.generate_audio=e.generateAudio),e.watermark!==void 0&&(u.watermark=e.watermark),e.enhancePrompt!==void 0&&(u.enhance_prompt=e.enhancePrompt),e.cameraFixed!==void 0&&(u.camera_fixed=e.cameraFixed),e.returnLastFrame!==void 0&&(u.return_last_frame=e.returnLastFrame),e.serviceTier&&(u.service_tier=e.serviceTier),e.executionExpiresAfterSeconds!==void 0&&(u.execution_expires_after=e.executionExpiresAfterSeconds),e.draft!==void 0&&(u.draft=e.draft),e.safetyIdentifier&&(u.safety_identifier=e.safetyIdentifier),e.callbackUrl&&(u.callback_url=e.callbackUrl),e.videoTools?.length&&(u.tools=e.videoTools.map(k=>({type:k})));let p=await this.submitTask(s,u,t,o),m=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${p}`,t,o,e.onProgress,p),h=[],f=m.content;typeof f?.video_url=="string"&&h.push(f.video_url);let y=typeof f?.last_frame_url=="string"?f.last_frame_url:void 0,b=pu(m);return{mediaUrls:h,model:e.model,durationMs:Date.now()-r,lastFrameUrl:y,taskId:p,billingUnit:"per_token",billingQuantity:b.completionTokens,metadata:{billableUnits:{completion_tokens:b.completionTokens,total_tokens:b.totalTokens},usage:b.rawUsage,usageMissing:!b.hasUsage,pricingSpec:e.resolution??"720p"}}}async generate3D(e,t,o){let r=Date.now(),s=`${this.baseUrl}/v3/contents/generations/tasks`,i=[],a=[];e.outputFormat&&a.push(`--fileformat ${e.outputFormat}`),e.prompt&&a.push(e.prompt),a.length>0&&i.push({type:"text",text:a.join(" ")}),e.imageUrl&&i.push({type:"image_url",image_url:{url:e.imageUrl}});let l={model:e.model,content:i},c=await this.submitTask(s,l,t,o),d=await this.pollTask(`${this.baseUrl}/v3/contents/generations/tasks/${c}`,t,o,e.onProgress,c),u=[],p=d.content;if(typeof p?.video_url=="string"&&u.push(p.video_url),u.length===0&&p)for(let[,f]of Object.entries(p))typeof f=="string"&&/^https?:\/\//.test(f)&&u.push(f);let m=d.output;if(m?.model_urls){let f=m.model_urls;for(let y of Object.values(f))y&&!u.includes(y)&&u.push(y)}if(u.length===0){let f=Object.keys(d),y=p?Object.keys(p):[],b=m?Object.keys(m):[];console.error(`[volcengine-3d] No media URLs found. Response keys: [${f}], content keys: [${y}], output keys: [${b}]`);let k=d.data;if(k?.content){let x=k.content;for(let[,I]of Object.entries(x))typeof I=="string"&&/^https?:\/\//.test(I)&&u.push(I)}}let h=pu(d);return{mediaUrls:u,model:e.model,durationMs:Date.now()-r,billingUnit:"per_token",billingQuantity:h.completionTokens,metadata:u.length===0?{billableUnits:{completion_tokens:h.completionTokens,total_tokens:h.totalTokens},usage:h.rawUsage,usageMissing:!h.hasUsage,debugResponseKeys:Object.keys(d),debugContentKeys:p?Object.keys(p):null,debugContentSample:p?JSON.stringify(p).slice(0,500):null,debugOutputKeys:m?Object.keys(m):null,debugResultSample:JSON.stringify(d).slice(0,800)}:{billableUnits:{completion_tokens:h.completionTokens,total_tokens:h.totalTokens},usage:h.rawUsage,usageMissing:!h.hasUsage,pricingSpec:e.outputFormat??"3d"}}}async getTaskStatus(e,t,o){let r=`${this.baseUrl}/v3/contents/generations/tasks/${e}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Volcengine task status error ${s.status}: ${l}`)}let i=await s.json();return{status:i.status??"unknown",task:i}}async listVideoTasks(e,t,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 l=await a.text().catch(()=>"");throw new Error(`Volcengine list tasks error ${a.status}: ${l}`)}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 c=await a.text().catch(()=>"");throw new Error(`Volcengine file upload error ${a.status}: ${c}`)}let l=await a.json();return{id:String(l.id??""),status:String(l.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 l=await a.text().catch(()=>"");throw new Error(`Volcengine list files error ${a.status}: ${l}`)}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 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,o,r,s){let i=Date.now()+6e5,a=0;for(;Date.now()<i;){o?.throwIfAborted();let l=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let m=await l.text().catch(()=>"");throw new Error(`Volcengine task poll error ${l.status}: ${m}`)}let c=await l.json(),d=c.status;if(d==="succeeded"||d==="complete")return r?.(100,"completed",s),c;if(d==="failed"||d==="cancelled"){let m=c.error?.message??"Task failed";throw new Error(`Volcengine task failed: ${m}`)}a++;let u=Date.now()-(i-6e5),p=Math.min(95,Math.round(u/6e5*100));r?.(p,d??"running",s),await new Promise(m=>setTimeout(m,3e3))}throw new Error("Volcengine task timed out after polling")}}});import{join as Na}from"node:path";import{homedir as kS,tmpdir as vS}from"node:os";function mu(){return process.env.QLOGICAGENT_HOME??Na(kS()||vS(),".qlogicagent")}function Ft(){return process.env.QLOGICAGENT_CACHE_DIR??Na(mu(),"cache")}function fu(){return process.env.QLOGICAGENT_DEBUG_LOG_DIR??Na(mu(),"debug-logs")}var Un=N(()=>{"use strict"});import{writeFileSync as SS,mkdirSync as TS}from"node:fs";import{join as gu}from"node:path";import{randomUUID as wS}from"node:crypto";var xS,To,$a=N(()=>{"use strict";Un();xS=18e4,To=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??xS}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 d=await a.text().catch(()=>"");throw new Error(`OpenAI images API error ${a.status}: ${d}`)}return{mediaUrls:((await a.json()).data??[]).map(d=>d.url).filter(d=>!!d),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 l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??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()),d=gu(Ft(),"tts");TS(d,{recursive:!0});let u=`openai-tts-${wS()}.mp3`,p=gu(d,u);return SS(p,c),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:s.length}}}});var kn,Or=N(()=>{"use strict";kn=class{supportedTypes=["music","video","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/anthropic\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??6e4}async generate(e,t,o){switch(e.mediaType){case"music":return this.generateMusic(e,t,o);case"video":return this.generateVideo(e,t,o);case"tts":return this.generateTTS(e,t,o);default:throw new Error(`MiniMaxMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async generateTTS(e,t,o){let r=Date.now(),s=e.text??e.prompt;if(!s)throw new Error("MiniMaxMediaTransport: text or prompt is required for TTS");let i=e.audioFormat??"mp3",a=`${this.baseUrl}/v1/t2a_v2`,l={model:e.model||"speech-2.8-turbo",text:s,stream:!1,output_format:"url",voice_setting:{voice_id:e.voice??"male-qn-qingse",speed:e.speed??1,vol:e.metadata?.volume??1,pitch:e.metadata?.pitch??0},audio_setting:{sample_rate:e.metadata?.sampleRate??32e3,bitrate:e.metadata?.bitrate??128e3,format:i,channel:e.metadata?.channel??1}},c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`MiniMax TTS error ${c.status}: ${m}`)}let d=await c.json();if(d.base_resp?.status_code&&d.base_resp.status_code!==0)throw new Error(`MiniMax TTS rejected: ${d.base_resp.status_msg??"unknown"}`);let u=d.data?.audio;if(!u)throw new Error("MiniMax TTS: no audio in response");let p=d.extra_info?.usage_characters??s.length;return{mediaUrls:[u],model:e.model,durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:p,metadata:{traceId:d.trace_id,status:d.data?.status,extraInfo:d.extra_info,billableUnits:{characters:p}}}}async generateMusic(e,t,o){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 l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax music rejected: ${l.base_resp.status_msg??"unknown"}`);let c=l.data?.audio??l.audio_file;if(c)return{mediaUrls:[c],model:e.model,durationMs:Date.now()-r,billingUnit:"per_second",billingQuantity:e.duration??0,metadata:{billableUnits:{seconds:e.duration??0}}};let d=l.task_id;if(!d)throw new Error("MiniMax music: no audio_file or task_id in response");let u=`${this.baseUrl}/v1/music_generation/${d}`;return{mediaUrls:(await this.pollTask(u,t,o,e.onProgress,d)).audioUrls,model:e.model,durationMs:Date.now()-r,billingUnit:"per_second",billingQuantity:e.duration??0,metadata:{billableUnits:{seconds:e.duration??0}}}}async pollTask(e,t,o,r,s){let i=Date.now()+6e5;for(;Date.now()<i;){o?.throwIfAborted();let a=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`MiniMax music poll error ${a.status}: ${u}`)}let l=await a.json(),c=l.status;if(c==="Success"||c==="Finished"){r?.(100,"completed",s);let u=[];return l.audio_file&&u.push(l.audio_file),{audioUrls:u}}if(c==="Failed"||c==="Cancelled")throw new Error(`MiniMax music task failed: ${l.base_resp?.status_msg??"unknown"}`);let d=Date.now()-(i-6e5);r?.(Math.min(95,Math.round(d/6e5*100)),c??"running",s),await new Promise(u=>setTimeout(u,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??""}async generateVideo(e,t,o){let r=Date.now(),s=`${this.baseUrl}/v1/video_generation`,i={model:e.model||"S2V-01",prompt:e.prompt};if(e.referenceImages?.length&&e.imageRoles){let u=e.imageRoles.includes("first_frame"),p=e.imageRoles.includes("last_frame");if(u&&p){let m=e.imageRoles.indexOf("first_frame"),h=e.imageRoles.indexOf("last_frame");i.first_frame_image=e.referenceImages[m],i.last_frame_image=e.referenceImages[h]}else if(u){let m=e.imageRoles.indexOf("first_frame");i.first_frame_image=e.referenceImages[m]}else i.subject_reference=e.referenceImages.map((m,h)=>({type:"character",image:m}))}else e.imageUrl&&(i.first_frame_image=e.imageUrl);e.callbackUrl&&(i.callback_url=e.callbackUrl);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`MiniMax video submit error ${a.status}: ${u}`)}let l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax video rejected: ${l.base_resp.status_msg??"unknown"}`);let c=l.task_id;if(!c)throw new Error("MiniMax video: no task_id in response");let d=await this.pollVideoTask(c,t,o,e.onProgress);return{mediaUrls:d.downloadUrl?[d.downloadUrl]:[],model:e.model||"S2V-01",durationMs:Date.now()-r,taskId:c,billingUnit:"per_second",billingQuantity:e.duration??0,metadata:{billableUnits:{videos:1,seconds:e.duration??0},fileId:d.fileId,width:d.width,height:d.height}}}async pollVideoTask(e,t,o,r){let s=Date.now()+6e5;for(;Date.now()<s;){o?.throwIfAborted();let i=`${this.baseUrl}/v1/query/video_generation?task_id=${encodeURIComponent(e)}`,a=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!a.ok){let m=await a.text().catch(()=>"");throw new Error(`MiniMax video poll error ${a.status}: ${m}`)}let l=await a.json();if(l.base_resp?.status_code&&l.base_resp.status_code!==0)throw new Error(`MiniMax video task error ${l.base_resp.status_code}: ${l.base_resp.status_msg??""}`);let c=l.status;if(c==="Success"){r?.(100,"completed",e);let m;if(l.file_id)try{m=await this.getFileDownloadUrl(l.file_id,t,o)}catch{}return{fileId:l.file_id,downloadUrl:m,width:l.video_width,height:l.video_height}}if(c==="Fail")throw new Error(`MiniMax video task failed: ${l.base_resp?.status_msg??"unknown"}`);let d=c??"running",u=Date.now()-(s-6e5),p=Math.min(95,Math.round(u/6e5*100));r?.(p,d,e),await new Promise(m=>setTimeout(m,3e3))}throw new Error("MiniMax video task timed out after polling")}async getFileDownloadUrl(e,t,o){let r=`${this.baseUrl}/v1/files/retrieve?file_id=${encodeURIComponent(e)}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`MiniMax file retrieve error ${s.status}: ${l}`)}let a=(await s.json()).file?.download_url;if(!a)throw new Error("MiniMax file retrieve: no download_url in response");return a}async getTaskStatus(e,t,o){let r=`${this.baseUrl}/v1/query/video_generation?task_id=${encodeURIComponent(e)}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`MiniMax task status error ${s.status}: ${c}`)}let i=await s.json(),a=i.status??"unknown";return{status:a==="Success"?"succeeded":a==="Fail"?"failed":a.toLowerCase(),task:i}}async listVideoTasks(e,t,o){return{data:[]}}async deleteVideoTask(e,t,o){throw new Error("MiniMax does not support video task cancellation.")}}});import{writeFileSync as RS,mkdirSync as _S}from"node:fs";import{join as hu}from"node:path";import{randomUUID as AS}from"node:crypto";async function Ua(n,e,t){let o=t.durationSeconds??30,r=Date.now(),s=new Dr(e),i=[];s.onAudioChunk=l=>{i.push(l.data)};let a=null;s.onError=l=>{a=l};try{await s.connect(n,{model:t.model??"lyria-realtime-exp",prompts:t.prompts,config:t.musicConfig}),t.onProgress?.(5,"connected"),await s.play(),t.onProgress?.(10,"streaming");let l=Date.now()+o*1e3,c=500;for(;Date.now()<l;){if(t.signal?.throwIfAborted(),a)throw a;if(!s.connected)break;let f=Date.now()-r,y=o*1e3,b=Math.min(95,Math.round(10+f/y*85));t.onProgress?.(b,"streaming"),await new Promise(k=>setTimeout(k,c))}s.connected&&await s.stop(),t.onProgress?.(98,"assembling");let d=Buffer.concat(i),u=PS(d,48e3,2,16),p=hu(Ft(),"gemini-music-realtime");_S(p,{recursive:!0});let m=`lyria-rt-${AS()}.wav`,h=hu(p,m);return RS(h,u),t.onProgress?.(100,"completed"),{filePath:`file://${h}`,durationMs:Date.now()-r}}finally{s.close()}}function PS(n,e,t,o){let r=e*t*(o/8),s=t*(o/8),i=n.length,a=Buffer.alloc(44);return a.write("RIFF",0),a.writeUInt32LE(36+i,4),a.write("WAVE",8),a.write("fmt ",12),a.writeUInt32LE(16,16),a.writeUInt16LE(1,20),a.writeUInt16LE(t,22),a.writeUInt32LE(e,24),a.writeUInt32LE(r,28),a.writeUInt16LE(s,30),a.writeUInt16LE(o,32),a.write("data",36),a.writeUInt32LE(i,40),Buffer.concat([a,n])}var Dr,ja=N(()=>{"use strict";Un();Dr=class{ws=null;wsUrl;model="models/lyria-realtime-exp";onAudioChunk=null;onFilteredPrompt=null;onError=null;onClose=null;constructor(e){let t=e.baseUrl.replace(/\/+$/,""),o=new URL(t).origin.replace(/^http/,"ws");this.wsUrl=`${o}/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent`}async connect(e,t){t.model&&(this.model=t.model.startsWith("models/")?t.model:`models/${t.model}`);let o=`${this.wsUrl}?key=${encodeURIComponent(e)}`,r=new WebSocket(o);this.ws=r,await new Promise((s,i)=>{let a=()=>{r.removeEventListener("error",l),s()},l=()=>{r.removeEventListener("open",a),i(new Error("Lyria RealTime WebSocket connection failed"))};r.addEventListener("open",a,{once:!0}),r.addEventListener("error",l,{once:!0})}),r.addEventListener("message",s=>this.handleMessage(s)),r.addEventListener("error",()=>{this.onError?.(new Error("Lyria RealTime WebSocket error"))}),r.addEventListener("close",()=>{this.ws=null,this.onClose?.()}),this.send({setup:{model:this.model}}),await new Promise(s=>setTimeout(s,100)),await this.setWeightedPrompts(t.prompts),t.config&&await this.setMusicGenerationConfig(t.config)}async setWeightedPrompts(e){this.send({musicInput:{weightedPrompts:e.map(t=>({text:t.text,weight:t.weight}))}})}async setMusicGenerationConfig(e){let t={};e.bpm!==void 0&&(t.bpm=e.bpm),e.density!==void 0&&(t.density=e.density),e.brightness!==void 0&&(t.brightness=e.brightness),e.guidance!==void 0&&(t.guidance=e.guidance),e.scale!==void 0&&(t.scale=e.scale),e.temperature!==void 0&&(t.temperature=e.temperature),e.topK!==void 0&&(t.top_k=e.topK),e.seed!==void 0&&(t.seed=e.seed),e.muteBass!==void 0&&(t.mute_bass=e.muteBass),e.muteDrums!==void 0&&(t.mute_drums=e.muteDrums),e.onlyBassAndDrums!==void 0&&(t.only_bass_and_drums=e.onlyBassAndDrums),e.musicGenerationMode!==void 0&&(t.music_generation_mode=e.musicGenerationMode),e.audioFormat!==void 0&&(t.audio_format=e.audioFormat),e.sampleRateHz!==void 0&&(t.sample_rate_hz=e.sampleRateHz),this.send({musicInput:{musicGenerationConfig:t}})}async play(){this.send({musicInput:{playbackControl:"PLAY"}})}async pause(){this.send({musicInput:{playbackControl:"PAUSE"}})}async stop(){this.send({musicInput:{playbackControl:"STOP"}})}async resetContext(){this.send({musicInput:{playbackControl:"RESET_CONTEXT"}})}close(){this.ws&&this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=null}get connected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Lyria RealTime session not connected");this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(typeof e.data=="string"?e.data:e.data.toString())}catch{return}let o=t.serverContent;if(!o)return;let r=o.audioChunks;if(r&&this.onAudioChunk)for(let i of r)i.data&&this.onAudioChunk({data:Buffer.from(i.data,"base64")});let s=o.filteredPrompt;s&&this.onFilteredPrompt?.(s)}}});import{writeFileSync as yu,mkdirSync as bu}from"node:fs";import{join as Lr}from"node:path";import{randomUUID as ku}from"node:crypto";function ES(n,e,t,o){let r=e*t*(o/8),s=t*(o/8),i=n.length,a=Buffer.alloc(44);return a.write("RIFF",0),a.writeUInt32LE(36+i,4),a.write("WAVE",8),a.write("fmt ",12),a.writeUInt32LE(16,16),a.writeUInt16LE(1,20),a.writeUInt16LE(t,22),a.writeUInt32LE(e,24),a.writeUInt32LE(r,28),a.writeUInt16LE(s,30),a.writeUInt16LE(o,32),a.write("data",36),a.writeUInt32LE(i,40),Buffer.concat([a,n])}var IS,CS,Fa,wo,Ba=N(()=>{"use strict";Un();ja();IS=18e4,CS=1e4,Fa=6e5,wo=class{supportedTypes=["image","video","music","music_realtime","tts","embedding"];apiBase;timeoutMs;constructor(e){this.apiBase=e.baseUrl.replace(/\/openai\/?$/,"").replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??IS}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"music":return this.generateMusic(e,t,o);case"music_realtime":return this.generateMusicRealtime(e,t,o);case"tts":return this.generateTTS(e,t,o);case"embedding":return this.generateEmbedding(e,t,o);default:throw new Error(`GeminiMediaTransport: unsupported mediaType "${e.mediaType}"`)}}async deleteVideoTask(e,t,o){throw new Error("Gemini does not support deleting video generation tasks")}async listVideoTasks(e,t,o){return{data:[]}}async getTaskStatus(e,t,o){let r=`${this.apiBase}/${e}`,s=await fetch(r,{method:"GET",headers:{"x-goog-api-key":t},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let l=await s.text().catch(()=>"");throw new Error(`Gemini operation query error ${s.status}: ${l}`)}let i=await s.json();return{status:i.done?"completed":"running",task:i}}async generateImage(e,t,o){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},l=await this.postJson(s,a,t,o);return{mediaUrls:this.extractInlineImages(l),model:e.model,durationMs:Date.now()-r}}async generateVideo(e,t,o){let r=Date.now(),s=`${this.apiBase}/models/${e.model}:predictLongRunning`,i={prompt:e.prompt};e.imageUrl&&(i.image={inlineData:await this.resolveImageData(e.imageUrl)}),e.referenceImages?.length&&(i.referenceImages=await Promise.all(e.referenceImages.map(async y=>({image:{inlineData:await this.resolveImageData(y)},referenceType:"asset"}))));let a={};e.aspectRatio&&(a.aspectRatio=e.aspectRatio),e.resolution&&(a.resolution=e.resolution),e.duration&&(a.durationSeconds=String(e.duration)),e.n&&(a.numberOfVideos=e.n),e.seed!==void 0&&(a.seed=e.seed);let l={instances:[i]};Object.keys(a).length>0&&(l.parameters=a);let d=(await this.postJson(s,l,t,o)).name;if(!d)throw new Error("Gemini video submit: no operation name in response");let u=d;e.onProgress?.(5,"submitted",u);let h=(await this.pollOperation(d,t,o,e.onProgress,u)).response?.generateVideoResponse?.generatedSamples??[],f=[];for(let y of h)y.video?.uri&&f.push(y.video.uri);return{mediaUrls:f,model:e.model,durationMs:Date.now()-r,taskId:u}}async generateMusic(e,t,o){let r=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i=[{text:e.prompt}],a={};e.audioFormat==="wav"&&(a.responseModalities=["AUDIO","TEXT"],a.responseFormat={audio:{mimeType:"audio/wav"}});let l={contents:[{parts:i}]};Object.keys(a).length>0&&(l.generationConfig=a);let c=await this.postJson(s,l,t,o);return{mediaUrls:this.extractInlineAudio(c,"gemini-music"),model:e.model,durationMs:Date.now()-r}}async generateMusicRealtime(e,t,o){let r=await Ua(t,{baseUrl:this.apiBase},{prompts:[{text:e.prompt,weight:1}],durationSeconds:e.duration??30,musicConfig:{audioFormat:e.audioFormat==="wav"?"pcm16":void 0,sampleRateHz:48e3},model:e.model,signal:o,onProgress:e.onProgress});return{mediaUrls:[r.filePath],model:e.model,durationMs:r.durationMs}}async generateTTS(e,t,o){let r=Date.now(),s=`${this.apiBase}/models/${e.model}:generateContent`,i={responseModalities:["AUDIO"]};e.voice&&(i.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}});let a={contents:[{parts:[{text:e.text??e.prompt}]}],generationConfig:i},l=await this.postJson(s,a,t,o);return{mediaUrls:this.extractInlineAudio(l,"gemini-tts"),model:e.model,durationMs:Date.now()-r}}async generateEmbedding(e,t,o){let r=Date.now(),s=`${this.apiBase}/models/${e.model}:embedContent`,i={content:{parts:[{text:e.text??e.prompt}]}},a=e.metadata?.outputDimensionality;a!==void 0&&(i.output_dimensionality=a);let l=await this.postJson(s,i,t,o),c=l.embedding?.values??l.embeddings?.[0]?.values??[];return{mediaUrls:[],model:e.model,durationMs:Date.now()-r,metadata:{embedding:c,dimensions:c.length}}}async postJson(e,t,o,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":o},body:JSON.stringify(t),signal:r??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`Gemini API error ${s.status}: ${i}`)}return s.json()}async pollOperation(e,t,o,r,s){let i=Date.now()+Fa;for(;Date.now()<i;){o?.throwIfAborted();let a=`${this.apiBase}/${e}`,l=await fetch(a,{method:"GET",headers:{"x-goog-api-key":t},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`Gemini operation poll error ${l.status}: ${p}`)}let c=await l.json();if(c.done===!0)return r?.(100,"completed",s),c;if(c.error){let p=c.error;throw new Error(`Gemini video generation failed: ${p.message??JSON.stringify(p)}`)}let d=Date.now()-(i-Fa),u=Math.min(95,Math.round(d/Fa*100));r?.(u,"running",s),await new Promise(p=>setTimeout(p,CS))}throw new Error("Gemini video generation timed out after polling")}async resolveImageData(e){if(e.startsWith("data:")){let s=e.match(/^data:([^;]+);base64,(.+)$/);if(s)return{mimeType:s[1],data:s[2]}}if(e.startsWith("file://")){let{readFileSync:s}=await import("node:fs"),i=e.replace(/^file:\/\//,""),a=s(i).toString("base64"),l=i.split(".").pop()?.toLowerCase()??"png";return{mimeType:l==="jpg"||l==="jpeg"?"image/jpeg":l==="webp"?"image/webp":"image/png",data:a}}let t=await fetch(e,{signal:AbortSignal.timeout(6e4)});if(!t.ok)throw new Error(`Failed to fetch image ${e}: ${t.status}`);let o=Buffer.from(await t.arrayBuffer());return{mimeType:t.headers.get("content-type")??"image/png",data:o.toString("base64")}}extractInlineImages(e){let t=[],o=Lr(Ft(),"gemini-images");bu(o,{recursive:!0});for(let r of e.candidates??[])for(let s of r.content?.parts??[])if(s.inlineData?.data){let i=s.inlineData.mimeType==="image/png"?"png":s.inlineData.mimeType==="image/webp"?"webp":"jpg",a=`gemini-${ku()}.${i}`,l=Lr(o,a);yu(l,Buffer.from(s.inlineData.data,"base64")),t.push(`file://${l}`)}return t}extractInlineAudio(e,t){let o=[],r=Lr(Ft(),t);bu(r,{recursive:!0});for(let s of e.candidates??[])for(let i of s.content?.parts??[])if(i.inlineData?.data&&i.inlineData.mimeType?.startsWith("audio/")){let a=i.inlineData.mimeType.includes("wav")?"wav":i.inlineData.mimeType.includes("mpeg")||i.inlineData.mimeType.includes("mp3")?"mp3":"pcm",l=Buffer.from(i.inlineData.data,"base64"),c=a==="pcm"?ES(l,24e3,1,16):l,d=`gemini-${ku()}.${a==="pcm"?"wav":a}`,u=Lr(r,d);yu(u,c),o.push(`file://${u}`)}return o}}});function MS(n){return new Promise(e=>setTimeout(e,n))}var Nr,vu=N(()=>{"use strict";Nr=class{supportedTypes=["tts","video","embedding","rerank"];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==="video")return this.generateVideo(e,t,o);if(e.mediaType==="embedding")return this.generateEmbedding(e,t,o);if(e.mediaType==="rerank")return this.generateRerank(e,t,o);if(e.mediaType!=="tts")throw new Error(`QwenMediaTransport: unsupported mediaType "${e.mediaType}"`);return this.generateTTS(e,t,o)}async generateTTS(e,t,o){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("QwenMediaTransport: text or prompt is required for TTS");return(e.model||"").startsWith("cosyvoice")?this.generateCosyVoiceTTS(e,t,o,r,s):this.generateQwenTTS(e,t,o,r,s)}async generateQwenTTS(e,t,o,r,s){let i=`${this.baseUrl}/api/v1/services/aigc/multimodal-generation/generation`,a={model:e.model||"qwen3-tts-flash",input:{text:s,voice:e.voice??"Cherry",language_type:e.metadata?.languageType??"English"}},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`DashScope Qwen TTS error ${l.status}: ${p}`)}let c=await l.json();if(c.code)throw new Error(`DashScope Qwen TTS rejected: ${c.code}: ${c.message??""}`);let d=c.output?.audio?.url,u=c.usage?.characters??s.length;return{mediaUrls:d?[d]:[],model:e.model||"qwen3-tts-flash",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:u,metadata:{usage:c.usage,finishReason:c.output?.finish_reason,requestId:c.request_id}}}async generateCosyVoiceTTS(e,t,o,r,s){let i=`${this.baseUrl}/api/v1/services/audio/tts/SpeechSynthesizer`,a={model:e.model||"cosyvoice-v2",input:{text:s},parameters:{voice:e.voice??"longxiaochun_v2",format:e.audioFormat??"mp3",sample_rate:e.metadata?.sampleRate??24e3}},l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`DashScope CosyVoice TTS error ${l.status}: ${p}`)}let c=await l.json();if(c.code)throw new Error(`DashScope CosyVoice TTS rejected: ${c.code}: ${c.message??""}`);let d=c.output?.audio?.url,u=c.usage?.characters??s.length;return{mediaUrls:d?[d]:[],model:e.model||"cosyvoice-v2",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:u,metadata:{usage:c.usage,finishReason:c.output?.finish_reason,requestId:c.request_id}}}async generateEmbedding(e,t,o){let r=Date.now(),s=e.text||e.prompt;if(!s)throw new Error("QwenMediaTransport: text or prompt is required for embedding");let i=`${this.baseUrl}/compatible-mode/v1/embeddings`,a={model:e.model||"text-embedding-v4",input:s};e.metadata?.dimensions&&(a.dimensions=e.metadata.dimensions);let l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`DashScope embedding error ${l.status}: ${p}`)}let c=await l.json(),d=(c.data??[]).map(p=>p.embedding).filter(p=>Array.isArray(p)),u=c.usage?.total_tokens??c.usage?.prompt_tokens;return{mediaUrls:[],model:c.model??e.model??"text-embedding-v4",durationMs:Date.now()-r,billingUnit:u!==void 0?"per_token":void 0,billingQuantity:u,metadata:{embeddings:d,dimensions:d[0]?.length??0,usage:c.usage}}}async generateRerank(e,t,o){let r=Date.now(),s=e.prompt,i=e.metadata?.documents;if(!s)throw new Error("QwenMediaTransport: prompt (query) is required for rerank");if(!Array.isArray(i))throw new Error("QwenMediaTransport: metadata.documents is required for rerank");let a=`${this.baseUrl}/api/v1/services/rerank/text-rerank/text-rerank`,l={model:e.model||"qwen3-rerank",input:{query:s,documents:i},parameters:{}};e.metadata?.topN!==void 0&&(l.parameters.top_n=e.metadata.topN);let c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`DashScope rerank error ${c.status}: ${p}`)}let d=await c.json(),u=d.usage?.total_tokens;return{mediaUrls:[],model:e.model||"qwen3-rerank",durationMs:Date.now()-r,billingUnit:u!==void 0?"per_token":void 0,billingQuantity:u,metadata:{results:(d.output?.results??[]).map(p=>({index:p.index,relevanceScore:p.relevance_score,document:p.document})),usage:d.usage}}}async pollTask(e,t,o,r,s=12e4){let i=Date.now()+s,a=`${this.baseUrl}/api/v1/tasks/${e}`;for(;Date.now()<i;){o?.throwIfAborted(),await MS(2e3);let l=await fetch(a,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let p=await l.text().catch(()=>"");throw new Error(`DashScope TTS poll error ${l.status}: ${p}`)}let c=await l.json();if(c.code)throw new Error(`DashScope poll rejected: ${c.code} \u9225?${c.message??""}`);let d=c.output?.task_status;if(d==="SUCCEEDED"){r?.(100,"completed",e);let p=this.extractMediaUrl(c);return p?[p]:[]}if(d==="FAILED")throw new Error(`DashScope task failed: ${c.message??"unknown error"}`);let u=Date.now()-(i-s);r?.(Math.min(95,Math.round(u/s*100)),d??"running",e)}throw new Error("DashScope task timed out")}async generateVideo(e,t,o){let r=Date.now(),s=e.model||"wan2.1-t2v-turbo",i={prompt:e.prompt};if(e.imageUrl)i.img_url=e.imageUrl;else if(e.referenceImages?.length)if(e.imageRoles){let h=e.imageRoles.indexOf("first_frame"),f=e.imageRoles.indexOf("last_frame");h>=0&&(i.img_url=e.referenceImages[h]),f>=0&&(i.tail_image_url=e.referenceImages[f]);let y=e.imageRoles.map((b,k)=>b==="reference_image"?k:-1).filter(b=>b>=0);y.length>0&&(i.ref_image_url=e.referenceImages[y[0]])}else i.img_url=e.referenceImages[0];let a={};e.duration&&(a.duration=e.duration),e.resolution&&(a.resolution=e.resolution),e.aspectRatio&&(a.ratio=e.aspectRatio),e.metadata?.size&&(a.size=e.metadata.size);let l=`${this.baseUrl}/api/v1/services/aigc/generation/generation`,c={model:s,input:i};Object.keys(a).length>0&&(c.parameters=a);let d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,"X-DashScope-Async":"enable"},body:JSON.stringify(c),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!d.ok){let h=await d.text().catch(()=>"");throw new Error(`DashScope video submit error ${d.status}: ${h}`)}let u=await d.json();if(u.code)throw new Error(`DashScope video submit rejected: ${u.code} \u9225?${u.message??""}`);let p=u.output?.task_id;if(!p)throw new Error("DashScope video submit: no task_id in response");return{mediaUrls:await this.pollTask(p,t,o,e.onProgress,6e5),model:s,durationMs:Date.now()-r,taskId:p}}async getTaskStatus(e,t,o){let r=`${this.baseUrl}/api/v1/tasks/${e}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(`DashScope task status error ${s.status}: ${d}`)}let i=await s.json(),l=i.output?.task_status??"unknown";return{status:l==="SUCCEEDED"?"succeeded":l==="FAILED"?"failed":l.toLowerCase(),task:i}}async listVideoTasks(e,t,o){let r=new URLSearchParams;r.set("page_size",String(t?.limit??20)),t?.status&&r.set("status",t.status.toUpperCase());let s=`${this.baseUrl}/api/v1/tasks?${r.toString()}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:o??AbortSignal.timeout(this.timeoutMs)});return i.ok?await i.json():{data:[]}}async deleteVideoTask(e,t,o){throw new Error("DashScope does not support task cancellation.")}extractMediaUrl(e){if(e.output?.video_url)return e.output.video_url;if(e.output?.audio_url)return e.output.audio_url;if(e.output?.results?.[0]?.url)return e.output.results[0].url}}});import{writeFileSync as OS,mkdirSync as DS}from"node:fs";import{join as Su}from"node:path";import{randomUUID as LS}from"node:crypto";function jS(n,e){return/^(https?:|data:)/i.test(n)?n:`data:${typeof e?.mimeType=="string"?e.mimeType:"application/pdf"};base64,${n}`}var NS,$S,$r,US,xo,Tu=N(()=>{"use strict";Un();NS=18e4,$S=3e3,$r=6e5,US=new Set(["glm-image"]),xo=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??NS}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 US.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(d=>d.url).filter(d=>!!d),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 l=(await this.postJSON(s,i,t,o)).id;if(!l)throw new Error("Zhipu async image: no task id in response");return{mediaUrls:((await this.pollAsyncResult(l,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 l=(await this.postJSON(s,i,t,o)).id;if(!l)throw new Error("Zhipu video generation: no task id in response");return{mediaUrls:((await this.pollAsyncResult(l,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 l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a),signal:o??AbortSignal.timeout(this.timeoutMs)});if(!l.ok){let h=await l.text().catch(()=>"");throw new Error(`Zhipu TTS API error ${l.status}: ${h}`)}let c=Buffer.from(await l.arrayBuffer()),d=Su(Ft(),"tts");DS(d,{recursive:!0});let u=e.audioFormat??"wav",p=`zhipu-tts-${LS()}.${u}`,m=Su(d,p);return OS(m,c),{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,{headers:{"User-Agent":"qlogicagent/1.0"},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!i.ok)throw new Error(`Failed to fetch audio from ${e.audioUrl}`);let a=await i.blob(),l=new FormData;l.append("model",e.model||"glm-asr-2512"),l.append("file",a,"audio.wav");let c=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:l,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let u=await c.text().catch(()=>"");throw new Error(`Zhipu STT API error ${c.status}: ${u}`)}let d=await c.json();return{mediaUrls:[],model:e.model||"glm-asr-2512",durationMs:Date.now()-r,metadata:{transcription:d.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},c=(await this.postJSON(i,a,t,o)).data??[];return{mediaUrls:[],model:e.model||"embedding-3",durationMs:Date.now()-r,metadata:{embeddings:c.map(d=>d.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=e.text||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: text or prompt required for voice_clone preview input");let i=await fetch(e.audioUrl,{signal:o??AbortSignal.timeout(this.timeoutMs)});if(!i.ok)throw new Error(`Failed to fetch audio sample from ${e.audioUrl}`);let a=await i.blob(),l=new FormData;l.append("purpose","voice-clone-input"),l.append("file",a,"sample.wav");let c=await fetch(`${this.baseUrl}/files`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:l,signal:o??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let m=await c.text().catch(()=>"");throw new Error(`Zhipu Voice Clone file upload error ${c.status}: ${m}`)}let d=await c.json();if(d.error)throw new Error(`Zhipu Voice Clone file upload rejected: ${d.error.code??""}: ${d.error.message??""}`);if(!d.id)throw new Error("Zhipu Voice Clone file upload: no file id in response");let u={model:e.model||"glm-tts-clone",voice_name:String(e.metadata?.voiceName??`qlogic_clone_${Date.now()}`),input:s,file_id:d.id,text:typeof e.metadata?.sampleText=="string"?e.metadata.sampleText:void 0},p=await this.postJSON(`${this.baseUrl}/voice/clone`,u,t,o);if(p.error)throw new Error(`Zhipu Voice Clone rejected: ${p.error.code??""}: ${p.error.message??""}`);return{mediaUrls:[],model:e.model||"glm-tts-clone",durationMs:Date.now()-r,metadata:{voiceId:p.voice,previewFileId:p.file_id,previewFilePurpose:p.file_purpose,requestId:p.request_id,sampleFileId:d.id}}}async generateDocumentParsing(e,t,o){let r=Date.now(),s=e.imageUrl||e.audioUrl||e.prompt;if(!s)throw new Error("ZhipuMediaTransport: imageUrl/audioUrl or prompt (data URL) required for document_parsing");let i=`${this.baseUrl}/layout_parsing`,a={model:e.model||"glm-ocr",file:jS(s,e.metadata)};e.metadata?.returnCropImages!==void 0&&(a.return_crop_images=e.metadata.returnCropImages),e.metadata?.needLayoutVisualization!==void 0&&(a.need_layout_visualization=e.metadata.needLayoutVisualization),e.metadata?.startPageId!==void 0&&(a.start_page_id=e.metadata.startPageId),e.metadata?.endPageId!==void 0&&(a.end_page_id=e.metadata.endPageId);let c=await this.postJSON(i,a,t,o);return{mediaUrls:[],model:e.model||"glm-ocr",durationMs:Date.now()-r,metadata:{content:c.md_results??"",mdResults:c.md_results??"",layoutDetails:c.layout_details,layoutVisualization:c.layout_visualization,dataInfo:c.data_info,pages:c.data_info?.pages??[],pageCount:c.data_info?.num_pages??c.data_info?.pages?.length??0,usage:c.usage,requestId:c.request_id}}}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 l=await this.postJSON(i,a,t,o);return{mediaUrls:[],model:e.model||"rerank",durationMs:Date.now()-r,metadata:{results:(l.results??[]).map(c=>({index:c.index,relevanceScore:c.relevance_score,document:c.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()+$r,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 d=await a.text().catch(()=>"");throw new Error(`Zhipu async-result error ${a.status}: ${d}`)}let l=await a.json();if(l.task_status==="SUCCESS")return r?.(100,"completed",e),l;if(l.task_status==="FAIL")throw new Error("Zhipu async task failed");let c=Date.now()-(s-$r);r?.(Math.min(95,Math.round(c/$r*100)),l.task_status??"running",e),await new Promise(d=>setTimeout(d,$S))}throw new Error(`Zhipu async task timed out after ${$r/1e3}s`)}async getTaskStatus(e,t,o){let r=`${this.baseUrl}/async-result/${encodeURIComponent(e)}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:o??AbortSignal.timeout(this.timeoutMs)});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Zhipu task query error ${s.status}: ${c}`)}let i=await s.json(),a=i.task_status??"unknown";return{status:a==="SUCCESS"?"succeeded":a==="FAIL"?"failed":a==="PROCESSING"?"running":a.toLowerCase(),task:i}}async listVideoTasks(e,t,o){return{data:[]}}async deleteVideoTask(e,t,o){throw new Error("Zhipu does not support task cancellation. Tasks complete or timeout automatically.")}async listVoices(e,t){let o=`${this.baseUrl}/voice/list`,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()).voice_list??[]).map(i=>({voice_id:i.voice_id??i.voice??"",voice_name:i.voice_name??"",status:i.status??""}))}async deleteVoice(e,t,o){let r=`${this.baseUrl}/voice/delete`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({voice:e}),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}`)}}}});function FS(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"music_realtime":return"realtime";case"tts":return"text2speech";case"3d":return n.imageUrl?"img2_3d":"text2_3d";default:return}}function BS(n,e){return!("operations"in n)||!n.operations?!0:n.operations.includes(e)}function WS(n){let e=n.baseUrl;switch(n.id){case"volcengine":return new dt({baseUrl:e});case"openai":return new To({baseUrl:e});case"minimax":return new kn({baseUrl:e});case"google":return new wo({baseUrl:e});case"qwen":return new Nr({baseUrl:e});case"zhipu":return new xo({baseUrl:e.replace(/\/api\/anthropic\/?$/,"/api/paas/v4")});case"zhipu-openai":case"zhipu-coding":return new xo({baseUrl:e.replace(/\/api\/coding\/paas\/v4\/?$/,"/api/paas/v4")});default:return}}var Ro,wu=N(()=>{"use strict";Mr();$a();Or();Ba();vu();Tu();Ro=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=WS(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?FS(o):void 0,a=s.find(l=>l.mediaType!==t?!1:!i||!l.mediaCapabilities?!0:BS(l.mediaCapabilities,i));if(a)return{providerId:e,providerDef:r,modelInfo:a,mediaType:t}}}});var Wa,Ga=N(()=>{"use strict";Wa=[{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,supportsThinkingParam:!0,disableThinkingByDefault:!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:.0028},{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:.0145}]},{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",quirks:{supportsThinkingParam:!0,disableThinkingByDefault:!0},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:"qwen3.5-omni-plus-realtime",name:"Qwen3.5 Omni Plus Realtime",contextWindow:131072,maxOutput:16384,toolCall:!1,reasoning:!1,streamRequired:!0,vision:!0,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",modalities:["text","audio"],vad:!0,toolCalling:!1}},{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-flash",name:"Qwen3 TTS Flash",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:"sensevoice-v1",name:"SenseVoice V1",contextWindow:0,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"stt",mediaCapabilities:{type:"stt",languages:["zh","en","ja","ko","yue"],formats:["wav","mp3","m4a","flac","aac"]}},{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:"Zhipu GLM",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:"glm-4-voice",name:"GLM-4-Voice",contextWindow:128e3,maxOutput:16e3,toolCall:!1,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",modalities:["text","audio"],vad:!0,toolCalling:!1}},{id:"glm-realtime-flash",name:"GLM Realtime Flash",contextWindow:128e3,maxOutput:16e3,toolCall:!1,reasoning:!1,vision:!0,mediaType:"realtime_video",mediaCapabilities:{type:"realtime_video",modalities:["text","audio","video"],vad:!0,toolCalling:!1}},{id:"glm-realtime-air",name:"GLM Realtime Air",contextWindow:128e3,maxOutput:16e3,toolCall:!1,reasoning:!1,vision:!0,mediaType:"realtime_video",mediaCapabilities:{type:"realtime_video",modalities:["text","audio","video"],vad:!0,toolCalling:!1}},{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:"Zhipu GLM OpenAI",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:"Zhipu GLM Coding",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:"voice-clone",aliases:["minimax-voice-clone"],name:"MiniMax Voice Clone",contextWindow:0,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:0,costOutput:0,mediaType:"voice_clone",mediaCapabilities:{type:"voice_clone",maxSampleDurationSeconds:30,maxSampleSizeMB:20,formats:["mp3","wav","m4a"]}}]},{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",aliases:["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,disableThinkingByDefault:!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:"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-260428",models:[{id:"doubao-seed-2-0-pro-260215",aliases:["doubao-seed-2-0-pro"],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",aliases:["doubao-seed-2-0-lite"],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",aliases:["doubao-seed-2-0-mini"],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",aliases:["doubao-seed-2-0-code-preview"],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-embedding-vision-251215",name:"Doubao Embedding Vision",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:2048,maxTokens:8192}},{id:"doubao-seedance-2-0-260128",aliases:["doubao-seedance-2-0"],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",aliases:["doubao-seedance-2-0-fast"],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",aliases:["doubao-seedream-5-0"],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:["2K"]}},{id:"doubao-seedream-4-5-251128",aliases:["doubao-seedream-4-5"],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:["2K"]}},{id:"doubao-seed3d-2-0-260328",aliases:["doubao-seed3d-2-0"],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",aliases:["hyper3d-gen2"],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",aliases:["hitem3d-2-0"],name:"HiTem3D 2.0",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"3d",mediaCapabilities:{type:"3d",operations:["img2_3d"],outputFormats:["glb","obj","usd"]}}]},{id:"openai",name:"OpenAI",transport:"openai-responses",baseUrl:"https://api.openai.com",apiKeyEnvVars:["OPENAI_API_KEY"],authType:"bearer",isAggregator:!1,defaultModel:"gpt-5.5",quirks:{builtinWebSearch:!0,builtinCodeInterpreter:!0,builtinFileSearch:!0},models:[{id:"gpt-5.5",name:"GPT-5.5",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:30,costCacheRead:.5},{id:"gpt-5.4",name:"GPT-5.4",contextWindow:105e4,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:2.5,costOutput:15,costCacheRead:.25},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.75,costOutput:4.5,costCacheRead:.075},{id:"gpt-5.4-nano",name:"GPT-5.4 Nano",contextWindow:4e5,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:.2,costOutput:1.25,costCacheRead:.02},{id:"gpt-image-2",name:"GPT Image 2",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img","inpainting"],sizes:["1024x1024","1536x1024","1024x1536","auto"],transparentBackground:!0}},{id:"gpt-realtime-2",name:"GPT Realtime 2",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!0,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}},{id:"gpt-realtime-translate",name:"GPT Realtime Translate",contextWindow:128e3,maxOutput:16e3,toolCall:!1,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!1}},{id:"gpt-realtime-1.5",name:"GPT Realtime 1.5",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}},{id:"gpt-realtime-mini",name:"GPT Realtime Mini",contextWindow:128e3,maxOutput:16e3,toolCall:!0,reasoning:!1,vision:!1,mediaType:"realtime_audio",mediaCapabilities:{type:"realtime_audio",voices:["alloy","ash","ballad","coral","echo","fable","onyx","nova","sage","shimmer"],modalities:["text","audio"],vad:!0,toolCalling:!0}}]},{id:"anthropic",name:"Anthropic",transport:"anthropic-messages",baseUrl:"https://api.anthropic.com",apiKeyEnvVars:["ANTHROPIC_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"claude-opus-4-7",quirks:{supportsDocumentVision:!0},models:[{id:"claude-opus-4-7",name:"Claude Opus 4.7",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-opus-4-6",name:"Claude Opus 4.6",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5,costCacheWrite:6.25},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindow:1e6,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:3,costOutput:15,costCacheRead:.3,costCacheWrite:3.75},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindow:2e5,maxOutput:64e3,toolCall:!0,reasoning:!0,vision:!0,costInput:1,costOutput:5,costCacheRead:.1,costCacheWrite:1.25}]},{id:"google",name:"Google Gemini",transport:"gemini-generatecontent",baseUrl:"https://generativelanguage.googleapis.com/v1beta",apiKeyEnvVars:["GOOGLE_API_KEY","GEMINI_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"gemini-3-flash-preview",quirks:{builtinWebSearch:!0,builtinCodeInterpreter:!0,builtinUrlContext:!0,builtinMapsGrounding:!0,builtinFileSearch:!0,supportsDocumentVision:!0},models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,reasoningRequired:!0,vision:!0,costInput:2,costOutput:12},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.5,costOutput:3},{id:"gemini-3.1-flash-lite",name:"Gemini 3.1 Flash-Lite",contextWindow:1048576,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!0,costInput:.25,costOutput:1.5},{id:"gemini-3.1-flash-image-preview",name:"Gemini 3.1 Flash Image (Nano Banana 2)",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}},{id:"gemini-3-pro-image-preview",name:"Gemini 3 Pro Image (Nano Banana Pro)",contextWindow:4096,maxOutput:1,toolCall:!1,reasoning:!1,vision:!0,costInput:0,costOutput:0,mediaType:"image",mediaCapabilities:{type:"image",operations:["text2image","img2img"],sizes:["1024x1024"]}},{id:"veo-3.1-generate-preview",name:"Veo 3.1 Standard",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P","4K"]}},{id:"veo-3.1-fast-generate-preview",name:"Veo 3.1 Fast",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P","4K"]}},{id:"veo-3.1-lite-generate-preview",name:"Veo 3.1 Lite",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"video",mediaCapabilities:{type:"video",operations:["text2video","img2video"],maxDurationSeconds:8,resolutions:["720P","1080P"]}},{id:"lyria-3-pro-preview",name:"Lyria 3 Pro",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:300,formats:["mp3"]}},{id:"lyria-3-clip-preview",name:"Lyria 3 Clip",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music",mediaCapabilities:{type:"music",operations:["text2music"],maxDurationSeconds:30,formats:["mp3"]}},{id:"lyria-realtime-exp",name:"Lyria RealTime (Experimental)",contextWindow:2e3,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,mediaType:"music_realtime",mediaCapabilities:{type:"music",operations:["realtime"],formats:["wav"]}},{id:"gemini-3.1-flash-tts-preview",name:"Gemini 3.1 Flash TTS",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:1,costOutput:20,mediaType:"tts",mediaCapabilities:{type:"tts",operations:["text2speech"],maxCharacters:8e3,formats:["mp3","wav"]}},{id:"gemini-embedding-2",name:"Gemini Embedding 2 (Multimodal)",contextWindow:8192,maxOutput:1,toolCall:!1,reasoning:!1,vision:!1,costInput:.2,costOutput:0,mediaType:"embedding",mediaCapabilities:{type:"embedding",dimensions:3072,maxTokens:8192}}]},{id:"openrouter",name:"OpenRouter",transport:"openai-chat",baseUrl:"https://openrouter.ai/api",apiKeyEnvVars:["OPENROUTER_API_KEY"],authType:"bearer",isAggregator:!0,defaultModel:"anthropic/claude-opus-4.7",extraHeaders:{"HTTP-Referer":"https://claw.bot","X-Title":"XiaozhiClaw"},models:[{id:"anthropic/claude-opus-4.7",name:"Claude Opus 4.7 (via OpenRouter)",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5},{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6 (via OpenRouter)",contextWindow:1e6,maxOutput:128e3,toolCall:!0,reasoning:!0,vision:!0,costInput:5,costOutput:25,costCacheRead:.5},{id:"deepseek/deepseek-v4-flash",name:"DeepSeek V4 Flash (via OpenRouter)",contextWindow:1048576,maxOutput:393216,toolCall:!0,reasoning:!0,vision:!1,costInput:.14,costOutput:.28,costCacheRead:.028}]},{id:"qwen-coding",name:"Alibaba Qwen (Coding Plan)",transport:"anthropic-messages",baseUrl:"https://coding.dashscope.aliyuncs.com/apps/anthropic",apiKeyEnvVars:["DASHSCOPE_API_KEY","QWEN_API_KEY"],authType:"x-api-key",isAggregator:!1,defaultModel:"qwen3-coder-plus",models:[{id:"qwen3-coder-plus",name:"Qwen3 Coder Plus (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1},{id:"qwen3-coder-flash",name:"Qwen3 Coder Flash (Coding Plan)",contextWindow:262144,maxOutput:65536,toolCall:!0,reasoning:!0,vision:!1}]}]});var GS,sn,xu=N(()=>{"use strict";Ga();GS={claude:"anthropic",gemini:"google",doubao:"volcengine"},sn=class{builtins=new Map;overrides=new Map;constructor(){for(let e of Wa)this.builtins.set(e.id,e)}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=GS[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){return this.getProvider(e)?.models??[]}getModelInfo(e,t){return this.listModels(e).find(o=>o.id===t)}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()}}}});function HS(n){if(n)return n==="openai"?"openai-chat":n==="anthropic"?"anthropic-messages":n}function VS(n,e){return Ru(n.id,e)?"exact":(n.aliases??[]).some(t=>Ru(t,e))?"alias":void 0}function Ru(n,e){return n.trim().toLowerCase()===e.trim().toLowerCase()}function KS(n,e){return n.variantKind?n.variantKind:e.mediaType==="realtime_audio"||e.mediaType==="realtime_video"?"realtime":e.mediaType?"media-plan":n.id.includes("coding")||e.id.toLowerCase().includes("coder")||e.id.toLowerCase().includes("codegeex")?"coding-plan":n.transport==="openai-chat"||n.transport==="openai-responses"||n.transport==="volcengine-responses"?"openai-compatible":n.transport==="anthropic-messages"?"anthropic-compatible":"standard"}function zS(n){return n==="coding-plan"||n==="media-plan"?"plan":"paygo"}function qS(n,e){let t=new Set(n.capabilities??[]);return e.reasoning&&t.add("thinking"),e.vision&&t.add("vision"),e.mediaType&&t.add("media"),(e.mediaType==="realtime_audio"||e.mediaType==="realtime_video")&&t.add("realtime"),e.toolCall&&n.quirks?.supportsToolStream&&t.add("tool_stream"),n.quirks?.supportsReasoningSplit&&t.add("reasoning_split"),(n.quirks?.builtinWebSearch||n.quirks?.builtinCodeInterpreter||n.quirks?.builtinUrlContext)&&t.add("builtin_tools"),(n.id.includes("coding")||e.id.toLowerCase().includes("coder")||e.id.toLowerCase().includes("codegeex"))&&t.add("coding"),[...t].sort()}function YS(n){let e=100;return e+=n.matchKind==="exact"?25:15,n.requestedTransport&&n.provider.transport===n.requestedTransport&&(e+=20),e+=n.requiredCapabilities.length*15,n.preferProviderId&&n.provider.id===n.preferProviderId&&(e+=50),n.preferVariantKind&&n.variantKind===n.preferVariantKind&&(e+=35),n.purpose==="textGeneration"&&!n.capabilities.includes("media")&&(e+=5),n.purpose==="imageGeneration"&&n.capabilities.includes("media")&&(e+=10),n.purpose==="videoGeneration"&&n.capabilities.includes("media")&&(e+=10),n.capabilities.includes("tool_stream")&&(e+=8),n.capabilities.includes("reasoning_split")&&(e+=8),n.variantKind==="coding-plan"&&(e+=n.provider.id.includes("coding")?12:5),e}function XS(n){let e=[n.matchKind==="exact"?"model id matched":"public alias matched"];n.requestedTransport&&e.push(`protocol ${n.requestedTransport} matched`);for(let t of n.requiredCapabilities)e.push(`capability ${t} matched`);return n.preferProviderId&&n.provider.id===n.preferProviderId&&e.push("preferred provider matched"),n.preferVariantKind&&n.variantKind===n.preferVariantKind&&e.push("preferred variant matched"),e}var _o,_u=N(()=>{"use strict";_o=class{registry;constructor(e){this.registry=e}resolve(e){let t=e.publicModel.trim();if(!t)return[];let o=e.userPreference?.providerIds?new Set(e.userPreference.providerIds):void 0,r=HS(e.requestedProtocol),s=e.capabilities??[],i=[];for(let a of this.registry.listProviders())if(!(o&&!o.has(a.id))&&!(r&&a.transport!==r))for(let l of this.registry.listModels(a.id)){let c=VS(l,t);if(!c)continue;let d=qS(a,l);if(s.some(f=>!d.includes(f)))continue;let u=KS(a,l),p=a.billingChannelKind??zS(u),m=XS({matchKind:c,requestedTransport:r,requiredCapabilities:s,preferProviderId:e.userPreference?.preferProviderId,preferVariantKind:e.userPreference?.preferVariantKind,purpose:e.purpose,provider:a,variantKind:u,capabilities:d}),h=YS({matchKind:c,requestedTransport:r,requiredCapabilities:s,preferProviderId:e.userPreference?.preferProviderId,preferVariantKind:e.userPreference?.preferVariantKind,purpose:e.purpose,provider:a,variantKind:u,capabilities:d});i.push({provider:a.id,group:a.group??a.id,publicModel:t,nativeModelId:l.id,displayName:l.name,transport:a.transport,variantKind:u,billingChannelKind:p,capabilities:d,score:h,reasons:m,providerDef:a,modelInfo:l})}return i.sort((a,l)=>l.score!==a.score?l.score-a.score:a.group!==l.group?a.group.localeCompare(l.group):a.provider.localeCompare(l.provider))}resolveBest(e){return this.resolve(e)[0]}}});var jn=N(()=>{"use strict"});function QS(n){let e=n.slice(n.lastIndexOf(".")).toLowerCase();return JS[e]||"application/octet-stream"}function eT(n){return ZS.test(n)}async function Au(n,e,t,o){if(n.startsWith("data:")||!eT(n))return n;let r=await fetch(n,{signal:o});if(!r.ok)throw new Error(`Failed to fetch local media ${n}: ${r.status}`);let s=Buffer.from(await r.arrayBuffer()),i=tT(n),a=r.headers.get("content-type")||QS(i);return(await e.uploadFile(s,i,a,t,o)).url}function tT(n){try{let t=new URL(n).pathname.split("/").pop();return t&&t.includes(".")?t:"upload"}catch{return"upload"}}var JS,ZS,Pu=N(()=>{"use strict";JS={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".avif":"image/avif",".heic":"image/heic",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".aac":"audio/aac",".flac":"audio/flac",".m4a":"audio/mp4",".opus":"audio/opus",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".json":"application/json"};ZS=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i});function z(n){return nT.test(n)}async function ut(n,e){return Au(n,e.uploadAdapter,e.apiKey,e.signal)}async function Ur(n,e){if(n.startsWith("data:")||!z(n))return n;let t=await fetch(n);if(!t.ok)throw new Error(`Failed to fetch local media ${n}: ${t.status}`);let o=Buffer.from(await t.arrayBuffer());if(o.byteLength>oT)throw new Error(`Local media too large for base64 (${(o.byteLength/1024/1024).toFixed(1)}MB). Use file upload API instead.`);return`data:${t.headers.get("content-type")||e||rT(n)};base64,${o.toString("base64")}`}function rT(n){let e=n.split("?")[0].split("#")[0],t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".avif":"image/avif",".heic":"image/heic",".mp4":"video/mp4",".webm":"video/webm",".mov":"video/quicktime",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".aac":"audio/aac",".flac":"audio/flac",".m4a":"audio/mp4",".opus":"audio/opus",".pdf":"application/pdf"}[t]||"application/octet-stream"}var nT,oT,Fn=N(()=>{"use strict";Pu();nT=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i;oT=20*1024*1024});function At(n){let e=Math.min(1e3*Math.pow(2,n-1),3e4),t=Math.random()*.25*e;return e+t}function Bt(n){return n!=null&&Ha.has(n)}function Pt(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 Wt(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 Ha,_t,Bn=N(()=>{"use strict";Ha=new Set([429,529,502,503,504]),_t=9e4});function Ao(n){return n.toLowerCase().startsWith("gpt-5")}function jr(n){return n.toLowerCase().includes("5.4-nano")}function Po(n){return/^o[1-4](-|$)/.test(n.toLowerCase())}var Va=N(()=>{"use strict"});function sT(n){switch(n){case"sensitive":return"content_filter";case"model_context_window_exceeded":return"length";case"network_error":return"error";default:return n}}async function iT(n,e,t,o){return n.some(s=>s.audioUrls?.some(z)||s.imageUrls?.some(z))?Promise.all(n.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.role==="user"&&s.audioUrls?.some(z)&&(i.audioUrls=await Promise.all(s.audioUrls.map(a=>z(a)?Ur(a):Promise.resolve(a)))),s.imageUrls?.some(z)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>z(a)?ut(a,{uploadAdapter:e,apiKey:t,signal:o}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):n}function aT(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 l=[];if(t.content&&l.push({type:"text",text:t.content}),o){let c=t.imageUrls.length>1;for(let d=0;d<t.imageUrls.length;d++){let u=t.imageUrls[d];c&&l.push({type:"text",text:`[Image ${d+1}]`});let p={url:u};t.imageDetail&&(p.detail=t.imageDetail),l.push({type:"image_url",image_url:p})}}if(r)for(let c of t.videoUrls)l.push({type:"video_url",video_url:{url:c}});if(s)for(let c of t.audioUrls){let d=c,u=t.audioFormat??"mp3";if(c.startsWith("data:")){let p=/^data:audio\/([^;]+);base64,(.+)$/.exec(c);p&&(u=p[1]==="mpeg"?"mp3":p[1],d=p[2])}l.push({type:"input_audio",input_audio:{data:d,format:u}})}if(i)for(let c of t.fileIds){let d=c.mimeType||"";if(c.size!=null&&c.size>52428800){let p=`${(c.size/1048576).toFixed(1)}MB`;l.push({type:"text",text:`[Attached: ${c.id} (${d||"unknown"}, ${p})file too large for direct vision, use tools to process]`})}else if(e.supportsDocumentVision&&(d==="application/pdf"||c.id.endsWith(".pdf")))c.id.startsWith("http://")||c.id.startsWith("https://")?l.push({type:"text",text:`[Attached PDF: ${c.id}]`}):l.push({type:"file",file:{file_id:c.id}});else if(c.id.startsWith("http://")||c.id.startsWith("https://")){let p=d?`[Attached: ${c.id} (${d})]`:`[Attached: ${c.id}]`;l.push({type:"text",text:p})}else l.push({type:"file",file:{file_id:c.id}})}return{role:"user",content:l}}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}if(t.role==="tool"){if(t.imageUrls&&t.imageUrls.length>0&&!e.filterImageBlocks){let o=[];t.content&&o.push({type:"text",text:t.content});for(let r of t.imageUrls)o.push({type:"image_url",image_url:{url:r}});return{role:"tool",content:o,tool_call_id:t.tool_call_id??""}}return{role:"tool",content:t.content??"",tool_call_id:t.tool_call_id??""}}return{role:t.role,content:t.content??""}})}var Wn,Ka=N(()=>{"use strict";jn();Fn();Bn();Va();Wn=class{baseUrl;extraHeaders;timeoutMs;supportsStreamOptions;omitZeroTemperature;quirks;fileUploadAdapter;cumulativeReasoningLen=0;cumulativeContentLen=0;constructor(e){if(!e.baseUrl)throw new Error("OpenAIChatTransport: baseUrl is required (got empty or undefined)");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.supportsStreamOptions=e.supportsStreamOptions??!0,this.omitZeroTemperature=e.omitZeroTemperature??!1,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,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:aT(await iT(e.messages,this.fileUploadAdapter,t,o),this.quirks),stream:!0};this.supportsStreamOptions&&(a.stream_options={include_usage:!0}),e.tools&&e.tools.length>0&&(a.tools=e.tools,e.toolChoice&&(a.tool_choice=e.toolChoice));let l=!e.disableBuiltinTools,c=!1;if(l&&this.quirks.builtinWebSearch&&a.tools){let f=a.tools;this.quirks.builtinCodeInterpreter?f.push({type:"web_search",web_search:{enable:!0,search_result:!0}}):(f.push({type:"builtin_function",function:{name:"$web_search"}}),c=!0)}l&&this.quirks.builtinCodeInterpreter&&a.tools&&a.tools.push({type:"code_interpreter",code_interpreter:{sandbox:"none"}}),this.quirks.supportsToolStream&&a.tools&&(a.tool_stream=!0);let d=this.quirks.useEffortInsteadOfBudget&&!!e.reasoning,u=e.model.startsWith("kimi-k2.6"),p=Ao(e.model);if(e.temperature!==void 0&&(this.omitZeroTemperature&&e.temperature===0||(p||!Po(e.model)&&!d&&!u)&&(a.temperature=e.temperature)),e.topP!==void 0&&(p||!Po(e.model)&&!d&&!u)&&(a.top_p=e.topP),e.maxTokens!==void 0&&(p||Po(e.model)||e.model.startsWith("kimi-k2")?a.max_completion_tokens=e.maxTokens:a.max_tokens=e.maxTokens),e.reasoning)if(p){let f=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;jr(e.model)&&(f==="high"||f==="xhigh")&&(f="medium"),a.reasoning={effort:f}}else if(Po(e.model))a.reasoning_effort=e.reasoning.effort;else if(this.quirks.useEffortInsteadOfBudget){a.thinking={type:"enabled"};let f=this.quirks.maxReasoningEffort??"high",y=e.reasoning.effort??"high";a.reasoning_effort=y==="low"||y==="medium"?"high":f}else this.quirks.supportsThinkingParam?(c?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 c?a.thinking={type:"disabled"}:this.quirks.supportsThinkingParam&&this.quirks.disableThinkingByDefault&&(a.thinking={type:"disabled"});e.structuredOutput&&(e.structuredOutput.mode==="json_object"?a.response_format={type:"json_object"}:e.structuredOutput.mode==="json_schema"&&(a.response_format={type:"json_schema",json_schema:{name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}})),this.quirks.supportsReasoningSplit&&e.reasoning&&(a.reasoning_split=!0),e.prediction&&p&&(a.prediction=e.prediction),r&&e.prefixMessage&&a.messages.push({role:"assistant",content:e.prefixMessage,prefix:!0});let m={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},h=null;for(let f=0;f<=2;f++){if(o?.aborted)throw new Error("Request aborted");f>0&&h&&await Pt(At(f),o);try{yield*this.fetchAndStream(i,m,a,o);return}catch(y){h=y instanceof Error?y:new Error(String(y));let b=h.message.includes("Stream idle timeout");if(!Bt(Wt(h))&&!b||f===2)throw h}}}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 c=await a.text().catch(()=>""),d=new Error(`LLM API error ${a.status}: ${c.slice(0,500)}`);throw d.status=a.status,d}if(!a.body)throw new Error("LLM API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStreamWithWatchdog(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();t.usage&&(yield{type:"usage",promptTokens:t.usage.prompt_tokens??0,completionTokens:t.usage.completion_tokens??0,reasoningTokens:t.usage.completion_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.prompt_tokens_details?.cached_tokens});for(let 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()},_t)};try{i();let a=e.getReader();try{for(;;){let{done:l,value:c}=await a.read();if(l)break;if(s.signal.aborted)throw new Error("Stream idle timeout");i(),o+=t.decode(c,{stream:!0});let d;for(;(d=o.indexOf(`
16
16
  `))!==-1;){let u=o.slice(0,d).trim();if(o=o.slice(d+1),!u||u.startsWith(":")||!u.startsWith("data: "))continue;let p=u.slice(6);if(p==="[DONE]")return;let m;try{m=JSON.parse(p)}catch{continue}yield*this.processChunk(m)}}}finally{a.releaseLock()}}finally{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:sT(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},l=AbortSignal.timeout(this.timeoutMs),c=o?AbortSignal.any([o,l]):l,d=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(i),signal:c});if(!d.ok){let h=await d.text().catch(()=>"");throw new Error(`FIM API error ${d.status}: ${h.slice(0,500)}`)}if(!d.body)throw new Error("FIM API returned no response body");let u=new TextDecoder,p="",m=d.body.getReader();try{for(;;){let{done:h,value:f}=await m.read();if(h)break;p+=u.decode(f,{stream:!0});let y;for(;(y=p.indexOf(`
17
17
  `))!==-1;){let b=p.slice(0,y).trim();if(p=p.slice(y+1),!b||b.startsWith(":")||!b.startsWith("data: "))continue;let k=b.slice(6);if(k==="[DONE]")return;let x;try{x=JSON.parse(k)}catch{continue}for(let I of x.choices??[])I.text&&(yield{type:"delta",text:I.text}),I.finish_reason&&(yield{type:"done",finishReason:I.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`,l=new FormData;l.append("file",e,t),l.append("purpose",o);let c=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${r}`,...this.extraHeaders},body:l,signal:s??AbortSignal.timeout(this.timeoutMs)});if(!c.ok){let u=await c.text().catch(()=>"");throw new Error(`File upload error ${c.status}: ${u}`)}let d=await c.json();return{fileId:d.id??"",filename:d.filename??t,bytes:d.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 l=await i.text().catch(()=>"");throw new Error(`File info error ${i.status}: ${l}`)}let a=await i.json();return{id:a.id??e,filename:a.filename??"",bytes:a.bytes??0,status:a.status??"unknown"}}}});async function lT(n,e,t,o){return n.some(s=>s.audioUrls?.some(z)||s.imageUrls?.some(z))?Promise.all(n.map(async s=>{if(s.role!=="user"&&s.role!=="tool")return s;let i={};if(s.role==="user"&&s.audioUrls?.some(z)&&(i.audioUrls=await Promise.all(s.audioUrls.map(a=>z(a)?Ur(a):Promise.resolve(a)))),s.imageUrls?.some(z)){if(!e||!t)throw new Error("FileUploadAdapter required for local image URLs. Configure OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET or QLOGICAGENT_HUB_URL.");i.imageUrls=await Promise.all(s.imageUrls.map(a=>z(a)?ut(a,{uploadAdapter:e,apiKey:t,signal:o}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):n}function cT(n,e={}){let t=[];for(let o of n){if(o.role==="system"){t.push({role:"developer",content:o.content??""});continue}if(o.role==="user"){let r=o.imageUrls&&o.imageUrls.length>0,s=o.videoUrls&&o.videoUrls.length>0,i=o.audioUrls&&o.audioUrls.length>0,a=o.fileIds&&o.fileIds.length>0;if(r||s||i||a){let c=[];if(r){let d=o.imageUrls.length>1;for(let u=0;u<o.imageUrls.length;u++){let p=o.imageUrls[u];d&&c.push({type:"input_text",text:`[Image ${u+1}]`});let m={type:"input_image",image_url:p};o.imageDetail&&(m.detail=o.imageDetail),c.push(m)}}if(s)for(let d of o.videoUrls)c.push({type:"input_video",video_url:d});if(i)for(let d of o.audioUrls){let u=d,p=o.audioFormat??"mp3";if(d.startsWith("data:")){let m=/^data:audio\/([^;]+);base64,(.+)$/.exec(d);m&&(p=m[1]==="mpeg"?"mp3":m[1],u=m[2])}c.push({type:"input_audio",data:u,format:p})}if(a)for(let d of o.fileIds){let u=d.mimeType||"";if(d.size!=null&&d.size>52428800){let m=`${(d.size/1048576).toFixed(1)}MB`;c.push({type:"input_text",text:`[Attached: ${d.id} (${u||"unknown"}, ${m}) \u2014 file too large for direct vision, use tools to process]`})}else if(e.supportsDocumentVision&&(u==="application/pdf"||d.id.endsWith(".pdf")))d.id.startsWith("http://")||d.id.startsWith("https://")?c.push({type:"input_text",text:`[Attached PDF: ${d.id}]`}):c.push({type:"input_file",file_id:d.id});else if(d.id.startsWith("http://")||d.id.startsWith("https://")){let m=u?`[Attached: ${d.id} (${u})]`:`[Attached: ${d.id}]`;c.push({type:"input_text",text:m})}else c.push({type:"input_file",file_id:d.id})}o.content&&c.push({type:"input_text",text:o.content}),t.push({role:"user",content:c})}else t.push({role:"user",content:o.content??""});continue}if(o.role==="assistant"){if(o.content&&t.push({role:"assistant",content:o.content}),o.tool_calls&&o.tool_calls.length>0)for(let r of o.tool_calls)t.push({type:"function_call",call_id:r.id,name:r.function.name,arguments:r.function.arguments});continue}if(o.role==="tool"){if(!o.tool_call_id)continue;if(o.imageUrls&&o.imageUrls.length>0){let r=[];o.content&&r.push({type:"input_text",text:o.content});for(let s of o.imageUrls)r.push({type:"input_image",image_url:s});t.push({type:"function_call_output",call_id:o.tool_call_id,output:r})}else t.push({type:"function_call_output",call_id:o.tool_call_id,output:o.content??""});continue}}return t}var Fr,Iu=N(()=>{"use strict";jn();Fn();Bn();Va();Fr=class{baseUrl;extraHeaders;timeoutMs;quirks;fileUploadAdapter;constructor(e){if(!e.baseUrl)throw new Error("OpenAIResponsesTransport: baseUrl is required");this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.extraHeaders=e.extraHeaders??{},this.timeoutMs=e.timeoutMs??18e4,this.quirks=e.quirks??{},this.fileUploadAdapter=e.fileUploadAdapter}async*stream(e,t,o){let s=/\/v\d+$/.test(this.baseUrl)?`${this.baseUrl}/responses`:`${this.baseUrl}/v1/responses`,i=await this.buildRequestBody(e,t,o),a={"Content-Type":"application/json",Authorization:`Bearer ${t}`,...this.extraHeaders},l=null;for(let c=0;c<=2;c++){if(o?.aborted)throw new Error("Request aborted");c>0&&l&&await Pt(At(c),o);try{yield*this.fetchAndStream(s,a,i,o);return}catch(d){l=d instanceof Error?d:new Error(String(d));let u=l.message.includes("Stream idle timeout");if(!Bt(Wt(l))&&!u||c===2)throw l}}}async buildRequestBody(e,t,o){let r={model:e.model,input:cT(await lT(e.messages,this.fileUploadAdapter,t,o),this.quirks),stream:!0};e.conversationId?r.conversation=e.conversationId:e.previousResponseId&&(r.previous_response_id=e.previousResponseId),e.store!==void 0&&(r.store=e.store),e.instructions&&(r.instructions=e.instructions),e.structuredOutput&&(e.structuredOutput.mode==="json_object"?r.text={format:{type:"json_object"}}:r.text={format:{type:"json_schema",name:e.structuredOutput.name,strict:e.structuredOutput.strict??!0,schema:e.structuredOutput.schema}}),e.tools&&e.tools.length>0&&(r.tools=e.tools.map(i=>({type:"function",name:i.function.name,description:i.function.description,parameters:i.function.parameters,strict:!0}))),e.toolChoice!==void 0&&(typeof e.toolChoice=="string"?r.tool_choice=e.toolChoice:r.tool_choice={type:e.toolChoice.type,name:e.toolChoice.name});let s=Ao(e.model);if(!s&&e.temperature!==void 0&&(r.temperature=e.temperature),!s&&e.topP!==void 0&&(r.top_p=e.topP),e.maxTokens!==void 0&&(r.max_output_tokens=e.maxTokens),e.reasoning){let i=e.reasoning.effort==="minimal"?"none":e.reasoning.effort;jr(e.model)&&(i==="high"||i==="xhigh")&&(i="medium");let a={effort:i};a.summary="auto",a.generate_summary="auto",r.reasoning=a}if(e.prediction&&Ao(e.model)&&(r.prediction=e.prediction),r.truncation="auto",e.promptCacheKey&&(r.prompt_cache_key=e.promptCacheKey),e.promptCacheRetention&&(r.prompt_cache_retention=e.promptCacheRetention),e.serviceTier&&(r.service_tier=e.serviceTier),e.reasoning?.includeEncryptedReasoning&&(e.store===void 0&&(r.store=!1),r.include=["reasoning.encrypted_content"]),e.contextManagement&&(r.context_management=e.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})),!e.disableBuiltinTools){let i=r.tools??[],a=r.include??[];if(e.openaiBuiltinTools&&e.openaiBuiltinTools.length>0){for(let c of e.openaiBuiltinTools)i.push({...c});let l=new Set(e.openaiBuiltinTools.map(c=>c.type));l.has("web_search_preview")&&a.push("web_search_call.action.sources"),l.has("file_search")&&a.push("file_search_call.results"),l.has("code_interpreter")&&a.push("code_interpreter_call.outputs"),l.has("computer_use_preview")&&a.push("computer_call_output.output.image_url")}else this.quirks.builtinWebSearch&&(i.push({type:"web_search_preview"}),a.push("web_search_call.action.sources")),this.quirks.builtinCodeInterpreter&&(i.push({type:"code_interpreter"}),a.push("code_interpreter_call.outputs")),this.quirks.builtinFileSearch&&(i.push({type:"file_search"}),a.push("file_search_call.results"));i.length>0&&(r.tools=i),a.length>0&&(r.include=a)}if(e.maxToolCalls!==void 0&&(r.max_tool_calls=e.maxToolCalls),e.parallelToolCalls!==void 0&&(r.parallel_tool_calls=e.parallelToolCalls),e.textVerbosity){let i=r.text??{};i.verbosity=e.textVerbosity,r.text=i}return r}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 c=await a.text().catch(()=>""),d=new Error(`OpenAI Responses API error ${a.status}: ${c.slice(0,500)}`);throw d.status=a.status,d}if(!a.body)throw new Error("OpenAI Responses API returned no response body");let l=a.headers.get("content-type")??"";if(l.includes("application/json")&&!l.includes("text/event-stream")){yield*this.handleNonStreamingResponse(a);return}yield*this.parseSSEStream(a.body)}async*handleNonStreamingResponse(e){let t=await e.json();if(t.id&&(yield{type:"response_id",id:t.id}),t.usage&&(yield{type:"usage",promptTokens:t.usage.input_tokens??0,completionTokens:t.usage.output_tokens??0,reasoningTokens:t.usage.output_tokens_details?.reasoning_tokens,cacheReadTokens:t.usage.input_tokens_details?.cached_tokens}),t.output)for(let 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??""},r.annotations&&r.annotations.length>0&&(yield{type:"annotations",annotations:r.annotations.map(s=>({...s,type:s.type??"url_citation",url:s.url,title:s.title}))}));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,l=new Map,c=()=>{s&&clearTimeout(s),s=setTimeout(()=>{i.abort()},_t)};try{c();let d=e.getReader();try{for(;;){let{done:u,value:p}=await d.read();if(u)break;if(i.signal.aborted)throw new Error("Stream idle timeout");c(),o+=t.decode(p,{stream:!0});let m;for(;(m=o.indexOf(`
@@ -39,21 +39,21 @@ ${s.executableCode.code}
39
39
  ...
40
40
  `:`
41
41
  `,e+=XT,e}async function Ju(n,e,t,o=ji){if(n.length<=o||qu(n))return n;let r=await Yu(n,e,t);return r?Xu(r):n.slice(0,o)+`
42
- ...[truncated ${n.length-o} chars]`}function ew(n){let e=[],t=[];for(let o of n)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?qu(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 tw(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 nw(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 Qu(n,e,t,o=Fi){let r=ew(n);if(r.length===0)return{messages:n,newlyReplacedCount:0};let s=new Map,i=[];for(let d of r){let{mustReapply:u,frozen:p,fresh:m}=tw(d,e);for(let k of u)s.set(k.toolCallId,k.replacement);if(m.length===0){for(let k of d)e.seenIds.add(k.toolCallId);continue}let h=p.reduce((k,x)=>k+x.size,0),f=m.reduce((k,x)=>k+x.size,0),y=h+f>o?nw(m,h,o):[],b=new Set(y.map(k=>k.toolCallId));for(let k of d)b.has(k.toolCallId)||e.seenIds.add(k.toolCallId);y.length>0&&i.push(...y)}if(s.size===0&&i.length===0)return{messages:n,newlyReplacedCount:0};let a=await Promise.all(i.map(async d=>{let u=await Yu(d.content,d.toolCallId,t);return{candidate:d,result:u}})),l=0;for(let{candidate:d,result:u}of a){if(e.seenIds.add(d.toolCallId),!u)continue;let p=Xu(u);s.set(d.toolCallId,p),e.replacements.set(d.toolCallId,p),l++}return s.size===0?{messages:n,newlyReplacedCount:0}:{messages:n.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let u=s.get(d.tool_call_id);return u===void 0?d:{...d,content:u}}),newlyReplacedCount:l}}var YT,Vu,XT,tl=N(()=>{"use strict";je();YT="tool-results",Vu="<persisted-output>",XT="</persisted-output>"});function sw(n){try{return JSON.parse(n)}catch{return}}var ow,rw,Kr,Zu=N(()=>{"use strict";$n();tl();ow=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),rw=new Set(["bash","execute_command","Bash","shell"]),Kr=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??ow,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:nn(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:l,log:c}=this.config,d=e.toolCall.function.name,u=!1,p=e.toolCall.function.arguments;if(i)try{let k=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:d,arguments:sw(p)});if(k.action==="abort"){let x=k.reason??"blocked by policy";c.info(`tool ${d} blocked: ${x}`),e.results.push({callId:e.id,toolName:d,ok:!1,error:x,blocked:!0,blockReason:x,message:nn(e.id,{ok:!1,error:x})}),e.status="completed";return}k.action==="continue"&&k.context?.arguments&&(p=JSON.stringify(k.context.arguments))}catch{}let m=await s.invoke(l,d,p,this.siblingAbortController.signal),h=this.getAbortReason();if(h&&!u){e.results.push(this.createSyntheticError(e,h)),e.status="completed";return}let f=!m.error,y=m.result;f&&y&&y.length>5e4&&(y=await Ju(y,e.id,a));let b=nn(e.id,{ok:f,payload:y,error:m.error,toolReferences:m.toolReferences,imageUrls:m.imageUrls});f||(u=!0,rw.has(d)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(f?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:l,callId:e.id,toolName:d,ok:f,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:d,ok:f,error:m.error,message:b}),e.status="completed"})();e.promise=o,o.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let e of this.tools)if(e.status!=="yielded"){if(e.status==="completed"&&e.results.length>0){e.status="yielded";for(let 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{homedir as iw}from"node:os";import{join as Ae}from"node:path";import{existsSync as aw}from"node:fs";function H(){return process.env.QLOGICAGENT_HOME||Ae(iw(),He)}function ep(){return Ae(H(),"plugins")}function Ht(){return Ae(H(),"skills")}function pt(){return Ae(H(),"settings.json")}function tp(){return Ae(H(),"plugin-cache")}function np(){return Ae(H(),"mcp.json")}function op(){return Ae(H(),"marketplace.json")}function rp(){return Ae(H(),"workflows")}function sp(){return Ae(H(),"rules")}function Oe(n){if(!n)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return Ae(n,He)}function ip(n){return Ae(Oe(n),"workflows")}function It(n){return Ae(Oe(n),"skills")}function Oo(n){return Ae(Oe(n),"INSTRUCTIONS.md")}function Gn(n){return Ae(Oe(n),"rules")}function Vt(n){return Ae(Oe(n),"sessions")}function ap(n,e){let t=Ae(Oe(n),"checkpoints");return e?Ae(t,e):t}function lp(n){return Ae(n,He,"hooks")}function cp(n,e){return n.filter(t=>t!==e&&aw(Ae(t,He,"skills")))}var He,le=N(()=>{"use strict";He=".qlogicagent"});var zr,dp=N(()=>{"use strict";zr=class{pools=new Map;runtimeStates=new Map;constructor(e){if(e)for(let t of e){this.pools.set(t.providerId,t);for(let o of t.keys)this.runtimeStates.set(o.id,this.createInitialState())}}acquireKey(e){let t=this.pools.get(e);if(!t||t.keys.length===0)return null;let o=Date.now(),r=this.getHealthyCandidates(t,o);if(r.length===0)return null;let s=this.selectByStrategy(r,t.strategy,o);if(!s)return null;let i=this.runtimeStates.get(s.id);return i.inFlight++,i.totalRequests++,i.lastUsedAt=o,i.requestTimestamps.push(o),{keyId:s.id,apiKey:s.key,providerId:e,release:a=>this.releaseKey(s.id,a)}}releaseKey(e,t){let o=this.runtimeStates.get(e);if(o)if(o.inFlight=Math.max(0,o.inFlight-1),t.success)o.consecutiveErrors=0,o.healthStatus="healthy",t.tokens&&(o.totalTokens+=t.tokens,o.tokenCounts.push(t.tokens));else if(o.consecutiveErrors++,o.lastErrorAt=Date.now(),t.errorCode===429){let r=t.retryAfter?t.retryAfter*1e3:3e4;o.cooldownUntil=Date.now()+r,o.healthStatus="cooldown"}else o.consecutiveErrors>=5?(o.cooldownUntil=Date.now()+6e4,o.healthStatus="cooldown"):o.consecutiveErrors>=3&&(o.healthStatus="degraded")}addProvider(e,t){this.pools.has(e)||this.pools.set(e,{providerId:e,baseUrl:t?.baseUrl,strategy:t?.strategy??"weighted-round-robin",keys:[],rateLimit:t?.rateLimit})}removeProvider(e){let t=this.pools.get(e);if(t){for(let o of t.keys)this.runtimeStates.delete(o.id);this.pools.delete(e)}}addKey(e,t,o){let r=this.pools.get(e);r||(r={providerId:e,strategy:"weighted-round-robin",keys:[]},this.pools.set(e,r));let s=o?.id??crypto.randomUUID(),i={id:s,key:t,label:o?.label,weight:o?.weight??1,enabled:o?.enabled??!0};return r.keys.push(i),this.runtimeStates.set(s,this.createInitialState()),s}removeKey(e){for(let t of this.pools.values()){let o=t.keys.findIndex(r=>r.id===e);if(o!==-1){t.keys.splice(o,1),this.runtimeStates.delete(e);return}}}updateKey(e,t){for(let o of this.pools.values()){let r=o.keys.find(s=>s.id===e);if(r){if(t.label!==void 0&&(r.label=t.label),t.weight!==void 0&&(r.weight=t.weight),t.enabled!==void 0){r.enabled=t.enabled;let s=this.runtimeStates.get(e);s&&(s.healthStatus=t.enabled?"healthy":"disabled")}return}}}setKeyHealth(e,t){let o=this.runtimeStates.get(e);o&&(o.healthStatus=t)}setStrategy(e,t){let o=this.pools.get(e);o&&(o.strategy=t)}setRateLimit(e,t){let o=this.pools.get(e);o&&(o.rateLimit=t)}getPoolStatus(e){let t=this.pools.get(e);return t?this.buildPoolStatus(t):null}getAllStatus(){return[...this.pools.values()].map(e=>this.buildPoolStatus(e))}getProviderIds(){return[...this.pools.keys()]}hasProvider(e){return this.pools.has(e)}hasAvailableKey(e){let t=this.pools.get(e);return t?this.getHealthyCandidates(t,Date.now()).length>0:!1}exportConfig(){return[...this.pools.values()]}reloadConfig(e){let t=new Set;for(let o of e){this.pools.set(o.providerId,o);for(let r of o.keys)t.add(r.id),this.runtimeStates.has(r.id)||this.runtimeStates.set(r.id,this.createInitialState())}for(let o of[...this.pools.keys()])e.some(r=>r.providerId===o)||this.pools.delete(o);for(let o of[...this.runtimeStates.keys()])t.has(o)||this.runtimeStates.delete(o)}createInitialState(){return{inFlight:0,totalRequests:0,totalTokens:0,lastUsedAt:0,lastErrorAt:0,consecutiveErrors:0,cooldownUntil:0,healthStatus:"healthy",requestTimestamps:[],tokenCounts:[]}}getHealthyCandidates(e,t){let o=[];for(let r of e.keys){if(!r.enabled)continue;let s=this.runtimeStates.get(r.id);if(s){if(s.healthStatus==="cooldown")if(t>=s.cooldownUntil)s.healthStatus="healthy",s.consecutiveErrors=0;else continue;s.healthStatus!=="disabled"&&(e.rateLimit?.rpm&&(this.pruneWindow(s.requestTimestamps,t),s.requestTimestamps.length>=e.rateLimit.rpm*.9)||e.rateLimit?.tpm&&(this.pruneWindow(s.tokenCounts,t),s.tokenCounts.reduce((a,l)=>a+l,0)>=e.rateLimit.tpm*.9)||o.push(r))}}return o}selectByStrategy(e,t,o){if(e.length===0)return null;if(e.length===1)return e[0];switch(t){case"weighted-round-robin":return this.weightedRandom(e);case"least-busy":return this.leastBusy(e);case"random":return e[Math.floor(Math.random()*e.length)];default:return this.weightedRandom(e)}}weightedRandom(e){let t=e.reduce((r,s)=>r+s.weight,0),o=Math.random()*t;for(let r of e)if(o-=r.weight,o<=0)return r;return e[e.length-1]}leastBusy(e){let t=1/0,o=e[0];for(let r of e){let i=this.runtimeStates.get(r.id)?.inFlight??0;(i<t||i===t&&r.weight>o.weight)&&(t=i,o=r)}return o}pruneWindow(e,t){let o=t-6e4;for(;e.length>0&&e[0]<o;)e.shift()}buildPoolStatus(e){return{providerId:e.providerId,baseUrl:e.baseUrl,strategy:e.strategy,rateLimit:e.rateLimit,keys:e.keys.map(t=>{let o=this.runtimeStates.get(t.id)??this.createInitialState();return{...t,inFlight:o.inFlight,totalRequests:o.totalRequests,totalTokens:o.totalTokens,lastUsedAt:o.lastUsedAt,lastErrorAt:o.lastErrorAt,consecutiveErrors:o.consecutiveErrors,cooldownUntil:o.cooldownUntil,healthStatus:t.enabled?o.healthStatus:"disabled"}})}}}});var up={};fn(up,{ALL_PURPOSES:()=>Lo,ModelRegistry:()=>qr,deriveModelPurposes:()=>cw,getModelRegistry:()=>X,resetModelRegistry:()=>lw});import*as et from"node:fs";function X(){return Do||(Do=new qr,Do.load()),Do}function lw(){Do=null}function cw(n){let e=[];switch((!n.mediaType||n.mediaType==="image_understanding"||n.mediaType==="video_understanding")&&e.push("textGeneration"),(n.vision||n.mediaType==="image_understanding")&&e.push("imageUnderstanding"),n.mediaType==="video_understanding"&&e.push("videoUnderstanding"),n.mediaType){case"image":e.push("imageGeneration");break;case"video":e.push("videoGeneration");break;case"tts":e.push("tts");break;case"stt":e.push("stt");break;case"music":case"music_realtime":e.push("musicGeneration");break;case"voice_clone":e.push("voiceClone");break;case"embedding":e.push("embedding");break;case"3d":e.push("threeDGeneration");break;case"realtime_audio":e.push("realtimeAudio");break}return e.includes("textGeneration")&&e.push("smallModel"),[...new Set(e.length>0?e:["textGeneration"])]}function dw(n){switch(n){case"openai-chat":case"openai-responses":case"anthropic-messages":case"volcengine-responses":return n;default:return}}var Lo,qr,Do,mt=N(()=>{"use strict";an();le();dp();Lo=["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"],qr=class{keyPool;coreProviderRegistry=new sn;providerVariantResolver=new _o(this.coreProviderRegistry);models=new Map;modelEnabledOverrides=new Map;bindings={};settingsPath;changeListeners=[];constructor(e){this.settingsPath=pt(),this.keyPool=new zr(e?.providers),e?.models&&this.loadModelState(e.models),e?.bindings&&(this.bindings={...e.bindings})}getActiveModel(e){let t=this.bindings[e];if(!t)return null;let o=this.models.get(t);if(!o||!o.enabled)return null;let r=this.resolveTechnicalVariant(o,e),s=r?.provider??o.provider,i=r?.nativeModelId??o.nativeModelId??o.model,a=this.acquireKeyForProviderVariant(s);if(!a)return null;let{keyHandle:l,keyProviderId:c}=a;return{provider:s,model:i,apiKey:l.apiKey,baseUrl:o.provider===s?o.baseUrl??this.getProviderBaseUrl(s)??this.getProviderBaseUrl(c):this.getProviderBaseUrl(s),keyHandle:l}}peekActiveModel(e){let t=this.bindings[e];return t?this.models.get(t)??null:null}isAvailable(e){let t=this.peekActiveModel(e);return!!t?.enabled&&this.hasAvailableKeyForProviderVariant(t.provider)}resolveModelForPurpose(e){let t=this.peekActiveModel(e);return t?t.model:null}addProvider(e,t){this.keyPool.addProvider(e,t),this.emitChange()}removeProvider(e){this.keyPool.removeProvider(e);for(let[t,o]of this.models)o.provider===e&&this.removeModel(t);this.emitChange()}addKey(e,t,o){let r=this.keyPool.addKey(e,t,o);return this.emitChange(),r}removeKey(e){this.keyPool.removeKey(e),this.emitChange()}updateKey(e,t){this.keyPool.updateKey(e,t),this.emitChange()}setKeyHealth(e,t){this.keyPool.setKeyHealth(e,t),this.emitChange()}setStrategy(e,t){this.keyPool.setStrategy(e,t),this.emitChange()}addModel(e){let t=e.id??`${e.provider}:${e.model}`;return this.models.set(t,{...e,id:t,enabled:this.modelEnabledOverrides.get(t)??e.enabled}),this.emitChange(),t}replaceCatalogModels(e){let t=new Map;for(let o of e)t.set(o.id,{...o,enabled:this.modelEnabledOverrides.get(o.id)??o.enabled});for(let o of this.modelEnabledOverrides.keys())t.has(o)||this.modelEnabledOverrides.delete(o);this.models=t;for(let[o,r]of Object.entries(this.bindings))r&&!this.models.has(r)&&delete this.bindings[o];this.emitChange()}migrateModelIds(e){for(let[t,o]of e){let r=this.modelEnabledOverrides.get(t);r!==void 0&&!this.modelEnabledOverrides.has(o)&&this.modelEnabledOverrides.set(o,r),this.modelEnabledOverrides.delete(t);for(let[s,i]of Object.entries(this.bindings))i===t&&(this.bindings[s]=o)}this.emitChange()}removeModel(e){this.models.delete(e),this.modelEnabledOverrides.delete(e);for(let[t,o]of Object.entries(this.bindings))o===e&&delete this.bindings[t];this.emitChange()}enableModel(e){let t=this.models.get(e);t&&(t.enabled=!0),this.modelEnabledOverrides.set(e,!0),this.emitChange()}disableModel(e){let t=this.models.get(e);t&&(t.enabled=!1),this.modelEnabledOverrides.set(e,!1),this.emitChange()}listModels(e){let t=[...this.models.values()];return e?.purpose&&(t=t.filter(o=>o.purposes.includes(e.purpose))),e?.provider&&(t=t.filter(o=>o.provider===e.provider)),e?.enabledOnly&&(t=t.filter(o=>o.enabled)),t}getModel(e){return this.models.get(e)??null}setBinding(e,t){let o=this.models.get(t);if(!o)throw new Error(`Model "${t}" not found in pool.`);if(!o.purposes.includes(e))throw new Error(`Model "${t}" does not support purpose "${e}".`);this.bindings[e]=t,this.emitChange()}removeBinding(e){delete this.bindings[e],this.emitChange()}getBinding(e){let t=this.bindings[e];return t?this.models.get(t)??null:null}getAllBindings(){let e={};for(let t of Lo){let o=this.bindings[t];e[t]=o?this.models.get(o)??null:null}return e}getProviderStatus(e){return this.keyPool.getPoolStatus(e)}getAllProviderStatus(){return this.keyPool.getAllStatus()}save(){let e={};try{et.existsSync(this.settingsPath)&&(e=JSON.parse(et.readFileSync(this.settingsPath,"utf-8")))}catch{e={}}delete e.provider,delete e.apiKey,delete e.model,delete e.baseUrl;let t={...e,providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}},o=this.settingsPath.replace(/[/\\][^/\\]+$/,"");et.existsSync(o)||et.mkdirSync(o,{recursive:!0}),et.writeFileSync(this.settingsPath,JSON.stringify(t,null,2),"utf-8")}load(){try{if(!et.existsSync(this.settingsPath))return!1;let e=et.readFileSync(this.settingsPath,"utf-8"),t=JSON.parse(e);return t.providers&&this.keyPool.reloadConfig(t.providers),this.models.clear(),this.modelEnabledOverrides.clear(),t.models&&this.loadModelState(t.models),this.bindings=t.bindings??{},this.emitChange(),!0}catch{return!1}}exportConfig(){return{providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}}}getTunable(e){try{if(!et.existsSync(this.settingsPath))return;let t=et.readFileSync(this.settingsPath,"utf-8");return JSON.parse(t).tunables?.[e]}catch{return}}getModelInfo(e,t){let o=this.listModels({provider:e}).find(r=>r.model===t);if(o)return{id:o.model,name:o.displayName,contextWindow:o.contextWindow,maxOutput:o.maxOutput,streamRequired:o.streamRequired}}getProviderDefaultModel(e){return this.listModels({provider:e,enabledOnly:!0})[0]?.model??this.listModels({provider:e})[0]?.model}hasConfiguredKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(t=>!!this.keyPool.getPoolStatus(t)?.keys.some(r=>r.enabled))}hasAvailableKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(t=>this.keyPool.hasAvailableKey(t))}listProviderDefs(){return this.keyPool.getAllStatus().map(e=>({id:e.providerId,name:e.providerId,transport:"",baseUrl:e.baseUrl??"",defaultModel:this.getProviderDefaultModel(e.providerId),models:this.listModels({provider:e.providerId}).map(t=>({id:t.model,name:t.displayName,contextWindow:t.contextWindow,maxOutput:t.maxOutput,streamRequired:t.streamRequired}))}))}resolveProviderApiKey(e){return this.getKeyForProvider(e)??void 0}onChange(e){return this.changeListeners.push(e),()=>{let t=this.changeListeners.indexOf(e);t>=0&&this.changeListeners.splice(t,1)}}getKeyForProvider(e){let o=this.acquireKeyForProviderVariant(e)?.keyHandle;if(!o)return null;let r=o.apiKey;return o.release({success:!0}),r}snapshotProviderKeys(){let e={};for(let t of this.keyPool.getAllStatus()){let o=this.getKeyForProvider(t.providerId);o&&(e[t.providerId]=o)}return e}getProviderBaseUrl(e){return this.keyPool.getPoolStatus(e)?.baseUrl}acquireKeyForProviderVariant(e){for(let t of this.providerVariantKeyCandidates(e)){let o=this.keyPool.acquireKey(t);if(o)return{keyHandle:o,keyProviderId:t}}return null}resolveTechnicalVariant(e,t){let o=this.providerVariantKeyCandidates(e.provider).filter(s=>this.hasConfiguredKeyForProviderVariant(s));if(o.length===0)return;let r=this.providerVariantResolver.resolveBest({publicModel:e.model,requestedProtocol:dw(e.transport),purpose:t,userPreference:{providerIds:o}});if(r)return{provider:r.provider,nativeModelId:r.nativeModelId}}providerVariantKeyCandidates(e){let t=[e],o=this.coreProviderRegistry.getProvider(e),r=o?.group??o?.id??e;for(let s of this.coreProviderRegistry.listProviders())(s.group??s.id)===r&&t.push(s.id);return r!==e&&t.push(r),[...new Set(t)]}loadModelState(e){for(let t of e)typeof t.id!="string"||!t.id||typeof t.enabled=="boolean"&&this.modelEnabledOverrides.set(t.id,t.enabled)}exportModelState(){let e=new Map;for(let[t,o]of this.modelEnabledOverrides)e.set(t,o);for(let t of this.models.values())e.set(t.id,t.enabled);return[...e.entries()].map(([t,o])=>({id:t,enabled:o}))}emitChange(){for(let e of this.changeListeners)try{e()}catch{}}},Do=null});import{readFile as uw}from"node:fs/promises";function Sn(n){let e=typeof n.content=="string"?n.content:n.content!=null?JSON.stringify(n.content):"";return Math.ceil(e.length/4)}function Tn(n){let e=0;for(let t of n)e+=Sn(t);return e}function mp(n){if(!n)return 128e3;if(n in nl)return nl[n];let e=n.toLowerCase();for(let[t,o]of Object.entries(nl))if(e.startsWith(t.toLowerCase()))return o;return 128e3}function mw(){return X().resolveModelForPurpose("textGeneration")??pw}function gp(){return rl}function fw(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"),ol(t);try{let i="",a=e?.model??mw();for await(let l of r.stream({model:a,messages:[{role:"system",content:"You are a precise conversation summarizer."},{role:"user",content:o}],maxTokens:2e3,temperature:.3},s,AbortSignal.timeout(3e4)))l.type==="delta"&&(i+=l.text);return i||(n.warn("[context-compression] empty summary response"),ol(t))}catch(i){return n.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),ol(t)}}}function ol(n){let e=[],t=n.filter(s=>s.role==="user"),o=t.slice(0,20).map(s=>{let i=typeof s.content=="string"?s.content:JSON.stringify(s.content??"");return`- [user]: ${i.slice(0,300)}${i.length>300?"...":""}`});e.push(`## User Requests (${t.length} messages)`),e.push(...o);let r=n.filter(s=>s.role==="assistant");if(r.length>0){let s=r.slice(0,10).map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??"");return`- [assistant]: ${a.slice(0,150)}${a.length>150?"...":""}`});e.push("",`## Assistant Responses (${r.length} total)`),e.push(...s)}return e.join(`
43
- `)}function gw(){return vi(new bn(sl),new on(20,Sn),new Dn(Sn))}function pp(n,e){let t=Si(new bn(sl),new on(20,Sn),new fo({protectedHeadExchanges:1,protectedTailMessages:8,summarize:n,estimateTokens:Sn}),new Dn(Sn));return new go({inner:t,estimateTokens:Sn,onCacheInvalidated:e?.onCacheInvalidated})}function hp(n,e){let t=e?.budget??Sr({modelContextWindow:mp(e?.model)}),r=(e?.pipeline??gw()).compress(n,t);if(r.droppedCount>0){let s=Tn(n),i=Tn(r.messages);fp.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:ko(s,t)})}return r.droppedCount>0&&il?.(r.droppedCount,Tn(r.messages)),r}async function hw(n,e,t){let o=t??Sr({modelContextWindow:mp(e.model)}),r=Tn(n),s=ko(r,o),i;switch(s){case"none":i={messages:n,droppedCount:0,strategy:"none"};break;case"trim-only":i=new bn(sl).compress(n,o);break;case"sliding-window":{i=await pp(e.summarize).compressAsync(n,o);break}case"llm-summarize":{let a=e.pipeline??pp(e.summarize);i=bo(a)?await a.compressAsync(n,o):a.compress(n,o);break}}return i.droppedCount>0&&(i={...i,messages:await wi(i.messages,n,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await uw(a,"utf-8")}catch{return null}}})}),yw(n,i,o),i}function yw(n,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let o=e.metrics?.tokensBefore||Tn(n),r=e.metrics?.tokensAfter||Tn(e.messages);fp.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:ko(o,t)})}if(e.droppedCount>0){let o=e.metrics?.tokensAfter||Tn(e.messages);il?.(e.droppedCount,o)}}function bw(n,e){let t=fw(n,e),o={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return hw(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};rl.register(o),rl.activate(o.id),n.info(`[context-compression] registered context engine: ${o.id}`)}function yp(n,e,t){bw(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"}}}),il=(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 nl,sl,pw,fp,rl,il,al=N(()=>{"use strict";$n();mt();nl={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-3.1-pro-preview":1e6,"gemini-3-flash-preview":1e6,"gemini-3.1-flash-lite":1e6};sl=8e3,pw="deepseek-v4-flash";fp=new ho(200),rl=new yo;il=null});function bp(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 taskyou are near the token limit.":"Continue workingdo not summarize prematurely.")}var kp=N(()=>{"use strict"});var vp={};fn(vp,{resolveToolEligibility:()=>ww});function vw(n,e){if(kw.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 Sw(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||vw(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function Tw(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 ww(n,e={}){let t=new Map,o=[],r=[],s=[];for(let i of n){let a=i.function.name,{level:l,reasons:c}=Sw(i,e),d=Tw(l),u={toolName:a,status:d,permissionLevel:l,approvalRequired:l===4,reasonCodes:c};t.set(a,u),l===5?r.push(u):(o.push(i),l===4&&s.push(u))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:s,eligibilityByName:t}}var kw,Sp=N(()=>{"use strict";kw=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Aw(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 Pw(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 Ew(n){if(!Cw.has(n.toolName))return!1;let e=typeof n.message?.content=="string"?n.message.content.trim():"";return e.length>0&&e.length<200&&Iw.test(e)}function Tp(n,e){for(let t=n.length-1;t>=0;t--){let o=n[t];if(!o||o.role!=="tool")continue;let r=typeof o.content=="string"?o.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Mw(n){return typeof n=="number"&&Number.isFinite(n)&&n>=1?Math.min(Math.round(n),100):Ii}function wp(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 Ow(n){return n==="length"||n==="max_tokens"}function xp(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 Dw(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 Lw(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 Nw(n){return n.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Rp(n,e,t,o){let{turnId:r,sessionId:s,messages:i,tools:a,model:l,apiKey:c,temperature:d=0,hooks:u,signal:p}=n,m={sessionId:s,turnId:r},h=n.maxTurns??0,f=n.querySource,{resolveToolEligibility:y}=await Promise.resolve().then(()=>(Sp(),vp)),b=y(a,n.toolEligibilityContext),k=b.eligibleTools;for(let j of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:j.toolName,reason:"blocked-by-policy"};if(!k.length){yield*$w(r,l,i,c,d,p,e,o);return}let x=Mw(n.maxRounds),I={contextWindowTokens:n.contextWindowTokens??Mi,responseBufferTokens:Oi,maxOutputTokens:n.maxOutputTokens??Di,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},P=new Set,O=0,$=k,W,S={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ia(I),reactiveCompactState:Da(),toolLoopState:Ar({maxRounds:x,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:_i(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:Ku(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map},ce=Math.max(h*5,200),de=0;for(;;){if(de++,de>ce){o.info(`hard iteration cap reached (${ce}), forcing completion`);let A=S.finalText||No(S.messages,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}let{messages:j,maxOutputTokensRecoveryCount:ve,hasAttemptedReactiveCompact:ie,maxOutputTokensOverride:Ue,turnCount:ne,guardState:Q,reactiveCompactState:T,collapseStore:F}=S,{toolLoopState:B}=S;if(W){try{let A=await W;A&&(yield{type:"tool_use_summary",turnId:r,summary:A})}catch{}W=void 0}if(n.refreshTools&&ne>1){let A=n.refreshTools();A!==$&&($=A,o.debug(`tools refreshed: ${A.length} tools`))}if(Oa(Q,I)){o.info(`turn aborted by guard at turn ${ne}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:S.totalUsage};return}let Re=Ca(Q,I);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&Nn(T)&&(T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Re.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${Re.reason}), ending tool loop`);break}Re.level==="warning"&&o.info(`token budget warning: ${Re.usagePercent}% used, ${Re.remainingTokens} remaining`);let he;{let A=await Qu(j,S.contentReplacementState,s);he=A.messages,A.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${A.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${A.newlyReplacedCount} persisted`})}{let A=xi(he,S.snipRemovedIds);he=A.messages,A.removedCount>0&&(o.info(`snip: removed ${A.removedCount} messages, freed ~${A.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${A.removedCount} messages`})}{let E=new on().compress(he,0);E.droppedCount>0&&(he=E.messages,o.info(`microcompact: cleared ${E.droppedCount} old tool results`))}if(he=Ai(he,F).messages,Q.promptTokens>0){let A=I.contextWindowTokens*.75,E=gp().getActive(),L;E?L=await E.compressAsync(he,A,{model:S.currentModel,sessionId:s}):L=hp(he,{budget:A,model:S.currentModel}),L.droppedCount>0&&(he=L.messages,o.info(`autocompact: ${L.strategy}, dropped ${L.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${L.strategy}: ${L.droppedCount} dropped`},S.hasAttemptedReactiveCompact=!1,u?.invoke("context.after_compact",{...m,removedCount:L.droppedCount}).catch(()=>{}))}he=Nw(he);let Ut=ha({tools:$,toolChoice:n.toolChoice??"auto"}),g=Ar({maxRounds:x,replayMessages:he,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),v=Ut.extraSystemPrompt?[{role:"system",content:Ut.extraSystemPrompt},...g.state.replayMessages]:g.state.replayMessages;B=g.state,g.recoveryActions.length>0&&o.debug(`tool loop recovery: ${g.recoveryActions.map(A=>A.detail??A.kind).join("; ")}`),o.debug(`turn ${ne}, messages: ${v.length}`),u?.invoke("turn.before_inference",{...m,model:S.currentModel}).catch(()=>{});let _=!1,C=[],R=new Map,U="stop",D,M=null,V=!1,ae=[],ee=[];try{for await(let A of e.stream({model:S.currentModel,messages:v,tools:Ut.tools,toolChoice:Ut.normalizedToolChoice??"auto",temperature:d,maxTokens:(Ue??Q.currentMaxOutputTokens)||void 0,streamRequired:n.streamRequired,previousResponseId:S.lastResponseId,reasoning:n.reasoning,promptCacheKey:n.promptCacheKey,promptCacheRetention:n.promptCacheRetention,serviceTier:n.serviceTier,openaiBuiltinTools:n.openaiBuiltinTools,maxToolCalls:n.maxToolCalls,parallelToolCalls:n.parallelToolCalls,textVerbosity:n.textVerbosity},c,p))switch(A.type){case"delta":C.push(A.text),_||(yield{type:"delta",turnId:r,text:A.text});break;case"tool_call_delta":_=!0,La(R,A);break;case"reasoning_delta":ae.push(A.text);break;case"reasoning_block_complete":A.signature&&ee.push({thinking:ae.join(""),signature:A.signature}),ae.length=0;break;case"usage":D={inputTokens:A.promptTokens,outputTokens:A.completionTokens,reasoningTokens:A.reasoningTokens,cacheRead:A.cacheReadTokens,cacheWrite:A.cacheCreationTokens};break;case"response_id":S.lastResponseId=A.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:A.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${A.toolType}: ${A.event}`};break;case"done":U=A.finishReason;break}if(_||u?.invoke("turn.after_inference",{...m,model:S.currentModel}).catch(()=>{}),n.postSamplingHooks&&n.postSamplingHooks.length>0){let A=S.currentModel;for(let E of n.postSamplingHooks)try{E({messages:[...he],model:A,sessionId:s})}catch{}}}catch(A){if(A instanceof So&&n.fallbackModel){o.info(`model fallback triggered: ${A.originalModel} \u2192 ${A.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${A.originalModel} \u2192 ${A.fallbackModel}`},S={...S,currentModel:A.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let E=A instanceof Error?A.message:String(A),L=typeof A?.status=="number"?A.status:void 0;if(!L&&E&&(E.includes("ECONNRESET")||E.includes("EPIPE"))){let re=(S.consecutiveApiRetries??0)+1;if(re>Ln){o.info(`stale connection retry limit reached (${Ln}), aborting`),yield{type:"error",turnId:r,error:E,code:"RETRIES_EXHAUSTED",usage:S.totalUsage};return}o.info(`stale connection (${E.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:E.slice(0,80)},S={...S,consecutiveApiRetries:re,transition:void 0};continue}let G=Lw({status:L,message:E});if(G!==null){o.info(`max_tokens overflow: adjusting to ${G}`),Q.currentMaxOutputTokens=G,S={...S,maxOutputTokensOverride:G,transition:void 0};continue}if(xa(L)){S.consecutive529Errors++;let re=2,_e=n.fallbackModel&&S.currentModel!==n.fallbackModel;if(S.consecutive529Errors>re&&!_e&&!Ir()){o.info(`transient ${L} \xD7 ${S.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:r,error:`API unavailable after ${S.consecutive529Errors} consecutive ${L} errors`,code:"API_ERROR",usage:S.totalUsage};return}if(S.consecutive529Errors>=Wi&&n.fallbackModel&&S.currentModel!==n.fallbackModel){o.info(`529 \xD7 ${S.consecutive529Errors}: triggering fallback to ${n.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${S.consecutive529Errors}`},S={...S,currentModel:n.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Ir()){let Z=Pr(S.consecutive529Errors);o.info(`persistent retry: waiting ${Z}ms (attempt ${S.consecutive529Errors})`);let ye=Z;for(;ye>0;){if(p?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED",usage:S.totalUsage};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(ye/1e3)}s (${L})`};let it=Math.min(ye,Bi);await new Promise(fi=>setTimeout(fi,it)),ye-=it}S={...S,transition:void 0};continue}if(wa(f)){let ye=Dw({status:L,message:E})??Pr(S.consecutive529Errors);o.info(`transient ${L}: retry in ${ye}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${L} retry in ${ye}ms`},await new Promise(it=>setTimeout(it,ye)),S={...S,transition:void 0};continue}o.info(`background source ${f}: not retrying ${L}`)}M={status:L,message:E}}if(M&&u?.invoke("turn.after_inference",{...m,model:S.currentModel,response:{error:M.message}}).catch(()=>{}),M)if(wp(M))V=!0,o.info(`withheld prompt_too_long error (status=${M.status})`);else if(xp(M))V=!0,o.info(`withheld media_size error (status=${M.status})`);else{let A=Ea({status:M.status??500,message:M.message},Q,I);if(A.action==="reactive_compact"&&Nn(T)&&(T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${M.status??500}: ${M.message}`}),A.action==="retry"){let L=(S.consecutiveApiRetries??0)+1;if(L>Ln){o.info(`API retry limit reached (${Ln}), aborting`);let G=On(M.status,M.message);yield{type:"error",turnId:r,error:M.message,code:G,usage:S.totalUsage};return}yield{type:"recovery",turnId:r,action:"retry",detail:A.reason},S={...S,consecutiveApiRetries:L,transition:void 0};continue}let E=On(M.status,M.message);u?.invoke("stop.failure",{sessionId:s,reason:E,error:M.message}).catch(()=>{}),yield{type:"error",turnId:r,error:M.message,code:E,usage:S.totalUsage};return}D&&(S.totalUsage.inputTokens+=D.inputTokens,S.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(S.totalUsage.reasoningTokens=(S.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(S.totalUsage.cacheRead=(S.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(S.totalUsage.cacheWrite=(S.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(Q.promptTokens=D.inputTokens);let oe=C.join("");oe&&(S.finalText=oe);let me=[...R.values()].map(A=>({id:A.id||`tc_${r}_${ne}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:A.name,arguments:A.arguments}}));if(me.length===0&&!_){if(V&&M&&wp(M)){if(S.transition?.reason!=="collapse_drain_retry"){let L=Pi(he,F);if(L.committed>0){o.info(`collapse drain: committed ${L.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${L.committed} stages committed`},S={...S,messages:L.messages,transition:{reason:"collapse_drain_retry",committed:L.committed}};continue}}if(Nn(T)){T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},S={...S,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),u?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:M.message}).catch(()=>{}),yield{type:"error",turnId:r,error:M.message,code:"PROMPT_TOO_LONG",usage:S.totalUsage};return}if(V&&M&&xp(M)){if(Nn(T)){T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},S={...S,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),u?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:M.message}).catch(()=>{}),yield{type:"error",turnId:r,error:M.message,code:"IMAGE_ERROR",usage:S.totalUsage};return}if(Ow(U)){Q.consecutiveTruncations+=1;let L=n.modelMaxOutputTokens??Li,G=Ma(Q,I,L);if(G.shouldEscalate&&Ue===void 0){Q.currentMaxOutputTokens=G.newMax,o.info(`max_output_tokens escalate: ${G.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${G.newMax} tokens`},S={...S,maxOutputTokensOverride:$i,transition:{reason:"max_output_tokens_escalate"}};continue}if(ve<Ni){let re={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 #${ve+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${ve+1}`},S={...S,messages:[...he,re],maxOutputTokensRecoveryCount:ve+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:ve+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else Q.consecutiveTruncations=0;if(B=_r(B,{replayMessages:j,lastStopReason:"completed"}),u){let L=await u.invoke("stop",{sessionId:s,reason:"completed"});if(L.action==="prevent"){o.info(`stop hook prevented continuation: ${L.reason??"no reason"}`),yield{type:"end",turnId:r,content:S.finalText,usage:S.totalUsage,model:S.currentModel};return}if(L.action==="abort"){let G=L.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${G}`);let re={role:"user",content:G},_e={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,_e,re],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(n.tokenBudget&&n.tokenBudget>0&&S.budgetContinuationCount<5){let L=S.totalUsage.inputTokens+S.totalUsage.outputTokens+(S.totalUsage.reasoningTokens??0),G=L/n.tokenBudget*100,re=L-S.lastBudgetGlobalTokens,_e=S.budgetContinuationCount>=Ui&&re<wr&&S.lastBudgetDeltaTokens<wr;if(_e&&o.info(`token budget early stop: diminishing returns at ${Math.round(G)}% (delta=${re})`),!_e&&G<90){let Z=S.budgetContinuationCount+1,ye={role:"user",content:bp(G,L,n.tokenBudget)};o.info(`token budget continuation #${Z}: ${Math.round(G)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(G)}% used (#${Z})`};let it={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,it,ye],budgetContinuationCount:Z,lastBudgetDeltaTokens:re,lastBudgetGlobalTokens:L,transition:{reason:"token_budget_continuation"}};continue}}if(!S.stopHookActive){let L=i.find(Z=>Z.role==="user"),G=typeof L?.content=="string"?L.content:"",re=/创建文件|生成文件|写入|写一个|建一个|新建|重写|改写|create\s+(a\s+)?file|write\s+(a\s+)?file|make\s+(a\s+)?file|修改|改成|把.*改|文件名叫/i.test(G),_e=P.has("write")||P.has("edit");if(re&&!_e){if(o.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),O>0){let it=[...j].reverse().find(fi=>fi.role==="tool");it&&typeof it.content=="string"&&(it.content+=`
42
+ ...[truncated ${n.length-o} chars]`}function ew(n){let e=[],t=[];for(let o of n)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?qu(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 tw(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 nw(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 Qu(n,e,t,o=Fi){let r=ew(n);if(r.length===0)return{messages:n,newlyReplacedCount:0};let s=new Map,i=[];for(let d of r){let{mustReapply:u,frozen:p,fresh:m}=tw(d,e);for(let k of u)s.set(k.toolCallId,k.replacement);if(m.length===0){for(let k of d)e.seenIds.add(k.toolCallId);continue}let h=p.reduce((k,x)=>k+x.size,0),f=m.reduce((k,x)=>k+x.size,0),y=h+f>o?nw(m,h,o):[],b=new Set(y.map(k=>k.toolCallId));for(let k of d)b.has(k.toolCallId)||e.seenIds.add(k.toolCallId);y.length>0&&i.push(...y)}if(s.size===0&&i.length===0)return{messages:n,newlyReplacedCount:0};let a=await Promise.all(i.map(async d=>{let u=await Yu(d.content,d.toolCallId,t);return{candidate:d,result:u}})),l=0;for(let{candidate:d,result:u}of a){if(e.seenIds.add(d.toolCallId),!u)continue;let p=Xu(u);s.set(d.toolCallId,p),e.replacements.set(d.toolCallId,p),l++}return s.size===0?{messages:n,newlyReplacedCount:0}:{messages:n.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let u=s.get(d.tool_call_id);return u===void 0?d:{...d,content:u}}),newlyReplacedCount:l}}var YT,Vu,XT,tl=N(()=>{"use strict";je();YT="tool-results",Vu="<persisted-output>",XT="</persisted-output>"});function sw(n){try{return JSON.parse(n)}catch{return}}var ow,rw,Kr,Zu=N(()=>{"use strict";$n();tl();ow=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),rw=new Set(["bash","execute_command","Bash","shell"]),Kr=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??ow,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:nn(e.id,{ok:!1,error:r})}}async executeTool(e){e.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){e.results.push(this.createSyntheticError(e,r)),e.status="completed";return}let{toolInvoker:s,hooks:i,sessionId:a,turnId:l,log:c}=this.config,d=e.toolCall.function.name,u=!1,p=e.toolCall.function.arguments;if(i)try{let k=await i.invoke("tool.before_invoke",{sessionId:a,turnId:l,callId:e.id,toolName:d,arguments:sw(p)});if(k.action==="abort"){let x=k.reason??"blocked by policy";c.info(`tool ${d} blocked: ${x}`),e.results.push({callId:e.id,toolName:d,ok:!1,error:x,blocked:!0,blockReason:x,message:nn(e.id,{ok:!1,error:x})}),e.status="completed";return}k.action==="continue"&&k.context?.arguments&&(p=JSON.stringify(k.context.arguments))}catch{}let m=await s.invoke(l,d,p,this.siblingAbortController.signal),h=this.getAbortReason();if(h&&!u){e.results.push(this.createSyntheticError(e,h)),e.status="completed";return}let f=!m.error,y=m.result;f&&y&&y.length>5e4&&(y=await Ju(y,e.id,a));let b=nn(e.id,{ok:f,payload:y,error:m.error,toolReferences:m.toolReferences,imageUrls:m.imageUrls});f||(u=!0,rw.has(d)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort("sibling_error"))),i?.invoke(f?"tool.after_invoke":"tool.invoke_failed",{sessionId:a,turnId:l,callId:e.id,toolName:d,ok:f,...m.error?{error:m.error}:{}}).catch(()=>{}),e.results.push({callId:e.id,toolName:d,ok:f,error:m.error,message:b}),e.status="completed"})();e.promise=o,o.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let e of this.tools)if(e.status!=="yielded"){if(e.status==="completed"&&e.results.length>0){e.status="yielded";for(let 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{homedir as iw}from"node:os";import{join as Ae}from"node:path";import{existsSync as aw}from"node:fs";function H(){return process.env.QLOGICAGENT_HOME||Ae(iw(),He)}function ep(){return Ae(H(),"plugins")}function Ht(){return Ae(H(),"skills")}function pt(){return Ae(H(),"settings.json")}function tp(){return Ae(H(),"plugin-cache")}function np(){return Ae(H(),"mcp.json")}function op(){return Ae(H(),"marketplace.json")}function rp(){return Ae(H(),"workflows")}function sp(){return Ae(H(),"rules")}function Oe(n){if(!n)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return Ae(n,He)}function ip(n){return Ae(Oe(n),"workflows")}function It(n){return Ae(Oe(n),"skills")}function Oo(n){return Ae(Oe(n),"INSTRUCTIONS.md")}function Gn(n){return Ae(Oe(n),"rules")}function Vt(n){return Ae(Oe(n),"sessions")}function ap(n,e){let t=Ae(Oe(n),"checkpoints");return e?Ae(t,e):t}function lp(n){return Ae(n,He,"hooks")}function cp(n,e){return n.filter(t=>t!==e&&aw(Ae(t,He,"skills")))}var He,le=N(()=>{"use strict";He=".qlogicagent"});var zr,dp=N(()=>{"use strict";zr=class{pools=new Map;runtimeStates=new Map;constructor(e){if(e)for(let t of e){this.pools.set(t.providerId,t);for(let o of t.keys)this.runtimeStates.set(o.id,this.createInitialState())}}acquireKey(e){let t=this.pools.get(e);if(!t||t.keys.length===0)return null;let o=Date.now(),r=this.getHealthyCandidates(t,o);if(r.length===0)return null;let s=this.selectByStrategy(r,t.strategy,o);if(!s)return null;let i=this.runtimeStates.get(s.id);return i.inFlight++,i.totalRequests++,i.lastUsedAt=o,i.requestTimestamps.push(o),{keyId:s.id,apiKey:s.key,providerId:e,release:a=>this.releaseKey(s.id,a)}}releaseKey(e,t){let o=this.runtimeStates.get(e);if(o)if(o.inFlight=Math.max(0,o.inFlight-1),t.success)o.consecutiveErrors=0,o.healthStatus="healthy",t.tokens&&(o.totalTokens+=t.tokens,o.tokenCounts.push(t.tokens));else if(o.consecutiveErrors++,o.lastErrorAt=Date.now(),t.errorCode===429){let r=t.retryAfter?t.retryAfter*1e3:3e4;o.cooldownUntil=Date.now()+r,o.healthStatus="cooldown"}else o.consecutiveErrors>=5?(o.cooldownUntil=Date.now()+6e4,o.healthStatus="cooldown"):o.consecutiveErrors>=3&&(o.healthStatus="degraded")}addProvider(e,t){this.pools.has(e)||this.pools.set(e,{providerId:e,baseUrl:t?.baseUrl,strategy:t?.strategy??"weighted-round-robin",keys:[],rateLimit:t?.rateLimit})}removeProvider(e){let t=this.pools.get(e);if(t){for(let o of t.keys)this.runtimeStates.delete(o.id);this.pools.delete(e)}}addKey(e,t,o){let r=this.pools.get(e);r||(r={providerId:e,strategy:"weighted-round-robin",keys:[]},this.pools.set(e,r));let s=o?.id??crypto.randomUUID(),i={id:s,key:t,label:o?.label,weight:o?.weight??1,enabled:o?.enabled??!0};return r.keys.push(i),this.runtimeStates.set(s,this.createInitialState()),s}removeKey(e){for(let t of this.pools.values()){let o=t.keys.findIndex(r=>r.id===e);if(o!==-1){t.keys.splice(o,1),this.runtimeStates.delete(e);return}}}updateKey(e,t){for(let o of this.pools.values()){let r=o.keys.find(s=>s.id===e);if(r){if(t.label!==void 0&&(r.label=t.label),t.weight!==void 0&&(r.weight=t.weight),t.enabled!==void 0){r.enabled=t.enabled;let s=this.runtimeStates.get(e);s&&(s.healthStatus=t.enabled?"healthy":"disabled")}return}}}setKeyHealth(e,t){let o=this.runtimeStates.get(e);o&&(o.healthStatus=t)}setStrategy(e,t){let o=this.pools.get(e);o&&(o.strategy=t)}setRateLimit(e,t){let o=this.pools.get(e);o&&(o.rateLimit=t)}getPoolStatus(e){let t=this.pools.get(e);return t?this.buildPoolStatus(t):null}getAllStatus(){return[...this.pools.values()].map(e=>this.buildPoolStatus(e))}getProviderIds(){return[...this.pools.keys()]}hasProvider(e){return this.pools.has(e)}hasAvailableKey(e){let t=this.pools.get(e);return t?this.getHealthyCandidates(t,Date.now()).length>0:!1}exportConfig(){return[...this.pools.values()]}reloadConfig(e){let t=new Set;for(let o of e){this.pools.set(o.providerId,o);for(let r of o.keys)t.add(r.id),this.runtimeStates.has(r.id)||this.runtimeStates.set(r.id,this.createInitialState())}for(let o of[...this.pools.keys()])e.some(r=>r.providerId===o)||this.pools.delete(o);for(let o of[...this.runtimeStates.keys()])t.has(o)||this.runtimeStates.delete(o)}createInitialState(){return{inFlight:0,totalRequests:0,totalTokens:0,lastUsedAt:0,lastErrorAt:0,consecutiveErrors:0,cooldownUntil:0,healthStatus:"healthy",requestTimestamps:[],tokenCounts:[]}}getHealthyCandidates(e,t){let o=[];for(let r of e.keys){if(!r.enabled)continue;let s=this.runtimeStates.get(r.id);if(s){if(s.healthStatus==="cooldown")if(t>=s.cooldownUntil)s.healthStatus="healthy",s.consecutiveErrors=0;else continue;s.healthStatus!=="disabled"&&(e.rateLimit?.rpm&&(this.pruneWindow(s.requestTimestamps,t),s.requestTimestamps.length>=e.rateLimit.rpm*.9)||e.rateLimit?.tpm&&(this.pruneWindow(s.tokenCounts,t),s.tokenCounts.reduce((a,l)=>a+l,0)>=e.rateLimit.tpm*.9)||o.push(r))}}return o}selectByStrategy(e,t,o){if(e.length===0)return null;if(e.length===1)return e[0];switch(t){case"weighted-round-robin":return this.weightedRandom(e);case"least-busy":return this.leastBusy(e);case"random":return e[Math.floor(Math.random()*e.length)];default:return this.weightedRandom(e)}}weightedRandom(e){let t=e.reduce((r,s)=>r+s.weight,0),o=Math.random()*t;for(let r of e)if(o-=r.weight,o<=0)return r;return e[e.length-1]}leastBusy(e){let t=1/0,o=e[0];for(let r of e){let i=this.runtimeStates.get(r.id)?.inFlight??0;(i<t||i===t&&r.weight>o.weight)&&(t=i,o=r)}return o}pruneWindow(e,t){let o=t-6e4;for(;e.length>0&&e[0]<o;)e.shift()}buildPoolStatus(e){return{providerId:e.providerId,baseUrl:e.baseUrl,strategy:e.strategy,rateLimit:e.rateLimit,keys:e.keys.map(t=>{let o=this.runtimeStates.get(t.id)??this.createInitialState();return{...t,inFlight:o.inFlight,totalRequests:o.totalRequests,totalTokens:o.totalTokens,lastUsedAt:o.lastUsedAt,lastErrorAt:o.lastErrorAt,consecutiveErrors:o.consecutiveErrors,cooldownUntil:o.cooldownUntil,healthStatus:t.enabled?o.healthStatus:"disabled"}})}}}});var up={};fn(up,{ALL_PURPOSES:()=>Lo,ModelRegistry:()=>qr,deriveModelPurposes:()=>cw,getModelRegistry:()=>X,resetModelRegistry:()=>lw});import*as et from"node:fs";function X(){return Do||(Do=new qr,Do.load()),Do}function lw(){Do=null}function cw(n){let e=[];switch((!n.mediaType||n.mediaType==="image_understanding"||n.mediaType==="video_understanding")&&e.push("textGeneration"),(n.vision||n.mediaType==="image_understanding")&&e.push("imageUnderstanding"),n.mediaType==="video_understanding"&&e.push("videoUnderstanding"),n.mediaType){case"image":e.push("imageGeneration");break;case"video":e.push("videoGeneration");break;case"tts":e.push("tts");break;case"stt":e.push("stt");break;case"music":case"music_realtime":e.push("musicGeneration");break;case"voice_clone":e.push("voiceClone");break;case"embedding":e.push("embedding");break;case"3d":e.push("threeDGeneration");break;case"realtime_audio":e.push("realtimeAudio");break}return e.includes("textGeneration")&&e.push("smallModel"),[...new Set(e.length>0?e:["textGeneration"])]}function dw(n){switch(n){case"openai-chat":case"openai-responses":case"anthropic-messages":case"volcengine-responses":return n;default:return}}function uw(n,e){switch(n){case"imageUnderstanding":case"videoUnderstanding":case"imageGeneration":case"videoGeneration":case"threeDGeneration":case"stt":case"tts":case"voiceClone":case"musicGeneration":case"realtimeAudio":case"realtimeVideo":case"embedding":return;default:return dw(e)}}function pw(n){switch(n){case"imageUnderstanding":case"videoUnderstanding":return["vision"];case"imageGeneration":case"videoGeneration":case"threeDGeneration":case"stt":case"tts":case"voiceClone":case"musicGeneration":case"realtimeAudio":case"realtimeVideo":case"embedding":return["media"];default:return[]}}var Lo,qr,Do,mt=N(()=>{"use strict";an();le();dp();Lo=["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"],qr=class{keyPool;coreProviderRegistry=new sn;providerVariantResolver=new _o(this.coreProviderRegistry);models=new Map;modelEnabledOverrides=new Map;bindings={};settingsPath;changeListeners=[];constructor(e){this.settingsPath=pt(),this.keyPool=new zr(e?.providers),e?.models&&this.loadModelState(e.models),e?.bindings&&(this.bindings={...e.bindings})}getActiveModel(e){let t=this.bindings[e];if(!t)return null;let o=this.models.get(t);if(!o||!o.enabled)return null;let r=this.resolveTechnicalVariant(o,e),s=r?.provider??o.provider,i=r?.nativeModelId??o.nativeModelId??o.model,a=this.acquireKeyForProviderVariant(s);if(!a)return null;let{keyHandle:l,keyProviderId:c}=a;return{provider:s,model:i,apiKey:l.apiKey,baseUrl:o.provider===s?o.baseUrl??this.getProviderBaseUrl(s)??this.getProviderBaseUrl(c):this.getProviderBaseUrl(s),keyHandle:l}}peekActiveModel(e){let t=this.bindings[e];return t?this.models.get(t)??null:null}isAvailable(e){let t=this.peekActiveModel(e);return!!t?.enabled&&this.hasAvailableKeyForProviderVariant(t.provider)}resolveModelForPurpose(e){let t=this.peekActiveModel(e);return t?t.model:null}addProvider(e,t){this.keyPool.addProvider(e,t),this.emitChange()}removeProvider(e){this.keyPool.removeProvider(e);for(let[t,o]of this.models)o.provider===e&&this.removeModel(t);this.emitChange()}addKey(e,t,o){let r=this.keyPool.addKey(e,t,o);return this.emitChange(),r}removeKey(e){this.keyPool.removeKey(e),this.emitChange()}updateKey(e,t){this.keyPool.updateKey(e,t),this.emitChange()}setKeyHealth(e,t){this.keyPool.setKeyHealth(e,t),this.emitChange()}setStrategy(e,t){this.keyPool.setStrategy(e,t),this.emitChange()}addModel(e){let t=e.id??`${e.provider}:${e.model}`;return this.models.set(t,{...e,id:t,enabled:this.modelEnabledOverrides.get(t)??e.enabled}),this.emitChange(),t}replaceCatalogModels(e){let t=new Map;for(let o of e)t.set(o.id,{...o,enabled:this.modelEnabledOverrides.get(o.id)??o.enabled});for(let o of this.modelEnabledOverrides.keys())t.has(o)||this.modelEnabledOverrides.delete(o);this.models=t;for(let[o,r]of Object.entries(this.bindings))r&&!this.models.has(r)&&delete this.bindings[o];this.emitChange()}migrateModelIds(e){for(let[t,o]of e){let r=this.modelEnabledOverrides.get(t);r!==void 0&&!this.modelEnabledOverrides.has(o)&&this.modelEnabledOverrides.set(o,r),this.modelEnabledOverrides.delete(t);for(let[s,i]of Object.entries(this.bindings))i===t&&(this.bindings[s]=o)}this.emitChange()}removeModel(e){this.models.delete(e),this.modelEnabledOverrides.delete(e);for(let[t,o]of Object.entries(this.bindings))o===e&&delete this.bindings[t];this.emitChange()}enableModel(e){let t=this.models.get(e);t&&(t.enabled=!0),this.modelEnabledOverrides.set(e,!0),this.emitChange()}disableModel(e){let t=this.models.get(e);t&&(t.enabled=!1),this.modelEnabledOverrides.set(e,!1),this.emitChange()}listModels(e){let t=[...this.models.values()];return e?.purpose&&(t=t.filter(o=>o.purposes.includes(e.purpose))),e?.provider&&(t=t.filter(o=>o.provider===e.provider)),e?.enabledOnly&&(t=t.filter(o=>o.enabled)),t}getModel(e){return this.models.get(e)??null}setBinding(e,t){let o=this.models.get(t);if(!o)throw new Error(`Model "${t}" not found in pool.`);if(!o.purposes.includes(e))throw new Error(`Model "${t}" does not support purpose "${e}".`);this.bindings[e]=t,this.emitChange()}removeBinding(e){delete this.bindings[e],this.emitChange()}getBinding(e){let t=this.bindings[e];return t?this.models.get(t)??null:null}getAllBindings(){let e={};for(let t of Lo){let o=this.bindings[t];e[t]=o?this.models.get(o)??null:null}return e}getProviderStatus(e){return this.keyPool.getPoolStatus(e)}getAllProviderStatus(){return this.keyPool.getAllStatus()}save(){let e={};try{et.existsSync(this.settingsPath)&&(e=JSON.parse(et.readFileSync(this.settingsPath,"utf-8")))}catch{e={}}delete e.provider,delete e.apiKey,delete e.model,delete e.baseUrl;let t={...e,providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}},o=this.settingsPath.replace(/[/\\][^/\\]+$/,"");et.existsSync(o)||et.mkdirSync(o,{recursive:!0}),et.writeFileSync(this.settingsPath,JSON.stringify(t,null,2),"utf-8")}load(){try{if(!et.existsSync(this.settingsPath))return!1;let e=et.readFileSync(this.settingsPath,"utf-8"),t=JSON.parse(e);return t.providers&&this.keyPool.reloadConfig(t.providers),this.models.clear(),this.modelEnabledOverrides.clear(),t.models&&this.loadModelState(t.models),this.bindings=t.bindings??{},this.emitChange(),!0}catch{return!1}}exportConfig(){return{providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}}}getTunable(e){try{if(!et.existsSync(this.settingsPath))return;let t=et.readFileSync(this.settingsPath,"utf-8");return JSON.parse(t).tunables?.[e]}catch{return}}getModelInfo(e,t){let o=this.listModels({provider:e}).find(r=>r.model===t);if(o)return{id:o.model,name:o.displayName,contextWindow:o.contextWindow,maxOutput:o.maxOutput,streamRequired:o.streamRequired}}getProviderDefaultModel(e){return this.listModels({provider:e,enabledOnly:!0})[0]?.model??this.listModels({provider:e})[0]?.model}hasConfiguredKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(t=>!!this.keyPool.getPoolStatus(t)?.keys.some(r=>r.enabled))}hasAvailableKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(t=>this.keyPool.hasAvailableKey(t))}listProviderDefs(){return this.keyPool.getAllStatus().map(e=>({id:e.providerId,name:e.providerId,transport:"",baseUrl:e.baseUrl??"",defaultModel:this.getProviderDefaultModel(e.providerId),models:this.listModels({provider:e.providerId}).map(t=>({id:t.model,name:t.displayName,contextWindow:t.contextWindow,maxOutput:t.maxOutput,streamRequired:t.streamRequired}))}))}resolveProviderApiKey(e){return this.getKeyForProvider(e)??void 0}onChange(e){return this.changeListeners.push(e),()=>{let t=this.changeListeners.indexOf(e);t>=0&&this.changeListeners.splice(t,1)}}getKeyForProvider(e){let o=this.acquireKeyForProviderVariant(e)?.keyHandle;if(!o)return null;let r=o.apiKey;return o.release({success:!0}),r}snapshotProviderKeys(){let e={};for(let t of this.keyPool.getAllStatus()){let o=this.getKeyForProvider(t.providerId);o&&(e[t.providerId]=o)}return e}getProviderBaseUrl(e){return this.coreProviderRegistry.getProvider(e)?.baseUrl??this.keyPool.getPoolStatus(e)?.baseUrl}acquireKeyForProviderVariant(e){for(let t of this.providerVariantKeyCandidates(e)){let o=this.keyPool.acquireKey(t);if(o)return{keyHandle:o,keyProviderId:t}}return null}resolveTechnicalVariant(e,t){let o=this.providerVariantKeyCandidates(e.provider).filter(s=>this.hasConfiguredKeyForProviderVariant(s));if(o.length===0)return;let r=this.providerVariantResolver.resolveBest({publicModel:e.model,requestedProtocol:uw(t,e.transport),capabilities:pw(t),purpose:t,userPreference:{providerIds:o}});if(r)return{provider:r.provider,nativeModelId:r.nativeModelId}}providerVariantKeyCandidates(e){let t=[e],o=this.coreProviderRegistry.getProvider(e),r=o?.group??o?.id??e;for(let s of this.coreProviderRegistry.listProviders())(s.group??s.id)===r&&t.push(s.id);return r!==e&&t.push(r),[...new Set(t)]}loadModelState(e){for(let t of e)typeof t.id!="string"||!t.id||typeof t.enabled=="boolean"&&this.modelEnabledOverrides.set(t.id,t.enabled)}exportModelState(){let e=new Map;for(let[t,o]of this.modelEnabledOverrides)e.set(t,o);for(let t of this.models.values())e.set(t.id,t.enabled);return[...e.entries()].map(([t,o])=>({id:t,enabled:o}))}emitChange(){for(let e of this.changeListeners)try{e()}catch{}}},Do=null});import{readFile as mw}from"node:fs/promises";function Sn(n){let e=typeof n.content=="string"?n.content:n.content!=null?JSON.stringify(n.content):"";return Math.ceil(e.length/4)}function Tn(n){let e=0;for(let t of n)e+=Sn(t);return e}function mp(n){if(!n)return 128e3;if(n in nl)return nl[n];let e=n.toLowerCase();for(let[t,o]of Object.entries(nl))if(e.startsWith(t.toLowerCase()))return o;return 128e3}function gw(){return X().resolveModelForPurpose("textGeneration")??fw}function gp(){return rl}function hw(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"),ol(t);try{let i="",a=e?.model??gw();for await(let l of r.stream({model:a,messages:[{role:"system",content:"You are a precise conversation summarizer."},{role:"user",content:o}],maxTokens:2e3,temperature:.3},s,AbortSignal.timeout(3e4)))l.type==="delta"&&(i+=l.text);return i||(n.warn("[context-compression] empty summary response"),ol(t))}catch(i){return n.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),ol(t)}}}function ol(n){let e=[],t=n.filter(s=>s.role==="user"),o=t.slice(0,20).map(s=>{let i=typeof s.content=="string"?s.content:JSON.stringify(s.content??"");return`- [user]: ${i.slice(0,300)}${i.length>300?"...":""}`});e.push(`## User Requests (${t.length} messages)`),e.push(...o);let r=n.filter(s=>s.role==="assistant");if(r.length>0){let s=r.slice(0,10).map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??"");return`- [assistant]: ${a.slice(0,150)}${a.length>150?"...":""}`});e.push("",`## Assistant Responses (${r.length} total)`),e.push(...s)}return e.join(`
43
+ `)}function yw(){return vi(new bn(sl),new on(20,Sn),new Dn(Sn))}function pp(n,e){let t=Si(new bn(sl),new on(20,Sn),new fo({protectedHeadExchanges:1,protectedTailMessages:8,summarize:n,estimateTokens:Sn}),new Dn(Sn));return new go({inner:t,estimateTokens:Sn,onCacheInvalidated:e?.onCacheInvalidated})}function hp(n,e){let t=e?.budget??Sr({modelContextWindow:mp(e?.model)}),r=(e?.pipeline??yw()).compress(n,t);if(r.droppedCount>0){let s=Tn(n),i=Tn(r.messages);fp.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:ko(s,t)})}return r.droppedCount>0&&il?.(r.droppedCount,Tn(r.messages)),r}async function bw(n,e,t){let o=t??Sr({modelContextWindow:mp(e.model)}),r=Tn(n),s=ko(r,o),i;switch(s){case"none":i={messages:n,droppedCount:0,strategy:"none"};break;case"trim-only":i=new bn(sl).compress(n,o);break;case"sliding-window":{i=await pp(e.summarize).compressAsync(n,o);break}case"llm-summarize":{let a=e.pipeline??pp(e.summarize);i=bo(a)?await a.compressAsync(n,o):a.compress(n,o);break}}return i.droppedCount>0&&(i={...i,messages:await wi(i.messages,n,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await mw(a,"utf-8")}catch{return null}}})}),kw(n,i,o),i}function kw(n,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let o=e.metrics?.tokensBefore||Tn(n),r=e.metrics?.tokensAfter||Tn(e.messages);fp.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:ko(o,t)})}if(e.droppedCount>0){let o=e.metrics?.tokensAfter||Tn(e.messages);il?.(e.droppedCount,o)}}function vw(n,e){let t=hw(n,e),o={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return bw(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};rl.register(o),rl.activate(o.id),n.info(`[context-compression] registered context engine: ${o.id}`)}function yp(n,e,t){vw(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"}}}),il=(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 nl,sl,fw,fp,rl,il,al=N(()=>{"use strict";$n();mt();nl={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-3.1-pro-preview":1e6,"gemini-3-flash-preview":1e6,"gemini-3.1-flash-lite":1e6};sl=8e3,fw="deepseek-v4-flash";fp=new ho(200),rl=new yo;il=null});function bp(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 taskyou are near the token limit.":"Continue workingdo not summarize prematurely.")}var kp=N(()=>{"use strict"});var vp={};fn(vp,{resolveToolEligibility:()=>Rw});function Tw(n,e){if(Sw.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 ww(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||Tw(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function xw(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 Rw(n,e={}){let t=new Map,o=[],r=[],s=[];for(let i of n){let a=i.function.name,{level:l,reasons:c}=ww(i,e),d=xw(l),u={toolName:a,status:d,permissionLevel:l,approvalRequired:l===4,reasonCodes:c};t.set(a,u),l===5?r.push(u):(o.push(i),l===4&&s.push(u))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:s,eligibilityByName:t}}var Sw,Sp=N(()=>{"use strict";Sw=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Iw(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 Cw(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 Ow(n){if(!Mw.has(n.toolName))return!1;let e=typeof n.message?.content=="string"?n.message.content.trim():"";return e.length>0&&e.length<200&&Ew.test(e)}function Tp(n,e){for(let t=n.length-1;t>=0;t--){let o=n[t];if(!o||o.role!=="tool")continue;let r=typeof o.content=="string"?o.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Dw(n){return typeof n=="number"&&Number.isFinite(n)&&n>=1?Math.min(Math.round(n),100):Ii}function wp(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 Lw(n){return n==="length"||n==="max_tokens"}function xp(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 Nw(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 $w(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 Uw(n){return n.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Rp(n,e,t,o){let{turnId:r,sessionId:s,messages:i,tools:a,model:l,apiKey:c,temperature:d=0,hooks:u,signal:p}=n,m={sessionId:s,turnId:r},h=n.maxTurns??0,f=n.querySource,{resolveToolEligibility:y}=await Promise.resolve().then(()=>(Sp(),vp)),b=y(a,n.toolEligibilityContext),k=b.eligibleTools;for(let j of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:j.toolName,reason:"blocked-by-policy"};if(!k.length){yield*jw(r,l,i,c,d,p,e,o);return}let x=Dw(n.maxRounds),I={contextWindowTokens:n.contextWindowTokens??Mi,responseBufferTokens:Oi,maxOutputTokens:n.maxOutputTokens??Di,abortSignal:p,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},P=new Set,O=0,$=k,W,S={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ia(I),reactiveCompactState:Da(),toolLoopState:Ar({maxRounds:x,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:_i(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:Ku(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map},ce=Math.max(h*5,200),de=0;for(;;){if(de++,de>ce){o.info(`hard iteration cap reached (${ce}), forcing completion`);let A=S.finalText||No(S.messages,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}let{messages:j,maxOutputTokensRecoveryCount:ve,hasAttemptedReactiveCompact:ie,maxOutputTokensOverride:Ue,turnCount:ne,guardState:Q,reactiveCompactState:T,collapseStore:F}=S,{toolLoopState:B}=S;if(W){try{let A=await W;A&&(yield{type:"tool_use_summary",turnId:r,summary:A})}catch{}W=void 0}if(n.refreshTools&&ne>1){let A=n.refreshTools();A!==$&&($=A,o.debug(`tools refreshed: ${A.length} tools`))}if(Oa(Q,I)){o.info(`turn aborted by guard at turn ${ne}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:S.totalUsage};return}let Re=Ca(Q,I);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&Nn(T)&&(T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Re.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${Re.reason}), ending tool loop`);break}Re.level==="warning"&&o.info(`token budget warning: ${Re.usagePercent}% used, ${Re.remainingTokens} remaining`);let he;{let A=await Qu(j,S.contentReplacementState,s);he=A.messages,A.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${A.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${A.newlyReplacedCount} persisted`})}{let A=xi(he,S.snipRemovedIds);he=A.messages,A.removedCount>0&&(o.info(`snip: removed ${A.removedCount} messages, freed ~${A.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${A.removedCount} messages`})}{let E=new on().compress(he,0);E.droppedCount>0&&(he=E.messages,o.info(`microcompact: cleared ${E.droppedCount} old tool results`))}if(he=Ai(he,F).messages,Q.promptTokens>0){let A=I.contextWindowTokens*.75,E=gp().getActive(),L;E?L=await E.compressAsync(he,A,{model:S.currentModel,sessionId:s}):L=hp(he,{budget:A,model:S.currentModel}),L.droppedCount>0&&(he=L.messages,o.info(`autocompact: ${L.strategy}, dropped ${L.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${L.strategy}: ${L.droppedCount} dropped`},S.hasAttemptedReactiveCompact=!1,u?.invoke("context.after_compact",{...m,removedCount:L.droppedCount}).catch(()=>{}))}he=Uw(he);let Ut=ha({tools:$,toolChoice:n.toolChoice??"auto"}),g=Ar({maxRounds:x,replayMessages:he,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),v=Ut.extraSystemPrompt?[{role:"system",content:Ut.extraSystemPrompt},...g.state.replayMessages]:g.state.replayMessages;B=g.state,g.recoveryActions.length>0&&o.debug(`tool loop recovery: ${g.recoveryActions.map(A=>A.detail??A.kind).join("; ")}`),o.debug(`turn ${ne}, messages: ${v.length}`),u?.invoke("turn.before_inference",{...m,model:S.currentModel}).catch(()=>{});let _=!1,C=[],R=new Map,U="stop",D,M=null,V=!1,ae=[],ee=[];try{for await(let A of e.stream({model:S.currentModel,messages:v,tools:Ut.tools,toolChoice:Ut.normalizedToolChoice??"auto",temperature:d,maxTokens:(Ue??Q.currentMaxOutputTokens)||void 0,streamRequired:n.streamRequired,previousResponseId:S.lastResponseId,reasoning:n.reasoning,promptCacheKey:n.promptCacheKey,promptCacheRetention:n.promptCacheRetention,serviceTier:n.serviceTier,openaiBuiltinTools:n.openaiBuiltinTools,maxToolCalls:n.maxToolCalls,parallelToolCalls:n.parallelToolCalls,textVerbosity:n.textVerbosity},c,p))switch(A.type){case"delta":C.push(A.text),_||(yield{type:"delta",turnId:r,text:A.text});break;case"tool_call_delta":_=!0,La(R,A);break;case"reasoning_delta":ae.push(A.text);break;case"reasoning_block_complete":A.signature&&ee.push({thinking:ae.join(""),signature:A.signature}),ae.length=0;break;case"usage":D={inputTokens:A.promptTokens,outputTokens:A.completionTokens,reasoningTokens:A.reasoningTokens,cacheRead:A.cacheReadTokens,cacheWrite:A.cacheCreationTokens};break;case"response_id":S.lastResponseId=A.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:A.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${A.toolType}: ${A.event}`};break;case"done":U=A.finishReason;break}if(_||u?.invoke("turn.after_inference",{...m,model:S.currentModel}).catch(()=>{}),n.postSamplingHooks&&n.postSamplingHooks.length>0){let A=S.currentModel;for(let E of n.postSamplingHooks)try{E({messages:[...he],model:A,sessionId:s})}catch{}}}catch(A){if(A instanceof So&&n.fallbackModel){o.info(`model fallback triggered: ${A.originalModel} \u2192 ${A.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${A.originalModel} \u2192 ${A.fallbackModel}`},S={...S,currentModel:A.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let E=A instanceof Error?A.message:String(A),L=typeof A?.status=="number"?A.status:void 0;if(!L&&E&&(E.includes("ECONNRESET")||E.includes("EPIPE"))){let re=(S.consecutiveApiRetries??0)+1;if(re>Ln){o.info(`stale connection retry limit reached (${Ln}), aborting`),yield{type:"error",turnId:r,error:E,code:"RETRIES_EXHAUSTED",usage:S.totalUsage};return}o.info(`stale connection (${E.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:E.slice(0,80)},S={...S,consecutiveApiRetries:re,transition:void 0};continue}let G=$w({status:L,message:E});if(G!==null){o.info(`max_tokens overflow: adjusting to ${G}`),Q.currentMaxOutputTokens=G,S={...S,maxOutputTokensOverride:G,transition:void 0};continue}if(xa(L)){S.consecutive529Errors++;let re=2,_e=n.fallbackModel&&S.currentModel!==n.fallbackModel;if(S.consecutive529Errors>re&&!_e&&!Ir()){o.info(`transient ${L} \xD7 ${S.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:r,error:`API unavailable after ${S.consecutive529Errors} consecutive ${L} errors`,code:"API_ERROR",usage:S.totalUsage};return}if(S.consecutive529Errors>=Wi&&n.fallbackModel&&S.currentModel!==n.fallbackModel){o.info(`529 \xD7 ${S.consecutive529Errors}: triggering fallback to ${n.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${S.consecutive529Errors}`},S={...S,currentModel:n.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Ir()){let Z=Pr(S.consecutive529Errors);o.info(`persistent retry: waiting ${Z}ms (attempt ${S.consecutive529Errors})`);let ye=Z;for(;ye>0;){if(p?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED",usage:S.totalUsage};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(ye/1e3)}s (${L})`};let it=Math.min(ye,Bi);await new Promise(fi=>setTimeout(fi,it)),ye-=it}S={...S,transition:void 0};continue}if(wa(f)){let ye=Nw({status:L,message:E})??Pr(S.consecutive529Errors);o.info(`transient ${L}: retry in ${ye}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${L} retry in ${ye}ms`},await new Promise(it=>setTimeout(it,ye)),S={...S,transition:void 0};continue}o.info(`background source ${f}: not retrying ${L}`)}M={status:L,message:E}}if(M&&u?.invoke("turn.after_inference",{...m,model:S.currentModel,response:{error:M.message}}).catch(()=>{}),M)if(wp(M))V=!0,o.info(`withheld prompt_too_long error (status=${M.status})`);else if(xp(M))V=!0,o.info(`withheld media_size error (status=${M.status})`);else{let A=Ea({status:M.status??500,message:M.message},Q,I);if(A.action==="reactive_compact"&&Nn(T)&&(T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${M.status??500}: ${M.message}`}),A.action==="retry"){let L=(S.consecutiveApiRetries??0)+1;if(L>Ln){o.info(`API retry limit reached (${Ln}), aborting`);let G=On(M.status,M.message);yield{type:"error",turnId:r,error:M.message,code:G,usage:S.totalUsage};return}yield{type:"recovery",turnId:r,action:"retry",detail:A.reason},S={...S,consecutiveApiRetries:L,transition:void 0};continue}let E=On(M.status,M.message);u?.invoke("stop.failure",{sessionId:s,reason:E,error:M.message}).catch(()=>{}),yield{type:"error",turnId:r,error:M.message,code:E,usage:S.totalUsage};return}D&&(S.totalUsage.inputTokens+=D.inputTokens,S.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(S.totalUsage.reasoningTokens=(S.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(S.totalUsage.cacheRead=(S.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(S.totalUsage.cacheWrite=(S.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(Q.promptTokens=D.inputTokens);let oe=C.join("");oe&&(S.finalText=oe);let me=[...R.values()].map(A=>({id:A.id||`tc_${r}_${ne}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:A.name,arguments:A.arguments}}));if(me.length===0&&!_){if(V&&M&&wp(M)){if(S.transition?.reason!=="collapse_drain_retry"){let L=Pi(he,F);if(L.committed>0){o.info(`collapse drain: committed ${L.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${L.committed} stages committed`},S={...S,messages:L.messages,transition:{reason:"collapse_drain_retry",committed:L.committed}};continue}}if(Nn(T)){T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},S={...S,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),u?.invoke("stop.failure",{sessionId:s,reason:"prompt_too_long",error:M.message}).catch(()=>{}),yield{type:"error",turnId:r,error:M.message,code:"PROMPT_TOO_LONG",usage:S.totalUsage};return}if(V&&M&&xp(M)){if(Nn(T)){T.attemptedThisTurn=!0,Q.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},S={...S,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),u?.invoke("stop.failure",{sessionId:s,reason:"media_error",error:M.message}).catch(()=>{}),yield{type:"error",turnId:r,error:M.message,code:"IMAGE_ERROR",usage:S.totalUsage};return}if(Lw(U)){Q.consecutiveTruncations+=1;let L=n.modelMaxOutputTokens??Li,G=Ma(Q,I,L);if(G.shouldEscalate&&Ue===void 0){Q.currentMaxOutputTokens=G.newMax,o.info(`max_output_tokens escalate: ${G.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${G.newMax} tokens`},S={...S,maxOutputTokensOverride:$i,transition:{reason:"max_output_tokens_escalate"}};continue}if(ve<Ni){let re={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 #${ve+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${ve+1}`},S={...S,messages:[...he,re],maxOutputTokensRecoveryCount:ve+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:ve+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else Q.consecutiveTruncations=0;if(B=_r(B,{replayMessages:j,lastStopReason:"completed"}),u){let L=await u.invoke("stop",{sessionId:s,reason:"completed"});if(L.action==="prevent"){o.info(`stop hook prevented continuation: ${L.reason??"no reason"}`),yield{type:"end",turnId:r,content:S.finalText,usage:S.totalUsage,model:S.currentModel};return}if(L.action==="abort"){let G=L.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${G}`);let re={role:"user",content:G},_e={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,_e,re],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(n.tokenBudget&&n.tokenBudget>0&&S.budgetContinuationCount<5){let L=S.totalUsage.inputTokens+S.totalUsage.outputTokens+(S.totalUsage.reasoningTokens??0),G=L/n.tokenBudget*100,re=L-S.lastBudgetGlobalTokens,_e=S.budgetContinuationCount>=Ui&&re<wr&&S.lastBudgetDeltaTokens<wr;if(_e&&o.info(`token budget early stop: diminishing returns at ${Math.round(G)}% (delta=${re})`),!_e&&G<90){let Z=S.budgetContinuationCount+1,ye={role:"user",content:bp(G,L,n.tokenBudget)};o.info(`token budget continuation #${Z}: ${Math.round(G)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(G)}% used (#${Z})`};let it={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,it,ye],budgetContinuationCount:Z,lastBudgetDeltaTokens:re,lastBudgetGlobalTokens:L,transition:{reason:"token_budget_continuation"}};continue}}if(!S.stopHookActive){let L=i.find(Z=>Z.role==="user"),G=typeof L?.content=="string"?L.content:"",re=/创建文件|生成文件|写入|写一个|建一个|新建|重写|改写|create\s+(a\s+)?file|write\s+(a\s+)?file|make\s+(a\s+)?file|修改|改成|把.*改|文件名叫/i.test(G),_e=P.has("write")||P.has("edit");if(re&&!_e){if(o.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),O>0){let it=[...j].reverse().find(fi=>fi.role==="tool");it&&typeof it.content=="string"&&(it.content+=`
44
44
 
45
- \u26A0\uFE0F NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}let Z={role:"user",content:O===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes \u2014 actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."},ye={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,ye,Z],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!S.stopHookActive&&O>=3&&P.has("write")){let L=0;for(let G of j){let re=G,_e=re.is_error===!0||typeof re.content=="string"&&re.content.startsWith("Error:");re.role==="tool"&&typeof re.content=="string"&&!_e&&L++}if(L>=3){o.info("AP3 verification nudge: 3+ files created, injecting completeness check");let G={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},re={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,re,G],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(O>0){let L={ok:!0,toolCallCount:O,distinctToolCount:P.size,multiStep:O>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},G=vo(L,{tools:[...P],projectRoot:n.projectRoot});G&&(yield{type:"skill_instruction",turnId:r,instruction:G})}let E=S.finalText||No(j,o);yield{type:"end",turnId:r,content:E,usage:S.totalUsage,model:S.currentModel};return}let Ge=ee.length===0&&ae.length>0?ae.join(""):void 0;j.push(yi(me,S.finalText||void 0,ee.length>0?ee:void 0,Ge)),B=Ta(B,{replayMessages:j,pendingToolCallIds:me.map(A=>A.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Me=S.identicalCallCounts,tn=[],ge=[],jt=!1;for(let A of me){let E=`${A.function.name}::${A.function.arguments}`,L=Me.get(E)??0;Me.set(E,L+1),L+1>Ei?(ge.push(A),jt||(jt=!0,o.info(`AP4 blocked: ${A.function.name} repeated ${L+1}x`))):tn.push(A)}let xt=[];for(let A of ge){let E=Me.get(`${A.function.name}::${A.function.arguments}`),L=Tp(j,A.function.name),G=L?`This exact tool call has been attempted ${E} times. Last error: ${L}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${E} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,re=nn(A.id,{ok:!1,error:G});j.push(re),xt.push(A.id),P.add(A.function.name),O++,yield{type:"tool_result",turnId:r,callId:A.id,name:A.function.name,ok:!1,error:G}}if(ge.length>0){let A=Tp(j,ge[0].function.name),E={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(A?`The error was: "${A}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};j.push(E)}let Ke=[],pi=[];for(let A of tn)(S.toolFailureCounts.get(A.function.name)??0)>=Tr?pi.push(A):Ke.push(A);if(pi.length>0){for(let E of pi){let L=S.toolFailureCounts.get(E.function.name),G=`Tool "${E.function.name}" has failed ${L} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`,re=nn(E.id,{ok:!1,error:G});j.push(re),xt.push(E.id),P.add(E.function.name),O++,yield{type:"tool_result",turnId:r,callId:E.id,name:E.function.name,ok:!1,error:G},o.info(`AP4-variant blocked: ${E.function.name} failed ${L}x with different args`)}let A={role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."};j.push(A)}for(let A of Ke){let E=A.function.arguments,L=$.find(G=>G.function.name===A.function.name);if(L?.backfillObservableInput)try{let G=JSON.parse(A.function.arguments),re={...G};L.backfillObservableInput(re),Object.keys(re).some(Z=>!(Z in G))&&(E=JSON.stringify(re))}catch{}yield{type:"tool_call",turnId:r,callId:A.id,name:A.function.name,arguments:E}}let Lk=new Map(S.toolFailureCounts);try{let A=new Kr({toolInvoker:t,hooks:u,sessionId:s,turnId:r,log:o,signal:p,maxConcurrentTools:n?.maxConcurrentTools});for(let E of Ke)A.addTool(E);for await(let E of A.getRemainingResults()){E.blocked&&(yield{type:"tool_blocked",turnId:r,callId:E.callId,name:E.toolName,reason:E.blockReason??"blocked"}),j.push(E.message),xt.push(E.callId),P.add(E.toolName),O++;let L=E.ok&&Ew(E);if(!E.ok||L){let Z=(S.toolFailureCounts.get(E.toolName)??0)+1;S.toolFailureCounts.set(E.toolName,Z)}if(E.ok&&E.toolName==="read"){let _e=Ke.find(Z=>Z.id===E.callId);if(_e)try{let Z=JSON.parse(_e.function.arguments),ye=Z.file_path??Z.path??Z.filePath??"";if(ye){let it=S.fileReadCounts.get(ye)??0;S.fileReadCounts.set(ye,it+1)}}catch{}}let G=typeof E.message?.content=="string"?E.message.content:"",re=E.ok&&G?G.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:E.callId,name:E.toolName,ok:E.ok,error:E.error,outputPreview:re},E.ok){let _e=me.find(Z=>Z.id===E.callId);if(_e){if(E.toolName==="plan_mode")try{let Z=JSON.parse(_e.function.arguments);Z.action==="exit"&&typeof Z.plan=="string"&&Z.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:Z.plan})}catch{}if(_w.has(E.toolName))try{let Z=JSON.parse(_e.function.arguments),ye=typeof Z.file_path=="string"?Z.file_path:typeof Z.filePath=="string"?Z.filePath:typeof Z.path=="string"?Z.path:void 0;ye&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${E.callId}`,artifactType:Aw(ye),title:ye.split(/[\\/]/).pop()||ye,filePath:ye,language:Pw(ye)})}catch{}}}}}catch(A){let E=A instanceof Error?A.message:String(A);yield{type:"error",turnId:r,error:E,code:"TOOL_EXECUTION_ERROR",usage:S.totalUsage};return}for(let[A,E]of S.toolFailureCounts)E>=Tr&&(Lk.get(A)??0)<Tr&&j.push({role:"user",content:`Tool "${A}" has now failed/returned empty results ${E} times with different arguments. The target clearly does not exist. Do NOT call "${A}" again. Report the result to the user immediately.`});if(B=_r(B,{replayMessages:j,completedToolCallIds:[...B.completedToolCallIds,...xt],lastStopReason:"tool_calls"}),n.generateToolUseSummary&&me.length>0){let A=me.map(E=>({name:E.function.name,arguments:E.function.arguments}));W=n.generateToolUseSummary(A).catch(()=>null)}let Nk=me.length>0&&me.every(A=>{let E=j.find(G=>G?.role==="tool"&&G?.tool_call_id===A.id);if(!E)return!0;let L=E.content;return typeof L=="string"&&L.startsWith("Error: ")}),mo=S.consecutiveFailedRounds;if(Nk){if(mo+=1,mo>=Ci){let A=S.finalText||No(j,o);o.info(`early exit: ${mo} consecutive failed rounds, returning ${S.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}}else mo=0;let $k=3,xd=[...S.fileReadCounts.entries()].filter(([,A])=>A>=$k);if(xd.length>0){let A=xd.map(([L])=>L).join(", ");o.info(`AP5: file read cycle detected on ${A}, injecting nudge`);let E={role:"user",content:`You are reading the same files repeatedly (${A}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};j.push(E),S.fileReadCounts.clear()}let mi=ne+1;if(h>0&&mi>h){if(o.info(`max turns reached (${h}), completing`),u){let E=await u.invoke("stop",{sessionId:s,reason:"max_turns"});if(E.action==="abort"){let L=E.reason??"Stop hook requested continuation after max_turns",G={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,G,{role:"user",content:L}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let A=S.finalText||No(j,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}if(mi>x){if(o.info(`tool loop budget exhausted (${x} rounds), returning`),O>0){let E={ok:!0,toolCallCount:O,distinctToolCount:P.size,multiStep:O>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},L=vo(E,{tools:[...P],projectRoot:n.projectRoot});L&&(yield{type:"skill_instruction",turnId:r,instruction:L})}let A=S.finalText||No(j,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}S={messages:j,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:mi,transition:{reason:"next_turn"},guardState:Q,reactiveCompactState:T,toolLoopState:B,consecutiveFailedRounds:mo,finalText:S.finalText,totalUsage:S.totalUsage,collapseStore:F,currentModel:S.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:S.stopHookActive,lastResponseId:S.lastResponseId,snipRemovedIds:S.snipRemovedIds,contentReplacementState:S.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:Me,toolFailureCounts:S.toolFailureCounts,fileReadCounts:S.fileReadCounts}}}function No(n,e){let t=[];for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.role==="tool"&&typeof r.content=="string")t.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return e.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return t.length>0?(e.info(`synthesizeFallbackContent: synthesized from ${t.length} tool result(s)`),t.join(`
45
+ \u26A0\uFE0F NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}let Z={role:"user",content:O===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes \u2014 actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."},ye={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,ye,Z],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!S.stopHookActive&&O>=3&&P.has("write")){let L=0;for(let G of j){let re=G,_e=re.is_error===!0||typeof re.content=="string"&&re.content.startsWith("Error:");re.role==="tool"&&typeof re.content=="string"&&!_e&&L++}if(L>=3){o.info("AP3 verification nudge: 3+ files created, injecting completeness check");let G={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},re={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,re,G],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(O>0){let L={ok:!0,toolCallCount:O,distinctToolCount:P.size,multiStep:O>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},G=vo(L,{tools:[...P],projectRoot:n.projectRoot});G&&(yield{type:"skill_instruction",turnId:r,instruction:G})}let E=S.finalText||No(j,o);yield{type:"end",turnId:r,content:E,usage:S.totalUsage,model:S.currentModel};return}let Ge=ee.length===0&&ae.length>0?ae.join(""):void 0;j.push(yi(me,S.finalText||void 0,ee.length>0?ee:void 0,Ge)),B=Ta(B,{replayMessages:j,pendingToolCallIds:me.map(A=>A.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Me=S.identicalCallCounts,tn=[],ge=[],jt=!1;for(let A of me){let E=`${A.function.name}::${A.function.arguments}`,L=Me.get(E)??0;Me.set(E,L+1),L+1>Ei?(ge.push(A),jt||(jt=!0,o.info(`AP4 blocked: ${A.function.name} repeated ${L+1}x`))):tn.push(A)}let xt=[];for(let A of ge){let E=Me.get(`${A.function.name}::${A.function.arguments}`),L=Tp(j,A.function.name),G=L?`This exact tool call has been attempted ${E} times. Last error: ${L}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${E} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,re=nn(A.id,{ok:!1,error:G});j.push(re),xt.push(A.id),P.add(A.function.name),O++,yield{type:"tool_result",turnId:r,callId:A.id,name:A.function.name,ok:!1,error:G}}if(ge.length>0){let A=Tp(j,ge[0].function.name),E={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(A?`The error was: "${A}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};j.push(E)}let Ke=[],pi=[];for(let A of tn)(S.toolFailureCounts.get(A.function.name)??0)>=Tr?pi.push(A):Ke.push(A);if(pi.length>0){for(let E of pi){let L=S.toolFailureCounts.get(E.function.name),G=`Tool "${E.function.name}" has failed ${L} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`,re=nn(E.id,{ok:!1,error:G});j.push(re),xt.push(E.id),P.add(E.function.name),O++,yield{type:"tool_result",turnId:r,callId:E.id,name:E.function.name,ok:!1,error:G},o.info(`AP4-variant blocked: ${E.function.name} failed ${L}x with different args`)}let A={role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."};j.push(A)}for(let A of Ke){let E=A.function.arguments,L=$.find(G=>G.function.name===A.function.name);if(L?.backfillObservableInput)try{let G=JSON.parse(A.function.arguments),re={...G};L.backfillObservableInput(re),Object.keys(re).some(Z=>!(Z in G))&&(E=JSON.stringify(re))}catch{}yield{type:"tool_call",turnId:r,callId:A.id,name:A.function.name,arguments:E}}let Lk=new Map(S.toolFailureCounts);try{let A=new Kr({toolInvoker:t,hooks:u,sessionId:s,turnId:r,log:o,signal:p,maxConcurrentTools:n?.maxConcurrentTools});for(let E of Ke)A.addTool(E);for await(let E of A.getRemainingResults()){E.blocked&&(yield{type:"tool_blocked",turnId:r,callId:E.callId,name:E.toolName,reason:E.blockReason??"blocked"}),j.push(E.message),xt.push(E.callId),P.add(E.toolName),O++;let L=E.ok&&Ow(E);if(!E.ok||L){let Z=(S.toolFailureCounts.get(E.toolName)??0)+1;S.toolFailureCounts.set(E.toolName,Z)}if(E.ok&&E.toolName==="read"){let _e=Ke.find(Z=>Z.id===E.callId);if(_e)try{let Z=JSON.parse(_e.function.arguments),ye=Z.file_path??Z.path??Z.filePath??"";if(ye){let it=S.fileReadCounts.get(ye)??0;S.fileReadCounts.set(ye,it+1)}}catch{}}let G=typeof E.message?.content=="string"?E.message.content:"",re=E.ok&&G?G.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:E.callId,name:E.toolName,ok:E.ok,error:E.error,outputPreview:re},E.ok){let _e=me.find(Z=>Z.id===E.callId);if(_e){if(E.toolName==="plan_mode")try{let Z=JSON.parse(_e.function.arguments);Z.action==="exit"&&typeof Z.plan=="string"&&Z.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:Z.plan})}catch{}if(Pw.has(E.toolName))try{let Z=JSON.parse(_e.function.arguments),ye=typeof Z.file_path=="string"?Z.file_path:typeof Z.filePath=="string"?Z.filePath:typeof Z.path=="string"?Z.path:void 0;ye&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${E.callId}`,artifactType:Iw(ye),title:ye.split(/[\\/]/).pop()||ye,filePath:ye,language:Cw(ye)})}catch{}}}}}catch(A){let E=A instanceof Error?A.message:String(A);yield{type:"error",turnId:r,error:E,code:"TOOL_EXECUTION_ERROR",usage:S.totalUsage};return}for(let[A,E]of S.toolFailureCounts)E>=Tr&&(Lk.get(A)??0)<Tr&&j.push({role:"user",content:`Tool "${A}" has now failed/returned empty results ${E} times with different arguments. The target clearly does not exist. Do NOT call "${A}" again. Report the result to the user immediately.`});if(B=_r(B,{replayMessages:j,completedToolCallIds:[...B.completedToolCallIds,...xt],lastStopReason:"tool_calls"}),n.generateToolUseSummary&&me.length>0){let A=me.map(E=>({name:E.function.name,arguments:E.function.arguments}));W=n.generateToolUseSummary(A).catch(()=>null)}let Nk=me.length>0&&me.every(A=>{let E=j.find(G=>G?.role==="tool"&&G?.tool_call_id===A.id);if(!E)return!0;let L=E.content;return typeof L=="string"&&L.startsWith("Error: ")}),mo=S.consecutiveFailedRounds;if(Nk){if(mo+=1,mo>=Ci){let A=S.finalText||No(j,o);o.info(`early exit: ${mo} consecutive failed rounds, returning ${S.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}}else mo=0;let $k=3,xd=[...S.fileReadCounts.entries()].filter(([,A])=>A>=$k);if(xd.length>0){let A=xd.map(([L])=>L).join(", ");o.info(`AP5: file read cycle detected on ${A}, injecting nudge`);let E={role:"user",content:`You are reading the same files repeatedly (${A}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};j.push(E),S.fileReadCounts.clear()}let mi=ne+1;if(h>0&&mi>h){if(o.info(`max turns reached (${h}), completing`),u){let E=await u.invoke("stop",{sessionId:s,reason:"max_turns"});if(E.action==="abort"){let L=E.reason??"Stop hook requested continuation after max_turns",G={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,G,{role:"user",content:L}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let A=S.finalText||No(j,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}if(mi>x){if(o.info(`tool loop budget exhausted (${x} rounds), returning`),O>0){let E={ok:!0,toolCallCount:O,distinctToolCount:P.size,multiStep:O>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},L=vo(E,{tools:[...P],projectRoot:n.projectRoot});L&&(yield{type:"skill_instruction",turnId:r,instruction:L})}let A=S.finalText||No(j,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}S={messages:j,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:mi,transition:{reason:"next_turn"},guardState:Q,reactiveCompactState:T,toolLoopState:B,consecutiveFailedRounds:mo,finalText:S.finalText,totalUsage:S.totalUsage,collapseStore:F,currentModel:S.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:S.stopHookActive,lastResponseId:S.lastResponseId,snipRemovedIds:S.snipRemovedIds,contentReplacementState:S.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:Me,toolFailureCounts:S.toolFailureCounts,fileReadCounts:S.fileReadCounts}}}function No(n,e){let t=[];for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.role==="tool"&&typeof r.content=="string")t.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return e.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return t.length>0?(e.info(`synthesizeFallbackContent: synthesized from ${t.length} tool result(s)`),t.join(`
46
46
 
47
- `)):""}async function*$w(n,e,t,o,r,s,i,a){let l=[],c;a.debug(`single LLM round, messages: ${t.length}`);for await(let d of i.stream({model:e,messages:t,temperature:r},o,s))switch(d.type){case"delta":l.push(d.text),yield{type:"delta",turnId:n,text:d.text};break;case"usage":c={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:n,content:l.join(""),usage:c??{inputTokens:0,outputTokens:0},model:e}}var _w,Iw,Cw,_p=N(()=>{"use strict";an();$n();Zu();al();kp();tl();je();_w=new Set(["write","edit","patch","apply_patch"]);Iw=/^no (matches|files|results) found\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Cw=new Set(["search","grep","glob","find","list","read","exec"])});function Ap(n){if(!n||n.length<5)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};let e=[];for(let[r,s]of Object.entries(Uw)){if(r==="general")continue;let i=s.filter(a=>a.test(n)).length;if(i>0){let a=Math.min(1,i/2);e.push({scenario:r,score:a})}}if(e.length===0)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};e.sort((r,s)=>s.score-r.score);let t=e[0];if(t.score<.5)return{scenario:"general",preferred:[],deprioritized:[],confidence:t.score};let o=jw[t.scenario];return{scenario:t.scenario,preferred:o.preferred,deprioritized:o.deprioritized,confidence:t.score}}function ll(n,e,t){return!e||t.scenario==="general"?n:t.preferred.includes(e)?Math.min(1,n*1.2):t.deprioritized.includes(e)?n*.7:n}function Pp(n){let e=n.replace(/\.md$/,"").toLowerCase();for(let[t,o]of Object.entries(Fw))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return o;return null}var Uw,jw,Fw,cl=N(()=>{"use strict";Uw={coding:[/(?:bug|error|fix|debug|报错|修复|编译|compile|build|lint)/i,/(?:implement|refactor|重构|实现|代码|code|function|method|class)/i,/(?:test|测试|vitest|jest|断言|assert)/i,/(?:type(?:script)?|接口|interface|generic|泛型)/i,/(?:import|export|module|依赖|package|npm|pnpm)/i,/(?:git|commit|branch|merge|rebase|PR|MR)/i],config:[/(?:deploy|部署|运维|docker|container|kubernetes|k8s)/i,/(?:port|端口|config|配置|env|环境变量|.env)/i,/(?:server|service|daemon|进程|systemd|nginx|redis)/i,/(?:版本|version|upgrade|migrate|迁移)/i,/(?:domain|域名|ssl|cert|证书|DNS)/i],conversation:[/(?:你好|hi|hello|hey|请问|问一下)/i,/(?:我(?:喜欢|偏好|习惯|想)|prefer|I (?:like|want|need))/i,/(?:帮我|help me|能不能|可以吗|would you)/i,/(?:style|风格|format|格式|命名|naming)/i],learning:[/(?:best practice|最佳实践|pattern|模式|惯例|convention)/i,/(?:怎么做|how to|how do|what's the|推荐|recommend)/i,/(?:为什么|why|原因|reason|explain|解释)/i,/(?:lesson|经验|教训|gotcha|pitfall|坑)/i],decision:[/(?:should|应该|选择|choose|decision|决定|trade-?off|权衡)/i,/(?:vs|versus|对比|compare|区别|difference)/i,/(?:architecture|架构|方案|approach|strategy)/i,/(?:pros|cons|优缺点|利弊|好处|坏处)/i],general:[]},jw={coding:{preferred:["lesson","pattern","fact"],deprioritized:["preference"]},config:{preferred:["fact","decision","lesson"],deprioritized:["preference","skill-learning"]},conversation:{preferred:["preference","fact"],deprioritized:["pattern","skill-learning"]},learning:{preferred:["lesson","pattern","skill-learning"],deprioritized:["preference"]},decision:{preferred:["decision","fact","lesson"],deprioritized:["skill-learning","preference"]},general:{preferred:[],deprioritized:[]}};Fw={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",skill:"skill-learning",workflow:"skill-learning"}});var Cp={};fn(Cp,{Agent:()=>Hn});var Hn,Yr=N(()=>{"use strict";$n();_p();je();cl();mt();Hn=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;projectRoot;constructor(e){this.transport=e.llmTransport,this.apiKey=e.apiKey,this.toolInvoker=e.toolInvoker,this.log=e.log,this.hooks=e.hooks,this.projectRoot=e.projectRoot,this.maxRounds=Math.min(e.maxRounds??25,100)}async*run(e,t){let{turnId:o,messages:r,tools:s,systemPrompt:i,config:a}=e,l={sessionId:e.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let c=va(r),d=[];if(i&&d.push({role:"system",content:i}),d.push(...c),this.hooks){let m=c.filter(f=>f.role==="user").pop(),h=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(h)try{let f=Ap(h),y=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:o,query:h,preferredCategories:f.preferred.length>0?f.preferred:void 0,deprioritizedCategories:f.deprioritized.length>0?f.deprioritized:void 0}),b=y?.context?.recalledMemories;if(b&&b.length>0){let x=0,I=[];for(let P of b){let O=(P.text?.length??0)*2;if(x+O>8192)break;I.push(P),x+=O}if(I.length>0){let P=I.map(O=>`- ${O.text}`).join(`
47
+ `)):""}async function*jw(n,e,t,o,r,s,i,a){let l=[],c;a.debug(`single LLM round, messages: ${t.length}`);for await(let d of i.stream({model:e,messages:t,temperature:r},o,s))switch(d.type){case"delta":l.push(d.text),yield{type:"delta",turnId:n,text:d.text};break;case"usage":c={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:n,content:l.join(""),usage:c??{inputTokens:0,outputTokens:0},model:e}}var Pw,Ew,Mw,_p=N(()=>{"use strict";an();$n();Zu();al();kp();tl();je();Pw=new Set(["write","edit","patch","apply_patch"]);Ew=/^no (matches|files|results) found\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Mw=new Set(["search","grep","glob","find","list","read","exec"])});function Ap(n){if(!n||n.length<5)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};let e=[];for(let[r,s]of Object.entries(Fw)){if(r==="general")continue;let i=s.filter(a=>a.test(n)).length;if(i>0){let a=Math.min(1,i/2);e.push({scenario:r,score:a})}}if(e.length===0)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};e.sort((r,s)=>s.score-r.score);let t=e[0];if(t.score<.5)return{scenario:"general",preferred:[],deprioritized:[],confidence:t.score};let o=Bw[t.scenario];return{scenario:t.scenario,preferred:o.preferred,deprioritized:o.deprioritized,confidence:t.score}}function ll(n,e,t){return!e||t.scenario==="general"?n:t.preferred.includes(e)?Math.min(1,n*1.2):t.deprioritized.includes(e)?n*.7:n}function Pp(n){let e=n.replace(/\.md$/,"").toLowerCase();for(let[t,o]of Object.entries(Ww))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return o;return null}var Fw,Bw,Ww,cl=N(()=>{"use strict";Fw={coding:[/(?:bug|error|fix|debug|报错|修复|编译|compile|build|lint)/i,/(?:implement|refactor|重构|实现|代码|code|function|method|class)/i,/(?:test|测试|vitest|jest|断言|assert)/i,/(?:type(?:script)?|接口|interface|generic|泛型)/i,/(?:import|export|module|依赖|package|npm|pnpm)/i,/(?:git|commit|branch|merge|rebase|PR|MR)/i],config:[/(?:deploy|部署|运维|docker|container|kubernetes|k8s)/i,/(?:port|端口|config|配置|env|环境变量|.env)/i,/(?:server|service|daemon|进程|systemd|nginx|redis)/i,/(?:版本|version|upgrade|migrate|迁移)/i,/(?:domain|域名|ssl|cert|证书|DNS)/i],conversation:[/(?:你好|hi|hello|hey|请问|问一下)/i,/(?:我(?:喜欢|偏好|习惯|想)|prefer|I (?:like|want|need))/i,/(?:帮我|help me|能不能|可以吗|would you)/i,/(?:style|风格|format|格式|命名|naming)/i],learning:[/(?:best practice|最佳实践|pattern|模式|惯例|convention)/i,/(?:怎么做|how to|how do|what's the|推荐|recommend)/i,/(?:为什么|why|原因|reason|explain|解释)/i,/(?:lesson|经验|教训|gotcha|pitfall|坑)/i],decision:[/(?:should|应该|选择|choose|decision|决定|trade-?off|权衡)/i,/(?:vs|versus|对比|compare|区别|difference)/i,/(?:architecture|架构|方案|approach|strategy)/i,/(?:pros|cons|优缺点|利弊|好处|坏处)/i],general:[]},Bw={coding:{preferred:["lesson","pattern","fact"],deprioritized:["preference"]},config:{preferred:["fact","decision","lesson"],deprioritized:["preference","skill-learning"]},conversation:{preferred:["preference","fact"],deprioritized:["pattern","skill-learning"]},learning:{preferred:["lesson","pattern","skill-learning"],deprioritized:["preference"]},decision:{preferred:["decision","fact","lesson"],deprioritized:["skill-learning","preference"]},general:{preferred:[],deprioritized:[]}};Ww={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",skill:"skill-learning",workflow:"skill-learning"}});var Cp={};fn(Cp,{Agent:()=>Hn});var Hn,Yr=N(()=>{"use strict";$n();_p();je();cl();mt();Hn=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;projectRoot;constructor(e){this.transport=e.llmTransport,this.apiKey=e.apiKey,this.toolInvoker=e.toolInvoker,this.log=e.log,this.hooks=e.hooks,this.projectRoot=e.projectRoot,this.maxRounds=Math.min(e.maxRounds??25,100)}async*run(e,t){let{turnId:o,messages:r,tools:s,systemPrompt:i,config:a}=e,l={sessionId:e.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let c=va(r),d=[];if(i&&d.push({role:"system",content:i}),d.push(...c),this.hooks){let m=c.filter(f=>f.role==="user").pop(),h=typeof m?.content=="string"?m.content.slice(0,500):void 0;if(h)try{let f=Ap(h),y=await this.hooks.invoke("memory.before_recall",{sessionId:e.sessionId,turnId:o,query:h,preferredCategories:f.preferred.length>0?f.preferred:void 0,deprioritizedCategories:f.deprioritized.length>0?f.deprioritized:void 0}),b=y?.context?.recalledMemories;if(b&&b.length>0){let x=0,I=[];for(let P of b){let O=(P.text?.length??0)*2;if(x+O>8192)break;I.push(P),x+=O}if(I.length>0){let P=I.map(O=>`- ${O.text}`).join(`
48
48
  `);d.splice(i?1:0,0,{role:"system",content:`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
49
- ${P}`})}}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o,blockCount:y?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let u=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=async y=>{let b=X().resolveModelForPurpose("smallModel");if(!b)return null;try{let k=y.map(P=>`${P.name}(${P.arguments.slice(0,200)})`).join(", "),x=this.transport.stream({model:b,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:k}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),I="";for await(let P of x)P.type==="delta"&&(I+=P.text);return I.trim()||null}catch{return null}},h={turnId:o,sessionId:e.sessionId,messages:d,tools:s,model:u,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:p,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:m,signal:t},f;for await(let y of Rp(h,this.transport,this.toolInvoker,this.log))f=y,yield y;f?.type==="end"?this.hooks?.invoke("turn.completed",{...l}).catch(()=>{}):f?.type==="error"&&this.hooks?.invoke("turn.failed",{...l,code:f.code,error:f.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let h=m instanceof Error?m.message:String(m),f=typeof m?.status=="number"?m.status:void 0,y=On(f,h);this.log.error(`turn ${o} error [${y}, retryable=${ki(y)}]: ${h}`),this.hooks?.invoke("turn.failed",{...l,code:y,error:h}).catch(()=>{}),yield{type:"error",turnId:o,error:h,code:y}}}}}});import{createHash as ed}from"node:crypto";import ir from"node:fs";import Kh from"node:path";function lE(n){return Zc.find(e=>e.id===n)}function cE(n,e,t){let o=lE(t);if(o)return o;let r=Zc.filter(a=>a.rarity===e);if(r.length===0)return Zc[0];let i=ed("sha256").update(`breed-${n}`).digest()[0]%r.length;return r[i]}function dE(n){let t=ed("sha256").update(n).digest()[0]%100,o=0;for(let r=0;r<zh.length;r++)if(o+=zh[r],t<o)return aE[r];return"common"}function uE(n){let e=ed("sha256").update(`stats-${n}`).digest();return{grip:e[0]%10+1,patience:e[1]%10+1,curiosity:e[2]%10+1,appetite:e[3]%10+1,humor:e[4]%10+1}}var aE,zh,Zc,$t,qh=N(()=>{"use strict";aE=["common","uncommon","rare","epic","legendary"],zh=[50,25,15,8,2],Zc=[{id:"default",name:"\u84DD\u8272\u4F19\u4F34",colors:{primary:"#5A7EFF",secondary:"#1E3A8A"},rarity:"default"},{id:"golden",name:"\u9EC4\u91D1\u4F19\u4F34",colors:{primary:"#F59E0B",secondary:"#92400E"},rarity:"legendary"},{id:"crystal",name:"\u6C34\u6676\u4F19\u4F34",colors:{primary:"#7DD3FC",secondary:"#0C4A6E"},rarity:"rare"},{id:"obsidian",name:"\u9ED1\u66DC\u4F19\u4F34",colors:{primary:"#7C3AED",secondary:"#1E1B4B"},rarity:"epic"},{id:"ghost",name:"\u96FE\u5F71\u4F19\u4F34",colors:{primary:"#94A3B8",secondary:"#475569"},rarity:"uncommon"},{id:"rainbow",name:"\u5F69\u8679\u4F19\u4F34",colors:{primary:"#EC4899",secondary:"#7C3AED"},rarity:"rare"}];$t=class{constructor(e){this.workspaceDir=e;this.storagePath=Kh.join(e,".qlogicagent","pet","soul.json")}workspaceDir;soul=null;storagePath;load(){if(this.soul)return this.soul;if(!ir.existsSync(this.storagePath))return null;try{let e=JSON.parse(ir.readFileSync(this.storagePath,"utf-8"));return this.soul=e,this.soul}catch{return null}}async hatch(e,t,o){let r=`${e}-xiaozhi-claw`,s=dE(r),i=uE(r),a=cE(r,s,o),l="\u963F\u84DD",c="\u5B89\u9759\u3001\u597D\u5947\uFF0C\u4F1A\u5728\u4F60\u4E13\u6CE8\u65F6\u966A\u5728\u65C1\u8FB9\u3002",d="\u6211\u5728\u8FD9\u91CC\u3002";if(t){let u=await t(s,i);l=u.name,c=u.personality,d=u.catchphrase}return this.soul={name:l,species:a.name,personality:c,catchphrase:d,stats:i,rarity:s,breed:a.id,breedColors:a.colors,level:1,experience:0,hatchedAt:new Date().toISOString()},this.persist(),this.soul}addExperience(e){if(!this.soul)return{leveledUp:!1,level:0,experience:0};this.soul.experience+=e;let t=this.soul.level*100,o=!1;for(;this.soul.experience>=t;)this.soul.experience-=t,this.soul.level+=1,o=!0;return this.persist(),{leveledUp:o,level:this.soul.level,experience:this.soul.experience}}getSoul(){return this.soul}updateSoul(e){this.soul=e,this.persist()}persist(){let e=Kh.dirname(this.storagePath);ir.existsSync(e)||ir.mkdirSync(e,{recursive:!0}),ir.writeFileSync(this.storagePath,JSON.stringify(this.soul,null,2),"utf-8")}}});function Ys(n){let e=mE[n];if(!e||Math.random()>e.probability)return null;let t=pE[e.pool];return{text:t[Math.floor(Math.random()*t.length)],style:e.style}}async function Xs(n,e){let t=ar.length>0?`
49
+ ${P}`})}}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o,blockCount:y?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let u=a?.model??"",p=Math.min(a?.maxRounds??this.maxRounds,100);try{let m=async y=>{let b=X().resolveModelForPurpose("smallModel");if(!b)return null;try{let k=y.map(P=>`${P.name}(${P.arguments.slice(0,200)})`).join(", "),x=this.transport.stream({model:b,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:k}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),I="";for await(let P of x)P.type==="delta"&&(I+=P.text);return I.trim()||null}catch{return null}},h={turnId:o,sessionId:e.sessionId,messages:d,tools:s,model:u,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:p,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:m,signal:t},f;for await(let y of Rp(h,this.transport,this.toolInvoker,this.log))f=y,yield y;f?.type==="end"?this.hooks?.invoke("turn.completed",{...l}).catch(()=>{}):f?.type==="error"&&this.hooks?.invoke("turn.failed",{...l,code:f.code,error:f.error}).catch(()=>{})}catch(m){if(t?.aborted)this.hooks?.invoke("turn.failed",{...l,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let h=m instanceof Error?m.message:String(m),f=typeof m?.status=="number"?m.status:void 0,y=On(f,h);this.log.error(`turn ${o} error [${y}, retryable=${ki(y)}]: ${h}`),this.hooks?.invoke("turn.failed",{...l,code:y,error:h}).catch(()=>{}),yield{type:"error",turnId:o,error:h,code:y}}}}}});import{createHash as ed}from"node:crypto";import ir from"node:fs";import Kh from"node:path";function dE(n){return Zc.find(e=>e.id===n)}function uE(n,e,t){let o=dE(t);if(o)return o;let r=Zc.filter(a=>a.rarity===e);if(r.length===0)return Zc[0];let i=ed("sha256").update(`breed-${n}`).digest()[0]%r.length;return r[i]}function pE(n){let t=ed("sha256").update(n).digest()[0]%100,o=0;for(let r=0;r<zh.length;r++)if(o+=zh[r],t<o)return cE[r];return"common"}function mE(n){let e=ed("sha256").update(`stats-${n}`).digest();return{grip:e[0]%10+1,patience:e[1]%10+1,curiosity:e[2]%10+1,appetite:e[3]%10+1,humor:e[4]%10+1}}var cE,zh,Zc,$t,qh=N(()=>{"use strict";cE=["common","uncommon","rare","epic","legendary"],zh=[50,25,15,8,2],Zc=[{id:"default",name:"\u84DD\u8272\u4F19\u4F34",colors:{primary:"#5A7EFF",secondary:"#1E3A8A"},rarity:"default"},{id:"golden",name:"\u9EC4\u91D1\u4F19\u4F34",colors:{primary:"#F59E0B",secondary:"#92400E"},rarity:"legendary"},{id:"crystal",name:"\u6C34\u6676\u4F19\u4F34",colors:{primary:"#7DD3FC",secondary:"#0C4A6E"},rarity:"rare"},{id:"obsidian",name:"\u9ED1\u66DC\u4F19\u4F34",colors:{primary:"#7C3AED",secondary:"#1E1B4B"},rarity:"epic"},{id:"ghost",name:"\u96FE\u5F71\u4F19\u4F34",colors:{primary:"#94A3B8",secondary:"#475569"},rarity:"uncommon"},{id:"rainbow",name:"\u5F69\u8679\u4F19\u4F34",colors:{primary:"#EC4899",secondary:"#7C3AED"},rarity:"rare"}];$t=class{constructor(e){this.workspaceDir=e;this.storagePath=Kh.join(e,".qlogicagent","pet","soul.json")}workspaceDir;soul=null;storagePath;load(){if(this.soul)return this.soul;if(!ir.existsSync(this.storagePath))return null;try{let e=JSON.parse(ir.readFileSync(this.storagePath,"utf-8"));return this.soul=e,this.soul}catch{return null}}async hatch(e,t,o){let r=`${e}-xiaozhi-claw`,s=pE(r),i=mE(r),a=uE(r,s,o),l="\u963F\u84DD",c="\u5B89\u9759\u3001\u597D\u5947\uFF0C\u4F1A\u5728\u4F60\u4E13\u6CE8\u65F6\u966A\u5728\u65C1\u8FB9\u3002",d="\u6211\u5728\u8FD9\u91CC\u3002";if(t){let u=await t(s,i);l=u.name,c=u.personality,d=u.catchphrase}return this.soul={name:l,species:a.name,personality:c,catchphrase:d,stats:i,rarity:s,breed:a.id,breedColors:a.colors,level:1,experience:0,hatchedAt:new Date().toISOString()},this.persist(),this.soul}addExperience(e){if(!this.soul)return{leveledUp:!1,level:0,experience:0};this.soul.experience+=e;let t=this.soul.level*100,o=!1;for(;this.soul.experience>=t;)this.soul.experience-=t,this.soul.level+=1,o=!0;return this.persist(),{leveledUp:o,level:this.soul.level,experience:this.soul.experience}}getSoul(){return this.soul}updateSoul(e){this.soul=e,this.persist()}persist(){let e=Kh.dirname(this.storagePath);ir.existsSync(e)||ir.mkdirSync(e,{recursive:!0}),ir.writeFileSync(this.storagePath,JSON.stringify(this.soul,null,2),"utf-8")}}});function Ys(n){let e=gE[n];if(!e||Math.random()>e.probability)return null;let t=fE[e.pool];return{text:t[Math.floor(Math.random()*t.length)],style:e.style}}async function Xs(n,e){let t=ar.length>0?`
50
50
  \u907F\u514D\u548C\u8FD9\u4E9B\u7C7B\u4F3C: ${ar.join("\u3001")}`:"",o=`\u4F60\u662F\u4E00\u53EA\u53EB\u300C${n.soul.name}\u300D\u7684${n.soul.species}\u684C\u9762\u5BA0\u7269\u3002
51
51
  \u6027\u683C: ${n.soul.personality}
52
52
  \u53E3\u5934\u7985\u98CE\u683C: "${n.soul.catchphrase}"
53
53
 
54
54
  \u521A\u624D\u53D1\u751F\u4E86: ${n.turnSummary}
55
55
 
56
- \u7528\u4E00\u53E5\u8BDD(\u226420\u5B57)\u4EE5\u4F60\u7684\u6027\u683C\u505A\u51FA\u7B80\u77ED\u53CD\u5E94\u3002\u53EA\u8F93\u51FA\u53CD\u5E94\u6587\u672C\uFF0C\u4E0D\u8981\u5176\u4ED6\u5185\u5BB9\u3002${t}`;try{let r=await e(o,50);if(!r||r.length>50)return null;ar.push(r),ar.length>fE&&ar.shift();let s=/[!!✨🎉]|搞定|完美|太棒/.test(r)?"excited":/[.。…]|嗯|想|看看/.test(r)?"thinking":/[zZ]|困|睡|累/.test(r)?"sleepy":"normal";return{text:r,style:s}}catch{return null}}var pE,mE,ar,fE,Yh=N(()=>{"use strict";pE={greeting:["\u65B0\u7684\u4E00\u5929\uFF0C\u65B0\u7684\u5192\u9669\uFF01","\u563F\u563F~\u53C8\u89C1\u9762\u4E86","\u51C6\u5907\u597D\u4E86\u5417\uFF1F","\u65B0\u5192\u9669\u5F00\u59CB\u5566\uFF01"],completion:["\u641E\u5B9A\uFF01","\u8FD8\u633A\u987A\u5229\u7684\u561B~","\u4E0B\u4E00\u4E2A\uFF01","\u8FD9\u6CE2\u64CD\u4F5C\u4E0D\u9519","\u5B8C\u7F8E~"],error:["\u5443...\u51FA\u4E86\u70B9\u95EE\u9898","\u522B\u614C\u522B\u614C","\u8BA9\u6211\u770B\u770B\u600E\u4E48\u56DE\u4E8B","\u7CDF\u7CD5...\u518D\u8BD5\u8BD5\uFF1F"],curiosity:["\u8FD9\u4E2A\u5DE5\u5177\u6709\u610F\u601D","\u55EF\u55EF\uFF0C\u5728\u5E72\u6D3B\u4E86","\u597D\u591A\u4E8B\u60C5\u8981\u505A\u5440"],bored:["...","\u6709\u4EBA\u5417\uFF1F","\u8981\u4E0D\u8981\u804A\u804A\uFF1F","*\u5410\u6CE1\u6CE1*"],memory:["\u8BA9\u6211\u6574\u7406\u4E0B\u8BB0\u5FC6...","\u55EF\u55EF\uFF0C\u8FD9\u4E9B\u503C\u5F97\u8BB0\u4F4F","\u8BB0\u4F4F\u4E86~"],tool_success:["\u4E0D\u9519\u4E0D\u9519~","\u53C8\u641E\u5B9A\u4E00\u4E2A","\u987A\u5229\uFF01"]},mE={"turn.error":{probability:1,pool:"error",style:"normal"},"session.created":{probability:1,pool:"greeting",style:"excited"},"turn.end":{probability:.3,pool:"completion",style:"excited"},"turn.tool_call":{probability:.1,pool:"curiosity",style:"thinking"},"turn.tool_result.success":{probability:.15,pool:"tool_success",style:"excited"},"memory.updated":{probability:.5,pool:"memory",style:"thinking"},"idle.long":{probability:.05,pool:"bored",style:"sleepy"}};ar=[],fE=5});function Js(n,e){return n.slice(0,e).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"").replace(/^#+\s*/gm,"").trim()}function Qs(n){if(!n)return"";let e=Js(n.name,10),t=Js(n.species,20),o=Js(n.personality,50),r=Js(n.catchphrase,30);return`
56
+ \u7528\u4E00\u53E5\u8BDD(\u226420\u5B57)\u4EE5\u4F60\u7684\u6027\u683C\u505A\u51FA\u7B80\u77ED\u53CD\u5E94\u3002\u53EA\u8F93\u51FA\u53CD\u5E94\u6587\u672C\uFF0C\u4E0D\u8981\u5176\u4ED6\u5185\u5BB9\u3002${t}`;try{let r=await e(o,50);if(!r||r.length>50)return null;ar.push(r),ar.length>hE&&ar.shift();let s=/[!!✨🎉]|搞定|完美|太棒/.test(r)?"excited":/[.。…]|嗯|想|看看/.test(r)?"thinking":/[zZ]|困|睡|累/.test(r)?"sleepy":"normal";return{text:r,style:s}}catch{return null}}var fE,gE,ar,hE,Yh=N(()=>{"use strict";fE={greeting:["\u65B0\u7684\u4E00\u5929\uFF0C\u65B0\u7684\u5192\u9669\uFF01","\u563F\u563F~\u53C8\u89C1\u9762\u4E86","\u51C6\u5907\u597D\u4E86\u5417\uFF1F","\u65B0\u5192\u9669\u5F00\u59CB\u5566\uFF01"],completion:["\u641E\u5B9A\uFF01","\u8FD8\u633A\u987A\u5229\u7684\u561B~","\u4E0B\u4E00\u4E2A\uFF01","\u8FD9\u6CE2\u64CD\u4F5C\u4E0D\u9519","\u5B8C\u7F8E~"],error:["\u5443...\u51FA\u4E86\u70B9\u95EE\u9898","\u522B\u614C\u522B\u614C","\u8BA9\u6211\u770B\u770B\u600E\u4E48\u56DE\u4E8B","\u7CDF\u7CD5...\u518D\u8BD5\u8BD5\uFF1F"],curiosity:["\u8FD9\u4E2A\u5DE5\u5177\u6709\u610F\u601D","\u55EF\u55EF\uFF0C\u5728\u5E72\u6D3B\u4E86","\u597D\u591A\u4E8B\u60C5\u8981\u505A\u5440"],bored:["...","\u6709\u4EBA\u5417\uFF1F","\u8981\u4E0D\u8981\u804A\u804A\uFF1F","*\u5410\u6CE1\u6CE1*"],memory:["\u8BA9\u6211\u6574\u7406\u4E0B\u8BB0\u5FC6...","\u55EF\u55EF\uFF0C\u8FD9\u4E9B\u503C\u5F97\u8BB0\u4F4F","\u8BB0\u4F4F\u4E86~"],tool_success:["\u4E0D\u9519\u4E0D\u9519~","\u53C8\u641E\u5B9A\u4E00\u4E2A","\u987A\u5229\uFF01"]},gE={"turn.error":{probability:1,pool:"error",style:"normal"},"session.created":{probability:1,pool:"greeting",style:"excited"},"turn.end":{probability:.3,pool:"completion",style:"excited"},"turn.tool_call":{probability:.1,pool:"curiosity",style:"thinking"},"turn.tool_result.success":{probability:.15,pool:"tool_success",style:"excited"},"memory.updated":{probability:.5,pool:"memory",style:"thinking"},"idle.long":{probability:.05,pool:"bored",style:"sleepy"}};ar=[],hE=5});function Js(n,e){return n.slice(0,e).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,"").replace(/^#+\s*/gm,"").trim()}function Qs(n){if(!n)return"";let e=Js(n.name,10),t=Js(n.species,20),o=Js(n.personality,50),r=Js(n.catchphrase,30);return`
57
57
  # \u684C\u9762\u4F19\u4F34
58
58
 
59
59
  \u4E00\u53EA\u540D\u53EB\u300C${e}\u300D\u7684${t}\u5750\u5728\u7528\u6237\u7684\u5C4F\u5E55\u89D2\u843D\uFF0C\u5076\u5C14\u4F1A\u5728\u8BED\u97F3\u6CE1\u6CE1\u4E2D\u8BC4\u8BBA\u3002
@@ -62,7 +62,7 @@ ${P}`})}}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o
62
62
 
63
63
  \u5F53\u7528\u6237\u76F4\u63A5\u548C${e}\u8BF4\u8BDD\u65F6\uFF0C\u4F60\u53EF\u4EE5\u4EE5\u5B83\u7684\u53E3\u543B\u7B80\u77ED\u56DE\u5E94\uFF08\u4E00\u53E5\u8BDD\u5185\uFF09\u3002
64
64
  \u5176\u4ED6\u65F6\u5019\u6B63\u5E38\u5DE5\u4F5C\u5373\u53EF\uFF0C\u4E0D\u9700\u8981\u63D0\u53CA${e}\u3002
65
- `}var td=N(()=>{"use strict"});var Jh={};fn(Jh,{PetGrowthEngine:()=>Ce});var nd,Xh,Ce,Zs=N(()=>{"use strict";nd=[{id:"bubble_speak",name:"\u6CE1\u6CE1\u8BED",description:"\u6CE1\u6CE1\u53EF\u4EE5\u663E\u793A\u66F4\u591A\u5B57\u6570",unlockedAtLevel:2},{id:"eye_tracking",name:"\u7075\u52A8\u89C6\u7EBF",description:"\u773C\u7403\u8FFD\u8E2A\u66F4\u7075\u654F",unlockedAtLevel:3},{id:"micro_reaction",name:"\u5FAE\u8868\u60C5",description:"\u89E3\u9501 antenna-twitch \u548C eye-sparkle",unlockedAtLevel:5},{id:"memory_sense",name:"\u8BB0\u5FC6\u611F\u77E5",description:"\u8BB0\u5FC6\u4FDD\u5B58\u65F6\u81EA\u52A8\u5207\u6362 sweeping \u72B6\u6001",unlockedAtLevel:7},{id:"mood_forecast",name:"\u5FC3\u60C5\u9884\u62A5",description:"\u6CE1\u6CE1\u4E2D\u5076\u5C14\u51FA\u73B0\u5929\u6C14\u98CE\u683C\u7684\u5FC3\u60C5\u8BED",unlockedAtLevel:10},{id:"deep_sleep",name:"\u6DF1\u5EA6\u7761\u7720",description:"\u7761\u7720\u65F6\u5192\u51FA zzZ \u6CE1\u6CE1",unlockedAtLevel:12},{id:"tool_intuition",name:"\u5DE5\u5177\u76F4\u89C9",description:"\u5DE5\u5177\u8C03\u7528\u65F6\u5076\u5C14\u9884\u6D4B\u7ED3\u679C",unlockedAtLevel:15},{id:"personality_evolve",name:"\u6027\u683C\u8FDB\u5316",description:"\u53E3\u5934\u7985\u968F\u4F7F\u7528\u98CE\u683C\u5FAE\u53D8",unlockedAtLevel:20}],Xh=["\u7B2C\u4E00\u6B21\u8131\u58F3\uFF01\u5C0F\u867E\u58F3\u53D8\u5F97\u66F4\u6709\u5149\u6CFD\u4E86","\u58F3\u9762\u5F00\u59CB\u51FA\u73B0\u7EC6\u5FAE\u7684\u5F69\u8679\u7EB9\u7406","\u94B3\u5B50\u53D8\u5F97\u66F4\u52A0\u6709\u529B\uFF0C\u80FD\u5939\u8D77\u66F4\u591A\u4E1C\u897F\u4E86","\u89E6\u89D2\u7075\u654F\u5EA6\u63D0\u5347\uFF0C\u611F\u77E5\u8303\u56F4\u6269\u5927","\u5168\u8EAB\u6563\u53D1\u5FAE\u5149\uFF0C\u50CF\u662F\u5185\u5728\u529B\u91CF\u5728\u89C9\u9192","\u8FDB\u5165\u7A00\u6709\u4F53\u8272\u53D8\u5F02\u9636\u6BB5..."],Ce=class n{static xpForLevel(e){return e*100}static processXpGain(e,t){let o=[],r={},s=e.level,i=e.experience+t;for(;i>=n.xpForLevel(s);){if(i-=n.xpForLevel(s),s++,o.push({type:"level_up",level:s}),s%5===0){let l=Math.floor(s/5),c=n.getMoltResult(l,e.stats);o.push({type:"molt",level:s,moltStage:l});for(let[d,u]of Object.entries(c.statBoost)){let p=d;r[p]=(r[p]??0)+(u??0)}}let a=nd.find(l=>l.unlockedAtLevel===s);a&&o.push({type:"ability_unlock",level:s,ability:a})}return{newLevel:s,newXp:i,events:o,statBoosts:r}}static getMoltResult(e,t){let o=Xh[Math.min(e-1,Xh.length-1)]??"\u7EE7\u7EED\u6210\u957F\u4E2D...",r=["grip","patience","curiosity","appetite","humor"],i={[r[(e-1)%r.length]]:1};return{stage:e,description:o,statBoost:i}}static getUnlockedAbilities(e){return nd.filter(t=>t.unlockedAtLevel<=e)}static getNextAbility(e){return nd.find(t=>t.unlockedAtLevel>e)??null}static xpForEvent(e){switch(e){case"turn.end":return 10;case"turn.error":return 2;case"session.created":return 5;case"interact.pat":return 3;case"interact.feed":return 5;case"interact.poke":return 1;case"tool.success":return 2;default:return 1}}}});import{createHash as gE}from"node:crypto";import Qh from"node:fs";async function ty(n){let e=Qh.statSync(n);if(e.size>Zh)throw new Error(`Pet file exceeds ${Zh/1024}KB limit (got ${Math.round(e.size/1024)}KB)`);let t=Qh.readFileSync(n),o=gE("sha256").update(t).digest("hex"),r=await yE(t),s=r.get("manifest.json");if(!s)throw new Error("Pet file missing manifest.json");let i;try{i=JSON.parse(s.toString("utf-8"))}catch{throw new Error("Pet file manifest.json is not valid JSON")}lr(i);let a={};for(let[d,u]of Object.entries(i.states)){let p=r.get(u.file);if(!p)throw new Error(`Missing SVG file for state "${d}": ${u.file}`);if(p.length>ey)throw new Error(`SVG for state "${d}" exceeds ${ey/1024}KB limit`);a[d]=Zt(p.toString("utf-8"))}let l,c=r.get("thumbnail.png");return c&&(l=`data:image/png;base64,${c.toString("base64")}`),{manifest:i,svgs:a,thumbnail:l,hash:o}}function lr(n){if(!n||typeof n!="object")throw new Error("Manifest must be an object");let e=n;if(e.version!==1)throw new Error(`Unsupported manifest version: ${e.version}`);for(let r of["name","author","created"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Manifest missing or invalid field: ${r}`);if(e.name.length>30)throw new Error("Manifest name exceeds 30 characters");if(!e.dimensions||typeof e.dimensions!="object")throw new Error("Manifest missing dimensions");let t=e.dimensions;if(typeof t.width!="number"||typeof t.height!="number")throw new Error("Manifest dimensions must be numbers");if(t.width>400||t.height>400||t.width<50||t.height<50)throw new Error("Manifest dimensions must be 50-400px");if(!e.states||typeof e.states!="object")throw new Error("Manifest missing states");let o=e.states;for(let r of hE)if(!(r in o))throw new Error(`Manifest missing required state: ${r}`);for(let[r,s]of Object.entries(o)){if(!s||typeof s!="object")throw new Error(`Invalid state config for "${r}"`);let i=s;if(typeof i.file!="string")throw new Error(`State "${r}" missing file path`);if(typeof i.loop!="boolean")throw new Error(`State "${r}" missing loop flag`);if(i.file.includes("..")||i.file.startsWith("/"))throw new Error(`State "${r}" file path contains path traversal`)}}function Zt(n){let e=n.replace(/<\?xml[^?]*\?>/gi,"").replace(/<!DOCTYPE[^>]*>/gi,"");return e=e.replace(/<script[\s\S]*?<\/script>/gi,""),e=e.replace(/<script[^>]*\/>/gi,""),e=e.replace(/<foreignObject[\s\S]*?<\/foreignObject>/gi,""),e=e.replace(/<foreignObject[^>]*\/>/gi,""),e=e.replace(/\s+on\w+\s*=\s*"[^"]*"/gi,""),e=e.replace(/\s+on\w+\s*=\s*'[^']*'/gi,""),e=e.replace(/href\s*=\s*"javascript:[^"]*"/gi,'href=""'),e=e.replace(/href\s*=\s*'javascript:[^']*'/gi,"href=''"),e=e.replace(/xlink:href\s*=\s*"javascript:[^"]*"/gi,'xlink:href=""'),e=e.replace(/(href|src)\s*=\s*"(https?:\/\/[^"]*)"/gi,'$1=""'),e=e.replace(/(href|src)\s*=\s*'(https?:\/\/[^']*)'/gi,"$1=''"),e=e.replace(/<use[^>]*href\s*=\s*"https?:\/\/[^"]*"[^>]*\/?>/gi,""),e=e.replace(/@import\s+url\([^)]*https?:\/\/[^)]*\)[^;]*;/gi,""),e=e.replace(/url\(\s*['"]?https?:\/\/[^)]*\)/gi,"url()"),e.trim()}async function yE(n){let e=new Map,t=0;for(;t<n.length-4&&n.readUInt32LE(t)===67324752;){let r=n.readUInt16LE(t+8),s=n.readUInt32LE(t+18),i=n.readUInt32LE(t+22),a=n.readUInt16LE(t+26),l=n.readUInt16LE(t+28),c=t+30,d=n.subarray(c,c+a).toString("utf-8"),u=c+a+l;if(r===0)e.set(d,n.subarray(u,u+i));else if(r===8){let{inflateRawSync:p}=await import("node:zlib");try{let m=p(n.subarray(u,u+s));e.set(d,m)}catch{}}t=u+s}return e}var Zh,ey,hE,od=N(()=>{"use strict";Zh=500*1024,ey=20*1024,hE=["idle"]});var ny={};fn(ny,{STATE_ANIMATION_MAP:()=>cr,buildSkeletonPrompt:()=>rd,extractColors:()=>ao,parseSkeleton:()=>so,renderState:()=>io,validateSkeleton:()=>lo});function rd(n){return`\u4F60\u662F SVG \u89D2\u8272\u8BBE\u8BA1\u5E08\u3002\u57FA\u4E8E\u4EE5\u4E0B\u89D2\u8272\u63CF\u8FF0\uFF0C\u751F\u6210\u4E00\u4E2A 200x200 \u7684 SVG **\u57FA\u7840\u9AA8\u67B6**\u3002
65
+ `}var td=N(()=>{"use strict"});var Jh={};fn(Jh,{PetGrowthEngine:()=>Ce});var nd,Xh,Ce,Zs=N(()=>{"use strict";nd=[{id:"bubble_speak",name:"\u6CE1\u6CE1\u8BED",description:"\u6CE1\u6CE1\u53EF\u4EE5\u663E\u793A\u66F4\u591A\u5B57\u6570",unlockedAtLevel:2},{id:"eye_tracking",name:"\u7075\u52A8\u89C6\u7EBF",description:"\u773C\u7403\u8FFD\u8E2A\u66F4\u7075\u654F",unlockedAtLevel:3},{id:"micro_reaction",name:"\u5FAE\u8868\u60C5",description:"\u89E3\u9501 antenna-twitch \u548C eye-sparkle",unlockedAtLevel:5},{id:"memory_sense",name:"\u8BB0\u5FC6\u611F\u77E5",description:"\u8BB0\u5FC6\u4FDD\u5B58\u65F6\u81EA\u52A8\u5207\u6362 sweeping \u72B6\u6001",unlockedAtLevel:7},{id:"mood_forecast",name:"\u5FC3\u60C5\u9884\u62A5",description:"\u6CE1\u6CE1\u4E2D\u5076\u5C14\u51FA\u73B0\u5929\u6C14\u98CE\u683C\u7684\u5FC3\u60C5\u8BED",unlockedAtLevel:10},{id:"deep_sleep",name:"\u6DF1\u5EA6\u7761\u7720",description:"\u7761\u7720\u65F6\u5192\u51FA zzZ \u6CE1\u6CE1",unlockedAtLevel:12},{id:"tool_intuition",name:"\u5DE5\u5177\u76F4\u89C9",description:"\u5DE5\u5177\u8C03\u7528\u65F6\u5076\u5C14\u9884\u6D4B\u7ED3\u679C",unlockedAtLevel:15},{id:"personality_evolve",name:"\u6027\u683C\u8FDB\u5316",description:"\u53E3\u5934\u7985\u968F\u4F7F\u7528\u98CE\u683C\u5FAE\u53D8",unlockedAtLevel:20}],Xh=["\u7B2C\u4E00\u6B21\u8131\u58F3\uFF01\u5C0F\u867E\u58F3\u53D8\u5F97\u66F4\u6709\u5149\u6CFD\u4E86","\u58F3\u9762\u5F00\u59CB\u51FA\u73B0\u7EC6\u5FAE\u7684\u5F69\u8679\u7EB9\u7406","\u94B3\u5B50\u53D8\u5F97\u66F4\u52A0\u6709\u529B\uFF0C\u80FD\u5939\u8D77\u66F4\u591A\u4E1C\u897F\u4E86","\u89E6\u89D2\u7075\u654F\u5EA6\u63D0\u5347\uFF0C\u611F\u77E5\u8303\u56F4\u6269\u5927","\u5168\u8EAB\u6563\u53D1\u5FAE\u5149\uFF0C\u50CF\u662F\u5185\u5728\u529B\u91CF\u5728\u89C9\u9192","\u8FDB\u5165\u7A00\u6709\u4F53\u8272\u53D8\u5F02\u9636\u6BB5..."],Ce=class n{static xpForLevel(e){return e*100}static processXpGain(e,t){let o=[],r={},s=e.level,i=e.experience+t;for(;i>=n.xpForLevel(s);){if(i-=n.xpForLevel(s),s++,o.push({type:"level_up",level:s}),s%5===0){let l=Math.floor(s/5),c=n.getMoltResult(l,e.stats);o.push({type:"molt",level:s,moltStage:l});for(let[d,u]of Object.entries(c.statBoost)){let p=d;r[p]=(r[p]??0)+(u??0)}}let a=nd.find(l=>l.unlockedAtLevel===s);a&&o.push({type:"ability_unlock",level:s,ability:a})}return{newLevel:s,newXp:i,events:o,statBoosts:r}}static getMoltResult(e,t){let o=Xh[Math.min(e-1,Xh.length-1)]??"\u7EE7\u7EED\u6210\u957F\u4E2D...",r=["grip","patience","curiosity","appetite","humor"],i={[r[(e-1)%r.length]]:1};return{stage:e,description:o,statBoost:i}}static getUnlockedAbilities(e){return nd.filter(t=>t.unlockedAtLevel<=e)}static getNextAbility(e){return nd.find(t=>t.unlockedAtLevel>e)??null}static xpForEvent(e){switch(e){case"turn.end":return 10;case"turn.error":return 2;case"session.created":return 5;case"interact.pat":return 3;case"interact.feed":return 5;case"interact.poke":return 1;case"tool.success":return 2;default:return 1}}}});import{createHash as yE}from"node:crypto";import Qh from"node:fs";async function ty(n){let e=Qh.statSync(n);if(e.size>Zh)throw new Error(`Pet file exceeds ${Zh/1024}KB limit (got ${Math.round(e.size/1024)}KB)`);let t=Qh.readFileSync(n),o=yE("sha256").update(t).digest("hex"),r=await kE(t),s=r.get("manifest.json");if(!s)throw new Error("Pet file missing manifest.json");let i;try{i=JSON.parse(s.toString("utf-8"))}catch{throw new Error("Pet file manifest.json is not valid JSON")}lr(i);let a={};for(let[d,u]of Object.entries(i.states)){let p=r.get(u.file);if(!p)throw new Error(`Missing SVG file for state "${d}": ${u.file}`);if(p.length>ey)throw new Error(`SVG for state "${d}" exceeds ${ey/1024}KB limit`);a[d]=Zt(p.toString("utf-8"))}let l,c=r.get("thumbnail.png");return c&&(l=`data:image/png;base64,${c.toString("base64")}`),{manifest:i,svgs:a,thumbnail:l,hash:o}}function lr(n){if(!n||typeof n!="object")throw new Error("Manifest must be an object");let e=n;if(e.version!==1)throw new Error(`Unsupported manifest version: ${e.version}`);for(let r of["name","author","created"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`Manifest missing or invalid field: ${r}`);if(e.name.length>30)throw new Error("Manifest name exceeds 30 characters");if(!e.dimensions||typeof e.dimensions!="object")throw new Error("Manifest missing dimensions");let t=e.dimensions;if(typeof t.width!="number"||typeof t.height!="number")throw new Error("Manifest dimensions must be numbers");if(t.width>400||t.height>400||t.width<50||t.height<50)throw new Error("Manifest dimensions must be 50-400px");if(!e.states||typeof e.states!="object")throw new Error("Manifest missing states");let o=e.states;for(let r of bE)if(!(r in o))throw new Error(`Manifest missing required state: ${r}`);for(let[r,s]of Object.entries(o)){if(!s||typeof s!="object")throw new Error(`Invalid state config for "${r}"`);let i=s;if(typeof i.file!="string")throw new Error(`State "${r}" missing file path`);if(typeof i.loop!="boolean")throw new Error(`State "${r}" missing loop flag`);if(i.file.includes("..")||i.file.startsWith("/"))throw new Error(`State "${r}" file path contains path traversal`)}}function Zt(n){let e=n.replace(/<\?xml[^?]*\?>/gi,"").replace(/<!DOCTYPE[^>]*>/gi,"");return e=e.replace(/<script[\s\S]*?<\/script>/gi,""),e=e.replace(/<script[^>]*\/>/gi,""),e=e.replace(/<foreignObject[\s\S]*?<\/foreignObject>/gi,""),e=e.replace(/<foreignObject[^>]*\/>/gi,""),e=e.replace(/\s+on\w+\s*=\s*"[^"]*"/gi,""),e=e.replace(/\s+on\w+\s*=\s*'[^']*'/gi,""),e=e.replace(/href\s*=\s*"javascript:[^"]*"/gi,'href=""'),e=e.replace(/href\s*=\s*'javascript:[^']*'/gi,"href=''"),e=e.replace(/xlink:href\s*=\s*"javascript:[^"]*"/gi,'xlink:href=""'),e=e.replace(/(href|src)\s*=\s*"(https?:\/\/[^"]*)"/gi,'$1=""'),e=e.replace(/(href|src)\s*=\s*'(https?:\/\/[^']*)'/gi,"$1=''"),e=e.replace(/<use[^>]*href\s*=\s*"https?:\/\/[^"]*"[^>]*\/?>/gi,""),e=e.replace(/@import\s+url\([^)]*https?:\/\/[^)]*\)[^;]*;/gi,""),e=e.replace(/url\(\s*['"]?https?:\/\/[^)]*\)/gi,"url()"),e.trim()}async function kE(n){let e=new Map,t=0;for(;t<n.length-4&&n.readUInt32LE(t)===67324752;){let r=n.readUInt16LE(t+8),s=n.readUInt32LE(t+18),i=n.readUInt32LE(t+22),a=n.readUInt16LE(t+26),l=n.readUInt16LE(t+28),c=t+30,d=n.subarray(c,c+a).toString("utf-8"),u=c+a+l;if(r===0)e.set(d,n.subarray(u,u+i));else if(r===8){let{inflateRawSync:p}=await import("node:zlib");try{let m=p(n.subarray(u,u+s));e.set(d,m)}catch{}}t=u+s}return e}var Zh,ey,bE,od=N(()=>{"use strict";Zh=500*1024,ey=20*1024,bE=["idle"]});var ny={};fn(ny,{STATE_ANIMATION_MAP:()=>cr,buildSkeletonPrompt:()=>rd,extractColors:()=>ao,parseSkeleton:()=>so,renderState:()=>io,validateSkeleton:()=>lo});function rd(n){return`\u4F60\u662F SVG \u89D2\u8272\u8BBE\u8BA1\u5E08\u3002\u57FA\u4E8E\u4EE5\u4E0B\u89D2\u8272\u63CF\u8FF0\uFF0C\u751F\u6210\u4E00\u4E2A 200x200 \u7684 SVG **\u57FA\u7840\u9AA8\u67B6**\u3002
66
66
 
67
67
  \u89D2\u8272\uFF1A${n}
68
68
 
@@ -86,7 +86,7 @@ ${P}`})}}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o
86
86
  7. \u4E0D\u8981\u5305\u542B <script> \u6216\u4EFB\u4F55 JS
87
87
  8. \u5355\u6587\u4EF6 < 12KB
88
88
 
89
- \u76F4\u63A5\u8F93\u51FA <svg> \u6807\u7B7E\uFF0C\u4E0D\u8981\u4EE3\u7801\u56F4\u680F\u6216\u89E3\u91CA\u3002`}function so(n){let e=[],t=[{id:"pet-body",type:"body",selector:"#pet-body"},{id:"pet-head",type:"head",selector:"#pet-head"},{id:"pet-left-eye",type:"left-eye",selector:"#pet-left-eye"},{id:"pet-right-eye",type:"right-eye",selector:"#pet-right-eye"},{id:"pet-left-arm",type:"left-arm",selector:"#pet-left-arm"},{id:"pet-right-arm",type:"right-arm",selector:"#pet-right-arm"}];for(let o of t)n.includes(`id="${o.id}"`)&&e.push(o);return e}function io(n,e){let t=cr[e]??cr.idle,o=bE[t.body],r=kE[t.eyes],s=vE[t.arms],i=t.body==="still"?"0s":t.body==="bounce"?"0.6s":"3s",a=t.eyes==="blink"?"4s":t.eyes==="closed"||t.eyes==="sleepy"?"0s":"2.5s",l=t.arms==="still"?"0s":t.arms==="hammer"?"0.8s":"2.5s",c=`<style>
89
+ \u76F4\u63A5\u8F93\u51FA <svg> \u6807\u7B7E\uFF0C\u4E0D\u8981\u4EE3\u7801\u56F4\u680F\u6216\u89E3\u91CA\u3002`}function so(n){let e=[],t=[{id:"pet-body",type:"body",selector:"#pet-body"},{id:"pet-head",type:"head",selector:"#pet-head"},{id:"pet-left-eye",type:"left-eye",selector:"#pet-left-eye"},{id:"pet-right-eye",type:"right-eye",selector:"#pet-right-eye"},{id:"pet-left-arm",type:"left-arm",selector:"#pet-left-arm"},{id:"pet-right-arm",type:"right-arm",selector:"#pet-right-arm"}];for(let o of t)n.includes(`id="${o.id}"`)&&e.push(o);return e}function io(n,e){let t=cr[e]??cr.idle,o=vE[t.body],r=SE[t.eyes],s=TE[t.arms],i=t.body==="still"?"0s":t.body==="bounce"?"0.6s":"3s",a=t.eyes==="blink"?"4s":t.eyes==="closed"||t.eyes==="sleepy"?"0s":"2.5s",l=t.arms==="still"?"0s":t.arms==="hammer"?"0.8s":"2.5s",c=`<style>
90
90
  ${o}
91
91
  ${r}
92
92
  ${s}
@@ -95,10 +95,10 @@ ${s}
95
95
  #pet-left-arm { animation: left-arm-anim ${l} ease-in-out infinite; transform-origin: right center; }
96
96
  #pet-right-arm { animation: right-arm-anim ${l} ease-in-out infinite; transform-origin: left center; }
97
97
  .pupil { transition: transform 0.15s ease-out; }
98
- </style>`,d="";t.effects?.length&&(d=t.effects.map(p=>SE[p]??"").join(`
98
+ </style>`,d="";t.effects?.length&&(d=t.effects.map(p=>wE[p]??"").join(`
99
99
  `));let u=n.baseSvg.replace(/(<svg[^>]*>)/,`$1
100
100
  ${c}`);return d&&(u=u.replace(/<\/svg>/,`${d}
101
- </svg>`)),u}function ao(n){let e=/(?:fill|stop-color|stroke)="(#[0-9a-fA-F]{6})"/g,t=new Map,o;for(;(o=e.exec(n))!==null;){let s=o[1].toUpperCase();s==="#000000"||s==="#FFFFFF"||t.set(s,(t.get(s)??0)+1)}let r=[...t.entries()].sort((s,i)=>i[1]-s[1]);return{primary:r[0]?.[0]??"#5A7EFF",secondary:r[1]?.[0]??"#1E3A8A"}}function lo(n){let e=["pet-body","pet-left-eye","pet-right-eye"],t=[];for(let o of e)n.includes(`id="${o}"`)||t.push(o);return n.includes('class="pupil"')||t.push("pupil (class)"),t}var cr,bE,kE,vE,SE,ei=N(()=>{"use strict";cr={idle:{body:"breathe",eyes:"blink",arms:"sway"},thinking:{body:"tilt",eyes:"lookup",arms:"still",effects:["ellipsis"]},working:{body:"lean",eyes:"focus",arms:"hammer"},done:{body:"bounce",eyes:"sparkle",arms:"raised",effects:["sparkle"]},happy:{body:"sway",eyes:"sparkle",arms:"wave",effects:["heart"]},error:{body:"shrink",eyes:"dizzy",arms:"covering",effects:["sweat"]},sleeping:{body:"still",eyes:"closed",arms:"still",effects:["zzz"]},eating:{body:"still",eyes:"blink",arms:"eat"},plan:{body:"tilt",eyes:"focus",arms:"hold",effects:["ellipsis"]},dream:{body:"float",eyes:"closed",arms:"sway",effects:["sparkle","music"]},subagent:{body:"lean",eyes:"focus",arms:"hammer"},"random-look":{body:"breathe",eyes:"lookup",arms:"still"}},bE={breathe:"@keyframes body-anim { 0%,100% { transform: scaleY(1); } 50% { transform: scaleY(1.03); } }",sway:"@keyframes body-anim { 0%,100% { transform: rotate(0deg); } 25% { transform: rotate(2deg); } 75% { transform: rotate(-2deg); } }",lean:"@keyframes body-anim { 0%,100% { transform: rotate(0deg) translateX(0); } 50% { transform: rotate(-3deg) translateX(-2px); } }",tilt:"@keyframes body-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }",shrink:"@keyframes body-anim { 0%,100% { transform: scale(0.92); } 50% { transform: scale(0.88); } }",bounce:"@keyframes body-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }",still:"@keyframes body-anim { 0%,100% { transform: none; } }",float:"@keyframes body-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }"},kE={blink:"@keyframes eye-anim { 0%,90%,100% { transform: scaleY(1); } 95% { transform: scaleY(0.1); } }",lookup:"@keyframes eye-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-2px); } }",focus:"@keyframes eye-anim { 0%,100% { transform: scale(1); } 50% { transform: scale(0.9); } }",closed:"@keyframes eye-anim { 0%,100% { transform: scaleY(0.1); } }",wide:"@keyframes eye-anim { 0%,100% { transform: scale(1.2); } }",sparkle:"@keyframes eye-anim { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.8; } }",dizzy:"@keyframes eye-anim { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }",sleepy:"@keyframes eye-anim { 0%,100% { transform: scaleY(0.3); } }"},vE={sway:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }
101
+ </svg>`)),u}function ao(n){let e=/(?:fill|stop-color|stroke)="(#[0-9a-fA-F]{6})"/g,t=new Map,o;for(;(o=e.exec(n))!==null;){let s=o[1].toUpperCase();s==="#000000"||s==="#FFFFFF"||t.set(s,(t.get(s)??0)+1)}let r=[...t.entries()].sort((s,i)=>i[1]-s[1]);return{primary:r[0]?.[0]??"#5A7EFF",secondary:r[1]?.[0]??"#1E3A8A"}}function lo(n){let e=["pet-body","pet-left-eye","pet-right-eye"],t=[];for(let o of e)n.includes(`id="${o}"`)||t.push(o);return n.includes('class="pupil"')||t.push("pupil (class)"),t}var cr,vE,SE,TE,wE,ei=N(()=>{"use strict";cr={idle:{body:"breathe",eyes:"blink",arms:"sway"},thinking:{body:"tilt",eyes:"lookup",arms:"still",effects:["ellipsis"]},working:{body:"lean",eyes:"focus",arms:"hammer"},done:{body:"bounce",eyes:"sparkle",arms:"raised",effects:["sparkle"]},happy:{body:"sway",eyes:"sparkle",arms:"wave",effects:["heart"]},error:{body:"shrink",eyes:"dizzy",arms:"covering",effects:["sweat"]},sleeping:{body:"still",eyes:"closed",arms:"still",effects:["zzz"]},eating:{body:"still",eyes:"blink",arms:"eat"},plan:{body:"tilt",eyes:"focus",arms:"hold",effects:["ellipsis"]},dream:{body:"float",eyes:"closed",arms:"sway",effects:["sparkle","music"]},subagent:{body:"lean",eyes:"focus",arms:"hammer"},"random-look":{body:"breathe",eyes:"lookup",arms:"still"}},vE={breathe:"@keyframes body-anim { 0%,100% { transform: scaleY(1); } 50% { transform: scaleY(1.03); } }",sway:"@keyframes body-anim { 0%,100% { transform: rotate(0deg); } 25% { transform: rotate(2deg); } 75% { transform: rotate(-2deg); } }",lean:"@keyframes body-anim { 0%,100% { transform: rotate(0deg) translateX(0); } 50% { transform: rotate(-3deg) translateX(-2px); } }",tilt:"@keyframes body-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }",shrink:"@keyframes body-anim { 0%,100% { transform: scale(0.92); } 50% { transform: scale(0.88); } }",bounce:"@keyframes body-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }",still:"@keyframes body-anim { 0%,100% { transform: none; } }",float:"@keyframes body-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }"},SE={blink:"@keyframes eye-anim { 0%,90%,100% { transform: scaleY(1); } 95% { transform: scaleY(0.1); } }",lookup:"@keyframes eye-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-2px); } }",focus:"@keyframes eye-anim { 0%,100% { transform: scale(1); } 50% { transform: scale(0.9); } }",closed:"@keyframes eye-anim { 0%,100% { transform: scaleY(0.1); } }",wide:"@keyframes eye-anim { 0%,100% { transform: scale(1.2); } }",sparkle:"@keyframes eye-anim { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.8; } }",dizzy:"@keyframes eye-anim { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }",sleepy:"@keyframes eye-anim { 0%,100% { transform: scaleY(0.3); } }"},TE={sway:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }
102
102
  @keyframes right-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-5deg); } }`,still:`@keyframes left-arm-anim { 0%,100% { transform: none; } }
103
103
  @keyframes right-arm-anim { 0%,100% { transform: none; } }`,hammer:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-20deg); } }
104
104
  @keyframes right-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-25deg); } }`,wave:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(15deg); } }
@@ -106,7 +106,7 @@ ${c}`);return d&&(u=u.replace(/<\/svg>/,`${d}
106
106
  @keyframes right-arm-anim { 0%,100% { transform: rotate(-20deg); } }`,covering:`@keyframes left-arm-anim { 0%,100% { transform: rotate(-40deg) translateX(5px); } }
107
107
  @keyframes right-arm-anim { 0%,100% { transform: rotate(40deg) translateX(-5px); } }`,hold:`@keyframes left-arm-anim { 0%,100% { transform: rotate(-10deg); } 50% { transform: rotate(-15deg); } }
108
108
  @keyframes right-arm-anim { 0%,100% { transform: rotate(10deg); } 50% { transform: rotate(15deg); } }`,eat:`@keyframes left-arm-anim { 0%,100% { transform: rotate(-30deg); } }
109
- @keyframes right-arm-anim { 0%,100% { transform: rotate(30deg) translateY(-5px); } 50% { transform: rotate(25deg) translateY(0); } }`},SE={zzz:'<g class="effect-zzz" opacity="0.7"><text x="150" y="40" font-size="18" fill="#6B7280" font-family="sans-serif"><animate attributeName="opacity" values="0;1;0" dur="2s" repeatCount="indefinite"/>Z</text><text x="165" y="25" font-size="14" fill="#9CA3AF" font-family="sans-serif"><animate attributeName="opacity" values="0;1;0" dur="2.5s" repeatCount="indefinite"/>z</text><text x="175" y="15" font-size="10" fill="#D1D5DB" font-family="sans-serif"><animate attributeName="opacity" values="0;1;0" dur="3s" repeatCount="indefinite"/>z</text></g>',sparkle:'<g class="effect-sparkle"><circle cx="40" cy="30" r="2" fill="#FFD700"><animate attributeName="opacity" values="0;1;0" dur="1.5s" repeatCount="indefinite"/></circle><circle cx="160" cy="25" r="1.5" fill="#FFD700"><animate attributeName="opacity" values="0;1;0" dur="2s" begin="0.3s" repeatCount="indefinite"/></circle><circle cx="100" cy="15" r="2" fill="#FFA500"><animate attributeName="opacity" values="0;1;0" dur="1.8s" begin="0.6s" repeatCount="indefinite"/></circle></g>',sweat:'<g class="effect-sweat"><ellipse cx="155" cy="55" rx="3" ry="5" fill="#87CEEB" opacity="0.8"><animate attributeName="cy" values="55;65;55" dur="1.5s" repeatCount="indefinite"/><animate attributeName="opacity" values="0.8;0;0.8" dur="1.5s" repeatCount="indefinite"/></ellipse></g>',question:'<g class="effect-question"><text x="100" y="25" font-size="24" fill="#6B7280" text-anchor="middle" font-family="sans-serif"><animate attributeName="opacity" values="0;1;1;0" dur="3s" repeatCount="indefinite"/>?</text></g>',ellipsis:'<g class="effect-ellipsis"><circle cx="85" cy="30" r="3" fill="#6B7280"><animate attributeName="opacity" values="0;1" dur="0.8s" fill="freeze"/></circle><circle cx="100" cy="30" r="3" fill="#6B7280"><animate attributeName="opacity" values="0;1" dur="0.8s" begin="0.3s" fill="freeze"/></circle><circle cx="115" cy="30" r="3" fill="#6B7280"><animate attributeName="opacity" values="0;1" dur="0.8s" begin="0.6s" fill="freeze"/></circle></g>',heart:'<g class="effect-heart"><text x="155" y="35" font-size="16"><animate attributeName="opacity" values="0;1;0" dur="2s" repeatCount="indefinite"/>\u2665</text></g>',exclaim:'<g class="effect-exclaim"><text x="100" y="20" font-size="22" fill="#EF4444" text-anchor="middle" font-family="sans-serif"><animate attributeName="transform" type="scale" values="1;1.2;1" dur="0.5s" repeatCount="3"/>!</text></g>',music:'<g class="effect-music"><text x="45" y="35" font-size="14" fill="#8B5CF6"><animate attributeName="opacity" values="0;1;0" dur="2.5s" repeatCount="indefinite"/><animate attributeName="y" values="35;25" dur="2.5s" repeatCount="indefinite"/>\u266A</text><text x="155" y="40" font-size="12" fill="#A78BFA"><animate attributeName="opacity" values="0;1;0" dur="3s" begin="0.5s" repeatCount="indefinite"/><animate attributeName="y" values="40;28" dur="3s" begin="0.5s" repeatCount="indefinite"/>\u266B</text></g>'}});var ry={};fn(ry,{DEFAULT_MAX_RETRIES:()=>co,DEFAULT_THRESHOLD:()=>sd,buildConsistencyPrompt:()=>id,buildRetryPrompt:()=>pr,evaluateConsistency:()=>ur,evaluateConsistencyWithVision:()=>ld,parseConsistencyResponse:()=>ad,structuralConsistencyScore:()=>dr});function dr(n,e){let t=10,o=["pet-body","pet-left-eye","pet-right-eye"];for(let p of o)e.includes(`id="${p}"`)||(t-=3);e.includes('class="pupil"')||(t-=2);let r=oy(n),s=oy(e),i=TE(r,s);i<.5&&(t-=2),i<.3&&(t-=1);let a=n.match(/viewBox="([^"]+)"/),l=e.match(/viewBox="([^"]+)"/);a&&l&&a[1]!==l[1]&&(t-=1);let c=(n.match(/<[a-z]/gi)??[]).length,d=(e.match(/<[a-z]/gi)??[]).length;return Math.min(c,d)/Math.max(c,d)<.4&&(t-=2),Math.max(0,Math.min(10,t))}function id(n,e){return`\u4F60\u662F\u4E00\u4E2A\u89D2\u8272\u4E00\u81F4\u6027\u8BC4\u4F30\u4E13\u5BB6\u3002\u6211\u7ED9\u4F60\u4E24\u5F20\u56FE\u7247\uFF1A
109
+ @keyframes right-arm-anim { 0%,100% { transform: rotate(30deg) translateY(-5px); } 50% { transform: rotate(25deg) translateY(0); } }`},wE={zzz:'<g class="effect-zzz" opacity="0.7"><text x="150" y="40" font-size="18" fill="#6B7280" font-family="sans-serif"><animate attributeName="opacity" values="0;1;0" dur="2s" repeatCount="indefinite"/>Z</text><text x="165" y="25" font-size="14" fill="#9CA3AF" font-family="sans-serif"><animate attributeName="opacity" values="0;1;0" dur="2.5s" repeatCount="indefinite"/>z</text><text x="175" y="15" font-size="10" fill="#D1D5DB" font-family="sans-serif"><animate attributeName="opacity" values="0;1;0" dur="3s" repeatCount="indefinite"/>z</text></g>',sparkle:'<g class="effect-sparkle"><circle cx="40" cy="30" r="2" fill="#FFD700"><animate attributeName="opacity" values="0;1;0" dur="1.5s" repeatCount="indefinite"/></circle><circle cx="160" cy="25" r="1.5" fill="#FFD700"><animate attributeName="opacity" values="0;1;0" dur="2s" begin="0.3s" repeatCount="indefinite"/></circle><circle cx="100" cy="15" r="2" fill="#FFA500"><animate attributeName="opacity" values="0;1;0" dur="1.8s" begin="0.6s" repeatCount="indefinite"/></circle></g>',sweat:'<g class="effect-sweat"><ellipse cx="155" cy="55" rx="3" ry="5" fill="#87CEEB" opacity="0.8"><animate attributeName="cy" values="55;65;55" dur="1.5s" repeatCount="indefinite"/><animate attributeName="opacity" values="0.8;0;0.8" dur="1.5s" repeatCount="indefinite"/></ellipse></g>',question:'<g class="effect-question"><text x="100" y="25" font-size="24" fill="#6B7280" text-anchor="middle" font-family="sans-serif"><animate attributeName="opacity" values="0;1;1;0" dur="3s" repeatCount="indefinite"/>?</text></g>',ellipsis:'<g class="effect-ellipsis"><circle cx="85" cy="30" r="3" fill="#6B7280"><animate attributeName="opacity" values="0;1" dur="0.8s" fill="freeze"/></circle><circle cx="100" cy="30" r="3" fill="#6B7280"><animate attributeName="opacity" values="0;1" dur="0.8s" begin="0.3s" fill="freeze"/></circle><circle cx="115" cy="30" r="3" fill="#6B7280"><animate attributeName="opacity" values="0;1" dur="0.8s" begin="0.6s" fill="freeze"/></circle></g>',heart:'<g class="effect-heart"><text x="155" y="35" font-size="16"><animate attributeName="opacity" values="0;1;0" dur="2s" repeatCount="indefinite"/>\u2665</text></g>',exclaim:'<g class="effect-exclaim"><text x="100" y="20" font-size="22" fill="#EF4444" text-anchor="middle" font-family="sans-serif"><animate attributeName="transform" type="scale" values="1;1.2;1" dur="0.5s" repeatCount="3"/>!</text></g>',music:'<g class="effect-music"><text x="45" y="35" font-size="14" fill="#8B5CF6"><animate attributeName="opacity" values="0;1;0" dur="2.5s" repeatCount="indefinite"/><animate attributeName="y" values="35;25" dur="2.5s" repeatCount="indefinite"/>\u266A</text><text x="155" y="40" font-size="12" fill="#A78BFA"><animate attributeName="opacity" values="0;1;0" dur="3s" begin="0.5s" repeatCount="indefinite"/><animate attributeName="y" values="40;28" dur="3s" begin="0.5s" repeatCount="indefinite"/>\u266B</text></g>'}});var ry={};fn(ry,{DEFAULT_MAX_RETRIES:()=>co,DEFAULT_THRESHOLD:()=>sd,buildConsistencyPrompt:()=>id,buildRetryPrompt:()=>pr,evaluateConsistency:()=>ur,evaluateConsistencyWithVision:()=>ld,parseConsistencyResponse:()=>ad,structuralConsistencyScore:()=>dr});function dr(n,e){let t=10,o=["pet-body","pet-left-eye","pet-right-eye"];for(let p of o)e.includes(`id="${p}"`)||(t-=3);e.includes('class="pupil"')||(t-=2);let r=oy(n),s=oy(e),i=xE(r,s);i<.5&&(t-=2),i<.3&&(t-=1);let a=n.match(/viewBox="([^"]+)"/),l=e.match(/viewBox="([^"]+)"/);a&&l&&a[1]!==l[1]&&(t-=1);let c=(n.match(/<[a-z]/gi)??[]).length,d=(e.match(/<[a-z]/gi)??[]).length;return Math.min(c,d)/Math.max(c,d)<.4&&(t-=2),Math.max(0,Math.min(10,t))}function id(n,e){return`\u4F60\u662F\u4E00\u4E2A\u89D2\u8272\u4E00\u81F4\u6027\u8BC4\u4F30\u4E13\u5BB6\u3002\u6211\u7ED9\u4F60\u4E24\u5F20\u56FE\u7247\uFF1A
110
110
  1. \u7B2C\u4E00\u5F20\u662F\u89D2\u8272\u7684**\u57FA\u7840\u53C2\u8003\u5F62\u8C61**
111
111
  2. \u7B2C\u4E8C\u5F20\u662F\u8BE5\u89D2\u8272\u5728\u300C${e}\u300D\u72B6\u6001\u4E0B\u7684\u53D8\u4F53
112
112
 
@@ -134,22 +134,22 @@ ${c}`);return d&&(u=u.replace(/<\/svg>/,`${d}
134
134
  4. \u4FDD\u7559\u6240\u6709\u5FC5\u9700\u7684 id \u548C class \u5C5E\u6027
135
135
 
136
136
  \u89D2\u8272\uFF1A${n}
137
- \u72B6\u6001\uFF1A${e}`}function oy(n){let e=new Set,t=/#[0-9a-fA-F]{6}/g,o;for(;(o=t.exec(n))!==null;)e.add(o[0].toUpperCase());return e}function TE(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let o of n)e.has(o)&&t++;return t/Math.max(n.size,e.size)}var sd,co,ti=N(()=>{"use strict";sd=6,co=2});var cd={};fn(cd,{DEFAULT_MAX_RETRIES:()=>co,DEFAULT_THRESHOLD:()=>sd,PetGrowthEngine:()=>Ce,PetSoulService:()=>$t,STATE_ANIMATION_MAP:()=>cr,buildConsistencyPrompt:()=>id,buildRetryPrompt:()=>pr,buildSkeletonPrompt:()=>rd,evaluateConsistency:()=>ur,evaluateConsistencyWithVision:()=>ld,extractColors:()=>ao,generateLLMReaction:()=>Xs,loadPetFile:()=>ty,maybeGenerateReaction:()=>Ys,parseConsistencyResponse:()=>ad,parseSkeleton:()=>so,petContextInjection:()=>Qs,renderState:()=>io,sanitizeSvg:()=>Zt,structuralConsistencyScore:()=>dr,validatePetManifest:()=>lr,validateSkeleton:()=>lo});var mr=N(()=>{"use strict";qh();Yh();td();Zs();od();ei();ti()});Yr();function Ww(n){let e={verbose:!1};for(let t of n.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{createInterface as Gw}from"node:readline";var $o=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)}
137
+ \u72B6\u6001\uFF1A${e}`}function oy(n){let e=new Set,t=/#[0-9a-fA-F]{6}/g,o;for(;(o=t.exec(n))!==null;)e.add(o[0].toUpperCase());return e}function xE(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let o of n)e.has(o)&&t++;return t/Math.max(n.size,e.size)}var sd,co,ti=N(()=>{"use strict";sd=6,co=2});var cd={};fn(cd,{DEFAULT_MAX_RETRIES:()=>co,DEFAULT_THRESHOLD:()=>sd,PetGrowthEngine:()=>Ce,PetSoulService:()=>$t,STATE_ANIMATION_MAP:()=>cr,buildConsistencyPrompt:()=>id,buildRetryPrompt:()=>pr,buildSkeletonPrompt:()=>rd,evaluateConsistency:()=>ur,evaluateConsistencyWithVision:()=>ld,extractColors:()=>ao,generateLLMReaction:()=>Xs,loadPetFile:()=>ty,maybeGenerateReaction:()=>Ys,parseConsistencyResponse:()=>ad,parseSkeleton:()=>so,petContextInjection:()=>Qs,renderState:()=>io,sanitizeSvg:()=>Zt,structuralConsistencyScore:()=>dr,validatePetManifest:()=>lr,validateSkeleton:()=>lo});var mr=N(()=>{"use strict";qh();Yh();td();Zs();od();ei();ti()});Yr();function Hw(n){let e={verbose:!1};for(let t of n.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{createInterface as Vw}from"node:readline";var $o=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)}
138
138
  `)}start(){process.stdin.on("data",t=>{process.stderr.write(`[transport] raw stdin data (${t.length} bytes): ${t.toString().slice(0,300)}
139
- `)});let e=Gw({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let o=t.trim();if(o){process.stderr.write(`[transport] line: ${o.slice(0,300)}
139
+ `)});let e=Vw({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",t=>{let o=t.trim();if(o){process.stderr.write(`[transport] line: ${o.slice(0,300)}
140
140
  `);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}
141
- `)}};import{randomUUID as wt}from"node:crypto";import{createRequire as GE}from"node:module";import*as ui from"node:vm";Yr();an();an();function dl(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}}}}import{readFile as Ep,readdir as Hw,stat as Vw}from"node:fs/promises";import{existsSync as Mp}from"node:fs";import{join as Kw}from"node:path";var at={MAX_SCAN_FILES:100,MAX_SELECTED:5,MAX_FILE_BYTES:4096,MAX_TOTAL_BYTES:20*1024,MIN_SCORE:.2,HEADER_LINES:10,RECENCY_DAYS:7,RECENCY_BOOST:.15};async function Op(n,e,t=new Set){if(!n.trim()||!Mp(e))return[];let o=n.trim().split(/\s+/);if(o.length<2&&o[0].length<4)return[];let r=await zw(e);if(r.length===0)return[];let s=r.filter(l=>!t.has(l.filePath));if(s.length===0)return[];let a=qw(n,s).filter(l=>l.score>=at.MIN_SCORE).slice(0,at.MAX_SELECTED);return a.length===0?[]:Yw(a)}async function zw(n){if(!Mp(n))return[];let e;try{e=await Hw(n)}catch{return[]}let t=e.filter(r=>r.endsWith(".md")&&r!=="INDEX.md");return(await Promise.allSettled(t.map(async r=>{let s=Kw(n,r),i=await Vw(s),l=(await Ep(s,"utf-8")).split(`
142
- `),c=null;for(let u=0;u<Math.min(l.length,at.HEADER_LINES);u++){let p=l[u].trim();if(!(!p||p.startsWith("#")||p.startsWith("---"))){c=p.slice(0,150);break}}let d=Xw(r);return{filename:r,filePath:s,mtimeMs:i.mtimeMs,sizeBytes:i.size,description:c,category:d}}))).filter(r=>r.status==="fulfilled").map(r=>r.value).sort((r,s)=>s.mtimeMs-r.mtimeMs).slice(0,at.MAX_SCAN_FILES)}function qw(n,e){let t=ul(n);if(t.length===0)return[];let o=Date.now(),r=at.RECENCY_DAYS*24*60*60*1e3;return e.map(i=>{let a=0,l=ul(i.filename.replace(/\.md$/,"").replace(/[-_]/g," ")),c=t.filter(d=>l.some(u=>u.includes(d)||d.includes(u))).length;if(a+=Math.min(.5,c/t.length*.5),i.description){let d=ul(i.description),u=t.filter(p=>d.some(m=>m.includes(p)||p.includes(m))).length;a+=Math.min(.3,u/t.length*.3)}return i.category&&Jw(n).includes(i.category)&&(a+=.1),o-i.mtimeMs<r&&(a+=at.RECENCY_BOOST),{header:i,score:a}}).sort((i,a)=>a.score-i.score)}async function Yw(n){let e=[],t=0;for(let{header:o,score:r}of n){if(t>=at.MAX_TOTAL_BYTES)break;try{let s=await Ep(o.filePath,"utf-8"),i=!1;s.length>at.MAX_FILE_BYTES&&(s=s.slice(0,at.MAX_FILE_BYTES)+`
141
+ `)}};import{randomUUID as wt}from"node:crypto";import{createRequire as VE}from"node:module";import*as ui from"node:vm";Yr();an();an();function dl(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}}}}import{readFile as Ep,readdir as Kw,stat as zw}from"node:fs/promises";import{existsSync as Mp}from"node:fs";import{join as qw}from"node:path";var at={MAX_SCAN_FILES:100,MAX_SELECTED:5,MAX_FILE_BYTES:4096,MAX_TOTAL_BYTES:20*1024,MIN_SCORE:.2,HEADER_LINES:10,RECENCY_DAYS:7,RECENCY_BOOST:.15};async function Op(n,e,t=new Set){if(!n.trim()||!Mp(e))return[];let o=n.trim().split(/\s+/);if(o.length<2&&o[0].length<4)return[];let r=await Yw(e);if(r.length===0)return[];let s=r.filter(l=>!t.has(l.filePath));if(s.length===0)return[];let a=Xw(n,s).filter(l=>l.score>=at.MIN_SCORE).slice(0,at.MAX_SELECTED);return a.length===0?[]:Jw(a)}async function Yw(n){if(!Mp(n))return[];let e;try{e=await Kw(n)}catch{return[]}let t=e.filter(r=>r.endsWith(".md")&&r!=="INDEX.md");return(await Promise.allSettled(t.map(async r=>{let s=qw(n,r),i=await zw(s),l=(await Ep(s,"utf-8")).split(`
142
+ `),c=null;for(let u=0;u<Math.min(l.length,at.HEADER_LINES);u++){let p=l[u].trim();if(!(!p||p.startsWith("#")||p.startsWith("---"))){c=p.slice(0,150);break}}let d=Qw(r);return{filename:r,filePath:s,mtimeMs:i.mtimeMs,sizeBytes:i.size,description:c,category:d}}))).filter(r=>r.status==="fulfilled").map(r=>r.value).sort((r,s)=>s.mtimeMs-r.mtimeMs).slice(0,at.MAX_SCAN_FILES)}function Xw(n,e){let t=ul(n);if(t.length===0)return[];let o=Date.now(),r=at.RECENCY_DAYS*24*60*60*1e3;return e.map(i=>{let a=0,l=ul(i.filename.replace(/\.md$/,"").replace(/[-_]/g," ")),c=t.filter(d=>l.some(u=>u.includes(d)||d.includes(u))).length;if(a+=Math.min(.5,c/t.length*.5),i.description){let d=ul(i.description),u=t.filter(p=>d.some(m=>m.includes(p)||p.includes(m))).length;a+=Math.min(.3,u/t.length*.3)}return i.category&&Zw(n).includes(i.category)&&(a+=.1),o-i.mtimeMs<r&&(a+=at.RECENCY_BOOST),{header:i,score:a}}).sort((i,a)=>a.score-i.score)}async function Jw(n){let e=[],t=0;for(let{header:o,score:r}of n){if(t>=at.MAX_TOTAL_BYTES)break;try{let s=await Ep(o.filePath,"utf-8"),i=!1;s.length>at.MAX_FILE_BYTES&&(s=s.slice(0,at.MAX_FILE_BYTES)+`
143
143
 
144
144
  > [Truncated at ${at.MAX_FILE_BYTES} bytes. Use memory tool read_file for full content: ${o.filename}]`,i=!0);let a=Buffer.byteLength(s,"utf-8");if(t+a>at.MAX_TOTAL_BYTES){let l=at.MAX_TOTAL_BYTES-t;s=s.slice(0,l)+`
145
145
 
146
- > [Truncated to fit session budget. Use memory tool read_file for full content: ${o.filename}]`,i=!0}t+=Buffer.byteLength(s,"utf-8"),e.push({filename:o.filename,filePath:o.filePath,mtimeMs:o.mtimeMs,score:r,content:s,truncated:i})}catch{}}return e}function ul(n){return n.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g," ").split(/\s+/).filter(e=>e.length>1)}function Xw(n){let e=n.replace(/\.md$/,""),t=["lesson","project","pattern","preference","fact","decision","task","reference"];for(let o of t)if(e.startsWith(o+"-")||e.startsWith(o+"_"))return o;return null}function Jw(n){let e=[],t=n.toLowerCase();return/(?:bug|error|fix|debug|issue|问题|报错|修复)/.test(t)&&e.push("lesson"),/(?:architecture|设计|架构|决定|decision)/.test(t)&&e.push("decision"),/(?:pattern|convention|惯例|标准|practice)/.test(t)&&e.push("pattern"),/(?:prefer|style|偏好|风格|习惯)/.test(t)&&e.push("preference"),/(?:deploy|port|config|version|部署|配置|环境)/.test(t)&&e.push("fact"),/(?:project|repo|codebase|项目|仓库)/.test(t)&&e.push("project"),/(?:task|todo|plan|任务|计划)/.test(t)&&e.push("task"),/(?:api|doc|guide|reference|文档|手册)/.test(t)&&e.push("reference"),e}function Dp(n){if(n.length===0)return"";let e=Date.now();return n.map(o=>{let r=Math.floor((e-o.mtimeMs)/864e5);return`## Memory (saved ${r===0?"today":r===1?"yesterday":`${r} days ago`}): ${o.filename}
146
+ > [Truncated to fit session budget. Use memory tool read_file for full content: ${o.filename}]`,i=!0}t+=Buffer.byteLength(s,"utf-8"),e.push({filename:o.filename,filePath:o.filePath,mtimeMs:o.mtimeMs,score:r,content:s,truncated:i})}catch{}}return e}function ul(n){return n.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g," ").split(/\s+/).filter(e=>e.length>1)}function Qw(n){let e=n.replace(/\.md$/,""),t=["lesson","project","pattern","preference","fact","decision","task","reference"];for(let o of t)if(e.startsWith(o+"-")||e.startsWith(o+"_"))return o;return null}function Zw(n){let e=[],t=n.toLowerCase();return/(?:bug|error|fix|debug|issue|问题|报错|修复)/.test(t)&&e.push("lesson"),/(?:architecture|设计|架构|决定|decision)/.test(t)&&e.push("decision"),/(?:pattern|convention|惯例|标准|practice)/.test(t)&&e.push("pattern"),/(?:prefer|style|偏好|风格|习惯)/.test(t)&&e.push("preference"),/(?:deploy|port|config|version|部署|配置|环境)/.test(t)&&e.push("fact"),/(?:project|repo|codebase|项目|仓库)/.test(t)&&e.push("project"),/(?:task|todo|plan|任务|计划)/.test(t)&&e.push("task"),/(?:api|doc|guide|reference|文档|手册)/.test(t)&&e.push("reference"),e}function Dp(n){if(n.length===0)return"";let e=Date.now();return n.map(o=>{let r=Math.floor((e-o.mtimeMs)/864e5);return`## Memory (saved ${r===0?"today":r===1?"yesterday":`${r} days ago`}): ${o.filename}
147
147
 
148
148
  ${o.content}`}).join(`
149
149
 
150
150
  ---
151
151
 
152
- `)}cl();var Qw=[/(?:收入|工资|薪资|月薪|年薪|到账|报销|预算|存款|花了|赚了|亏了)\s*[\d.]+/,/(?:搬家|换工作|离职|入职|跳槽|结婚|离婚|怀孕|生了|去世|住院|出院|手术)/,/(?:上线了|发布了|完成了|通过了|考上了|拿到了|录取|获奖|毕业|结业|答辩)/,/(?:今天|昨天|前天|上周|这周|上个月|这个月).*?(?:了|完|好|过)/,/(?:我是|我叫|我在|我住|我的(?:工作|职业|专业|公司|学校))/,/(?:我(?:老婆|老公|女朋友|男朋友|爸|妈|儿子|女儿|孩子))/,/(?:salary|income|earned|spent|budget|savings?)\s*(?:is|was|of)?\s*[\d$¥€£]/i,/(?:moved to|got (?:married|divorced|promoted|fired|hired)|graduated|diagnosed)/i,/(?:launched|published|shipped|released|completed|passed|got accepted)/i,/(?:my (?:name|job|company|school|major|birthday|anniversary) (?:is|was))/i];function pl(n){let e=n.slice(0,600);return Qw.some(t=>t.test(e))}var Zw=`You are a memory extraction assistant. Analyze the following conversation turn and extract any personal facts, events, or preferences worth remembering long-term.
152
+ `)}cl();var ex=[/(?:收入|工资|薪资|月薪|年薪|到账|报销|预算|存款|花了|赚了|亏了)\s*[\d.]+/,/(?:搬家|换工作|离职|入职|跳槽|结婚|离婚|怀孕|生了|去世|住院|出院|手术)/,/(?:上线了|发布了|完成了|通过了|考上了|拿到了|录取|获奖|毕业|结业|答辩)/,/(?:今天|昨天|前天|上周|这周|上个月|这个月).*?(?:了|完|好|过)/,/(?:我是|我叫|我在|我住|我的(?:工作|职业|专业|公司|学校))/,/(?:我(?:老婆|老公|女朋友|男朋友|爸|妈|儿子|女儿|孩子))/,/(?:salary|income|earned|spent|budget|savings?)\s*(?:is|was|of)?\s*[\d$¥€£]/i,/(?:moved to|got (?:married|divorced|promoted|fired|hired)|graduated|diagnosed)/i,/(?:launched|published|shipped|released|completed|passed|got accepted)/i,/(?:my (?:name|job|company|school|major|birthday|anniversary) (?:is|was))/i];function pl(n){let e=n.slice(0,600);return ex.some(t=>t.test(e))}var tx=`You are a memory extraction assistant. Analyze the following conversation turn and extract any personal facts, events, or preferences worth remembering long-term.
153
153
 
154
154
  Rules:
155
155
  - Only extract FACTS about the user (not the assistant)
@@ -167,10 +167,10 @@ Assistant response:
167
167
  Today's date: {today}
168
168
 
169
169
  Respond ONLY with a JSON array (or empty array [] if nothing worth extracting):
170
- [{"text": "...", "category": "personal_fact|preference|event|lesson", "importance": 0.5-0.9, "eventDate": "YYYY-MM-DD or null"}]`;async function ex(n,e,t){let o=Zw.replace("{user_message}",n.userMessage.slice(0,1e3)).replace("{assistant_message}",n.assistantMessage.slice(0,500)).replace("{today}",t);try{let r=await e(o);if(!r)return[];let s=r.replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"").trim(),i=JSON.parse(s);return Array.isArray(i)?i.filter(a=>a.text&&typeof a.text=="string"&&a.text.length>=5&&a.text.length<=500&&a.category).map(a=>({text:a.text.trim(),category:tx(a.category),importance:Math.min(.9,Math.max(.3,Number(a.importance)||.5)),eventDate:typeof a.eventDate=="string"?a.eventDate:void 0})).slice(0,3):[]}catch{return[]}}function tx(n){return new Set(["personal_fact","preference","event","lesson","pattern","decision"]).has(n)?n:"personal_fact"}async function Lp(n,e){if(!pl(n.userMessage))return 0;if(e.log.debug(`implicit-extract: signal detected in user message (${n.userMessage.slice(0,50)}...)`),!e.llmExtract)return e.log.debug("implicit-extract: no LLM extractor configured, skipping Layer 2"),0;let t=new Date().toISOString().slice(0,10),o=await ex(n,e.llmExtract,t);if(o.length===0)return e.log.debug("implicit-extract: LLM returned no facts"),0;let r=0;for(let s of o)try{if((await e.localProvider.addText(s.text,e.userId,{source:"implicit-extract",category:s.category,importance:s.importance})).memoriesAdded>0){if(r++,e.log.debug(`implicit-extract: stored "${s.text.slice(0,60)}..." [${s.category}]`),s.category==="event")try{let a=await e.localProvider.findRelatedEvents(s.text,e.userId);for(let l of a)e.localProvider.feedback([l.id],"useful").catch(()=>{});a.length>0&&e.log.debug(`implicit-extract: linked to ${a.length} related events`)}catch{}}else e.log.debug(`implicit-extract: dedup skipped "${s.text.slice(0,40)}..."`)}catch{}return r}je();var Vn={MAX_SESSION_BYTES:da,LIMIT_PER_RECALL:ua,MAX_SURFACED_ENTRIES:pa};function Kt(){return{surfacedPaths:new Set,sessionBytes:0}}function $p(n,e,t){let o=[],r=t??Kt(),s,i=[];return o.push(n.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>=Vn.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:Vn.LIMIT_PER_RECALL}),d=c.filter(m=>{let h=m,f=h.path??h.id??"";if(!f)return!0;if(r.surfacedPaths.has(f))return!1;let y=(h.content?.length??0)*2;if(r.sessionBytes+y>Vn.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(f),r.sessionBytes+=y,r.surfacedPaths.size>Vn.MAX_SURFACED_ENTRIES){let b=r.surfacedPaths.values().next().value;b!==void 0&&r.surfacedPaths.delete(b)}return!0});s=l.turnId,i=d,e.log.debug(`memory.before_recall: prefetched ${c.length} \u922B?${d.length} after dedup (${r.sessionBytes} bytes used)`);let u=d.map(m=>{let h=m;return{text:h.text??h.content??"",score:h.score,category:h.metadata?.category??null}}).filter(m=>m.text);if(l.preferredCategories?.length||l.deprioritizedCategories?.length){let m={scenario:"general",preferred:l.preferredCategories??[],deprioritized:l.deprioritizedCategories??[],confidence:1};u=u.map(h=>({...h,score:ll(h.score??.5,h.category,m)})).sort((h,f)=>(f.score??0)-(h.score??0))}let p=.15;return u=u.filter(m=>(m.score??0)>=p),{action:"continue",context:{...l,recalledMemories:u}}}catch(c){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${c instanceof Error?c.message:String(c)}`),i=[]}return{action:"continue",context:l}}})),o.push(n.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}}})),e.localMemoryProvider&&(o.push(n.register({point:"turn.completed",priority:90,label:"memory-auto-extract",handler:async(a,l)=>{let c=e.getLastUserMessage?.();if(!c)return{action:"continue",context:l};let d=Np(c);if(d.length===0)return{action:"continue",context:l};for(let u of d)try{await e.localMemoryProvider.addText(u.text,e.userId,{source:"auto-extract",category:u.category,importance:.6}),e.log.debug(`memory-auto-extract: stored "${u.text.slice(0,50)}..." (${u.category})`)}catch{}return{action:"continue",context:l}}})),o.push(n.register({point:"turn.completed",priority:95,label:"memory-implicit-extract",handler:async(a,l)=>{let c=e.getLastUserMessage?.();if(!c)return{action:"continue",context:l};if(Np(c).length>0)return{action:"continue",context:l};if(!pl(c))return{action:"continue",context:l};let u=e.getLastAssistantMessage?.();return!u||!e.llmExtract?{action:"continue",context:l}:(Lp({userMessage:c,assistantMessage:u},{localProvider:e.localMemoryProvider,userId:e.userId,log:e.log,llmExtract:e.llmExtract}).catch(()=>{}),{action:"continue",context:l})}}))),()=>{for(let a of o)a();i=[]}}function Up(n,e,t){let o=t??Kt();return n.register({point:"memory.before_recall",priority:40,label:"memdir-cross-file-recall",handler:async(s,i)=>{let a=e.getMemdir();if(!a||!i.query)return{action:"continue",context:i};if(o.sessionBytes>=Vn.MAX_SESSION_BYTES)return e.log.debug("memdir-recall: session byte budget exhausted, skipping"),{action:"continue",context:i};try{let l=a.getRootPath(),c=await Op(i.query,l,o.surfacedPaths);if(c.length===0)return{action:"continue",context:i};if(i.preferredCategories?.length||i.deprioritizedCategories?.length){let h={scenario:"general",preferred:i.preferredCategories??[],deprioritized:i.deprioritizedCategories??[],confidence:1};c=c.map(f=>({...f,score:ll(f.score,Pp(f.filename),h)})).sort((f,y)=>y.score-f.score)}let d=c.filter(h=>{let f=Buffer.byteLength(h.content,"utf-8");return o.sessionBytes+f>Vn.MAX_SESSION_BYTES?!1:(o.surfacedPaths.add(h.filePath),o.sessionBytes+=f,!0)});if(d.length===0)return{action:"continue",context:i};e.log.debug(`memdir-recall: found ${c.length} \u922B?accepted ${d.length} files (${o.sessionBytes} bytes used)`);let u=Dp(d),p=i.recalledMemories??[];return{action:"continue",context:{...i,recalledMemories:[...[{text:u,score:.9}],...p]}}}catch(l){e.log.warn(`memdir-recall: cross-file recall failed: ${l instanceof Error?l.message:String(l)}`)}return{action:"continue",context:i}}})}var nx=[{pattern:/(?:请|帮我)?记住[::]\s*(.+)/i,category:"personal_fact",extractor:n=>n[1]?.trim()||null},{pattern:/(?:请|帮我)?记住(.{10,120})/i,category:"personal_fact",extractor:n=>n[1]?.trim()||null},{pattern:/我的偏好[是为::]\s*(.+)/i,category:"preference",extractor:n=>n[1]?.trim()||null},{pattern:/我(?:喜欢|偏好|习惯)(.{5,100})/i,category:"preference",extractor:n=>`\u7528\u6237\u504F\u597D: ${n[1]?.trim()}`},{pattern:/以后(?:都|请|要)(.{5,100})/i,category:"preference",extractor:n=>`\u7528\u6237\u8981\u6C42: ${n[1]?.trim()}`},{pattern:/remember(?:\s+that)?[::]\s*(.+)/i,category:"personal_fact",extractor:n=>n[1]?.trim()||null},{pattern:/(?:note|memo)[::]\s*(.+)/i,category:"lesson",extractor:n=>n[1]?.trim()||null},{pattern:/my preference is[::]?\s*(.+)/i,category:"preference",extractor:n=>n[1]?.trim()||null},{pattern:/i (?:always|prefer|like to|want you to)\s+(.{10,120})/i,category:"preference",extractor:n=>`User preference: ${n[1]?.trim()}`}];function Np(n){let e=[],t=n.slice(0,500);for(let{pattern:o,category:r,extractor:s}of nx){let i=t.match(o);if(i){let a=s(i,t);if(a&&a.length>=5&&a.length<=300){e.push({text:a,category:r});break}}}return e}le();import*as es from"node:fs";import*as Uo from"node:path";le();import{existsSync as jp,mkdirSync as ox,readFileSync as rx,writeFileSync as sx}from"node:fs";import{join as ix}from"node:path";import{randomUUID as Fp}from"node:crypto";function Bp(){return ix(H(),"projects.json")}function ze(){let n=Bp();if(!jp(n))return{activeProjectId:null,projects:[]};try{let e=rx(n,"utf-8");return JSON.parse(e)}catch{return{activeProjectId:null,projects:[]}}}function Ct(n){let e=Bp(),t=H();jp(t)||ox(t,{recursive:!0}),sx(e,JSON.stringify(n,null,2),"utf-8")}function Xr(n){let e=ze(),t=new Date().toISOString(),o={id:Fp(),name:n.name,workspaceDir:n.workspaceDir,type:n.type??"personal",status:"active",groupId:n.groupId,createdAt:t,updatedAt:t};return e.projects.push(o),n.skipAutoSwitch||(e.activeProjectId=o.id),Ct(e),o}function fe(){return ze().projects.filter(e=>e.status==="active")}function Ne(){let n=ze();if(!n.activeProjectId)return null;let e=n.projects.find(t=>t.id===n.activeProjectId)??null;return e&&e.status!=="active"?null:e}function lt(n){return ze().projects.find(t=>t.id===n)??null}function Wp(n,e){let t=ze(),o=t.projects.find(r=>r.id===n);return o?("planStatus"in e&&(o.planStatus=e.planStatus),"planAgents"in e&&(o.planAgents=e.planAgents),"planWinnerId"in e&&(o.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(o.leaderSessionId=e.leaderSessionId),o.updatedAt=new Date().toISOString(),Ct(t),!0):!1}function ft(n){let e=ze(),t=e.projects.find(o=>o.id===n&&o.status==="active");return t?(e.activeProjectId=t.id,Ct(e),t):null}function ml(n){let e=ze(),t=e.projects.findIndex(s=>s.id===n);if(t===-1)return{deleted:!1};if(e.projects[t].type==="default")return{deleted:!1};e.projects.splice(t,1);let r;if(e.activeProjectId===n){let s=e.projects.find(i=>i.type==="default"&&i.status==="active");if(s)e.activeProjectId=s.id,r=s;else{let i=e.projects.find(a=>a.status==="active"&&a.id!==n);e.activeProjectId=i?.id??null,r=i}}return Ct(e),{deleted:!0,switchedTo:r}}function Gp(n){let e=ze(),t=e.projects.find(s=>s.type==="default"&&s.status==="active");if(t)return t;let o=new Date().toISOString(),r={id:Fp(),name:"\u9ED8\u8BA4\u9879\u76EE",workspaceDir:n,type:"default",status:"active",createdAt:o,updatedAt:o};return e.projects.push(r),e.activeProjectId||(e.activeProjectId=r.id),Ct(e),r}function Hp(n,e){let t=ze(),o=t.projects.find(s=>s.id===n&&s.status==="active");return!o||o.type==="default"||t.projects.find(s=>s.name===e&&s.status==="active"&&s.id!==n)?null:(o.name=e,o.updatedAt=new Date().toISOString(),Ct(t),o)}function Vp(n,e){let t=ze(),o=t.projects.find(r=>r.id===n);return o?(o.workspaceDir=e,o.updatedAt=new Date().toISOString(),Ct(t),!0):!1}function Kp(n){let e=ze(),t=e.projects.find(r=>r.id===n&&r.status==="active");if(!t)return{archived:!1};if(t.type==="default")return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let o;if(e.activeProjectId===n){let r=e.projects.find(s=>s.type==="default"&&s.status==="active");if(r)e.activeProjectId=r.id,o=r;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==n);e.activeProjectId=s?.id??null,o=s}}return Ct(e),{archived:!0,switchedTo:o}}function zp(n){let e=ze(),t=e.projects.find(o=>o.id===n&&o.status==="archived");return t?(t.status="active",t.updatedAt=new Date().toISOString(),Ct(e),t):null}function Jr(n){return ze().projects.find(t=>t.groupId===n&&t.status==="active")??null}function qp(n){let e=ze(),t=e.projects.find(r=>r.groupId===n&&r.status==="active");if(!t)return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let o;if(e.activeProjectId===t.id){let r=e.projects.find(s=>s.type==="default"&&s.status==="active");if(r)e.activeProjectId=r.id,o=r;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==t.id);e.activeProjectId=s?.id??null,o=s}}return Ct(e),{archived:!0,projectId:t.id,switchedTo:o}}je();var Zr={MAX_RECALLED_SKILLS:zi,MAX_SKILL_CONTENT_CHARS:qi,CACHE_TTL_MS:Yi};function ax(n){let e=[/之前.{0,8}(?:做过|写过|实现过|处理过|用过|搞过|弄过)/,/以前.{0,8}(?:做过|写过|实现过|处理过|用过)/,/(?:上次|上回|之前|以前).{0,12}(?:不是|是不是|已经).{0,8}(?:做|写|实现|处理)/,/(?:参考|参照|照着|按照).{0,6}(?:项目|工程|仓库)/,/(?:那个|那边|另一个).{0,6}(?:项目|工程).{0,6}(?:里|中|的)/,/(?:跟|和|像).{0,6}(?:项目|工程).{0,6}(?:一样|类似|差不多)/,/(?:复用|重用|搬过来|拿过来|移过来|copy过来)/],t=[/(?:有没有|有无|是否有).{0,6}(?:技能|skill|模板|template|现成的)/,/(?:能不能|可以).{0,6}(?:自动|像之前|快速).{0,6}(?:生成|创建|写|做)/,/(?:跟|和|类似|像).{0,4}(?:上次|之前|其他|那个).{0,4}(?:一样|类似)/,/(?:批量|自动化|一键).{0,6}(?:生成|创建|部署|处理)/,/(?:同样的|相同的|一样的).{0,4}(?:方式|方法|流程|步骤)/],o=[/(?:before|previously|earlier|last time).{0,20}(?:did|done|made|built|implemented|wrote)/i,/(?:didn't|did) you.{0,15}(?:already|before|earlier)/i,/(?:same|similar).{0,10}(?:as|to|like).{0,10}(?:project|repo)/i,/(?:reuse|re-use|copy from|bring over|port from).{0,15}(?:project|repo)/i,/(?:remember|recall).{0,10}(?:doing|making|building|writing)/i,/(?:other|another|different)\s+project/i],r=[/(?:is there|do you have|any).{0,10}(?:skill|template|automation|workflow)/i,/(?:like|similar to|same as).{0,15}(?:last time|before|the other)/i,/(?:automate|batch|bulk).{0,10}(?:create|generate|process|build)/i,/(?:can you|could you).{0,10}(?:do the same|repeat|replicate)/i];if(![...e,...t,...o,...r].some(l=>l.test(n)))return null;let a=lx(n);return a.length>0?a:null}function lx(n){let t=n.replace(/之前|以前|上次|上回|不是|是不是|已经|做过|写过|实现过|处理过|用过|搞过|弄过/g," ").replace(/参考|参照|照着|按照|项目|工程|仓库|那个|那边|另一个|里|中|的|跟|和|像|一样|类似|差不多/g," ").replace(/复用|重用|搬过来|拿过来|移过来/g," ").replace(/\b(the|a|an|is|was|were|did|didn't|do|you|i|we|it|this|that|before|previously|earlier|last|time|already|same|similar|as|to|like|from|project|repo|remember|recall|doing|making|building|writing|other|another|different)\b/gi," ").trim().split(/[\s,;.!?,。!?、;:""''()\[\]{}]+/).filter(o=>o.length>=2).map(o=>o.toLowerCase());return[...new Set(t)].slice(0,8)}var Qr=null,fl=0;function cx(n){let e=Date.now();if(Qr&&e-fl<Zr.CACHE_TTL_MS)return Qr;let t=[],o=fe().map(s=>s.workspaceDir).filter(Boolean),r=cp(o,n);for(let s of r){let i=Uo.join(s,".qlogicagent","skills");try{let a=es.readdirSync(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=Uo.join(i,l.name,"SKILL.md");try{let d=es.readFileSync(c,"utf8"),u=d.split(`
171
- `).slice(0,5).join(" ").toLowerCase();t.push({name:l.name,projectDir:s,projectName:Uo.basename(s),content:d,searchText:`${l.name.toLowerCase()} ${u}`})}catch{}}}catch{}}return Qr=t,fl=e,t}function dx(n,e){if(n.length===0)return[];let t=cx(e);return t.length===0?[]:t.map(r=>{let s=0;for(let i of n)r.searchText.includes(i)&&(s+=2),r.name.includes(i)&&(s+=3);return{skill:r,score:s}}).filter(r=>r.score>0).sort((r,s)=>s.score-r.score).slice(0,Zr.MAX_RECALLED_SKILLS).map(r=>r.skill)}function Yp(n,e){return n.register({point:"memory.before_recall",priority:60,label:"cross-project-skill-recall",handler:(o,r)=>{let s=r.query;if(!s)return{action:"continue",context:r};let i=ax(s);if(!i)return{action:"continue",context:r};e.log.debug(`skill-recall: retrospective trigger detected, keywords: [${i.join(", ")}]`);let a=dx(i,e.currentCwd);if(a.length===0)return e.log.debug("skill-recall: no cross-project skill matches found"),{action:"continue",context:r};e.log.debug(`skill-recall: found ${a.length} cross-project skill(s): ${a.map(d=>`${d.name}@${d.projectName}`).join(", ")}`);let l=r.recalledMemories??[],c=a.map(d=>{let u=d.content.length>Zr.MAX_SKILL_CONTENT_CHARS?d.content.slice(0,Zr.MAX_SKILL_CONTENT_CHARS)+`
170
+ [{"text": "...", "category": "personal_fact|preference|event|lesson", "importance": 0.5-0.9, "eventDate": "YYYY-MM-DD or null"}]`;async function nx(n,e,t){let o=tx.replace("{user_message}",n.userMessage.slice(0,1e3)).replace("{assistant_message}",n.assistantMessage.slice(0,500)).replace("{today}",t);try{let r=await e(o);if(!r)return[];let s=r.replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"").trim(),i=JSON.parse(s);return Array.isArray(i)?i.filter(a=>a.text&&typeof a.text=="string"&&a.text.length>=5&&a.text.length<=500&&a.category).map(a=>({text:a.text.trim(),category:ox(a.category),importance:Math.min(.9,Math.max(.3,Number(a.importance)||.5)),eventDate:typeof a.eventDate=="string"?a.eventDate:void 0})).slice(0,3):[]}catch{return[]}}function ox(n){return new Set(["personal_fact","preference","event","lesson","pattern","decision"]).has(n)?n:"personal_fact"}async function Lp(n,e){if(!pl(n.userMessage))return 0;if(e.log.debug(`implicit-extract: signal detected in user message (${n.userMessage.slice(0,50)}...)`),!e.llmExtract)return e.log.debug("implicit-extract: no LLM extractor configured, skipping Layer 2"),0;let t=new Date().toISOString().slice(0,10),o=await nx(n,e.llmExtract,t);if(o.length===0)return e.log.debug("implicit-extract: LLM returned no facts"),0;let r=0;for(let s of o)try{if((await e.localProvider.addText(s.text,e.userId,{source:"implicit-extract",category:s.category,importance:s.importance})).memoriesAdded>0){if(r++,e.log.debug(`implicit-extract: stored "${s.text.slice(0,60)}..." [${s.category}]`),s.category==="event")try{let a=await e.localProvider.findRelatedEvents(s.text,e.userId);for(let l of a)e.localProvider.feedback([l.id],"useful").catch(()=>{});a.length>0&&e.log.debug(`implicit-extract: linked to ${a.length} related events`)}catch{}}else e.log.debug(`implicit-extract: dedup skipped "${s.text.slice(0,40)}..."`)}catch{}return r}je();var Vn={MAX_SESSION_BYTES:da,LIMIT_PER_RECALL:ua,MAX_SURFACED_ENTRIES:pa};function Kt(){return{surfacedPaths:new Set,sessionBytes:0}}function $p(n,e,t){let o=[],r=t??Kt(),s,i=[];return o.push(n.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>=Vn.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:Vn.LIMIT_PER_RECALL}),d=c.filter(m=>{let h=m,f=h.path??h.id??"";if(!f)return!0;if(r.surfacedPaths.has(f))return!1;let y=(h.content?.length??0)*2;if(r.sessionBytes+y>Vn.MAX_SESSION_BYTES)return!1;if(r.surfacedPaths.add(f),r.sessionBytes+=y,r.surfacedPaths.size>Vn.MAX_SURFACED_ENTRIES){let b=r.surfacedPaths.values().next().value;b!==void 0&&r.surfacedPaths.delete(b)}return!0});s=l.turnId,i=d,e.log.debug(`memory.before_recall: prefetched ${c.length} \u922B?${d.length} after dedup (${r.sessionBytes} bytes used)`);let u=d.map(m=>{let h=m;return{text:h.text??h.content??"",score:h.score,category:h.metadata?.category??null}}).filter(m=>m.text);if(l.preferredCategories?.length||l.deprioritizedCategories?.length){let m={scenario:"general",preferred:l.preferredCategories??[],deprioritized:l.deprioritizedCategories??[],confidence:1};u=u.map(h=>({...h,score:ll(h.score??.5,h.category,m)})).sort((h,f)=>(f.score??0)-(h.score??0))}let p=.15;return u=u.filter(m=>(m.score??0)>=p),{action:"continue",context:{...l,recalledMemories:u}}}catch(c){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${c instanceof Error?c.message:String(c)}`),i=[]}return{action:"continue",context:l}}})),o.push(n.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}}})),e.localMemoryProvider&&(o.push(n.register({point:"turn.completed",priority:90,label:"memory-auto-extract",handler:async(a,l)=>{let c=e.getLastUserMessage?.();if(!c)return{action:"continue",context:l};let d=Np(c);if(d.length===0)return{action:"continue",context:l};for(let u of d)try{await e.localMemoryProvider.addText(u.text,e.userId,{source:"auto-extract",category:u.category,importance:.6}),e.log.debug(`memory-auto-extract: stored "${u.text.slice(0,50)}..." (${u.category})`)}catch{}return{action:"continue",context:l}}})),o.push(n.register({point:"turn.completed",priority:95,label:"memory-implicit-extract",handler:async(a,l)=>{let c=e.getLastUserMessage?.();if(!c)return{action:"continue",context:l};if(Np(c).length>0)return{action:"continue",context:l};if(!pl(c))return{action:"continue",context:l};let u=e.getLastAssistantMessage?.();return!u||!e.llmExtract?{action:"continue",context:l}:(Lp({userMessage:c,assistantMessage:u},{localProvider:e.localMemoryProvider,userId:e.userId,log:e.log,llmExtract:e.llmExtract}).catch(()=>{}),{action:"continue",context:l})}}))),()=>{for(let a of o)a();i=[]}}function Up(n,e,t){let o=t??Kt();return n.register({point:"memory.before_recall",priority:40,label:"memdir-cross-file-recall",handler:async(s,i)=>{let a=e.getMemdir();if(!a||!i.query)return{action:"continue",context:i};if(o.sessionBytes>=Vn.MAX_SESSION_BYTES)return e.log.debug("memdir-recall: session byte budget exhausted, skipping"),{action:"continue",context:i};try{let l=a.getRootPath(),c=await Op(i.query,l,o.surfacedPaths);if(c.length===0)return{action:"continue",context:i};if(i.preferredCategories?.length||i.deprioritizedCategories?.length){let h={scenario:"general",preferred:i.preferredCategories??[],deprioritized:i.deprioritizedCategories??[],confidence:1};c=c.map(f=>({...f,score:ll(f.score,Pp(f.filename),h)})).sort((f,y)=>y.score-f.score)}let d=c.filter(h=>{let f=Buffer.byteLength(h.content,"utf-8");return o.sessionBytes+f>Vn.MAX_SESSION_BYTES?!1:(o.surfacedPaths.add(h.filePath),o.sessionBytes+=f,!0)});if(d.length===0)return{action:"continue",context:i};e.log.debug(`memdir-recall: found ${c.length} \u922B?accepted ${d.length} files (${o.sessionBytes} bytes used)`);let u=Dp(d),p=i.recalledMemories??[];return{action:"continue",context:{...i,recalledMemories:[...[{text:u,score:.9}],...p]}}}catch(l){e.log.warn(`memdir-recall: cross-file recall failed: ${l instanceof Error?l.message:String(l)}`)}return{action:"continue",context:i}}})}var rx=[{pattern:/(?:请|帮我)?记住[::]\s*(.+)/i,category:"personal_fact",extractor:n=>n[1]?.trim()||null},{pattern:/(?:请|帮我)?记住(.{10,120})/i,category:"personal_fact",extractor:n=>n[1]?.trim()||null},{pattern:/我的偏好[是为::]\s*(.+)/i,category:"preference",extractor:n=>n[1]?.trim()||null},{pattern:/我(?:喜欢|偏好|习惯)(.{5,100})/i,category:"preference",extractor:n=>`\u7528\u6237\u504F\u597D: ${n[1]?.trim()}`},{pattern:/以后(?:都|请|要)(.{5,100})/i,category:"preference",extractor:n=>`\u7528\u6237\u8981\u6C42: ${n[1]?.trim()}`},{pattern:/remember(?:\s+that)?[::]\s*(.+)/i,category:"personal_fact",extractor:n=>n[1]?.trim()||null},{pattern:/(?:note|memo)[::]\s*(.+)/i,category:"lesson",extractor:n=>n[1]?.trim()||null},{pattern:/my preference is[::]?\s*(.+)/i,category:"preference",extractor:n=>n[1]?.trim()||null},{pattern:/i (?:always|prefer|like to|want you to)\s+(.{10,120})/i,category:"preference",extractor:n=>`User preference: ${n[1]?.trim()}`}];function Np(n){let e=[],t=n.slice(0,500);for(let{pattern:o,category:r,extractor:s}of rx){let i=t.match(o);if(i){let a=s(i,t);if(a&&a.length>=5&&a.length<=300){e.push({text:a,category:r});break}}}return e}le();import*as es from"node:fs";import*as Uo from"node:path";le();import{existsSync as jp,mkdirSync as sx,readFileSync as ix,writeFileSync as ax}from"node:fs";import{join as lx}from"node:path";import{randomUUID as Fp}from"node:crypto";function Bp(){return lx(H(),"projects.json")}function ze(){let n=Bp();if(!jp(n))return{activeProjectId:null,projects:[]};try{let e=ix(n,"utf-8");return JSON.parse(e)}catch{return{activeProjectId:null,projects:[]}}}function Ct(n){let e=Bp(),t=H();jp(t)||sx(t,{recursive:!0}),ax(e,JSON.stringify(n,null,2),"utf-8")}function Xr(n){let e=ze(),t=new Date().toISOString(),o={id:Fp(),name:n.name,workspaceDir:n.workspaceDir,type:n.type??"personal",status:"active",groupId:n.groupId,createdAt:t,updatedAt:t};return e.projects.push(o),n.skipAutoSwitch||(e.activeProjectId=o.id),Ct(e),o}function fe(){return ze().projects.filter(e=>e.status==="active")}function Ne(){let n=ze();if(!n.activeProjectId)return null;let e=n.projects.find(t=>t.id===n.activeProjectId)??null;return e&&e.status!=="active"?null:e}function lt(n){return ze().projects.find(t=>t.id===n)??null}function Wp(n,e){let t=ze(),o=t.projects.find(r=>r.id===n);return o?("planStatus"in e&&(o.planStatus=e.planStatus),"planAgents"in e&&(o.planAgents=e.planAgents),"planWinnerId"in e&&(o.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(o.leaderSessionId=e.leaderSessionId),o.updatedAt=new Date().toISOString(),Ct(t),!0):!1}function ft(n){let e=ze(),t=e.projects.find(o=>o.id===n&&o.status==="active");return t?(e.activeProjectId=t.id,Ct(e),t):null}function ml(n){let e=ze(),t=e.projects.findIndex(s=>s.id===n);if(t===-1)return{deleted:!1};if(e.projects[t].type==="default")return{deleted:!1};e.projects.splice(t,1);let r;if(e.activeProjectId===n){let s=e.projects.find(i=>i.type==="default"&&i.status==="active");if(s)e.activeProjectId=s.id,r=s;else{let i=e.projects.find(a=>a.status==="active"&&a.id!==n);e.activeProjectId=i?.id??null,r=i}}return Ct(e),{deleted:!0,switchedTo:r}}function Gp(n){let e=ze(),t=e.projects.find(s=>s.type==="default"&&s.status==="active");if(t)return t;let o=new Date().toISOString(),r={id:Fp(),name:"\u9ED8\u8BA4\u9879\u76EE",workspaceDir:n,type:"default",status:"active",createdAt:o,updatedAt:o};return e.projects.push(r),e.activeProjectId||(e.activeProjectId=r.id),Ct(e),r}function Hp(n,e){let t=ze(),o=t.projects.find(s=>s.id===n&&s.status==="active");return!o||o.type==="default"||t.projects.find(s=>s.name===e&&s.status==="active"&&s.id!==n)?null:(o.name=e,o.updatedAt=new Date().toISOString(),Ct(t),o)}function Vp(n,e){let t=ze(),o=t.projects.find(r=>r.id===n);return o?(o.workspaceDir=e,o.updatedAt=new Date().toISOString(),Ct(t),!0):!1}function Kp(n){let e=ze(),t=e.projects.find(r=>r.id===n&&r.status==="active");if(!t)return{archived:!1};if(t.type==="default")return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let o;if(e.activeProjectId===n){let r=e.projects.find(s=>s.type==="default"&&s.status==="active");if(r)e.activeProjectId=r.id,o=r;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==n);e.activeProjectId=s?.id??null,o=s}}return Ct(e),{archived:!0,switchedTo:o}}function zp(n){let e=ze(),t=e.projects.find(o=>o.id===n&&o.status==="archived");return t?(t.status="active",t.updatedAt=new Date().toISOString(),Ct(e),t):null}function Jr(n){return ze().projects.find(t=>t.groupId===n&&t.status==="active")??null}function qp(n){let e=ze(),t=e.projects.find(r=>r.groupId===n&&r.status==="active");if(!t)return{archived:!1};t.status="archived",t.updatedAt=new Date().toISOString();let o;if(e.activeProjectId===t.id){let r=e.projects.find(s=>s.type==="default"&&s.status==="active");if(r)e.activeProjectId=r.id,o=r;else{let s=e.projects.find(i=>i.status==="active"&&i.id!==t.id);e.activeProjectId=s?.id??null,o=s}}return Ct(e),{archived:!0,projectId:t.id,switchedTo:o}}je();var Zr={MAX_RECALLED_SKILLS:zi,MAX_SKILL_CONTENT_CHARS:qi,CACHE_TTL_MS:Yi};function cx(n){let e=[/之前.{0,8}(?:做过|写过|实现过|处理过|用过|搞过|弄过)/,/以前.{0,8}(?:做过|写过|实现过|处理过|用过)/,/(?:上次|上回|之前|以前).{0,12}(?:不是|是不是|已经).{0,8}(?:做|写|实现|处理)/,/(?:参考|参照|照着|按照).{0,6}(?:项目|工程|仓库)/,/(?:那个|那边|另一个).{0,6}(?:项目|工程).{0,6}(?:里|中|的)/,/(?:跟|和|像).{0,6}(?:项目|工程).{0,6}(?:一样|类似|差不多)/,/(?:复用|重用|搬过来|拿过来|移过来|copy过来)/],t=[/(?:有没有|有无|是否有).{0,6}(?:技能|skill|模板|template|现成的)/,/(?:能不能|可以).{0,6}(?:自动|像之前|快速).{0,6}(?:生成|创建|写|做)/,/(?:跟|和|类似|像).{0,4}(?:上次|之前|其他|那个).{0,4}(?:一样|类似)/,/(?:批量|自动化|一键).{0,6}(?:生成|创建|部署|处理)/,/(?:同样的|相同的|一样的).{0,4}(?:方式|方法|流程|步骤)/],o=[/(?:before|previously|earlier|last time).{0,20}(?:did|done|made|built|implemented|wrote)/i,/(?:didn't|did) you.{0,15}(?:already|before|earlier)/i,/(?:same|similar).{0,10}(?:as|to|like).{0,10}(?:project|repo)/i,/(?:reuse|re-use|copy from|bring over|port from).{0,15}(?:project|repo)/i,/(?:remember|recall).{0,10}(?:doing|making|building|writing)/i,/(?:other|another|different)\s+project/i],r=[/(?:is there|do you have|any).{0,10}(?:skill|template|automation|workflow)/i,/(?:like|similar to|same as).{0,15}(?:last time|before|the other)/i,/(?:automate|batch|bulk).{0,10}(?:create|generate|process|build)/i,/(?:can you|could you).{0,10}(?:do the same|repeat|replicate)/i];if(![...e,...t,...o,...r].some(l=>l.test(n)))return null;let a=dx(n);return a.length>0?a:null}function dx(n){let t=n.replace(/之前|以前|上次|上回|不是|是不是|已经|做过|写过|实现过|处理过|用过|搞过|弄过/g," ").replace(/参考|参照|照着|按照|项目|工程|仓库|那个|那边|另一个|里|中|的|跟|和|像|一样|类似|差不多/g," ").replace(/复用|重用|搬过来|拿过来|移过来/g," ").replace(/\b(the|a|an|is|was|were|did|didn't|do|you|i|we|it|this|that|before|previously|earlier|last|time|already|same|similar|as|to|like|from|project|repo|remember|recall|doing|making|building|writing|other|another|different)\b/gi," ").trim().split(/[\s,;.!?,。!?、;:""''()\[\]{}]+/).filter(o=>o.length>=2).map(o=>o.toLowerCase());return[...new Set(t)].slice(0,8)}var Qr=null,fl=0;function ux(n){let e=Date.now();if(Qr&&e-fl<Zr.CACHE_TTL_MS)return Qr;let t=[],o=fe().map(s=>s.workspaceDir).filter(Boolean),r=cp(o,n);for(let s of r){let i=Uo.join(s,".qlogicagent","skills");try{let a=es.readdirSync(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=Uo.join(i,l.name,"SKILL.md");try{let d=es.readFileSync(c,"utf8"),u=d.split(`
171
+ `).slice(0,5).join(" ").toLowerCase();t.push({name:l.name,projectDir:s,projectName:Uo.basename(s),content:d,searchText:`${l.name.toLowerCase()} ${u}`})}catch{}}}catch{}}return Qr=t,fl=e,t}function px(n,e){if(n.length===0)return[];let t=ux(e);return t.length===0?[]:t.map(r=>{let s=0;for(let i of n)r.searchText.includes(i)&&(s+=2),r.name.includes(i)&&(s+=3);return{skill:r,score:s}}).filter(r=>r.score>0).sort((r,s)=>s.score-r.score).slice(0,Zr.MAX_RECALLED_SKILLS).map(r=>r.skill)}function Yp(n,e){return n.register({point:"memory.before_recall",priority:60,label:"cross-project-skill-recall",handler:(o,r)=>{let s=r.query;if(!s)return{action:"continue",context:r};let i=cx(s);if(!i)return{action:"continue",context:r};e.log.debug(`skill-recall: retrospective trigger detected, keywords: [${i.join(", ")}]`);let a=px(i,e.currentCwd);if(a.length===0)return e.log.debug("skill-recall: no cross-project skill matches found"),{action:"continue",context:r};e.log.debug(`skill-recall: found ${a.length} cross-project skill(s): ${a.map(d=>`${d.name}@${d.projectName}`).join(", ")}`);let l=r.recalledMemories??[],c=a.map(d=>{let u=d.content.length>Zr.MAX_SKILL_CONTENT_CHARS?d.content.slice(0,Zr.MAX_SKILL_CONTENT_CHARS)+`
172
172
  ...(truncated)`:d.content;return{text:[`[Cross-project skill available] Skill "${d.name}" learned in project "${d.projectName}" (${d.projectDir}):`,u,`\u2192 To use this skill in current project: use skill tool with action "create" name "${d.name}" and copy the content above`,`\u2192 After creating locally, promote to global: skill tool with action "promote" name "${d.name}"`,"\u2192 Or just follow the instructions above directly without saving"].join(`
173
- `),score:.85}});return{action:"continue",context:{...r,recalledMemories:[...l,...c]}}}})}function gt(){Qr=null,fl=0}an();import{createRequire as gx}from"node:module";le();import*as ns from"node:fs";import*as gl from"node:path";import{randomUUID as ux}from"node:crypto";var px=`
173
+ `),score:.85}});return{action:"continue",context:{...r,recalledMemories:[...l,...c]}}}})}function gt(){Qr=null,fl=0}an();import{createRequire as yx}from"node:module";le();import*as ns from"node:fs";import*as gl from"node:path";import{randomUUID as mx}from"node:crypto";var fx=`
174
174
  CREATE TABLE IF NOT EXISTS memories (
175
175
  id TEXT PRIMARY KEY,
176
176
  text TEXT NOT NULL,
@@ -222,7 +222,7 @@ CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
222
222
  INSERT INTO memories_fts(rowid, id, user_id, text, category, tags)
223
223
  VALUES (new.rowid, new.id, new.user_id, new.text, new.category, new.tags);
224
224
  END;
225
- `,ts=class{db;constructor(e){this.db=e,this.initSchema()}initSchema(){this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.exec(px)}insert(e){let t=`mem_${ux().replace(/-/g,"").slice(0,16)}`,o=Date.now(),r=JSON.stringify(e.tags??[]),s=e.embedding?Buffer.from(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength):null;return this.db.prepare(`
225
+ `,ts=class{db;constructor(e){this.db=e,this.initSchema()}initSchema(){this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.exec(fx)}insert(e){let t=`mem_${mx().replace(/-/g,"").slice(0,16)}`,o=Date.now(),r=JSON.stringify(e.tags??[]),s=e.embedding?Buffer.from(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength):null;return this.db.prepare(`
226
226
  INSERT INTO memories (id, text, user_id, category, importance, source, session_id, event_date, tags, embedding, created_at, updated_at, last_accessed_at)
227
227
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
228
228
  `).run(t,e.text,e.userId,e.category??"general",e.importance??.5,e.source??"agent",e.sessionId??"",e.eventDate??"",r,s,o,o,o),t}searchFts(e,t,o=10){let r=e.replace(/['"*()]/g," ").trim();return r?this.db.prepare(`
@@ -237,7 +237,7 @@ END;
237
237
  SELECT id, text, category, importance, tags, created_at, access_count, embedding
238
238
  FROM memories
239
239
  WHERE user_id = ? AND is_archived = 0 AND embedding IS NOT NULL
240
- `).all(t),i=[],a=Jp(e);for(let l of s){let c=new Float32Array(l.embedding.buffer,l.embedding.byteOffset,l.embedding.byteLength/4),d=Jp(c),u=mx(a,d);u>=r&&i.push({id:l.id,text:l.text,score:u*.7+l.importance*.3,category:l.category,importance:l.importance,metadata:{tags:JSON.parse(l.tags||"[]"),createdAt:l.created_at,accessCount:l.access_count,cosineSimilarity:u}})}return i.sort((l,c)=>c.score-l.score),i.slice(0,o)}searchHybrid(e,t,o,r=10){let s=this.searchFts(e,o,r*2);if(!t)return s.slice(0,r);let i=this.searchVector(t,o,r*2),a=new Map;for(let l of s)a.set(l.id,l);for(let l of i){let c=a.get(l.id);(!c||l.score>c.score)&&a.set(l.id,l)}return Array.from(a.values()).sort((l,c)=>c.score-l.score).slice(0,r)}listByUser(e,t=1,o=50,r=!0){let s=(t-1)*o,i=r?"AND is_archived = 0":"";return this.db.prepare(`
240
+ `).all(t),i=[],a=Jp(e);for(let l of s){let c=new Float32Array(l.embedding.buffer,l.embedding.byteOffset,l.embedding.byteLength/4),d=Jp(c),u=gx(a,d);u>=r&&i.push({id:l.id,text:l.text,score:u*.7+l.importance*.3,category:l.category,importance:l.importance,metadata:{tags:JSON.parse(l.tags||"[]"),createdAt:l.created_at,accessCount:l.access_count,cosineSimilarity:u}})}return i.sort((l,c)=>c.score-l.score),i.slice(0,o)}searchHybrid(e,t,o,r=10){let s=this.searchFts(e,o,r*2);if(!t)return s.slice(0,r);let i=this.searchVector(t,o,r*2),a=new Map;for(let l of s)a.set(l.id,l);for(let l of i){let c=a.get(l.id);(!c||l.score>c.score)&&a.set(l.id,l)}return Array.from(a.values()).sort((l,c)=>c.score-l.score).slice(0,r)}listByUser(e,t=1,o=50,r=!0){let s=(t-1)*o,i=r?"AND is_archived = 0":"";return this.db.prepare(`
241
241
  SELECT * FROM memories
242
242
  WHERE user_id = ? ${i}
243
243
  ORDER BY created_at DESC
@@ -313,41 +313,41 @@ END;
313
313
  ORDER BY importance ASC, access_count ASC, created_at ASC
314
314
  LIMIT ?
315
315
  )
316
- `).run(Date.now(),e,r).changes}close(){this.db.close()}};function Xp(n){return{id:n.id,text:n.text,userId:n.user_id,category:n.category,importance:n.importance,confidence:n.confidence??1,source:n.source,sessionId:n.session_id,eventDate:n.event_date,tags:JSON.parse(n.tags||"[]"),embedding:n.embedding?new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4):null,createdAt:n.created_at,updatedAt:n.updated_at,accessCount:n.access_count,lastAccessedAt:n.last_accessed_at,isArchived:!!n.is_archived}}function Jp(n){let e=0;for(let o=0;o<n.length;o++)e+=n[o]*n[o];if(e=Math.sqrt(e),e===0)return n;let t=new Float32Array(n.length);for(let o=0;o<n.length;o++)t[o]=n[o]/e;return t}function mx(n,e){let t=0,o=Math.min(n.length,e.length);for(let r=0;r<o;r++)t+=n[r]*e[r];return t}function Qp(){let n=gl.join(H(),"memory");return ns.existsSync(n)||ns.mkdirSync(n,{recursive:!0}),gl.join(n,"memories.db")}import{createRequire as bl}from"node:module";import*as os from"node:path";import*as zn from"node:fs";var jo=class{dimensions=0;model="none";async embed(e){return new Float32Array(0)}async embedBatch(e){return e.map(()=>new Float32Array(0))}},hl=class{dimensions;model;primary;fallback;onFallback;constructor(e){this.primary=e.primary,this.fallback=e.fallback,this.onFallback=e.onFallback,this.dimensions=e.primary.dimensions,this.model=`${e.primary.model}+fallback:${e.fallback.model}`}async embed(e){try{return await this.primary.embed(e)}catch(t){return this.onFallback?.(t),this.fallback.embed(e)}}async embedBatch(e){try{return await this.primary.embedBatch(e)}catch(t){return this.onFallback?.(t),this.fallback.embedBatch(e)}}},yl=class{dimensions;model;baseUrl;apiKey;timeoutMs;format;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.model=e.model,this.dimensions=e.dimensions??1536,this.timeoutMs=e.timeoutMs??1e4,this.format=e.format??"openai"}async embed(e){return(await this.embedBatch([e]))[0]}async embedBatch(e){if(e.length===0)return[];let t=new AbortController,o=setTimeout(()=>t.abort(),this.timeoutMs);try{let{url:r,body:s}=this.buildRequest(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s),signal:t.signal});if(!i.ok){let l=await i.text().catch(()=>"");throw new Error(`Embedding API error [${this.format}]: ${i.status} ${i.statusText}${l?` \u2014 ${l.slice(0,200)}`:""}`)}let a=await i.json();return this.parseResponse(a,e.length)}finally{clearTimeout(o)}}buildRequest(e){switch(this.format){case"minimax":return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,texts:e,type:"db"}};case"volcengine":return{url:`${this.baseUrl}/v1/embeddings/multimodal`,body:{model:this.model,input:e.map(t=>({type:"text",text:t})),dimensions:this.dimensions}};default:return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,input:e,dimensions:this.dimensions}}}}parseResponse(e,t){switch(this.format){case"minimax":{let o=e.vectors;if(!o||o.length===0)throw new Error("MiniMax embedding returned empty vectors");return o.map(r=>new Float32Array(r))}case"volcengine":{let o=e.data;if(Array.isArray(o))return o.map(r=>new Float32Array(r.embedding));if(o?.embedding)return[new Float32Array(o.embedding)];throw new Error("Volcengine embedding returned unexpected structure")}default:{let o=e.data;if(!o||o.length===0)throw new Error("OpenAI embedding returned empty data");return o.sort((s,i)=>s.index-i.index).map(s=>new Float32Array(s.embedding))}}}};function Zp(){let n=process.env.HOME||process.env.USERPROFILE||"",e=os.join(n,".qlogicagent","models");return zn.existsSync(e)||zn.mkdirSync(e,{recursive:!0}),e}var Kn=class{dimensions;model;maxLength;localModelPath;pipeline=null;loading=null;constructor(e){this.model=e?.modelId??"Xenova/bge-small-zh-v1.5",this.dimensions=e?.dimensions??512,this.maxLength=e?.maxLength??256,this.localModelPath=e?.localModelPath}async getPipeline(){return this.pipeline?this.pipeline:this.loading?this.loading:(this.loading=(async()=>{let e;try{e=await import(bl(import.meta.url).resolve("@xenova/transformers"))}catch{throw new Error("ONNX embedding requires @xenova/transformers. Install it: pnpm add @xenova/transformers")}let t="https://dl.xiaozhi.qlogicagent.com/models/onnx",o=process.env.ONNX_MODEL_MIRROR,r=process.env.HF_MIRROR||process.env.HF_ENDPOINT,s=o||r||t;e.env&&(e.env.remoteHost=s);let i=Zp();e.env&&(e.env.cacheDir=i);let{pipeline:a}=e;return this.localModelPath&&zn.existsSync(this.localModelPath)?this.pipeline=await a("feature-extraction",this.localModelPath,{quantized:!0,local_files_only:!0}):this.pipeline=await a("feature-extraction",this.model,{quantized:!0}),this.pipeline})(),this.loading)}async embed(e){return(await this.embedBatch([e]))[0]}async embedBatch(e){if(e.length===0)return[];let t=await this.getPipeline(),o=[];for(let r of e){let s=r.slice(0,this.maxLength*4),i=await t(s,{pooling:"mean",normalize:!0});o.push(new Float32Array(i.data))}return o}async warmup(){await this.getPipeline()}};async function em(n){let e=n?.modelId??"Xenova/bge-small-zh-v1.5",t=n?.dimensions??512;try{bl(import.meta.url).resolve("@xenova/transformers")}catch{return{onnxAvailable:!1,modelCached:!1,modelDownloaded:!1,dimensions:t,error:"@xenova/transformers not installed"}}let o=Zp(),r=os.join(o,e.replace("/","_")),s=os.join(r,"onnx","model_quantized.onnx");if(zn.existsSync(s))return{onnxAvailable:!0,modelCached:!0,modelDownloaded:!1,dimensions:t};try{return await new Kn(n).warmup(),{onnxAvailable:!0,modelCached:!1,modelDownloaded:!0,dimensions:t}}catch(a){return{onnxAvailable:!0,modelCached:!1,modelDownloaded:!1,dimensions:t,error:a.message}}}function tm(n){if(n){if(n.strategy==="none")return new jo;if(n.strategy==="api"&&n.api){let e=new yl(n.api);if(n.fallbackStrategy==="onnx"){let t=new Kn(n.fallbackOnnx);return new hl({primary:e,fallback:t,onFallback:o=>{console.warn(`[embedding] Primary API failed, using local ONNX fallback: ${o.message}`)}})}return e}return n.strategy==="onnx"?new Kn(n.onnx):new jo}try{return bl(import.meta.url).resolve("@xenova/transformers"),new Kn}catch{return new jo}}var fx={qwen:{format:"openai",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode",defaultModel:"text-embedding-v3",defaultDimensions:1024},zhipu:{format:"openai",baseUrl:"https://open.bigmodel.cn/api/paas",defaultModel:"embedding-3",defaultDimensions:2048},minimax:{format:"minimax",baseUrl:"https://api.minimax.chat",defaultModel:"embo-01",defaultDimensions:1024},volcengine:{format:"volcengine",baseUrl:"https://ark.cn-beijing.volces.com/api",defaultModel:"doubao-embedding-vision-251215",defaultDimensions:1024},openai:{format:"openai",baseUrl:"https://api.openai.com",defaultModel:"text-embedding-3-small",defaultDimensions:1536},google:{format:"openai",baseUrl:"https://generativelanguage.googleapis.com",defaultModel:"text-embedding-004",defaultDimensions:768},deepseek:{format:"openai",baseUrl:"https://api.deepseek.com",defaultModel:"text-embedding-v1",defaultDimensions:1024}};function kl(n,e,t){let o=fx[n.toLowerCase()];return o?{baseUrl:t?.baseUrl||o.baseUrl,apiKey:e,model:t?.model||o.defaultModel,dimensions:t?.dimensions||o.defaultDimensions,format:o.format}:null}var nm="qmemory-local",vl=class{providerId=nm;store;embedding;userIdPrefix;dbPath;constructor(e){if(this.dbPath=Qp(),this.userIdPrefix=e.userIdPrefix??"",this.embedding=tm(e.embedding),!e.createDatabase)throw new Error("LocalMemoryProvider requires a createDatabase factory. Install better-sqlite3 and pass: (path) => new Database(path)");let t=e.createDatabase(this.dbPath);this.store=new ts(t)}resolveUserId(e){return this.userIdPrefix?`${this.userIdPrefix}:${e}`:e}async search(e,t,o){let r=this.resolveUserId(t),s=o?.limit??10,i=o?.minScore??.1,a=null;if(this.embedding.dimensions>0)try{a=await this.embedding.embed(e)}catch{}let l=Math.min(s*3,50),c=this.store.searchHybrid(e,a,r,l),d=this.rerank(c.map(u=>({id:u.id,text:u.text,score:u.score,category:u.category,metadata:{...u.metadata,createdAt:u.metadata?.createdAt,accessCount:u.metadata?.accessCount}})),{preferredCategories:o?.preferredCategories});for(let u of d.slice(0,3))this.store.recordAccess(u.id);return d.filter(u=>u.score>=i).slice(0,s).map(u=>({blockId:u.id,text:u.text,score:u.score,source:nm,metadata:u.metadata}))}async ingest(e,t,o){let r=this.resolveUserId(t);for(let s of e){if(!s.content||s.content.trim().length<10)continue;let i;if(this.embedding.dimensions>0)try{i=await this.embedding.embed(s.content)}catch{}this.store.insert({text:s.content,userId:r,category:"conversation",importance:.4,source:o?.source??"turn",sessionId:o?.sessionId??"",embedding:i?.length?i:void 0})}}async addText(e,t,o){let r=this.resolveUserId(t),s;if(this.embedding.dimensions>0)try{s=await this.embedding.embed(e)}catch{}if(s?.length){let i=this.store.searchVector(s,r,3,.82);for(let a of i){let l=a.metadata?.cosineSimilarity;if(l&&l>=.92)return this.store.recordAccess(a.id),{memoriesAdded:0};l&&l>=.82&&this.store.archive(a.id)}}return this.store.insert({text:e,userId:r,category:o?.category??"fact",importance:o?.importance??.6,source:o?.source??"agent",sessionId:o?.sessionId??"",embedding:s?.length?s:void 0}),{memoriesAdded:1}}async remove(e){return this.store.delete(e)}async ingestExtracted(e,t,o){if(e.length===0)return{memoriesAdded:0};let r=this.resolveUserId(t),s=null;if(this.embedding.dimensions>0)try{s=await this.embedding.embedBatch(e.map(a=>a.text))}catch{}let i=0;for(let a=0;a<e.length;a++){let l=e[a];this.store.insert({text:l.text,userId:r,category:l.category??"general",importance:l.importance??.5,source:o?.source??"agent",sessionId:o?.sessionId??"",eventDate:l.event_date??"",tags:l.tags??[],embedding:s?.[a]?.length?s[a]:void 0}),i++}return{memoriesAdded:i}}async triggerDecay(e,t=90){let o=this.resolveUserId(e),r=this.store.runFullDecay(o),s=this.store.enforceCapacityLimit(o,1e4);return r.total+s>10&&(this.store.exportAndPurgeArchived(o,200),this.store.vacuum()),{decayed:r.total+s}}async feedback(e,t){let o=0;for(let r of e)this.store.applyFeedback(r,t)&&o++;return{affected:o}}getProfile(e,t){return this.store.getProfile(this.resolveUserId(e),t)}setProfile(e,t,o){this.store.setProfile(this.resolveUserId(e),t,o)}getAllProfiles(e){return this.store.getAllProfiles(this.resolveUserId(e))}deleteProfile(e,t){return this.store.deleteProfile(this.resolveUserId(e),t)}getTemporalSlice(e,t,o,r){return this.store.getTemporalSlice(this.resolveUserId(e),t,o,r)}getActivitySummary(e,t=7){return this.store.getActivitySummary(this.resolveUserId(e),t)}list(e,t){return this.store.listByUser(this.resolveUserId(e),t?.page??1,t?.pageSize??500,t?.activeOnly??!0)}findByEventDate(e,t,o=1){return this.store.findByEventDate(this.resolveUserId(e),t,o)}async findRelatedEvents(e,t,o){let r=this.resolveUserId(t),s=o?.minSimilarity??.55,i=o?.maxSimilarity??.82,a=o?.maxDaysBack??14,l=o?.limit??5;if(this.embedding.dimensions===0)return[];let c;try{c=await this.embedding.embed(e)}catch{return[]}let d=this.store.searchVector(c,r,l*3,s),u=Date.now()-a*864e5;return d.filter(p=>{let m=p.metadata?.cosineSimilarity??p.score,h=p.metadata?.createdAt??0;return m>=s&&m<i&&h>=u}).slice(0,l).map(p=>({id:p.id,text:p.text,score:p.metadata?.cosineSimilarity??p.score,date:new Date(p.metadata?.createdAt??Date.now()).toISOString().slice(0,10)}))}synthesizeTimeline(e,t,o){let r=this.getTemporalSlice(e,t,o);if(r.length===0)return"No memories in this time range.";let s=[];for(let i of r){s.push(`## ${i.date}`);for(let a of i.memories){let l=a.importance>=.7?"\u2605":"\xB7";s.push(`${l} [${a.category}] ${a.text}`)}}return s.join(`
317
- `)}rerank(e,t){let o=(t?.recencyBoostDays??7)*864e5,r=Date.now(),s=new Set(t?.preferredCategories??[]);return e.map(i=>{let a=i.score,l=i.metadata?.createdAt??0;if(l>0){let d=r-l;d<o&&(a+=.1*(1-d/o))}let c=i.metadata?.accessCount??0;return c>0&&(a+=Math.min(.05,c*.01)),s.size>0&&i.category&&s.has(i.category)&&(a+=.08),{...i,score:Math.min(1,a)}}).sort((i,a)=>a.score-i.score)}async health(){return{status:"healthy",memoryCount:0,dbPath:this.dbPath}}count(e){return this.store.count(this.resolveUserId(e))}async resetUser(e){return this.store.resetUser(this.resolveUserId(e))}close(){this.store.close()}};function om(n){return new vl(n)}mt();function Sl(n){try{let e=hx();if(e){let t={projectRoot:n.projectRoot,userIdPrefix:n.userIdPrefix,embedding:n.embedding,createDatabase:e};return{provider:om(t),mode:"local"}}}catch(e){return{provider:null,mode:"none",error:`Local provider failed: ${e.message}`}}return{provider:null,mode:"none",error:"better-sqlite3 not available"}}function hx(){try{let e=gx(import.meta.url)("better-sqlite3"),t=e.default??e;if(typeof t!="function")return null;let o=t;return r=>new o(r)}catch{return null}}function Tl(n){let e=process.env.QMEMORY_USER_PREFIX||void 0,o=X().getActiveModel("embedding");if(o){let i={projectRoot:n,userIdPrefix:e,embedding:{strategy:"api",api:{baseUrl:o.baseUrl||"",apiKey:o.apiKey,model:o.model||"text-embedding-3-small"},fallbackStrategy:"onnx"}};return o.keyHandle.release({success:!0}),i}let r=process.env.QMEMORY_EMBEDDING_STRATEGY||"auto",s;if(r==="auto")s=yx();else if(r==="api"){let i=process.env.QMEMORY_EMBEDDING_BASE_URL||void 0,a=process.env.QMEMORY_EMBEDDING_API_KEY||void 0,l=process.env.QMEMORY_EMBEDDING_MODEL||"text-embedding-3-small";i&&a&&(s={strategy:"api",api:{baseUrl:i,apiKey:a,model:l}})}else if(r==="onnx"){let i=process.env.QMEMORY_ONNX_MODEL_ID||void 0;s={strategy:"onnx",onnx:i?{modelId:i}:void 0}}return{projectRoot:n,userIdPrefix:e,embedding:s}}var rm={qwen:["QWEN_API_KEY","DASHSCOPE_API_KEY"],zhipu:["ZHIPU_API_KEY","GLM_API_KEY"],minimax:["MINIMAX_API_KEY"],volcengine:["VOLCENGINE_API_KEY","ARK_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],deepseek:["DEEPSEEK_API_KEY"]};function yx(){let t=X().peekActiveModel("textGeneration")?.provider?.toLowerCase();if(t){let c=bx(t);if(c){let d=kl(t,c);if(d)return{strategy:"api",api:d,fallbackStrategy:"onnx"}}}for(let[c,d]of Object.entries(rm))for(let u of d){let p=process.env[u];if(p){let m=kl(c,p);if(m)return{strategy:"api",api:m,fallbackStrategy:"onnx"}}}let o=process.env.QMEMORY_TEI_URL||process.env.QMEMORY_GPU_ECS_URL,r=process.env.QMEMORY_TEI_FALLBACK_URL,s=process.env.QMEMORY_TEI_KEY||process.env.QMEMORY_GPU_ECS_KEY||"none",i=process.env.QMEMORY_TEI_MODEL||"BAAI/bge-m3",a=parseInt(process.env.QMEMORY_TEI_DIMENSIONS||"1024",10),l=o||r;return l?{strategy:"api",api:{baseUrl:l,apiKey:s,model:i,dimensions:a,format:"openai"},fallbackStrategy:"onnx"}:{strategy:"onnx"}}function bx(n){let e=rm[n];if(e)for(let t of e){let o=process.env[t];if(o)return o}}var ln=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_listeners=new Set;constructor(e){this.sessionId=e}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}get turnCount(){return this._turnCount}get toolCallCount(){return this._toolCallCount}getModelUsage(e){return this._modelUsage.get(e)}getAllModelUsage(){let e={};for(let[t,o]of this._modelUsage)e[t]={...o};return e}addUsage(e,t){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let o=this._modelUsage.get(t);o?(o.inputTokens+=e.inputTokens,o.outputTokens+=e.outputTokens,o.cacheRead+=e.cacheRead??0,o.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(t,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,t,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;case"per_token":s.outputTokens+=o;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[t,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{}}};le();je();import*as ue from"node:fs";import*as qe from"node:path";var sm="transcript.jsonl",qt="metadata.json";function kx(n){return Vt(n)}function qn(n,e){let t=n.replace(/[^a-zA-Z0-9_-]/g,"_");return qe.join(kx(e),t)}function im(n,e){let t=n.replace(/[^a-zA-Z0-9_-]/g,"_"),o=qe.join(Vt(e),t),r=qe.join(o,qt);if(ue.existsSync(r))return o}function wn(n,e){let t=im(n,e);if(!t)return null;try{let o=ue.readFileSync(qe.join(t,qt),"utf8");return JSON.parse(o)}catch{return null}}async function wl(n,e,t,o){let r=qn(n,t);try{await ue.promises.mkdir(r,{recursive:!0});let s={role:e.role,content:e.content,ts:Date.now()};o&&(s.turnId=o);let i=JSON.stringify(s)+`
316
+ `).run(Date.now(),e,r).changes}close(){this.db.close()}};function Xp(n){return{id:n.id,text:n.text,userId:n.user_id,category:n.category,importance:n.importance,confidence:n.confidence??1,source:n.source,sessionId:n.session_id,eventDate:n.event_date,tags:JSON.parse(n.tags||"[]"),embedding:n.embedding?new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4):null,createdAt:n.created_at,updatedAt:n.updated_at,accessCount:n.access_count,lastAccessedAt:n.last_accessed_at,isArchived:!!n.is_archived}}function Jp(n){let e=0;for(let o=0;o<n.length;o++)e+=n[o]*n[o];if(e=Math.sqrt(e),e===0)return n;let t=new Float32Array(n.length);for(let o=0;o<n.length;o++)t[o]=n[o]/e;return t}function gx(n,e){let t=0,o=Math.min(n.length,e.length);for(let r=0;r<o;r++)t+=n[r]*e[r];return t}function Qp(){let n=gl.join(H(),"memory");return ns.existsSync(n)||ns.mkdirSync(n,{recursive:!0}),gl.join(n,"memories.db")}import{createRequire as bl}from"node:module";import*as os from"node:path";import*as zn from"node:fs";var jo=class{dimensions=0;model="none";async embed(e){return new Float32Array(0)}async embedBatch(e){return e.map(()=>new Float32Array(0))}},hl=class{dimensions;model;primary;fallback;onFallback;constructor(e){this.primary=e.primary,this.fallback=e.fallback,this.onFallback=e.onFallback,this.dimensions=e.primary.dimensions,this.model=`${e.primary.model}+fallback:${e.fallback.model}`}async embed(e){try{return await this.primary.embed(e)}catch(t){return this.onFallback?.(t),this.fallback.embed(e)}}async embedBatch(e){try{return await this.primary.embedBatch(e)}catch(t){return this.onFallback?.(t),this.fallback.embedBatch(e)}}},yl=class{dimensions;model;baseUrl;apiKey;timeoutMs;format;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.model=e.model,this.dimensions=e.dimensions??1536,this.timeoutMs=e.timeoutMs??1e4,this.format=e.format??"openai"}async embed(e){return(await this.embedBatch([e]))[0]}async embedBatch(e){if(e.length===0)return[];let t=new AbortController,o=setTimeout(()=>t.abort(),this.timeoutMs);try{let{url:r,body:s}=this.buildRequest(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s),signal:t.signal});if(!i.ok){let l=await i.text().catch(()=>"");throw new Error(`Embedding API error [${this.format}]: ${i.status} ${i.statusText}${l?` \u2014 ${l.slice(0,200)}`:""}`)}let a=await i.json();return this.parseResponse(a,e.length)}finally{clearTimeout(o)}}buildRequest(e){switch(this.format){case"minimax":return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,texts:e,type:"db"}};case"volcengine":return{url:`${this.baseUrl}/v1/embeddings/multimodal`,body:{model:this.model,input:e.map(t=>({type:"text",text:t})),dimensions:this.dimensions}};default:return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,input:e,dimensions:this.dimensions}}}}parseResponse(e,t){switch(this.format){case"minimax":{let o=e.vectors;if(!o||o.length===0)throw new Error("MiniMax embedding returned empty vectors");return o.map(r=>new Float32Array(r))}case"volcengine":{let o=e.data;if(Array.isArray(o))return o.map(r=>new Float32Array(r.embedding));if(o?.embedding)return[new Float32Array(o.embedding)];throw new Error("Volcengine embedding returned unexpected structure")}default:{let o=e.data;if(!o||o.length===0)throw new Error("OpenAI embedding returned empty data");return o.sort((s,i)=>s.index-i.index).map(s=>new Float32Array(s.embedding))}}}};function Zp(){let n=process.env.HOME||process.env.USERPROFILE||"",e=os.join(n,".qlogicagent","models");return zn.existsSync(e)||zn.mkdirSync(e,{recursive:!0}),e}var Kn=class{dimensions;model;maxLength;localModelPath;pipeline=null;loading=null;constructor(e){this.model=e?.modelId??"Xenova/bge-small-zh-v1.5",this.dimensions=e?.dimensions??512,this.maxLength=e?.maxLength??256,this.localModelPath=e?.localModelPath}async getPipeline(){return this.pipeline?this.pipeline:this.loading?this.loading:(this.loading=(async()=>{let e;try{e=await import(bl(import.meta.url).resolve("@xenova/transformers"))}catch{throw new Error("ONNX embedding requires @xenova/transformers. Install it: pnpm add @xenova/transformers")}let t="https://dl.xiaozhi.qlogicagent.com/models/onnx",o=process.env.ONNX_MODEL_MIRROR,r=process.env.HF_MIRROR||process.env.HF_ENDPOINT,s=o||r||t;e.env&&(e.env.remoteHost=s);let i=Zp();e.env&&(e.env.cacheDir=i);let{pipeline:a}=e;return this.localModelPath&&zn.existsSync(this.localModelPath)?this.pipeline=await a("feature-extraction",this.localModelPath,{quantized:!0,local_files_only:!0}):this.pipeline=await a("feature-extraction",this.model,{quantized:!0}),this.pipeline})(),this.loading)}async embed(e){return(await this.embedBatch([e]))[0]}async embedBatch(e){if(e.length===0)return[];let t=await this.getPipeline(),o=[];for(let r of e){let s=r.slice(0,this.maxLength*4),i=await t(s,{pooling:"mean",normalize:!0});o.push(new Float32Array(i.data))}return o}async warmup(){await this.getPipeline()}};async function em(n){let e=n?.modelId??"Xenova/bge-small-zh-v1.5",t=n?.dimensions??512;try{bl(import.meta.url).resolve("@xenova/transformers")}catch{return{onnxAvailable:!1,modelCached:!1,modelDownloaded:!1,dimensions:t,error:"@xenova/transformers not installed"}}let o=Zp(),r=os.join(o,e.replace("/","_")),s=os.join(r,"onnx","model_quantized.onnx");if(zn.existsSync(s))return{onnxAvailable:!0,modelCached:!0,modelDownloaded:!1,dimensions:t};try{return await new Kn(n).warmup(),{onnxAvailable:!0,modelCached:!1,modelDownloaded:!0,dimensions:t}}catch(a){return{onnxAvailable:!0,modelCached:!1,modelDownloaded:!1,dimensions:t,error:a.message}}}function tm(n){if(n){if(n.strategy==="none")return new jo;if(n.strategy==="api"&&n.api){let e=new yl(n.api);if(n.fallbackStrategy==="onnx"){let t=new Kn(n.fallbackOnnx);return new hl({primary:e,fallback:t,onFallback:o=>{console.warn(`[embedding] Primary API failed, using local ONNX fallback: ${o.message}`)}})}return e}return n.strategy==="onnx"?new Kn(n.onnx):new jo}try{return bl(import.meta.url).resolve("@xenova/transformers"),new Kn}catch{return new jo}}var hx={qwen:{format:"openai",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode",defaultModel:"text-embedding-v3",defaultDimensions:1024},zhipu:{format:"openai",baseUrl:"https://open.bigmodel.cn/api/paas",defaultModel:"embedding-3",defaultDimensions:2048},minimax:{format:"minimax",baseUrl:"https://api.minimax.chat",defaultModel:"embo-01",defaultDimensions:1024},volcengine:{format:"volcengine",baseUrl:"https://ark.cn-beijing.volces.com/api",defaultModel:"doubao-embedding-vision-251215",defaultDimensions:1024},openai:{format:"openai",baseUrl:"https://api.openai.com",defaultModel:"text-embedding-3-small",defaultDimensions:1536},google:{format:"openai",baseUrl:"https://generativelanguage.googleapis.com",defaultModel:"text-embedding-004",defaultDimensions:768},deepseek:{format:"openai",baseUrl:"https://api.deepseek.com",defaultModel:"text-embedding-v1",defaultDimensions:1024}};function kl(n,e,t){let o=hx[n.toLowerCase()];return o?{baseUrl:t?.baseUrl||o.baseUrl,apiKey:e,model:t?.model||o.defaultModel,dimensions:t?.dimensions||o.defaultDimensions,format:o.format}:null}var nm="qmemory-local",vl=class{providerId=nm;store;embedding;userIdPrefix;dbPath;constructor(e){if(this.dbPath=Qp(),this.userIdPrefix=e.userIdPrefix??"",this.embedding=tm(e.embedding),!e.createDatabase)throw new Error("LocalMemoryProvider requires a createDatabase factory. Install better-sqlite3 and pass: (path) => new Database(path)");let t=e.createDatabase(this.dbPath);this.store=new ts(t)}resolveUserId(e){return this.userIdPrefix?`${this.userIdPrefix}:${e}`:e}async search(e,t,o){let r=this.resolveUserId(t),s=o?.limit??10,i=o?.minScore??.1,a=null;if(this.embedding.dimensions>0)try{a=await this.embedding.embed(e)}catch{}let l=Math.min(s*3,50),c=this.store.searchHybrid(e,a,r,l),d=this.rerank(c.map(u=>({id:u.id,text:u.text,score:u.score,category:u.category,metadata:{...u.metadata,createdAt:u.metadata?.createdAt,accessCount:u.metadata?.accessCount}})),{preferredCategories:o?.preferredCategories});for(let u of d.slice(0,3))this.store.recordAccess(u.id);return d.filter(u=>u.score>=i).slice(0,s).map(u=>({blockId:u.id,text:u.text,score:u.score,source:nm,metadata:u.metadata}))}async ingest(e,t,o){let r=this.resolveUserId(t);for(let s of e){if(!s.content||s.content.trim().length<10)continue;let i;if(this.embedding.dimensions>0)try{i=await this.embedding.embed(s.content)}catch{}this.store.insert({text:s.content,userId:r,category:"conversation",importance:.4,source:o?.source??"turn",sessionId:o?.sessionId??"",embedding:i?.length?i:void 0})}}async addText(e,t,o){let r=this.resolveUserId(t),s;if(this.embedding.dimensions>0)try{s=await this.embedding.embed(e)}catch{}if(s?.length){let i=this.store.searchVector(s,r,3,.82);for(let a of i){let l=a.metadata?.cosineSimilarity;if(l&&l>=.92)return this.store.recordAccess(a.id),{memoriesAdded:0};l&&l>=.82&&this.store.archive(a.id)}}return this.store.insert({text:e,userId:r,category:o?.category??"fact",importance:o?.importance??.6,source:o?.source??"agent",sessionId:o?.sessionId??"",embedding:s?.length?s:void 0}),{memoriesAdded:1}}async remove(e){return this.store.delete(e)}async ingestExtracted(e,t,o){if(e.length===0)return{memoriesAdded:0};let r=this.resolveUserId(t),s=null;if(this.embedding.dimensions>0)try{s=await this.embedding.embedBatch(e.map(a=>a.text))}catch{}let i=0;for(let a=0;a<e.length;a++){let l=e[a];this.store.insert({text:l.text,userId:r,category:l.category??"general",importance:l.importance??.5,source:o?.source??"agent",sessionId:o?.sessionId??"",eventDate:l.event_date??"",tags:l.tags??[],embedding:s?.[a]?.length?s[a]:void 0}),i++}return{memoriesAdded:i}}async triggerDecay(e,t=90){let o=this.resolveUserId(e),r=this.store.runFullDecay(o),s=this.store.enforceCapacityLimit(o,1e4);return r.total+s>10&&(this.store.exportAndPurgeArchived(o,200),this.store.vacuum()),{decayed:r.total+s}}async feedback(e,t){let o=0;for(let r of e)this.store.applyFeedback(r,t)&&o++;return{affected:o}}getProfile(e,t){return this.store.getProfile(this.resolveUserId(e),t)}setProfile(e,t,o){this.store.setProfile(this.resolveUserId(e),t,o)}getAllProfiles(e){return this.store.getAllProfiles(this.resolveUserId(e))}deleteProfile(e,t){return this.store.deleteProfile(this.resolveUserId(e),t)}getTemporalSlice(e,t,o,r){return this.store.getTemporalSlice(this.resolveUserId(e),t,o,r)}getActivitySummary(e,t=7){return this.store.getActivitySummary(this.resolveUserId(e),t)}list(e,t){return this.store.listByUser(this.resolveUserId(e),t?.page??1,t?.pageSize??500,t?.activeOnly??!0)}findByEventDate(e,t,o=1){return this.store.findByEventDate(this.resolveUserId(e),t,o)}async findRelatedEvents(e,t,o){let r=this.resolveUserId(t),s=o?.minSimilarity??.55,i=o?.maxSimilarity??.82,a=o?.maxDaysBack??14,l=o?.limit??5;if(this.embedding.dimensions===0)return[];let c;try{c=await this.embedding.embed(e)}catch{return[]}let d=this.store.searchVector(c,r,l*3,s),u=Date.now()-a*864e5;return d.filter(p=>{let m=p.metadata?.cosineSimilarity??p.score,h=p.metadata?.createdAt??0;return m>=s&&m<i&&h>=u}).slice(0,l).map(p=>({id:p.id,text:p.text,score:p.metadata?.cosineSimilarity??p.score,date:new Date(p.metadata?.createdAt??Date.now()).toISOString().slice(0,10)}))}synthesizeTimeline(e,t,o){let r=this.getTemporalSlice(e,t,o);if(r.length===0)return"No memories in this time range.";let s=[];for(let i of r){s.push(`## ${i.date}`);for(let a of i.memories){let l=a.importance>=.7?"\u2605":"\xB7";s.push(`${l} [${a.category}] ${a.text}`)}}return s.join(`
317
+ `)}rerank(e,t){let o=(t?.recencyBoostDays??7)*864e5,r=Date.now(),s=new Set(t?.preferredCategories??[]);return e.map(i=>{let a=i.score,l=i.metadata?.createdAt??0;if(l>0){let d=r-l;d<o&&(a+=.1*(1-d/o))}let c=i.metadata?.accessCount??0;return c>0&&(a+=Math.min(.05,c*.01)),s.size>0&&i.category&&s.has(i.category)&&(a+=.08),{...i,score:Math.min(1,a)}}).sort((i,a)=>a.score-i.score)}async health(){return{status:"healthy",memoryCount:0,dbPath:this.dbPath}}count(e){return this.store.count(this.resolveUserId(e))}async resetUser(e){return this.store.resetUser(this.resolveUserId(e))}close(){this.store.close()}};function om(n){return new vl(n)}mt();function Sl(n){try{let e=bx();if(e){let t={projectRoot:n.projectRoot,userIdPrefix:n.userIdPrefix,embedding:n.embedding,createDatabase:e};return{provider:om(t),mode:"local"}}}catch(e){return{provider:null,mode:"none",error:`Local provider failed: ${e.message}`}}return{provider:null,mode:"none",error:"better-sqlite3 not available"}}function bx(){try{let e=yx(import.meta.url)("better-sqlite3"),t=e.default??e;if(typeof t!="function")return null;let o=t;return r=>new o(r)}catch{return null}}function Tl(n){let e=process.env.QMEMORY_USER_PREFIX||void 0,o=X().getActiveModel("embedding");if(o){let i={projectRoot:n,userIdPrefix:e,embedding:{strategy:"api",api:{baseUrl:o.baseUrl||"",apiKey:o.apiKey,model:o.model||"text-embedding-3-small"},fallbackStrategy:"onnx"}};return o.keyHandle.release({success:!0}),i}let r=process.env.QMEMORY_EMBEDDING_STRATEGY||"auto",s;if(r==="auto")s=kx();else if(r==="api"){let i=process.env.QMEMORY_EMBEDDING_BASE_URL||void 0,a=process.env.QMEMORY_EMBEDDING_API_KEY||void 0,l=process.env.QMEMORY_EMBEDDING_MODEL||"text-embedding-3-small";i&&a&&(s={strategy:"api",api:{baseUrl:i,apiKey:a,model:l}})}else if(r==="onnx"){let i=process.env.QMEMORY_ONNX_MODEL_ID||void 0;s={strategy:"onnx",onnx:i?{modelId:i}:void 0}}return{projectRoot:n,userIdPrefix:e,embedding:s}}var rm={qwen:["QWEN_API_KEY","DASHSCOPE_API_KEY"],zhipu:["ZHIPU_API_KEY","GLM_API_KEY"],minimax:["MINIMAX_API_KEY"],volcengine:["VOLCENGINE_API_KEY","ARK_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],deepseek:["DEEPSEEK_API_KEY"]};function kx(){let t=X().peekActiveModel("textGeneration")?.provider?.toLowerCase();if(t){let c=vx(t);if(c){let d=kl(t,c);if(d)return{strategy:"api",api:d,fallbackStrategy:"onnx"}}}for(let[c,d]of Object.entries(rm))for(let u of d){let p=process.env[u];if(p){let m=kl(c,p);if(m)return{strategy:"api",api:m,fallbackStrategy:"onnx"}}}let o=process.env.QMEMORY_TEI_URL||process.env.QMEMORY_GPU_ECS_URL,r=process.env.QMEMORY_TEI_FALLBACK_URL,s=process.env.QMEMORY_TEI_KEY||process.env.QMEMORY_GPU_ECS_KEY||"none",i=process.env.QMEMORY_TEI_MODEL||"BAAI/bge-m3",a=parseInt(process.env.QMEMORY_TEI_DIMENSIONS||"1024",10),l=o||r;return l?{strategy:"api",api:{baseUrl:l,apiKey:s,model:i,dimensions:a,format:"openai"},fallbackStrategy:"onnx"}:{strategy:"onnx"}}function vx(n){let e=rm[n];if(e)for(let t of e){let o=process.env[t];if(o)return o}}var ln=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_listeners=new Set;constructor(e){this.sessionId=e}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}get turnCount(){return this._turnCount}get toolCallCount(){return this._toolCallCount}getModelUsage(e){return this._modelUsage.get(e)}getAllModelUsage(){let e={};for(let[t,o]of this._modelUsage)e[t]={...o};return e}addUsage(e,t){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let o=this._modelUsage.get(t);o?(o.inputTokens+=e.inputTokens,o.outputTokens+=e.outputTokens,o.cacheRead+=e.cacheRead??0,o.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(t,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,t,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;case"per_token":s.outputTokens+=o;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[t,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{}}};le();je();import*as ue from"node:fs";import*as qe from"node:path";var sm="transcript.jsonl",qt="metadata.json";function Sx(n){return Vt(n)}function qn(n,e){let t=n.replace(/[^a-zA-Z0-9_-]/g,"_");return qe.join(Sx(e),t)}function im(n,e){let t=n.replace(/[^a-zA-Z0-9_-]/g,"_"),o=qe.join(Vt(e),t),r=qe.join(o,qt);if(ue.existsSync(r))return o}function wn(n,e){let t=im(n,e);if(!t)return null;try{let o=ue.readFileSync(qe.join(t,qt),"utf8");return JSON.parse(o)}catch{return null}}async function wl(n,e,t,o){let r=qn(n,t);try{await ue.promises.mkdir(r,{recursive:!0});let s={role:e.role,content:e.content,ts:Date.now()};o&&(s.turnId=o);let i=JSON.stringify(s)+`
318
318
  `;return await ue.promises.appendFile(qe.join(r,sm),i,"utf8"),!0}catch(s){return console.error(`[session-persistence] appendMessage failed for ${n}: ${s.message}`),!1}}async function am(n,e,t,o){let r=qn(n,o);await ue.promises.mkdir(r,{recursive:!0});let s={};try{let c=await ue.promises.readFile(qe.join(r,qt),"utf8");s=JSON.parse(c)}catch{}let i=new Date().toISOString(),a={sessionId:n,projectId:t.projectId??s.projectId??"",createdAt:t.createdAt??s.createdAt??i,lastActiveAt:i,model:t.model??s.model,cwd:t.cwd??s.cwd,turnCount:e.turnCount,messageCount:t.messageCount??s.messageCount??0,title:t.title??s.title,pinnedAt:t.pinnedAt!==void 0?t.pinnedAt:s.pinnedAt,archivedAt:t.archivedAt!==void 0?t.archivedAt:s.archivedAt,type:t.type??s.type,ownerId:t.ownerId??s.ownerId,groupKey:t.groupKey??s.groupKey,groupName:t.groupName??s.groupName,groupPlatform:t.groupPlatform??s.groupPlatform,sealedAt:t.sealedAt??s.sealedAt,previousSessionId:t.previousSessionId??s.previousSessionId,carryoverSummary:t.carryoverSummary??s.carryoverSummary,totalInputTokens:e.totalInputTokens,totalOutputTokens:e.totalOutputTokens},l=qe.join(r,qt+".tmp");await ue.promises.writeFile(l,JSON.stringify(a,null,2),"utf8"),await ue.promises.rename(l,qe.join(r,qt))}async function tt(n,e,t){let r=im(n,t)??qn(n,t),s=qe.join(r,qt),i=new Date().toISOString(),a;try{let d=await ue.promises.readFile(s,"utf8");a=JSON.parse(d)}catch{await ue.promises.mkdir(r,{recursive:!0}),a={sessionId:n,projectId:e.projectId??"",createdAt:i,lastActiveAt:i,turnCount:0,messageCount:0,...e};let d=s+".tmp";return await ue.promises.writeFile(d,JSON.stringify(a,null,2),"utf8"),await ue.promises.rename(d,s),a}let l={...a};e.title!==void 0&&(l.title=e.title??void 0),e.pinnedAt!==void 0&&(l.pinnedAt=e.pinnedAt??void 0),e.archivedAt!==void 0&&(l.archivedAt=e.archivedAt??void 0),e.sealedAt!==void 0&&(l.sealedAt=e.sealedAt??void 0),e.previousSessionId!==void 0&&(l.previousSessionId=e.previousSessionId??void 0),e.carryoverSummary!==void 0&&(l.carryoverSummary=e.carryoverSummary??void 0),e.projectId!==void 0&&(l.projectId=e.projectId??l.projectId),e.type!==void 0&&(l.type=e.type??void 0),e.ownerId!==void 0&&(l.ownerId=e.ownerId??void 0),e.groupKey!==void 0&&(l.groupKey=e.groupKey??void 0),e.groupName!==void 0&&(l.groupName=e.groupName??void 0),e.groupPlatform!==void 0&&(l.groupPlatform=e.groupPlatform??void 0),l.lastActiveAt=i;let c=s+".tmp";return await ue.promises.writeFile(c,JSON.stringify(l,null,2),"utf8"),await ue.promises.rename(c,s),l}async function xl(n,e){try{await ue.promises.access(e,ue.constants.R_OK)}catch{return console.error(`[session-persistence] loadSessionForResume: projectRoot not accessible: ${e}`),null}let t=qn(n,e),o=qe.join(t,sm),r=qe.join(t,qt),s=[],i=0;try{let d=await ue.promises.readFile(o,"utf8");for(let u of d.split(`
319
- `))if(u.trim())try{let p=JSON.parse(u);s.push({role:p.role,content:p.content??null})}catch{i++}i>0&&console.warn(`[session-persistence] ${i} corrupt line(s) skipped in ${o}`)}catch{return null}if(s.length===0&&i>0)return console.error(`[session-persistence] Transcript fully corrupt for session ${n}`),null;let a=new Date().toISOString(),l={sessionId:n,projectId:"",createdAt:a,lastActiveAt:a,turnCount:0,messageCount:s.length};try{let d=await ue.promises.readFile(r,"utf8");l=JSON.parse(d)}catch{}let c=s.filter(d=>d.role!=="system");return{metadata:l,messages:c}}async function Et(n=Qi,e){let t=Vt(e),o;try{o=await ue.promises.readdir(t)}catch{return[]}let r=[];for(let s of o){let i=qe.join(t,s,qt);try{let a=await ue.promises.readFile(i,"utf8"),l=JSON.parse(a);r.push({sessionId:l.sessionId,title:l.title,lastActiveAt:l.lastActiveAt,messageCount:l.messageCount,model:l.model,pinnedAt:l.pinnedAt,archivedAt:l.archivedAt,sealedAt:l.sealedAt,projectId:l.projectId,type:l.type,createdAt:l.createdAt,groupKey:l.groupKey,previousSessionId:l.previousSessionId})}catch{}}return r.sort((s,i)=>s.lastActiveAt>i.lastActiveAt?-1:s.lastActiveAt<i.lastActiveAt?1:0),r.slice(0,n)}async function Rl(n,e){let t=qn(n,e);await ue.promises.rm(t,{recursive:!0,force:!0})}function vx(n){return n.turnCount<Zi?!1:n.taskSummaryGeneratedAt?n.turnCount-(n.taskSummaryGeneratedAt??0)>=ea:!0}var Sx="Based on the user's message below, generate a very short session title (2-8 Chinese characters or 3-6 English words). The title should capture the main topic or intent. Reply with ONLY the title text, no quotes, no punctuation.";async function lm(n,e){if(!n.trim())return null;try{let t=e.transport.stream({model:e.model,messages:[{role:"system",content:Sx},{role:"user",content:n.slice(0,500)}],tools:[],maxTokens:30},e.apiKey),o="";for await(let r of t)r.type==="delta"&&(o+=r.text);return o=o.trim().replace(/^["'""'']+|["'""'']+$/g,""),o||null}catch{return null}}async function cm(n,e,t,o,r){if(!vx(e))return null;try{let i=t.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
320
- `),a=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:i}],tools:[],maxTokens:200},o.apiKey),l="";for await(let u of a)u.type==="delta"&&(l+=u.text);if(l=l.trim(),!l)return null;let c=qn(n,r),d=qe.join(c,qt);try{let u=await ue.promises.readFile(d,"utf8"),p=JSON.parse(u);p.taskSummary=l,p.taskSummaryGeneratedAt=e.turnCount;let m=d+".tmp";await ue.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await ue.promises.rename(m,d)}catch{}return l}catch{return null}}al();import{randomUUID as $L}from"node:crypto";var Tx=3e4;var ss=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),!rs(o.lifecycle)&&rs(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&&rs(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=Tx){let t=Date.now();for(let[o,r]of this.tasks)rs(r.lifecycle)&&r.endedAt&&t-r.endedAt>e&&(this.tasks.delete(o),this.notify(o,null))}};function rs(n){return n==="completed"||n==="failed"||n==="cancelled"||n==="timeout"}le();import{watch as wx}from"node:fs";import{stat as xx}from"node:fs/promises";import{join as dm,relative as Rx,resolve as _x}from"node:path";var Ax=[`${He}/settings.json`,"INSTRUCTIONS.md",`${He}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${He}/rules`],Px=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${He}/rules`],_l=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 Ax){let t=dm(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=wx(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(r,s)=>{let i=s?dm(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 xx(e)}catch{r="deleted"}let s=Rx(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(()=>{}),Px.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=_x(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 um(n){let e=new _l(n);return await e.start(),e}le();je();import{readFile as Ix,readdir as Cx,stat as Ex}from"node:fs/promises";import{dirname as is,extname as Mx,isAbsolute as Ox,join as Xn,parse as mm,resolve as pm}from"node:path";import{homedir as Dx}from"node:os";var Lx="INSTRUCTIONS.md",Nx="INSTRUCTIONS.local.md",$x=[".instructions.md"],Ux=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 jx(n){try{return await Ix(n,"utf-8")}catch{return null}}function Fx(n){return n.includes("<!--")?n.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):n}function Bx(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(l=>l.trim()).filter(Boolean);let a=s.map(l=>l.endsWith("/**")?l.slice(0,-3):l).filter(l=>l.length>0&&l!=="**");return{content:o,globs:a.length>0?a:void 0}}function Wx(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 l=a.indexOf("#");if(l!==-1&&(a=a.substring(0,l)),!a)continue;a=a.replace(/\\ /g," ");let c;if(a.startsWith("~/"))c=Xn(Dx(),a.slice(2));else if(Ox(a))c=a;else if(a.startsWith("./"))c=pm(is(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))c=pm(is(e),a);else continue;t.add(c)}return[...t]}async function Yn(n,e,t,o=0,r){let s=n.toLowerCase();if(t.has(s)||o>=ta)return[];let i=Mx(n).toLowerCase();if(i&&!Ux.has(i))return[];t.add(s);let a=await jx(n);if(!a?.trim())return[];let{content:l,globs:c}=Bx(a),d=Fx(l);if(!d.trim())return[];let u=[],p={path:n,type:e,content:d.trim()};r&&(p.parent=r),c&&(p.globs=c),u.push(p);let m=Wx(l,n);for(let h of m){let f=await Yn(h,e,t,o+1,n);u.push(...f)}return u}async function fm(n,e,t,o,r=new Set){if(r.has(n))return[];r.add(n);let s=[];try{let i=await Cx(n,{withFileTypes:!0});for(let a of i){let l=Xn(n,a.name);if(a.isDirectory())s.push(...await fm(l,e,t,o,r));else if(a.isFile()&&a.name.endsWith(".md")){let c=await Yn(l,e,t);s.push(...c.filter(d=>o?!!d.globs:!d.globs))}}}catch{}return s}async function Gx(n){let e=n,t=mm(e).root;for(;e!==t;){try{let o=Xn(e,".git"),r=await Ex(o);if(r.isDirectory()||r.isFile())return e}catch{}e=is(e)}return null}async function Hx(n,e){let t=[],o=new Set,s=await Gx(n)??mm(n).root,i=[],a=n;for(;i.push(a),!(a===s&&a!==n);){let l=is(a);if(l===a)break;a=l}for(let l of i.reverse()){t.push(...await Yn(Xn(l,Lx),"Project",o));for(let c of $x)t.push(...await Yn(Xn(l,c),"Project",o));t.push(...await Yn(Oo(l),"Project",o)),t.push(...await fm(Gn(l),"Project",o,!1)),t.push(...await Yn(Xn(l,Nx),"Local",o))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:n,fileCount:t.length}).catch(()=>{}),t}function gm(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}:
319
+ `))if(u.trim())try{let p=JSON.parse(u);s.push({role:p.role,content:p.content??null})}catch{i++}i>0&&console.warn(`[session-persistence] ${i} corrupt line(s) skipped in ${o}`)}catch{return null}if(s.length===0&&i>0)return console.error(`[session-persistence] Transcript fully corrupt for session ${n}`),null;let a=new Date().toISOString(),l={sessionId:n,projectId:"",createdAt:a,lastActiveAt:a,turnCount:0,messageCount:s.length};try{let d=await ue.promises.readFile(r,"utf8");l=JSON.parse(d)}catch{}let c=s.filter(d=>d.role!=="system");return{metadata:l,messages:c}}async function Et(n=Qi,e){let t=Vt(e),o;try{o=await ue.promises.readdir(t)}catch{return[]}let r=[];for(let s of o){let i=qe.join(t,s,qt);try{let a=await ue.promises.readFile(i,"utf8"),l=JSON.parse(a);r.push({sessionId:l.sessionId,title:l.title,lastActiveAt:l.lastActiveAt,messageCount:l.messageCount,model:l.model,pinnedAt:l.pinnedAt,archivedAt:l.archivedAt,sealedAt:l.sealedAt,projectId:l.projectId,type:l.type,createdAt:l.createdAt,groupKey:l.groupKey,previousSessionId:l.previousSessionId})}catch{}}return r.sort((s,i)=>s.lastActiveAt>i.lastActiveAt?-1:s.lastActiveAt<i.lastActiveAt?1:0),r.slice(0,n)}async function Rl(n,e){let t=qn(n,e);await ue.promises.rm(t,{recursive:!0,force:!0})}function Tx(n){return n.turnCount<Zi?!1:n.taskSummaryGeneratedAt?n.turnCount-(n.taskSummaryGeneratedAt??0)>=ea:!0}var wx="Based on the user's message below, generate a very short session title (2-8 Chinese characters or 3-6 English words). The title should capture the main topic or intent. Reply with ONLY the title text, no quotes, no punctuation.";async function lm(n,e){if(!n.trim())return null;try{let t=e.transport.stream({model:e.model,messages:[{role:"system",content:wx},{role:"user",content:n.slice(0,500)}],tools:[],maxTokens:30},e.apiKey),o="";for await(let r of t)r.type==="delta"&&(o+=r.text);return o=o.trim().replace(/^["'""'']+|["'""'']+$/g,""),o||null}catch{return null}}async function cm(n,e,t,o,r){if(!Tx(e))return null;try{let i=t.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
320
+ `),a=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:i}],tools:[],maxTokens:200},o.apiKey),l="";for await(let u of a)u.type==="delta"&&(l+=u.text);if(l=l.trim(),!l)return null;let c=qn(n,r),d=qe.join(c,qt);try{let u=await ue.promises.readFile(d,"utf8"),p=JSON.parse(u);p.taskSummary=l,p.taskSummaryGeneratedAt=e.turnCount;let m=d+".tmp";await ue.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await ue.promises.rename(m,d)}catch{}return l}catch{return null}}al();import{randomUUID as jL}from"node:crypto";var xx=3e4;var ss=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),!rs(o.lifecycle)&&rs(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&&rs(t.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=xx){let t=Date.now();for(let[o,r]of this.tasks)rs(r.lifecycle)&&r.endedAt&&t-r.endedAt>e&&(this.tasks.delete(o),this.notify(o,null))}};function rs(n){return n==="completed"||n==="failed"||n==="cancelled"||n==="timeout"}le();import{watch as Rx}from"node:fs";import{stat as _x}from"node:fs/promises";import{join as dm,relative as Ax,resolve as Px}from"node:path";var Ix=[`${He}/settings.json`,"INSTRUCTIONS.md",`${He}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${He}/rules`],Cx=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${He}/rules`],_l=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 Ix){let t=dm(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=Rx(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(r,s)=>{let i=s?dm(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 _x(e)}catch{r="deleted"}let s=Ax(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(()=>{}),Cx.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=Px(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 um(n){let e=new _l(n);return await e.start(),e}le();je();import{readFile as Ex,readdir as Mx,stat as Ox}from"node:fs/promises";import{dirname as is,extname as Dx,isAbsolute as Lx,join as Xn,parse as mm,resolve as pm}from"node:path";import{homedir as Nx}from"node:os";var $x="INSTRUCTIONS.md",Ux="INSTRUCTIONS.local.md",jx=[".instructions.md"],Fx=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 Bx(n){try{return await Ex(n,"utf-8")}catch{return null}}function Wx(n){return n.includes("<!--")?n.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):n}function Gx(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(l=>l.trim()).filter(Boolean);let a=s.map(l=>l.endsWith("/**")?l.slice(0,-3):l).filter(l=>l.length>0&&l!=="**");return{content:o,globs:a.length>0?a:void 0}}function Hx(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 l=a.indexOf("#");if(l!==-1&&(a=a.substring(0,l)),!a)continue;a=a.replace(/\\ /g," ");let c;if(a.startsWith("~/"))c=Xn(Nx(),a.slice(2));else if(Lx(a))c=a;else if(a.startsWith("./"))c=pm(is(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))c=pm(is(e),a);else continue;t.add(c)}return[...t]}async function Yn(n,e,t,o=0,r){let s=n.toLowerCase();if(t.has(s)||o>=ta)return[];let i=Dx(n).toLowerCase();if(i&&!Fx.has(i))return[];t.add(s);let a=await Bx(n);if(!a?.trim())return[];let{content:l,globs:c}=Gx(a),d=Wx(l);if(!d.trim())return[];let u=[],p={path:n,type:e,content:d.trim()};r&&(p.parent=r),c&&(p.globs=c),u.push(p);let m=Hx(l,n);for(let h of m){let f=await Yn(h,e,t,o+1,n);u.push(...f)}return u}async function fm(n,e,t,o,r=new Set){if(r.has(n))return[];r.add(n);let s=[];try{let i=await Mx(n,{withFileTypes:!0});for(let a of i){let l=Xn(n,a.name);if(a.isDirectory())s.push(...await fm(l,e,t,o,r));else if(a.isFile()&&a.name.endsWith(".md")){let c=await Yn(l,e,t);s.push(...c.filter(d=>o?!!d.globs:!d.globs))}}}catch{}return s}async function Vx(n){let e=n,t=mm(e).root;for(;e!==t;){try{let o=Xn(e,".git"),r=await Ox(o);if(r.isDirectory()||r.isFile())return e}catch{}e=is(e)}return null}async function Kx(n,e){let t=[],o=new Set,s=await Vx(n)??mm(n).root,i=[],a=n;for(;i.push(a),!(a===s&&a!==n);){let l=is(a);if(l===a)break;a=l}for(let l of i.reverse()){t.push(...await Yn(Xn(l,$x),"Project",o));for(let c of jx)t.push(...await Yn(Xn(l,c),"Project",o));t.push(...await Yn(Oo(l),"Project",o)),t.push(...await fm(Gn(l),"Project",o,!1)),t.push(...await Yn(Xn(l,Ux),"Local",o))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:n,fileCount:t.length}).catch(()=>{}),t}function gm(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}:
321
321
 
322
322
  ${o.content.trim()}`)}return t.length>0?`${e}
323
323
 
324
324
  ${t.join(`
325
325
 
326
- `)}`:""}var Fo=null,Al=null;async function hm(n,e){return Fo&&Al===n||(Fo=await Hx(n,e),Al=n),Fo}function ym(){Fo=null,Al=null}import*as K from"node:fs";import*as q from"node:path";import{execFile as hA}from"node:child_process";var Pl=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),bm=new Set([...Pl,"agent"]);function Il(n,e){let t=e?Pl:bm;return n.filter(o=>o.function.name.startsWith("mcp__")?!0:!t.has(o.function.name))}var Yt=new Map,Cl=new Set;function km(n){Yt.clear(),Cl.clear();for(let e of n)Yt.set(e.name,e)}function Pe(n){Yt.set(n.name,n)}function El(n){for(let e of n)Yt.set(e.name,e)}function as(n){return Yt.delete(n)}function nt(n){return Yt.get(n)}function cn(){return Array.from(Yt.keys())}function vm(n){let e=Yt.get(n);return!e||e.isEnabled?.()===!1?!1:(Cl.add(n),!0)}function Mt(n=!1){let e=[];for(let t of Yt.values())t.isEnabled?.()!==!1&&(!n&&t.shouldDefer&&!Cl.has(t.name)||e.push({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters},meta:{parallelSafe:t.isConcurrencySafe??!1,isReadOnly:t.isReadOnly??!1,isDangerous:!(t.isReadOnly??!1)&&!(t.isConcurrencySafe??!1)}}));return e}var Vx="think",Kx={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(`
327
- `)}},required:["thought"]};function Sm(){return{name:Vx,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(`
328
- `),parameters:Kx,execute:async(n,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}var zx="task",qx=["create","update","delete","list","get"];var Yx={type:"object",properties:{action:{type:"string",enum:[...qx],description:"create \u2014 add a new task (auto-assigns id). update \u2014 modify a task by id (partial, supports dependency wiring). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list with summary. get \u2014 get a single task by id."},id:{type:"number",description:"[update|delete|get] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words, imperative form)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block (they depend on this task)."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task (this task depends on them)."}},required:["action"]};function Bo(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}}function Tm(n,e){let t=[],o=0,r=n??{},s=r.verificationNudge!==!1;function i(){let f=t.reduce((y,b)=>Math.max(y,b.id),0);return o=Math.max(o,f)+1,o}function a(f){return{content:[{type:"text",text:`Error: ${f}`}],details:{type:"task",error:f}}}function l(f){let y=Bo(t),b=new Set(t.filter(P=>P.status==="completed").map(P=>P.id)),k=t.map(P=>{let O=P.blockedBy?.filter($=>!b.has($));return{...P,...O?.length?{blockedBy:O}:{blockedBy:void 0}}}),x=[];if(x.push(`Task list updated. ${y.total} tasks: ${y.completed} completed, ${y.inProgress} in-progress, ${y.notStarted} not-started.`),y.blocked>0&&x.push(`${y.blocked} blocked.`),f?.created){let P=f.created;x.push(`Created task #${P.id}: "${P.title}"`)}if(f?.updated){let P=f.updated;x.push(`Updated task #${P.id}: "${P.title}"`)}if(f?.deleted!=null&&x.push(`Deleted task #${f.deleted}`),k.length>0){x.push("");for(let P of k){let O=P.status==="completed"?"\u2713":P.status==="in-progress"?"\u2192":"\u25CB",$=P.blockedBy?.length?` [blocked by #${P.blockedBy.join(", #")}]`:"",W=P.owner?` (${P.owner})`:"";x.push(` ${O} #${P.id}: ${P.title} (${P.status})${W}${$}`)}}let I=!1;if(s&&f?.updated&&f.updated.status==="completed"){let O=t.every(S=>S.status==="completed"),$=t.length,W=t.some(S=>/verif/i.test(S.title));O&&$>=3&&!W&&(I=!0,x.push(""),x.push("NOTE: You just closed out "+$+' tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (agent type="verify"). You cannot self-assign PARTIAL by listing caveats in your summary \u2014 only the verifier issues a verdict.'))}return{content:[{type:"text",text:x.join(`
326
+ `)}`:""}var Fo=null,Al=null;async function hm(n,e){return Fo&&Al===n||(Fo=await Kx(n,e),Al=n),Fo}function ym(){Fo=null,Al=null}import*as K from"node:fs";import*as q from"node:path";import{execFile as bA}from"node:child_process";var Pl=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),bm=new Set([...Pl,"agent"]);function Il(n,e){let t=e?Pl:bm;return n.filter(o=>o.function.name.startsWith("mcp__")?!0:!t.has(o.function.name))}var Yt=new Map,Cl=new Set;function km(n){Yt.clear(),Cl.clear();for(let e of n)Yt.set(e.name,e)}function Pe(n){Yt.set(n.name,n)}function El(n){for(let e of n)Yt.set(e.name,e)}function as(n){return Yt.delete(n)}function nt(n){return Yt.get(n)}function cn(){return Array.from(Yt.keys())}function vm(n){let e=Yt.get(n);return!e||e.isEnabled?.()===!1?!1:(Cl.add(n),!0)}function Mt(n=!1){let e=[];for(let t of Yt.values())t.isEnabled?.()!==!1&&(!n&&t.shouldDefer&&!Cl.has(t.name)||e.push({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters},meta:{parallelSafe:t.isConcurrencySafe??!1,isReadOnly:t.isReadOnly??!1,isDangerous:!(t.isReadOnly??!1)&&!(t.isConcurrencySafe??!1)}}));return e}var zx="think",qx={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(`
327
+ `)}},required:["thought"]};function Sm(){return{name:zx,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(`
328
+ `),parameters:qx,execute:async(n,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}var Yx="task",Xx=["create","update","delete","list","get"];var Jx={type:"object",properties:{action:{type:"string",enum:[...Xx],description:"create \u2014 add a new task (auto-assigns id). update \u2014 modify a task by id (partial, supports dependency wiring). delete \u2014 remove a task by id (cascades block refs). list \u2014 read current task list with summary. get \u2014 get a single task by id."},id:{type:"number",description:"[update|delete|get] Task id to operate on."},title:{type:"string",description:"[create|update] Task title (3-7 words, imperative form)."},description:{type:"string",description:"[create|update] Detailed task description."},status:{type:"string",enum:["not-started","in-progress","completed"],description:"[create|update] Task status. create defaults to not-started."},owner:{type:"string",description:"[create|update] Owner agent/subagent identifier."},addBlocks:{type:"array",items:{type:"number"},description:"[update] Task IDs that this task should block (they depend on this task)."},addBlockedBy:{type:"array",items:{type:"number"},description:"[update] Task IDs that should block this task (this task depends on them)."}},required:["action"]};function Bo(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}}function Tm(n,e){let t=[],o=0,r=n??{},s=r.verificationNudge!==!1;function i(){let f=t.reduce((y,b)=>Math.max(y,b.id),0);return o=Math.max(o,f)+1,o}function a(f){return{content:[{type:"text",text:`Error: ${f}`}],details:{type:"task",error:f}}}function l(f){let y=Bo(t),b=new Set(t.filter(P=>P.status==="completed").map(P=>P.id)),k=t.map(P=>{let O=P.blockedBy?.filter($=>!b.has($));return{...P,...O?.length?{blockedBy:O}:{blockedBy:void 0}}}),x=[];if(x.push(`Task list updated. ${y.total} tasks: ${y.completed} completed, ${y.inProgress} in-progress, ${y.notStarted} not-started.`),y.blocked>0&&x.push(`${y.blocked} blocked.`),f?.created){let P=f.created;x.push(`Created task #${P.id}: "${P.title}"`)}if(f?.updated){let P=f.updated;x.push(`Updated task #${P.id}: "${P.title}"`)}if(f?.deleted!=null&&x.push(`Deleted task #${f.deleted}`),k.length>0){x.push("");for(let P of k){let O=P.status==="completed"?"\u2713":P.status==="in-progress"?"\u2192":"\u25CB",$=P.blockedBy?.length?` [blocked by #${P.blockedBy.join(", #")}]`:"",W=P.owner?` (${P.owner})`:"";x.push(` ${O} #${P.id}: ${P.title} (${P.status})${W}${$}`)}}let I=!1;if(s&&f?.updated&&f.updated.status==="completed"){let O=t.every(S=>S.status==="completed"),$=t.length,W=t.some(S=>/verif/i.test(S.title));O&&$>=3&&!W&&(I=!0,x.push(""),x.push("NOTE: You just closed out "+$+' tasks and none of them was a verification step. Before writing your final summary, spawn the verification agent (agent type="verify"). You cannot self-assign PARTIAL by listing caveats in your summary \u2014 only the verifier issues a verdict.'))}return{content:[{type:"text",text:x.join(`
329
329
  `)}],details:{type:"task",...y,...f,taskList:k,agentId:r.agentId,...I&&{verificationNudgeNeeded:!0}}}}function c(f,y,b){let k=t.find(x=>x.id===f);if(k){if(y?.length){k.blocks=[...new Set([...k.blocks??[],...y])];for(let x of y){let I=t.find(P=>P.id===x);I&&(I.blockedBy=[...new Set([...I.blockedBy??[],f])])}}if(b?.length){k.blockedBy=[...new Set([...k.blockedBy??[],...b])];for(let x of b){let I=t.find(P=>P.id===x);I&&(I.blocks=[...new Set([...I.blocks??[],f])])}}}}function d(f){for(let y of t)y.blocks&&(y.blocks=y.blocks.filter(b=>b!==f)),y.blockedBy&&(y.blockedBy=y.blockedBy.filter(b=>b!==f))}function u(f){if(!f.title)return a("title is required for create action.");let y={id:i(),title:f.title,status:f.status??"not-started",...f.description!=null&&{description:f.description},...f.owner!=null&&{owner:f.owner}};return t.push(y),c(y.id,void 0,f.addBlockedBy),e?.onTaskCreated?.(y),l({created:{id:y.id,title:y.title}})}function p(f){if(f.id==null)return a("id is required for update action.");let y=t.find(b=>b.id===f.id);if(!y)return a(`Task #${f.id} not found.`);if(f.status==="in-progress"){let b=new Set(t.filter(x=>x.status==="completed").map(x=>x.id)),k=y.blockedBy?.filter(x=>!b.has(x));if(k?.length)return a(`Cannot set #${f.id} to in-progress: blocked by unresolved task(s) #${k.join(", #")}.`)}if(f.title!=null&&(y.title=f.title),f.description!=null&&(y.description=f.description),f.owner!=null&&(y.owner=f.owner),f.status!=null){let b=y.status;y.status=f.status,b!=="completed"&&f.status==="completed"&&e?.onTaskCompleted?.(y)}return c(y.id,f.addBlocks,f.addBlockedBy),l({updated:{id:y.id,title:y.title,status:y.status}})}function m(f){if(f.id==null)return a("id is required for delete action.");let y=t.findIndex(b=>b.id===f.id);return y===-1?a(`Task #${f.id} not found.`):(o=Math.max(o,f.id),t.splice(y,1),d(f.id),l({deleted:f.id}))}function h(f){if(f.id==null)return a("id is required for get action.");let y=t.find(I=>I.id===f.id);if(!y)return a(`Task #${f.id} not found.`);let b=new Set(t.filter(I=>I.status==="completed").map(I=>I.id)),k=y.blockedBy?.filter(I=>!b.has(I));return{content:[{type:"text",text:[`Task #${y.id}: ${y.title}`,`Status: ${y.status}`,y.description?`Description: ${y.description}`:"",y.owner?`Owner: ${y.owner}`:"",k?.length?`Blocked by: #${k.join(", #")}`:"",y.blocks?.length?`Blocks: #${y.blocks.join(", #")}`:""].filter(Boolean).join(`
330
- `)}],details:{type:"task",action:"get",task:y}}}return{name:zx,label:"Task",description:"Manage a structured task list to track multi-step work progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all), get (single task). Supports dependency tracking (blocks/blockedBy) \u2014 tasks cannot start until blockers complete. Use frequently during complex work to plan steps, coordinate subagents, and show progress.",parameters:Yx,searchHint:"manage session task checklist progress tracking dependencies planning",maxResultSizeChars:1e5,execute:async(f,y)=>{let b=y.action;switch(b){case"create":return u(y);case"update":return p(y);case"delete":return m(y);case"list":return l();case"get":return h(y);default:return a(`Unknown action: ${b}. Valid: create, update, delete, list, get.`)}}}}import{isAbsolute as vR,resolve as SR}from"node:path";var wm=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),xm=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Rm=new Set(["ls","tree","du"]);var _m=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Xx(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 l=o[r];if(s.test(l)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Am(n){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(n)}function Ml(n){let e=Xx(n),t=e!==null&&wm.has(e),o=e!==null&&xm.has(e),r=e!==null&&Rm.has(e),s=e!==null&&_m.has(e),i=/(?:[^2]>|^>|\|>)/.test(n),a=Am(n),l=(t||o||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:o,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}var Jx=n=>({isError:n!==0,message:n!==0?`Command failed with exit code ${n}`:void 0}),Qx=new Map([["grep",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["rg",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["egrep",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["fgrep",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["ag",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["find",n=>({isError:n>=2,message:n===1?"Some directories were inaccessible":void 0})],["diff",n=>({isError:n>=2,message:n===1?"Files differ":void 0})],["test",n=>({isError:n>=2,message:n===1?"Condition is false":void 0})],["[",n=>({isError:n>=2,message:n===1?"Condition is false":void 0})],["cmp",n=>({isError:n>=2,message:n===1?"Files differ":void 0})]]);function Zx(n){let e=n.trim(),t=e.split(/\s*\|\s*/);return(t[t.length-1]??e).trim().split(/\s+/)[0]??""}function Ol(n,e,t,o){let r=Zx(n);return(Qx.get(r)??Jx)(e,t,o)}function Dl(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 pR}from"node:child_process";import{constants as ds,readFileSync as mR,unlinkSync as fR}from"node:fs";import{mkdir as gR,open as hR,realpath as Em}from"node:fs/promises";import{isAbsolute as yR,resolve as bR}from"node:path";function xn(){if(process.platform!=="win32")return!1;let n=process.env.QLOGICAGENT_USE_POWERSHELL;return n==="1"||n==="true"}function Ll(){return xn()?"powershell":"bash"}function Nl(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as eR,readFile as tR,writeFile as nR,unlink as oR}from"node:fs/promises";import{join as Pm}from"node:path";import{tmpdir as rR}from"node:os";var sR=8*1024*1024,iR=5*1024*1024*1024;var $l;function Wo(){if(!$l){let n=Math.random().toString(36).slice(2,10);$l=Pm(rR(),"qla-tasks",n)}return $l}function Im(n){return Pm(Wo(),`${n}.output`)}function Xt(n="local_bash"){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var dn=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,o=!1,r=sR){this.taskId=e,this.path=Im(e),this.stdoutToFile=o,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=aR(e),this.#d()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await tR(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#d(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&eR(Wo(),{recursive:!0}).then(()=>nR(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await oR(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function aR(n){let e=0;for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&e++;return e}var Ul=137,Cm=143,lR=5e3,jl=5*1024*1024*1024,ls=class{#e;#n;#r;#s=!1;constructor(e,t,o){this.#e=e,this.#n=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.#n.writeStderr(t):this.#n.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#n=null)}},Fl=class n{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#d;#l;#u;#f;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,o,r,s=!1,i=jl){this.#t=e,this.#l=t,this.#f=o,this.#b=s,this.#d=i,this.taskOutput=r,this.#s=e.stderr?new ls(e.stderr,r,!0):null,this.#r=e.stdout?new ls(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#u=a}),this.result=this.#R()}get status(){return this.#e}static#v(e){e.#b&&e.#u?e.#u(e.background.bind(e)):e.#y(Cm)}#S(){this.#l.reason!=="interrupt"&&this.kill()}#T(e,t){let o=e??(t==="SIGTERM"?144:1);this.#g(o)}#w(){this.#g(1)}#g(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#k(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#k(){this.#o&&(clearInterval(this.#o),this.#o=null)}#x(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#d&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(Ul))},()=>{}))},lR),this.#o.unref?.()}#R(){this.#c=this.#S.bind(this),this.#l.addEventListener("abort",this.#c,{once:!0}),this.#t.once("exit",this.#T.bind(this)),this.#t.once("error",this.#w.bind(this)),this.#i=setTimeout(n.#v,this.#f,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(),o={code:e,stdout:t,stderr:this.taskOutput.getStderr(),interrupted:e===Ul,backgroundTaskId:this.#n};this.taskOutput.stdoutToFile&&!this.#n&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(o.outputFilePath=this.taskOutput.path,o.outputFileSize=this.taskOutput.outputFileSize)),this.#a?o.stderr=`Background command killed: output file exceeded ${jl} bytes. ${o.stderr}`:e===Cm&&(o.stderr=`Command timed out after ${this.#f}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.#g(e??Ul)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#x():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#u=void 0}};function Bl(n,e,t,o,r=!1,s=jl){return new Fl(n,e,t,o,r,s)}function cs(n,e){let t=new dn(Xt("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 Wl(n){let e=new dn(Xt("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 cR=new Set(["API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","DEEPSEEK_API_KEY","DOUBAO_API_KEY","MINIMAX_API_KEY","GLM_API_KEY","KIMI_API_KEY","QWEN_API_KEY","MOONSHOT_API_KEY","ZHIPU_API_KEY","BAICHUAN_API_KEY","VOLCENGINE_API_KEY","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","GOOGLE_APPLICATION_CREDENTIALS","AZURE_CLIENT_SECRET","AZURE_CLIENT_ID","AZURE_TENANT_ID","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_RUNTIME_TOKEN","GITHUB_TOKEN","GH_TOKEN","GITLAB_TOKEN","CI_JOB_TOKEN","DATABASE_URL","REDIS_URL","REDIS_PASSWORD"]),dR=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function Gl(){let n={...process.env};for(let e of Object.keys(n))uR(e)&&delete n[e];return n}function uR(n){if(cR.has(n))return!0;let e=n.toUpperCase();for(let t of dR)if(e.includes(t))return!0;return!1}var kR=1800*1e3,us=process.cwd(),Mm=process.cwd();function ps(){return us}function Hl(n,e){us=yR(n)?n:bR(e||us,n)}function Om(){return Mm}function ms(n){us=n,Mm=n}var Vl=null;function Go(n){Vl={provider:n}}function Dm(){if(!Vl)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return Vl.provider}async function fs(n,e,t,o){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:c}=o??{},d=r||kR,u=t??Ll(),p=Dm(),m=Nl(),{commandString:h,cwdFilePath:f}=await p.buildExecCommand(n,{id:m,useSandbox:!1}),y=h,b=c??ps();try{await Em(b)}catch{let S=Om();try{await Em(S),Hl(S),b=S}catch{return Wl(`Working directory "${b}" no longer exists.`)}}if(e.aborted)return cs();let k=p.shellPath,x=p.getSpawnArgs(y),I=await p.getEnvironmentOverrides(n),P=!!l,O=Xt("local_bash"),$=new dn(O,s??null,!P);await gR(Wo(),{recursive:!0});let W;if(!P){let S=ds.O_NOFOLLOW??0;W=await hR($.path,process.platform==="win32"?"w":ds.O_WRONLY|ds.O_CREAT|ds.O_APPEND|S)}try{let S=pR(k,x,{env:{...Gl(),GIT_EDITOR:"true",QLOGICAGENT:"1",...I},cwd:b,stdio:P?["pipe","pipe","pipe"]:["pipe",W?.fd,W?.fd],detached:p.detached,windowsHide:!0}),ce=Bl(S,e,d,$,a);if(W!==void 0)try{await W.close()}catch{}return S.stdout&&l&&S.stdout.on("data",de=>{l(typeof de=="string"?de:de.toString())}),f&&ce.result.then(de=>{if(de&&!i&&!de.backgroundTaskId){try{let j=mR(f,{encoding:"utf8"}).trim();j&&j.normalize("NFC")!==b&&Hl(j,b)}catch{}try{fR(f)}catch{}}}),ce}catch(S){if(W!==void 0)try{await W.close()}catch{}return $.clear(),cs(void 0,{code:126,stderr:S instanceof Error?S.message:String(S)})}}var TR="exec",wR={type:"object",properties:{command:{type:"string",description:xn()?"Shell command to execute in PowerShell.":"Shell command to execute in bash. Use Unix-style commands (ls, cat, mkdir -p, etc.)."},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"]},xR=12e4,RR=6e5,gs=3e4;function Kl(n,e){if(n.length<=e)return n;let t=Math.floor(e/2)-50;return`${n.slice(0,t)}
330
+ `)}],details:{type:"task",action:"get",task:y}}}return{name:Yx,label:"Task",description:"Manage a structured task list to track multi-step work progress. Actions: create (add task), update (modify by id), delete (remove by id), list (read all), get (single task). Supports dependency tracking (blocks/blockedBy) \u2014 tasks cannot start until blockers complete. Use frequently during complex work to plan steps, coordinate subagents, and show progress.",parameters:Jx,searchHint:"manage session task checklist progress tracking dependencies planning",maxResultSizeChars:1e5,execute:async(f,y)=>{let b=y.action;switch(b){case"create":return u(y);case"update":return p(y);case"delete":return m(y);case"list":return l();case"get":return h(y);default:return a(`Unknown action: ${b}. Valid: create, update, delete, list, get.`)}}}}import{isAbsolute as TR,resolve as wR}from"node:path";var wm=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),xm=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Rm=new Set(["ls","tree","du"]);var _m=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Qx(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 l=o[r];if(s.test(l)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Am(n){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(n)}function Ml(n){let e=Qx(n),t=e!==null&&wm.has(e),o=e!==null&&xm.has(e),r=e!==null&&Rm.has(e),s=e!==null&&_m.has(e),i=/(?:[^2]>|^>|\|>)/.test(n),a=Am(n),l=(t||o||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:o,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}var Zx=n=>({isError:n!==0,message:n!==0?`Command failed with exit code ${n}`:void 0}),eR=new Map([["grep",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["rg",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["egrep",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["fgrep",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["ag",n=>({isError:n>=2,message:n===1?"No matches found":void 0})],["find",n=>({isError:n>=2,message:n===1?"Some directories were inaccessible":void 0})],["diff",n=>({isError:n>=2,message:n===1?"Files differ":void 0})],["test",n=>({isError:n>=2,message:n===1?"Condition is false":void 0})],["[",n=>({isError:n>=2,message:n===1?"Condition is false":void 0})],["cmp",n=>({isError:n>=2,message:n===1?"Files differ":void 0})]]);function tR(n){let e=n.trim(),t=e.split(/\s*\|\s*/);return(t[t.length-1]??e).trim().split(/\s+/)[0]??""}function Ol(n,e,t,o){let r=tR(n);return(eR.get(r)??Zx)(e,t,o)}function Dl(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 fR}from"node:child_process";import{constants as ds,readFileSync as gR,unlinkSync as hR}from"node:fs";import{mkdir as yR,open as bR,realpath as Em}from"node:fs/promises";import{isAbsolute as kR,resolve as vR}from"node:path";function xn(){if(process.platform!=="win32")return!1;let n=process.env.QLOGICAGENT_USE_POWERSHELL;return n==="1"||n==="true"}function Ll(){return xn()?"powershell":"bash"}function Nl(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as nR,readFile as oR,writeFile as rR,unlink as sR}from"node:fs/promises";import{join as Pm}from"node:path";import{tmpdir as iR}from"node:os";var aR=8*1024*1024,lR=5*1024*1024*1024;var $l;function Wo(){if(!$l){let n=Math.random().toString(36).slice(2,10);$l=Pm(iR(),"qla-tasks",n)}return $l}function Im(n){return Pm(Wo(),`${n}.output`)}function Xt(n="local_bash"){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var dn=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,o=!1,r=aR){this.taskId=e,this.path=Im(e),this.stdoutToFile=o,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=cR(e),this.#d()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await oR(this.path,"utf-8");return this.#o=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#n}get outputFileSize(){return this.#o}get outputFileRedundant(){return this.#o<=this.#t}#d(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&nR(Wo(),{recursive:!0}).then(()=>rR(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await sR(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function cR(n){let e=0;for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&e++;return e}var Ul=137,Cm=143,dR=5e3,jl=5*1024*1024*1024,ls=class{#e;#n;#r;#s=!1;constructor(e,t,o){this.#e=e,this.#n=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.#n.writeStderr(t):this.#n.writeStdout(t)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#n=null)}},Fl=class n{#e="running";#n;#r;#s;#t;#i=null;#o=null;#a=!1;#d;#l;#u;#f;#b;#p=null;#m=null;#c=null;taskOutput;result;onTimeout;constructor(e,t,o,r,s=!1,i=jl){this.#t=e,this.#l=t,this.#f=o,this.#b=s,this.#d=i,this.taskOutput=r,this.#s=e.stderr?new ls(e.stderr,r,!0):null,this.#r=e.stdout?new ls(e.stdout,r,!1):null,s&&(this.onTimeout=a=>{this.#u=a}),this.result=this.#R()}get status(){return this.#e}static#v(e){e.#b&&e.#u?e.#u(e.background.bind(e)):e.#y(Cm)}#S(){this.#l.reason!=="interrupt"&&this.kill()}#T(e,t){let o=e??(t==="SIGTERM"?144:1);this.#g(o)}#w(){this.#g(1)}#g(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#k(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#c&&(this.#l.removeEventListener("abort",this.#c),this.#c=null)}#k(){this.#o&&(clearInterval(this.#o),this.#o=null)}#x(){this.#o=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(t=>{t.size>this.#d&&this.#e==="backgrounded"&&this.#o!==null&&(this.#a=!0,this.#k(),this.#y(Ul))},()=>{}))},dR),this.#o.unref?.()}#R(){this.#c=this.#S.bind(this),this.#l.addEventListener("abort",this.#c,{once:!0}),this.#t.once("exit",this.#T.bind(this)),this.#t.once("error",this.#w.bind(this)),this.#i=setTimeout(n.#v,this.#f,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(),o={code:e,stdout:t,stderr:this.taskOutput.getStderr(),interrupted:e===Ul,backgroundTaskId:this.#n};this.taskOutput.stdoutToFile&&!this.#n&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(o.outputFilePath=this.taskOutput.path,o.outputFileSize=this.taskOutput.outputFileSize)),this.#a?o.stderr=`Background command killed: output file exceeded ${jl} bytes. ${o.stderr}`:e===Cm&&(o.stderr=`Command timed out after ${this.#f}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.#g(e??Ul)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#x():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#r?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#l=null,this.#u=void 0}};function Bl(n,e,t,o,r=!1,s=jl){return new Fl(n,e,t,o,r,s)}function cs(n,e){let t=new dn(Xt("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 Wl(n){let e=new dn(Xt("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 uR=new Set(["API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","DEEPSEEK_API_KEY","DOUBAO_API_KEY","MINIMAX_API_KEY","GLM_API_KEY","KIMI_API_KEY","QWEN_API_KEY","MOONSHOT_API_KEY","ZHIPU_API_KEY","BAICHUAN_API_KEY","VOLCENGINE_API_KEY","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","GOOGLE_APPLICATION_CREDENTIALS","AZURE_CLIENT_SECRET","AZURE_CLIENT_ID","AZURE_TENANT_ID","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_RUNTIME_TOKEN","GITHUB_TOKEN","GH_TOKEN","GITLAB_TOKEN","CI_JOB_TOKEN","DATABASE_URL","REDIS_URL","REDIS_PASSWORD"]),pR=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function Gl(){let n={...process.env};for(let e of Object.keys(n))mR(e)&&delete n[e];return n}function mR(n){if(uR.has(n))return!0;let e=n.toUpperCase();for(let t of pR)if(e.includes(t))return!0;return!1}var SR=1800*1e3,us=process.cwd(),Mm=process.cwd();function ps(){return us}function Hl(n,e){us=kR(n)?n:vR(e||us,n)}function Om(){return Mm}function ms(n){us=n,Mm=n}var Vl=null;function Go(n){Vl={provider:n}}function Dm(){if(!Vl)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return Vl.provider}async function fs(n,e,t,o){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:c}=o??{},d=r||SR,u=t??Ll(),p=Dm(),m=Nl(),{commandString:h,cwdFilePath:f}=await p.buildExecCommand(n,{id:m,useSandbox:!1}),y=h,b=c??ps();try{await Em(b)}catch{let S=Om();try{await Em(S),Hl(S),b=S}catch{return Wl(`Working directory "${b}" no longer exists.`)}}if(e.aborted)return cs();let k=p.shellPath,x=p.getSpawnArgs(y),I=await p.getEnvironmentOverrides(n),P=!!l,O=Xt("local_bash"),$=new dn(O,s??null,!P);await yR(Wo(),{recursive:!0});let W;if(!P){let S=ds.O_NOFOLLOW??0;W=await bR($.path,process.platform==="win32"?"w":ds.O_WRONLY|ds.O_CREAT|ds.O_APPEND|S)}try{let S=fR(k,x,{env:{...Gl(),GIT_EDITOR:"true",QLOGICAGENT:"1",...I},cwd:b,stdio:P?["pipe","pipe","pipe"]:["pipe",W?.fd,W?.fd],detached:p.detached,windowsHide:!0}),ce=Bl(S,e,d,$,a);if(W!==void 0)try{await W.close()}catch{}return S.stdout&&l&&S.stdout.on("data",de=>{l(typeof de=="string"?de:de.toString())}),f&&ce.result.then(de=>{if(de&&!i&&!de.backgroundTaskId){try{let j=gR(f,{encoding:"utf8"}).trim();j&&j.normalize("NFC")!==b&&Hl(j,b)}catch{}try{hR(f)}catch{}}}),ce}catch(S){if(W!==void 0)try{await W.close()}catch{}return $.clear(),cs(void 0,{code:126,stderr:S instanceof Error?S.message:String(S)})}}var xR="exec",RR={type:"object",properties:{command:{type:"string",description:xn()?"Shell command to execute in PowerShell.":"Shell command to execute in bash. Use Unix-style commands (ls, cat, mkdir -p, etc.)."},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"]},_R=12e4,AR=6e5,gs=3e4;function Kl(n,e){if(n.length<=e)return n;let t=Math.floor(e/2)-50;return`${n.slice(0,t)}
331
331
 
332
332
  ... [truncated ${n.length-e} chars] ...
333
333
 
334
- ${n.slice(-t)}`}function _R(n){return n==null||n<=0?xR:Math.min(n,RR)}async function*AR(n){let{command:e,abortController:t,timeout:o,shouldAutoBackground:r,cwd:s}=n,i="",a=0,l=0,c=Date.now(),d=null;function u(){return new Promise(h=>{d=()=>h(null)})}let p=await fs(e,t.signal,void 0,{timeout:o,onProgress(h,f,y,b,k){i=f,a=y,l=b,d&&(d(),d=null)},shouldAutoBackground:r,cwd:s});for(p.onTimeout&&r&&p.onTimeout(h=>{let f=Xt("bg");h(f)});p.status==="running"&&await Promise.race([u(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-c)/1e3,totalLines:a,totalBytes:l};let m=await p.result;return p.cleanup(),m}function Lm(n={}){return{name:TR,label:"Execute Command",description:"Execute a shell command. Supports foreground (blocking, returns output) and background (non-blocking, returns task ID) modes. "+(xn()?"Uses PowerShell. ":"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.
335
- IMPORTANT: Do NOT use this tool for file operations when dedicated tools exist. Use the 'write' tool instead of echo/cat/heredoc for creating files. Use the 'edit' tool instead of sed/awk for modifying files. Use the 'read' tool instead of cat/head/tail for reading files. Reserve this tool exclusively for system commands, builds, tests, and terminal operations that require shell execution.`,searchHint:"execute shell commands",parameters:wR,maxResultSizeChars:gs,execute:async(e,t)=>{let o=Ml(t.command);if(!t.background){let m=Dl(t.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:o}}}if(n.validateCommand){let m=await n.validateCommand(t.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_by_guard",reason:m,classification:o}}}let r=new AbortController,s=_R(t.timeout),i=t.workdir?vR(t.workdir)?t.workdir:SR(ps(),t.workdir):void 0;if(t.background){let m=await fs(t.command,r.signal,void 0,{shouldAutoBackground:!1,cwd:i}),h=Xt("bg");if(m.background(h))return{content:[{type:"text",text:`Background task started (id: ${h}).
336
- Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:h,description:t.description,classification:o}}}let a=AR({command:t.command,abortController:r,timeout:s,shouldAutoBackground:!0,cwd:i}),l;do l=await a.next(),!l.done&&n.onProgress&&n.onProgress(l.value);while(!l.done);let c=l.value,d=[];if(c.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${c.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:c.backgroundTaskId,assistantAutoBackgrounded:c.assistantAutoBackgrounded,classification:o}};c.outputFilePath?(d.push(Kl(c.stdout,gs)),d.push(`[full output: ${c.outputFilePath} (${c.outputFileSize} bytes)]`)):c.stdout&&d.push(Kl(c.stdout,gs)),c.stderr&&d.push(`[stderr]
334
+ ${n.slice(-t)}`}function PR(n){return n==null||n<=0?_R:Math.min(n,AR)}async function*IR(n){let{command:e,abortController:t,timeout:o,shouldAutoBackground:r,cwd:s}=n,i="",a=0,l=0,c=Date.now(),d=null;function u(){return new Promise(h=>{d=()=>h(null)})}let p=await fs(e,t.signal,void 0,{timeout:o,onProgress(h,f,y,b,k){i=f,a=y,l=b,d&&(d(),d=null)},shouldAutoBackground:r,cwd:s});for(p.onTimeout&&r&&p.onTimeout(h=>{let f=Xt("bg");h(f)});p.status==="running"&&await Promise.race([u(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-c)/1e3,totalLines:a,totalBytes:l};let m=await p.result;return p.cleanup(),m}function Lm(n={}){return{name:xR,label:"Execute Command",description:"Execute a shell command. Supports foreground (blocking, returns output) and background (non-blocking, returns task ID) modes. "+(xn()?"Uses PowerShell. ":"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.
335
+ IMPORTANT: Do NOT use this tool for file operations when dedicated tools exist. Use the 'write' tool instead of echo/cat/heredoc for creating files. Use the 'edit' tool instead of sed/awk for modifying files. Use the 'read' tool instead of cat/head/tail for reading files. Reserve this tool exclusively for system commands, builds, tests, and terminal operations that require shell execution.`,searchHint:"execute shell commands",parameters:RR,maxResultSizeChars:gs,execute:async(e,t)=>{let o=Ml(t.command);if(!t.background){let m=Dl(t.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:o}}}if(n.validateCommand){let m=await n.validateCommand(t.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_by_guard",reason:m,classification:o}}}let r=new AbortController,s=PR(t.timeout),i=t.workdir?TR(t.workdir)?t.workdir:wR(ps(),t.workdir):void 0;if(t.background){let m=await fs(t.command,r.signal,void 0,{shouldAutoBackground:!1,cwd:i}),h=Xt("bg");if(m.background(h))return{content:[{type:"text",text:`Background task started (id: ${h}).
336
+ Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:h,description:t.description,classification:o}}}let a=IR({command:t.command,abortController:r,timeout:s,shouldAutoBackground:!0,cwd:i}),l;do l=await a.next(),!l.done&&n.onProgress&&n.onProgress(l.value);while(!l.done);let c=l.value,d=[];if(c.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${c.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:c.backgroundTaskId,assistantAutoBackgrounded:c.assistantAutoBackgrounded,classification:o}};c.outputFilePath?(d.push(Kl(c.stdout,gs)),d.push(`[full output: ${c.outputFilePath} (${c.outputFileSize} bytes)]`)):c.stdout&&d.push(Kl(c.stdout,gs)),c.stderr&&d.push(`[stderr]
337
337
  ${Kl(c.stderr,Math.floor(gs/4))}`),c.interrupted&&d.push(`[interrupted \u2014 exit code ${c.code}]`);let u=c.code!==0?Ol(t.command,c.code,c.stdout,c.stderr):void 0;u&&!u.isError&&u.message&&d.push(`[exit ${c.code}: ${u.message}]`);let p;return c.code!==0&&n.interpretExitCode&&(!u||u.isError)&&(p=n.interpretExitCode(c.code,c.stderr),p&&d.push(`[exit ${c.code}: ${p}]`)),d.length===0&&d.push(o.isSilent&&c.code===0?"Done":`(exit code ${c.code}, no output)`),{content:[{type:"text",text:d.join(`
338
- `)}],details:{type:"exec",exitCode:c.code,interrupted:c.interrupted,description:t.description,returnCodeInterpretation:p??u?.message,noOutputExpected:o.isSilent,outputFilePath:c.outputFilePath,semanticNonError:u?!u.isError:void 0,classification:o}}}}}import{tmpdir as PR}from"node:os";import{join as IR,posix as zl}from"node:path";function CR(n){return n.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function ER(n){return!(/(?:^|[;&|])\s*<\s/.test(n)||/<<[-]?\s*['"]?[A-Za-z_]/.test(n))}function MR(n,e){return`$'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Nm(n){return process.platform!=="win32"?n:n.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function hs(n,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:n,detached:!0,async buildExecCommand(o,r){let s=process.platform==="win32",i=PR(),a=s?Nm(i):i,l=r.useSandbox&&r.sandboxTmpDir?zl.join(r.sandboxTmpDir,`cwd-${r.id}`):zl.join(a,`qla-${r.id}-cwd`),c=r.useSandbox&&r.sandboxTmpDir?zl.join(r.sandboxTmpDir,`cwd-${r.id}`):IR(i,`qla-${r.id}-cwd`),d=CR(o),u=ER(d),p=MR(d,u),m=[];if(t){let f=s?Nm(t):t;m.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${l}'`),{commandString:m.join(" && "),cwdFilePath:c}},getSpawnArgs(o){return["-c",...!!t?[]:["-l"],o]},async getEnvironmentOverrides(o){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as OR}from"node:os";import{join as DR,posix as LR}from"node:path";function $m(n){return Buffer.from(n,"utf16le").toString("base64")}function NR(n){return["-NoProfile","-NonInteractive","-Command",n]}function ql(n){return{type:"powershell",shellPath:n,detached:!1,async buildExecCommand(e,t){let o=t.useSandbox&&t.sandboxTmpDir?LR.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):DR(OR(),`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(`
339
- ; `),i=e+s;return{commandString:t.useSandbox?[`'${n.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",$m(i)].join(" "):i,cwdFilePath:o}},getSpawnArgs(e){return NR(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var $R=[{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"}],UR=[{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 Yl(n){for(let{pattern:e,warning:t}of $R)if(e.test(n))return t;return null}function Xl(n){for(let{pattern:e,warning:t}of UR)if(e.test(n))return t;return null}var jR="read",FR={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 Um(n){return{name:jR,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:FR,isReadOnly:!0,execute:async(o,r)=>{let s=n.resolvePath(r.path);if(n.validatePath){let f=n.validatePath(s);if(f)return{content:[{type:"text",text:`Access denied: ${f}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await n.readFile(s);if(i.type==="image")return{content:[{type:"text",text:`[Image: ${s}] (${i.mimeType})`}],details:{type:"read",path:s,isImage:!0},imageUrls:[i.localPath]};if(i.type==="binary")return{content:[{type:"text",text:`Cannot read binary file (${i.mimeType}). Use a specific tool for this file type (e.g. pdf tool for PDFs).`}],details:{type:"read",path:s,error:"binary_file",mimeType:i.mimeType}};let a=i.text.split(`
338
+ `)}],details:{type:"exec",exitCode:c.code,interrupted:c.interrupted,description:t.description,returnCodeInterpretation:p??u?.message,noOutputExpected:o.isSilent,outputFilePath:c.outputFilePath,semanticNonError:u?!u.isError:void 0,classification:o}}}}}import{tmpdir as CR}from"node:os";import{join as ER,posix as zl}from"node:path";function MR(n){return n.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function OR(n){return!(/(?:^|[;&|])\s*<\s/.test(n)||/<<[-]?\s*['"]?[A-Za-z_]/.test(n))}function DR(n,e){return`$'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Nm(n){return process.platform!=="win32"?n:n.replace(/^([A-Za-z]):/,(e,t)=>`/${t.toLowerCase()}`).replace(/\\/g,"/")}function hs(n,e){let t=e?.snapshotFilePath;return{type:"bash",shellPath:n,detached:!0,async buildExecCommand(o,r){let s=process.platform==="win32",i=CR(),a=s?Nm(i):i,l=r.useSandbox&&r.sandboxTmpDir?zl.join(r.sandboxTmpDir,`cwd-${r.id}`):zl.join(a,`qla-${r.id}-cwd`),c=r.useSandbox&&r.sandboxTmpDir?zl.join(r.sandboxTmpDir,`cwd-${r.id}`):ER(i,`qla-${r.id}-cwd`),d=MR(o),u=OR(d),p=DR(d,u),m=[];if(t){let f=s?Nm(t):t;m.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${l}'`),{commandString:m.join(" && "),cwdFilePath:c}},getSpawnArgs(o){return["-c",...!!t?[]:["-l"],o]},async getEnvironmentOverrides(o){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as LR}from"node:os";import{join as NR,posix as $R}from"node:path";function $m(n){return Buffer.from(n,"utf16le").toString("base64")}function UR(n){return["-NoProfile","-NonInteractive","-Command",n]}function ql(n){return{type:"powershell",shellPath:n,detached:!1,async buildExecCommand(e,t){let o=t.useSandbox&&t.sandboxTmpDir?$R.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):NR(LR(),`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(`
339
+ ; `),i=e+s;return{commandString:t.useSandbox?[`'${n.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",$m(i)].join(" "):i,cwdFilePath:o}},getSpawnArgs(e){return UR(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var jR=[{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"}],FR=[{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 Yl(n){for(let{pattern:e,warning:t}of jR)if(e.test(n))return t;return null}function Xl(n){for(let{pattern:e,warning:t}of FR)if(e.test(n))return t;return null}var BR="read",WR={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 Um(n){return{name:BR,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:WR,isReadOnly:!0,execute:async(o,r)=>{let s=n.resolvePath(r.path);if(n.validatePath){let f=n.validatePath(s);if(f)return{content:[{type:"text",text:`Access denied: ${f}`}],details:{type:"read",path:s,error:"access_denied"}}}let i=await n.readFile(s);if(i.type==="image")return{content:[{type:"text",text:`[Image: ${s}] (${i.mimeType})`}],details:{type:"read",path:s,isImage:!0},imageUrls:[i.localPath]};if(i.type==="binary")return{content:[{type:"text",text:`Cannot read binary file (${i.mimeType}). Use a specific tool for this file type (e.g. pdf tool for PDFs).`}],details:{type:"read",path:s,error:"binary_file",mimeType:i.mimeType}};let a=i.text.split(`
340
340
  `),l=Math.max(0,(r.offset??1)-1),c=Math.min(r.limit??2e3,2e3),d=a.slice(l,l+c),u=d.join(`
341
341
  `);u.length>5e4&&(u=u.slice(0,5e4)+`
342
- ... (truncated)`);let p=a.length,m=l+d.length,h=m<p;return{content:[{type:"text",text:u}],details:{type:"read",path:s,totalLines:p,startLine:l+1,endLine:m,hasMore:h}}}}}var BR="write",WR={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"]},jm=5e5;function Fm(n){return{name:BR,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). ALWAYS use this tool to create new files \u2014 never use shell commands (echo, cat, heredoc) for file creation.",parameters:WR,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>jm)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${jm}). 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(`
343
- `).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${o}`}],details:{type:"write",path:o,lineCount:r}}}}}var GR="edit",HR={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 Bm(n){return{name:GR,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. ALWAYS use this tool to modify existing files \u2014 never use sed/awk/shell commands for text replacement.",parameters:HR,execute:async(e,t)=>{let o=n.resolvePath(t.path);if(n.checkConcurrentModification){let d=n.checkConcurrentModification(o);if(d)return{content:[{type:"text",text:`Concurrent modification detected: ${d}. 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 c=r.slice(0,s).split(`
344
- `).length;return{content:[{type:"text",text:`Edited ${o} (line ${c})`}],details:{type:"edit",path:o,success:!0,firstChangedLine:c}}}}}var VR="search",KR={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"]},Wm=100,Gm=250,Jl=1e5;function Hm(n){return{name:VR,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:KR,isReadOnly:!0,execute:async(e,t)=>{let o=t.path?n.resolvePath?n.resolvePath(t.path):t.path:"",r=t.mode;return r==="filename"?zR(n,t,o):r==="content"?qR(n,t,o):YR(n,t,o)}}}async function zR(n,e,t){let o=e.headLimit??Wm,{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,l=o===0?a.length:o,c=a.slice(0,l),d=s||a.length>l;if(c.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let u=c.join(`
342
+ ... (truncated)`);let p=a.length,m=l+d.length,h=m<p;return{content:[{type:"text",text:u}],details:{type:"read",path:s,totalLines:p,startLine:l+1,endLine:m,hasMore:h}}}}}var GR="write",HR={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"]},jm=5e5;function Fm(n){return{name:GR,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). ALWAYS use this tool to create new files \u2014 never use shell commands (echo, cat, heredoc) for file creation.",parameters:HR,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>jm)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${jm}). 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(`
343
+ `).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${o}`}],details:{type:"write",path:o,lineCount:r}}}}}var VR="edit",KR={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 Bm(n){return{name:VR,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. ALWAYS use this tool to modify existing files \u2014 never use sed/awk/shell commands for text replacement.",parameters:KR,execute:async(e,t)=>{let o=n.resolvePath(t.path);if(n.checkConcurrentModification){let d=n.checkConcurrentModification(o);if(d)return{content:[{type:"text",text:`Concurrent modification detected: ${d}. 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 c=r.slice(0,s).split(`
344
+ `).length;return{content:[{type:"text",text:`Edited ${o} (line ${c})`}],details:{type:"edit",path:o,success:!0,firstChangedLine:c}}}}}var zR="search",qR={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"]},Wm=100,Gm=250,Jl=1e5;function Hm(n){return{name:zR,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:qR,isReadOnly:!0,execute:async(e,t)=>{let o=t.path?n.resolvePath?n.resolvePath(t.path):t.path:"",r=t.mode;return r==="filename"?YR(n,t,o):r==="content"?XR(n,t,o):JR(n,t,o)}}}async function YR(n,e,t){let o=e.headLimit??Wm,{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,l=o===0?a.length:o,c=a.slice(0,l),d=s||a.length>l;if(c.length===0)return{content:[{type:"text",text:"No files found matching pattern."}],details:{mode:"filename",totalMatches:0,truncated:!1}};let u=c.join(`
345
345
  `);return d&&(u+=`
346
346
 
347
- (Results truncated. ${c.length} shown. Use a more specific pattern or increase headLimit.)`),u=Ql(u,Jl),{content:[{type:"text",text:u}],details:{mode:"filename",totalMatches:c.length,truncated:d}}}async function qR(n,e,t){let o=e.headLimit??Gm,{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 l of r){if(l.contextBefore&&l.contextBefore.length>0)for(let c of l.contextBefore)i.push(` ${c}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let c of l.contextAfter)i.push(` ${c}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
347
+ (Results truncated. ${c.length} shown. Use a more specific pattern or increase headLimit.)`),u=Ql(u,Jl),{content:[{type:"text",text:u}],details:{mode:"filename",totalMatches:c.length,truncated:d}}}async function XR(n,e,t){let o=e.headLimit??Gm,{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 l of r){if(l.contextBefore&&l.contextBefore.length>0)for(let c of l.contextBefore)i.push(` ${c}`);if(i.push(`${l.path}:${l.line}: ${l.text}`),l.contextAfter&&l.contextAfter.length>0)for(let c of l.contextAfter)i.push(` ${c}`);e.contextLines&&e.contextLines>0&&i.push("--")}let a=i.join(`
348
348
  `);return s&&(a+=`
349
349
 
350
- (Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=Ql(a,Jl),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function YR(n,e,t){let[o,r]=await Promise.all([e.fileGlob?n.glob(e.fileGlob,{cwd:t,limit:Wm}):Promise.resolve({files:[],truncated:!1}),n.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Gm,offset:e.offset})]),s=new Set(r.matches.map(d=>d.path)),i=o.files.filter(d=>!s.has(d)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
350
+ (Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=Ql(a,Jl),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function JR(n,e,t){let[o,r]=await Promise.all([e.fileGlob?n.glob(e.fileGlob,{cwd:t,limit:Wm}):Promise.resolve({files:[],truncated:!1}),n.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??Gm,offset:e.offset})]),s=new Set(r.matches.map(d=>d.path)),i=o.files.filter(d=>!s.has(d)),a=[];if(i.length>0&&a.push(`## Files matching glob (${i.length}):
351
351
  ${i.join(`
352
352
  `)}`),r.matches.length>0){let d=[];for(let u of r.matches)d.push(`${u.path}:${u.line}: ${u.text}`);a.push(`## Content matches (${r.matches.length}):
353
353
  ${d.join(`
@@ -359,18 +359,18 @@ ${d.join(`
359
359
 
360
360
  ... [truncated ${n.length-e} chars] ...
361
361
 
362
- ${n.slice(-t)}`}var XR="apply_patch",JR={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function QR(n){let e=n.split(`
363
- `),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 ZR(n,e){let o=[...n.split(`
362
+ ${n.slice(-t)}`}var QR="apply_patch",ZR={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function e_(n){let e=n.split(`
363
+ `),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 t_(n,e){let o=[...n.split(`
364
364
  `)];for(let r of e){let s=-1;if(r.contextBefore.length>0)for(let i=0;i<=o.length-r.contextBefore.length;i++){let a=!0;for(let l=0;l<r.contextBefore.length;l++)if(o[i+l]!==r.contextBefore[l]){a=!1;break}if(a){s=i+r.contextBefore.length;break}}else s=0;s!==-1&&(r.removals.length>0?o.splice(s,r.removals.length,...r.additions):o.splice(s,0,...r.additions))}return o.join(`
365
- `)}function Vm(n){return{name:XR,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:JR,execute:async(e,t)=>{let o=QR(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 l=n.resolvePath(a.path);try{switch(a.type){case"add":{let c=a.hunks.flatMap(d=>[...d.additions]).join(`
366
- `);await n.writeFile(l,c),r.added.push(a.path);break}case"update":{let c=await n.readFile(l),d=ZR(c,a.hunks);if(a.moveTo){let u=n.resolvePath(a.moveTo);await n.writeFile(u,d),await n.deleteFile(l),r.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await n.writeFile(l,d),r.modified.push(a.path);break}case"delete":{await n.deleteFile(l),r.deleted.push(a.path);break}}}catch(c){s.push(`${a.type} ${a.path}: ${c instanceof Error?c.message:String(c)}`)}}let i=[];return r.added.length&&i.push(`Added: ${r.added.join(", ")}`),r.modified.length&&i.push(`Modified: ${r.modified.join(", ")}`),r.deleted.length&&i.push(`Deleted: ${r.deleted.join(", ")}`),s.length&&i.push(`Errors: ${s.join("; ")}`),{content:[{type:"text",text:i.join(`
367
- `)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var e_="patch",t_={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
365
+ `)}function Vm(n){return{name:QR,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:ZR,execute:async(e,t)=>{let o=e_(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 l=n.resolvePath(a.path);try{switch(a.type){case"add":{let c=a.hunks.flatMap(d=>[...d.additions]).join(`
366
+ `);await n.writeFile(l,c),r.added.push(a.path);break}case"update":{let c=await n.readFile(l),d=t_(c,a.hunks);if(a.moveTo){let u=n.resolvePath(a.moveTo);await n.writeFile(u,d),await n.deleteFile(l),r.modified.push(`${a.path} \u2192 ${a.moveTo}`)}else await n.writeFile(l,d),r.modified.push(a.path);break}case"delete":{await n.deleteFile(l),r.deleted.push(a.path);break}}}catch(c){s.push(`${a.type} ${a.path}: ${c instanceof Error?c.message:String(c)}`)}}let i=[];return r.added.length&&i.push(`Added: ${r.added.join(", ")}`),r.modified.length&&i.push(`Modified: ${r.modified.join(", ")}`),r.deleted.length&&i.push(`Deleted: ${r.deleted.join(", ")}`),s.length&&i.push(`Errors: ${s.join("; ")}`),{content:[{type:"text",text:i.join(`
367
+ `)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var n_="patch",o_={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
368
368
  1) V4A unified diff (*** Begin Patch / *** End Patch markers)
369
369
  2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
370
- 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 n_(n){return n.replace(/\\n/g,`
370
+ 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 r_(n){return n.replace(/\\n/g,`
371
371
  `).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Km(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 zm(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 Zm(n,e,t){let o=[],r=n.indexOf(e);if(r!==-1){if(t){let f=0;for(;(r=n.indexOf(e,f))!==-1;)o.push({start:r,end:r+e.length,strategy:"exact"}),f=r+e.length}else o.push({start:r,end:r+e.length,strategy:"exact"});return o}let s=e.split(`
372
372
  `).map(f=>f.trim()),i=n.split(`
373
- `),a=qm(i,s,(f,y)=>f.trim()===y);if(a)return[{...Ym(n,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),c=n.replace(/[ \t]+/g," ");if(r=c.indexOf(l),r!==-1){let f=Xm(n,c,r,l.length);if(f)return[{...f,strategy:"whitespace_normalized"}]}let d=qm(i,s,(f,y)=>f.trimStart()===y.trimStart());if(d)return[{...Ym(n,i,d),strategy:"indentation_flexible"}];let u=n_(e);if(u!==e&&(r=n.indexOf(u),r!==-1))return[{start:r,end:r+u.length,strategy:"escape_normalized"}];let p=e.split(`
373
+ `),a=qm(i,s,(f,y)=>f.trim()===y);if(a)return[{...Ym(n,i,a),strategy:"line_trimmed"}];let l=e.replace(/[ \t]+/g," "),c=n.replace(/[ \t]+/g," ");if(r=c.indexOf(l),r!==-1){let f=Xm(n,c,r,l.length);if(f)return[{...f,strategy:"whitespace_normalized"}]}let d=qm(i,s,(f,y)=>f.trimStart()===y.trimStart());if(d)return[{...Ym(n,i,d),strategy:"indentation_flexible"}];let u=r_(e);if(u!==e&&(r=n.indexOf(u),r!==-1))return[{start:r,end:r+u.length,strategy:"escape_normalized"}];let p=e.split(`
374
374
  `);if(p.length>=3){let f=p.slice(1,-1).join(`
375
375
  `),y=p[0].trim(),b=p[p.length-1].trim();for(let k=0;k<i.length;k++)if(i[k].trim()===y){let x=i.slice(0,k+1).join(`
376
376
  `).length+1,I=n.indexOf(f,x);if(I!==-1){let P=I+f.length,O=n.indexOf(`
@@ -385,7 +385,7 @@ Fuzzy matching automatically handles whitespace/indent/unicode drift in the sear
385
385
  `).length;return[{start:x,end:I,strategy:"context_aware"}]}}return[]}function qm(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 Ym(n,e,t){let o=e.slice(0,t.startIdx).join(`
386
386
  `).length+(t.startIdx>0?1:0),r=e.slice(0,t.endIdx).join(`
387
387
  `).length;return{start:o,end:r}}function Xm(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 Jm(n){let e=n.split(`
388
- `),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 o_(n){let e=[],t=n.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let o=t[0].trim().split(`
388
+ `),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 s_(n){let e=[],t=n.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let o=t[0].trim().split(`
389
389
  `).pop()?.trim();if(!o)return[];for(let r=1;r<t.length;r+=2){let s=t[r+1]||"",i=s.indexOf(`
390
390
  ====
391
391
  `);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),l=s.slice(i+6),c=l.indexOf(`
@@ -393,10 +393,10 @@ Fuzzy matching automatically handles whitespace/indent/unicode drift in the sear
393
393
  `);if(!l)return{content:n+`
394
394
  `+s.join(`
395
395
  `),strategy:"exact"};let c=Zm(n,l,t);if(c.length===0)return null;let d=[];for(let h of e.lines)(h.prefix===" "||h.prefix==="+")&&d.push(h.content);let u=d.join(`
396
- `),p=c[0];return{content:n.slice(0,p.start)+u+n.slice(p.end),strategy:p.strategy}}function Zl(n){return{name:e_,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:t_,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 c=Jm(t.input);if(c.length===0)return{content:[{type:"text",text:"Error: No valid V4A operations found. Ensure *** Begin Patch / *** End Patch markers are present."}],details:{type:"patch",error:"parse_failed"}};for(let d of c){let u=n.resolvePath(d.path);try{switch(d.type){case"add":{let p=d.hunks.flatMap(m=>m.lines.filter(h=>h.prefix==="+").map(h=>h.content)).join(`
396
+ `),p=c[0];return{content:n.slice(0,p.start)+u+n.slice(p.end),strategy:p.strategy}}function Zl(n){return{name:n_,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:o_,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 c=Jm(t.input);if(c.length===0)return{content:[{type:"text",text:"Error: No valid V4A operations found. Ensure *** Begin Patch / *** End Patch markers are present."}],details:{type:"patch",error:"parse_failed"}};for(let d of c){let u=n.resolvePath(d.path);try{switch(d.type){case"add":{let p=d.hunks.flatMap(m=>m.lines.filter(h=>h.prefix==="+").map(h=>h.content)).join(`
397
397
  `);await n.writeFile(u,p),r.filesAdded.push(d.path),r.strategies[d.path]="exact";break}case"delete":{await n.deleteFile(u),r.filesDeleted.push(d.path);break}case"move":{let p=await n.readFile(u);if(d.newPath){let m=n.resolvePath(d.newPath),h=p;for(let f of d.hunks){let y=Qm(h,f,o);y&&(h=y.content,r.strategies[d.path]=y.strategy)}await n.writeFile(m,h),await n.deleteFile(u),r.filesModified.push(`${d.path} \u2192 ${d.newPath}`)}break}case"update":{let p=await n.readFile(u),m="exact",h=!0;for(let f of d.hunks){let y=Qm(p,f,o);if(y)p=y.content,m=y.strategy;else{h=!1;let b=f.lines.filter(k=>k.prefix===" "||k.prefix==="-").map(k=>k.content).slice(0,5).join(`
398
398
  `);r.errors.push(`${d.path}: hunk not matched. Search begins with:
399
- ${b}`)}}(h||p!==await n.readFile(u))&&(await n.writeFile(u,p),r.filesModified.push(d.path),r.strategies[d.path]=m);break}}}catch(p){r.errors.push(`${d.type} ${d.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let c=o_(t.input);if(c.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let d of c){let u=n.resolvePath(d.path);try{let p=await n.readFile(u),m=Zm(p,d.search,o);if(m.length===0){r.errors.push(`${d.path}: search text not matched (tried all 9 strategies)`);continue}let h=[...m].sort((f,y)=>y.start-f.start);for(let f of h)p=p.slice(0,f.start)+d.replace+p.slice(f.end);await n.writeFile(u,p),r.filesModified.push(d.path),r.strategies[d.path]=m[0].strategy}catch(p){r.errors.push(`${d.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return Jm(`*** Begin Patch
399
+ ${b}`)}}(h||p!==await n.readFile(u))&&(await n.writeFile(u,p),r.filesModified.push(d.path),r.strategies[d.path]=m);break}}}catch(p){r.errors.push(`${d.type} ${d.path}: ${p instanceof Error?p.message:String(p)}`)}}}else if(i){let c=s_(t.input);if(c.length===0)return{content:[{type:"text",text:"Error: Invalid search/replace format. Use <<<< SEARCH / ==== / >>>> REPLACE blocks."}],details:{type:"patch",error:"parse_failed"}};for(let d of c){let u=n.resolvePath(d.path);try{let p=await n.readFile(u),m=Zm(p,d.search,o);if(m.length===0){r.errors.push(`${d.path}: search text not matched (tried all 9 strategies)`);continue}let h=[...m].sort((f,y)=>y.start-f.start);for(let f of h)p=p.slice(0,f.start)+d.replace+p.slice(f.end);await n.writeFile(u,p),r.filesModified.push(d.path),r.strategies[d.path]=m[0].strategy}catch(p){r.errors.push(`${d.path}: ${p instanceof Error?p.message:String(p)}`)}}}else return Jm(`*** Begin Patch
400
400
  `+t.input+`
401
401
  *** End Patch`).length>0?Zl(n).execute(e,{input:`*** Begin Patch
402
402
  `+t.input+`
@@ -404,65 +404,65 @@ ${b}`)}}(h||p!==await n.readFile(u))&&(await n.writeFile(u,p),r.filesModified.pu
404
404
  Errors:
405
405
  ${r.errors.join(`
406
406
  `)}`);let l=r.errors.length===0;return{content:[{type:"text",text:a.join(`
407
- `)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var r_="web_fetch",s_={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"]},i_=5e4;function ef(n){return{name:r_,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:s_,isReadOnly:!0,execute:async(e,t)=>{let o=await n.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??i_,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}
407
+ `)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var i_="web_fetch",a_={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"]},l_=5e4;function ef(n){return{name:i_,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:a_,isReadOnly:!0,execute:async(e,t)=>{let o=await n.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??l_,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}
408
408
 
409
409
  ${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}
410
410
  `),r.push(o.content),o.relevantExcerpts?.length){r.push(`
411
411
  ---
412
412
  ## Relevant Excerpts
413
413
  `);for(let s of o.relevantExcerpts)r.push(`- ${s}`)}return{content:[{type:"text",text:r.join(`
414
- `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!o.extraction,extraction:o.extraction}}}}}var a_="web_search",l_={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"]},c_=10;function tf(n){return{name:a_,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:l_,isReadOnly:!0,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:c_});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(`
415
- `)}],details:{type:"web_search",query:o.query,resultCount:o.results.length}}}}}var d_="instructions",u_={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 nf(n){return{name:d_,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:u_,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(`
414
+ `)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!o.extraction,extraction:o.extraction}}}}}var c_="web_search",d_={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"]},u_=10;function tf(n){return{name:c_,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:d_,isReadOnly:!0,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:u_});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(`
415
+ `)}],details:{type:"web_search",query:o.query,resultCount:o.results.length}}}}}var p_="instructions",m_={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 nf(n){return{name:p_,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:m_,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(`
416
416
  `);return{content:[{type:"text",text:`Found ${o.length} instruction file(s):
417
- ${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 p_="worktree",m_={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
417
+ ${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 f_="worktree",g_={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
418
418
  exit: Leave worktree (keep or remove it).
419
- 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"]},f_=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function of(n){return{name:p_,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:m_,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&&!f_.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(`
419
+ 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"]},h_=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function of(n){return{name:f_,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:g_,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&&!h_.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(`
420
420
  `)}],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."}
421
421
  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(`
422
- `)}],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"}}}}}}le();import{execFile as g_}from"node:child_process";import{promisify as h_}from"node:util";import{join as Rn,resolve as rf,basename as ec}from"node:path";import{mkdir as uf,rm as pf,symlink as y_,readdir as S$,stat as b_}from"node:fs/promises";var Vo=h_(g_),k_=/^[a-zA-Z0-9._-]+$/,sf=64;function mf(n){if(n.length>sf)throw new Error(`Invalid worktree name: must be ${sf} 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(!k_.test(e))throw new Error(`Invalid worktree name "${n}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function tc(n){return n.replaceAll("/","+")}function ff(n){return`worktree-${tc(n)}`}var ot=null;async function $e(n,e){try{let{stdout:t,stderr:o}=await Vo("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 Ho(n){let{stdout:e,code:t}=await $e(["rev-parse","--show-toplevel"],n);return t===0?e.trim():null}async function af(n){let{stdout:e,code:t}=await $e(["status","--porcelain"],n);return t!==0?-1:e.trim().split(`
423
- `).filter(Boolean).length}async function lf(n,e){let{stdout:t,code:o}=await $e(["rev-list",`origin/${e}..${e}`,"--count"],n);return o!==0?0:parseInt(t.trim(),10)||0}async function gf(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=Rn(n,r),i=Rn(e,r);try{await y_(s,i,"dir"),o?.info(`[worktree] symlinked ${r} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&o?.warn(`[worktree] failed to symlink ${r} (${l??"unknown"}): ${a}`)}}}async function v_(n,e,t){let{code:o,stderr:r}=await $e(["sparse-checkout","set","--cone","--",...t],n);if(o!==0)throw await $e(["worktree","remove","--force",n],e),new Error(`Failed to configure sparse-checkout: ${r}`);let{code:s,stderr:i}=await $e(["checkout","HEAD"],n);if(s!==0)throw await $e(["worktree","remove","--force",n],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function S_(){try{return await Vo("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function T_(n,e){return`${ec(n)}_${e}`.replace(/[/.]/g,"_")}async function w_(n,e){if(!await S_())return null;try{return await Vo("tmux",["new-session","-d","-s",e,"-c",n],{timeout:1e4}),e}catch{return null}}async function cf(n){try{return await Vo("tmux",["kill-session","-t",n],{timeout:5e3}),!0}catch{return!1}}async function df(n,e,t,o){let r=lp(e),s=Rn(r,n);try{if(!(await b_(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await Vo(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}}async function hf(n,e,t){mf(e);let o=tc(e),r=ff(e),s=Rn(n,".worktrees"),i=Rn(s,o);await uf(s,{recursive:!0});let{code:a,stderr:l}=await $e(["worktree","add","-B",r,i,"HEAD"],n);return a!==0?(t?.warn(`[worktree] agent worktree creation failed: ${l}`),null):(await gf(n,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:r})}async function yf(n,e,t,o){let{code:r}=await $e(["worktree","remove","--force",e],n);return r!==0&&(await pf(e,{recursive:!0,force:!0}).catch(()=>{}),await $e(["worktree","prune"],n)),await $e(["branch","-D",t],n),o?.info(`[worktree] agent worktree removed: ${e}`),!0}function bf(n){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:o}=n;return{async enterWorktree(r){try{let s=Date.now(),i=await Ho();if(!i)return{success:!1,error:"Not in a git repository"};let a=await df("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let $=process.cwd();return process.chdir(a),ot={originalCwd:$,worktreePath:a,worktreeName:r??ec(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:ot.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=r??`agent-${Date.now().toString(36)}`;mf(l);let c=tc(l),d=ff(l),u=Rn(i,".worktrees"),p=Rn(u,c);await uf(u,{recursive:!0});let{stdout:m}=await $e(["worktree","list","--porcelain"],i),h=m.split(`
424
- `).find($=>$.startsWith("worktree ")&&$.includes(c));if(h){let $=h.replace("worktree ","").trim(),W=process.cwd();return process.chdir($),ot={originalCwd:W,worktreePath:$,worktreeName:l,worktreeBranch:d},e.info(`[worktree] resumed existing worktree: ${l} at ${$}`),{success:!0,worktree:{name:l,path:$,branch:d,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=o&&o.length>0,y=["worktree","add"];f&&y.push("--no-checkout"),y.push("-B",d,p,"HEAD");let{code:b,stderr:k}=await $e(y,i);if(b!==0)return{success:!1,error:`git worktree add failed: ${k.trim()}`};let x=!1;f&&o&&(await v_(p,i,o),x=!0),await gf(i,p,t,e);let I=process.cwd();process.chdir(p);let P=T_(i,d),O=await w_(p,P);return ot={originalCwd:I,worktreePath:p,worktreeName:l,worktreeBranch:d,tmuxSessionName:O??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:x},e.info(`[worktree] entered: ${l} at ${p}`),{success:!0,worktree:{name:l,path:p,branch:d,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(r,s){if(!ot)return{success:!1,error:"Not in a worktree"};try{let i=ot,a=await Ho(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let l=await af(i.worktreePath),c=await lf(i.worktreePath,i.worktreeBranch);if((l>0||c>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${c} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),ot=null,i.tmuxSessionName&&await cf(i.tmuxSessionName),await df("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let d=["worktree","remove"];s&&d.push("--force"),d.push(i.worktreePath);let{code:u,stderr:p}=await $e(d,a);u!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await pf(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await $e(["worktree","prune"],a)),await $e(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await cf(i.tmuxSessionName),ot=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 $e(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=r.split(`
422
+ `)}],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"}}}}}}le();import{execFile as y_}from"node:child_process";import{promisify as b_}from"node:util";import{join as Rn,resolve as rf,basename as ec}from"node:path";import{mkdir as uf,rm as pf,symlink as k_,readdir as w$,stat as v_}from"node:fs/promises";var Vo=b_(y_),S_=/^[a-zA-Z0-9._-]+$/,sf=64;function mf(n){if(n.length>sf)throw new Error(`Invalid worktree name: must be ${sf} 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(!S_.test(e))throw new Error(`Invalid worktree name "${n}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function tc(n){return n.replaceAll("/","+")}function ff(n){return`worktree-${tc(n)}`}var ot=null;async function $e(n,e){try{let{stdout:t,stderr:o}=await Vo("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 Ho(n){let{stdout:e,code:t}=await $e(["rev-parse","--show-toplevel"],n);return t===0?e.trim():null}async function af(n){let{stdout:e,code:t}=await $e(["status","--porcelain"],n);return t!==0?-1:e.trim().split(`
423
+ `).filter(Boolean).length}async function lf(n,e){let{stdout:t,code:o}=await $e(["rev-list",`origin/${e}..${e}`,"--count"],n);return o!==0?0:parseInt(t.trim(),10)||0}async function gf(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=Rn(n,r),i=Rn(e,r);try{await k_(s,i,"dir"),o?.info(`[worktree] symlinked ${r} from main repo to worktree`)}catch(a){let l=a.code;l!=="ENOENT"&&l!=="EEXIST"&&o?.warn(`[worktree] failed to symlink ${r} (${l??"unknown"}): ${a}`)}}}async function T_(n,e,t){let{code:o,stderr:r}=await $e(["sparse-checkout","set","--cone","--",...t],n);if(o!==0)throw await $e(["worktree","remove","--force",n],e),new Error(`Failed to configure sparse-checkout: ${r}`);let{code:s,stderr:i}=await $e(["checkout","HEAD"],n);if(s!==0)throw await $e(["worktree","remove","--force",n],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function w_(){try{return await Vo("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function x_(n,e){return`${ec(n)}_${e}`.replace(/[/.]/g,"_")}async function R_(n,e){if(!await w_())return null;try{return await Vo("tmux",["new-session","-d","-s",e,"-c",n],{timeout:1e4}),e}catch{return null}}async function cf(n){try{return await Vo("tmux",["kill-session","-t",n],{timeout:5e3}),!0}catch{return!1}}async function df(n,e,t,o){let r=lp(e),s=Rn(r,n);try{if(!(await v_(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await Vo(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}}async function hf(n,e,t){mf(e);let o=tc(e),r=ff(e),s=Rn(n,".worktrees"),i=Rn(s,o);await uf(s,{recursive:!0});let{code:a,stderr:l}=await $e(["worktree","add","-B",r,i,"HEAD"],n);return a!==0?(t?.warn(`[worktree] agent worktree creation failed: ${l}`),null):(await gf(n,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:r})}async function yf(n,e,t,o){let{code:r}=await $e(["worktree","remove","--force",e],n);return r!==0&&(await pf(e,{recursive:!0,force:!0}).catch(()=>{}),await $e(["worktree","prune"],n)),await $e(["branch","-D",t],n),o?.info(`[worktree] agent worktree removed: ${e}`),!0}function bf(n){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:o}=n;return{async enterWorktree(r){try{let s=Date.now(),i=await Ho();if(!i)return{success:!1,error:"Not in a git repository"};let a=await df("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let $=process.cwd();return process.chdir(a),ot={originalCwd:$,worktreePath:a,worktreeName:r??ec(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:ot.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=r??`agent-${Date.now().toString(36)}`;mf(l);let c=tc(l),d=ff(l),u=Rn(i,".worktrees"),p=Rn(u,c);await uf(u,{recursive:!0});let{stdout:m}=await $e(["worktree","list","--porcelain"],i),h=m.split(`
424
+ `).find($=>$.startsWith("worktree ")&&$.includes(c));if(h){let $=h.replace("worktree ","").trim(),W=process.cwd();return process.chdir($),ot={originalCwd:W,worktreePath:$,worktreeName:l,worktreeBranch:d},e.info(`[worktree] resumed existing worktree: ${l} at ${$}`),{success:!0,worktree:{name:l,path:$,branch:d,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=o&&o.length>0,y=["worktree","add"];f&&y.push("--no-checkout"),y.push("-B",d,p,"HEAD");let{code:b,stderr:k}=await $e(y,i);if(b!==0)return{success:!1,error:`git worktree add failed: ${k.trim()}`};let x=!1;f&&o&&(await T_(p,i,o),x=!0),await gf(i,p,t,e);let I=process.cwd();process.chdir(p);let P=x_(i,d),O=await R_(p,P);return ot={originalCwd:I,worktreePath:p,worktreeName:l,worktreeBranch:d,tmuxSessionName:O??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:x},e.info(`[worktree] entered: ${l} at ${p}`),{success:!0,worktree:{name:l,path:p,branch:d,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(r,s){if(!ot)return{success:!1,error:"Not in a worktree"};try{let i=ot,a=await Ho(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let l=await af(i.worktreePath),c=await lf(i.worktreePath,i.worktreeBranch);if((l>0||c>0)&&!s)return{success:!1,error:`Worktree has ${l} uncommitted change(s) and ${c} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),ot=null,i.tmuxSessionName&&await cf(i.tmuxSessionName),await df("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let d=["worktree","remove"];s&&d.push("--force"),d.push(i.worktreePath);let{code:u,stderr:p}=await $e(d,a);u!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await pf(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await $e(["worktree","prune"],a)),await $e(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await cf(i.tmuxSessionName),ot=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 $e(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),l=r.split(`
425
425
 
426
426
  `).filter(Boolean);for(let c of l){let d=c.split(`
427
- `),u="",p="";for(let y of d)y.startsWith("worktree ")&&(u=y.slice(9).trim()),y.startsWith("branch ")&&(p=y.slice(7).trim().replace("refs/heads/",""));if(!u)continue;let m=rf(u)===rf(a),h=await af(u),f=await lf(u,p);i.push({name:p.startsWith("worktree-")?p.slice(9):ec(u),path:u,branch:p,isCurrent:m,hasChanges:h>0,unpushedCommits:f})}return{success:!0,worktrees:i}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}},isInWorktree(){return ot!==null},currentWorktree(){return ot?{name:ot.worktreeName,path:ot.worktreePath,branch:ot.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as x_,writeFile as R_}from"node:fs/promises";import*as kf from"node:path";var __={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 vf(n){let e=n.split(`
427
+ `),u="",p="";for(let y of d)y.startsWith("worktree ")&&(u=y.slice(9).trim()),y.startsWith("branch ")&&(p=y.slice(7).trim().replace("refs/heads/",""));if(!u)continue;let m=rf(u)===rf(a),h=await af(u),f=await lf(u,p);i.push({name:p.startsWith("worktree-")?p.slice(9):ec(u),path:u,branch:p,isCurrent:m,hasChanges:h>0,unpushedCommits:f})}return{success:!0,worktrees:i}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}},isInWorktree(){return ot!==null},currentWorktree(){return ot?{name:ot.worktreeName,path:ot.worktreePath,branch:ot.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as __,writeFile as A_}from"node:fs/promises";import*as kf from"node:path";var P_={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 vf(n){let e=n.split(`
428
428
  `);return e.map((t,o)=>o<e.length-1?t+`
429
- `:t)}function Sf(n){return n.join("")}function A_(n,e){let t=Sf(n.source).trim(),o=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${n.cell_type}]: ${o}`}function P_(n,e){let t={cell_type:n,source:vf(e),metadata:{}};return n==="code"&&(t.execution_count=null,t.outputs=[]),t}function Tf(){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:__,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=kf.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 x_(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let l=a.cells.length,c=o-1;if(r==="insert"){if(o<0||o>l)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(c<0||c>=l)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let d;switch(r){case"replace":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'replace' mode."}],details:{error:"missing_source"}};let m=a.cells[c],h=Sf(m.source);m.source=vf(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),d=`Replaced cell ${o} [${m.cell_type}].
429
+ `:t)}function Sf(n){return n.join("")}function I_(n,e){let t=Sf(n.source).trim(),o=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${n.cell_type}]: ${o}`}function C_(n,e){let t={cell_type:n,source:vf(e),metadata:{}};return n==="code"&&(t.execution_count=null,t.outputs=[]),t}function Tf(){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:P_,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=kf.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 __(t,"utf-8")}catch(m){return{content:[{type:"text",text:`Error reading notebook: ${m.message}`}],details:{error:"read_failed"}}}let a;try{a=JSON.parse(i)}catch{return{content:[{type:"text",text:"Error: File is not valid JSON (not a valid .ipynb)."}],details:{error:"parse_failed"}}}if(!Array.isArray(a.cells))return{content:[{type:"text",text:"Error: Notebook has no cells array."}],details:{error:"invalid_notebook"}};let l=a.cells.length,c=o-1;if(r==="insert"){if(o<0||o>l)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. For insert, use 0-${l}.`}],details:{error:"out_of_range"}}}else if(c<0||c>=l)return{content:[{type:"text",text:`Error: cell_number ${o} out of range. Notebook has ${l} cell(s).`}],details:{error:"out_of_range"}};let d;switch(r){case"replace":{if(!e.new_source)return{content:[{type:"text",text:"Error: new_source is required for 'replace' mode."}],details:{error:"missing_source"}};let m=a.cells[c],h=Sf(m.source);m.source=vf(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),d=`Replaced cell ${o} [${m.cell_type}].
430
430
  Old: ${h.slice(0,120)}${h.length>120?"...":""}
431
- 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=P_(m,e.new_source);a.cells.splice(o,0,h),d=`Inserted new ${m} cell after position ${o}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(c,1)[0];d=`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)+`
432
- `;await R_(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let u=a.cells.slice(0,10).map((m,h)=>A_(m,h)).join(`
431
+ 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=C_(m,e.new_source);a.cells.splice(o,0,h),d=`Inserted new ${m} cell after position ${o}. Total cells: ${a.cells.length}.`;break}case"delete":{let m=a.cells.splice(c,1)[0];d=`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)+`
432
+ `;await A_(t,m,"utf-8")}catch(m){return{content:[{type:"text",text:`Error writing notebook: ${m.message}`}],details:{error:"write_failed"}}}let u=a.cells.slice(0,10).map((m,h)=>I_(m,h)).join(`
433
433
  `),p=a.cells.length>10?`
434
434
  ... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${d}
435
435
 
436
436
  Current cells:
437
- ${u}${p}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:o,total_cells:a.cells.length}}}}}le();import{readFile as I_,readdir as C_}from"node:fs/promises";import*as xf from"node:path";import{existsSync as E_}from"node:fs";var M_={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
437
+ ${u}${p}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:o,total_cells:a.cells.length}}}}}le();import{readFile as E_,readdir as M_}from"node:fs/promises";import*as xf from"node:path";import{existsSync as O_}from"node:fs";var D_={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
438
438
  run: Execute a workflow by name.
439
- 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 nc(n){let e=new Map,t=ip(n);await wf(t,e);let o=rp();return await wf(o,e),e}async function wf(n,e){if(E_(n))try{let t=await C_(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,xf.join(n,o.name))}}catch{}}async function oc(n){let e=await I_(n,"utf-8");return JSON.parse(e)}function O_(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 l of a.dependsOn??[])r(l,i);i.delete(s),t.add(s),o.push(a)}for(let s of n)r(s.id,new Set);return o}function D_(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,l)=>e[l]??`\${var.${l}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,l)=>t.get(l)?.output??""),o[r]=i}else o[r]=s;return o}function Rf(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:M_,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 nc(r);if(s.size===0)return{content:[{type:"text",text:"No workflows found. Create .json files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/."}],details:{type:"workflow",action:"list",count:0}};let i=["Available workflows:"];for(let[a,l]of s)try{let c=await oc(l);i.push(` - ${a}: ${c.description??"(no description)"} (${c.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
439
+ 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 nc(n){let e=new Map,t=ip(n);await wf(t,e);let o=rp();return await wf(o,e),e}async function wf(n,e){if(O_(n))try{let t=await M_(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,xf.join(n,o.name))}}catch{}}async function oc(n){let e=await E_(n,"utf-8");return JSON.parse(e)}function L_(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 l of a.dependsOn??[])r(l,i);i.delete(s),t.add(s),o.push(a)}for(let s of n)r(s.id,new Set);return o}function N_(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,l)=>e[l]??`\${var.${l}}`),i=i.replace(/\$\{step\.(\w+)\.result\}/g,(a,l)=>t.get(l)?.output??""),o[r]=i}else o[r]=s;return o}function Rf(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:D_,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 nc(r);if(s.size===0)return{content:[{type:"text",text:"No workflows found. Create .json files in .qlogicagent/workflows/ or ~/.qlogicagent/workflows/."}],details:{type:"workflow",action:"list",count:0}};let i=["Available workflows:"];for(let[a,l]of s)try{let c=await oc(l);i.push(` - ${a}: ${c.description??"(no description)"} (${c.steps.length} steps)`)}catch{i.push(` - ${a}: (failed to load)`)}return{content:[{type:"text",text:i.join(`
440
440
  `)}],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 nc(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await oc(i),l=[`Workflow: ${a.name}`,a.description?`Description: ${a.description}`:"","","Steps:"];for(let c of a.steps){let d=c.dependsOn?.length?` (after: ${c.dependsOn.join(", ")})`:"";l.push(` ${c.id}: ${c.label??c.tool}${d}`),l.push(` tool: ${c.tool}`),l.push(` args: ${JSON.stringify(c.args)}`)}if(a.variables&&Object.keys(a.variables).length>0){l.push("","Variables (defaults):");for(let[c,d]of Object.entries(a.variables))l.push(` ${c} = ${d}`)}return{content:[{type:"text",text:l.filter(Boolean).join(`
441
- `)}],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 nc(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await oc(i),l={...a.variables,...t.variables},c;try{c=O_(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let d=new Map,u=[`Running workflow: ${a.name}`,""],p=!0;for(let m of c){if(o?.aborted){u.push(`\u26A1 Aborted at step: ${m.id}`),p=!1;break}let h=(m.dependsOn??[]).some(b=>!d.get(b)?.success),f=m.condition??"on_success";if(f==="on_success"&&h){u.push(`\u23ED Skipped ${m.id} (dependency failed)`),d.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(f==="on_failure"&&!h){u.push(`\u23ED Skipped ${m.id} (no failure to handle)`),d.set(m.id,{stepId:m.id,success:!0,output:""});continue}u.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let y=D_(m.args,l,d);try{let b=await n.invokeTool(m.tool,y,o),k=!b.error;if(d.set(m.id,{stepId:m.id,success:k,output:b.result,error:b.error}),k){let x=b.result.length>200?b.result.slice(0,200)+"...":b.result;u.push(` \u2705 ${x}`)}else u.push(` \u274C ${b.error}`),p=!1}catch(b){let k=b.message;d.set(m.id,{stepId:m.id,success:!1,output:"",error:k}),u.push(` \u274C ${k}`),p=!1}}return u.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:u.join(`
442
- `)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:d.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 L_="sleep",N_={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 _f(n){return{name:L_,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(`
443
- `),parameters:N_,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 l=await n.sleep(s,i.signal),c=[];return l.interrupted?(c.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&c.push(`Reason: ${l.interruptReason}`),c.push("Check for new messages or tasks.")):c.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:c.join(`
444
- `)}],details:{...l,requestedSeconds:r}}}finally{o?.removeEventListener("abort",a)}}}}var $_="tool_search",U_={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"]},j_=5;function Pf(n){return{name:$_,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:U_,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??j_;if(o.startsWith("select:")){let i=o.slice(7).split(",").map(d=>d.trim()).filter(Boolean),a=[],l=[];if(n.activateTool)for(let d of i)await n.activateTool(d)?a.push(d):l.push(d);else{let d=await n.searchTools(o,{maxResults:r});return Af(d)}let c=[];return a.length>0&&c.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&c.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:c.join(`
441
+ `)}],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 nc(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await oc(i),l={...a.variables,...t.variables},c;try{c=L_(a.steps)}catch(m){return{content:[{type:"text",text:`Error: ${m.message}`}],details:{error:"dag_error"}}}let d=new Map,u=[`Running workflow: ${a.name}`,""],p=!0;for(let m of c){if(o?.aborted){u.push(`\u26A1 Aborted at step: ${m.id}`),p=!1;break}let h=(m.dependsOn??[]).some(b=>!d.get(b)?.success),f=m.condition??"on_success";if(f==="on_success"&&h){u.push(`\u23ED Skipped ${m.id} (dependency failed)`),d.set(m.id,{stepId:m.id,success:!1,output:"",error:"dependency_failed"}),p=!1;continue}if(f==="on_failure"&&!h){u.push(`\u23ED Skipped ${m.id} (no failure to handle)`),d.set(m.id,{stepId:m.id,success:!0,output:""});continue}u.push(`\u25B6 ${m.id}: ${m.label??m.tool}`);let y=N_(m.args,l,d);try{let b=await n.invokeTool(m.tool,y,o),k=!b.error;if(d.set(m.id,{stepId:m.id,success:k,output:b.result,error:b.error}),k){let x=b.result.length>200?b.result.slice(0,200)+"...":b.result;u.push(` \u2705 ${x}`)}else u.push(` \u274C ${b.error}`),p=!1}catch(b){let k=b.message;d.set(m.id,{stepId:m.id,success:!1,output:"",error:k}),u.push(` \u274C ${k}`),p=!1}}return u.push("",p?"Workflow completed successfully.":"Workflow completed with errors."),{content:[{type:"text",text:u.join(`
442
+ `)}],details:{type:"workflow",action:"run",workflow:a.name,success:p,stepsExecuted:d.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 $_="sleep",U_={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 _f(n){return{name:$_,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(`
443
+ `),parameters:U_,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 l=await n.sleep(s,i.signal),c=[];return l.interrupted?(c.push(`Sleep interrupted after ${l.sleptSeconds}s.`),l.interruptReason&&c.push(`Reason: ${l.interruptReason}`),c.push("Check for new messages or tasks.")):c.push(`Slept for ${l.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:c.join(`
444
+ `)}],details:{...l,requestedSeconds:r}}}finally{o?.removeEventListener("abort",a)}}}}var j_="tool_search",F_={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"]},B_=5;function Pf(n){return{name:j_,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:F_,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??B_;if(o.startsWith("select:")){let i=o.slice(7).split(",").map(d=>d.trim()).filter(Boolean),a=[],l=[];if(n.activateTool)for(let d of i)await n.activateTool(d)?a.push(d):l.push(d);else{let d=await n.searchTools(o,{maxResults:r});return Af(d)}let c=[];return a.length>0&&c.push(`Activated: ${a.join(", ")}. These tools are now available.`),l.length>0&&c.push(`Not found: ${l.join(", ")}.`),{content:[{type:"text",text:c.join(`
445
445
  `)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await n.searchTools(o,{maxResults:r});return Af(s)}}}function Af(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(`
446
- `)}],details:{type:"tool_search",query:n.query,matchCount:n.matches.length,totalDeferred:n.totalDeferred,matches:n.matches.map(t=>t.name)}}}var rc="image_generate",F_={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 If(n){return{name:rc,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:F_,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 B_={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 Cf(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:B_,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 sc="video_generate",W_={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 Ef(n){return{name:sc,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:W_,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,...o.taskId?{taskId:o.taskId}:{}}}}}}var ic="music_generate",G_={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 Mf(n){return{name:ic,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:G_,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 H_="video_edit",V_={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 Of(n){return{name:H_,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:V_,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 K_="video_merge",z_={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 Df(n){return{name:K_,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:z_,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 q_="video_upscale",Y_={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 Lf(n){return{name:q_,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:Y_,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 X_="three_d_generate",J_={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 Nf(n){return{name:X_,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:J_,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,s=`Generated ${r} 3D model${r>1?"s":""}${o.model?` (model: ${o.model})`:""}`;return r===0&&o.metadata?.debugResponseKeys&&(s+=` [debug: response keys=${JSON.stringify(o.metadata.debugResponseKeys)}, content=${o.metadata.debugContentSample??"null"}]`),{content:[{type:"text",text:s}],details:{type:"three_d_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls,...o.metadata??{}}}}}}var Q_={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 $f(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:Q_,execute:async(e,t)=>{if(!t.audio_url)return{content:[{type:"text",text:"Error: audio_url parameter is required. Provide a publicly accessible HTTP/HTTPS URL to an audio file."}],details:{error:"audio_url parameter is required"}};let 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 Z_="voice_clone",eA={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 Uf(n){return{name:Z_,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:eA,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 tA="media_cancel",nA={type:"object",properties:{task_id:{type:"string",description:"The task ID of the media generation to cancel (returned in previous generation results)."},provider:{type:"string",description:"Provider name (e.g. 'doubao', 'zhipu'). If omitted, auto-detects from task context."}},required:["task_id"]};function jf(n){return{name:tA,label:"Media Cancel",description:"Cancel an in-progress media generation task (video, 3D, etc.). Provide the task_id from a previous generation result. Use this when a user wants to abort a long-running generation.",parameters:nA,execute:async(e,t)=>{if(!t.task_id)return{content:[{type:"text",text:"Error: task_id is required."}],details:{error:"task_id is required"}};let o=await n.cancelTask({taskId:t.task_id,provider:t.provider});return{content:[{type:"text",text:o.ok?`Task ${t.task_id} cancelled.`:`Cancel failed: ${o.message}`}],details:o.ok?void 0:{error:o.message}}}}}var oA="file_upload",rA={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 Ff(n){return{name:oA,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:rA,execute:async(e,t)=>{let o=await n.uploadFile({filePath:t.file_path,purpose:t.purpose}),r=[`Uploaded "${o.filename}" (${ac(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(`
447
- `)}],details:{type:"file_upload",fileId:o.fileId,url:o.url,filename:o.filename,bytes:o.bytes,provider:o.provider}}}}}var sA="file_query",iA={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 Bf(n){return{name:sA,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:iA,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: ${ac(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(`
446
+ `)}],details:{type:"tool_search",query:n.query,matchCount:n.matches.length,totalDeferred:n.totalDeferred,matches:n.matches.map(t=>t.name)}}}var rc="image_generate",W_={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 If(n){return{name:rc,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:W_,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 G_={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 Cf(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:G_,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 sc="video_generate",H_={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 Ef(n){return{name:sc,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:H_,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,...o.taskId?{taskId:o.taskId}:{}}}}}}var ic="music_generate",V_={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 Mf(n){return{name:ic,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:V_,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 K_="video_edit",z_={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 Of(n){return{name:K_,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:z_,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 q_="video_merge",Y_={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 Df(n){return{name:q_,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:Y_,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 X_="video_upscale",J_={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 Lf(n){return{name:X_,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:J_,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 Q_="three_d_generate",Z_={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 Nf(n){return{name:Q_,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:Z_,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,s=`Generated ${r} 3D model${r>1?"s":""}${o.model?` (model: ${o.model})`:""}`;return r===0&&o.metadata?.debugResponseKeys&&(s+=` [debug: response keys=${JSON.stringify(o.metadata.debugResponseKeys)}, content=${o.metadata.debugContentSample??"null"}]`),{content:[{type:"text",text:s}],details:{type:"three_d_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls,...o.metadata??{}}}}}}var eA={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 $f(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:eA,execute:async(e,t)=>{if(!t.audio_url)return{content:[{type:"text",text:"Error: audio_url parameter is required. Provide a publicly accessible HTTP/HTTPS URL to an audio file."}],details:{error:"audio_url parameter is required"}};let 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 tA="voice_clone",nA={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 Uf(n){return{name:tA,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:nA,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 oA="media_cancel",rA={type:"object",properties:{task_id:{type:"string",description:"The task ID of the media generation to cancel (returned in previous generation results)."},provider:{type:"string",description:"Provider name (e.g. 'doubao', 'zhipu'). If omitted, auto-detects from task context."}},required:["task_id"]};function jf(n){return{name:oA,label:"Media Cancel",description:"Cancel an in-progress media generation task (video, 3D, etc.). Provide the task_id from a previous generation result. Use this when a user wants to abort a long-running generation.",parameters:rA,execute:async(e,t)=>{if(!t.task_id)return{content:[{type:"text",text:"Error: task_id is required."}],details:{error:"task_id is required"}};let o=await n.cancelTask({taskId:t.task_id,provider:t.provider});return{content:[{type:"text",text:o.ok?`Task ${t.task_id} cancelled.`:`Cancel failed: ${o.message}`}],details:o.ok?void 0:{error:o.message}}}}}var sA="file_upload",iA={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 Ff(n){return{name:sA,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:iA,execute:async(e,t)=>{let o=await n.uploadFile({filePath:t.file_path,purpose:t.purpose}),r=[`Uploaded "${o.filename}" (${ac(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(`
447
+ `)}],details:{type:"file_upload",fileId:o.fileId,url:o.url,filename:o.filename,bytes:o.bytes,provider:o.provider}}}}}var aA="file_query",lA={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 Bf(n){return{name:aA,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:lA,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: ${ac(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(`
448
448
  `)}],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):
449
449
  `];for(let i of r)s.push(`- ${i.filename} | ID: ${i.id} | ${ac(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
450
- `)}],details:{type:"file_query",count:r.length}}}}}var aA="file_delete",lA={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function Wf(n){return{name:aA,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:lA,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 ac(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var cA="ask_user",dA={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:4,description:"1-4 clarifying questions to ask the user.",items:{type:"object",properties:{question:{type:"string",description:"The question text. Should end with '?'."},header:{type:"string",description:"Short identifier/tag for this question (max 50 chars)."},options:{type:"array",description:"2-4 options for the user to choose from. Omit for free text.",items:{type:"object",properties:{label:{type:"string",description:"Display label (1-5 words)."},description:{type:"string",description:"Brief explanation of this option."}},required:["label"]}},multiSelect:{type:"boolean",description:"Allow selecting multiple options (default: false)."}},required:["question","header"]}}},required:["questions"]};function Gf(n){return{name:cA,label:"Ask User",description:"Ask the user clarifying questions when you need more information to proceed. Supports free text questions and multiple-choice options. Use this when the user's intent is ambiguous or you need confirmation.",parameters:dA,execute:async(e,t)=>{if(!t.questions||t.questions.length===0)return{content:[{type:"text",text:"Error: at least one question is required."}],details:{type:"ask_user",error:"no_questions"}};if(t.questions.length>4)return{content:[{type:"text",text:"Error: maximum 4 questions allowed."}],details:{type:"ask_user",error:"too_many_questions"}};let o=t.questions.map(i=>i.question);if(new Set(o).size!==o.length)return{content:[{type:"text",text:"Error: all questions must have unique text."}],details:{type:"ask_user",error:"duplicate_questions"}};for(let i of t.questions){if(i.options&&(i.options.length<2||i.options.length>4))return{content:[{type:"text",text:`Error: question "${i.header}" must have 2-4 options (got ${i.options.length}).`}],details:{type:"ask_user",error:"invalid_option_count"}};if(i.options){let a=i.options.map(l=>l.label);if(new Set(a).size!==a.length)return{content:[{type:"text",text:`Error: question "${i.header}" has duplicate option labels.`}],details:{type:"ask_user",error:"duplicate_option_labels"}}}}let r=await n.askUser(t.questions);if(r===null)return{content:[{type:"text",text:"User declined to answer questions."}],details:{type:"ask_user",declined:!0}};let s=["User answered:"];for(let i of t.questions){let a=r[i.question]??"(no answer)";s.push(`- ${i.header}: ${a}`)}return{content:[{type:"text",text:s.join(`
451
- `)}],details:{type:"ask_user",answers:r,questionCount:t.questions.length}}}}}var uA="project_switch",pA={type:"object",properties:{projectName:{type:"string",description:"The name of the project to switch to. Use the exact project name from the available project list."}},required:["projectName"]};function Hf(n){return{name:uA,label:"Switch Project",description:["Switch the active project context. ONLY call this when the user EXPLICITLY asks to switch projects","(e.g. '\u5207\u6362\u5230XX\u9879\u76EE', 'switch to project X').","Do NOT call this if the user merely mentions a project name in conversation.","The projectName must be an EXACT match from the available project list.","If unsure which project the user means, ask them to clarify first."].join(`
452
- `),parameters:pA,isReadOnly:!1,isConcurrencySafe:!1,shouldDefer:!0,searchHint:"switch project change workspace \u5207\u6362\u9879\u76EE",execute:async(e,t)=>{let o=n.listProjects();if(o.length===0)return{content:[{type:"text",text:"Error: No projects available."}]};let r=t.projectName.toLowerCase().trim(),s=o.find(a=>a.name.toLowerCase()===r);if(!s){let a=o.map(l=>`"${l.name}"`).join(", ");return{content:[{type:"text",text:`Error: No project with exact name "${t.projectName}". Available projects: ${a}. Please confirm the exact project name with the user before retrying.`}]}}let i=n.switchProject(s.id);return i?(n.onSwitched?.(i),{content:[{type:"text",text:`Switched to project "${i.name}" (workspace: ${i.workspaceDir}).`}]}):{content:[{type:"text",text:`Error: Failed to switch to project "${s.name}".`}]}}}}var ys=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 l of s.web_search.slice(0,a))i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content});return i}for(let l of s.choices??[])for(let c of l.message?.tool_calls??[])for(let d of c.search_result??[]){if(i.length>=a)break;i.push({title:d.title??"",url:d.link??"",snippet:(d.content??"").slice(0,500),content:d.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()}};Or();Mr();Qa();function Vf(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 mA=[{pattern:"Bash",behavior:"ask",reason:"Group security: shell commands require approval in group chat",source:"group-policy"},{pattern:"computer",behavior:"deny",reason:"Group security: computer control blocked in group chat",source:"group-policy"}],fA=[/\.env($|\.)/i,/\.(key|pem|p12|pfx|jks)$/i,/id_rsa/i,/id_ed25519/i,/\.ssh\//i,/secret/i,/credential/i,/token/i,/password/i,/\.aws\//i,/\.gnupg\//i];function Kf(){return[...mA]}function lc(n){return fA.some(e=>e.test(n))}var gc=!1;function hc(n){gc=n}var Se,Fe={},Xf,uc,un={},Jf;function yc(n){Jf=n}var yA=new Set(["zhipu","zhipu-openai","zhipu-coding"]),bA="https://open.bigmodel.cn/api/paas/v4";function Qf(n,e){if(!(!n||!e)&&yA.has(n))return new ys({baseUrl:bA,apiKey:e})}var Zf=null,kA;var pc;function eg(n){pc=n}function tg(n){Zf=n}function ng(n,e,t,o,r){Se=n,Fe=e??{},Xf=t,uc=r,un=o??{},vA()}function bc(n){let e=un[n];if(!(!e||!Se))return Se.resolveModelById(e.provider,e.model,n)}function vA(){SA(),TA(),wA(),xA()}function SA(){let n=nt(sc);if(!n)return;let e=un.video;if(!e||!Se)return;let t=Se.resolveModelById(e.provider,e.model,"video");if(!t)return;let o=t.modelInfo.mediaCapabilities;if(!o)return;let r=o.maxDurationSeconds??10,s=r>=10?4:3,i=o.resolutions?.join("/")||"720P",a=t.modelInfo.name||t.modelInfo.id;n.description=`Generate a short video clip from a text prompt, reference image, source video, or multimodal references. Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Current model: ${a}. Single-shot: ${s}\u2013${r}s. For longer videos (>${r}s), use multi-shot storyboard workflow. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. IMPORTANT: If the user has not specified aspect ratio or duration, use ask_user to clarify (e.g. aspect: 16:9 for landscape / 9:16 for vertical / 1:1 for square; duration: ${s}-${r}s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).`;let l=n.parameters?.properties,c=l?.duration;c&&(c.minimum=s,c.maximum=r,c.description=`Video duration in seconds (${s}\u2013${r}s for ${a}). For longer videos (>${r}s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation.`);let d=l?.resolution;d&&o.resolutions&&(d.description=`Output resolution: ${i}. Default: '720p'.`)}function TA(){let n=nt(rc);if(!n)return;let e=bc("image");if(!e)return;let t=e.modelInfo.mediaCapabilities,o=e.modelInfo.name||e.modelInfo.id,r=[];if(t?.sizes?.length&&r.push(`Sizes: ${t.sizes.join(", ")}`),t?.transparentBackground&&r.push("Supports transparent background"),n.description=`Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately. Current model: ${o}. ${r.join(". ")}${r.length?". ":""}IMPORTANT: If the user has not specified purpose or preferred style, use ask_user to clarify (e.g. purpose: social-media / wallpaper / poster; style: photorealistic / anime / watercolor). Infer image size automatically from purpose. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file.`,t?.sizes?.length){let i=n.parameters?.properties?.size;i&&(i.description=`Dimensions: ${t.sizes.join(", ")}. Default: '1024x1024'. Auto-infer from purpose.`)}}function wA(){let n=nt("tts");if(!n)return;let e=bc("tts");if(!e)return;let t=e.modelInfo.mediaCapabilities,o=e.modelInfo.name||e.modelInfo.id,r=[];if(t?.voices?.length&&r.push(`Voices: ${t.voices.join(", ")}`),t?.maxCharacters&&r.push(`Max: ${t.maxCharacters} characters per request`),t?.formats?.length&&r.push(`Formats: ${t.formats.join(", ")}`),n.description=`Convert text to speech (TTS) \u2014 read text aloud as spoken audio. Use for narration, voice messages, or any spoken-word output. DO NOT use for music, songs, or melodies \u2014 use music_generate instead. Current model: ${o}. ${r.join(". ")}${r.length?".":""}`,t?.voices?.length){let i=n.parameters?.properties?.voice;i&&(i.description=`Voice name. Available: ${t.voices.join(", ")}.`)}}function xA(){let n=nt(ic);if(!n)return;let e=bc("music");if(!e)return;let t=e.modelInfo.mediaCapabilities,o=e.modelInfo.name||e.modelInfo.id,r=[];if(t?.maxDurationSeconds&&r.push(`Max duration: ${t.maxDurationSeconds}s`),t?.formats?.length&&r.push(`Formats: ${t.formats.join(", ")}`),n.description=`Generate music, songs, or melodies from text descriptions. Prompt MUST be in English. Supports lyrics for vocal songs. DO NOT use for spoken-word audio or TTS \u2014 use tts tool instead. Current model: ${o}. ${r.join(". ")}${r.length?". ":""}IMPORTANT: If the user has not specified genre/style or duration, use ask_user to clarify (e.g. style: lo-fi / pop / rock / jazz; duration inferred from purpose).`,t?.maxDurationSeconds){let i=n.parameters?.properties?.duration;i&&(i.maximum=t.maxDurationSeconds,i.description=`Duration in seconds (5\u2013${t.maxDurationSeconds}s for ${o}). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s.`)}}async function Ot(n){if(!Se)throw new Error(`No media provider configured for ${n.mediaType}`);let e=un[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={...n};uc&&!r.onProgress&&(r.onProgress=(l,c,d)=>{uc(d??"pending",n.mediaType,l,c,t)});let s=await zf(t,o||n.model,r);if(s.ok)return s.result;let i=Se.listMediaModels(n.mediaType),a=[`${t}: ${s.error}`];for(let l of i){if(l.providerId===t||!Fe[l.providerId])continue;let d=await zf(l.providerId,l.modelInfo.id,n);if(d.ok)return d.result;a.push(`${l.providerId}/${l.modelInfo.id}: ${d.error}`)}throw new Error(`All media providers failed for ${n.mediaType}:
450
+ `)}],details:{type:"file_query",count:r.length}}}}}var cA="file_delete",dA={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function Wf(n){return{name:cA,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:dA,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 ac(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var uA="ask_user",pA={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:4,description:"1-4 clarifying questions to ask the user.",items:{type:"object",properties:{question:{type:"string",description:"The question text. Should end with '?'."},header:{type:"string",description:"Short identifier/tag for this question (max 50 chars)."},options:{type:"array",description:"2-4 options for the user to choose from. Omit for free text.",items:{type:"object",properties:{label:{type:"string",description:"Display label (1-5 words)."},description:{type:"string",description:"Brief explanation of this option."}},required:["label"]}},multiSelect:{type:"boolean",description:"Allow selecting multiple options (default: false)."}},required:["question","header"]}}},required:["questions"]};function Gf(n){return{name:uA,label:"Ask User",description:"Ask the user clarifying questions when you need more information to proceed. Supports free text questions and multiple-choice options. Use this when the user's intent is ambiguous or you need confirmation.",parameters:pA,execute:async(e,t)=>{if(!t.questions||t.questions.length===0)return{content:[{type:"text",text:"Error: at least one question is required."}],details:{type:"ask_user",error:"no_questions"}};if(t.questions.length>4)return{content:[{type:"text",text:"Error: maximum 4 questions allowed."}],details:{type:"ask_user",error:"too_many_questions"}};let o=t.questions.map(i=>i.question);if(new Set(o).size!==o.length)return{content:[{type:"text",text:"Error: all questions must have unique text."}],details:{type:"ask_user",error:"duplicate_questions"}};for(let i of t.questions){if(i.options&&(i.options.length<2||i.options.length>4))return{content:[{type:"text",text:`Error: question "${i.header}" must have 2-4 options (got ${i.options.length}).`}],details:{type:"ask_user",error:"invalid_option_count"}};if(i.options){let a=i.options.map(l=>l.label);if(new Set(a).size!==a.length)return{content:[{type:"text",text:`Error: question "${i.header}" has duplicate option labels.`}],details:{type:"ask_user",error:"duplicate_option_labels"}}}}let r=await n.askUser(t.questions);if(r===null)return{content:[{type:"text",text:"User declined to answer questions."}],details:{type:"ask_user",declined:!0}};let s=["User answered:"];for(let i of t.questions){let a=r[i.question]??"(no answer)";s.push(`- ${i.header}: ${a}`)}return{content:[{type:"text",text:s.join(`
451
+ `)}],details:{type:"ask_user",answers:r,questionCount:t.questions.length}}}}}var mA="project_switch",fA={type:"object",properties:{projectName:{type:"string",description:"The name of the project to switch to. Use the exact project name from the available project list."}},required:["projectName"]};function Hf(n){return{name:mA,label:"Switch Project",description:["Switch the active project context. ONLY call this when the user EXPLICITLY asks to switch projects","(e.g. '\u5207\u6362\u5230XX\u9879\u76EE', 'switch to project X').","Do NOT call this if the user merely mentions a project name in conversation.","The projectName must be an EXACT match from the available project list.","If unsure which project the user means, ask them to clarify first."].join(`
452
+ `),parameters:fA,isReadOnly:!1,isConcurrencySafe:!1,shouldDefer:!0,searchHint:"switch project change workspace \u5207\u6362\u9879\u76EE",execute:async(e,t)=>{let o=n.listProjects();if(o.length===0)return{content:[{type:"text",text:"Error: No projects available."}]};let r=t.projectName.toLowerCase().trim(),s=o.find(a=>a.name.toLowerCase()===r);if(!s){let a=o.map(l=>`"${l.name}"`).join(", ");return{content:[{type:"text",text:`Error: No project with exact name "${t.projectName}". Available projects: ${a}. Please confirm the exact project name with the user before retrying.`}]}}let i=n.switchProject(s.id);return i?(n.onSwitched?.(i),{content:[{type:"text",text:`Switched to project "${i.name}" (workspace: ${i.workspaceDir}).`}]}):{content:[{type:"text",text:`Error: Failed to switch to project "${s.name}".`}]}}}}var ys=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 l of s.web_search.slice(0,a))i.push({title:l.title??"",url:l.link??"",snippet:(l.content??"").slice(0,500),content:l.content});return i}for(let l of s.choices??[])for(let c of l.message?.tool_calls??[])for(let d of c.search_result??[]){if(i.length>=a)break;i.push({title:d.title??"",url:d.link??"",snippet:(d.content??"").slice(0,500),content:d.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()}};Or();Mr();Qa();function Vf(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 gA=[{pattern:"Bash",behavior:"ask",reason:"Group security: shell commands require approval in group chat",source:"group-policy"},{pattern:"computer",behavior:"deny",reason:"Group security: computer control blocked in group chat",source:"group-policy"}],hA=[/\.env($|\.)/i,/\.(key|pem|p12|pfx|jks)$/i,/id_rsa/i,/id_ed25519/i,/\.ssh\//i,/secret/i,/credential/i,/token/i,/password/i,/\.aws\//i,/\.gnupg\//i];function Kf(){return[...gA]}function lc(n){return hA.some(e=>e.test(n))}var gc=!1;function hc(n){gc=n}var Se,Fe={},Xf,uc,un={},Jf;function yc(n){Jf=n}var kA=new Set(["zhipu","zhipu-openai","zhipu-coding"]),vA="https://open.bigmodel.cn/api/paas/v4";function Qf(n,e){if(!(!n||!e)&&kA.has(n))return new ys({baseUrl:vA,apiKey:e})}var Zf=null,SA;var pc;function eg(n){pc=n}function tg(n){Zf=n}function ng(n,e,t,o,r){Se=n,Fe=e??{},Xf=t,uc=r,un=o??{},TA()}function bc(n){let e=un[n];if(!(!e||!Se))return Se.resolveModelById(e.provider,e.model,n)}function TA(){wA(),xA(),RA(),_A()}function wA(){let n=nt(sc);if(!n)return;let e=un.video;if(!e||!Se)return;let t=Se.resolveModelById(e.provider,e.model,"video");if(!t)return;let o=t.modelInfo.mediaCapabilities;if(!o)return;let r=o.maxDurationSeconds??10,s=r>=10?4:3,i=o.resolutions?.join("/")||"720P",a=t.modelInfo.name||t.modelInfo.id;n.description=`Generate a short video clip from a text prompt, reference image, source video, or multimodal references. Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Current model: ${a}. Single-shot: ${s}\u2013${r}s. For longer videos (>${r}s), use multi-shot storyboard workflow. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. IMPORTANT: If the user has not specified aspect ratio or duration, use ask_user to clarify (e.g. aspect: 16:9 for landscape / 9:16 for vertical / 1:1 for square; duration: ${s}-${r}s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).`;let l=n.parameters?.properties,c=l?.duration;c&&(c.minimum=s,c.maximum=r,c.description=`Video duration in seconds (${s}\u2013${r}s for ${a}). For longer videos (>${r}s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation.`);let d=l?.resolution;d&&o.resolutions&&(d.description=`Output resolution: ${i}. Default: '720p'.`)}function xA(){let n=nt(rc);if(!n)return;let e=bc("image");if(!e)return;let t=e.modelInfo.mediaCapabilities,o=e.modelInfo.name||e.modelInfo.id,r=[];if(t?.sizes?.length&&r.push(`Sizes: ${t.sizes.join(", ")}`),t?.transparentBackground&&r.push("Supports transparent background"),n.description=`Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately. Current model: ${o}. ${r.join(". ")}${r.length?". ":""}IMPORTANT: If the user has not specified purpose or preferred style, use ask_user to clarify (e.g. purpose: social-media / wallpaper / poster; style: photorealistic / anime / watercolor). Infer image size automatically from purpose. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file.`,t?.sizes?.length){let i=n.parameters?.properties?.size;i&&(i.description=`Dimensions: ${t.sizes.join(", ")}. Default: '1024x1024'. Auto-infer from purpose.`)}}function RA(){let n=nt("tts");if(!n)return;let e=bc("tts");if(!e)return;let t=e.modelInfo.mediaCapabilities,o=e.modelInfo.name||e.modelInfo.id,r=[];if(t?.voices?.length&&r.push(`Voices: ${t.voices.join(", ")}`),t?.maxCharacters&&r.push(`Max: ${t.maxCharacters} characters per request`),t?.formats?.length&&r.push(`Formats: ${t.formats.join(", ")}`),n.description=`Convert text to speech (TTS) \u2014 read text aloud as spoken audio. Use for narration, voice messages, or any spoken-word output. DO NOT use for music, songs, or melodies \u2014 use music_generate instead. Current model: ${o}. ${r.join(". ")}${r.length?".":""}`,t?.voices?.length){let i=n.parameters?.properties?.voice;i&&(i.description=`Voice name. Available: ${t.voices.join(", ")}.`)}}function _A(){let n=nt(ic);if(!n)return;let e=bc("music");if(!e)return;let t=e.modelInfo.mediaCapabilities,o=e.modelInfo.name||e.modelInfo.id,r=[];if(t?.maxDurationSeconds&&r.push(`Max duration: ${t.maxDurationSeconds}s`),t?.formats?.length&&r.push(`Formats: ${t.formats.join(", ")}`),n.description=`Generate music, songs, or melodies from text descriptions. Prompt MUST be in English. Supports lyrics for vocal songs. DO NOT use for spoken-word audio or TTS \u2014 use tts tool instead. Current model: ${o}. ${r.join(". ")}${r.length?". ":""}IMPORTANT: If the user has not specified genre/style or duration, use ask_user to clarify (e.g. style: lo-fi / pop / rock / jazz; duration inferred from purpose).`,t?.maxDurationSeconds){let i=n.parameters?.properties?.duration;i&&(i.maximum=t.maxDurationSeconds,i.description=`Duration in seconds (5\u2013${t.maxDurationSeconds}s for ${o}). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s.`)}}async function Ot(n){if(!Se)throw new Error(`No media provider configured for ${n.mediaType}`);let e=un[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={...n};uc&&!r.onProgress&&(r.onProgress=(l,c,d)=>{uc(d??"pending",n.mediaType,l,c,t)});let s=await zf(t,o||n.model,r);if(s.ok)return s.result;let i=Se.listMediaModels(n.mediaType),a=[`${t}: ${s.error}`];for(let l of i){if(l.providerId===t||!Fe[l.providerId])continue;let d=await zf(l.providerId,l.modelInfo.id,n);if(d.ok)return d.result;a.push(`${l.providerId}/${l.modelInfo.id}: ${d.error}`)}throw new Error(`All media providers failed for ${n.mediaType}:
453
453
  `+a.map(l=>` - ${l}`).join(`
454
- `))}async function zf(n,e,t){let o=Se.getTransport(n);if(!o)return{ok:!1,error:"transport not available"};let r=Fe[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,l=i.billingUnit??"per_call",c=i.billingQuantity??1;return Xf?.(a,l,c),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Dt(n){if(!Se)return!1;let e=un[n];if(!e)return!1;let t=Se.getTransport(e.provider),o=Fe[e.provider];return!!(t&&o)}function cc(n,e){if(!Dt(n))return!1;let t=un[n],o=Se.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 bs(){if(!Se)return;for(let[,e]of Object.entries(un)){if(!e)continue;let t=Se.getTransport(e.provider),o=Fe[e.provider];if(t instanceof dt&&o)return{id:e.provider,type:"volcengine"}}if(Fe.google)return{id:"google",type:"gemini"}}var dc;function ks(){return dc||(dc=new Mo({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),dc}var rt=process.cwd(),mc=!1;function og(n){rt=n,mc=!0,ms(n)}function Be(n){return q.isAbsolute(n)?q.normalize(n):q.resolve(rt,n)}function Ko(n){let e=q.resolve(rt)+q.sep,t=q.resolve(n);return process.platform==="win32"?t.toLowerCase().startsWith(e.toLowerCase())||t.toLowerCase()===e.slice(0,-1).toLowerCase():t.startsWith(e)||t===e.slice(0,-1)}function Jt(n){return Ko(n)?null:`Blocked: path "${n}" is outside the workspace boundary "${rt}"`}function qf(n){let e=n.replace(/\\/g,"/");return e.includes("../")||e.includes("..")}var RA=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),rg=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),fc=new Set,_A={".pdf":"application/pdf",".txt":"text/plain",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/plain",".json":"application/json",".xml":"application/xml",".csv":"text/csv",".md":"text/markdown",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".mp4":"video/mp4",".webm":"video/webm",".avi":"video/x-msvideo",".mov":"video/quicktime",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function AA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=q.extname(e).toLowerCase();if(mc){let r=Jt(e);if(r)throw new Error(r)}else if(qf(n)&&!Ko(e))throw new Error(`Blocked: path traversal "${n}" escapes workspace "${rt}"`);if(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/"))throw new Error(`Blocked: reading device/system path ${e}`);if(rg.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(RA.has(t))return{type:"image",localPath:e,mimeType:t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg"};let o=await K.promises.readFile(e,"utf8");return fc.add(e),{type:"text",text:o}},validatePath(n){let e=Be(n);if(mc){let t=Jt(e);if(t)return t}else if(qf(n)&&!Ko(e))return`Blocked: path traversal "${n}" escapes workspace "${rt}"`;return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:gc&&lc(e)?"Blocked: reading sensitive file in group chat mode":null}}}function PA(){return{resolvePath:Be,validatePath(n){let e=Be(n),t=Jt(e);return t||(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: writing to device/system path ${e}`:gc&&lc(e)?"Blocked: writing sensitive file in group chat mode":null)},checkReadBeforeWrite(n){try{K.accessSync(n,K.constants.F_OK)}catch{return null}return fc.has(n)?null:"File already exists but has not been read yet in this session. Read it first with the read tool before overwriting, to avoid unintended data loss. If you intend to completely replace the file, read it first to confirm."},async writeFile(n,e){let t=Be(n),o=Jt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8"),fc.add(t)}}}function IA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=Jt(e);if(t)throw new Error(t);return K.promises.readFile(e,"utf8")},async writeFile(n,e){let t=Be(n),o=Jt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8")}}}function CA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=Jt(e);if(t)throw new Error(t);return K.promises.readFile(e,"utf8")},async writeFile(n,e){let t=Be(n),o=Jt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8")},async deleteFile(n){let e=Be(n),t=Jt(e);if(t)throw new Error(t);await K.promises.unlink(e)},async fileExists(n){let e=Be(n);try{return await K.promises.access(e),!0}catch{return!1}}}}function EA(){return{resolvePath:Be,async glob(n,e){let t=e.cwd||rt,o=e.limit||1e3,r=[],s=!1,i=n.replace(/\\/g,"/").split("/"),a=i.some(d=>d==="**"),l=i[i.length-1]??"*",c=sg(l);try{await kc(t,async d=>{if(r.length>=o)return s=!0,!1;let u=q.basename(d);return c.test(u)&&r.push(d),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(n,e){let t=e.cwd||rt;try{return await OA(n,t,e)}catch{return await DA(n,t,e)}}}}function sg(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 MA=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function kc(n,e,t,o=0,r=""){if(o>t)return;let s;try{s=await K.promises.readdir(n,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(MA.has(i.name))continue;await kc(q.join(n,i.name),e,t,o+1,a)}else if(i.isFile()&&!await e(a))return}}function OA(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("."),hA("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 p of a.split(`
455
- `))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&l.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let c=t.headLimit??250,d=t.offset??0,u=l.slice(d,d+c);o({matches:u,truncated:l.length>d+c})})})}async function DA(n,e,t){let o=new RegExp(n,t.caseInsensitive?"i":""),r=t.headLimit??250,s=t.offset??0,i=t.fileGlob?sg(t.fileGlob):null,a=[],l=!1;return await kc(e,async c=>{if(a.length>=s+r+1)return l=!0,!1;if(i&&!i.test(q.basename(c)))return!0;let d=q.extname(c).toLowerCase();if(rg.has(d))return!0;try{let p=(await K.promises.readFile(q.join(e,c),"utf8")).split(`
456
- `);for(let m=0;m<p.length;m++)if(o.test(p[m])&&(a.push({path:c,line:m+1,text:p[m].slice(0,500)}),a.length>=s+r+1))return l=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+r),truncated:l}}var Yf=!1;function LA(){if(!Yf)if(Yf=!0,xn()){let n=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";Go(ql(n))}else if(process.platform==="win32"){let n=NA();Go(hs(n))}else{let n=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";Go(hs(n))}}function NA(){let n=process.env.QLOGICAGENT_BASH_PATH;if(n&&K.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?q.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let o of e)if(K.existsSync(o))return o;return"bash"}function $A(){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=UA(s)),{content:s,title:jA(s)}}finally{clearTimeout(t)}}}}function UA(n){return n.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s{2,}/g," ").trim()}function jA(n){return n.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function FA(){let n=async(e,t)=>{let{getModelRegistry:o}=await Promise.resolve().then(()=>(mt(),up)),r=o().getTunable("searxngBaseUrl")??process.env.SEARXNG_BASE_URL?.trim();if(!r)return{query:e,results:[],totalResults:0};let s=t?.maxResults??10,i=new URL("/search",r);i.searchParams.set("q",e),i.searchParams.set("format","json"),i.searchParams.set("pageno","1");let a=new AbortController,l=setTimeout(()=>a.abort(),15e3);try{let c=await fetch(i.toString(),{signal:a.signal,headers:{Accept:"application/json"}});if(!c.ok)return{query:e,results:[]};let d=await c.json(),u=(d.results??[]).slice(0,s).map(p=>({title:p.title??"",url:p.url??"",snippet:p.content??""}));if(t?.allowedDomains?.length){let p=new Set(t.allowedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return p.has(new URL(m.url).hostname.toLowerCase())}catch{return!1}})}}if(t?.blockedDomains?.length){let p=new Set(t.blockedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return!p.has(new URL(m.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:u,totalResults:d.number_of_results}}finally{clearTimeout(l)}};return{search:(e,t)=>Vf(Jf,n)(e,t)}}function BA(){let n=q.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(r){return q.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=q.resolve(i,s);if(!a.startsWith(i+q.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function o(r,s){if(!K.existsSync(r))return[];let i=[];for(let a of K.readdirSync(r,{withFileTypes:!0})){let l=q.join(r,a.name);if(a.isDirectory())i.push(...o(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let c=K.statSync(l);i.push({filename:q.relative(s,l).replace(/\\/g,"/"),path:l,size:c.size,updatedAt:c.mtime.toISOString(),content:K.readFileSync(l,"utf-8")})}}return i}return{list(r){let s=e(r);return o(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(r,s){try{let i=t(r,s);if(!K.existsSync(i))return null;let a=K.statSync(i),l=K.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:l}}catch{return null}},write(r,s,i){let a=t(r,s);K.mkdirSync(q.dirname(a),{recursive:!0}),K.writeFileSync(a,i,"utf-8");let l=K.statSync(a);return{filename:s,path:a,size:l.size,updatedAt:l.mtime.toISOString(),content:i}},remove(r,s){try{let i=t(r,s);return K.existsSync(i)?(K.unlinkSync(i),!0):!1}catch{return!1}}}}function ig(n){n?.workdir&&(rt=n.workdir),LA(),ms(rt);let e=[];e.push(Sm()),e.push(Tm(void 0,{onTaskCreated:u=>pc?.onTaskCreated?.(u),onTaskCompleted:u=>pc?.onTaskCompleted?.(u)})),e.push(Gf({askUser:async u=>Zf?.(u)??null})),e.push(Lm({onProgress:n?.onExecProgress,validateCommand:async u=>{let p=/(?:>>?|[12]>)\s*(?:"([^"]+)"|'([^']+)'|(\S+))/g,m;for(;(m=p.exec(u))!==null;){let f=m[1]||m[2]||m[3];if(f){let y=q.isAbsolute(f)?q.normalize(f):q.resolve(rt,f);if(!Ko(y))return`Blocked: output redirection to path outside workspace: ${f}`}}let h=[/(?:^|[\s;|&(])(?:"(\/[^"]+)"|'(\/[^']+)'|(\/(?!dev\/null\b)[^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([A-Za-z]:[\\\/][^"]+)"|'([A-Za-z]:[\\\/][^']+)'|([A-Za-z]:[\\\/][^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([^"]*\.\.[\\/][^"]+)"|'([^']*\.\.[\\/][^']+)'|([^\s;|&><)"']*\.\.[\\/][^\s;|&><)]+))/g];for(let f of h){let y;for(;(y=f.exec(u))!==null;){let b=y[1]||y[2]||y[3];if(!b||/^\/[a-zA-Z](?:[- ]|$)/.test(b)||/^\/[a-zA-Z]{1,3}$/.test(b))continue;let k;if(process.platform==="win32"&&/^\/[a-zA-Z]\//.test(b)){let x=b.replace(/^\/([a-zA-Z])\//,(I,P)=>`${P.toUpperCase()}:\\`).replace(/\//g,"\\");k=q.normalize(x)}else k=q.isAbsolute(b)?q.normalize(b):q.resolve(rt,b);if(!Ko(k))return`Blocked: command references path outside workspace: ${b}`}}return null},interpretExitCode:(u,p)=>{if(u===127)return"command not found";if(u===126)return"permission denied";if(u===137)return"killed (SIGKILL / OOM)";if(u===143)return"terminated (SIGTERM)";if(u===130)return"interrupted (Ctrl+C)"}}));let t=AA(),o=PA(),r=IA(),s=CA();e.push(Um(t)),e.push(Fm(o)),e.push(Bm(r)),e.push(Zl(s)),e.push(Vm(s)),e.push(Hm(EA())),e.push(ef($A())),e.push(tf(FA()));let i=BA();e.push(nf(i));let a=n?.log??{info:()=>{},warn:()=>{}};e.push(of(bf({log:a}))),e.push(Tf());let l={invokeTool:async(u,p,m)=>{let h=nt(u);if(!h)return{result:"",error:`Unknown tool: ${u}`};try{let f=await h.execute(`wf_${Date.now()}`,p,m);return{result:f.content.map(b=>b.text??"").join(`
457
- `),error:f.details?.error}}catch(f){return{result:"",error:f.message}}},getCwd:()=>rt};e.push(Rf(l)),e.push(_f({sleep:(u,p)=>new Promise(m=>{let h=Date.now(),f=setTimeout(()=>{m({sleptSeconds:Math.round((Date.now()-h)/1e3),interrupted:!1})},u),y=()=>{clearTimeout(f),m({sleptSeconds:Math.round((Date.now()-h)/1e3),interrupted:!0,interruptReason:"aborted"})};p.addEventListener("abort",y,{once:!0}),p.aborted&&(clearTimeout(f),y())})}));let c={listProjects:()=>fe(),switchProject:u=>ft(u),onSwitched:u=>kA?.(u)};e.push(Hf(c)),e.push(Pf({searchTools:async(u,p)=>{let m=p?.maxResults??5,h=cn(),f=u.toLowerCase().split(/\s+/).filter(Boolean),y=[],b=[];for(let O of f)O.startsWith("+")&&O.length>1?y.push(O.slice(1)):b.push(O);let k=[...y,...b],x=O=>O.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:h.map(O=>{let $=nt(O),W=x(O),S=($?.description??"").toLowerCase(),ce=($?.searchHint??"").toLowerCase();if(y.length>0){let j=`${W.join(" ")} ${S} ${ce}`;if(!y.every(ie=>j.includes(ie)))return null}let de=0;for(let j of k){let ve=0;W.some(ie=>ie===j)?ve=10:W.some(ie=>ie.includes(j))?ve=5:O.toLowerCase().includes(j)&&(ve=3),ce&&new RegExp(`\\b${j}`,"i").test(ce)&&(ve+=4),new RegExp(`\\b${j}`,"i").test(S)&&(ve+=2),de+=ve}return{name:O,description:$?.description??"",searchHint:$?.searchHint,score:de}}).filter(O=>O!==null&&O.score>0).sort((O,$)=>$.score-O.score).slice(0,m),query:u,totalDeferred:h.length}},activateTool:async u=>vm(u)})),e.push({...If({generateImage:async u=>{let p=await Ot({mediaType:"image",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,size:u.size,imageUrl:u.imageUrl,n:u.n,quality:u.quality,seed:u.seed});return{mediaUrls:p.mediaUrls,model:p.model,size:p.size,durationMs:p.durationMs}}}),isEnabled:()=>Dt("image")}),e.push({...Cf({textToSpeech:async u=>{let p=await Ot({mediaType:"tts",model:"",prompt:"",text:u.text,channel:u.channel,voice:u.voice,speed:u.speed});return{audioPath:"",provider:p.model,mediaUrls:p.mediaUrls}}}),isEnabled:()=>Dt("tts")}),e.push({...Ef({generateVideo:async u=>{let p=await Ot({mediaType:"video",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,imageUrl:u.imageUrl,referenceVideos:u.referenceVideos,referenceAudios:u.referenceAudios,generateAudio:u.generateAudio,aspectRatio:u.aspectRatio,duration:u.duration,resolution:u.resolution,fps:u.fps,seed:u.seed,cameraFixed:u.cameraFixed,returnLastFrame:u.returnLastFrame,draft:u.draft,serviceTier:u.serviceTier,callbackUrl:u.callbackUrl,safetyIdentifier:u.safetyIdentifier,executionExpiresAfterSeconds:u.executionExpiresAfterSeconds,videoTools:u.videoTools});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs,lastFrameUrl:p.lastFrameUrl,taskId:p.taskId}}}),isEnabled:()=>Dt("video")}),e.push({...Mf({generateMusic:async u=>{let p=await Ot({mediaType:"music",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,lyrics:u.lyrics,duration:u.duration,isInstrumental:u.isInstrumental,audioUrl:u.audioUrl,audioFormat:u.audioFormat});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs}},generateLyrics:async u=>{let p=un.music;if(!p||!Se)return"";let m=Se.getTransport(p.provider);if(!(m instanceof kn))return"";let h=Fe[p.provider];return h?m.generateLyrics(u,h):""}}),isEnabled:()=>Dt("music")}),e.push({...Of({editVideo:async u=>{let p=await Ot({mediaType:"video",model:"",prompt:u.prompt,operation:"edit",sourceVideos:u.sourceVideos,referenceImages:u.referenceImages,duration:u.duration,aspectRatio:u.aspectRatio,resolution:u.resolution});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>cc("video","edit")}),e.push({...Df({mergeVideos:async u=>{let p=[`merge ${u.clips.length} clips`];u.transition&&p.push(`transition: ${u.transition}${u.transitionDuration?` (${u.transitionDuration}s)`:""}`),u.subtitles&&p.push(`burn-in subtitles: ${u.subtitles}`),u.bgm&&p.push(`background music: ${u.bgm}${u.bgmVolume!==void 0?` at volume ${u.bgmVolume}`:""}`);let m=await Ot({mediaType:"video",model:"",prompt:p.join("; "),operation:"merge",sourceVideos:u.clips.map(h=>h.video),resolution:u.outputResolution,fps:u.outputFps});return{localPath:"",servePath:m.mediaUrls[0]??"",durationSec:(m.durationMs??0)/1e3,clipCount:u.clips.length,mediaUrls:m.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>cc("video","merge")}),e.push({...Lf({upscaleVideo:async u=>{let p=["upscale"];u.sharpness&&p.push(`sharpness: ${u.sharpness}`);let m=await Ot({mediaType:"video",model:"",prompt:p.join(", "),operation:"upscale",sourceVideos:[u.video],resolution:u.targetResolution??"1080p"});return{localPath:"",servePath:m.mediaUrls[0]??"",resolution:u.targetResolution??"1080p",durationSec:(m.durationMs??0)/1e3,mediaUrls:m.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>cc("video","upscale")}),e.push({...Nf({generate3D:async u=>{let p=await Ot({mediaType:"3d",model:"",prompt:u.prompt,imageUrl:u.imageUrl,outputFormat:u.outputFormat,seed:u.seed});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs,metadata:p.metadata}}}),shouldDefer:!0,isEnabled:()=>Dt("3d")}),e.push({...$f({speechToText:async u=>{let p=await Ot({mediaType:"stt",model:"",prompt:"",audioUrl:u.audioUrl,metadata:u.language?{language:u.language}:void 0});return{transcription:p.metadata?.transcription??"",model:p.model,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>Dt("stt")}),e.push({...Uf({cloneVoice:async u=>{let p=await Ot({mediaType:"voice_clone",model:"",prompt:"",text:u.text,audioUrl:u.sampleAudioUrl,speed:u.speed});return{mediaUrls:p.mediaUrls,model:p.model,voiceId:p.metadata?.voiceId,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>Dt("voice_clone")}),e.push({...jf({cancelTask:async u=>{let p=u.provider??"doubao";if(!Se)return{ok:!1,message:"Media client not configured."};let m=Se.getTransport(p);if(!m)return{ok:!1,message:`No transport for provider: ${p}`};let h=Fe[p];if(!h)return{ok:!1,message:`No API key for provider: ${p}`};try{return"deleteVideoTask"in m&&typeof m.deleteVideoTask=="function"?(await m.deleteVideoTask(u.taskId,h),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${p} does not support task cancellation.`}}catch(f){return{ok:!1,message:f instanceof Error?f.message:String(f)}}}}),shouldDefer:!0,isEnabled:()=>Dt("video")||Dt("3d")});let d=bs();return e.push({...Ff({uploadFile:async u=>{if(!d)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");let p=Be(u.filePath);if(!K.existsSync(p))throw new Error(`File not found: ${p}`);let m=K.statSync(p);if(m.size>100*1024*1024)throw new Error(`File too large (${(m.size/1024/1024).toFixed(1)} MB). Max: 100 MB.`);let h=await K.promises.readFile(p),f=q.basename(p);if(d.type==="gemini"){let P=ks(),O=Fe.google,$=q.extname(p).toLowerCase(),W=_A[$]??"application/octet-stream",S=await P.uploadFile(Buffer.from(h),O,{mimeType:W,displayName:f});if(S.state==="PROCESSING"){let ce=await P.waitForProcessing(S.name,O);return{fileId:ce.name,url:ce.uri,filename:f,bytes:m.size,provider:"google"}}return{fileId:S.name,url:S.uri,filename:f,bytes:m.size,provider:"google"}}let y=new Blob([h]),b=Se.getTransport(d.id),k=Fe[d.id];if(!(b instanceof dt))throw new Error(`File upload only supported via Volcengine or Google provider. Current: ${d.id}`);let x=await b.uploadFile(y,k,{purpose:u.purpose??"media_reference",filename:f}),I;try{let P=await b.getFile(x.id,k);typeof P.url=="string"&&P.url&&(I=P.url)}catch{}return{fileId:x.id,url:I,filename:f,bytes:m.size,provider:d.id}}}),shouldDefer:!0,isEnabled:()=>!!bs()}),e.push({...Bf({queryFile:async u=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let f=ks(),y=Fe.google,b=await f.getFile(u.fileId,y);return{id:b.name,filename:b.displayName??"",bytes:Number(b.sizeBytes??0),status:b.state?.toLowerCase()??"unknown",createdAt:b.createTime,url:b.uri}}let p=Se.getTransport(d.id),m=Fe[d.id];if(!(p instanceof dt))throw new Error("File query only supported via Volcengine or Google provider.");let h=await p.getFile(u.fileId,m);return{id:String(h.id??u.fileId),filename:String(h.filename??""),bytes:Number(h.bytes??0),status:String(h.status??"unknown"),createdAt:h.created_at?String(h.created_at):void 0,url:h.url?String(h.url):void 0}},listFiles:async u=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let y=ks(),b=Fe.google;return(await y.listFiles(b,{pageSize:u.limit??10})).files.map(x=>({id:x.name,filename:x.displayName??"",bytes:Number(x.sizeBytes??0),status:x.state?.toLowerCase()??"unknown",createdAt:x.createTime,url:x.uri}))}let p=Se.getTransport(d.id),m=Fe[d.id];if(!(p instanceof dt))throw new Error("File list only supported via Volcengine or Google provider.");return((await p.listFiles(m,{limit:u.limit??10})).data??[]).map(y=>({id:String(y.id??""),filename:String(y.filename??""),bytes:Number(y.bytes??0),status:String(y.status??"unknown"),createdAt:y.created_at?String(y.created_at):void 0,url:y.url?String(y.url):void 0}))}}),shouldDefer:!0,isEnabled:()=>!!bs()}),e.push({...Wf({deleteFile:async u=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let h=ks(),f=Fe.google;await h.deleteFile(u.fileId,f);return}let p=Se.getTransport(d.id),m=Fe[d.id];if(!(p instanceof dt))throw new Error("File delete only supported via Volcengine or Google provider.");await p.deleteFile(u.fileId,m)}}),shouldDefer:!0,isEnabled:()=>!!bs()}),km(e),n?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(u=>u.isEnabled?.()!==!1).length} enabled): ${cn().join(", ")}`),e}import{spawn as WA}from"node:child_process";import{createInterface as GA}from"node:readline";var vs=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=WA(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=GA({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=HA(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(`
454
+ `))}async function zf(n,e,t){let o=Se.getTransport(n);if(!o)return{ok:!1,error:"transport not available"};let r=Fe[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,l=i.billingUnit??"per_call",c=i.billingQuantity??1;return Xf?.(a,l,c),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Dt(n){if(!Se)return!1;let e=un[n];if(!e)return!1;let t=Se.getTransport(e.provider),o=Fe[e.provider];return!!(t&&o)}function cc(n,e){if(!Dt(n))return!1;let t=un[n],o=Se.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 bs(){if(!Se)return;for(let[,e]of Object.entries(un)){if(!e)continue;let t=Se.getTransport(e.provider),o=Fe[e.provider];if(t instanceof dt&&o)return{id:e.provider,type:"volcengine"}}if(Fe.google)return{id:"google",type:"gemini"}}var dc;function ks(){return dc||(dc=new Mo({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),dc}var rt=process.cwd(),mc=!1;function og(n){rt=n,mc=!0,ms(n)}function Be(n){return q.isAbsolute(n)?q.normalize(n):q.resolve(rt,n)}function Ko(n){let e=q.resolve(rt)+q.sep,t=q.resolve(n);return process.platform==="win32"?t.toLowerCase().startsWith(e.toLowerCase())||t.toLowerCase()===e.slice(0,-1).toLowerCase():t.startsWith(e)||t===e.slice(0,-1)}function Jt(n){return Ko(n)?null:`Blocked: path "${n}" is outside the workspace boundary "${rt}"`}function qf(n){let e=n.replace(/\\/g,"/");return e.includes("../")||e.includes("..")}var AA=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),rg=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),fc=new Set,PA={".pdf":"application/pdf",".txt":"text/plain",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/plain",".json":"application/json",".xml":"application/xml",".csv":"text/csv",".md":"text/markdown",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".mp4":"video/mp4",".webm":"video/webm",".avi":"video/x-msvideo",".mov":"video/quicktime",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function IA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=q.extname(e).toLowerCase();if(mc){let r=Jt(e);if(r)throw new Error(r)}else if(qf(n)&&!Ko(e))throw new Error(`Blocked: path traversal "${n}" escapes workspace "${rt}"`);if(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/"))throw new Error(`Blocked: reading device/system path ${e}`);if(rg.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(AA.has(t))return{type:"image",localPath:e,mimeType:t===".png"?"image/png":t===".svg"?"image/svg+xml":t===".gif"?"image/gif":t===".webp"?"image/webp":"image/jpeg"};let o=await K.promises.readFile(e,"utf8");return fc.add(e),{type:"text",text:o}},validatePath(n){let e=Be(n);if(mc){let t=Jt(e);if(t)return t}else if(qf(n)&&!Ko(e))return`Blocked: path traversal "${n}" escapes workspace "${rt}"`;return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:gc&&lc(e)?"Blocked: reading sensitive file in group chat mode":null}}}function CA(){return{resolvePath:Be,validatePath(n){let e=Be(n),t=Jt(e);return t||(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: writing to device/system path ${e}`:gc&&lc(e)?"Blocked: writing sensitive file in group chat mode":null)},checkReadBeforeWrite(n){try{K.accessSync(n,K.constants.F_OK)}catch{return null}return fc.has(n)?null:"File already exists but has not been read yet in this session. Read it first with the read tool before overwriting, to avoid unintended data loss. If you intend to completely replace the file, read it first to confirm."},async writeFile(n,e){let t=Be(n),o=Jt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8"),fc.add(t)}}}function EA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=Jt(e);if(t)throw new Error(t);return K.promises.readFile(e,"utf8")},async writeFile(n,e){let t=Be(n),o=Jt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8")}}}function MA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=Jt(e);if(t)throw new Error(t);return K.promises.readFile(e,"utf8")},async writeFile(n,e){let t=Be(n),o=Jt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8")},async deleteFile(n){let e=Be(n),t=Jt(e);if(t)throw new Error(t);await K.promises.unlink(e)},async fileExists(n){let e=Be(n);try{return await K.promises.access(e),!0}catch{return!1}}}}function OA(){return{resolvePath:Be,async glob(n,e){let t=e.cwd||rt,o=e.limit||1e3,r=[],s=!1,i=n.replace(/\\/g,"/").split("/"),a=i.some(d=>d==="**"),l=i[i.length-1]??"*",c=sg(l);try{await kc(t,async d=>{if(r.length>=o)return s=!0,!1;let u=q.basename(d);return c.test(u)&&r.push(d),!0},a?1/0:1)}catch{}return{files:r,truncated:s}},async grep(n,e){let t=e.cwd||rt;try{return await LA(n,t,e)}catch{return await NA(n,t,e)}}}}function sg(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 DA=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function kc(n,e,t,o=0,r=""){if(o>t)return;let s;try{s=await K.promises.readdir(n,{withFileTypes:!0})}catch{return}for(let i of s){let a=r?`${r}/${i.name}`:i.name;if(i.isDirectory()){if(DA.has(i.name))continue;await kc(q.join(n,i.name),e,t,o+1,a)}else if(i.isFile()&&!await e(a))return}}function LA(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("."),bA("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 p of a.split(`
455
+ `))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&l.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let c=t.headLimit??250,d=t.offset??0,u=l.slice(d,d+c);o({matches:u,truncated:l.length>d+c})})})}async function NA(n,e,t){let o=new RegExp(n,t.caseInsensitive?"i":""),r=t.headLimit??250,s=t.offset??0,i=t.fileGlob?sg(t.fileGlob):null,a=[],l=!1;return await kc(e,async c=>{if(a.length>=s+r+1)return l=!0,!1;if(i&&!i.test(q.basename(c)))return!0;let d=q.extname(c).toLowerCase();if(rg.has(d))return!0;try{let p=(await K.promises.readFile(q.join(e,c),"utf8")).split(`
456
+ `);for(let m=0;m<p.length;m++)if(o.test(p[m])&&(a.push({path:c,line:m+1,text:p[m].slice(0,500)}),a.length>=s+r+1))return l=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+r),truncated:l}}var Yf=!1;function $A(){if(!Yf)if(Yf=!0,xn()){let n=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";Go(ql(n))}else if(process.platform==="win32"){let n=UA();Go(hs(n))}else{let n=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";Go(hs(n))}}function UA(){let n=process.env.QLOGICAGENT_BASH_PATH;if(n&&K.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?q.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;t&&!e.includes(t)&&e.unshift(t);for(let o of e)if(K.existsSync(o))return o;return"bash"}function jA(){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=FA(s)),{content:s,title:BA(s)}}finally{clearTimeout(t)}}}}function FA(n){return n.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s{2,}/g," ").trim()}function BA(n){return n.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function WA(){let n=async(e,t)=>{let{getModelRegistry:o}=await Promise.resolve().then(()=>(mt(),up)),r=o().getTunable("searxngBaseUrl")??process.env.SEARXNG_BASE_URL?.trim();if(!r)return{query:e,results:[],totalResults:0};let s=t?.maxResults??10,i=new URL("/search",r);i.searchParams.set("q",e),i.searchParams.set("format","json"),i.searchParams.set("pageno","1");let a=new AbortController,l=setTimeout(()=>a.abort(),15e3);try{let c=await fetch(i.toString(),{signal:a.signal,headers:{Accept:"application/json"}});if(!c.ok)return{query:e,results:[]};let d=await c.json(),u=(d.results??[]).slice(0,s).map(p=>({title:p.title??"",url:p.url??"",snippet:p.content??""}));if(t?.allowedDomains?.length){let p=new Set(t.allowedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return p.has(new URL(m.url).hostname.toLowerCase())}catch{return!1}})}}if(t?.blockedDomains?.length){let p=new Set(t.blockedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return!p.has(new URL(m.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:u,totalResults:d.number_of_results}}finally{clearTimeout(l)}};return{search:(e,t)=>Vf(Jf,n)(e,t)}}function GA(){let n=q.join(process.env.HOME??process.env.USERPROFILE??".",".qlogicagent");function e(r){return q.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=q.resolve(i,s);if(!a.startsWith(i+q.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function o(r,s){if(!K.existsSync(r))return[];let i=[];for(let a of K.readdirSync(r,{withFileTypes:!0})){let l=q.join(r,a.name);if(a.isDirectory())i.push(...o(l,s));else if(a.isFile()&&a.name.endsWith(".md")){let c=K.statSync(l);i.push({filename:q.relative(s,l).replace(/\\/g,"/"),path:l,size:c.size,updatedAt:c.mtime.toISOString(),content:K.readFileSync(l,"utf-8")})}}return i}return{list(r){let s=e(r);return o(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(r,s){try{let i=t(r,s);if(!K.existsSync(i))return null;let a=K.statSync(i),l=K.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:l}}catch{return null}},write(r,s,i){let a=t(r,s);K.mkdirSync(q.dirname(a),{recursive:!0}),K.writeFileSync(a,i,"utf-8");let l=K.statSync(a);return{filename:s,path:a,size:l.size,updatedAt:l.mtime.toISOString(),content:i}},remove(r,s){try{let i=t(r,s);return K.existsSync(i)?(K.unlinkSync(i),!0):!1}catch{return!1}}}}function ig(n){n?.workdir&&(rt=n.workdir),$A(),ms(rt);let e=[];e.push(Sm()),e.push(Tm(void 0,{onTaskCreated:u=>pc?.onTaskCreated?.(u),onTaskCompleted:u=>pc?.onTaskCompleted?.(u)})),e.push(Gf({askUser:async u=>Zf?.(u)??null})),e.push(Lm({onProgress:n?.onExecProgress,validateCommand:async u=>{let p=/(?:>>?|[12]>)\s*(?:"([^"]+)"|'([^']+)'|(\S+))/g,m;for(;(m=p.exec(u))!==null;){let f=m[1]||m[2]||m[3];if(f){let y=q.isAbsolute(f)?q.normalize(f):q.resolve(rt,f);if(!Ko(y))return`Blocked: output redirection to path outside workspace: ${f}`}}let h=[/(?:^|[\s;|&(])(?:"(\/[^"]+)"|'(\/[^']+)'|(\/(?!dev\/null\b)[^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([A-Za-z]:[\\\/][^"]+)"|'([A-Za-z]:[\\\/][^']+)'|([A-Za-z]:[\\\/][^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([^"]*\.\.[\\/][^"]+)"|'([^']*\.\.[\\/][^']+)'|([^\s;|&><)"']*\.\.[\\/][^\s;|&><)]+))/g];for(let f of h){let y;for(;(y=f.exec(u))!==null;){let b=y[1]||y[2]||y[3];if(!b||/^\/[a-zA-Z](?:[- ]|$)/.test(b)||/^\/[a-zA-Z]{1,3}$/.test(b))continue;let k;if(process.platform==="win32"&&/^\/[a-zA-Z]\//.test(b)){let x=b.replace(/^\/([a-zA-Z])\//,(I,P)=>`${P.toUpperCase()}:\\`).replace(/\//g,"\\");k=q.normalize(x)}else k=q.isAbsolute(b)?q.normalize(b):q.resolve(rt,b);if(!Ko(k))return`Blocked: command references path outside workspace: ${b}`}}return null},interpretExitCode:(u,p)=>{if(u===127)return"command not found";if(u===126)return"permission denied";if(u===137)return"killed (SIGKILL / OOM)";if(u===143)return"terminated (SIGTERM)";if(u===130)return"interrupted (Ctrl+C)"}}));let t=IA(),o=CA(),r=EA(),s=MA();e.push(Um(t)),e.push(Fm(o)),e.push(Bm(r)),e.push(Zl(s)),e.push(Vm(s)),e.push(Hm(OA())),e.push(ef(jA())),e.push(tf(WA()));let i=GA();e.push(nf(i));let a=n?.log??{info:()=>{},warn:()=>{}};e.push(of(bf({log:a}))),e.push(Tf());let l={invokeTool:async(u,p,m)=>{let h=nt(u);if(!h)return{result:"",error:`Unknown tool: ${u}`};try{let f=await h.execute(`wf_${Date.now()}`,p,m);return{result:f.content.map(b=>b.text??"").join(`
457
+ `),error:f.details?.error}}catch(f){return{result:"",error:f.message}}},getCwd:()=>rt};e.push(Rf(l)),e.push(_f({sleep:(u,p)=>new Promise(m=>{let h=Date.now(),f=setTimeout(()=>{m({sleptSeconds:Math.round((Date.now()-h)/1e3),interrupted:!1})},u),y=()=>{clearTimeout(f),m({sleptSeconds:Math.round((Date.now()-h)/1e3),interrupted:!0,interruptReason:"aborted"})};p.addEventListener("abort",y,{once:!0}),p.aborted&&(clearTimeout(f),y())})}));let c={listProjects:()=>fe(),switchProject:u=>ft(u),onSwitched:u=>SA?.(u)};e.push(Hf(c)),e.push(Pf({searchTools:async(u,p)=>{let m=p?.maxResults??5,h=cn(),f=u.toLowerCase().split(/\s+/).filter(Boolean),y=[],b=[];for(let O of f)O.startsWith("+")&&O.length>1?y.push(O.slice(1)):b.push(O);let k=[...y,...b],x=O=>O.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:h.map(O=>{let $=nt(O),W=x(O),S=($?.description??"").toLowerCase(),ce=($?.searchHint??"").toLowerCase();if(y.length>0){let j=`${W.join(" ")} ${S} ${ce}`;if(!y.every(ie=>j.includes(ie)))return null}let de=0;for(let j of k){let ve=0;W.some(ie=>ie===j)?ve=10:W.some(ie=>ie.includes(j))?ve=5:O.toLowerCase().includes(j)&&(ve=3),ce&&new RegExp(`\\b${j}`,"i").test(ce)&&(ve+=4),new RegExp(`\\b${j}`,"i").test(S)&&(ve+=2),de+=ve}return{name:O,description:$?.description??"",searchHint:$?.searchHint,score:de}}).filter(O=>O!==null&&O.score>0).sort((O,$)=>$.score-O.score).slice(0,m),query:u,totalDeferred:h.length}},activateTool:async u=>vm(u)})),e.push({...If({generateImage:async u=>{let p=await Ot({mediaType:"image",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,size:u.size,imageUrl:u.imageUrl,n:u.n,quality:u.quality,seed:u.seed});return{mediaUrls:p.mediaUrls,model:p.model,size:p.size,durationMs:p.durationMs}}}),isEnabled:()=>Dt("image")}),e.push({...Cf({textToSpeech:async u=>{let p=await Ot({mediaType:"tts",model:"",prompt:"",text:u.text,channel:u.channel,voice:u.voice,speed:u.speed});return{audioPath:"",provider:p.model,mediaUrls:p.mediaUrls}}}),isEnabled:()=>Dt("tts")}),e.push({...Ef({generateVideo:async u=>{let p=await Ot({mediaType:"video",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,imageUrl:u.imageUrl,referenceVideos:u.referenceVideos,referenceAudios:u.referenceAudios,generateAudio:u.generateAudio,aspectRatio:u.aspectRatio,duration:u.duration,resolution:u.resolution,fps:u.fps,seed:u.seed,cameraFixed:u.cameraFixed,returnLastFrame:u.returnLastFrame,draft:u.draft,serviceTier:u.serviceTier,callbackUrl:u.callbackUrl,safetyIdentifier:u.safetyIdentifier,executionExpiresAfterSeconds:u.executionExpiresAfterSeconds,videoTools:u.videoTools});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs,lastFrameUrl:p.lastFrameUrl,taskId:p.taskId}}}),isEnabled:()=>Dt("video")}),e.push({...Mf({generateMusic:async u=>{let p=await Ot({mediaType:"music",model:"",prompt:u.prompt,purpose:u.purpose,style:u.style,lyrics:u.lyrics,duration:u.duration,isInstrumental:u.isInstrumental,audioUrl:u.audioUrl,audioFormat:u.audioFormat});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs}},generateLyrics:async u=>{let p=un.music;if(!p||!Se)return"";let m=Se.getTransport(p.provider);if(!(m instanceof kn))return"";let h=Fe[p.provider];return h?m.generateLyrics(u,h):""}}),isEnabled:()=>Dt("music")}),e.push({...Of({editVideo:async u=>{let p=await Ot({mediaType:"video",model:"",prompt:u.prompt,operation:"edit",sourceVideos:u.sourceVideos,referenceImages:u.referenceImages,duration:u.duration,aspectRatio:u.aspectRatio,resolution:u.resolution});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>cc("video","edit")}),e.push({...Df({mergeVideos:async u=>{let p=[`merge ${u.clips.length} clips`];u.transition&&p.push(`transition: ${u.transition}${u.transitionDuration?` (${u.transitionDuration}s)`:""}`),u.subtitles&&p.push(`burn-in subtitles: ${u.subtitles}`),u.bgm&&p.push(`background music: ${u.bgm}${u.bgmVolume!==void 0?` at volume ${u.bgmVolume}`:""}`);let m=await Ot({mediaType:"video",model:"",prompt:p.join("; "),operation:"merge",sourceVideos:u.clips.map(h=>h.video),resolution:u.outputResolution,fps:u.outputFps});return{localPath:"",servePath:m.mediaUrls[0]??"",durationSec:(m.durationMs??0)/1e3,clipCount:u.clips.length,mediaUrls:m.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>cc("video","merge")}),e.push({...Lf({upscaleVideo:async u=>{let p=["upscale"];u.sharpness&&p.push(`sharpness: ${u.sharpness}`);let m=await Ot({mediaType:"video",model:"",prompt:p.join(", "),operation:"upscale",sourceVideos:[u.video],resolution:u.targetResolution??"1080p"});return{localPath:"",servePath:m.mediaUrls[0]??"",resolution:u.targetResolution??"1080p",durationSec:(m.durationMs??0)/1e3,mediaUrls:m.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>cc("video","upscale")}),e.push({...Nf({generate3D:async u=>{let p=await Ot({mediaType:"3d",model:"",prompt:u.prompt,imageUrl:u.imageUrl,outputFormat:u.outputFormat,seed:u.seed});return{mediaUrls:p.mediaUrls,model:p.model,durationMs:p.durationMs,metadata:p.metadata}}}),shouldDefer:!0,isEnabled:()=>Dt("3d")}),e.push({...$f({speechToText:async u=>{let p=await Ot({mediaType:"stt",model:"",prompt:"",audioUrl:u.audioUrl,metadata:u.language?{language:u.language}:void 0});return{transcription:p.metadata?.transcription??"",model:p.model,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>Dt("stt")}),e.push({...Uf({cloneVoice:async u=>{let p=await Ot({mediaType:"voice_clone",model:"",prompt:"",text:u.text,audioUrl:u.sampleAudioUrl,speed:u.speed});return{mediaUrls:p.mediaUrls,model:p.model,voiceId:p.metadata?.voiceId,durationMs:p.durationMs}}}),shouldDefer:!0,isEnabled:()=>Dt("voice_clone")}),e.push({...jf({cancelTask:async u=>{let p=u.provider??"doubao";if(!Se)return{ok:!1,message:"Media client not configured."};let m=Se.getTransport(p);if(!m)return{ok:!1,message:`No transport for provider: ${p}`};let h=Fe[p];if(!h)return{ok:!1,message:`No API key for provider: ${p}`};try{return"deleteVideoTask"in m&&typeof m.deleteVideoTask=="function"?(await m.deleteVideoTask(u.taskId,h),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${p} does not support task cancellation.`}}catch(f){return{ok:!1,message:f instanceof Error?f.message:String(f)}}}}),shouldDefer:!0,isEnabled:()=>Dt("video")||Dt("3d")});let d=bs();return e.push({...Ff({uploadFile:async u=>{if(!d)throw new Error("No file upload provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");let p=Be(u.filePath);if(!K.existsSync(p))throw new Error(`File not found: ${p}`);let m=K.statSync(p);if(m.size>100*1024*1024)throw new Error(`File too large (${(m.size/1024/1024).toFixed(1)} MB). Max: 100 MB.`);let h=await K.promises.readFile(p),f=q.basename(p);if(d.type==="gemini"){let P=ks(),O=Fe.google,$=q.extname(p).toLowerCase(),W=PA[$]??"application/octet-stream",S=await P.uploadFile(Buffer.from(h),O,{mimeType:W,displayName:f});if(S.state==="PROCESSING"){let ce=await P.waitForProcessing(S.name,O);return{fileId:ce.name,url:ce.uri,filename:f,bytes:m.size,provider:"google"}}return{fileId:S.name,url:S.uri,filename:f,bytes:m.size,provider:"google"}}let y=new Blob([h]),b=Se.getTransport(d.id),k=Fe[d.id];if(!(b instanceof dt))throw new Error(`File upload only supported via Volcengine or Google provider. Current: ${d.id}`);let x=await b.uploadFile(y,k,{purpose:u.purpose??"media_reference",filename:f}),I;try{let P=await b.getFile(x.id,k);typeof P.url=="string"&&P.url&&(I=P.url)}catch{}return{fileId:x.id,url:I,filename:f,bytes:m.size,provider:d.id}}}),shouldDefer:!0,isEnabled:()=>!!bs()}),e.push({...Bf({queryFile:async u=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let f=ks(),y=Fe.google,b=await f.getFile(u.fileId,y);return{id:b.name,filename:b.displayName??"",bytes:Number(b.sizeBytes??0),status:b.state?.toLowerCase()??"unknown",createdAt:b.createTime,url:b.uri}}let p=Se.getTransport(d.id),m=Fe[d.id];if(!(p instanceof dt))throw new Error("File query only supported via Volcengine or Google provider.");let h=await p.getFile(u.fileId,m);return{id:String(h.id??u.fileId),filename:String(h.filename??""),bytes:Number(h.bytes??0),status:String(h.status??"unknown"),createdAt:h.created_at?String(h.created_at):void 0,url:h.url?String(h.url):void 0}},listFiles:async u=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let y=ks(),b=Fe.google;return(await y.listFiles(b,{pageSize:u.limit??10})).files.map(x=>({id:x.name,filename:x.displayName??"",bytes:Number(x.sizeBytes??0),status:x.state?.toLowerCase()??"unknown",createdAt:x.createTime,url:x.uri}))}let p=Se.getTransport(d.id),m=Fe[d.id];if(!(p instanceof dt))throw new Error("File list only supported via Volcengine or Google provider.");return((await p.listFiles(m,{limit:u.limit??10})).data??[]).map(y=>({id:String(y.id??""),filename:String(y.filename??""),bytes:Number(y.bytes??0),status:String(y.status??"unknown"),createdAt:y.created_at?String(y.created_at):void 0,url:y.url?String(y.url):void 0}))}}),shouldDefer:!0,isEnabled:()=>!!bs()}),e.push({...Wf({deleteFile:async u=>{if(!d)throw new Error("No file API provider available.");if(d.type==="gemini"){let h=ks(),f=Fe.google;await h.deleteFile(u.fileId,f);return}let p=Se.getTransport(d.id),m=Fe[d.id];if(!(p instanceof dt))throw new Error("File delete only supported via Volcengine or Google provider.");await p.deleteFile(u.fileId,m)}}),shouldDefer:!0,isEnabled:()=>!!bs()}),km(e),n?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(u=>u.isEnabled?.()!==!1).length} enabled): ${cn().join(", ")}`),e}import{spawn as HA}from"node:child_process";import{createInterface as VA}from"node:readline";var vs=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=HA(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=VA({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=KA(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(`
458
458
  `)||"(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++,l={jsonrpc:"2.0",id:a,method:e,params:t},c=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${o}ms`))},o),d=()=>{clearTimeout(c),this.pending.delete(a)};r?.addEventListener("abort",()=>{d(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:u=>{d(),u.error?i(new Error(`MCP error ${u.error.code}: ${u.error.message}`)):s(u.result)},reject:u=>{d(),i(u)}}),this.writeLine(JSON.stringify(l))})}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+`
459
- `)}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 HA(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as VA}from"node:crypto";var Ss=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=VA(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,l=setTimeout(()=>a.abort(),o);r&&r.addEventListener("abort",()=>a.abort(),{once:!0});try{let c={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(c["Mcp-Session-Id"]=this.sessionId);let d=await fetch(this.config.url,{method:"POST",headers:c,body:JSON.stringify(i),signal:a.signal}),u=d.headers.get("mcp-session-id");if(u&&(this.sessionId=u),!d.ok)throw new Error(`MCP HTTP error ${d.status}: ${d.statusText}`);if((d.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(d,s);let m=await d.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(l)}}async sendNotification(e,t){let 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:l}=await r.read();if(a)break;i+=s.decode(l,{stream:!0});let c=i.split(`
460
- `);i=c.pop()??"";for(let d of c){if(!d.startsWith("data: "))continue;let u=d.slice(6).trim();if(u)try{let p=JSON.parse(u);if("method"in p&&p.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(p.id===t){if(p.error)throw new Error(`MCP error ${p.error.code}: ${p.error.message}`);return p.result}}catch(p){if(p instanceof Error&&p.message.startsWith("MCP error"))throw p}}}}finally{r.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${KA(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(d=>d.type==="text"&&d.text).map(d=>d.text).join(`
461
- `)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function KA(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Ts=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 Ss(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 vs(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();El(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 cn())s.startsWith(o)&&as(s);let r=t.toPortableTools();El(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function vc(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 zA={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function ag(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:zA,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 l=s.get(a.server)??[];l.push(a),s.set(a.server,l)}let i=[];for(let[a,l]of s){i.push(`Server: ${a} (${l.length} resources)`);for(let c of l){let d=c.mimeType?` [${c.mimeType}]`:"",u=c.description?` \u2014 ${c.description}`:"";i.push(` ${c.name}: ${c.uri}${d}${u}`)}i.push("")}return{content:[{type:"text",text:i.join(`
462
- `).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var qA={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 lg(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:qA,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}-
459
+ `)}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 KA(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as zA}from"node:crypto";var Ss=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=zA(),i={jsonrpc:"2.0",id:s,method:e,params:t},a=new AbortController,l=setTimeout(()=>a.abort(),o);r&&r.addEventListener("abort",()=>a.abort(),{once:!0});try{let c={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(c["Mcp-Session-Id"]=this.sessionId);let d=await fetch(this.config.url,{method:"POST",headers:c,body:JSON.stringify(i),signal:a.signal}),u=d.headers.get("mcp-session-id");if(u&&(this.sessionId=u),!d.ok)throw new Error(`MCP HTTP error ${d.status}: ${d.statusText}`);if((d.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(d,s);let m=await d.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(l)}}async sendNotification(e,t){let 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:l}=await r.read();if(a)break;i+=s.decode(l,{stream:!0});let c=i.split(`
460
+ `);i=c.pop()??"";for(let d of c){if(!d.startsWith("data: "))continue;let u=d.slice(6).trim();if(u)try{let p=JSON.parse(u);if("method"in p&&p.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(p.id===t){if(p.error)throw new Error(`MCP error ${p.error.code}: ${p.error.message}`);return p.result}}catch(p){if(p instanceof Error&&p.message.startsWith("MCP error"))throw p}}}}finally{r.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let t=this;return{name:`mcp__${qA(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(d=>d.type==="text"&&d.text).map(d=>d.text).join(`
461
+ `)||"(no output)"}],details:a.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function qA(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Ts=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 Ss(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 vs(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();El(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 cn())s.startsWith(o)&&as(s);let r=t.toPortableTools();El(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function vc(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 YA={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function ag(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:YA,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 l=s.get(a.server)??[];l.push(a),s.set(a.server,l)}let i=[];for(let[a,l]of s){i.push(`Server: ${a} (${l.length} resources)`);for(let c of l){let d=c.mimeType?` [${c.mimeType}]`:"",u=c.description?` \u2014 ${c.description}`:"";i.push(` ${c.name}: ${c.uri}${d}${u}`)}i.push("")}return{content:[{type:"text",text:i.join(`
462
+ `).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var XA={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 lg(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:XA,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}-
463
463
  ${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"})-
464
- [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 Lt from"node:fs";import*as zo from"node:path";import{pathToFileURL as YA}from"node:url";var cg={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var ws=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(!Lt.existsSync(e))continue;let t;try{t=Lt.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let o of t){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let r=zo.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 discoverNew(){let e=new Set(this.loaded.map(o=>o.name)),t=0;for(let o of this.config.pluginDirs){if(!Lt.existsSync(o))continue;let r;try{r=Lt.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let s of r){if(!s.isDirectory()||s.name.startsWith(".")||s.name.startsWith("_")||e.has(s.name))continue;let i=zo.join(o,s.name);await this.loadPlugin(s.name,i),t++}}return t>0&&this.log.info(`[plugins] discovered ${t} new plugin(s)`),t}async refreshActivations(){let e=Date.now();for(let[t,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)Pe(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)as(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 f of o){let y=zo.join(t,f);if(Lt.existsSync(y)){r=y;break}}if(!r){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],c=[],d=null,u=6e4,p={},m=zo.join(t,"config.json");if(Lt.existsSync(m))try{p=JSON.parse(Lt.readFileSync(m,"utf8"))}catch{}let h={pluginName:e,registerTool:f=>{Pe(f),l.push(f),s++},registerHook:(f,y)=>{let b=cg[f];if(!b){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let k=this.config.hookRegistry.register({point:b,handler:y,label:`plugin:${e}:${f}`,priority:200});c.push(k),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>p,setActivationCheck:(f,y)=>{d=f,y!==void 0&&(u=y)}};try{let y=await import(YA(r).href);if(typeof y.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await y.register(h),d&&this.activations.set(e,{checkFn:d,ttlMs:u,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:c,active:!0}),this.loaded.push({name:e,directory:t,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(f){this.log.warn(`[plugins] ${e}: load error: ${f instanceof Error?f.message:f}`)}}};le();import*as De from"node:fs";import*as qo from"node:path";function Sc(){return tp()}function dg(){return qo.join(Sc(),"installed_plugins.json")}function ug(){let n=dg();if(!De.existsSync(n))return{version:1,plugins:[]};try{return JSON.parse(De.readFileSync(n,"utf-8"))}catch{return{version:1,plugins:[]}}}function XA(n){let e=Sc();De.existsSync(e)||De.mkdirSync(e,{recursive:!0}),De.writeFileSync(dg(),JSON.stringify(n,null,2),"utf-8")}function JA(n,e){return!(e.blocklist?.includes(n)||e.allowlist&&!e.allowlist.includes(n))}async function QA(n,e,t){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(o),i=Sc(),a=e?`${n}@${e}`:n;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),c=l.trim().split(`
465
- `).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let d=qo.join(i,c),p=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=qo.join(i,`${n}@${p}`);De.existsSync(m)||De.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",d,"-C",m,"--strip-components=1"],{timeout:3e4});try{De.unlinkSync(d)}catch{}let h=qo.join(m,"package.json");if(De.existsSync(h))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){t.warn(`[marketplace] npm install for ${n} failed: ${f.message}`)}return t.info(`[marketplace] installed ${n}@${p} from npm`),{name:n,version:p,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function ZA(){return ug().plugins.filter(e=>De.existsSync(e.installPath)).map(e=>e.installPath)}async function eP(n,e){let t=ug(),o=[];for(let r of n.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!JA(s,n)){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&&De.existsSync(i.installPath)&&(!r.version||i.version===r.version)){o.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await QA(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),o.push(a.installPath)}}return XA(t),o}function tP(){let n=op();if(!De.existsSync(n))return null;try{return JSON.parse(De.readFileSync(n,"utf-8"))}catch{return null}}async function pg(n,e){let t=[...n],o=ZA();t.push(...o);let r=tP();if(r&&r.enabledPlugins.length>0)try{let s=await eP(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 xs=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 o?.isReadOnly?{behavior:"allow",decisionReason:{type:"mode",mode:"dontAsk"}}:{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 oP(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"}}:this.mode==="acceptEdits"?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:o?.isDangerous?{behavior:"ask",message:`Tool "${t}" is marked dangerous`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}: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:nP(t.pattern)}))}};function Rs(n){if(!n||typeof n!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=n,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,d=l.behavior??l.action;typeof c=="string"&&typeof d=="string"&&(d==="allow"||d==="deny"||d==="ask")&&t.push({pattern:c,behavior:d,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let o=e.mode,r=typeof o=="string"&&rP(o)?o:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&sP(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function nP(n){let t=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function oP(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 rP(n){return n==="default"||n==="bypassPermissions"||n==="acceptEdits"||n==="dontAsk"||n==="plan"}function sP(n){return n==="allow"||n==="deny"||n==="ask"}import{randomUUID as hP}from"node:crypto";var iP=new Set(["nodeversion","npmversion","npxversion","pnpmversion","yarnversion","bunversion","denoversion","pythonversion","python3version","pipversion","rubyversion","go version","rustcversion","cargoversion","java -version","javac -version","dotnetversion","gccversion","g++version","clangversion","gitversion","dockerversion","--help","-h"]),mg=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","tscnoEmit","eslint","prettier","oxlint"]),aP=[/\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],fg=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 gg(n,e,t){let o=n.trim();if(!o)return{decision:"allow",reason:"empty command"};let r=Yl(o)??Xl(o)??void 0;for(let c of aP)if(c.test(o))return{decision:"deny",reason:`matches dangerous pattern: ${c.source}`,destructiveWarning:r};for(let c of iP)if(o===c||o.startsWith(c+" "))return{decision:"allow",reason:`known safe command: ${c}`,destructiveWarning:r};let s=o.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return mg.has(i)||mg.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&(fg.has(i)||fg.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function lP(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 Tc(n,e){return`${n}::${lP(e)}`}var cP=500,_s=class{cache=new Map;get(e,t){let o=Tc(e,t),r=this.cache.get(o);if(r)return r.hitCount++,r}set(e,t,o){if(this.cache.size>=cP){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=Tc(e,t);this.cache.set(r,{shouldBlock:o.shouldBlock,reason:o.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(Tc(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 dP=new Set(["read","search","instructions","think","task","memory","skill","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function Yo(n){return dP.has(n)}var hg=`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.
464
+ [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 Lt from"node:fs";import*as zo from"node:path";import{pathToFileURL as JA}from"node:url";var cg={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var ws=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(!Lt.existsSync(e))continue;let t;try{t=Lt.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let o of t){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let r=zo.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 discoverNew(){let e=new Set(this.loaded.map(o=>o.name)),t=0;for(let o of this.config.pluginDirs){if(!Lt.existsSync(o))continue;let r;try{r=Lt.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let s of r){if(!s.isDirectory()||s.name.startsWith(".")||s.name.startsWith("_")||e.has(s.name))continue;let i=zo.join(o,s.name);await this.loadPlugin(s.name,i),t++}}return t>0&&this.log.info(`[plugins] discovered ${t} new plugin(s)`),t}async refreshActivations(){let e=Date.now();for(let[t,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)Pe(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)as(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 f of o){let y=zo.join(t,f);if(Lt.existsSync(y)){r=y;break}}if(!r){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,l=[],c=[],d=null,u=6e4,p={},m=zo.join(t,"config.json");if(Lt.existsSync(m))try{p=JSON.parse(Lt.readFileSync(m,"utf8"))}catch{}let h={pluginName:e,registerTool:f=>{Pe(f),l.push(f),s++},registerHook:(f,y)=>{let b=cg[f];if(!b){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let k=this.config.hookRegistry.register({point:b,handler:y,label:`plugin:${e}:${f}`,priority:200});c.push(k),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>p,setActivationCheck:(f,y)=>{d=f,y!==void 0&&(u=y)}};try{let y=await import(JA(r).href);if(typeof y.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await y.register(h),d&&this.activations.set(e,{checkFn:d,ttlMs:u,lastCheckAt:Date.now(),lastResult:!0,tools:l,hookUnregisterFns:c,active:!0}),this.loaded.push({name:e,directory:t,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(f){this.log.warn(`[plugins] ${e}: load error: ${f instanceof Error?f.message:f}`)}}};le();import*as De from"node:fs";import*as qo from"node:path";function Sc(){return tp()}function dg(){return qo.join(Sc(),"installed_plugins.json")}function ug(){let n=dg();if(!De.existsSync(n))return{version:1,plugins:[]};try{return JSON.parse(De.readFileSync(n,"utf-8"))}catch{return{version:1,plugins:[]}}}function QA(n){let e=Sc();De.existsSync(e)||De.mkdirSync(e,{recursive:!0}),De.writeFileSync(dg(),JSON.stringify(n,null,2),"utf-8")}function ZA(n,e){return!(e.blocklist?.includes(n)||e.allowlist&&!e.allowlist.includes(n))}async function eP(n,e,t){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(o),i=Sc(),a=e?`${n}@${e}`:n;try{let{stdout:l}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),c=l.trim().split(`
465
+ `).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let d=qo.join(i,c),p=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=qo.join(i,`${n}@${p}`);De.existsSync(m)||De.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",d,"-C",m,"--strip-components=1"],{timeout:3e4});try{De.unlinkSync(d)}catch{}let h=qo.join(m,"package.json");if(De.existsSync(h))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){t.warn(`[marketplace] npm install for ${n} failed: ${f.message}`)}return t.info(`[marketplace] installed ${n}@${p} from npm`),{name:n,version:p,installPath:m}}catch(l){return t.warn(`[marketplace] failed to install ${a} from npm: ${l.message}`),null}}function tP(){return ug().plugins.filter(e=>De.existsSync(e.installPath)).map(e=>e.installPath)}async function nP(n,e){let t=ug(),o=[];for(let r of n.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!ZA(s,n)){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&&De.existsSync(i.installPath)&&(!r.version||i.version===r.version)){o.push(i.installPath);continue}let a=null;switch(r.type){case"npm":a=await eP(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),o.push(a.installPath)}}return QA(t),o}function oP(){let n=op();if(!De.existsSync(n))return null;try{return JSON.parse(De.readFileSync(n,"utf-8"))}catch{return null}}async function pg(n,e){let t=[...n],o=tP();t.push(...o);let r=oP();if(r&&r.enabledPlugins.length>0)try{let s=await nP(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 xs=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 o?.isReadOnly?{behavior:"allow",decisionReason:{type:"mode",mode:"dontAsk"}}:{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 sP(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"}}:this.mode==="acceptEdits"?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:o?.isDangerous?{behavior:"ask",message:`Tool "${t}" is marked dangerous`,toolName:t,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}: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:rP(t.pattern)}))}};function Rs(n){if(!n||typeof n!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=n,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,d=l.behavior??l.action;typeof c=="string"&&typeof d=="string"&&(d==="allow"||d==="deny"||d==="ask")&&t.push({pattern:c,behavior:d,reason:typeof l.reason=="string"?l.reason:void 0,source:typeof l.source=="string"?l.source:"config"})}}let o=e.mode,r=typeof o=="string"&&iP(o)?o:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&aP(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function rP(n){let t=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function sP(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 iP(n){return n==="default"||n==="bypassPermissions"||n==="acceptEdits"||n==="dontAsk"||n==="plan"}function aP(n){return n==="allow"||n==="deny"||n==="ask"}import{randomUUID as bP}from"node:crypto";var lP=new Set(["nodeversion","npmversion","npxversion","pnpmversion","yarnversion","bunversion","denoversion","pythonversion","python3version","pipversion","rubyversion","go version","rustcversion","cargoversion","java -version","javac -version","dotnetversion","gccversion","g++version","clangversion","gitversion","dockerversion","--help","-h"]),mg=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","tscnoEmit","eslint","prettier","oxlint"]),cP=[/\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],fg=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 gg(n,e,t){let o=n.trim();if(!o)return{decision:"allow",reason:"empty command"};let r=Yl(o)??Xl(o)??void 0;for(let c of cP)if(c.test(o))return{decision:"deny",reason:`matches dangerous pattern: ${c.source}`,destructiveWarning:r};for(let c of lP)if(o===c||o.startsWith(c+" "))return{decision:"allow",reason:`known safe command: ${c}`,destructiveWarning:r};let s=o.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return mg.has(i)||mg.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&(fg.has(i)||fg.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function dP(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 Tc(n,e){return`${n}::${dP(e)}`}var uP=500,_s=class{cache=new Map;get(e,t){let o=Tc(e,t),r=this.cache.get(o);if(r)return r.hitCount++,r}set(e,t,o){if(this.cache.size>=uP){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=Tc(e,t);this.cache.set(r,{shouldBlock:o.shouldBlock,reason:o.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(Tc(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 pP=new Set(["read","search","instructions","think","task","memory","skill","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function Yo(n){return pP.has(n)}var hg=`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.
466
466
 
467
467
  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).
468
468
 
@@ -484,7 +484,7 @@ DANGEROUS operations (SHOULD be blocked):
484
484
  - Running commands with sudo/admin privileges
485
485
  - Downloading and executing unknown scripts
486
486
 
487
- Respond ONLY with XML. No other text.`;async function wc(n,e,t,o){let r=Date.now();if(Yo(n))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=uP(t),i=pP(n,e),a=`<transcript>
487
+ Respond ONLY with XML. No other text.`;async function wc(n,e,t,o){let r=Date.now();if(Yo(n))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=mP(t),i=fP(n,e),a=`<transcript>
488
488
  ${s}
489
489
  </transcript>
490
490
 
@@ -500,58 +500,58 @@ ${s}
500
500
  ${i}
501
501
  </action>
502
502
 
503
- The fast classifier flagged this action. Review carefullyis 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:hg,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=kg(p.text),h=yg(m),f=bg(m)??bg(c)??"classifier decision";return{shouldBlock:h!==!1,reason:f,stage:"thinking",durationMs:Date.now()-r}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-r}}}function uP(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(`
504
- `)}function pP(n,e){let t=JSON.stringify(e,null,0),o=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${n}
505
- Arguments: ${o}`}function yg(n){let e=n.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function bg(n){let e=n.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function kg(n){return n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var vg={maxConsecutive:3,maxTotal:20};function Sg(){return{consecutiveDenials:0,totalDenials:0}}function xc(n){return{consecutiveDenials:n.consecutiveDenials+1,totalDenials:n.totalDenials+1}}function Rc(n){return n.consecutiveDenials===0?n:{...n,consecutiveDenials:0}}function Tg(n){return n.consecutiveDenials>=vg.maxConsecutive||n.totalDenials>=vg.maxTotal}import*as ht from"node:fs";import*as Xo from"node:path";var mP="audit",fP="denials.jsonl",gP=10*1024*1024,As=class{filePath;writeQueue=Promise.resolve();constructor(e){let t=Xo.join(e,".qlogicagent",mP);this.filePath=Xo.join(t,fP)}record(e){this.writeQueue=this.writeQueue.then(()=>this.doWrite(e)).catch(()=>{})}getFilePath(){return this.filePath}async doWrite(e){try{let t=Xo.dirname(this.filePath);if(ht.existsSync(t)||ht.mkdirSync(t,{recursive:!0}),ht.existsSync(this.filePath)&&ht.statSync(this.filePath).size>gP){let s=this.filePath+".1";ht.renameSync(this.filePath,s)}let o=JSON.stringify(e)+`
506
- `;ht.appendFileSync(this.filePath,o,"utf-8")}catch{}}};function wg(n){if(!n)return;let e={},t=/key|secret|token|password|credential|auth/i;for(let[o,r]of Object.entries(n))t.test(o)?e[o]="[REDACTED]":typeof r=="string"&&r.length>500?e[o]=r.slice(0,500)+"...[truncated]":e[o]=r;return e}var yP=12e4,Ps=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;auditLogger;sessionId;getTurnId;unregisterHook=null;toolMetaCache=new Map;classifierCache=new _s;denialTracking=Sg();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",this.auditLogger=e.auditLogger,this.sessionId=e.sessionId??"",this.getTurnId=e.getTurnId??(()=>"")}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,r="classifier",s){this.onDenied?.(t,o),this.hookRegistry.invoke("permission.denied",{sessionId:this.sessionId,turnId:this.getTurnId(),approvalId:e,callId:e,toolName:t,decision:"denied",reason:o}).catch(()=>{}),this.auditLogger&&this.auditLogger.record({timestamp:new Date().toISOString(),sessionId:this.sessionId,turnId:this.getTurnId(),toolName:t,reason:o,source:r,permissionRole:this.permissionRole,callId:e,toolArgs:wg(s),cumulativeDenials:this.denialTracking.totalDenials,consecutiveDenials:this.denialTracking.consecutiveDenials})}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,"rule-engine",r),{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)`,"safety",r),{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 c=r.command??r.cmd??"";if(c){let d=gg(c);if(d.decision==="allow")return{action:"continue"};if(d.decision==="deny")return this.fireDenied(t,o,d.reason,"classifier",r),{action:"abort",reason:d.reason}}}if(r){let c=this.classifierCache.get(o,r);if(c)return c.shouldBlock?(this.fireDenied(t,o,`cached: ${c.reason}`,"classifier",r),{action:"abort",reason:c.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,o,r);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(o)?.isReadOnly||Yo(o)?{action:"continue"}:this.handleWorkerAsk(t,o,r);if(this.ruleEngine.getMode()==="auto"){if(Yo(o))return{action:"continue"};let c=Tg(this.denialTracking);if(this.classifierLLMCall&&!c)try{let d=this.getRecentMessages?.()??[],u=await wc(o,r??{},d,this.classifierLLMCall);if(r&&this.classifierCache.set(o,r,{shouldBlock:u.shouldBlock,reason:u.reason}),!u.shouldBlock)return this.denialTracking=Rc(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:u.reason}}};this.denialTracking=xc(this.denialTracking)}catch{}}let a=hP(),l={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 c=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:o,decision:c.decision==="approved"?"approved":"denied"}).catch(()=>{}),c.permissionUpdate&&(this.ruleEngine.applyUpdate(c.permissionUpdate),this.onPermissionUpdate?.(c.permissionUpdate)),c.decision==="approved"?{action:"continue",context:c.updatedInput?{arguments:c.updatedInput}:void 0}:(this.fireDenied(t,o,`denied by user (approval ${a})`,"user",r),{action:"abort",reason:`Tool "${o}" denied by user`})}catch{return this.fireDenied(t,o,`approval timeout or error (approval ${a})`,"timeout",r),{action:"abort",reason:`Tool "${o}"approval timed out`}}}async handleWorkerAsk(e,t,o){if(Yo(t))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await wc(t,o??{},r,this.classifierLLMCall);return o&&this.classifierCache.set(t,o,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=xc(this.denialTracking),this.fireDenied(e,t,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`,"classifier",o),{action:"abort",reason:`Tool "${t}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=Rc(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`,"static-deny"),{action:"abort",reason:`Tool "${t}" deniedno 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"))},yP);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 bP="skill",kP={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete","promote","install"],description:["The operation to perform:","\u2022 'invoke' \u2014 Run a skill by name (provide 'name', optional 'args')","\u2022 'list' \u2014 List all available skills (optional 'category' filter)","\u2022 'view' \u2014 View full skill content (provide 'name', optional 'filePath')","\u2022 'create' \u2014 Create a new skill (provide 'name', 'content')","\u2022 'edit' \u2014 Overwrite skill content (provide 'name', 'content')","\u2022 'patch' \u2014 Find/replace in skill (provide 'name', 'oldString', 'newString')","\u2022 'delete' \u2014 Remove a skill (provide 'name')","\u2022 'promote' \u2014 Promote a project-level skill to global/user-level (provide 'name')","\u2022 'install' \u2014 Download and install a skill from a URL (provide 'url', optional 'name')"].join(`
507
- `)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete/promote)."},args:{type:"string",description:"Arguments or context to pass when invoking a skill."},category:{type:"string",description:"Filter skills by category (for 'list' action)."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"View a specific file within the skill (for 'view' action)."},fileContent:{type:"string",description:"Content for writing supporting files."},oldString:{type:"string",description:"Text to find for patch action."},newString:{type:"string",description:"Replacement text for patch action."},url:{type:"string",description:"URL to download a skill from (for 'install' action). Supports skill stores (skillhub.cn, skill.io, GitHub raw links, etc.) and any direct .md URL."}},required:["action"]};function xg(n){return{name:bP,label:"Skill",description:_P(n),parameters:kP,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke list view create edit delete command workflow",execute:async(e,t,o)=>{let{action:r}=t;switch(r){case"invoke":return vP(n,t,o);case"list":return SP(n,t);case"view":return TP(n,t);case"create":case"edit":case"patch":case"delete":return wP(n,t);case"promote":return xP(n,t);case"install":return RP(n,t);default:return{content:[{type:"text",text:`Unknown action: ${r}. Use invoke, list, view, create, edit, patch, delete, promote, or install.`}]}}}}}async function vP(n,e,t){let{name:o,args:r}=e;if(!o)return{content:[{type:"text",text:`Error: 'name' is required for invoke. Available skills: ${n.listSkills().map(c=>c.name).join(", ")||"(none)"}`}]};let s=await n.readSkillContent(o);if(!s){let l=n.listSkills().map(c=>c.name).join(", ");return{content:[{type:"text",text:`Skill "${o}" not found. Available skills: ${l||"(none)"}`}]}}if(n.executeSkillSubturn)try{return{content:[{type:"text",text:await n.executeSkillSubturn(o,s,r,t)}],details:{skillName:o,action:"invoke",mode:"subturn"}}}catch(l){let c=l instanceof Error?l.message:String(l);return{content:[{type:"text",text:`Skill execution error: ${c}`}],details:{error:c,skillName:o}}}let i=`## Skill: ${o}
503
+ The fast classifier flagged this action. Review carefullyis 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:hg,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=kg(p.text),h=yg(m),f=bg(m)??bg(c)??"classifier decision";return{shouldBlock:h!==!1,reason:f,stage:"thinking",durationMs:Date.now()-r}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-r}}}function mP(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(`
504
+ `)}function fP(n,e){let t=JSON.stringify(e,null,0),o=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${n}
505
+ Arguments: ${o}`}function yg(n){let e=n.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function bg(n){let e=n.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function kg(n){return n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var vg={maxConsecutive:3,maxTotal:20};function Sg(){return{consecutiveDenials:0,totalDenials:0}}function xc(n){return{consecutiveDenials:n.consecutiveDenials+1,totalDenials:n.totalDenials+1}}function Rc(n){return n.consecutiveDenials===0?n:{...n,consecutiveDenials:0}}function Tg(n){return n.consecutiveDenials>=vg.maxConsecutive||n.totalDenials>=vg.maxTotal}import*as ht from"node:fs";import*as Xo from"node:path";var gP="audit",hP="denials.jsonl",yP=10*1024*1024,As=class{filePath;writeQueue=Promise.resolve();constructor(e){let t=Xo.join(e,".qlogicagent",gP);this.filePath=Xo.join(t,hP)}record(e){this.writeQueue=this.writeQueue.then(()=>this.doWrite(e)).catch(()=>{})}getFilePath(){return this.filePath}async doWrite(e){try{let t=Xo.dirname(this.filePath);if(ht.existsSync(t)||ht.mkdirSync(t,{recursive:!0}),ht.existsSync(this.filePath)&&ht.statSync(this.filePath).size>yP){let s=this.filePath+".1";ht.renameSync(this.filePath,s)}let o=JSON.stringify(e)+`
506
+ `;ht.appendFileSync(this.filePath,o,"utf-8")}catch{}}};function wg(n){if(!n)return;let e={},t=/key|secret|token|password|credential|auth/i;for(let[o,r]of Object.entries(n))t.test(o)?e[o]="[REDACTED]":typeof r=="string"&&r.length>500?e[o]=r.slice(0,500)+"...[truncated]":e[o]=r;return e}var kP=12e4,Ps=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;auditLogger;sessionId;getTurnId;unregisterHook=null;toolMetaCache=new Map;classifierCache=new _s;denialTracking=Sg();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",this.auditLogger=e.auditLogger,this.sessionId=e.sessionId??"",this.getTurnId=e.getTurnId??(()=>"")}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,r="classifier",s){this.onDenied?.(t,o),this.hookRegistry.invoke("permission.denied",{sessionId:this.sessionId,turnId:this.getTurnId(),approvalId:e,callId:e,toolName:t,decision:"denied",reason:o}).catch(()=>{}),this.auditLogger&&this.auditLogger.record({timestamp:new Date().toISOString(),sessionId:this.sessionId,turnId:this.getTurnId(),toolName:t,reason:o,source:r,permissionRole:this.permissionRole,callId:e,toolArgs:wg(s),cumulativeDenials:this.denialTracking.totalDenials,consecutiveDenials:this.denialTracking.consecutiveDenials})}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,"rule-engine",r),{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)`,"safety",r),{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 c=r.command??r.cmd??"";if(c){let d=gg(c);if(d.decision==="allow")return{action:"continue"};if(d.decision==="deny")return this.fireDenied(t,o,d.reason,"classifier",r),{action:"abort",reason:d.reason}}}if(r){let c=this.classifierCache.get(o,r);if(c)return c.shouldBlock?(this.fireDenied(t,o,`cached: ${c.reason}`,"classifier",r),{action:"abort",reason:c.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(t,o,r);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(o)?.isReadOnly||Yo(o)?{action:"continue"}:this.handleWorkerAsk(t,o,r);if(this.ruleEngine.getMode()==="auto"){if(Yo(o))return{action:"continue"};let c=Tg(this.denialTracking);if(this.classifierLLMCall&&!c)try{let d=this.getRecentMessages?.()??[],u=await wc(o,r??{},d,this.classifierLLMCall);if(r&&this.classifierCache.set(o,r,{shouldBlock:u.shouldBlock,reason:u.reason}),!u.shouldBlock)return this.denialTracking=Rc(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:u.reason}}};this.denialTracking=xc(this.denialTracking)}catch{}}let a=bP(),l={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 c=await this.requestApproval(l);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:a,callId:t,toolName:o,decision:c.decision==="approved"?"approved":"denied"}).catch(()=>{}),c.permissionUpdate&&(this.ruleEngine.applyUpdate(c.permissionUpdate),this.onPermissionUpdate?.(c.permissionUpdate)),c.decision==="approved"?{action:"continue",context:c.updatedInput?{arguments:c.updatedInput}:void 0}:(this.fireDenied(t,o,`denied by user (approval ${a})`,"user",r),{action:"abort",reason:`Tool "${o}" denied by user`})}catch{return this.fireDenied(t,o,`approval timeout or error (approval ${a})`,"timeout",r),{action:"abort",reason:`Tool "${o}"approval timed out`}}}async handleWorkerAsk(e,t,o){if(Yo(t))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await wc(t,o??{},r,this.classifierLLMCall);return o&&this.classifierCache.set(t,o,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=xc(this.denialTracking),this.fireDenied(e,t,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`,"classifier",o),{action:"abort",reason:`Tool "${t}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=Rc(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`,"static-deny"),{action:"abort",reason:`Tool "${t}" deniedno 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"))},kP);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 vP="skill",SP={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete","promote","install"],description:["The operation to perform:","\u2022 'invoke' \u2014 Run a skill by name (provide 'name', optional 'args')","\u2022 'list' \u2014 List all available skills (optional 'category' filter)","\u2022 'view' \u2014 View full skill content (provide 'name', optional 'filePath')","\u2022 'create' \u2014 Create a new skill (provide 'name', 'content')","\u2022 'edit' \u2014 Overwrite skill content (provide 'name', 'content')","\u2022 'patch' \u2014 Find/replace in skill (provide 'name', 'oldString', 'newString')","\u2022 'delete' \u2014 Remove a skill (provide 'name')","\u2022 'promote' \u2014 Promote a project-level skill to global/user-level (provide 'name')","\u2022 'install' \u2014 Download and install a skill from a URL (provide 'url', optional 'name')"].join(`
507
+ `)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete/promote)."},args:{type:"string",description:"Arguments or context to pass when invoking a skill."},category:{type:"string",description:"Filter skills by category (for 'list' action)."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"View a specific file within the skill (for 'view' action)."},fileContent:{type:"string",description:"Content for writing supporting files."},oldString:{type:"string",description:"Text to find for patch action."},newString:{type:"string",description:"Replacement text for patch action."},url:{type:"string",description:"URL to download a skill from (for 'install' action). Supports skill stores (skillhub.cn, skill.io, GitHub raw links, etc.) and any direct .md URL."}},required:["action"]};function xg(n){return{name:vP,label:"Skill",description:PP(n),parameters:SP,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke list view create edit delete command workflow",execute:async(e,t,o)=>{let{action:r}=t;switch(r){case"invoke":return TP(n,t,o);case"list":return wP(n,t);case"view":return xP(n,t);case"create":case"edit":case"patch":case"delete":return RP(n,t);case"promote":return _P(n,t);case"install":return AP(n,t);default:return{content:[{type:"text",text:`Unknown action: ${r}. Use invoke, list, view, create, edit, patch, delete, promote, or install.`}]}}}}}async function TP(n,e,t){let{name:o,args:r}=e;if(!o)return{content:[{type:"text",text:`Error: 'name' is required for invoke. Available skills: ${n.listSkills().map(c=>c.name).join(", ")||"(none)"}`}]};let s=await n.readSkillContent(o);if(!s){let l=n.listSkills().map(c=>c.name).join(", ");return{content:[{type:"text",text:`Skill "${o}" not found. Available skills: ${l||"(none)"}`}]}}if(n.executeSkillSubturn)try{return{content:[{type:"text",text:await n.executeSkillSubturn(o,s,r,t)}],details:{skillName:o,action:"invoke",mode:"subturn"}}}catch(l){let c=l instanceof Error?l.message:String(l);return{content:[{type:"text",text:`Skill execution error: ${c}`}],details:{error:c,skillName:o}}}let i=`## Skill: ${o}
508
508
 
509
509
  `,a=r?`
510
510
 
511
511
  ### User Context
512
512
  ${r}`:"";return{content:[{type:"text",text:`${i}Follow these instructions:
513
513
 
514
- ${s}${a}`}],details:{skillName:o,action:"invoke",mode:"inline"}}}async function SP(n,e){let t=await n.listSkillsFull(e.category);if(t.skills.length===0)return{content:[{type:"text",text:e.category?`No skills found in category "${e.category}".`:"No skills available."}],details:{action:"list",count:0}};let o=[`Available skills (${t.skills.length}):`];t.categories.length>0&&o.push(`Categories: ${t.categories.join(", ")}`),o.push("");for(let r of t.skills){let s=r.category?` [${r.category}]`:"",i=r.version?` (v${r.version})`:"",a=r.scope?` {${r.scope}}`:"";o.push(`- **${r.name}**${i}${s}${a}: ${r.description}`)}return{content:[{type:"text",text:o.join(`
515
- `)}],details:{action:"list",count:t.skills.length}}}async function TP(n,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for view."}]};let t=await n.viewSkill(e.name,e.filePath);if(!t)return{content:[{type:"text",text:`Skill "${e.name}" not found. Use action: "list" to see available skills.`}],details:{action:"view",error:"not_found"}};let o=[`## Skill: ${t.name}
514
+ ${s}${a}`}],details:{skillName:o,action:"invoke",mode:"inline"}}}async function wP(n,e){let t=await n.listSkillsFull(e.category);if(t.skills.length===0)return{content:[{type:"text",text:e.category?`No skills found in category "${e.category}".`:"No skills available."}],details:{action:"list",count:0}};let o=[`Available skills (${t.skills.length}):`];t.categories.length>0&&o.push(`Categories: ${t.categories.join(", ")}`),o.push("");for(let r of t.skills){let s=r.category?` [${r.category}]`:"",i=r.version?` (v${r.version})`:"",a=r.scope?` {${r.scope}}`:"";o.push(`- **${r.name}**${i}${s}${a}: ${r.description}`)}return{content:[{type:"text",text:o.join(`
515
+ `)}],details:{action:"list",count:t.skills.length}}}async function xP(n,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for view."}]};let t=await n.viewSkill(e.name,e.filePath);if(!t)return{content:[{type:"text",text:`Skill "${e.name}" not found. Use action: "list" to see available skills.`}],details:{action:"view",error:"not_found"}};let o=[`## Skill: ${t.name}
516
516
  `,t.content];return t.referenceFiles&&t.referenceFiles.length>0&&o.push(`
517
517
  ### Reference Files
518
518
  ${t.referenceFiles.map(r=>`- ${r}`).join(`
519
519
  `)}`),{content:[{type:"text",text:o.join(`
520
- `)}],details:{action:"view",name:t.name}}}async function wP(n,e){if(!e.name)return{content:[{type:"text",text:`Error: 'name' is required for ${e.action}.`}]};let t=await n.manageSkill({action:e.action,name:e.name,category:e.category,content:e.content,filePath:e.filePath,fileContent:e.fileContent,oldString:e.oldString,newString:e.newString});return{content:[{type:"text",text:t.message}],details:{action:e.action,success:t.success,path:t.path}}}async function xP(n,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for promote."}]};if(!n.promoteSkill)return{content:[{type:"text",text:"Promote is not available in this configuration. Skills may already be at user-level."}]};let t=await n.promoteSkill(e.name);return{content:[{type:"text",text:t.message}],details:{action:"promote",success:t.success,name:e.name}}}async function RP(n,e){if(!e.url)return{content:[{type:"text",text:"Error: 'url' is required for install. Provide a direct link to a .md skill file."}]};if(!n.installSkill)return{content:[{type:"text",text:"Install from URL is not available in this configuration."}]};let t=await n.installSkill(e.url,e.name);return{content:[{type:"text",text:t.message}],details:{action:"install",success:t.success,url:e.url,name:e.name}}}function _P(n){let e=n.listSkills(),t=`Manage and invoke skills \u2014 reusable workflows and domain-specific knowledge packages. Use action: 'list' to discover skills, 'view' to read content, 'invoke' to run a skill. Skills can also be created, edited, patched, or deleted. Use 'promote' (with name) to copy a project skill to global (user-level) so it's available across all projects. Use 'install' (with url) to download a skill from a URL and save it globally.
520
+ `)}],details:{action:"view",name:t.name}}}async function RP(n,e){if(!e.name)return{content:[{type:"text",text:`Error: 'name' is required for ${e.action}.`}]};let t=await n.manageSkill({action:e.action,name:e.name,category:e.category,content:e.content,filePath:e.filePath,fileContent:e.fileContent,oldString:e.oldString,newString:e.newString});return{content:[{type:"text",text:t.message}],details:{action:e.action,success:t.success,path:t.path}}}async function _P(n,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for promote."}]};if(!n.promoteSkill)return{content:[{type:"text",text:"Promote is not available in this configuration. Skills may already be at user-level."}]};let t=await n.promoteSkill(e.name);return{content:[{type:"text",text:t.message}],details:{action:"promote",success:t.success,name:e.name}}}async function AP(n,e){if(!e.url)return{content:[{type:"text",text:"Error: 'url' is required for install. Provide a direct link to a .md skill file."}]};if(!n.installSkill)return{content:[{type:"text",text:"Install from URL is not available in this configuration."}]};let t=await n.installSkill(e.url,e.name);return{content:[{type:"text",text:t.message}],details:{action:"install",success:t.success,url:e.url,name:e.name}}}function PP(n){let e=n.listSkills(),t=`Manage and invoke skills \u2014 reusable workflows and domain-specific knowledge packages. Use action: 'list' to discover skills, 'view' to read content, 'invoke' to run a skill. Skills can also be created, edited, patched, or deleted. Use 'promote' (with name) to copy a project skill to global (user-level) so it's available across all projects. Use 'install' (with url) to download a skill from a URL and save it globally.
521
521
 
522
522
  CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled memories, it means a relevant skill exists in another project. You should proactively inform the user and offer to use it (invoke) or promote it to global. Do not wait for explicit instructions \u2014 the user may not know the skill exists. Typical user signals: '\u4E4B\u524D\u505A\u8FC7', '\u53C2\u8003XX\u9879\u76EE', 'didn't you do this before', 'same as the other project'.`;if(e.length===0)return t;let o=e.slice(0,50).map(r=>`- ${r.name}: ${r.description??"(no description)"}`).join(`
523
523
  `);return`${t}
524
524
 
525
525
  Available skills:
526
- ${o}`}var AP="agent",Rg=["general","explore","plan","code","research","verify"],PP={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
526
+ ${o}`}var IP="agent",Rg=["general","explore","plan","code","research","verify"],CP={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
527
527
  - general: Full tool access, any task
528
528
  - explore: Read-only codebase exploration (search, read, analyze)
529
529
  - plan: Planning mode (explore + produce plan, no writes)
530
530
  - code: Coding agent with full tool access
531
531
  - research: Web research and information gathering
532
- - 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},_g=4;function Ag(n){return{name:AP,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:PP,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(!Rg.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${Rg.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let o=n.currentForkDepth??0;if(o>=_g)return{content:[{type:"text",text:`Error: maximum fork depth (${_g}) 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.
532
+ - 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},_g=4;function Ag(n){return{name:IP,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:CP,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(!Rg.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${Rg.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let o=n.currentForkDepth??0;if(o>=_g)return{content:[{type:"text",text:`Error: maximum fork depth (${_g}) 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.
533
533
  Agent ID: ${r.agentId}
534
534
  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?`
535
535
 
536
- [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 IP="config",CP={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
536
+ [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 EP="config",MP={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
537
537
  - get: Read a config setting
538
538
  - set: Write a config setting
539
539
  - list: List all available settings
540
- - 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"]},Jo=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Pg(n){return{name:IP,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:CP,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(`
540
+ - 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"]},Jo=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Pg(n){return{name:EP,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:MP,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(`
541
541
  `)}],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(Jo.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(`
542
- `)}],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(Jo.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 EP="cron",MP={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:
542
+ `)}],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(Jo.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 OP="cron",DP={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:
543
543
  - Cron: '0 9 * * *' (every day at 9am)
544
544
  - Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
545
- 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"]},Ig=50;function Cg(n){return{name:EP,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:MP,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>=Ig)return{content:[{type:"text",text:`Error: maximum ${Ig} 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:_c(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(`
545
+ 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"]},Ig=50;function Cg(n){return{name:OP,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:DP,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>=Ig)return{content:[{type:"text",text:`Error: maximum ${Ig} 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:_c(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(`
546
546
  `)}],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:_c(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.
547
547
  ${_c(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 _c(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(`
548
- `)}var OP="monitor",DP={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 Eg(n){return{name:OP,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(`
549
- `),parameters:DP,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:
548
+ `)}var LP="monitor",NP={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 Eg(n){return{name:LP,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(`
549
+ `),parameters:NP,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:
550
550
  ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.eventCount}, timeout: ${l.timeoutSeconds}s)`).join(`
551
- `)}`}],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 LP="team",NP={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 Mg(n){return{name:LP,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:NP,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(`
551
+ `)}`}],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 $P="team",UP={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 Mg(n){return{name:$P,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:UP,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(`
552
552
  `)}],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(`
553
553
  `)}],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=o.memberProgress??{},i=[`Team: ${r.name}`,`Description: ${r.description||"\u2014"}`,`Lead: ${r.leadId}`,`Created: ${r.createdAt}`,"",`Members (${r.members.length}):`];for(let a of r.members){let l=a.tools?` [tools: ${a.tools.join(", ")}]`:"",c=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",d=s[a.name],u=a.isActive===!1?" (idle)":" (active)";if(d){let p=[];if(d.runningFor&&p.push(`running ${Math.round(d.runningFor/1e3)}s`),d.lastToolCall&&p.push(`tool: ${d.lastToolCall}`),d.idleFor!==void 0&&d.idleFor>5&&p.push(`idle ${d.idleFor}s`),d.mediaProgress){let m=d.mediaProgress;p.push(`${m.mediaType} ${m.percent}% [${m.status}] taskId=${m.taskId}${m.provider?` provider=${m.provider}`:""}`)}p.length&&(u=` (${p.join(", ")})`)}i.push(` - ${a.name} (${a.role})${l}${c}${u}`)}return{content:[{type:"text",text:i.join(`
554
- `)}],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 UP="mcp",jP={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:
554
+ `)}],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 FP="mcp",BP={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:
555
555
  - list_servers: List configured MCP servers, their status and capabilities
556
556
  - list_tools: List tools provided by a specific server
557
557
  - call_tool: Execute a tool on an MCP server
@@ -560,12 +560,12 @@ ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.
560
560
  - list_prompts: List prompts available from a server
561
561
  - get_prompt: Get a specific prompt with arguments
562
562
  - authenticate: Initiate OAuth authentication with a server
563
- - 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 Og(n){return{name:UP,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).
563
+ - 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 Og(n){return{name:FP,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).
564
564
 
565
- 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:jP,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=FP(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let l=[];i.capabilities.tools?.listChanged&&l.push("tools/listChanged"),i.capabilities.resources?.subscribe&&l.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&l.push("prompts/listChanged"),l.length>0&&s.push(` Capabilities: ${l.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
566
- `)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!t.server)return Te("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=BP(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(`
565
+ 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:BP,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=WP(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let l=[];i.capabilities.tools?.listChanged&&l.push("tools/listChanged"),i.capabilities.resources?.subscribe&&l.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&l.push("prompts/listChanged"),l.length>0&&s.push(` Capabilities: ${l.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
566
+ `)}],details:{type:"mcp",action:"list_servers",count:r.length}}}case"list_tools":{if(!t.server)return Te("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=GP(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(`
567
567
  `)}],details:{type:"mcp",action:"list_tools",server:t.server,count:r.length}}}case"call_tool":{if(!t.server)return Te("server is required for call_tool.");if(!t.toolName)return Te("toolName is required for call_tool.");let 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(`
568
- `)}],details:{type:"mcp",action:"list_resources",count:r.length,server:t.server}}}case"read_resource":{if(!t.server)return Te("server is required for read_resource.");if(!t.uri)return Te("uri is required for read_resource.");let 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?` (${WP(i.blobSize)})`:""}]`}):i.text&&s.push({type:"text",text:i.text});return s.length===0&&s.push({type:"text",text:"(empty content)"}),{content:s,details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}}}case"list_prompts":{if(!t.server)return Te("server is required for list_prompts.");if(!n.listPrompts)return Te("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(l=>`${l.name}${l.required?" (required)":""}${l.description?`: ${l.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
568
+ `)}],details:{type:"mcp",action:"list_resources",count:r.length,server:t.server}}}case"read_resource":{if(!t.server)return Te("server is required for read_resource.");if(!t.uri)return Te("uri is required for read_resource.");let 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?` (${HP(i.blobSize)})`:""}]`}):i.text&&s.push({type:"text",text:i.text});return s.length===0&&s.push({type:"text",text:"(empty content)"}),{content:s,details:{type:"mcp",action:"read_resource",server:t.server,uri:t.uri}}}case"list_prompts":{if(!t.server)return Te("server is required for list_prompts.");if(!n.listPrompts)return Te("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(l=>`${l.name}${l.required?" (required)":""}${l.description?`: ${l.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
569
569
  `)}],details:{type:"mcp",action:"list_prompts",server:t.server,count:r.length}}}case"get_prompt":{if(!t.server)return Te("server is required for get_prompt.");if(!t.promptName)return Te("promptName is required for get_prompt.");if(!n.getPrompt)return Te("Prompt retrieval not supported by the current MCP host.");let r=t.arguments?Object.fromEntries(Object.entries(t.arguments).map(([a,l])=>[a,String(l)])):void 0,s=await 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(`
570
570
  `)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:t.server,promptName:t.promptName}}}case"authenticate":{if(!t.server)return Te("server is required for authenticate.");let r=await n.authenticate(t.server);switch(r.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${t.server}".
571
571
 
@@ -575,23 +575,23 @@ ${r.authUrl}
575
575
  ${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.
576
576
  Required scopes: ${r.requiredScopes?.join(", ")||"unknown"}
577
577
 
578
- `+(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 Te("server is required for manage_server.");if(!t.manageAction)return Te("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!n.addServer)return Te("Server addition not supported by the current MCP host.");if(!t.config)return Te("config is required for manage_server add.");let r=await n.addServer(t.server,t.config);return Qo("add",t.server,r)}case"remove":{if(!n.removeServer)return Te("Server removal not supported by the current MCP host.");let r=await n.removeServer(t.server);return Qo("remove",t.server,r)}case"restart":{if(!n.restartServer)return Te("Server restart not supported by the current MCP host.");let r=await n.restartServer(t.server);return Qo("restart",t.server,r)}case"health_check":{if(!n.healthCheck)return Te("Health check not supported by the current MCP host.");let r=await n.healthCheck(t.server);return Qo("health_check",t.server,r)}case"enable":case"disable":{if(!n.setServerEnabled)return Te("Server enable/disable not supported by the current MCP host.");let r=await n.setServerEnabled(t.server,t.manageAction==="enable");return Qo(t.manageAction,t.server,r)}default:return Te(`Unknown manageAction: ${t.manageAction}`)}}default:return Te(`Unknown action: "${t.action}".`)}}}}function Te(n){return{content:[{type:"text",text:`Error: ${n}`}],details:{type:"mcp",error:n}}}function FP(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 BP(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 WP(n){return n<1024?`${n}B`:n<1024*1024?`${(n/1024).toFixed(1)}KB`:`${(n/(1024*1024)).toFixed(1)}MB`}function Qo(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(`
579
- `)}],details:{type:"mcp",action:"manage_server",manageAction:n,server:e,success:t.success}}}var GP="checkpoint",HP={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"]},Dg=/^[0-9a-fA-F]{4,64}$/;function Lg(n){return{name:GP,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:HP,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}
578
+ `+(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 Te("server is required for manage_server.");if(!t.manageAction)return Te("manageAction is required for manage_server.");switch(t.manageAction){case"add":{if(!n.addServer)return Te("Server addition not supported by the current MCP host.");if(!t.config)return Te("config is required for manage_server add.");let r=await n.addServer(t.server,t.config);return Qo("add",t.server,r)}case"remove":{if(!n.removeServer)return Te("Server removal not supported by the current MCP host.");let r=await n.removeServer(t.server);return Qo("remove",t.server,r)}case"restart":{if(!n.restartServer)return Te("Server restart not supported by the current MCP host.");let r=await n.restartServer(t.server);return Qo("restart",t.server,r)}case"health_check":{if(!n.healthCheck)return Te("Health check not supported by the current MCP host.");let r=await n.healthCheck(t.server);return Qo("health_check",t.server,r)}case"enable":case"disable":{if(!n.setServerEnabled)return Te("Server enable/disable not supported by the current MCP host.");let r=await n.setServerEnabled(t.server,t.manageAction==="enable");return Qo(t.manageAction,t.server,r)}default:return Te(`Unknown manageAction: ${t.manageAction}`)}}default:return Te(`Unknown action: "${t.action}".`)}}}}function Te(n){return{content:[{type:"text",text:`Error: ${n}`}],details:{type:"mcp",error:n}}}function WP(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 GP(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 HP(n){return n<1024?`${n}B`:n<1024*1024?`${(n/1024).toFixed(1)}KB`:`${(n/(1024*1024)).toFixed(1)}MB`}function Qo(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(`
579
+ `)}],details:{type:"mcp",action:"manage_server",manageAction:n,server:e,success:t.success}}}var VP="checkpoint",KP={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"]},Dg=/^[0-9a-fA-F]{4,64}$/;function Lg(n){return{name:VP,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:KP,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}
580
580
  Message: ${o.checkpoint.message}
581
581
  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(`
582
582
  `)}],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(!Dg.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(!Dg.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"}}}}}}le();import*as Ye from"node:fs";import*as Jn from"node:path";function Ng(n,e){let t=ap(n,e);return{createCheckpoint:async o=>{try{Ye.mkdirSync(t,{recursive:!0});let{execSync:r}=await import("node:child_process"),s=Jn.join(t,".git");Ye.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"})),Ye.cpSync(n,t,{recursive:!0,filter:c=>!c.includes(".git")&&!c.includes("node_modules")}),r("git add -A",{cwd:t,stdio:"pipe"});let i=o||`checkpoint ${new Date().toISOString()}`;r(`git commitallow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:t,stdio:"pipe"});let a=r("git rev-parse HEAD",{cwd:t,stdio:"pipe"}).toString().trim(),l=parseInt(r("git ls-files | wc -l",{cwd:t,stdio:"pipe"}).toString().trim(),10)||0;return{success:!0,checkpoint:{id:a,message:i,timestamp:new Date().toISOString(),fileCount:l}}}catch(r){return{success:!1,error:r.message}}},listCheckpoints:async()=>{try{let{execSync:o}=await import("node:child_process"),r=Jn.join(t,".git");if(!Ye.existsSync(r))return{success:!0,checkpoints:[]};let s=o('git logformat="%H|%aI|%s"max-count=20',{cwd:t,stdio:"pipe"}).toString().trim();return s?{success:!0,checkpoints:s.split(`
583
- `).map(a=>{let[l="",c="",...d]=a.split("|");return{id:l,timestamp:c,message:d.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){s(`git checkout ${o} ${r.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(" ")}`,{cwd:t,stdio:"pipe"});for(let i of r){let a=Jn.join(t,i),l=Jn.join(n,i);Ye.existsSync(a)&&Ye.cpSync(a,l,{recursive:!0})}}else{s(`git checkout ${o} .`,{cwd:t,stdio:"pipe"});let i=Ye.readdirSync(n);for(let a of i){if(a===".git"||a==="node_modules")continue;let l=Jn.join(n,a);Ye.rmSync(l,{recursive:!0,force:!0})}Ye.cpSync(t,n,{recursive:!0,filter:a=>!a.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 VP="notify",KP={type:"object",properties:{message:{type:"string",description:"Notification content to send to the user."},title:{type:"string",description:"Optional notification title/subject line."},priority:{type:"string",enum:["low","normal","high"],description:"Notification priority (default: normal). High may trigger sound/vibration."},channel:{type:"string",description:"Target delivery channel (e.g. 'wechat', 'feishu', 'discord'). Default: user's primary."}},required:["message"]};function $g(n){return{name:VP,label:"Notify",description:"Send a notification to the user. Used for alerting about completed long-running tasks, important updates, or requesting attention. Supports multiple channels (WeChat, Feishu, Discord, etc).",parameters:KP,execute:async(e,t)=>{if(!t.message||t.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"notify",error:"empty_message"}};let o=await n.sendNotification({message:t.message.trim(),title:t.title,priority:t.priority||"normal",channel:t.channel});return o.delivered?{content:[{type:"text",text:`Notification sent via ${o.channel}.`}],details:{type:"notify",delivered:!0,channel:o.channel}}:{content:[{type:"text",text:`Notification failed: ${o.error||"delivery error"}`}],details:{type:"notify",delivered:!1,error:o.error}}}}}var zP="send_message",qP={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function Ug(n){return{name:zP,label:"Send Message",description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:qP,execute:async(e,t)=>{if(!t.to||t.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!t.message||t.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(t.to!=="*"&&n.listTeammates){let s=n.listTeammates();if(!s.includes(t.to))return{content:[{type:"text",text:`Error: agent "${t.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let o=await n.sendMessage({to:t.to.trim(),message:t.message.trim(),summary:t.summary,senderId:n.getSenderId()});return o.success?{content:[{type:"text",text:`Message sent to ${t.to==="*"?`broadcast (${o.recipients?.length||0} recipients)`:t.to}.`}],details:{type:"send_message",success:!0,to:t.to,recipients:o.recipients}}:{content:[{type:"text",text:`Message delivery failed: ${o.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:o.error}}}}}var YP="repl",XP={type:"object",properties:{code:{type:"string",description:`JavaScript code to execute. The VM has access to these built-in primitives:
583
+ `).map(a=>{let[l="",c="",...d]=a.split("|");return{id:l,timestamp:c,message:d.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){s(`git checkout ${o} ${r.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(" ")}`,{cwd:t,stdio:"pipe"});for(let i of r){let a=Jn.join(t,i),l=Jn.join(n,i);Ye.existsSync(a)&&Ye.cpSync(a,l,{recursive:!0})}}else{s(`git checkout ${o} .`,{cwd:t,stdio:"pipe"});let i=Ye.readdirSync(n);for(let a of i){if(a===".git"||a==="node_modules")continue;let l=Jn.join(n,a);Ye.rmSync(l,{recursive:!0,force:!0})}Ye.cpSync(t,n,{recursive:!0,filter:a=>!a.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 zP="notify",qP={type:"object",properties:{message:{type:"string",description:"Notification content to send to the user."},title:{type:"string",description:"Optional notification title/subject line."},priority:{type:"string",enum:["low","normal","high"],description:"Notification priority (default: normal). High may trigger sound/vibration."},channel:{type:"string",description:"Target delivery channel (e.g. 'wechat', 'feishu', 'discord'). Default: user's primary."}},required:["message"]};function $g(n){return{name:zP,label:"Notify",description:"Send a notification to the user. Used for alerting about completed long-running tasks, important updates, or requesting attention. Supports multiple channels (WeChat, Feishu, Discord, etc).",parameters:qP,execute:async(e,t)=>{if(!t.message||t.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"notify",error:"empty_message"}};let o=await n.sendNotification({message:t.message.trim(),title:t.title,priority:t.priority||"normal",channel:t.channel});return o.delivered?{content:[{type:"text",text:`Notification sent via ${o.channel}.`}],details:{type:"notify",delivered:!0,channel:o.channel}}:{content:[{type:"text",text:`Notification failed: ${o.error||"delivery error"}`}],details:{type:"notify",delivered:!1,error:o.error}}}}}var YP="send_message",XP={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function Ug(n){return{name:YP,label:"Send Message",description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:XP,execute:async(e,t)=>{if(!t.to||t.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!t.message||t.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(t.to!=="*"&&n.listTeammates){let s=n.listTeammates();if(!s.includes(t.to))return{content:[{type:"text",text:`Error: agent "${t.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let o=await n.sendMessage({to:t.to.trim(),message:t.message.trim(),summary:t.summary,senderId:n.getSenderId()});return o.success?{content:[{type:"text",text:`Message sent to ${t.to==="*"?`broadcast (${o.recipients?.length||0} recipients)`:t.to}.`}],details:{type:"send_message",success:!0,to:t.to,recipients:o.recipients}}:{content:[{type:"text",text:`Message delivery failed: ${o.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:o.error}}}}}var JP="repl",QP={type:"object",properties:{code:{type:"string",description:`JavaScript code to execute. The VM has access to these built-in primitives:
584
584
  - readFile(path): Promise<string> \u2014 read a file
585
585
  - writeFile(path, content): Promise<void> \u2014 write a file
586
586
  - editFile(path, edits): Promise<string> \u2014 apply edits [{oldText, newText}]
587
587
  - exec(command): Promise<{stdout, stderr, exitCode}> \u2014 run shell command
588
588
  - glob(pattern): Promise<string[]> \u2014 find files by glob
589
589
  - grep(pattern, path?): Promise<{file,line,text}[]> \u2014 search files
590
- Use this for batch operations (rename many files, transform data, etc) to reduce tool call round-trips.`}},required:["code"]};var jg=1e5,Fg=5e4;function Bg(n){return{name:YP,label:"REPL",description:"Execute JavaScript in a persistent VM with built-in file/shell primitives. Use for batch operations that would otherwise require many individual tool calls. The VM persists variables between calls within the same session. Each primitive (readFile, writeFile, exec, etc.) still goes through permission checks.",parameters:XP,execute:async(e,t)=>{if(!t.code||t.code.trim().length===0)return{content:[{type:"text",text:"Error: code is required."}],details:{type:"repl",error:"empty_code"}};if(t.code.length>jg)return{content:[{type:"text",text:`Error: code too large (${t.code.length} chars, max ${jg}).`}],details:{type:"repl",error:"code_too_large"}};let o=await n.executeInVm(t.code),r=o.output||"";return r.length>Fg&&(r=r.slice(0,Fg)+`
590
+ Use this for batch operations (rename many files, transform data, etc) to reduce tool call round-trips.`}},required:["code"]};var jg=1e5,Fg=5e4;function Bg(n){return{name:JP,label:"REPL",description:"Execute JavaScript in a persistent VM with built-in file/shell primitives. Use for batch operations that would otherwise require many individual tool calls. The VM persists variables between calls within the same session. Each primitive (readFile, writeFile, exec, etc.) still goes through permission checks.",parameters:QP,execute:async(e,t)=>{if(!t.code||t.code.trim().length===0)return{content:[{type:"text",text:"Error: code is required."}],details:{type:"repl",error:"empty_code"}};if(t.code.length>jg)return{content:[{type:"text",text:`Error: code too large (${t.code.length} chars, max ${jg}).`}],details:{type:"repl",error:"code_too_large"}};let o=await n.executeInVm(t.code),r=o.output||"";return r.length>Fg&&(r=r.slice(0,Fg)+`
591
591
  ... (truncated)`),o.error?{content:[{type:"text",text:`Error: ${o.error}
592
592
 
593
593
  Output:
594
- ${r}`}],details:{type:"repl",error:o.error,duration:o.duration}}:{content:[{type:"text",text:r||"(no output)"}],details:{type:"repl",duration:o.duration,outputLength:r.length}}}}}var JP={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
594
+ ${r}`}],details:{type:"repl",error:o.error,duration:o.duration}}:{content:[{type:"text",text:r||"(no output)"}],details:{type:"repl",duration:o.duration,outputLength:r.length}}}}}var ZP={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
595
595
  - goToDefinition: jump to symbol definition
596
596
  - findReferences: find all usages of a symbol
597
597
  - hover: get type/docs for symbol at position
@@ -600,29 +600,29 @@ ${r}`}],details:{type:"repl",error:o.error,duration:o.duration}}:{content:[{type
600
600
  - completion: get completions at position
601
601
  - signatureHelp: get function signature at call site
602
602
  - rename: preview rename of symbol
603
- - codeAction: get available quick-fixes/refactorings`},filePath:{type:"string",description:"File path. Absolute or relative to workspace root."},line:{type:"number",description:"Line number (1-indexed). Required for positional operations."},character:{type:"number",description:"Character position (1-indexed). Required for positional operations."},newName:{type:"string",description:"New name for rename operation."},includeContext:{type:"boolean",description:"Include surrounding code context in results (default: true)."}},required:["operation","filePath"]},QP=10*1024*1024,ZP=["goToDefinition","findReferences","hover","completion","signatureHelp","rename","codeAction"];function Wg(n){return{name:"lsp",label:"LSP",description:"Query language servers for code intelligence. Supports go-to-definition, find-references, hover (type info), document symbols, diagnostics (errors/warnings), completions, signature help, rename preview, and code actions. Read-only \u2014 does not modify files.",parameters:JP,execute:async(e,t)=>{if(!t.filePath||t.filePath.trim().length===0)return{content:[{type:"text",text:"Error: filePath is required."}],details:{type:"lsp",error:"missing_filePath"}};if(t.filePath.startsWith("\\\\")||t.filePath.startsWith("//"))return{content:[{type:"text",text:"Error: UNC paths are not allowed."}],details:{type:"lsp",error:"unc_blocked"}};if(ZP.includes(t.operation)){if(t.line==null||t.character==null)return{content:[{type:"text",text:`Error: line and character are required for ${t.operation}.`}],details:{type:"lsp",error:"missing_position"}};if(t.line<1||t.character<1)return{content:[{type:"text",text:"Error: line and character must be \u2265 1."}],details:{type:"lsp",error:"invalid_position"}}}if(t.operation==="rename"&&!t.newName)return{content:[{type:"text",text:"Error: newName is required for rename operation."}],details:{type:"lsp",error:"missing_newName"}};let o=n.resolvePath(t.filePath);if(n.statFile){let s=await n.statFile(o);if(!s||!s.exists)return{content:[{type:"text",text:`Error: file not found: ${t.filePath}`}],details:{type:"lsp",error:"file_not_found"}};if(s.size>QP)return{content:[{type:"text",text:`Error: file too large (${(s.size/1024/1024).toFixed(1)}MB, max 10MB).`}],details:{type:"lsp",error:"file_too_large"}}}let r=await n.executeOperation({operation:t.operation,filePath:o,line:t.line,character:t.character,newName:t.newName,includeContext:t.includeContext??!0});return{content:[{type:"text",text:eI(t.operation,r)}],details:{type:"lsp",operation:t.operation}}}}}function eI(n,e){switch(e.type){case"locations":{if(e.locations.length===0)return"No results found.";let t=[`Found ${e.locations.length} location(s):`,""];for(let o of e.locations.slice(0,50))t.push(` ${o.filePath}:${o.line}:${o.character}`),o.context&&t.push(` ${o.context.trim()}`);return e.locations.length>50&&t.push(` ... and ${e.locations.length-50} more`),t.join(`
603
+ - codeAction: get available quick-fixes/refactorings`},filePath:{type:"string",description:"File path. Absolute or relative to workspace root."},line:{type:"number",description:"Line number (1-indexed). Required for positional operations."},character:{type:"number",description:"Character position (1-indexed). Required for positional operations."},newName:{type:"string",description:"New name for rename operation."},includeContext:{type:"boolean",description:"Include surrounding code context in results (default: true)."}},required:["operation","filePath"]},eI=10*1024*1024,tI=["goToDefinition","findReferences","hover","completion","signatureHelp","rename","codeAction"];function Wg(n){return{name:"lsp",label:"LSP",description:"Query language servers for code intelligence. Supports go-to-definition, find-references, hover (type info), document symbols, diagnostics (errors/warnings), completions, signature help, rename preview, and code actions. Read-only \u2014 does not modify files.",parameters:ZP,execute:async(e,t)=>{if(!t.filePath||t.filePath.trim().length===0)return{content:[{type:"text",text:"Error: filePath is required."}],details:{type:"lsp",error:"missing_filePath"}};if(t.filePath.startsWith("\\\\")||t.filePath.startsWith("//"))return{content:[{type:"text",text:"Error: UNC paths are not allowed."}],details:{type:"lsp",error:"unc_blocked"}};if(tI.includes(t.operation)){if(t.line==null||t.character==null)return{content:[{type:"text",text:`Error: line and character are required for ${t.operation}.`}],details:{type:"lsp",error:"missing_position"}};if(t.line<1||t.character<1)return{content:[{type:"text",text:"Error: line and character must be \u2265 1."}],details:{type:"lsp",error:"invalid_position"}}}if(t.operation==="rename"&&!t.newName)return{content:[{type:"text",text:"Error: newName is required for rename operation."}],details:{type:"lsp",error:"missing_newName"}};let o=n.resolvePath(t.filePath);if(n.statFile){let s=await n.statFile(o);if(!s||!s.exists)return{content:[{type:"text",text:`Error: file not found: ${t.filePath}`}],details:{type:"lsp",error:"file_not_found"}};if(s.size>eI)return{content:[{type:"text",text:`Error: file too large (${(s.size/1024/1024).toFixed(1)}MB, max 10MB).`}],details:{type:"lsp",error:"file_too_large"}}}let r=await n.executeOperation({operation:t.operation,filePath:o,line:t.line,character:t.character,newName:t.newName,includeContext:t.includeContext??!0});return{content:[{type:"text",text:nI(t.operation,r)}],details:{type:"lsp",operation:t.operation}}}}}function nI(n,e){switch(e.type){case"locations":{if(e.locations.length===0)return"No results found.";let t=[`Found ${e.locations.length} location(s):`,""];for(let o of e.locations.slice(0,50))t.push(` ${o.filePath}:${o.line}:${o.character}`),o.context&&t.push(` ${o.context.trim()}`);return e.locations.length>50&&t.push(` ... and ${e.locations.length-50} more`),t.join(`
604
604
  `)}case"symbols":{if(e.symbols.length===0)return"No symbols found.";let t=[`Document symbols (${e.symbols.length}):`,""];for(let o of e.symbols)if(t.push(` ${o.kind} ${o.name} (L${o.range.startLine}-${o.range.endLine})`),o.children){for(let r of o.children.slice(0,10))t.push(` ${r.kind} ${r.name} (L${r.range.startLine})`);o.children.length>10&&t.push(` ... and ${o.children.length-10} more`)}return t.join(`
605
605
  `)}case"diagnostics":{if(e.diagnostics.length===0)return"No diagnostics (clean file).";let t=[`Diagnostics (${e.diagnostics.length}):`,""];for(let o of e.diagnostics){let r=o.severity==="error"?"\u274C":o.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";t.push(` ${r} L${o.line}:${o.character} [${o.source||""}${o.code?`:${o.code}`:""}] ${o.message}`)}return t.join(`
606
606
  `)}case"hover":return e.hover?e.hover.contents:"No hover information available.";case"completions":{if(e.completions.length===0)return"No completions available.";let t=[`Completions (${e.completions.length}):`,""];for(let o of e.completions.slice(0,20))t.push(` [${o.kind}] ${o.label}${o.detail?` \u2014 ${o.detail}`:""}`);return e.completions.length>20&&t.push(` ... and ${e.completions.length-20} more`),t.join(`
607
607
  `)}case"signatureHelp":return e.signatures.length===0?"No signature information available.":e.signatures.join(`
608
608
  `);case"rename":{if(e.edits.length===0)return"No edits generated for rename.";let o=[`Rename would affect ${e.edits.reduce((r,s)=>r+s.edits.length,0)} location(s) in ${e.edits.length} file(s):`,""];for(let r of e.edits)o.push(` ${r.filePath} (${r.edits.length} edits)`);return o.join(`
609
609
  `)}case"codeActions":{if(e.actions.length===0)return"No code actions available.";let t=[`Available code actions (${e.actions.length}):`,""];for(let o of e.actions)t.push(` ${o.isPreferred?"\u2605":"-"} ${o.title}${o.kind?` [${o.kind}]`:""}`);return t.join(`
610
- `)}default:return"Unknown result type."}}je();import{spawn as Pc}from"node:child_process";import{createInterface as Cs}from"node:readline";import{resolve as cI,join as er}from"node:path";import{createServer as dI}from"node:net";import{createWriteStream as uI,mkdirSync as pI}from"node:fs";import{tmpdir as mI}from"node:os";import{createInterface as tI}from"node:readline";var nI=1,oI=1,yt={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"},rI=1e4,_n=class{pendingRpcs=new Map;rl=null;child=null;onNotification=null;hostHandler=null;attach(e,t,o){this.onNotification=t??null,this.hostHandler=o??null,this.child=e,this.rl=tI({input:e.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.rl.on("line",r=>{let s=r.trim();if(!s)return;let i;try{i=JSON.parse(s)}catch{return}let a="id"in i&&(typeof i.id=="number"||typeof i.id=="string"),l="method"in i&&typeof i.method=="string";if(a&&!l){let c=this.pendingRpcs.get(i.id);if(c){clearTimeout(c.timer),this.pendingRpcs.delete(i.id);let d=i;d.error?c.reject(new Error(d.error.message)):c.resolve(d.result)}return}if(a&&l){this.handleAgentRequest(i.id,i.method,i.params);return}l&&!a&&this.onNotification?.(i.method,i.params)})}handleAgentRequest(e,t,o){let r=(l,c)=>{if(!this.child?.stdin?.writable)return;let d={jsonrpc:"2.0",id:e};c?d.error=c:d.result=l??{};try{this.child.stdin.write(`${JSON.stringify(d)}
611
- `)}catch{}},s=this.hostHandler,i=o;(async()=>{switch(t){case"fs/read_text_file":return s?.readTextFile?.(i)??{};case"fs/write_text_file":return s?.writeTextFile?.(i)??{};case"session/request_permission":return s?.requestPermission?.(i??{})??{outcome:"cancelled"};case"session/elicitation":case"session/elicitation/complete":return s?.elicitation?.(i??{})??{};case"terminal/create":return s?.createTerminal?.(i??{})??{};case"terminal/output":return s?.terminalOutput?.(i??{})??{};case"terminal/release":return s?.releaseTerminal?.(i??{})??{};case"terminal/wait_for_exit":return s?.waitForTerminalExit?.(i??{})??{};case"terminal/kill":return s?.killTerminal?.(i??{})??{};default:if(s?.extMethod)return s.extMethod(t,o);throw new Error(`Method not found: ${t}`)}})().then(l=>r(l)).catch(l=>r(null,{code:-32601,message:l instanceof Error?l.message:String(l)}))}detach(){this.rl?.close(),this.rl=null,this.child=null,this.hostHandler=null;for(let[e,t]of this.pendingRpcs)clearTimeout(t.timer),t.reject(new Error("ACP adapter detached")),this.pendingRpcs.delete(e)}sendRpc(e,t,o,r=3e4){let s=nI++,i={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((a,l)=>{let c=setTimeout(()=>{this.pendingRpcs.delete(s),l(new Error(`ACP RPC timeout: ${t} (${r}ms)`))},r);this.pendingRpcs.set(s,{resolve:a,reject:l,timer:c});try{e.stdin.write(`${JSON.stringify(i)}
612
- `)}catch(d){clearTimeout(c),this.pendingRpcs.delete(s),l(d instanceof Error?d:new Error(String(d)))}})}async initialize(e){let t=await this.sendRpc(e,"initialize",{protocolVersion:oI,clientInfo:{name:"qlogicagent",version:"1.0.0"},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,auth:{terminal:!1}}},rI),o=t?.agentCapabilities??{};return{protocolVersion:typeof t?.protocolVersion=="number"?t.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities},agentInfo:t?.agentInfo,authMethods:t?.authMethods}}async createSession(e,t){let o={cwd:t.cwd,mcpServers:t.mcpServers??[]};t.additionalDirectories?.length&&(o.additionalDirectories=t.additionalDirectories),t.systemPrompt&&(o.systemPrompt=t.systemPrompt);let r=await this.sendRpc(e,"session/new",o);if(typeof r?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:r.sessionId}}async sendPrompt(e,t,o,r=3e5){let s=await this.sendRpc(e,"session/prompt",{sessionId:t,prompt:[{type:"text",text:o}]},r);return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:s?.userMessageId}}async resumeSession(e,t,o){let r={sessionId:t,cwd:o?.cwd??process.cwd(),mcpServers:o?.mcpServers??[]},s=await this.sendRpc(e,"session/load",r,3e4);if(typeof s?.sessionId!="string")throw new Error("ACP session/load: agent did not return sessionId");return{sessionId:s.sessionId}}async closeSession(e,t){try{await this.sendRpc(e,"session/close",{sessionId:t},5e3)}catch{}}static translateNotification(e,t){let o=t;if(e==="session/update"){if(!o)return null;let r=o.update;if(!r)return null;let s=r.sessionUpdate,i=o.sessionId;switch(s){case yt.AGENT_MESSAGE_CHUNK:{let a=r.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:i,messageId:r.messageId}}}case yt.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:r.content?.text??"",sessionId:i}};case yt.TOOL_CALL:return{method:"turn.tool_call",params:{callId:r.toolCallId,toolName:r.title,status:r.status??"running",content:r.content,kind:r.kind,rawInput:r.rawInput,sessionId:i}};case yt.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:r.toolCallId,toolName:r.title,status:r.status??"completed",content:r.content,rawOutput:r.rawOutput,sessionId:i}};case yt.USAGE_UPDATE:return{method:"turn.usage_update",params:r??{}};case yt.PLAN:return{method:"turn.plan",params:{steps:r.steps,sessionId:i}};case yt.AVAILABLE_COMMANDS_UPDATE:case yt.CURRENT_MODE_UPDATE:case yt.CONFIG_OPTION_UPDATE:case yt.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:s,...r,sessionId:i}};case yt.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${s??"unknown"}`,params:{...r,sessionId:i}}}}return null}};var Zo=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{execSync as Hg}from"node:child_process";import{platform as sI}from"node:os";var Ac={claude:{id:"claude",name:"Claude Code",cliCommand:"claude",acpArgs:["--experimental-acp"],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:[],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen-code",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!1,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!0},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!1,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!1},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"ZHIPU_API_KEY"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}};var iI=sI()==="win32";function Gg(n){try{let e=iI?`where ${n}`:`which ${n}`;return Hg(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function aI(n){try{return Hg(`"${n}"version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var lI=6e4,Is=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<lI)return this.cache.agents;let t=[];for(let o of Object.values(Ac))t.push(this.detectBackend(o));if(this.configStore?.customAgents)for(let o of Object.values(this.configStore.customAgents))t.push(this.detectCustomAgent(o));return this.cache={agents:t,timestamp:Date.now()},t}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let t=Gg(e.cliCommand),o=this.hasAgentConfig(e.id);if(!t)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let r=aI(t);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:t,version:r??void 0,authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose",supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){let t=Gg(e.cliCommand),o=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:t?"available":"not_installed",cliPath:t??void 0,authRequired:e.authRequired??!1,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let t=this.configStore.agents[e];return!!(t?.apiKey||t?.baseUrl||t?.customCliPath)}buildExternalDescriptor(e){let t=this.list().find(s=>s.id===e);if(!t||t.protocol!=="acp"||t.status!=="available"||!t.cliPath)return null;let o=Ac[e],r=this.configStore?.agents[e];return{id:e,cliPath:r?.customCliPath??t.cliPath,acpArgs:r?.customArgs??o?.acpArgs??[],env:r?.env??o?.env,protocol:"acp"}}};var fI=1;function gI(n,e){return{jsonrpc:"2.0",id:fI++,method:n,params:e}}var hI=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function yI(n){let e={};for(let t of hI)process.env[t]&&(e[t]=process.env[t]);return n.apiKey&&(e.OPENAI_API_KEY=n.apiKey),n.baseUrl&&(e.OPENAI_BASE_URL=n.baseUrl),e.QLOGICAGENT_MEMBER_ID=n.memberId,e.QLOGICAGENT_MEMBER_NAME=n.name,n.agentType&&(e.QLOGICAGENT_AGENT_TYPE=n.agentType),n.model&&(e.QLOGICAGENT_MODEL=n.model),n.env&&Object.assign(e,n.env),e}var Ic=ia,bI=aa,Qn=la,Vg=ca;function kI(n){return new Promise(e=>setTimeout(e,n))}var pn=class n{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=cI(er(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=er(t,"dist","cli.js"),this.mcpBridgeScriptPath=er(t,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,t,o,r){let i=`[${new Date().toISOString()}] [${e}] [agent:${t}] [${o}] ${r}`;e==="warn"?this.callbacks.log?.warn(i):this.callbacks.log?.info(i)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let t=this.callbacks.log,o=yI(e),r={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,r,o);let s=[this.cliBinaryPath];e.verbose&&s.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let i=Pc(process.execPath,s,{cwd:e.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:!1});r.pid=i.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:r,child:i,pendingRpc:a}),Cs({input:i.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",c=>{let d=c.trim();if(d)try{let u=JSON.parse(d);if("id"in u&&typeof u.id=="number"){let p=a.get(u.id);if(p){clearTimeout(p.timer),a.delete(u.id);let m=u;m.error?p.reject(new Error(m.error.message)):p.resolve(m.result)}}if("method"in u&&!("id"in u)){let p=u;this.captureChildProgress(e.memberId,p.method,p.params),this.callbacks.onNotification?.(e.memberId,p.method,p.params)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${d.slice(0,200)}`)}}),i.stderr&&Cs({input:i.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${d}`)}),i.on("exit",(c,d)=>{r.state!=="killed"&&(r.state=c===0?"completed":"failed"),r.endedAt=Date.now(),c!==0&&!r.error&&(r.error=`Process exited with code ${c} (signal: ${d})`);for(let[p,m]of a)clearTimeout(m.timer),m.reject(new Error(`Agent process exited (code=${c})`)),a.delete(p);this.callbacks.onStateChange?.(e.memberId,r.state),this.callbacks.onExit?.(e.memberId,c,d),this.slog("info",e.memberId,"exit",`exited (code=${c}, signal=${d})`)}),i.on("error",c=>{r.state="failed",r.error=c.message,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",c.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let c=await this.sendRpc(e.memberId,"initialize",{protocolVersion:"1.0",clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"}},15e3);r.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${r.pid})`);let d=c;d&&typeof d.sessionId=="string"&&(r.sessionId=d.sessionId)}catch(c){throw r.state="failed",r.error=`Initialize handshake failed: ${c instanceof Error?c.message:String(c)}`,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(r.error)}return r}async sendTask(e,t,o){let r=this.processes.get(e);if(!r)throw new Error(`No agent process: ${e}`);r.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let s;if(r.acpAdapter){let i=r.handle.sessionId??"default",a=await r.acpAdapter.sendPrompt(r.child,i,t,o?.timeout??3e5),l=r.handle.resultText??"";a.usage&&r.usageTracker&&r.usageTracker.onPromptResponseUsage(a.usage),s={content:l,stopReason:a.stopReason}}else{let i={content:t};o?.model&&(i.model=o.model),o?.apiKey&&(i.apiKey=o.apiKey),o?.baseUrl&&(i.baseUrl=o.baseUrl),o?.sessionId&&(i.sessionId=o.sessionId),s=await this.sendRpc(e,"thread.turn",i,o?.timeout??3e5);let a=s;a&&typeof a.content=="string"&&(r.handle.resultText=a.content)}return r.handle.state="completed",r.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),s}catch(s){throw r.handle.state="failed",r.handle.error=s instanceof Error?s.message:String(s),r.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),s}}async sendRpc(e,t,o,r=3e4){let s=this.processes.get(e);if(!s)throw new Error(`No agent process: ${e}`);let i=gI(t,o);return new Promise((a,l)=>{let c=setTimeout(()=>{s.pendingRpc.delete(i.id),l(new Error(`RPC timeout: ${t} (${r}ms)`))},r);s.pendingRpc.set(i.id,{resolve:a,reject:l,timer:c});try{s.child.stdin.write(`${JSON.stringify(i)}
610
+ `)}default:return"Unknown result type."}}je();import{spawn as Pc}from"node:child_process";import{createInterface as Cs}from"node:readline";import{resolve as uI,join as er}from"node:path";import{createServer as pI}from"node:net";import{createWriteStream as mI,mkdirSync as fI}from"node:fs";import{tmpdir as gI}from"node:os";import{createInterface as oI}from"node:readline";var rI=1,sI=1,yt={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"},iI=1e4,_n=class{pendingRpcs=new Map;rl=null;child=null;onNotification=null;hostHandler=null;attach(e,t,o){this.onNotification=t??null,this.hostHandler=o??null,this.child=e,this.rl=oI({input:e.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.rl.on("line",r=>{let s=r.trim();if(!s)return;let i;try{i=JSON.parse(s)}catch{return}let a="id"in i&&(typeof i.id=="number"||typeof i.id=="string"),l="method"in i&&typeof i.method=="string";if(a&&!l){let c=this.pendingRpcs.get(i.id);if(c){clearTimeout(c.timer),this.pendingRpcs.delete(i.id);let d=i;d.error?c.reject(new Error(d.error.message)):c.resolve(d.result)}return}if(a&&l){this.handleAgentRequest(i.id,i.method,i.params);return}l&&!a&&this.onNotification?.(i.method,i.params)})}handleAgentRequest(e,t,o){let r=(l,c)=>{if(!this.child?.stdin?.writable)return;let d={jsonrpc:"2.0",id:e};c?d.error=c:d.result=l??{};try{this.child.stdin.write(`${JSON.stringify(d)}
611
+ `)}catch{}},s=this.hostHandler,i=o;(async()=>{switch(t){case"fs/read_text_file":return s?.readTextFile?.(i)??{};case"fs/write_text_file":return s?.writeTextFile?.(i)??{};case"session/request_permission":return s?.requestPermission?.(i??{})??{outcome:"cancelled"};case"session/elicitation":case"session/elicitation/complete":return s?.elicitation?.(i??{})??{};case"terminal/create":return s?.createTerminal?.(i??{})??{};case"terminal/output":return s?.terminalOutput?.(i??{})??{};case"terminal/release":return s?.releaseTerminal?.(i??{})??{};case"terminal/wait_for_exit":return s?.waitForTerminalExit?.(i??{})??{};case"terminal/kill":return s?.killTerminal?.(i??{})??{};default:if(s?.extMethod)return s.extMethod(t,o);throw new Error(`Method not found: ${t}`)}})().then(l=>r(l)).catch(l=>r(null,{code:-32601,message:l instanceof Error?l.message:String(l)}))}detach(){this.rl?.close(),this.rl=null,this.child=null,this.hostHandler=null;for(let[e,t]of this.pendingRpcs)clearTimeout(t.timer),t.reject(new Error("ACP adapter detached")),this.pendingRpcs.delete(e)}sendRpc(e,t,o,r=3e4){let s=rI++,i={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((a,l)=>{let c=setTimeout(()=>{this.pendingRpcs.delete(s),l(new Error(`ACP RPC timeout: ${t} (${r}ms)`))},r);this.pendingRpcs.set(s,{resolve:a,reject:l,timer:c});try{e.stdin.write(`${JSON.stringify(i)}
612
+ `)}catch(d){clearTimeout(c),this.pendingRpcs.delete(s),l(d instanceof Error?d:new Error(String(d)))}})}async initialize(e){let t=await this.sendRpc(e,"initialize",{protocolVersion:sI,clientInfo:{name:"qlogicagent",version:"1.0.0"},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,auth:{terminal:!1}}},iI),o=t?.agentCapabilities??{};return{protocolVersion:typeof t?.protocolVersion=="number"?t.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities},agentInfo:t?.agentInfo,authMethods:t?.authMethods}}async createSession(e,t){let o={cwd:t.cwd,mcpServers:t.mcpServers??[]};t.additionalDirectories?.length&&(o.additionalDirectories=t.additionalDirectories),t.systemPrompt&&(o.systemPrompt=t.systemPrompt);let r=await this.sendRpc(e,"session/new",o);if(typeof r?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:r.sessionId}}async sendPrompt(e,t,o,r=3e5){let s=await this.sendRpc(e,"session/prompt",{sessionId:t,prompt:[{type:"text",text:o}]},r);return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:s?.userMessageId}}async resumeSession(e,t,o){let r={sessionId:t,cwd:o?.cwd??process.cwd(),mcpServers:o?.mcpServers??[]},s=await this.sendRpc(e,"session/load",r,3e4);if(typeof s?.sessionId!="string")throw new Error("ACP session/load: agent did not return sessionId");return{sessionId:s.sessionId}}async closeSession(e,t){try{await this.sendRpc(e,"session/close",{sessionId:t},5e3)}catch{}}static translateNotification(e,t){let o=t;if(e==="session/update"){if(!o)return null;let r=o.update;if(!r)return null;let s=r.sessionUpdate,i=o.sessionId;switch(s){case yt.AGENT_MESSAGE_CHUNK:{let a=r.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:i,messageId:r.messageId}}}case yt.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:r.content?.text??"",sessionId:i}};case yt.TOOL_CALL:return{method:"turn.tool_call",params:{callId:r.toolCallId,toolName:r.title,status:r.status??"running",content:r.content,kind:r.kind,rawInput:r.rawInput,sessionId:i}};case yt.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:r.toolCallId,toolName:r.title,status:r.status??"completed",content:r.content,rawOutput:r.rawOutput,sessionId:i}};case yt.USAGE_UPDATE:return{method:"turn.usage_update",params:r??{}};case yt.PLAN:return{method:"turn.plan",params:{steps:r.steps,sessionId:i}};case yt.AVAILABLE_COMMANDS_UPDATE:case yt.CURRENT_MODE_UPDATE:case yt.CONFIG_OPTION_UPDATE:case yt.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:s,...r,sessionId:i}};case yt.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${s??"unknown"}`,params:{...r,sessionId:i}}}}return null}};var Zo=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{execSync as Hg}from"node:child_process";import{platform as aI}from"node:os";var Ac={claude:{id:"claude",name:"Claude Code",cliCommand:"claude",acpArgs:["--experimental-acp"],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:[],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen-code",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!1,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!0},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!1,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!1},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"ZHIPU_API_KEY"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}};var lI=aI()==="win32";function Gg(n){try{let e=lI?`where ${n}`:`which ${n}`;return Hg(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function cI(n){try{return Hg(`"${n}"version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var dI=6e4,Is=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<dI)return this.cache.agents;let t=[];for(let o of Object.values(Ac))t.push(this.detectBackend(o));if(this.configStore?.customAgents)for(let o of Object.values(this.configStore.customAgents))t.push(this.detectCustomAgent(o));return this.cache={agents:t,timestamp:Date.now()},t}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let t=Gg(e.cliCommand),o=this.hasAgentConfig(e.id);if(!t)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let r=cI(t);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:t,version:r??void 0,authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose",supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){let t=Gg(e.cliCommand),o=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:t?"available":"not_installed",cliPath:t??void 0,authRequired:e.authRequired??!1,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let t=this.configStore.agents[e];return!!(t?.apiKey||t?.baseUrl||t?.customCliPath)}buildExternalDescriptor(e){let t=this.list().find(s=>s.id===e);if(!t||t.protocol!=="acp"||t.status!=="available"||!t.cliPath)return null;let o=Ac[e],r=this.configStore?.agents[e];return{id:e,cliPath:r?.customCliPath??t.cliPath,acpArgs:r?.customArgs??o?.acpArgs??[],env:r?.env??o?.env,protocol:"acp"}}};var hI=1;function yI(n,e){return{jsonrpc:"2.0",id:hI++,method:n,params:e}}var bI=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function kI(n){let e={};for(let t of bI)process.env[t]&&(e[t]=process.env[t]);return n.apiKey&&(e.OPENAI_API_KEY=n.apiKey),n.baseUrl&&(e.OPENAI_BASE_URL=n.baseUrl),e.QLOGICAGENT_MEMBER_ID=n.memberId,e.QLOGICAGENT_MEMBER_NAME=n.name,n.agentType&&(e.QLOGICAGENT_AGENT_TYPE=n.agentType),n.model&&(e.QLOGICAGENT_MODEL=n.model),n.env&&Object.assign(e,n.env),e}var Ic=ia,vI=aa,Qn=la,Vg=ca;function SI(n){return new Promise(e=>setTimeout(e,n))}var pn=class n{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=uI(er(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=er(t,"dist","cli.js"),this.mcpBridgeScriptPath=er(t,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,t,o,r){let i=`[${new Date().toISOString()}] [${e}] [agent:${t}] [${o}] ${r}`;e==="warn"?this.callbacks.log?.warn(i):this.callbacks.log?.info(i)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let t=this.callbacks.log,o=kI(e),r={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,r,o);let s=[this.cliBinaryPath];e.verbose&&s.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let i=Pc(process.execPath,s,{cwd:e.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:!1});r.pid=i.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:r,child:i,pendingRpc:a}),Cs({input:i.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",c=>{let d=c.trim();if(d)try{let u=JSON.parse(d);if("id"in u&&typeof u.id=="number"){let p=a.get(u.id);if(p){clearTimeout(p.timer),a.delete(u.id);let m=u;m.error?p.reject(new Error(m.error.message)):p.resolve(m.result)}}if("method"in u&&!("id"in u)){let p=u;this.captureChildProgress(e.memberId,p.method,p.params),this.callbacks.onNotification?.(e.memberId,p.method,p.params)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${d.slice(0,200)}`)}}),i.stderr&&Cs({input:i.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${d}`)}),i.on("exit",(c,d)=>{r.state!=="killed"&&(r.state=c===0?"completed":"failed"),r.endedAt=Date.now(),c!==0&&!r.error&&(r.error=`Process exited with code ${c} (signal: ${d})`);for(let[p,m]of a)clearTimeout(m.timer),m.reject(new Error(`Agent process exited (code=${c})`)),a.delete(p);this.callbacks.onStateChange?.(e.memberId,r.state),this.callbacks.onExit?.(e.memberId,c,d),this.slog("info",e.memberId,"exit",`exited (code=${c}, signal=${d})`)}),i.on("error",c=>{r.state="failed",r.error=c.message,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",c.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let c=await this.sendRpc(e.memberId,"initialize",{protocolVersion:"1.0",clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"}},15e3);r.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${r.pid})`);let d=c;d&&typeof d.sessionId=="string"&&(r.sessionId=d.sessionId)}catch(c){throw r.state="failed",r.error=`Initialize handshake failed: ${c instanceof Error?c.message:String(c)}`,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(r.error)}return r}async sendTask(e,t,o){let r=this.processes.get(e);if(!r)throw new Error(`No agent process: ${e}`);r.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let s;if(r.acpAdapter){let i=r.handle.sessionId??"default",a=await r.acpAdapter.sendPrompt(r.child,i,t,o?.timeout??3e5),l=r.handle.resultText??"";a.usage&&r.usageTracker&&r.usageTracker.onPromptResponseUsage(a.usage),s={content:l,stopReason:a.stopReason}}else{let i={content:t};o?.model&&(i.model=o.model),o?.apiKey&&(i.apiKey=o.apiKey),o?.baseUrl&&(i.baseUrl=o.baseUrl),o?.sessionId&&(i.sessionId=o.sessionId),s=await this.sendRpc(e,"thread.turn",i,o?.timeout??3e5);let a=s;a&&typeof a.content=="string"&&(r.handle.resultText=a.content)}return r.handle.state="completed",r.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),s}catch(s){throw r.handle.state="failed",r.handle.error=s instanceof Error?s.message:String(s),r.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),s}}async sendRpc(e,t,o,r=3e4){let s=this.processes.get(e);if(!s)throw new Error(`No agent process: ${e}`);let i=yI(t,o);return new Promise((a,l)=>{let c=setTimeout(()=>{s.pendingRpc.delete(i.id),l(new Error(`RPC timeout: ${t} (${r}ms)`))},r);s.pendingRpc.set(i.id,{resolve:a,reject:l,timer:c});try{s.child.stdin.write(`${JSON.stringify(i)}
613
613
  `)}catch(d){clearTimeout(c),s.pendingRpc.delete(i.id),l(d instanceof Error?d:new Error(String(d)))}})}async sendTaskAsync(e,t,o){let r=this.processes.get(e);if(!r)throw new Error(`No agent process: ${e}`);r.handle.state="running",this.callbacks.onStateChange?.(e,"running");let s={content:t};o?.model&&(s.model=o.model),o?.apiKey&&(s.apiKey=o.apiKey),o?.baseUrl&&(s.baseUrl=o.baseUrl),o?.sessionId&&(s.sessionId=o.sessionId);let i=o?.pingInterval??6e4,a=o?.pingTimeout??1e4,l=o?.timeout??0,c=Date.now(),d=l>0?l:1440*60*1e3,u=this.sendRpc(e,"thread.turn",s,d),p=setInterval(async()=>{if(l>0&&Date.now()-c>l){clearInterval(p),r.handle.state="failed",r.handle.error="Task timed out",r.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed");return}try{await this.sendRpc(e,"ping",void 0,a)}catch{this.slog("warn",r.handle.memberId,"heartbeat","ping failed")}},i);try{let m=await u;clearInterval(p),r.handle.state="completed",r.handle.endedAt=Date.now();let h=m;return h&&typeof h.content=="string"&&(r.handle.resultText=h.content),this.callbacks.onStateChange?.(e,"completed"),m}catch(m){throw clearInterval(p),r.handle.state="failed",r.handle.error=m instanceof Error?m.message:String(m),r.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),m}}async ping(e,t=5e3){let o=this.processes.get(e);if(!o)return!1;if(o.acpAdapter){try{let i=JSON.stringify({jsonrpc:"2.0",method:"notifications/ping",params:{timestamp:Date.now()}})+`
614
- `;o.child.stdin?.write(i)}catch{return!1}let r=o.handle.lastActivityAt??0,s=Date.now()+t;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,500)),(o.handle.lastActivityAt??0)>r)return!0;try{return await this.sendRpc(e,"ping",void 0,Math.min(t,3e3)),!0}catch{return!1}}try{return await this.sendRpc(e,"ping",void 0,t),!0}catch{return!1}}getStatus(e){let t=this.processes.get(e);if(!t)return null;let{handle:o}=t,r=o.state==="starting"||o.state==="ready"||o.state==="running",s=r?Date.now()-o.startedAt:void 0,i=o.lastActivityAt&&r?Math.round((Date.now()-o.lastActivityAt)/1e3):void 0;return{alive:r,state:o.state,runningFor:s,resultText:o.resultText,error:o.error,mediaProgress:o.mediaProgress,lastToolCall:o.lastToolCall,idleFor:i}}captureChildProgress(e,t,o){let r=this.processes.get(e);if(!r)return;let{handle:s}=r;switch(s.lastActivityAt=Date.now(),t){case"turn.media_progress":{let i=o;i&&typeof i.taskId=="string"&&(s.mediaProgress={taskId:i.taskId,mediaType:i.mediaType??"unknown",percent:typeof i.percent=="number"?i.percent:0,status:i.status??"unknown",provider:i.provider,updatedAt:Date.now()});break}case"turn.tool_call":{let i=o;i&&typeof i.name=="string"&&(s.lastToolCall=i.name);break}case"turn.delta":{let i=o;i&&typeof i.text=="string"&&(s.lastDelta=i.text.slice(-200));break}case"turn.tool_result":{o&&s.mediaProgress&&s.mediaProgress.percent>=100&&(s.mediaProgress=void 0);break}}}async spawnAcpAgentWithRetry(e,t,o){let r=null;for(let s=0;s<=Ic;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=bI*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${Ic} after ${i}ms`),await kI(i)}return await this.spawnAcpAgent(e,t,o)}catch(i){r=i instanceof Error?i:new Error(String(i)),this.slog("warn",e.memberId,"spawn",`attempt ${s+1} failed: ${r.message}`)}throw t.state="failed",t.error=`ACP spawn failed after ${Ic+1} attempts: ${r?.message}`,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),new Error(t.error)}async spawnAcpAgent(e,t,o){let r=this.callbacks.log,s=e.external;s.env&&Object.assign(o,s.env);let i=[...s.acpArgs];this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${s.cliPath} ${i.join(" ")}`);let a=Pc(s.cliPath,i,{cwd:e.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:!1});t.pid=a.pid??-1;let l=new Map,c=new _n,d=new Zo,{server:u,pipePath:p}=this.createMcpIpcServer(e.memberId);o.QLOGICAGENT_PARENT_RPC=p;let m;if(this.callbacks.sessionDir)try{pI(this.callbacks.sessionDir,{recursive:!0}),m=uI(er(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}this.processes.set(e.memberId,{handle:t,child:a,pendingRpc:l,acpAdapter:c,usageTracker:d,ipcServer:u,ipcPath:p,stderrStream:m}),c.attach(a,(h,f)=>{h==="usage_update"&&d.onUsageUpdate(f);let y=_n.translateNotification(h,f);y?(this.captureChildProgress(e.memberId,y.method,y.params),this.callbacks.onNotification?.(e.memberId,y.method,y.params)):(this.captureChildProgress(e.memberId,h,f),this.callbacks.onNotification?.(e.memberId,h,f))}),a.stderr&&Cs({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",f=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${f}`),m?.write(`${new Date().toISOString()} ${f}
615
- `)}),a.on("exit",(h,f)=>{c.detach();let y=t.state;if(y!=="killed"&&y!=="completed"&&h!==0){let k=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(k<Qn){let x=Vg*2**k;this.slog("warn",e.memberId,"crash",`crashed (code=${h}), restarting ${k+1}/${Qn} after ${x}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${h}, signal=${f}), restarting`,retriesLeft:Qn-k-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,o,k+1).catch(I=>{this.slog("warn",e.memberId,"restart",`failed: ${I instanceof Error?I.message:String(I)}`)})},x);return}}y!=="killed"&&(t.state=h===0?"completed":"failed"),t.endedAt=Date.now(),h!==0&&!t.error&&(t.error=`ACP process exited with code ${h} (signal: ${f})`),this.callbacks.onStateChange?.(e.memberId,t.state),this.callbacks.onExit?.(e.memberId,h,f),this.slog("info",e.memberId,"exit",`ACP exited (code=${h}, signal=${f})`)}),a.on("error",h=>{c.detach(),t.state="failed",t.error=h.message,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:h.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",h.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let h=await c.initialize(a);t.state="ready",t.supportsResume=h.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${h.protocolVersion}, loadSession=${t.supportsResume}, pid=${t.pid})`);try{let f={cwd:e.cwd},y=[...e.mcpServers??[]],b=this.processes.get(e.memberId);b?.ipcPath&&y.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:b.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),y.length>0&&(f.mcpServers=y),e.systemPrompt&&(f.systemPrompt=e.systemPrompt);let k=await c.createSession(a,f);t.sessionId=k.sessionId,this.slog("info",e.memberId,"session",`session created (id=${k.sessionId})`)}catch(f){this.slog("warn",e.memberId,"session",`session creation failed: ${f instanceof Error?f.message:String(f)}`)}this.startHeartbeat(e.memberId,f=>{this.slog("warn",f,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(f,"agents.error",{agentId:f,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${n.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(f)})}catch(h){throw t.state="failed",t.error=`ACP handshake failed: ${h instanceof Error?h.message:String(h)}`,t.endedAt=Date.now(),c.detach(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"handshake",error:t.error,retriesLeft:0}),this.kill(e.memberId),new Error(t.error)}return t}kill(e){let t=this.processes.get(e);if(t){this.stopHeartbeat(e),t.handle.state="killed",t.handle.endedAt=Date.now(),t.acpAdapter?.detach();try{t.ipcServer?.close()}catch{}try{t.stderrStream?.end()}catch{}try{t.child.kill("SIGTERM"),setTimeout(()=>{try{t.child.kill("SIGKILL")}catch{}},1e4)}catch{}this.callbacks.onStateChange?.(e,"killed"),this.slog("info",e,"kill",`killed (pid=${t.handle.pid})`)}}killAll(){for(let e of this.processes.keys())this.kill(e)}getHandle(e){return this.processes.get(e)?.handle}getAllHandles(){return[...this.processes.values()].map(e=>e.handle)}getUsageTracker(e){return this.processes.get(e)?.usageTracker??null}createMcpIpcServer(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"-"),o=process.platform==="win32"?`\\\\.\\pipe\\qlogicagent-mcp-${t}-${Date.now()}`:er(mI(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),r=dI(s=>{let i="";s.on("data",a=>{i+=a.toString();let l;for(;(l=i.indexOf(`
614
+ `;o.child.stdin?.write(i)}catch{return!1}let r=o.handle.lastActivityAt??0,s=Date.now()+t;for(;Date.now()<s;)if(await new Promise(i=>setTimeout(i,500)),(o.handle.lastActivityAt??0)>r)return!0;try{return await this.sendRpc(e,"ping",void 0,Math.min(t,3e3)),!0}catch{return!1}}try{return await this.sendRpc(e,"ping",void 0,t),!0}catch{return!1}}getStatus(e){let t=this.processes.get(e);if(!t)return null;let{handle:o}=t,r=o.state==="starting"||o.state==="ready"||o.state==="running",s=r?Date.now()-o.startedAt:void 0,i=o.lastActivityAt&&r?Math.round((Date.now()-o.lastActivityAt)/1e3):void 0;return{alive:r,state:o.state,runningFor:s,resultText:o.resultText,error:o.error,mediaProgress:o.mediaProgress,lastToolCall:o.lastToolCall,idleFor:i}}captureChildProgress(e,t,o){let r=this.processes.get(e);if(!r)return;let{handle:s}=r;switch(s.lastActivityAt=Date.now(),t){case"turn.media_progress":{let i=o;i&&typeof i.taskId=="string"&&(s.mediaProgress={taskId:i.taskId,mediaType:i.mediaType??"unknown",percent:typeof i.percent=="number"?i.percent:0,status:i.status??"unknown",provider:i.provider,updatedAt:Date.now()});break}case"turn.tool_call":{let i=o;i&&typeof i.name=="string"&&(s.lastToolCall=i.name);break}case"turn.delta":{let i=o;i&&typeof i.text=="string"&&(s.lastDelta=i.text.slice(-200));break}case"turn.tool_result":{o&&s.mediaProgress&&s.mediaProgress.percent>=100&&(s.mediaProgress=void 0);break}}}async spawnAcpAgentWithRetry(e,t,o){let r=null;for(let s=0;s<=Ic;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=vI*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${Ic} after ${i}ms`),await SI(i)}return await this.spawnAcpAgent(e,t,o)}catch(i){r=i instanceof Error?i:new Error(String(i)),this.slog("warn",e.memberId,"spawn",`attempt ${s+1} failed: ${r.message}`)}throw t.state="failed",t.error=`ACP spawn failed after ${Ic+1} attempts: ${r?.message}`,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),new Error(t.error)}async spawnAcpAgent(e,t,o){let r=this.callbacks.log,s=e.external;s.env&&Object.assign(o,s.env);let i=[...s.acpArgs];this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${s.cliPath} ${i.join(" ")}`);let a=Pc(s.cliPath,i,{cwd:e.cwd,env:o,stdio:["pipe","pipe","pipe"],detached:!1});t.pid=a.pid??-1;let l=new Map,c=new _n,d=new Zo,{server:u,pipePath:p}=this.createMcpIpcServer(e.memberId);o.QLOGICAGENT_PARENT_RPC=p;let m;if(this.callbacks.sessionDir)try{fI(this.callbacks.sessionDir,{recursive:!0}),m=mI(er(this.callbacks.sessionDir,`${e.memberId}.stderr.log`),{flags:"a"})}catch{}this.processes.set(e.memberId,{handle:t,child:a,pendingRpc:l,acpAdapter:c,usageTracker:d,ipcServer:u,ipcPath:p,stderrStream:m}),c.attach(a,(h,f)=>{h==="usage_update"&&d.onUsageUpdate(f);let y=_n.translateNotification(h,f);y?(this.captureChildProgress(e.memberId,y.method,y.params),this.callbacks.onNotification?.(e.memberId,y.method,y.params)):(this.captureChildProgress(e.memberId,h,f),this.callbacks.onNotification?.(e.memberId,h,f))}),a.stderr&&Cs({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",f=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${f}`),m?.write(`${new Date().toISOString()} ${f}
615
+ `)}),a.on("exit",(h,f)=>{c.detach();let y=t.state;if(y!=="killed"&&y!=="completed"&&h!==0){let k=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(k<Qn){let x=Vg*2**k;this.slog("warn",e.memberId,"crash",`crashed (code=${h}), restarting ${k+1}/${Qn} after ${x}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${h}, signal=${f}), restarting`,retriesLeft:Qn-k-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,o,k+1).catch(I=>{this.slog("warn",e.memberId,"restart",`failed: ${I instanceof Error?I.message:String(I)}`)})},x);return}}y!=="killed"&&(t.state=h===0?"completed":"failed"),t.endedAt=Date.now(),h!==0&&!t.error&&(t.error=`ACP process exited with code ${h} (signal: ${f})`),this.callbacks.onStateChange?.(e.memberId,t.state),this.callbacks.onExit?.(e.memberId,h,f),this.slog("info",e.memberId,"exit",`ACP exited (code=${h}, signal=${f})`)}),a.on("error",h=>{c.detach(),t.state="failed",t.error=h.message,t.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:h.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",h.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let h=await c.initialize(a);t.state="ready",t.supportsResume=h.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${h.protocolVersion}, loadSession=${t.supportsResume}, pid=${t.pid})`);try{let f={cwd:e.cwd},y=[...e.mcpServers??[]],b=this.processes.get(e.memberId);b?.ipcPath&&y.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:b.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),y.length>0&&(f.mcpServers=y),e.systemPrompt&&(f.systemPrompt=e.systemPrompt);let k=await c.createSession(a,f);t.sessionId=k.sessionId,this.slog("info",e.memberId,"session",`session created (id=${k.sessionId})`)}catch(f){this.slog("warn",e.memberId,"session",`session creation failed: ${f instanceof Error?f.message:String(f)}`)}this.startHeartbeat(e.memberId,f=>{this.slog("warn",f,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(f,"agents.error",{agentId:f,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${n.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(f)})}catch(h){throw t.state="failed",t.error=`ACP handshake failed: ${h instanceof Error?h.message:String(h)}`,t.endedAt=Date.now(),c.detach(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"handshake",error:t.error,retriesLeft:0}),this.kill(e.memberId),new Error(t.error)}return t}kill(e){let t=this.processes.get(e);if(t){this.stopHeartbeat(e),t.handle.state="killed",t.handle.endedAt=Date.now(),t.acpAdapter?.detach();try{t.ipcServer?.close()}catch{}try{t.stderrStream?.end()}catch{}try{t.child.kill("SIGTERM"),setTimeout(()=>{try{t.child.kill("SIGKILL")}catch{}},1e4)}catch{}this.callbacks.onStateChange?.(e,"killed"),this.slog("info",e,"kill",`killed (pid=${t.handle.pid})`)}}killAll(){for(let e of this.processes.keys())this.kill(e)}getHandle(e){return this.processes.get(e)?.handle}getAllHandles(){return[...this.processes.values()].map(e=>e.handle)}getUsageTracker(e){return this.processes.get(e)?.usageTracker??null}createMcpIpcServer(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"-"),o=process.platform==="win32"?`\\\\.\\pipe\\qlogicagent-mcp-${t}-${Date.now()}`:er(gI(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),r=pI(s=>{let i="";s.on("data",a=>{i+=a.toString();let l;for(;(l=i.indexOf(`
616
616
  `))!==-1;){let c=i.slice(0,l).trim();i=i.slice(l+1),c&&this.handleMcpIpcMessage(e,c,s)}})});return r.listen(o),r.on("error",s=>{this.slog("warn",e,"mcp-ipc",`server error: ${s.message}`)}),{server:r,pipePath:o}}handleMcpIpcMessage(e,t,o){let r;try{r=JSON.parse(t)}catch{return}if(r.method==="mcp.toolCall"&&r.id!==void 0){let s=typeof r.params?.tool=="string"?r.params.tool:"",i=r.params?.arguments??{};if(!this.callbacks.onMcpToolCall){let a=JSON.stringify({jsonrpc:"2.0",id:r.id,error:{code:-32601,message:"No onMcpToolCall handler"}})+`
617
617
  `;try{o.write(a)}catch{}return}this.callbacks.onMcpToolCall(e,s,i).then(a=>{let l=JSON.stringify({jsonrpc:"2.0",id:r.id,result:a})+`
618
618
  `;try{o.write(l)}catch{}}).catch(a=>{let l=JSON.stringify({jsonrpc:"2.0",id:r.id,error:{code:-32603,message:a instanceof Error?a.message:String(a)}})+`
619
619
  `;try{o.write(l)}catch{}})}else if(r.id!==void 0){let s=JSON.stringify({jsonrpc:"2.0",id:r.id,error:{code:-32601,message:`Unknown IPC method: ${r.method}`}})+`
620
620
  `;try{o.write(s)}catch{}}}async attemptRuntimeRestart(e,t,o){let r=this.callbacks.log,s=this.processes.get(e.memberId),i=s?.ipcServer,a=s?.ipcPath,l=s?.stderrStream;this.processes.delete(e.memberId);try{let c={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()},d=e.external,u=[...d.acpArgs];a&&(t.QLOGICAGENT_PARENT_RPC=a);let p=Pc(d.cliPath,u,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!1});c.pid=p.pid??-1;let m=new Map,h=new _n,f=new Zo;this.processes.set(e.memberId,{handle:c,child:p,pendingRpc:m,acpAdapter:h,usageTracker:f,ipcServer:i,ipcPath:a,stderrStream:l,runtimeRestartCount:o}),h.attach(p,(k,x)=>{k==="usage_update"&&f.onUsageUpdate(x);let I=_n.translateNotification(k,x);I?(this.captureChildProgress(e.memberId,I.method,I.params),this.callbacks.onNotification?.(e.memberId,I.method,I.params)):(this.captureChildProgress(e.memberId,k,x),this.callbacks.onNotification?.(e.memberId,k,x))}),p.stderr&&Cs({input:p.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",x=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${x}`),l?.write(`${new Date().toISOString()} ${x}
621
- `)}),p.on("exit",(k,x)=>{h.detach();let I=c.state;if(I!=="killed"&&I!=="completed"&&k!==0){let O=this.processes.get(e.memberId)?.runtimeRestartCount??o;if(O<Qn){let $=Vg*2**O;this.slog("warn",e.memberId,"crash",`crashed again (code=${k}), restart ${O+1}/${Qn}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${k}), restarting`,retriesLeft:Qn-O-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,t,O+1).catch(W=>{this.slog("warn",e.memberId,"restart",`failed: ${W instanceof Error?W.message:String(W)}`)})},$);return}}I!=="killed"&&(c.state=k===0?"completed":"failed"),c.endedAt=Date.now(),k!==0&&!c.error&&(c.error=`ACP process exited with code ${k} (signal: ${x})`),this.callbacks.onStateChange?.(e.memberId,c.state),this.callbacks.onExit?.(e.memberId,k,x)}),p.on("error",k=>{h.detach(),c.state="failed",c.error=k.message,c.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let y=await h.initialize(p);c.state="ready",c.supportsResume=y.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${o}, protocol=${y.protocolVersion}, loadSession=${c.supportsResume}, pid=${c.pid})`);let b=[...e.mcpServers??[]];a&&b.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(c.supportsResume&&c.sessionId){let k=await h.resumeSession(p,c.sessionId,{cwd:e.cwd,mcpServers:b.length>0?b:void 0});c.sessionId=k.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${c.sessionId})`)}else{let k={cwd:e.cwd};b.length>0&&(k.mcpServers=b),e.systemPrompt&&(k.systemPrompt=e.systemPrompt);let x=await h.createSession(p,k);c.sessionId=x.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${c.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,k=>{this.slog("warn",k,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(k,"agents.error",{agentId:k,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(k)})}catch(c){let d=this.processes.get(e.memberId);d&&(d.handle.state="failed",d.handle.error=`Runtime restart failed: ${c instanceof Error?c.message:String(c)}`,d.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${o} attempts: ${c instanceof Error?c.message:String(c)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,t){this.stopHeartbeat(e),this.missedBeats.set(e,0);let o=setInterval(async()=>{let r=this.processes.get(e);if(!r||r.handle.state==="completed"||r.handle.state==="failed"||r.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let i=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,i),this.slog("warn",e,"heartbeat",`missed (${i}/${n.MAX_MISSED_BEATS})`),i>=n.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),r.handle.error=`Hang detected: ${i} consecutive heartbeat failures`,this.kill(e),t?.(e))},n.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,o)}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let t=this.processes.get(e);t&&(this.stopHeartbeat(e),(t.handle.state==="running"||t.handle.state==="starting"||t.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};le();import{join as zg}from"node:path";import{chmod as PI}from"node:fs/promises";import{readFile as vI,writeFile as SI,mkdir as TI,rename as wI,unlink as xI}from"node:fs/promises";import{dirname as RI,join as _I}from"node:path";import{randomUUID as AI}from"node:crypto";async function Zn(n,e){let t=RI(n);await TI(t,{recursive:!0});let o=_I(t,`.tmp-${AI()}`);try{await SI(o,e,"utf-8");let r;for(let s=0;s<3;s++)try{await wI(o,n);return}catch(i){if(r=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw r}catch(r){throw await xI(o).catch(()=>{}),r}}async function An(n){try{let e=await vI(n,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function eo(n,e){await Zn(n,JSON.stringify(e,null,2)+`
622
- `)}var qg="agent-configs.json";function Kg(){return zg(H(),qg)}function II(n){return zg(Oe(n),qg)}function CI(){return{agents:{}}}var Es=class{data=CI();cwd;constructor(e){this.cwd=e}async load(){let e=await An(Kg()),t=this.cwd?await An(II(this.cwd)):void 0,o={gatewayUrl:e?.gatewayUrl,agents:{...e?.agents},customAgents:{...e?.customAgents}};if(t){t.gatewayUrl&&(o.gatewayUrl=t.gatewayUrl);for(let[r,s]of Object.entries(t.agents??{}))o.agents[r]={...o.agents[r],...s};for(let[r,s]of Object.entries(t.customAgents??{}))o.customAgents??={},o.customAgents[r]=s}this.data=o}getData(){return this.data}getAgentConfig(e){return this.data.agents[e]??null}async setAgentConfig(e,t){this.data.agents[e]={...this.data.agents[e],...t},await this.save()}async removeAgentConfig(e){delete this.data.agents[e],await this.save()}getGatewayUrl(){return this.data.gatewayUrl}async setGatewayUrl(e){this.data.gatewayUrl=e,await this.save()}registerCustomAgent(e){this.data.customAgents??={},this.data.customAgents[e.id]=e}unregisterCustomAgent(e){this.data.customAgents&&delete this.data.customAgents[e]}getCustomAgents(){return{...this.data.customAgents}}async save(){let e=Kg();await eo(e,this.data);try{await PI(e,384)}catch{}}};var Yg="memory",Xg="Memory",EI=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],Jg={type:"object",properties:{action:{type:"string",enum:EI,description:["Operation to perform:","","INDEX.md operations (project-level notes, always visible in system prompt):","\xB7 'add' \u2014 Append a note to INDEX.md","\xB7 'replace' \u2014 Replace text in INDEX.md (str_replace semantics)","\xB7 'remove' \u2014 Remove text from INDEX.md","","Topic file operations (project-level, on-demand, for longer content):","\xB7 'create_file' \u2014 Create a new .md topic file","\xB7 'write_file' \u2014 Overwrite an existing topic file","\xB7 'read_file' \u2014 Read a topic file","\xB7 'delete_file' \u2014 Delete a topic file","\xB7 'list_files' \u2014 List all memory topic files","","Long-term memory (user-level, persists across projects):","\xB7 'remember' \u2014 Store a fact/preference/lesson to long-term memory (semantic search)","\xB7 'search' \u2014 Search long-term memory + local keyword match","\xB7 'temporal' \u2014 Query memories by time range ('what happened last week')","","Feedback:","\xB7 'feedback' \u2014 Mark memories as useful/irrelevant/outdated/wrong"].join(`
621
+ `)}),p.on("exit",(k,x)=>{h.detach();let I=c.state;if(I!=="killed"&&I!=="completed"&&k!==0){let O=this.processes.get(e.memberId)?.runtimeRestartCount??o;if(O<Qn){let $=Vg*2**O;this.slog("warn",e.memberId,"crash",`crashed again (code=${k}), restart ${O+1}/${Qn}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${k}), restarting`,retriesLeft:Qn-O-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,t,O+1).catch(W=>{this.slog("warn",e.memberId,"restart",`failed: ${W instanceof Error?W.message:String(W)}`)})},$);return}}I!=="killed"&&(c.state=k===0?"completed":"failed"),c.endedAt=Date.now(),k!==0&&!c.error&&(c.error=`ACP process exited with code ${k} (signal: ${x})`),this.callbacks.onStateChange?.(e.memberId,c.state),this.callbacks.onExit?.(e.memberId,k,x)}),p.on("error",k=>{h.detach(),c.state="failed",c.error=k.message,c.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let y=await h.initialize(p);c.state="ready",c.supportsResume=y.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${o}, protocol=${y.protocolVersion}, loadSession=${c.supportsResume}, pid=${c.pid})`);let b=[...e.mcpServers??[]];a&&b.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(c.supportsResume&&c.sessionId){let k=await h.resumeSession(p,c.sessionId,{cwd:e.cwd,mcpServers:b.length>0?b:void 0});c.sessionId=k.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${c.sessionId})`)}else{let k={cwd:e.cwd};b.length>0&&(k.mcpServers=b),e.systemPrompt&&(k.systemPrompt=e.systemPrompt);let x=await h.createSession(p,k);c.sessionId=x.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${c.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,k=>{this.slog("warn",k,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(k,"agents.error",{agentId:k,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(k)})}catch(c){let d=this.processes.get(e.memberId);d&&(d.handle.state="failed",d.handle.error=`Runtime restart failed: ${c instanceof Error?c.message:String(c)}`,d.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${o} attempts: ${c instanceof Error?c.message:String(c)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,t){this.stopHeartbeat(e),this.missedBeats.set(e,0);let o=setInterval(async()=>{let r=this.processes.get(e);if(!r||r.handle.state==="completed"||r.handle.state==="failed"||r.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let i=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,i),this.slog("warn",e,"heartbeat",`missed (${i}/${n.MAX_MISSED_BEATS})`),i>=n.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),r.handle.error=`Hang detected: ${i} consecutive heartbeat failures`,this.kill(e),t?.(e))},n.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,o)}stopHeartbeat(e){let t=this.heartbeatTimers.get(e);t&&(clearInterval(t),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let t=this.processes.get(e);t&&(this.stopHeartbeat(e),(t.handle.state==="running"||t.handle.state==="starting"||t.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};le();import{join as zg}from"node:path";import{chmod as CI}from"node:fs/promises";import{readFile as TI,writeFile as wI,mkdir as xI,rename as RI,unlink as _I}from"node:fs/promises";import{dirname as AI,join as PI}from"node:path";import{randomUUID as II}from"node:crypto";async function Zn(n,e){let t=AI(n);await xI(t,{recursive:!0});let o=PI(t,`.tmp-${II()}`);try{await wI(o,e,"utf-8");let r;for(let s=0;s<3;s++)try{await RI(o,n);return}catch(i){if(r=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw r}catch(r){throw await _I(o).catch(()=>{}),r}}async function An(n){try{let e=await TI(n,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function eo(n,e){await Zn(n,JSON.stringify(e,null,2)+`
622
+ `)}var qg="agent-configs.json";function Kg(){return zg(H(),qg)}function EI(n){return zg(Oe(n),qg)}function MI(){return{agents:{}}}var Es=class{data=MI();cwd;constructor(e){this.cwd=e}async load(){let e=await An(Kg()),t=this.cwd?await An(EI(this.cwd)):void 0,o={gatewayUrl:e?.gatewayUrl,agents:{...e?.agents},customAgents:{...e?.customAgents}};if(t){t.gatewayUrl&&(o.gatewayUrl=t.gatewayUrl);for(let[r,s]of Object.entries(t.agents??{}))o.agents[r]={...o.agents[r],...s};for(let[r,s]of Object.entries(t.customAgents??{}))o.customAgents??={},o.customAgents[r]=s}this.data=o}getData(){return this.data}getAgentConfig(e){return this.data.agents[e]??null}async setAgentConfig(e,t){this.data.agents[e]={...this.data.agents[e],...t},await this.save()}async removeAgentConfig(e){delete this.data.agents[e],await this.save()}getGatewayUrl(){return this.data.gatewayUrl}async setGatewayUrl(e){this.data.gatewayUrl=e,await this.save()}registerCustomAgent(e){this.data.customAgents??={},this.data.customAgents[e.id]=e}unregisterCustomAgent(e){this.data.customAgents&&delete this.data.customAgents[e]}getCustomAgents(){return{...this.data.customAgents}}async save(){let e=Kg();await eo(e,this.data);try{await CI(e,384)}catch{}}};var Yg="memory",Xg="Memory",OI=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],Jg={type:"object",properties:{action:{type:"string",enum:OI,description:["Operation to perform:","","INDEX.md operations (project-level notes, always visible in system prompt):","\xB7 'add' \u2014 Append a note to INDEX.md","\xB7 'replace' \u2014 Replace text in INDEX.md (str_replace semantics)","\xB7 'remove' \u2014 Remove text from INDEX.md","","Topic file operations (project-level, on-demand, for longer content):","\xB7 'create_file' \u2014 Create a new .md topic file","\xB7 'write_file' \u2014 Overwrite an existing topic file","\xB7 'read_file' \u2014 Read a topic file","\xB7 'delete_file' \u2014 Delete a topic file","\xB7 'list_files' \u2014 List all memory topic files","","Long-term memory (user-level, persists across projects):","\xB7 'remember' \u2014 Store a fact/preference/lesson to long-term memory (semantic search)","\xB7 'search' \u2014 Search long-term memory + local keyword match","\xB7 'temporal' \u2014 Query memories by time range ('what happened last week')","","Feedback:","\xB7 'feedback' \u2014 Mark memories as useful/irrelevant/outdated/wrong"].join(`
623
623
  `)},content:{type:"string",description:["Content for add/replace/create_file/write_file.","For INDEX.md notes: write concise, factual statements.","For topic files: can be longer (up to 8KB), use markdown formatting."].join(`
624
624
  `)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search'/'temporal': natural language query to find relevant memories."},days:{type:"number",description:"For 'temporal': look back N days from today (default: 7)."},memory_ids:{type:"array",items:{type:"string"},description:"For 'feedback': IDs of memories to give feedback on."},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"For 'feedback': the feedback signal to apply."},category:{type:"string",enum:["preference","personal_fact","lesson","pattern","decision","context"],description:"For 'remember': categorize the memory (helps with future recall precision)."}},required:["action"]},Qg=["Manage persistent memory across sessions. Two distinct systems with clear roles:","","## Project memory (INDEX.md + topic files)","Scope: current project / workspace. Visible every turn.","Use for: architecture decisions, file conventions, build commands, known issues, task logs.","Actions: add, replace, remove, create_file, write_file, read_file, delete_file, list_files.","","## Long-term memory (QMemory)","Scope: user-level, persists across all projects. Searched on demand.","Use for: user preferences, personal facts, recurring lessons, communication style, past insights.","Actions: remember, search, temporal, feedback.","","## When to store (guidelines):","- User explicitly says 'remember this' or 'note that' \u2192 store immediately","- User states a preference (style, format, tools, habits) \u2192 remember (long-term)","- Project-specific decision or fact \u2192 add/create_file (project memory)","- A debugging lesson or insight that applies broadly \u2192 remember (long-term)","- DO NOT store: trivial/obvious info, one-off questions, transient state","- DO NOT store: information the user did not share or confirm","","## When to recall:","- Use 'search' when you suspect relevant past context exists for the current task","- Use 'temporal' to find what happened in a specific time period","- Memory is auto-recalled each turn \u2014 manual search is for deeper queries"].join(`
625
- `),MI=[/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 OI(n){return!MI.some(e=>e.test(n))}async function Zg(n,e){let{action:t}=n,{memdir:o}=e;if(t==="add"){let r=n.content?.trim();if(!r)return{ok:!1,message:"content is required for 'add'.",action:t};let s=await o.addToIndex(r);return{ok:s.ok,message:s.message,action:t}}if(t==="replace"){let r=n.old_text?.trim(),s=n.new_text?.trim()||n.content?.trim();if(!r)return{ok:!1,message:"old_text is required for 'replace'.",action:t};if(!s)return{ok:!1,message:"new_text (or content) is required for 'replace'.",action:t};let i=await o.replaceInIndex(r,s);return{ok:i.ok,message:i.message,action:t}}if(t==="remove"){let r=n.old_text?.trim();if(!r)return{ok:!1,message:"old_text is required for 'remove'.",action:t};let s=await o.removeFromIndex(r);return{ok:s.ok,message:s.message,action:t}}if(t==="create_file"){let r=n.file?.trim(),s=n.content?.trim();if(!r)return{ok:!1,message:"file is required for 'create_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'create_file'.",action:t};let i=await o.createFile(r,s);return{ok:i.ok,message:i.message,action:t}}if(t==="write_file"){let r=n.file?.trim(),s=n.content?.trim();if(!r)return{ok:!1,message:"file is required for 'write_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'write_file'.",action:t};let i=await o.writeFile(r,s);return{ok:i.ok,message:i.message,action:t}}if(t==="read_file"){let r=n.file?.trim();if(!r)return{ok:!1,message:"file is required for 'read_file'.",action:t};let s=await o.readFile(r);return s.ok?{ok:!0,message:s.content,action:t}:{ok:!1,message:s.message,action:t}}if(t==="delete_file"){let r=n.file?.trim();if(!r)return{ok:!1,message:"file is required for 'delete_file'.",action:t};let s=await o.deleteFile(r);return{ok:s.ok,message:s.message,action:t}}if(t==="list_files"){let r=await o.listFiles();if(r.length===0)return{ok:!0,message:"No topic files yet. Use 'create_file' to create one.",action:t};let s=r.map(i=>{let a=(i.size/1024).toFixed(1),l=i.modifiedAt.slice(0,10);return`--${i.name} (${a}KB, ${l})${i.preview?""+i.preview:""}`}).join(`
625
+ `),DI=[/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 LI(n){return!DI.some(e=>e.test(n))}async function Zg(n,e){let{action:t}=n,{memdir:o}=e;if(t==="add"){let r=n.content?.trim();if(!r)return{ok:!1,message:"content is required for 'add'.",action:t};let s=await o.addToIndex(r);return{ok:s.ok,message:s.message,action:t}}if(t==="replace"){let r=n.old_text?.trim(),s=n.new_text?.trim()||n.content?.trim();if(!r)return{ok:!1,message:"old_text is required for 'replace'.",action:t};if(!s)return{ok:!1,message:"new_text (or content) is required for 'replace'.",action:t};let i=await o.replaceInIndex(r,s);return{ok:i.ok,message:i.message,action:t}}if(t==="remove"){let r=n.old_text?.trim();if(!r)return{ok:!1,message:"old_text is required for 'remove'.",action:t};let s=await o.removeFromIndex(r);return{ok:s.ok,message:s.message,action:t}}if(t==="create_file"){let r=n.file?.trim(),s=n.content?.trim();if(!r)return{ok:!1,message:"file is required for 'create_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'create_file'.",action:t};let i=await o.createFile(r,s);return{ok:i.ok,message:i.message,action:t}}if(t==="write_file"){let r=n.file?.trim(),s=n.content?.trim();if(!r)return{ok:!1,message:"file is required for 'write_file'.",action:t};if(!s)return{ok:!1,message:"content is required for 'write_file'.",action:t};let i=await o.writeFile(r,s);return{ok:i.ok,message:i.message,action:t}}if(t==="read_file"){let r=n.file?.trim();if(!r)return{ok:!1,message:"file is required for 'read_file'.",action:t};let s=await o.readFile(r);return s.ok?{ok:!0,message:s.content,action:t}:{ok:!1,message:s.message,action:t}}if(t==="delete_file"){let r=n.file?.trim();if(!r)return{ok:!1,message:"file is required for 'delete_file'.",action:t};let s=await o.deleteFile(r);return{ok:s.ok,message:s.message,action:t}}if(t==="list_files"){let r=await o.listFiles();if(r.length===0)return{ok:!0,message:"No topic files yet. Use 'create_file' to create one.",action:t};let s=r.map(i=>{let a=(i.size/1024).toFixed(1),l=i.modifiedAt.slice(0,10);return`--${i.name} (${a}KB, ${l})${i.preview?""+i.preview:""}`}).join(`
626
626
  `);return{ok:!0,message:`Memory files (${r.length}):
627
627
  ${s}`,action:t}}if(t==="search"){let r=n.query?.trim();if(!r)return{ok:!1,message:"query is required for 'search'.",action:t};let s=[],i;try{let a=await o.searchLocal(r);a.length>0&&s.push(`## Local Memory
628
628
  `+a.map(l=>`--[${l.file}] ${l.snippet}`).join(`
@@ -630,8 +630,8 @@ ${s}`,action:t}}if(t==="search"){let r=n.query?.trim();if(!r)return{ok:!1,messag
630
630
  `+a.map((l,c)=>`${c+1}. ${l.text}`).join(`
631
631
  `))}catch{}return s.length===0?{ok:!0,message:"No matching memories found.",action:t,results:[]}:{ok:!0,message:s.join(`
632
632
 
633
- `),action:t,results:i}}if(t==="remember"){if(!e.localProvider)return{ok:!1,message:"Long-term memory requires local memory provider.",action:t};let r=n.content?.trim();if(!r)return{ok:!1,message:"content is required for 'remember'.",action:t};if(!OI(r))return{ok:!1,message:"Content blocked by safety filter.",action:t};if(r.length<10)return{ok:!1,message:"Memory too short \u2014 provide a meaningful fact or insight (\u226510 chars).",action:t};if(r.length>2e3)return{ok:!1,message:"Memory too long (max 2000 chars). Condense the insight.",action:t};try{return await e.localProvider.addText(r,e.userId,{source:"agent-remember",category:n.category??"lesson",importance:.7}),{ok:!0,message:`Stored to long-term memory: "${r.slice(0,80)}${r.length>80?"...":""}"`,action:t}}catch(s){return{ok:!1,message:`Failed to store: ${s instanceof Error?s.message:String(s)}`,action:t}}}if(t==="temporal"){if(!e.localProvider)return{ok:!1,message:"Temporal query requires local memory provider.",action:t};let r=n.days??7,s=Date.now()-r*864e5;return{ok:!0,message:e.localProvider.synthesizeTimeline(e.userId,s,Date.now()),action:t}}if(t==="feedback"){if(!e.localProvider)return{ok:!1,message:"Feedback requires local memory provider.",action:t};let r=n.memory_ids,s=n.signal;if(!r||r.length===0)return{ok:!1,message:"memory_ids is required for 'feedback'.",action:t};if(!s)return{ok:!1,message:"signal is required for 'feedback' (useful/irrelevant/outdated/wrong).",action:t};let i=await e.localProvider.feedback(r,s);return{ok:!0,message:`Feedback '${s}' applied to ${i.affected} memories.`,action:t}}return{ok:!1,message:`Unknown action: "${t}".`,action:t}}le();import{readFile as Cc,readdir as eh,unlink as DI,stat as LI,mkdir as NI}from"node:fs/promises";import{existsSync as bt,readFileSync as th,mkdirSync as nh,writeFileSync as $I}from"node:fs";import{join as st}from"node:path";var Ie=12288,Ec=200,Ms=8192,UI="memory",mn="INDEX.md";function Mc(n){return st(Oe(n),UI)}var jI=[/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 Os(n){return!jI.some(e=>e.test(n))}var FI=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function Ds(n){return!(!FI.test(n)||n===mn||n.includes("..")||n.includes("/")||n.includes("\\"))}var Nt=class{root;indexCache=null;constructor(e){this.root=Mc(e)}getRootPath(){return this.root}ensureInitialized(){bt(this.root)||nh(this.root,{recursive:!0});let e=st(this.root,mn);if(!bt(e)){let t=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt.>","<!-- Use memory tool to add notes, or create topic files for longer content.>","","## User Profile","","## Notes",""].join(`
634
- `);BI(e,t)}}getIndexForPrompt(){let e=st(this.root,mn);if(!bt(e))return"";let t;try{t=th(e,"utf-8")}catch{return""}this.indexCache=t;let o=t.split(`
633
+ `),action:t,results:i}}if(t==="remember"){if(!e.localProvider)return{ok:!1,message:"Long-term memory requires local memory provider.",action:t};let r=n.content?.trim();if(!r)return{ok:!1,message:"content is required for 'remember'.",action:t};if(!LI(r))return{ok:!1,message:"Content blocked by safety filter.",action:t};if(r.length<10)return{ok:!1,message:"Memory too short \u2014 provide a meaningful fact or insight (\u226510 chars).",action:t};if(r.length>2e3)return{ok:!1,message:"Memory too long (max 2000 chars). Condense the insight.",action:t};try{return await e.localProvider.addText(r,e.userId,{source:"agent-remember",category:n.category??"lesson",importance:.7}),{ok:!0,message:`Stored to long-term memory: "${r.slice(0,80)}${r.length>80?"...":""}"`,action:t}}catch(s){return{ok:!1,message:`Failed to store: ${s instanceof Error?s.message:String(s)}`,action:t}}}if(t==="temporal"){if(!e.localProvider)return{ok:!1,message:"Temporal query requires local memory provider.",action:t};let r=n.days??7,s=Date.now()-r*864e5;return{ok:!0,message:e.localProvider.synthesizeTimeline(e.userId,s,Date.now()),action:t}}if(t==="feedback"){if(!e.localProvider)return{ok:!1,message:"Feedback requires local memory provider.",action:t};let r=n.memory_ids,s=n.signal;if(!r||r.length===0)return{ok:!1,message:"memory_ids is required for 'feedback'.",action:t};if(!s)return{ok:!1,message:"signal is required for 'feedback' (useful/irrelevant/outdated/wrong).",action:t};let i=await e.localProvider.feedback(r,s);return{ok:!0,message:`Feedback '${s}' applied to ${i.affected} memories.`,action:t}}return{ok:!1,message:`Unknown action: "${t}".`,action:t}}le();import{readFile as Cc,readdir as eh,unlink as NI,stat as $I,mkdir as UI}from"node:fs/promises";import{existsSync as bt,readFileSync as th,mkdirSync as nh,writeFileSync as jI}from"node:fs";import{join as st}from"node:path";var Ie=12288,Ec=200,Ms=8192,FI="memory",mn="INDEX.md";function Mc(n){return st(Oe(n),FI)}var BI=[/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 Os(n){return!BI.some(e=>e.test(n))}var WI=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function Ds(n){return!(!WI.test(n)||n===mn||n.includes("..")||n.includes("/")||n.includes("\\"))}var Nt=class{root;indexCache=null;constructor(e){this.root=Mc(e)}getRootPath(){return this.root}ensureInitialized(){bt(this.root)||nh(this.root,{recursive:!0});let e=st(this.root,mn);if(!bt(e)){let t=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt.>","<!-- Use memory tool to add notes, or create topic files for longer content.>","","## User Profile","","## Notes",""].join(`
634
+ `);GI(e,t)}}getIndexForPrompt(){let e=st(this.root,mn);if(!bt(e))return"";let t;try{t=th(e,"utf-8")}catch{return""}this.indexCache=t;let o=t.split(`
635
635
  `);return o.length>Ec&&(t=o.slice(0,Ec).join(`
636
636
  `)+`
637
637
 
@@ -652,24 +652,24 @@ ${s}`,action:t}}if(t==="search"){let r=n.query?.trim();if(!r)return{ok:!1,messag
652
652
  `+t+`
653
653
  `;return Buffer.byteLength(p,"utf-8")<=Ie?p:null}async replaceInIndex(e,t){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};if(!t.trim())return{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."};if(!Os(t))return{ok:!1,message:"Content rejected: potential injection detected."};let o=this.getIndexRaw(),r=o.split(e).length-1;if(r===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(r>1)return{ok:!1,message:`Multiple matches (${r}) for: "${e.slice(0,80)}". Be more specific.`};let s=o.replace(e,t);if(Buffer.byteLength(s,"utf-8")>Ie)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${Buffer.byteLength(s,"utf-8")}/${Ie} bytes).`};await this.writeIndex(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${Ie} chars]`,indexUsage:`${i.chars}/${Ie}`}}async removeFromIndex(e){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};let t=this.getIndexRaw();if(!t.includes(e))return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};let o=t.replace(e,"");o=o.replace(/\n{3,}/g,`
654
654
 
655
- `),await this.writeIndex(o);let r=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${r.chars}/${Ie} chars]`,indexUsage:`${r.chars}/${Ie}`}}async listFiles(){if(!bt(this.root))return[];let e=await eh(this.root),t=[];for(let o of e){if(o===mn||!o.endsWith(".md"))continue;let r=st(this.root,o);try{let s=await LI(r);if(!s.isFile())continue;let a=(await Cc(r,"utf-8")).split(`
655
+ `),await this.writeIndex(o);let r=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${r.chars}/${Ie} chars]`,indexUsage:`${r.chars}/${Ie}`}}async listFiles(){if(!bt(this.root))return[];let e=await eh(this.root),t=[];for(let o of e){if(o===mn||!o.endsWith(".md"))continue;let r=st(this.root,o);try{let s=await $I(r);if(!s.isFile())continue;let a=(await Cc(r,"utf-8")).split(`
656
656
  `).find(l=>l.trim()&&!l.startsWith("#"))?.trim();t.push({name:o,size:s.size,modifiedAt:s.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return t.sort((o,r)=>r.modifiedAt.localeCompare(o.modifiedAt))}async createFile(e,t){if(!Ds(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!Os(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>Ms)return{ok:!1,message:`Content too long (${t.length} chars, max ${Ms}).`};let o=st(this.root,e);if(bt(o))return{ok:!1,message:`File already exists: "${e}". Use write_file to update.`};await this.ensureDir(),await Zn(o,t);let r=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return await this.appendIndexEntry(r),{ok:!0,message:`Created "${e}" (${t.length} chars). Entry added to INDEX.md.`,file:e}}async writeFile(e,t){if(!Ds(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files.`};if(!Os(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>Ms)return this.writeFileSplit(e,t);let o=st(this.root,e),r=!bt(o);if(await this.ensureDir(),await Zn(o,t),r){let s=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(s)}return{ok:!0,message:`${r?"Created":"Updated"} "${e}" (${t.length} chars).`,file:e}}async writeFileSplit(e,t){let o=e.replace(/\.md$/,""),r=t.split(/\n{2,}/),s=[],i="";for(let c of r)i.length+c.length+2>Ms*.9&&i.length>0?(s.push(i),i=c):i=i?i+`
657
657
 
658
- `+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let d=`${o}-${c+1}.md`,u=st(this.root,d);await this.ensureDir(),await Zn(u,s[c]),a.push(d)}let l=this.getIndexRaw();for(let c of a)if(!l.includes(`[${c}]`)){let d=`- [${c}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(d)}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${t.length} chars total): ${a.join(", ")}`,file:a[0]}}async readFile(e){if(!Ds(e)&&e!==mn)return{ok:!1,message:`Invalid filename: "${e}".`};let t=st(this.root,e);try{let o=await Cc(t,"utf-8");return{ok:!0,content:o,message:`Read "${e}" (${o.length} chars).`}}catch(o){return o.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${o.message}`}}}async deleteFile(e){if(e===mn)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!Ds(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=st(this.root,e);if(!bt(t))return{ok:!1,message:`File not found: "${e}".`};await DI(t);let o=this.getIndexRaw(),r=new RegExp(`^.*\\[${WI(e)}\\].*$\\n?`,"m");if(r.test(o)){let s=o.replace(r,"").replace(/\n{3,}/g,`
658
+ `+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let d=`${o}-${c+1}.md`,u=st(this.root,d);await this.ensureDir(),await Zn(u,s[c]),a.push(d)}let l=this.getIndexRaw();for(let c of a)if(!l.includes(`[${c}]`)){let d=`- [${c}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(d)}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${t.length} chars total): ${a.join(", ")}`,file:a[0]}}async readFile(e){if(!Ds(e)&&e!==mn)return{ok:!1,message:`Invalid filename: "${e}".`};let t=st(this.root,e);try{let o=await Cc(t,"utf-8");return{ok:!0,content:o,message:`Read "${e}" (${o.length} chars).`}}catch(o){return o.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${o.message}`}}}async deleteFile(e){if(e===mn)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!Ds(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=st(this.root,e);if(!bt(t))return{ok:!1,message:`File not found: "${e}".`};await NI(t);let o=this.getIndexRaw(),r=new RegExp(`^.*\\[${HI(e)}\\].*$\\n?`,"m");if(r.test(o)){let s=o.replace(r,"").replace(/\n{3,}/g,`
659
659
 
660
660
  `);await this.writeIndex(s)}return{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}}async searchLocal(e){if(!bt(this.root))return[];let t=e.toLowerCase().split(/\s+/).filter(s=>s.length>1);if(t.length===0)return[];let o=await eh(this.root),r=[];for(let s of o){if(!s.endsWith(".md"))continue;let i=st(this.root,s);try{let a=await Cc(i,"utf-8"),l=a.toLowerCase(),c=t.filter(m=>l.includes(m)).length;if(c===0)continue;let d=a.split(`
661
- `),u="",p=0;for(let m of d){let h=m.toLowerCase(),f=t.filter(y=>h.includes(y)).length;f>p&&(p=f,u=m.trim())}r.push({file:s,snippet:u.slice(0,200),score:c/t.length})}catch{}}return r.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await this.ensureDir(),await Zn(st(this.root,mn),e),this.indexCache=e}async ensureDir(){bt(this.root)||await NI(this.root,{recursive:!0})}async appendIndexEntry(e){let t=this.getIndexRaw();if(t.includes(e))return;let o=t.endsWith(`
661
+ `),u="",p=0;for(let m of d){let h=m.toLowerCase(),f=t.filter(y=>h.includes(y)).length;f>p&&(p=f,u=m.trim())}r.push({file:s,snippet:u.slice(0,200),score:c/t.length})}catch{}}return r.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await this.ensureDir(),await Zn(st(this.root,mn),e),this.indexCache=e}async ensureDir(){bt(this.root)||await UI(this.root,{recursive:!0})}async appendIndexEntry(e){let t=this.getIndexRaw();if(t.includes(e))return;let o=t.endsWith(`
662
662
  `)?t+e+`
663
663
  `:t+`
664
664
  `+e+`
665
- `;Buffer.byteLength(o,"utf-8")<=Ie&&await this.writeIndex(o)}};function BI(n,e){let t=st(n,"..");bt(t)||nh(t,{recursive:!0}),$I(n,e,"utf-8")}function WI(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oh(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function GI(n){return n.latestInputTokens+n.cumulativeOutputTokens}var HI=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),rh=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function VI(n){return{isSearch:HI.has(n)||void 0,isRead:rh.has(n)||void 0}}function KI(n,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${rh.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 sh(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 ih(n,e,t,o){n.toolUseCount++;let r=VI(e),s={toolName:e,input:t,activityDescription:o?.(e,t)??KI(e,t),isSearch:r.isSearch,isRead:r.isRead};for(n.recentActivities.push(s);n.recentActivities.length>5;)n.recentActivities.shift()}function Oc(n){return{toolUseCount:n.toolUseCount,tokenCount:GI(n),lastActivity:n.recentActivities.length>0?n.recentActivities[n.recentActivities.length-1]:void 0,recentActivities:[...n.recentActivities]}}import{randomUUID as ah}from"node:crypto";function zI(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 Dc(n){let e=Date.now(),t=[],o={inputTokens:0,outputTokens:0},r=oh(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:c,toolInvoker:d,apiKey:u,model:p,log:m,hooks:h,forkLabel:f,maxTurns:y,temperature:b,parentSignal:k,onEvent:x,onProgress:I,budgetTokens:P,parentDepth:O}=n,$=zI(k),W=`fork-${f}-${ah().slice(0,8)}`,S=`fork-session-${ah().slice(0,8)}`;m.info(`[fork:${f}] starting \u2014 ${s.length} initial messages, model=${p}`);let ce=l?{invoke:async(ie,Ue,ne,Q)=>{let T={};try{T=JSON.parse(ne)}catch{}let F=l(Ue,T);return F.allowed?d.invoke(ie,Ue,ne,Q):(m.info(`[fork:${f}] tool ${Ue} denied: ${F.reason}`),{result:"",error:F.reason})}}:d,de=!0,j;try{let{Agent:ie}=await Promise.resolve().then(()=>(Yr(),Cp)),Ue=new ie({llmTransport:c,apiKey:u,toolInvoker:ce,log:m,hooks:h,maxRounds:y});for await(let ne of Ue.run({turnId:W,sessionId:S,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:u,temperature:b,maxOutputTokens:n.maxOutputTokens,parentDepth:O}},$.signal)){if(t.push(ne),x?.(ne),ne.type==="end"&&ne.usage&&(sh(r,{input_tokens:ne.usage.inputTokens,output_tokens:ne.usage.outputTokens}),o.inputTokens+=ne.usage.inputTokens,o.outputTokens+=ne.usage.outputTokens,ne.usage.cacheRead&&(o.cacheRead=(o.cacheRead??0)+ne.usage.cacheRead),ne.usage.cacheWrite&&(o.cacheWrite=(o.cacheWrite??0)+ne.usage.cacheWrite),P&&P>0)){let Q=o.inputTokens+o.outputTokens+(o.reasoningTokens??0);Q>=P&&(m.info(`[fork:${f}] budget exceeded (${Q} / ${P} tokens), aborting`),$.abort("budget_exceeded"))}if(ne.type==="tool_call"){let Q={};try{Q=JSON.parse(ne.arguments??"{}")}catch{}ih(r,ne.name,Q),I?.(Oc(r))}ne.type==="error"&&(de=!1,j=ne.error)}}catch(ie){de=!1,j=ie instanceof Error?ie.message:String(ie),m.warn(`[fork:${f}] error: ${j}`)}finally{$.signal.aborted||$.abort("fork_complete")}let ve=Date.now()-e;return m.info(`[fork:${f}] finished in ${ve}ms \u2014 ${t.length} events, usage: prompt=${o.inputTokens} completion=${o.outputTokens}, ok=${de}`),{events:t,totalUsage:o,progress:Oc(r),durationMs:ve,ok:de,error:j}}Pa();_a();je();var Lc=class{teamBudget={tokensUsed:0,budgetTokens:Ji};isTeamBudgetExceeded(){return this.teamBudget.budgetTokens>0&&this.teamBudget.tokensUsed>=this.teamBudget.budgetTokens}recordForkTokens(e){return this.teamBudget.tokensUsed+=e,this.teamBudget.tokensUsed}teamBudgetExceededError(){return`Team budget exceeded (${this.teamBudget.tokensUsed} / ${this.teamBudget.budgetTokens} tokens). No more sub-agents allowed.`}dream={idleMinutes:30,enabled:!1,lastDreamAt:0,cooldownMs:14400*1e3,maxDurationMs:300*1e3};resetAccumulators(){this.teamBudget.tokensUsed=0}},we=new Lc;le();import{readFile as qI}from"node:fs/promises";import{watch as YI}from"node:fs";import{join as XI}from"node:path";var JI=He,QI="settings.json";function ZI(n){return XI(n,JI,QI)}async function eC(n){try{let e=await qI(n,"utf-8");return JSON.parse(e)}catch{return null}}function tC(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 lh(n){let e=ZI(n.projectRoot),t=null,o=null,r=async()=>{let s=await eC(e);s&&tC(s,n.ruleEngine,n.hooks,n.log)};r().catch(()=>{});try{t=YI(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 Nc=new Set;function Pn(n){return Nc.add(n),()=>{Nc.delete(n)}}async function ch(){await Promise.all(Array.from(Nc).map(n=>n()))}le();mt();var Ls="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",to=class extends Error{constructor(e=Ls){super(e),this.name="LlmrouterCatalogUnavailableError"}};function nC(){let n=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim().replace(/\/+$/,"");if(!n)throw new to;return n}function oC(){let n={accept:"application/json"},e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return e&&(n.authorization=`Bearer ${e}`),n}async function dh(n){let e=nC(),t;try{t=await fetch(`${e}${n}`,{method:"GET",headers:oC(),signal:AbortSignal.timeout(1e4)})}catch{throw new to}if(!t.ok)throw new to;let o=await t.json().catch(()=>null),r=Array.isArray(o)?o:lC(o)&&Array.isArray(o.data)?o.data:null;if(!r)throw new to;return r}async function Ns(){return dh("/ext/model-catalog/providers")}async function rC(){return dh("/ext/model-catalog/models")}function $c(n){let e={zhipu:"Zhipu GLM","zhipu-openai":"Zhipu GLM OpenAI","zhipu-coding":"Zhipu GLM Coding",volcengine:"Doubao / Volcengine"};return e[n.id]?e[n.id]:n.displayName??n.name??n.id}function $s(n){return n.baseUrl??n.base_url}async function Uc(n){return(await Ns()).find(t=>t.id===n)??null}async function tr(n){let e=await rC();n.migrateModelIds(sC(e));let t=e.map(iC).filter(o=>!!o);return n.replaceCatalogModels(t),t}function sC(n){let e=new Map;for(let t of n){let o=t.provider??t.owned_by,r=t.public_model??t.publicModel??t.id,s=t.native_model_id??t.nativeModelId??t.id;if(!o||!r||!s)continue;let i=`${o}:${r}`;for(let a of[s,t.id])!a||a===r||e.set(`${o}:${a}`,i)}return e}function iC(n){let e=n.provider??n.owned_by,t=n.public_model??n.publicModel??n.id,o=n.native_model_id??n.nativeModelId??n.id;return!e||!t||!o?null:{id:`${e}:${t}`,provider:e,model:t,displayName:n.display_name??n.displayName??n.name??n.id,purposes:aC(n.purposes,n.category),baseUrl:n.baseUrl??n.base_url,enabled:!0,nativeModelId:o,transport:n.provider_transport??n.providerTransport,contextWindow:n.context_window??n.contextWindow,maxOutput:n.max_output??n.maxOutput,streamRequired:n.stream_required??n.streamRequired,capabilities:n.capabilities,pricing:n.pricing}}function aC(n,e){let t=[...n??[],e].filter(s=>!!s),o=new Set(["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"]),r=t.filter(s=>o.has(s));return[...new Set(r.length?r:["textGeneration"])]}function lC(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}je();import{join as jc}from"node:path";import{mkdirSync as cC,existsSync as dC,createWriteStream as uC}from"node:fs";import{pipeline as pC}from"node:stream/promises";import{Readable as mC}from"node:stream";var fC=ra,gC=sa,uh={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/mp4":".m4a","audio/flac":".flac","application/pdf":".pdf","model/gltf-binary":".glb","model/gltf+json":".gltf"},Us=class{projectDir;maxFileSize;timeoutMs;constructor(e){this.projectDir=e?.projectDir??null,this.maxFileSize=e?.maxFileSize??fC,this.timeoutMs=e?.timeoutMs??gC}setProjectDir(e){this.projectDir=e}resolveMediaDir(e){if(!this.projectDir)throw new Error("MediaPersistence requires projectDir \u2014 call setProjectDir() first");if(!e)return jc(this.projectDir,".qlogicagent","media",hC());let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t!==e&&t.length>0&&[...e].filter(r=>!/[a-zA-Z0-9_-]/.test(r)).length>e.length/2&&console.warn(`[media-persistence] sessionId heavily sanitized: "${e}" \u2192 "${t}" \u2014 potential collision risk`),jc(this.projectDir,".qlogicagent","sessions",t,"media")}async download(e,t){let o=this.resolveMediaDir(t?.sessionId);if(o.length+60>255)throw new Error(`Media path too long (${o.length} chars) \u2014 would exceed OS limit. Use a shorter project path or session ID.`);dC(o)||cC(o,{recursive:!0});let r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs),i="";try{let a=await fetch(e,{signal:r.signal});if(!a.ok)throw new Error(`Download failed: ${a.status} ${a.statusText}`);let l=parseInt(a.headers.get("content-length")??"0",10);if(l>this.maxFileSize)throw new Error(`File too large: ${l} bytes (max: ${this.maxFileSize})`);let c=a.headers.get("content-type")?.split(";")[0].trim()||"application/octet-stream",d=bC(e,c),u=yC(t?.type??kC(c),d);i=jc(o,u);let p=a.body;if(!p)throw new Error("No response body");let m=uC(i);await pC(mC.fromWeb(p),m);let{size:h}=await import("node:fs/promises").then(f=>f.stat(i));if(h===0)throw await import("node:fs/promises").then(f=>f.unlink(i).catch(()=>{})),new Error("Download produced empty file (connection dropped)");return{remoteUrl:e,localPath:i,bytes:h,mimeType:c}}catch(a){if(i)try{let{unlink:l}=await import("node:fs/promises");await l(i)}catch{}throw a}finally{clearTimeout(s)}}async downloadAll(e,t,o){let r=[];for(let s of e)try{let i=await this.download(s,t);r.push(i)}catch(i){o?.warn(`media-persistence: failed to download ${s}: ${i.message}`)}return r}getMediaDir(e){return this.resolveMediaDir(e)}getProjectDir(){return this.projectDir}};function hC(){let n=new Date;return`${n.getFullYear()}${String(n.getMonth()+1).padStart(2,"0")}${String(n.getDate()).padStart(2,"0")}`}function yC(n,e){let t=new Date,o=`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}${String(t.getMinutes()).padStart(2,"0")}${String(t.getSeconds()).padStart(2,"0")}`,r=Math.random().toString(36).slice(2,6);return`${n}_${o}_${r}${e}`}function bC(n,e){if(uh[e])return uh[e];try{let t=new URL(n).pathname,o=t.lastIndexOf(".");if(o>0){let r=t.slice(o).toLowerCase().split("?")[0];if(r.length<=5)return r}}catch{}return".bin"}function kC(n){return n.startsWith("image/")?"image":n.startsWith("video/")?"video":n.startsWith("audio/")?"audio":n.startsWith("model/")?"3d":"file"}import{join as vC}from"node:path";import{readFileSync as SC,writeFileSync as TC,mkdirSync as wC}from"node:fs";var In=null,Fc=!1;function ph(n){return vC(n,"skill-stats.json")}function Bc(n){if(In)return In;try{In=JSON.parse(SC(ph(n),"utf8"))}catch{In={}}return In}function xC(n){if(!(!Fc||!In))try{wC(n,{recursive:!0}),TC(ph(n),JSON.stringify(In,null,2),"utf8"),Fc=!1}catch{}}function js(n,e,t){let o=Bc(n);o[e]||(o[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),o[e].invokeCount++,o[e].lastUsedAt=new Date().toISOString(),t?o[e].positiveCount++:o[e].negativeCount++,o[e].invokeCount>0&&(o[e].successRate=(o[e].invokeCount-o[e].negativeCount)/o[e].invokeCount),Fc=!0,xC(n)}function mh(n,e){return Bc(n)[e]}function fh(n){return Bc(n)}import{existsSync as RC,readFileSync as _C,writeFileSync as AC,mkdirSync as hh,renameSync as PC}from"node:fs";import{join as Wc,dirname as yh}from"node:path";var gh=30,IC=90,CC="skill-lifecycle.json";function bh(n){return Wc(n,CC)}function We(n){let e=bh(n);try{return JSON.parse(_C(e,"utf8"))}catch{return{version:1,records:{}}}}function Ve(n,e){let t=bh(n);hh(yh(t),{recursive:!0});let o=t+".tmp";AC(o,JSON.stringify(e,null,2),"utf8");let{renameSync:r}=gi("node:fs");r(o,t)}function Qt(n,e,t="learned"){return n.records[e]||(n.records[e]={name:e,state:"active",createdAt:new Date().toISOString(),pinned:!1,useCount:0,source:t}),n.records[e]}function Gc(n,e){let t=Qt(n,e);t.lastUsedAt=new Date().toISOString(),t.useCount++,t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function Hc(n,e){let t=Qt(n,e);t.lastPatchedAt=new Date().toISOString(),t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function kh(n,e){let t=n.records[e];return t?(t.pinned=!0,!0):!1}function vh(n,e){let t=n.records[e];return t?(t.pinned=!1,!0):!1}function EC(n){let e=[n.lastUsedAt,n.lastViewedAt,n.lastPatchedAt,n.createdAt].filter(Boolean).map(t=>new Date(t));return new Date(Math.max(...e.map(t=>t.getTime())))}function MC(n){let e=Date.now(),t={transitioned:[],skippedPinned:[]};for(let[o,r]of Object.entries(n.records)){if(r.source==="installed")continue;if(r.pinned){r.state!=="active"&&t.skippedPinned.push(o);continue}let s=EC(r),i=(e-s.getTime())/(1e3*60*60*24);r.state==="active"&&i>=gh?(r.state="stale",r.staleAt=new Date().toISOString(),t.transitioned.push({name:o,from:"active",to:"stale"})):r.state==="stale"&&i>=IC?(r.state="archived",r.archivedAt=new Date().toISOString(),t.transitioned.push({name:o,from:"stale",to:"archived"})):r.state==="stale"&&i<gh&&(r.state="active",r.staleAt=void 0,t.transitioned.push({name:o,from:"stale",to:"active"}))}return t}function OC(n,e){let t=Wc(n,e);if(!RC(t))return!1;let o=Wc(n,".archive",e);hh(yh(o),{recursive:!0});try{return PC(t,o),!0}catch{return!1}}function Sh(n,e){let t=We(n),o=MC(t);for(let r of o.transitioned)r.to==="archived"&&OC(e,r.name);return Ve(n,t),o}function Th(n,e){return Object.values(n.records).filter(t=>t.state===e)}function Fs(n,e){delete n.records[e]}function DC(n){let e=n.replace(/\r\n/g,`
665
+ `;Buffer.byteLength(o,"utf-8")<=Ie&&await this.writeIndex(o)}};function GI(n,e){let t=st(n,"..");bt(t)||nh(t,{recursive:!0}),jI(n,e,"utf-8")}function HI(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oh(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function VI(n){return n.latestInputTokens+n.cumulativeOutputTokens}var KI=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),rh=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function zI(n){return{isSearch:KI.has(n)||void 0,isRead:rh.has(n)||void 0}}function qI(n,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${rh.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 sh(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 ih(n,e,t,o){n.toolUseCount++;let r=zI(e),s={toolName:e,input:t,activityDescription:o?.(e,t)??qI(e,t),isSearch:r.isSearch,isRead:r.isRead};for(n.recentActivities.push(s);n.recentActivities.length>5;)n.recentActivities.shift()}function Oc(n){return{toolUseCount:n.toolUseCount,tokenCount:VI(n),lastActivity:n.recentActivities.length>0?n.recentActivities[n.recentActivities.length-1]:void 0,recentActivities:[...n.recentActivities]}}import{randomUUID as ah}from"node:crypto";function YI(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 Dc(n){let e=Date.now(),t=[],o={inputTokens:0,outputTokens:0},r=oh(),{promptMessages:s,systemPrompt:i,tools:a,canUseTool:l,transport:c,toolInvoker:d,apiKey:u,model:p,log:m,hooks:h,forkLabel:f,maxTurns:y,temperature:b,parentSignal:k,onEvent:x,onProgress:I,budgetTokens:P,parentDepth:O}=n,$=YI(k),W=`fork-${f}-${ah().slice(0,8)}`,S=`fork-session-${ah().slice(0,8)}`;m.info(`[fork:${f}] starting \u2014 ${s.length} initial messages, model=${p}`);let ce=l?{invoke:async(ie,Ue,ne,Q)=>{let T={};try{T=JSON.parse(ne)}catch{}let F=l(Ue,T);return F.allowed?d.invoke(ie,Ue,ne,Q):(m.info(`[fork:${f}] tool ${Ue} denied: ${F.reason}`),{result:"",error:F.reason})}}:d,de=!0,j;try{let{Agent:ie}=await Promise.resolve().then(()=>(Yr(),Cp)),Ue=new ie({llmTransport:c,apiKey:u,toolInvoker:ce,log:m,hooks:h,maxRounds:y});for await(let ne of Ue.run({turnId:W,sessionId:S,messages:s,tools:a,systemPrompt:i,config:{model:p,apiKey:u,temperature:b,maxOutputTokens:n.maxOutputTokens,parentDepth:O}},$.signal)){if(t.push(ne),x?.(ne),ne.type==="end"&&ne.usage&&(sh(r,{input_tokens:ne.usage.inputTokens,output_tokens:ne.usage.outputTokens}),o.inputTokens+=ne.usage.inputTokens,o.outputTokens+=ne.usage.outputTokens,ne.usage.cacheRead&&(o.cacheRead=(o.cacheRead??0)+ne.usage.cacheRead),ne.usage.cacheWrite&&(o.cacheWrite=(o.cacheWrite??0)+ne.usage.cacheWrite),P&&P>0)){let Q=o.inputTokens+o.outputTokens+(o.reasoningTokens??0);Q>=P&&(m.info(`[fork:${f}] budget exceeded (${Q} / ${P} tokens), aborting`),$.abort("budget_exceeded"))}if(ne.type==="tool_call"){let Q={};try{Q=JSON.parse(ne.arguments??"{}")}catch{}ih(r,ne.name,Q),I?.(Oc(r))}ne.type==="error"&&(de=!1,j=ne.error)}}catch(ie){de=!1,j=ie instanceof Error?ie.message:String(ie),m.warn(`[fork:${f}] error: ${j}`)}finally{$.signal.aborted||$.abort("fork_complete")}let ve=Date.now()-e;return m.info(`[fork:${f}] finished in ${ve}ms \u2014 ${t.length} events, usage: prompt=${o.inputTokens} completion=${o.outputTokens}, ok=${de}`),{events:t,totalUsage:o,progress:Oc(r),durationMs:ve,ok:de,error:j}}Pa();_a();je();var Lc=class{teamBudget={tokensUsed:0,budgetTokens:Ji};isTeamBudgetExceeded(){return this.teamBudget.budgetTokens>0&&this.teamBudget.tokensUsed>=this.teamBudget.budgetTokens}recordForkTokens(e){return this.teamBudget.tokensUsed+=e,this.teamBudget.tokensUsed}teamBudgetExceededError(){return`Team budget exceeded (${this.teamBudget.tokensUsed} / ${this.teamBudget.budgetTokens} tokens). No more sub-agents allowed.`}dream={idleMinutes:30,enabled:!1,lastDreamAt:0,cooldownMs:14400*1e3,maxDurationMs:300*1e3};resetAccumulators(){this.teamBudget.tokensUsed=0}},we=new Lc;le();import{readFile as XI}from"node:fs/promises";import{watch as JI}from"node:fs";import{join as QI}from"node:path";var ZI=He,eC="settings.json";function tC(n){return QI(n,ZI,eC)}async function nC(n){try{let e=await XI(n,"utf-8");return JSON.parse(e)}catch{return null}}function oC(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 lh(n){let e=tC(n.projectRoot),t=null,o=null,r=async()=>{let s=await nC(e);s&&oC(s,n.ruleEngine,n.hooks,n.log)};r().catch(()=>{});try{t=JI(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 Nc=new Set;function Pn(n){return Nc.add(n),()=>{Nc.delete(n)}}async function ch(){await Promise.all(Array.from(Nc).map(n=>n()))}le();mt();var Ls="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",to=class extends Error{constructor(e=Ls){super(e),this.name="LlmrouterCatalogUnavailableError"}};function rC(){let n=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim().replace(/\/+$/,"");if(!n)throw new to;return n}function sC(){let n={accept:"application/json"},e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return e&&(n.authorization=`Bearer ${e}`),n}async function dh(n){let e=rC(),t;try{t=await fetch(`${e}${n}`,{method:"GET",headers:sC(),signal:AbortSignal.timeout(1e4)})}catch{throw new to}if(!t.ok)throw new to;let o=await t.json().catch(()=>null),r=Array.isArray(o)?o:dC(o)&&Array.isArray(o.data)?o.data:null;if(!r)throw new to;return r}async function Ns(){return dh("/ext/model-catalog/providers")}async function iC(){return dh("/ext/model-catalog/models")}function $c(n){let e={zhipu:"Zhipu GLM","zhipu-openai":"Zhipu GLM OpenAI","zhipu-coding":"Zhipu GLM Coding",volcengine:"Doubao / Volcengine"};return e[n.id]?e[n.id]:n.displayName??n.name??n.id}function $s(n){return n.baseUrl??n.base_url}async function Uc(n){return(await Ns()).find(t=>t.id===n)??null}async function tr(n){let e=await iC();n.migrateModelIds(aC(e));let t=e.map(lC).filter(o=>!!o);return n.replaceCatalogModels(t),t}function aC(n){let e=new Map;for(let t of n){let o=t.provider??t.owned_by,r=t.public_model??t.publicModel??t.id,s=t.native_model_id??t.nativeModelId??t.id;if(!o||!r||!s)continue;let i=`${o}:${r}`;for(let a of[s,t.id])!a||a===r||e.set(`${o}:${a}`,i)}return e}function lC(n){let e=n.provider??n.owned_by,t=n.public_model??n.publicModel??n.id,o=n.native_model_id??n.nativeModelId??n.id;return!e||!t||!o?null:{id:`${e}:${t}`,provider:e,model:t,displayName:n.display_name??n.displayName??n.name??n.id,purposes:cC(n.purposes,n.category),baseUrl:n.baseUrl??n.base_url,enabled:!0,nativeModelId:o,transport:n.provider_transport??n.providerTransport,contextWindow:n.context_window??n.contextWindow,maxOutput:n.max_output??n.maxOutput,streamRequired:n.stream_required??n.streamRequired,capabilities:n.capabilities,pricing:n.pricing}}function cC(n,e){let t=[...n??[],e].filter(s=>!!s),o=new Set(["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"]),r=t.filter(s=>o.has(s));return[...new Set(r.length?r:["textGeneration"])]}function dC(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}je();import{join as jc}from"node:path";import{mkdirSync as uC,existsSync as pC,createWriteStream as mC}from"node:fs";import{pipeline as fC}from"node:stream/promises";import{Readable as gC}from"node:stream";var hC=ra,yC=sa,uh={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/mp4":".m4a","audio/flac":".flac","application/pdf":".pdf","model/gltf-binary":".glb","model/gltf+json":".gltf"},Us=class{projectDir;maxFileSize;timeoutMs;constructor(e){this.projectDir=e?.projectDir??null,this.maxFileSize=e?.maxFileSize??hC,this.timeoutMs=e?.timeoutMs??yC}setProjectDir(e){this.projectDir=e}resolveMediaDir(e){if(!this.projectDir)throw new Error("MediaPersistence requires projectDir \u2014 call setProjectDir() first");if(!e)return jc(this.projectDir,".qlogicagent","media",bC());let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return t!==e&&t.length>0&&[...e].filter(r=>!/[a-zA-Z0-9_-]/.test(r)).length>e.length/2&&console.warn(`[media-persistence] sessionId heavily sanitized: "${e}" \u2192 "${t}" \u2014 potential collision risk`),jc(this.projectDir,".qlogicagent","sessions",t,"media")}async download(e,t){let o=this.resolveMediaDir(t?.sessionId);if(o.length+60>255)throw new Error(`Media path too long (${o.length} chars) \u2014 would exceed OS limit. Use a shorter project path or session ID.`);pC(o)||uC(o,{recursive:!0});let r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs),i="";try{let a=await fetch(e,{signal:r.signal});if(!a.ok)throw new Error(`Download failed: ${a.status} ${a.statusText}`);let l=parseInt(a.headers.get("content-length")??"0",10);if(l>this.maxFileSize)throw new Error(`File too large: ${l} bytes (max: ${this.maxFileSize})`);let c=a.headers.get("content-type")?.split(";")[0].trim()||"application/octet-stream",d=vC(e,c),u=kC(t?.type??SC(c),d);i=jc(o,u);let p=a.body;if(!p)throw new Error("No response body");let m=mC(i);await fC(gC.fromWeb(p),m);let{size:h}=await import("node:fs/promises").then(f=>f.stat(i));if(h===0)throw await import("node:fs/promises").then(f=>f.unlink(i).catch(()=>{})),new Error("Download produced empty file (connection dropped)");return{remoteUrl:e,localPath:i,bytes:h,mimeType:c}}catch(a){if(i)try{let{unlink:l}=await import("node:fs/promises");await l(i)}catch{}throw a}finally{clearTimeout(s)}}async downloadAll(e,t,o){let r=[];for(let s of e)try{let i=await this.download(s,t);r.push(i)}catch(i){o?.warn(`media-persistence: failed to download ${s}: ${i.message}`)}return r}getMediaDir(e){return this.resolveMediaDir(e)}getProjectDir(){return this.projectDir}};function bC(){let n=new Date;return`${n.getFullYear()}${String(n.getMonth()+1).padStart(2,"0")}${String(n.getDate()).padStart(2,"0")}`}function kC(n,e){let t=new Date,o=`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}${String(t.getMinutes()).padStart(2,"0")}${String(t.getSeconds()).padStart(2,"0")}`,r=Math.random().toString(36).slice(2,6);return`${n}_${o}_${r}${e}`}function vC(n,e){if(uh[e])return uh[e];try{let t=new URL(n).pathname,o=t.lastIndexOf(".");if(o>0){let r=t.slice(o).toLowerCase().split("?")[0];if(r.length<=5)return r}}catch{}return".bin"}function SC(n){return n.startsWith("image/")?"image":n.startsWith("video/")?"video":n.startsWith("audio/")?"audio":n.startsWith("model/")?"3d":"file"}import{join as TC}from"node:path";import{readFileSync as wC,writeFileSync as xC,mkdirSync as RC}from"node:fs";var In=null,Fc=!1;function ph(n){return TC(n,"skill-stats.json")}function Bc(n){if(In)return In;try{In=JSON.parse(wC(ph(n),"utf8"))}catch{In={}}return In}function _C(n){if(!(!Fc||!In))try{RC(n,{recursive:!0}),xC(ph(n),JSON.stringify(In,null,2),"utf8"),Fc=!1}catch{}}function js(n,e,t){let o=Bc(n);o[e]||(o[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),o[e].invokeCount++,o[e].lastUsedAt=new Date().toISOString(),t?o[e].positiveCount++:o[e].negativeCount++,o[e].invokeCount>0&&(o[e].successRate=(o[e].invokeCount-o[e].negativeCount)/o[e].invokeCount),Fc=!0,_C(n)}function mh(n,e){return Bc(n)[e]}function fh(n){return Bc(n)}import{existsSync as AC,readFileSync as PC,writeFileSync as IC,mkdirSync as hh,renameSync as CC}from"node:fs";import{join as Wc,dirname as yh}from"node:path";var gh=30,EC=90,MC="skill-lifecycle.json";function bh(n){return Wc(n,MC)}function We(n){let e=bh(n);try{return JSON.parse(PC(e,"utf8"))}catch{return{version:1,records:{}}}}function Ve(n,e){let t=bh(n);hh(yh(t),{recursive:!0});let o=t+".tmp";IC(o,JSON.stringify(e,null,2),"utf8");let{renameSync:r}=gi("node:fs");r(o,t)}function Qt(n,e,t="learned"){return n.records[e]||(n.records[e]={name:e,state:"active",createdAt:new Date().toISOString(),pinned:!1,useCount:0,source:t}),n.records[e]}function Gc(n,e){let t=Qt(n,e);t.lastUsedAt=new Date().toISOString(),t.useCount++,t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function Hc(n,e){let t=Qt(n,e);t.lastPatchedAt=new Date().toISOString(),t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function kh(n,e){let t=n.records[e];return t?(t.pinned=!0,!0):!1}function vh(n,e){let t=n.records[e];return t?(t.pinned=!1,!0):!1}function OC(n){let e=[n.lastUsedAt,n.lastViewedAt,n.lastPatchedAt,n.createdAt].filter(Boolean).map(t=>new Date(t));return new Date(Math.max(...e.map(t=>t.getTime())))}function DC(n){let e=Date.now(),t={transitioned:[],skippedPinned:[]};for(let[o,r]of Object.entries(n.records)){if(r.source==="installed")continue;if(r.pinned){r.state!=="active"&&t.skippedPinned.push(o);continue}let s=OC(r),i=(e-s.getTime())/(1e3*60*60*24);r.state==="active"&&i>=gh?(r.state="stale",r.staleAt=new Date().toISOString(),t.transitioned.push({name:o,from:"active",to:"stale"})):r.state==="stale"&&i>=EC?(r.state="archived",r.archivedAt=new Date().toISOString(),t.transitioned.push({name:o,from:"stale",to:"archived"})):r.state==="stale"&&i<gh&&(r.state="active",r.staleAt=void 0,t.transitioned.push({name:o,from:"stale",to:"active"}))}return t}function LC(n,e){let t=Wc(n,e);if(!AC(t))return!1;let o=Wc(n,".archive",e);hh(yh(o),{recursive:!0});try{return CC(t,o),!0}catch{return!1}}function Sh(n,e){let t=We(n),o=DC(t);for(let r of o.transitioned)r.to==="archived"&&LC(e,r.name);return Ve(n,t),o}function Th(n,e){return Object.values(n.records).filter(t=>t.state===e)}function Fs(n,e){delete n.records[e]}function NC(n){let e=n.replace(/\r\n/g,`
666
666
  `).replace(/\r/g,`
667
667
  `);if(!e.startsWith("---"))return;let t=e.indexOf(`
668
- ---`,3);if(t!==-1)return e.slice(4,t)}function LC(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function NC(n,e){let t=[],o=e+1;for(;o<n.length;){let r=n[o];if(r.length>0&&!r.startsWith(" ")&&!r.startsWith(" "))break;t.push(r),o+=1}return{value:t.join(`
669
- `).trim(),linesConsumed:o-e}}function Vc(n){let e=DC(n);if(!e)return{};let t={},o=e.split(`
670
- `),r=0;for(;r<o.length;){let i=o[r].match(/^([\w-]+):\s*(.*)$/);if(!i){r+=1;continue}let a=i[1],l=i[2].trim();if(!a){r+=1;continue}if(!l&&r+1<o.length){let d=o[r+1];if(d.startsWith(" ")||d.startsWith(" ")){let{value:u,linesConsumed:p}=NC(o,r);u&&(t[a]=u),r+=p;continue}}let c=LC(l);c&&(t[a]=c),r+=1}return t}var Kc=1024,wh=1e5,$C=/^[a-z0-9][a-z0-9._-]*$/;function Ws(n,e){let t=[],o=[];if(!n||n.trim().length===0)return{valid:!1,errors:["Content is empty"],warnings:[]};if(n.length>wh)return{valid:!1,errors:[`Content exceeds ${wh} chars`],warnings:[]};if(!n.trimStart().startsWith("---"))return t.push("SKILL.md must start with YAML frontmatter (---)"),{valid:!1,errors:t,warnings:o};let r=n.replace(/\r\n/g,`
668
+ ---`,3);if(t!==-1)return e.slice(4,t)}function $C(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function UC(n,e){let t=[],o=e+1;for(;o<n.length;){let r=n[o];if(r.length>0&&!r.startsWith(" ")&&!r.startsWith(" "))break;t.push(r),o+=1}return{value:t.join(`
669
+ `).trim(),linesConsumed:o-e}}function Vc(n){let e=NC(n);if(!e)return{};let t={},o=e.split(`
670
+ `),r=0;for(;r<o.length;){let i=o[r].match(/^([\w-]+):\s*(.*)$/);if(!i){r+=1;continue}let a=i[1],l=i[2].trim();if(!a){r+=1;continue}if(!l&&r+1<o.length){let d=o[r+1];if(d.startsWith(" ")||d.startsWith(" ")){let{value:u,linesConsumed:p}=UC(o,r);u&&(t[a]=u),r+=p;continue}}let c=$C(l);c&&(t[a]=c),r+=1}return t}var Kc=1024,wh=1e5,jC=/^[a-z0-9][a-z0-9._-]*$/;function Ws(n,e){let t=[],o=[];if(!n||n.trim().length===0)return{valid:!1,errors:["Content is empty"],warnings:[]};if(n.length>wh)return{valid:!1,errors:[`Content exceeds ${wh} chars`],warnings:[]};if(!n.trimStart().startsWith("---"))return t.push("SKILL.md must start with YAML frontmatter (---)"),{valid:!1,errors:t,warnings:o};let r=n.replace(/\r\n/g,`
671
671
  `),s=r.indexOf(`
672
- ---`,3);if(s===-1)return t.push("YAML frontmatter has no closing delimiter (---)"),{valid:!1,errors:t,warnings:o};let i=Vc(n);return i.name?($C.test(i.name)||t.push(`Skill name '${i.name}' must be lowercase alphanumeric with dots, hyphens, or underscores`),e&&i.name!==e&&o.push(`Frontmatter name '${i.name}' differs from expected '${e}'`)):t.push("Frontmatter must include 'name' field"),i.description?i.description.length>Kc&&t.push(`Description exceeds ${Kc} characters`):t.push("Frontmatter must include 'description' field"),r.slice(s+4).trim()||t.push("SKILL.md must have content after frontmatter"),i.version&&(/^\d+\.\d+(\.\d+)?(-[\w.]+)?$/.test(i.version)||o.push(`Version '${i.version}' is not a valid semver format`)),{valid:t.length===0,errors:t,warnings:o,parsed:t.length===0?i:void 0}}function Bs(n){let e=["---"];if(e.push(`name: ${n.name}`),e.push(`description: ${n.description.slice(0,Kc)}`),n.version&&e.push(`version: ${n.version}`),n.category&&e.push(`category: ${n.category}`),n.tools&&n.tools.length>0){e.push("tools:");for(let t of n.tools)e.push(` - ${t}`)}return e.push("---"),e.push(""),e.push(n.body),e.join(`
672
+ ---`,3);if(s===-1)return t.push("YAML frontmatter has no closing delimiter (---)"),{valid:!1,errors:t,warnings:o};let i=Vc(n);return i.name?(jC.test(i.name)||t.push(`Skill name '${i.name}' must be lowercase alphanumeric with dots, hyphens, or underscores`),e&&i.name!==e&&o.push(`Frontmatter name '${i.name}' differs from expected '${e}'`)):t.push("Frontmatter must include 'name' field"),i.description?i.description.length>Kc&&t.push(`Description exceeds ${Kc} characters`):t.push("Frontmatter must include 'description' field"),r.slice(s+4).trim()||t.push("SKILL.md must have content after frontmatter"),i.version&&(/^\d+\.\d+(\.\d+)?(-[\w.]+)?$/.test(i.version)||o.push(`Version '${i.version}' is not a valid semver format`)),{valid:t.length===0,errors:t,warnings:o,parsed:t.length===0?i:void 0}}function Bs(n){let e=["---"];if(e.push(`name: ${n.name}`),e.push(`description: ${n.description.slice(0,Kc)}`),n.version&&e.push(`version: ${n.version}`),n.category&&e.push(`category: ${n.category}`),n.tools&&n.tools.length>0){e.push("tools:");for(let t of n.tools)e.push(` - ${t}`)}return e.push("---"),e.push(""),e.push(n.body),e.join(`
673
673
  `)}function zc(n,e,t){let o=n.replace(/\r\n/g,`
674
674
  `);if(!o.trimStart().startsWith("---"))return Bs({name:e,description:t??`Auto-learned skill: ${e}`,body:o.trim(),version:"1.0.0"});let r=Vc(n),s=o.indexOf(`
675
675
  ---`,3);if(s===-1)return Bs({name:e,description:t??`Auto-learned skill: ${e}`,body:o.replace(/^---.*$/m,"").trim(),version:"1.0.0"});let i=!1,a=o.slice(4,s),l=o.slice(s+4).trim();if(r.name||(a+=`
@@ -678,29 +678,29 @@ description: ${c}`,i=!0}return i?`---
678
678
  ${a}
679
679
  ---
680
680
 
681
- ${l}`:n}import*as Y from"node:fs";import*as te from"node:path";var no="1.0.0",w={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030};function qc(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}var xh=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.forged","system.activity"],Rh=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],UC=[...xh,...Rh];var kt={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},be={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},vt={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},xe={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function nr(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function or(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function Yc(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var _h="openai-codex";var c1={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[_h]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as jC}from"node:crypto";var Gs={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PROTOCOL_MISMATCH:-32001,SESSION_NOT_FOUND:-32002,AGENT_BUSY:-32003},Hs=class{transport;handler;verbose;hostCapabilities={};hostSupportsExtendedEvents=!1;hostSupportsExtendedMethods=!1;activeSessionId=null;pendingPermissions=new Map;outboundRequestMap=new Map;constructor(e,t,o){this.transport=e,this.handler=t,this.verbose=o?.verbose??!1}dispatchMessage(e){if(this.isJsonRpcResponse(e))return this.handleResponse(e),!0;if(nr(e)){let t=e;return process.stderr.write(`[acp-server] \u922B?recv id=${String(t.id)} method=${t.method}
682
- `),this.handleRequest(t),!0}return or(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,t,o){if(t.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let r={jsonrpc:"2.0",method:kt.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:t,...o}}};this.transport.send(r)}async requestPermission(e){let t=`perm-${jC().slice(0,8)}`,o={jsonrpc:"2.0",method:kt.SESSION_REQUEST_PERMISSION,params:e,id:t};return new Promise(r=>{this.outboundRequestMap.set(t,e.permissionId),this.pendingPermissions.set(e.permissionId,{resolve:s=>r({optionId:s})}),this.transport.send(o)})}get supportsExtendedEvents(){return this.hostSupportsExtendedEvents}get supportsExtendedMethods(){return this.hostSupportsExtendedMethods}get sessionId(){return this.activeSessionId}async handleRequest(e){let{method:t,params:o,id:r}=e,s=o??{};try{switch(t){case kt.INITIALIZE:await this.onInitialize(r,s);break;case kt.SESSION_NEW:await this.onSessionNew(r,s);break;case kt.SESSION_PROMPT:await this.onSessionPrompt(r,s);break;case kt.SESSION_END:await this.onSessionEnd(r,s);break;case kt.SESSION_SET_CONFIG:await this.onSessionSetConfig(r,s);break;case kt.SESSION_SET_MODEL:await this.handler.handleAcpSessionSetModel(s.sessionId??this.activeSessionId??"",s.modelId??s.model??""),this.sendResult(r,{});break;case kt.SESSION_SET_MODE:await this.handler.handleAcpSessionSetMode(s.sessionId??this.activeSessionId??"",s.modeId??s.mode??""),this.sendResult(r,{});break;case be.ABORT:await this.onAbort(r,s);break;case be.DREAM:await this.onDream(r,s);break;case be.AGENTS_LIST:{let i=await this.handler.handleAcpAgentsList();this.sendResult(r,i);break}case be.SOLO_START:{let i=await this.handler.handleAcpSoloStart(s);this.sendResult(r,i);break}case be.SOLO_STATUS:{let i=await this.handler.handleAcpSoloStatus(s);this.sendResult(r,i);break}case be.SOLO_SELECT:{let i=await this.handler.handleAcpSoloSelect(s);this.sendResult(r,i);break}case be.SOLO_CANCEL:{let i=await this.handler.handleAcpSoloCancel(s);this.sendResult(r,i);break}case be.SOLO_SUBSCRIBE:{let i=await this.handler.handleAcpSoloSubscribe(s);this.sendResult(r,i);break}case be.SOLO_MESSAGE:{let i=await this.handler.handleAcpSoloMessage(s);this.sendResult(r,i);break}case be.SOLO_EVALUATE:{let i=await this.handler.handleAcpSoloEvaluate(s);this.sendResult(r,i);break}case be.PRODUCT_CREATE:{let i=await this.handler.handleAcpProductCreate(s);this.sendResult(r,i);break}case be.PRODUCT_PLAN:{let i=await this.handler.handleAcpProductPlan(s);this.sendResult(r,i);break}case be.PRODUCT_CONFIRM:{let i=await this.handler.handleAcpProductConfirm(s);this.sendResult(r,i);break}case be.PRODUCT_MESSAGE:{let i=await this.handler.handleAcpProductMessage(s);this.sendResult(r,i);break}case be.PRODUCT_PAUSE:{let i=await this.handler.handleAcpProductPause(s);this.sendResult(r,i);break}case be.PRODUCT_RESUME:{let i=await this.handler.handleAcpProductResume(s);this.sendResult(r,i);break}case be.PRODUCT_CANCEL:{let i=await this.handler.handleAcpProductCancel(s);this.sendResult(r,i);break}case be.PRODUCT_ROLLBACK:{let i=await this.handler.handleAcpProductRollback(s);this.sendResult(r,i);break}case be.PRODUCT_STATUS:{let i=await this.handler.handleAcpProductStatus(s);this.sendResult(r,i);break}case be.PRODUCT_SUBSCRIBE:{let i=await this.handler.handleAcpProductSubscribe(s);this.sendResult(r,i);break}case be.TEAM_DELEGATE:{let i=await this.handler.handleAcpTeamDelegate(s);this.sendResult(r,i);break}default:this.sendError(r,Gs.METHOD_NOT_FOUND,`Unknown method: ${t}`)}}catch(i){this.sendError(r,Gs.INTERNAL_ERROR,i.message)}}handleNotification(e){this.log(`received notification: ${e.method}`)}handleResponse(e){let t=this.outboundRequestMap.get(e.id);if(t){this.outboundRequestMap.delete(e.id);let o=this.pendingPermissions.get(t);if(o){this.pendingPermissions.delete(t);let r=e.result;o.resolve(r?.optionId??"deny")}}else this.log(`received response for id=${String(e.id)} (no matching outbound request)`)}async onInitialize(e,t){this.hostCapabilities=t.clientCapabilities??{},this.hostSupportsExtendedEvents=this.hostCapabilities.extendedEvents??!1,this.hostSupportsExtendedMethods=this.hostCapabilities.extendedMethods??!1;let o=t.clientInfo?.name??"unknown",r=t.clientInfo?.version??"unknown";this.log(`initialize: host=${o} v=${r}, proto=${String(t.protocolVersion)}, extendedEvents=${this.hostSupportsExtendedEvents}, extendedMethods=${this.hostSupportsExtendedMethods}`);let s=await this.handler.handleAcpInitialize(t);this.sendResult(e,s)}async onSessionNew(e,t){let o=await this.handler.handleAcpSessionNew(t);this.activeSessionId=o.sessionId,this.sendResult(e,o)}async onSessionPrompt(e,t){if(!this.activeSessionId||this.activeSessionId!==t.sessionId){this.sendError(e,Gs.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}let o=await this.handler.handleAcpSessionPrompt(t);this.sendResult(e,o)}async onSessionEnd(e,t){await this.handler.handleAcpSessionEnd(t),this.activeSessionId===t.sessionId&&(this.activeSessionId=null),this.sendResult(e,{})}async onSessionSetConfig(e,t){if(this.activeSessionId!==t.sessionId){this.sendError(e,Gs.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}await this.handler.handleAcpSessionSetConfig(t),this.sendResult(e,{})}async onAbort(e,t){await this.handler.handleAcpAbort(t),this.sendResult(e,{aborted:!0})}async onDream(e,t){let o=await this.handler.handleAcpDream(t);this.sendResult(e,o)}sendResult(e,t){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} result
681
+ ${l}`:n}import*as Y from"node:fs";import*as te from"node:path";var no="1.0.0",w={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030};function qc(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}var xh=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.forged","system.activity"],Rh=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],FC=[...xh,...Rh];var kt={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},be={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},vt={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},xe={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function nr(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function or(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function Yc(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var _h="openai-codex";var u1={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[_h]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as BC}from"node:crypto";var Gs={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PROTOCOL_MISMATCH:-32001,SESSION_NOT_FOUND:-32002,AGENT_BUSY:-32003},Hs=class{transport;handler;verbose;hostCapabilities={};hostSupportsExtendedEvents=!1;hostSupportsExtendedMethods=!1;activeSessionId=null;pendingPermissions=new Map;outboundRequestMap=new Map;constructor(e,t,o){this.transport=e,this.handler=t,this.verbose=o?.verbose??!1}dispatchMessage(e){if(this.isJsonRpcResponse(e))return this.handleResponse(e),!0;if(nr(e)){let t=e;return process.stderr.write(`[acp-server] \u922B?recv id=${String(t.id)} method=${t.method}
682
+ `),this.handleRequest(t),!0}return or(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,t,o){if(t.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let r={jsonrpc:"2.0",method:kt.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:t,...o}}};this.transport.send(r)}async requestPermission(e){let t=`perm-${BC().slice(0,8)}`,o={jsonrpc:"2.0",method:kt.SESSION_REQUEST_PERMISSION,params:e,id:t};return new Promise(r=>{this.outboundRequestMap.set(t,e.permissionId),this.pendingPermissions.set(e.permissionId,{resolve:s=>r({optionId:s})}),this.transport.send(o)})}get supportsExtendedEvents(){return this.hostSupportsExtendedEvents}get supportsExtendedMethods(){return this.hostSupportsExtendedMethods}get sessionId(){return this.activeSessionId}async handleRequest(e){let{method:t,params:o,id:r}=e,s=o??{};try{switch(t){case kt.INITIALIZE:await this.onInitialize(r,s);break;case kt.SESSION_NEW:await this.onSessionNew(r,s);break;case kt.SESSION_PROMPT:await this.onSessionPrompt(r,s);break;case kt.SESSION_END:await this.onSessionEnd(r,s);break;case kt.SESSION_SET_CONFIG:await this.onSessionSetConfig(r,s);break;case kt.SESSION_SET_MODEL:await this.handler.handleAcpSessionSetModel(s.sessionId??this.activeSessionId??"",s.modelId??s.model??""),this.sendResult(r,{});break;case kt.SESSION_SET_MODE:await this.handler.handleAcpSessionSetMode(s.sessionId??this.activeSessionId??"",s.modeId??s.mode??""),this.sendResult(r,{});break;case be.ABORT:await this.onAbort(r,s);break;case be.DREAM:await this.onDream(r,s);break;case be.AGENTS_LIST:{let i=await this.handler.handleAcpAgentsList();this.sendResult(r,i);break}case be.SOLO_START:{let i=await this.handler.handleAcpSoloStart(s);this.sendResult(r,i);break}case be.SOLO_STATUS:{let i=await this.handler.handleAcpSoloStatus(s);this.sendResult(r,i);break}case be.SOLO_SELECT:{let i=await this.handler.handleAcpSoloSelect(s);this.sendResult(r,i);break}case be.SOLO_CANCEL:{let i=await this.handler.handleAcpSoloCancel(s);this.sendResult(r,i);break}case be.SOLO_SUBSCRIBE:{let i=await this.handler.handleAcpSoloSubscribe(s);this.sendResult(r,i);break}case be.SOLO_MESSAGE:{let i=await this.handler.handleAcpSoloMessage(s);this.sendResult(r,i);break}case be.SOLO_EVALUATE:{let i=await this.handler.handleAcpSoloEvaluate(s);this.sendResult(r,i);break}case be.PRODUCT_CREATE:{let i=await this.handler.handleAcpProductCreate(s);this.sendResult(r,i);break}case be.PRODUCT_PLAN:{let i=await this.handler.handleAcpProductPlan(s);this.sendResult(r,i);break}case be.PRODUCT_CONFIRM:{let i=await this.handler.handleAcpProductConfirm(s);this.sendResult(r,i);break}case be.PRODUCT_MESSAGE:{let i=await this.handler.handleAcpProductMessage(s);this.sendResult(r,i);break}case be.PRODUCT_PAUSE:{let i=await this.handler.handleAcpProductPause(s);this.sendResult(r,i);break}case be.PRODUCT_RESUME:{let i=await this.handler.handleAcpProductResume(s);this.sendResult(r,i);break}case be.PRODUCT_CANCEL:{let i=await this.handler.handleAcpProductCancel(s);this.sendResult(r,i);break}case be.PRODUCT_ROLLBACK:{let i=await this.handler.handleAcpProductRollback(s);this.sendResult(r,i);break}case be.PRODUCT_STATUS:{let i=await this.handler.handleAcpProductStatus(s);this.sendResult(r,i);break}case be.PRODUCT_SUBSCRIBE:{let i=await this.handler.handleAcpProductSubscribe(s);this.sendResult(r,i);break}case be.TEAM_DELEGATE:{let i=await this.handler.handleAcpTeamDelegate(s);this.sendResult(r,i);break}default:this.sendError(r,Gs.METHOD_NOT_FOUND,`Unknown method: ${t}`)}}catch(i){this.sendError(r,Gs.INTERNAL_ERROR,i.message)}}handleNotification(e){this.log(`received notification: ${e.method}`)}handleResponse(e){let t=this.outboundRequestMap.get(e.id);if(t){this.outboundRequestMap.delete(e.id);let o=this.pendingPermissions.get(t);if(o){this.pendingPermissions.delete(t);let r=e.result;o.resolve(r?.optionId??"deny")}}else this.log(`received response for id=${String(e.id)} (no matching outbound request)`)}async onInitialize(e,t){this.hostCapabilities=t.clientCapabilities??{},this.hostSupportsExtendedEvents=this.hostCapabilities.extendedEvents??!1,this.hostSupportsExtendedMethods=this.hostCapabilities.extendedMethods??!1;let o=t.clientInfo?.name??"unknown",r=t.clientInfo?.version??"unknown";this.log(`initialize: host=${o} v=${r}, proto=${String(t.protocolVersion)}, extendedEvents=${this.hostSupportsExtendedEvents}, extendedMethods=${this.hostSupportsExtendedMethods}`);let s=await this.handler.handleAcpInitialize(t);this.sendResult(e,s)}async onSessionNew(e,t){let o=await this.handler.handleAcpSessionNew(t);this.activeSessionId=o.sessionId,this.sendResult(e,o)}async onSessionPrompt(e,t){if(!this.activeSessionId||this.activeSessionId!==t.sessionId){this.sendError(e,Gs.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}let o=await this.handler.handleAcpSessionPrompt(t);this.sendResult(e,o)}async onSessionEnd(e,t){await this.handler.handleAcpSessionEnd(t),this.activeSessionId===t.sessionId&&(this.activeSessionId=null),this.sendResult(e,{})}async onSessionSetConfig(e,t){if(this.activeSessionId!==t.sessionId){this.sendError(e,Gs.SESSION_NOT_FOUND,`No active session with id: ${t.sessionId}`);return}await this.handler.handleAcpSessionSetConfig(t),this.sendResult(e,{})}async onAbort(e,t){await this.handler.handleAcpAbort(t),this.sendResult(e,{aborted:!0})}async onDream(e,t){let o=await this.handler.handleAcpDream(t);this.sendResult(e,o)}sendResult(e,t){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} result
683
683
  `);let o={jsonrpc:"2.0",id:e,result:t};this.transport.send(o)}sendError(e,t,o,r){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} error=${o}
684
684
  `);let s={jsonrpc:"2.0",id:e,error:{code:t,message:o,...r!==void 0?{data:r}:{}}};this.transport.send(s)}isJsonRpcResponse(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&("result"in t||"error"in t)&&!("method"in t)}log(e){this.verbose&&process.stderr.write(`[acp-server] ${e}
685
- `)}};function Ph(n,e,t,o){let r=FC(t,o);r&&n.emitSessionUpdate(e,r.type,r.payload)}function FC(n,e){switch(n){case"turn.delta":return{type:vt.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:e.text}}};case"turn.reasoning_delta":return{type:vt.AGENT_THOUGHT_CHUNK,payload:{content:{type:"text",text:e.delta}}};case"turn.tool_call":return{type:vt.TOOL_CALL,payload:{toolCallId:e.callId,toolName:e.name,status:"in_progress",title:e.name,kind:"execute",rawInput:BC(e.arguments)}};case"turn.tool_result":return{type:vt.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:e.ok?"completed":"failed",...e.outputPreview?{content:[{type:"content",content:{type:"text",text:e.outputPreview}}]}:{},...e.error?{content:[{type:"content",content:{type:"text",text:e.error}}]}:{}}};case"turn.tool_blocked":return{type:vt.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:"failed",content:[{type:"content",content:{type:"text",text:e.reason??"blocked"}}]}};case"turn.plan_update":return{type:vt.PLAN,payload:{entries:[{content:e.content,priority:"medium",status:"in_progress"}]}};case"turn.usage_update":{let t=e.usage,o=t?.inputTokens??t?.input_tokens??0,r=t?.outputTokens??t?.output_tokens??0;return{type:vt.USAGE_UPDATE,payload:{used:o+r,size:t?.contextWindow??2e5}}}case"turn.end":return null;case"turn.error":return{type:vt.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:`[Error] ${e.error?.message??"Unknown error"}`}}};case"turn.suggestions":return{type:vt.AVAILABLE_COMMANDS_UPDATE,payload:{availableCommands:(e.items??[]).map(t=>({name:t.text,description:t.description??""}))}};case"turn.sidechain_started":return{type:xe.X_SUBAGENT_STARTED,payload:{agentId:String(e.depth??0),agentName:e.role,task:void 0}};case"turn.subagent_delta":return{type:xe.X_SUBAGENT_DELTA,payload:{agentId:e.subagentId??e.agentType,text:e.text}};case"turn.sidechain_completed":return{type:xe.X_SUBAGENT_ENDED,payload:{agentId:String(e.depth??0),result:void 0}};case"turn.media_result":return{type:xe.X_MEDIA_RESULT,payload:{mediaId:e.taskId??WC(),type:e.mediaType,url:e.url,metadata:{model:e.model,provider:e.provider}}};case"turn.media_progress":return{type:xe.X_MEDIA_PROGRESS,payload:{mediaId:e.taskId,progress:e.percent,stage:e.status}};case"turn.skill_instruction":return{type:xe.X_SKILL_INSTRUCTION,payload:{skillId:"unknown",instruction:String(e.instruction??"")}};case"turn.recovery":return{type:xe.X_RECOVERY,payload:{errorType:e.action,message:e.detail??"",action:"retry"}};case"turn.ask_user":return{type:xe.X_ASK_USER,payload:{question:(e.questions??[])[0]?.question??"",options:(e.questions??[])[0]?.options?.map(t=>t.label)}};case"session.info":return{type:xe.X_SESSION_INFO,payload:{sessionId:e.sessionId,model:e.model,metadata:{cwd:e.cwd,turnCount:e.turnCount}}};case"memory.updated":return{type:xe.X_MEMORY_UPDATED,payload:{memoryId:e.source,action:"updated",summary:e.summary}};case"team.member.notification":return{type:xe.X_TEAM_MEMBER_UPDATE,payload:{memberId:e.memberId,type:e.method,payload:e.params??{}}};case"solo.progress":return{type:xe.X_SOLO_STARTED,payload:{evaluationId:e.soloId,agents:[e.agentId],task:e.progress??""}};case"solo.agentDelta":return{type:xe.X_SUBAGENT_DELTA,payload:{agentId:e.agentId,text:e.text}};case"solo.evaluation":return{type:xe.X_SOLO_SELECTED,payload:{evaluationId:e.soloId,winnerId:e.winnerId,reason:e.reasoning}};case"product.taskStarted":return{type:xe.X_PRODUCT_TASK_STARTED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:e.assignee}};case"product.taskCompleted":return{type:xe.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",result:e.result,status:"completed"}};case"product.taskFailed":return{type:xe.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",status:"failed"}};case"product.checkpointed":return{type:xe.X_PRODUCT_CHECKPOINT,payload:{workflowId:e.productId,checkpointId:e.timestamp,completedTasks:[]}};case"turn.start":case"turn.task_updated":case"turn.exec_progress":case"turn.heartbeat":case"turn.tool_use_summary":case"turn.artifact":case"turn.annotations":case"tool.approval.request":case"permission.rule_updated":case"pong":case"agents.status":case"agents.error":case"product.budgetWarning":case"product.completed":return null;default:return null}}function BC(n){if(n)try{return JSON.parse(n)}catch{return{raw:n}}}function WC(){return Math.random().toString(36).slice(2,10)}var Ih=["initialize","thread.create","thread.list","thread.turn","session.resume","session.getInfo","session.getMessages","memory.list","memory.read","memory.write","memory.search","memory.delete","memory.dream","tools.list","media.listModels","config.get","config.update","todos.list","tasks.list","tasks.cancel","agent.ping","agent.abort","tool.approval.response","agents.scan","agents.list","agents.config","agents.setConfig","agents.getConfig","agents.removeConfig","agents.setGateway","solo.start","solo.status","solo.cancel","solo.select","solo.list","solo.delete","solo.message","solo.evaluate","product.plan","product.confirm","product.message","product.create","product.resume","product.pause","product.checkpoint","product.status","product.list","product.delete","product.cancel","product.rollback","project.create","project.list","project.delete","project.rename","project.archive","project.unarchive","project.update","project.archiveByGroup","session.switchProject","session.getState","session.create","session.list","session.get","session.update","session.delete","session.archive","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","settings.listProviders","settings.addKey","settings.removeKey","settings.toggleKey","settings.listModels","settings.setActiveModel","settings.getActiveModel","settings.getOverview","settings.refreshModels","settings.validateKey"];import{randomUUID as ni}from"node:crypto";import*as fr from"node:path";le();mt();import*as Ch from"node:fs";import*as Xc from"node:path";le();var oo=class{getSessionsRoot(e){let t=lt(e);if(!t)throw new Error(`Project not found: ${e}`);return Vt(t.workspaceDir)}getProjectWorkspaceDir(e){let t=lt(e);if(!t)throw new Error(`Project not found: ${e}`);return t.workspaceDir}getSessionDir(e,t){return Xc.join(this.getSessionsRoot(e),t)}resolveWorkspaceDir(e,t){if(t)return this.getProjectWorkspaceDir(t);let o=fe();for(let r of o){let s=Vt(r.workspaceDir),i=Xc.join(s,e);try{if(Ch.existsSync(i))return r.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=Ne();if(e)return e.workspaceDir;let t=fe();if(t.length>0)return t[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=Ne();if(e)return e.id;let t=fe();if(t.length>0)return t[0].id;throw new Error("No active project available")}};function Ks(n,e){return{name:n,compute:e,cacheBreak:!1}}function ro(n,e,t){return{name:n,compute:e,cacheBreak:!0}}var Vs=new Map;async function GC(n){return(await Promise.all(n.map(async t=>{if(!t.cacheBreak&&Vs.has(t.name))return Vs.get(t.name)??null;let o=await t.compute();return Vs.set(t.name,o),o}))).filter(t=>t!=null)}function Eh(){Vs.clear()}async function Mh(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 GC(n.sections);e.push(...t)}return n.appendSystemPrompt&&e.push(n.appendSystemPrompt),e.filter(Boolean).join(`
685
+ `)}};function Ph(n,e,t,o){let r=WC(t,o);r&&n.emitSessionUpdate(e,r.type,r.payload)}function WC(n,e){switch(n){case"turn.delta":return{type:vt.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:e.text}}};case"turn.reasoning_delta":return{type:vt.AGENT_THOUGHT_CHUNK,payload:{content:{type:"text",text:e.delta}}};case"turn.tool_call":return{type:vt.TOOL_CALL,payload:{toolCallId:e.callId,toolName:e.name,status:"in_progress",title:e.name,kind:"execute",rawInput:GC(e.arguments)}};case"turn.tool_result":return{type:vt.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:e.ok?"completed":"failed",...e.outputPreview?{content:[{type:"content",content:{type:"text",text:e.outputPreview}}]}:{},...e.error?{content:[{type:"content",content:{type:"text",text:e.error}}]}:{}}};case"turn.tool_blocked":return{type:vt.TOOL_CALL_UPDATE,payload:{toolCallId:e.callId,status:"failed",content:[{type:"content",content:{type:"text",text:e.reason??"blocked"}}]}};case"turn.plan_update":return{type:vt.PLAN,payload:{entries:[{content:e.content,priority:"medium",status:"in_progress"}]}};case"turn.usage_update":{let t=e.usage,o=t?.inputTokens??t?.input_tokens??0,r=t?.outputTokens??t?.output_tokens??0;return{type:vt.USAGE_UPDATE,payload:{used:o+r,size:t?.contextWindow??2e5}}}case"turn.end":return null;case"turn.error":return{type:vt.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:`[Error] ${e.error?.message??"Unknown error"}`}}};case"turn.suggestions":return{type:vt.AVAILABLE_COMMANDS_UPDATE,payload:{availableCommands:(e.items??[]).map(t=>({name:t.text,description:t.description??""}))}};case"turn.sidechain_started":return{type:xe.X_SUBAGENT_STARTED,payload:{agentId:String(e.depth??0),agentName:e.role,task:void 0}};case"turn.subagent_delta":return{type:xe.X_SUBAGENT_DELTA,payload:{agentId:e.subagentId??e.agentType,text:e.text}};case"turn.sidechain_completed":return{type:xe.X_SUBAGENT_ENDED,payload:{agentId:String(e.depth??0),result:void 0}};case"turn.media_result":return{type:xe.X_MEDIA_RESULT,payload:{mediaId:e.taskId??HC(),type:e.mediaType,url:e.url,metadata:{model:e.model,provider:e.provider}}};case"turn.media_progress":return{type:xe.X_MEDIA_PROGRESS,payload:{mediaId:e.taskId,progress:e.percent,stage:e.status}};case"turn.skill_instruction":return{type:xe.X_SKILL_INSTRUCTION,payload:{skillId:"unknown",instruction:String(e.instruction??"")}};case"turn.recovery":return{type:xe.X_RECOVERY,payload:{errorType:e.action,message:e.detail??"",action:"retry"}};case"turn.ask_user":return{type:xe.X_ASK_USER,payload:{question:(e.questions??[])[0]?.question??"",options:(e.questions??[])[0]?.options?.map(t=>t.label)}};case"session.info":return{type:xe.X_SESSION_INFO,payload:{sessionId:e.sessionId,model:e.model,metadata:{cwd:e.cwd,turnCount:e.turnCount}}};case"memory.updated":return{type:xe.X_MEMORY_UPDATED,payload:{memoryId:e.source,action:"updated",summary:e.summary}};case"team.member.notification":return{type:xe.X_TEAM_MEMBER_UPDATE,payload:{memberId:e.memberId,type:e.method,payload:e.params??{}}};case"solo.progress":return{type:xe.X_SOLO_STARTED,payload:{evaluationId:e.soloId,agents:[e.agentId],task:e.progress??""}};case"solo.agentDelta":return{type:xe.X_SUBAGENT_DELTA,payload:{agentId:e.agentId,text:e.text}};case"solo.evaluation":return{type:xe.X_SOLO_SELECTED,payload:{evaluationId:e.soloId,winnerId:e.winnerId,reason:e.reasoning}};case"product.taskStarted":return{type:xe.X_PRODUCT_TASK_STARTED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:e.assignee}};case"product.taskCompleted":return{type:xe.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",result:e.result,status:"completed"}};case"product.taskFailed":return{type:xe.X_PRODUCT_TASK_COMPLETED,payload:{workflowId:e.productId,taskId:e.taskId,agentId:"",status:"failed"}};case"product.checkpointed":return{type:xe.X_PRODUCT_CHECKPOINT,payload:{workflowId:e.productId,checkpointId:e.timestamp,completedTasks:[]}};case"turn.start":case"turn.task_updated":case"turn.exec_progress":case"turn.heartbeat":case"turn.tool_use_summary":case"turn.artifact":case"turn.annotations":case"tool.approval.request":case"permission.rule_updated":case"pong":case"agents.status":case"agents.error":case"product.budgetWarning":case"product.completed":return null;default:return null}}function GC(n){if(n)try{return JSON.parse(n)}catch{return{raw:n}}}function HC(){return Math.random().toString(36).slice(2,10)}var Ih=["initialize","thread.create","thread.list","thread.turn","session.resume","session.getInfo","session.getMessages","memory.list","memory.read","memory.write","memory.search","memory.delete","memory.dream","tools.list","media.listModels","config.get","config.update","todos.list","tasks.list","tasks.cancel","agent.ping","agent.abort","tool.approval.response","agents.scan","agents.list","agents.config","agents.setConfig","agents.getConfig","agents.removeConfig","agents.setGateway","solo.start","solo.status","solo.cancel","solo.select","solo.list","solo.delete","solo.message","solo.evaluate","product.plan","product.confirm","product.message","product.create","product.resume","product.pause","product.checkpoint","product.status","product.list","product.delete","product.cancel","product.rollback","project.create","project.list","project.delete","project.rename","project.archive","project.unarchive","project.update","project.archiveByGroup","session.switchProject","session.getState","session.create","session.list","session.get","session.update","session.delete","session.archive","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","settings.listProviders","settings.addKey","settings.removeKey","settings.toggleKey","settings.listModels","settings.setActiveModel","settings.getActiveModel","settings.getOverview","settings.refreshModels","settings.validateKey"];import{randomUUID as ni}from"node:crypto";import*as fr from"node:path";le();mt();import*as Ch from"node:fs";import*as Xc from"node:path";le();var oo=class{getSessionsRoot(e){let t=lt(e);if(!t)throw new Error(`Project not found: ${e}`);return Vt(t.workspaceDir)}getProjectWorkspaceDir(e){let t=lt(e);if(!t)throw new Error(`Project not found: ${e}`);return t.workspaceDir}getSessionDir(e,t){return Xc.join(this.getSessionsRoot(e),t)}resolveWorkspaceDir(e,t){if(t)return this.getProjectWorkspaceDir(t);let o=fe();for(let r of o){let s=Vt(r.workspaceDir),i=Xc.join(s,e);try{if(Ch.existsSync(i))return r.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=Ne();if(e)return e.workspaceDir;let t=fe();if(t.length>0)return t[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=Ne();if(e)return e.id;let t=fe();if(t.length>0)return t[0].id;throw new Error("No active project available")}};function Ks(n,e){return{name:n,compute:e,cacheBreak:!1}}function ro(n,e,t){return{name:n,compute:e,cacheBreak:!0}}var Vs=new Map;async function VC(n){return(await Promise.all(n.map(async t=>{if(!t.cacheBreak&&Vs.has(t.name))return Vs.get(t.name)??null;let o=await t.compute();return Vs.set(t.name,o),o}))).filter(t=>t!=null)}function Eh(){Vs.clear()}async function Mh(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 VC(n.sections);e.push(...t)}return n.appendSystemPrompt&&e.push(n.appendSystemPrompt),e.filter(Boolean).join(`
686
686
 
687
- `)}le();import{existsSync as Oh,mkdirSync as HC,readFileSync as rr,writeFileSync as Dh}from"node:fs";import{join as sr}from"node:path";var zs=new Set(["coding","office","creative","general"]),Lh="settings.yaml";function VC(n){try{let e=sr(n,He,Lh),o=rr(e,"utf-8").match(/^taskDomain\s*:\s*(\w+)/m);if(o){let r=o[1].toLowerCase();if(zs.has(r))return r}}catch{}try{let e=sr(n,He,"INSTRUCTIONS.md"),o=rr(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(o){let r=o[0].match(/^domain\s*:\s*(\w+)/m);if(r){let s=r[1].toLowerCase();if(zs.has(s))return s}}}catch{}try{let e=sr(n,"INSTRUCTIONS.md"),o=rr(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(o){let r=o[0].match(/^domain\s*:\s*(\w+)/m);if(r){let s=r[1].toLowerCase();if(zs.has(s))return s}}}catch{}}var KC=3;function zC(n,e){let t=JC(n);return e?t===e||t==="general"?e:(Qc(n)[t]??0)>=KC?t:e:t}var qC=/\b(?:code|coding|bug|debug|fix|refactor|function|class|method|api|compile|build|deploy|test|unittest|lint|git|commit|merge|branch|pull\s*request|PR|npm|pnpm|yarn|pip|docker|k8s|kubernetes|sql|database|migration|endpoint|route|middleware|typescript|javascript|python|java|rust|go(?:lang)?|css|html|react|vue|angular|nextjs|express|fastapi|flask|django|springboot|webpack|vite|rollup|esbuild|CI\/?CD|GitHub\s*Actions|workflow|pipeline|variable|const|let|var|import|export|module|package|dependency|dependencies|node_modules|tsconfig|eslint|prettier|interface|type\b|enum|struct|async|await|promise|callback|exception|error\s*handling|stack\s*trace|breakpoint|源码|代码|编程|编码|调试|重构|修复|Bug|函数|类|方法|接口|模块|依赖|组件|编译|构建|部署|测试|单元测试|提交|合并|分支|数据库|迁移|路由|中间件)\b/i,YC=/\b(?:report|document|spreadsheet|excel|csv|table|chart|graph|data\s*analysis|statistics|slides?|presentation|ppt|powerpoint|email|mail|memo|minutes|meeting|schedule|calendar|summary|summarize|brief|overview|outline|template|format|agenda|invoice|budget|forecast|dashboard|KPI|OKR|metric|analytics|insight|文档|报告|报表|表格|数据分析|统计|幻灯片|PPT|演示|邮件|信件|备忘录|会议纪要|日程|摘要|总结|概要|简报|模板|格式|议程|发票|预算|预测|看板|报表|分析)\b/i,XC=/\b(?:write|writing|essay|article|blog|story|novel|poem|poetry|lyrics|copywriting|copy|slogan|tagline|headline|marketing|campaign|branding|creative|brainstorm|idea|concept|draft|narrative|character|dialogue|script|screenplay|pitch|proposal|content\s*strategy|social\s*media|SEO|newsletter|press\s*release|写作|文章|博客|故事|小说|诗|歌词|文案|标语|营销|策划|品牌|创意|头脑风暴|灵感|构思|草稿|叙事|角色|对话|剧本|策划案|提案|内容策略|自媒体|公众号|推文|软文|种草)\b/i;function JC(n){if(!n||n.trim().length===0)return"general";let e=Qc(n),t=Math.max(e.coding,e.office,e.creative);return t===0||[e.coding,e.office,e.creative].filter(r=>r>=t-1&&r>0).length>=2&&t<=2?"general":e.coding===t?"coding":e.office===t?"office":e.creative===t?"creative":"general"}function Qc(n){return{coding:Jc(n,qC),office:Jc(n,YC),creative:Jc(n,XC),general:0}}function Jc(n,e){let t=new RegExp(e.source,"gi"),o=n.match(t);return o?o.length:0}function Nh(n){let e=VC(n.cwd);if(e)return{domain:e,source:"project-file"};if(n.hostOverride&&zs.has(n.hostOverride))return{domain:n.hostOverride,source:"host-override"};let t=zC(n.userText,n.sessionDomain);return n.sessionDomain&&t===n.sessionDomain?{domain:t,source:"session-sticky"}:{domain:t,source:"auto-detect"}}var QC=3;function $h(n,e){if(e==="general")return!1;try{let t=sr(n,He),o=sr(t,Lh);if(Oh(o)){let s=rr(o,"utf-8");if(/^taskDomain\s*:/m.test(s))return!1}HC(t,{recursive:!0});let r=`# Auto-detected task domain for this workspace.
687
+ `)}le();import{existsSync as Oh,mkdirSync as KC,readFileSync as rr,writeFileSync as Dh}from"node:fs";import{join as sr}from"node:path";var zs=new Set(["coding","office","creative","general"]),Lh="settings.yaml";function zC(n){try{let e=sr(n,He,Lh),o=rr(e,"utf-8").match(/^taskDomain\s*:\s*(\w+)/m);if(o){let r=o[1].toLowerCase();if(zs.has(r))return r}}catch{}try{let e=sr(n,He,"INSTRUCTIONS.md"),o=rr(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(o){let r=o[0].match(/^domain\s*:\s*(\w+)/m);if(r){let s=r[1].toLowerCase();if(zs.has(s))return s}}}catch{}try{let e=sr(n,"INSTRUCTIONS.md"),o=rr(e,"utf-8").match(/^---\r?\n[\s\S]*?\r?\n---/);if(o){let r=o[0].match(/^domain\s*:\s*(\w+)/m);if(r){let s=r[1].toLowerCase();if(zs.has(s))return s}}}catch{}}var qC=3;function YC(n,e){let t=ZC(n);return e?t===e||t==="general"?e:(Qc(n)[t]??0)>=qC?t:e:t}var XC=/\b(?:code|coding|bug|debug|fix|refactor|function|class|method|api|compile|build|deploy|test|unittest|lint|git|commit|merge|branch|pull\s*request|PR|npm|pnpm|yarn|pip|docker|k8s|kubernetes|sql|database|migration|endpoint|route|middleware|typescript|javascript|python|java|rust|go(?:lang)?|css|html|react|vue|angular|nextjs|express|fastapi|flask|django|springboot|webpack|vite|rollup|esbuild|CI\/?CD|GitHub\s*Actions|workflow|pipeline|variable|const|let|var|import|export|module|package|dependency|dependencies|node_modules|tsconfig|eslint|prettier|interface|type\b|enum|struct|async|await|promise|callback|exception|error\s*handling|stack\s*trace|breakpoint|源码|代码|编程|编码|调试|重构|修复|Bug|函数|类|方法|接口|模块|依赖|组件|编译|构建|部署|测试|单元测试|提交|合并|分支|数据库|迁移|路由|中间件)\b/i,JC=/\b(?:report|document|spreadsheet|excel|csv|table|chart|graph|data\s*analysis|statistics|slides?|presentation|ppt|powerpoint|email|mail|memo|minutes|meeting|schedule|calendar|summary|summarize|brief|overview|outline|template|format|agenda|invoice|budget|forecast|dashboard|KPI|OKR|metric|analytics|insight|文档|报告|报表|表格|数据分析|统计|幻灯片|PPT|演示|邮件|信件|备忘录|会议纪要|日程|摘要|总结|概要|简报|模板|格式|议程|发票|预算|预测|看板|报表|分析)\b/i,QC=/\b(?:write|writing|essay|article|blog|story|novel|poem|poetry|lyrics|copywriting|copy|slogan|tagline|headline|marketing|campaign|branding|creative|brainstorm|idea|concept|draft|narrative|character|dialogue|script|screenplay|pitch|proposal|content\s*strategy|social\s*media|SEO|newsletter|press\s*release|写作|文章|博客|故事|小说|诗|歌词|文案|标语|营销|策划|品牌|创意|头脑风暴|灵感|构思|草稿|叙事|角色|对话|剧本|策划案|提案|内容策略|自媒体|公众号|推文|软文|种草)\b/i;function ZC(n){if(!n||n.trim().length===0)return"general";let e=Qc(n),t=Math.max(e.coding,e.office,e.creative);return t===0||[e.coding,e.office,e.creative].filter(r=>r>=t-1&&r>0).length>=2&&t<=2?"general":e.coding===t?"coding":e.office===t?"office":e.creative===t?"creative":"general"}function Qc(n){return{coding:Jc(n,XC),office:Jc(n,JC),creative:Jc(n,QC),general:0}}function Jc(n,e){let t=new RegExp(e.source,"gi"),o=n.match(t);return o?o.length:0}function Nh(n){let e=zC(n.cwd);if(e)return{domain:e,source:"project-file"};if(n.hostOverride&&zs.has(n.hostOverride))return{domain:n.hostOverride,source:"host-override"};let t=YC(n.userText,n.sessionDomain);return n.sessionDomain&&t===n.sessionDomain?{domain:t,source:"session-sticky"}:{domain:t,source:"auto-detect"}}var eE=3;function $h(n,e){if(e==="general")return!1;try{let t=sr(n,He),o=sr(t,Lh);if(Oh(o)){let s=rr(o,"utf-8");if(/^taskDomain\s*:/m.test(s))return!1}KC(t,{recursive:!0});let r=`# Auto-detected task domain for this workspace.
688
688
  # Values: coding | office | creative | general
689
689
  `;if(Oh(o)){let s=rr(o,"utf-8");Dh(o,s.trimEnd()+`
690
690
 
691
691
  `+r+`taskDomain: ${e}
692
692
  `,"utf-8")}else Dh(o,r+`taskDomain: ${e}
693
- `,"utf-8");return!0}catch{return!1}}function Uh(n,e){return e==="general"?!1:(Qc(n)[e]??0)>=QC}import{release as ZC,homedir as eE}from"node:os";import{resolve as tE}from"node:path";function nE(){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 oE(){let n=process.platform,e=ZC();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 jh(n){return Ks("environment_context",()=>{let e=nE(),t=oE(),o=n??process.cwd(),r=process.version,s=eE(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${tE(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(`
694
- `)})}function qs(){return["## Problem Solving","- If an approach fails, diagnose why before switching tactics \u2014 read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.","- Report outcomes faithfully: if verification fails, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded.","- Do not create files unless they are absolutely necessary for achieving your goal. Prefer editing an existing file to creating a new one.","","## Safety","- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities.","- If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code."]}function rE(){return["# Doing Tasks","","You will primarily perform software engineering tasks: solving bugs, adding new functionality, refactoring code, and more.","","## Code Quality","- In general, do not propose changes to code you haven't read. If you need to modify a file, read it first. Understand existing code before suggesting modifications.","","## Implementation Discipline",`- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.`,"- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).","- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. Three similar lines of code is better than a premature abstraction.","- Default to writing no comments unless the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug. Don't explain WHAT the code does \u2014 well-named identifiers already do that.",'- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding "// removed" comments for removed code. If code is unused, delete it completely.',"","## Completeness and Correctness","- When a task lists multiple constraints or requirements, implement ALL of them explicitly. Do not drop any.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns in the same codebase.","- After making changes, verify you met every requirement from the original request.","- For security fixes, use standard proven patterns (parameterized queries, input validation, etc.).","- NEVER leave TODO comments, placeholder implementations, or stub functions. Every function you write must have a complete, working implementation.","- When creating multiple files that import from each other, ensure every import resolves to a real export. Do not leave dead imports or forward declarations without implementations.","- If you create a file with a function signature, you MUST provide the full body \u2014 not `// implement later` or `throw new Error('not implemented')`.","","## Proactive Action","- When asked to fix, change, or improve code, implement the changes directly by writing to the file. Do not merely describe what should be changed.","- When you identify issues (bugs, security vulnerabilities, style problems), fix them immediately using your tools rather than listing recommendations.","- Default to action: read the file, make the fix, write it back. Only describe without acting when explicitly asked for advice or review only.","","## Faithful Reporting","- Report outcomes faithfully: if a tool call failed, say so with the error output. Do not claim success when a tool returned an error.","- If you did not run a verification step, say that rather than implying it succeeded.","- Never claim 'all tests pass' or 'file created successfully' when tool output shows otherwise.","- If you are unsure whether your changes are complete, state that explicitly rather than asserting completeness."]}function sE(){return["# Doing Tasks","","You will assist with office and analytical tasks: reports, data analysis, documents, presentations, and more.","","## Accuracy and Rigor","- Verify numerical calculations and statistical claims. When presenting data, ensure totals, percentages, and comparisons are mathematically correct.","- Distinguish clearly between facts, inferences, and assumptions. Label uncertain information explicitly.","- When summarizing source material, preserve the original meaning. Do not introduce information not present in the source.","","## Structure and Formatting","- Use clear headings, bullet points, and tables to organize information. Match the formatting conventions of the document type (report, memo, email, slides).","- For data-heavy outputs, prefer tables over prose. Include units, time periods, and comparison baselines.","- Keep language professional and concise. Avoid filler, hedging, and unnecessary qualifiers.","","## Completeness","- When the task lists multiple sections, data points, or requirements, address ALL of them. Do not silently omit items.","- If source data is insufficient to answer a question, state what is missing rather than guessing."]}function iE(){return["# Doing Tasks","","You will assist with creative and content tasks: writing, copywriting, brainstorming, and content strategy.","","## Voice and Style","- Match the requested tone, register, and style. If no style is specified, adapt to the content type (formal for press releases, conversational for blog posts, punchy for ad copy).","- Vary sentence length and structure for rhythm. Avoid monotonous patterns.","- Show, don't tell where appropriate. Use concrete details and vivid language over abstract statements.","","## Audience Awareness","- Write for the intended audience. Consider their knowledge level, interests, and expectations.","- For marketing/copywriting, lead with the benefit. Focus on what matters to the reader, not the feature list.","- Respect cultural context and sensitivity in language choices.","","## Creative Process","- When brainstorming, provide diverse options rather than variations on a single idea. Quantity and variety first, then refine.","- When editing existing text, preserve the author's voice. Make targeted improvements rather than rewriting from scratch.","- If creative constraints are given (word count, format, platform), follow them precisely."]}function Fh(n="general"){return ro("task_guidance",()=>{let e;switch(n){case"coding":e=[...rE(),"",...qs()];break;case"office":e=[...sE(),"",...qs()];break;case"creative":e=[...iE(),"",...qs()];break;default:e=["# Doing Tasks","","You are a versatile assistant that handles software engineering, office, and creative tasks.","",...qs(),"","## When Coding","- Read existing code before modifying it. Understand the structure before making changes.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns.","- Implement ALL listed constraints or requirements explicitly. Do not drop any.","- Don't add features or abstractions beyond what was asked.","- When asked to fix or change code, implement changes directly by writing to the file \u2014 do not merely describe what to change.","","## When Writing Documents or Analyzing Data","- Verify numerical calculations and statistical claims for correctness.","- Use clear structure: headings, tables, bullet points as appropriate.","- Distinguish facts from inferences. Label uncertain information.","","## When Creating Content","- Match the requested tone, style, and audience. Adapt if not specified.","- Lead with the benefit for marketing/copywriting tasks.","- Provide diverse options when brainstorming."];break}return e.join(`
693
+ `,"utf-8");return!0}catch{return!1}}function Uh(n,e){return e==="general"?!1:(Qc(n)[e]??0)>=eE}import{release as tE,homedir as nE}from"node:os";import{resolve as oE}from"node:path";function rE(){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 sE(){let n=process.platform,e=tE();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 jh(n){return Ks("environment_context",()=>{let e=rE(),t=sE(),o=n??process.cwd(),r=process.version,s=nE(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${oE(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(`
694
+ `)})}function qs(){return["## Problem Solving","- If an approach fails, diagnose why before switching tactics \u2014 read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.","- Report outcomes faithfully: if verification fails, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded.","- Do not create files unless they are absolutely necessary for achieving your goal. Prefer editing an existing file to creating a new one.","","## Safety","- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities.","- If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code."]}function iE(){return["# Doing Tasks","","You will primarily perform software engineering tasks: solving bugs, adding new functionality, refactoring code, and more.","","## Code Quality","- In general, do not propose changes to code you haven't read. If you need to modify a file, read it first. Understand existing code before suggesting modifications.","","## Implementation Discipline",`- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.`,"- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).","- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. Three similar lines of code is better than a premature abstraction.","- Default to writing no comments unless the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug. Don't explain WHAT the code does \u2014 well-named identifiers already do that.",'- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding "// removed" comments for removed code. If code is unused, delete it completely.',"","## Completeness and Correctness","- When a task lists multiple constraints or requirements, implement ALL of them explicitly. Do not drop any.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns in the same codebase.","- After making changes, verify you met every requirement from the original request.","- For security fixes, use standard proven patterns (parameterized queries, input validation, etc.).","- NEVER leave TODO comments, placeholder implementations, or stub functions. Every function you write must have a complete, working implementation.","- When creating multiple files that import from each other, ensure every import resolves to a real export. Do not leave dead imports or forward declarations without implementations.","- If you create a file with a function signature, you MUST provide the full body \u2014 not `// implement later` or `throw new Error('not implemented')`.","","## Proactive Action","- When asked to fix, change, or improve code, implement the changes directly by writing to the file. Do not merely describe what should be changed.","- When you identify issues (bugs, security vulnerabilities, style problems), fix them immediately using your tools rather than listing recommendations.","- Default to action: read the file, make the fix, write it back. Only describe without acting when explicitly asked for advice or review only.","","## Faithful Reporting","- Report outcomes faithfully: if a tool call failed, say so with the error output. Do not claim success when a tool returned an error.","- If you did not run a verification step, say that rather than implying it succeeded.","- Never claim 'all tests pass' or 'file created successfully' when tool output shows otherwise.","- If you are unsure whether your changes are complete, state that explicitly rather than asserting completeness."]}function aE(){return["# Doing Tasks","","You will assist with office and analytical tasks: reports, data analysis, documents, presentations, and more.","","## Accuracy and Rigor","- Verify numerical calculations and statistical claims. When presenting data, ensure totals, percentages, and comparisons are mathematically correct.","- Distinguish clearly between facts, inferences, and assumptions. Label uncertain information explicitly.","- When summarizing source material, preserve the original meaning. Do not introduce information not present in the source.","","## Structure and Formatting","- Use clear headings, bullet points, and tables to organize information. Match the formatting conventions of the document type (report, memo, email, slides).","- For data-heavy outputs, prefer tables over prose. Include units, time periods, and comparison baselines.","- Keep language professional and concise. Avoid filler, hedging, and unnecessary qualifiers.","","## Completeness","- When the task lists multiple sections, data points, or requirements, address ALL of them. Do not silently omit items.","- If source data is insufficient to answer a question, state what is missing rather than guessing."]}function lE(){return["# Doing Tasks","","You will assist with creative and content tasks: writing, copywriting, brainstorming, and content strategy.","","## Voice and Style","- Match the requested tone, register, and style. If no style is specified, adapt to the content type (formal for press releases, conversational for blog posts, punchy for ad copy).","- Vary sentence length and structure for rhythm. Avoid monotonous patterns.","- Show, don't tell where appropriate. Use concrete details and vivid language over abstract statements.","","## Audience Awareness","- Write for the intended audience. Consider their knowledge level, interests, and expectations.","- For marketing/copywriting, lead with the benefit. Focus on what matters to the reader, not the feature list.","- Respect cultural context and sensitivity in language choices.","","## Creative Process","- When brainstorming, provide diverse options rather than variations on a single idea. Quantity and variety first, then refine.","- When editing existing text, preserve the author's voice. Make targeted improvements rather than rewriting from scratch.","- If creative constraints are given (word count, format, platform), follow them precisely."]}function Fh(n="general"){return ro("task_guidance",()=>{let e;switch(n){case"coding":e=[...iE(),"",...qs()];break;case"office":e=[...aE(),"",...qs()];break;case"creative":e=[...lE(),"",...qs()];break;default:e=["# Doing Tasks","","You are a versatile assistant that handles software engineering, office, and creative tasks.","",...qs(),"","## When Coding","- Read existing code before modifying it. Understand the structure before making changes.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns.","- Implement ALL listed constraints or requirements explicitly. Do not drop any.","- Don't add features or abstractions beyond what was asked.","- When asked to fix or change code, implement changes directly by writing to the file \u2014 do not merely describe what to change.","","## When Writing Documents or Analyzing Data","- Verify numerical calculations and statistical claims for correctness.","- Use clear structure: headings, tables, bullet points as appropriate.","- Distinguish facts from inferences. Label uncertain information.","","## When Creating Content","- Match the requested tone, style, and audience. Adapt if not specified.","- Lead with the benefit for marketing/copywriting tasks.","- Provide diverse options when brainstorming."];break}return e.join(`
695
695
  `)})}function Bh(){return Ks("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify ambiguous requests before proceeding,","especially for expensive operations like media generation.","","## Project Rules Management","You can create, edit, and delete project rule files at `.qlogicagent/rules/*.md`.","These files are loaded into your system prompt every turn \u2014 changes take effect immediately.","Use this to help users establish coding conventions, workflow guidelines, or project-specific instructions.","When the user asks to 'add a rule', 'set up conventions', or 'configure instructions', write to `.qlogicagent/rules/<descriptive-name>.md`.","You may also create or edit `.qlogicagent/INSTRUCTIONS.md` for a single top-level instruction file."].join(`
696
696
  `))}function Wh(n){return Ks("language",()=>n?["# Language","",`Always respond in ${n}.`,`Use ${n} for all text output, explanations, and descriptions.`,"Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
697
697
  `):["# Language","","Respond in the same language as the user's message.","If the user writes in English, respond in English. If in Chinese, respond in Chinese.","Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
698
- `))}je();import{randomUUID as Gh}from"node:crypto";async function Hh(n,e){let t=new Date(n.lastActiveAt).getTime();if(Date.now()-t<Hd)return{split:!1,activeSessionId:n.sessionId};let s=Gh(),i=new Date().toISOString();await tt(n.sessionId,{sealedAt:i},e);let a=n.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${n.taskSummary}`:void 0;return await tt(s,{sessionId:s,projectId:n.projectId,type:"group",ownerId:n.ownerId,groupKey:n.groupKey,groupName:n.groupName,groupPlatform:n.groupPlatform,previousSessionId:n.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:n.sessionId}}async function Vh(n,e){if(n.type!=="group")return{split:!1,activeSessionId:n.sessionId};if(n.turnCount<Vd)return{split:!1,activeSessionId:n.sessionId};let t=Gh(),o=new Date().toISOString();await tt(n.sessionId,{sealedAt:o},e);let r=n.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${n.taskSummary}`:void 0;return await tt(t,{sessionId:t,projectId:n.projectId,type:"group",ownerId:n.ownerId,groupKey:n.groupKey,groupName:n.groupName,groupPlatform:n.groupPlatform,previousSessionId:n.sessionId,carryoverSummary:r},e),{split:!0,activeSessionId:t,sealedSessionId:n.sessionId}}mr();td();import*as uo from"node:fs";var sy=new oo,xE=[/继续(桌面|电脑|刚才|上次|之前)的/,/接着(桌面|电脑|刚才|上次|之前)的/,/刚才(那个|那件|说的|聊的|做的)/,/上次(说到|聊到|做到|讲到)/,/桌面(端|上)?(那个|那边|的任务|的对话|在做)/,/电脑(端|上)?(那个|那边|的任务|的对话|在做)/,/之前(那个|在做的|讨论的|说的)/,/帮我继续/,/接着(做|干|搞|写|改)/,/continue (from |where |the )?desktop/i,/pick up where/i,/what were we (doing|working on|talking about)/i,/continue (the |our )?(last |previous )?(task|conversation|chat)/i];function RE(n){return!n||n.length<3?!1:xE.some(e=>e.test(n))}function iy(n){let e=n.params?.turnId??"";this.log(`abort requested for turn ${e}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),n.id!==void 0&&this.sendResponse(n.id,{aborted:!0})}function ay(n){let e=n.params;if(!e)return;let t=e.approvalId,o=e.decision;if(!t||!o){this.log("[warn] tool.approval.response missing approvalId or decision");return}let r={approvalId:t,decision:o==="approved"?"approved":"denied",updatedInput:e.updatedInput,permissionUpdate:e.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(r),n.id!==void 0&&this.sendResponse(n.id,{received:!0})}function ly(n){let e=n.params,t=e?.requestId;if(!t){this.log("[warn] thread.user_response missing requestId"),n.id!==void 0&&this.sendResponse(n.id,{received:!1});return}let o=this.pendingAskUser.get(t);if(!o){this.log(`[warn] thread.user_response: no pending request ${t}`),n.id!==void 0&&this.sendResponse(n.id,{received:!1});return}if(this.pendingAskUser.delete(t),e?.declined===!0)o.resolve(null);else{let s=e?.answers??{};o.resolve(s)}n.id!==void 0&&this.sendResponse(n.id,{received:!0})}async function cy(n){let e=n.params??{},t=e.turnId??ni();this.currentTurnId=t;let o=e.sessionId,r=e.messages??[],s=e.tools??[],i=e.config;n.id!==void 0&&this.sendResponse(n.id,{accepted:!0,turnId:t});let a=this.resumedSessionHistory.get(o);if(a&&a.length>0&&(r=[...a,...r]),i?.workdir&&typeof i.workdir=="string"&&this.setActiveWorkdir(i.workdir),!i?.workdir&&o&&i?.projectId){let y=i.projectId;try{let b=sy.getProjectWorkspaceDir(y);this.getActiveProjectRoot()!==b&&(this.log(`[turn] routing session ${o} to project ${y} (${b})`),this.setActiveWorkdir(b))}catch{this.log(`[turn] project ${y} not found, using active project`)}}if(i?.sessionType==="group"&&typeof i?.groupKey=="string"){let y=i.groupKey,b=y.split(":"),k=b.length>=3?b.slice(1).join(":"):y,x=Jr(k);if(x)this.setActiveWorkdir(x.workspaceDir),Ne()?.id!==x.id&&ft(x.id);else{let I=i.groupName||k,P=k.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",O=fr.join(H(),"workspaces","groups",P),$=Xr({name:I,workspaceDir:O,type:"group",groupId:k});$&&(this.setActiveWorkdir($.workspaceDir),ft($.id),this.sendNotification("project.created",{id:$.id,name:$.name,type:"group",groupId:k,workspaceDir:$.workspaceDir}))}}let l=1800*1e3,c=!1,d=i?.projectHint,u=d&&typeof d=="object"&&"name"in d?d:typeof d=="string"?{name:d,updatedAt:Date.now()}:null;if(u&&i?.sessionType!=="group"){let y=Date.now()-u.updatedAt;if(y>l)c=!0,this.log(`[projectHint] stale (${Math.round(y/6e4)}min old), skipping auto-switch`);else{let b=u.name,k=Ne();if(!k||k.name.toLowerCase()!==b.toLowerCase()){let x=fe(),I=b.toLowerCase(),P=x.find(O=>O.name.toLowerCase()===I)??x.find(O=>O.name.toLowerCase().includes(I));P&&P.status==="active"&&(ft(P.id),this.setActiveWorkdir(P.workspaceDir))}}}let p=(()=>{let y=i?.projectId;if(y)try{return sy.getProjectWorkspaceDir(y)}catch{}return this.getActiveProjectRoot()})();{let y=X(),b=y.snapshotProviderKeys();this.currentMediaApiKeys=b,ng(this.mediaClient,b,(x,I,P)=>{this.sessionState?.addMediaUsage(x,I,P)},i?.mediaProviders,(x,I,P,O,$)=>{this.sendNotification("turn.media_progress",{turnId:t,taskId:x,mediaType:I,percent:P,status:O,...$?{provider:$}:{}})});let k=y.getActiveModel("textGeneration");k?(yc(Qf(k.provider,k.apiKey)),k.keyHandle.release({success:!0})):yc(void 0)}tg(async y=>{let b=`ask-${ni().slice(0,8)}`;return new Promise(k=>{this.pendingAskUser.set(b,{resolve:k}),this.sendNotification("turn.ask_user",{requestId:b,questions:y.map(x=>({header:x.header,question:x.question,options:x.options}))})})});let m=new AbortController;this.activeTurn&&(this.activeTurn.abort(),await this.turnDone),this.activeTurn=m;let h;this.turnDone=new Promise(y=>{h=y}),o&&o!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),Eh()),this.currentSessionId=o,this.sessionState=new ln(o),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Kt(),this.enableIdleDream()),this.log(`turn ${t} starting (session: ${o})`),this.sendNotification("turn.start",{turnId:t,model:i?.model??(this.currentModel||void 0),provider:i?.provider||void 0,projectId:i?.projectId||void 0});let f=[...r].reverse().find(y=>y.role==="user");if(this.lastUserMessageForAutoExtract=typeof f?.content=="string"?f.content:void 0,!f||!String(f.content??"").trim()){this.sendNotification("turn.end",{turnId:t,content:"",item:{id:`${t}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}});return}try{let y={provider:i?.provider,model:i?.model,apiKey:i?.apiKey,baseUrl:i?.baseUrl,maxRounds:i?.maxRounds,temperature:i?.temperature,contextWindowTokens:i?.contextWindowTokens,maxOutputTokens:i?.maxOutputTokens,modelMaxOutputTokens:i?.modelMaxOutputTokens,maxConcurrentTools:i?.maxConcurrentTools,mediaProviders:i?.mediaProviders,reasoning:i?.reasoning,promptCacheKey:i?.promptCacheKey,promptCacheRetention:i?.promptCacheRetention,serviceTier:i?.serviceTier,openaiBuiltinTools:i?.openaiBuiltinTools,maxToolCalls:i?.maxToolCalls,parallelToolCalls:i?.parallelToolCalls,textVerbosity:i?.textVerbosity,mcpServers:i?.mcpServers,fallbackModel:X().resolveModelForPurpose("smallModel")??void 0};{let T=y.provider??"",F=y.model??"";T&&F&&X().getModelInfo(T,F)?.streamRequired&&(y.streamRequired=!0)}let b=this.resolveAgent(y);if(this.permissionChecker&&i?.permissions){let T=i.permissions,F=Rs(T);this.permissionChecker.ruleEngineRef.setMode(F.mode),F.rules.length>0&&this.permissionChecker.ruleEngineRef.replaceRules(F.rules),F.defaultBehavior&&this.permissionChecker.ruleEngineRef.setDefaultBehavior(F.defaultBehavior),F.mode}if(!b){this.sendNotification("turn.error",{turnId:t,error:{message:"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 k,x=i?.workdir??this.getActiveProjectRoot();this.setActiveWorkdir(x);try{let T=await hm(x,this.currentHooks??void 0);T.length>0&&(k=gm(T))}catch{}let I=r.filter(T=>T.role==="user").map(T=>typeof T.content=="string"?T.content:"").join(" "),{domain:P,source:O}=Nh({cwd:x,hostOverride:i?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:I});if(this.sessionTaskDomain=P,O==="auto-detect"&&Uh(I,P)&&$h(x,P),!this.memdir||this.memdir.getRootPath()!==new Nt(x).getRootPath()){let T=new Nt(x);T.ensureInitialized(),this.memdir=T}let $=this.memdir,W;if(o){let T=wn(o,p);T?.carryoverSummary&&(W=T.carryoverSummary)}let S=await Mh({basePrompt:i?.systemPrompt,instructionBlock:k,customSystemPrompt:i?.customSystemPrompt,appendSystemPrompt:i?.appendSystemPrompt,sections:[jh(x),Wh(),Fh(P),Bh(),ro("pet",()=>{let F=new $t(x).load();return Qs(F)||null},"pet soul may change between turns"),...W?[ro("carryover",()=>W,"carryover from predecessor session")]:[],ro("memory",()=>{if(!$)return null;let T=$.getIndexForPrompt();return T?["## Your Memory (project-level notes \u2014 always visible)","",T,"","<!-- Use memory(action='remember') for user-level long-term facts/preferences that persist across projects.>","<!-- Use memory(action='add') for project-specific notes that should be visible every turn.>"].join(`
699
- `):null},"memory INDEX.md may change between turns")]}),ce=[...r].reverse().find(T=>T.role==="user");ce&&wl(o,ce,p,t).catch(()=>{}),await this.mcpReady;let de=Mt(),j=new Set(de.map(T=>T.function.name)),ve=[...de,...s.filter(T=>!j.has(T.function.name))],ie=r;if(c&&r.length>0){let T=Ne(),F=fe().filter(Re=>Re.status==="active").map(Re=>Re.name).slice(0,10).join(", ");ie=[{role:"system",content:`[\u6CE8\u610F\uFF1A\u7528\u6237\u4ECE IM \u7AEF\u53D1\u6765\u6D88\u606F\uFF0C\u4F46\u684C\u9762\u7AEF\u5DF2\u8D85\u8FC730\u5206\u949F\u672A\u6D3B\u8DC3\uFF0C\u65E0\u6CD5\u786E\u5B9A\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u5DE5\u4F5C\u3002\u5F53\u524D\u6D3B\u8DC3\u9879\u76EE\uFF1A${T?.name??"\u65E0"}\u3002\u53EF\u7528\u9879\u76EE\uFF1A${F||"\u65E0"}\u3002\u8BF7\u5728\u56DE\u590D\u5F00\u5934\u7B80\u77ED\u8BE2\u95EE\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u7EE7\u7EED\uFF0C\u4F8B\u5982\uFF1A"\u4F60\u60F3\u7EE7\u7EED\u5728\u300CXX\u300D\u9879\u76EE\u4E2D\u5DE5\u4F5C\u5417\uFF1F"]`},...r]}let Ue=i?.desktopRecentContext;if(!c&&Ue&&Ue.length>0&&r.length>0){let T=r[r.length-1],F=T?.role==="user"&&typeof T.content=="string"?T.content:"";if(RE(F)){let B={role:"system",content:"[\u4EE5\u4E0B\u662F\u7528\u6237\u5728\u684C\u9762\u7AEF\u7684\u8FD1\u671F\u5BF9\u8BDD\uFF0C\u4F9B\u4F60\u53C2\u8003\u4EE5\u4FDD\u6301\u4E0A\u4E0B\u6587\u8FDE\u8D2F]"},Re={role:"system",content:"[\u684C\u9762\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u7ED3\u675F\uFF0C\u4EE5\u4E0B\u662F\u5F53\u524D IM \u7AEF\u7684\u5BF9\u8BDD]"};ie=[B,...Ue,Re,...ie],this.log(`[continuation] injected ${Ue.length} desktop messages as reference`)}}if(!wn(o,p)?.title){let T=typeof ce?.content=="string"?ce.content:Array.isArray(ce?.content)?ce.content.filter(F=>F.type==="text").map(F=>F.text??"").join(""):"";if(T.trim()){let F=null,B=this.resolveClientForPurpose("smallModel");B&&(F=await lm(T,{transport:B.transport,apiKey:B.apiKey,model:B.model})),F||(F=T.trim().slice(0,20)+(T.trim().length>20?"\u2026":"")),await tt(o,{title:F},p).catch(()=>{}),this.sendNotification("session.info",{sessionId:o,title:F,projectId:i?.projectId||void 0}),this.log(`[title-gen] generated title for session ${o}: "${F}"`)}}for await(let T of b.run({turnId:t,sessionId:o,messages:ie,tools:ve,systemPrompt:S,config:y},m.signal)){let F=new Date().toISOString();switch(T.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:T.turnId,text:T.text,item:{id:`${t}-delta`,type:"message",role:"assistant",text:T.text,createdAt:F}});break;case"end":if(this.sendNotification("turn.end",{turnId:T.turnId,content:T.content,usage:T.usage,model:T.model,provider:T.provider,item:{id:`${t}-end`,type:"message",role:"assistant",text:T.content,createdAt:F}}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,T.model??this.currentModel);let B=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:T.model??this.currentModel,sessionCostUSD:B.totalInputTokens*3e-6+B.totalOutputTokens*15e-6})}T.content&&(this.lastAssistantMessageForExtract=T.content,wl(o,{role:"assistant",content:T.content},p,t).catch(()=>{}));break;case"error":if(this.sendNotification("turn.error",{turnId:T.turnId,error:{message:T.error,code:T.code}}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,this.currentModel);let B=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:this.currentModel,sessionCostUSD:B.totalInputTokens*3e-6+B.totalOutputTokens*15e-6})}break;case"skill_instruction":if(this.sendNotification("turn.skill_instruction",{turnId:T.turnId,instruction:T.instruction}),T.instruction.type==="skill.create"){let B=T.instruction,he=fr.join(p,".qlogicagent","skills"),Ut=fr.join(he,B.suggestedName),g=fr.join(Ut,"SKILL.md");if(!uo.existsSync(g)){let v=Bs({name:B.suggestedName,description:B.description,tools:B.tools,body:`# ${B.suggestedName}
698
+ `))}je();import{randomUUID as Gh}from"node:crypto";async function Hh(n,e){let t=new Date(n.lastActiveAt).getTime();if(Date.now()-t<Hd)return{split:!1,activeSessionId:n.sessionId};let s=Gh(),i=new Date().toISOString();await tt(n.sessionId,{sealedAt:i},e);let a=n.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${n.taskSummary}`:void 0;return await tt(s,{sessionId:s,projectId:n.projectId,type:"group",ownerId:n.ownerId,groupKey:n.groupKey,groupName:n.groupName,groupPlatform:n.groupPlatform,previousSessionId:n.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:n.sessionId}}async function Vh(n,e){if(n.type!=="group")return{split:!1,activeSessionId:n.sessionId};if(n.turnCount<Vd)return{split:!1,activeSessionId:n.sessionId};let t=Gh(),o=new Date().toISOString();await tt(n.sessionId,{sealedAt:o},e);let r=n.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${n.taskSummary}`:void 0;return await tt(t,{sessionId:t,projectId:n.projectId,type:"group",ownerId:n.ownerId,groupKey:n.groupKey,groupName:n.groupName,groupPlatform:n.groupPlatform,previousSessionId:n.sessionId,carryoverSummary:r},e),{split:!0,activeSessionId:t,sealedSessionId:n.sessionId}}mr();td();import*as uo from"node:fs";var sy=new oo,_E=[/继续(桌面|电脑|刚才|上次|之前)的/,/接着(桌面|电脑|刚才|上次|之前)的/,/刚才(那个|那件|说的|聊的|做的)/,/上次(说到|聊到|做到|讲到)/,/桌面(端|上)?(那个|那边|的任务|的对话|在做)/,/电脑(端|上)?(那个|那边|的任务|的对话|在做)/,/之前(那个|在做的|讨论的|说的)/,/帮我继续/,/接着(做|干|搞|写|改)/,/continue (from |where |the )?desktop/i,/pick up where/i,/what were we (doing|working on|talking about)/i,/continue (the |our )?(last |previous )?(task|conversation|chat)/i];function AE(n){return!n||n.length<3?!1:_E.some(e=>e.test(n))}function iy(n){let e=n.params?.turnId??"";this.log(`abort requested for turn ${e}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),n.id!==void 0&&this.sendResponse(n.id,{aborted:!0})}function ay(n){let e=n.params;if(!e)return;let t=e.approvalId,o=e.decision;if(!t||!o){this.log("[warn] tool.approval.response missing approvalId or decision");return}let r={approvalId:t,decision:o==="approved"?"approved":"denied",updatedInput:e.updatedInput,permissionUpdate:e.permissionUpdate};this.permissionChecker&&this.permissionChecker.resolveApproval(r),n.id!==void 0&&this.sendResponse(n.id,{received:!0})}function ly(n){let e=n.params,t=e?.requestId;if(!t){this.log("[warn] thread.user_response missing requestId"),n.id!==void 0&&this.sendResponse(n.id,{received:!1});return}let o=this.pendingAskUser.get(t);if(!o){this.log(`[warn] thread.user_response: no pending request ${t}`),n.id!==void 0&&this.sendResponse(n.id,{received:!1});return}if(this.pendingAskUser.delete(t),e?.declined===!0)o.resolve(null);else{let s=e?.answers??{};o.resolve(s)}n.id!==void 0&&this.sendResponse(n.id,{received:!0})}async function cy(n){let e=n.params??{},t=e.turnId??ni();this.currentTurnId=t;let o=e.sessionId,r=e.messages??[],s=e.tools??[],i=e.config;n.id!==void 0&&this.sendResponse(n.id,{accepted:!0,turnId:t});let a=this.resumedSessionHistory.get(o);if(a&&a.length>0&&(r=[...a,...r]),i?.workdir&&typeof i.workdir=="string"&&this.setActiveWorkdir(i.workdir),!i?.workdir&&o&&i?.projectId){let y=i.projectId;try{let b=sy.getProjectWorkspaceDir(y);this.getActiveProjectRoot()!==b&&(this.log(`[turn] routing session ${o} to project ${y} (${b})`),this.setActiveWorkdir(b))}catch{this.log(`[turn] project ${y} not found, using active project`)}}if(i?.sessionType==="group"&&typeof i?.groupKey=="string"){let y=i.groupKey,b=y.split(":"),k=b.length>=3?b.slice(1).join(":"):y,x=Jr(k);if(x)this.setActiveWorkdir(x.workspaceDir),Ne()?.id!==x.id&&ft(x.id);else{let I=i.groupName||k,P=k.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",O=fr.join(H(),"workspaces","groups",P),$=Xr({name:I,workspaceDir:O,type:"group",groupId:k});$&&(this.setActiveWorkdir($.workspaceDir),ft($.id),this.sendNotification("project.created",{id:$.id,name:$.name,type:"group",groupId:k,workspaceDir:$.workspaceDir}))}}let l=1800*1e3,c=!1,d=i?.projectHint,u=d&&typeof d=="object"&&"name"in d?d:typeof d=="string"?{name:d,updatedAt:Date.now()}:null;if(u&&i?.sessionType!=="group"){let y=Date.now()-u.updatedAt;if(y>l)c=!0,this.log(`[projectHint] stale (${Math.round(y/6e4)}min old), skipping auto-switch`);else{let b=u.name,k=Ne();if(!k||k.name.toLowerCase()!==b.toLowerCase()){let x=fe(),I=b.toLowerCase(),P=x.find(O=>O.name.toLowerCase()===I)??x.find(O=>O.name.toLowerCase().includes(I));P&&P.status==="active"&&(ft(P.id),this.setActiveWorkdir(P.workspaceDir))}}}let p=(()=>{let y=i?.projectId;if(y)try{return sy.getProjectWorkspaceDir(y)}catch{}return this.getActiveProjectRoot()})();{let y=X(),b=y.snapshotProviderKeys();this.currentMediaApiKeys=b,ng(this.mediaClient,b,(x,I,P)=>{this.sessionState?.addMediaUsage(x,I,P)},i?.mediaProviders,(x,I,P,O,$)=>{this.sendNotification("turn.media_progress",{turnId:t,taskId:x,mediaType:I,percent:P,status:O,...$?{provider:$}:{}})});let k=y.getActiveModel("textGeneration");k?(yc(Qf(k.provider,k.apiKey)),k.keyHandle.release({success:!0})):yc(void 0)}tg(async y=>{let b=`ask-${ni().slice(0,8)}`;return new Promise(k=>{this.pendingAskUser.set(b,{resolve:k}),this.sendNotification("turn.ask_user",{requestId:b,questions:y.map(x=>({header:x.header,question:x.question,options:x.options}))})})});let m=new AbortController;this.activeTurn&&(this.activeTurn.abort(),await this.turnDone),this.activeTurn=m;let h;this.turnDone=new Promise(y=>{h=y}),o&&o!==this.currentSessionId&&(this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}),Eh()),this.currentSessionId=o,this.sessionState=new ln(o),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Kt(),this.enableIdleDream()),this.log(`turn ${t} starting (session: ${o})`),this.sendNotification("turn.start",{turnId:t,model:i?.model??(this.currentModel||void 0),provider:i?.provider||void 0,projectId:i?.projectId||void 0});let f=[...r].reverse().find(y=>y.role==="user");if(this.lastUserMessageForAutoExtract=typeof f?.content=="string"?f.content:void 0,!f||!String(f.content??"").trim()){this.sendNotification("turn.end",{turnId:t,content:"",item:{id:`${t}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}});return}try{let y={provider:i?.provider,model:i?.model,apiKey:i?.apiKey,baseUrl:i?.baseUrl,maxRounds:i?.maxRounds,temperature:i?.temperature,contextWindowTokens:i?.contextWindowTokens,maxOutputTokens:i?.maxOutputTokens,modelMaxOutputTokens:i?.modelMaxOutputTokens,maxConcurrentTools:i?.maxConcurrentTools,mediaProviders:i?.mediaProviders,reasoning:i?.reasoning,promptCacheKey:i?.promptCacheKey,promptCacheRetention:i?.promptCacheRetention,serviceTier:i?.serviceTier,openaiBuiltinTools:i?.openaiBuiltinTools,maxToolCalls:i?.maxToolCalls,parallelToolCalls:i?.parallelToolCalls,textVerbosity:i?.textVerbosity,mcpServers:i?.mcpServers,fallbackModel:X().resolveModelForPurpose("smallModel")??void 0};{let T=y.provider??"",F=y.model??"";T&&F&&X().getModelInfo(T,F)?.streamRequired&&(y.streamRequired=!0)}let b=this.resolveAgent(y);if(this.permissionChecker&&i?.permissions){let T=i.permissions,F=Rs(T);this.permissionChecker.ruleEngineRef.setMode(F.mode),F.rules.length>0&&this.permissionChecker.ruleEngineRef.replaceRules(F.rules),F.defaultBehavior&&this.permissionChecker.ruleEngineRef.setDefaultBehavior(F.defaultBehavior),F.mode}if(!b){this.sendNotification("turn.error",{turnId:t,error:{message:"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 k,x=i?.workdir??this.getActiveProjectRoot();this.setActiveWorkdir(x);try{let T=await hm(x,this.currentHooks??void 0);T.length>0&&(k=gm(T))}catch{}let I=r.filter(T=>T.role==="user").map(T=>typeof T.content=="string"?T.content:"").join(" "),{domain:P,source:O}=Nh({cwd:x,hostOverride:i?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:I});if(this.sessionTaskDomain=P,O==="auto-detect"&&Uh(I,P)&&$h(x,P),!this.memdir||this.memdir.getRootPath()!==new Nt(x).getRootPath()){let T=new Nt(x);T.ensureInitialized(),this.memdir=T}let $=this.memdir,W;if(o){let T=wn(o,p);T?.carryoverSummary&&(W=T.carryoverSummary)}let S=await Mh({basePrompt:i?.systemPrompt,instructionBlock:k,customSystemPrompt:i?.customSystemPrompt,appendSystemPrompt:i?.appendSystemPrompt,sections:[jh(x),Wh(),Fh(P),Bh(),ro("pet",()=>{let F=new $t(x).load();return Qs(F)||null},"pet soul may change between turns"),...W?[ro("carryover",()=>W,"carryover from predecessor session")]:[],ro("memory",()=>{if(!$)return null;let T=$.getIndexForPrompt();return T?["## Your Memory (project-level notes \u2014 always visible)","",T,"","<!-- Use memory(action='remember') for user-level long-term facts/preferences that persist across projects.>","<!-- Use memory(action='add') for project-specific notes that should be visible every turn.>"].join(`
699
+ `):null},"memory INDEX.md may change between turns")]}),ce=[...r].reverse().find(T=>T.role==="user");ce&&wl(o,ce,p,t).catch(()=>{}),await this.mcpReady;let de=Mt(),j=new Set(de.map(T=>T.function.name)),ve=[...de,...s.filter(T=>!j.has(T.function.name))],ie=r;if(c&&r.length>0){let T=Ne(),F=fe().filter(Re=>Re.status==="active").map(Re=>Re.name).slice(0,10).join(", ");ie=[{role:"system",content:`[\u6CE8\u610F\uFF1A\u7528\u6237\u4ECE IM \u7AEF\u53D1\u6765\u6D88\u606F\uFF0C\u4F46\u684C\u9762\u7AEF\u5DF2\u8D85\u8FC730\u5206\u949F\u672A\u6D3B\u8DC3\uFF0C\u65E0\u6CD5\u786E\u5B9A\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u5DE5\u4F5C\u3002\u5F53\u524D\u6D3B\u8DC3\u9879\u76EE\uFF1A${T?.name??"\u65E0"}\u3002\u53EF\u7528\u9879\u76EE\uFF1A${F||"\u65E0"}\u3002\u8BF7\u5728\u56DE\u590D\u5F00\u5934\u7B80\u77ED\u8BE2\u95EE\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u7EE7\u7EED\uFF0C\u4F8B\u5982\uFF1A"\u4F60\u60F3\u7EE7\u7EED\u5728\u300CXX\u300D\u9879\u76EE\u4E2D\u5DE5\u4F5C\u5417\uFF1F"]`},...r]}let Ue=i?.desktopRecentContext;if(!c&&Ue&&Ue.length>0&&r.length>0){let T=r[r.length-1],F=T?.role==="user"&&typeof T.content=="string"?T.content:"";if(AE(F)){let B={role:"system",content:"[\u4EE5\u4E0B\u662F\u7528\u6237\u5728\u684C\u9762\u7AEF\u7684\u8FD1\u671F\u5BF9\u8BDD\uFF0C\u4F9B\u4F60\u53C2\u8003\u4EE5\u4FDD\u6301\u4E0A\u4E0B\u6587\u8FDE\u8D2F]"},Re={role:"system",content:"[\u684C\u9762\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u7ED3\u675F\uFF0C\u4EE5\u4E0B\u662F\u5F53\u524D IM \u7AEF\u7684\u5BF9\u8BDD]"};ie=[B,...Ue,Re,...ie],this.log(`[continuation] injected ${Ue.length} desktop messages as reference`)}}if(!wn(o,p)?.title){let T=typeof ce?.content=="string"?ce.content:Array.isArray(ce?.content)?ce.content.filter(F=>F.type==="text").map(F=>F.text??"").join(""):"";if(T.trim()){let F=null,B=this.resolveClientForPurpose("smallModel");B&&(F=await lm(T,{transport:B.transport,apiKey:B.apiKey,model:B.model})),F||(F=T.trim().slice(0,20)+(T.trim().length>20?"\u2026":"")),await tt(o,{title:F},p).catch(()=>{}),this.sendNotification("session.info",{sessionId:o,title:F,projectId:i?.projectId||void 0}),this.log(`[title-gen] generated title for session ${o}: "${F}"`)}}for await(let T of b.run({turnId:t,sessionId:o,messages:ie,tools:ve,systemPrompt:S,config:y},m.signal)){let F=new Date().toISOString();switch(T.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:T.turnId,text:T.text,item:{id:`${t}-delta`,type:"message",role:"assistant",text:T.text,createdAt:F}});break;case"end":if(this.sendNotification("turn.end",{turnId:T.turnId,content:T.content,usage:T.usage,model:T.model,provider:T.provider,item:{id:`${t}-end`,type:"message",role:"assistant",text:T.content,createdAt:F}}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,T.model??this.currentModel);let B=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:T.model??this.currentModel,sessionCostUSD:B.totalInputTokens*3e-6+B.totalOutputTokens*15e-6})}T.content&&(this.lastAssistantMessageForExtract=T.content,wl(o,{role:"assistant",content:T.content},p,t).catch(()=>{}));break;case"error":if(this.sendNotification("turn.error",{turnId:T.turnId,error:{message:T.error,code:T.code}}),T.usage&&this.sessionState){this.sessionState.addUsage(T.usage,this.currentModel);let B=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:T.turnId,usage:T.usage,model:this.currentModel,sessionCostUSD:B.totalInputTokens*3e-6+B.totalOutputTokens*15e-6})}break;case"skill_instruction":if(this.sendNotification("turn.skill_instruction",{turnId:T.turnId,instruction:T.instruction}),T.instruction.type==="skill.create"){let B=T.instruction,he=fr.join(p,".qlogicagent","skills"),Ut=fr.join(he,B.suggestedName),g=fr.join(Ut,"SKILL.md");if(!uo.existsSync(g)){let v=Bs({name:B.suggestedName,description:B.description,tools:B.tools,body:`# ${B.suggestedName}
700
700
 
701
701
  Auto-learned multi-step workflow using: ${B.tools.join(", ")}.
702
702
  `,version:"1.0.0",category:"learned"}),_=Ws(v,B.suggestedName);if(_.valid){uo.mkdirSync(Ut,{recursive:!0}),uo.writeFileSync(g,v,"utf8"),gt();let C=H(),R=We(C);Qt(R,B.suggestedName,"learned"),Ve(C,R),this.log(`[skill-auto-persist] Created skill "${B.suggestedName}" from turn ${T.turnId}`)}else this.log(`[skill-auto-persist] Validation failed for "${B.suggestedName}": ${_.errors.join(", ")}`)}}break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:T.turnId,callId:T.callId,name:T.name,arguments:T.arguments,item:{id:T.callId,type:"tool_call",role:"assistant",toolName:T.name,toolCallId:T.callId,arguments:T.arguments,createdAt:F}}),this.sessionState?.recordToolCall();break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:T.turnId,callId:T.callId,name:T.name,ok:T.ok,...T.error?{error:T.error}:{},...T.outputPreview?{outputPreview:T.outputPreview}:{},item:{id:`${T.callId}-result`,type:"tool_result",role:"assistant",toolName:T.name,toolCallId:T.callId,output:T.ok?T.outputPreview??"":T.error,approved:T.ok,createdAt:F}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:T.turnId,callId:T.callId,name:T.name,reason:T.reason,item:{id:`${T.callId}-blocked`,type:"tool_blocked",role:"system",toolName:T.name,toolCallId:T.callId,text:T.reason,approved:!1,createdAt:F}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:T.turnId,action:T.action,...T.detail?{detail:T.detail}:{},item:{id:`${t}-recovery-${ni().slice(0,8)}`,type:"recovery",role:"system",strategy:T.action,text:T.detail,createdAt:F}});break;case"plan_update":this.sendNotification("turn.plan_update",{turnId:T.turnId,slug:T.slug,content:T.content,item:{id:`${t}-plan-${ni().slice(0,8)}`,type:"plan_update",role:"assistant",text:T.content,createdAt:F}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:T.turnId,text:T.text});break;case"suggestions":this.sendNotification("turn.suggestions",{turnId:T.turnId,items:T.items});break;case"media_result":this.sendNotification("turn.media_result",{turnId:T.turnId,mediaType:T.mediaType,url:T.url,...T.model?{model:T.model}:{},...T.provider?{provider:T.provider}:{},...T.taskId?{taskId:T.taskId}:{}});break;case"artifact":this.sendNotification("turn.artifact",{turnId:T.turnId,artifactId:T.artifactId,type:T.artifactType,title:T.title,...T.filePath?{filePath:T.filePath}:{},...T.language?{language:T.language}:{},...T.content?{content:T.content}:{},...T.mimeType?{mimeType:T.mimeType}:{}});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:T.turnId,subagentId:T.subagentId,agentType:T.agentType,...T.prompt?{prompt:T.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:T.turnId,subagentId:T.subagentId,agentType:T.agentType,ok:T.ok,...T.outputPreview?{outputPreview:T.outputPreview}:{},...T.error?{error:T.error}:{}});break;case"annotations":this.sendNotification("turn.annotations",{turnId:T.turnId,annotations:T.annotations});break;case"heartbeat":this.sendNotification("turn.heartbeat",{turnId:T.turnId,message:T.message});break;case"tool_use_summary":this.sendNotification("turn.tool_use_summary",{turnId:T.turnId,summary:T.summary});break}}if(this.log(`turn ${t} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){am(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:p,messageCount:r.length},p).catch(()=>{});let T=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:p,turnCount:T.turnCount,projectId:i?.projectId||void 0});let F=this.resolveClientForPurpose("smallModel");if(F&&cm(o,{sessionId:o,projectId:"",createdAt:"",lastActiveAt:"",turnCount:T.turnCount,messageCount:r.length},r,{transport:F.transport,apiKey:F.apiKey,model:F.model},p),this.generateSuggestions(t,r),this.petAwardXp("turn.end"),this.petReactionAfterTurn(r),i?.sessionType==="group"&&this.sessionState){let B=this.sessionState.createSnapshot(),Re=wn(o,p);Re&&Vh({...Re,turnCount:B.turnCount},p).then(he=>{he.split&&this.sendNotification("session-update",{sessionId:he.activeSessionId,projectId:i?.projectId??"",title:"",type:"group"})}).catch(()=>{})}}}catch(y){if(m.signal.aborted)this.sendNotification("turn.error",{turnId:t,error:{message:"Turn aborted",code:"ABORTED"}});else{let b=y instanceof Error?y.message:String(y);this.sendNotification("turn.error",{turnId:t,error:{message:b,code:"INTERNAL_ERROR"}})}}finally{this.activeTurn===m&&(this.activeTurn=null),h()}}mt();import{randomUUID as dy}from"node:crypto";async function oi(n){let e=n.params??{},t=e.turnId??dy(),o=e.sessionId,r=e.config,s=r?.memoryRoot??"",i=r?.transcriptDir??"",a=r?.dreamSessionIds??[];n.id!==void 0&&this.sendResponse(n.id,{accepted:!0,turnId:t});let l=new AbortController;this.activeTurn=l,this.log(`dream ${t} starting (session: ${o}, sessions reviewing: ${a.length})`),this.sendNotification("system.activity",{category:"dream",level:"info",title:"\u68A6\u5883\u6574\u7406\u542F\u52A8",detail:`\u6B63\u5728\u56DE\u987E ${a.length} \u4E2A\u4F1A\u8BDD\u7684\u8BB0\u5FC6...`});let c={provider:r?.provider,model:r?.model,apiKey:r?.apiKey,baseUrl:r?.baseUrl,maxRounds:r?.maxRounds,temperature:r?.temperature,contextWindowTokens:r?.contextWindowTokens,maxOutputTokens:r?.maxOutputTokens,modelMaxOutputTokens:r?.modelMaxOutputTokens,reasoning:r?.reasoning,promptCacheKey:r?.promptCacheKey,promptCacheRetention:r?.promptCacheRetention,serviceTier:r?.serviceTier,openaiBuiltinTools:r?.openaiBuiltinTools,maxToolCalls:r?.maxToolCalls,parallelToolCalls:r?.parallelToolCalls,textVerbosity:r?.textVerbosity};{let u=c.provider??"",p=c.model??"";if(u&&p){let m=X().getModelInfo(u,p);m?.streamRequired&&(c.streamRequired=!0),!c.contextWindowTokens&&m?.contextWindow&&(c.contextWindowTokens=m.contextWindow)}}if(!this.resolveAgent(c)){this.sendNotification("turn.start",{turnId:t}),this.sendNotification("turn.error",{turnId:t,error:{message:"No LLM provider configured for dream.",code:"NO_PROVIDER"}});return}this.sendNotification("turn.start",{turnId:t});try{let u={context:{memoryRoot:s,transcriptDir:i,currentSessionId:o,listSessionsSince:async()=>a,currentSessionTurnCount:r?.currentSessionTurnCount??0},triggerConfig:{force:r?.force!==!1},transport:this.currentTransport,toolInvoker:{invoke:async(m,h,f,y)=>{if(h.startsWith("$"))return{result:f};let b=findTool(h);if(!b)return{result:"",error:`Unknown tool: ${h}`};let k=`tc_${dy().slice(0,8)}`;try{let x=JSON.parse(f),I=await b.execute(k,x,y);return{result:I.content.map(O=>O.text??"").join(`
703
- `),error:I.details?.error}}catch(x){return{result:"",error:x instanceof Error?x.message:String(x)}}}},tools:getToolManifest(),apiKey:this.currentApiKey,model:c.model??this.currentModel,log:{info:m=>this.log(m),warn:m=>this.log(`[warn] ${m}`),error:m=>this.log(`[error] ${m}`),debug:m=>{this.verbose&&this.log(`[debug] ${m}`)}},hooks:this.currentHooks??void 0,parentSignal:l.signal,memoryProvider:this.memoryProvider??void 0,memoryUserId:this.memoryUserId||void 0},p=await runDream(u);if(p.ok){if(this.memoryProvider&&this.memoryUserId)try{let m=await runDecayCycle({adapter:this.memoryProvider,userId:this.memoryUserId,memoryRoot:s,log:{info:h=>this.log(h),debug:h=>{this.verbose&&this.log(h)}}});m.ran&&(this.sendNotification("memory.decay.completed",{decayed:m.decayed,archived:m.archived,durationMs:m.durationMs}),this.sendNotification("system.activity",{category:"decay",level:"info",title:"\u8BB0\u5FC6\u8870\u51CF\u5B8C\u6210",detail:`\u8870\u51CF ${m.decayed} \u6761\uFF0C\u5F52\u6863 ${m.archived} \u6761 (${m.durationMs}ms)`}))}catch(m){this.log(`[decay] post-dream decay error: ${m instanceof Error?m.message:String(m)}`)}this.sendNotification("system.activity",{category:"dream",level:"success",title:"\u68A6\u5883\u6574\u7406\u5B8C\u6210",detail:`\u56DE\u987E ${p.sessionsReviewed} \u4E2A\u4F1A\u8BDD\uFF0C\u6574\u7406 ${p.filesTouched.length} \u4E2A\u8BB0\u5FC6\u6587\u4EF6\uFF0C\u8017\u65F6 ${p.durationMs}ms`}),this.sendNotification("turn.end",{turnId:t,content:`Dream consolidation completed. ${p.sessionsReviewed} sessions reviewed, ${p.filesTouched.length} files touched. Duration: ${p.durationMs}ms.`,usage:{inputTokens:0,outputTokens:0}})}else this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5931\u8D25",detail:p.error??"\u672A\u77E5\u9519\u8BEF"}),this.sendNotification("turn.error",{turnId:t,error:{message:p.error??"Dream consolidation failed",code:"DREAM_FAILED"}});this.log(`dream ${t} completed`)}catch(u){if(l.signal.aborted)this.sendNotification("system.activity",{category:"dream",level:"warn",title:"\u68A6\u5883\u6574\u7406\u88AB\u4E2D\u65AD"}),this.sendNotification("turn.error",{turnId:t,error:{message:"Dream aborted",code:"ABORTED"}});else{let p=u instanceof Error?u.message:String(u);this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5F02\u5E38",detail:p}),this.sendNotification("turn.error",{turnId:t,error:{message:p,code:"INTERNAL_ERROR"}})}}finally{this.activeTurn===l&&(this.activeTurn=null)}}import{randomUUID as ME}from"node:crypto";var gr=class{nodes=new Map;constructor(e){for(let t of e){if(this.nodes.has(t.taskId))throw new Error(`Duplicate task ID: ${t.taskId}`);this.nodes.set(t.taskId,{taskId:t.taskId,assignee:t.assignee,prompt:t.prompt,dependsOn:t.dependsOn??[],status:"pending"})}this.validateDag()}getAllTasks(){return[...this.nodes.values()]}getTask(e){return this.nodes.get(e)}getReadyTasks(){let e=[];for(let t of this.nodes.values()){if(t.status!=="pending")continue;t.dependsOn.every(r=>this.nodes.get(r)?.status==="completed")&&e.push(t)}return e}markRunning(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);if(t.status!=="pending")throw new Error(`Task ${e} is ${t.status}, cannot start`);t.status="running",t.startedAt=Date.now()}markCompleted(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="running")throw new Error(`Task ${e} is ${o.status}, cannot complete`);o.status="completed",o.result=t,o.completedAt=Date.now()}markFailed(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);o.status="failed",o.error=t,o.completedAt=Date.now()}markPaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="running"&&(t.status="paused")}resumePaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="paused"&&(t.status="pending")}isFinished(){for(let e of this.nodes.values())if(e.status==="running"||e.status==="paused"||e.status==="pending"&&!e.dependsOn.some(o=>this.nodes.get(o)?.status==="failed"))return!1;return!0}isAllCompleted(){return[...this.nodes.values()].every(e=>e.status==="completed")}getBlockedTasks(){return[...this.nodes.values()].filter(e=>e.status!=="pending"?!1:e.dependsOn.some(t=>this.nodes.get(t)?.status==="failed"))}pauseAll(){for(let e of this.nodes.values())e.status==="running"&&(e.status="paused")}resumeAll(){for(let e of this.nodes.values())e.status==="paused"&&(e.status="pending")}serialize(){return[...this.nodes.values()].map(e=>({taskId:e.taskId,assignee:e.assignee,prompt:e.prompt,dependsOn:e.dependsOn,status:e.status,result:e.result,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt}))}restore(e){for(let t of e){let o=this.nodes.get(t.taskId);o&&(o.status=t.status==="running"?"pending":t.status,o.result=t.result,o.error=t.error,o.startedAt=t.startedAt,o.completedAt=t.completedAt)}}addTask(e){if(this.nodes.has(e.taskId))throw new Error(`Task "${e.taskId}" already exists`);for(let o of e.dependsOn??[])if(!this.nodes.has(o))throw new Error(`New task "${e.taskId}" depends on unknown task "${o}"`);let t={taskId:e.taskId,assignee:e.assignee,prompt:e.prompt,dependsOn:e.dependsOn??[],status:"pending"};this.nodes.set(e.taskId,t);try{this.validateDag()}catch(o){throw this.nodes.delete(e.taskId),o}}addTasks(e){let t=[];try{for(let o of e)this.addTask(o),t.push(o.taskId)}catch(o){for(let r of t)this.nodes.delete(r);throw o}}removeTask(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);if(t.status==="running")throw new Error(`Cannot remove running task "${e}"`);if(t.status==="completed")throw new Error(`Cannot remove completed task "${e}"`);for(let o of this.nodes.values()){let r=o.dependsOn.indexOf(e);r!==-1&&o.dependsOn.splice(r,1)}this.nodes.delete(e)}retryTask(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="failed")throw new Error(`Task "${e}" is ${o.status}, only failed tasks can be retried`);o.status="pending",o.error=void 0,o.result=void 0,o.startedAt=void 0,o.completedAt=void 0,t&&(o.prompt=t)}updateTaskPrompt(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="pending")throw new Error(`Task "${e}" is ${o.status}, can only update pending tasks`);o.prompt=t}reassignTask(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="pending")throw new Error(`Task "${e}" is ${o.status}, can only reassign pending tasks`);o.assignee=t}addDependency(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(!this.nodes.has(t))throw new Error(`Unknown dependency task: ${t}`);if(!o.dependsOn.includes(t)){o.dependsOn.push(t);try{this.validateDag()}catch(r){throw o.dependsOn.pop(),r}}}getProgress(){let e=0,t=0,o=0,r=0,s=0;for(let i of this.nodes.values())switch(i.status){case"completed":e++;break;case"running":t++;break;case"failed":o++;break;case"pending":r++;break;case"paused":s++;break}return{total:this.nodes.size,completed:e,running:t,failed:o,pending:r,paused:s}}validateDag(){for(let r of this.nodes.values())for(let s of r.dependsOn)if(!this.nodes.has(s))throw new Error(`Task "${r.taskId}" depends on unknown task "${s}"`);let e=new Set,t=new Set,o=r=>{if(t.has(r))throw new Error(`Cycle detected involving task "${r}"`);if(e.has(r))return;t.add(r);let s=this.nodes.get(r);for(let i of s.dependsOn)o(i);t.delete(r),e.add(r)};for(let r of this.nodes.keys())o(r)}};var hr=class{maxTotalTokens;maxDuration;usedTokens=0;startedAt;warningEmitted=!1;constructor(e){this.maxTotalTokens=e?.maxTotalTokens,this.maxDuration=e?.maxDuration,this.startedAt=Date.now()}addUsage(e,t){this.usedTokens+=e+t}addFromTracker(e){if(!e.hasData())return;let t=e.getUsage();this.usedTokens+=t.totalTokens}getElapsed(){return Date.now()-this.startedAt}getBudget(){return{maxTotalTokens:this.maxTotalTokens,maxDuration:this.maxDuration,usedTokens:this.usedTokens,elapsed:this.getElapsed()}}check(){let e=this.getElapsed();if(this.maxDuration&&e>=this.maxDuration)return{action:"exceeded",percentage:Math.round(e/this.maxDuration*100),usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(this.maxTotalTokens){let o=Math.round(this.usedTokens/this.maxTotalTokens*100);if(this.usedTokens>=this.maxTotalTokens)return{action:"exceeded",percentage:o,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(o>=80&&!this.warningEmitted)return this.warningEmitted=!0,{action:"warning",percentage:o,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}return{action:"ok",percentage:this.maxTotalTokens?Math.round(this.usedTokens/this.maxTotalTokens*100):0,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}restore(e){this.usedTokens=e.usedTokens,this.startedAt=e.startedAt,this.warningEmitted=e.warningEmitted}serialize(){return{usedTokens:this.usedTokens,startedAt:this.startedAt,warningEmitted:this.warningEmitted}}};import{join as dd}from"node:path";import{mkdir as _E,readdir as AE}from"node:fs/promises";le();function uy(n){return dd(Oe(n),"products")}function py(n,e){return dd(uy(e),n)}function my(n,e){return dd(py(n,e),"product-state.json")}async function fy(n,e){let t=py(n.productId,e);await _E(t,{recursive:!0}),await eo(my(n.productId,e),n)}async function ud(n,e){return An(my(n,e))}async function gy(n){let e=uy(n),t;try{t=await AE(e)}catch{return[]}let o=[];for(let r of t){let s=await ud(r,n);s&&o.push(s)}return o}var yr=class n{constructor(e={}){this.callbacks=e}callbacks;static DEFAULT_INTERVAL=5*6e4;static LONG_RUNNING_INTERVAL=30*6e4;static LONG_RUNNING_THRESHOLD=2880*6e4;timer=null;lastCheckpointAt=0;cwd;start(e){this.cwd=e,this.stop(),this.timer=setInterval(()=>{let t=this.callbacks.getState?.();t&&this.checkpoint(t).catch(o=>{this.callbacks.log?.warn(`[checkpoint] periodic save failed: ${o instanceof Error?o.message:String(o)}`)})},n.DEFAULT_INTERVAL),this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getInterval(e){return e>n.LONG_RUNNING_THRESHOLD?n.LONG_RUNNING_INTERVAL:n.DEFAULT_INTERVAL}isDue(e){if(this.lastCheckpointAt===0)return!0;let t=this.getInterval(e);return Date.now()-this.lastCheckpointAt>=t}async checkpoint(e){let t=new Date().toISOString();e.lastCheckpointAt=t,await fy(e,this.cwd),this.lastCheckpointAt=Date.now(),this.callbacks.onCheckpoint?.(e.productId,t),this.callbacks.log?.info(`[checkpoint] saved ${e.productId} at ${t}`)}getLastCheckpointAt(){return this.lastCheckpointAt}};import{execFile as PE}from"node:child_process";import{promisify as IE}from"node:util";import{join as hy}from"node:path";import{mkdir as CE,rm as EE}from"node:fs/promises";var po=IE(PE);async function br(n){try{let{stdout:e}=await po("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8"});return e.trim()}catch{return null}}async function ri(n,e,t){let o=hy(n,".worktrees");await CE(o,{recursive:!0});let r=hy(o,e),i=["worktree","add","-B",`solo/${e}`,r];return t?i.push(t):i.push("HEAD"),await po("git",i,{cwd:n,encoding:"utf8"}),r}async function pd(n){try{await po("git",["add","-A"],{cwd:n});let{stdout:e}=await po("git",["diff","--cached","--stat"],{cwd:n,encoding:"utf8"});return e.trim()}catch{return""}}async function yy(n,e){try{await po("git",["worktree","remove","--force",e],{cwd:n,encoding:"utf8"})}catch{try{await EE(e,{recursive:!0,force:!0})}catch{}}}async function by(n,e){let{stdout:t}=await po("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:n,encoding:"utf8"});return t.trim()}var si=class{constructor(e,t,o,r={}){this.processManager=e;this.acpDetector=t;this.configStore=o;this.callbacks=r}processManager;acpDetector;configStore;callbacks;sessions=new Map;async create(e){let{name:t,cwd:o,instances:r,tasks:s,budget:i}=e;if(r.length===0)throw new Error("Product requires at least 1 instance");if(s.length===0)throw new Error("Product requires at least 1 task");let a=new Set(r.map(b=>b.name));for(let b of s)if(!a.has(b.assignee))throw new Error(`Task "${b.taskId}" references unknown instance "${b.assignee}"`);let l=`product-${ME().slice(0,8)}`,c=new gr(s),d=new hr(i),u=new yr({onCheckpoint:(b,k)=>this.callbacks.onCheckpointed?.(b,k),getState:()=>{let b=this.sessions.get(l);return b?this.buildPersistedState(b):null},log:this.callbacks.log}),p=await br(o),m=r.map((b,k)=>({instanceId:`${l}:${b.name}:${k}`,name:b.name,agentId:b.agentId,state:"idle"})),h={productId:l,name:t,cwd:o,phase:"active",instances:m,dag:c,budget:d,checkpoint:u,createdAt:new Date().toISOString(),gitRoot:p};this.sessions.set(l,h),u.start(o),this.callbacks.log?.info(`[product] created ${l} "${t}" with ${r.length} instances, ${s.length} tasks`);let f=s.map(b=>({id:b.taskId,label:b.taskId,deps:b.dependsOn??[]})),y=[];for(let b of s)if(b.dependsOn)for(let k of b.dependsOn)y.push({from:k,to:b.taskId});return this.callbacks.onDagTopology?.(l,f,y),setTimeout(()=>this.scheduleNext(h),0),l}async resume(e,t){let o=await ud(e,t);if(!o)throw new Error(`Product ${e} not found on disk`);let r=new gr(o.tasks);r.restore(o.tasks);let s=new hr({maxTotalTokens:o.budget.maxTotalTokens,maxDuration:o.budget.maxDuration});s.restore(o.budget);let i=new yr({onCheckpoint:(d,u)=>this.callbacks.onCheckpointed?.(d,u),getState:()=>{let d=this.sessions.get(e);return d?this.buildPersistedState(d):null},log:this.callbacks.log}),a=await br(o.cwd),l=o.instances.map((d,u)=>({instanceId:`${e}:${d.name}:${u}`,name:d.name,agentId:d.agentId,state:"idle"})),c={productId:o.productId,name:o.name,cwd:o.cwd,phase:"active",instances:l,dag:r,budget:s,checkpoint:i,createdAt:o.createdAt,gitRoot:a};this.sessions.set(e,c),i.start(o.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(c)}async pause(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase!=="active")throw new Error(`Product ${e} is not active`);t.phase="paused",t.dag.pauseAll();for(let o of t.instances)if(o.state==="running"&&o.memberId){try{this.processManager.kill(o.memberId)}catch{}o.state="paused"}await t.checkpoint.checkpoint(this.buildPersistedState(t)),t.checkpoint.stop(),this.callbacks.log?.info(`[product] paused ${e}`)}async checkpoint(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);await t.checkpoint.checkpoint(this.buildPersistedState(t))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase==="active"){t.phase="failed",t.dag.pauseAll();for(let o of t.instances)if(o.state==="running"&&o.memberId){try{this.processManager.kill(o.memberId)}catch{}o.state="failed"}}t.checkpoint.stop(),this.sessions.delete(e),this.callbacks.log?.info(`[product] deleted ${e}`)}async rollback(e,t){let o=this.sessions.get(e);if(!o)throw new Error(`Product ${e} not found`);let r=o.cwd;await this.delete(e),await this.resume(e,r),this.callbacks.log?.info(`[product] rolled back ${e} to checkpoint ${t}`)}getStatus(e){let t=this.sessions.get(e);return t?{productId:t.productId,name:t.name,phase:t.phase,instances:t.instances.map(o=>{let s=(o.memberId?this.processManager.getUsageTracker(o.memberId):null)?.getUsage();return{instanceId:o.instanceId,name:o.name,agentId:o.agentId,state:o.state,worktreePath:o.worktreePath,usage:s&&(s.inputTokens>0||s.outputTokens>0)?{inputTokens:s.inputTokens,outputTokens:s.outputTokens}:void 0}}),tasks:t.dag.getAllTasks().map(o=>({taskId:o.taskId,assignee:o.assignee,status:o.status,result:o.result,error:o.error,startedAt:o.startedAt?new Date(o.startedAt).toISOString():void 0,completedAt:o.completedAt?new Date(o.completedAt).toISOString():void 0})),budget:t.budget.getBudget(),lastCheckpointAt:new Date(t.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}:null}async list(e){let t=[];for(let r of this.sessions.values()){let s=r.dag.getAllTasks();t.push({productId:r.productId,name:r.name,phase:r.phase,instanceCount:r.instances.length,taskCount:s.length,completedTasks:s.filter(i=>i.status==="completed").length,createdAt:r.createdAt,lastCheckpointAt:new Date(r.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()})}let o=await gy(e);for(let r of o)this.sessions.has(r.productId)||t.push({productId:r.productId,name:r.name,phase:r.phase,instanceCount:r.instances.length,taskCount:r.tasks.length,completedTasks:r.tasks.filter(s=>s.status==="completed").length,createdAt:r.createdAt,lastCheckpointAt:r.lastCheckpointAt});return t}scheduleNext(e){if(e.phase!=="active")return;let t=e.budget.check();if(t.action==="exceeded"){this.callbacks.log?.warn(`[product] ${e.productId} budget exceeded, auto-pausing`),this.pause(e.productId).catch(r=>{this.callbacks.log?.warn(`[product] auto-pause failed: ${r instanceof Error?r.message:String(r)}`)});return}if(t.action==="warning"&&this.callbacks.onBudgetWarning?.(e.productId,t.usedTokens,t.maxTotalTokens,t.percentage),e.dag.isFinished()){this.finishProduct(e);return}let o=e.dag.getReadyTasks();for(let r of o)this.dispatchTask(e,r)}dispatchTask(e,t){let o=e.instances.find(r=>r.name===t.assignee);if(!o){e.dag.markFailed(t.taskId,`No instance found for assignee "${t.assignee}"`),this.callbacks.onTaskFailed?.(e.productId,t.taskId,`No instance for "${t.assignee}"`),this.scheduleNext(e);return}e.dag.markRunning(t.taskId),o.state="running",this.callbacks.onTaskStarted?.(e.productId,t.taskId,t.assignee),this.callbacks.log?.info(`[product] ${e.productId} dispatching task ${t.taskId} to ${t.assignee}`),this.runTask(e,o,t).catch(r=>{this.callbacks.log?.warn(`[product] task dispatch error: ${r instanceof Error?r.message:String(r)}`)})}async runTask(e,t,o){let r=`${e.productId}:${t.name}:${o.taskId}`;t.memberId=r;try{let s=this.acpDetector.buildExternalDescriptor(t.agentId);if(!s)throw new Error(`Agent ${t.agentId} is not available`);let i=e.cwd;if(e.gitRoot){let d=`${e.productId}-${t.name}-${o.taskId}`;try{i=await ri(e.gitRoot,d),t.worktreePath=i}catch{this.callbacks.log?.warn(`[product] worktree creation failed for ${o.taskId}, using project cwd`)}}await this.processManager.spawn({memberId:r,name:`product-${t.name}`,cwd:i,prompt:o.prompt,external:s});let a=await this.processManager.sendTask(r,o.prompt),l=typeof a=="string"?a:JSON.stringify(a),c=this.processManager.getUsageTracker(r);if(c?.hasData()){let d=c.getUsage();e.budget.addUsage(d.inputTokens,d.outputTokens);let u=e.budget.getBudget();this.callbacks.onBudgetUpdate?.(e.productId,u.usedTokens,0,u.elapsed,u.maxTotalTokens)}e.dag.markCompleted(o.taskId,l),t.state="completed",this.callbacks.onTaskCompleted?.(e.productId,o.taskId,l);try{this.processManager.kill(r)}catch{}this.processManager.remove(r)}catch(s){let i=s instanceof Error?s.message:String(s);e.dag.markFailed(o.taskId,i),t.state="failed",this.callbacks.onTaskFailed?.(e.productId,o.taskId,i);try{this.processManager.kill(r)}catch{}try{this.processManager.remove(r)}catch{}}try{await e.checkpoint.checkpoint(this.buildPersistedState(e))}catch(s){this.callbacks.log?.warn(`[product] checkpoint failed: ${s instanceof Error?s.message:String(s)}`)}this.scheduleNext(e)}finishProduct(e){if(e.dag.isAllCompleted()){e.phase="completed";let t=e.dag.getAllTasks(),o=`Product "${e.name}" completed: ${t.length} tasks all done.`;this.callbacks.onCompleted?.(e.productId,o)}else{e.phase="failed";let o=e.dag.getAllTasks().filter(i=>i.status==="failed").length,r=e.dag.getBlockedTasks().length,s=`Product "${e.name}" finished with ${o} failed, ${r} blocked tasks.`;this.callbacks.onCompleted?.(e.productId,s)}e.checkpoint.stop(),e.checkpoint.checkpoint(this.buildPersistedState(e)).catch(t=>{this.callbacks.log?.warn(`[product] final checkpoint failed: ${t instanceof Error?t.message:String(t)}`)}),this.callbacks.log?.info(`[product] ${e.productId} finished (phase=${e.phase})`)}buildPersistedState(e){return{productId:e.productId,name:e.name,phase:e.phase,cwd:e.cwd,instances:e.instances.map(t=>({name:t.name,role:"",agentId:t.agentId})),tasks:e.dag.serialize(),budget:e.budget.serialize(),createdAt:e.createdAt,lastCheckpointAt:new Date(e.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}}};import{randomUUID as ky}from"node:crypto";function OE(n,e){let t=e?`
703
+ `),error:I.details?.error}}catch(x){return{result:"",error:x instanceof Error?x.message:String(x)}}}},tools:getToolManifest(),apiKey:this.currentApiKey,model:c.model??this.currentModel,log:{info:m=>this.log(m),warn:m=>this.log(`[warn] ${m}`),error:m=>this.log(`[error] ${m}`),debug:m=>{this.verbose&&this.log(`[debug] ${m}`)}},hooks:this.currentHooks??void 0,parentSignal:l.signal,memoryProvider:this.memoryProvider??void 0,memoryUserId:this.memoryUserId||void 0},p=await runDream(u);if(p.ok){if(this.memoryProvider&&this.memoryUserId)try{let m=await runDecayCycle({adapter:this.memoryProvider,userId:this.memoryUserId,memoryRoot:s,log:{info:h=>this.log(h),debug:h=>{this.verbose&&this.log(h)}}});m.ran&&(this.sendNotification("memory.decay.completed",{decayed:m.decayed,archived:m.archived,durationMs:m.durationMs}),this.sendNotification("system.activity",{category:"decay",level:"info",title:"\u8BB0\u5FC6\u8870\u51CF\u5B8C\u6210",detail:`\u8870\u51CF ${m.decayed} \u6761\uFF0C\u5F52\u6863 ${m.archived} \u6761 (${m.durationMs}ms)`}))}catch(m){this.log(`[decay] post-dream decay error: ${m instanceof Error?m.message:String(m)}`)}this.sendNotification("system.activity",{category:"dream",level:"success",title:"\u68A6\u5883\u6574\u7406\u5B8C\u6210",detail:`\u56DE\u987E ${p.sessionsReviewed} \u4E2A\u4F1A\u8BDD\uFF0C\u6574\u7406 ${p.filesTouched.length} \u4E2A\u8BB0\u5FC6\u6587\u4EF6\uFF0C\u8017\u65F6 ${p.durationMs}ms`}),this.sendNotification("turn.end",{turnId:t,content:`Dream consolidation completed. ${p.sessionsReviewed} sessions reviewed, ${p.filesTouched.length} files touched. Duration: ${p.durationMs}ms.`,usage:{inputTokens:0,outputTokens:0}})}else this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5931\u8D25",detail:p.error??"\u672A\u77E5\u9519\u8BEF"}),this.sendNotification("turn.error",{turnId:t,error:{message:p.error??"Dream consolidation failed",code:"DREAM_FAILED"}});this.log(`dream ${t} completed`)}catch(u){if(l.signal.aborted)this.sendNotification("system.activity",{category:"dream",level:"warn",title:"\u68A6\u5883\u6574\u7406\u88AB\u4E2D\u65AD"}),this.sendNotification("turn.error",{turnId:t,error:{message:"Dream aborted",code:"ABORTED"}});else{let p=u instanceof Error?u.message:String(u);this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5F02\u5E38",detail:p}),this.sendNotification("turn.error",{turnId:t,error:{message:p,code:"INTERNAL_ERROR"}})}}finally{this.activeTurn===l&&(this.activeTurn=null)}}import{randomUUID as DE}from"node:crypto";var gr=class{nodes=new Map;constructor(e){for(let t of e){if(this.nodes.has(t.taskId))throw new Error(`Duplicate task ID: ${t.taskId}`);this.nodes.set(t.taskId,{taskId:t.taskId,assignee:t.assignee,prompt:t.prompt,dependsOn:t.dependsOn??[],status:"pending"})}this.validateDag()}getAllTasks(){return[...this.nodes.values()]}getTask(e){return this.nodes.get(e)}getReadyTasks(){let e=[];for(let t of this.nodes.values()){if(t.status!=="pending")continue;t.dependsOn.every(r=>this.nodes.get(r)?.status==="completed")&&e.push(t)}return e}markRunning(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);if(t.status!=="pending")throw new Error(`Task ${e} is ${t.status}, cannot start`);t.status="running",t.startedAt=Date.now()}markCompleted(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="running")throw new Error(`Task ${e} is ${o.status}, cannot complete`);o.status="completed",o.result=t,o.completedAt=Date.now()}markFailed(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);o.status="failed",o.error=t,o.completedAt=Date.now()}markPaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="running"&&(t.status="paused")}resumePaused(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);t.status==="paused"&&(t.status="pending")}isFinished(){for(let e of this.nodes.values())if(e.status==="running"||e.status==="paused"||e.status==="pending"&&!e.dependsOn.some(o=>this.nodes.get(o)?.status==="failed"))return!1;return!0}isAllCompleted(){return[...this.nodes.values()].every(e=>e.status==="completed")}getBlockedTasks(){return[...this.nodes.values()].filter(e=>e.status!=="pending"?!1:e.dependsOn.some(t=>this.nodes.get(t)?.status==="failed"))}pauseAll(){for(let e of this.nodes.values())e.status==="running"&&(e.status="paused")}resumeAll(){for(let e of this.nodes.values())e.status==="paused"&&(e.status="pending")}serialize(){return[...this.nodes.values()].map(e=>({taskId:e.taskId,assignee:e.assignee,prompt:e.prompt,dependsOn:e.dependsOn,status:e.status,result:e.result,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt}))}restore(e){for(let t of e){let o=this.nodes.get(t.taskId);o&&(o.status=t.status==="running"?"pending":t.status,o.result=t.result,o.error=t.error,o.startedAt=t.startedAt,o.completedAt=t.completedAt)}}addTask(e){if(this.nodes.has(e.taskId))throw new Error(`Task "${e.taskId}" already exists`);for(let o of e.dependsOn??[])if(!this.nodes.has(o))throw new Error(`New task "${e.taskId}" depends on unknown task "${o}"`);let t={taskId:e.taskId,assignee:e.assignee,prompt:e.prompt,dependsOn:e.dependsOn??[],status:"pending"};this.nodes.set(e.taskId,t);try{this.validateDag()}catch(o){throw this.nodes.delete(e.taskId),o}}addTasks(e){let t=[];try{for(let o of e)this.addTask(o),t.push(o.taskId)}catch(o){for(let r of t)this.nodes.delete(r);throw o}}removeTask(e){let t=this.nodes.get(e);if(!t)throw new Error(`Unknown task: ${e}`);if(t.status==="running")throw new Error(`Cannot remove running task "${e}"`);if(t.status==="completed")throw new Error(`Cannot remove completed task "${e}"`);for(let o of this.nodes.values()){let r=o.dependsOn.indexOf(e);r!==-1&&o.dependsOn.splice(r,1)}this.nodes.delete(e)}retryTask(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="failed")throw new Error(`Task "${e}" is ${o.status}, only failed tasks can be retried`);o.status="pending",o.error=void 0,o.result=void 0,o.startedAt=void 0,o.completedAt=void 0,t&&(o.prompt=t)}updateTaskPrompt(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="pending")throw new Error(`Task "${e}" is ${o.status}, can only update pending tasks`);o.prompt=t}reassignTask(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(o.status!=="pending")throw new Error(`Task "${e}" is ${o.status}, can only reassign pending tasks`);o.assignee=t}addDependency(e,t){let o=this.nodes.get(e);if(!o)throw new Error(`Unknown task: ${e}`);if(!this.nodes.has(t))throw new Error(`Unknown dependency task: ${t}`);if(!o.dependsOn.includes(t)){o.dependsOn.push(t);try{this.validateDag()}catch(r){throw o.dependsOn.pop(),r}}}getProgress(){let e=0,t=0,o=0,r=0,s=0;for(let i of this.nodes.values())switch(i.status){case"completed":e++;break;case"running":t++;break;case"failed":o++;break;case"pending":r++;break;case"paused":s++;break}return{total:this.nodes.size,completed:e,running:t,failed:o,pending:r,paused:s}}validateDag(){for(let r of this.nodes.values())for(let s of r.dependsOn)if(!this.nodes.has(s))throw new Error(`Task "${r.taskId}" depends on unknown task "${s}"`);let e=new Set,t=new Set,o=r=>{if(t.has(r))throw new Error(`Cycle detected involving task "${r}"`);if(e.has(r))return;t.add(r);let s=this.nodes.get(r);for(let i of s.dependsOn)o(i);t.delete(r),e.add(r)};for(let r of this.nodes.keys())o(r)}};var hr=class{maxTotalTokens;maxDuration;usedTokens=0;startedAt;warningEmitted=!1;constructor(e){this.maxTotalTokens=e?.maxTotalTokens,this.maxDuration=e?.maxDuration,this.startedAt=Date.now()}addUsage(e,t){this.usedTokens+=e+t}addFromTracker(e){if(!e.hasData())return;let t=e.getUsage();this.usedTokens+=t.totalTokens}getElapsed(){return Date.now()-this.startedAt}getBudget(){return{maxTotalTokens:this.maxTotalTokens,maxDuration:this.maxDuration,usedTokens:this.usedTokens,elapsed:this.getElapsed()}}check(){let e=this.getElapsed();if(this.maxDuration&&e>=this.maxDuration)return{action:"exceeded",percentage:Math.round(e/this.maxDuration*100),usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(this.maxTotalTokens){let o=Math.round(this.usedTokens/this.maxTotalTokens*100);if(this.usedTokens>=this.maxTotalTokens)return{action:"exceeded",percentage:o,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(o>=80&&!this.warningEmitted)return this.warningEmitted=!0,{action:"warning",percentage:o,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}return{action:"ok",percentage:this.maxTotalTokens?Math.round(this.usedTokens/this.maxTotalTokens*100):0,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}restore(e){this.usedTokens=e.usedTokens,this.startedAt=e.startedAt,this.warningEmitted=e.warningEmitted}serialize(){return{usedTokens:this.usedTokens,startedAt:this.startedAt,warningEmitted:this.warningEmitted}}};import{join as dd}from"node:path";import{mkdir as PE,readdir as IE}from"node:fs/promises";le();function uy(n){return dd(Oe(n),"products")}function py(n,e){return dd(uy(e),n)}function my(n,e){return dd(py(n,e),"product-state.json")}async function fy(n,e){let t=py(n.productId,e);await PE(t,{recursive:!0}),await eo(my(n.productId,e),n)}async function ud(n,e){return An(my(n,e))}async function gy(n){let e=uy(n),t;try{t=await IE(e)}catch{return[]}let o=[];for(let r of t){let s=await ud(r,n);s&&o.push(s)}return o}var yr=class n{constructor(e={}){this.callbacks=e}callbacks;static DEFAULT_INTERVAL=5*6e4;static LONG_RUNNING_INTERVAL=30*6e4;static LONG_RUNNING_THRESHOLD=2880*6e4;timer=null;lastCheckpointAt=0;cwd;start(e){this.cwd=e,this.stop(),this.timer=setInterval(()=>{let t=this.callbacks.getState?.();t&&this.checkpoint(t).catch(o=>{this.callbacks.log?.warn(`[checkpoint] periodic save failed: ${o instanceof Error?o.message:String(o)}`)})},n.DEFAULT_INTERVAL),this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getInterval(e){return e>n.LONG_RUNNING_THRESHOLD?n.LONG_RUNNING_INTERVAL:n.DEFAULT_INTERVAL}isDue(e){if(this.lastCheckpointAt===0)return!0;let t=this.getInterval(e);return Date.now()-this.lastCheckpointAt>=t}async checkpoint(e){let t=new Date().toISOString();e.lastCheckpointAt=t,await fy(e,this.cwd),this.lastCheckpointAt=Date.now(),this.callbacks.onCheckpoint?.(e.productId,t),this.callbacks.log?.info(`[checkpoint] saved ${e.productId} at ${t}`)}getLastCheckpointAt(){return this.lastCheckpointAt}};import{execFile as CE}from"node:child_process";import{promisify as EE}from"node:util";import{join as hy}from"node:path";import{mkdir as ME,rm as OE}from"node:fs/promises";var po=EE(CE);async function br(n){try{let{stdout:e}=await po("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8"});return e.trim()}catch{return null}}async function ri(n,e,t){let o=hy(n,".worktrees");await ME(o,{recursive:!0});let r=hy(o,e),i=["worktree","add","-B",`solo/${e}`,r];return t?i.push(t):i.push("HEAD"),await po("git",i,{cwd:n,encoding:"utf8"}),r}async function pd(n){try{await po("git",["add","-A"],{cwd:n});let{stdout:e}=await po("git",["diff","--cached","--stat"],{cwd:n,encoding:"utf8"});return e.trim()}catch{return""}}async function yy(n,e){try{await po("git",["worktree","remove","--force",e],{cwd:n,encoding:"utf8"})}catch{try{await OE(e,{recursive:!0,force:!0})}catch{}}}async function by(n,e){let{stdout:t}=await po("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:n,encoding:"utf8"});return t.trim()}var si=class{constructor(e,t,o,r={}){this.processManager=e;this.acpDetector=t;this.configStore=o;this.callbacks=r}processManager;acpDetector;configStore;callbacks;sessions=new Map;async create(e){let{name:t,cwd:o,instances:r,tasks:s,budget:i}=e;if(r.length===0)throw new Error("Product requires at least 1 instance");if(s.length===0)throw new Error("Product requires at least 1 task");let a=new Set(r.map(b=>b.name));for(let b of s)if(!a.has(b.assignee))throw new Error(`Task "${b.taskId}" references unknown instance "${b.assignee}"`);let l=`product-${DE().slice(0,8)}`,c=new gr(s),d=new hr(i),u=new yr({onCheckpoint:(b,k)=>this.callbacks.onCheckpointed?.(b,k),getState:()=>{let b=this.sessions.get(l);return b?this.buildPersistedState(b):null},log:this.callbacks.log}),p=await br(o),m=r.map((b,k)=>({instanceId:`${l}:${b.name}:${k}`,name:b.name,agentId:b.agentId,state:"idle"})),h={productId:l,name:t,cwd:o,phase:"active",instances:m,dag:c,budget:d,checkpoint:u,createdAt:new Date().toISOString(),gitRoot:p};this.sessions.set(l,h),u.start(o),this.callbacks.log?.info(`[product] created ${l} "${t}" with ${r.length} instances, ${s.length} tasks`);let f=s.map(b=>({id:b.taskId,label:b.taskId,deps:b.dependsOn??[]})),y=[];for(let b of s)if(b.dependsOn)for(let k of b.dependsOn)y.push({from:k,to:b.taskId});return this.callbacks.onDagTopology?.(l,f,y),setTimeout(()=>this.scheduleNext(h),0),l}async resume(e,t){let o=await ud(e,t);if(!o)throw new Error(`Product ${e} not found on disk`);let r=new gr(o.tasks);r.restore(o.tasks);let s=new hr({maxTotalTokens:o.budget.maxTotalTokens,maxDuration:o.budget.maxDuration});s.restore(o.budget);let i=new yr({onCheckpoint:(d,u)=>this.callbacks.onCheckpointed?.(d,u),getState:()=>{let d=this.sessions.get(e);return d?this.buildPersistedState(d):null},log:this.callbacks.log}),a=await br(o.cwd),l=o.instances.map((d,u)=>({instanceId:`${e}:${d.name}:${u}`,name:d.name,agentId:d.agentId,state:"idle"})),c={productId:o.productId,name:o.name,cwd:o.cwd,phase:"active",instances:l,dag:r,budget:s,checkpoint:i,createdAt:o.createdAt,gitRoot:a};this.sessions.set(e,c),i.start(o.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(c)}async pause(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase!=="active")throw new Error(`Product ${e} is not active`);t.phase="paused",t.dag.pauseAll();for(let o of t.instances)if(o.state==="running"&&o.memberId){try{this.processManager.kill(o.memberId)}catch{}o.state="paused"}await t.checkpoint.checkpoint(this.buildPersistedState(t)),t.checkpoint.stop(),this.callbacks.log?.info(`[product] paused ${e}`)}async checkpoint(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);await t.checkpoint.checkpoint(this.buildPersistedState(t))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Product ${e} not found`);if(t.phase==="active"){t.phase="failed",t.dag.pauseAll();for(let o of t.instances)if(o.state==="running"&&o.memberId){try{this.processManager.kill(o.memberId)}catch{}o.state="failed"}}t.checkpoint.stop(),this.sessions.delete(e),this.callbacks.log?.info(`[product] deleted ${e}`)}async rollback(e,t){let o=this.sessions.get(e);if(!o)throw new Error(`Product ${e} not found`);let r=o.cwd;await this.delete(e),await this.resume(e,r),this.callbacks.log?.info(`[product] rolled back ${e} to checkpoint ${t}`)}getStatus(e){let t=this.sessions.get(e);return t?{productId:t.productId,name:t.name,phase:t.phase,instances:t.instances.map(o=>{let s=(o.memberId?this.processManager.getUsageTracker(o.memberId):null)?.getUsage();return{instanceId:o.instanceId,name:o.name,agentId:o.agentId,state:o.state,worktreePath:o.worktreePath,usage:s&&(s.inputTokens>0||s.outputTokens>0)?{inputTokens:s.inputTokens,outputTokens:s.outputTokens}:void 0}}),tasks:t.dag.getAllTasks().map(o=>({taskId:o.taskId,assignee:o.assignee,status:o.status,result:o.result,error:o.error,startedAt:o.startedAt?new Date(o.startedAt).toISOString():void 0,completedAt:o.completedAt?new Date(o.completedAt).toISOString():void 0})),budget:t.budget.getBudget(),lastCheckpointAt:new Date(t.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}:null}async list(e){let t=[];for(let r of this.sessions.values()){let s=r.dag.getAllTasks();t.push({productId:r.productId,name:r.name,phase:r.phase,instanceCount:r.instances.length,taskCount:s.length,completedTasks:s.filter(i=>i.status==="completed").length,createdAt:r.createdAt,lastCheckpointAt:new Date(r.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()})}let o=await gy(e);for(let r of o)this.sessions.has(r.productId)||t.push({productId:r.productId,name:r.name,phase:r.phase,instanceCount:r.instances.length,taskCount:r.tasks.length,completedTasks:r.tasks.filter(s=>s.status==="completed").length,createdAt:r.createdAt,lastCheckpointAt:r.lastCheckpointAt});return t}scheduleNext(e){if(e.phase!=="active")return;let t=e.budget.check();if(t.action==="exceeded"){this.callbacks.log?.warn(`[product] ${e.productId} budget exceeded, auto-pausing`),this.pause(e.productId).catch(r=>{this.callbacks.log?.warn(`[product] auto-pause failed: ${r instanceof Error?r.message:String(r)}`)});return}if(t.action==="warning"&&this.callbacks.onBudgetWarning?.(e.productId,t.usedTokens,t.maxTotalTokens,t.percentage),e.dag.isFinished()){this.finishProduct(e);return}let o=e.dag.getReadyTasks();for(let r of o)this.dispatchTask(e,r)}dispatchTask(e,t){let o=e.instances.find(r=>r.name===t.assignee);if(!o){e.dag.markFailed(t.taskId,`No instance found for assignee "${t.assignee}"`),this.callbacks.onTaskFailed?.(e.productId,t.taskId,`No instance for "${t.assignee}"`),this.scheduleNext(e);return}e.dag.markRunning(t.taskId),o.state="running",this.callbacks.onTaskStarted?.(e.productId,t.taskId,t.assignee),this.callbacks.log?.info(`[product] ${e.productId} dispatching task ${t.taskId} to ${t.assignee}`),this.runTask(e,o,t).catch(r=>{this.callbacks.log?.warn(`[product] task dispatch error: ${r instanceof Error?r.message:String(r)}`)})}async runTask(e,t,o){let r=`${e.productId}:${t.name}:${o.taskId}`;t.memberId=r;try{let s=this.acpDetector.buildExternalDescriptor(t.agentId);if(!s)throw new Error(`Agent ${t.agentId} is not available`);let i=e.cwd;if(e.gitRoot){let d=`${e.productId}-${t.name}-${o.taskId}`;try{i=await ri(e.gitRoot,d),t.worktreePath=i}catch{this.callbacks.log?.warn(`[product] worktree creation failed for ${o.taskId}, using project cwd`)}}await this.processManager.spawn({memberId:r,name:`product-${t.name}`,cwd:i,prompt:o.prompt,external:s});let a=await this.processManager.sendTask(r,o.prompt),l=typeof a=="string"?a:JSON.stringify(a),c=this.processManager.getUsageTracker(r);if(c?.hasData()){let d=c.getUsage();e.budget.addUsage(d.inputTokens,d.outputTokens);let u=e.budget.getBudget();this.callbacks.onBudgetUpdate?.(e.productId,u.usedTokens,0,u.elapsed,u.maxTotalTokens)}e.dag.markCompleted(o.taskId,l),t.state="completed",this.callbacks.onTaskCompleted?.(e.productId,o.taskId,l);try{this.processManager.kill(r)}catch{}this.processManager.remove(r)}catch(s){let i=s instanceof Error?s.message:String(s);e.dag.markFailed(o.taskId,i),t.state="failed",this.callbacks.onTaskFailed?.(e.productId,o.taskId,i);try{this.processManager.kill(r)}catch{}try{this.processManager.remove(r)}catch{}}try{await e.checkpoint.checkpoint(this.buildPersistedState(e))}catch(s){this.callbacks.log?.warn(`[product] checkpoint failed: ${s instanceof Error?s.message:String(s)}`)}this.scheduleNext(e)}finishProduct(e){if(e.dag.isAllCompleted()){e.phase="completed";let t=e.dag.getAllTasks(),o=`Product "${e.name}" completed: ${t.length} tasks all done.`;this.callbacks.onCompleted?.(e.productId,o)}else{e.phase="failed";let o=e.dag.getAllTasks().filter(i=>i.status==="failed").length,r=e.dag.getBlockedTasks().length,s=`Product "${e.name}" finished with ${o} failed, ${r} blocked tasks.`;this.callbacks.onCompleted?.(e.productId,s)}e.checkpoint.stop(),e.checkpoint.checkpoint(this.buildPersistedState(e)).catch(t=>{this.callbacks.log?.warn(`[product] final checkpoint failed: ${t instanceof Error?t.message:String(t)}`)}),this.callbacks.log?.info(`[product] ${e.productId} finished (phase=${e.phase})`)}buildPersistedState(e){return{productId:e.productId,name:e.name,phase:e.phase,cwd:e.cwd,instances:e.instances.map(t=>({name:t.name,role:"",agentId:t.agentId})),tasks:e.dag.serialize(),budget:e.budget.serialize(),createdAt:e.createdAt,lastCheckpointAt:new Date(e.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}}};import{randomUUID as ky}from"node:crypto";function LE(n,e){let t=e?`
704
704
 
705
705
  Budget constraints: ${e.maxTotalTokens?`max ${e.maxTotalTokens} total tokens`:""}${e.maxDuration?` / max ${Math.round(e.maxDuration/6e4)} minutes`:""}`:"";return`You are a team leader agent managing a software development project.
706
706
 
@@ -730,7 +730,7 @@ When you're ready to output the final plan, use this EXACT JSON schema wrapped i
730
730
  "reasoning": "<decomposition strategy explanation>"
731
731
  }
732
732
 
733
- Start by greeting the user and asking your first clarifying question about the project.`}function DE(n,e){return`${n.map(o=>`[${o.role}]: ${o.content}`).join(`
733
+ Start by greeting the user and asking your first clarifying question about the project.`}function NE(n,e){return`${n.map(o=>`[${o.role}]: ${o.content}`).join(`
734
734
 
735
735
  `)}
736
736
 
@@ -763,13 +763,13 @@ To mutate the DAG, output a \`\`\`json block with an array of mutations:
763
763
  {"type": "update_prompt", "taskId": "...", "prompt": "..."}
764
764
  ]
765
765
 
766
- If no action needed, just respond with a progress update message to the user.`,e}var ii=class{constructor(e,t,o,r={}){this.processManager=e;this.acpDetector=t;this.configStore=o;this.callbacks=r}processManager;acpDetector;configStore;callbacks;sessions=new Map;async plan(e){let{goal:t,cwd:o,leaderAgentId:r,name:s,budget:i}=e,a=`product-${ky().slice(0,8)}`,l={productId:a,goal:t,cwd:o,leaderAgentId:r,phase:"planning",dialogue:[],budget:i,createdAt:new Date().toISOString()};this.sessions.set(a,l),this.callbacks.log?.info(`[planner] started planning ${a} with leader=${r}`);let c=await this.sendToLeader(l,OE(t,i));l.dialogue.push({role:"leader",content:c,timestamp:new Date().toISOString()});let d=this.tryParsePlan(c,l);if(d)return l.plan=d,l.phase="awaiting_confirmation",s&&(d.name=s),this.callbacks.onPlanReady?.(a,d),{productId:a,plan:d};this.callbacks.onLeaderMessage?.(a,c),this.callbacks.onPlanningDelta?.(a,c);let u={name:s??t.slice(0,50),modules:[],instances:[],tasks:[],reasoning:"Planning in progress \u2014 leader is asking clarifying questions. Use product.message to respond."};return{productId:a,plan:u}}async message(e,t){let o=this.sessions.get(e);if(!o)throw new Error(`Session ${e} not found`);if(o.dialogue.push({role:"user",content:t,timestamp:new Date().toISOString()}),o.phase==="planning")return this.handlePlanningMessage(o,t);if(o.phase==="executing"||o.phase==="paused")return this.handleExecutionMessage(o,t);if(o.phase==="awaiting_confirmation")return this.handlePlanningMessage(o,t);throw new Error(`Cannot message in phase "${o.phase}"`)}async confirm(e){let t=this.sessions.get(e.productId);if(!t)throw new Error(`Planning session ${e.productId} not found`);if(t.phase!=="awaiting_confirmation")throw new Error(`Session ${e.productId} is in phase "${t.phase}", not "awaiting_confirmation"`);return t.phase="confirmed",t.lastCheckpoint=new Date().toISOString(),this.callbacks.log?.info(`[planner] confirmed ${e.productId}: ${e.instances.length} instances, ${e.tasks.length} tasks`),{productId:e.productId,ok:!0}}markExecuting(e){let t=this.sessions.get(e);t&&(t.phase="executing",t.lastCheckpoint=new Date().toISOString())}markCompleted(e){let t=this.sessions.get(e);t&&(t.phase="completed")}getSession(e){return this.sessions.get(e)}async cancel(e){let t=this.sessions.get(e);if(t){if(t.phase="cancelled",t.leaderMemberId)try{await this.processManager.kill(t.leaderMemberId)}catch{}this.sessions.delete(e)}}listSessions(){return[...this.sessions.values()]}async consultLeader(e,t){let o=this.sessions.get(e);if(!o)return[];let r=vy(t),s=await this.sendToLeader(o,r);return o.dialogue.push({role:"leader",content:s,timestamp:new Date().toISOString()}),this.parseDagMutations(s)}serializeSession(e){return this.sessions.get(e)??null}restoreSession(e){this.sessions.set(e.productId,e),e.leaderMemberId=void 0}async handlePlanningMessage(e,t){let o=DE(e.dialogue.slice(0,-1),t),r=await this.sendToLeader(e,o);e.dialogue.push({role:"leader",content:r,timestamp:new Date().toISOString()});let s=this.tryParsePlan(r,e);return s?(e.plan=s,e.phase="awaiting_confirmation",this.callbacks.onPlanReady?.(e.productId,s),{response:r,plan:s}):(this.callbacks.onLeaderMessage?.(e.productId,r),{response:r})}async handleExecutionMessage(e,t){let o=vy({progress:{total:0,completed:0,running:0,failed:0},userMessage:t}),r=await this.sendToLeader(e,o);e.dialogue.push({role:"leader",content:r,timestamp:new Date().toISOString()});let s=this.parseDagMutations(r);for(let i of s)this.callbacks.onDagMutated?.(e.productId,i);return{response:r,mutations:s.length>0?s:void 0}}async sendToLeader(e,t){if(!e.leaderMemberId){let r=`${e.productId}:leader`,s=this.acpDetector.buildExternalDescriptor(e.leaderAgentId);if(!s)throw new Error(`Leader agent ${e.leaderAgentId} is not available`);await this.processManager.spawn({memberId:r,name:"product-leader",cwd:e.cwd,prompt:t,external:s}),e.leaderMemberId=r}let o=await this.processManager.sendTask(e.leaderMemberId,t);return typeof o=="string"?o:JSON.stringify(o)}tryParsePlan(e,t){let o=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(!o)return null;try{let r=JSON.parse(o[1]);return!r.name||!Array.isArray(r.tasks)||r.tasks.length===0?null:{name:r.name,modules:(r.modules??[]).map(s=>({name:String(s.name??""),description:String(s.description??""),suggestedAgentId:s.suggestedAgentId?String(s.suggestedAgentId):void 0})),instances:(r.instances??[]).map(s=>({name:String(s.name??""),agentId:String(s.agentId??t.leaderAgentId),role:String(s.role??s.description??"")})),tasks:r.tasks.map(s=>({taskId:String(s.taskId??`task-${ky().slice(0,6)}`),assignee:String(s.assignee??""),prompt:String(s.description??s.prompt??""),dependsOn:Array.isArray(s.dependsOn)?s.dependsOn.map(String):void 0})),reasoning:String(r.reasoning??"")}}catch{return null}}parseDagMutations(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(!t)return[];try{let o=JSON.parse(t[1]);return Array.isArray(o)?o.filter(r=>r.type).map(r=>({type:String(r.type),taskId:String(r.taskId??r.task?.taskId??""),details:r})):[]}catch{return[]}}};function Le(){if(!this.productOrchestrator){let n=new pn({log:{info:t=>process.stderr.write(`[product:pm] ${t}
766
+ If no action needed, just respond with a progress update message to the user.`,e}var ii=class{constructor(e,t,o,r={}){this.processManager=e;this.acpDetector=t;this.configStore=o;this.callbacks=r}processManager;acpDetector;configStore;callbacks;sessions=new Map;async plan(e){let{goal:t,cwd:o,leaderAgentId:r,name:s,budget:i}=e,a=`product-${ky().slice(0,8)}`,l={productId:a,goal:t,cwd:o,leaderAgentId:r,phase:"planning",dialogue:[],budget:i,createdAt:new Date().toISOString()};this.sessions.set(a,l),this.callbacks.log?.info(`[planner] started planning ${a} with leader=${r}`);let c=await this.sendToLeader(l,LE(t,i));l.dialogue.push({role:"leader",content:c,timestamp:new Date().toISOString()});let d=this.tryParsePlan(c,l);if(d)return l.plan=d,l.phase="awaiting_confirmation",s&&(d.name=s),this.callbacks.onPlanReady?.(a,d),{productId:a,plan:d};this.callbacks.onLeaderMessage?.(a,c),this.callbacks.onPlanningDelta?.(a,c);let u={name:s??t.slice(0,50),modules:[],instances:[],tasks:[],reasoning:"Planning in progress \u2014 leader is asking clarifying questions. Use product.message to respond."};return{productId:a,plan:u}}async message(e,t){let o=this.sessions.get(e);if(!o)throw new Error(`Session ${e} not found`);if(o.dialogue.push({role:"user",content:t,timestamp:new Date().toISOString()}),o.phase==="planning")return this.handlePlanningMessage(o,t);if(o.phase==="executing"||o.phase==="paused")return this.handleExecutionMessage(o,t);if(o.phase==="awaiting_confirmation")return this.handlePlanningMessage(o,t);throw new Error(`Cannot message in phase "${o.phase}"`)}async confirm(e){let t=this.sessions.get(e.productId);if(!t)throw new Error(`Planning session ${e.productId} not found`);if(t.phase!=="awaiting_confirmation")throw new Error(`Session ${e.productId} is in phase "${t.phase}", not "awaiting_confirmation"`);return t.phase="confirmed",t.lastCheckpoint=new Date().toISOString(),this.callbacks.log?.info(`[planner] confirmed ${e.productId}: ${e.instances.length} instances, ${e.tasks.length} tasks`),{productId:e.productId,ok:!0}}markExecuting(e){let t=this.sessions.get(e);t&&(t.phase="executing",t.lastCheckpoint=new Date().toISOString())}markCompleted(e){let t=this.sessions.get(e);t&&(t.phase="completed")}getSession(e){return this.sessions.get(e)}async cancel(e){let t=this.sessions.get(e);if(t){if(t.phase="cancelled",t.leaderMemberId)try{await this.processManager.kill(t.leaderMemberId)}catch{}this.sessions.delete(e)}}listSessions(){return[...this.sessions.values()]}async consultLeader(e,t){let o=this.sessions.get(e);if(!o)return[];let r=vy(t),s=await this.sendToLeader(o,r);return o.dialogue.push({role:"leader",content:s,timestamp:new Date().toISOString()}),this.parseDagMutations(s)}serializeSession(e){return this.sessions.get(e)??null}restoreSession(e){this.sessions.set(e.productId,e),e.leaderMemberId=void 0}async handlePlanningMessage(e,t){let o=NE(e.dialogue.slice(0,-1),t),r=await this.sendToLeader(e,o);e.dialogue.push({role:"leader",content:r,timestamp:new Date().toISOString()});let s=this.tryParsePlan(r,e);return s?(e.plan=s,e.phase="awaiting_confirmation",this.callbacks.onPlanReady?.(e.productId,s),{response:r,plan:s}):(this.callbacks.onLeaderMessage?.(e.productId,r),{response:r})}async handleExecutionMessage(e,t){let o=vy({progress:{total:0,completed:0,running:0,failed:0},userMessage:t}),r=await this.sendToLeader(e,o);e.dialogue.push({role:"leader",content:r,timestamp:new Date().toISOString()});let s=this.parseDagMutations(r);for(let i of s)this.callbacks.onDagMutated?.(e.productId,i);return{response:r,mutations:s.length>0?s:void 0}}async sendToLeader(e,t){if(!e.leaderMemberId){let r=`${e.productId}:leader`,s=this.acpDetector.buildExternalDescriptor(e.leaderAgentId);if(!s)throw new Error(`Leader agent ${e.leaderAgentId} is not available`);await this.processManager.spawn({memberId:r,name:"product-leader",cwd:e.cwd,prompt:t,external:s}),e.leaderMemberId=r}let o=await this.processManager.sendTask(e.leaderMemberId,t);return typeof o=="string"?o:JSON.stringify(o)}tryParsePlan(e,t){let o=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(!o)return null;try{let r=JSON.parse(o[1]);return!r.name||!Array.isArray(r.tasks)||r.tasks.length===0?null:{name:r.name,modules:(r.modules??[]).map(s=>({name:String(s.name??""),description:String(s.description??""),suggestedAgentId:s.suggestedAgentId?String(s.suggestedAgentId):void 0})),instances:(r.instances??[]).map(s=>({name:String(s.name??""),agentId:String(s.agentId??t.leaderAgentId),role:String(s.role??s.description??"")})),tasks:r.tasks.map(s=>({taskId:String(s.taskId??`task-${ky().slice(0,6)}`),assignee:String(s.assignee??""),prompt:String(s.description??s.prompt??""),dependsOn:Array.isArray(s.dependsOn)?s.dependsOn.map(String):void 0})),reasoning:String(r.reasoning??"")}}catch{return null}}parseDagMutations(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(!t)return[];try{let o=JSON.parse(t[1]);return Array.isArray(o)?o.filter(r=>r.type).map(r=>({type:String(r.type),taskId:String(r.taskId??r.task?.taskId??""),details:r})):[]}catch{return[]}}};function Le(){if(!this.productOrchestrator){let n=new pn({log:{info:t=>process.stderr.write(`[product:pm] ${t}
767
767
  `),warn:t=>process.stderr.write(`[product:pm] WARN ${t}
768
768
  `)},onNotification:(t,o,r)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,r),this.sendNotification("team.member.notification",{memberId:t,method:o,params:r})},onStateChange:(t,o)=>{let r=n.getHandle(t),i=n.getUsageTracker(t)?.getUsage();this.emitAgentStatus(t,o,{missedBeats:n.getMissedBeats(t),lastActivityAt:r?.lastActivityAt,usage:i&&i.totalTokens>0?{inputTokens:i.inputTokens,outputTokens:i.outputTokens,totalTokens:i.totalTokens}:void 0})},onMcpToolCall:(t,o,r)=>this.handleMcpToolCall(t,o,r),sessionDir:path.join(getUserAgentHome(),"agent-logs")}),e={log:{info:t=>process.stderr.write(`${t}
769
769
  `),warn:t=>process.stderr.write(`${t}
770
770
  `)},onTaskStarted:(t,o,r)=>{this.sendNotification("product.taskStarted",{productId:t,taskId:o,assignee:r})},onTaskCompleted:(t,o,r)=>{this.sendNotification("product.taskCompleted",{productId:t,taskId:o,result:r})},onTaskFailed:(t,o,r)=>{this.sendNotification("product.taskFailed",{productId:t,taskId:o,error:r})},onCheckpointed:(t,o)=>{this.sendNotification("product.checkpointed",{productId:t,timestamp:o})},onBudgetWarning:(t,o,r,s)=>{this.sendNotification("product.budgetWarning",{productId:t,usedTokens:o,maxTotalTokens:r,percentage:s})},onCompleted:(t,o)=>{this.sendNotification("product.completed",{productId:t,summary:o})},onDagTopology:(t,o,r)=>{this.sendNotification("product.dagTopology",{productId:t,nodes:o,edges:r})},onBudgetUpdate:(t,o,r,s,i)=>{this.sendNotification("product.budgetUpdate",{productId:t,inputTokens:o,outputTokens:r,elapsed:s,maxTotalTokens:i})},onTaskOutputDelta:(t,o,r)=>{this.sendNotification("product.taskOutput",{productId:t,taskId:o,text:r})}};this.productOrchestrator=new si(n,this.acpDetector,this.agentConfigStore,e),this.productProcessManager=n}return this.productOrchestrator}function Cn(){if(!this.productPlanner){let n=Le.call(this);this.productPlanner=new ii(this.productProcessManager,this.acpDetector,this.agentConfigStore,{log:{info:e=>process.stderr.write(`${e}
771
771
  `),warn:e=>process.stderr.write(`${e}
772
- `)},onPlanReady:(e,t)=>{this.sendNotification("product.planReady",{productId:e,plan:t})},onPlanFailed:(e,t)=>{this.sendNotification("product.planFailed",{productId:e,error:t})},onPlanningDelta:(e,t)=>{this.sendNotification("product.planningDelta",{productId:e,text:t})}})}return this.productPlanner}async function Sy(n){try{let e=n.params;if(!e?.goal||!e?.cwd||!e?.leaderAgentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"goal, cwd, and leaderAgentId are required."});return}let o=await Cn.call(this).plan(e);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ty(n){try{let e=n.params;if(!e?.productId||!e?.instances||!e?.tasks){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId, instances, and tasks are required."});return}let t=Cn.call(this),o=await t.confirm(e),r=t.getSession(e.productId);r&&await Le.call(this).create({name:r.plan?.name??r.goal.slice(0,50),cwd:r.cwd,instances:e.instances,tasks:e.tasks,budget:e.budget}),n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function wy(n){try{let e=n.params;if(!e?.productId||!e?.content){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId and content are required."});return}let o=await Cn.call(this).message(e.productId,e.content);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function xy(n){try{let e=n.params,t;if(e?.name&&e?.cwd&&e?.instances&&e?.tasks)t=e;else if(e?.tasks&&Array.isArray(e.tasks)){let i=e.config?.workdir??this.getActiveProjectRoot(),a=e.tasks.map(l=>({taskId:String(l.id??l.taskId??`task_${Math.random().toString(36).slice(2,8)}`),assignee:String(l.assignee??"default"),prompt:String(l.description??l.prompt??""),dependsOn:l.dependsOn??[]}));t={name:String(e.name??`product_${Date.now()}`),cwd:i,instances:[{name:"default",role:"executor",agentId:"self"}],tasks:a},e.budget&&(t.budget=e.budget)}else{n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"tasks is required. Provide either {name, cwd, instances, tasks} or simplified {tasks, config}."});return}if(!t.projectId){let s=Ne();s&&(t.projectId=s.id)}let r=await Le.call(this).create(t);n.id!==void 0&&this.sendResponse(n.id,{productId:r})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ry(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).resume(e.productId,this.getActiveProjectRoot()),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function _y(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).pause(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ay(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).checkpoint(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Py(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}let o=Le.call(this).getStatus(e.productId);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Iy(n){try{let t=await Le.call(this).list(this.getActiveProjectRoot());n.id!==void 0&&this.sendResponse(n.id,t)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Cy(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).delete(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ey(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).delete(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function My(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).rollback(e.productId,e.checkpoint??"latest"),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}import{randomUUID as md}from"node:crypto";import*as Xe from"node:fs";import*as En from"node:path";le();var Ee=new oo;function Oy(n){let e=n.params,t=e?.id??md();this.log(`[thread.create] id=${t} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=t,this.sessionState=new ln(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Kt(),this.enableIdleDream(),n.id!==void 0&&this.sendResponse(n.id,{id:t,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function Dy(n){let e=n.params,t=e?.limit??20;try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o),i=(await Et(t,r)).map(a=>({id:a.sessionId,title:a.title,status:"active",turnCount:a.messageCount,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt}));n.id!==void 0&&this.sendResponse(n.id,{threads:i})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to list threads: ${o.message}`})}}async function Ly(n){let e=n.params,t=e?.sessionId??md();try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o);await tt(t,{sessionId:t,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:o},r),n.id!==void 0&&this.sendResponse(n.id,{sessionId:t,title:e?.title})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to create session: ${o.message}`})}}async function Ny(n){let e=n.params;if(n.id===void 0)return;let t=e?.platform??"desktop",o=e?.chatId,r=e?.chatType,s=e?.userId??"local";try{if(t==="desktop"&&o){let d=e?.projectId??Ee.getActiveProjectId(),u=Ee.getProjectWorkspaceDir(d),m=(await Et(500,u)).find(h=>h.sessionId===o);if(m){this.sendResponse(n.id,{sessionId:o,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await tt(o,{sessionId:o,type:"personal",ownerId:s,projectId:d},u),this.sendResponse(n.id,{sessionId:o,type:"personal",ownerId:s,projectId:d});return}if(r==="group"&&o&&t){let d=`group:${t}:${o}`,u=fe();for(let p of u){if(!p.workspaceDir)continue;let h=(await Et(500,p.workspaceDir)).find(f=>f.groupKey===d&&!f.sealedAt);if(h){let f=wn(h.sessionId,p.workspaceDir);if(f){let y=await Hh(f,p.workspaceDir);if(y.split){this.sendResponse(n.id,{sessionId:y.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:t,groupName:e?.groupName,projectId:p.id,previousSessionId:y.sealedSessionId});return}}this.sendResponse(n.id,{sessionId:h.sessionId,title:h.title,type:"group",ownerId:s,groupKey:d,groupPlatform:t,groupName:e?.groupName,projectId:p.id});return}}}let i=md(),a=Ee.getActiveProjectId(),l=Ee.getProjectWorkspaceDir(a),c=r==="group"?`group:${t}:${o}`:void 0;await tt(i,{sessionId:i,type:r==="group"?"group":"personal",ownerId:s,groupKey:c,groupPlatform:r==="group"?t:void 0,groupName:e?.groupName,projectId:a},l),this.sendResponse(n.id,{sessionId:i,type:r==="group"?"group":"personal",ownerId:s,groupKey:c,groupPlatform:r==="group"?t:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to resolve session: ${i.message}`})}}async function $y(n){let e=n.params,t=e?.limit??50;try{let o;if(e?.projectId){let s=lt(e.projectId);if(!s){n.id!==void 0&&this.sendResponse(n.id,{sessions:[]});return}let i=s.workspaceDir;o=await Et(t*2,i),o=o.filter(a=>a.projectId===e.projectId);for(let a of o)a.projectId=e.projectId}else{let s=fe(),i=new Set,a=[];for(let l of s){if(!l.workspaceDir)continue;let c=await Et(t,l.workspaceDir);for(let d of c)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((l,c)=>l.lastActiveAt>c.lastActiveAt?-1:l.lastActiveAt<c.lastActiveAt?1:0),o=a}e?.archived===!0?o=o.filter(s=>s.archivedAt!=null):e?.archived===!1&&(o=o.filter(s=>s.archivedAt==null));let r=o.slice(0,t).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type,lastActiveAt:s.lastActiveAt,pinnedAt:s.pinnedAt??null,archivedAt:s.archivedAt??null,sealedAt:s.sealedAt??null,projectId:s.projectId,previousSessionId:s.previousSessionId??null,carryoverSummary:s.carryoverSummary??null}));n.id!==void 0&&this.sendResponse(n.id,{sessions:r})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to list sessions: ${o.message}`})}}async function Uy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId),r=(await Et(500,t)).find(s=>s.sessionId===e.sessionId);n.id!==void 0&&this.sendResponse(n.id,{session:r?{sessionId:r.sessionId,title:r.title,type:r.type,lastActiveAt:r.lastActiveAt,pinnedAt:r.pinnedAt??null,archivedAt:r.archivedAt??null,projectId:r.projectId}:null})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to get session: ${t.message}`})}}async function jy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId),o=await xl(e.sessionId,t);if(!o){n.id!==void 0&&this.sendResponse(n.id,{messages:[],total:0});return}let r=o.messages,s=e.limit&&e.limit>0?e.limit:r.length,i=r.slice(-s);n.id!==void 0&&this.sendResponse(n.id,{messages:i,total:r.length})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to get messages: ${t.message}`})}}async function Fy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId),o=await tt(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},t);o&&this.sendNotification("session.info",{sessionId:e.sessionId,title:o.title,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:e.projectId||void 0}),n.id!==void 0&&this.sendResponse(n.id,{ok:o!==null})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to update session: ${t.message}`})}}async function By(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId);await Rl(e.sessionId,t),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to delete session: ${t.message}`})}}async function Wy(n){let e=n.params;if(!e?.projectId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let t=Ee.getProjectWorkspaceDir(e.projectId),o=await Et(1e4,t),r=0;for(let s of o)await Rl(s.sessionId,t),r++;n.id!==void 0&&this.sendResponse(n.id,{ok:!0,deletedCount:r})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to delete all sessions: ${t.message}`})}}async function Gy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId);await tt(e.sessionId,{archivedAt:new Date().toISOString()},t),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to archive session: ${t.message}`})}}async function Hy(n){let e=n.params,t=e?.sessionId;if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"sessionId is required"});return}try{let o=Ee.resolveWorkspaceDir(t,e?.projectId),r=await xl(t,o);if(!r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Session not found: ${t}`});return}r.messages&&r.messages.length>0&&this.resumedSessionHistory.set(t,r.messages),n.id!==void 0&&this.sendResponse(n.id,{metadata:r.metadata,messages:r.messages})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to resume session: ${o.message}`})}}function Vy(n){let e=this.currentSessionId||"default",t=this.sessionState?.createSnapshot(),o,r=this.getActiveProjectRoot();r&&(o=En.join(Vt(r),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:o,agentHome:H(),settings:pt()},usage:t?{turnCount:t.turnCount,inputTokens:t.totalInputTokens,outputTokens:t.totalOutputTokens}:void 0};n.id!==void 0&&this.sendResponse(n.id,s)}function Ky(n){let e=n.params,t=null;if(e?.projectId)t=lt(e.projectId);else if(e?.projectName){let s=fe(),i=e.projectName.toLowerCase();if(t=s.find(a=>a.name.toLowerCase()===i)??null,t||(t=s.find(a=>a.name.toLowerCase().includes(i))??null),!t){let a=s.map(l=>l.name).slice(0,10);n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!t||t.status!=="active"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let o=e.workspaceDir??t.workspaceDir;if(!Xe.existsSync(o)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Workspace directory does not exist: ${o}`});return}let r=ft(t.id);if(!r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(r.workspaceDir),this.sendNotification("project.switched",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,project:r})}function zy(n){let e=Ne(),t=fe();n.id!==void 0&&this.sendResponse(n.id,{sessionId:this.currentSessionId,activeProject:e,projects:t})}async function qy(n){let e=n.params,t=e?.sessionId;if(!t){n.id!==void 0&&this.sendResponse(n.id,{ok:!1});return}let o=fe();for(let r of o)try{let s=Ee.getProjectWorkspaceDir(r.id),i=await wn(t,s);if(i&&i.projectId===r.id){ft(r.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${r.id} for session ${t}`),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,projectId:r.id});return}}catch{}if(e?.projectName){let r=o.find(s=>s.name===e.projectName);if(r){let s=Ee.getProjectWorkspaceDir(r.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${r.id} by name "${e.projectName}"`)),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,projectId:r.id});return}}n.id!==void 0&&this.sendResponse(n.id,{ok:!1})}async function Yy(n){let e=n.params,{sessionId:t,fromProjectId:o,toProjectId:r}=e??{};if(!t||!o||!r){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(o===r){n.id!==void 0&&this.sendResponse(n.id,{ok:!0});return}let s=lt(o),i=lt(r);if(!s||!i){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,"Source or target project not found");return}let a=En.join(Ee.getProjectWorkspaceDir(o),".qlogicagent","sessions",t),l=En.join(Ee.getProjectWorkspaceDir(r),".qlogicagent","sessions",t);if(!Xe.existsSync(a)){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,`Session ${t} not found in project ${o}`);return}try{Xe.mkdirSync(En.dirname(l),{recursive:!0}),Xe.cpSync(a,l,{recursive:!0});let c=En.join(l,"metadata.json");if(Xe.existsSync(c)){let d=JSON.parse(Xe.readFileSync(c,"utf-8"));d.projectId=r,Xe.writeFileSync(c,JSON.stringify(d,null,2))}Xe.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:t,projectId:r}),this.log(`[session.moveToProject] moved ${t}: ${o} \u2192 ${r}`),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,projectId:r})}catch(c){this.log(`[session.moveToProject] error: ${c.message}`),n.id!==void 0&&this.sendError(n.id,w.INTERNAL_ERROR,`Move failed: ${c.message}`)}}import*as eb from"node:path";import{randomUUID as UE}from"node:crypto";import{join as fd}from"node:path";import{mkdir as LE,readdir as NE}from"node:fs/promises";le();function Xy(n){return fd(Oe(n),"solos")}function gd(n,e){return fd(Xy(e),n)}function Jy(n,e){return fd(gd(n,e),"solo-state.json")}async function Qy(n,e){let t=gd(n.soloId,e);await LE(t,{recursive:!0}),await eo(Jy(n.soloId,e),n)}async function $E(n,e){return An(Jy(n,e))}async function Zy(n){let e=Xy(n),t;try{t=await NE(e)}catch{return[]}let o=[];for(let r of t){let s=await $E(r,n);s&&o.push(s)}return o}async function hd(n,e){let{rm:t}=await import("node:fs/promises"),o=gd(n,e);try{return await t(o,{recursive:!0,force:!0}),!0}catch{return!1}}var ai=class{constructor(e,t,o,r={}){this.processManager=e;this.acpDetector=t;this.configStore=o;this.callbacks=r}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let t={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(o=>({agentId:o.agentId,memberId:o.memberId,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,state:o.state,resultText:o.resultText,diff:o.diff,usage:o.usage,error:o.error,turns:o.turns})),evaluation:e.evaluation,createdAt:e.createdAt};Qy(t,e.cwd).catch(()=>{})}async restoreFromDisk(e){let t=await Zy(e);for(let o of t)this.sessions.has(o.soloId)||this.sessions.set(o.soloId,{soloId:o.soloId,state:o.state,task:o.task,cwd:o.cwd,gitRoot:o.gitRoot,agents:o.agents.map(r=>({...r,turns:r.turns??[]})),evaluation:o.evaluation,createdAt:o.createdAt});return t.length}async deleteSolo(e){return this.sessions.delete(e),hd(e)}async start(e){let{task:t,agents:o,cwd:r,sharedConfig:s}=e;if(o.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await br(r);if(!i)throw new Error("Solo Mode requires a git repository");let a=t;if(s){let p=[];s.rules?.length&&p.push(`<rules>
772
+ `)},onPlanReady:(e,t)=>{this.sendNotification("product.planReady",{productId:e,plan:t})},onPlanFailed:(e,t)=>{this.sendNotification("product.planFailed",{productId:e,error:t})},onPlanningDelta:(e,t)=>{this.sendNotification("product.planningDelta",{productId:e,text:t})}})}return this.productPlanner}async function Sy(n){try{let e=n.params;if(!e?.goal||!e?.cwd||!e?.leaderAgentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"goal, cwd, and leaderAgentId are required."});return}let o=await Cn.call(this).plan(e);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ty(n){try{let e=n.params;if(!e?.productId||!e?.instances||!e?.tasks){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId, instances, and tasks are required."});return}let t=Cn.call(this),o=await t.confirm(e),r=t.getSession(e.productId);r&&await Le.call(this).create({name:r.plan?.name??r.goal.slice(0,50),cwd:r.cwd,instances:e.instances,tasks:e.tasks,budget:e.budget}),n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function wy(n){try{let e=n.params;if(!e?.productId||!e?.content){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId and content are required."});return}let o=await Cn.call(this).message(e.productId,e.content);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function xy(n){try{let e=n.params,t;if(e?.name&&e?.cwd&&e?.instances&&e?.tasks)t=e;else if(e?.tasks&&Array.isArray(e.tasks)){let i=e.config?.workdir??this.getActiveProjectRoot(),a=e.tasks.map(l=>({taskId:String(l.id??l.taskId??`task_${Math.random().toString(36).slice(2,8)}`),assignee:String(l.assignee??"default"),prompt:String(l.description??l.prompt??""),dependsOn:l.dependsOn??[]}));t={name:String(e.name??`product_${Date.now()}`),cwd:i,instances:[{name:"default",role:"executor",agentId:"self"}],tasks:a},e.budget&&(t.budget=e.budget)}else{n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"tasks is required. Provide either {name, cwd, instances, tasks} or simplified {tasks, config}."});return}if(!t.projectId){let s=Ne();s&&(t.projectId=s.id)}let r=await Le.call(this).create(t);n.id!==void 0&&this.sendResponse(n.id,{productId:r})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ry(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).resume(e.productId,this.getActiveProjectRoot()),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function _y(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).pause(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ay(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).checkpoint(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Py(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}let o=Le.call(this).getStatus(e.productId);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Iy(n){try{let t=await Le.call(this).list(this.getActiveProjectRoot());n.id!==void 0&&this.sendResponse(n.id,t)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Cy(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).delete(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ey(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).delete(e.productId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function My(n){try{let e=n.params;if(!e?.productId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INVALID_PARAMS,message:"productId is required."});return}await Le.call(this).rollback(e.productId,e.checkpoint??"latest"),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:AGENT_RPC_ERROR_CODES.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}import{randomUUID as md}from"node:crypto";import*as Xe from"node:fs";import*as En from"node:path";le();var Ee=new oo;function Oy(n){let e=n.params,t=e?.id??md();this.log(`[thread.create] id=${t} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=t,this.sessionState=new ln(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Kt(),this.enableIdleDream(),n.id!==void 0&&this.sendResponse(n.id,{id:t,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function Dy(n){let e=n.params,t=e?.limit??20;try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o),i=(await Et(t,r)).map(a=>({id:a.sessionId,title:a.title,status:"active",turnCount:a.messageCount,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt}));n.id!==void 0&&this.sendResponse(n.id,{threads:i})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to list threads: ${o.message}`})}}async function Ly(n){let e=n.params,t=e?.sessionId??md();try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o);await tt(t,{sessionId:t,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:o},r),n.id!==void 0&&this.sendResponse(n.id,{sessionId:t,title:e?.title})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to create session: ${o.message}`})}}async function Ny(n){let e=n.params;if(n.id===void 0)return;let t=e?.platform??"desktop",o=e?.chatId,r=e?.chatType,s=e?.userId??"local";try{if(t==="desktop"&&o){let d=e?.projectId??Ee.getActiveProjectId(),u=Ee.getProjectWorkspaceDir(d),m=(await Et(500,u)).find(h=>h.sessionId===o);if(m){this.sendResponse(n.id,{sessionId:o,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await tt(o,{sessionId:o,type:"personal",ownerId:s,projectId:d},u),this.sendResponse(n.id,{sessionId:o,type:"personal",ownerId:s,projectId:d});return}if(r==="group"&&o&&t){let d=`group:${t}:${o}`,u=fe();for(let p of u){if(!p.workspaceDir)continue;let h=(await Et(500,p.workspaceDir)).find(f=>f.groupKey===d&&!f.sealedAt);if(h){let f=wn(h.sessionId,p.workspaceDir);if(f){let y=await Hh(f,p.workspaceDir);if(y.split){this.sendResponse(n.id,{sessionId:y.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:t,groupName:e?.groupName,projectId:p.id,previousSessionId:y.sealedSessionId});return}}this.sendResponse(n.id,{sessionId:h.sessionId,title:h.title,type:"group",ownerId:s,groupKey:d,groupPlatform:t,groupName:e?.groupName,projectId:p.id});return}}}let i=md(),a=Ee.getActiveProjectId(),l=Ee.getProjectWorkspaceDir(a),c=r==="group"?`group:${t}:${o}`:void 0;await tt(i,{sessionId:i,type:r==="group"?"group":"personal",ownerId:s,groupKey:c,groupPlatform:r==="group"?t:void 0,groupName:e?.groupName,projectId:a},l),this.sendResponse(n.id,{sessionId:i,type:r==="group"?"group":"personal",ownerId:s,groupKey:c,groupPlatform:r==="group"?t:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to resolve session: ${i.message}`})}}async function $y(n){let e=n.params,t=e?.limit??50;try{let o;if(e?.projectId){let s=lt(e.projectId);if(!s){n.id!==void 0&&this.sendResponse(n.id,{sessions:[]});return}let i=s.workspaceDir;o=await Et(t*2,i),o=o.filter(a=>a.projectId===e.projectId);for(let a of o)a.projectId=e.projectId}else{let s=fe(),i=new Set,a=[];for(let l of s){if(!l.workspaceDir)continue;let c=await Et(t,l.workspaceDir);for(let d of c)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((l,c)=>l.lastActiveAt>c.lastActiveAt?-1:l.lastActiveAt<c.lastActiveAt?1:0),o=a}e?.archived===!0?o=o.filter(s=>s.archivedAt!=null):e?.archived===!1&&(o=o.filter(s=>s.archivedAt==null));let r=o.slice(0,t).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type,lastActiveAt:s.lastActiveAt,pinnedAt:s.pinnedAt??null,archivedAt:s.archivedAt??null,sealedAt:s.sealedAt??null,projectId:s.projectId,previousSessionId:s.previousSessionId??null,carryoverSummary:s.carryoverSummary??null}));n.id!==void 0&&this.sendResponse(n.id,{sessions:r})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to list sessions: ${o.message}`})}}async function Uy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId),r=(await Et(500,t)).find(s=>s.sessionId===e.sessionId);n.id!==void 0&&this.sendResponse(n.id,{session:r?{sessionId:r.sessionId,title:r.title,type:r.type,lastActiveAt:r.lastActiveAt,pinnedAt:r.pinnedAt??null,archivedAt:r.archivedAt??null,projectId:r.projectId}:null})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to get session: ${t.message}`})}}async function jy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId),o=await xl(e.sessionId,t);if(!o){n.id!==void 0&&this.sendResponse(n.id,{messages:[],total:0});return}let r=o.messages,s=e.limit&&e.limit>0?e.limit:r.length,i=r.slice(-s);n.id!==void 0&&this.sendResponse(n.id,{messages:i,total:r.length})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to get messages: ${t.message}`})}}async function Fy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId),o=await tt(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},t);o&&this.sendNotification("session.info",{sessionId:e.sessionId,title:o.title,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:e.projectId||void 0}),n.id!==void 0&&this.sendResponse(n.id,{ok:o!==null})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to update session: ${t.message}`})}}async function By(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId);await Rl(e.sessionId,t),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to delete session: ${t.message}`})}}async function Wy(n){let e=n.params;if(!e?.projectId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let t=Ee.getProjectWorkspaceDir(e.projectId),o=await Et(1e4,t),r=0;for(let s of o)await Rl(s.sessionId,t),r++;n.id!==void 0&&this.sendResponse(n.id,{ok:!0,deletedCount:r})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to delete all sessions: ${t.message}`})}}async function Gy(n){let e=n.params;if(!e?.sessionId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let t=Ee.resolveWorkspaceDir(e.sessionId,e.projectId);await tt(e.sessionId,{archivedAt:new Date().toISOString()},t),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to archive session: ${t.message}`})}}async function Hy(n){let e=n.params,t=e?.sessionId;if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"sessionId is required"});return}try{let o=Ee.resolveWorkspaceDir(t,e?.projectId),r=await xl(t,o);if(!r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Session not found: ${t}`});return}r.messages&&r.messages.length>0&&this.resumedSessionHistory.set(t,r.messages),n.id!==void 0&&this.sendResponse(n.id,{metadata:r.metadata,messages:r.messages})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to resume session: ${o.message}`})}}function Vy(n){let e=this.currentSessionId||"default",t=this.sessionState?.createSnapshot(),o,r=this.getActiveProjectRoot();r&&(o=En.join(Vt(r),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:o,agentHome:H(),settings:pt()},usage:t?{turnCount:t.turnCount,inputTokens:t.totalInputTokens,outputTokens:t.totalOutputTokens}:void 0};n.id!==void 0&&this.sendResponse(n.id,s)}function Ky(n){let e=n.params,t=null;if(e?.projectId)t=lt(e.projectId);else if(e?.projectName){let s=fe(),i=e.projectName.toLowerCase();if(t=s.find(a=>a.name.toLowerCase()===i)??null,t||(t=s.find(a=>a.name.toLowerCase().includes(i))??null),!t){let a=s.map(l=>l.name).slice(0,10);n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!t||t.status!=="active"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let o=e.workspaceDir??t.workspaceDir;if(!Xe.existsSync(o)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Workspace directory does not exist: ${o}`});return}let r=ft(t.id);if(!r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(r.workspaceDir),this.sendNotification("project.switched",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,project:r})}function zy(n){let e=Ne(),t=fe();n.id!==void 0&&this.sendResponse(n.id,{sessionId:this.currentSessionId,activeProject:e,projects:t})}async function qy(n){let e=n.params,t=e?.sessionId;if(!t){n.id!==void 0&&this.sendResponse(n.id,{ok:!1});return}let o=fe();for(let r of o)try{let s=Ee.getProjectWorkspaceDir(r.id),i=await wn(t,s);if(i&&i.projectId===r.id){ft(r.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${r.id} for session ${t}`),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,projectId:r.id});return}}catch{}if(e?.projectName){let r=o.find(s=>s.name===e.projectName);if(r){let s=Ee.getProjectWorkspaceDir(r.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${r.id} by name "${e.projectName}"`)),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,projectId:r.id});return}}n.id!==void 0&&this.sendResponse(n.id,{ok:!1})}async function Yy(n){let e=n.params,{sessionId:t,fromProjectId:o,toProjectId:r}=e??{};if(!t||!o||!r){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(o===r){n.id!==void 0&&this.sendResponse(n.id,{ok:!0});return}let s=lt(o),i=lt(r);if(!s||!i){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,"Source or target project not found");return}let a=En.join(Ee.getProjectWorkspaceDir(o),".qlogicagent","sessions",t),l=En.join(Ee.getProjectWorkspaceDir(r),".qlogicagent","sessions",t);if(!Xe.existsSync(a)){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,`Session ${t} not found in project ${o}`);return}try{Xe.mkdirSync(En.dirname(l),{recursive:!0}),Xe.cpSync(a,l,{recursive:!0});let c=En.join(l,"metadata.json");if(Xe.existsSync(c)){let d=JSON.parse(Xe.readFileSync(c,"utf-8"));d.projectId=r,Xe.writeFileSync(c,JSON.stringify(d,null,2))}Xe.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:t,projectId:r}),this.log(`[session.moveToProject] moved ${t}: ${o} \u2192 ${r}`),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,projectId:r})}catch(c){this.log(`[session.moveToProject] error: ${c.message}`),n.id!==void 0&&this.sendError(n.id,w.INTERNAL_ERROR,`Move failed: ${c.message}`)}}import*as eb from"node:path";import{randomUUID as FE}from"node:crypto";import{join as fd}from"node:path";import{mkdir as $E,readdir as UE}from"node:fs/promises";le();function Xy(n){return fd(Oe(n),"solos")}function gd(n,e){return fd(Xy(e),n)}function Jy(n,e){return fd(gd(n,e),"solo-state.json")}async function Qy(n,e){let t=gd(n.soloId,e);await $E(t,{recursive:!0}),await eo(Jy(n.soloId,e),n)}async function jE(n,e){return An(Jy(n,e))}async function Zy(n){let e=Xy(n),t;try{t=await UE(e)}catch{return[]}let o=[];for(let r of t){let s=await jE(r,n);s&&o.push(s)}return o}async function hd(n,e){let{rm:t}=await import("node:fs/promises"),o=gd(n,e);try{return await t(o,{recursive:!0,force:!0}),!0}catch{return!1}}var ai=class{constructor(e,t,o,r={}){this.processManager=e;this.acpDetector=t;this.configStore=o;this.callbacks=r}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let t={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(o=>({agentId:o.agentId,memberId:o.memberId,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,state:o.state,resultText:o.resultText,diff:o.diff,usage:o.usage,error:o.error,turns:o.turns})),evaluation:e.evaluation,createdAt:e.createdAt};Qy(t,e.cwd).catch(()=>{})}async restoreFromDisk(e){let t=await Zy(e);for(let o of t)this.sessions.has(o.soloId)||this.sessions.set(o.soloId,{soloId:o.soloId,state:o.state,task:o.task,cwd:o.cwd,gitRoot:o.gitRoot,agents:o.agents.map(r=>({...r,turns:r.turns??[]})),evaluation:o.evaluation,createdAt:o.createdAt});return t.length}async deleteSolo(e){return this.sessions.delete(e),hd(e)}async start(e){let{task:t,agents:o,cwd:r,sharedConfig:s}=e;if(o.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await br(r);if(!i)throw new Error("Solo Mode requires a git repository");let a=t;if(s){let p=[];s.rules?.length&&p.push(`<rules>
773
773
  ${s.rules.join(`
774
774
  `)}
775
775
  </rules>`),s.memory?.length&&p.push(`<memory>
@@ -779,7 +779,7 @@ ${s.memory.join(`
779
779
 
780
780
  `)}
781
781
 
782
- ${t}`)}let l=`solo-${UE().slice(0,8)}`,c={soloId:l,state:"running",task:t,cwd:r,gitRoot:i,agents:[],createdAt:Date.now()};this.sessions.set(l,c),this.persistSession(c),this.callbacks.log?.info(`[solo] starting ${l} with ${o.length} agents`);let d=o.map(async(p,m)=>{let h=`${l}-${p}-${m}`,f=`solo/${h}`,y=`${l}:${p}:${m}`,b;try{b=await ri(i,h)}catch(x){this.callbacks.log?.warn(`[solo] worktree creation failed for ${p}: ${x instanceof Error?x.message:String(x)}`);let I={agentId:p,memberId:y,worktreePath:"",worktreeBranch:f,state:"failed",error:`Worktree creation failed: ${x instanceof Error?x.message:String(x)}`,turns:[]};c.agents.push(I);return}let k={agentId:p,memberId:y,worktreePath:b,worktreeBranch:f,state:"pending",turns:[]};c.agents.push(k);try{k.state="running",this.callbacks.onProgress?.(l,p,"running");let x=this.acpDetector.buildExternalDescriptor(p);if(!x)throw new Error(`Agent ${p} is not available or not ACP-compatible`);await this.processManager.spawn({memberId:y,name:`solo-${p}`,cwd:b,prompt:a,external:x});let I=this.processManager.getHandle(y);if(!I||I.state!=="ready")throw new Error(`Agent ${p} spawn did not reach ready state`);let P=await this.processManager.sendTask(y,a);k.state="completed",k.resultText=typeof P=="string"?P:JSON.stringify(P),k.diff=await pd(b),k.turns.push({role:"user",content:t,timestamp:Date.now()}),k.turns.push({role:"agent",content:k.resultText,timestamp:Date.now()});let O=this.processManager.getUsageTracker(y);if(O?.hasData()){let $=O.getUsage();k.usage={inputTokens:$.inputTokens,outputTokens:$.outputTokens}}this.callbacks.onProgress?.(l,p,"completed"),k.diff&&this.callbacks.onAgentDiff?.(l,p,[{path:".",hunks:k.diff}]),k.usage&&this.callbacks.onAgentUsage?.(l,p,k.usage.inputTokens,k.usage.outputTokens),this.callbacks.log?.info(`[solo] ${p} completed (diff: ${k.diff?"yes":"none"})`)}catch(x){k.state="failed",k.error=x instanceof Error?x.message:String(x),this.callbacks.onProgress?.(l,p,"failed",k.error),this.callbacks.log?.warn(`[solo] ${p} failed: ${k.error}`)}});await Promise.allSettled(d);let u=c.agents.filter(p=>p.state==="completed");if(u.length===0)return c.state="failed",this.persistSession(c),this.callbacks.log?.warn(`[solo] all agents failed for ${l}`),l;for(let p of c.agents)p.state==="completed"&&(p.state="idle");return this.persistSession(c),this.callbacks.log?.info(`[solo] ${u.length}/${c.agents.length} agents ready for interaction`),l}async message(e,t,o,r){let s=this.sessions.get(e);if(!s)throw new Error(`Solo session ${e} not found`);if(s.state!=="running")throw new Error(`Solo session ${e} is not active (state: ${s.state})`);let i=s.agents.filter(c=>c.agentId===t),a=r!==void 0?i[r]:i[0];if(!a)throw new Error(`Agent ${t} not found in solo session ${e}`);if(!["idle","completed"].includes(a.state))throw new Error(`Agent ${t} is not ready for messages (state: ${a.state})`);a.turns.push({role:"user",content:o,timestamp:Date.now()}),a.state="running",this.callbacks.onProgress?.(e,t,"running");try{let c=await this.processManager.sendTask(a.memberId,o),d=typeof c=="string"?c:c?.content??JSON.stringify(c);a.turns.push({role:"agent",content:d,timestamp:Date.now()}),a.resultText=d,a.diff=await pd(a.worktreePath),a.state="idle";let u=this.processManager.getUsageTracker(a.memberId);if(u?.hasData()){let p=u.getUsage();a.usage={inputTokens:p.inputTokens,outputTokens:p.outputTokens}}return this.callbacks.onProgress?.(e,t,"idle"),this.persistSession(s),{resultText:d}}catch(c){throw a.state="failed",a.error=c instanceof Error?c.message:String(c),this.callbacks.onProgress?.(e,t,"failed",a.error),this.persistSession(s),c}}async triggerEvaluation(e,t,o){let r=this.sessions.get(e);if(!r)throw new Error(`Solo session ${e} not found`);let s=r.agents.filter(l=>l.state==="completed"||l.state==="idle");if(s.length===0)throw new Error(`No agents have completed work in session ${e}`);let i=r.agents.filter(l=>l.agentId===t),a=o!==void 0?i[o]:i[0];if(!a)throw new Error(`Evaluator agent ${t} not found in session ${e}`);if(a.state!=="idle"&&a.state!=="completed")throw new Error(`Evaluator agent ${t} is not ready (state: ${a.state})`);r.state="evaluating",this.callbacks.log?.info(`[solo] user-triggered evaluation for ${e} by ${t} (${s.length} candidates)`);try{let l=await this.evaluate(r,s,a);return r.evaluation=l,r.state="running",this.callbacks.onEvaluation?.(e,l),this.persistSession(r),l}catch(l){throw r.state="running",this.persistSession(r),new Error(`Evaluation failed: ${l instanceof Error?l.message:String(l)}`)}}getStatus(e){let t=this.sessions.get(e);return t?{soloId:t.soloId,state:t.state,agents:t.agents.map(o=>({id:o.agentId,state:o.state,progress:o.state==="running"?"Working...":void 0,resultText:o.resultText,diff:o.diff,usage:o.usage,error:o.error,worktreePath:o.worktreePath})),evaluation:t.evaluation}:null}async cancel(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state!=="running"&&t.state!=="evaluating")throw new Error(`Solo session ${e} is not running (state: ${t.state})`);t.state="cancelled";for(let o of t.agents)if(o.state==="running"||o.state==="pending"||o.state==="idle"){o.state="failed",o.error="Cancelled by user";try{this.processManager.kill(o.memberId)}catch{}}await this.cleanupWorktrees(t),this.callbacks.log?.info(`[solo] cancelled ${e}`)}async select(e){let t=this.sessions.get(e.soloId);if(!t)throw new Error(`Solo session ${e.soloId} not found`);if(t.state!=="completed"&&t.state!=="running")throw new Error(`Solo session ${e.soloId} is not ready for selection (state: ${t.state})`);let o=t.agents.find(s=>s.agentId===e.winnerId&&(s.state==="completed"||s.state==="idle"));if(!o)throw new Error(`Agent ${e.winnerId} is not a completed participant in ${e.soloId}`);let r=await by(t.gitRoot,o.worktreeBranch);return this.callbacks.log?.info(`[solo] merged ${o.worktreeBranch}: ${r}`),t.state="completed",await this.cleanupWorktrees(t),this.persistSession(t),o.worktreeBranch}listSessions(){return[...this.sessions.values()].map(e=>this.getStatus(e.soloId))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state==="running"||t.state==="evaluating"){t.state="cancelled";for(let o of t.agents)if(o.state==="running"||o.state==="pending"||o.state==="idle"){o.state="failed",o.error="Deleted";try{this.processManager.kill(o.memberId)}catch{}}await this.cleanupWorktrees(t)}this.sessions.delete(e),await hd(e,t?.cwd),this.callbacks.log?.info(`[solo] deleted ${e}`)}async evaluate(e,t,o){if(t.length===1)return{winnerId:t[0].agentId,reasoning:`Only one agent (${t[0].agentId}) completed successfully.`};let r=["# Task Evaluation","","## Original Task",e.task,"","## Agent Results",""];for(let a of t)r.push(`### Agent: ${a.agentId}`,"","**Result:**",a.resultText??"(no output)","","**Changes (git diff stat):**",a.diff||"(no changes)","");r.push("## Instructions","","Review all agent results above. Select the best implementation and explain your reasoning.","Respond in this exact format:","","WINNER: <agent-id>","REASONING: <your explanation>");let s=r.join(`
782
+ ${t}`)}let l=`solo-${FE().slice(0,8)}`,c={soloId:l,state:"running",task:t,cwd:r,gitRoot:i,agents:[],createdAt:Date.now()};this.sessions.set(l,c),this.persistSession(c),this.callbacks.log?.info(`[solo] starting ${l} with ${o.length} agents`);let d=o.map(async(p,m)=>{let h=`${l}-${p}-${m}`,f=`solo/${h}`,y=`${l}:${p}:${m}`,b;try{b=await ri(i,h)}catch(x){this.callbacks.log?.warn(`[solo] worktree creation failed for ${p}: ${x instanceof Error?x.message:String(x)}`);let I={agentId:p,memberId:y,worktreePath:"",worktreeBranch:f,state:"failed",error:`Worktree creation failed: ${x instanceof Error?x.message:String(x)}`,turns:[]};c.agents.push(I);return}let k={agentId:p,memberId:y,worktreePath:b,worktreeBranch:f,state:"pending",turns:[]};c.agents.push(k);try{k.state="running",this.callbacks.onProgress?.(l,p,"running");let x=this.acpDetector.buildExternalDescriptor(p);if(!x)throw new Error(`Agent ${p} is not available or not ACP-compatible`);await this.processManager.spawn({memberId:y,name:`solo-${p}`,cwd:b,prompt:a,external:x});let I=this.processManager.getHandle(y);if(!I||I.state!=="ready")throw new Error(`Agent ${p} spawn did not reach ready state`);let P=await this.processManager.sendTask(y,a);k.state="completed",k.resultText=typeof P=="string"?P:JSON.stringify(P),k.diff=await pd(b),k.turns.push({role:"user",content:t,timestamp:Date.now()}),k.turns.push({role:"agent",content:k.resultText,timestamp:Date.now()});let O=this.processManager.getUsageTracker(y);if(O?.hasData()){let $=O.getUsage();k.usage={inputTokens:$.inputTokens,outputTokens:$.outputTokens}}this.callbacks.onProgress?.(l,p,"completed"),k.diff&&this.callbacks.onAgentDiff?.(l,p,[{path:".",hunks:k.diff}]),k.usage&&this.callbacks.onAgentUsage?.(l,p,k.usage.inputTokens,k.usage.outputTokens),this.callbacks.log?.info(`[solo] ${p} completed (diff: ${k.diff?"yes":"none"})`)}catch(x){k.state="failed",k.error=x instanceof Error?x.message:String(x),this.callbacks.onProgress?.(l,p,"failed",k.error),this.callbacks.log?.warn(`[solo] ${p} failed: ${k.error}`)}});await Promise.allSettled(d);let u=c.agents.filter(p=>p.state==="completed");if(u.length===0)return c.state="failed",this.persistSession(c),this.callbacks.log?.warn(`[solo] all agents failed for ${l}`),l;for(let p of c.agents)p.state==="completed"&&(p.state="idle");return this.persistSession(c),this.callbacks.log?.info(`[solo] ${u.length}/${c.agents.length} agents ready for interaction`),l}async message(e,t,o,r){let s=this.sessions.get(e);if(!s)throw new Error(`Solo session ${e} not found`);if(s.state!=="running")throw new Error(`Solo session ${e} is not active (state: ${s.state})`);let i=s.agents.filter(c=>c.agentId===t),a=r!==void 0?i[r]:i[0];if(!a)throw new Error(`Agent ${t} not found in solo session ${e}`);if(!["idle","completed"].includes(a.state))throw new Error(`Agent ${t} is not ready for messages (state: ${a.state})`);a.turns.push({role:"user",content:o,timestamp:Date.now()}),a.state="running",this.callbacks.onProgress?.(e,t,"running");try{let c=await this.processManager.sendTask(a.memberId,o),d=typeof c=="string"?c:c?.content??JSON.stringify(c);a.turns.push({role:"agent",content:d,timestamp:Date.now()}),a.resultText=d,a.diff=await pd(a.worktreePath),a.state="idle";let u=this.processManager.getUsageTracker(a.memberId);if(u?.hasData()){let p=u.getUsage();a.usage={inputTokens:p.inputTokens,outputTokens:p.outputTokens}}return this.callbacks.onProgress?.(e,t,"idle"),this.persistSession(s),{resultText:d}}catch(c){throw a.state="failed",a.error=c instanceof Error?c.message:String(c),this.callbacks.onProgress?.(e,t,"failed",a.error),this.persistSession(s),c}}async triggerEvaluation(e,t,o){let r=this.sessions.get(e);if(!r)throw new Error(`Solo session ${e} not found`);let s=r.agents.filter(l=>l.state==="completed"||l.state==="idle");if(s.length===0)throw new Error(`No agents have completed work in session ${e}`);let i=r.agents.filter(l=>l.agentId===t),a=o!==void 0?i[o]:i[0];if(!a)throw new Error(`Evaluator agent ${t} not found in session ${e}`);if(a.state!=="idle"&&a.state!=="completed")throw new Error(`Evaluator agent ${t} is not ready (state: ${a.state})`);r.state="evaluating",this.callbacks.log?.info(`[solo] user-triggered evaluation for ${e} by ${t} (${s.length} candidates)`);try{let l=await this.evaluate(r,s,a);return r.evaluation=l,r.state="running",this.callbacks.onEvaluation?.(e,l),this.persistSession(r),l}catch(l){throw r.state="running",this.persistSession(r),new Error(`Evaluation failed: ${l instanceof Error?l.message:String(l)}`)}}getStatus(e){let t=this.sessions.get(e);return t?{soloId:t.soloId,state:t.state,agents:t.agents.map(o=>({id:o.agentId,state:o.state,progress:o.state==="running"?"Working...":void 0,resultText:o.resultText,diff:o.diff,usage:o.usage,error:o.error,worktreePath:o.worktreePath})),evaluation:t.evaluation}:null}async cancel(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state!=="running"&&t.state!=="evaluating")throw new Error(`Solo session ${e} is not running (state: ${t.state})`);t.state="cancelled";for(let o of t.agents)if(o.state==="running"||o.state==="pending"||o.state==="idle"){o.state="failed",o.error="Cancelled by user";try{this.processManager.kill(o.memberId)}catch{}}await this.cleanupWorktrees(t),this.callbacks.log?.info(`[solo] cancelled ${e}`)}async select(e){let t=this.sessions.get(e.soloId);if(!t)throw new Error(`Solo session ${e.soloId} not found`);if(t.state!=="completed"&&t.state!=="running")throw new Error(`Solo session ${e.soloId} is not ready for selection (state: ${t.state})`);let o=t.agents.find(s=>s.agentId===e.winnerId&&(s.state==="completed"||s.state==="idle"));if(!o)throw new Error(`Agent ${e.winnerId} is not a completed participant in ${e.soloId}`);let r=await by(t.gitRoot,o.worktreeBranch);return this.callbacks.log?.info(`[solo] merged ${o.worktreeBranch}: ${r}`),t.state="completed",await this.cleanupWorktrees(t),this.persistSession(t),o.worktreeBranch}listSessions(){return[...this.sessions.values()].map(e=>this.getStatus(e.soloId))}async delete(e){let t=this.sessions.get(e);if(!t)throw new Error(`Solo session ${e} not found`);if(t.state==="running"||t.state==="evaluating"){t.state="cancelled";for(let o of t.agents)if(o.state==="running"||o.state==="pending"||o.state==="idle"){o.state="failed",o.error="Deleted";try{this.processManager.kill(o.memberId)}catch{}}await this.cleanupWorktrees(t)}this.sessions.delete(e),await hd(e,t?.cwd),this.callbacks.log?.info(`[solo] deleted ${e}`)}async evaluate(e,t,o){if(t.length===1)return{winnerId:t[0].agentId,reasoning:`Only one agent (${t[0].agentId}) completed successfully.`};let r=["# Task Evaluation","","## Original Task",e.task,"","## Agent Results",""];for(let a of t)r.push(`### Agent: ${a.agentId}`,"","**Result:**",a.resultText??"(no output)","","**Changes (git diff stat):**",a.diff||"(no changes)","");r.push("## Instructions","","Review all agent results above. Select the best implementation and explain your reasoning.","Respond in this exact format:","","WINNER: <agent-id>","REASONING: <your explanation>");let s=r.join(`
783
783
  `),i=o.memberId;try{let a=await this.processManager.sendTask(i,s),l=typeof a=="string"?a:JSON.stringify(a);return this.parseEvaluationResponse(l,t)}catch{return{winnerId:t[0].agentId,reasoning:"Evaluation failed; defaulting to first completed agent."}}}parseEvaluationResponse(e,t){let o=e.match(/WINNER:\s*(\S+)/i),r=e.match(/REASONING:\s*(.+)/is),s=t.map(a=>a.agentId),i=o?.[1];if(i&&s.includes(i))return{winnerId:i,reasoning:r?.[1]?.trim()||"Selected by leader evaluation."};for(let a of s)if(e.includes(a))return{winnerId:a,reasoning:r?.[1]?.trim()||e.slice(0,500)};return{winnerId:t[0].agentId,reasoning:`Could not parse evaluation. Full response: ${e.slice(0,500)}`}}async cleanupWorktrees(e){for(let t of e.agents)if(t.worktreePath)try{try{this.processManager.kill(t.memberId)}catch{}this.processManager.remove(t.memberId),await yy(e.gitRoot,t.worktreePath)}catch(o){this.callbacks.log?.warn(`[solo] failed to clean worktree for ${t.agentId}: ${o instanceof Error?o.message:String(o)}`)}}};le();function Je(){if(!this.soloEvaluator){let n=new pn({log:{info:t=>process.stderr.write(`[solo:pm] ${t}
784
784
  `),warn:t=>process.stderr.write(`[solo:pm] WARN ${t}
785
785
  `)},onNotification:(t,o,r)=>{(o==="agents.error"||o==="agents.status")&&this.sendNotification(o,r),this.sendNotification("team.member.notification",{memberId:t,method:o,params:r})},onStateChange:(t,o)=>{let r=n.getHandle(t),i=n.getUsageTracker(t)?.getUsage();this.emitAgentStatus(t,o,{missedBeats:n.getMissedBeats(t),lastActivityAt:r?.lastActivityAt,usage:i&&i.totalTokens>0?{inputTokens:i.inputTokens,outputTokens:i.outputTokens,totalTokens:i.totalTokens}:void 0})},onMcpToolCall:(t,o,r)=>this.handleMcpToolCall(t,o,r),sessionDir:eb.join(H(),"agent-logs")}),e={log:{info:t=>process.stderr.write(`${t}
@@ -790,7 +790,7 @@ ${o.content}`).join(`
790
790
 
791
791
  `)}
792
792
  </project-instructions>`}isValidFilename(e){return!(!e.endsWith(".md")||e.includes("/")||e.includes("\\")||e.includes("..")||e.startsWith("."))}getDirSize(e){if(!Qe.existsSync(this.dir))return 0;let t=0;for(let o of Qe.readdirSync(this.dir)){if(o===e)continue;let r=kr.join(this.dir,o);try{let s=Qe.statSync(r);s.isFile()&&(t+=s.size)}catch{}}return t}};le();function Mn(n){return lt(n)?.workspaceDir??null}function ci(n){return n?new li(n):null}async function Eb(n){let e=n.params;if(!e?.projectId){n.id!==void 0&&this.sendResponse(n.id,{entries:[]});return}let t=Mn(e.projectId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{entries:[]});return}try{let o=e.path?Tt.join(t,e.path):t,s=(await St.promises.readdir(o,{withFileTypes:!0})).filter(i=>!i.name.startsWith(".")).map(i=>({name:i.name,path:e.path?`${e.path}/${i.name}`:i.name,type:i.isDirectory()?"directory":"file"}));n.id!==void 0&&this.sendResponse(n.id,{entries:s})}catch{n.id!==void 0&&this.sendResponse(n.id,{entries:[]})}}async function Mb(n){let e=n.params;if(!e?.projectId||!e?.path){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required params: projectId, path"});return}let t=Mn(e.projectId);if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Project not found"});return}let o=Tt.join(t,e.path);if(!o.startsWith(t)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Path escapes project directory"});return}try{e.type==="directory"?await St.promises.mkdir(o,{recursive:!0}):(await St.promises.mkdir(Tt.dirname(o),{recursive:!0}),await St.promises.writeFile(o,e.content??"","utf-8")),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,path:e.path})}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to create: ${r.message}`})}}async function Ob(n){let e=n.params;if(!e?.projectId||!e?.oldPath||!e?.newName){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required params: projectId, oldPath, newName"});return}let t=Mn(e.projectId);if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Project not found"});return}let o=Tt.join(t,e.oldPath),r=Tt.join(Tt.dirname(o),e.newName);if(!o.startsWith(t)||!r.startsWith(t)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Path escapes project directory"});return}try{await St.promises.rename(o,r);let s=Tt.relative(t,r).replace(/\\/g,"/");n.id!==void 0&&this.sendResponse(n.id,{ok:!0,newPath:s})}catch(s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to rename: ${s.message}`})}}async function Db(n){let e=n.params;if(!e?.projectId||!e?.path){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required params: projectId, path"});return}let t=Mn(e.projectId);if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Project not found"});return}let o=Tt.join(t,e.path);if(!o.startsWith(t)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Path escapes project directory"});return}try{await St.promises.rm(o,{recursive:!0}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`Failed to delete: ${r.message}`})}}async function Lb(n){let e=n.params;if(!e?.projectId){n.id!==void 0&&this.sendResponse(n.id,{files:[]});return}let t=Mn(e.projectId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{files:[]});return}try{let{execSync:o}=await import("node:child_process"),s=o("git statusporcelain",{cwd:t,encoding:"utf-8",timeout:5e3}).split(`
793
- `).filter(Boolean).map(i=>({path:i.slice(3),status:i.slice(0,2).trim()}));n.id!==void 0&&this.sendResponse(n.id,{files:s})}catch{n.id!==void 0&&this.sendResponse(n.id,{files:[]})}}function Nb(n){let e=n.params,t;if(e?.projectId&&(t=Mn(e.projectId)??void 0),t||(t=this.getActiveProjectRoot()),!t){n.id!==void 0&&this.sendResponse(n.id,{instructions:[]});return}let o=[],r=Oo(t);try{let i=St.statSync(r);i.isFile()&&o.push({name:"INSTRUCTIONS.md",path:"INSTRUCTIONS.md",size:i.size})}catch{}let s=ci(t);if(s)for(let i of s.list())o.push({name:i.filename,path:`rules/${i.filename}`,size:i.sizeBytes});n.id!==void 0&&this.sendResponse(n.id,{instructions:o})}function $b(n){let e=n.params;if(!e?.path){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: path"});return}let t;if(e?.projectId&&(t=Mn(e.projectId)??void 0),t||(t=this.getActiveProjectRoot()),!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}if(e.path==="INSTRUCTIONS.md"){let i=Oo(t);try{let a=St.readFileSync(i,"utf8");this.sendResponse(n.id,{content:a,metadata:{filename:"INSTRUCTIONS.md",sizeBytes:Buffer.byteLength(a)}})}catch{this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Instruction file not found"})}return}let o=e.path.startsWith("rules/")?e.path.slice(6):e.path,r=ci(t);if(!r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}let s=r.read(o);if(!s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Instruction file not found"});return}n.id!==void 0&&this.sendResponse(n.id,{content:s.content,metadata:{filename:s.filename,sizeBytes:s.sizeBytes}})}function Ub(n){let e=n.params;if(!e?.path||typeof e?.content!="string"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required params: path, content"});return}let t=ci(this.getActiveProjectRoot());if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}try{t.write(e.path,e.content),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}function jb(n){let e=n.params;if(!e?.path){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: path"});return}let t=ci(this.getActiveProjectRoot());if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}if(!t.remove(e.path)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Instruction file not found"});return}n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}function bd(n,e){let o=(typeof e=="string"&&e.trim()?e:typeof n.memoryUserId=="string"&&n.memoryUserId.trim()?n.memoryUserId:"").trim();return o||null}function jE(){return{records:[],stats:{formed:0,insights:0,preferences:0}}}async function Fb(n){let e=[];this.memdir&&e.push({id:"memdir",type:"file",path:Mc(this.getActiveProjectRoot())}),this.memoryProvider&&e.push({id:"local",type:"vector"}),n.id!==void 0&&this.sendResponse(n.id,{sources:e})}async function Bb(n){let e=n.params;if(this.ensureMemoryProvider?.(),!this.memoryProvider||typeof this.memoryProvider.list!="function"){n.id!==void 0&&this.sendResponse(n.id,{records:[],stats:{formed:0,insights:0,preferences:0}});return}try{let t=bd(this,e?.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,jE());return}let r=this.memoryProvider.list(t,{pageSize:e?.pageSize??500,activeOnly:!0}).map(a=>({id:a.id,text:a.text,category:a.category,importance:a.importance,confidence:a.confidence,source:a.source,sessionId:a.sessionId,eventDate:a.eventDate,tags:a.tags,createdAt:a.createdAt,updatedAt:a.updatedAt,accessCount:a.accessCount,lastAccessedAt:a.lastAccessedAt,isArchived:a.isArchived})),s=0,i=0;for(let a of r)a.category==="insight"||a.category==="lesson"?s++:a.category==="preference"&&i++;n.id!==void 0&&this.sendResponse(n.id,{records:r,stats:{formed:r.length,insights:s,preferences:i}})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async function Wb(n){let e=n.params;if(this.ensureMemoryProvider?.(),!this.memoryProvider||typeof this.memoryProvider.getActivitySummary!="function"){n.id!==void 0&&this.sendResponse(n.id,{dailyCounts:[],highlights:[]});return}try{let t=bd(this,e?.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{dailyCounts:[],highlights:[]});return}let o=this.memoryProvider.getActivitySummary(t,e?.days??180);n.id!==void 0&&this.sendResponse(n.id,o)}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async function Gb(n){let e=n.params,t=e?.source??"memdir",o=e?.target??"index";if(t==="memdir"||t==="local"){if(!this.memdir){n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:o,content:""});return}try{if(o==="index"){let r=this.memdir.getIndexRaw();n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:"index",content:r})}else{let r=await this.memdir.readFile(o);n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:o,content:r.content??""})}}catch{n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:o,content:""})}}else n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown memory source: ${t}`})}async function Hb(n){let e=n.params,t=e?.target??"index",o=e?.content;if(o==null){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"content is required."});return}if(!this.memdir){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Memory system not initialized."});return}try{if(t==="index"){let r=await this.memdir.addToIndex(o);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,target:"index",message:r.message})}else{let r=await this.memdir.writeFile(t,o);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,target:t,message:r.message})}this.sendNotification("memory.updated",{target:t,source:"rpc"})}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}}async function Vb(n){let e=n.params;if(!e?.query){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"query is required."});return}if(this.memoryProvider){let t=bd(this,e.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{results:[]});return}try{let o=await this.memoryProvider.search(e.query,t,{limit:e.limit??10});n.id!==void 0&&this.sendResponse(n.id,{results:o.map(r=>({id:r.blockId??"",text:r.text,score:r.score,source:"local",metadata:r.metadata}))})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}else if(this.memdir)try{let t=await this.memdir.searchLocal(e.query);n.id!==void 0&&this.sendResponse(n.id,{results:t.slice(0,e.limit??10).map((o,r)=>({id:`memdir-${r}`,text:o.snippet,score:o.score,source:"memdir",metadata:{file:o.file}}))})}catch{n.id!==void 0&&this.sendResponse(n.id,{results:[]})}else n.id!==void 0&&this.sendResponse(n.id,{results:[]})}async function Kb(n){let e=n.params;if(!e?.match){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"match is required."});return}let t=e.source??"memdir";if(t==="memdir"||t==="local"){if(!this.memdir){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Memory system not initialized."});return}let o=e.target??"index";try{if(o==="index"){let r=await this.memdir.removeFromIndex(e.match);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,removedCount:r.ok?1:0,message:r.message}),r.ok&&this.sendNotification("memory.updated",{source:"memdir",target:"index"})}else{let r=await this.memdir.deleteFile(o);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,removedCount:r.ok?1:0,message:r.message}),r.ok&&this.sendNotification("memory.updated",{source:"memdir",target:o})}}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}}else if(t==="vector"&&this.memoryProvider)try{await this.memoryProvider.remove(e.match),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,removedCount:1,message:"Removed from local memory."}),this.sendNotification("memory.updated",{source:"local"})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}else n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown or unavailable source: ${t}`})}le();mt();import*as en from"node:fs";import*as kd from"node:path";je();function zb(n){let e=n.params,o=Mt(e?.includeDeferred??!1).map(r=>({name:r.function.name,description:r.function.description??"",parameters:r.function.parameters,source:"builtin"}));if(e?.category){let r=o.filter(s=>s.name.startsWith(e.category)||s.description.toLowerCase().includes(e.category.toLowerCase()));n.id!==void 0&&this.sendResponse(n.id,{tools:r,total:r.length})}else n.id!==void 0&&this.sendResponse(n.id,{tools:o,total:o.length})}function qb(n){let e=X().listProviderDefs(),t=new Map;for(let r of e){let s=r.group??r.id;t.has(s)||t.set(s,[]);let i=!!X().resolveProviderApiKey(r.id);t.get(s).push({id:r.id,name:r.name,transport:r.transport,baseUrl:r.baseUrl,defaultModel:r.defaultModel,modelCount:r.models?.length??0,available:i})}let o=[...t.entries()].map(([r,s])=>({group:r,variants:s}));n.id!==void 0&&this.sendResponse(n.id,{providers:o})}function Yb(n){try{let t=X().exportConfig();n.id!==void 0&&this.sendResponse(n.id,{config:{providers:t.providers,models:t.models,bindings:t.bindings},paths:{userSettings:pt(),agentHome:H()}})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}var FE=new Set(["providers","models","bindings","provider","model","apiKey","baseUrl","providerKeys"]);async function Xb(n){let e=n.params;if(!e?.updates||typeof e.updates!="object"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"updates (object) is required."});return}let t=[],o={};for(let[r,s]of Object.entries(e.updates))FE.has(r)?t.push({key:r,reason:"Use settings.* RPC methods for model/key management"}):o[r]=s;if(t.length>0&&Object.keys(o).length===0){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Rejected keys: ${t.map(r=>r.key).join(", ")}. Use settings.* RPC for model management.`});return}try{let r=pt(),s={};try{let i=await en.promises.readFile(r,"utf-8");s=JSON.parse(i)}catch{}Object.assign(s,o),await en.promises.mkdir(kd.dirname(r),{recursive:!0}),await en.promises.writeFile(r,JSON.stringify(s,null,2),"utf-8"),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,applied:Object.keys(o),rejected:t})}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}}function Jb(n){try{let e=ma(),t=pt(),o={};try{let r=en.readFileSync(t,"utf-8"),s=JSON.parse(r);s.tunables&&typeof s.tunables=="object"&&(o=s.tunables)}catch{}n.id!==void 0&&this.sendResponse(n.id,{defaults:e,overrides:o})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Qb(n){let e=n.params,t=e?.key,o=e?.value;if(!t||typeof t!="string"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: key (string)"});return}let r=ma();if(!(t in r)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown tunable key: "${t}". Valid keys: ${Object.keys(r).join(", ")}`});return}let s=typeof r[t];if(o==null||typeof o!==s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Invalid value for "${t}": expected ${s}, got ${typeof o}`});return}try{let i=pt(),a={};try{let l=await en.promises.readFile(i,"utf-8");a=JSON.parse(l)}catch{}(!a.tunables||typeof a.tunables!="object")&&(a.tunables={}),a.tunables[t]=o,await en.promises.mkdir(kd.dirname(i),{recursive:!0}),await en.promises.writeFile(i,JSON.stringify(a,null,2),"utf-8"),t==="teamBudgetTokens"&&typeof o=="number"&&(we.teamBudget.budgetTokens=o),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,key:t,value:o})}catch(i){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:i instanceof Error?i.message:String(i)})}}async function Zb(n){let e=nt("task");if(!e){n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Bo([])});return}try{let r=(await e.execute("rpc-todos-list",{action:"list"},void 0)).details?.taskList??[];n.id!==void 0&&this.sendResponse(n.id,{items:r,summary:Bo(r)})}catch{n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Bo([])})}}function ek(n){let t=n.params?.lifecycle??"all",o=this.taskStore.getAllTasks(),r=t==="all"?o:o.filter(s=>s.lifecycle===t);n.id!==void 0&&this.sendResponse(n.id,{tasks:r.map(s=>({taskId:s.taskId,type:s.type,lifecycle:s.lifecycle,label:s.label}))})}function tk(n){let e=n.params;if(!e?.taskId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"taskId is required."});return}let o=this.taskStore.getAllTasks().find(r=>r.taskId===e.taskId);if(!o){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,message:`Task ${e.taskId} not found.`});return}if(o.lifecycle!=="running"&&o.lifecycle!=="pending"){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,message:`Task ${e.taskId} is already ${o.lifecycle}.`});return}this.taskStore.updateTask(e.taskId,r=>(r.lifecycle="cancelled",r)),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,message:`Task ${e.taskId} cancelled.`})}le();import*as nk from"node:fs";import*as vd from"node:path";async function ok(n){try{let e=n.params,t=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(t.getData());let o=this.acpDetector.scan(e?.force);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function rk(n){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let t=this.acpDetector.list();n.id!==void 0&&this.sendResponse(n.id,t)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function sk(n){try{let e=n.params;if(!e?.action||!e?.agent){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"action and agent are required."});return}let t=await this.ensureAgentConfigStore();switch(e.action){case"register":t.registerCustomAgent(e.agent);break;case"unregister":t.unregisterCustomAgent(e.agent.id);break;case"update":t.registerCustomAgent(e.agent);break}this.acpDetector.setConfigStore(t.getData()),this.acpDetector.clearCache(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function ik(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=await this.ensureAgentConfigStore(),{agentId:o,...r}=e;await t.setAgentConfig(o,r),this.acpDetector.setConfigStore(t.getData()),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function ak(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let o=(await this.ensureAgentConfigStore()).getAgentConfig(e.agentId);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function lk(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=await this.ensureAgentConfigStore();await t.removeAgentConfig(e.agentId),this.acpDetector.setConfigStore(t.getData()),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function ck(n){try{let e=n.params;if(!e?.url){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"url is required."});return}await(await this.ensureAgentConfigStore()).setGatewayUrl(e.url),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function dk(n){try{let t=(await this.ensureAgentConfigStore()).getGatewayUrl();n.id!==void 0&&this.sendResponse(n.id,{url:t})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function uk(n){try{let t=(await this.ensureAgentConfigStore()).getData(),o=Object.entries(t.agents).map(([r,s])=>({agentId:r,hasApiKey:!!s.apiKey,hasBaseUrl:!!s.baseUrl,hasModel:!!s.model}));n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function pk(n){try{let e=[],t=(o,r)=>{if(o)for(let s of o.getAllHandles())e.push({memberId:s.memberId,name:s.name,pid:s.pid,state:s.state,startedAt:s.startedAt,endedAt:s.endedAt,source:r})};t(this.soloProcessManager,"solo"),t(this.productProcessManager,"product"),n.id!==void 0&&this.sendResponse(n.id,e)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function mk(n){try{let e=n.params;if(!e?.memberId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"memberId is required."});return}let t=!1;for(let o of[this.soloProcessManager,this.productProcessManager])if(o?.getHandle(e.memberId)){o.kill(e.memberId),t=!0;break}n.id!==void 0&&this.sendResponse(n.id,{ok:t})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function fk(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=vd.join(H(),"agent-logs"),o=vd.join(t,`${e.agentId}.stderr.log`),r="";try{r=nk.readFileSync(o,"utf-8")}catch{}e.tail&&e.tail>0&&r&&(r=r.split(`
793
+ `).filter(Boolean).map(i=>({path:i.slice(3),status:i.slice(0,2).trim()}));n.id!==void 0&&this.sendResponse(n.id,{files:s})}catch{n.id!==void 0&&this.sendResponse(n.id,{files:[]})}}function Nb(n){let e=n.params,t;if(e?.projectId&&(t=Mn(e.projectId)??void 0),t||(t=this.getActiveProjectRoot()),!t){n.id!==void 0&&this.sendResponse(n.id,{instructions:[]});return}let o=[],r=Oo(t);try{let i=St.statSync(r);i.isFile()&&o.push({name:"INSTRUCTIONS.md",path:"INSTRUCTIONS.md",size:i.size})}catch{}let s=ci(t);if(s)for(let i of s.list())o.push({name:i.filename,path:`rules/${i.filename}`,size:i.sizeBytes});n.id!==void 0&&this.sendResponse(n.id,{instructions:o})}function $b(n){let e=n.params;if(!e?.path){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: path"});return}let t;if(e?.projectId&&(t=Mn(e.projectId)??void 0),t||(t=this.getActiveProjectRoot()),!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}if(e.path==="INSTRUCTIONS.md"){let i=Oo(t);try{let a=St.readFileSync(i,"utf8");this.sendResponse(n.id,{content:a,metadata:{filename:"INSTRUCTIONS.md",sizeBytes:Buffer.byteLength(a)}})}catch{this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Instruction file not found"})}return}let o=e.path.startsWith("rules/")?e.path.slice(6):e.path,r=ci(t);if(!r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}let s=r.read(o);if(!s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Instruction file not found"});return}n.id!==void 0&&this.sendResponse(n.id,{content:s.content,metadata:{filename:s.filename,sizeBytes:s.sizeBytes}})}function Ub(n){let e=n.params;if(!e?.path||typeof e?.content!="string"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required params: path, content"});return}let t=ci(this.getActiveProjectRoot());if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}try{t.write(e.path,e.content),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}function jb(n){let e=n.params;if(!e?.path){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: path"});return}let t=ci(this.getActiveProjectRoot());if(!t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"No active project workspace"});return}if(!t.remove(e.path)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Instruction file not found"});return}n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}function bd(n,e){let o=(typeof e=="string"&&e.trim()?e:typeof n.memoryUserId=="string"&&n.memoryUserId.trim()?n.memoryUserId:"").trim();return o||null}function BE(){return{records:[],stats:{formed:0,insights:0,preferences:0}}}async function Fb(n){let e=[];this.memdir&&e.push({id:"memdir",type:"file",path:Mc(this.getActiveProjectRoot())}),this.memoryProvider&&e.push({id:"local",type:"vector"}),n.id!==void 0&&this.sendResponse(n.id,{sources:e})}async function Bb(n){let e=n.params;if(this.ensureMemoryProvider?.(),!this.memoryProvider||typeof this.memoryProvider.list!="function"){n.id!==void 0&&this.sendResponse(n.id,{records:[],stats:{formed:0,insights:0,preferences:0}});return}try{let t=bd(this,e?.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,BE());return}let r=this.memoryProvider.list(t,{pageSize:e?.pageSize??500,activeOnly:!0}).map(a=>({id:a.id,text:a.text,category:a.category,importance:a.importance,confidence:a.confidence,source:a.source,sessionId:a.sessionId,eventDate:a.eventDate,tags:a.tags,createdAt:a.createdAt,updatedAt:a.updatedAt,accessCount:a.accessCount,lastAccessedAt:a.lastAccessedAt,isArchived:a.isArchived})),s=0,i=0;for(let a of r)a.category==="insight"||a.category==="lesson"?s++:a.category==="preference"&&i++;n.id!==void 0&&this.sendResponse(n.id,{records:r,stats:{formed:r.length,insights:s,preferences:i}})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async function Wb(n){let e=n.params;if(this.ensureMemoryProvider?.(),!this.memoryProvider||typeof this.memoryProvider.getActivitySummary!="function"){n.id!==void 0&&this.sendResponse(n.id,{dailyCounts:[],highlights:[]});return}try{let t=bd(this,e?.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{dailyCounts:[],highlights:[]});return}let o=this.memoryProvider.getActivitySummary(t,e?.days??180);n.id!==void 0&&this.sendResponse(n.id,o)}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async function Gb(n){let e=n.params,t=e?.source??"memdir",o=e?.target??"index";if(t==="memdir"||t==="local"){if(!this.memdir){n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:o,content:""});return}try{if(o==="index"){let r=this.memdir.getIndexRaw();n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:"index",content:r})}else{let r=await this.memdir.readFile(o);n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:o,content:r.content??""})}}catch{n.id!==void 0&&this.sendResponse(n.id,{source:"memdir",target:o,content:""})}}else n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown memory source: ${t}`})}async function Hb(n){let e=n.params,t=e?.target??"index",o=e?.content;if(o==null){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"content is required."});return}if(!this.memdir){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Memory system not initialized."});return}try{if(t==="index"){let r=await this.memdir.addToIndex(o);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,target:"index",message:r.message})}else{let r=await this.memdir.writeFile(t,o);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,target:t,message:r.message})}this.sendNotification("memory.updated",{target:t,source:"rpc"})}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}}async function Vb(n){let e=n.params;if(!e?.query){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"query is required."});return}if(this.memoryProvider){let t=bd(this,e.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{results:[]});return}try{let o=await this.memoryProvider.search(e.query,t,{limit:e.limit??10});n.id!==void 0&&this.sendResponse(n.id,{results:o.map(r=>({id:r.blockId??"",text:r.text,score:r.score,source:"local",metadata:r.metadata}))})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}}else if(this.memdir)try{let t=await this.memdir.searchLocal(e.query);n.id!==void 0&&this.sendResponse(n.id,{results:t.slice(0,e.limit??10).map((o,r)=>({id:`memdir-${r}`,text:o.snippet,score:o.score,source:"memdir",metadata:{file:o.file}}))})}catch{n.id!==void 0&&this.sendResponse(n.id,{results:[]})}else n.id!==void 0&&this.sendResponse(n.id,{results:[]})}async function Kb(n){let e=n.params;if(!e?.match){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"match is required."});return}let t=e.source??"memdir";if(t==="memdir"||t==="local"){if(!this.memdir){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"Memory system not initialized."});return}let o=e.target??"index";try{if(o==="index"){let r=await this.memdir.removeFromIndex(e.match);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,removedCount:r.ok?1:0,message:r.message}),r.ok&&this.sendNotification("memory.updated",{source:"memdir",target:"index"})}else{let r=await this.memdir.deleteFile(o);n.id!==void 0&&this.sendResponse(n.id,{ok:r.ok,removedCount:r.ok?1:0,message:r.message}),r.ok&&this.sendNotification("memory.updated",{source:"memdir",target:o})}}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}}else if(t==="vector"&&this.memoryProvider)try{await this.memoryProvider.remove(e.match),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,removedCount:1,message:"Removed from local memory."}),this.sendNotification("memory.updated",{source:"local"})}catch(o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})}else n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown or unavailable source: ${t}`})}le();mt();import*as en from"node:fs";import*as kd from"node:path";je();function zb(n){let e=n.params,o=Mt(e?.includeDeferred??!1).map(r=>({name:r.function.name,description:r.function.description??"",parameters:r.function.parameters,source:"builtin"}));if(e?.category){let r=o.filter(s=>s.name.startsWith(e.category)||s.description.toLowerCase().includes(e.category.toLowerCase()));n.id!==void 0&&this.sendResponse(n.id,{tools:r,total:r.length})}else n.id!==void 0&&this.sendResponse(n.id,{tools:o,total:o.length})}function qb(n){let e=X().listProviderDefs(),t=new Map;for(let r of e){let s=r.group??r.id;t.has(s)||t.set(s,[]);let i=!!X().resolveProviderApiKey(r.id);t.get(s).push({id:r.id,name:r.name,transport:r.transport,baseUrl:r.baseUrl,defaultModel:r.defaultModel,modelCount:r.models?.length??0,available:i})}let o=[...t.entries()].map(([r,s])=>({group:r,variants:s}));n.id!==void 0&&this.sendResponse(n.id,{providers:o})}function Yb(n){try{let t=X().exportConfig();n.id!==void 0&&this.sendResponse(n.id,{config:{providers:t.providers,models:t.models,bindings:t.bindings},paths:{userSettings:pt(),agentHome:H()}})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}var WE=new Set(["providers","models","bindings","provider","model","apiKey","baseUrl","providerKeys"]);async function Xb(n){let e=n.params;if(!e?.updates||typeof e.updates!="object"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"updates (object) is required."});return}let t=[],o={};for(let[r,s]of Object.entries(e.updates))WE.has(r)?t.push({key:r,reason:"Use settings.* RPC methods for model/key management"}):o[r]=s;if(t.length>0&&Object.keys(o).length===0){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Rejected keys: ${t.map(r=>r.key).join(", ")}. Use settings.* RPC for model management.`});return}try{let r=pt(),s={};try{let i=await en.promises.readFile(r,"utf-8");s=JSON.parse(i)}catch{}Object.assign(s,o),await en.promises.mkdir(kd.dirname(r),{recursive:!0}),await en.promises.writeFile(r,JSON.stringify(s,null,2),"utf-8"),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,applied:Object.keys(o),rejected:t})}catch(r){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)})}}function Jb(n){try{let e=ma(),t=pt(),o={};try{let r=en.readFileSync(t,"utf-8"),s=JSON.parse(r);s.tunables&&typeof s.tunables=="object"&&(o=s.tunables)}catch{}n.id!==void 0&&this.sendResponse(n.id,{defaults:e,overrides:o})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Qb(n){let e=n.params,t=e?.key,o=e?.value;if(!t||typeof t!="string"){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Missing required param: key (string)"});return}let r=ma();if(!(t in r)){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown tunable key: "${t}". Valid keys: ${Object.keys(r).join(", ")}`});return}let s=typeof r[t];if(o==null||typeof o!==s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:`Invalid value for "${t}": expected ${s}, got ${typeof o}`});return}try{let i=pt(),a={};try{let l=await en.promises.readFile(i,"utf-8");a=JSON.parse(l)}catch{}(!a.tunables||typeof a.tunables!="object")&&(a.tunables={}),a.tunables[t]=o,await en.promises.mkdir(kd.dirname(i),{recursive:!0}),await en.promises.writeFile(i,JSON.stringify(a,null,2),"utf-8"),t==="teamBudgetTokens"&&typeof o=="number"&&(we.teamBudget.budgetTokens=o),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,key:t,value:o})}catch(i){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:i instanceof Error?i.message:String(i)})}}async function Zb(n){let e=nt("task");if(!e){n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Bo([])});return}try{let r=(await e.execute("rpc-todos-list",{action:"list"},void 0)).details?.taskList??[];n.id!==void 0&&this.sendResponse(n.id,{items:r,summary:Bo(r)})}catch{n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Bo([])})}}function ek(n){let t=n.params?.lifecycle??"all",o=this.taskStore.getAllTasks(),r=t==="all"?o:o.filter(s=>s.lifecycle===t);n.id!==void 0&&this.sendResponse(n.id,{tasks:r.map(s=>({taskId:s.taskId,type:s.type,lifecycle:s.lifecycle,label:s.label}))})}function tk(n){let e=n.params;if(!e?.taskId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"taskId is required."});return}let o=this.taskStore.getAllTasks().find(r=>r.taskId===e.taskId);if(!o){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,message:`Task ${e.taskId} not found.`});return}if(o.lifecycle!=="running"&&o.lifecycle!=="pending"){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,message:`Task ${e.taskId} is already ${o.lifecycle}.`});return}this.taskStore.updateTask(e.taskId,r=>(r.lifecycle="cancelled",r)),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,message:`Task ${e.taskId} cancelled.`})}le();import*as nk from"node:fs";import*as vd from"node:path";async function ok(n){try{let e=n.params,t=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(t.getData());let o=this.acpDetector.scan(e?.force);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function rk(n){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let t=this.acpDetector.list();n.id!==void 0&&this.sendResponse(n.id,t)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function sk(n){try{let e=n.params;if(!e?.action||!e?.agent){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"action and agent are required."});return}let t=await this.ensureAgentConfigStore();switch(e.action){case"register":t.registerCustomAgent(e.agent);break;case"unregister":t.unregisterCustomAgent(e.agent.id);break;case"update":t.registerCustomAgent(e.agent);break}this.acpDetector.setConfigStore(t.getData()),this.acpDetector.clearCache(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function ik(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=await this.ensureAgentConfigStore(),{agentId:o,...r}=e;await t.setAgentConfig(o,r),this.acpDetector.setConfigStore(t.getData()),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function ak(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let o=(await this.ensureAgentConfigStore()).getAgentConfig(e.agentId);n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function lk(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=await this.ensureAgentConfigStore();await t.removeAgentConfig(e.agentId),this.acpDetector.setConfigStore(t.getData()),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function ck(n){try{let e=n.params;if(!e?.url){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"url is required."});return}await(await this.ensureAgentConfigStore()).setGatewayUrl(e.url),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function dk(n){try{let t=(await this.ensureAgentConfigStore()).getGatewayUrl();n.id!==void 0&&this.sendResponse(n.id,{url:t})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function uk(n){try{let t=(await this.ensureAgentConfigStore()).getData(),o=Object.entries(t.agents).map(([r,s])=>({agentId:r,hasApiKey:!!s.apiKey,hasBaseUrl:!!s.baseUrl,hasModel:!!s.model}));n.id!==void 0&&this.sendResponse(n.id,o)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function pk(n){try{let e=[],t=(o,r)=>{if(o)for(let s of o.getAllHandles())e.push({memberId:s.memberId,name:s.name,pid:s.pid,state:s.state,startedAt:s.startedAt,endedAt:s.endedAt,source:r})};t(this.soloProcessManager,"solo"),t(this.productProcessManager,"product"),n.id!==void 0&&this.sendResponse(n.id,e)}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function mk(n){try{let e=n.params;if(!e?.memberId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"memberId is required."});return}let t=!1;for(let o of[this.soloProcessManager,this.productProcessManager])if(o?.getHandle(e.memberId)){o.kill(e.memberId),t=!0;break}n.id!==void 0&&this.sendResponse(n.id,{ok:t})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function fk(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=vd.join(H(),"agent-logs"),o=vd.join(t,`${e.agentId}.stderr.log`),r="";try{r=nk.readFileSync(o,"utf-8")}catch{}e.tail&&e.tail>0&&r&&(r=r.split(`
794
794
  `).slice(-e.tail).join(`
795
795
  `)),n.id!==void 0&&this.sendResponse(n.id,{log:r})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function gk(n){try{let e=n.params;if(!e?.agentId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let t=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(t.getData());let r=this.acpDetector.list().find(i=>i.id===e.agentId);if(!r){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,error:`Agent ${e.agentId} not found`,durationMs:0});return}if(r.status==="not_installed"){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,error:`Agent ${e.agentId} is not installed`,durationMs:0});return}let s=Date.now();n.id!==void 0&&this.sendResponse(n.id,{ok:r.status==="available",version:r.version,capabilities:r.capabilities,error:r.status!=="available"?`Agent status: ${r.status}`:void 0,durationMs:Date.now()-s})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}an();mt();async function hk(n){try{if(!this.mediaClient){n.id!==void 0&&this.sendResponse(n.id,{models:[]});return}let e=await this.mediaClient.listModels();n.id!==void 0&&this.sendResponse(n.id,{models:e})}catch(e){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function yk(n){let e=n.params;if(!e?.taskId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"taskId is required."});return}try{if(!this.mediaClient||!Er(this.mediaClient)){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,message:"Media client does not support async cancel."});return}await this.mediaClient.cancel(e.taskId),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async function bk(n){let e=n.params;if(!e?.taskId){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"taskId is required."});return}try{if(!this.mediaClient||!Er(this.mediaClient)){n.id!==void 0&&this.sendResponse(n.id,{status:"unknown",message:"Media client does not support status queries."});return}let t=await this.mediaClient.queryStatus(e.taskId);n.id!==void 0&&this.sendResponse(n.id,t)}catch(t){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t instanceof Error?t.message:String(t)})}}async function kk(n){let e=n.params;if(!e?.audioBase64){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"audioBase64 is required."});return}let o=X().getActiveModel("stt");if(!o){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"STT not configured. Add an STT model and bind it in settings."});return}let{apiKey:r,model:s,baseUrl:i,keyHandle:a}=o;if(!i){a.release({success:!1}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:"STT baseUrl not configured. Set baseUrl on the STT model entry."});return}try{let l=`----STTBoundary${Date.now()}`,c=[];c.push(`--${l}\r
796
796
  Content-Disposition: form-data; name="model"\r
@@ -803,9 +803,9 @@ Content-Disposition: form-data; name="prompt"\r
803
803
  \r
804
804
  \u8BF7\u7528${e.language==="zh"?"\u4E2D\u6587":"\u82F1\u6587"}\u8F6C\u5F55`),c.push(`--${l}--`);let d=c.join(`\r
805
805
  `)+`\r
806
- `,u=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":`multipart/form-data; boundary=${l}`},body:d});if(!u.ok){let m=await u.text();a.release({success:!1,errorCode:u.status}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`STT API error (${u.status}): ${m.slice(0,200)}`});return}let p=await u.json();a.release({success:!0}),n.id!==void 0&&this.sendResponse(n.id,{text:p.text??"",model:p.model})}catch(l){a.release({success:!1}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:l instanceof Error?l.message:String(l)})}}mt();function BE(n){return n.length<=8?"****":`${n.slice(0,3)}***${n.slice(-4)}`}function ct(n,e,t,o=w.INTERNAL_ERROR){if(e.id!==void 0){if(typeof n.sendError=="function"){n.sendError(e.id,o,t);return}n.sendResponse(e.id,void 0,{code:o,message:t})}}function di(n,e){ct(n,e,Ls)}function WE(n){let e={};for(let t of n)for(let o of t.purposes)e[o]??=[],e[o].push(t);return e}async function Sd(){let n=X(),e=await tr(n);return n.save(),e}async function vk(n){try{let e=(await Ns()).map(t=>({id:t.id,displayName:$c(t),baseUrl:$s(t)??"",modelCount:t.models?.length??0}));n.id!==void 0&&this.sendResponse(n.id,{providers:e})}catch{di(this,n)}}async function Sk(n){let e=n.params;if(!e?.providerId||!e?.key){ct(this,n,"Required: providerId (string), key (string)",w.INVALID_PARAMS);return}let{providerId:t,key:o,label:r}=e;try{let s=await Uc(t);if(!s){ct(this,n,`Unknown provider: ${t}`,w.INVALID_PARAMS);return}let i=X();if(i.getProviderStatus(t)?.keys.some(c=>c.key===o)){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}i.addProvider(t,{baseUrl:$s(s)});let l=i.addKey(t,o,{label:r});await Sd();for(let c of Lo)if(!i.getBinding(c)){let d=i.listModels({purpose:c,provider:t,enabledOnly:!0});d.length>0&&i.setBinding(c,d[0].id)}i.setKeyHealth(l,"healthy"),i.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,keyId:l,providerId:t})}catch(s){let i=s instanceof Error?s.message:Ls;ct(this,n,i)}}function Tk(n){let e=n.params;if(!e?.keyId){ct(this,n,"Required: keyId (string)",w.INVALID_PARAMS);return}let t=X();t.removeKey(e.keyId),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}function wk(n){let e=n.params;if(!e?.keyId||typeof e.enabled!="boolean"){ct(this,n,"Required: keyId (string), enabled (boolean)",w.INVALID_PARAMS);return}let t=X();t.updateKey(e.keyId,{enabled:e.enabled}),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}function xk(n){let e=n.params;if(!e?.modelId||typeof e.enabled!="boolean"){ct(this,n,"Required: modelId (string), enabled (boolean)",w.INVALID_PARAMS);return}let t=X();e.enabled?t.enableModel(e.modelId):t.disableModel(e.modelId),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}async function Rk(n){let e=n.params;try{await Sd();let t=X(),o=new Set(t.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),r=t.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>t.hasConfiguredKeyForProviderVariant(s.provider));n.id!==void 0&&this.sendResponse(n.id,{models:r,grouped:WE(r),configuredProviderIds:[...o]})}catch{di(this,n)}}function _k(n){let e=n.params;if(!e?.purpose||!e?.modelId){ct(this,n,"Required: purpose (string), modelId (string)",w.INVALID_PARAMS);return}try{let t=X();t.setBinding(e.purpose,e.modelId),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){ct(this,n,t instanceof Error?t.message:String(t),w.INVALID_PARAMS)}}function Ak(n){let e=n.params;if(!e?.purpose){ct(this,n,"Required: purpose (string)",w.INVALID_PARAMS);return}let t=X(),o=t.getBinding(e.purpose);n.id!==void 0&&this.sendResponse(n.id,{model:o?{id:o.id,provider:o.provider,model:o.model,displayName:o.displayName,purposes:o.purposes,enabled:o.enabled}:null,available:t.isAvailable(e.purpose)})}async function Pk(n){try{let e=await Ns(),t=new Map(e.map(a=>[a.id,$c(a)]));await Sd();let o=X(),r=o.getAllProviderStatus().map(a=>({providerId:a.providerId,displayName:t.get(a.providerId)??a.providerId,baseUrl:a.baseUrl,keyCount:a.keys.length,healthyKeys:a.keys.filter(l=>l.healthStatus==="healthy"&&l.enabled).length,totalKeys:a.keys.length,keys:a.keys.map(l=>({id:l.id,label:l.label,maskedKey:BE(l.key),enabled:l.enabled,health:l.healthStatus}))})),s=o.getAllBindings(),i={};for(let a of Lo){let l=s[a];i[a]={bound:!!l,modelId:l?.id,modelName:l?.displayName,available:o.isAvailable(a)}}n.id!==void 0&&this.sendResponse(n.id,{providers:r,purposes:i})}catch{di(this,n)}}async function Ik(n){try{let e=X();e.load(),await tr(e),e.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,catalogRefreshed:!0})}catch{di(this,n)}}async function Ck(n){let e=n.params;if(!e?.providerId||!e?.apiKey){ct(this,n,"providerId and apiKey required",w.INVALID_PARAMS);return}try{let t=await Uc(e.providerId),o=e.baseUrl||(t?$s(t):void 0);if(!o){ct(this,n,`Unknown provider: ${e.providerId}`,w.INVALID_PARAMS);return}let r=`${o.replace(/\/$/,"")}/models`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(1e4)});if(s.ok){n.id!==void 0&&this.sendResponse(n.id,{valid:!0,status:s.status});return}let i=await s.text().catch(()=>"");n.id!==void 0&&this.sendResponse(n.id,{valid:!1,status:s.status,error:i.slice(0,500)})}catch(t){let o=t instanceof Error?t.message:String(t);n.id!==void 0&&this.sendResponse(n.id,{valid:!1,status:0,error:o})}}mr();Zs();od();ei();ti();function Td(n){let e=Ce.getNextAbility(n.level);return{level:n.level,experience:n.experience,xpNeeded:Ce.xpForLevel(n.level),abilities:Ce.getUnlockedAbilities(n.level).map(t=>t.name),nextAbility:e?{name:e.name,level:e.unlockedAtLevel}:void 0}}async function Ek(n){let e=n.params,t=this.getActiveProjectRoot(),o=new $t(t),r=o.load();if(r){this.sendNotification("pet.soul_ready",{name:r.name,species:r.species,personality:r.personality,catchphrase:r.catchphrase,stats:r.stats,rarity:r.rarity,breed:r.breed,breedColors:r.breedColors}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:r,growth:Td(r)});return}let s=this.deviceId??"default-user";try{let i=this.createPetSoulGenerator?.(),a=await o.hatch(s,i,e?.breed);this.sendNotification("pet.soul_ready",{name:a.name,species:a.species,personality:a.personality,catchphrase:a.catchphrase,stats:a.stats,rarity:a.rarity,breed:a.breed,breedColors:a.breedColors}),this.sendNotification("pet.growth",{level:a.level,experience:a.experience,xpNeeded:Ce.xpForLevel(a.level),abilities:Ce.getUnlockedAbilities(a.level).map(l=>l.name)}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:a,growth:Td(a)})}catch(i){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:i.message??"Failed to hatch pet"})}}async function Mk(n){let t=n.params?.action??"pat",o=this.getActiveProjectRoot(),r=new $t(o),s=r.load();if(!s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Pet not hatched yet"});return}let i=Ce.xpForEvent(`interact.${t}`),{newLevel:a,newXp:l,events:c,statBoosts:d}=Ce.processXpGain(s,i);s.level=a,s.experience=l;for(let[b,k]of Object.entries(d)){let x=b;s.stats[x]=Math.min(10,s.stats[x]+(k??0))}r.updateSoul(s),this.sendNotification("pet.state",{state:"happy"});let u=Ce.getUnlockedAbilities(a).map(b=>b.name),p=Ce.getNextAbility(a);this.sendNotification("pet.growth",{level:a,experience:l,xpNeeded:Ce.xpForLevel(a),abilities:u,nextAbility:p?{name:p.name,level:p.unlockedAtLevel}:void 0});for(let b of c)b.type==="molt"?this.sendNotification("pet.reaction",{text:`\u2728 \u8131\u58F3\u4E86\uFF01\u7B2C ${b.moltStage} \u6B21\u8715\u53D8`,style:"excited"}):b.type==="ability_unlock"&&b.ability&&this.sendNotification("pet.reaction",{text:`\u{1F389} \u89E3\u9501\u65B0\u80FD\u529B\uFF1A${b.ability.name}`,style:"excited"});let m=null,h="excited";try{let b=[],k=this.getActiveProjectRoot?.()??"";if(k){let $=k.split(/[\\/]/).pop()??k;b.push(`\u7528\u6237\u6B63\u5728\u9879\u76EE\u300C${$}\u300D\u4E2D\u5DE5\u4F5C`)}if(this.sessionState){let $=this.sessionState.turnCount??0;$>0&&b.push(`\u672C\u6B21\u4F1A\u8BDD\u5DF2\u8FDB\u884C\u4E86 ${$} \u8F6E\u5BF9\u8BDD`)}if(this.memoryProvider&&this.memoryUserId)try{let $=this.memoryProvider.getActivitySummary(this.memoryUserId,7);if($?.highlights?.length){let W=$.highlights.slice(0,3).map(S=>S.text);b.push(`\u7528\u6237\u8FD1\u671F\u8BB0\u5FC6\u4EAE\u70B9: ${W.join("\uFF1B")}`)}}catch{}let x=new Date().getHours(),I=x<6?"\u6DF1\u591C":x<9?"\u65E9\u6668":x<12?"\u4E0A\u5348":x<14?"\u4E2D\u5348":x<18?"\u4E0B\u5348":x<22?"\u665A\u4E0A":"\u6DF1\u591C";b.push(`\u5F53\u524D\u65F6\u6BB5: ${I}`);let P=t==="pat"?"\u7528\u6237\u6478\u4E86\u6478\u4F60":t==="feed"?"\u7528\u6237\u5582\u4E86\u4F60\u4E1C\u897F":`\u7528\u6237\u5BF9\u4F60\u505A\u4E86\u300C${t}\u300D`;b.push(P);let O=b.join("\u3002");if(this.createSmallLLMCall){let $=this.createSmallLLMCall();if($){let W=await Xs({turnSummary:O,soul:s},$);W&&(m=W.text,h=W.style)}}}catch{}if(!m){let b=Ys("session.created");m=b?.text??null,h=b?.style??"excited"}let f=[],y=new Date().getHours();y>=22||y<6?f.push({label:"\u5E2E\u6211\u6574\u7406\u4ECA\u5929\u7684\u8FDB\u5EA6",action:"summarize-today"}):this.sessionState?.turnCount&&this.sessionState.turnCount>5&&f.push({label:"\u7EE7\u7EED\u521A\u624D\u7684\u5BF9\u8BDD",action:"resume-session"}),t==="click"&&f.push({label:"\u6709\u4EC0\u4E48\u80FD\u5E2E\u4F60\u7684\uFF1F",action:"start-chat"}),m&&this.sendNotification("pet.reaction",{text:m,style:h,actions:f.length>0?f:void 0}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,action:t,level:a,experience:l,events:c.map(b=>({type:b.type,level:b.level})),reaction:m?{text:m,style:h,actions:f.length>0?f:void 0}:null})}async function Ok(n){let e=this.getActiveProjectRoot(),o=new $t(e).load();if(n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:o??null,growth:o?Td(o):null}),o){this.sendNotification("pet.soul_ready",{name:o.name,species:o.species,personality:o.personality,catchphrase:o.catchphrase,stats:o.stats,rarity:o.rarity,breed:o.breed,breedColors:o.breedColors});let r=Ce.getUnlockedAbilities(o.level).map(i=>i.name),s=Ce.getNextAbility(o.level);this.sendNotification("pet.growth",{level:o.level,experience:o.experience,xpNeeded:Ce.xpForLevel(o.level),abilities:r,nextAbility:s?{name:s.name,level:s.unlockedAtLevel}:void 0})}}async function Dk(n){let e=n.params;if(!e?.description&&!e?.imageBase64){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Provide description or imageBase64"});return}typeof this.ensureModelRegistryHydrated=="function"&&await this.ensureModelRegistryHydrated(),this.sendNotification("pet.state",{state:"building"}),this.sendNotification("pet.reaction",{text:"\u6B63\u5728\u5B75\u5316\u4F60\u7684\u4E13\u5C5E\u5BA0\u7269...",style:"thinking"});try{let t=e.description?.slice(0,10)??"\u81EA\u5B9A\u4E49\u5BA0\u7269",o=e.description??"";e.imageBase64&&(o=await this.forgeAnalyzeImage(e.imageBase64,e.description),this.sendNotification("pet.reaction",{text:"\u5206\u6790\u5B8C\u6210\uFF0C\u6B63\u5728\u751F\u6210\u9AA8\u67B6...",style:"thinking"}));let r=await this.forgeGenerateSkeleton(o),s=Zt(r),i=lo(s),a=0;for(;i.length>0&&a<2;){a++,this.sendNotification("pet.reaction",{text:`\u9AA8\u67B6\u7F3A\u5C11 ${i.join("\u3001")}\uFF0C\u91CD\u65B0\u751F\u6210 (${a}/${2})...`,style:"thinking",duration:3e3});let m=`\u4E0A\u6B21\u751F\u6210\u7F3A\u5C11\u4EE5\u4E0B\u90E8\u4F4D: ${i.join(", ")}\u3002\u8BF7\u786E\u4FDD\u6240\u6709 id \u5C5E\u6027\u90FD\u5B58\u5728\u3002`;r=await this.forgeGenerateSkeleton(o+`
806
+ `,u=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":`multipart/form-data; boundary=${l}`},body:d});if(!u.ok){let m=await u.text();a.release({success:!1,errorCode:u.status}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:`STT API error (${u.status}): ${m.slice(0,200)}`});return}let p=await u.json();a.release({success:!0}),n.id!==void 0&&this.sendResponse(n.id,{text:p.text??"",model:p.model})}catch(l){a.release({success:!1}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:l instanceof Error?l.message:String(l)})}}mt();function GE(n){return n.length<=8?"****":`${n.slice(0,3)}***${n.slice(-4)}`}function ct(n,e,t,o=w.INTERNAL_ERROR){if(e.id!==void 0){if(typeof n.sendError=="function"){n.sendError(e.id,o,t);return}n.sendResponse(e.id,void 0,{code:o,message:t})}}function di(n,e){ct(n,e,Ls)}function HE(n){let e={};for(let t of n)for(let o of t.purposes)e[o]??=[],e[o].push(t);return e}async function Sd(){let n=X(),e=await tr(n);return n.save(),e}async function vk(n){try{let e=(await Ns()).map(t=>({id:t.id,displayName:$c(t),baseUrl:$s(t)??"",modelCount:t.models?.length??0}));n.id!==void 0&&this.sendResponse(n.id,{providers:e})}catch{di(this,n)}}async function Sk(n){let e=n.params;if(!e?.providerId||!e?.key){ct(this,n,"Required: providerId (string), key (string)",w.INVALID_PARAMS);return}let{providerId:t,key:o,label:r}=e;try{let s=await Uc(t);if(!s){ct(this,n,`Unknown provider: ${t}`,w.INVALID_PARAMS);return}let i=X();if(i.getProviderStatus(t)?.keys.some(c=>c.key===o)){n.id!==void 0&&this.sendResponse(n.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}i.addProvider(t,{baseUrl:$s(s)});let l=i.addKey(t,o,{label:r});await Sd();for(let c of Lo)if(!i.getBinding(c)){let d=i.listModels({purpose:c,provider:t,enabledOnly:!0});d.length>0&&i.setBinding(c,d[0].id)}i.setKeyHealth(l,"healthy"),i.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,keyId:l,providerId:t})}catch(s){let i=s instanceof Error?s.message:Ls;ct(this,n,i)}}function Tk(n){let e=n.params;if(!e?.keyId){ct(this,n,"Required: keyId (string)",w.INVALID_PARAMS);return}let t=X();t.removeKey(e.keyId),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}function wk(n){let e=n.params;if(!e?.keyId||typeof e.enabled!="boolean"){ct(this,n,"Required: keyId (string), enabled (boolean)",w.INVALID_PARAMS);return}let t=X();t.updateKey(e.keyId,{enabled:e.enabled}),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}function xk(n){let e=n.params;if(!e?.modelId||typeof e.enabled!="boolean"){ct(this,n,"Required: modelId (string), enabled (boolean)",w.INVALID_PARAMS);return}let t=X();e.enabled?t.enableModel(e.modelId):t.disableModel(e.modelId),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}async function Rk(n){let e=n.params;try{await Sd();let t=X(),o=new Set(t.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),r=t.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>t.hasConfiguredKeyForProviderVariant(s.provider));n.id!==void 0&&this.sendResponse(n.id,{models:r,grouped:HE(r),configuredProviderIds:[...o]})}catch{di(this,n)}}function _k(n){let e=n.params;if(!e?.purpose||!e?.modelId){ct(this,n,"Required: purpose (string), modelId (string)",w.INVALID_PARAMS);return}try{let t=X();t.setBinding(e.purpose,e.modelId),t.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0})}catch(t){ct(this,n,t instanceof Error?t.message:String(t),w.INVALID_PARAMS)}}function Ak(n){let e=n.params;if(!e?.purpose){ct(this,n,"Required: purpose (string)",w.INVALID_PARAMS);return}let t=X(),o=t.getBinding(e.purpose);n.id!==void 0&&this.sendResponse(n.id,{model:o?{id:o.id,provider:o.provider,model:o.model,displayName:o.displayName,purposes:o.purposes,enabled:o.enabled}:null,available:t.isAvailable(e.purpose)})}async function Pk(n){try{let e=await Ns(),t=new Map(e.map(a=>[a.id,$c(a)]));await Sd();let o=X(),r=o.getAllProviderStatus().map(a=>({providerId:a.providerId,displayName:t.get(a.providerId)??a.providerId,baseUrl:a.baseUrl,keyCount:a.keys.length,healthyKeys:a.keys.filter(l=>l.healthStatus==="healthy"&&l.enabled).length,totalKeys:a.keys.length,keys:a.keys.map(l=>({id:l.id,label:l.label,maskedKey:GE(l.key),enabled:l.enabled,health:l.healthStatus}))})),s=o.getAllBindings(),i={};for(let a of Lo){let l=s[a];i[a]={bound:!!l,modelId:l?.id,modelName:l?.displayName,available:o.isAvailable(a)}}n.id!==void 0&&this.sendResponse(n.id,{providers:r,purposes:i})}catch{di(this,n)}}async function Ik(n){try{let e=X();e.load(),await tr(e),e.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,catalogRefreshed:!0})}catch{di(this,n)}}async function Ck(n){let e=n.params;if(!e?.providerId||!e?.apiKey){ct(this,n,"providerId and apiKey required",w.INVALID_PARAMS);return}try{let t=await Uc(e.providerId),o=e.baseUrl||(t?$s(t):void 0);if(!o){ct(this,n,`Unknown provider: ${e.providerId}`,w.INVALID_PARAMS);return}let r=`${o.replace(/\/$/,"")}/models`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(1e4)});if(s.ok){n.id!==void 0&&this.sendResponse(n.id,{valid:!0,status:s.status});return}let i=await s.text().catch(()=>"");n.id!==void 0&&this.sendResponse(n.id,{valid:!1,status:s.status,error:i.slice(0,500)})}catch(t){let o=t instanceof Error?t.message:String(t);n.id!==void 0&&this.sendResponse(n.id,{valid:!1,status:0,error:o})}}mr();Zs();od();ei();ti();function Td(n){let e=Ce.getNextAbility(n.level);return{level:n.level,experience:n.experience,xpNeeded:Ce.xpForLevel(n.level),abilities:Ce.getUnlockedAbilities(n.level).map(t=>t.name),nextAbility:e?{name:e.name,level:e.unlockedAtLevel}:void 0}}async function Ek(n){let e=n.params,t=this.getActiveProjectRoot(),o=new $t(t),r=o.load();if(r){this.sendNotification("pet.soul_ready",{name:r.name,species:r.species,personality:r.personality,catchphrase:r.catchphrase,stats:r.stats,rarity:r.rarity,breed:r.breed,breedColors:r.breedColors}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:r,growth:Td(r)});return}let s=this.deviceId??"default-user";try{let i=this.createPetSoulGenerator?.(),a=await o.hatch(s,i,e?.breed);this.sendNotification("pet.soul_ready",{name:a.name,species:a.species,personality:a.personality,catchphrase:a.catchphrase,stats:a.stats,rarity:a.rarity,breed:a.breed,breedColors:a.breedColors}),this.sendNotification("pet.growth",{level:a.level,experience:a.experience,xpNeeded:Ce.xpForLevel(a.level),abilities:Ce.getUnlockedAbilities(a.level).map(l=>l.name)}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:a,growth:Td(a)})}catch(i){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:i.message??"Failed to hatch pet"})}}async function Mk(n){let t=n.params?.action??"pat",o=this.getActiveProjectRoot(),r=new $t(o),s=r.load();if(!s){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Pet not hatched yet"});return}let i=Ce.xpForEvent(`interact.${t}`),{newLevel:a,newXp:l,events:c,statBoosts:d}=Ce.processXpGain(s,i);s.level=a,s.experience=l;for(let[b,k]of Object.entries(d)){let x=b;s.stats[x]=Math.min(10,s.stats[x]+(k??0))}r.updateSoul(s),this.sendNotification("pet.state",{state:"happy"});let u=Ce.getUnlockedAbilities(a).map(b=>b.name),p=Ce.getNextAbility(a);this.sendNotification("pet.growth",{level:a,experience:l,xpNeeded:Ce.xpForLevel(a),abilities:u,nextAbility:p?{name:p.name,level:p.unlockedAtLevel}:void 0});for(let b of c)b.type==="molt"?this.sendNotification("pet.reaction",{text:`\u2728 \u8131\u58F3\u4E86\uFF01\u7B2C ${b.moltStage} \u6B21\u8715\u53D8`,style:"excited"}):b.type==="ability_unlock"&&b.ability&&this.sendNotification("pet.reaction",{text:`\u{1F389} \u89E3\u9501\u65B0\u80FD\u529B\uFF1A${b.ability.name}`,style:"excited"});let m=null,h="excited";try{let b=[],k=this.getActiveProjectRoot?.()??"";if(k){let $=k.split(/[\\/]/).pop()??k;b.push(`\u7528\u6237\u6B63\u5728\u9879\u76EE\u300C${$}\u300D\u4E2D\u5DE5\u4F5C`)}if(this.sessionState){let $=this.sessionState.turnCount??0;$>0&&b.push(`\u672C\u6B21\u4F1A\u8BDD\u5DF2\u8FDB\u884C\u4E86 ${$} \u8F6E\u5BF9\u8BDD`)}if(this.memoryProvider&&this.memoryUserId)try{let $=this.memoryProvider.getActivitySummary(this.memoryUserId,7);if($?.highlights?.length){let W=$.highlights.slice(0,3).map(S=>S.text);b.push(`\u7528\u6237\u8FD1\u671F\u8BB0\u5FC6\u4EAE\u70B9: ${W.join("\uFF1B")}`)}}catch{}let x=new Date().getHours(),I=x<6?"\u6DF1\u591C":x<9?"\u65E9\u6668":x<12?"\u4E0A\u5348":x<14?"\u4E2D\u5348":x<18?"\u4E0B\u5348":x<22?"\u665A\u4E0A":"\u6DF1\u591C";b.push(`\u5F53\u524D\u65F6\u6BB5: ${I}`);let P=t==="pat"?"\u7528\u6237\u6478\u4E86\u6478\u4F60":t==="feed"?"\u7528\u6237\u5582\u4E86\u4F60\u4E1C\u897F":`\u7528\u6237\u5BF9\u4F60\u505A\u4E86\u300C${t}\u300D`;b.push(P);let O=b.join("\u3002");if(this.createSmallLLMCall){let $=this.createSmallLLMCall();if($){let W=await Xs({turnSummary:O,soul:s},$);W&&(m=W.text,h=W.style)}}}catch{}if(!m){let b=Ys("session.created");m=b?.text??null,h=b?.style??"excited"}let f=[],y=new Date().getHours();y>=22||y<6?f.push({label:"\u5E2E\u6211\u6574\u7406\u4ECA\u5929\u7684\u8FDB\u5EA6",action:"summarize-today"}):this.sessionState?.turnCount&&this.sessionState.turnCount>5&&f.push({label:"\u7EE7\u7EED\u521A\u624D\u7684\u5BF9\u8BDD",action:"resume-session"}),t==="click"&&f.push({label:"\u6709\u4EC0\u4E48\u80FD\u5E2E\u4F60\u7684\uFF1F",action:"start-chat"}),m&&this.sendNotification("pet.reaction",{text:m,style:h,actions:f.length>0?f:void 0}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,action:t,level:a,experience:l,events:c.map(b=>({type:b.type,level:b.level})),reaction:m?{text:m,style:h,actions:f.length>0?f:void 0}:null})}async function Ok(n){let e=this.getActiveProjectRoot(),o=new $t(e).load();if(n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:o??null,growth:o?Td(o):null}),o){this.sendNotification("pet.soul_ready",{name:o.name,species:o.species,personality:o.personality,catchphrase:o.catchphrase,stats:o.stats,rarity:o.rarity,breed:o.breed,breedColors:o.breedColors});let r=Ce.getUnlockedAbilities(o.level).map(i=>i.name),s=Ce.getNextAbility(o.level);this.sendNotification("pet.growth",{level:o.level,experience:o.experience,xpNeeded:Ce.xpForLevel(o.level),abilities:r,nextAbility:s?{name:s.name,level:s.unlockedAtLevel}:void 0})}}async function Dk(n){let e=n.params;if(!e?.description&&!e?.imageBase64){n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INVALID_PARAMS,message:"Provide description or imageBase64"});return}typeof this.ensureModelRegistryHydrated=="function"&&await this.ensureModelRegistryHydrated(),this.sendNotification("pet.state",{state:"building"}),this.sendNotification("pet.reaction",{text:"\u6B63\u5728\u5B75\u5316\u4F60\u7684\u4E13\u5C5E\u5BA0\u7269...",style:"thinking"});try{let t=e.description?.slice(0,10)??"\u81EA\u5B9A\u4E49\u5BA0\u7269",o=e.description??"";e.imageBase64&&(o=await this.forgeAnalyzeImage(e.imageBase64,e.description),this.sendNotification("pet.reaction",{text:"\u5206\u6790\u5B8C\u6210\uFF0C\u6B63\u5728\u751F\u6210\u9AA8\u67B6...",style:"thinking"}));let r=await this.forgeGenerateSkeleton(o),s=Zt(r),i=lo(s),a=0;for(;i.length>0&&a<2;){a++,this.sendNotification("pet.reaction",{text:`\u9AA8\u67B6\u7F3A\u5C11 ${i.join("\u3001")}\uFF0C\u91CD\u65B0\u751F\u6210 (${a}/${2})...`,style:"thinking",duration:3e3});let m=`\u4E0A\u6B21\u751F\u6210\u7F3A\u5C11\u4EE5\u4E0B\u90E8\u4F4D: ${i.join(", ")}\u3002\u8BF7\u786E\u4FDD\u6240\u6709 id \u5C5E\u6027\u90FD\u5B58\u5728\u3002`;r=await this.forgeGenerateSkeleton(o+`
807
807
 
808
- `+m),s=Zt(r),i=lo(s)}i.length>0&&this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u4E0D\u5B8C\u6574\uFF0C\u90E8\u5206\u52A8\u753B\u53EF\u80FD\u7F3A\u5931\uFF0C\u7EE7\u7EED\u751F\u6210...",style:"normal",duration:3e3}),this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u751F\u6210\u5B8C\u6210\uFF0C\u5F00\u59CB\u6E32\u67D3\u5404\u72B6\u6001...",style:"thinking"});let l=["idle","thinking","working","done","happy","error","sleeping","eating"],c={baseSvg:s,parts:so(s),colors:ao(s),characterDesc:o},d={};for(let m of l)d[m]=io(c,m),this.sendNotification("pet.reaction",{text:`\u6E32\u67D3 ${m} \u72B6\u6001... (${Object.keys(d).length}/${l.length})`,style:"thinking",duration:2e3});let u=ur(d.idle,d,{threshold:6});if(!u.passedAll&&u.retryStates.length>0&&(this.sendNotification("pet.reaction",{text:`\u4E00\u81F4\u6027\u68C0\u67E5\uFF1A${u.retryStates.length} \u4E2A\u72B6\u6001\u9700\u4F18\u5316...`,style:"thinking",duration:3e3}),u.overallScore<4)){let m=pr(o,"all","\u9AA8\u67B6\u7ED3\u6784\u4E0D\u5B8C\u6574\u5BFC\u81F4\u591A\u72B6\u6001\u4E00\u81F4\u6027\u5DEE",1);r=await this.forgeGenerateSkeleton(m);let h={baseSvg:Zt(r),parts:so(Zt(r)),colors:ao(Zt(r)),characterDesc:o};for(let f of l)d[f]=io(h,f)}let p={version:1,name:t,author:"user-generated",created:new Date().toISOString(),generator:"xiaozhi-pet-forge-v2-skeleton",source:{type:e.imageBase64?"image":"text",prompt:e.description},dimensions:{width:200,height:200},states:Object.fromEntries(l.map(m=>[m,{file:`states/${m}.svg`,loop:m!=="done"&&m!=="happy"&&m!=="eating",...m==="done"||m==="happy"?{duration:3e3}:m==="eating"?{duration:4e3}:{}}])),eyeTracking:{enabled:!0,pupils:[".left-eye .pupil",".right-eye .pupil"],maxOffset:3},colors:c.colors,consistency:{score:u.overallScore,method:"skeleton-parameterized"}};lr(p),this.sendNotification("pet.reaction",{text:`\u2705 \u5BA0\u7269\u300C${t}\u300D\u5DF2\u953B\u9020\u5B8C\u6210\uFF01\u4E00\u81F4\u6027\u8BC4\u5206 ${u.overallScore.toFixed(1)}/10`,style:"excited"}),this.sendNotification("pet.state",{state:"done"}),this.sendNotification("pet.forged",{name:t,svgs:d}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,manifest:p,svgs:d,status:"complete",consistency:{score:u.overallScore,passedAll:u.passedAll}})}catch(t){this.sendNotification("pet.state",{state:"error"}),this.sendNotification("pet.reaction",{text:"\u953B\u9020\u5931\u8D25\u4E86...",style:"normal"}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t.message??"Forge failed"})}}var HE=GE(import.meta.url);function VE(){for(let n of["../package.json","../../package.json"])try{return HE(n).version}catch{}return"0.0.0"}var KE=VE();function zE(n){let e=n.pathname.split("/").filter(Boolean),o=(e[e.length-1]??"").replace(/\.md$/i,"").replace(/[^a-zA-Z0-9_-]/g,"-");return/^(skill|readme|index|install|main)$/i.test(o)&&e.length>=2?e[e.length-2].replace(/[^a-zA-Z0-9_-]/g,"-"):o||""}var wd=class n{running=!1;activeTurn=null;turnDone=Promise.resolve();verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentHooks=null;mcpManager=null;mcpReady=Promise.resolve();pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new ss;mediaPersistence=new Us;memoryPrefetchState=Kt();memoryProvider=null;memoryUserId="";lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;acpDetector=new Is;agentConfigStore=null;soloEvaluator=null;productOrchestrator=null;productPlanner=null;soloProcessManager=null;productProcessManager=null;acpServer=null;acpSessionHistory=new Map;resumedSessionHistory=new Map;idleDreamTimer=null;modelRegistryHydration=null;constructor(e){this.verbose=e.verbose,this.registry=new sn,this.mediaClient=new Ro({registry:this.registry}),X().onChange(()=>{this.lastLlmConfigKey=""}),this.ensureModelRegistryHydrated().catch(()=>{});let t=Number(process.env.QLOGICAGENT_IDLE_DREAM_MS);t>0&&(we.dream.idleMinutes=t/6e4);let o=Number(process.env.QLOGICAGENT_DREAM_COOLDOWN_MS);o>=0&&(we.dream.cooldownMs=o),this.transport=e.transport??new $o({verbose:e.verbose}),this.taskStore.onTaskChange((r,s)=>{s&&this.sendNotification("task.updated",{taskId:r,type:s.type,lifecycle:s.lifecycle,label:s.label})}),ig({log:{info:r=>this.log(r),warn:r=>this.log(`[warn] ${r}`),error:r=>this.log(`[error] ${r}`),debug:r=>{e.verbose&&this.log(`[debug] ${r}`)}},onExecProgress:r=>{this.sendNotification("turn.exec_progress",{output:r.output,elapsedTimeSeconds:r.elapsedTimeSeconds,totalLines:r.totalLines,totalBytes:r.totalBytes})}})}getActiveProjectRoot(){let e=Ne();return e?.workspaceDir?e.workspaceDir:process.cwd()}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=X();e.load(),await tr(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let t=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${t}`),e})),this.modelRegistryHydration}setActiveWorkdir(e){e!==this.getActiveProjectRoot()&&(og(e),this.mediaPersistence.setProjectDir(e))}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),em().then(e=>{e.error?this.log(`[warmup] embedding model not available: ${e.error}`):e.modelDownloaded?this.log(`[warmup] embedding model downloaded (${e.dimensions}d)`):e.modelCached&&this.log(`[warmup] embedding model ready (cached, ${e.dimensions}d)`)}).catch(()=>{}),this.transport.onMessage(e=>{if(this.acpServer){if(Yc(e)||or(e)){this.acpServer.dispatchMessage(e);return}if(nr(e)){let t=e.method;if(t==="initialize"||t.startsWith("session/")||t.startsWith("x/")||t.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!qc(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{ch().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")}}methodHandlers=new Map([["initialize",e=>this.handleInitialize(e)],["agent.ping",e=>this.handlePing(e)],["thread.turn",e=>cy.call(this,e)],["memory.dream",e=>oi.call(this,e)],["agent.abort",e=>iy.call(this,e)],["tool.approval.response",e=>ay.call(this,e)],["thread.user_response",e=>ly.call(this,e)],["thread.list",e=>Dy.call(this,e)],["session.resume",e=>Hy.call(this,e)],["thread.create",e=>Oy.call(this,e)],["session.getInfo",e=>Vy.call(this,e)],["session.create",e=>Ly.call(this,e)],["session.resolve",e=>Ny.call(this,e)],["session.list",e=>$y.call(this,e)],["session.get",e=>Uy.call(this,e)],["session.getMessages",e=>jy.call(this,e)],["session.update",e=>Fy.call(this,e)],["session.delete",e=>By.call(this,e)],["session.deleteAll",e=>Wy.call(this,e)],["session.archive",e=>Gy.call(this,e)],["memory.list",e=>Fb.call(this,e)],["memory.atlas",e=>Bb.call(this,e)],["memory.activity",e=>Wb.call(this,e)],["memory.read",e=>Gb.call(this,e)],["memory.write",e=>Hb.call(this,e)],["memory.search",e=>Vb.call(this,e)],["memory.delete",e=>Kb.call(this,e)],["tools.list",e=>zb.call(this,e)],["media.listModels",e=>hk.call(this,e)],["media.cancel",e=>yk.call(this,e)],["media.status",e=>bk.call(this,e)],["media.stt",e=>kk.call(this,e)],["settings.listProviders",e=>vk.call(this,e)],["settings.addKey",e=>Sk.call(this,e)],["settings.removeKey",e=>Tk.call(this,e)],["settings.toggleKey",e=>wk.call(this,e)],["settings.toggleModel",e=>xk.call(this,e)],["settings.listModels",e=>Rk.call(this,e)],["settings.setActiveModel",e=>_k.call(this,e)],["settings.getActiveModel",e=>Ak.call(this,e)],["settings.getOverview",e=>Pk.call(this,e)],["settings.refreshModels",e=>Ik.call(this,e)],["settings.validateKey",e=>Ck.call(this,e)],["provider.list",e=>qb.call(this,e)],["config.get",e=>Yb.call(this,e)],["config.update",e=>Xb.call(this,e)],["config.tunables",e=>Jb.call(this,e)],["config.updateTunable",e=>Qb.call(this,e)],["todos.list",e=>Zb.call(this,e)],["tasks.list",e=>ek.call(this,e)],["tasks.cancel",e=>tk.call(this,e)],["agents.scan",e=>ok.call(this,e)],["agents.list",e=>rk.call(this,e)],["agents.config",e=>sk.call(this,e)],["agents.setConfig",e=>ik.call(this,e)],["agents.getConfig",e=>ak.call(this,e)],["agents.removeConfig",e=>lk.call(this,e)],["agents.setGateway",e=>ck.call(this,e)],["agents.getGateway",e=>dk.call(this,e)],["agents.processes",e=>pk.call(this,e)],["agents.kill",e=>mk.call(this,e)],["agents.listConfigured",e=>uk.call(this,e)],["agents.getLog",e=>fk.call(this,e)],["agents.testConnection",e=>gk.call(this,e)],["solo.start",e=>tb.call(this,e)],["solo.status",e=>nb.call(this,e)],["solo.cancel",e=>ob.call(this,e)],["solo.select",e=>rb.call(this,e)],["solo.list",e=>sb.call(this,e)],["solo.delete",e=>ib.call(this,e)],["solo.message",e=>ab.call(this,e)],["solo.evaluate",e=>lb.call(this,e)],["product.plan",e=>Sy.call(this,e)],["product.confirm",e=>Ty.call(this,e)],["product.message",e=>wy.call(this,e)],["product.create",e=>xy.call(this,e)],["product.resume",e=>Ry.call(this,e)],["product.pause",e=>_y.call(this,e)],["product.checkpoint",e=>Ay.call(this,e)],["product.status",e=>Py.call(this,e)],["product.list",e=>Iy.call(this,e)],["product.delete",e=>Cy.call(this,e)],["product.cancel",e=>Ey.call(this,e)],["product.rollback",e=>My.call(this,e)],["project.create",e=>vb.call(this,e)],["project.list",e=>Sb.call(this,e)],["project.delete",e=>Tb.call(this,e)],["project.purgeAll",e=>wb.call(this,e)],["project.rename",e=>xb.call(this,e)],["project.archive",e=>Rb.call(this,e)],["project.unarchive",e=>_b.call(this,e)],["project.update",e=>Pb.call(this,e)],["project.archiveByGroup",e=>Ab.call(this,e)],["session.switchProject",e=>Ky.call(this,e)],["session.focus",e=>qy.call(this,e)],["session.moveToProject",e=>Yy.call(this,e)],["session.getState",e=>zy.call(this,e)],["files.list",e=>Eb.call(this,e)],["files.create",e=>Mb.call(this,e)],["files.rename",e=>Ob.call(this,e)],["files.delete",e=>Db.call(this,e)],["files.gitStatus",e=>Lb.call(this,e)],["instructions.list",e=>Nb.call(this,e)],["instructions.read",e=>$b.call(this,e)],["instructions.write",e=>Ub.call(this,e)],["instructions.delete",e=>jb.call(this,e)],["skills.list",e=>db.call(this,e)],["skills.activate",e=>ub.call(this,e)],["skills.deactivate",e=>pb.call(this,e)],["skills.delete",e=>mb.call(this,e)],["skills.promote",e=>fb.call(this,e)],["skills.stats",e=>gb.call(this,e)],["skills.pin",e=>hb.call(this,e)],["skills.unpin",e=>yb.call(this,e)],["skills.curator",e=>bb.call(this,e)],["skills.lifecycle",e=>kb.call(this,e)],["pet.hatch",e=>Ek.call(this,e)],["pet.interact",e=>Mk.call(this,e)],["pet.status",e=>Ok.call(this,e)],["pet.forge",e=>Dk.call(this,e)],["pet.confirm_response",e=>this.handlePetConfirmResponse(e)]]);handleMessage(e){let t=this.methodHandlers.get(e.method);t?t(e):e.id!==void 0&&this.sendResponse(e.id,void 0,{code:w.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=no.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${o} agent=${no}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:w.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${o}, agent=${no}`});return}this.log(`[initialize] host=${r} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:no,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:Mt().map(l=>l.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","turn.ask_user","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...Ih]}}),this.ensureDefaultProject()}ensureDefaultProject(){let e=Ne();if(e)e.workspaceDir&&this.setActiveWorkdir(e.workspaceDir);else{let t=te.join(H(),"workspaces","default");Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0});let o=Gp(t);yd(t),this.setActiveWorkdir(t),this.sendNotification("project.created",{id:o.id,name:o.name,workspaceDir:o.workspaceDir,type:o.type})}this.ensureDefaultProjectDir();{let t=this.getActiveProjectRoot(),o=new Nt(t);o.ensureInitialized(),this.memdir=o}}ensureDefaultProjectDir(){let t=fe().find(o=>o.type==="default"&&o.status==="active");t&&(Y.existsSync(t.workspaceDir)||Y.mkdirSync(t.workspaceDir,{recursive:!0}))}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
808
+ `+m),s=Zt(r),i=lo(s)}i.length>0&&this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u4E0D\u5B8C\u6574\uFF0C\u90E8\u5206\u52A8\u753B\u53EF\u80FD\u7F3A\u5931\uFF0C\u7EE7\u7EED\u751F\u6210...",style:"normal",duration:3e3}),this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u751F\u6210\u5B8C\u6210\uFF0C\u5F00\u59CB\u6E32\u67D3\u5404\u72B6\u6001...",style:"thinking"});let l=["idle","thinking","working","done","happy","error","sleeping","eating"],c={baseSvg:s,parts:so(s),colors:ao(s),characterDesc:o},d={};for(let m of l)d[m]=io(c,m),this.sendNotification("pet.reaction",{text:`\u6E32\u67D3 ${m} \u72B6\u6001... (${Object.keys(d).length}/${l.length})`,style:"thinking",duration:2e3});let u=ur(d.idle,d,{threshold:6});if(!u.passedAll&&u.retryStates.length>0&&(this.sendNotification("pet.reaction",{text:`\u4E00\u81F4\u6027\u68C0\u67E5\uFF1A${u.retryStates.length} \u4E2A\u72B6\u6001\u9700\u4F18\u5316...`,style:"thinking",duration:3e3}),u.overallScore<4)){let m=pr(o,"all","\u9AA8\u67B6\u7ED3\u6784\u4E0D\u5B8C\u6574\u5BFC\u81F4\u591A\u72B6\u6001\u4E00\u81F4\u6027\u5DEE",1);r=await this.forgeGenerateSkeleton(m);let h={baseSvg:Zt(r),parts:so(Zt(r)),colors:ao(Zt(r)),characterDesc:o};for(let f of l)d[f]=io(h,f)}let p={version:1,name:t,author:"user-generated",created:new Date().toISOString(),generator:"xiaozhi-pet-forge-v2-skeleton",source:{type:e.imageBase64?"image":"text",prompt:e.description},dimensions:{width:200,height:200},states:Object.fromEntries(l.map(m=>[m,{file:`states/${m}.svg`,loop:m!=="done"&&m!=="happy"&&m!=="eating",...m==="done"||m==="happy"?{duration:3e3}:m==="eating"?{duration:4e3}:{}}])),eyeTracking:{enabled:!0,pupils:[".left-eye .pupil",".right-eye .pupil"],maxOffset:3},colors:c.colors,consistency:{score:u.overallScore,method:"skeleton-parameterized"}};lr(p),this.sendNotification("pet.reaction",{text:`\u2705 \u5BA0\u7269\u300C${t}\u300D\u5DF2\u953B\u9020\u5B8C\u6210\uFF01\u4E00\u81F4\u6027\u8BC4\u5206 ${u.overallScore.toFixed(1)}/10`,style:"excited"}),this.sendNotification("pet.state",{state:"done"}),this.sendNotification("pet.forged",{name:t,svgs:d}),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,manifest:p,svgs:d,status:"complete",consistency:{score:u.overallScore,passedAll:u.passedAll}})}catch(t){this.sendNotification("pet.state",{state:"error"}),this.sendNotification("pet.reaction",{text:"\u953B\u9020\u5931\u8D25\u4E86...",style:"normal"}),n.id!==void 0&&this.sendResponse(n.id,void 0,{code:w.INTERNAL_ERROR,message:t.message??"Forge failed"})}}var KE=VE(import.meta.url);function zE(){for(let n of["../package.json","../../package.json"])try{return KE(n).version}catch{}return"0.0.0"}var qE=zE();function YE(n){let e=n.pathname.split("/").filter(Boolean),o=(e[e.length-1]??"").replace(/\.md$/i,"").replace(/[^a-zA-Z0-9_-]/g,"-");return/^(skill|readme|index|install|main)$/i.test(o)&&e.length>=2?e[e.length-2].replace(/[^a-zA-Z0-9_-]/g,"-"):o||""}var wd=class n{running=!1;activeTurn=null;turnDone=Promise.resolve();verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentHooks=null;mcpManager=null;mcpReady=Promise.resolve();pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new ss;mediaPersistence=new Us;memoryPrefetchState=Kt();memoryProvider=null;memoryUserId="";lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;acpDetector=new Is;agentConfigStore=null;soloEvaluator=null;productOrchestrator=null;productPlanner=null;soloProcessManager=null;productProcessManager=null;acpServer=null;acpSessionHistory=new Map;resumedSessionHistory=new Map;idleDreamTimer=null;modelRegistryHydration=null;constructor(e){this.verbose=e.verbose,this.registry=new sn,this.mediaClient=new Ro({registry:this.registry}),X().onChange(()=>{this.lastLlmConfigKey=""}),this.ensureModelRegistryHydrated().catch(()=>{});let t=Number(process.env.QLOGICAGENT_IDLE_DREAM_MS);t>0&&(we.dream.idleMinutes=t/6e4);let o=Number(process.env.QLOGICAGENT_DREAM_COOLDOWN_MS);o>=0&&(we.dream.cooldownMs=o),this.transport=e.transport??new $o({verbose:e.verbose}),this.taskStore.onTaskChange((r,s)=>{s&&this.sendNotification("task.updated",{taskId:r,type:s.type,lifecycle:s.lifecycle,label:s.label})}),ig({log:{info:r=>this.log(r),warn:r=>this.log(`[warn] ${r}`),error:r=>this.log(`[error] ${r}`),debug:r=>{e.verbose&&this.log(`[debug] ${r}`)}},onExecProgress:r=>{this.sendNotification("turn.exec_progress",{output:r.output,elapsedTimeSeconds:r.elapsedTimeSeconds,totalLines:r.totalLines,totalBytes:r.totalBytes})}})}getActiveProjectRoot(){let e=Ne();return e?.workspaceDir?e.workspaceDir:process.cwd()}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=X();e.load(),await tr(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let t=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${t}`),e})),this.modelRegistryHydration}setActiveWorkdir(e){e!==this.getActiveProjectRoot()&&(og(e),this.mediaPersistence.setProjectDir(e))}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),em().then(e=>{e.error?this.log(`[warmup] embedding model not available: ${e.error}`):e.modelDownloaded?this.log(`[warmup] embedding model downloaded (${e.dimensions}d)`):e.modelCached&&this.log(`[warmup] embedding model ready (cached, ${e.dimensions}d)`)}).catch(()=>{}),this.transport.onMessage(e=>{if(this.acpServer){if(Yc(e)||or(e)){this.acpServer.dispatchMessage(e);return}if(nr(e)){let t=e.method;if(t==="initialize"||t.startsWith("session/")||t.startsWith("x/")||t.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!qc(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{ch().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")}}methodHandlers=new Map([["initialize",e=>this.handleInitialize(e)],["agent.ping",e=>this.handlePing(e)],["thread.turn",e=>cy.call(this,e)],["memory.dream",e=>oi.call(this,e)],["agent.abort",e=>iy.call(this,e)],["tool.approval.response",e=>ay.call(this,e)],["thread.user_response",e=>ly.call(this,e)],["thread.list",e=>Dy.call(this,e)],["session.resume",e=>Hy.call(this,e)],["thread.create",e=>Oy.call(this,e)],["session.getInfo",e=>Vy.call(this,e)],["session.create",e=>Ly.call(this,e)],["session.resolve",e=>Ny.call(this,e)],["session.list",e=>$y.call(this,e)],["session.get",e=>Uy.call(this,e)],["session.getMessages",e=>jy.call(this,e)],["session.update",e=>Fy.call(this,e)],["session.delete",e=>By.call(this,e)],["session.deleteAll",e=>Wy.call(this,e)],["session.archive",e=>Gy.call(this,e)],["memory.list",e=>Fb.call(this,e)],["memory.atlas",e=>Bb.call(this,e)],["memory.activity",e=>Wb.call(this,e)],["memory.read",e=>Gb.call(this,e)],["memory.write",e=>Hb.call(this,e)],["memory.search",e=>Vb.call(this,e)],["memory.delete",e=>Kb.call(this,e)],["tools.list",e=>zb.call(this,e)],["media.listModels",e=>hk.call(this,e)],["media.cancel",e=>yk.call(this,e)],["media.status",e=>bk.call(this,e)],["media.stt",e=>kk.call(this,e)],["settings.listProviders",e=>vk.call(this,e)],["settings.addKey",e=>Sk.call(this,e)],["settings.removeKey",e=>Tk.call(this,e)],["settings.toggleKey",e=>wk.call(this,e)],["settings.toggleModel",e=>xk.call(this,e)],["settings.listModels",e=>Rk.call(this,e)],["settings.setActiveModel",e=>_k.call(this,e)],["settings.getActiveModel",e=>Ak.call(this,e)],["settings.getOverview",e=>Pk.call(this,e)],["settings.refreshModels",e=>Ik.call(this,e)],["settings.validateKey",e=>Ck.call(this,e)],["provider.list",e=>qb.call(this,e)],["config.get",e=>Yb.call(this,e)],["config.update",e=>Xb.call(this,e)],["config.tunables",e=>Jb.call(this,e)],["config.updateTunable",e=>Qb.call(this,e)],["todos.list",e=>Zb.call(this,e)],["tasks.list",e=>ek.call(this,e)],["tasks.cancel",e=>tk.call(this,e)],["agents.scan",e=>ok.call(this,e)],["agents.list",e=>rk.call(this,e)],["agents.config",e=>sk.call(this,e)],["agents.setConfig",e=>ik.call(this,e)],["agents.getConfig",e=>ak.call(this,e)],["agents.removeConfig",e=>lk.call(this,e)],["agents.setGateway",e=>ck.call(this,e)],["agents.getGateway",e=>dk.call(this,e)],["agents.processes",e=>pk.call(this,e)],["agents.kill",e=>mk.call(this,e)],["agents.listConfigured",e=>uk.call(this,e)],["agents.getLog",e=>fk.call(this,e)],["agents.testConnection",e=>gk.call(this,e)],["solo.start",e=>tb.call(this,e)],["solo.status",e=>nb.call(this,e)],["solo.cancel",e=>ob.call(this,e)],["solo.select",e=>rb.call(this,e)],["solo.list",e=>sb.call(this,e)],["solo.delete",e=>ib.call(this,e)],["solo.message",e=>ab.call(this,e)],["solo.evaluate",e=>lb.call(this,e)],["product.plan",e=>Sy.call(this,e)],["product.confirm",e=>Ty.call(this,e)],["product.message",e=>wy.call(this,e)],["product.create",e=>xy.call(this,e)],["product.resume",e=>Ry.call(this,e)],["product.pause",e=>_y.call(this,e)],["product.checkpoint",e=>Ay.call(this,e)],["product.status",e=>Py.call(this,e)],["product.list",e=>Iy.call(this,e)],["product.delete",e=>Cy.call(this,e)],["product.cancel",e=>Ey.call(this,e)],["product.rollback",e=>My.call(this,e)],["project.create",e=>vb.call(this,e)],["project.list",e=>Sb.call(this,e)],["project.delete",e=>Tb.call(this,e)],["project.purgeAll",e=>wb.call(this,e)],["project.rename",e=>xb.call(this,e)],["project.archive",e=>Rb.call(this,e)],["project.unarchive",e=>_b.call(this,e)],["project.update",e=>Pb.call(this,e)],["project.archiveByGroup",e=>Ab.call(this,e)],["session.switchProject",e=>Ky.call(this,e)],["session.focus",e=>qy.call(this,e)],["session.moveToProject",e=>Yy.call(this,e)],["session.getState",e=>zy.call(this,e)],["files.list",e=>Eb.call(this,e)],["files.create",e=>Mb.call(this,e)],["files.rename",e=>Ob.call(this,e)],["files.delete",e=>Db.call(this,e)],["files.gitStatus",e=>Lb.call(this,e)],["instructions.list",e=>Nb.call(this,e)],["instructions.read",e=>$b.call(this,e)],["instructions.write",e=>Ub.call(this,e)],["instructions.delete",e=>jb.call(this,e)],["skills.list",e=>db.call(this,e)],["skills.activate",e=>ub.call(this,e)],["skills.deactivate",e=>pb.call(this,e)],["skills.delete",e=>mb.call(this,e)],["skills.promote",e=>fb.call(this,e)],["skills.stats",e=>gb.call(this,e)],["skills.pin",e=>hb.call(this,e)],["skills.unpin",e=>yb.call(this,e)],["skills.curator",e=>bb.call(this,e)],["skills.lifecycle",e=>kb.call(this,e)],["pet.hatch",e=>Ek.call(this,e)],["pet.interact",e=>Mk.call(this,e)],["pet.status",e=>Ok.call(this,e)],["pet.forge",e=>Dk.call(this,e)],["pet.confirm_response",e=>this.handlePetConfirmResponse(e)]]);handleMessage(e){let t=this.methodHandlers.get(e.method);t?t(e):e.id!==void 0&&this.sendResponse(e.id,void 0,{code:w.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=no.split(".")[0];if(i!==a){this.log(`[initialize] protocol mismatch: host=${o} agent=${no}`),e.id!==void 0&&this.sendResponse(e.id,void 0,{code:w.PROTOCOL_MISMATCH,message:`Protocol version mismatch: host=${o}, agent=${no}`});return}this.log(`[initialize] host=${r} v${s}`),e.id!==void 0&&this.sendResponse(e.id,{protocolVersion:no,agent:{name:"qlogicagent",version:"0.1.0"},capabilities:{tools:Mt().map(l=>l.function.name),streaming:!0,threads:!0,notifications:["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.plan_update","turn.suggestions","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.media_result","turn.todos_updated","task.updated","turn.exec_progress","turn.artifact","tool.approval.request","turn.skill_instruction","turn.ask_user","memory.updated","session.info","permission.rule_updated","team.updated","turn.usage_update","pong"],methods:[...Ih]}}),this.ensureDefaultProject()}ensureDefaultProject(){let e=Ne();if(e)e.workspaceDir&&this.setActiveWorkdir(e.workspaceDir);else{let t=te.join(H(),"workspaces","default");Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0});let o=Gp(t);yd(t),this.setActiveWorkdir(t),this.sendNotification("project.created",{id:o.id,name:o.name,workspaceDir:o.workspaceDir,type:o.type})}this.ensureDefaultProjectDir();{let t=this.getActiveProjectRoot(),o=new Nt(t);o.ensureInitialized(),this.memdir=o}}ensureDefaultProjectDir(){let t=fe().find(o=>o.type==="default"&&o.status==="active");t&&(Y.existsSync(t.workspaceDir)||Y.mkdirSync(t.workspaceDir,{recursive:!0}))}handlePing(e){e.id!==void 0&&this.sendResponse(e.id,{status:"ok"}),this.sendNotification("pong",{})}static SUGGESTION_PROMPT=`[SUGGESTION MODE]
809
809
  Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
810
810
  Be specific: "run the tests" beats "continue".
811
811
  Stay silent if the next step isn't obvious.
@@ -840,7 +840,7 @@ ${t?`\u7528\u6237\u8865\u5145\u63CF\u8FF0\uFF1A${t}`:""}
840
840
  `)}}catch(V){return{success:!1,error:V.message}}},listResources:async v=>{let _=this.mcpManager;return _?(await _.listResources(v)).map(R=>({uri:R.uri,name:R.name,mimeType:R.mimeType,description:R.description,server:R.server})):[]},readResource:async(v,_)=>{let C=this.mcpManager;if(!C)throw new Error("MCP not initialized");return(await C.readResource(v,_)).map(U=>({uri:U.uri,mimeType:U.mimeType,text:U.text}))},authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})),this.mcpReady=this.mcpManager.connectAll().then(()=>{this.mcpManager?.injectTools(),l.info(`[mcp] ${this.mcpManager?.getToolCount()??0} tools from ${this.mcpManager?.getConnectedServers().length??0} servers`)}).catch(v=>{l.warn(`[mcp] connection error: ${v instanceof Error?v.message:v}`)})}let y=[],b=ep();Y.existsSync(b)&&y.push(b);let k=e?.pluginPaths;if(Array.isArray(k))for(let g of k)typeof g=="string"&&Y.existsSync(g)&&y.push(g);pg(y,l).then(g=>{if(g.length===0)return;this.pluginLoader=new ws({pluginDirs:g,hookRegistry:d,log:l}),this.pluginLoader.loadAll().then(_=>{l.info(`[plugins] ${_.length} loaded, ${this.pluginLoader?.getPluginSkills().length??0} skills`)}).catch(_=>{l.warn(`[plugins] load error: ${_ instanceof Error?_.message:_}`)});let v=this.pluginLoader;d.register({point:"turn.submitted",handler:async()=>(await v.discoverNew(),await v.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(g=>{l.warn(`[plugins] marketplace resolve error: ${g instanceof Error?g.message:g}`)});let x=e?.permissions,I=Rs(x),P=new xs(I);if(I.mode,Ne()?.type==="group"){let g=Kf();for(let v of g)P.addRule(v);hc(!0),l.info(`[permissions] group security mode active: ${g.length} rules injected`)}else hc(!1);this.permissionUnregister&&this.permissionUnregister(),this.permissionChecker=new Ps({ruleEngine:P,hookRegistry:d,auditLogger:new As(this.getActiveProjectRoot()),sessionId:this.currentSessionId,getTurnId:()=>this.currentTurnId,onRequestApproval:async g=>{if(this.acpServer&&this.acpServer.sessionId)try{let v=await this.acpServer.requestPermission({sessionId:this.acpServer.sessionId,permissionId:g.approvalId,toolCall:{callId:g.callId,toolName:g.toolName,arguments:g.arguments?JSON.stringify(g.arguments):""},message:g.message,options:[{id:"allow",label:"Allow"},{id:"deny",label:"Deny"},{id:"allowAlways",label:"Always allow",persistent:!0}]});return{approvalId:g.approvalId,decision:v.optionId==="allow"||v.optionId==="allowAlways"?"approved":"denied"}}catch{return{approvalId:g.approvalId,decision:"denied"}}if(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(v=>`${v.pattern}:${v.behavior}`)}),this.isPetActive()){let v=g.toolName.match(/delete|rm|drop|reset|force/i)?"high":g.toolName.match(/write|exec|bash|shell|move/i)?"medium":"low";this.sendNotification("pet.confirm",{confirmId:g.approvalId,toolName:g.toolName,description:g.message??`\u5141\u8BB8\u6267\u884C ${g.toolName}\uFF1F`,risk:v,timeoutMs:3e4})}return 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,v)=>{l.warn(`[permissions] blocked "${g}": ${v}`)}});let $=Mt();this.permissionChecker.setToolMeta($),this.permissionUnregister=this.permissionChecker.register();let W=It(this.getActiveProjectRoot()),S=[W,Ht(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];Pe(xg({listSkills:()=>{let g=[];this.pluginLoader&&g.push(...this.pluginLoader.getPluginSkills());let v=e?.skillPaths;if(Array.isArray(v)){for(let _ of v)if(typeof _=="string"){let C=te.basename(_);g.some(R=>R.name===C)||g.push({name:C,source:"gateway",filePath:te.join(_,"SKILL.md"),baseDir:_})}}return g},listSkillsFull:async g=>{let v=[],_=new Set,C=Ht();for(let R of S)try{let U=await Y.promises.readdir(R,{withFileTypes:!0});for(let D of U){if(!D.isDirectory())continue;let M=te.join(R,D.name,"SKILL.md");try{let V=await Y.promises.readFile(M,"utf8"),ae=te.basename(R);if(g&&ae!==g)continue;_.add(ae);let ee=R===C?"global":R===W?"project":"config",me=V.match(/^---\n[\s\S]*?^version:\s*(\S+)/m)?.[1],Ge=V.startsWith(`---
841
841
  `)?V.indexOf("---",4):-1,ge=(Ge>=0?V.slice(Ge+3).trimStart():V).split(`
842
842
  `).find(jt=>jt.trim()&&!jt.startsWith("#"))?.trim()??`Skill from ${ae}`;v.push({name:D.name,description:ge,category:ae,scope:ee,version:me})}catch{}}}catch{}if(this.pluginLoader)for(let R of this.pluginLoader.getPluginSkills())g&&R.source!==g||(_.add(R.source??"plugin"),v.push({name:R.name,description:`Plugin skill (${R.source})`,category:R.source,scope:"plugin"}));return{skills:v,categories:[..._]}},readSkillContent:async g=>{for(let v of S){let _=te.join(v,g,"SKILL.md");try{return await Y.promises.readFile(_,"utf8")}catch{}}return null},viewSkill:async(g,v)=>{for(let _ of S){let C=v?te.join(_,g,v):te.join(_,g,"SKILL.md");try{let R=await Y.promises.readFile(C,"utf8");return{name:g,content:R}}catch{}}return null},executeSkillSubturn:async(g,v,_,C)=>{let R=`skill_${g}_${wt().slice(0,8)}`,U=this.agent;if(!U)return"[skill] Cannot execute: no LLM provider configured";let D=H(),M=this.currentSessionId??"skill";this.currentHooks?.invoke("subagent.started",{sessionId:M,turnId:R,subagentId:R,agentType:`skill:${g}`}).catch(()=>{});let V=new Set(["skill","agent"]),ae=Mt().filter(Me=>!V.has(Me.function.name)),ee=_??`Execute skill "${g}" instructions.`,oe=[],me;for await(let Me of U.run({turnId:R,sessionId:M,messages:[{role:"user",content:ee}],tools:ae,systemPrompt:v,config:{parentDepth:1,maxRounds:5}},C)){if(Me.type==="end"&&Me.content){this.currentHooks?.invoke("subagent.stopped",{sessionId:M,turnId:R,subagentId:R,agentType:`skill:${g}`,reason:"normal"}).catch(()=>{}),js(D,g,!0);let tn=We(D);return Gc(tn,g),Ve(D,tn),Me.content}if(Me.type==="delta"&&Me.text&&oe.push(Me.text),Me.type==="error"){me=Me.error;break}}if(this.currentHooks?.invoke("subagent.stopped",{sessionId:M,turnId:R,subagentId:R,agentType:`skill:${g}`,reason:me?"error":"normal",error:me}).catch(()=>{}),me)return js(D,g,!1),`[skill "${g}"] error: ${me}`;js(D,g,!0);let Ge=We(D);return Gc(Ge,g),Ve(D,Ge),oe.join("")||`[skill "${g}"] completed (no output)`},manageSkill:async g=>{let v=this.getActiveProjectRoot(),_=It(v),C=te.join(_,g.name),R=te.join(C,"SKILL.md"),U=H();switch(g.action){case"create":{let D=g.content??"",V=zc(D,g.name,`Skill: ${g.name}`)??D,ae=Ws(V,g.name);if(!ae.valid)return{success:!1,message:`Skill validation failed: ${ae.errors.join("; ")}`};let ee=We(U);if(ee.records[g.name]?.pinned&&Y.existsSync(R))return{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`};if(await Y.promises.mkdir(C,{recursive:!0}),await Y.promises.writeFile(R,V,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",content:V,scope:"project"}}),gt(),Qt(ee,g.name,"created"),Ve(U,ee),this.memoryProvider&&this.memoryUserId){let me=V.split(`
843
- `).slice(0,3).join(" ").slice(0,200),Ge=v?te.basename(v):"unknown";this.memoryProvider.ingestExtracted([{text:`Learned skill "${g.name}" in project "${Ge}": ${me}`,category:"skill-learning"}],this.memoryUserId).catch(()=>{})}let oe=v?` (project-scoped). To make it available across all projects, use: skill promote name:"${g.name}"`:"";return{success:!0,message:`Skill "${g.name}" created${oe}`,path:C}}case"edit":{let D=We(U);if(D.records[g.name]?.pinned)return{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`};let M=g.content??"",ae=zc(M,g.name)??M;return await Y.promises.writeFile(R,ae,"utf8"),Hc(D,g.name),Ve(U,D),this.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",content:ae,scope:"project"}}),{success:!0,message:`Skill "${g.name}" updated`,path:R}}case"patch":{let D=We(U);if(D.records[g.name]?.pinned)return{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`};let M=await Y.promises.readFile(R,"utf8");if(!g.oldString||!M.includes(g.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let V=M.replace(g.oldString,g.newString??"");return await Y.promises.writeFile(R,V,"utf8"),Hc(D,g.name),Ve(U,D),this.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",content:V,scope:"project"}}),{success:!0,message:`Skill "${g.name}" patched`,path:R}}case"delete":{let D=We(U);return D.records[g.name]?.pinned?{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`}:(await Y.promises.rm(C,{recursive:!0,force:!0}),Fs(D,g.name),Ve(U,D),this.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",action:"delete",scope:"project"}}),gt(),{success:!0,message:`Skill "${g.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${g.action}`}}},promoteSkill:async g=>{let v=It(this.getActiveProjectRoot()),_=te.join(v,g,"SKILL.md");try{await Y.promises.access(_)}catch{return{success:!1,message:`Skill "${g}" not found in project skills. Cannot promote.`}}let C=Ht(),R=te.join(C,g);await Y.promises.mkdir(R,{recursive:!0});let U=te.join(v,g),D=await Y.promises.readdir(U);for(let M of D){let V=await Y.promises.readFile(te.join(U,M));await Y.promises.writeFile(te.join(R,M),V)}return this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:g,category:"promoted",content:await Y.promises.readFile(_,"utf8"),scope:"global"}}),await Y.promises.rm(U,{recursive:!0,force:!0}),this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-cleanup-${Date.now()}`,instruction:{name:g,category:"learned",action:"delete",scope:"project"}}),gt(),{success:!0,message:`Skill "${g}" promoted to global (user-level) and removed from project scope. It will now be available across all projects.`,path:R}},installSkill:async(g,v)=>{let _;try{if(_=new URL(g),!["http:","https:"].includes(_.protocol))return{success:!1,message:`Invalid URL scheme: ${_.protocol}. Only http/https allowed.`}}catch{return{success:!1,message:`Invalid URL: ${g}`}}let C=v??zE(_);if(!C)return{success:!1,message:"Cannot derive skill name from URL. Please provide 'name' parameter."};try{let R=await fetch(g,{signal:AbortSignal.timeout(3e4)});if(!R.ok)return{success:!1,message:`Download failed: HTTP ${R.status} ${R.statusText}`};let U=R.headers.get("content-length");if(U&&parseInt(U,10)>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};let D=await R.text();if(!D.trim())return{success:!1,message:"Downloaded content is empty."};if(D.length>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};if(D.trimStart().startsWith("<!DOCTYPE")||D.trimStart().startsWith("<html"))return{success:!1,message:"URL returned an HTML page, not a raw markdown file. Use a raw/direct download link."};let M=Ht(),V=te.join(M,C);return await Y.promises.mkdir(V,{recursive:!0}),await Y.promises.writeFile(te.join(V,"SKILL.md"),D,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-install-${Date.now()}`,instruction:{name:C,category:"installed",content:D,scope:"global"}}),gt(),{success:!0,message:`Skill "${C}" installed from ${_.host}. Available globally across all projects.`,path:V}}catch(R){return{success:!1,message:`Install failed: ${R instanceof Error?R.message:String(R)}`}}}})),Pe(Ag({abortSignal:void 0,currentForkDepth:0,forkAgent:async g=>{let v=Cr(g.agent);if(!v)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 _=cn(),C=Ra(_,v),U=Mt().filter(oe=>C.includes(oe.function.name)),D=Il(U,!0),M=g.maxTurns??v.maxTurns??200;if(we.isTeamBudgetExceeded())return{agentId:`fork-${g.agent}-budget-exceeded`,status:"failed",output:void 0,error:we.teamBudgetExceededError(),tokensUsed:0};let V=await Dc({promptMessages:[{role:"user",content:g.prompt}],tools:D,transport:this.currentTransport,toolInvoker:c,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:d,forkLabel:`agent-${g.agent}`,maxTurns:M,parentSignal:g.abortSignal,parentDepth:0,onEvent:oe=>{oe.type==="delta"&&oe.text&&this.sendNotification("turn.subagent_delta",{agentType:g.agent,text:oe.text})}}),ae=V.events.filter(oe=>oe.type==="end"&&"content"in oe).map(oe=>oe.content??"").join("")||V.events.filter(oe=>oe.type==="delta"&&"text"in oe).map(oe=>oe.text).join(""),ee=V.totalUsage.inputTokens+V.totalUsage.outputTokens;return we.recordForkTokens(ee),{agentId:`fork-${g.agent}-${wt().slice(0,8)}`,status:V.ok?"completed":"failed",output:ae||void 0,error:V.error,tokensUsed:ee}}}));let ce=pt(),de=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 Y.promises.readFile(ce,"utf8"))}catch{return{}}},ve=async g=>{await Y.promises.mkdir(te.dirname(ce),{recursive:!0}),await Y.promises.writeFile(ce,JSON.stringify(g,null,2),"utf8")};Pe(Pg({getConfig:async g=>{let v=de.get(g);if(!v)return{success:!1,error:`Unknown key: ${g}`};let _=await j(),C=g in _?_[g]:v.value;return{success:!0,setting:{...v,value:C,readOnly:Jo.includes(g)}}},setConfig:async(g,v)=>{let _=de.get(g);if(!_)return{success:!1,error:`Unknown key: ${g}`};let C=await j(),R=g in C?C[g]:_.value;return C[g]=v,await ve(C),{success:!0,previousValue:R,setting:{..._,value:v}}},listConfig:async()=>{let g=await j();return{success:!0,settings:[...de.values()].map(_=>({..._,value:_.key in g?g[_.key]:_.value,readOnly:Jo.includes(_.key)}))}},resetConfig:async g=>{let v=de.get(g);if(!v)return{success:!1,error:`Unknown key: ${g}`};let _=await j();return delete _[g],await ve(_),{success:!0,setting:v}},isValidKey:g=>de.has(g)}));let ie=new Map,Ue=g=>{let v=/^(\d+)([smhd])$/.exec(g.trim());if(!v)return null;let _=parseInt(v[1],10),C=v[2];return _*({s:1e3,m:6e4,h:36e5,d:864e5}[C]??6e4)},ne=g=>{g.timerId&&clearTimeout(g.timerId);let v=Ue(g.schedule);if(!v)return;let _=Date.now(),C=v-_%v||v;g.timerId=setTimeout(()=>{g.lastRunAt=new Date().toISOString(),g.repeat.completed++,g.lastStatus="success",l.info(`[cron] triggered job ${g.id} (${g.name})`),this.sendNotification("system.activity",{category:"cron",level:"info",title:`\u5B9A\u65F6\u4EFB\u52A1\u89E6\u53D1: ${g.name}`,detail:`\u8C03\u5EA6 ${g.scheduleDisplay}\uFF0C\u7B2C ${g.repeat.completed} \u6B21\u6267\u884C`}),g.repeat.times===null||g.repeat.completed<g.repeat.times?ne(g):(g.state="paused",g.enabled=!1,this.sendNotification("system.activity",{category:"cron",level:"info",title:`\u5B9A\u65F6\u4EFB\u52A1\u5B8C\u6210: ${g.name}`,detail:`\u5DF2\u8FBE\u5230\u6700\u5927\u6267\u884C\u6B21\u6570 (${g.repeat.completed}\u6B21)`}))},C),g.nextRunAt=new Date(_+C).toISOString()};Pn(async()=>{for(let g of ie.values())g.timerId&&clearTimeout(g.timerId)}),Pe(Cg({createJob:async g=>{let v=`cron_${wt().slice(0,8)}`,_={id:v,name:g.name??`Job ${v}`,prompt:g.prompt,schedule:g.schedule,scheduleDisplay:g.schedule,state:"scheduled",enabled:!0,repeat:{times:g.repeat??null,completed:0},allowedTools:g.allowedTools};return ie.set(v,_),ne(_),{success:!0,job:{..._,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...ie.values()].map(v=>({...v,timerId:void 0}))}),getJob:async g=>{let v=ie.get(g);return v?{success:!0,job:{...v,timerId:void 0}}:{success:!1,error:`Job not found: ${g}`}},updateJob:async(g,v)=>{let _=ie.get(g);return _?(v.prompt!==void 0&&(_.prompt=v.prompt),v.schedule!==void 0&&(_.schedule=v.schedule,_.scheduleDisplay=v.schedule),v.name!==void 0&&(_.name=v.name),v.enabled!==void 0&&(_.enabled=v.enabled,_.state=v.enabled?"scheduled":"paused"),v.repeat!==void 0&&(_.repeat.times=v.repeat),v.allowedTools!==void 0&&(_.allowedTools=v.allowedTools),_.enabled?ne(_):_.timerId&&(clearTimeout(_.timerId),_.timerId=void 0),{success:!0,job:{..._,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},deleteJob:async g=>{let v=ie.get(g);return v?(v.timerId&&clearTimeout(v.timerId),ie.delete(g),{success:!0}):{success:!1,error:`Job not found: ${g}`}},pauseJob:async g=>{let v=ie.get(g);return v?(v.state="paused",v.enabled=!1,v.timerId&&(clearTimeout(v.timerId),v.timerId=void 0),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},resumeJob:async g=>{let v=ie.get(g);return v?(v.state="scheduled",v.enabled=!0,ne(v),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},triggerJob:async g=>{let v=ie.get(g);return v?(v.lastRunAt=new Date().toISOString(),v.repeat.completed++,v.lastStatus="success",{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},validateSchedule:g=>Ue(g)!==null||/^\d{1,2}\s/.test(g)?null:`Invalid schedule: ${g}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let Q=new Map;Pn(async()=>{for(let g of Q.values())g.cleanup();Q.clear()}),Pe(Eg({startMonitor:async g=>{if(Q.has(g.monitorId))return{action:"start",success:!1,error:`Monitor "${g.monitorId}" already exists.`};let v={monitorId:g.monitorId,source:g.source,target:g.target,conditions:g.conditions,startedAt:Date.now(),timeoutSeconds:g.timeoutSeconds,eventCount:0},_=()=>{};if(g.source==="file")try{let C=Y.watch(g.target,{persistent:!1},()=>{v.eventCount++,l.info(`[monitor] file change detected: ${g.target}`)});_=()=>C.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${g.target}`}}if(g.timeoutSeconds>0){let C=setTimeout(()=>{let U=Q.get(g.monitorId);U&&(U.cleanup(),Q.delete(g.monitorId))},g.timeoutSeconds*1e3),R=_;_=()=>{clearTimeout(C),R()}}return Q.set(g.monitorId,{info:v,cleanup:_}),{action:"start",success:!0,monitorId:g.monitorId}},stopMonitor:async g=>{let v=Q.get(g);return v?(v.cleanup(),Q.delete(g),{action:"stop",success:!0,monitorId:g}):{action:"stop",success:!1,error:`Monitor "${g}" not found.`}},listMonitors:async()=>[...Q.values()].map(g=>g.info)}));let T=new Map,F={info:g=>l.info(g),warn:g=>l.warn(g)},B=new pn({onNotification:(g,v,_)=>{this.sendNotification("team.member.notification",{memberId:g,method:v,params:_})},onStateChange:(g,v)=>{this.sendNotification("team.member.state",{memberId:g,state:v});let _=B.getHandle(g),R=B.getUsageTracker(g)?.getUsage();this.emitAgentStatus(g,v,{missedBeats:B.getMissedBeats(g),lastActivityAt:_?.lastActivityAt,usage:R&&R.totalTokens>0?{inputTokens:R.inputTokens,outputTokens:R.outputTokens,totalTokens:R.totalTokens}:void 0})},onExit:(g,v,_)=>{for(let C of T.values()){let R=C.members.find(U=>U.cwd&&`team-${C.name}-${U.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()===g.replace(/^team-/,""));R&&(R.isActive=!1)}l.info(`[team] member ${g} exited (code=${v}, signal=${_})`)},onMcpToolCall:(g,v,_)=>this.handleMcpToolCall(g,v,_),log:{info:g=>l.info(g),warn:g=>l.warn(g),debug:g=>l.debug(g)},sessionDir:te.join(H(),"agent-logs")});Pn(async()=>{B.dispose()}),Pe(Mg({createTeam:async g=>{if(T.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let v=await Ho(),_=[];for(let R of g.members??[]){let U={...R,isActive:!0};if(v){let D=`team-${g.teamName}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),M=await hf(v,D,F);M?(U.worktreePath=M.worktreePath,U.worktreeBranch=M.branch,U.cwd=M.worktreePath,l.info(`[team] provisioned worktree for ${R.name}: ${M.worktreePath}`)):(U.cwd=process.cwd(),l.warn(`[team] worktree provision failed for ${R.name}, using shared cwd`))}else U.cwd=process.cwd();_.push(U)}let C={name:g.teamName,description:g.description,leadId:this.currentSessionId??"default",members:_,createdAt:new Date().toISOString()};T.set(g.teamName,C);for(let R of _){if(!R.cwd)continue;let U=`team-${g.teamName}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();try{await B.spawn({memberId:U,name:R.name,cwd:R.cwd,prompt:`You are the "${R.name}" team member. Role: ${R.role}.`,agentType:R.role,verbose:this.verbose}),l.info(`[team] spawned child process for ${R.name} in ${R.cwd}`)}catch(D){l.warn(`[team] failed to spawn child process for ${R.name}: ${D instanceof Error?D.message:String(D)}`),R.isActive=!1}}return this.sendNotification("team.updated",{teamName:g.teamName,action:"created",members:C.members.map(R=>({agentName:R.name,role:R.role,worktreePath:R.worktreePath,pid:B.getHandle(`team-${g.teamName}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase())?.pid}))}),{success:!0,team:C}},deleteTeam:async g=>{let v=T.get(g);if(!v)return{success:!1,error:`Team "${g}" not found.`};for(let C of v.members){let R=`team-${g}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();B.kill(R),B.remove(R)}let _=await Ho();if(_)for(let C of v.members)C.worktreePath&&C.worktreeBranch&&(await yf(_,C.worktreePath,C.worktreeBranch,F),l.info(`[team] cleaned up worktree for ${C.name}: ${C.worktreePath}`));return T.delete(g),this.sendNotification("team.updated",{teamName:g,action:"destroyed",members:[]}),{success:!0}},listTeams:async()=>({success:!0,teams:[...T.values()]}),getTeamStatus:async g=>{let v=T.get(g);if(!v)return{success:!1,error:`Team "${g}" not found.`};let _={};for(let C of v.members){let R=`team-${g}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),U=B.getStatus(R);U&&(C.isActive=U.alive,_[C.name]={mediaProgress:U.mediaProgress,lastToolCall:U.lastToolCall,idleFor:U.idleFor,runningFor:U.runningFor})}return{success:!0,team:v,memberProgress:_}}}));{let g=this.memdir;Pe({name:Yg,label:Xg,description:Qg,parameters:Jg,execute:async(v,_)=>{let C=await Zg(_,{memdir:g,provider:this.memoryUserId?this.memoryProvider??void 0:void 0,localProvider:this.memoryUserId?this.memoryProvider??void 0:void 0,userId:this.memoryUserId});return{content:[{type:"text",text:C.message}],details:{type:"memory",action:C.action,ok:C.ok}}}})}Up(d,{getMemdir:()=>this.memdir,log:{debug:g=>l.debug(g),warn:g=>l.warn(g)}},this.memoryPrefetchState);{let g=e?.workdir??process.cwd(),v=Ng(g,this.currentSessionId||"default");Pe(Lg(v))}Pe($g({sendNotification:async g=>(l.info(`[notify] ${g.title??""}: ${g.message}`),{delivered:!0,channel:g.channel??"cli"})})),Pe(Ug({sendMessage:async g=>(l.info(`[send_message] ${g.senderId} \u2192 ${g.to}: ${g.message}`),{success:!0,recipients:[g.to]}),getSenderId:()=>this.currentSessionId??"default",listTeammates:()=>[]}));{let g=e?.workdir??process.cwd(),v,_=()=>(v||(v=ui.createContext({...{readFile:async R=>Y.promises.readFile(te.resolve(g,R),"utf8"),writeFile:async(R,U)=>{await Y.promises.writeFile(te.resolve(g,R),U,"utf8")},editFile:async(R,U)=>{let D=await Y.promises.readFile(te.resolve(g,R),"utf8");for(let M of U)D=D.replace(M.oldText,M.newText);return await Y.promises.writeFile(te.resolve(g,R),D,"utf8"),D},exec:async R=>{let U=await import("node:child_process");return new Promise(D=>{U.execFile("bash",["-c",R],{cwd:g,timeout:3e4},(M,V,ae)=>{D({stdout:V?.toString()??"",stderr:ae?.toString()??"",exitCode:M?M.code??1:0})})})},glob:async R=>{try{let{globSync:U}=await import("node:fs");return U(R,{cwd:g})}catch{return[]}},grep:async(R,U)=>{let D=[],M=te.resolve(g,U??".");try{let V=await import("node:child_process"),ae=await new Promise(ee=>{V.execFile("grep",["-rn",R,M,"--include=*"],{timeout:1e4},(oe,me)=>ee(me?.toString()??""))});for(let ee of ae.split(`
843
+ `).slice(0,3).join(" ").slice(0,200),Ge=v?te.basename(v):"unknown";this.memoryProvider.ingestExtracted([{text:`Learned skill "${g.name}" in project "${Ge}": ${me}`,category:"skill-learning"}],this.memoryUserId).catch(()=>{})}let oe=v?` (project-scoped). To make it available across all projects, use: skill promote name:"${g.name}"`:"";return{success:!0,message:`Skill "${g.name}" created${oe}`,path:C}}case"edit":{let D=We(U);if(D.records[g.name]?.pinned)return{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`};let M=g.content??"",ae=zc(M,g.name)??M;return await Y.promises.writeFile(R,ae,"utf8"),Hc(D,g.name),Ve(U,D),this.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",content:ae,scope:"project"}}),{success:!0,message:`Skill "${g.name}" updated`,path:R}}case"patch":{let D=We(U);if(D.records[g.name]?.pinned)return{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`};let M=await Y.promises.readFile(R,"utf8");if(!g.oldString||!M.includes(g.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let V=M.replace(g.oldString,g.newString??"");return await Y.promises.writeFile(R,V,"utf8"),Hc(D,g.name),Ve(U,D),this.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",content:V,scope:"project"}}),{success:!0,message:`Skill "${g.name}" patched`,path:R}}case"delete":{let D=We(U);return D.records[g.name]?.pinned?{success:!1,message:`Skill "${g.name}" is pinned. Unpin it first.`}:(await Y.promises.rm(C,{recursive:!0,force:!0}),Fs(D,g.name),Ve(U,D),this.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:g.name,category:g.category??"learned",action:"delete",scope:"project"}}),gt(),{success:!0,message:`Skill "${g.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${g.action}`}}},promoteSkill:async g=>{let v=It(this.getActiveProjectRoot()),_=te.join(v,g,"SKILL.md");try{await Y.promises.access(_)}catch{return{success:!1,message:`Skill "${g}" not found in project skills. Cannot promote.`}}let C=Ht(),R=te.join(C,g);await Y.promises.mkdir(R,{recursive:!0});let U=te.join(v,g),D=await Y.promises.readdir(U);for(let M of D){let V=await Y.promises.readFile(te.join(U,M));await Y.promises.writeFile(te.join(R,M),V)}return this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:g,category:"promoted",content:await Y.promises.readFile(_,"utf8"),scope:"global"}}),await Y.promises.rm(U,{recursive:!0,force:!0}),this.sendNotification("turn.skill_instruction",{turnId:`skill-promote-cleanup-${Date.now()}`,instruction:{name:g,category:"learned",action:"delete",scope:"project"}}),gt(),{success:!0,message:`Skill "${g}" promoted to global (user-level) and removed from project scope. It will now be available across all projects.`,path:R}},installSkill:async(g,v)=>{let _;try{if(_=new URL(g),!["http:","https:"].includes(_.protocol))return{success:!1,message:`Invalid URL scheme: ${_.protocol}. Only http/https allowed.`}}catch{return{success:!1,message:`Invalid URL: ${g}`}}let C=v??YE(_);if(!C)return{success:!1,message:"Cannot derive skill name from URL. Please provide 'name' parameter."};try{let R=await fetch(g,{signal:AbortSignal.timeout(3e4)});if(!R.ok)return{success:!1,message:`Download failed: HTTP ${R.status} ${R.statusText}`};let U=R.headers.get("content-length");if(U&&parseInt(U,10)>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};let D=await R.text();if(!D.trim())return{success:!1,message:"Downloaded content is empty."};if(D.length>512e3)return{success:!1,message:"Content too large (>512KB). Skill files should be small markdown documents."};if(D.trimStart().startsWith("<!DOCTYPE")||D.trimStart().startsWith("<html"))return{success:!1,message:"URL returned an HTML page, not a raw markdown file. Use a raw/direct download link."};let M=Ht(),V=te.join(M,C);return await Y.promises.mkdir(V,{recursive:!0}),await Y.promises.writeFile(te.join(V,"SKILL.md"),D,"utf8"),this.sendNotification("turn.skill_instruction",{turnId:`skill-install-${Date.now()}`,instruction:{name:C,category:"installed",content:D,scope:"global"}}),gt(),{success:!0,message:`Skill "${C}" installed from ${_.host}. Available globally across all projects.`,path:V}}catch(R){return{success:!1,message:`Install failed: ${R instanceof Error?R.message:String(R)}`}}}})),Pe(Ag({abortSignal:void 0,currentForkDepth:0,forkAgent:async g=>{let v=Cr(g.agent);if(!v)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 _=cn(),C=Ra(_,v),U=Mt().filter(oe=>C.includes(oe.function.name)),D=Il(U,!0),M=g.maxTurns??v.maxTurns??200;if(we.isTeamBudgetExceeded())return{agentId:`fork-${g.agent}-budget-exceeded`,status:"failed",output:void 0,error:we.teamBudgetExceededError(),tokensUsed:0};let V=await Dc({promptMessages:[{role:"user",content:g.prompt}],tools:D,transport:this.currentTransport,toolInvoker:c,apiKey:this.currentApiKey,model:this.currentModel,log:l,hooks:d,forkLabel:`agent-${g.agent}`,maxTurns:M,parentSignal:g.abortSignal,parentDepth:0,onEvent:oe=>{oe.type==="delta"&&oe.text&&this.sendNotification("turn.subagent_delta",{agentType:g.agent,text:oe.text})}}),ae=V.events.filter(oe=>oe.type==="end"&&"content"in oe).map(oe=>oe.content??"").join("")||V.events.filter(oe=>oe.type==="delta"&&"text"in oe).map(oe=>oe.text).join(""),ee=V.totalUsage.inputTokens+V.totalUsage.outputTokens;return we.recordForkTokens(ee),{agentId:`fork-${g.agent}-${wt().slice(0,8)}`,status:V.ok?"completed":"failed",output:ae||void 0,error:V.error,tokensUsed:ee}}}));let ce=pt(),de=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 Y.promises.readFile(ce,"utf8"))}catch{return{}}},ve=async g=>{await Y.promises.mkdir(te.dirname(ce),{recursive:!0}),await Y.promises.writeFile(ce,JSON.stringify(g,null,2),"utf8")};Pe(Pg({getConfig:async g=>{let v=de.get(g);if(!v)return{success:!1,error:`Unknown key: ${g}`};let _=await j(),C=g in _?_[g]:v.value;return{success:!0,setting:{...v,value:C,readOnly:Jo.includes(g)}}},setConfig:async(g,v)=>{let _=de.get(g);if(!_)return{success:!1,error:`Unknown key: ${g}`};let C=await j(),R=g in C?C[g]:_.value;return C[g]=v,await ve(C),{success:!0,previousValue:R,setting:{..._,value:v}}},listConfig:async()=>{let g=await j();return{success:!0,settings:[...de.values()].map(_=>({..._,value:_.key in g?g[_.key]:_.value,readOnly:Jo.includes(_.key)}))}},resetConfig:async g=>{let v=de.get(g);if(!v)return{success:!1,error:`Unknown key: ${g}`};let _=await j();return delete _[g],await ve(_),{success:!0,setting:v}},isValidKey:g=>de.has(g)}));let ie=new Map,Ue=g=>{let v=/^(\d+)([smhd])$/.exec(g.trim());if(!v)return null;let _=parseInt(v[1],10),C=v[2];return _*({s:1e3,m:6e4,h:36e5,d:864e5}[C]??6e4)},ne=g=>{g.timerId&&clearTimeout(g.timerId);let v=Ue(g.schedule);if(!v)return;let _=Date.now(),C=v-_%v||v;g.timerId=setTimeout(()=>{g.lastRunAt=new Date().toISOString(),g.repeat.completed++,g.lastStatus="success",l.info(`[cron] triggered job ${g.id} (${g.name})`),this.sendNotification("system.activity",{category:"cron",level:"info",title:`\u5B9A\u65F6\u4EFB\u52A1\u89E6\u53D1: ${g.name}`,detail:`\u8C03\u5EA6 ${g.scheduleDisplay}\uFF0C\u7B2C ${g.repeat.completed} \u6B21\u6267\u884C`}),g.repeat.times===null||g.repeat.completed<g.repeat.times?ne(g):(g.state="paused",g.enabled=!1,this.sendNotification("system.activity",{category:"cron",level:"info",title:`\u5B9A\u65F6\u4EFB\u52A1\u5B8C\u6210: ${g.name}`,detail:`\u5DF2\u8FBE\u5230\u6700\u5927\u6267\u884C\u6B21\u6570 (${g.repeat.completed}\u6B21)`}))},C),g.nextRunAt=new Date(_+C).toISOString()};Pn(async()=>{for(let g of ie.values())g.timerId&&clearTimeout(g.timerId)}),Pe(Cg({createJob:async g=>{let v=`cron_${wt().slice(0,8)}`,_={id:v,name:g.name??`Job ${v}`,prompt:g.prompt,schedule:g.schedule,scheduleDisplay:g.schedule,state:"scheduled",enabled:!0,repeat:{times:g.repeat??null,completed:0},allowedTools:g.allowedTools};return ie.set(v,_),ne(_),{success:!0,job:{..._,timerId:void 0}}},listJobs:async()=>({success:!0,jobs:[...ie.values()].map(v=>({...v,timerId:void 0}))}),getJob:async g=>{let v=ie.get(g);return v?{success:!0,job:{...v,timerId:void 0}}:{success:!1,error:`Job not found: ${g}`}},updateJob:async(g,v)=>{let _=ie.get(g);return _?(v.prompt!==void 0&&(_.prompt=v.prompt),v.schedule!==void 0&&(_.schedule=v.schedule,_.scheduleDisplay=v.schedule),v.name!==void 0&&(_.name=v.name),v.enabled!==void 0&&(_.enabled=v.enabled,_.state=v.enabled?"scheduled":"paused"),v.repeat!==void 0&&(_.repeat.times=v.repeat),v.allowedTools!==void 0&&(_.allowedTools=v.allowedTools),_.enabled?ne(_):_.timerId&&(clearTimeout(_.timerId),_.timerId=void 0),{success:!0,job:{..._,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},deleteJob:async g=>{let v=ie.get(g);return v?(v.timerId&&clearTimeout(v.timerId),ie.delete(g),{success:!0}):{success:!1,error:`Job not found: ${g}`}},pauseJob:async g=>{let v=ie.get(g);return v?(v.state="paused",v.enabled=!1,v.timerId&&(clearTimeout(v.timerId),v.timerId=void 0),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},resumeJob:async g=>{let v=ie.get(g);return v?(v.state="scheduled",v.enabled=!0,ne(v),{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},triggerJob:async g=>{let v=ie.get(g);return v?(v.lastRunAt=new Date().toISOString(),v.repeat.completed++,v.lastStatus="success",{success:!0,job:{...v,timerId:void 0}}):{success:!1,error:`Job not found: ${g}`}},validateSchedule:g=>Ue(g)!==null||/^\d{1,2}\s/.test(g)?null:`Invalid schedule: ${g}. Use shorthand (5m, 1h, 1d) or cron expression.`}));let Q=new Map;Pn(async()=>{for(let g of Q.values())g.cleanup();Q.clear()}),Pe(Eg({startMonitor:async g=>{if(Q.has(g.monitorId))return{action:"start",success:!1,error:`Monitor "${g.monitorId}" already exists.`};let v={monitorId:g.monitorId,source:g.source,target:g.target,conditions:g.conditions,startedAt:Date.now(),timeoutSeconds:g.timeoutSeconds,eventCount:0},_=()=>{};if(g.source==="file")try{let C=Y.watch(g.target,{persistent:!1},()=>{v.eventCount++,l.info(`[monitor] file change detected: ${g.target}`)});_=()=>C.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${g.target}`}}if(g.timeoutSeconds>0){let C=setTimeout(()=>{let U=Q.get(g.monitorId);U&&(U.cleanup(),Q.delete(g.monitorId))},g.timeoutSeconds*1e3),R=_;_=()=>{clearTimeout(C),R()}}return Q.set(g.monitorId,{info:v,cleanup:_}),{action:"start",success:!0,monitorId:g.monitorId}},stopMonitor:async g=>{let v=Q.get(g);return v?(v.cleanup(),Q.delete(g),{action:"stop",success:!0,monitorId:g}):{action:"stop",success:!1,error:`Monitor "${g}" not found.`}},listMonitors:async()=>[...Q.values()].map(g=>g.info)}));let T=new Map,F={info:g=>l.info(g),warn:g=>l.warn(g)},B=new pn({onNotification:(g,v,_)=>{this.sendNotification("team.member.notification",{memberId:g,method:v,params:_})},onStateChange:(g,v)=>{this.sendNotification("team.member.state",{memberId:g,state:v});let _=B.getHandle(g),R=B.getUsageTracker(g)?.getUsage();this.emitAgentStatus(g,v,{missedBeats:B.getMissedBeats(g),lastActivityAt:_?.lastActivityAt,usage:R&&R.totalTokens>0?{inputTokens:R.inputTokens,outputTokens:R.outputTokens,totalTokens:R.totalTokens}:void 0})},onExit:(g,v,_)=>{for(let C of T.values()){let R=C.members.find(U=>U.cwd&&`team-${C.name}-${U.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()===g.replace(/^team-/,""));R&&(R.isActive=!1)}l.info(`[team] member ${g} exited (code=${v}, signal=${_})`)},onMcpToolCall:(g,v,_)=>this.handleMcpToolCall(g,v,_),log:{info:g=>l.info(g),warn:g=>l.warn(g),debug:g=>l.debug(g)},sessionDir:te.join(H(),"agent-logs")});Pn(async()=>{B.dispose()}),Pe(Mg({createTeam:async g=>{if(T.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let v=await Ho(),_=[];for(let R of g.members??[]){let U={...R,isActive:!0};if(v){let D=`team-${g.teamName}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),M=await hf(v,D,F);M?(U.worktreePath=M.worktreePath,U.worktreeBranch=M.branch,U.cwd=M.worktreePath,l.info(`[team] provisioned worktree for ${R.name}: ${M.worktreePath}`)):(U.cwd=process.cwd(),l.warn(`[team] worktree provision failed for ${R.name}, using shared cwd`))}else U.cwd=process.cwd();_.push(U)}let C={name:g.teamName,description:g.description,leadId:this.currentSessionId??"default",members:_,createdAt:new Date().toISOString()};T.set(g.teamName,C);for(let R of _){if(!R.cwd)continue;let U=`team-${g.teamName}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();try{await B.spawn({memberId:U,name:R.name,cwd:R.cwd,prompt:`You are the "${R.name}" team member. Role: ${R.role}.`,agentType:R.role,verbose:this.verbose}),l.info(`[team] spawned child process for ${R.name} in ${R.cwd}`)}catch(D){l.warn(`[team] failed to spawn child process for ${R.name}: ${D instanceof Error?D.message:String(D)}`),R.isActive=!1}}return this.sendNotification("team.updated",{teamName:g.teamName,action:"created",members:C.members.map(R=>({agentName:R.name,role:R.role,worktreePath:R.worktreePath,pid:B.getHandle(`team-${g.teamName}-${R.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase())?.pid}))}),{success:!0,team:C}},deleteTeam:async g=>{let v=T.get(g);if(!v)return{success:!1,error:`Team "${g}" not found.`};for(let C of v.members){let R=`team-${g}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase();B.kill(R),B.remove(R)}let _=await Ho();if(_)for(let C of v.members)C.worktreePath&&C.worktreeBranch&&(await yf(_,C.worktreePath,C.worktreeBranch,F),l.info(`[team] cleaned up worktree for ${C.name}: ${C.worktreePath}`));return T.delete(g),this.sendNotification("team.updated",{teamName:g,action:"destroyed",members:[]}),{success:!0}},listTeams:async()=>({success:!0,teams:[...T.values()]}),getTeamStatus:async g=>{let v=T.get(g);if(!v)return{success:!1,error:`Team "${g}" not found.`};let _={};for(let C of v.members){let R=`team-${g}-${C.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),U=B.getStatus(R);U&&(C.isActive=U.alive,_[C.name]={mediaProgress:U.mediaProgress,lastToolCall:U.lastToolCall,idleFor:U.idleFor,runningFor:U.runningFor})}return{success:!0,team:v,memberProgress:_}}}));{let g=this.memdir;Pe({name:Yg,label:Xg,description:Qg,parameters:Jg,execute:async(v,_)=>{let C=await Zg(_,{memdir:g,provider:this.memoryUserId?this.memoryProvider??void 0:void 0,localProvider:this.memoryUserId?this.memoryProvider??void 0:void 0,userId:this.memoryUserId});return{content:[{type:"text",text:C.message}],details:{type:"memory",action:C.action,ok:C.ok}}}})}Up(d,{getMemdir:()=>this.memdir,log:{debug:g=>l.debug(g),warn:g=>l.warn(g)}},this.memoryPrefetchState);{let g=e?.workdir??process.cwd(),v=Ng(g,this.currentSessionId||"default");Pe(Lg(v))}Pe($g({sendNotification:async g=>(l.info(`[notify] ${g.title??""}: ${g.message}`),{delivered:!0,channel:g.channel??"cli"})})),Pe(Ug({sendMessage:async g=>(l.info(`[send_message] ${g.senderId} \u2192 ${g.to}: ${g.message}`),{success:!0,recipients:[g.to]}),getSenderId:()=>this.currentSessionId??"default",listTeammates:()=>[]}));{let g=e?.workdir??process.cwd(),v,_=()=>(v||(v=ui.createContext({...{readFile:async R=>Y.promises.readFile(te.resolve(g,R),"utf8"),writeFile:async(R,U)=>{await Y.promises.writeFile(te.resolve(g,R),U,"utf8")},editFile:async(R,U)=>{let D=await Y.promises.readFile(te.resolve(g,R),"utf8");for(let M of U)D=D.replace(M.oldText,M.newText);return await Y.promises.writeFile(te.resolve(g,R),D,"utf8"),D},exec:async R=>{let U=await import("node:child_process");return new Promise(D=>{U.execFile("bash",["-c",R],{cwd:g,timeout:3e4},(M,V,ae)=>{D({stdout:V?.toString()??"",stderr:ae?.toString()??"",exitCode:M?M.code??1:0})})})},glob:async R=>{try{let{globSync:U}=await import("node:fs");return U(R,{cwd:g})}catch{return[]}},grep:async(R,U)=>{let D=[],M=te.resolve(g,U??".");try{let V=await import("node:child_process"),ae=await new Promise(ee=>{V.execFile("grep",["-rn",R,M,"--include=*"],{timeout:1e4},(oe,me)=>ee(me?.toString()??""))});for(let ee of ae.split(`
844
844
  `).filter(Boolean).slice(0,100)){let oe=ee.match(/^(.+?):(\d+):(.*)$/);oe&&D.push({file:oe[1],line:parseInt(oe[2]),text:oe[3]})}}catch{}return D},console:{log:(...R)=>R.map(String).join(" ")}},setTimeout,clearTimeout,Promise,JSON,Math,Date,Array,Object,String,Number,Boolean,RegExp,Map,Set,Error,Buffer})),v);Pe(Bg({executeInVm:async C=>{let R=Date.now();try{let U=_(),D=await ui.runInContext(`(async () => { ${C} })()`,U,{timeout:3e4});return{output:D!==void 0?String(D):"",duration:Date.now()-R}}catch(U){return{output:"",error:U instanceof Error?U.message:String(U),duration:Date.now()-R}}},resetVm:()=>{v=void 0}}))}{let g=e?.workdir??process.cwd();Pe(Wg({executeOperation:async v=>{switch(v.operation){case"goToDefinition":case"findReferences":return{type:"locations",locations:[]};case"hover":return{type:"hover",hover:null};case"documentSymbol":return{type:"symbols",symbols:[]};case"diagnostics":return{type:"diagnostics",diagnostics:[]};case"completion":return{type:"completions",completions:[]};case"signatureHelp":return{type:"signatureHelp",signatures:[]};case"rename":return{type:"rename",edits:[]};case"codeAction":return{type:"codeActions",actions:[]};default:return{type:"locations",locations:[]}}},resolvePath:v=>te.isAbsolute(v)?v:te.resolve(g,v)}))}let Re=e?.workdir??process.cwd(),he=lh({projectRoot:Re,ruleEngine:P,hooks:d,log:g=>l.info(`[settings] ${g}`)});Pn(async()=>{he()}),this.currentSessionId&&d.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let Ut=e?.workdir??process.cwd();return um({projectRoot:Ut,sessionId:this.currentSessionId,hooks:d,log:g=>l.debug(g),onInstructionCacheReset:ym}).then(g=>{this.fileWatcher=g,Pn(async()=>{this.fileWatcher?.stop()})}).catch(g=>{l.warn(`[file-watcher] init error: ${g instanceof Error?g.message:g}`)}),this.agent=new Hn({llmTransport:a.transport,apiKey:a.apiKey,toolInvoker:c,log:l,hooks:d,maxRounds:e.maxRounds,verbose:this.verbose,projectRoot:this.getActiveProjectRoot()}),this.lastLlmConfigKey=i,this.currentTransport=a.transport,this.currentApiKey=a.apiKey,this.currentModel=o,this.currentProvider=t,this.currentBaseUrl=s??"",this.log(`created Agent (provider: ${t}, model: ${o})`),this.agent}static STATE_TO_STATUS={starting:"spawning",ready:"available",running:"running",completed:"available",failed:"failed",killed:"unavailable"};emitAgentStatus(e,t,o){let r=n.STATE_TO_STATUS[t]??"unavailable",s={agentId:e,status:r};(o?.missedBeats!==void 0||o?.lastActivityAt!==void 0)&&(s.health={missedBeats:o.missedBeats??0,lastActiveAt:o.lastActivityAt?new Date(o.lastActivityAt).toISOString():new Date().toISOString()}),o?.usage&&(s.usage=o.usage),this.sendNotification("agents.status",s)}async handleMcpToolCall(e,t,o){let r=nt(t);if(!r)return`Error: Unknown tool "${t}"`;let s=`mcp_${e}_${wt().slice(0,8)}`;try{return(await r.execute(s,o)).content.map(a=>a.text??"").join(`
845
845
  `)||"OK"}catch(i){return`Error: ${i instanceof Error?i.message:String(i)}`}}async ensureAgentConfigStore(){return this.agentConfigStore||(this.agentConfigStore=new Es(this.getActiveProjectRoot()),await this.agentConfigStore.load(),this.acpDetector.setConfigStore(this.agentConfigStore.getData())),this.agentConfigStore}sendResponse(e,t,o){let r={jsonrpc:"2.0",id:e};o?r.error=o:r.result=t,this.writeStdout(r)}sendNotification(e,t){if(this.acpServer&&this.acpServer.sessionId)Ph(this.acpServer,this.acpServer.sessionId,e,t);else{let o={jsonrpc:"2.0",method:e,params:t};this.writeStdout(o)}e==="turn.end"&&this.resetIdleDreamTimer(),e==="turn.start"&&this.cancelIdleDreamTimer()}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`[qlogicagent] ${e}
846
- `)}enableIdleDream(e){we.dream.enabled=!0,e&&e>0&&(we.dream.idleMinutes=e),this.resetIdleDreamTimer()}resetIdleDreamTimer(){this.cancelIdleDreamTimer(),we.dream.enabled&&this.currentSessionId&&(this.idleDreamTimer=setTimeout(()=>{this.triggerIdleDream()},we.dream.idleMinutes*6e4),this.idleDreamTimer.unref?.())}cancelIdleDreamTimer(){this.idleDreamTimer&&(clearTimeout(this.idleDreamTimer),this.idleDreamTimer=null)}async triggerIdleDream(){if(Date.now()-we.dream.lastDreamAt<we.dream.cooldownMs){this.log("[dream:idle] Skipped \u2014 cooldown not elapsed");return}let e=this.resolveClientForPurpose("textGeneration");if(!e){this.log("[dream:idle] Skipped \u2014 no LLM transport configured");return}if(this.activeTurn){this.log("[dream:idle] Skipped \u2014 turn in progress");return}this.log("[dream:idle] Triggering idle dream consolidation"),we.dream.lastDreamAt=Date.now(),this.sendNotification("system.activity",{category:"dream",level:"info",title:"\u7A7A\u95F2\u68A6\u5883\u6574\u7406\u89E6\u53D1",detail:`\u7A7A\u95F2 ${we.dream.idleMinutes} \u5206\u949F\u540E\u81EA\u52A8\u89E6\u53D1`});let t=setTimeout(()=>{this.activeTurn&&(this.log("[dream:idle] Aborting \u2014 max duration reached"),this.activeTurn.abort())},we.dream.maxDurationMs);t.unref?.();let o=H(),r=[];try{r=(await Et(20,this.getActiveProjectRoot())).filter(a=>a.sessionId!==this.currentSessionId).map(a=>a.sessionId)}catch{}let s={jsonrpc:"2.0",id:void 0,method:"memory.dream",params:{turnId:`idle-dream-${wt().slice(0,8)}`,sessionId:this.currentSessionId,config:{memoryRoot:o,transcriptDir:te.join(o,"agent-logs"),dreamSessionIds:r,currentSessionTurnCount:this.sessionState?.turnCount??0,model:e.model,apiKey:e.apiKey,force:!1}}};try{await oi.call(this,s)}finally{clearTimeout(t)}this.resetIdleDreamTimer()}initAcpServer(){let e={handleAcpInitialize:t=>this.acpHandleInitialize(t),handleAcpSessionNew:t=>this.acpHandleSessionNew(t),handleAcpSessionPrompt:t=>this.acpHandleSessionPrompt(t),handleAcpSessionEnd:t=>this.acpHandleSessionEnd(t),handleAcpSessionSetConfig:t=>this.acpHandleSessionSetConfig(t),handleAcpSessionSetModel:(t,o)=>this.acpHandleSessionSetModel(t,o),handleAcpSessionSetMode:(t,o)=>this.acpHandleSessionSetMode(t,o),handleAcpPermissionResponse:(t,o)=>this.acpHandlePermissionResponse(t,o),handleAcpAbort:t=>this.acpHandleAbort(t),handleAcpDream:t=>this.acpHandleDream(t),handleAcpAgentsList:()=>this.acpHandleAgentsList(),handleAcpSoloStart:t=>this.acpHandleSoloStart(t),handleAcpSoloStatus:t=>this.acpHandleSoloStatus(t),handleAcpSoloSelect:t=>this.acpHandleSoloSelect(t),handleAcpSoloCancel:t=>this.acpHandleSoloCancel(t),handleAcpSoloSubscribe:t=>this.acpHandleSoloSubscribe(t),handleAcpSoloMessage:t=>this.acpHandleSoloMessage(t),handleAcpSoloEvaluate:t=>this.acpHandleSoloEvaluate(t),handleAcpProductCreate:t=>this.acpHandleProductCreate(t),handleAcpProductPlan:t=>this.acpHandleProductPlan(t),handleAcpProductConfirm:t=>this.acpHandleProductConfirm(t),handleAcpProductMessage:t=>this.acpHandleProductMessage(t),handleAcpProductPause:t=>this.acpHandleProductPause(t),handleAcpProductResume:t=>this.acpHandleProductResume(t),handleAcpProductCancel:t=>this.acpHandleProductCancel(t),handleAcpProductRollback:t=>this.acpHandleProductRollback(t),handleAcpProductStatus:t=>this.acpHandleProductStatus(t),handleAcpProductSubscribe:t=>this.acpHandleProductSubscribe(t),handleAcpTeamDelegate:t=>this.acpHandleTeamDelegate(t)};this.acpServer=new Hs(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}async acpHandleInitialize(e){let t=e.clientInfo?.name??"unknown";this.log(`[acp] initialize: host=${t}`);let o={extendedEvents:!0,extendedMethods:!0,orchestration:!0,configOptions:[{name:"model",type:"string",description:"LLM model identifier"},{name:"provider",type:"string",description:"LLM provider identifier"},{name:"maxRounds",type:"number",description:"Max tool loop rounds"},{name:"temperature",type:"number",description:"Sampling temperature"}]};return this.ensureDefaultProject(),{protocolVersion:1,agentInfo:{name:"qlogicagent",version:KE},agentCapabilities:o}}async acpHandleSessionNew(e){let t=e.sessionId??wt();return this.log(`[acp] session/new: id=${t}`),this.currentSessionId=t,this.sessionState=new ln(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Kt(),e.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.enableIdleDream(),{sessionId:t}}async acpHandleSessionPrompt(e){let t=wt(),o=e.sessionId,r=e.prompt.map(l=>l.type==="text"?l.text:`[${l.type}]`).join("");if(!r.trim())return this.sendNotification("turn.start",{turnId:t,model:this.currentModel||void 0}),this.sendNotification("turn.end",{turnId:t,content:"",item:{id:`${t}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),{stopReason:"end_turn"};let s=this.acpSessionHistory.get(o);s||(s=[],this.acpSessionHistory.set(o,s)),s.push({role:"user",content:r});let i=[...s],a=await this.runAcpTurn(t,o,i);return a.content&&s.push({role:"assistant",content:a.content}),a}async runAcpTurn(e,t,o){let r=new AbortController;this.activeTurn=r,this.sendNotification("turn.start",{turnId:e,model:this.currentModel||void 0});try{let s={model:this.currentModel||void 0,provider:this.currentProvider||void 0,apiKey:this.currentApiKey||void 0,baseUrl:this.currentBaseUrl||void 0},i=this.resolveAgent(s);if(!i)return this.sendNotification("turn.delta",{turnId:e,text:"Error: No LLM provider configured. Configure via ~/.qlogicagent/settings.json or pass provider/apiKey in session config.",item:{id:`${e}-err`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.sendNotification("turn.end",{turnId:e,content:"",item:{id:`${e}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.activeTurn=null,{stopReason:"end_turn"};await this.mcpReady;let a=Mt(),l,c="end_turn",d="";for await(let u of i.run({turnId:e,sessionId:t,messages:o,tools:a,config:s},r.signal)){let p=new Date().toISOString();switch(u.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:u.turnId,text:u.text,item:{id:`${e}-delta`,type:"message",role:"assistant",text:u.text,createdAt:p}});break;case"end":u.usage&&(l={inputTokens:u.usage.inputTokens??0,outputTokens:u.usage.outputTokens??0,cacheReadTokens:u.usage.cacheRead,cacheWriteTokens:u.usage.cacheWrite}),d=u.content??"",this.sendNotification("turn.end",{turnId:u.turnId,content:u.content,usage:u.usage,model:u.model,provider:u.provider,item:{id:`${e}-end`,type:"message",role:"assistant",text:u.content,createdAt:p}});break;case"error":c="end_turn",this.sendNotification("turn.error",{turnId:u.turnId,error:{message:u.error,code:u.code}});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:u.turnId,callId:u.callId,name:u.name,arguments:u.arguments,item:{id:u.callId,type:"tool_call",role:"assistant",toolName:u.name,toolCallId:u.callId,arguments:u.arguments,createdAt:p}});break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:u.turnId,callId:u.callId,name:u.name,ok:u.ok,...u.error?{error:u.error}:{},...u.outputPreview?{outputPreview:u.outputPreview}:{},item:{id:`${u.callId}-result`,type:"tool_result",role:"assistant",toolName:u.name,toolCallId:u.callId,output:u.ok?u.outputPreview??"":u.error,approved:u.ok,createdAt:p}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:u.turnId,callId:u.callId,name:u.name,reason:u.reason,item:{id:`${u.callId}-blocked`,type:"tool_blocked",role:"system",toolName:u.name,toolCallId:u.callId,text:u.reason,approved:!1,createdAt:p}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:u.turnId,action:u.action,...u.detail?{detail:u.detail}:{},item:{id:`${e}-recovery-${wt().slice(0,8)}`,type:"recovery",role:"system",strategy:u.action,text:u.detail,createdAt:p}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:u.turnId,text:u.text});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:u.turnId,subagentId:u.subagentId,agentType:u.agentType,...u.prompt?{prompt:u.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:u.turnId,subagentId:u.subagentId,agentType:u.agentType,ok:u.ok,...u.outputPreview?{outputPreview:u.outputPreview}:{},...u.error?{error:u.error}:{}});break;case"media_result":this.sendNotification("turn.media_result",{turnId:u.turnId,mediaType:u.mediaType,url:u.url,...u.model?{model:u.model}:{},...u.provider?{provider:u.provider}:{},...u.taskId?{taskId:u.taskId}:{}});break}}return this.activeTurn=null,{stopReason:c,usage:l,content:d}}catch(s){this.activeTurn=null;let i=s instanceof Error?s.message:String(s);return this.log(`[acp] runAcpTurn error: ${i}`),this.sendNotification("turn.error",{turnId:e,error:{message:i,code:"INTERNAL_ERROR"}}),{stopReason:"end_turn"}}}async acpHandleSessionEnd(e){this.log(`[acp] session/end: id=${e.sessionId}`),this.acpSessionHistory.delete(e.sessionId),this.currentSessionId===e.sessionId&&(this.cancelIdleDreamTimer(),this.currentHooks&&await this.currentHooks.invoke("session.ended",{sessionId:e.sessionId}).catch(()=>{}),this.currentSessionId="",this.sessionState=null)}async acpHandleSessionSetConfig(e){let t=e.configId??e.option;this.log(`[acp] session/set_config: ${t}=${JSON.stringify(e.value)}`);let o=typeof e.value=="string"?e.value:"";switch(t){case"model":this.currentModel=o;break;case"provider":this.currentProvider=o;break;case"apiKey":this.currentApiKey=o;break;case"baseUrl":this.currentBaseUrl=o;break}}async acpHandleSessionSetModel(e,t){this.log(`[acp] session/set_model: ${t} (note: model is managed by ModelRegistry, this is a hint only)`),t&&(this.currentModel=t)}async acpHandleSessionSetMode(e,t){this.log(`[acp] session/set_mode: ${t}`)}acpHandlePermissionResponse(e,t){this.log(`[acp] permission response: ${e} \u2192 ${t}`),this.permissionChecker&&this.permissionChecker.resolveApproval({approvalId:e,decision:t==="allow"?"approved":"denied"})}async acpHandleAbort(e){this.log(`[acp] abort: session=${e.sessionId}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null)}async acpHandleDream(e){this.log(`[acp] x/dream: session=${e.sessionId}`);let t=this.resolveClientForPurpose("textGeneration");if(!t)return{ok:!1,summary:"No LLM transport configured for dream"};let o=H(),r={jsonrpc:"2.0",id:`acp-dream-${wt().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${wt().slice(0,8)}`,sessionId:e.sessionId||this.currentSessionId,config:{memoryRoot:e.config?.memoryRoot||o,transcriptDir:e.config?.transcriptDir||te.join(o,"agent-logs"),model:t.model,apiKey:t.apiKey,...e.config}}};return await oi.call(this,r),{ok:!0,summary:"Dream consolidation triggered"}}async acpHandleSoloStart(e){this.log("[acp] x/solo.start");let t=Je.call(this),o=await t.start(e);return t.getStatus(o)}async acpHandleSoloStatus(e){this.log("[acp] x/solo.status");let t=e.soloId;if(!t)return this.soloEvaluator?this.soloEvaluator.listSessions():[];let r=Je.call(this).getStatus(t);if(!r)throw new Error(`Solo session ${t} not found`);return r}async acpHandleSoloSelect(e){return this.log("[acp] x/solo.select"),{ok:!0,mergedBranch:await Je.call(this).select(e)}}async acpHandleSoloCancel(e){this.log("[acp] x/solo.cancel");let t=Je.call(this),o=e.soloId;return await t.cancel(o),{ok:!0}}async acpHandleSoloSubscribe(e){return this.log("[acp] x/solo.subscribe"),{ok:!0,soloId:e.soloId}}async acpHandleSoloMessage(e){this.log("[acp] x/solo.message");let t=Je.call(this),{soloId:o,agentId:r,content:s,agentIndex:i}=e;return t.message(o,r,s,i)}async acpHandleSoloEvaluate(e){this.log("[acp] x/solo.evaluate");let t=Je.call(this),{soloId:o,evaluatorAgentId:r,evaluatorIndex:s}=e;return t.triggerEvaluation(o,r,s)}async acpHandleAgentsList(){return this.log("[acp] x/agents.list"),Aa()}async acpHandleProductCreate(e){return this.log("[acp] x/product.create"),{productId:await Le.call(this).create(e)}}async acpHandleProductPlan(e){return this.log("[acp] x/product.plan"),await Cn.call(this).plan(e)}async acpHandleProductConfirm(e){this.log("[acp] x/product.confirm");let t=Cn.call(this),o=e,r=await t.confirm(o),s=t.getSession(o.productId);return s&&await Le.call(this).create({name:s.plan?.name??s.goal.slice(0,50),cwd:s.cwd,instances:o.instances,tasks:o.tasks,budget:o.budget}),r}async acpHandleProductMessage(e){this.log("[acp] x/product.message");let t=Cn.call(this),o=e;return t.message(o.productId,o.content)}async acpHandleProductResume(e){this.log("[acp] x/product.resume");let t=Le.call(this),o=e.productId;return await t.resume(o,this.getActiveProjectRoot()),{ok:!0}}async acpHandleProductStatus(e){this.log("[acp] x/product.status");let t=e.productId;if(!this.productOrchestrator)return t?null:[];if(!t)return this.productOrchestrator.list(this.getActiveProjectRoot());let o=this.productOrchestrator.getStatus(t);if(!o)throw new Error(`Product session ${t} not found`);return o}async acpHandleProductPause(e){this.log("[acp] x/product.pause");let t=Le.call(this),o=e.productId;return await t.pause(o),{ok:!0}}async acpHandleProductCancel(e){this.log("[acp] x/product.cancel");let t=Le.call(this),o=e.productId;return await t.delete(o),{ok:!0}}async acpHandleProductRollback(e){this.log("[acp] x/product.rollback");let t=Le.call(this),o=e.productId,r=e.checkpointId??"latest";return await t.rollback(o,r),{ok:!0}}async acpHandleProductSubscribe(e){return this.log("[acp] x/product.subscribe"),{ok:!0,productId:e.productId}}async acpHandleTeamDelegate(e){let t=e.agentType,o=e.prompt,r=e.maxTurns;if(!o)throw new Error("Missing required param: prompt");if(!t)throw new Error("Missing required param: agentType");let s=Cr(t);if(!s)throw new Error(`Unknown agent type: ${t}`);let i=this.resolveClientForPurpose("textGeneration");if(!i)throw new Error("No LLM provider configured \u2014 send a prompt first to configure the model");if(this.log(`[acp] x/team.delegate: agent=${t}, maxTurns=${r??s.maxTurns}`),we.isTeamBudgetExceeded())return{ok:!1,agentType:t,output:void 0,error:we.teamBudgetExceededError(),tokensUsed:0};let a={invoke:async()=>({result:"Tool execution not available in delegated mode"})},l={info:p=>this.log(`[delegate:${t}] ${p}`),warn:p=>this.log(`[delegate:${t}] WARN: ${p}`),error:p=>this.log(`[delegate:${t}] ERROR: ${p}`),debug:p=>this.log(`[delegate:${t}] ${p}`)},c=await Dc({promptMessages:[{role:"user",content:o}],tools:[],transport:i.transport,toolInvoker:a,apiKey:i.apiKey,model:i.model,log:l,forkLabel:`team-delegate-${t}`,maxTurns:r??s.maxTurns,parentSignal:this.activeTurn?.signal,parentDepth:0}),d=c.events.filter(p=>p.type==="end"&&"content"in p).map(p=>p.content??"").join("")||c.events.filter(p=>p.type==="delta"&&"text"in p).map(p=>p.text).join(""),u=c.totalUsage.inputTokens+c.totalUsage.outputTokens;return we.recordForkTokens(u),{ok:c.ok,agentType:t,output:d||void 0,error:c.error,tokensUsed:u}}};an();$n();export{Hn as Agent,sn as ProviderRegistry,wd as StdioServer,$o as StdioTransport,vo as buildSkillInstruction,dl as createHookRegistry,Eo as createLLMClient,Ww as parseCliArgs};
846
+ `)}enableIdleDream(e){we.dream.enabled=!0,e&&e>0&&(we.dream.idleMinutes=e),this.resetIdleDreamTimer()}resetIdleDreamTimer(){this.cancelIdleDreamTimer(),we.dream.enabled&&this.currentSessionId&&(this.idleDreamTimer=setTimeout(()=>{this.triggerIdleDream()},we.dream.idleMinutes*6e4),this.idleDreamTimer.unref?.())}cancelIdleDreamTimer(){this.idleDreamTimer&&(clearTimeout(this.idleDreamTimer),this.idleDreamTimer=null)}async triggerIdleDream(){if(Date.now()-we.dream.lastDreamAt<we.dream.cooldownMs){this.log("[dream:idle] Skipped \u2014 cooldown not elapsed");return}let e=this.resolveClientForPurpose("textGeneration");if(!e){this.log("[dream:idle] Skipped \u2014 no LLM transport configured");return}if(this.activeTurn){this.log("[dream:idle] Skipped \u2014 turn in progress");return}this.log("[dream:idle] Triggering idle dream consolidation"),we.dream.lastDreamAt=Date.now(),this.sendNotification("system.activity",{category:"dream",level:"info",title:"\u7A7A\u95F2\u68A6\u5883\u6574\u7406\u89E6\u53D1",detail:`\u7A7A\u95F2 ${we.dream.idleMinutes} \u5206\u949F\u540E\u81EA\u52A8\u89E6\u53D1`});let t=setTimeout(()=>{this.activeTurn&&(this.log("[dream:idle] Aborting \u2014 max duration reached"),this.activeTurn.abort())},we.dream.maxDurationMs);t.unref?.();let o=H(),r=[];try{r=(await Et(20,this.getActiveProjectRoot())).filter(a=>a.sessionId!==this.currentSessionId).map(a=>a.sessionId)}catch{}let s={jsonrpc:"2.0",id:void 0,method:"memory.dream",params:{turnId:`idle-dream-${wt().slice(0,8)}`,sessionId:this.currentSessionId,config:{memoryRoot:o,transcriptDir:te.join(o,"agent-logs"),dreamSessionIds:r,currentSessionTurnCount:this.sessionState?.turnCount??0,model:e.model,apiKey:e.apiKey,force:!1}}};try{await oi.call(this,s)}finally{clearTimeout(t)}this.resetIdleDreamTimer()}initAcpServer(){let e={handleAcpInitialize:t=>this.acpHandleInitialize(t),handleAcpSessionNew:t=>this.acpHandleSessionNew(t),handleAcpSessionPrompt:t=>this.acpHandleSessionPrompt(t),handleAcpSessionEnd:t=>this.acpHandleSessionEnd(t),handleAcpSessionSetConfig:t=>this.acpHandleSessionSetConfig(t),handleAcpSessionSetModel:(t,o)=>this.acpHandleSessionSetModel(t,o),handleAcpSessionSetMode:(t,o)=>this.acpHandleSessionSetMode(t,o),handleAcpPermissionResponse:(t,o)=>this.acpHandlePermissionResponse(t,o),handleAcpAbort:t=>this.acpHandleAbort(t),handleAcpDream:t=>this.acpHandleDream(t),handleAcpAgentsList:()=>this.acpHandleAgentsList(),handleAcpSoloStart:t=>this.acpHandleSoloStart(t),handleAcpSoloStatus:t=>this.acpHandleSoloStatus(t),handleAcpSoloSelect:t=>this.acpHandleSoloSelect(t),handleAcpSoloCancel:t=>this.acpHandleSoloCancel(t),handleAcpSoloSubscribe:t=>this.acpHandleSoloSubscribe(t),handleAcpSoloMessage:t=>this.acpHandleSoloMessage(t),handleAcpSoloEvaluate:t=>this.acpHandleSoloEvaluate(t),handleAcpProductCreate:t=>this.acpHandleProductCreate(t),handleAcpProductPlan:t=>this.acpHandleProductPlan(t),handleAcpProductConfirm:t=>this.acpHandleProductConfirm(t),handleAcpProductMessage:t=>this.acpHandleProductMessage(t),handleAcpProductPause:t=>this.acpHandleProductPause(t),handleAcpProductResume:t=>this.acpHandleProductResume(t),handleAcpProductCancel:t=>this.acpHandleProductCancel(t),handleAcpProductRollback:t=>this.acpHandleProductRollback(t),handleAcpProductStatus:t=>this.acpHandleProductStatus(t),handleAcpProductSubscribe:t=>this.acpHandleProductSubscribe(t),handleAcpTeamDelegate:t=>this.acpHandleTeamDelegate(t)};this.acpServer=new Hs(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}async acpHandleInitialize(e){let t=e.clientInfo?.name??"unknown";this.log(`[acp] initialize: host=${t}`);let o={extendedEvents:!0,extendedMethods:!0,orchestration:!0,configOptions:[{name:"model",type:"string",description:"LLM model identifier"},{name:"provider",type:"string",description:"LLM provider identifier"},{name:"maxRounds",type:"number",description:"Max tool loop rounds"},{name:"temperature",type:"number",description:"Sampling temperature"}]};return this.ensureDefaultProject(),{protocolVersion:1,agentInfo:{name:"qlogicagent",version:qE},agentCapabilities:o}}async acpHandleSessionNew(e){let t=e.sessionId??wt();return this.log(`[acp] session/new: id=${t}`),this.currentSessionId=t,this.sessionState=new ln(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=Kt(),e.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.enableIdleDream(),{sessionId:t}}async acpHandleSessionPrompt(e){let t=wt(),o=e.sessionId,r=e.prompt.map(l=>l.type==="text"?l.text:`[${l.type}]`).join("");if(!r.trim())return this.sendNotification("turn.start",{turnId:t,model:this.currentModel||void 0}),this.sendNotification("turn.end",{turnId:t,content:"",item:{id:`${t}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),{stopReason:"end_turn"};let s=this.acpSessionHistory.get(o);s||(s=[],this.acpSessionHistory.set(o,s)),s.push({role:"user",content:r});let i=[...s],a=await this.runAcpTurn(t,o,i);return a.content&&s.push({role:"assistant",content:a.content}),a}async runAcpTurn(e,t,o){let r=new AbortController;this.activeTurn=r,this.sendNotification("turn.start",{turnId:e,model:this.currentModel||void 0});try{let s={model:this.currentModel||void 0,provider:this.currentProvider||void 0,apiKey:this.currentApiKey||void 0,baseUrl:this.currentBaseUrl||void 0},i=this.resolveAgent(s);if(!i)return this.sendNotification("turn.delta",{turnId:e,text:"Error: No LLM provider configured. Configure via ~/.qlogicagent/settings.json or pass provider/apiKey in session config.",item:{id:`${e}-err`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.sendNotification("turn.end",{turnId:e,content:"",item:{id:`${e}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),this.activeTurn=null,{stopReason:"end_turn"};await this.mcpReady;let a=Mt(),l,c="end_turn",d="";for await(let u of i.run({turnId:e,sessionId:t,messages:o,tools:a,config:s},r.signal)){let p=new Date().toISOString();switch(u.type){case"start":break;case"delta":this.sendNotification("turn.delta",{turnId:u.turnId,text:u.text,item:{id:`${e}-delta`,type:"message",role:"assistant",text:u.text,createdAt:p}});break;case"end":u.usage&&(l={inputTokens:u.usage.inputTokens??0,outputTokens:u.usage.outputTokens??0,cacheReadTokens:u.usage.cacheRead,cacheWriteTokens:u.usage.cacheWrite}),d=u.content??"",this.sendNotification("turn.end",{turnId:u.turnId,content:u.content,usage:u.usage,model:u.model,provider:u.provider,item:{id:`${e}-end`,type:"message",role:"assistant",text:u.content,createdAt:p}});break;case"error":c="end_turn",this.sendNotification("turn.error",{turnId:u.turnId,error:{message:u.error,code:u.code}});break;case"tool_call":this.sendNotification("turn.tool_call",{turnId:u.turnId,callId:u.callId,name:u.name,arguments:u.arguments,item:{id:u.callId,type:"tool_call",role:"assistant",toolName:u.name,toolCallId:u.callId,arguments:u.arguments,createdAt:p}});break;case"tool_result":this.sendNotification("turn.tool_result",{turnId:u.turnId,callId:u.callId,name:u.name,ok:u.ok,...u.error?{error:u.error}:{},...u.outputPreview?{outputPreview:u.outputPreview}:{},item:{id:`${u.callId}-result`,type:"tool_result",role:"assistant",toolName:u.name,toolCallId:u.callId,output:u.ok?u.outputPreview??"":u.error,approved:u.ok,createdAt:p}});break;case"tool_blocked":this.sendNotification("turn.tool_blocked",{turnId:u.turnId,callId:u.callId,name:u.name,reason:u.reason,item:{id:`${u.callId}-blocked`,type:"tool_blocked",role:"system",toolName:u.name,toolCallId:u.callId,text:u.reason,approved:!1,createdAt:p}});break;case"recovery":this.sendNotification("turn.recovery",{turnId:u.turnId,action:u.action,...u.detail?{detail:u.detail}:{},item:{id:`${e}-recovery-${wt().slice(0,8)}`,type:"recovery",role:"system",strategy:u.action,text:u.detail,createdAt:p}});break;case"reasoning_delta":this.sendNotification("turn.reasoning_delta",{turnId:u.turnId,text:u.text});break;case"subagent_started":this.sendNotification("turn.subagent_started",{turnId:u.turnId,subagentId:u.subagentId,agentType:u.agentType,...u.prompt?{prompt:u.prompt}:{}});break;case"subagent_ended":this.sendNotification("turn.subagent_ended",{turnId:u.turnId,subagentId:u.subagentId,agentType:u.agentType,ok:u.ok,...u.outputPreview?{outputPreview:u.outputPreview}:{},...u.error?{error:u.error}:{}});break;case"media_result":this.sendNotification("turn.media_result",{turnId:u.turnId,mediaType:u.mediaType,url:u.url,...u.model?{model:u.model}:{},...u.provider?{provider:u.provider}:{},...u.taskId?{taskId:u.taskId}:{}});break}}return this.activeTurn=null,{stopReason:c,usage:l,content:d}}catch(s){this.activeTurn=null;let i=s instanceof Error?s.message:String(s);return this.log(`[acp] runAcpTurn error: ${i}`),this.sendNotification("turn.error",{turnId:e,error:{message:i,code:"INTERNAL_ERROR"}}),{stopReason:"end_turn"}}}async acpHandleSessionEnd(e){this.log(`[acp] session/end: id=${e.sessionId}`),this.acpSessionHistory.delete(e.sessionId),this.currentSessionId===e.sessionId&&(this.cancelIdleDreamTimer(),this.currentHooks&&await this.currentHooks.invoke("session.ended",{sessionId:e.sessionId}).catch(()=>{}),this.currentSessionId="",this.sessionState=null)}async acpHandleSessionSetConfig(e){let t=e.configId??e.option;this.log(`[acp] session/set_config: ${t}=${JSON.stringify(e.value)}`);let o=typeof e.value=="string"?e.value:"";switch(t){case"model":this.currentModel=o;break;case"provider":this.currentProvider=o;break;case"apiKey":this.currentApiKey=o;break;case"baseUrl":this.currentBaseUrl=o;break}}async acpHandleSessionSetModel(e,t){this.log(`[acp] session/set_model: ${t} (note: model is managed by ModelRegistry, this is a hint only)`),t&&(this.currentModel=t)}async acpHandleSessionSetMode(e,t){this.log(`[acp] session/set_mode: ${t}`)}acpHandlePermissionResponse(e,t){this.log(`[acp] permission response: ${e} \u2192 ${t}`),this.permissionChecker&&this.permissionChecker.resolveApproval({approvalId:e,decision:t==="allow"?"approved":"denied"})}async acpHandleAbort(e){this.log(`[acp] abort: session=${e.sessionId}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null)}async acpHandleDream(e){this.log(`[acp] x/dream: session=${e.sessionId}`);let t=this.resolveClientForPurpose("textGeneration");if(!t)return{ok:!1,summary:"No LLM transport configured for dream"};let o=H(),r={jsonrpc:"2.0",id:`acp-dream-${wt().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${wt().slice(0,8)}`,sessionId:e.sessionId||this.currentSessionId,config:{memoryRoot:e.config?.memoryRoot||o,transcriptDir:e.config?.transcriptDir||te.join(o,"agent-logs"),model:t.model,apiKey:t.apiKey,...e.config}}};return await oi.call(this,r),{ok:!0,summary:"Dream consolidation triggered"}}async acpHandleSoloStart(e){this.log("[acp] x/solo.start");let t=Je.call(this),o=await t.start(e);return t.getStatus(o)}async acpHandleSoloStatus(e){this.log("[acp] x/solo.status");let t=e.soloId;if(!t)return this.soloEvaluator?this.soloEvaluator.listSessions():[];let r=Je.call(this).getStatus(t);if(!r)throw new Error(`Solo session ${t} not found`);return r}async acpHandleSoloSelect(e){return this.log("[acp] x/solo.select"),{ok:!0,mergedBranch:await Je.call(this).select(e)}}async acpHandleSoloCancel(e){this.log("[acp] x/solo.cancel");let t=Je.call(this),o=e.soloId;return await t.cancel(o),{ok:!0}}async acpHandleSoloSubscribe(e){return this.log("[acp] x/solo.subscribe"),{ok:!0,soloId:e.soloId}}async acpHandleSoloMessage(e){this.log("[acp] x/solo.message");let t=Je.call(this),{soloId:o,agentId:r,content:s,agentIndex:i}=e;return t.message(o,r,s,i)}async acpHandleSoloEvaluate(e){this.log("[acp] x/solo.evaluate");let t=Je.call(this),{soloId:o,evaluatorAgentId:r,evaluatorIndex:s}=e;return t.triggerEvaluation(o,r,s)}async acpHandleAgentsList(){return this.log("[acp] x/agents.list"),Aa()}async acpHandleProductCreate(e){return this.log("[acp] x/product.create"),{productId:await Le.call(this).create(e)}}async acpHandleProductPlan(e){return this.log("[acp] x/product.plan"),await Cn.call(this).plan(e)}async acpHandleProductConfirm(e){this.log("[acp] x/product.confirm");let t=Cn.call(this),o=e,r=await t.confirm(o),s=t.getSession(o.productId);return s&&await Le.call(this).create({name:s.plan?.name??s.goal.slice(0,50),cwd:s.cwd,instances:o.instances,tasks:o.tasks,budget:o.budget}),r}async acpHandleProductMessage(e){this.log("[acp] x/product.message");let t=Cn.call(this),o=e;return t.message(o.productId,o.content)}async acpHandleProductResume(e){this.log("[acp] x/product.resume");let t=Le.call(this),o=e.productId;return await t.resume(o,this.getActiveProjectRoot()),{ok:!0}}async acpHandleProductStatus(e){this.log("[acp] x/product.status");let t=e.productId;if(!this.productOrchestrator)return t?null:[];if(!t)return this.productOrchestrator.list(this.getActiveProjectRoot());let o=this.productOrchestrator.getStatus(t);if(!o)throw new Error(`Product session ${t} not found`);return o}async acpHandleProductPause(e){this.log("[acp] x/product.pause");let t=Le.call(this),o=e.productId;return await t.pause(o),{ok:!0}}async acpHandleProductCancel(e){this.log("[acp] x/product.cancel");let t=Le.call(this),o=e.productId;return await t.delete(o),{ok:!0}}async acpHandleProductRollback(e){this.log("[acp] x/product.rollback");let t=Le.call(this),o=e.productId,r=e.checkpointId??"latest";return await t.rollback(o,r),{ok:!0}}async acpHandleProductSubscribe(e){return this.log("[acp] x/product.subscribe"),{ok:!0,productId:e.productId}}async acpHandleTeamDelegate(e){let t=e.agentType,o=e.prompt,r=e.maxTurns;if(!o)throw new Error("Missing required param: prompt");if(!t)throw new Error("Missing required param: agentType");let s=Cr(t);if(!s)throw new Error(`Unknown agent type: ${t}`);let i=this.resolveClientForPurpose("textGeneration");if(!i)throw new Error("No LLM provider configured \u2014 send a prompt first to configure the model");if(this.log(`[acp] x/team.delegate: agent=${t}, maxTurns=${r??s.maxTurns}`),we.isTeamBudgetExceeded())return{ok:!1,agentType:t,output:void 0,error:we.teamBudgetExceededError(),tokensUsed:0};let a={invoke:async()=>({result:"Tool execution not available in delegated mode"})},l={info:p=>this.log(`[delegate:${t}] ${p}`),warn:p=>this.log(`[delegate:${t}] WARN: ${p}`),error:p=>this.log(`[delegate:${t}] ERROR: ${p}`),debug:p=>this.log(`[delegate:${t}] ${p}`)},c=await Dc({promptMessages:[{role:"user",content:o}],tools:[],transport:i.transport,toolInvoker:a,apiKey:i.apiKey,model:i.model,log:l,forkLabel:`team-delegate-${t}`,maxTurns:r??s.maxTurns,parentSignal:this.activeTurn?.signal,parentDepth:0}),d=c.events.filter(p=>p.type==="end"&&"content"in p).map(p=>p.content??"").join("")||c.events.filter(p=>p.type==="delta"&&"text"in p).map(p=>p.text).join(""),u=c.totalUsage.inputTokens+c.totalUsage.outputTokens;return we.recordForkTokens(u),{ok:c.ok,agentType:t,output:d||void 0,error:c.error,tokensUsed:u}}};an();$n();export{Hn as Agent,sn as ProviderRegistry,wd as StdioServer,$o as StdioTransport,vo as buildSkillInstruction,dl as createHookRegistry,Eo as createLLMClient,Hw as parseCliArgs};