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/agent.js +8 -8
- package/dist/cli.js +149 -149
- package/dist/index.js +149 -149
- package/dist/types/runtime/infra/model-registry.test.d.ts +1 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ var zk=Object.defineProperty;var yi=(n=>typeof require<"u"?require:typeof Proxy<
|
|
|
12
12
|
${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 _i(n,e,t=xi){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 Ud,Nn,yn,fo,go,Fd,ho,yo,Av,rn,Ai=N(()=>{"use strict";Ud=4,Nn=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>=Ud)break;if(s-p<0&&l<Ud){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"}}},yn=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:Rv(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??xi,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}=_v(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=jd(p,{taskContext:this.config.taskContext}),f=await this.config.summarize(p,h),y={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
13
13
|
|
|
14
14
|
${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=kr(e),r=this.config.inner.compress(e,t),s=kr(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=kr(e),r=bo(this.config.inner)?await this.config.inner.compressAsync(e,t):this.config.inner.compress(e,t),s=kr(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}}}},Fd={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}))}};Av=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"]),rn=class{constructor(e=20,t=xi){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||!Av.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 Pi(){return{stages:[]}}function Ii(n,e,t){let o=t?.thresholdMessages??40;if(n.filter(a=>a.role!=="system").length<=o)return{messages:n,stagedCount:0};let s=Bd(n,e),i=Iv(s,e,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=Bd(n,e),{messages:s,stagedCount:i.length}}function Ci(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:Wd(n,e),committed:t}}function Bd(n,e){return e.stages.filter(o=>o.committed).length===0?n:Wd(n,e)}function Wd(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 Iv(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 Gd=N(()=>{"use strict"});function ga(){return{maxRoundsLimit:100,defaultMaxRounds:25,defaultTemperature:0,maxToolBudgetCap:100,defaultToolBudget:Ei,maxConsecutiveFailures:Mi,maxIdenticalCallRepeats:Oi,defaultContextWindowTokens:Di,responseBufferTokens:Li,defaultMaxOutputTokens:Ni,defaultModelMaxOutputTokens:$i,maxOutputTokensRecoveryLimit:Ui,escalatedMaxOutputTokens:ji,diminishingReturnsThreshold:Tr,diminishingReturnsMinContinuations:Fi,defaultMaxResultSizeChars:Bi,maxToolResultsPerMessageChars:Wi,toolResultPreviewBytes:wr,heartbeatIntervalMs:Gi,max529Retries:Hi,maxApiRetries:$n,persistentRetryMaxBackoffMs:Cv,persistentRetryResetCapMs:Ev,compressionTargetUsageRatio:Mv,compressionMinBudget:Ov,compressionMaxBudget:Dv,reactiveCompactMaxFailures:Lv,reactiveCompactMinMessages:Nv,reactiveCompactTargetPercent:$v,maxSkillsPerProject:Vi,maxSkillsGlobal:Hd,minToolCallsForSkill:Ki,minDistinctToolsForSkill:zi,skillCreationCooldownMs:qi,skillInjectionMaxChars:Uv,skillInjectionMaxCount:jv,skillRecallMaxSkills:Yi,skillRecallMaxContentChars:Xi,skillRecallCacheTtlMs:Ji,maxForkDepth:Qi,maxSessions:ea,taskSummaryTurnThreshold:ta,taskSummaryRegenInterval:na,maxIncludeDepth:oa,maxInstructionChars:Fv,instructionsMaxFileSize:ra,instructionsMaxDirSize:sa,mediaMaxDownloadSize:ia,mediaMaxUploadSize:Bv,mediaDownloadTimeoutMs:aa,acpMaxSpawnRetries:la,acpRetryBackoffBase:ca,acpRuntimeRestartMax:da,acpRuntimeRestartBackoffBase:ua,taskPollIntervalMs:Wv,taskStoppedDisplayMs:Gv,taskPanelGraceMs:Hv,memoryPrefetchMaxSessionBytes:pa,memoryPrefetchLimitPerRecall:ma,memoryMaxSurfacedEntries:fa,dreamMinIntervalHours:Vv,dreamMinSessions:Kv,dreamScanIntervalMs:zv,idleDreamMinutes:qv,dreamCooldownMs:Yv,dreamMaxDurationMs:Xv,teamBudgetTokens:Zi}}var Ei,Mi,Oi,Sr,Di,Li,Ni,$i,Ui,ji,Tr,Fi,Bi,Wi,wr,Gi,Hi,$n,Cv,Ev,Mv,Ov,Dv,Lv,Nv,$v,Vi,Hd,Ki,zi,qi,Vd,Kd,Uv,jv,Yi,Xi,Ji,Qi,Zi,ea,ta,na,zd,qd,oa,Fv,ra,sa,ia,Bv,aa,la,ca,da,ua,Wv,Gv,Hv,pa,ma,fa,Vv,Kv,zv,qv,Yv,Xv,je=N(()=>{"use strict";Ei=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Mi=3,Oi=2,Sr=2,Di=128e3,Li=13e3,Ni=16384,$i=65536,Ui=3,ji=65536,Tr=500,Fi=3,Bi=5e4,Wi=2e5,wr=2e3,Gi=3e4,Hi=3,$n=2,Cv=3e5,Ev=216e5,Mv=.75,Ov=16e3,Dv=12e4,Lv=3,Nv=4,$v=50,Vi=20,Hd=50,Ki=3,zi=2,qi=300*1e3,Vd=3,Kd=720*60*60*1e3,Uv=4e3,jv=5,Yi=3,Xi=800,Ji=300*1e3,Qi=4,Zi=0,ea=50,ta=50,na=30,zd=3600*1e3,qd=200,oa=5,Fv=4e4,ra=50*1024,sa=500*1024,ia=500*1024*1024,Bv=50*1024*1024,aa=3e5,la=2,ca=3e3,da=3,ua=5e3,Wv=1e3,Gv=3e3,Hv=3e4,pa=60*1024,ma=10,fa=100,Vv=24,Kv=5,zv=6e5,qv=30,Yv=144e5,Xv=3e5});import{existsSync as ha,readFileSync as Xd,writeFileSync as Jv,readdirSync as Jd,mkdirSync as Qv}from"node:fs";import{join as ya,dirname as Zv}from"node:path";function Zd(n){return ya(n,".qlogicagent",eS)}function tS(n){let e=Zd(n);try{return JSON.parse(Xd(e,"utf8"))}catch{return{version:1,patterns:{}}}}function Yd(n,e){let t=Zd(n);Qv(Zv(t),{recursive:!0}),Jv(t,JSON.stringify(e,null,2),"utf8")}function nS(n){let e=Date.now()-Kd;for(let[t,o]of Object.entries(n.patterns))new Date(o.lastSeen).getTime()<e&&delete n.patterns[t]}function eu(n,e){if(e.length===0)return!1;let t=xr(e),o=tS(n);nS(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 Yd(n,o),!1;s.count++,s.lastSeen=r;let i=s.count>=Vd;return i&&(s.promoted=!0),Yd(n,o),i}function xr(n){return[...n].sort().join("+")}function oS(n,e){if(!ha(e))return null;let t=xr(n);try{let o=Jd(e,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=ya(e,r.name,"SKILL.md");try{let a=Xd(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let l=a[1].split(`
|
|
15
|
-
`).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(xr(l)===t)return r.name}}catch{}}}catch{}return null}function rS(n){if(!ha(n))return 0;try{return Jd(n,{withFileTypes:!0}).filter(e=>e.isDirectory()&&ha(ya(n,e.name,"SKILL.md"))).length}catch{return 0}}function sS(n,e){return!(!n.ok||n.existingSkillName||!n.multiStep||n.toolCallCount<Ki||n.distinctToolCount<zi||Date.now()-Qd<qi||e?.projectSkillsDir&&(rS(e.projectSkillsDir)>=Vi||e.tools.length>0&&oS(e.tools,e.projectSkillsDir))||e?.projectRoot&&e.tools.length>0&&!eu(e.projectRoot,e.tools))}function iS(n){return n.existingSkillName?n.feedback==="negative":!1}function Rr(n,e){return iS(n)?{type:"skill.improve",skillName:n.existingSkillName,reason:"negative user feedback on existing skill execution"}:sS(n,e)?(Qd=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 Qd,eS,tu=N(()=>{"use strict";je();Qd=0,eS="skill-patterns.json"});function nu(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 aS(n){return n==="enabled-eligible"||n==="installed-awaiting-approval"}function lS(n){return new Map((n??[]).map(e=>[e.toolName,e]))}function cS(n){if(!n.eligibility?.length)return[...n.tools];let e=lS(n.eligibility);return n.tools.filter(t=>{let o=nu(t);if(!o)return!1;let r=e.get(o);return!r||aS(r.status)})}function dS(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 ba(n){let e=dS({toolChoice:n.toolChoice,thinkingEnabled:n.thinkingEnabled,compatibility:n.compatibility}),t=e.normalizedToolChoice,o=[...e.warnings],r=cS({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=>nu(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 ou=N(()=>{"use strict"});function ru(n){return n==null?[]:typeof n=="string"?n.length>0?[{type:"text",text:n}]:[]:Array.isArray(n)?n:[{type:"text",text:String(n)}]}function mS(n,e){return{...n,content:[...ru(n.content),...ru(e.content)]}}function fS(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 gS(n){return new Set((n??uS).map(e=>e.trim().toLowerCase()))}function hS(n,e){return n?gS(e).has(n.trim().toLowerCase()):!1}function ka(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=>fS(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]=mS(l,a);continue}i.push(a)}return i}function va(n,e){return hS(e?.stopReason,e?.forcedStopReasons)?n.map(t=>{if(t.role!=="assistant")return{...t};let o={...t};for(let r of pS)delete o[r];return o}):[...n]}function Sa(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 Ta(n,e){let t=ka(n),o=va(t,e);return Sa(o,e)}var uS,pS,wa=N(()=>{"use strict";uS=["stop","aborted","timeout","cancelled","interrupted","error"],pS=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function yS(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 bS(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 kS(n){return{round:n.round??0,maxRounds:n.maxRounds,pendingToolCallIds:[...n.pendingToolCallIds??[]],completedToolCallIds:[...n.completedToolCallIds??[]],lastStopReason:n.lastStopReason,replayMessages:[...n.replayMessages??[]]}}function xa(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=ka(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=va(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=Sa(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:kS({maxRounds:n.maxRounds,round:n.round,lastStopReason:n.lastStopReason,replayMessages:r,pendingToolCallIds:yS(r),completedToolCallIds:bS(r)}),recoveryActions:e}}var su=N(()=>{"use strict";wa()});function Ra(n){return n?vS.has(n):!0}function _a(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 vS,PM,vo,iu=N(()=>{"use strict";vS=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);PM={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};vo=class extends Error{constructor(t,o){super(`Model fallback triggered: ${t} -> ${o}`);this.originalModel=t;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Aa(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 Pa=N(()=>{"use strict";je()});function Ia(){return[...au]}function Cr(n){return au.find(e=>e.name===n)}var SS,TS,wS,xS,RS,_S,au,Ca=N(()=>{"use strict";SS={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},TS={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},wS={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},xS={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},RS={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},_S={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},au=[SS,TS,wS,xS,RS,_S]});var lu=N(()=>{"use strict"});function Ea(n){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:n.maxOutputTokens,consecutiveTruncations:0,aborted:n.abortSignal?.aborted??!1}}function Ma(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 Oa(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 Da(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 La(n,e){return n.aborted?!0:e.abortSignal?.aborted?(n.aborted=!0,!0):!1}var cu=N(()=>{"use strict"});function Na(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Un(n,e=AS){return!(n.attemptedThisTurn||n.consecutiveFailures>=e.maxConsecutiveFailures)}var AS,du=N(()=>{"use strict";AS={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var So=N(()=>{"use strict";Pd();$d();Ai();Ai();Gd();tu();ou();wa();su();iu();Pa();Ca();lu();cu();du()});function $a(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 uu=N(()=>{"use strict"});var pu=N(()=>{"use strict"});var mu=N(()=>{"use strict"});function Er(n){return typeof n.deleteVideoTask=="function"&&typeof n.listVideoTasks=="function"}var fu=N(()=>{"use strict"});function gu(n){let e=n.usage??n.data?.usage,t=sn(e?.completion_tokens)??sn(e?.completionTokens)??sn(e?.output_tokens)??sn(e?.outputTokens)??sn(e?.total_tokens)??sn(e?.totalTokens)??0,o=sn(e?.total_tokens)??sn(e?.totalTokens)??t;return{completionTokens:t,totalTokens:o,hasUsage:!!e,rawUsage:e}}function sn(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 ut,Mr=N(()=>{"use strict";ut=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
|
+
`).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(xr(l)===t)return r.name}}catch{}}}catch{}return null}function rS(n){if(!ha(n))return 0;try{return Jd(n,{withFileTypes:!0}).filter(e=>e.isDirectory()&&ha(ya(n,e.name,"SKILL.md"))).length}catch{return 0}}function sS(n,e){return!(!n.ok||n.existingSkillName||!n.multiStep||n.toolCallCount<Ki||n.distinctToolCount<zi||Date.now()-Qd<qi||e?.projectSkillsDir&&(rS(e.projectSkillsDir)>=Vi||e.tools.length>0&&oS(e.tools,e.projectSkillsDir))||e?.projectRoot&&e.tools.length>0&&!eu(e.projectRoot,e.tools))}function iS(n){return n.existingSkillName?n.feedback==="negative":!1}function Rr(n,e){return iS(n)?{type:"skill.improve",skillName:n.existingSkillName,reason:"negative user feedback on existing skill execution"}:sS(n,e)?(Qd=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 Qd,eS,tu=N(()=>{"use strict";je();Qd=0,eS="skill-patterns.json"});function nu(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 aS(n){return n==="enabled-eligible"||n==="installed-awaiting-approval"}function lS(n){return new Map((n??[]).map(e=>[e.toolName,e]))}function cS(n){if(!n.eligibility?.length)return[...n.tools];let e=lS(n.eligibility);return n.tools.filter(t=>{let o=nu(t);if(!o)return!1;let r=e.get(o);return!r||aS(r.status)})}function dS(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 ba(n){let e=dS({toolChoice:n.toolChoice,thinkingEnabled:n.thinkingEnabled,compatibility:n.compatibility}),t=e.normalizedToolChoice,o=[...e.warnings],r=cS({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=>nu(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 ou=N(()=>{"use strict"});function ru(n){return n==null?[]:typeof n=="string"?n.length>0?[{type:"text",text:n}]:[]:Array.isArray(n)?n:[{type:"text",text:String(n)}]}function mS(n,e){return{...n,content:[...ru(n.content),...ru(e.content)]}}function fS(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 gS(n){return new Set((n??uS).map(e=>e.trim().toLowerCase()))}function hS(n,e){return n?gS(e).has(n.trim().toLowerCase()):!1}function ka(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=>fS(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]=mS(l,a);continue}i.push(a)}return i}function va(n,e){return hS(e?.stopReason,e?.forcedStopReasons)?n.map(t=>{if(t.role!=="assistant")return{...t};let o={...t};for(let r of pS)delete o[r];return o}):[...n]}function Sa(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 Ta(n,e){let t=ka(n),o=va(t,e);return Sa(o,e)}var uS,pS,wa=N(()=>{"use strict";uS=["stop","aborted","timeout","cancelled","interrupted","error"],pS=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"]});function yS(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 bS(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 kS(n){return{round:n.round??0,maxRounds:n.maxRounds,pendingToolCallIds:[...n.pendingToolCallIds??[]],completedToolCallIds:[...n.completedToolCallIds??[]],lastStopReason:n.lastStopReason,replayMessages:[...n.replayMessages??[]]}}function xa(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=ka(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=va(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=Sa(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:kS({maxRounds:n.maxRounds,round:n.round,lastStopReason:n.lastStopReason,replayMessages:r,pendingToolCallIds:yS(r),completedToolCallIds:bS(r)}),recoveryActions:e}}var su=N(()=>{"use strict";wa()});function Ra(n){return n?vS.has(n):!0}function _a(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 vS,CM,vo,iu=N(()=>{"use strict";vS=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);CM={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};vo=class extends Error{constructor(t,o){super(`Model fallback triggered: ${t} -> ${o}`);this.originalModel=t;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel}});function Aa(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 Pa=N(()=>{"use strict";je()});function Ia(){return[...au]}function Cr(n){return au.find(e=>e.name===n)}var SS,TS,wS,xS,RS,_S,au,Ca=N(()=>{"use strict";SS={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},TS={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},wS={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},xS={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},RS={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},_S={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},au=[SS,TS,wS,xS,RS,_S]});var lu=N(()=>{"use strict"});function Ea(n){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:n.maxOutputTokens,consecutiveTruncations:0,aborted:n.abortSignal?.aborted??!1}}function Ma(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 Oa(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 Da(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 La(n,e){return n.aborted?!0:e.abortSignal?.aborted?(n.aborted=!0,!0):!1}var cu=N(()=>{"use strict"});function Na(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Un(n,e=AS){return!(n.attemptedThisTurn||n.consecutiveFailures>=e.maxConsecutiveFailures)}var AS,du=N(()=>{"use strict";AS={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50}});var So=N(()=>{"use strict";Pd();$d();Ai();Ai();Gd();tu();ou();wa();su();iu();Pa();Ca();lu();cu();du()});function $a(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 uu=N(()=>{"use strict"});var pu=N(()=>{"use strict"});var mu=N(()=>{"use strict"});function Er(n){return typeof n.deleteVideoTask=="function"&&typeof n.listVideoTasks=="function"}var fu=N(()=>{"use strict"});function gu(n){let e=n.usage??n.data?.usage,t=sn(e?.completion_tokens)??sn(e?.completionTokens)??sn(e?.output_tokens)??sn(e?.outputTokens)??sn(e?.total_tokens)??sn(e?.totalTokens)??0,o=sn(e?.total_tokens)??sn(e?.totalTokens)??t;return{completionTokens:t,totalTokens:o,hasUsage:!!e,rawUsage:e}}function sn(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 ut,Mr=N(()=>{"use strict";ut=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(`
|
|
16
16
|
`))!==-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=gu(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=gu(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 Ua}from"node:path";import{homedir as IS,tmpdir as CS}from"node:os";function hu(){return process.env.QLOGICAGENT_HOME??Ua(IS()||CS(),".qlogicagent")}function Bt(){return process.env.QLOGICAGENT_CACHE_DIR??Ua(hu(),"cache")}function yu(){return process.env.QLOGICAGENT_DEBUG_LOG_DIR??Ua(hu(),"debug-logs")}var jn=N(()=>{"use strict"});import{writeFileSync as ES,mkdirSync as MS}from"node:fs";import{join as bu}from"node:path";import{randomUUID as OS}from"node:crypto";var DS,To,ja=N(()=>{"use strict";jn();DS=18e4,To=class{supportedTypes=["image","tts"];baseUrl;timeoutMs;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.timeoutMs=e.timeoutMs??DS}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=bu(Bt(),"tts");MS(d,{recursive:!0});let u=`openai-tts-${OS()}.mp3`,p=bu(d,u);return ES(p,c),{mediaUrls:[`file://${p}`],model:e.model||"tts-1",durationMs:Date.now()-r,billingUnit:"per_character",billingQuantity:s.length}}}});var bn,Or=N(()=>{"use strict";bn=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 LS,mkdirSync as NS}from"node:fs";import{join as ku}from"node:path";import{randomUUID as $S}from"node:crypto";async function Fa(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=US(d,48e3,2,16),p=ku(Bt(),"gemini-music-realtime");NS(p,{recursive:!0});let m=`lyria-rt-${$S()}.wav`,h=ku(p,m);return LS(h,u),t.onProgress?.(100,"completed"),{filePath:`file://${h}`,durationMs:Date.now()-r}}finally{s.close()}}function US(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,Ba=N(()=>{"use strict";jn();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 vu,mkdirSync as Su}from"node:fs";import{join as Lr}from"node:path";import{randomUUID as Tu}from"node:crypto";function BS(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 jS,FS,Wa,wo,Ga=N(()=>{"use strict";jn();Ba();jS=18e4,FS=1e4,Wa=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??jS}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 Fa(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()+Wa;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-Wa),u=Math.min(95,Math.round(d/Wa*100));r?.(u,"running",s),await new Promise(p=>setTimeout(p,FS))}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(Bt(),"gemini-images");Su(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-${Tu()}.${i}`,l=Lr(o,a);vu(l,Buffer.from(s.inlineData.data,"base64")),t.push(`file://${l}`)}return t}extractInlineAudio(e,t){let o=[],r=Lr(Bt(),t);Su(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"?BS(l,24e3,1,16):l,d=`gemini-${Tu()}.${a==="pcm"?"wav":a}`,u=Lr(r,d);vu(u,c),o.push(`file://${u}`)}return o}}});function WS(n){return new Promise(e=>setTimeout(e,n))}var Nr,wu=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 WS(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 GS,mkdirSync as HS}from"node:fs";import{join as xu}from"node:path";import{randomUUID as VS}from"node:crypto";function YS(n,e){return/^(https?:|data:)/i.test(n)?n:`data:${typeof e?.mimeType=="string"?e.mimeType:"application/pdf"};base64,${n}`}var KS,zS,$r,qS,xo,Ru=N(()=>{"use strict";jn();KS=18e4,zS=3e3,$r=6e5,qS=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??KS}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 qS.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=xu(Bt(),"tts");HS(d,{recursive:!0});let u=e.audioFormat??"wav",p=`zhipu-tts-${VS()}.${u}`,m=xu(d,p);return GS(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:YS(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,zS))}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 XS(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 JS(n,e){return!("operations"in n)||!n.operations?!0:n.operations.includes(e)}function QS(n){let e=n.baseUrl;switch(n.id){case"volcengine":return new ut({baseUrl:e});case"openai":return new To({baseUrl:e});case"minimax":return new bn({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,_u=N(()=>{"use strict";Mr();ja();Or();Ga();wu();Ru();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=QS(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?XS(o):void 0,a=s.find(l=>l.mediaType!==t?!1:!i||!l.mediaCapabilities?!0:JS(l.mediaCapabilities,i));if(a)return{providerId:e,providerDef:r,modelInfo:a,mediaType:t}}}});var Ha,Va=N(()=>{"use strict";Ha=[{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 ZS,kn,Au=N(()=>{"use strict";Va();ZS={claude:"anthropic",gemini:"google",doubao:"volcengine"},kn=class{builtins=new Map;overrides=new Map;constructor(){for(let e of Ha)this.builtins.set(e.id,e)}applyOverride(e,t){this.overrides.set(e,{...this.overrides.get(e),...t})}getProvider(e){let t=ZS[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 eT(n){if(n)return n==="openai"?"openai-chat":n==="anthropic"?"anthropic-messages":n}function tT(n,e){return Pu(n.id,e)?"exact":(n.aliases??[]).some(t=>Pu(t,e))?"alias":void 0}function Pu(n,e){return n.trim().toLowerCase()===e.trim().toLowerCase()}function nT(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 oT(n){return n==="coding-plan"||n==="media-plan"?"plan":"paygo"}function rT(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 sT(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 iT(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,Iu=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=eT(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=tT(l,t);if(!c)continue;let d=rT(a,l);if(s.some(f=>!d.includes(f)))continue;let u=nT(a,l),p=a.billingChannelKind??oT(u),m=iT({matchKind:c,requestedTransport:r,requiredCapabilities:s,preferProviderId:e.userPreference?.preferProviderId,preferVariantKind:e.userPreference?.preferVariantKind,purpose:e.purpose,provider:a,variantKind:u,capabilities:d}),h=sT({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 Fn=N(()=>{"use strict"});function lT(n){let e=n.slice(n.lastIndexOf(".")).toLowerCase();return aT[e]||"application/octet-stream"}function dT(n){return cT.test(n)}async function Cu(n,e,t,o){if(n.startsWith("data:")||!dT(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=uT(n),a=r.headers.get("content-type")||lT(i);return(await e.uploadFile(s,i,a,t,o)).url}function uT(n){try{let t=new URL(n).pathname.split("/").pop();return t&&t.includes(".")?t:"upload"}catch{return"upload"}}var aT,cT,Eu=N(()=>{"use strict";aT={".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"};cT=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i});function z(n){return pT.test(n)}async function pt(n,e){return Cu(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>mT)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||fT(n)};base64,${o.toString("base64")}`}function fT(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 pT,mT,Bn=N(()=>{"use strict";Eu();pT=/^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0|\[::1\])(:\d+)?/i;mT=20*1024*1024});function Pt(n){let e=Math.min(1e3*Math.pow(2,n-1),3e4),t=Math.random()*.25*e;return e+t}function Wt(n){return n!=null&&Ka.has(n)}function It(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 Gt(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 Ka,At,Wn=N(()=>{"use strict";Ka=new Set([429,529,502,503,504]),At=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 za=N(()=>{"use strict"});function gT(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 hT(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)?pt(a,{uploadAdapter:e,apiKey:t,signal:o}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):n}function yT(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 Gn,qa=N(()=>{"use strict";Fn();Bn();Wn();za();Gn=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:yT(await hT(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 It(Pt(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(!Wt(Gt(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()},At)};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(`
|
|
17
17
|
`))!==-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:gT(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(`
|
|
18
18
|
`))!==-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 bT(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)?pt(a,{uploadAdapter:e,apiKey:t,signal:o}):Promise.resolve(a)))}return Object.keys(i).length>0?{...s,...i}:s})):n}function kT(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,Mu=N(()=>{"use strict";Fn();Bn();Wn();za();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 It(Pt(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(!Wt(Gt(l))&&!u||c===2)throw l}}}async buildRequestBody(e,t,o){let r={model:e.model,input:kT(await bT(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()},At)};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(`
|
|
@@ -40,21 +40,21 @@ ${s.executableCode.code}
|
|
|
40
40
|
...
|
|
41
41
|
`:`
|
|
42
42
|
`,e+=iw,e}async function ep(n,e,t,o=Bi){if(n.length<=o||Ju(n))return n;let r=await Qu(n,e,t);return r?Zu(r):n.slice(0,o)+`
|
|
43
|
-
...[truncated ${n.length-o} chars]`}function dw(n){let e=[],t=[];for(let o of n)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?Ju(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 uw(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 pw(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 tp(n,e,t,o=Wi){let r=dw(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}=uw(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?pw(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 Qu(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=Zu(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 sw,qu,iw,ol=N(()=>{"use strict";je();sw="tool-results",qu="<persisted-output>",iw="</persisted-output>"});function gw(n){try{return JSON.parse(n)}catch{return}}var mw,fw,zr,np=N(()=>{"use strict";So();ol();mw=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),fw=new Set(["bash","execute_command","Bash","shell"]),zr=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??mw,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:on(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:gw(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:on(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 ep(y,e.id,a));let b=on(e.id,{ok:f,payload:y,error:m.error,toolReferences:m.toolReferences,imageUrls:m.imageUrls});f||(u=!0,fw.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 hw}from"node:os";import{join as Ae}from"node:path";import{existsSync as yw}from"node:fs";function H(){return process.env.QLOGICAGENT_HOME||Ae(hw(),He)}function op(){return Ae(H(),"plugins")}function Vt(){return Ae(H(),"skills")}function mt(){return Ae(H(),"settings.json")}function rp(){return Ae(H(),"plugin-cache")}function sp(){return Ae(H(),"mcp.json")}function ip(){return Ae(H(),"marketplace.json")}function ap(){return Ae(H(),"workflows")}function lp(){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 cp(n){return Ae(Oe(n),"workflows")}function Ct(n){return Ae(Oe(n),"skills")}function Mo(n){return Ae(Oe(n),"INSTRUCTIONS.md")}function Hn(n){return Ae(Oe(n),"rules")}function Kt(n){return Ae(Oe(n),"sessions")}function dp(n,e){let t=Ae(Oe(n),"checkpoints");return e?Ae(t,e):t}function up(n){return Ae(n,He,"hooks")}function pp(n,e){return n.filter(t=>t!==e&&yw(Ae(t,He,"skills")))}var He,le=N(()=>{"use strict";He=".qlogicagent"});var qr,mp=N(()=>{"use strict";qr=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 fp={};mn(fp,{ALL_PURPOSES:()=>Do,ModelRegistry:()=>Yr,deriveModelPurposes:()=>kw,getModelRegistry:()=>X,resetModelRegistry:()=>bw});import*as tt from"node:fs";function X(){return Oo||(Oo=new Yr,Oo.load()),Oo}function bw(){Oo=null}function kw(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 vw(n){switch(n){case"openai-chat":case"openai-responses":case"anthropic-messages":case"volcengine-responses":return n;default:return}}var Do,Yr,Oo,ft=N(()=>{"use strict";Sn();le();mp();Do=["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"],Yr=class{keyPool;coreProviderRegistry=new kn;providerVariantResolver=new _o(this.coreProviderRegistry);models=new Map;modelEnabledOverrides=new Map;bindings={};settingsPath;changeListeners=[];constructor(e){this.settingsPath=mt(),this.keyPool=new qr(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 Do){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{tt.existsSync(this.settingsPath)&&(e=JSON.parse(tt.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(/[/\\][^/\\]+$/,"");tt.existsSync(o)||tt.mkdirSync(o,{recursive:!0}),tt.writeFileSync(this.settingsPath,JSON.stringify(t,null,2),"utf-8")}load(){try{if(!tt.existsSync(this.settingsPath))return!1;let e=tt.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(!tt.existsSync(this.settingsPath))return;let t=tt.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:vw(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{}}},Oo=null});import{readFile as Sw}from"node:fs/promises";function Tn(n){let e=typeof n.content=="string"?n.content:n.content!=null?JSON.stringify(n.content):"";return Math.ceil(e.length/4)}function wn(n){let e=0;for(let t of n)e+=Tn(t);return e}function hp(n){if(!n)return 128e3;if(n in rl)return rl[n];let e=n.toLowerCase();for(let[t,o]of Object.entries(rl))if(e.startsWith(t.toLowerCase()))return o;return 128e3}function ww(){return X().resolveModelForPurpose("textGeneration")??Tw}function bp(){return il}function xw(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"),sl(t);try{let i="",a=e?.model??ww();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"),sl(t))}catch(i){return n.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),sl(t)}}}function sl(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(`
|
|
44
|
-
`)}function Rw(){return Ti(new yn(al),new rn(20,Tn),new Nn(Tn))}function gp(n,e){let t=wi(new yn(al),new rn(20,Tn),new fo({protectedHeadExchanges:1,protectedTailMessages:8,summarize:n,estimateTokens:Tn}),new Nn(Tn));return new go({inner:t,estimateTokens:Tn,onCacheInvalidated:e?.onCacheInvalidated})}function kp(n,e){let t=e?.budget??vr({modelContextWindow:hp(e?.model)}),r=(e?.pipeline??Rw()).compress(n,t);if(r.droppedCount>0){let s=wn(n),i=wn(r.messages);yp.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&&ll?.(r.droppedCount,wn(r.messages)),r}async function _w(n,e,t){let o=t??vr({modelContextWindow:hp(e.model)}),r=wn(n),s=ko(r,o),i;switch(s){case"none":i={messages:n,droppedCount:0,strategy:"none"};break;case"trim-only":i=new yn(al).compress(n,o);break;case"sliding-window":{i=await gp(e.summarize).compressAsync(n,o);break}case"llm-summarize":{let a=e.pipeline??gp(e.summarize);i=bo(a)?await a.compressAsync(n,o):a.compress(n,o);break}}return i.droppedCount>0&&(i={...i,messages:await Ri(i.messages,n,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await Sw(a,"utf-8")}catch{return null}}})}),Aw(n,i,o),i}function Aw(n,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let o=e.metrics?.tokensBefore||wn(n),r=e.metrics?.tokensAfter||wn(e.messages);yp.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||wn(e.messages);ll?.(e.droppedCount,o)}}function Pw(n,e){let t=xw(n,e),o={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return _w(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};il.register(o),il.activate(o.id),n.info(`[context-compression] registered context engine: ${o.id}`)}function vp(n,e,t){Pw(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"}}}),ll=(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 rl,al,Tw,yp,il,ll,cl=N(()=>{"use strict";So();ft();rl={"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};al=8e3,Tw="deepseek-v4-flash";yp=new ho(200),il=new yo;ll=null});function Sp(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 Tp=N(()=>{"use strict"});var wp={};mn(wp,{resolveToolEligibility:()=>Ow});function Cw(n,e){if(Iw.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 Ew(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||Cw(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function Mw(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 Ow(n,e={}){let t=new Map,o=[],r=[],s=[];for(let i of n){let a=i.function.name,{level:l,reasons:c}=Ew(i,e),d=Mw(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 Iw,xp=N(()=>{"use strict";Iw=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function $w(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 Uw(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 Bw(n){if(!Fw.has(n.toolName))return!1;let e=typeof n.message?.content=="string"?n.message.content.trim():"";return e.length>0&&e.length<200&&jw.test(e)}function Rp(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 Ww(n){return typeof n=="number"&&Number.isFinite(n)&&n>=1?Math.min(Math.round(n),100):Ei}function _p(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 Gw(n){return n==="length"||n==="max_tokens"}function Ap(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 Hw(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 Vw(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 Kw(n){return n.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Pp(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(()=>(xp(),wp)),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*zw(r,l,i,c,d,p,e,o);return}let x=Ww(n.maxRounds),I={contextWindowTokens:n.contextWindowTokens??Di,responseBufferTokens:Li,maxOutputTokens:n.maxOutputTokens??Ni,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:Ea(I),reactiveCompactState:Na(),toolLoopState:Ar({maxRounds:x,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Pi(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:Yu(),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||Lo(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(La(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=Ma(Q,I);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&Un(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 tp(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=_i(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 rn().compress(he,0);E.droppedCount>0&&(he=E.messages,o.info(`microcompact: cleared ${E.droppedCount} old tool results`))}if(he=Ii(he,F).messages,Q.promptTokens>0){let A=I.contextWindowTokens*.75,E=bp().getActive(),L;E?L=await E.compressAsync(he,A,{model:S.currentModel,sessionId:s}):L=kp(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=Kw(he);let jt=ba({tools:$,toolChoice:n.toolChoice??"auto"}),g=Ar({maxRounds:x,replayMessages:he,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),v=jt.extraSystemPrompt?[{role:"system",content:jt.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:jt.tools,toolChoice:jt.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,$a(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 vo&&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>$n){o.info(`stale connection retry limit reached (${$n}), 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=Vw({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(_a(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>=Hi&&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 at=Math.min(ye,Gi);await new Promise(hi=>setTimeout(hi,at)),ye-=at}S={...S,transition:void 0};continue}if(Ra(f)){let ye=Hw({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(at=>setTimeout(at,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(_p(M))V=!0,o.info(`withheld prompt_too_long error (status=${M.status})`);else if(Ap(M))V=!0,o.info(`withheld media_size error (status=${M.status})`);else{let A=Oa({status:M.status??500,message:M.message},Q,I);if(A.action==="reactive_compact"&&Un(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>$n){o.info(`API retry limit reached (${$n}), aborting`);let G=Ln(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=Ln(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&&_p(M)){if(S.transition?.reason!=="collapse_drain_retry"){let L=Ci(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(Un(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&&Ap(M)){if(Un(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(Gw(U)){Q.consecutiveTruncations+=1;let L=n.modelMaxOutputTokens??$i,G=Da(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:ji,transition:{reason:"max_output_tokens_escalate"}};continue}if(ve<Ui){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>=Fi&&re<Tr&&S.lastBudgetDeltaTokens<Tr;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:Sp(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 at={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,at,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 at=[...j].reverse().find(hi=>hi.role==="tool");at&&typeof at.content=="string"&&(at.content+=`
|
|
43
|
+
...[truncated ${n.length-o} chars]`}function dw(n){let e=[],t=[];for(let o of n)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?Ju(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 uw(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 pw(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 tp(n,e,t,o=Wi){let r=dw(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}=uw(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?pw(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 Qu(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=Zu(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 sw,qu,iw,ol=N(()=>{"use strict";je();sw="tool-results",qu="<persisted-output>",iw="</persisted-output>"});function gw(n){try{return JSON.parse(n)}catch{return}}var mw,fw,zr,np=N(()=>{"use strict";So();ol();mw=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),fw=new Set(["bash","execute_command","Bash","shell"]),zr=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(e){this.config=e,this.concurrencySafe=e.concurrencySafeTools??mw,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:on(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:gw(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:on(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 ep(y,e.id,a));let b=on(e.id,{ok:f,payload:y,error:m.error,toolReferences:m.toolReferences,imageUrls:m.imageUrls});f||(u=!0,fw.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 hw}from"node:os";import{join as Ae}from"node:path";import{existsSync as yw}from"node:fs";function H(){return process.env.QLOGICAGENT_HOME||Ae(hw(),He)}function op(){return Ae(H(),"plugins")}function Vt(){return Ae(H(),"skills")}function mt(){return Ae(H(),"settings.json")}function rp(){return Ae(H(),"plugin-cache")}function sp(){return Ae(H(),"mcp.json")}function ip(){return Ae(H(),"marketplace.json")}function ap(){return Ae(H(),"workflows")}function lp(){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 cp(n){return Ae(Oe(n),"workflows")}function Ct(n){return Ae(Oe(n),"skills")}function Mo(n){return Ae(Oe(n),"INSTRUCTIONS.md")}function Hn(n){return Ae(Oe(n),"rules")}function Kt(n){return Ae(Oe(n),"sessions")}function dp(n,e){let t=Ae(Oe(n),"checkpoints");return e?Ae(t,e):t}function up(n){return Ae(n,He,"hooks")}function pp(n,e){return n.filter(t=>t!==e&&yw(Ae(t,He,"skills")))}var He,le=N(()=>{"use strict";He=".qlogicagent"});var qr,mp=N(()=>{"use strict";qr=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 fp={};mn(fp,{ALL_PURPOSES:()=>Do,ModelRegistry:()=>Yr,deriveModelPurposes:()=>kw,getModelRegistry:()=>X,resetModelRegistry:()=>bw});import*as tt from"node:fs";function X(){return Oo||(Oo=new Yr,Oo.load()),Oo}function bw(){Oo=null}function kw(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 vw(n){switch(n){case"openai-chat":case"openai-responses":case"anthropic-messages":case"volcengine-responses":return n;default:return}}function Sw(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 vw(e)}}function Tw(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 Do,Yr,Oo,ft=N(()=>{"use strict";Sn();le();mp();Do=["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"],Yr=class{keyPool;coreProviderRegistry=new kn;providerVariantResolver=new _o(this.coreProviderRegistry);models=new Map;modelEnabledOverrides=new Map;bindings={};settingsPath;changeListeners=[];constructor(e){this.settingsPath=mt(),this.keyPool=new qr(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 Do){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{tt.existsSync(this.settingsPath)&&(e=JSON.parse(tt.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(/[/\\][^/\\]+$/,"");tt.existsSync(o)||tt.mkdirSync(o,{recursive:!0}),tt.writeFileSync(this.settingsPath,JSON.stringify(t,null,2),"utf-8")}load(){try{if(!tt.existsSync(this.settingsPath))return!1;let e=tt.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(!tt.existsSync(this.settingsPath))return;let t=tt.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:Sw(t,e.transport),capabilities:Tw(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{}}},Oo=null});import{readFile as ww}from"node:fs/promises";function Tn(n){let e=typeof n.content=="string"?n.content:n.content!=null?JSON.stringify(n.content):"";return Math.ceil(e.length/4)}function wn(n){let e=0;for(let t of n)e+=Tn(t);return e}function hp(n){if(!n)return 128e3;if(n in rl)return rl[n];let e=n.toLowerCase();for(let[t,o]of Object.entries(rl))if(e.startsWith(t.toLowerCase()))return o;return 128e3}function Rw(){return X().resolveModelForPurpose("textGeneration")??xw}function bp(){return il}function _w(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"),sl(t);try{let i="",a=e?.model??Rw();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"),sl(t))}catch(i){return n.warn({err:i.message},"[context-compression] summarize call error \u2014 using fallback"),sl(t)}}}function sl(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(`
|
|
44
|
+
`)}function Aw(){return Ti(new yn(al),new rn(20,Tn),new Nn(Tn))}function gp(n,e){let t=wi(new yn(al),new rn(20,Tn),new fo({protectedHeadExchanges:1,protectedTailMessages:8,summarize:n,estimateTokens:Tn}),new Nn(Tn));return new go({inner:t,estimateTokens:Tn,onCacheInvalidated:e?.onCacheInvalidated})}function kp(n,e){let t=e?.budget??vr({modelContextWindow:hp(e?.model)}),r=(e?.pipeline??Aw()).compress(n,t);if(r.droppedCount>0){let s=wn(n),i=wn(r.messages);yp.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&&ll?.(r.droppedCount,wn(r.messages)),r}async function Pw(n,e,t){let o=t??vr({modelContextWindow:hp(e.model)}),r=wn(n),s=ko(r,o),i;switch(s){case"none":i={messages:n,droppedCount:0,strategy:"none"};break;case"trim-only":i=new yn(al).compress(n,o);break;case"sliding-window":{i=await gp(e.summarize).compressAsync(n,o);break}case"llm-summarize":{let a=e.pipeline??gp(e.summarize);i=bo(a)?await a.compressAsync(n,o):a.compress(n,o);break}}return i.droppedCount>0&&(i={...i,messages:await Ri(i.messages,n,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await ww(a,"utf-8")}catch{return null}}})}),Iw(n,i,o),i}function Iw(n,e,t){if(e.droppedCount>0||e.metrics?.usedLlm){let o=e.metrics?.tokensBefore||wn(n),r=e.metrics?.tokensAfter||wn(e.messages);yp.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||wn(e.messages);ll?.(e.droppedCount,o)}}function Cw(n,e){let t=_w(n,e),o={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(r,s,i){return Pw(r,{budget:s,model:i?.model,sessionId:i?.sessionId,summarize:t},s)}};il.register(o),il.activate(o.id),n.info(`[context-compression] registered context engine: ${o.id}`)}function vp(n,e,t){Cw(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"}}}),ll=(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 rl,al,xw,yp,il,ll,cl=N(()=>{"use strict";So();ft();rl={"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};al=8e3,xw="deepseek-v4-flash";yp=new ho(200),il=new yo;ll=null});function Sp(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 Tp=N(()=>{"use strict"});var wp={};mn(wp,{resolveToolEligibility:()=>Lw});function Mw(n,e){if(Ew.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 Ow(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||Mw(t,e.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function Dw(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 Lw(n,e={}){let t=new Map,o=[],r=[],s=[];for(let i of n){let a=i.function.name,{level:l,reasons:c}=Ow(i,e),d=Dw(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 Ew,xp=N(()=>{"use strict";Ew=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function jw(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 Fw(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 Gw(n){if(!Ww.has(n.toolName))return!1;let e=typeof n.message?.content=="string"?n.message.content.trim():"";return e.length>0&&e.length<200&&Bw.test(e)}function Rp(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 Hw(n){return typeof n=="number"&&Number.isFinite(n)&&n>=1?Math.min(Math.round(n),100):Ei}function _p(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 Vw(n){return n==="length"||n==="max_tokens"}function Ap(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 Kw(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 zw(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 qw(n){return n.filter(e=>e.role!=="assistant"?!0:!(typeof e.content=="string"&&e.content.trim()===""))}async function*Pp(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(()=>(xp(),wp)),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*Yw(r,l,i,c,d,p,e,o);return}let x=Hw(n.maxRounds),I={contextWindowTokens:n.contextWindowTokens??Di,responseBufferTokens:Li,maxOutputTokens:n.maxOutputTokens??Ni,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:Ea(I),reactiveCompactState:Na(),toolLoopState:Ar({maxRounds:x,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Pi(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:Yu(),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||Lo(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(La(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=Ma(Q,I);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&Un(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 tp(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=_i(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 rn().compress(he,0);E.droppedCount>0&&(he=E.messages,o.info(`microcompact: cleared ${E.droppedCount} old tool results`))}if(he=Ii(he,F).messages,Q.promptTokens>0){let A=I.contextWindowTokens*.75,E=bp().getActive(),L;E?L=await E.compressAsync(he,A,{model:S.currentModel,sessionId:s}):L=kp(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=qw(he);let jt=ba({tools:$,toolChoice:n.toolChoice??"auto"}),g=Ar({maxRounds:x,replayMessages:he,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),v=jt.extraSystemPrompt?[{role:"system",content:jt.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:jt.tools,toolChoice:jt.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,$a(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 vo&&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>$n){o.info(`stale connection retry limit reached (${$n}), 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=zw({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(_a(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>=Hi&&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 at=Math.min(ye,Gi);await new Promise(hi=>setTimeout(hi,at)),ye-=at}S={...S,transition:void 0};continue}if(Ra(f)){let ye=Kw({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(at=>setTimeout(at,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(_p(M))V=!0,o.info(`withheld prompt_too_long error (status=${M.status})`);else if(Ap(M))V=!0,o.info(`withheld media_size error (status=${M.status})`);else{let A=Oa({status:M.status??500,message:M.message},Q,I);if(A.action==="reactive_compact"&&Un(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>$n){o.info(`API retry limit reached (${$n}), aborting`);let G=Ln(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=Ln(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&&_p(M)){if(S.transition?.reason!=="collapse_drain_retry"){let L=Ci(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(Un(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&&Ap(M)){if(Un(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(Vw(U)){Q.consecutiveTruncations+=1;let L=n.modelMaxOutputTokens??$i,G=Da(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:ji,transition:{reason:"max_output_tokens_escalate"}};continue}if(ve<Ui){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>=Fi&&re<Tr&&S.lastBudgetDeltaTokens<Tr;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:Sp(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 at={role:"assistant",content:S.finalText,...ee.length>0&&{thinkingBlocks:[...ee]}};S={...S,messages:[...j,at,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 at=[...j].reverse().find(hi=>hi.role==="tool");at&&typeof at.content=="string"&&(at.content+=`
|
|
45
45
|
|
|
46
|
-
\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=Rr(L,{tools:[...P],projectRoot:n.projectRoot});G&&(yield{type:"skill_instruction",turnId:r,instruction:G})}let E=S.finalText||Lo(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(ki(me,S.finalText||void 0,ee.length>0?ee:void 0,Ge)),B=xa(B,{replayMessages:j,pendingToolCallIds:me.map(A=>A.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Me=S.identicalCallCounts,nn=[],ge=[],Ft=!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>Oi?(ge.push(A),Ft||(Ft=!0,o.info(`AP4 blocked: ${A.function.name} repeated ${L+1}x`))):nn.push(A)}let Rt=[];for(let A of ge){let E=Me.get(`${A.function.name}::${A.function.arguments}`),L=Rp(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=on(A.id,{ok:!1,error:G});j.push(re),Rt.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=Rp(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=[],fi=[];for(let A of nn)(S.toolFailureCounts.get(A.function.name)??0)>=Sr?fi.push(A):Ke.push(A);if(fi.length>0){for(let E of fi){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=on(E.id,{ok:!1,error:G});j.push(re),Rt.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 Hk=new Map(S.toolFailureCounts);try{let A=new zr({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),Rt.push(E.callId),P.add(E.toolName),O++;let L=E.ok&&
|
|
46
|
+
\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=Rr(L,{tools:[...P],projectRoot:n.projectRoot});G&&(yield{type:"skill_instruction",turnId:r,instruction:G})}let E=S.finalText||Lo(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(ki(me,S.finalText||void 0,ee.length>0?ee:void 0,Ge)),B=xa(B,{replayMessages:j,pendingToolCallIds:me.map(A=>A.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Me=S.identicalCallCounts,nn=[],ge=[],Ft=!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>Oi?(ge.push(A),Ft||(Ft=!0,o.info(`AP4 blocked: ${A.function.name} repeated ${L+1}x`))):nn.push(A)}let Rt=[];for(let A of ge){let E=Me.get(`${A.function.name}::${A.function.arguments}`),L=Rp(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=on(A.id,{ok:!1,error:G});j.push(re),Rt.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=Rp(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=[],fi=[];for(let A of nn)(S.toolFailureCounts.get(A.function.name)??0)>=Sr?fi.push(A):Ke.push(A);if(fi.length>0){for(let E of fi){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=on(E.id,{ok:!1,error:G});j.push(re),Rt.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 Hk=new Map(S.toolFailureCounts);try{let A=new zr({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),Rt.push(E.callId),P.add(E.toolName),O++;let L=E.ok&&Gw(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 at=S.fileReadCounts.get(ye)??0;S.fileReadCounts.set(ye,at+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(Uw.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:jw(ye),title:ye.split(/[\\/]/).pop()||ye,filePath:ye,language:Fw(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>=Sr&&(Hk.get(A)??0)<Sr&&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,...Rt],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 Vk=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(Vk){if(mo+=1,mo>=Mi){let A=S.finalText||Lo(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 Kk=3,Ad=[...S.fileReadCounts.entries()].filter(([,A])=>A>=Kk);if(Ad.length>0){let A=Ad.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 gi=ne+1;if(h>0&&gi>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||Lo(j,o);yield{type:"end",turnId:r,content:A,usage:S.totalUsage,model:S.currentModel};return}if(gi>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=Rr(E,{tools:[...P],projectRoot:n.projectRoot});L&&(yield{type:"skill_instruction",turnId:r,instruction:L})}let A=S.finalText||Lo(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:gi,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 Lo(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(`
|
|
47
47
|
|
|
48
|
-
`)):""}async function*
|
|
48
|
+
`)):""}async function*Yw(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 Uw,Bw,Ww,Ip=N(()=>{"use strict";Sn();So();np();cl();Tp();ol();je();Uw=new Set(["write","edit","patch","apply_patch"]);Bw=/^no (matches|files|results) found\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Ww=new Set(["search","grep","glob","find","list","read","exec"])});function Cp(n){if(!n||n.length<5)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};let e=[];for(let[r,s]of Object.entries(Xw)){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 dl(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 Ep(n){let e=n.replace(/\.md$/,"").toLowerCase();for(let[t,o]of Object.entries(Qw))if(e.startsWith(t+"-")||e.startsWith(t+"_")||e===t)return o;return null}var Xw,Jw,Qw,ul=N(()=>{"use strict";Xw={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:[]}};Qw={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 Op={};mn(Op,{Agent:()=>No});var No,pl=N(()=>{"use strict";So();Ip();je();ul();ft();No=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=Ta(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=Cp(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(`
|
|
49
49
|
`);d.splice(i?1:0,0,{role:"system",content:`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
50
|
-
${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 Pp(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=Ln(f,h);this.log.error(`turn ${o} error [${y}, retryable=${Si(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 nd}from"node:crypto";import sr from"node:fs";import Xh from"node:path";function
|
|
50
|
+
${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 Pp(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=Ln(f,h);this.log.error(`turn ${o} error [${y}, retryable=${Si(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 nd}from"node:crypto";import sr from"node:fs";import Xh from"node:path";function bE(n){return td.find(e=>e.id===n)}function kE(n,e,t){let o=bE(t);if(o)return o;let r=td.filter(a=>a.rarity===e);if(r.length===0)return td[0];let i=nd("sha256").update(`breed-${n}`).digest()[0]%r.length;return r[i]}function vE(n){let t=nd("sha256").update(n).digest()[0]%100,o=0;for(let r=0;r<Jh.length;r++)if(o+=Jh[r],t<o)return yE[r];return"common"}function SE(n){let e=nd("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 yE,Jh,td,Ut,Qh=N(()=>{"use strict";yE=["common","uncommon","rare","epic","legendary"],Jh=[50,25,15,8,2],td=[{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"}];Ut=class{constructor(e){this.workspaceDir=e;this.storagePath=Xh.join(e,".qlogicagent","pet","soul.json")}workspaceDir;soul=null;storagePath;load(){if(this.soul)return this.soul;if(!sr.existsSync(this.storagePath))return null;try{let e=JSON.parse(sr.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=vE(r),i=SE(r),a=kE(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=Xh.dirname(this.storagePath);sr.existsSync(e)||sr.mkdirSync(e,{recursive:!0}),sr.writeFileSync(this.storagePath,JSON.stringify(this.soul,null,2),"utf-8")}}});function Ys(n){let e=wE[n];if(!e||Math.random()>e.probability)return null;let t=TE[e.pool];return{text:t[Math.floor(Math.random()*t.length)],style:e.style}}async function Xs(n,e){let t=ir.length>0?`
|
|
51
51
|
\u907F\u514D\u548C\u8FD9\u4E9B\u7C7B\u4F3C: ${ir.join("\u3001")}`:"",o=`\u4F60\u662F\u4E00\u53EA\u53EB\u300C${n.soul.name}\u300D\u7684${n.soul.species}\u684C\u9762\u5BA0\u7269\u3002
|
|
52
52
|
\u6027\u683C: ${n.soul.personality}
|
|
53
53
|
\u53E3\u5934\u7985\u98CE\u683C: "${n.soul.catchphrase}"
|
|
54
54
|
|
|
55
55
|
\u521A\u624D\u53D1\u751F\u4E86: ${n.turnSummary}
|
|
56
56
|
|
|
57
|
-
\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;ir.push(r),ir.length>
|
|
57
|
+
\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;ir.push(r),ir.length>xE&&ir.shift();let s=/[!!✨🎉]|搞定|完美|太棒/.test(r)?"excited":/[.。…]|嗯|想|看看/.test(r)?"thinking":/[zZ]|困|睡|累/.test(r)?"sleepy":"normal";return{text:r,style:s}}catch{return null}}var TE,wE,ir,xE,Zh=N(()=>{"use strict";TE={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"]},wE={"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"}};ir=[],xE=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`
|
|
58
58
|
# \u684C\u9762\u4F19\u4F34
|
|
59
59
|
|
|
60
60
|
\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
|
|
@@ -63,7 +63,7 @@ ${P}`})}}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o
|
|
|
63
63
|
|
|
64
64
|
\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
|
|
65
65
|
\u5176\u4ED6\u65F6\u5019\u6B63\u5E38\u5DE5\u4F5C\u5373\u53EF\uFF0C\u4E0D\u9700\u8981\u63D0\u53CA${e}\u3002
|
|
66
|
-
`}var od=N(()=>{"use strict"});var ty={};mn(ty,{PetGrowthEngine:()=>Ce});var rd,ey,Ce,Zs=N(()=>{"use strict";rd=[{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}],ey=["\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=rd.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=ey[Math.min(e-1,ey.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 rd.filter(t=>t.unlockedAtLevel<=e)}static getNextAbility(e){return rd.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
|
|
66
|
+
`}var od=N(()=>{"use strict"});var ty={};mn(ty,{PetGrowthEngine:()=>Ce});var rd,ey,Ce,Zs=N(()=>{"use strict";rd=[{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}],ey=["\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=rd.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=ey[Math.min(e-1,ey.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 rd.filter(t=>t.unlockedAtLevel<=e)}static getNextAbility(e){return rd.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 RE}from"node:crypto";import ny from"node:fs";async function sy(n){let e=ny.statSync(n);if(e.size>oy)throw new Error(`Pet file exceeds ${oy/1024}KB limit (got ${Math.round(e.size/1024)}KB)`);let t=ny.readFileSync(n),o=RE("sha256").update(t).digest("hex"),r=await AE(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")}ar(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>ry)throw new Error(`SVG for state "${d}" exceeds ${ry/1024}KB limit`);a[d]=en(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 ar(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 _E)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 en(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 AE(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 oy,ry,_E,sd=N(()=>{"use strict";oy=500*1024,ry=20*1024,_E=["idle"]});var iy={};mn(iy,{STATE_ANIMATION_MAP:()=>lr,buildSkeletonPrompt:()=>id,extractColors:()=>ao,parseSkeleton:()=>so,renderState:()=>io,validateSkeleton:()=>lo});function id(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
|
|
67
67
|
|
|
68
68
|
\u89D2\u8272\uFF1A${n}
|
|
69
69
|
|
|
@@ -87,7 +87,7 @@ ${P}`})}}this.hooks.invoke("memory.after_recall",{sessionId:e.sessionId,turnId:o
|
|
|
87
87
|
7. \u4E0D\u8981\u5305\u542B <script> \u6216\u4EFB\u4F55 JS
|
|
88
88
|
8. \u5355\u6587\u4EF6 < 12KB
|
|
89
89
|
|
|
90
|
-
\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=lr[e]??lr.idle,o=
|
|
90
|
+
\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=lr[e]??lr.idle,o=PE[t.body],r=IE[t.eyes],s=CE[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>
|
|
91
91
|
${o}
|
|
92
92
|
${r}
|
|
93
93
|
${s}
|
|
@@ -96,10 +96,10 @@ ${s}
|
|
|
96
96
|
#pet-left-arm { animation: left-arm-anim ${l} ease-in-out infinite; transform-origin: right center; }
|
|
97
97
|
#pet-right-arm { animation: right-arm-anim ${l} ease-in-out infinite; transform-origin: left center; }
|
|
98
98
|
.pupil { transition: transform 0.15s ease-out; }
|
|
99
|
-
</style>`,d="";t.effects?.length&&(d=t.effects.map(p=>
|
|
99
|
+
</style>`,d="";t.effects?.length&&(d=t.effects.map(p=>EE[p]??"").join(`
|
|
100
100
|
`));let u=n.baseSvg.replace(/(<svg[^>]*>)/,`$1
|
|
101
101
|
${c}`);return d&&(u=u.replace(/<\/svg>/,`${d}
|
|
102
|
-
</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 lr,
|
|
102
|
+
</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 lr,PE,IE,CE,EE,ei=N(()=>{"use strict";lr={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"}},PE={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); } }"},IE={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); } }"},CE={sway:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }
|
|
103
103
|
@keyframes right-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-5deg); } }`,still:`@keyframes left-arm-anim { 0%,100% { transform: none; } }
|
|
104
104
|
@keyframes right-arm-anim { 0%,100% { transform: none; } }`,hammer:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-20deg); } }
|
|
105
105
|
@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); } }
|
|
@@ -107,7 +107,7 @@ ${c}`);return d&&(u=u.replace(/<\/svg>/,`${d}
|
|
|
107
107
|
@keyframes right-arm-anim { 0%,100% { transform: rotate(-20deg); } }`,covering:`@keyframes left-arm-anim { 0%,100% { transform: rotate(-40deg) translateX(5px); } }
|
|
108
108
|
@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); } }
|
|
109
109
|
@keyframes right-arm-anim { 0%,100% { transform: rotate(10deg); } 50% { transform: rotate(15deg); } }`,eat:`@keyframes left-arm-anim { 0%,100% { transform: rotate(-30deg); } }
|
|
110
|
-
@keyframes right-arm-anim { 0%,100% { transform: rotate(30deg) translateY(-5px); } 50% { transform: rotate(25deg) translateY(0); } }`},
|
|
110
|
+
@keyframes right-arm-anim { 0%,100% { transform: rotate(30deg) translateY(-5px); } 50% { transform: rotate(25deg) translateY(0); } }`},EE={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 ly={};mn(ly,{DEFAULT_MAX_RETRIES:()=>co,DEFAULT_THRESHOLD:()=>ad,buildConsistencyPrompt:()=>ld,buildRetryPrompt:()=>ur,evaluateConsistency:()=>dr,evaluateConsistencyWithVision:()=>dd,parseConsistencyResponse:()=>cd,structuralConsistencyScore:()=>cr});function cr(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=ay(n),s=ay(e),i=ME(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 ld(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
|
|
111
111
|
1. \u7B2C\u4E00\u5F20\u662F\u89D2\u8272\u7684**\u57FA\u7840\u53C2\u8003\u5F62\u8C61**
|
|
112
112
|
2. \u7B2C\u4E8C\u5F20\u662F\u8BE5\u89D2\u8272\u5728\u300C${e}\u300D\u72B6\u6001\u4E0B\u7684\u53D8\u4F53
|
|
113
113
|
|
|
@@ -135,22 +135,22 @@ ${c}`);return d&&(u=u.replace(/<\/svg>/,`${d}
|
|
|
135
135
|
4. \u4FDD\u7559\u6240\u6709\u5FC5\u9700\u7684 id \u548C class \u5C5E\u6027
|
|
136
136
|
|
|
137
137
|
\u89D2\u8272\uFF1A${n}
|
|
138
|
-
\u72B6\u6001\uFF1A${e}`}function ay(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
|
|
138
|
+
\u72B6\u6001\uFF1A${e}`}function ay(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 ME(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 ad,co,ti=N(()=>{"use strict";ad=6,co=2});var ud={};mn(ud,{DEFAULT_MAX_RETRIES:()=>co,DEFAULT_THRESHOLD:()=>ad,PetGrowthEngine:()=>Ce,PetSoulService:()=>Ut,STATE_ANIMATION_MAP:()=>lr,buildConsistencyPrompt:()=>ld,buildRetryPrompt:()=>ur,buildSkeletonPrompt:()=>id,evaluateConsistency:()=>dr,evaluateConsistencyWithVision:()=>dd,extractColors:()=>ao,generateLLMReaction:()=>Xs,loadPetFile:()=>sy,maybeGenerateReaction:()=>Ys,parseConsistencyResponse:()=>cd,parseSkeleton:()=>so,petContextInjection:()=>Qs,renderState:()=>io,sanitizeSvg:()=>en,structuralConsistencyScore:()=>cr,validatePetManifest:()=>ar,validateSkeleton:()=>lo});var pr=N(()=>{"use strict";Qh();Zh();od();Zs();sd();ei();ti()});import{randomUUID as xt}from"node:crypto";import{createRequire as ZE}from"node:module";import*as pi from"node:vm";import{createInterface as qk}from"node:readline";var Dn=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)}
|
|
139
139
|
`)}start(){process.stdin.on("data",t=>{process.stderr.write(`[transport] raw stdin data (${t.length} bytes): ${t.toString().slice(0,300)}
|
|
140
140
|
`)});let e=qk({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)}
|
|
141
141
|
`);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}
|
|
142
|
-
`)}};pl();Sn();Sn();function Dp(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 Lp,readdir as
|
|
143
|
-
`),c=null;for(let u=0;u<Math.min(l.length,lt.HEADER_LINES);u++){let p=l[u].trim();if(!(!p||p.startsWith("#")||p.startsWith("---"))){c=p.slice(0,150);break}}let d=
|
|
142
|
+
`)}};pl();Sn();Sn();function Dp(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 Lp,readdir as ex,stat as tx}from"node:fs/promises";import{existsSync as Np}from"node:fs";import{join as nx}from"node:path";var lt={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 $p(n,e,t=new Set){if(!n.trim()||!Np(e))return[];let o=n.trim().split(/\s+/);if(o.length<2&&o[0].length<4)return[];let r=await ox(e);if(r.length===0)return[];let s=r.filter(l=>!t.has(l.filePath));if(s.length===0)return[];let a=rx(n,s).filter(l=>l.score>=lt.MIN_SCORE).slice(0,lt.MAX_SELECTED);return a.length===0?[]:sx(a)}async function ox(n){if(!Np(n))return[];let e;try{e=await ex(n)}catch{return[]}let t=e.filter(r=>r.endsWith(".md")&&r!=="INDEX.md");return(await Promise.allSettled(t.map(async r=>{let s=nx(n,r),i=await tx(s),l=(await Lp(s,"utf-8")).split(`
|
|
143
|
+
`),c=null;for(let u=0;u<Math.min(l.length,lt.HEADER_LINES);u++){let p=l[u].trim();if(!(!p||p.startsWith("#")||p.startsWith("---"))){c=p.slice(0,150);break}}let d=ix(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,lt.MAX_SCAN_FILES)}function rx(n,e){let t=ml(n);if(t.length===0)return[];let o=Date.now(),r=lt.RECENCY_DAYS*24*60*60*1e3;return e.map(i=>{let a=0,l=ml(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=ml(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&&ax(n).includes(i.category)&&(a+=.1),o-i.mtimeMs<r&&(a+=lt.RECENCY_BOOST),{header:i,score:a}}).sort((i,a)=>a.score-i.score)}async function sx(n){let e=[],t=0;for(let{header:o,score:r}of n){if(t>=lt.MAX_TOTAL_BYTES)break;try{let s=await Lp(o.filePath,"utf-8"),i=!1;s.length>lt.MAX_FILE_BYTES&&(s=s.slice(0,lt.MAX_FILE_BYTES)+`
|
|
144
144
|
|
|
145
145
|
> [Truncated at ${lt.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>lt.MAX_TOTAL_BYTES){let l=lt.MAX_TOTAL_BYTES-t;s=s.slice(0,l)+`
|
|
146
146
|
|
|
147
|
-
> [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 ml(n){return n.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g," ").split(/\s+/).filter(e=>e.length>1)}function
|
|
147
|
+
> [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 ml(n){return n.toLowerCase().replace(/[^\w\u4e00-\u9fff]+/g," ").split(/\s+/).filter(e=>e.length>1)}function ix(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 ax(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 Up(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}
|
|
148
148
|
|
|
149
149
|
${o.content}`}).join(`
|
|
150
150
|
|
|
151
151
|
---
|
|
152
152
|
|
|
153
|
-
`)}ul();var
|
|
153
|
+
`)}ul();var lx=[/(?:收入|工资|薪资|月薪|年薪|到账|报销|预算|存款|花了|赚了|亏了)\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 fl(n){let e=n.slice(0,600);return lx.some(t=>t.test(e))}var cx=`You are a memory extraction assistant. Analyze the following conversation turn and extract any personal facts, events, or preferences worth remembering long-term.
|
|
154
154
|
|
|
155
155
|
Rules:
|
|
156
156
|
- Only extract FACTS about the user (not the assistant)
|
|
@@ -168,10 +168,10 @@ Assistant response:
|
|
|
168
168
|
Today's date: {today}
|
|
169
169
|
|
|
170
170
|
Respond ONLY with a JSON array (or empty array [] if nothing worth extracting):
|
|
171
|
-
[{"text": "...", "category": "personal_fact|preference|event|lesson", "importance": 0.5-0.9, "eventDate": "YYYY-MM-DD or null"}]`;async function lx(n,e,t){let o=ax.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:cx(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 cx(n){return new Set(["personal_fact","preference","event","lesson","pattern","decision"]).has(n)?n:"personal_fact"}async function jp(n,e){if(!fl(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 lx(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:pa,LIMIT_PER_RECALL:ma,MAX_SURFACED_ENTRIES:fa};function zt(){return{surfacedPaths:new Set,sessionBytes:0}}function Bp(n,e,t){let o=[],r=t??zt(),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:dl(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=Fp(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(Fp(c).length>0)return{action:"continue",context:l};if(!fl(c))return{action:"continue",context:l};let u=e.getLastAssistantMessage?.();return!u||!e.llmExtract?{action:"continue",context:l}:(jp({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 Wp(n,e,t){let o=t??zt();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 $p(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:dl(f.score,Ep(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=Up(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 dx=[{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 Fp(n){let e=[],t=n.slice(0,500);for(let{pattern:o,category:r,extractor:s}of dx){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 $o from"node:path";le();import{existsSync as Gp,mkdirSync as ux,readFileSync as px,writeFileSync as mx}from"node:fs";import{join as fx}from"node:path";import{randomUUID as Hp}from"node:crypto";function Vp(){return fx(H(),"projects.json")}function ze(){let n=Vp();if(!Gp(n))return{activeProjectId:null,projects:[]};try{let e=px(n,"utf-8");return JSON.parse(e)}catch{return{activeProjectId:null,projects:[]}}}function Et(n){let e=Vp(),t=H();Gp(t)||ux(t,{recursive:!0}),mx(e,JSON.stringify(n,null,2),"utf-8")}function Xr(n){let e=ze(),t=new Date().toISOString(),o={id:Hp(),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),Et(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 ct(n){return ze().projects.find(t=>t.id===n)??null}function Kp(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(),Et(t),!0):!1}function gt(n){let e=ze(),t=e.projects.find(o=>o.id===n&&o.status==="active");return t?(e.activeProjectId=t.id,Et(e),t):null}function gl(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 Et(e),{deleted:!0,switchedTo:r}}function zp(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:Hp(),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),Et(e),r}function qp(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(),Et(t),o)}function Yp(n,e){let t=ze(),o=t.projects.find(r=>r.id===n);return o?(o.workspaceDir=e,o.updatedAt=new Date().toISOString(),Et(t),!0):!1}function Xp(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 Et(e),{archived:!0,switchedTo:o}}function Jp(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(),Et(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 Et(e),{archived:!0,projectId:t.id,switchedTo:o}}je();var Zr={MAX_RECALLED_SKILLS:Yi,MAX_SKILL_CONTENT_CHARS:Xi,CACHE_TTL_MS:Ji};function gx(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=hx(n);return a.length>0?a:null}function hx(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,hl=0;function yx(n){let e=Date.now();if(Qr&&e-hl<Zr.CACHE_TTL_MS)return Qr;let t=[],o=fe().map(s=>s.workspaceDir).filter(Boolean),r=pp(o,n);for(let s of r){let i=$o.join(s,".qlogicagent","skills");try{let a=es.readdirSync(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=$o.join(i,l.name,"SKILL.md");try{let d=es.readFileSync(c,"utf8"),u=d.split(`
|
|
172
|
-
`).slice(0,5).join(" ").toLowerCase();t.push({name:l.name,projectDir:s,projectName:$o.basename(s),content:d,searchText:`${l.name.toLowerCase()} ${u}`})}catch{}}}catch{}}return Qr=t,hl=e,t}function
|
|
171
|
+
[{"text": "...", "category": "personal_fact|preference|event|lesson", "importance": 0.5-0.9, "eventDate": "YYYY-MM-DD or null"}]`;async function dx(n,e,t){let o=cx.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:ux(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 ux(n){return new Set(["personal_fact","preference","event","lesson","pattern","decision"]).has(n)?n:"personal_fact"}async function jp(n,e){if(!fl(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 dx(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:pa,LIMIT_PER_RECALL:ma,MAX_SURFACED_ENTRIES:fa};function zt(){return{surfacedPaths:new Set,sessionBytes:0}}function Bp(n,e,t){let o=[],r=t??zt(),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:dl(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=Fp(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(Fp(c).length>0)return{action:"continue",context:l};if(!fl(c))return{action:"continue",context:l};let u=e.getLastAssistantMessage?.();return!u||!e.llmExtract?{action:"continue",context:l}:(jp({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 Wp(n,e,t){let o=t??zt();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 $p(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:dl(f.score,Ep(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=Up(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 px=[{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 Fp(n){let e=[],t=n.slice(0,500);for(let{pattern:o,category:r,extractor:s}of px){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 $o from"node:path";le();import{existsSync as Gp,mkdirSync as mx,readFileSync as fx,writeFileSync as gx}from"node:fs";import{join as hx}from"node:path";import{randomUUID as Hp}from"node:crypto";function Vp(){return hx(H(),"projects.json")}function ze(){let n=Vp();if(!Gp(n))return{activeProjectId:null,projects:[]};try{let e=fx(n,"utf-8");return JSON.parse(e)}catch{return{activeProjectId:null,projects:[]}}}function Et(n){let e=Vp(),t=H();Gp(t)||mx(t,{recursive:!0}),gx(e,JSON.stringify(n,null,2),"utf-8")}function Xr(n){let e=ze(),t=new Date().toISOString(),o={id:Hp(),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),Et(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 ct(n){return ze().projects.find(t=>t.id===n)??null}function Kp(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(),Et(t),!0):!1}function gt(n){let e=ze(),t=e.projects.find(o=>o.id===n&&o.status==="active");return t?(e.activeProjectId=t.id,Et(e),t):null}function gl(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 Et(e),{deleted:!0,switchedTo:r}}function zp(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:Hp(),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),Et(e),r}function qp(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(),Et(t),o)}function Yp(n,e){let t=ze(),o=t.projects.find(r=>r.id===n);return o?(o.workspaceDir=e,o.updatedAt=new Date().toISOString(),Et(t),!0):!1}function Xp(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 Et(e),{archived:!0,switchedTo:o}}function Jp(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(),Et(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 Et(e),{archived:!0,projectId:t.id,switchedTo:o}}je();var Zr={MAX_RECALLED_SKILLS:Yi,MAX_SKILL_CONTENT_CHARS:Xi,CACHE_TTL_MS:Ji};function yx(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=bx(n);return a.length>0?a:null}function bx(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,hl=0;function kx(n){let e=Date.now();if(Qr&&e-hl<Zr.CACHE_TTL_MS)return Qr;let t=[],o=fe().map(s=>s.workspaceDir).filter(Boolean),r=pp(o,n);for(let s of r){let i=$o.join(s,".qlogicagent","skills");try{let a=es.readdirSync(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=$o.join(i,l.name,"SKILL.md");try{let d=es.readFileSync(c,"utf8"),u=d.split(`
|
|
172
|
+
`).slice(0,5).join(" ").toLowerCase();t.push({name:l.name,projectDir:s,projectName:$o.basename(s),content:d,searchText:`${l.name.toLowerCase()} ${u}`})}catch{}}}catch{}}return Qr=t,hl=e,t}function vx(n,e){if(n.length===0)return[];let t=kx(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 Zp(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=yx(s);if(!i)return{action:"continue",context:r};e.log.debug(`skill-recall: retrospective trigger detected, keywords: [${i.join(", ")}]`);let a=vx(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)+`
|
|
173
173
|
...(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(`
|
|
174
|
-
`),score:.85}});return{action:"continue",context:{...r,recalledMemories:[...l,...c]}}}})}function ht(){Qr=null,hl=0}Sn();import{createRequire as
|
|
174
|
+
`),score:.85}});return{action:"continue",context:{...r,recalledMemories:[...l,...c]}}}})}function ht(){Qr=null,hl=0}Sn();import{createRequire as Rx}from"node:module";le();import*as ns from"node:fs";import*as yl from"node:path";import{randomUUID as Sx}from"node:crypto";var Tx=`
|
|
175
175
|
CREATE TABLE IF NOT EXISTS memories (
|
|
176
176
|
id TEXT PRIMARY KEY,
|
|
177
177
|
text TEXT NOT NULL,
|
|
@@ -223,7 +223,7 @@ CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
|
|
|
223
223
|
INSERT INTO memories_fts(rowid, id, user_id, text, category, tags)
|
|
224
224
|
VALUES (new.rowid, new.id, new.user_id, new.text, new.category, new.tags);
|
|
225
225
|
END;
|
|
226
|
-
`,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(
|
|
226
|
+
`,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(Tx)}insert(e){let t=`mem_${Sx().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(`
|
|
227
227
|
INSERT INTO memories (id, text, user_id, category, importance, source, session_id, event_date, tags, embedding, created_at, updated_at, last_accessed_at)
|
|
228
228
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
229
229
|
`).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(`
|
|
@@ -238,7 +238,7 @@ END;
|
|
|
238
238
|
SELECT id, text, category, importance, tags, created_at, access_count, embedding
|
|
239
239
|
FROM memories
|
|
240
240
|
WHERE user_id = ? AND is_archived = 0 AND embedding IS NOT NULL
|
|
241
|
-
`).all(t),i=[],a=tm(e);for(let l of s){let c=new Float32Array(l.embedding.buffer,l.embedding.byteOffset,l.embedding.byteLength/4),d=tm(c),u=
|
|
241
|
+
`).all(t),i=[],a=tm(e);for(let l of s){let c=new Float32Array(l.embedding.buffer,l.embedding.byteOffset,l.embedding.byteLength/4),d=tm(c),u=wx(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(`
|
|
242
242
|
SELECT * FROM memories
|
|
243
243
|
WHERE user_id = ? ${i}
|
|
244
244
|
ORDER BY created_at DESC
|
|
@@ -314,41 +314,41 @@ END;
|
|
|
314
314
|
ORDER BY importance ASC, access_count ASC, created_at ASC
|
|
315
315
|
LIMIT ?
|
|
316
316
|
)
|
|
317
|
-
`).run(Date.now(),e,r).changes}close(){this.db.close()}};function em(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 tm(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 Sx(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 nm(){let n=yl.join(H(),"memory");return ns.existsSync(n)||ns.mkdirSync(n,{recursive:!0}),yl.join(n,"memories.db")}import{createRequire as vl}from"node:module";import*as os from"node:path";import*as zn from"node:fs";var Uo=class{dimensions=0;model="none";async embed(e){return new Float32Array(0)}async embedBatch(e){return e.map(()=>new Float32Array(0))}},bl=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)}}},kl=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 om(){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(vl(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=om();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 rm(n){let e=n?.modelId??"Xenova/bge-small-zh-v1.5",t=n?.dimensions??512;try{vl(import.meta.url).resolve("@xenova/transformers")}catch{return{onnxAvailable:!1,modelCached:!1,modelDownloaded:!1,dimensions:t,error:"@xenova/transformers not installed"}}let o=om(),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 sm(n){if(n){if(n.strategy==="none")return new Uo;if(n.strategy==="api"&&n.api){let e=new kl(n.api);if(n.fallbackStrategy==="onnx"){let t=new Kn(n.fallbackOnnx);return new bl({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 Uo}try{return vl(import.meta.url).resolve("@xenova/transformers"),new Kn}catch{return new Uo}}var Tx={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 Sl(n,e,t){let o=Tx[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 im="qmemory-local",Tl=class{providerId=im;store;embedding;userIdPrefix;dbPath;constructor(e){if(this.dbPath=nm(),this.userIdPrefix=e.userIdPrefix??"",this.embedding=sm(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:im,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(`
|
|
318
|
-
`)}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 am(n){return new Tl(n)}ft();function wl(n){try{let e=
|
|
317
|
+
`).run(Date.now(),e,r).changes}close(){this.db.close()}};function em(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 tm(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 wx(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 nm(){let n=yl.join(H(),"memory");return ns.existsSync(n)||ns.mkdirSync(n,{recursive:!0}),yl.join(n,"memories.db")}import{createRequire as vl}from"node:module";import*as os from"node:path";import*as zn from"node:fs";var Uo=class{dimensions=0;model="none";async embed(e){return new Float32Array(0)}async embedBatch(e){return e.map(()=>new Float32Array(0))}},bl=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)}}},kl=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 om(){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(vl(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=om();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 rm(n){let e=n?.modelId??"Xenova/bge-small-zh-v1.5",t=n?.dimensions??512;try{vl(import.meta.url).resolve("@xenova/transformers")}catch{return{onnxAvailable:!1,modelCached:!1,modelDownloaded:!1,dimensions:t,error:"@xenova/transformers not installed"}}let o=om(),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 sm(n){if(n){if(n.strategy==="none")return new Uo;if(n.strategy==="api"&&n.api){let e=new kl(n.api);if(n.fallbackStrategy==="onnx"){let t=new Kn(n.fallbackOnnx);return new bl({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 Uo}try{return vl(import.meta.url).resolve("@xenova/transformers"),new Kn}catch{return new Uo}}var xx={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 Sl(n,e,t){let o=xx[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 im="qmemory-local",Tl=class{providerId=im;store;embedding;userIdPrefix;dbPath;constructor(e){if(this.dbPath=nm(),this.userIdPrefix=e.userIdPrefix??"",this.embedding=sm(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:im,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(`
|
|
318
|
+
`)}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 am(n){return new Tl(n)}ft();function wl(n){try{let e=_x();if(e){let t={projectRoot:n.projectRoot,userIdPrefix:n.userIdPrefix,embedding:n.embedding,createDatabase:e};return{provider:am(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 _x(){try{let e=Rx(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 xl(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=Ax();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 lm={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 Ax(){let t=X().peekActiveModel("textGeneration")?.provider?.toLowerCase();if(t){let c=Px(t);if(c){let d=Sl(t,c);if(d)return{strategy:"api",api:d,fallbackStrategy:"onnx"}}}for(let[c,d]of Object.entries(lm))for(let u of d){let p=process.env[u];if(p){let m=Sl(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 Px(n){let e=lm[n];if(e)for(let t of e){let o=process.env[t];if(o)return o}}var an=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 cm="transcript.jsonl",Yt="metadata.json";function Ix(n){return Kt(n)}function qn(n,e){let t=n.replace(/[^a-zA-Z0-9_-]/g,"_");return qe.join(Ix(e),t)}function dm(n,e){let t=n.replace(/[^a-zA-Z0-9_-]/g,"_"),o=qe.join(Kt(e),t),r=qe.join(o,Yt);if(ue.existsSync(r))return o}function xn(n,e){let t=dm(n,e);if(!t)return null;try{let o=ue.readFileSync(qe.join(t,Yt),"utf8");return JSON.parse(o)}catch{return null}}async function Rl(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)+`
|
|
319
319
|
`;return await ue.promises.appendFile(qe.join(r,cm),i,"utf8"),!0}catch(s){return console.error(`[session-persistence] appendMessage failed for ${n}: ${s.message}`),!1}}async function um(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,Yt),"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,Yt+".tmp");await ue.promises.writeFile(l,JSON.stringify(a,null,2),"utf8"),await ue.promises.rename(l,qe.join(r,Yt))}async function nt(n,e,t){let r=dm(n,t)??qn(n,t),s=qe.join(r,Yt),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 _l(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,cm),r=qe.join(t,Yt),s=[],i=0;try{let d=await ue.promises.readFile(o,"utf8");for(let u of d.split(`
|
|
320
|
-
`))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 Mt(n=ea,e){let t=Kt(e),o;try{o=await ue.promises.readdir(t)}catch{return[]}let r=[];for(let s of o){let i=qe.join(t,s,Yt);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 Al(n,e){let t=qn(n,e);await ue.promises.rm(t,{recursive:!0,force:!0})}function
|
|
321
|
-
`),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,Yt);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}}cl();import{randomUUID as
|
|
320
|
+
`))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 Mt(n=ea,e){let t=Kt(e),o;try{o=await ue.promises.readdir(t)}catch{return[]}let r=[];for(let s of o){let i=qe.join(t,s,Yt);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 Al(n,e){let t=qn(n,e);await ue.promises.rm(t,{recursive:!0,force:!0})}function Cx(n){return n.turnCount<ta?!1:n.taskSummaryGeneratedAt?n.turnCount-(n.taskSummaryGeneratedAt??0)>=na:!0}var Ex="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 pm(n,e){if(!n.trim())return null;try{let t=e.transport.stream({model:e.model,messages:[{role:"system",content:Ex},{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 mm(n,e,t,o,r){if(!Cx(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(`
|
|
321
|
+
`),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,Yt);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}}cl();import{randomUUID as JL}from"node:crypto";var Mx=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=Mx){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 Ox}from"node:fs";import{stat as Dx}from"node:fs/promises";import{join as fm,relative as Lx,resolve as Nx}from"node:path";var $x=[`${He}/settings.json`,"INSTRUCTIONS.md",`${He}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${He}/rules`],Ux=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${He}/rules`],Pl=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 $x){let t=fm(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=Ox(e,{persistent:!1,recursive:t.includes("/")?!1:void 0},(r,s)=>{let i=s?fm(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 Dx(e)}catch{r="deleted"}let s=Lx(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(()=>{}),Ux.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let t=Nx(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 gm(n){let e=new Pl(n);return await e.start(),e}le();je();import{readFile as jx,readdir as Fx,stat as Bx}from"node:fs/promises";import{dirname as is,extname as Wx,isAbsolute as Gx,join as Xn,parse as ym,resolve as hm}from"node:path";import{homedir as Hx}from"node:os";var Vx="INSTRUCTIONS.md",Kx="INSTRUCTIONS.local.md",zx=[".instructions.md"],qx=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 Yx(n){try{return await jx(n,"utf-8")}catch{return null}}function Xx(n){return n.includes("<!--")?n.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):n}function Jx(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 Qx(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(Hx(),a.slice(2));else if(Gx(a))c=a;else if(a.startsWith("./"))c=hm(is(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))c=hm(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>=oa)return[];let i=Wx(n).toLowerCase();if(i&&!qx.has(i))return[];t.add(s);let a=await Yx(n);if(!a?.trim())return[];let{content:l,globs:c}=Jx(a),d=Xx(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=Qx(l,n);for(let h of m){let f=await Yn(h,e,t,o+1,n);u.push(...f)}return u}async function bm(n,e,t,o,r=new Set){if(r.has(n))return[];r.add(n);let s=[];try{let i=await Fx(n,{withFileTypes:!0});for(let a of i){let l=Xn(n,a.name);if(a.isDirectory())s.push(...await bm(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 Zx(n){let e=n,t=ym(e).root;for(;e!==t;){try{let o=Xn(e,".git"),r=await Bx(o);if(r.isDirectory()||r.isFile())return e}catch{}e=is(e)}return null}async function eR(n,e){let t=[],o=new Set,s=await Zx(n)??ym(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,Vx),"Project",o));for(let c of zx)t.push(...await Yn(Xn(l,c),"Project",o));t.push(...await Yn(Mo(l),"Project",o)),t.push(...await bm(Hn(l),"Project",o,!1)),t.push(...await Yn(Xn(l,Kx),"Local",o))}return e&&t.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:n,fileCount:t.length}).catch(()=>{}),t}function km(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}:
|
|
322
322
|
|
|
323
323
|
${o.content.trim()}`)}return t.length>0?`${e}
|
|
324
324
|
|
|
325
325
|
${t.join(`
|
|
326
326
|
|
|
327
|
-
`)}`:""}var jo=null,Il=null;async function vm(n,e){return jo&&Il===n||(jo=await
|
|
328
|
-
`)}},required:["thought"]};function Rm(){return{name:
|
|
329
|
-
`),parameters:
|
|
327
|
+
`)}`:""}var jo=null,Il=null;async function vm(n,e){return jo&&Il===n||(jo=await eR(n,e),Il=n),jo}function Sm(){jo=null,Il=null}import*as K from"node:fs";import*as q from"node:path";import{execFile as _A}from"node:child_process";var Cl=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),Tm=new Set([...Cl,"agent"]);function El(n,e){let t=e?Cl:Tm;return n.filter(o=>o.function.name.startsWith("mcp__")?!0:!t.has(o.function.name))}var Xt=new Map,Ml=new Set;function wm(n){Xt.clear(),Ml.clear();for(let e of n)Xt.set(e.name,e)}function Pe(n){Xt.set(n.name,n)}function Ol(n){for(let e of n)Xt.set(e.name,e)}function as(n){return Xt.delete(n)}function ot(n){return Xt.get(n)}function ln(){return Array.from(Xt.keys())}function xm(n){let e=Xt.get(n);return!e||e.isEnabled?.()===!1?!1:(Ml.add(n),!0)}function Ot(n=!1){let e=[];for(let t of Xt.values())t.isEnabled?.()!==!1&&(!n&&t.shouldDefer&&!Ml.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 tR="think",nR={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(`
|
|
328
|
+
`)}},required:["thought"]};function Rm(){return{name:tR,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(`
|
|
329
|
+
`),parameters:nR,execute:async(n,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}var oR="task",rR=["create","update","delete","list","get"];var sR={type:"object",properties:{action:{type:"string",enum:[...rR],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 Fo(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 _m(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=Fo(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(`
|
|
330
330
|
`)}],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(`
|
|
331
|
-
`)}],details:{type:"task",action:"get",task:y}}}return{name:tR,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:oR,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 PR,resolve as IR}from"node:path";var Am=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Pm=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Im=new Set(["ls","tree","du"]);var Cm=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function rR(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 Em(n){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(n)}function Dl(n){let e=rR(n),t=e!==null&&Am.has(e),o=e!==null&&Pm.has(e),r=e!==null&&Im.has(e),s=e!==null&&Cm.has(e),i=/(?:[^2]>|^>|\|>)/.test(n),a=Em(n),l=(t||o||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:o,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}var sR=n=>({isError:n!==0,message:n!==0?`Command failed with exit code ${n}`:void 0}),iR=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 aR(n){let e=n.trim(),t=e.split(/\s*\|\s*/);return(t[t.length-1]??e).trim().split(/\s+/)[0]??""}function Ll(n,e,t,o){let r=aR(n);return(iR.get(r)??sR)(e,t,o)}function Nl(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 vR}from"node:child_process";import{constants as ds,readFileSync as SR,unlinkSync as TR}from"node:fs";import{mkdir as wR,open as xR,realpath as Lm}from"node:fs/promises";import{isAbsolute as RR,resolve as _R}from"node:path";function Rn(){if(process.platform!=="win32")return!1;let n=process.env.QLOGICAGENT_USE_POWERSHELL;return n==="1"||n==="true"}function $l(){return Rn()?"powershell":"bash"}function Ul(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as lR,readFile as cR,writeFile as dR,unlink as uR}from"node:fs/promises";import{join as Mm}from"node:path";import{tmpdir as pR}from"node:os";var mR=8*1024*1024,fR=5*1024*1024*1024;var jl;function Bo(){if(!jl){let n=Math.random().toString(36).slice(2,10);jl=Mm(pR(),"qla-tasks",n)}return jl}function Om(n){return Mm(Bo(),`${n}.output`)}function Jt(n="local_bash"){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var cn=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,o=!1,r=mR){this.taskId=e,this.path=Om(e),this.stdoutToFile=o,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=gR(e),this.#d()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await cR(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&&lR(Bo(),{recursive:!0}).then(()=>dR(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await uR(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function gR(n){let e=0;for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&e++;return e}var Fl=137,Dm=143,hR=5e3,Bl=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)}},Wl=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=Bl){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(Dm)}#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(Fl))},()=>{}))},hR),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===Fl,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 ${Bl} bytes. ${o.stderr}`:e===Dm&&(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??Fl)}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 Gl(n,e,t,o,r=!1,s=Bl){return new Wl(n,e,t,o,r,s)}function cs(n,e){let t=new cn(Jt("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 Hl(n){let e=new cn(Jt("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 yR=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"]),bR=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function Vl(){let n={...process.env};for(let e of Object.keys(n))kR(e)&&delete n[e];return n}function kR(n){if(yR.has(n))return!0;let e=n.toUpperCase();for(let t of bR)if(e.includes(t))return!0;return!1}var AR=1800*1e3,us=process.cwd(),Nm=process.cwd();function ps(){return us}function Kl(n,e){us=RR(n)?n:_R(e||us,n)}function $m(){return Nm}function ms(n){us=n,Nm=n}var zl=null;function Wo(n){zl={provider:n}}function Um(){if(!zl)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return zl.provider}async function fs(n,e,t,o){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:c}=o??{},d=r||AR,u=t??$l(),p=Um(),m=Ul(),{commandString:h,cwdFilePath:f}=await p.buildExecCommand(n,{id:m,useSandbox:!1}),y=h,b=c??ps();try{await Lm(b)}catch{let S=$m();try{await Lm(S),Kl(S),b=S}catch{return Hl(`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=Jt("local_bash"),$=new cn(O,s??null,!P);await wR(Bo(),{recursive:!0});let W;if(!P){let S=ds.O_NOFOLLOW??0;W=await xR($.path,process.platform==="win32"?"w":ds.O_WRONLY|ds.O_CREAT|ds.O_APPEND|S)}try{let S=vR(k,x,{env:{...Vl(),GIT_EDITOR:"true",QLOGICAGENT:"1",...I},cwd:b,stdio:P?["pipe","pipe","pipe"]:["pipe",W?.fd,W?.fd],detached:p.detached,windowsHide:!0}),ce=Gl(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=SR(f,{encoding:"utf8"}).trim();j&&j.normalize("NFC")!==b&&Kl(j,b)}catch{}try{TR(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 CR="exec",ER={type:"object",properties:{command:{type:"string",description:Rn()?"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"]},MR=12e4,OR=6e5,gs=3e4;function ql(n,e){if(n.length<=e)return n;let t=Math.floor(e/2)-50;return`${n.slice(0,t)}
|
|
331
|
+
`)}],details:{type:"task",action:"get",task:y}}}return{name:oR,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:sR,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 CR,resolve as ER}from"node:path";var Am=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Pm=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),Im=new Set(["ls","tree","du"]);var Cm=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function iR(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 Em(n){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(n)}function Dl(n){let e=iR(n),t=e!==null&&Am.has(e),o=e!==null&&Pm.has(e),r=e!==null&&Im.has(e),s=e!==null&&Cm.has(e),i=/(?:[^2]>|^>|\|>)/.test(n),a=Em(n),l=(t||o||r)&&!i&&!a;return{firstCommand:e,isSearch:t,isRead:o,isList:r,isSilent:s,isConcurrencySafe:l,isReadOnly:l}}var aR=n=>({isError:n!==0,message:n!==0?`Command failed with exit code ${n}`:void 0}),lR=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 cR(n){let e=n.trim(),t=e.split(/\s*\|\s*/);return(t[t.length-1]??e).trim().split(/\s+/)[0]??""}function Ll(n,e,t,o){let r=cR(n);return(lR.get(r)??aR)(e,t,o)}function Nl(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 TR}from"node:child_process";import{constants as ds,readFileSync as wR,unlinkSync as xR}from"node:fs";import{mkdir as RR,open as _R,realpath as Lm}from"node:fs/promises";import{isAbsolute as AR,resolve as PR}from"node:path";function Rn(){if(process.platform!=="win32")return!1;let n=process.env.QLOGICAGENT_USE_POWERSHELL;return n==="1"||n==="true"}function $l(){return Rn()?"powershell":"bash"}function Ul(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as dR,readFile as uR,writeFile as pR,unlink as mR}from"node:fs/promises";import{join as Mm}from"node:path";import{tmpdir as fR}from"node:os";var gR=8*1024*1024,hR=5*1024*1024*1024;var jl;function Bo(){if(!jl){let n=Math.random().toString(36).slice(2,10);jl=Mm(fR(),"qla-tasks",n)}return jl}function Om(n){return Mm(Bo(),`${n}.output`)}function Jt(n="local_bash"){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var cn=class{taskId;path;stdoutToFile;#e="";#n="";#r=0;#s=0;#t;#i;#o=0;#a=!1;constructor(e,t,o=!1,r=gR){this.taskId=e,this.path=Om(e),this.stdoutToFile=o,this.#t=r,this.#i=t}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#r+=yR(e),this.#d()}writeStderr(e){this.#n+=e}async getStdout(){if(this.stdoutToFile)try{let e=await uR(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&&dR(Bo(),{recursive:!0}).then(()=>pR(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await mR(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#n="",this.#i=null,this.deleteOutputFile())}};function yR(n){let e=0;for(let t=0;t<n.length;t++)n.charCodeAt(t)===10&&e++;return e}var Fl=137,Dm=143,bR=5e3,Bl=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)}},Wl=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=Bl){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(Dm)}#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(Fl))},()=>{}))},bR),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===Fl,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 ${Bl} bytes. ${o.stderr}`:e===Dm&&(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??Fl)}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 Gl(n,e,t,o,r=!1,s=Bl){return new Wl(n,e,t,o,r,s)}function cs(n,e){let t=new cn(Jt("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 Hl(n){let e=new cn(Jt("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 kR=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"]),vR=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function Vl(){let n={...process.env};for(let e of Object.keys(n))SR(e)&&delete n[e];return n}function SR(n){if(kR.has(n))return!0;let e=n.toUpperCase();for(let t of vR)if(e.includes(t))return!0;return!1}var IR=1800*1e3,us=process.cwd(),Nm=process.cwd();function ps(){return us}function Kl(n,e){us=AR(n)?n:PR(e||us,n)}function $m(){return Nm}function ms(n){us=n,Nm=n}var zl=null;function Wo(n){zl={provider:n}}function Um(){if(!zl)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return zl.provider}async function fs(n,e,t,o){let{timeout:r,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:l,cwd:c}=o??{},d=r||IR,u=t??$l(),p=Um(),m=Ul(),{commandString:h,cwdFilePath:f}=await p.buildExecCommand(n,{id:m,useSandbox:!1}),y=h,b=c??ps();try{await Lm(b)}catch{let S=$m();try{await Lm(S),Kl(S),b=S}catch{return Hl(`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=Jt("local_bash"),$=new cn(O,s??null,!P);await RR(Bo(),{recursive:!0});let W;if(!P){let S=ds.O_NOFOLLOW??0;W=await _R($.path,process.platform==="win32"?"w":ds.O_WRONLY|ds.O_CREAT|ds.O_APPEND|S)}try{let S=TR(k,x,{env:{...Vl(),GIT_EDITOR:"true",QLOGICAGENT:"1",...I},cwd:b,stdio:P?["pipe","pipe","pipe"]:["pipe",W?.fd,W?.fd],detached:p.detached,windowsHide:!0}),ce=Gl(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=wR(f,{encoding:"utf8"}).trim();j&&j.normalize("NFC")!==b&&Kl(j,b)}catch{}try{xR(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 MR="exec",OR={type:"object",properties:{command:{type:"string",description:Rn()?"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"]},DR=12e4,LR=6e5,gs=3e4;function ql(n,e){if(n.length<=e)return n;let t=Math.floor(e/2)-50;return`${n.slice(0,t)}
|
|
332
332
|
|
|
333
333
|
... [truncated ${n.length-e} chars] ...
|
|
334
334
|
|
|
335
|
-
${n.slice(-t)}`}function
|
|
336
|
-
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:
|
|
337
|
-
Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:h,description:t.description,classification:o}}}let a
|
|
335
|
+
${n.slice(-t)}`}function NR(n){return n==null||n<=0?DR:Math.min(n,LR)}async function*$R(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=Jt("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 jm(n={}){return{name:MR,label:"Execute Command",description:"Execute a shell command. Supports foreground (blocking, returns output) and background (non-blocking, returns task ID) modes. "+(Rn()?"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.
|
|
336
|
+
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:OR,maxResultSizeChars:gs,execute:async(e,t)=>{let o=Dl(t.command);if(!t.background){let m=Nl(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=NR(t.timeout),i=t.workdir?CR(t.workdir)?t.workdir:ER(ps(),t.workdir):void 0;if(t.background){let m=await fs(t.command,r.signal,void 0,{shouldAutoBackground:!1,cwd:i}),h=Jt("bg");if(m.background(h))return{content:[{type:"text",text:`Background task started (id: ${h}).
|
|
337
|
+
Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:h,description:t.description,classification:o}}}let a=$R({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(ql(c.stdout,gs)),d.push(`[full output: ${c.outputFilePath} (${c.outputFileSize} bytes)]`)):c.stdout&&d.push(ql(c.stdout,gs)),c.stderr&&d.push(`[stderr]
|
|
338
338
|
${ql(c.stderr,Math.floor(gs/4))}`),c.interrupted&&d.push(`[interrupted \u2014 exit code ${c.code}]`);let u=c.code!==0?Ll(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(`
|
|
339
|
-
`)}],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
|
|
340
|
-
; `),i=e+s;return{commandString:t.useSandbox?[`'${n.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Bm(i)].join(" "):i,cwdFilePath:o}},getSpawnArgs(e){return
|
|
339
|
+
`)}],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 UR}from"node:os";import{join as jR,posix as Yl}from"node:path";function FR(n){return n.replace(/(\d?)>nul\b/gi,(e,t)=>`${t||""}>/dev/null`)}function BR(n){return!(/(?:^|[;&|])\s*<\s/.test(n)||/<<[-]?\s*['"]?[A-Za-z_]/.test(n))}function WR(n,e){return`$'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function Fm(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=UR(),a=s?Fm(i):i,l=r.useSandbox&&r.sandboxTmpDir?Yl.join(r.sandboxTmpDir,`cwd-${r.id}`):Yl.join(a,`qla-${r.id}-cwd`),c=r.useSandbox&&r.sandboxTmpDir?Yl.join(r.sandboxTmpDir,`cwd-${r.id}`):jR(i,`qla-${r.id}-cwd`),d=FR(o),u=BR(d),p=WR(d,u),m=[];if(t){let f=s?Fm(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 GR}from"node:os";import{join as HR,posix as VR}from"node:path";function Bm(n){return Buffer.from(n,"utf16le").toString("base64")}function KR(n){return["-NoProfile","-NonInteractive","-Command",n]}function Xl(n){return{type:"powershell",shellPath:n,detached:!1,async buildExecCommand(e,t){let o=t.useSandbox&&t.sandboxTmpDir?VR.join(t.sandboxTmpDir,`qla-pwd-ps-${t.id}`):HR(GR(),`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(`
|
|
340
|
+
; `),i=e+s;return{commandString:t.useSandbox?[`'${n.replace(/'/g,"'\\''")}'`,"-NoProfile","-NonInteractive","-EncodedCommand",Bm(i)].join(" "):i,cwdFilePath:o}},getSpawnArgs(e){return KR(e)},async getEnvironmentOverrides(e){return{QLOGICAGENT:"1"}}}}var zR=[{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"}],qR=[{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 Jl(n){for(let{pattern:e,warning:t}of zR)if(e.test(n))return t;return null}function Ql(n){for(let{pattern:e,warning:t}of qR)if(e.test(n))return t;return null}var YR="read",XR={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 Wm(n){return{name:YR,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:XR,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(`
|
|
341
341
|
`),l=Math.max(0,(r.offset??1)-1),c=Math.min(r.limit??2e3,2e3),d=a.slice(l,l+c),u=d.join(`
|
|
342
342
|
`);u.length>5e4&&(u=u.slice(0,5e4)+`
|
|
343
|
-
... (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
|
|
344
|
-
`).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${o}`}],details:{type:"write",path:o,lineCount:r}}}}}var
|
|
345
|
-
`).length;return{content:[{type:"text",text:`Edited ${o} (line ${c})`}],details:{type:"edit",path:o,success:!0,firstChangedLine:c}}}}}var
|
|
343
|
+
... (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 JR="write",QR={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"]},Gm=5e5;function Hm(n){return{name:JR,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:QR,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>Gm)return{content:[{type:"text",text:`Content too large (${t.content.length} chars, max ${Gm}). 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(`
|
|
344
|
+
`).length;return{content:[{type:"text",text:`Wrote ${r} lines to ${o}`}],details:{type:"write",path:o,lineCount:r}}}}}var ZR="edit",e_={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 Vm(n){return{name:ZR,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:e_,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(`
|
|
345
|
+
`).length;return{content:[{type:"text",text:`Edited ${o} (line ${c})`}],details:{type:"edit",path:o,success:!0,firstChangedLine:c}}}}}var t_="search",n_={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"]},Km=100,zm=250,Zl=1e5;function qm(n){return{name:t_,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:n_,isReadOnly:!0,execute:async(e,t)=>{let o=t.path?n.resolvePath?n.resolvePath(t.path):t.path:"",r=t.mode;return r==="filename"?o_(n,t,o):r==="content"?r_(n,t,o):s_(n,t,o)}}}async function o_(n,e,t){let o=e.headLimit??Km,{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(`
|
|
346
346
|
`);return d&&(u+=`
|
|
347
347
|
|
|
348
|
-
(Results truncated. ${c.length} shown. Use a more specific pattern or increase headLimit.)`),u=ec(u,Zl),{content:[{type:"text",text:u}],details:{mode:"filename",totalMatches:c.length,truncated:d}}}async function
|
|
348
|
+
(Results truncated. ${c.length} shown. Use a more specific pattern or increase headLimit.)`),u=ec(u,Zl),{content:[{type:"text",text:u}],details:{mode:"filename",totalMatches:c.length,truncated:d}}}async function r_(n,e,t){let o=e.headLimit??zm,{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(`
|
|
349
349
|
`);return s&&(a+=`
|
|
350
350
|
|
|
351
|
-
(Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=ec(a,Zl),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function
|
|
351
|
+
(Results truncated at ${r.length} matches. Use offset/headLimit for pagination.)`),a=ec(a,Zl),{content:[{type:"text",text:a}],details:{mode:"content",totalMatches:r.length,truncated:s}}}async function s_(n,e,t){let[o,r]=await Promise.all([e.fileGlob?n.glob(e.fileGlob,{cwd:t,limit:Km}):Promise.resolve({files:[],truncated:!1}),n.grep(e.pattern,{cwd:t,fileGlob:e.fileGlob,caseInsensitive:e.caseInsensitive,contextLines:e.contextLines,headLimit:e.headLimit??zm,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}):
|
|
352
352
|
${i.join(`
|
|
353
353
|
`)}`),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}):
|
|
354
354
|
${d.join(`
|
|
@@ -360,18 +360,18 @@ ${d.join(`
|
|
|
360
360
|
|
|
361
361
|
... [truncated ${n.length-e} chars] ...
|
|
362
362
|
|
|
363
|
-
${n.slice(-t)}`}var
|
|
364
|
-
`),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
|
|
363
|
+
${n.slice(-t)}`}var i_="apply_patch",a_={type:"object",properties:{input:{type:"string",description:"Patch content using the *** Begin Patch / *** End Patch format."}},required:["input"]};function l_(n){let e=n.split(`
|
|
364
|
+
`),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 c_(n,e){let o=[...n.split(`
|
|
365
365
|
`)];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(`
|
|
366
|
-
`)}function Ym(n){return{name:
|
|
367
|
-
`);await n.writeFile(l,c),r.added.push(a.path);break}case"update":{let c=await n.readFile(l),d=
|
|
368
|
-
`)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var
|
|
366
|
+
`)}function Ym(n){return{name:i_,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:a_,execute:async(e,t)=>{let o=l_(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(`
|
|
367
|
+
`);await n.writeFile(l,c),r.added.push(a.path);break}case"update":{let c=await n.readFile(l),d=c_(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(`
|
|
368
|
+
`)||"No changes applied."}],details:{type:"apply_patch",summary:r,errors:s}}}}}var d_="patch",u_={type:"object",properties:{input:{type:"string",description:`Patch content. Supports two formats:
|
|
369
369
|
1) V4A unified diff (*** Begin Patch / *** End Patch markers)
|
|
370
370
|
2) Simple find-replace: first line is file path, then <<<< SEARCH / ==== / >>>> REPLACE blocks.
|
|
371
|
-
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
|
|
371
|
+
Fuzzy matching automatically handles whitespace/indent/unicode drift in the search text.`},replaceAll:{type:"boolean",description:"Replace all occurrences instead of first only (default: false)."}},required:["input"]};function p_(n){return n.replace(/\\n/g,`
|
|
372
372
|
`).replace(/\\t/g," ").replace(/\\'/g,"'").replace(/\\"/g,'"')}function Xm(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 Jm(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 of(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(`
|
|
373
373
|
`).map(f=>f.trim()),i=n.split(`
|
|
374
|
-
`),a=Qm(i,s,(f,y)=>f.trim()===y);if(a)return[{...Zm(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=ef(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[{...Zm(n,i,d),strategy:"indentation_flexible"}];let u=
|
|
374
|
+
`),a=Qm(i,s,(f,y)=>f.trim()===y);if(a)return[{...Zm(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=ef(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[{...Zm(n,i,d),strategy:"indentation_flexible"}];let u=p_(e);if(u!==e&&(r=n.indexOf(u),r!==-1))return[{start:r,end:r+u.length,strategy:"escape_normalized"}];let p=e.split(`
|
|
375
375
|
`);if(p.length>=3){let f=p.slice(1,-1).join(`
|
|
376
376
|
`),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(`
|
|
377
377
|
`).length+1,I=n.indexOf(f,x);if(I!==-1){let P=I+f.length,O=n.indexOf(`
|
|
@@ -386,7 +386,7 @@ Fuzzy matching automatically handles whitespace/indent/unicode drift in the sear
|
|
|
386
386
|
`).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 Zm(n,e,t){let o=e.slice(0,t.startIdx).join(`
|
|
387
387
|
`).length+(t.startIdx>0?1:0),r=e.slice(0,t.endIdx).join(`
|
|
388
388
|
`).length;return{start:o,end:r}}function ef(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 tf(n){let e=n.split(`
|
|
389
|
-
`),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
|
|
389
|
+
`),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 m_(n){let e=[],t=n.split(/^(<<<< SEARCH)$/m);if(t.length<2)return[];let o=t[0].trim().split(`
|
|
390
390
|
`).pop()?.trim();if(!o)return[];for(let r=1;r<t.length;r+=2){let s=t[r+1]||"",i=s.indexOf(`
|
|
391
391
|
====
|
|
392
392
|
`);if(i===-1)continue;let a=s.slice(0,i).replace(/^\n/,""),l=s.slice(i+6),c=l.indexOf(`
|
|
@@ -394,10 +394,10 @@ Fuzzy matching automatically handles whitespace/indent/unicode drift in the sear
|
|
|
394
394
|
`);if(!l)return{content:n+`
|
|
395
395
|
`+s.join(`
|
|
396
396
|
`),strategy:"exact"};let c=of(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(`
|
|
397
|
-
`),p=c[0];return{content:n.slice(0,p.start)+u+n.slice(p.end),strategy:p.strategy}}function tc(n){return{name:
|
|
397
|
+
`),p=c[0];return{content:n.slice(0,p.start)+u+n.slice(p.end),strategy:p.strategy}}function tc(n){return{name:d_,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:u_,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=tf(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(`
|
|
398
398
|
`);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=nf(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=nf(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(`
|
|
399
399
|
`);r.errors.push(`${d.path}: hunk not matched. Search begins with:
|
|
400
|
-
${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=
|
|
400
|
+
${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=m_(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=of(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 tf(`*** Begin Patch
|
|
401
401
|
`+t.input+`
|
|
402
402
|
*** End Patch`).length>0?tc(n).execute(e,{input:`*** Begin Patch
|
|
403
403
|
`+t.input+`
|
|
@@ -405,65 +405,65 @@ ${b}`)}}(h||p!==await n.readFile(u))&&(await n.writeFile(u,p),r.filesModified.pu
|
|
|
405
405
|
Errors:
|
|
406
406
|
${r.errors.join(`
|
|
407
407
|
`)}`);let l=r.errors.length===0;return{content:[{type:"text",text:a.join(`
|
|
408
|
-
`)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var
|
|
408
|
+
`)||"No changes applied."}],details:{type:"patch",...r,success:l}}}}}var f_="web_fetch",g_={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"]},h_=5e4;function rf(n){return{name:f_,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:g_,isReadOnly:!0,execute:async(e,t)=>{let o=await n.fetchUrl({url:t.url,extractMode:t.extractMode,maxChars:t.maxChars??h_,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}
|
|
409
409
|
|
|
410
410
|
${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}
|
|
411
411
|
`),r.push(o.content),o.relevantExcerpts?.length){r.push(`
|
|
412
412
|
---
|
|
413
413
|
## Relevant Excerpts
|
|
414
414
|
`);for(let s of o.relevantExcerpts)r.push(`- ${s}`)}return{content:[{type:"text",text:r.join(`
|
|
415
|
-
`)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!o.extraction,extraction:o.extraction}}}}}var
|
|
416
|
-
`)}],details:{type:"web_search",query:o.query,resultCount:o.results.length}}}}}var
|
|
415
|
+
`)}],details:{type:"web_fetch",url:t.url,extractMode:t.extractMode??"markdown",hasExtraction:!!o.extraction,extraction:o.extraction}}}}}var y_="web_search",b_={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"]},k_=10;function sf(n){return{name:y_,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:b_,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:k_});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(`
|
|
416
|
+
`)}],details:{type:"web_search",query:o.query,resultCount:o.results.length}}}}}var v_="instructions",S_={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 af(n){return{name:v_,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:S_,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(`
|
|
417
417
|
`);return{content:[{type:"text",text:`Found ${o.length} instruction file(s):
|
|
418
|
-
${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
|
|
418
|
+
${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 T_="worktree",w_={type:"object",properties:{action:{type:"string",enum:["enter","exit","list"],description:`enter: Create and switch to an isolated git worktree branch.
|
|
419
419
|
exit: Leave worktree (keep or remove it).
|
|
420
|
-
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"]},
|
|
420
|
+
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"]},x_=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function lf(n){return{name:T_,label:"Git Worktree",description:"Create isolated git worktree branches for parallel development. Each worktree has its own working directory independent of the main branch. Use for: parallel features, safe experimentation, sub-agent isolation. Exit to keep or remove the worktree when done.",parameters:w_,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&&!x_.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(`
|
|
421
421
|
`)}],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."}
|
|
422
422
|
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(`
|
|
423
|
-
`)}],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
|
|
424
|
-
`).filter(Boolean).length}async function pf(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 kf(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=_n(n,r),i=_n(e,r);try{await
|
|
425
|
-
`).find($=>$.startsWith("worktree ")&&$.includes(c));if(h){let $=h.replace("worktree ","").trim(),W=process.cwd();return process.chdir($),rt={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
|
|
423
|
+
`)}],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 R_}from"node:child_process";import{promisify as __}from"node:util";import{join as _n,resolve as cf,basename as nc}from"node:path";import{mkdir as gf,rm as hf,symlink as A_,readdir as L$,stat as P_}from"node:fs/promises";var Ho=__(R_),I_=/^[a-zA-Z0-9._-]+$/,df=64;function yf(n){if(n.length>df)throw new Error(`Invalid worktree name: must be ${df} 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(!I_.test(e))throw new Error(`Invalid worktree name "${n}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function oc(n){return n.replaceAll("/","+")}function bf(n){return`worktree-${oc(n)}`}var rt=null;async function $e(n,e){try{let{stdout:t,stderr:o}=await Ho("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 Go(n){let{stdout:e,code:t}=await $e(["rev-parse","--show-toplevel"],n);return t===0?e.trim():null}async function uf(n){let{stdout:e,code:t}=await $e(["status","--porcelain"],n);return t!==0?-1:e.trim().split(`
|
|
424
|
+
`).filter(Boolean).length}async function pf(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 kf(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=_n(n,r),i=_n(e,r);try{await A_(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 C_(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 E_(){try{return await Ho("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function M_(n,e){return`${nc(n)}_${e}`.replace(/[/.]/g,"_")}async function O_(n,e){if(!await E_())return null;try{return await Ho("tmux",["new-session","-d","-s",e,"-c",n],{timeout:1e4}),e}catch{return null}}async function mf(n){try{return await Ho("tmux",["kill-session","-t",n],{timeout:5e3}),!0}catch{return!1}}async function ff(n,e,t,o){let r=up(e),s=_n(r,n);try{if(!(await P_(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await Ho(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 vf(n,e,t){yf(e);let o=oc(e),r=bf(e),s=_n(n,".worktrees"),i=_n(s,o);await gf(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 kf(n,i,["node_modules"],t),t?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:r})}async function Sf(n,e,t,o){let{code:r}=await $e(["worktree","remove","--force",e],n);return r!==0&&(await hf(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 Tf(n){let{log:e,symlinkDirs:t=["node_modules"],sparsePaths:o}=n;return{async enterWorktree(r){try{let s=Date.now(),i=await Go();if(!i)return{success:!1,error:"Not in a git repository"};let a=await ff("worktree-create",i,{WORKTREE_NAME:r??""},e);if(a){let $=process.cwd();return process.chdir(a),rt={originalCwd:$,worktreePath:a,worktreeName:r??nc(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:rt.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let l=r??`agent-${Date.now().toString(36)}`;yf(l);let c=oc(l),d=bf(l),u=_n(i,".worktrees"),p=_n(u,c);await gf(u,{recursive:!0});let{stdout:m}=await $e(["worktree","list","--porcelain"],i),h=m.split(`
|
|
425
|
+
`).find($=>$.startsWith("worktree ")&&$.includes(c));if(h){let $=h.replace("worktree ","").trim(),W=process.cwd();return process.chdir($),rt={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 C_(p,i,o),x=!0),await kf(i,p,t,e);let I=process.cwd();process.chdir(p);let P=M_(i,d),O=await O_(p,P);return rt={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(!rt)return{success:!1,error:"Not in a worktree"};try{let i=rt,a=await Go(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(r==="remove"){let l=await uf(i.worktreePath),c=await pf(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),rt=null,i.tmuxSessionName&&await mf(i.tmuxSessionName),await ff("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 hf(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 mf(i.tmuxSessionName),rt=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(`
|
|
426
426
|
|
|
427
427
|
`).filter(Boolean);for(let c of l){let d=c.split(`
|
|
428
|
-
`),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=cf(u)===cf(a),h=await uf(u),f=await pf(u,p);i.push({name:p.startsWith("worktree-")?p.slice(9):nc(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 rt!==null},currentWorktree(){return rt?{name:rt.worktreeName,path:rt.worktreePath,branch:rt.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as
|
|
428
|
+
`),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=cf(u)===cf(a),h=await uf(u),f=await pf(u,p);i.push({name:p.startsWith("worktree-")?p.slice(9):nc(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 rt!==null},currentWorktree(){return rt?{name:rt.worktreeName,path:rt.worktreePath,branch:rt.worktreeBranch,isCurrent:!0,hasChanges:!1,unpushedCommits:0}:null}}}import{readFile as D_,writeFile as L_}from"node:fs/promises";import*as wf from"node:path";var N_={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 xf(n){let e=n.split(`
|
|
429
429
|
`);return e.map((t,o)=>o<e.length-1?t+`
|
|
430
|
-
`:t)}function Rf(n){return n.join("")}function
|
|
430
|
+
`:t)}function Rf(n){return n.join("")}function $_(n,e){let t=Rf(n.source).trim(),o=t.length>80?t.slice(0,80)+"...":t;return`Cell ${e+1} [${n.cell_type}]: ${o}`}function U_(n,e){let t={cell_type:n,source:xf(e),metadata:{}};return n==="code"&&(t.execution_count=null,t.outputs=[]),t}function _f(){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:N_,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=wf.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 D_(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=Rf(m.source);m.source=xf(e.new_source),m.cell_type==="code"&&(m.execution_count=null,m.outputs=[]),d=`Replaced cell ${o} [${m.cell_type}].
|
|
431
431
|
Old: ${h.slice(0,120)}${h.length>120?"...":""}
|
|
432
|
-
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=
|
|
433
|
-
`;await
|
|
432
|
+
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=U_(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)+`
|
|
433
|
+
`;await L_(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)=>$_(m,h)).join(`
|
|
434
434
|
`),p=a.cells.length>10?`
|
|
435
435
|
... and ${a.cells.length-10} more cells`:"";return{content:[{type:"text",text:`${d}
|
|
436
436
|
|
|
437
437
|
Current cells:
|
|
438
|
-
${u}${p}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:o,total_cells:a.cells.length}}}}}le();import{readFile as
|
|
438
|
+
${u}${p}`}],details:{type:"notebook_edit",edit_mode:r,cell_number:o,total_cells:a.cells.length}}}}}le();import{readFile as j_,readdir as F_}from"node:fs/promises";import*as Pf from"node:path";import{existsSync as B_}from"node:fs";var W_={type:"object",properties:{action:{type:"string",enum:["list","run","describe"],description:`list: Show available workflows.
|
|
439
439
|
run: Execute a workflow by name.
|
|
440
|
-
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 rc(n){let e=new Map,t=cp(n);await Af(t,e);let o=ap();return await Af(o,e),e}async function Af(n,e){if(
|
|
440
|
+
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 rc(n){let e=new Map,t=cp(n);await Af(t,e);let o=ap();return await Af(o,e),e}async function Af(n,e){if(B_(n))try{let t=await F_(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,Pf.join(n,o.name))}}catch{}}async function sc(n){let e=await j_(n,"utf-8");return JSON.parse(e)}function G_(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 H_(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 If(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:W_,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 rc(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 sc(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(`
|
|
441
441
|
`)}],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 rc(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await sc(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(`
|
|
442
|
-
`)}],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 rc(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await sc(i),l={...a.variables,...t.variables},c;try{c=
|
|
443
|
-
`)}],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
|
|
444
|
-
`),parameters:
|
|
445
|
-
`)}],details:{...l,requestedSeconds:r}}}finally{o?.removeEventListener("abort",a)}}}}var
|
|
442
|
+
`)}],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 rc(r)).get(t.workflow);if(!i)return{content:[{type:"text",text:`Error: Workflow "${t.workflow}" not found.`}],details:{error:"not_found"}};let a=await sc(i),l={...a.variables,...t.variables},c;try{c=G_(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=H_(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(`
|
|
443
|
+
`)}],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 V_="sleep",K_={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 Cf(n){return{name:V_,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(`
|
|
444
|
+
`),parameters:K_,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(`
|
|
445
|
+
`)}],details:{...l,requestedSeconds:r}}}finally{o?.removeEventListener("abort",a)}}}}var z_="tool_search",q_={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"]},Y_=5;function Mf(n){return{name:z_,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:q_,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??Y_;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 Ef(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(`
|
|
446
446
|
`)}],details:{type:"tool_search",activated:a,notFound:l,mode:"select"}}}let s=await n.searchTools(o,{maxResults:r});return Ef(s)}}}function Ef(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(`
|
|
447
|
-
`)}],details:{type:"tool_search",query:n.query,matchCount:n.matches.length,totalDeferred:n.totalDeferred,matches:n.matches.map(t=>t.name)}}}var ic="image_generate",q_={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 Of(n){return{name:ic,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:q_,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 Y_={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 Df(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:Y_,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 ac="video_generate",X_={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 Lf(n){return{name:ac,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:X_,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 lc="music_generate",J_={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 Nf(n){return{name:lc,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:J_,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 Q_="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 $f(n){return{name:Q_,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 eA="video_merge",tA={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 Uf(n){return{name:eA,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:tA,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 nA="video_upscale",oA={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 jf(n){return{name:nA,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:oA,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 rA="three_d_generate",sA={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 Ff(n){return{name:rA,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:sA,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 iA={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 Bf(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:iA,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 aA="voice_clone",lA={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 Wf(n){return{name:aA,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:lA,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 cA="media_cancel",dA={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 Gf(n){return{name:cA,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:dA,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 uA="file_upload",pA={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 Hf(n){return{name:uA,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:pA,execute:async(e,t)=>{let o=await n.uploadFile({filePath:t.file_path,purpose:t.purpose}),r=[`Uploaded "${o.filename}" (${cc(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(`
|
|
448
|
-
`)}],details:{type:"file_upload",fileId:o.fileId,url:o.url,filename:o.filename,bytes:o.bytes,provider:o.provider}}}}}var
|
|
447
|
+
`)}],details:{type:"tool_search",query:n.query,matchCount:n.matches.length,totalDeferred:n.totalDeferred,matches:n.matches.map(t=>t.name)}}}var ic="image_generate",X_={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 Of(n){return{name:ic,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:X_,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 J_={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 Df(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:J_,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 ac="video_generate",Q_={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 Lf(n){return{name:ac,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:Q_,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 lc="music_generate",Z_={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 Nf(n){return{name:lc,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:Z_,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 eA="video_edit",tA={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 $f(n){return{name:eA,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:tA,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 nA="video_merge",oA={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 Uf(n){return{name:nA,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:oA,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 rA="video_upscale",sA={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 jf(n){return{name:rA,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:sA,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 iA="three_d_generate",aA={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 Ff(n){return{name:iA,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:aA,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 lA={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 Bf(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:lA,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 cA="voice_clone",dA={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 Wf(n){return{name:cA,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:dA,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 uA="media_cancel",pA={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 Gf(n){return{name:uA,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:pA,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 mA="file_upload",fA={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 Hf(n){return{name:mA,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:fA,execute:async(e,t)=>{let o=await n.uploadFile({filePath:t.file_path,purpose:t.purpose}),r=[`Uploaded "${o.filename}" (${cc(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(`
|
|
448
|
+
`)}],details:{type:"file_upload",fileId:o.fileId,url:o.url,filename:o.filename,bytes:o.bytes,provider:o.provider}}}}}var gA="file_query",hA={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 Vf(n){return{name:gA,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:hA,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: ${cc(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(`
|
|
449
449
|
`)}],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):
|
|
450
450
|
`];for(let i of r)s.push(`- ${i.filename} | ID: ${i.id} | ${cc(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
|
|
451
|
-
`)}],details:{type:"file_query",count:r.length}}}}}var
|
|
452
|
-
`)}],details:{type:"ask_user",answers:r,questionCount:t.questions.length}}}}}var
|
|
453
|
-
`),parameters:
|
|
451
|
+
`)}],details:{type:"file_query",count:r.length}}}}}var yA="file_delete",bA={type:"object",properties:{file_id:{type:"string",description:"ID of the uploaded file to delete."}},required:["file_id"]};function Kf(n){return{name:yA,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:bA,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 cc(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var kA="ask_user",vA={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 zf(n){return{name:kA,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:vA,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(`
|
|
452
|
+
`)}],details:{type:"ask_user",answers:r,questionCount:t.questions.length}}}}}var SA="project_switch",TA={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 qf(n){return{name:SA,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(`
|
|
453
|
+
`),parameters:TA,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();el();function Yf(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 wA=[{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"}],xA=[/\.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 Xf(){return[...wA]}function dc(n){return xA.some(e=>e.test(n))}var yc=!1;function bc(n){yc=n}var Se,Fe={},eg,mc,dn={},tg;function kc(n){tg=n}var AA=new Set(["zhipu","zhipu-openai","zhipu-coding"]),PA="https://open.bigmodel.cn/api/paas/v4";function ng(n,e){if(!(!n||!e)&&AA.has(n))return new ys({baseUrl:PA,apiKey:e})}var og=null,IA;var fc;function rg(n){fc=n}function sg(n){og=n}function ig(n,e,t,o,r){Se=n,Fe=e??{},eg=t,mc=r,dn=o??{},CA()}function vc(n){let e=dn[n];if(!(!e||!Se))return Se.resolveModelById(e.provider,e.model,n)}function CA(){EA(),MA(),OA(),DA()}function EA(){let n=ot(ac);if(!n)return;let e=dn.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 MA(){let n=ot(ic);if(!n)return;let e=vc("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 OA(){let n=ot("tts");if(!n)return;let e=vc("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 DA(){let n=ot(lc);if(!n)return;let e=vc("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 Dt(n){if(!Se)throw new Error(`No media provider configured for ${n.mediaType}`);let e=dn[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};mc&&!r.onProgress&&(r.onProgress=(l,c,d)=>{mc(d??"pending",n.mediaType,l,c,t)});let s=await Jf(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 Jf(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}:
|
|
454
454
|
`+a.map(l=>` - ${l}`).join(`
|
|
455
|
-
`))}async function Jf(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 eg?.(a,l,c),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Lt(n){if(!Se)return!1;let e=dn[n];if(!e)return!1;let t=Se.getTransport(e.provider),o=Fe[e.provider];return!!(t&&o)}function uc(n,e){if(!Lt(n))return!1;let t=dn[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(dn)){if(!e)continue;let t=Se.getTransport(e.provider),o=Fe[e.provider];if(t instanceof ut&&o)return{id:e.provider,type:"volcengine"}}if(Fe.google)return{id:"google",type:"gemini"}}var pc;function ks(){return pc||(pc=new Eo({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),pc}var st=process.cwd(),gc=!1;function ag(n){st=n,gc=!0,ms(n)}function Be(n){return q.isAbsolute(n)?q.normalize(n):q.resolve(st,n)}function Vo(n){let e=q.resolve(st)+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 Qt(n){return Vo(n)?null:`Blocked: path "${n}" is outside the workspace boundary "${st}"`}function Qf(n){let e=n.replace(/\\/g,"/");return e.includes("../")||e.includes("..")}var
|
|
456
|
-
`))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
|
|
457
|
-
`);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 Zf=!1;function
|
|
458
|
-
`),error:f.details?.error}}catch(f){return{result:"",error:f.message}}},getCwd:()=>st};e.push(If(l)),e.push(Cf({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=>gt(u),onSwitched:u=>AA?.(u)};e.push(qf(c)),e.push(Mf({searchTools:async(u,p)=>{let m=p?.maxResults??5,h=ln(),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 $=ot(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=>xm(u)})),e.push({...Of({generateImage:async u=>{let p=await Dt({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:()=>Lt("image")}),e.push({...Df({textToSpeech:async u=>{let p=await Dt({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:()=>Lt("tts")}),e.push({...Lf({generateVideo:async u=>{let p=await Dt({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:()=>Lt("video")}),e.push({...Nf({generateMusic:async u=>{let p=await Dt({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=dn.music;if(!p||!Se)return"";let m=Se.getTransport(p.provider);if(!(m instanceof bn))return"";let h=Fe[p.provider];return h?m.generateLyrics(u,h):""}}),isEnabled:()=>Lt("music")}),e.push({...$f({editVideo:async u=>{let p=await Dt({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:()=>uc("video","edit")}),e.push({...Uf({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 Dt({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:()=>uc("video","merge")}),e.push({...jf({upscaleVideo:async u=>{let p=["upscale"];u.sharpness&&p.push(`sharpness: ${u.sharpness}`);let m=await Dt({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:()=>uc("video","upscale")}),e.push({...Ff({generate3D:async u=>{let p=await Dt({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:()=>Lt("3d")}),e.push({...Bf({speechToText:async u=>{let p=await Dt({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:()=>Lt("stt")}),e.push({...Wf({cloneVoice:async u=>{let p=await Dt({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:()=>Lt("voice_clone")}),e.push({...Gf({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:()=>Lt("video")||Lt("3d")});let d=bs();return e.push({...Hf({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=DA[$]??"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 ut))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({...Vf({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 ut))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 ut))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({...Kf({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 ut))throw new Error("File delete only supported via Volcengine or Google provider.");await p.deleteFile(u.fileId,m)}}),shouldDefer:!0,isEnabled:()=>!!bs()}),wm(e),n?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(u=>u.isEnabled?.()!==!1).length} enabled): ${ln().join(", ")}`),e}import{spawn as XA}from"node:child_process";import{createInterface as JA}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=XA(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=JA({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=QA(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(`
|
|
455
|
+
`))}async function Jf(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 eg?.(a,l,c),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Lt(n){if(!Se)return!1;let e=dn[n];if(!e)return!1;let t=Se.getTransport(e.provider),o=Fe[e.provider];return!!(t&&o)}function uc(n,e){if(!Lt(n))return!1;let t=dn[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(dn)){if(!e)continue;let t=Se.getTransport(e.provider),o=Fe[e.provider];if(t instanceof ut&&o)return{id:e.provider,type:"volcengine"}}if(Fe.google)return{id:"google",type:"gemini"}}var pc;function ks(){return pc||(pc=new Eo({baseUrl:"https://generativelanguage.googleapis.com/v1beta"})),pc}var st=process.cwd(),gc=!1;function ag(n){st=n,gc=!0,ms(n)}function Be(n){return q.isAbsolute(n)?q.normalize(n):q.resolve(st,n)}function Vo(n){let e=q.resolve(st)+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 Qt(n){return Vo(n)?null:`Blocked: path "${n}" is outside the workspace boundary "${st}"`}function Qf(n){let e=n.replace(/\\/g,"/");return e.includes("../")||e.includes("..")}var LA=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),lg=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),hc=new Set,NA={".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 $A(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=q.extname(e).toLowerCase();if(gc){let r=Qt(e);if(r)throw new Error(r)}else if(Qf(n)&&!Vo(e))throw new Error(`Blocked: path traversal "${n}" escapes workspace "${st}"`);if(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/"))throw new Error(`Blocked: reading device/system path ${e}`);if(lg.has(t))return{type:"binary",mimeType:"application/octet-stream"};if(LA.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 hc.add(e),{type:"text",text:o}},validatePath(n){let e=Be(n);if(gc){let t=Qt(e);if(t)return t}else if(Qf(n)&&!Vo(e))return`Blocked: path traversal "${n}" escapes workspace "${st}"`;return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:yc&&dc(e)?"Blocked: reading sensitive file in group chat mode":null}}}function UA(){return{resolvePath:Be,validatePath(n){let e=Be(n),t=Qt(e);return t||(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: writing to device/system path ${e}`:yc&&dc(e)?"Blocked: writing sensitive file in group chat mode":null)},checkReadBeforeWrite(n){try{K.accessSync(n,K.constants.F_OK)}catch{return null}return hc.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=Qt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8"),hc.add(t)}}}function jA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=Qt(e);if(t)throw new Error(t);return K.promises.readFile(e,"utf8")},async writeFile(n,e){let t=Be(n),o=Qt(t);if(o)throw new Error(o);await K.promises.mkdir(q.dirname(t),{recursive:!0}),await K.promises.writeFile(t,e,"utf8")}}}function FA(){return{resolvePath:Be,async readFile(n){let e=Be(n),t=Qt(e);if(t)throw new Error(t);return K.promises.readFile(e,"utf8")},async writeFile(n,e){let t=Be(n),o=Qt(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=Qt(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 BA(){return{resolvePath:Be,async glob(n,e){let t=e.cwd||st,o=e.limit||1e3,r=[],s=!1,i=n.replace(/\\/g,"/").split("/"),a=i.some(d=>d==="**"),l=i[i.length-1]??"*",c=cg(l);try{await Sc(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||st;try{return await GA(n,t,e)}catch{return await HA(n,t,e)}}}}function cg(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 WA=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function Sc(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(WA.has(i.name))continue;await Sc(q.join(n,i.name),e,t,o+1,a)}else if(i.isFile()&&!await e(a))return}}function GA(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("."),_A("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(`
|
|
456
|
+
`))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 HA(n,e,t){let o=new RegExp(n,t.caseInsensitive?"i":""),r=t.headLimit??250,s=t.offset??0,i=t.fileGlob?cg(t.fileGlob):null,a=[],l=!1;return await Sc(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(lg.has(d))return!0;try{let p=(await K.promises.readFile(q.join(e,c),"utf8")).split(`
|
|
457
|
+
`);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 Zf=!1;function VA(){if(!Zf)if(Zf=!0,Rn()){let n=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";Wo(Xl(n))}else if(process.platform==="win32"){let n=KA();Wo(hs(n))}else{let n=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";Wo(hs(n))}}function KA(){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 zA(){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=qA(s)),{content:s,title:YA(s)}}finally{clearTimeout(t)}}}}function qA(n){return n.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s{2,}/g," ").trim()}function YA(n){return n.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function XA(){let n=async(e,t)=>{let{getModelRegistry:o}=await Promise.resolve().then(()=>(ft(),fp)),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)=>Yf(tg,n)(e,t)}}function JA(){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 dg(n){n?.workdir&&(st=n.workdir),VA(),ms(st);let e=[];e.push(Rm()),e.push(_m(void 0,{onTaskCreated:u=>fc?.onTaskCreated?.(u),onTaskCompleted:u=>fc?.onTaskCompleted?.(u)})),e.push(zf({askUser:async u=>og?.(u)??null})),e.push(jm({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(st,f);if(!Vo(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(st,b);if(!Vo(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=$A(),o=UA(),r=jA(),s=FA();e.push(Wm(t)),e.push(Hm(o)),e.push(Vm(r)),e.push(tc(s)),e.push(Ym(s)),e.push(qm(BA())),e.push(rf(zA())),e.push(sf(XA()));let i=JA();e.push(af(i));let a=n?.log??{info:()=>{},warn:()=>{}};e.push(lf(Tf({log:a}))),e.push(_f());let l={invokeTool:async(u,p,m)=>{let h=ot(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(`
|
|
458
|
+
`),error:f.details?.error}}catch(f){return{result:"",error:f.message}}},getCwd:()=>st};e.push(If(l)),e.push(Cf({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=>gt(u),onSwitched:u=>IA?.(u)};e.push(qf(c)),e.push(Mf({searchTools:async(u,p)=>{let m=p?.maxResults??5,h=ln(),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 $=ot(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=>xm(u)})),e.push({...Of({generateImage:async u=>{let p=await Dt({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:()=>Lt("image")}),e.push({...Df({textToSpeech:async u=>{let p=await Dt({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:()=>Lt("tts")}),e.push({...Lf({generateVideo:async u=>{let p=await Dt({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:()=>Lt("video")}),e.push({...Nf({generateMusic:async u=>{let p=await Dt({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=dn.music;if(!p||!Se)return"";let m=Se.getTransport(p.provider);if(!(m instanceof bn))return"";let h=Fe[p.provider];return h?m.generateLyrics(u,h):""}}),isEnabled:()=>Lt("music")}),e.push({...$f({editVideo:async u=>{let p=await Dt({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:()=>uc("video","edit")}),e.push({...Uf({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 Dt({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:()=>uc("video","merge")}),e.push({...jf({upscaleVideo:async u=>{let p=["upscale"];u.sharpness&&p.push(`sharpness: ${u.sharpness}`);let m=await Dt({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:()=>uc("video","upscale")}),e.push({...Ff({generate3D:async u=>{let p=await Dt({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:()=>Lt("3d")}),e.push({...Bf({speechToText:async u=>{let p=await Dt({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:()=>Lt("stt")}),e.push({...Wf({cloneVoice:async u=>{let p=await Dt({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:()=>Lt("voice_clone")}),e.push({...Gf({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:()=>Lt("video")||Lt("3d")});let d=bs();return e.push({...Hf({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=NA[$]??"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 ut))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({...Vf({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 ut))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 ut))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({...Kf({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 ut))throw new Error("File delete only supported via Volcengine or Google provider.");await p.deleteFile(u.fileId,m)}}),shouldDefer:!0,isEnabled:()=>!!bs()}),wm(e),n?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(u=>u.isEnabled?.()!==!1).length} enabled): ${ln().join(", ")}`),e}import{spawn as QA}from"node:child_process";import{createInterface as ZA}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=QA(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=ZA({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=eP(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(`
|
|
459
459
|
`)||"(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+`
|
|
460
|
-
`)}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
|
|
461
|
-
`);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__${
|
|
462
|
-
`)||"(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
|
|
463
|
-
`).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var
|
|
460
|
+
`)}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 eP(n){return n.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as tP}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=tP(),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(`
|
|
461
|
+
`);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__${nP(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(`
|
|
462
|
+
`)||"(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 nP(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();Ol(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 ln())s.startsWith(o)&&as(s);let r=t.toPortableTools();Ol(r),this.log.info(`[mcp] re-injected ${r.length} tools from ${e}`)}};function Tc(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 oP={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function ug(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:oP,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(`
|
|
463
|
+
`).trim()}],details:{type:"list_mcp_resources",count:r.length}}}}}var rP={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 pg(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:rP,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}-
|
|
464
464
|
${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"})-
|
|
465
|
-
[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 Nt from"node:fs";import*as Ko from"node:path";import{pathToFileURL as
|
|
466
|
-
`).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let d=zo.join(i,c),p=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=zo.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=zo.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
|
|
465
|
+
[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 Nt from"node:fs";import*as Ko from"node:path";import{pathToFileURL as sP}from"node:url";var mg={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(!Nt.existsSync(e))continue;let t;try{t=Nt.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let o of t){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let r=Ko.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(!Nt.existsSync(o))continue;let r;try{r=Nt.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=Ko.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=Ko.join(t,f);if(Nt.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=Ko.join(t,"config.json");if(Nt.existsSync(m))try{p=JSON.parse(Nt.readFileSync(m,"utf8"))}catch{}let h={pluginName:e,registerTool:f=>{Pe(f),l.push(f),s++},registerHook:(f,y)=>{let b=mg[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(sP(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 zo from"node:path";function wc(){return rp()}function fg(){return zo.join(wc(),"installed_plugins.json")}function gg(){let n=fg();if(!De.existsSync(n))return{version:1,plugins:[]};try{return JSON.parse(De.readFileSync(n,"utf-8"))}catch{return{version:1,plugins:[]}}}function iP(n){let e=wc();De.existsSync(e)||De.mkdirSync(e,{recursive:!0}),De.writeFileSync(fg(),JSON.stringify(n,null,2),"utf-8")}function aP(n,e){return!(e.blocklist?.includes(n)||e.allowlist&&!e.allowlist.includes(n))}async function lP(n,e,t){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),s=r(o),i=wc(),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(`
|
|
466
|
+
`).pop()?.trim();if(!c)return t.warn(`[marketplace] npm pack returned no output for ${a}`),null;let d=zo.join(i,c),p=c.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=zo.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=zo.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 cP(){return gg().plugins.filter(e=>De.existsSync(e.installPath)).map(e=>e.installPath)}async function dP(n,e){let t=gg(),o=[];for(let r of n.enabledPlugins){let s=r.specifier.split("/").pop()??r.specifier;if(!aP(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 lP(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 iP(t),o}function uP(){let n=ip();if(!De.existsSync(n))return null;try{return JSON.parse(De.readFileSync(n,"utf-8"))}catch{return null}}async function hg(n,e){let t=[...n],o=cP();t.push(...o);let r=uP();if(r&&r.enabledPlugins.length>0)try{let s=await dP(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 mP(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:pP(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"&&fP(o)?o:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&gP(s)?s:"allow";return{mode:r,rules:t,defaultBehavior:i}}function pP(n){let t=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${t}$`,"i")}function mP(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 fP(n){return n==="default"||n==="bypassPermissions"||n==="acceptEdits"||n==="dontAsk"||n==="plan"}function gP(n){return n==="allow"||n==="deny"||n==="ask"}import{randomUUID as _P}from"node:crypto";var hP=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"]),yg=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"]),yP=[/\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],bg=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 kg(n,e,t){let o=n.trim();if(!o)return{decision:"allow",reason:"empty command"};let r=Jl(o)??Ql(o)??void 0;for(let c of yP)if(c.test(o))return{decision:"deny",reason:`matches dangerous pattern: ${c.source}`,destructiveWarning:r};for(let c of hP)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 yg.has(i)||yg.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:r}:e&&t&&e.startsWith(t)&&(bg.has(i)||bg.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:r}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:r}}function bP(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 xc(n,e){return`${n}::${bP(e)}`}var kP=500,_s=class{cache=new Map;get(e,t){let o=xc(e,t),r=this.cache.get(o);if(r)return r.hitCount++,r}set(e,t,o){if(this.cache.size>=kP){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let r=xc(e,t);this.cache.set(r,{shouldBlock:o.shouldBlock,reason:o.reason,classifiedAt:Date.now(),hitCount:0})}has(e,t){return this.cache.has(xc(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 vP=new Set(["read","search","instructions","think","task","memory","skill","tool_search","plan_mode","lsp","brief","web_search","checkpoint"]);function qo(n){return vP.has(n)}var vg=`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.
|
|
467
467
|
|
|
468
468
|
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).
|
|
469
469
|
|
|
@@ -485,7 +485,7 @@ DANGEROUS operations (SHOULD be blocked):
|
|
|
485
485
|
- Running commands with sudo/admin privileges
|
|
486
486
|
- Downloading and executing unknown scripts
|
|
487
487
|
|
|
488
|
-
Respond ONLY with XML. No other text.`;async function Rc(n,e,t,o){let r=Date.now();if(qo(n))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=
|
|
488
|
+
Respond ONLY with XML. No other text.`;async function Rc(n,e,t,o){let r=Date.now();if(qo(n))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-r};let s=SP(t),i=TP(n,e),a=`<transcript>
|
|
489
489
|
${s}
|
|
490
490
|
</transcript>
|
|
491
491
|
|
|
@@ -501,58 +501,58 @@ ${s}
|
|
|
501
501
|
${i}
|
|
502
502
|
</action>
|
|
503
503
|
|
|
504
|
-
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:vg,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=wg(p.text),h=Sg(m),f=Tg(m)??Tg(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
|
|
505
|
-
`)}function
|
|
506
|
-
Arguments: ${o}`}function Sg(n){let e=n.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function Tg(n){let e=n.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function wg(n){return n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var xg={maxConsecutive:3,maxTotal:20};function Rg(){return{consecutiveDenials:0,totalDenials:0}}function _c(n){return{consecutiveDenials:n.consecutiveDenials+1,totalDenials:n.totalDenials+1}}function Ac(n){return n.consecutiveDenials===0?n:{...n,consecutiveDenials:0}}function _g(n){return n.consecutiveDenials>=xg.maxConsecutive||n.totalDenials>=xg.maxTotal}import*as yt from"node:fs";import*as Yo from"node:path";var
|
|
507
|
-
`;yt.appendFileSync(this.filePath,o,"utf-8")}catch{}}};function Ag(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
|
|
508
|
-
`)},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 Pg(n){return{name:
|
|
504
|
+
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:vg,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=wg(p.text),h=Sg(m),f=Tg(m)??Tg(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 SP(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(`
|
|
505
|
+
`)}function TP(n,e){let t=JSON.stringify(e,null,0),o=t.length>2e3?t.slice(0,2e3)+"...":t;return`Tool: ${n}
|
|
506
|
+
Arguments: ${o}`}function Sg(n){let e=n.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function Tg(n){let e=n.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function wg(n){return n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var xg={maxConsecutive:3,maxTotal:20};function Rg(){return{consecutiveDenials:0,totalDenials:0}}function _c(n){return{consecutiveDenials:n.consecutiveDenials+1,totalDenials:n.totalDenials+1}}function Ac(n){return n.consecutiveDenials===0?n:{...n,consecutiveDenials:0}}function _g(n){return n.consecutiveDenials>=xg.maxConsecutive||n.totalDenials>=xg.maxTotal}import*as yt from"node:fs";import*as Yo from"node:path";var wP="audit",xP="denials.jsonl",RP=10*1024*1024,As=class{filePath;writeQueue=Promise.resolve();constructor(e){let t=Yo.join(e,".qlogicagent",wP);this.filePath=Yo.join(t,xP)}record(e){this.writeQueue=this.writeQueue.then(()=>this.doWrite(e)).catch(()=>{})}getFilePath(){return this.filePath}async doWrite(e){try{let t=Yo.dirname(this.filePath);if(yt.existsSync(t)||yt.mkdirSync(t,{recursive:!0}),yt.existsSync(this.filePath)&&yt.statSync(this.filePath).size>RP){let s=this.filePath+".1";yt.renameSync(this.filePath,s)}let o=JSON.stringify(e)+`
|
|
507
|
+
`;yt.appendFileSync(this.filePath,o,"utf-8")}catch{}}};function Ag(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 AP=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=Rg();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:Ag(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=kg(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||qo(o)?{action:"continue"}:this.handleWorkerAsk(t,o,r);if(this.ruleEngine.getMode()==="auto"){if(qo(o))return{action:"continue"};let c=_g(this.denialTracking);if(this.classifierLLMCall&&!c)try{let d=this.getRecentMessages?.()??[],u=await Rc(o,r??{},d,this.classifierLLMCall);if(r&&this.classifierCache.set(o,r,{shouldBlock:u.shouldBlock,reason:u.reason}),!u.shouldBlock)return this.denialTracking=Ac(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:u.reason}}};this.denialTracking=_c(this.denialTracking)}catch{}}let a=_P(),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(qo(t))return{action:"continue"};if(this.classifierLLMCall)try{let r=this.getRecentMessages?.()??[],s=await Rc(t,o??{},r,this.classifierLLMCall);return o&&this.classifierCache.set(t,o,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=_c(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=Ac(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"))},AP);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 PP="skill",IP={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(`
|
|
508
|
+
`)},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 Pg(n){return{name:PP,label:"Skill",description:NP(n),parameters:IP,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 CP(n,t,o);case"list":return EP(n,t);case"view":return MP(n,t);case"create":case"edit":case"patch":case"delete":return OP(n,t);case"promote":return DP(n,t);case"install":return LP(n,t);default:return{content:[{type:"text",text:`Unknown action: ${r}. Use invoke, list, view, create, edit, patch, delete, promote, or install.`}]}}}}}async function CP(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}
|
|
509
509
|
|
|
510
510
|
`,a=r?`
|
|
511
511
|
|
|
512
512
|
### User Context
|
|
513
513
|
${r}`:"";return{content:[{type:"text",text:`${i}Follow these instructions:
|
|
514
514
|
|
|
515
|
-
${s}${a}`}],details:{skillName:o,action:"invoke",mode:"inline"}}}async function
|
|
516
|
-
`)}],details:{action:"list",count:t.skills.length}}}async function
|
|
515
|
+
${s}${a}`}],details:{skillName:o,action:"invoke",mode:"inline"}}}async function EP(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(`
|
|
516
|
+
`)}],details:{action:"list",count:t.skills.length}}}async function MP(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}
|
|
517
517
|
`,t.content];return t.referenceFiles&&t.referenceFiles.length>0&&o.push(`
|
|
518
518
|
### Reference Files
|
|
519
519
|
${t.referenceFiles.map(r=>`- ${r}`).join(`
|
|
520
520
|
`)}`),{content:[{type:"text",text:o.join(`
|
|
521
|
-
`)}],details:{action:"view",name:t.name}}}async function
|
|
521
|
+
`)}],details:{action:"view",name:t.name}}}async function OP(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 DP(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 LP(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 NP(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.
|
|
522
522
|
|
|
523
523
|
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(`
|
|
524
524
|
`);return`${t}
|
|
525
525
|
|
|
526
526
|
Available skills:
|
|
527
|
-
${o}`}var
|
|
527
|
+
${o}`}var $P="agent",Ig=["general","explore","plan","code","research","verify"],UP={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
|
|
528
528
|
- general: Full tool access, any task
|
|
529
529
|
- explore: Read-only codebase exploration (search, read, analyze)
|
|
530
530
|
- plan: Planning mode (explore + produce plan, no writes)
|
|
531
531
|
- code: Coding agent with full tool access
|
|
532
532
|
- research: Web research and information gathering
|
|
533
|
-
- 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},Cg=4;function Eg(n){return{name
|
|
533
|
+
- 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},Cg=4;function Eg(n){return{name:$P,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:UP,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(!Ig.includes(t.agent))return{content:[{type:"text",text:`Error: unknown agent "${t.agent}". Available: ${Ig.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let o=n.currentForkDepth??0;if(o>=Cg)return{content:[{type:"text",text:`Error: maximum fork depth (${Cg}) 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.
|
|
534
534
|
Agent ID: ${r.agentId}
|
|
535
535
|
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?`
|
|
536
536
|
|
|
537
|
-
[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
|
|
537
|
+
[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 jP="config",FP={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
|
|
538
538
|
- get: Read a config setting
|
|
539
539
|
- set: Write a config setting
|
|
540
540
|
- list: List all available settings
|
|
541
|
-
- 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"]},Xo=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Mg(n){return{name
|
|
541
|
+
- 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"]},Xo=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function Mg(n){return{name:jP,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:FP,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(`
|
|
542
542
|
`)}],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(Xo.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(`
|
|
543
|
-
`)}],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(Xo.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
|
|
543
|
+
`)}],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(Xo.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 BP="cron",WP={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:
|
|
544
544
|
- Cron: '0 9 * * *' (every day at 9am)
|
|
545
545
|
- Shorthand: '5m' (every 5 min), '1h' (hourly), '1d' (daily)
|
|
546
|
-
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"]},Og=50;function Dg(n){return{name:
|
|
546
|
+
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"]},Og=50;function Dg(n){return{name:BP,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:WP,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>=Og)return{content:[{type:"text",text:`Error: maximum ${Og} 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:Pc(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(`
|
|
547
547
|
`)}],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:Pc(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.
|
|
548
548
|
${Pc(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 Pc(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(`
|
|
549
|
-
`)}var
|
|
550
|
-
`),parameters:
|
|
549
|
+
`)}var GP="monitor",HP={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 Lg(n){return{name:GP,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(`
|
|
550
|
+
`),parameters:HP,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:
|
|
551
551
|
${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.eventCount}, timeout: ${l.timeoutSeconds}s)`).join(`
|
|
552
|
-
`)}`}],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
|
|
552
|
+
`)}`}],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 VP="team",KP={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 Ng(n){return{name:VP,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:KP,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(`
|
|
553
553
|
`)}],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(`
|
|
554
554
|
`)}],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(`
|
|
555
|
-
`)}],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
|
|
555
|
+
`)}],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 qP="mcp",YP={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:
|
|
556
556
|
- list_servers: List configured MCP servers, their status and capabilities
|
|
557
557
|
- list_tools: List tools provided by a specific server
|
|
558
558
|
- call_tool: Execute a tool on an MCP server
|
|
@@ -561,12 +561,12 @@ ${i.map(l=>`\u2022 ${l.monitorId} [${l.source}] \u2192 ${l.target} (events: ${l.
|
|
|
561
561
|
- list_prompts: List prompts available from a server
|
|
562
562
|
- get_prompt: Get a specific prompt with arguments
|
|
563
563
|
- authenticate: Initiate OAuth authentication with a server
|
|
564
|
-
- 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 $g(n){return{name:
|
|
564
|
+
- 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 $g(n){return{name:qP,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).
|
|
565
565
|
|
|
566
|
-
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:
|
|
567
|
-
`)}],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=
|
|
566
|
+
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:YP,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=XP(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(`
|
|
567
|
+
`)}],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=JP(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(`
|
|
568
568
|
`)}],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(`
|
|
569
|
-
`)}],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?` (${
|
|
569
|
+
`)}],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?` (${QP(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(`
|
|
570
570
|
`)}],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(`
|
|
571
571
|
`)||"(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}".
|
|
572
572
|
|
|
@@ -576,23 +576,23 @@ ${r.authUrl}
|
|
|
576
576
|
${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.
|
|
577
577
|
Required scopes: ${r.requiredScopes?.join(", ")||"unknown"}
|
|
578
578
|
|
|
579
|
-
`+(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 Jo("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 Jo("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 Jo("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 Jo("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 Jo(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
|
|
580
|
-
`)}],details:{type:"mcp",action:"manage_server",manageAction:n,server:e,success:t.success}}}var
|
|
579
|
+
`+(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 Jo("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 Jo("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 Jo("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 Jo("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 Jo(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 XP(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 JP(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 QP(n){return n<1024?`${n}B`:n<1024*1024?`${(n/1024).toFixed(1)}KB`:`${(n/(1024*1024)).toFixed(1)}MB`}function Jo(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(`
|
|
580
|
+
`)}],details:{type:"mcp",action:"manage_server",manageAction:n,server:e,success:t.success}}}var ZP="checkpoint",eI={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"]},Ug=/^[0-9a-fA-F]{4,64}$/;function jg(n){return{name:ZP,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:eI,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}
|
|
581
581
|
Message: ${o.checkpoint.message}
|
|
582
582
|
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(`
|
|
583
583
|
`)}],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(!Ug.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(!Ug.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 Fg(n,e){let t=dp(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(`
|
|
584
|
-
`).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
|
|
584
|
+
`).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 tI="notify",nI={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 Bg(n){return{name:tI,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:nI,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 oI="send_message",rI={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 Wg(n){return{name:oI,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:rI,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 sI="repl",iI={type:"object",properties:{code:{type:"string",description:`JavaScript code to execute. The VM has access to these built-in primitives:
|
|
585
585
|
- readFile(path): Promise<string> \u2014 read a file
|
|
586
586
|
- writeFile(path, content): Promise<void> \u2014 write a file
|
|
587
587
|
- editFile(path, edits): Promise<string> \u2014 apply edits [{oldText, newText}]
|
|
588
588
|
- exec(command): Promise<{stdout, stderr, exitCode}> \u2014 run shell command
|
|
589
589
|
- glob(pattern): Promise<string[]> \u2014 find files by glob
|
|
590
590
|
- grep(pattern, path?): Promise<{file,line,text}[]> \u2014 search files
|
|
591
|
-
Use this for batch operations (rename many files, transform data, etc) to reduce tool call round-trips.`}},required:["code"]};var Gg=1e5,Hg=5e4;function Vg(n){return{name:
|
|
591
|
+
Use this for batch operations (rename many files, transform data, etc) to reduce tool call round-trips.`}},required:["code"]};var Gg=1e5,Hg=5e4;function Vg(n){return{name:sI,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:iI,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>Gg)return{content:[{type:"text",text:`Error: code too large (${t.code.length} chars, max ${Gg}).`}],details:{type:"repl",error:"code_too_large"}};let o=await n.executeInVm(t.code),r=o.output||"";return r.length>Hg&&(r=r.slice(0,Hg)+`
|
|
592
592
|
... (truncated)`),o.error?{content:[{type:"text",text:`Error: ${o.error}
|
|
593
593
|
|
|
594
594
|
Output:
|
|
595
|
-
${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
|
|
595
|
+
${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 aI={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
596
596
|
- goToDefinition: jump to symbol definition
|
|
597
597
|
- findReferences: find all usages of a symbol
|
|
598
598
|
- hover: get type/docs for symbol at position
|
|
@@ -601,29 +601,29 @@ ${r}`}],details:{type:"repl",error:o.error,duration:o.duration}}:{content:[{type
|
|
|
601
601
|
- completion: get completions at position
|
|
602
602
|
- signatureHelp: get function signature at call site
|
|
603
603
|
- rename: preview rename of symbol
|
|
604
|
-
- 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"]},
|
|
604
|
+
- 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"]},lI=10*1024*1024,cI=["goToDefinition","findReferences","hover","completion","signatureHelp","rename","codeAction"];function Kg(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:aI,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(cI.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>lI)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:dI(t.operation,r)}],details:{type:"lsp",operation:t.operation}}}}}function dI(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(`
|
|
605
605
|
`)}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(`
|
|
606
606
|
`)}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(`
|
|
607
607
|
`)}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(`
|
|
608
608
|
`)}case"signatureHelp":return e.signatures.length===0?"No signature information available.":e.signatures.join(`
|
|
609
609
|
`);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(`
|
|
610
610
|
`)}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(`
|
|
611
|
-
`)}default:return"Unknown result type."}}je();import{spawn as Cc}from"node:child_process";import{createInterface as Cs}from"node:readline";import{resolve as
|
|
612
|
-
`)}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=
|
|
613
|
-
`)}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:uI,clientInfo:{name:"qlogicagent",version:"1.0.0"},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,auth:{terminal:!1}}},pI),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 bt.AGENT_MESSAGE_CHUNK:{let a=r.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:i,messageId:r.messageId}}}case bt.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:r.content?.text??"",sessionId:i}};case bt.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 bt.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 bt.USAGE_UPDATE:return{method:"turn.usage_update",params:r??{}};case bt.PLAN:return{method:"turn.plan",params:{steps:r.steps,sessionId:i}};case bt.AVAILABLE_COMMANDS_UPDATE:case bt.CURRENT_MODE_UPDATE:case bt.CONFIG_OPTION_UPDATE:case bt.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:s,...r,sessionId:i}};case bt.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${s??"unknown"}`,params:{...r,sessionId:i}}}}return null}};var Qo=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 qg}from"node:child_process";import{platform as mI}from"node:os";var Ic={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 fI=mI()==="win32";function zg(n){try{let e=fI?`where ${n}`:`which ${n}`;return qg(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function gI(n){try{return qg(`"${n}"version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var hI=6e4,Is=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<hI)return this.cache.agents;let t=[];for(let o of Object.values(Ic))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=zg(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=gI(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=zg(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=Ic[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 TI=1;function wI(n,e){return{jsonrpc:"2.0",id:TI++,method:n,params:e}}var xI=["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 RI(n){let e={};for(let t of xI)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 Ec=la,_I=ca,Qn=da,Yg=ua;function AI(n){return new Promise(e=>setTimeout(e,n))}var un=class n{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=yI(Zo(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Zo(t,"dist","cli.js"),this.mcpBridgeScriptPath=Zo(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=RI(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=Cc(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=wI(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)}
|
|
611
|
+
`)}default:return"Unknown result type."}}je();import{spawn as Cc}from"node:child_process";import{createInterface as Cs}from"node:readline";import{resolve as kI,join as Zo}from"node:path";import{createServer as vI}from"node:net";import{createWriteStream as SI,mkdirSync as TI}from"node:fs";import{tmpdir as wI}from"node:os";import{createInterface as uI}from"node:readline";var pI=1,mI=1,bt={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"},fI=1e4,An=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=uI({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)}
|
|
612
|
+
`)}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=pI++,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)}
|
|
613
|
+
`)}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:mI,clientInfo:{name:"qlogicagent",version:"1.0.0"},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,auth:{terminal:!1}}},fI),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 bt.AGENT_MESSAGE_CHUNK:{let a=r.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:i,messageId:r.messageId}}}case bt.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:r.content?.text??"",sessionId:i}};case bt.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 bt.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 bt.USAGE_UPDATE:return{method:"turn.usage_update",params:r??{}};case bt.PLAN:return{method:"turn.plan",params:{steps:r.steps,sessionId:i}};case bt.AVAILABLE_COMMANDS_UPDATE:case bt.CURRENT_MODE_UPDATE:case bt.CONFIG_OPTION_UPDATE:case bt.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:s,...r,sessionId:i}};case bt.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${s??"unknown"}`,params:{...r,sessionId:i}}}}return null}};var Qo=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 qg}from"node:child_process";import{platform as gI}from"node:os";var Ic={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 hI=gI()==="win32";function zg(n){try{let e=hI?`where ${n}`:`which ${n}`;return qg(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function yI(n){try{return qg(`"${n}"version`,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}var bI=6e4,Is=class{cache=null;configStore=null;setConfigStore(e){this.configStore=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<bI)return this.cache.agents;let t=[];for(let o of Object.values(Ic))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=zg(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=yI(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=zg(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=Ic[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 xI=1;function RI(n,e){return{jsonrpc:"2.0",id:xI++,method:n,params:e}}var _I=["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 AI(n){let e={};for(let t of _I)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 Ec=la,PI=ca,Qn=da,Yg=ua;function II(n){return new Promise(e=>setTimeout(e,n))}var un=class n{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let t=kI(Zo(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=Zo(t,"dist","cli.js"),this.mcpBridgeScriptPath=Zo(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=AI(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=Cc(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=RI(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)}
|
|
614
614
|
`)}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()}})+`
|
|
615
|
-
`;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<=Ec;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=
|
|
616
|
-
`)}),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=Yg*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()}`:Zo(
|
|
615
|
+
`;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<=Ec;s++)try{if(s>0){this.processes.delete(e.memberId),t.state="starting",t.error=void 0,t.endedAt=void 0;let i=PI*s;this.slog("info",e.memberId,"spawn",`retry ${s}/${Ec} after ${i}ms`),await II(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 ${Ec+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=Cc(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 An,d=new Qo,{server:u,pipePath:p}=this.createMcpIpcServer(e.memberId);o.QLOGICAGENT_PARENT_RPC=p;let m;if(this.callbacks.sessionDir)try{TI(this.callbacks.sessionDir,{recursive:!0}),m=SI(Zo(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=An.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}
|
|
616
|
+
`)}),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=Yg*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()}`:Zo(wI(),`qlogicagent-mcp-${t}-${Date.now()}.sock`),r=vI(s=>{let i="";s.on("data",a=>{i+=a.toString();let l;for(;(l=i.indexOf(`
|
|
617
617
|
`))!==-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"}})+`
|
|
618
618
|
`;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})+`
|
|
619
619
|
`;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)}})+`
|
|
620
620
|
`;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}`}})+`
|
|
621
621
|
`;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=Cc(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 An,f=new Qo;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=An.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}
|
|
622
|
-
`)}),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 $=Yg*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 Jg}from"node:path";import{chmod as
|
|
623
|
-
`)}var Qg="agent-configs.json";function Xg(){return Jg(H(),Qg)}function
|
|
622
|
+
`)}),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 $=Yg*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 Jg}from"node:path";import{chmod as UI}from"node:fs/promises";import{readFile as CI,writeFile as EI,mkdir as MI,rename as OI,unlink as DI}from"node:fs/promises";import{dirname as LI,join as NI}from"node:path";import{randomUUID as $I}from"node:crypto";async function Zn(n,e){let t=LI(n);await MI(t,{recursive:!0});let o=NI(t,`.tmp-${$I()}`);try{await EI(o,e,"utf-8");let r;for(let s=0;s<3;s++)try{await OI(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 DI(o).catch(()=>{}),r}}async function Pn(n){try{let e=await CI(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)+`
|
|
623
|
+
`)}var Qg="agent-configs.json";function Xg(){return Jg(H(),Qg)}function jI(n){return Jg(Oe(n),Qg)}function FI(){return{agents:{}}}var Es=class{data=FI();cwd;constructor(e){this.cwd=e}async load(){let e=await Pn(Xg()),t=this.cwd?await Pn(jI(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=Xg();await eo(e,this.data);try{await UI(e,384)}catch{}}};var Zg="memory",eh="Memory",BI=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],th={type:"object",properties:{action:{type:"string",enum:BI,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(`
|
|
624
624
|
`)},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(`
|
|
625
625
|
`)},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"]},nh=["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(`
|
|
626
|
-
`),
|
|
626
|
+
`),WI=[/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 GI(n){return!WI.some(e=>e.test(n))}async function oh(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(`
|
|
627
627
|
`);return{ok:!0,message:`Memory files (${r.length}):
|
|
628
628
|
${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
|
|
629
629
|
`+a.map(l=>`--[${l.file}] ${l.snippet}`).join(`
|
|
@@ -631,8 +631,8 @@ ${s}`,action:t}}if(t==="search"){let r=n.query?.trim();if(!r)return{ok:!1,messag
|
|
|
631
631
|
`+a.map((l,c)=>`${c+1}. ${l.text}`).join(`
|
|
632
632
|
`))}catch{}return s.length===0?{ok:!0,message:"No matching memories found.",action:t,results:[]}:{ok:!0,message:s.join(`
|
|
633
633
|
|
|
634
|
-
`),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(!
|
|
635
|
-
`);
|
|
634
|
+
`),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(!GI(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 Mc,readdir as rh,unlink as HI,stat as VI,mkdir as KI}from"node:fs/promises";import{existsSync as kt,readFileSync as sh,mkdirSync as ih,writeFileSync as zI}from"node:fs";import{join as it}from"node:path";var Ie=12288,Oc=200,Ms=8192,qI="memory",pn="INDEX.md";function Dc(n){return it(Oe(n),qI)}var YI=[/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!YI.some(e=>e.test(n))}var XI=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function Ds(n){return!(!XI.test(n)||n===pn||n.includes("..")||n.includes("/")||n.includes("\\"))}var $t=class{root;indexCache=null;constructor(e){this.root=Dc(e)}getRootPath(){return this.root}ensureInitialized(){kt(this.root)||ih(this.root,{recursive:!0});let e=it(this.root,pn);if(!kt(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(`
|
|
635
|
+
`);JI(e,t)}}getIndexForPrompt(){let e=it(this.root,pn);if(!kt(e))return"";let t;try{t=sh(e,"utf-8")}catch{return""}this.indexCache=t;let o=t.split(`
|
|
636
636
|
`);return o.length>Oc&&(t=o.slice(0,Oc).join(`
|
|
637
637
|
`)+`
|
|
638
638
|
|
|
@@ -653,24 +653,24 @@ ${s}`,action:t}}if(t==="search"){let r=n.query?.trim();if(!r)return{ok:!1,messag
|
|
|
653
653
|
`+t+`
|
|
654
654
|
`;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,`
|
|
655
655
|
|
|
656
|
-
`),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(!kt(this.root))return[];let e=await rh(this.root),t=[];for(let o of e){if(o===pn||!o.endsWith(".md"))continue;let r=it(this.root,o);try{let s=await
|
|
656
|
+
`),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(!kt(this.root))return[];let e=await rh(this.root),t=[];for(let o of e){if(o===pn||!o.endsWith(".md"))continue;let r=it(this.root,o);try{let s=await VI(r);if(!s.isFile())continue;let a=(await Mc(r,"utf-8")).split(`
|
|
657
657
|
`).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=it(this.root,e);if(kt(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=it(this.root,e),r=!kt(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+`
|
|
658
658
|
|
|
659
|
-
`+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let d=`${o}-${c+1}.md`,u=it(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!==pn)return{ok:!1,message:`Invalid filename: "${e}".`};let t=it(this.root,e);try{let o=await Mc(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===pn)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=it(this.root,e);if(!kt(t))return{ok:!1,message:`File not found: "${e}".`};await
|
|
659
|
+
`+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let d=`${o}-${c+1}.md`,u=it(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!==pn)return{ok:!1,message:`Invalid filename: "${e}".`};let t=it(this.root,e);try{let o=await Mc(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===pn)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=it(this.root,e);if(!kt(t))return{ok:!1,message:`File not found: "${e}".`};await HI(t);let o=this.getIndexRaw(),r=new RegExp(`^.*\\[${QI(e)}\\].*$\\n?`,"m");if(r.test(o)){let s=o.replace(r,"").replace(/\n{3,}/g,`
|
|
660
660
|
|
|
661
661
|
`);await this.writeIndex(s)}return{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}}async searchLocal(e){if(!kt(this.root))return[];let t=e.toLowerCase().split(/\s+/).filter(s=>s.length>1);if(t.length===0)return[];let o=await rh(this.root),r=[];for(let s of o){if(!s.endsWith(".md"))continue;let i=it(this.root,s);try{let a=await Mc(i,"utf-8"),l=a.toLowerCase(),c=t.filter(m=>l.includes(m)).length;if(c===0)continue;let d=a.split(`
|
|
662
|
-
`),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(it(this.root,pn),e),this.indexCache=e}async ensureDir(){kt(this.root)||await
|
|
662
|
+
`),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(it(this.root,pn),e),this.indexCache=e}async ensureDir(){kt(this.root)||await KI(this.root,{recursive:!0})}async appendIndexEntry(e){let t=this.getIndexRaw();if(t.includes(e))return;let o=t.endsWith(`
|
|
663
663
|
`)?t+e+`
|
|
664
664
|
`:t+`
|
|
665
665
|
`+e+`
|
|
666
|
-
`;Buffer.byteLength(o,"utf-8")<=Ie&&await this.writeIndex(o)}};function YI(n,e){let t=it(n,"..");kt(t)||ih(t,{recursive:!0}),VI(n,e,"utf-8")}function XI(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ah(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function JI(n){return n.latestInputTokens+n.cumulativeOutputTokens}var QI=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),lh=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function ZI(n){return{isSearch:QI.has(n)||void 0,isRead:lh.has(n)||void 0}}function eC(n,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${lh.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 ch(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 dh(n,e,t,o){n.toolUseCount++;let r=ZI(e),s={toolName:e,input:t,activityDescription:o?.(e,t)??eC(e,t),isSearch:r.isSearch,isRead:r.isRead};for(n.recentActivities.push(s);n.recentActivities.length>5;)n.recentActivities.shift()}function Lc(n){return{toolUseCount:n.toolUseCount,tokenCount:JI(n),lastActivity:n.recentActivities.length>0?n.recentActivities[n.recentActivities.length-1]:void 0,recentActivities:[...n.recentActivities]}}import{randomUUID as uh}from"node:crypto";function tC(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 Nc(n){let e=Date.now(),t=[],o={inputTokens:0,outputTokens:0},r=ah(),{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,$=tC(k),W=`fork-${f}-${uh().slice(0,8)}`,S=`fork-session-${uh().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(()=>(pl(),Op)),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&&(ch(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{}dh(r,ne.name,Q),I?.(Lc(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:Lc(r),durationMs:ve,ok:de,error:j}}Ca();Pa();je();var $c=class{teamBudget={tokensUsed:0,budgetTokens:Zi};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 $c;le();import{readFile as nC}from"node:fs/promises";import{watch as oC}from"node:fs";import{join as rC}from"node:path";var sC=He,iC="settings.json";function aC(n){return rC(n,sC,iC)}async function lC(n){try{let e=await nC(n,"utf-8");return JSON.parse(e)}catch{return null}}function cC(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 ph(n){let e=aC(n.projectRoot),t=null,o=null,r=async()=>{let s=await lC(e);s&&cC(s,n.ruleEngine,n.hooks,n.log)};r().catch(()=>{});try{t=oC(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 Uc=new Set;function In(n){return Uc.add(n),()=>{Uc.delete(n)}}async function mh(){await Promise.all(Array.from(Uc).map(n=>n()))}le();ft();var Ls="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",to=class extends Error{constructor(e=Ls){super(e),this.name="LlmrouterCatalogUnavailableError"}};function dC(){let n=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim().replace(/\/+$/,"");if(!n)throw new to;return n}function uC(){let n={accept:"application/json"},e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return e&&(n.authorization=`Bearer ${e}`),n}async function fh(n){let e=dC(),t;try{t=await fetch(`${e}${n}`,{method:"GET",headers:uC(),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:hC(o)&&Array.isArray(o.data)?o.data:null;if(!r)throw new to;return r}async function Ns(){return fh("/ext/model-catalog/providers")}async function pC(){return fh("/ext/model-catalog/models")}function jc(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 Fc(n){return(await Ns()).find(t=>t.id===n)??null}async function er(n){let e=await pC();n.migrateModelIds(mC(e));let t=e.map(fC).filter(o=>!!o);return n.replaceCatalogModels(t),t}function mC(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 fC(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:gC(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 gC(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 hC(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}je();import{join as Bc}from"node:path";import{mkdirSync as yC,existsSync as bC,createWriteStream as kC}from"node:fs";import{pipeline as vC}from"node:stream/promises";import{Readable as SC}from"node:stream";var TC=ia,wC=aa,gh={"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??TC,this.timeoutMs=e?.timeoutMs??wC}setProjectDir(e){this.projectDir=e}resolveMediaDir(e){if(!this.projectDir)throw new Error("MediaPersistence requires projectDir \u2014 call setProjectDir() first");if(!e)return Bc(this.projectDir,".qlogicagent","media",xC());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`),Bc(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.`);bC(o)||yC(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=_C(e,c),u=RC(t?.type??AC(c),d);i=Bc(o,u);let p=a.body;if(!p)throw new Error("No response body");let m=kC(i);await vC(SC.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 xC(){let n=new Date;return`${n.getFullYear()}${String(n.getMonth()+1).padStart(2,"0")}${String(n.getDate()).padStart(2,"0")}`}function RC(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 _C(n,e){if(gh[e])return gh[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 AC(n){return n.startsWith("image/")?"image":n.startsWith("video/")?"video":n.startsWith("audio/")?"audio":n.startsWith("model/")?"3d":"file"}import{join as PC}from"node:path";import{readFileSync as IC,writeFileSync as CC,mkdirSync as EC}from"node:fs";var Cn=null,Wc=!1;function hh(n){return PC(n,"skill-stats.json")}function Gc(n){if(Cn)return Cn;try{Cn=JSON.parse(IC(hh(n),"utf8"))}catch{Cn={}}return Cn}function MC(n){if(!(!Wc||!Cn))try{EC(n,{recursive:!0}),CC(hh(n),JSON.stringify(Cn,null,2),"utf8"),Wc=!1}catch{}}function js(n,e,t){let o=Gc(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),Wc=!0,MC(n)}function yh(n,e){return Gc(n)[e]}function bh(n){return Gc(n)}import{existsSync as OC,readFileSync as DC,writeFileSync as LC,mkdirSync as vh,renameSync as NC}from"node:fs";import{join as Hc,dirname as Sh}from"node:path";var kh=30,$C=90,UC="skill-lifecycle.json";function Th(n){return Hc(n,UC)}function We(n){let e=Th(n);try{return JSON.parse(DC(e,"utf8"))}catch{return{version:1,records:{}}}}function Ve(n,e){let t=Th(n);vh(Sh(t),{recursive:!0});let o=t+".tmp";LC(o,JSON.stringify(e,null,2),"utf8");let{renameSync:r}=yi("node:fs");r(o,t)}function Zt(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 Vc(n,e){let t=Zt(n,e);t.lastUsedAt=new Date().toISOString(),t.useCount++,t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function Kc(n,e){let t=Zt(n,e);t.lastPatchedAt=new Date().toISOString(),t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function wh(n,e){let t=n.records[e];return t?(t.pinned=!0,!0):!1}function xh(n,e){let t=n.records[e];return t?(t.pinned=!1,!0):!1}function jC(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 FC(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=jC(r),i=(e-s.getTime())/(1e3*60*60*24);r.state==="active"&&i>=kh?(r.state="stale",r.staleAt=new Date().toISOString(),t.transitioned.push({name:o,from:"active",to:"stale"})):r.state==="stale"&&i>=$C?(r.state="archived",r.archivedAt=new Date().toISOString(),t.transitioned.push({name:o,from:"stale",to:"archived"})):r.state==="stale"&&i<kh&&(r.state="active",r.staleAt=void 0,t.transitioned.push({name:o,from:"stale",to:"active"}))}return t}function BC(n,e){let t=Hc(n,e);if(!OC(t))return!1;let o=Hc(n,".archive",e);vh(Sh(o),{recursive:!0});try{return NC(t,o),!0}catch{return!1}}function Rh(n,e){let t=We(n),o=FC(t);for(let r of o.transitioned)r.to==="archived"&&BC(e,r.name);return Ve(n,t),o}function _h(n,e){return Object.values(n.records).filter(t=>t.state===e)}function Fs(n,e){delete n.records[e]}function WC(n){let e=n.replace(/\r\n/g,`
|
|
666
|
+
`;Buffer.byteLength(o,"utf-8")<=Ie&&await this.writeIndex(o)}};function JI(n,e){let t=it(n,"..");kt(t)||ih(t,{recursive:!0}),zI(n,e,"utf-8")}function QI(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ah(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function ZI(n){return n.latestInputTokens+n.cumulativeOutputTokens}var eC=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),lh=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function tC(n){return{isSearch:eC.has(n)||void 0,isRead:lh.has(n)||void 0}}function nC(n,e){let t=e.file_path??e.path??e.filePath;if(typeof t=="string")return`${lh.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 ch(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 dh(n,e,t,o){n.toolUseCount++;let r=tC(e),s={toolName:e,input:t,activityDescription:o?.(e,t)??nC(e,t),isSearch:r.isSearch,isRead:r.isRead};for(n.recentActivities.push(s);n.recentActivities.length>5;)n.recentActivities.shift()}function Lc(n){return{toolUseCount:n.toolUseCount,tokenCount:ZI(n),lastActivity:n.recentActivities.length>0?n.recentActivities[n.recentActivities.length-1]:void 0,recentActivities:[...n.recentActivities]}}import{randomUUID as uh}from"node:crypto";function oC(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 Nc(n){let e=Date.now(),t=[],o={inputTokens:0,outputTokens:0},r=ah(),{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,$=oC(k),W=`fork-${f}-${uh().slice(0,8)}`,S=`fork-session-${uh().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(()=>(pl(),Op)),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&&(ch(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{}dh(r,ne.name,Q),I?.(Lc(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:Lc(r),durationMs:ve,ok:de,error:j}}Ca();Pa();je();var $c=class{teamBudget={tokensUsed:0,budgetTokens:Zi};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 $c;le();import{readFile as rC}from"node:fs/promises";import{watch as sC}from"node:fs";import{join as iC}from"node:path";var aC=He,lC="settings.json";function cC(n){return iC(n,aC,lC)}async function dC(n){try{let e=await rC(n,"utf-8");return JSON.parse(e)}catch{return null}}function uC(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 ph(n){let e=cC(n.projectRoot),t=null,o=null,r=async()=>{let s=await dC(e);s&&uC(s,n.ruleEngine,n.hooks,n.log)};r().catch(()=>{});try{t=sC(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 Uc=new Set;function In(n){return Uc.add(n),()=>{Uc.delete(n)}}async function mh(){await Promise.all(Array.from(Uc).map(n=>n()))}le();ft();var Ls="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",to=class extends Error{constructor(e=Ls){super(e),this.name="LlmrouterCatalogUnavailableError"}};function pC(){let n=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim().replace(/\/+$/,"");if(!n)throw new to;return n}function mC(){let n={accept:"application/json"},e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return e&&(n.authorization=`Bearer ${e}`),n}async function fh(n){let e=pC(),t;try{t=await fetch(`${e}${n}`,{method:"GET",headers:mC(),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:bC(o)&&Array.isArray(o.data)?o.data:null;if(!r)throw new to;return r}async function Ns(){return fh("/ext/model-catalog/providers")}async function fC(){return fh("/ext/model-catalog/models")}function jc(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 Fc(n){return(await Ns()).find(t=>t.id===n)??null}async function er(n){let e=await fC();n.migrateModelIds(gC(e));let t=e.map(hC).filter(o=>!!o);return n.replaceCatalogModels(t),t}function gC(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 hC(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:yC(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 yC(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 bC(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}je();import{join as Bc}from"node:path";import{mkdirSync as kC,existsSync as vC,createWriteStream as SC}from"node:fs";import{pipeline as TC}from"node:stream/promises";import{Readable as wC}from"node:stream";var xC=ia,RC=aa,gh={"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??xC,this.timeoutMs=e?.timeoutMs??RC}setProjectDir(e){this.projectDir=e}resolveMediaDir(e){if(!this.projectDir)throw new Error("MediaPersistence requires projectDir \u2014 call setProjectDir() first");if(!e)return Bc(this.projectDir,".qlogicagent","media",_C());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`),Bc(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.`);vC(o)||kC(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=PC(e,c),u=AC(t?.type??IC(c),d);i=Bc(o,u);let p=a.body;if(!p)throw new Error("No response body");let m=SC(i);await TC(wC.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 _C(){let n=new Date;return`${n.getFullYear()}${String(n.getMonth()+1).padStart(2,"0")}${String(n.getDate()).padStart(2,"0")}`}function AC(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 PC(n,e){if(gh[e])return gh[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 IC(n){return n.startsWith("image/")?"image":n.startsWith("video/")?"video":n.startsWith("audio/")?"audio":n.startsWith("model/")?"3d":"file"}import{join as CC}from"node:path";import{readFileSync as EC,writeFileSync as MC,mkdirSync as OC}from"node:fs";var Cn=null,Wc=!1;function hh(n){return CC(n,"skill-stats.json")}function Gc(n){if(Cn)return Cn;try{Cn=JSON.parse(EC(hh(n),"utf8"))}catch{Cn={}}return Cn}function DC(n){if(!(!Wc||!Cn))try{OC(n,{recursive:!0}),MC(hh(n),JSON.stringify(Cn,null,2),"utf8"),Wc=!1}catch{}}function js(n,e,t){let o=Gc(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),Wc=!0,DC(n)}function yh(n,e){return Gc(n)[e]}function bh(n){return Gc(n)}import{existsSync as LC,readFileSync as NC,writeFileSync as $C,mkdirSync as vh,renameSync as UC}from"node:fs";import{join as Hc,dirname as Sh}from"node:path";var kh=30,jC=90,FC="skill-lifecycle.json";function Th(n){return Hc(n,FC)}function We(n){let e=Th(n);try{return JSON.parse(NC(e,"utf8"))}catch{return{version:1,records:{}}}}function Ve(n,e){let t=Th(n);vh(Sh(t),{recursive:!0});let o=t+".tmp";$C(o,JSON.stringify(e,null,2),"utf8");let{renameSync:r}=yi("node:fs");r(o,t)}function Zt(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 Vc(n,e){let t=Zt(n,e);t.lastUsedAt=new Date().toISOString(),t.useCount++,t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function Kc(n,e){let t=Zt(n,e);t.lastPatchedAt=new Date().toISOString(),t.state==="stale"&&(t.state="active",t.staleAt=void 0)}function wh(n,e){let t=n.records[e];return t?(t.pinned=!0,!0):!1}function xh(n,e){let t=n.records[e];return t?(t.pinned=!1,!0):!1}function BC(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 WC(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=BC(r),i=(e-s.getTime())/(1e3*60*60*24);r.state==="active"&&i>=kh?(r.state="stale",r.staleAt=new Date().toISOString(),t.transitioned.push({name:o,from:"active",to:"stale"})):r.state==="stale"&&i>=jC?(r.state="archived",r.archivedAt=new Date().toISOString(),t.transitioned.push({name:o,from:"stale",to:"archived"})):r.state==="stale"&&i<kh&&(r.state="active",r.staleAt=void 0,t.transitioned.push({name:o,from:"stale",to:"active"}))}return t}function GC(n,e){let t=Hc(n,e);if(!LC(t))return!1;let o=Hc(n,".archive",e);vh(Sh(o),{recursive:!0});try{return UC(t,o),!0}catch{return!1}}function Rh(n,e){let t=We(n),o=WC(t);for(let r of o.transitioned)r.to==="archived"&&GC(e,r.name);return Ve(n,t),o}function _h(n,e){return Object.values(n.records).filter(t=>t.state===e)}function Fs(n,e){delete n.records[e]}function HC(n){let e=n.replace(/\r\n/g,`
|
|
667
667
|
`).replace(/\r/g,`
|
|
668
668
|
`);if(!e.startsWith("---"))return;let t=e.indexOf(`
|
|
669
|
-
---`,3);if(t!==-1)return e.slice(4,t)}function
|
|
670
|
-
`).trim(),linesConsumed:o-e}}function zc(n){let e=
|
|
671
|
-
`),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}=
|
|
669
|
+
---`,3);if(t!==-1)return e.slice(4,t)}function VC(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function KC(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(`
|
|
670
|
+
`).trim(),linesConsumed:o-e}}function zc(n){let e=HC(n);if(!e)return{};let t={},o=e.split(`
|
|
671
|
+
`),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}=KC(o,r);u&&(t[a]=u),r+=p;continue}}let c=VC(l);c&&(t[a]=c),r+=1}return t}var qc=1024,Ah=1e5,zC=/^[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>Ah)return{valid:!1,errors:[`Content exceeds ${Ah} 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,`
|
|
672
672
|
`),s=r.indexOf(`
|
|
673
|
-
---`,3);if(s===-1)return t.push("YAML frontmatter has no closing delimiter (---)"),{valid:!1,errors:t,warnings:o};let i=zc(n);return i.name?(
|
|
673
|
+
---`,3);if(s===-1)return t.push("YAML frontmatter has no closing delimiter (---)"),{valid:!1,errors:t,warnings:o};let i=zc(n);return i.name?(zC.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>qc&&t.push(`Description exceeds ${qc} 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,qc)}`),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(`
|
|
674
674
|
`)}function Yc(n,e,t){let o=n.replace(/\r\n/g,`
|
|
675
675
|
`);if(!o.trimStart().startsWith("---"))return Bs({name:e,description:t??`Auto-learned skill: ${e}`,body:o.trim(),version:"1.0.0"});let r=zc(n),s=o.indexOf(`
|
|
676
676
|
---`,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+=`
|
|
@@ -679,29 +679,29 @@ description: ${c}`,i=!0}return i?`---
|
|
|
679
679
|
${a}
|
|
680
680
|
---
|
|
681
681
|
|
|
682
|
-
${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 Xc(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 Ph=["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"],Ih=["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"],
|
|
683
|
-
`),this.handleRequest(t),!0}return nr(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,t,o){if(t.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let r={jsonrpc:"2.0",method:vt.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:t,...o}}};this.transport.send(r)}async requestPermission(e){let t=`perm-${
|
|
682
|
+
${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 Xc(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 Ph=["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"],Ih=["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"],qC=[...Ph,...Ih];var vt={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"},St={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 tr(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}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 Jc(n){if(!n||typeof n!="object")return!1;let e=n;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var Ch="openai-codex";var w1={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"},[Ch]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as YC}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(tr(e)){let t=e;return process.stderr.write(`[acp-server] \u922B?recv id=${String(t.id)} method=${t.method}
|
|
683
|
+
`),this.handleRequest(t),!0}return nr(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,t,o){if(t.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let r={jsonrpc:"2.0",method:vt.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:t,...o}}};this.transport.send(r)}async requestPermission(e){let t=`perm-${YC().slice(0,8)}`,o={jsonrpc:"2.0",method:vt.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 vt.INITIALIZE:await this.onInitialize(r,s);break;case vt.SESSION_NEW:await this.onSessionNew(r,s);break;case vt.SESSION_PROMPT:await this.onSessionPrompt(r,s);break;case vt.SESSION_END:await this.onSessionEnd(r,s);break;case vt.SESSION_SET_CONFIG:await this.onSessionSetConfig(r,s);break;case vt.SESSION_SET_MODEL:await this.handler.handleAcpSessionSetModel(s.sessionId??this.activeSessionId??"",s.modelId??s.model??""),this.sendResult(r,{});break;case vt.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
|
|
684
684
|
`);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}
|
|
685
685
|
`);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}
|
|
686
|
-
`)}};function Mh(n,e,t,o){let r=
|
|
686
|
+
`)}};function Mh(n,e,t,o){let r=XC(t,o);r&&n.emitSessionUpdate(e,r.type,r.payload)}function XC(n,e){switch(n){case"turn.delta":return{type:St.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:e.text}}};case"turn.reasoning_delta":return{type:St.AGENT_THOUGHT_CHUNK,payload:{content:{type:"text",text:e.delta}}};case"turn.tool_call":return{type:St.TOOL_CALL,payload:{toolCallId:e.callId,toolName:e.name,status:"in_progress",title:e.name,kind:"execute",rawInput:JC(e.arguments)}};case"turn.tool_result":return{type:St.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:St.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:St.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:St.USAGE_UPDATE,payload:{used:o+r,size:t?.contextWindow??2e5}}}case"turn.end":return null;case"turn.error":return{type:St.AGENT_MESSAGE_CHUNK,payload:{content:{type:"text",text:`[Error] ${e.error?.message??"Unknown error"}`}}};case"turn.suggestions":return{type:St.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??QC(),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 JC(n){if(n)try{return JSON.parse(n)}catch{return{raw:n}}}function QC(){return Math.random().toString(36).slice(2,10)}var Oh=["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 mr from"node:path";le();ft();import*as Dh from"node:fs";import*as Qc from"node:path";le();var oo=class{getSessionsRoot(e){let t=ct(e);if(!t)throw new Error(`Project not found: ${e}`);return Kt(t.workspaceDir)}getProjectWorkspaceDir(e){let t=ct(e);if(!t)throw new Error(`Project not found: ${e}`);return t.workspaceDir}getSessionDir(e,t){return Qc.join(this.getSessionsRoot(e),t)}resolveWorkspaceDir(e,t){if(t)return this.getProjectWorkspaceDir(t);let o=fe();for(let r of o){let s=Kt(r.workspaceDir),i=Qc.join(s,e);try{if(Dh.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 ZC(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 Lh(){Vs.clear()}async function Nh(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 ZC(n.sections);e.push(...t)}return n.appendSystemPrompt&&e.push(n.appendSystemPrompt),e.filter(Boolean).join(`
|
|
687
687
|
|
|
688
|
-
`)}le();import{existsSync as $h,mkdirSync as
|
|
688
|
+
`)}le();import{existsSync as $h,mkdirSync as eE,readFileSync as or,writeFileSync as Uh}from"node:fs";import{join as rr}from"node:path";var zs=new Set(["coding","office","creative","general"]),jh="settings.yaml";function tE(n){try{let e=rr(n,He,jh),o=or(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=rr(n,He,"INSTRUCTIONS.md"),o=or(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=rr(n,"INSTRUCTIONS.md"),o=or(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 nE=3;function oE(n,e){let t=aE(n);return e?t===e||t==="general"?e:(ed(n)[t]??0)>=nE?t:e:t}var rE=/\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,sE=/\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,iE=/\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 aE(n){if(!n||n.trim().length===0)return"general";let e=ed(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 ed(n){return{coding:Zc(n,rE),office:Zc(n,sE),creative:Zc(n,iE),general:0}}function Zc(n,e){let t=new RegExp(e.source,"gi"),o=n.match(t);return o?o.length:0}function Fh(n){let e=tE(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=oE(n.userText,n.sessionDomain);return n.sessionDomain&&t===n.sessionDomain?{domain:t,source:"session-sticky"}:{domain:t,source:"auto-detect"}}var lE=3;function Bh(n,e){if(e==="general")return!1;try{let t=rr(n,He),o=rr(t,jh);if($h(o)){let s=or(o,"utf-8");if(/^taskDomain\s*:/m.test(s))return!1}eE(t,{recursive:!0});let r=`# Auto-detected task domain for this workspace.
|
|
689
689
|
# Values: coding | office | creative | general
|
|
690
690
|
`;if($h(o)){let s=or(o,"utf-8");Uh(o,s.trimEnd()+`
|
|
691
691
|
|
|
692
692
|
`+r+`taskDomain: ${e}
|
|
693
693
|
`,"utf-8")}else Uh(o,r+`taskDomain: ${e}
|
|
694
|
-
`,"utf-8");return!0}catch{return!1}}function Wh(n,e){return e==="general"?!1:(ed(n)[e]??0)>=
|
|
695
|
-
`)})}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
|
|
694
|
+
`,"utf-8");return!0}catch{return!1}}function Wh(n,e){return e==="general"?!1:(ed(n)[e]??0)>=lE}import{release as cE,homedir as dE}from"node:os";import{resolve as uE}from"node:path";function pE(){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 mE(){let n=process.platform,e=cE();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 Gh(n){return Ks("environment_context",()=>{let e=pE(),t=mE(),o=n??process.cwd(),r=process.version,s=dE(),i=["# Environment","",`- Platform: ${t}`,`- Shell: ${e}`,`- Working directory: ${uE(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(`
|
|
695
|
+
`)})}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 fE(){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 gE(){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 hE(){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 Hh(n="general"){return ro("task_guidance",()=>{let e;switch(n){case"coding":e=[...fE(),"",...qs()];break;case"office":e=[...gE(),"",...qs()];break;case"creative":e=[...hE(),"",...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(`
|
|
696
696
|
`)})}function Vh(){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(`
|
|
697
697
|
`))}function Kh(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(`
|
|
698
698
|
`):["# 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(`
|
|
699
|
-
`))}je();import{randomUUID as zh}from"node:crypto";async function qh(n,e){let t=new Date(n.lastActiveAt).getTime();if(Date.now()-t<zd)return{split:!1,activeSessionId:n.sessionId};let s=zh(),i=new Date().toISOString();await nt(n.sessionId,{sealedAt:i},e);let a=n.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${n.taskSummary}`:void 0;return await nt(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 Yh(n,e){if(n.type!=="group")return{split:!1,activeSessionId:n.sessionId};if(n.turnCount<qd)return{split:!1,activeSessionId:n.sessionId};let t=zh(),o=new Date().toISOString();await nt(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 nt(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}}pr();od();import*as uo from"node:fs";var cy=new oo,
|
|
700
|
-
`):null},"memory INDEX.md may change between turns")]}),ce=[...r].reverse().find(T=>T.role==="user");ce&&Rl(o,ce,p,t).catch(()=>{}),await this.mcpReady;let de=Ot(),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(
|
|
699
|
+
`))}je();import{randomUUID as zh}from"node:crypto";async function qh(n,e){let t=new Date(n.lastActiveAt).getTime();if(Date.now()-t<zd)return{split:!1,activeSessionId:n.sessionId};let s=zh(),i=new Date().toISOString();await nt(n.sessionId,{sealedAt:i},e);let a=n.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${n.taskSummary}`:void 0;return await nt(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 Yh(n,e){if(n.type!=="group")return{split:!1,activeSessionId:n.sessionId};if(n.turnCount<qd)return{split:!1,activeSessionId:n.sessionId};let t=zh(),o=new Date().toISOString();await nt(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 nt(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}}pr();od();import*as uo from"node:fs";var cy=new oo,DE=[/继续(桌面|电脑|刚才|上次|之前)的/,/接着(桌面|电脑|刚才|上次|之前)的/,/刚才(那个|那件|说的|聊的|做的)/,/上次(说到|聊到|做到|讲到)/,/桌面(端|上)?(那个|那边|的任务|的对话|在做)/,/电脑(端|上)?(那个|那边|的任务|的对话|在做)/,/之前(那个|在做的|讨论的|说的)/,/帮我继续/,/接着(做|干|搞|写|改)/,/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 LE(n){return!n||n.length<3?!1:DE.some(e=>e.test(n))}function dy(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 uy(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 py(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 my(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=cy.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&>(x.id);else{let I=i.groupName||k,P=k.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",O=mr.join(H(),"workspaces","groups",P),$=Xr({name:I,workspaceDir:O,type:"group",groupId:k});$&&(this.setActiveWorkdir($.workspaceDir),gt($.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"&&(gt(P.id),this.setActiveWorkdir(P.workspaceDir))}}}let p=(()=>{let y=i?.projectId;if(y)try{return cy.getProjectWorkspaceDir(y)}catch{}return this.getActiveProjectRoot()})();{let y=X(),b=y.snapshotProviderKeys();this.currentMediaApiKeys=b,ig(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?(kc(ng(k.provider,k.apiKey)),k.keyHandle.release({success:!0})):kc(void 0)}sg(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(()=>{}),Lh()),this.currentSessionId=o,this.sessionState=new an(o),this.sessionTaskDomain=void 0,this.memoryPrefetchState=zt(),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 vm(x,this.currentHooks??void 0);T.length>0&&(k=km(T))}catch{}let I=r.filter(T=>T.role==="user").map(T=>typeof T.content=="string"?T.content:"").join(" "),{domain:P,source:O}=Fh({cwd:x,hostOverride:i?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:I});if(this.sessionTaskDomain=P,O==="auto-detect"&&Wh(I,P)&&Bh(x,P),!this.memdir||this.memdir.getRootPath()!==new $t(x).getRootPath()){let T=new $t(x);T.ensureInitialized(),this.memdir=T}let $=this.memdir,W;if(o){let T=xn(o,p);T?.carryoverSummary&&(W=T.carryoverSummary)}let S=await Nh({basePrompt:i?.systemPrompt,instructionBlock:k,customSystemPrompt:i?.customSystemPrompt,appendSystemPrompt:i?.appendSystemPrompt,sections:[Gh(x),Kh(),Hh(P),Vh(),ro("pet",()=>{let F=new Ut(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(`
|
|
700
|
+
`):null},"memory INDEX.md may change between turns")]}),ce=[...r].reverse().find(T=>T.role==="user");ce&&Rl(o,ce,p,t).catch(()=>{}),await this.mcpReady;let de=Ot(),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(LE(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(!xn(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 pm(T,{transport:B.transport,apiKey:B.apiKey,model:B.model})),F||(F=T.trim().slice(0,20)+(T.trim().length>20?"\u2026":"")),await nt(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,Rl(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=mr.join(p,".qlogicagent","skills"),jt=mr.join(he,B.suggestedName),g=mr.join(jt,"SKILL.md");if(!uo.existsSync(g)){let v=Bs({name:B.suggestedName,description:B.description,tools:B.tools,body:`# ${B.suggestedName}
|
|
701
701
|
|
|
702
702
|
Auto-learned multi-step workflow using: ${B.tools.join(", ")}.
|
|
703
703
|
`,version:"1.0.0",category:"learned"}),_=Ws(v,B.suggestedName);if(_.valid){uo.mkdirSync(jt,{recursive:!0}),uo.writeFileSync(g,v,"utf8"),ht();let C=H(),R=We(C);Zt(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){um(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&&mm(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=xn(o,p);Re&&Yh({...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()}}ft();import{randomUUID as fy}from"node:crypto";async function oi(n){let e=n.params??{},t=e.turnId??fy(),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_${fy().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(`
|
|
704
|
-
`),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 FE}from"node:crypto";var fr=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 gr=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 pd}from"node:path";import{mkdir as DE,readdir as LE}from"node:fs/promises";le();function gy(n){return pd(Oe(n),"products")}function hy(n,e){return pd(gy(e),n)}function yy(n,e){return pd(hy(n,e),"product-state.json")}async function by(n,e){let t=hy(n.productId,e);await DE(t,{recursive:!0}),await eo(yy(n.productId,e),n)}async function md(n,e){return Pn(yy(n,e))}async function ky(n){let e=gy(n),t;try{t=await LE(e)}catch{return[]}let o=[];for(let r of t){let s=await md(r,n);s&&o.push(s)}return o}var hr=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 by(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 NE}from"node:child_process";import{promisify as $E}from"node:util";import{join as vy}from"node:path";import{mkdir as UE,rm as jE}from"node:fs/promises";var po=$E(NE);async function yr(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=vy(n,".worktrees");await UE(o,{recursive:!0});let r=vy(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 fd(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 Sy(n,e){try{await po("git",["worktree","remove","--force",e],{cwd:n,encoding:"utf8"})}catch{try{await jE(e,{recursive:!0,force:!0})}catch{}}}async function Ty(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-${FE().slice(0,8)}`,c=new fr(s),d=new gr(i),u=new hr({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 yr(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 md(e,t);if(!o)throw new Error(`Product ${e} not found on disk`);let r=new fr(o.tasks);r.restore(o.tasks);let s=new gr({maxTotalTokens:o.budget.maxTotalTokens,maxDuration:o.budget.maxDuration});s.restore(o.budget);let i=new hr({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 yr(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 ky(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 wy}from"node:crypto";function BE(n,e){let t=e?`
|
|
704
|
+
`),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 WE}from"node:crypto";var fr=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 gr=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 pd}from"node:path";import{mkdir as NE,readdir as $E}from"node:fs/promises";le();function gy(n){return pd(Oe(n),"products")}function hy(n,e){return pd(gy(e),n)}function yy(n,e){return pd(hy(n,e),"product-state.json")}async function by(n,e){let t=hy(n.productId,e);await NE(t,{recursive:!0}),await eo(yy(n.productId,e),n)}async function md(n,e){return Pn(yy(n,e))}async function ky(n){let e=gy(n),t;try{t=await $E(e)}catch{return[]}let o=[];for(let r of t){let s=await md(r,n);s&&o.push(s)}return o}var hr=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 by(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 UE}from"node:child_process";import{promisify as jE}from"node:util";import{join as vy}from"node:path";import{mkdir as FE,rm as BE}from"node:fs/promises";var po=jE(UE);async function yr(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=vy(n,".worktrees");await FE(o,{recursive:!0});let r=vy(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 fd(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 Sy(n,e){try{await po("git",["worktree","remove","--force",e],{cwd:n,encoding:"utf8"})}catch{try{await BE(e,{recursive:!0,force:!0})}catch{}}}async function Ty(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-${WE().slice(0,8)}`,c=new fr(s),d=new gr(i),u=new hr({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 yr(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 md(e,t);if(!o)throw new Error(`Product ${e} not found on disk`);let r=new fr(o.tasks);r.restore(o.tasks);let s=new gr({maxTotalTokens:o.budget.maxTotalTokens,maxDuration:o.budget.maxDuration});s.restore(o.budget);let i=new hr({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 yr(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 ky(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 wy}from"node:crypto";function GE(n,e){let t=e?`
|
|
705
705
|
|
|
706
706
|
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.
|
|
707
707
|
|
|
@@ -731,7 +731,7 @@ When you're ready to output the final plan, use this EXACT JSON schema wrapped i
|
|
|
731
731
|
"reasoning": "<decomposition strategy explanation>"
|
|
732
732
|
}
|
|
733
733
|
|
|
734
|
-
Start by greeting the user and asking your first clarifying question about the project.`}function
|
|
734
|
+
Start by greeting the user and asking your first clarifying question about the project.`}function HE(n,e){return`${n.map(o=>`[${o.role}]: ${o.content}`).join(`
|
|
735
735
|
|
|
736
736
|
`)}
|
|
737
737
|
|
|
@@ -764,13 +764,13 @@ To mutate the DAG, output a \`\`\`json block with an array of mutations:
|
|
|
764
764
|
{"type": "update_prompt", "taskId": "...", "prompt": "..."}
|
|
765
765
|
]
|
|
766
766
|
|
|
767
|
-
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-${wy().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,
|
|
767
|
+
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-${wy().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,GE(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=xy(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=HE(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=xy({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-${wy().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 un({log:{info:t=>process.stderr.write(`[product:pm] ${t}
|
|
768
768
|
`),warn:t=>process.stderr.write(`[product:pm] WARN ${t}
|
|
769
769
|
`)},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}
|
|
770
770
|
`),warn:t=>process.stderr.write(`${t}
|
|
771
771
|
`)},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 En(){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}
|
|
772
772
|
`),warn:e=>process.stderr.write(`${e}
|
|
773
|
-
`)},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 Ry(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 En.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 _y(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=En.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 Ay(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 En.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 Py(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 Iy(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 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).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 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).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 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}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 Oy(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 Dy(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 Ly(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 Ny(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 gd}from"node:crypto";import*as Xe from"node:fs";import*as Mn from"node:path";le();var Ee=new oo;function $y(n){let e=n.params,t=e?.id??gd();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 an(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=zt(),this.enableIdleDream(),n.id!==void 0&&this.sendResponse(n.id,{id:t,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function Uy(n){let e=n.params,t=e?.limit??20;try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o),i=(await Mt(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 jy(n){let e=n.params,t=e?.sessionId??gd();try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o);await nt(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 Fy(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 Mt(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 nt(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 Mt(500,p.workspaceDir)).find(f=>f.groupKey===d&&!f.sealedAt);if(h){let f=xn(h.sessionId,p.workspaceDir);if(f){let y=await qh(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=gd(),a=Ee.getActiveProjectId(),l=Ee.getProjectWorkspaceDir(a),c=r==="group"?`group:${t}:${o}`:void 0;await nt(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 By(n){let e=n.params,t=e?.limit??50;try{let o;if(e?.projectId){let s=ct(e.projectId);if(!s){n.id!==void 0&&this.sendResponse(n.id,{sessions:[]});return}let i=s.workspaceDir;o=await Mt(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 Mt(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 Wy(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 Mt(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 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),o=await _l(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 Hy(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 nt(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 Vy(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 Al(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 Ky(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 Mt(1e4,t),r=0;for(let s of o)await Al(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 zy(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 nt(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 qy(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 _l(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 Yy(n){let e=this.currentSessionId||"default",t=this.sessionState?.createSnapshot(),o,r=this.getActiveProjectRoot();r&&(o=Mn.join(Kt(r),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:o,agentHome:H(),settings:mt()},usage:t?{turnCount:t.turnCount,inputTokens:t.totalInputTokens,outputTokens:t.totalOutputTokens}:void 0};n.id!==void 0&&this.sendResponse(n.id,s)}function Xy(n){let e=n.params,t=null;if(e?.projectId)t=ct(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=gt(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 Jy(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 xn(t,s);if(i&&i.projectId===r.id){gt(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 Zy(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=ct(o),i=ct(r);if(!s||!i){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,"Source or target project not found");return}let a=Mn.join(Ee.getProjectWorkspaceDir(o),".qlogicagent","sessions",t),l=Mn.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(Mn.dirname(l),{recursive:!0}),Xe.cpSync(a,l,{recursive:!0});let c=Mn.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 rb from"node:path";import{randomUUID as KE}from"node:crypto";import{join as hd}from"node:path";import{mkdir as GE,readdir as HE}from"node:fs/promises";le();function eb(n){return hd(Oe(n),"solos")}function yd(n,e){return hd(eb(e),n)}function tb(n,e){return hd(yd(n,e),"solo-state.json")}async function nb(n,e){let t=yd(n.soloId,e);await GE(t,{recursive:!0}),await eo(tb(n.soloId,e),n)}async function VE(n,e){return Pn(tb(n,e))}async function ob(n){let e=eb(n),t;try{t=await HE(e)}catch{return[]}let o=[];for(let r of t){let s=await VE(r,n);s&&o.push(s)}return o}async function bd(n,e){let{rm:t}=await import("node:fs/promises"),o=yd(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};nb(t,e.cwd).catch(()=>{})}async restoreFromDisk(e){let t=await ob(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),bd(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 yr(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
|
+
`)},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 Ry(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 En.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 _y(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=En.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 Ay(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 En.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 Py(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 Iy(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 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).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 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).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 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}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 Oy(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 Dy(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 Ly(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 Ny(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 gd}from"node:crypto";import*as Xe from"node:fs";import*as Mn from"node:path";le();var Ee=new oo;function $y(n){let e=n.params,t=e?.id??gd();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 an(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=zt(),this.enableIdleDream(),n.id!==void 0&&this.sendResponse(n.id,{id:t,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function Uy(n){let e=n.params,t=e?.limit??20;try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o),i=(await Mt(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 jy(n){let e=n.params,t=e?.sessionId??gd();try{let o=e?.projectId??Ee.getActiveProjectId(),r=Ee.getProjectWorkspaceDir(o);await nt(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 Fy(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 Mt(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 nt(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 Mt(500,p.workspaceDir)).find(f=>f.groupKey===d&&!f.sealedAt);if(h){let f=xn(h.sessionId,p.workspaceDir);if(f){let y=await qh(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=gd(),a=Ee.getActiveProjectId(),l=Ee.getProjectWorkspaceDir(a),c=r==="group"?`group:${t}:${o}`:void 0;await nt(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 By(n){let e=n.params,t=e?.limit??50;try{let o;if(e?.projectId){let s=ct(e.projectId);if(!s){n.id!==void 0&&this.sendResponse(n.id,{sessions:[]});return}let i=s.workspaceDir;o=await Mt(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 Mt(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 Wy(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 Mt(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 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),o=await _l(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 Hy(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 nt(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 Vy(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 Al(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 Ky(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 Mt(1e4,t),r=0;for(let s of o)await Al(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 zy(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 nt(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 qy(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 _l(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 Yy(n){let e=this.currentSessionId||"default",t=this.sessionState?.createSnapshot(),o,r=this.getActiveProjectRoot();r&&(o=Mn.join(Kt(r),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:o,agentHome:H(),settings:mt()},usage:t?{turnCount:t.turnCount,inputTokens:t.totalInputTokens,outputTokens:t.totalOutputTokens}:void 0};n.id!==void 0&&this.sendResponse(n.id,s)}function Xy(n){let e=n.params,t=null;if(e?.projectId)t=ct(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=gt(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 Jy(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 xn(t,s);if(i&&i.projectId===r.id){gt(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 Zy(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=ct(o),i=ct(r);if(!s||!i){n.id!==void 0&&this.sendError(n.id,w.INVALID_PARAMS,"Source or target project not found");return}let a=Mn.join(Ee.getProjectWorkspaceDir(o),".qlogicagent","sessions",t),l=Mn.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(Mn.dirname(l),{recursive:!0}),Xe.cpSync(a,l,{recursive:!0});let c=Mn.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 rb from"node:path";import{randomUUID as qE}from"node:crypto";import{join as hd}from"node:path";import{mkdir as VE,readdir as KE}from"node:fs/promises";le();function eb(n){return hd(Oe(n),"solos")}function yd(n,e){return hd(eb(e),n)}function tb(n,e){return hd(yd(n,e),"solo-state.json")}async function nb(n,e){let t=yd(n.soloId,e);await VE(t,{recursive:!0}),await eo(tb(n.soloId,e),n)}async function zE(n,e){return Pn(tb(n,e))}async function ob(n){let e=eb(n),t;try{t=await KE(e)}catch{return[]}let o=[];for(let r of t){let s=await zE(r,n);s&&o.push(s)}return o}async function bd(n,e){let{rm:t}=await import("node:fs/promises"),o=yd(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};nb(t,e.cwd).catch(()=>{})}async restoreFromDisk(e){let t=await ob(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),bd(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 yr(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>
|
|
774
774
|
${s.rules.join(`
|
|
775
775
|
`)}
|
|
776
776
|
</rules>`),s.memory?.length&&p.push(`<memory>
|
|
@@ -780,7 +780,7 @@ ${s.memory.join(`
|
|
|
780
780
|
|
|
781
781
|
`)}
|
|
782
782
|
|
|
783
|
-
${t}`)}let l=`solo-${
|
|
783
|
+
${t}`)}let l=`solo-${qE().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 fd(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 fd(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 Ty(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 bd(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(`
|
|
784
784
|
`),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 Sy(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 un({log:{info:t=>process.stderr.write(`[solo:pm] ${t}
|
|
785
785
|
`),warn:t=>process.stderr.write(`[solo:pm] WARN ${t}
|
|
786
786
|
`)},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:rb.join(H(),"agent-logs")}),e={log:{info:t=>process.stderr.write(`${t}
|
|
@@ -791,7 +791,7 @@ ${o.content}`).join(`
|
|
|
791
791
|
|
|
792
792
|
`)}
|
|
793
793
|
</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=br.join(this.dir,o);try{let s=Qe.statSync(r);s.isFile()&&(t+=s.size)}catch{}}return t}};le();function On(n){return ct(n)?.workspaceDir??null}function ci(n){return n?new li(n):null}async function Lb(n){let e=n.params;if(!e?.projectId){n.id!==void 0&&this.sendResponse(n.id,{entries:[]});return}let t=On(e.projectId);if(!t){n.id!==void 0&&this.sendResponse(n.id,{entries:[]});return}try{let o=e.path?wt.join(t,e.path):t,s=(await Tt.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 Nb(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=On(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=wt.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 Tt.promises.mkdir(o,{recursive:!0}):(await Tt.promises.mkdir(wt.dirname(o),{recursive:!0}),await Tt.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 $b(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=On(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=wt.join(t,e.oldPath),r=wt.join(wt.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 Tt.promises.rename(o,r);let s=wt.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 Ub(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=On(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=wt.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 Tt.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 jb(n){let e=n.params;if(!e?.projectId){n.id!==void 0&&this.sendResponse(n.id,{files:[]});return}let t=On(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(`
|
|
794
|
-
`).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 Fb(n){let e=n.params,t;if(e?.projectId&&(t=On(e.projectId)??void 0),t||(t=this.getActiveProjectRoot()),!t){n.id!==void 0&&this.sendResponse(n.id,{instructions:[]});return}let o=[],r=Mo(t);try{let i=Tt.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 Bb(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=On(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=Mo(t);try{let a=Tt.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 Wb(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 Gb(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 vd(n,e){let o=(typeof e=="string"&&e.trim()?e:typeof n.memoryUserId=="string"&&n.memoryUserId.trim()?n.memoryUserId:"").trim();return o||null}function zE(){return{records:[],stats:{formed:0,insights:0,preferences:0}}}async function Hb(n){let e=[];this.memdir&&e.push({id:"memdir",type:"file",path:Dc(this.getActiveProjectRoot())}),this.memoryProvider&&e.push({id:"local",type:"vector"}),n.id!==void 0&&this.sendResponse(n.id,{sources:e})}async function Vb(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=vd(this,e?.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,zE());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 Kb(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=vd(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 zb(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 qb(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 Yb(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=vd(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 Xb(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();ft();import*as tn from"node:fs";import*as Sd from"node:path";je();function Jb(n){let e=n.params,o=Ot(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 Zb(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:mt(),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 qE=new Set(["providers","models","bindings","provider","model","apiKey","baseUrl","providerKeys"]);async function ek(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))qE.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=mt(),s={};try{let i=await tn.promises.readFile(r,"utf-8");s=JSON.parse(i)}catch{}Object.assign(s,o),await tn.promises.mkdir(Sd.dirname(r),{recursive:!0}),await tn.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 tk(n){try{let e=ga(),t=mt(),o={};try{let r=tn.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 nk(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=ga();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=mt(),a={};try{let l=await tn.promises.readFile(i,"utf-8");a=JSON.parse(l)}catch{}(!a.tunables||typeof a.tunables!="object")&&(a.tunables={}),a.tunables[t]=o,await tn.promises.mkdir(Sd.dirname(i),{recursive:!0}),await tn.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 ok(n){let e=ot("task");if(!e){n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Fo([])});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:Fo(r)})}catch{n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Fo([])})}}function rk(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 sk(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 ik from"node:fs";import*as Td from"node:path";async function ak(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 lk(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 ck(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 dk(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 uk(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 pk(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 mk(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 fk(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 gk(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 hk(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 yk(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 bk(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=Td.join(H(),"agent-logs"),o=Td.join(t,`${e.agentId}.stderr.log`),r="";try{r=ik.readFileSync(o,"utf-8")}catch{}e.tail&&e.tail>0&&r&&(r=r.split(`
|
|
794
|
+
`).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 Fb(n){let e=n.params,t;if(e?.projectId&&(t=On(e.projectId)??void 0),t||(t=this.getActiveProjectRoot()),!t){n.id!==void 0&&this.sendResponse(n.id,{instructions:[]});return}let o=[],r=Mo(t);try{let i=Tt.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 Bb(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=On(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=Mo(t);try{let a=Tt.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 Wb(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 Gb(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 vd(n,e){let o=(typeof e=="string"&&e.trim()?e:typeof n.memoryUserId=="string"&&n.memoryUserId.trim()?n.memoryUserId:"").trim();return o||null}function YE(){return{records:[],stats:{formed:0,insights:0,preferences:0}}}async function Hb(n){let e=[];this.memdir&&e.push({id:"memdir",type:"file",path:Dc(this.getActiveProjectRoot())}),this.memoryProvider&&e.push({id:"local",type:"vector"}),n.id!==void 0&&this.sendResponse(n.id,{sources:e})}async function Vb(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=vd(this,e?.userId);if(!t){n.id!==void 0&&this.sendResponse(n.id,YE());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 Kb(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=vd(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 zb(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 qb(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 Yb(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=vd(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 Xb(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();ft();import*as tn from"node:fs";import*as Sd from"node:path";je();function Jb(n){let e=n.params,o=Ot(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 Zb(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:mt(),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 XE=new Set(["providers","models","bindings","provider","model","apiKey","baseUrl","providerKeys"]);async function ek(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))XE.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=mt(),s={};try{let i=await tn.promises.readFile(r,"utf-8");s=JSON.parse(i)}catch{}Object.assign(s,o),await tn.promises.mkdir(Sd.dirname(r),{recursive:!0}),await tn.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 tk(n){try{let e=ga(),t=mt(),o={};try{let r=tn.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 nk(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=ga();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=mt(),a={};try{let l=await tn.promises.readFile(i,"utf-8");a=JSON.parse(l)}catch{}(!a.tunables||typeof a.tunables!="object")&&(a.tunables={}),a.tunables[t]=o,await tn.promises.mkdir(Sd.dirname(i),{recursive:!0}),await tn.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 ok(n){let e=ot("task");if(!e){n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Fo([])});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:Fo(r)})}catch{n.id!==void 0&&this.sendResponse(n.id,{items:[],summary:Fo([])})}}function rk(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 sk(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 ik from"node:fs";import*as Td from"node:path";async function ak(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 lk(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 ck(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 dk(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 uk(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 pk(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 mk(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 fk(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 gk(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 hk(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 yk(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 bk(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=Td.join(H(),"agent-logs"),o=Td.join(t,`${e.agentId}.stderr.log`),r="";try{r=ik.readFileSync(o,"utf-8")}catch{}e.tail&&e.tail>0&&r&&(r=r.split(`
|
|
795
795
|
`).slice(-e.tail).join(`
|
|
796
796
|
`)),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 kk(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)})}}Sn();ft();async function vk(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 Sk(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 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}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 wk(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
|
|
797
797
|
Content-Disposition: form-data; name="model"\r
|
|
@@ -804,9 +804,9 @@ Content-Disposition: form-data; name="prompt"\r
|
|
|
804
804
|
\r
|
|
805
805
|
\u8BF7\u7528${e.language==="zh"?"\u4E2D\u6587":"\u82F1\u6587"}\u8F6C\u5F55`),c.push(`--${l}--`);let d=c.join(`\r
|
|
806
806
|
`)+`\r
|
|
807
|
-
`,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)})}}ft();function YE(n){return n.length<=8?"****":`${n.slice(0,3)}***${n.slice(-4)}`}function dt(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){dt(n,e,Ls)}function XE(n){let e={};for(let t of n)for(let o of t.purposes)e[o]??=[],e[o].push(t);return e}async function wd(){let n=X(),e=await er(n);return n.save(),e}async function xk(n){try{let e=(await Ns()).map(t=>({id:t.id,displayName:jc(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 Rk(n){let e=n.params;if(!e?.providerId||!e?.key){dt(this,n,"Required: providerId (string), key (string)",w.INVALID_PARAMS);return}let{providerId:t,key:o,label:r}=e;try{let s=await Fc(t);if(!s){dt(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 wd();for(let c of Do)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;dt(this,n,i)}}function _k(n){let e=n.params;if(!e?.keyId){dt(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 Ak(n){let e=n.params;if(!e?.keyId||typeof e.enabled!="boolean"){dt(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 Pk(n){let e=n.params;if(!e?.modelId||typeof e.enabled!="boolean"){dt(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 Ik(n){let e=n.params;try{await wd();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:XE(r),configuredProviderIds:[...o]})}catch{di(this,n)}}function Ck(n){let e=n.params;if(!e?.purpose||!e?.modelId){dt(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){dt(this,n,t instanceof Error?t.message:String(t),w.INVALID_PARAMS)}}function Ek(n){let e=n.params;if(!e?.purpose){dt(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 Mk(n){try{let e=await Ns(),t=new Map(e.map(a=>[a.id,jc(a)]));await wd();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:YE(l.key),enabled:l.enabled,health:l.healthStatus}))})),s=o.getAllBindings(),i={};for(let a of Do){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 Ok(n){try{let e=X();e.load(),await er(e),e.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,catalogRefreshed:!0})}catch{di(this,n)}}async function Dk(n){let e=n.params;if(!e?.providerId||!e?.apiKey){dt(this,n,"providerId and apiKey required",w.INVALID_PARAMS);return}try{let t=await Fc(e.providerId),o=e.baseUrl||(t?$s(t):void 0);if(!o){dt(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})}}pr();Zs();sd();ei();ti();function xd(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 Lk(n){let e=n.params,t=this.getActiveProjectRoot(),o=new Ut(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:xd(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:xd(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 Nk(n){let t=n.params?.action??"pat",o=this.getActiveProjectRoot(),r=new Ut(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 $k(n){let e=this.getActiveProjectRoot(),o=new Ut(e).load();if(n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:o??null,growth:o?xd(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 Uk(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=en(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
|
+
`,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)})}}ft();function JE(n){return n.length<=8?"****":`${n.slice(0,3)}***${n.slice(-4)}`}function dt(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){dt(n,e,Ls)}function QE(n){let e={};for(let t of n)for(let o of t.purposes)e[o]??=[],e[o].push(t);return e}async function wd(){let n=X(),e=await er(n);return n.save(),e}async function xk(n){try{let e=(await Ns()).map(t=>({id:t.id,displayName:jc(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 Rk(n){let e=n.params;if(!e?.providerId||!e?.key){dt(this,n,"Required: providerId (string), key (string)",w.INVALID_PARAMS);return}let{providerId:t,key:o,label:r}=e;try{let s=await Fc(t);if(!s){dt(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 wd();for(let c of Do)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;dt(this,n,i)}}function _k(n){let e=n.params;if(!e?.keyId){dt(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 Ak(n){let e=n.params;if(!e?.keyId||typeof e.enabled!="boolean"){dt(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 Pk(n){let e=n.params;if(!e?.modelId||typeof e.enabled!="boolean"){dt(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 Ik(n){let e=n.params;try{await wd();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:QE(r),configuredProviderIds:[...o]})}catch{di(this,n)}}function Ck(n){let e=n.params;if(!e?.purpose||!e?.modelId){dt(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){dt(this,n,t instanceof Error?t.message:String(t),w.INVALID_PARAMS)}}function Ek(n){let e=n.params;if(!e?.purpose){dt(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 Mk(n){try{let e=await Ns(),t=new Map(e.map(a=>[a.id,jc(a)]));await wd();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:JE(l.key),enabled:l.enabled,health:l.healthStatus}))})),s=o.getAllBindings(),i={};for(let a of Do){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 Ok(n){try{let e=X();e.load(),await er(e),e.save(),n.id!==void 0&&this.sendResponse(n.id,{ok:!0,catalogRefreshed:!0})}catch{di(this,n)}}async function Dk(n){let e=n.params;if(!e?.providerId||!e?.apiKey){dt(this,n,"providerId and apiKey required",w.INVALID_PARAMS);return}try{let t=await Fc(e.providerId),o=e.baseUrl||(t?$s(t):void 0);if(!o){dt(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})}}pr();Zs();sd();ei();ti();function xd(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 Lk(n){let e=n.params,t=this.getActiveProjectRoot(),o=new Ut(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:xd(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:xd(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 Nk(n){let t=n.params?.action??"pat",o=this.getActiveProjectRoot(),r=new Ut(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 $k(n){let e=this.getActiveProjectRoot(),o=new Ut(e).load();if(n.id!==void 0&&this.sendResponse(n.id,{ok:!0,soul:o??null,growth:o?xd(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 Uk(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=en(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+`
|
|
808
808
|
|
|
809
|
-
`+m),s=en(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=dr(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=ur(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:en(r),parts:so(en(r)),colors:ao(en(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"}};ar(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 QE=JE(import.meta.url);function ZE(){for(let n of["../package.json","../../package.json"])try{return QE(n).version}catch{}return"0.0.0"}var eM=ZE();function tM(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 ui=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=zt();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 kn,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 Dn({verbose:e.verbose}),this.taskStore.onTaskChange((r,s)=>{s&&this.sendNotification("task.updated",{taskId:r,type:s.type,lifecycle:s.lifecycle,label:s.label})}),dg({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 er(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()&&(ag(e),this.mediaPersistence.setProjectDir(e))}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),rm().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(Jc(e)||nr(e)){this.acpServer.dispatchMessage(e);return}if(tr(e)){let t=e.method;if(t==="initialize"||t.startsWith("session/")||t.startsWith("x/")||t.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Xc(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{mh().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=>my.call(this,e)],["memory.dream",e=>oi.call(this,e)],["agent.abort",e=>dy.call(this,e)],["tool.approval.response",e=>uy.call(this,e)],["thread.user_response",e=>py.call(this,e)],["thread.list",e=>Uy.call(this,e)],["session.resume",e=>qy.call(this,e)],["thread.create",e=>$y.call(this,e)],["session.getInfo",e=>Yy.call(this,e)],["session.create",e=>jy.call(this,e)],["session.resolve",e=>Fy.call(this,e)],["session.list",e=>By.call(this,e)],["session.get",e=>Wy.call(this,e)],["session.getMessages",e=>Gy.call(this,e)],["session.update",e=>Hy.call(this,e)],["session.delete",e=>Vy.call(this,e)],["session.deleteAll",e=>Ky.call(this,e)],["session.archive",e=>zy.call(this,e)],["memory.list",e=>Hb.call(this,e)],["memory.atlas",e=>Vb.call(this,e)],["memory.activity",e=>Kb.call(this,e)],["memory.read",e=>zb.call(this,e)],["memory.write",e=>qb.call(this,e)],["memory.search",e=>Yb.call(this,e)],["memory.delete",e=>Xb.call(this,e)],["tools.list",e=>Jb.call(this,e)],["media.listModels",e=>vk.call(this,e)],["media.cancel",e=>Sk.call(this,e)],["media.status",e=>Tk.call(this,e)],["media.stt",e=>wk.call(this,e)],["settings.listProviders",e=>xk.call(this,e)],["settings.addKey",e=>Rk.call(this,e)],["settings.removeKey",e=>_k.call(this,e)],["settings.toggleKey",e=>Ak.call(this,e)],["settings.toggleModel",e=>Pk.call(this,e)],["settings.listModels",e=>Ik.call(this,e)],["settings.setActiveModel",e=>Ck.call(this,e)],["settings.getActiveModel",e=>Ek.call(this,e)],["settings.getOverview",e=>Mk.call(this,e)],["settings.refreshModels",e=>Ok.call(this,e)],["settings.validateKey",e=>Dk.call(this,e)],["provider.list",e=>Qb.call(this,e)],["config.get",e=>Zb.call(this,e)],["config.update",e=>ek.call(this,e)],["config.tunables",e=>tk.call(this,e)],["config.updateTunable",e=>nk.call(this,e)],["todos.list",e=>ok.call(this,e)],["tasks.list",e=>rk.call(this,e)],["tasks.cancel",e=>sk.call(this,e)],["agents.scan",e=>ak.call(this,e)],["agents.list",e=>lk.call(this,e)],["agents.config",e=>ck.call(this,e)],["agents.setConfig",e=>dk.call(this,e)],["agents.getConfig",e=>uk.call(this,e)],["agents.removeConfig",e=>pk.call(this,e)],["agents.setGateway",e=>mk.call(this,e)],["agents.getGateway",e=>fk.call(this,e)],["agents.processes",e=>hk.call(this,e)],["agents.kill",e=>yk.call(this,e)],["agents.listConfigured",e=>gk.call(this,e)],["agents.getLog",e=>bk.call(this,e)],["agents.testConnection",e=>kk.call(this,e)],["solo.start",e=>sb.call(this,e)],["solo.status",e=>ib.call(this,e)],["solo.cancel",e=>ab.call(this,e)],["solo.select",e=>lb.call(this,e)],["solo.list",e=>cb.call(this,e)],["solo.delete",e=>db.call(this,e)],["solo.message",e=>ub.call(this,e)],["solo.evaluate",e=>pb.call(this,e)],["product.plan",e=>Ry.call(this,e)],["product.confirm",e=>_y.call(this,e)],["product.message",e=>Ay.call(this,e)],["product.create",e=>Py.call(this,e)],["product.resume",e=>Iy.call(this,e)],["product.pause",e=>Cy.call(this,e)],["product.checkpoint",e=>Ey.call(this,e)],["product.status",e=>My.call(this,e)],["product.list",e=>Oy.call(this,e)],["product.delete",e=>Dy.call(this,e)],["product.cancel",e=>Ly.call(this,e)],["product.rollback",e=>Ny.call(this,e)],["project.create",e=>xb.call(this,e)],["project.list",e=>Rb.call(this,e)],["project.delete",e=>_b.call(this,e)],["project.purgeAll",e=>Ab.call(this,e)],["project.rename",e=>Pb.call(this,e)],["project.archive",e=>Ib.call(this,e)],["project.unarchive",e=>Cb.call(this,e)],["project.update",e=>Mb.call(this,e)],["project.archiveByGroup",e=>Eb.call(this,e)],["session.switchProject",e=>Xy.call(this,e)],["session.focus",e=>Qy.call(this,e)],["session.moveToProject",e=>Zy.call(this,e)],["session.getState",e=>Jy.call(this,e)],["files.list",e=>Lb.call(this,e)],["files.create",e=>Nb.call(this,e)],["files.rename",e=>$b.call(this,e)],["files.delete",e=>Ub.call(this,e)],["files.gitStatus",e=>jb.call(this,e)],["instructions.list",e=>Fb.call(this,e)],["instructions.read",e=>Bb.call(this,e)],["instructions.write",e=>Wb.call(this,e)],["instructions.delete",e=>Gb.call(this,e)],["skills.list",e=>fb.call(this,e)],["skills.activate",e=>gb.call(this,e)],["skills.deactivate",e=>hb.call(this,e)],["skills.delete",e=>yb.call(this,e)],["skills.promote",e=>bb.call(this,e)],["skills.stats",e=>kb.call(this,e)],["skills.pin",e=>vb.call(this,e)],["skills.unpin",e=>Sb.call(this,e)],["skills.curator",e=>Tb.call(this,e)],["skills.lifecycle",e=>wb.call(this,e)],["pet.hatch",e=>Lk.call(this,e)],["pet.interact",e=>Nk.call(this,e)],["pet.status",e=>$k.call(this,e)],["pet.forge",e=>Uk.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:Ot().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:[...Oh]}}),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=zp(t);kd(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 $t(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
|
+
`+m),s=en(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=dr(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=ur(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:en(r),parts:so(en(r)),colors:ao(en(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"}};ar(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 eM=ZE(import.meta.url);function tM(){for(let n of["../package.json","../../package.json"])try{return eM(n).version}catch{}return"0.0.0"}var nM=tM();function oM(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 ui=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=zt();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 kn,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 Dn({verbose:e.verbose}),this.taskStore.onTaskChange((r,s)=>{s&&this.sendNotification("task.updated",{taskId:r,type:s.type,lifecycle:s.lifecycle,label:s.label})}),dg({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 er(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()&&(ag(e),this.mediaPersistence.setProjectDir(e))}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),rm().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(Jc(e)||nr(e)){this.acpServer.dispatchMessage(e);return}if(tr(e)){let t=e.method;if(t==="initialize"||t.startsWith("session/")||t.startsWith("x/")||t.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Xc(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{mh().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=>my.call(this,e)],["memory.dream",e=>oi.call(this,e)],["agent.abort",e=>dy.call(this,e)],["tool.approval.response",e=>uy.call(this,e)],["thread.user_response",e=>py.call(this,e)],["thread.list",e=>Uy.call(this,e)],["session.resume",e=>qy.call(this,e)],["thread.create",e=>$y.call(this,e)],["session.getInfo",e=>Yy.call(this,e)],["session.create",e=>jy.call(this,e)],["session.resolve",e=>Fy.call(this,e)],["session.list",e=>By.call(this,e)],["session.get",e=>Wy.call(this,e)],["session.getMessages",e=>Gy.call(this,e)],["session.update",e=>Hy.call(this,e)],["session.delete",e=>Vy.call(this,e)],["session.deleteAll",e=>Ky.call(this,e)],["session.archive",e=>zy.call(this,e)],["memory.list",e=>Hb.call(this,e)],["memory.atlas",e=>Vb.call(this,e)],["memory.activity",e=>Kb.call(this,e)],["memory.read",e=>zb.call(this,e)],["memory.write",e=>qb.call(this,e)],["memory.search",e=>Yb.call(this,e)],["memory.delete",e=>Xb.call(this,e)],["tools.list",e=>Jb.call(this,e)],["media.listModels",e=>vk.call(this,e)],["media.cancel",e=>Sk.call(this,e)],["media.status",e=>Tk.call(this,e)],["media.stt",e=>wk.call(this,e)],["settings.listProviders",e=>xk.call(this,e)],["settings.addKey",e=>Rk.call(this,e)],["settings.removeKey",e=>_k.call(this,e)],["settings.toggleKey",e=>Ak.call(this,e)],["settings.toggleModel",e=>Pk.call(this,e)],["settings.listModels",e=>Ik.call(this,e)],["settings.setActiveModel",e=>Ck.call(this,e)],["settings.getActiveModel",e=>Ek.call(this,e)],["settings.getOverview",e=>Mk.call(this,e)],["settings.refreshModels",e=>Ok.call(this,e)],["settings.validateKey",e=>Dk.call(this,e)],["provider.list",e=>Qb.call(this,e)],["config.get",e=>Zb.call(this,e)],["config.update",e=>ek.call(this,e)],["config.tunables",e=>tk.call(this,e)],["config.updateTunable",e=>nk.call(this,e)],["todos.list",e=>ok.call(this,e)],["tasks.list",e=>rk.call(this,e)],["tasks.cancel",e=>sk.call(this,e)],["agents.scan",e=>ak.call(this,e)],["agents.list",e=>lk.call(this,e)],["agents.config",e=>ck.call(this,e)],["agents.setConfig",e=>dk.call(this,e)],["agents.getConfig",e=>uk.call(this,e)],["agents.removeConfig",e=>pk.call(this,e)],["agents.setGateway",e=>mk.call(this,e)],["agents.getGateway",e=>fk.call(this,e)],["agents.processes",e=>hk.call(this,e)],["agents.kill",e=>yk.call(this,e)],["agents.listConfigured",e=>gk.call(this,e)],["agents.getLog",e=>bk.call(this,e)],["agents.testConnection",e=>kk.call(this,e)],["solo.start",e=>sb.call(this,e)],["solo.status",e=>ib.call(this,e)],["solo.cancel",e=>ab.call(this,e)],["solo.select",e=>lb.call(this,e)],["solo.list",e=>cb.call(this,e)],["solo.delete",e=>db.call(this,e)],["solo.message",e=>ub.call(this,e)],["solo.evaluate",e=>pb.call(this,e)],["product.plan",e=>Ry.call(this,e)],["product.confirm",e=>_y.call(this,e)],["product.message",e=>Ay.call(this,e)],["product.create",e=>Py.call(this,e)],["product.resume",e=>Iy.call(this,e)],["product.pause",e=>Cy.call(this,e)],["product.checkpoint",e=>Ey.call(this,e)],["product.status",e=>My.call(this,e)],["product.list",e=>Oy.call(this,e)],["product.delete",e=>Dy.call(this,e)],["product.cancel",e=>Ly.call(this,e)],["product.rollback",e=>Ny.call(this,e)],["project.create",e=>xb.call(this,e)],["project.list",e=>Rb.call(this,e)],["project.delete",e=>_b.call(this,e)],["project.purgeAll",e=>Ab.call(this,e)],["project.rename",e=>Pb.call(this,e)],["project.archive",e=>Ib.call(this,e)],["project.unarchive",e=>Cb.call(this,e)],["project.update",e=>Mb.call(this,e)],["project.archiveByGroup",e=>Eb.call(this,e)],["session.switchProject",e=>Xy.call(this,e)],["session.focus",e=>Qy.call(this,e)],["session.moveToProject",e=>Zy.call(this,e)],["session.getState",e=>Jy.call(this,e)],["files.list",e=>Lb.call(this,e)],["files.create",e=>Nb.call(this,e)],["files.rename",e=>$b.call(this,e)],["files.delete",e=>Ub.call(this,e)],["files.gitStatus",e=>jb.call(this,e)],["instructions.list",e=>Fb.call(this,e)],["instructions.read",e=>Bb.call(this,e)],["instructions.write",e=>Wb.call(this,e)],["instructions.delete",e=>Gb.call(this,e)],["skills.list",e=>fb.call(this,e)],["skills.activate",e=>gb.call(this,e)],["skills.deactivate",e=>hb.call(this,e)],["skills.delete",e=>yb.call(this,e)],["skills.promote",e=>bb.call(this,e)],["skills.stats",e=>kb.call(this,e)],["skills.pin",e=>vb.call(this,e)],["skills.unpin",e=>Sb.call(this,e)],["skills.curator",e=>Tb.call(this,e)],["skills.lifecycle",e=>wb.call(this,e)],["pet.hatch",e=>Lk.call(this,e)],["pet.interact",e=>Nk.call(this,e)],["pet.status",e=>$k.call(this,e)],["pet.forge",e=>Uk.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:Ot().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:[...Oh]}}),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=zp(t);kd(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 $t(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]
|
|
810
810
|
Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
|
|
811
811
|
Be specific: "run the tests" beats "continue".
|
|
812
812
|
Stay silent if the next step isn't obvious.
|
|
@@ -841,8 +841,8 @@ ${t?`\u7528\u6237\u8865\u5145\u63CF\u8FF0\uFF1A${t}`:""}
|
|
|
841
841
|
`)}}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=op();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);hg(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=Xf();for(let v of g)P.addRule(v);bc(!0),l.info(`[permissions] group security mode active: ${g.length} rules injected`)}else bc(!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 $=Ot();this.permissionChecker.setToolMeta($),this.permissionUnregister=this.permissionChecker.register();let W=Ct(this.getActiveProjectRoot()),S=[W,Vt(),...Array.isArray(e?.skillPaths)?e.skillPaths:[]];Pe(Pg({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=Vt();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(`---
|
|
842
842
|
`)?V.indexOf("---",4):-1,ge=(Ge>=0?V.slice(Ge+3).trimStart():V).split(`
|
|
843
843
|
`).find(Ft=>Ft.trim()&&!Ft.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}_${xt().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=Ot().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 nn=We(D);return Vc(nn,g),Ve(D,nn),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 Vc(Ge,g),Ve(D,Ge),oe.join("")||`[skill "${g}"] completed (no output)`},manageSkill:async g=>{let v=this.getActiveProjectRoot(),_=Ct(v),C=te.join(_,g.name),R=te.join(C,"SKILL.md"),U=H();switch(g.action){case"create":{let D=g.content??"",V=Yc(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"}}),ht(),Zt(ee,g.name,"created"),Ve(U,ee),this.memoryProvider&&this.memoryUserId){let me=V.split(`
|
|
844
|
-
`).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=Yc(M,g.name)??M;return await Y.promises.writeFile(R,ae,"utf8"),Kc(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"),Kc(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"}}),ht(),{success:!0,message:`Skill "${g.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${g.action}`}}},promoteSkill:async g=>{let v=Ct(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=Vt(),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"}}),ht(),{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??tM(_);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=Vt(),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"}}),ht(),{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(Eg({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 _=ln(),C=Aa(_,v),U=Ot().filter(oe=>C.includes(oe.function.name)),D=El(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 Nc({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}-${xt().slice(0,8)}`,status:V.ok?"completed":"failed",output:ae||void 0,error:V.error,tokensUsed:ee}}}));let ce=mt(),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(Mg({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:Xo.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:Xo.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()};In(async()=>{for(let g of ie.values())g.timerId&&clearTimeout(g.timerId)}),Pe(Dg({createJob:async g=>{let v=`cron_${xt().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;In(async()=>{for(let g of Q.values())g.cleanup();Q.clear()}),Pe(Lg({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 un({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")});In(async()=>{B.dispose()}),Pe(Ng({createTeam:async g=>{if(T.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let v=await Go(),_=[];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 vf(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 Go();if(_)for(let C of v.members)C.worktreePath&&C.worktreeBranch&&(await Sf(_,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:Zg,label:eh,description:nh,parameters:th,execute:async(v,_)=>{let C=await oh(_,{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}}}})}Wp(d,{getMemdir:()=>this.memdir,log:{debug:g=>l.debug(g),warn:g=>l.warn(g)}},this.memoryPrefetchState);{let g=e?.workdir??process.cwd(),v=Fg(g,this.currentSessionId||"default");Pe(jg(v))}Pe(Bg({sendNotification:async g=>(l.info(`[notify] ${g.title??""}: ${g.message}`),{delivered:!0,channel:g.channel??"cli"})})),Pe(Wg({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=pi.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
|
+
`).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=Yc(M,g.name)??M;return await Y.promises.writeFile(R,ae,"utf8"),Kc(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"),Kc(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"}}),ht(),{success:!0,message:`Skill "${g.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${g.action}`}}},promoteSkill:async g=>{let v=Ct(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=Vt(),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"}}),ht(),{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??oM(_);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=Vt(),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"}}),ht(),{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(Eg({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 _=ln(),C=Aa(_,v),U=Ot().filter(oe=>C.includes(oe.function.name)),D=El(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 Nc({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}-${xt().slice(0,8)}`,status:V.ok?"completed":"failed",output:ae||void 0,error:V.error,tokensUsed:ee}}}));let ce=mt(),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(Mg({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:Xo.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:Xo.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()};In(async()=>{for(let g of ie.values())g.timerId&&clearTimeout(g.timerId)}),Pe(Dg({createJob:async g=>{let v=`cron_${xt().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;In(async()=>{for(let g of Q.values())g.cleanup();Q.clear()}),Pe(Lg({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 un({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")});In(async()=>{B.dispose()}),Pe(Ng({createTeam:async g=>{if(T.has(g.teamName))return{success:!1,error:`Team "${g.teamName}" already exists.`};let v=await Go(),_=[];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 vf(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 Go();if(_)for(let C of v.members)C.worktreePath&&C.worktreeBranch&&(await Sf(_,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:Zg,label:eh,description:nh,parameters:th,execute:async(v,_)=>{let C=await oh(_,{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}}}})}Wp(d,{getMemdir:()=>this.memdir,log:{debug:g=>l.debug(g),warn:g=>l.warn(g)}},this.memoryPrefetchState);{let g=e?.workdir??process.cwd(),v=Fg(g,this.currentSessionId||"default");Pe(jg(v))}Pe(Bg({sendNotification:async g=>(l.info(`[notify] ${g.title??""}: ${g.message}`),{delivered:!0,channel:g.channel??"cli"})})),Pe(Wg({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=pi.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(`
|
|
845
845
|
`).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(Vg({executeInVm:async C=>{let R=Date.now();try{let U=_(),D=await pi.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(Kg({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=ph({projectRoot:Re,ruleEngine:P,hooks:d,log:g=>l.info(`[settings] ${g}`)});In(async()=>{he()}),this.currentSessionId&&d.invoke("session.created",{sessionId:this.currentSessionId}).catch(()=>{}),this.fileWatcher&&this.fileWatcher.stop();let jt=e?.workdir??process.cwd();return gm({projectRoot:jt,sessionId:this.currentSessionId,hooks:d,log:g=>l.debug(g),onInstructionCacheReset:Sm}).then(g=>{this.fileWatcher=g,In(async()=>{this.fileWatcher?.stop()})}).catch(g=>{l.warn(`[file-watcher] init error: ${g instanceof Error?g.message:g}`)}),this.agent=new No({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=ot(t);if(!r)return`Error: Unknown tool "${t}"`;let s=`mcp_${e}_${xt().slice(0,8)}`;try{return(await r.execute(s,o)).content.map(a=>a.text??"").join(`
|
|
846
846
|
`)||"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)Mh(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}
|
|
847
|
-
`)}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 Mt(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-${xt().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:eM},agentCapabilities:o}}async acpHandleSessionNew(e){let t=e.sessionId??xt();return this.log(`[acp] session/new: id=${t}`),this.currentSessionId=t,this.sessionState=new an(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=zt(),e.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.enableIdleDream(),{sessionId:t}}async acpHandleSessionPrompt(e){let t=xt(),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=Ot(),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-${xt().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-${xt().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${xt().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"),Ia()}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 En.call(this).plan(e)}async acpHandleProductConfirm(e){this.log("[acp] x/product.confirm");let t=En.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=En.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 Nc({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}}};function jk(n){let e={verbose:!1};for(let t of n.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{writeFileSync as nM,appendFileSync as Fk,mkdirSync as oM}from"node:fs";import{join as Rd}from"node:path";import{homedir as rM}from"node:os";var Bk=Rd(process.env.QLOGICAGENT_HOME||Rd(rM(),".qlogicagent"),"debug-logs");try{oM(Bk,{recursive:!0})}catch{}var _d=Rd(Bk,"acp-session.log");try{nM(_d,"")}catch{}function Ze(n){let e=`[${new Date().toISOString()}] ${n}
|
|
848
|
-
`;Wk.call(process.stderr,e);try{Fk(_d,e)}catch{}}var Wk=process.stderr.write.bind(process.stderr);process.stderr.write=((n,...e)=>{let t=typeof n=="string"?n:Buffer.from(n).toString();try{Fk(_d,t)}catch{}return Wk(n,...e)});Ze(`PID=${process.pid} argv=${JSON.stringify(process.argv.slice(1))} cwd=${process.cwd()} HOME=${process.env.QLOGICAGENT_HOME??"(unset)"} NODE=${process.version}`);var Gk=jk(process.argv),
|
|
847
|
+
`)}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 Mt(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-${xt().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:nM},agentCapabilities:o}}async acpHandleSessionNew(e){let t=e.sessionId??xt();return this.log(`[acp] session/new: id=${t}`),this.currentSessionId=t,this.sessionState=new an(t),this.sessionTaskDomain=void 0,this.memoryPrefetchState=zt(),e.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.enableIdleDream(),{sessionId:t}}async acpHandleSessionPrompt(e){let t=xt(),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=Ot(),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-${xt().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-${xt().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${xt().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"),Ia()}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 En.call(this).plan(e)}async acpHandleProductConfirm(e){this.log("[acp] x/product.confirm");let t=En.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=En.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 Nc({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}}};function jk(n){let e={verbose:!1};for(let t of n.slice(2))(t==="--verbose"||t==="-v")&&(e.verbose=!0);return e}import{writeFileSync as rM,appendFileSync as Fk,mkdirSync as sM}from"node:fs";import{join as Rd}from"node:path";import{homedir as iM}from"node:os";var Bk=Rd(process.env.QLOGICAGENT_HOME||Rd(iM(),".qlogicagent"),"debug-logs");try{sM(Bk,{recursive:!0})}catch{}var _d=Rd(Bk,"acp-session.log");try{rM(_d,"")}catch{}function Ze(n){let e=`[${new Date().toISOString()}] ${n}
|
|
848
|
+
`;Wk.call(process.stderr,e);try{Fk(_d,e)}catch{}}var Wk=process.stderr.write.bind(process.stderr);process.stderr.write=((n,...e)=>{let t=typeof n=="string"?n:Buffer.from(n).toString();try{Fk(_d,t)}catch{}return Wk(n,...e)});Ze(`PID=${process.pid} argv=${JSON.stringify(process.argv.slice(1))} cwd=${process.cwd()} HOME=${process.env.QLOGICAGENT_HOME??"(unset)"} NODE=${process.version}`);var Gk=jk(process.argv),aM=!process.argv.includes("--no-acp"),lM=new Dn({verbose:Gk.verbose}),mi=new ui({verbose:Gk.verbose,transport:lM});aM&&(mi.initAcpServer(),Ze("ACP server initialized, waiting for messages"));process.on("unhandledRejection",n=>{Ze(`unhandledRejection: ${n instanceof Error?n.stack??n.message:String(n)}`)});process.on("uncaughtException",n=>{Ze(`uncaughtException: ${n.stack??n.message}`)});process.stdin.on("end",()=>{Ze("stdin END received")});process.stdin.on("close",()=>{Ze("stdin CLOSE received")});process.stdout.on("error",n=>{Ze(`stdout ERROR: ${n.message}`)});process.stdout.on("close",()=>{Ze("stdout CLOSE")});process.on("exit",n=>{Ze(`process.exit code=${n}`)});process.on("SIGTERM",()=>{Ze("SIGTERM received"),mi.stop(),process.exit(0)});process.on("SIGINT",()=>{Ze("SIGINT received"),mi.stop(),process.exit(0)});process.on("SIGHUP",()=>{Ze("SIGHUP received")});Ze("calling server.start()");mi.start();Ze("server.start() returned, event loop active");
|