qlogicagent 2.10.42 → 2.10.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -543,7 +543,7 @@ If no action needed, just respond with a progress update message to the user.`,e
543
543
  `)},onMcpToolCall:(a,c,l)=>this.handleMcpToolCall(a,c,l),sessionDir:nR.join(X(),"agent-logs")}),n=Zk({findTool:a=>this.toolCatalog.findTool(a),runAgent:async({agentId:a,prompt:c,signal:l})=>{let d=a??"self",p=this.acpDetector.buildExternalDescriptor(d);if(!p)throw new Error(`workflow agent node: agent "${d}" is not available`);let u=`workflow-agent-${oR().slice(0,8)}`;if(l?.aborted)throw new Error("workflow agent node aborted before dispatch");await r.spawn({memberId:u,name:`workflow-${d}`,cwd:t,prompt:c,external:p});try{let m=await r.sendTask(u,c);return typeof m=="string"?m:JSON.stringify(m)}finally{try{r.kill(u),r.remove(u)}catch(m){process.stderr.write(`[workflow:pm] WARN cleanup of ${u} failed: ${m instanceof Error?m.message:String(m)}
544
544
  `)}}},invokeMcp:({server:a,tool:c,args:l})=>this.handleMcpToolCall(`workflow-mcp:${a}`,c,l),sendChannel:async({channel:a,target:c,payload:l})=>(this.sendNotification("workflow.channel.send",{channel:a,target:c,payload:l}),{queued:!0})}),o=new fn;for(let[a,c]of Object.entries(ho))o.register(a,c);let s=ob({registry:o,host:n,budget:{maxNodeExecutions:Cj}});this.workflowController=new pr(e,s),this.workflowStore=e,this.workflowProcessManager=r,ab(this.workflowController);let i=new Mi({controller:this.workflowController,onError:(a,c)=>{let l=a instanceof Error?a.message:String(a);process.stderr.write(`[workflow:scheduler] run error for ${c}: ${l}
545
545
  `),this.sendNotification("workflow.runFailed",{workflowId:c,triggerType:"schedule",error:l})}});this.workflowScheduler=i,i.start().catch(a=>{process.stderr.write(`[workflow:scheduler] start failed: ${a instanceof Error?a.message:String(a)}
546
- `)})}return this.workflowController}function rr(t){return t.params??{}}function nr(t,e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:e})}function Ij(t){return{id:t.id,name:t.name,active:t.active,concurrency:t.concurrency,rev:t.rev,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.trigger!==void 0?{trigger:t.trigger}:{},def:t.def}}function Ou(t,e){this.sendNotification(t,{workflow:Ij(e)})}function ju(t,e){if(t.status==="failed"){this.sendNotification("workflow.runFailed",{workflowId:t.workflowId,triggerType:e,error:"Workflow run failed",outcome:t});return}this.sendNotification("workflow.runCompleted",{workflowId:t.workflowId,status:t.status,triggerType:e,outcome:t})}function Ej(t){return t instanceof Error?t.message:String(t)}async function sR(t){let e=rr(t);if(!e.def)return nr.call(this,t,"workflow.create requires `def`");let r=Ht.call(this),n=String(e.id??`wf_${oR().slice(0,8)}`),o=await r.create({id:n,name:String(e.name??n),def:e.def,concurrency:e.concurrency,active:e.active===!0});o.active&&await this.workflowScheduler?.refresh(o.id),Ou.call(this,"workflow.created",o),t.id!==void 0&&this.sendResponse(t.id,o)}async function iR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.get requires `id`");let n=await Ht.call(this).get(String(e.id));t.id!==void 0&&this.sendResponse(t.id,n)}async function aR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.describe requires `id`");let n=await Ht.call(this).describe(String(e.id));t.id!==void 0&&this.sendResponse(t.id,{rendered:n})}async function cR(t){let e=rr(t);if(!e.id||!e.patch)return nr.call(this,t,"workflow.patch requires `id` and `patch`");let r=Ht.call(this),n={patch:e.patch,baseRev:e.baseRev,scope:e.scope},o=await r.patch(String(e.id),n);await this.workflowScheduler?.refresh(String(e.id)),o.ok&&Ou.call(this,"workflow.updated",await r.get(String(e.id))),t.id!==void 0&&this.sendResponse(t.id,o)}async function lR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.run requires `id`");let r=Ht.call(this),n=e.trigger??{type:"manual"},o=String(e.id);this.sendNotification("workflow.runStarted",{workflowId:o,triggerType:n.type});let s;try{s=await r.run(o,n),ju.call(this,s,n.type)}catch(i){throw this.sendNotification("workflow.runFailed",{workflowId:o,triggerType:n.type,error:Ej(i)}),i}t.id!==void 0&&this.sendResponse(t.id,s)}async function dR(t){let e=rr(t);if(!e.id||typeof e.active!="boolean")return nr.call(this,t,"workflow.setActive requires `id` and boolean `active`");let n=await Ht.call(this).setActive(String(e.id),e.active);await this.workflowScheduler?.refresh(n.id),Ou.call(this,"workflow.updated",n),t.id!==void 0&&this.sendResponse(t.id,n)}async function uR(t){Ht.call(this);let r=await this.workflowStore.list();t.id!==void 0&&this.sendResponse(t.id,{workflows:r})}async function pR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.delete requires `id`");Ht.call(this),await this.workflowStore.delete(String(e.id)),await this.workflowScheduler?.refresh(String(e.id)),this.sendNotification("workflow.deleted",{workflowId:String(e.id)}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function mR(t){let e=rr(t);if(!e.channel||typeof e.text!="string")return nr.call(this,t,"workflow.onImMessage requires `channel` and string `text`");Ht.call(this);let r=await this.workflowScheduler.onImMessage(String(e.channel),e.text,e.payload);for(let n of r)ju.call(this,n,"im-message");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}async function gR(t){let e=rr(t);if(!e.path)return nr.call(this,t,"workflow.onWebhook requires `path`");Ht.call(this);let r=await this.workflowScheduler.onWebhook(String(e.path),e.payload);for(let n of r)ju.call(this,n,"webhook");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}import*as Ce from"node:fs";import*as me from"node:path";G();import*as Hr from"node:fs";import*as $u from"node:path";G();import*as xe from"node:fs";import*as Ao from"node:path";function _i(t){let e=X(),r=De(t);xe.existsSync(r)||xe.mkdirSync(r,{recursive:!0});let n=Ao.join(e,"INSTRUCTIONS.md"),o=Ao.join(r,"INSTRUCTIONS.md");if(xe.existsSync(n)&&!xe.existsSync(o))try{xe.copyFileSync(n,o)}catch{}let s=sm(),i=Xr(t);if(xe.existsSync(s)&&!xe.existsSync(i))try{xe.mkdirSync(i,{recursive:!0});for(let a of xe.readdirSync(s)){if(!a.endsWith(".md"))continue;let c=Ao.join(s,a),l=Ao.join(i,a);xe.statSync(c).isFile()&&xe.copyFileSync(c,l)}}catch{}}var Mj=["creating","running","completed","cancelled"];function fR(t){return typeof t=="string"&&Mj.includes(t)}function hR(t,e){let r=I(),n=e.workspaceDir||$u.join(r.getUserAgentHome(),"workspaces",e.name);if(e.groupId){let l=Ns(e.groupId);if(l)return{project:l,isAgentTeamProject:l.type==="solo"||l.type==="product",deduplicated:!0}}let s=z().find(l=>l.name===e.name);_j(n);let i=Ds({name:e.name,workspaceDir:n,type:e.type??"personal",groupId:e.groupId,skipAutoSwitch:e.type==="solo"||e.type==="product"}),a=i.type==="solo"||i.type==="product";a||(Ct(i.id),t.setActiveWorkdir(i.workspaceDir)),_i(i.workspaceDir);let c=t.projectMemoryStoreFactory.create(i.workspaceDir);return c.ensureInitialized(),a||(t.memdir=c,t.mediaPersistence.setProjectDir(i.workspaceDir)),Dj(i),{project:i,nameDuplicate:s,isAgentTeamProject:a}}function _j(t){Hr.existsSync(t)||Hr.mkdirSync(t,{recursive:!0})}function Dj(t){let e=I();if(t.type!=="solo"&&t.type!=="product")return;let r=$u.join(e.getProjectAgentDir(t.workspaceDir),t.type==="solo"?"solo-state.json":"product-state.json");if(Hr.existsSync(r))return;let n=t.type==="solo"?{agents:[],status:"idle",createdAt:new Date().toISOString()}:{tasks:[],instances:[],status:"idle",createdAt:new Date().toISOString()};Hr.writeFileSync(r,JSON.stringify(n,null,2))}function yR(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let r;try{r=hR(this,{name:e.name,workspaceDir:e.workspaceDir,type:e.type,groupId:e.groupId})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:a instanceof Error?a.message:`Cannot create workspace directory: ${e.workspaceDir??e.name}`});return}let{project:n,nameDuplicate:o,isAgentTeamProject:s,deduplicated:i}=r;if(i){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:n,deduplicated:!0});return}if(this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type}),s||this.sendNotification("project.switched",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),t.id!==void 0){let a={ok:!0,project:n};o&&(a.warning=`A project named "${o.name}" already exists at ${o.workspaceDir}. Consider renaming one of them to avoid ambiguity.`),this.sendResponse(t.id,a)}}function vR(t){let e=z();t.id!==void 0&&this.sendResponse(t.id,{projects:e})}function bR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Te(e.projectId),n=ed(e.projectId);if(!n.deleted){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}let o=!1,s;if(r?.workspaceDir){let i=me.join(X(),"workspaces"),a=me.resolve(r.workspaceDir);if(a.startsWith(me.resolve(i)+me.sep)){try{this.mediaPersistence?.releaseProjectDir?.(a)}catch{}for(let c=0;c<3;c++)try{Ce.rmSync(a,{recursive:!0,force:!0}),o=!0;break}catch(l){if(c<2&&(l.code==="EBUSY"||l.code==="EPERM"||l.code==="ENOTEMPTY")){let d=Date.now();for(;Date.now()-d<200;);}else{s=l.message??String(l);break}}}else s="Project directory is outside the managed workspace root and was not deleted automatically."}this.sendNotification("project.deleted",{id:e.projectId}),n.switchedTo&&(this.setActiveWorkdir(n.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:n.switchedTo,dirDeleted:o,dirDeleteError:s})}function kR(t){let e=z(),r=me.join(X(),"workspaces"),n=me.resolve(r)+me.sep,o=0,s=[];for(let a of e)if(a.type!=="default"){if(ed(a.id),o++,a.workspaceDir){let c=me.resolve(a.workspaceDir);try{this.mediaPersistence?.releaseProjectDir?.(c)}catch{}for(let l=0;l<3;l++)try{Ce.existsSync(c)&&Ce.rmSync(c,{recursive:!0,force:!0});break}catch(d){if(l<2&&(d.code==="EBUSY"||d.code==="EPERM"||d.code==="ENOTEMPTY")){let p=Date.now();for(;Date.now()-p<300;);}else{s.push(`${a.name}: ${d.message??d}`);break}}}this.sendNotification("project.deleted",{id:a.id})}if(Ce.existsSync(r)){let a=z().find(d=>d.type==="default"),c=new Set;a?.workspaceDir&&c.add(me.resolve(a.workspaceDir));let l=d=>{try{let p=Ce.readdirSync(d,{withFileTypes:!0});for(let u of p){if(!u.isDirectory())continue;let m=me.join(d,u.name);if(!c.has(me.resolve(m))){if(u.name==="groups"){l(m);try{Ce.readdirSync(m).length===0&&Ce.rmdirSync(m)}catch{}continue}try{Ce.rmSync(m,{recursive:!0,force:!0})}catch(f){s.push(`orphan:${u.name}: ${f.message??f}`)}}}}catch{}};l(r)}let i=z().find(a=>a.type==="default");i&&(this.setActiveWorkdir(i.workspaceDir),this.sendNotification("project.switched",{id:i.id,name:i.name,workspaceDir:i.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o,dirErrors:s.length?s:void 0})}function RR(t){let e=t.params;if(!e?.projectId||!e?.newName){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let r=Zf(e.projectId,e.newName);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}let n=me.join(X(),"workspaces"),o=me.resolve(r.workspaceDir);if(o.startsWith(me.resolve(n)+me.sep)){let s=me.join(n,e.newName);if(Ce.existsSync(o)&&!Ce.existsSync(s))try{Ce.renameSync(o,s),eh(e.projectId,s),r.workspaceDir=s,this.getActiveProjectRoot()===o&&this.setActiveWorkdir(s)}catch{}}this.sendNotification("project.renamed",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function SR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=th(e.projectId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:e.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:r.switchedTo})}function TR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=rh(e.projectId);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function wR(t){let e=t.params;if(!e?.groupId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: groupId"});return}let r=nh(e.groupId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:r.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:r.projectId})}function AR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"projectId is required"});return}let r={};if("planStatus"in e){if(e.planStatus!==void 0&&!fR(e.planStatus)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Invalid planStatus: ${e.planStatus}`});return}r.planStatus=e.planStatus}"planAgents"in e&&(r.planAgents=e.planAgents),"planWinnerId"in e&&(r.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(r.leaderSessionId=e.leaderSessionId);let n=Jf(e.projectId,r);t.id!==void 0&&this.sendResponse(t.id,{ok:n})}import{randomUUID as Fu}from"node:crypto";import*as Ve from"node:fs";import*as Br from"node:path";var fr=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[r,n]of this._modelUsage)e[r]={...n};return e}addUsage(e,r){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(r);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(r,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,r,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||this._modelUsage.set(e,s),s.mediaCalls+=1,r){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break;case"per_token":s.outputTokens+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[r,n]of Object.entries(e.modelUsage))this._modelUsage.set(r,{...n});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as PR from"node:fs";import*as Uu from"node:path";var hr=class{getSessionsRoot(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return I().getProjectSessionsRoot(r.workspaceDir)}getProjectWorkspaceDir(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return r.workspaceDir}getSessionDir(e,r){return Uu.join(this.getSessionsRoot(e),r)}resolveWorkspaceDir(e,r){if(r)return this.getProjectWorkspaceDir(r);let n=z();for(let o of n){let s=I().getProjectSessionsRoot(o.workspaceDir),i=Uu.join(s,e);try{if(PR.existsSync(i))return o.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=ne();if(e)return e.workspaceDir;let r=z();if(r.length>0)return r[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=ne();if(e)return e.id;let r=z();if(r.length>0)return r[0].id;throw new Error("No active project available")}};import{randomUUID as xR}from"node:crypto";async function CR(t,e){let r=new Date(t.lastActiveAt).getTime();if(Date.now()-r<Yp)return{split:!1,activeSessionId:t.sessionId};let s=xR(),i=new Date().toISOString();await Fe(t.sessionId,{sealedAt:i},e);let a=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${t.taskSummary}`:void 0;return await Fe(s,{sessionId:s,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:t.sessionId}}async function IR(t,e){if(t.type!=="group")return{split:!1,activeSessionId:t.sessionId};if(t.turnCount<Jp)return{split:!1,activeSessionId:t.sessionId};let r=xR(),n=new Date().toISOString();await Fe(t.sessionId,{sealedAt:n},e);let o=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${t.taskSummary}`:void 0;return await Fe(r,{sessionId:r,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:o},e),{split:!0,activeSessionId:r,sealedSessionId:t.sessionId}}G();import*as ER from"node:fs";import*as MR from"node:path";var Di=class{constructor(e=new hr,r=I()){this.locator=e;this.pathService=r}locator;pathService;getActiveProjectId(){return this.locator.getActiveProjectId()}getProjectWorkspaceDir(e){return this.locator.getProjectWorkspaceDir(e)}resolveWorkspaceDir(e,r){return this.locator.resolveWorkspaceDir(e,r)}async listThreads(e,r){let n=r??this.getActiveProjectId(),o=this.getProjectWorkspaceDir(n);return(await Rt(e,o)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:i.createdAt,lastActiveAt:i.lastActiveAt}))}resolveSessionWorkspaceDir(e,r,n){if(n)return this.resolveWorkspaceDir(r,n);let o=e.getActiveProjectRoot();if(o){let s=MR.join(this.pathService.getProjectSessionsRoot(o),Nj(r));try{if(ER.existsSync(s))return o}catch{}}return this.resolveWorkspaceDir(r)}};function Nj(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}var Lj=new hr,tt=new Di(Lj);function yt(t,e="Unknown error"){return t instanceof Error?t.message:e}function Rn(t,e,r){return tt.resolveSessionWorkspaceDir(t,e,r)}function _R(t){let e=t.params,r=e?.id??Fu();this.log(`[thread.create] id=${r} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=r,this.sessionState=new fr(r),this.sessionTaskDomain=void 0,this.memoryPrefetchState=kt(),this.enableIdleDream(),t.id!==void 0&&this.sendResponse(t.id,{id:r,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function DR(t){let e=t.params,r=e?.limit??20;try{let n=await tt.listThreads(r,e?.projectId);t.id!==void 0&&this.sendResponse(t.id,{threads:n})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list threads: ${yt(n)}`})}}async function NR(t){let e=t.params,r=e?.sessionId??Fu();try{let n=e?.projectId??tt.getActiveProjectId(),o=tt.getProjectWorkspaceDir(n);await Fe(r,{sessionId:r,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:n},o),t.id!==void 0&&this.sendResponse(t.id,{sessionId:r,title:e?.title})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to create session: ${yt(n)}`})}}async function LR(t){let e=t.params;if(t.id===void 0)return;let r=e?.platform??"desktop",n=e?.chatId,o=e?.chatType,s=e?.userId??"local";try{if(r==="desktop"&&n){let d=e?.projectId??tt.getActiveProjectId(),p=tt.getProjectWorkspaceDir(d),m=(await Rt(500,p)).find(f=>f.sessionId===n);if(m){this.sendResponse(t.id,{sessionId:n,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await Fe(n,{sessionId:n,type:"personal",ownerId:s,projectId:d},p),this.sendResponse(t.id,{sessionId:n,type:"personal",ownerId:s,projectId:d});return}if(o==="group"&&n&&r){let d=`group:${r}:${n}`,p=z();for(let u of p){if(!u.workspaceDir)continue;let f=(await Rt(500,u.workspaceDir)).find(g=>g.groupKey===d&&!g.sealedAt);if(f){let g=Vt(f.sessionId,u.workspaceDir);if(g){let h=await CR(g,u.workspaceDir);if(h.split){this.sendResponse(t.id,{sessionId:h.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id,previousSessionId:h.sealedSessionId});return}}this.sendResponse(t.id,{sessionId:f.sessionId,title:f.title,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id});return}}}let i=Fu(),a=tt.getActiveProjectId(),c=tt.getProjectWorkspaceDir(a),l=o==="group"?`group:${r}:${n}`:void 0;await Fe(i,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a},c),this.sendResponse(t.id,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resolve session: ${yt(i)}`})}}async function OR(t){let e=t.params,r=e?.limit??50;try{let n;if(e?.projectId){let s=Te(e.projectId);if(!s){t.id!==void 0&&this.sendResponse(t.id,{sessions:[]});return}let i=s.workspaceDir;n=await Rt(r*2,i),n=n.filter(a=>a.projectId===e.projectId);for(let a of n)a.projectId=e.projectId}else{let s=z(),i=new Set,a=[];for(let c of s){if(!c.workspaceDir)continue;let l=await Rt(r,c.workspaceDir);for(let d of l)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((c,l)=>c.lastActiveAt>l.lastActiveAt?-1:c.lastActiveAt<l.lastActiveAt?1:0),n=a}e?.archived===!0?n=n.filter(s=>s.archivedAt!=null):e?.archived===!1&&(n=n.filter(s=>s.archivedAt==null));let o=n.slice(0,r).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type??"personal",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}));t.id!==void 0&&this.sendResponse(t.id,{sessions:o})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list sessions: ${yt(n)}`})}}async function jR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId),o=(await Rt(500,r)).find(s=>s.sessionId===e.sessionId);t.id!==void 0&&this.sendResponse(t.id,{session:o?{sessionId:o.sessionId,title:o.title,type:o.type,lastActiveAt:o.lastActiveAt,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:o.projectId}:null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get session: ${yt(r)}`})}}async function $R(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId),n=await Ec(e.sessionId,r);if(!n){t.id!==void 0&&this.sendResponse(t.id,{messages:[],total:0});return}let o=n.messages,s=e.limit&&e.limit>0?e.limit:o.length,i=o.slice(-s);t.id!==void 0&&this.sendResponse(t.id,{messages:i,total:o.length})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get messages: ${yt(r)}`})}}async function UR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId),n=await Fe(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},r);n&&this.sendNotification("session.info",{sessionId:e.sessionId,title:n.title,pinnedAt:n.pinnedAt??null,archivedAt:n.archivedAt??null,projectId:e.projectId||void 0}),t.id!==void 0&&this.sendResponse(t.id,{ok:n!==null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to update session: ${yt(r)}`})}}async function FR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId);await Mc(e.sessionId,r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete session: ${yt(r)}`})}}async function HR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let r=tt.getProjectWorkspaceDir(e.projectId),n=(await Rt(1e4,r)).filter(s=>s.projectId===e.projectId),o=0;for(let s of n)await Mc(s.sessionId,r),o++;t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete all sessions: ${yt(r)}`})}}async function BR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId);await Fe(e.sessionId,{archivedAt:new Date().toISOString()},r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to archive session: ${yt(r)}`})}}async function qR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"sessionId is required"});return}try{let n=Rn(this,r,e?.projectId),o=await Ec(r,n);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Session not found: ${r}`});return}o.messages&&o.messages.length>0&&this.sessionHistory.saveResumedSession(r,o.messages),t.id!==void 0&&this.sendResponse(t.id,{metadata:o.metadata,messages:o.messages})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resume session: ${yt(n)}`})}}function WR(t){let e=this.currentSessionId||"default",r=this.sessionState?.createSnapshot(),n,o=this.getActiveProjectRoot();o&&(n=Br.join(Jo(o),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:n,agentHome:X(),settings:Ue()},usage:r?{turnCount:r.turnCount,inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens}:void 0};t.id!==void 0&&this.sendResponse(t.id,s)}function GR(t){let e=t.params,r=null;if(e?.projectId)r=Te(e.projectId);else if(e?.projectName){let s=z(),i=e.projectName.toLowerCase();if(r=s.find(a=>a.name.toLowerCase()===i)??null,r||(r=s.find(a=>a.name.toLowerCase().includes(i))??null),!r){let a=s.map(c=>c.name).slice(0,10);t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!r||r.status!=="active"){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let n=e.workspaceDir??r.workspaceDir;if(!Ve.existsSync(n)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Workspace directory does not exist: ${n}`});return}let o=Ct(r.id);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(o.workspaceDir),this.sendNotification("project.switched",{id:o.id,name:o.name,workspaceDir:o.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:o})}function KR(t){let e=ne(),r=z();t.id!==void 0&&this.sendResponse(t.id,{sessionId:this.currentSessionId,activeProject:e,projects:r})}async function zR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,{ok:!1});return}let n=z();for(let o of n)try{let s=tt.getProjectWorkspaceDir(o.id),i=await Vt(r,s);if(i&&i.projectId===o.id){Ct(o.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} for session ${r}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}catch{}if(e?.projectName){let o=n.find(s=>s.name===e.projectName);if(o){let s=tt.getProjectWorkspaceDir(o.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} by name "${e.projectName}"`)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}t.id!==void 0&&this.sendResponse(t.id,{ok:!1})}async function VR(t){let e=t.params,{sessionId:r,fromProjectId:n,toProjectId:o}=e??{};if(!r||!n||!o){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(n===o){t.id!==void 0&&this.sendResponse(t.id,{ok:!0});return}let s=Te(n),i=Te(o);if(!s||!i){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"Source or target project not found");return}let a=Br.join(tt.getProjectWorkspaceDir(n),".qlogicagent","sessions",r),c=Br.join(tt.getProjectWorkspaceDir(o),".qlogicagent","sessions",r);if(!Ve.existsSync(a)){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,`Session ${r} not found in project ${n}`);return}try{Ve.mkdirSync(Br.dirname(c),{recursive:!0}),Ve.cpSync(a,c,{recursive:!0});let l=Br.join(c,"metadata.json");if(Ve.existsSync(l)){let d=JSON.parse(Ve.readFileSync(l,"utf-8"));d.projectId=o,Ve.writeFileSync(l,JSON.stringify(d,null,2))}Ve.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:r,projectId:o}),this.log(`[session.moveToProject] moved ${r}: ${n} \u2192 ${o}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o})}catch(l){let d=yt(l);this.log(`[session.moveToProject] error: ${d}`),t.id!==void 0&&this.sendError(t.id,y.INTERNAL_ERROR,`Move failed: ${d}`)}}He();function Oj(t){return t.length<=8?"****":`${t.slice(0,3)}***${t.slice(-4)}`}function Ne(t,e,r,n=y.INTERNAL_ERROR){if(e.id!==void 0){if(typeof t.sendError=="function"){t.sendError(e.id,n,r);return}t.sendResponse(e.id,void 0,{code:n,message:r})}}function Hu(t,e){Ne(t,e,ns)}function jj(t){let e={};for(let r of t)for(let n of r.purposes)e[n]??=[],e[n].push(r);return e}async function $j(){let t=D(),e=await $n(t);return t.save(),e}async function XR(t){try{return await $j(),!0}catch(e){if(t)throw e;return!1}}function Bu(t=D()){try{return Tm()}catch{return t.getKnownProviderDef(Y)?.baseUrl??"https://www.qlogicagent.com"}}function qu(t){return t.id===Y?Y:t.group?.trim()||t.id}function Uj(t){return t.id===qu(t)}function YR(t){let e=qu(t);return Oc({...t,id:e})}function Fj(t){return{volcengine:"\u5E38\u89C4 Ark API Key","volcengine-plan":"\u8BA2\u9605 / Plan \u901A\u9053",qwen:"\u5E38\u89C4 DashScope API Key","qwen-coding":"Coding Plan \u901A\u9053",zhipu:"Anthropic \u901A\u9053","zhipu-openai":"OpenAI \u517C\u5BB9\u901A\u9053","zhipu-coding":"Coding \u901A\u9053"}[t.id]??Oc(t)}function Hj(t){return t.authType==="none"?!1:t.apiKeyEnvVars===void 0||t.apiKeyEnvVars.length>0}function Bj(t){return{id:t.id,displayName:Fj(t),baseUrl:jn(t)??"",modelCount:t.models?.length??0}}function qj(t){let e=new Map;for(let r of t){if(!Hj(r))continue;let n=qu(r);if(n===Y)continue;let o=r.models?.length??0,s=Bj(r),i=e.get(n);if(!i){e.set(n,{id:n,displayName:YR(r),baseUrl:jn(r)??"",modelCount:o,variants:[s]});continue}i.modelCount+=o,i.variants??=[],i.variants.some(a=>a.id===s.id)||i.variants.push(s),Uj(r)&&(i.displayName=YR(r),i.baseUrl=jn(r)??i.baseUrl)}return Array.from(e.values()).map(r=>({...r,variants:r.variants&&r.variants.length>1?r.variants:void 0}))}async function JR(t){let e=D(),r=e.getKeyForProvider(Y);if(!r){if(t)throw new Error("LLMRouter API Key is required to fetch available models.");return!1}let n=e.getProviderStatus(Y)?.baseUrl??Bu(e);try{if((await jc(e,{baseUrl:n,apiKey:r})).length===0){if(t)throw new Error("LLMRouter did not return any available models for this API Key.");return!1}return e.save(),!0}catch(o){if(t)throw o;return!1}}async function QR(t=!1){let e=D();if(!!e.getProviderStatus(Y)?.keys.length)return await JR(!1)?!0:XR(t);let o=e.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId).some(s=>s!=="deepseek"&&s!==Y);return!t&&!o?!1:XR(t)}async function ZR(t,e,r){let n=t===Y?Nc(r):`${r.replace(/\/$/,"")}/models`;try{let o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)});if(o.ok)return{valid:!0,status:o.status};let s=await o.text().catch(()=>"");return{valid:!1,status:o.status,error:s.slice(0,500)}}catch(o){return{valid:!1,status:0,error:o instanceof Error?o.message:String(o)}}}async function Wj(t,e,r){let n=await ZR(t,e,r);if(!n.valid){let o=n.error?`: ${n.error}`:"";throw new Error(`API Key validation failed (${n.status})${o}`)}}async function eS(t){try{let e=D(),r=["deepseek",Y].map(s=>e.getKnownProviderDef(s)).filter(s=>!!s).map(s=>({id:s.id,displayName:s.name,baseUrl:s.baseUrl,modelCount:s.models?.length??0})),n=await Lc().catch(()=>[]),o=qj(n);o.unshift({id:Y,displayName:Dc,baseUrl:Bu(e),modelCount:n.reduce((s,i)=>s+(i.models?.length??0),0)});for(let s of r.reverse()){let i=o.findIndex(a=>a.id===s.id);if(i>=0){s.id!==Y&&o.splice(i,1,s);continue}o.unshift(s)}t.id!==void 0&&this.sendResponse(t.id,{providers:o})}catch(e){Ne(this,t,e instanceof Error?e.message:String(e))}}async function tS(t){let e=t.params;if(!e?.providerId||!e?.key){Ne(this,t,"Required: providerId (string), key (string)",y.INVALID_PARAMS);return}let{providerId:r,key:n,label:o}=e,s=D(),i,a=!1;try{let c=await pS(r);if(!c){Ne(this,t,`Unknown provider: ${r}`,y.INVALID_PARAMS);return}let l=s.getProviderStatus(r);if(l?.keys.some(d=>d.key===n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}if(a=!l,s.addProvider(r,{baseUrl:c}),i=s.addKey(r,n,{label:o}),r===Y){if((await jc(s,{baseUrl:c,apiKey:n})).length===0)throw new Error("LLMRouter did not return any available models for this API Key.")}else await Wj(r,n,c);for(let d of On)if(!s.getBinding(d)){let p=s.listModels({purpose:d,provider:r,enabledOnly:!0});p.length===0&&(p=s.listModels({purpose:d,provider:r}),p[0]&&s.enableModel(p[0].id)),p.length>0&&s.setBinding(d,p[0].id)}s.setKeyHealth(i,"healthy"),s.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,keyId:i,providerId:r})}catch(c){i&&(s.removeKey(i),a&&s.removeProvider(r));let l=c instanceof Error?c.message:ns;Ne(this,t,l)}}function rS(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D();r.removeKey(e.keyId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function nS(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D().getKeyById(e.keyId);if(!r){Ne(this,t,"API Key not found",y.INVALID_PARAMS);return}t.id!==void 0&&this.sendResponse(t.id,{key:r})}function oS(t){let e=t.params;if(!e?.keyId||typeof e.enabled!="boolean"){Ne(this,t,"Required: keyId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();r.updateKey(e.keyId,{enabled:e.enabled}),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function sS(t){let e=t.params;if(!e?.modelId||typeof e.enabled!="boolean"){Ne(this,t,"Required: modelId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();e.enabled?r.enableModel(e.modelId):r.disableModel(e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function iS(t){let e=t.params;try{await QR(!1);let r=D(),n=new Set(r.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),o=r.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>r.hasConfiguredKeyForProviderVariant(s.provider));t.id!==void 0&&this.sendResponse(t.id,{models:o,grouped:jj(o),configuredProviderIds:[...n]})}catch{Hu(this,t)}}function aS(t){let e=t.params;if(!e?.purpose||!e?.modelId){Ne(this,t,"Required: purpose (string), modelId (string)",y.INVALID_PARAMS);return}try{let r=D();r.setBinding(e.purpose,e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){Ne(this,t,r instanceof Error?r.message:String(r),y.INVALID_PARAMS)}}function cS(t){let e=t.params;if(!e?.purpose){Ne(this,t,"Required: purpose (string)",y.INVALID_PARAMS);return}let r=D(),n=r.getBinding(e.purpose);t.id!==void 0&&this.sendResponse(t.id,{model:n?{id:n.id,provider:n.provider,model:n.model,displayName:n.displayName,purposes:n.purposes,enabled:n.enabled}:null,available:r.isAvailable(e.purpose)})}async function lS(t){try{await QR(!1);let e=D(),r=e.getAllProviderStatus().map(s=>({providerId:s.providerId,displayName:s.providerId===Y?Dc:s.providerId,baseUrl:s.baseUrl,keyCount:s.keys.length,healthyKeys:s.keys.filter(i=>i.healthStatus==="healthy"&&i.enabled).length,totalKeys:s.keys.length,keys:s.keys.map(i=>({id:i.id,label:i.label,maskedKey:Oj(i.key),enabled:i.enabled,health:i.healthStatus}))})),n=e.getAllBindings(),o={};for(let s of On){let i=n[s];o[s]={bound:!!i,modelId:i?.id,modelName:i?.displayName,available:e.isAvailable(s)}}t.id!==void 0&&this.sendResponse(t.id,{providers:r,purposes:o})}catch{Hu(this,t)}}async function dS(t){try{let e=D();e.load(),await JR(!1)||await $n(e),e.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,catalogRefreshed:!0})}catch{Hu(this,t)}}async function uS(t){let e=t.params;if(!e?.providerId||!e?.apiKey){Ne(this,t,"providerId and apiKey required",y.INVALID_PARAMS);return}try{let r=e.baseUrl||await pS(e.providerId);if(!r){Ne(this,t,`Unknown provider: ${e.providerId}`,y.INVALID_PARAMS);return}let n=await ZR(e.providerId,e.apiKey,r);t.id!==void 0&&this.sendResponse(t.id,n)}catch(r){let n=r instanceof Error?r.message:String(r);t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:0,error:n})}}async function pS(t){if(t===Y)return Bu();let e=D().getKnownProviderDef(t);if(e?.baseUrl)return e.baseUrl;let r=await Am(t);return r?jn(r):void 0}G();import*as ce from"node:fs";import*as Le from"node:path";import{join as Gj}from"node:path";import{readFileSync as Kj,writeFileSync as zj,mkdirSync as Vj}from"node:fs";var qr=null,Wu=!1;function mS(t){return Gj(t,"skill-stats.json")}function Gu(t){if(qr)return qr;try{qr=JSON.parse(Kj(mS(t),"utf8"))}catch{qr={}}return qr}function Xj(t){if(!(!Wu||!qr))try{Vj(t,{recursive:!0}),zj(mS(t),JSON.stringify(qr,null,2),"utf8"),Wu=!1}catch{}}function Ku(t,e,r){let n=Gu(t);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),r?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Wu=!0,Xj(t)}function gS(t,e){return Gu(t)[e]}function fS(t){return Gu(t)}import*as Bt from"node:fs";import*as Ni from"node:path";function Yj(t){try{let e=Bt.readFileSync(t,"utf8"),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),n=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:r?.[1],description:n?.[1]?.trim()}}catch{return{}}}function yS(t){let e=I(),r=[],n=t?e.getProjectSkillsDir(t):void 0,o=e.getUserSkillsDir();return n&&hS(r,n,"project"),hS(r,o,"global"),r}function hS(t,e,r){if(Bt.existsSync(e))for(let n of Bt.readdirSync(e)){let o=Ni.join(e,n);try{if(!Bt.statSync(o).isDirectory())continue}catch{continue}let s=Ni.join(o,"SKILL.md"),i=Ni.join(o,"SKILL.md.disabled"),a=Bt.existsSync(s)?s:null;if(!a&&!Bt.existsSync(i))continue;let c=a?Yj(a):{};t.push({id:`${r}:${n}`,name:n,path:o,active:!!a,scope:r,category:"automation",displayName:Jj(n),displayDescription:Qj(n,c.description),fallbackName:n,fallbackDescription:c.description??"",systemGenerated:Zj(n),version:c.version,description:c.description})}}function Jj(t){return{key:`capability.skill.${t}.name`,fallback:t}}function Qj(t,e){return{key:`capability.skill.${t}.description`,fallback:e??""}}function Zj(t){return t.startsWith("auto-skill-")||t.startsWith("test-skill-")}function e$(t){return t==="active"||t==="stale"||t==="archived"}function vS(t){let r=t.params?.projectId,n=this.getActiveProjectRoot();if(r&&this.projectLocator){let s=this.projectLocator.resolveProjectRoot(r);s&&(n=s)}let o=yS(n);t.id!==void 0&&this.sendResponse(t.id,{skills:o})}function bS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md.disabled"),a=Le.join(s,"SKILL.md");if(ce.existsSync(a)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}if(ce.existsSync(i))try{ce.renameSync(i,a);let c=B(),l=ue(c),d=It(l,r);d.state!=="active"&&(d.state="active",d.staleAt=void 0,d.archivedAt=void 0),he(c,l),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"activate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to activate skill: ${c instanceof Error?c.message:c}`})}else t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found`})}function kS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md"),a=Le.join(s,"SKILL.md.disabled");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}try{ce.renameSync(i,a),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"deactivate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to deactivate skill: ${c instanceof Error?c.message:c}`})}}function RS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=B(),o=ue(n);if(o.records[r]?.pinned){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Skill "${r}" is pinned. Unpin it first.`});return}let s=e?.scope??"project",i;if(s==="global")i=Le.join(sr(),r);else{let a=this.getActiveProjectRoot(),c=a?ir(a):void 0;if(!c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}i=Le.join(c,r)}if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in ${s} scope`});return}try{ce.rmSync(i,{recursive:!0,force:!0}),gt(),$s(o,r),he(n,o),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deleted:r,scope:s}),this.sendNotification("skills.updated",{action:"delete",name:r})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete skill: ${a instanceof Error?a.message:a}`})}}function SS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in project scope`});return}let a=sr(),c=Le.join(a,r);try{ce.mkdirSync(c,{recursive:!0});let l=ce.readdirSync(s);for(let d of l){let p=ce.readFileSync(Le.join(s,d));ce.writeFileSync(Le.join(c,d),p)}e?.keepLocal||ce.rmSync(s,{recursive:!0,force:!0}),gt(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,promoted:r,globalPath:c,removedFromProject:!e?.keepLocal})}catch(l){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}function TS(t){let e=t.params,r=B();if(e?.name){let n=gS(r,e.name);t.id!==void 0&&this.sendResponse(t.id,{name:e.name,stats:n??null})}else{let n=fS(r);t.id!==void 0&&this.sendResponse(t.id,{stats:n})}}function wS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);It(n,e.name),uh(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!0})}function AS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);ph(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!1})}function PS(t){let e=B(),r=this.getActiveProjectRoot(),n=r?Le.join(r,".qlogicagent","skills"):sr(),o=mh(e,n);o.transitioned.length>0&&gt(),t.id!==void 0&&this.sendResponse(t.id,o)}function xS(t){let e=t.params,r=B(),n=ue(r);if(e?.name){let o=n.records[e.name]??null;t.id!==void 0&&this.sendResponse(t.id,{record:o})}else if(e?.state){if(!e$(e.state)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Invalid skill lifecycle state"});return}let o=gh(n,e.state);t.id!==void 0&&this.sendResponse(t.id,{records:o})}else t.id!==void 0&&this.sendResponse(t.id,{records:Object.values(n.records)})}import*as _S from"node:path";import{randomUUID as i$}from"node:crypto";import{join as zu}from"node:path";import{mkdir as t$,readdir as r$}from"node:fs/promises";function n$(t){return t?.pathService??I()}function o$(t,e){return t??e.getActiveProjectRoot()}function CS(t,e){let r=n$(e);return zu(r.getProjectAgentDir(o$(t,r)),"solos")}function Vu(t,e,r){return zu(CS(e,r),t)}function IS(t,e,r){return zu(Vu(t,e,r),"solo-state.json")}async function ES(t,e,r){let n=Vu(t.soloId,e,r);await t$(n,{recursive:!0}),await mr(IS(t.soloId,e,r),t)}async function s$(t,e,r){return Zt(IS(t,e,r))}async function MS(t,e){let r=CS(t,e),n;try{n=await r$(r)}catch{return[]}let o=[];for(let s of n){let i=await s$(s,t,e);i&&o.push(i)}return o}async function Xu(t,e,r){let{rm:n}=await import("node:fs/promises"),o=Vu(t,e,r);try{return await n(o,{recursive:!0,force:!0}),!0}catch{return!1}}var Li=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let r={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(n=>({agentId:n.agentId,memberId:n.memberId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,state:n.state,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,turns:n.turns})),evaluation:e.evaluation,createdAt:e.createdAt};ES(r,e.cwd).catch(()=>{})}async restoreFromDisk(e){let r=await MS(e);for(let n of r)this.sessions.has(n.soloId)||this.sessions.set(n.soloId,{soloId:n.soloId,state:n.state,task:n.task,cwd:n.cwd,gitRoot:n.gitRoot,agents:n.agents.map(o=>({...o,turns:o.turns??[]})),evaluation:n.evaluation,createdAt:n.createdAt});return r.length}async deleteSolo(e){return this.sessions.delete(e),Xu(e)}async start(e){let{task:r,agents:n,cwd:o,sharedConfig:s}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await wo(o);if(!i)throw new Error("Solo Mode requires a git repository");let a=r;if(s){let u=[];s.rules?.length&&u.push(`<rules>
546
+ `)})}return this.workflowController}function rr(t){return t.params??{}}function nr(t,e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:e})}function Ij(t){return{id:t.id,name:t.name,active:t.active,concurrency:t.concurrency,rev:t.rev,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.trigger!==void 0?{trigger:t.trigger}:{},def:t.def}}function Ou(t,e){this.sendNotification(t,{workflow:Ij(e)})}function ju(t,e){if(t.status==="failed"){this.sendNotification("workflow.runFailed",{workflowId:t.workflowId,triggerType:e,error:"Workflow run failed",outcome:t});return}this.sendNotification("workflow.runCompleted",{workflowId:t.workflowId,status:t.status,triggerType:e,outcome:t})}function Ej(t){return t instanceof Error?t.message:String(t)}async function sR(t){let e=rr(t);if(!e.def)return nr.call(this,t,"workflow.create requires `def`");let r=Ht.call(this),n=String(e.id??`wf_${oR().slice(0,8)}`),o=await r.create({id:n,name:String(e.name??n),def:e.def,concurrency:e.concurrency,active:e.active===!0});o.active&&await this.workflowScheduler?.refresh(o.id),Ou.call(this,"workflow.created",o),t.id!==void 0&&this.sendResponse(t.id,o)}async function iR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.get requires `id`");let n=await Ht.call(this).get(String(e.id));t.id!==void 0&&this.sendResponse(t.id,n)}async function aR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.describe requires `id`");let n=await Ht.call(this).describe(String(e.id));t.id!==void 0&&this.sendResponse(t.id,{rendered:n})}async function cR(t){let e=rr(t);if(!e.id||!e.patch)return nr.call(this,t,"workflow.patch requires `id` and `patch`");let r=Ht.call(this),n={patch:e.patch,baseRev:e.baseRev,scope:e.scope},o=await r.patch(String(e.id),n);await this.workflowScheduler?.refresh(String(e.id)),o.ok&&Ou.call(this,"workflow.updated",await r.get(String(e.id))),t.id!==void 0&&this.sendResponse(t.id,o)}async function lR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.run requires `id`");let r=Ht.call(this),n=e.trigger??{type:"manual"},o=String(e.id);this.sendNotification("workflow.runStarted",{workflowId:o,triggerType:n.type});let s;try{s=await r.run(o,n),ju.call(this,s,n.type)}catch(i){throw this.sendNotification("workflow.runFailed",{workflowId:o,triggerType:n.type,error:Ej(i)}),i}t.id!==void 0&&this.sendResponse(t.id,s)}async function dR(t){let e=rr(t);if(!e.id||typeof e.active!="boolean")return nr.call(this,t,"workflow.setActive requires `id` and boolean `active`");let n=await Ht.call(this).setActive(String(e.id),e.active);await this.workflowScheduler?.refresh(n.id),Ou.call(this,"workflow.updated",n),t.id!==void 0&&this.sendResponse(t.id,n)}async function uR(t){Ht.call(this);let r=await this.workflowStore.list();t.id!==void 0&&this.sendResponse(t.id,{workflows:r})}async function pR(t){let e=rr(t);if(!e.id)return nr.call(this,t,"workflow.delete requires `id`");Ht.call(this),await this.workflowStore.delete(String(e.id)),await this.workflowScheduler?.refresh(String(e.id)),this.sendNotification("workflow.deleted",{workflowId:String(e.id)}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function mR(t){let e=rr(t);if(!e.channel||typeof e.text!="string")return nr.call(this,t,"workflow.onImMessage requires `channel` and string `text`");Ht.call(this);let r=await this.workflowScheduler.onImMessage(String(e.channel),e.text,e.payload);for(let n of r)ju.call(this,n,"im-message");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}async function gR(t){let e=rr(t);if(!e.path)return nr.call(this,t,"workflow.onWebhook requires `path`");Ht.call(this);let r=await this.workflowScheduler.onWebhook(String(e.path),e.payload);for(let n of r)ju.call(this,n,"webhook");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}import*as Ce from"node:fs";import*as me from"node:path";G();import*as Hr from"node:fs";import*as $u from"node:path";G();import*as xe from"node:fs";import*as Ao from"node:path";function _i(t){let e=X(),r=De(t);xe.existsSync(r)||xe.mkdirSync(r,{recursive:!0});let n=Ao.join(e,"INSTRUCTIONS.md"),o=Ao.join(r,"INSTRUCTIONS.md");if(xe.existsSync(n)&&!xe.existsSync(o))try{xe.copyFileSync(n,o)}catch{}let s=sm(),i=Xr(t);if(xe.existsSync(s)&&!xe.existsSync(i))try{xe.mkdirSync(i,{recursive:!0});for(let a of xe.readdirSync(s)){if(!a.endsWith(".md"))continue;let c=Ao.join(s,a),l=Ao.join(i,a);xe.statSync(c).isFile()&&xe.copyFileSync(c,l)}}catch{}}var Mj=["creating","running","completed","cancelled"];function fR(t){return typeof t=="string"&&Mj.includes(t)}function hR(t,e){let r=I(),n=e.workspaceDir||$u.join(r.getUserAgentHome(),"workspaces",e.name);if(e.groupId){let l=Ns(e.groupId);if(l)return{project:l,isAgentTeamProject:l.type==="solo"||l.type==="product",deduplicated:!0}}let s=z().find(l=>l.name===e.name);_j(n);let i=Ds({name:e.name,workspaceDir:n,type:e.type??"personal",groupId:e.groupId,skipAutoSwitch:e.type==="solo"||e.type==="product"}),a=i.type==="solo"||i.type==="product";a||(Ct(i.id),t.setActiveWorkdir(i.workspaceDir)),_i(i.workspaceDir);let c=t.projectMemoryStoreFactory.create(i.workspaceDir);return c.ensureInitialized(),a||(t.memdir=c,t.mediaPersistence.setProjectDir(i.workspaceDir)),Dj(i),{project:i,nameDuplicate:s,isAgentTeamProject:a}}function _j(t){Hr.existsSync(t)||Hr.mkdirSync(t,{recursive:!0})}function Dj(t){let e=I();if(t.type!=="solo"&&t.type!=="product")return;let r=$u.join(e.getProjectAgentDir(t.workspaceDir),t.type==="solo"?"solo-state.json":"product-state.json");if(Hr.existsSync(r))return;let n=t.type==="solo"?{agents:[],status:"idle",createdAt:new Date().toISOString()}:{tasks:[],instances:[],status:"idle",createdAt:new Date().toISOString()};Hr.writeFileSync(r,JSON.stringify(n,null,2))}function yR(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let r;try{r=hR(this,{name:e.name,workspaceDir:e.workspaceDir,type:e.type,groupId:e.groupId})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:a instanceof Error?a.message:`Cannot create workspace directory: ${e.workspaceDir??e.name}`});return}let{project:n,nameDuplicate:o,isAgentTeamProject:s,deduplicated:i}=r;if(i){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:n,deduplicated:!0});return}if(this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type}),s||this.sendNotification("project.switched",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),t.id!==void 0){let a={ok:!0,project:n};o&&(a.warning=`A project named "${o.name}" already exists at ${o.workspaceDir}. Consider renaming one of them to avoid ambiguity.`),this.sendResponse(t.id,a)}}function vR(t){let e=z();t.id!==void 0&&this.sendResponse(t.id,{projects:e})}function bR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Te(e.projectId),n=ed(e.projectId);if(!n.deleted){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}let o=!1,s;if(r?.workspaceDir){let i=me.join(X(),"workspaces"),a=me.resolve(r.workspaceDir);if(a.startsWith(me.resolve(i)+me.sep)){try{this.mediaPersistence?.releaseProjectDir?.(a)}catch{}for(let c=0;c<3;c++)try{Ce.rmSync(a,{recursive:!0,force:!0}),o=!0;break}catch(l){if(c<2&&(l.code==="EBUSY"||l.code==="EPERM"||l.code==="ENOTEMPTY")){let d=Date.now();for(;Date.now()-d<200;);}else{s=l.message??String(l);break}}}else s="Project directory is outside the managed workspace root and was not deleted automatically."}this.sendNotification("project.deleted",{id:e.projectId}),n.switchedTo&&(this.setActiveWorkdir(n.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:n.switchedTo,dirDeleted:o,dirDeleteError:s})}function kR(t){let e=z(),r=me.join(X(),"workspaces"),n=me.resolve(r)+me.sep,o=0,s=[];for(let a of e)if(a.type!=="default"){if(ed(a.id),o++,a.workspaceDir){let c=me.resolve(a.workspaceDir);try{this.mediaPersistence?.releaseProjectDir?.(c)}catch{}for(let l=0;l<3;l++)try{Ce.existsSync(c)&&Ce.rmSync(c,{recursive:!0,force:!0});break}catch(d){if(l<2&&(d.code==="EBUSY"||d.code==="EPERM"||d.code==="ENOTEMPTY")){let p=Date.now();for(;Date.now()-p<300;);}else{s.push(`${a.name}: ${d.message??d}`);break}}}this.sendNotification("project.deleted",{id:a.id})}if(Ce.existsSync(r)){let a=z().find(d=>d.type==="default"),c=new Set;a?.workspaceDir&&c.add(me.resolve(a.workspaceDir));let l=d=>{try{let p=Ce.readdirSync(d,{withFileTypes:!0});for(let u of p){if(!u.isDirectory())continue;let m=me.join(d,u.name);if(!c.has(me.resolve(m))){if(u.name==="groups"){l(m);try{Ce.readdirSync(m).length===0&&Ce.rmdirSync(m)}catch{}continue}try{Ce.rmSync(m,{recursive:!0,force:!0})}catch(f){s.push(`orphan:${u.name}: ${f.message??f}`)}}}}catch{}};l(r)}let i=z().find(a=>a.type==="default");i&&(this.setActiveWorkdir(i.workspaceDir),this.sendNotification("project.switched",{id:i.id,name:i.name,workspaceDir:i.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o,dirErrors:s.length?s:void 0})}function RR(t){let e=t.params;if(!e?.projectId||!e?.newName){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let r=Zf(e.projectId,e.newName);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}let n=me.join(X(),"workspaces"),o=me.resolve(r.workspaceDir);if(o.startsWith(me.resolve(n)+me.sep)){let s=me.join(n,e.newName);if(Ce.existsSync(o)&&!Ce.existsSync(s))try{Ce.renameSync(o,s),eh(e.projectId,s),r.workspaceDir=s,this.getActiveProjectRoot()===o&&this.setActiveWorkdir(s)}catch{}}this.sendNotification("project.renamed",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function SR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=th(e.projectId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:e.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:r.switchedTo})}function TR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=rh(e.projectId);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function wR(t){let e=t.params;if(!e?.groupId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: groupId"});return}let r=nh(e.groupId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:r.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:r.projectId})}function AR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"projectId is required"});return}let r={};if("planStatus"in e){if(e.planStatus!==void 0&&!fR(e.planStatus)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Invalid planStatus: ${e.planStatus}`});return}r.planStatus=e.planStatus}"planAgents"in e&&(r.planAgents=e.planAgents),"planWinnerId"in e&&(r.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(r.leaderSessionId=e.leaderSessionId);let n=Jf(e.projectId,r);t.id!==void 0&&this.sendResponse(t.id,{ok:n})}import{randomUUID as Fu}from"node:crypto";import*as Ve from"node:fs";import*as Br from"node:path";var fr=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[r,n]of this._modelUsage)e[r]={...n};return e}addUsage(e,r){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(r);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(r,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,r,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||this._modelUsage.set(e,s),s.mediaCalls+=1,r){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break;case"per_token":s.outputTokens+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[r,n]of Object.entries(e.modelUsage))this._modelUsage.set(r,{...n});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as PR from"node:fs";import*as Uu from"node:path";var hr=class{getSessionsRoot(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return I().getProjectSessionsRoot(r.workspaceDir)}getProjectWorkspaceDir(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return r.workspaceDir}getSessionDir(e,r){return Uu.join(this.getSessionsRoot(e),r)}resolveWorkspaceDir(e,r){if(r)return this.getProjectWorkspaceDir(r);let n=z();for(let o of n){let s=I().getProjectSessionsRoot(o.workspaceDir),i=Uu.join(s,e);try{if(PR.existsSync(i))return o.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=ne();if(e)return e.workspaceDir;let r=z();if(r.length>0)return r[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=ne();if(e)return e.id;let r=z();if(r.length>0)return r[0].id;throw new Error("No active project available")}};import{randomUUID as xR}from"node:crypto";async function CR(t,e){let r=new Date(t.lastActiveAt).getTime();if(Date.now()-r<Yp)return{split:!1,activeSessionId:t.sessionId};let s=xR(),i=new Date().toISOString();await Fe(t.sessionId,{sealedAt:i},e);let a=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${t.taskSummary}`:void 0;return await Fe(s,{sessionId:s,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:t.sessionId}}async function IR(t,e){if(t.type!=="group")return{split:!1,activeSessionId:t.sessionId};if(t.turnCount<Jp)return{split:!1,activeSessionId:t.sessionId};let r=xR(),n=new Date().toISOString();await Fe(t.sessionId,{sealedAt:n},e);let o=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${t.taskSummary}`:void 0;return await Fe(r,{sessionId:r,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:o},e),{split:!0,activeSessionId:r,sealedSessionId:t.sessionId}}G();import*as ER from"node:fs";import*as MR from"node:path";var Di=class{constructor(e=new hr,r=I()){this.locator=e;this.pathService=r}locator;pathService;getActiveProjectId(){return this.locator.getActiveProjectId()}getProjectWorkspaceDir(e){return this.locator.getProjectWorkspaceDir(e)}resolveWorkspaceDir(e,r){return this.locator.resolveWorkspaceDir(e,r)}async listThreads(e,r){let n=r??this.getActiveProjectId(),o=this.getProjectWorkspaceDir(n);return(await Rt(e,o)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:i.createdAt,lastActiveAt:i.lastActiveAt}))}resolveSessionWorkspaceDir(e,r,n){if(n)return this.resolveWorkspaceDir(r,n);let o=e.getActiveProjectRoot();if(o){let s=MR.join(this.pathService.getProjectSessionsRoot(o),Nj(r));try{if(ER.existsSync(s))return o}catch{}}return this.resolveWorkspaceDir(r)}};function Nj(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}var Lj=new hr,tt=new Di(Lj);function yt(t,e="Unknown error"){return t instanceof Error?t.message:e}function Rn(t,e,r){return tt.resolveSessionWorkspaceDir(t,e,r)}function _R(t){let e=t.params,r=e?.id??Fu();this.log(`[thread.create] id=${r} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=r,this.sessionState=new fr(r),this.sessionTaskDomain=void 0,this.memoryPrefetchState=kt(),this.enableIdleDream(),t.id!==void 0&&this.sendResponse(t.id,{id:r,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function DR(t){let e=t.params,r=e?.limit??20;try{let n=await tt.listThreads(r,e?.projectId);t.id!==void 0&&this.sendResponse(t.id,{threads:n})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list threads: ${yt(n)}`})}}async function NR(t){let e=t.params,r=e?.sessionId??Fu();try{let n=e?.projectId??tt.getActiveProjectId(),o=tt.getProjectWorkspaceDir(n);await Fe(r,{sessionId:r,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:n},o),t.id!==void 0&&this.sendResponse(t.id,{sessionId:r,title:e?.title})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to create session: ${yt(n)}`})}}async function LR(t){let e=t.params;if(t.id===void 0)return;let r=e?.platform??"desktop",n=e?.chatId,o=e?.chatType,s=e?.userId??"local";try{if(r==="desktop"&&n){let d=e?.projectId??tt.getActiveProjectId(),p=tt.getProjectWorkspaceDir(d),m=(await Rt(500,p)).find(f=>f.sessionId===n);if(m){this.sendResponse(t.id,{sessionId:n,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await Fe(n,{sessionId:n,type:"personal",ownerId:s,projectId:d},p),this.sendResponse(t.id,{sessionId:n,type:"personal",ownerId:s,projectId:d});return}if(o==="group"&&n&&r){let d=`group:${r}:${n}`,p=z();for(let u of p){if(!u.workspaceDir)continue;let f=(await Rt(500,u.workspaceDir)).find(g=>g.groupKey===d&&!g.sealedAt);if(f){let g=Vt(f.sessionId,u.workspaceDir);if(g){let h=await CR(g,u.workspaceDir);if(h.split){this.sendResponse(t.id,{sessionId:h.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id,previousSessionId:h.sealedSessionId});return}}this.sendResponse(t.id,{sessionId:f.sessionId,title:f.title,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id});return}}}let i=Fu(),a=tt.getActiveProjectId(),c=tt.getProjectWorkspaceDir(a),l=o==="group"?`group:${r}:${n}`:void 0;await Fe(i,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a},c),this.sendResponse(t.id,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resolve session: ${yt(i)}`})}}async function OR(t){let e=t.params,r=e?.limit??50;try{let n;if(e?.projectId){let s=Te(e.projectId);if(!s){t.id!==void 0&&this.sendResponse(t.id,{sessions:[]});return}let i=s.workspaceDir;n=await Rt(r*2,i),n=n.filter(a=>a.projectId===e.projectId);for(let a of n)a.projectId=e.projectId}else{let s=z(),i=new Set,a=[];for(let c of s){if(!c.workspaceDir)continue;let l=await Rt(r,c.workspaceDir);for(let d of l)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((c,l)=>c.lastActiveAt>l.lastActiveAt?-1:c.lastActiveAt<l.lastActiveAt?1:0),n=a}e?.archived===!0?n=n.filter(s=>s.archivedAt!=null):e?.archived===!1&&(n=n.filter(s=>s.archivedAt==null));let o=n.slice(0,r).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type??"personal",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}));t.id!==void 0&&this.sendResponse(t.id,{sessions:o})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list sessions: ${yt(n)}`})}}async function jR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId),o=(await Rt(500,r)).find(s=>s.sessionId===e.sessionId);t.id!==void 0&&this.sendResponse(t.id,{session:o?{sessionId:o.sessionId,title:o.title,type:o.type,lastActiveAt:o.lastActiveAt,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:o.projectId}:null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get session: ${yt(r)}`})}}async function $R(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId),n=await Ec(e.sessionId,r);if(!n){t.id!==void 0&&this.sendResponse(t.id,{messages:[],total:0});return}let o=n.messages,s=e.limit&&e.limit>0?e.limit:o.length,i=o.slice(-s);t.id!==void 0&&this.sendResponse(t.id,{messages:i,total:o.length})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get messages: ${yt(r)}`})}}async function UR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId),n=await Fe(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},r);n&&this.sendNotification("session.info",{sessionId:e.sessionId,title:n.title,pinnedAt:n.pinnedAt??null,archivedAt:n.archivedAt??null,projectId:e.projectId||void 0}),t.id!==void 0&&this.sendResponse(t.id,{ok:n!==null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to update session: ${yt(r)}`})}}async function FR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId);await Mc(e.sessionId,r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete session: ${yt(r)}`})}}async function HR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let r=tt.getProjectWorkspaceDir(e.projectId),n=(await Rt(1e4,r)).filter(s=>s.projectId===e.projectId),o=0;for(let s of n)await Mc(s.sessionId,r),o++;t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete all sessions: ${yt(r)}`})}}async function BR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=Rn(this,e.sessionId,e.projectId);await Fe(e.sessionId,{archivedAt:new Date().toISOString()},r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to archive session: ${yt(r)}`})}}async function qR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"sessionId is required"});return}try{let n=Rn(this,r,e?.projectId),o=await Ec(r,n);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Session not found: ${r}`});return}o.messages&&o.messages.length>0&&this.sessionHistory.saveResumedSession(r,o.messages),t.id!==void 0&&this.sendResponse(t.id,{metadata:o.metadata,messages:o.messages})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resume session: ${yt(n)}`})}}function WR(t){let e=this.currentSessionId||"default",r=this.sessionState?.createSnapshot(),n,o=this.getActiveProjectRoot();o&&(n=Br.join(Jo(o),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:n,agentHome:X(),settings:Ue()},usage:r?{turnCount:r.turnCount,inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens}:void 0};t.id!==void 0&&this.sendResponse(t.id,s)}function GR(t){let e=t.params,r=null;if(e?.projectId)r=Te(e.projectId);else if(e?.projectName){let s=z(),i=e.projectName.toLowerCase();if(r=s.find(a=>a.name.toLowerCase()===i)??null,r||(r=s.find(a=>a.name.toLowerCase().includes(i))??null),!r){let a=s.map(c=>c.name).slice(0,10);t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!r||r.status!=="active"){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let n=e.workspaceDir??r.workspaceDir;if(!Ve.existsSync(n)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Workspace directory does not exist: ${n}`});return}let o=Ct(r.id);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(o.workspaceDir),this.sendNotification("project.switched",{id:o.id,name:o.name,workspaceDir:o.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:o})}function KR(t){let e=ne(),r=z();t.id!==void 0&&this.sendResponse(t.id,{sessionId:this.currentSessionId,activeProject:e,projects:r})}async function zR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,{ok:!1});return}let n=z();for(let o of n)try{let s=tt.getProjectWorkspaceDir(o.id),i=await Vt(r,s);if(i&&i.projectId===o.id){Ct(o.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} for session ${r}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}catch{}if(e?.projectName){let o=n.find(s=>s.name===e.projectName);if(o){let s=tt.getProjectWorkspaceDir(o.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} by name "${e.projectName}"`)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}t.id!==void 0&&this.sendResponse(t.id,{ok:!1})}async function VR(t){let e=t.params,{sessionId:r,fromProjectId:n,toProjectId:o}=e??{};if(!r||!n||!o){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(n===o){t.id!==void 0&&this.sendResponse(t.id,{ok:!0});return}let s=Te(n),i=Te(o);if(!s||!i){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"Source or target project not found");return}let a=Br.join(tt.getProjectWorkspaceDir(n),".qlogicagent","sessions",r),c=Br.join(tt.getProjectWorkspaceDir(o),".qlogicagent","sessions",r);if(!Ve.existsSync(a)){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,`Session ${r} not found in project ${n}`);return}try{Ve.mkdirSync(Br.dirname(c),{recursive:!0}),Ve.cpSync(a,c,{recursive:!0});let l=Br.join(c,"metadata.json");if(Ve.existsSync(l)){let d=JSON.parse(Ve.readFileSync(l,"utf-8"));d.projectId=o,Ve.writeFileSync(l,JSON.stringify(d,null,2))}Ve.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:r,projectId:o}),this.log(`[session.moveToProject] moved ${r}: ${n} \u2192 ${o}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o})}catch(l){let d=yt(l);this.log(`[session.moveToProject] error: ${d}`),t.id!==void 0&&this.sendError(t.id,y.INTERNAL_ERROR,`Move failed: ${d}`)}}He();function Oj(t){return t.length<=8?"****":`${t.slice(0,3)}***${t.slice(-4)}`}function Ne(t,e,r,n=y.INTERNAL_ERROR){if(e.id!==void 0){if(typeof t.sendError=="function"){t.sendError(e.id,n,r);return}t.sendResponse(e.id,void 0,{code:n,message:r})}}function Hu(t,e){Ne(t,e,ns)}function jj(t){let e={};for(let r of t)for(let n of r.purposes)e[n]??=[],e[n].push(r);return e}async function $j(){let t=D(),e=await $n(t);return t.save(),e}async function XR(t){try{return await $j(),!0}catch(e){if(t)throw e;return!1}}function Bu(t=D()){try{return Tm()}catch{return t.getKnownProviderDef(Y)?.baseUrl??"https://www.qlogicagent.com"}}function qu(t){return t.id===Y?Y:t.group?.trim()||t.id}function Uj(t){return t.id===qu(t)}function YR(t){let e=qu(t);return Oc({...t,id:e})}function Fj(t){return{volcengine:"\u5E38\u89C4 Ark API Key","volcengine-plan":"\u8BA2\u9605 / Plan \u901A\u9053",qwen:"\u5E38\u89C4 DashScope API Key","qwen-coding":"Coding Plan \u901A\u9053",zhipu:"Anthropic \u901A\u9053","zhipu-openai":"OpenAI \u517C\u5BB9\u901A\u9053","zhipu-coding":"Coding \u901A\u9053"}[t.id]??Oc(t)}function Hj(t){return t.authType==="none"?!1:t.apiKeyEnvVars===void 0||t.apiKeyEnvVars.length>0}function Bj(t){return{id:t.id,displayName:Fj(t),baseUrl:jn(t)??"",modelCount:t.models?.length??0}}function qj(t){let e=new Map;for(let r of t){if(!Hj(r))continue;let n=qu(r);if(n===Y)continue;let o=r.models?.length??0,s=Bj(r),i=e.get(n);if(!i){e.set(n,{id:n,displayName:YR(r),baseUrl:jn(r)??"",modelCount:o,variants:[s]});continue}i.modelCount+=o,i.variants??=[],i.variants.some(a=>a.id===s.id)||i.variants.push(s),Uj(r)&&(i.displayName=YR(r),i.baseUrl=jn(r)??i.baseUrl)}return Array.from(e.values()).map(r=>({...r,variants:r.variants&&r.variants.length>1?r.variants:void 0}))}async function JR(t){let e=D(),r=e.getKeyForProvider(Y);if(!r){if(t)throw new Error("LLMRouter API Key is required to fetch available models.");return!1}let n=e.getProviderStatus(Y)?.baseUrl??Bu(e);try{if((await jc(e,{baseUrl:n,apiKey:r})).length===0){if(t)throw new Error("LLMRouter did not return any available models for this API Key.");return!1}return e.save(),!0}catch(o){if(t)throw o;return!1}}async function QR(t=!1){let e=D();if(!!e.getProviderStatus(Y)?.keys.length)return await JR(!1)?!0:XR(t);let o=e.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId).some(s=>s!=="deepseek"&&s!==Y);return!t&&!o?!1:XR(t)}async function ZR(t,e,r){let n;if(t===Y)n=Nc(r);else{let o=D().getKnownProviderDef(t)?.transport,s=r.replace(/\/$/,"");o==="anthropic-messages"&&(s=s.replace(/\/anthropic$/,"")),n=`${s}/models`}try{let o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)});if(o.ok)return{valid:!0,status:o.status};let s=await o.text().catch(()=>"");return{valid:!1,status:o.status,error:s.slice(0,500)}}catch(o){return{valid:!1,status:0,error:o instanceof Error?o.message:String(o)}}}async function Wj(t,e,r){let n=await ZR(t,e,r);if(!n.valid){let o=n.error?`: ${n.error}`:"";throw new Error(`API Key validation failed (${n.status})${o}`)}}async function eS(t){try{let e=D(),r=["deepseek",Y].map(s=>e.getKnownProviderDef(s)).filter(s=>!!s).map(s=>({id:s.id,displayName:s.name,baseUrl:s.baseUrl,modelCount:s.models?.length??0})),n=await Lc().catch(()=>[]),o=qj(n);o.unshift({id:Y,displayName:Dc,baseUrl:Bu(e),modelCount:n.reduce((s,i)=>s+(i.models?.length??0),0)});for(let s of r.reverse()){let i=o.findIndex(a=>a.id===s.id);if(i>=0){s.id!==Y&&o.splice(i,1,s);continue}o.unshift(s)}t.id!==void 0&&this.sendResponse(t.id,{providers:o})}catch(e){Ne(this,t,e instanceof Error?e.message:String(e))}}async function tS(t){let e=t.params;if(!e?.providerId||!e?.key){Ne(this,t,"Required: providerId (string), key (string)",y.INVALID_PARAMS);return}let{providerId:r,key:n,label:o}=e,s=D(),i,a=!1;try{let c=await pS(r);if(!c){Ne(this,t,`Unknown provider: ${r}`,y.INVALID_PARAMS);return}let l=s.getProviderStatus(r);if(l?.keys.some(d=>d.key===n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}if(a=!l,s.addProvider(r,{baseUrl:c}),i=s.addKey(r,n,{label:o}),r===Y){if((await jc(s,{baseUrl:c,apiKey:n})).length===0)throw new Error("LLMRouter did not return any available models for this API Key.")}else await Wj(r,n,c);for(let d of On)if(!s.getBinding(d)){let p=s.listModels({purpose:d,provider:r,enabledOnly:!0});p.length===0&&(p=s.listModels({purpose:d,provider:r}),p[0]&&s.enableModel(p[0].id)),p.length>0&&s.setBinding(d,p[0].id)}s.setKeyHealth(i,"healthy"),s.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,keyId:i,providerId:r})}catch(c){i&&(s.removeKey(i),a&&s.removeProvider(r));let l=c instanceof Error?c.message:ns;Ne(this,t,l)}}function rS(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D();r.removeKey(e.keyId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function nS(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D().getKeyById(e.keyId);if(!r){Ne(this,t,"API Key not found",y.INVALID_PARAMS);return}t.id!==void 0&&this.sendResponse(t.id,{key:r})}function oS(t){let e=t.params;if(!e?.keyId||typeof e.enabled!="boolean"){Ne(this,t,"Required: keyId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();r.updateKey(e.keyId,{enabled:e.enabled}),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function sS(t){let e=t.params;if(!e?.modelId||typeof e.enabled!="boolean"){Ne(this,t,"Required: modelId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();e.enabled?r.enableModel(e.modelId):r.disableModel(e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function iS(t){let e=t.params;try{await QR(!1);let r=D(),n=new Set(r.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),o=r.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>r.hasConfiguredKeyForProviderVariant(s.provider));t.id!==void 0&&this.sendResponse(t.id,{models:o,grouped:jj(o),configuredProviderIds:[...n]})}catch{Hu(this,t)}}function aS(t){let e=t.params;if(!e?.purpose||!e?.modelId){Ne(this,t,"Required: purpose (string), modelId (string)",y.INVALID_PARAMS);return}try{let r=D();r.setBinding(e.purpose,e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){Ne(this,t,r instanceof Error?r.message:String(r),y.INVALID_PARAMS)}}function cS(t){let e=t.params;if(!e?.purpose){Ne(this,t,"Required: purpose (string)",y.INVALID_PARAMS);return}let r=D(),n=r.getBinding(e.purpose);t.id!==void 0&&this.sendResponse(t.id,{model:n?{id:n.id,provider:n.provider,model:n.model,displayName:n.displayName,purposes:n.purposes,enabled:n.enabled}:null,available:r.isAvailable(e.purpose)})}async function lS(t){try{await QR(!1);let e=D(),r=e.getAllProviderStatus().map(s=>({providerId:s.providerId,displayName:s.providerId===Y?Dc:s.providerId,baseUrl:s.baseUrl,keyCount:s.keys.length,healthyKeys:s.keys.filter(i=>i.healthStatus==="healthy"&&i.enabled).length,totalKeys:s.keys.length,keys:s.keys.map(i=>({id:i.id,label:i.label,maskedKey:Oj(i.key),enabled:i.enabled,health:i.healthStatus}))})),n=e.getAllBindings(),o={};for(let s of On){let i=n[s];o[s]={bound:!!i,modelId:i?.id,modelName:i?.displayName,available:e.isAvailable(s)}}t.id!==void 0&&this.sendResponse(t.id,{providers:r,purposes:o})}catch{Hu(this,t)}}async function dS(t){try{let e=D();e.load(),await JR(!1)||await $n(e),e.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,catalogRefreshed:!0})}catch{Hu(this,t)}}async function uS(t){let e=t.params;if(!e?.providerId||!e?.apiKey){Ne(this,t,"providerId and apiKey required",y.INVALID_PARAMS);return}try{let r=e.baseUrl||await pS(e.providerId);if(!r){Ne(this,t,`Unknown provider: ${e.providerId}`,y.INVALID_PARAMS);return}let n=await ZR(e.providerId,e.apiKey,r);t.id!==void 0&&this.sendResponse(t.id,n)}catch(r){let n=r instanceof Error?r.message:String(r);t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:0,error:n})}}async function pS(t){if(t===Y)return Bu();let e=D().getKnownProviderDef(t);if(e?.baseUrl)return e.baseUrl;let r=await Am(t);return r?jn(r):void 0}G();import*as ce from"node:fs";import*as Le from"node:path";import{join as Gj}from"node:path";import{readFileSync as Kj,writeFileSync as zj,mkdirSync as Vj}from"node:fs";var qr=null,Wu=!1;function mS(t){return Gj(t,"skill-stats.json")}function Gu(t){if(qr)return qr;try{qr=JSON.parse(Kj(mS(t),"utf8"))}catch{qr={}}return qr}function Xj(t){if(!(!Wu||!qr))try{Vj(t,{recursive:!0}),zj(mS(t),JSON.stringify(qr,null,2),"utf8"),Wu=!1}catch{}}function Ku(t,e,r){let n=Gu(t);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),r?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Wu=!0,Xj(t)}function gS(t,e){return Gu(t)[e]}function fS(t){return Gu(t)}import*as Bt from"node:fs";import*as Ni from"node:path";function Yj(t){try{let e=Bt.readFileSync(t,"utf8"),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),n=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:r?.[1],description:n?.[1]?.trim()}}catch{return{}}}function yS(t){let e=I(),r=[],n=t?e.getProjectSkillsDir(t):void 0,o=e.getUserSkillsDir();return n&&hS(r,n,"project"),hS(r,o,"global"),r}function hS(t,e,r){if(Bt.existsSync(e))for(let n of Bt.readdirSync(e)){let o=Ni.join(e,n);try{if(!Bt.statSync(o).isDirectory())continue}catch{continue}let s=Ni.join(o,"SKILL.md"),i=Ni.join(o,"SKILL.md.disabled"),a=Bt.existsSync(s)?s:null;if(!a&&!Bt.existsSync(i))continue;let c=a?Yj(a):{};t.push({id:`${r}:${n}`,name:n,path:o,active:!!a,scope:r,category:"automation",displayName:Jj(n),displayDescription:Qj(n,c.description),fallbackName:n,fallbackDescription:c.description??"",systemGenerated:Zj(n),version:c.version,description:c.description})}}function Jj(t){return{key:`capability.skill.${t}.name`,fallback:t}}function Qj(t,e){return{key:`capability.skill.${t}.description`,fallback:e??""}}function Zj(t){return t.startsWith("auto-skill-")||t.startsWith("test-skill-")}function e$(t){return t==="active"||t==="stale"||t==="archived"}function vS(t){let r=t.params?.projectId,n=this.getActiveProjectRoot();if(r&&this.projectLocator){let s=this.projectLocator.resolveProjectRoot(r);s&&(n=s)}let o=yS(n);t.id!==void 0&&this.sendResponse(t.id,{skills:o})}function bS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md.disabled"),a=Le.join(s,"SKILL.md");if(ce.existsSync(a)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}if(ce.existsSync(i))try{ce.renameSync(i,a);let c=B(),l=ue(c),d=It(l,r);d.state!=="active"&&(d.state="active",d.staleAt=void 0,d.archivedAt=void 0),he(c,l),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"activate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to activate skill: ${c instanceof Error?c.message:c}`})}else t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found`})}function kS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md"),a=Le.join(s,"SKILL.md.disabled");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}try{ce.renameSync(i,a),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"deactivate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to deactivate skill: ${c instanceof Error?c.message:c}`})}}function RS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=B(),o=ue(n);if(o.records[r]?.pinned){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Skill "${r}" is pinned. Unpin it first.`});return}let s=e?.scope??"project",i;if(s==="global")i=Le.join(sr(),r);else{let a=this.getActiveProjectRoot(),c=a?ir(a):void 0;if(!c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}i=Le.join(c,r)}if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in ${s} scope`});return}try{ce.rmSync(i,{recursive:!0,force:!0}),gt(),$s(o,r),he(n,o),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deleted:r,scope:s}),this.sendNotification("skills.updated",{action:"delete",name:r})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete skill: ${a instanceof Error?a.message:a}`})}}function SS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in project scope`});return}let a=sr(),c=Le.join(a,r);try{ce.mkdirSync(c,{recursive:!0});let l=ce.readdirSync(s);for(let d of l){let p=ce.readFileSync(Le.join(s,d));ce.writeFileSync(Le.join(c,d),p)}e?.keepLocal||ce.rmSync(s,{recursive:!0,force:!0}),gt(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,promoted:r,globalPath:c,removedFromProject:!e?.keepLocal})}catch(l){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}function TS(t){let e=t.params,r=B();if(e?.name){let n=gS(r,e.name);t.id!==void 0&&this.sendResponse(t.id,{name:e.name,stats:n??null})}else{let n=fS(r);t.id!==void 0&&this.sendResponse(t.id,{stats:n})}}function wS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);It(n,e.name),uh(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!0})}function AS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);ph(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!1})}function PS(t){let e=B(),r=this.getActiveProjectRoot(),n=r?Le.join(r,".qlogicagent","skills"):sr(),o=mh(e,n);o.transitioned.length>0&&gt(),t.id!==void 0&&this.sendResponse(t.id,o)}function xS(t){let e=t.params,r=B(),n=ue(r);if(e?.name){let o=n.records[e.name]??null;t.id!==void 0&&this.sendResponse(t.id,{record:o})}else if(e?.state){if(!e$(e.state)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Invalid skill lifecycle state"});return}let o=gh(n,e.state);t.id!==void 0&&this.sendResponse(t.id,{records:o})}else t.id!==void 0&&this.sendResponse(t.id,{records:Object.values(n.records)})}import*as _S from"node:path";import{randomUUID as i$}from"node:crypto";import{join as zu}from"node:path";import{mkdir as t$,readdir as r$}from"node:fs/promises";function n$(t){return t?.pathService??I()}function o$(t,e){return t??e.getActiveProjectRoot()}function CS(t,e){let r=n$(e);return zu(r.getProjectAgentDir(o$(t,r)),"solos")}function Vu(t,e,r){return zu(CS(e,r),t)}function IS(t,e,r){return zu(Vu(t,e,r),"solo-state.json")}async function ES(t,e,r){let n=Vu(t.soloId,e,r);await t$(n,{recursive:!0}),await mr(IS(t.soloId,e,r),t)}async function s$(t,e,r){return Zt(IS(t,e,r))}async function MS(t,e){let r=CS(t,e),n;try{n=await r$(r)}catch{return[]}let o=[];for(let s of n){let i=await s$(s,t,e);i&&o.push(i)}return o}async function Xu(t,e,r){let{rm:n}=await import("node:fs/promises"),o=Vu(t,e,r);try{return await n(o,{recursive:!0,force:!0}),!0}catch{return!1}}var Li=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let r={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(n=>({agentId:n.agentId,memberId:n.memberId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,state:n.state,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,turns:n.turns})),evaluation:e.evaluation,createdAt:e.createdAt};ES(r,e.cwd).catch(()=>{})}async restoreFromDisk(e){let r=await MS(e);for(let n of r)this.sessions.has(n.soloId)||this.sessions.set(n.soloId,{soloId:n.soloId,state:n.state,task:n.task,cwd:n.cwd,gitRoot:n.gitRoot,agents:n.agents.map(o=>({...o,turns:o.turns??[]})),evaluation:n.evaluation,createdAt:n.createdAt});return r.length}async deleteSolo(e){return this.sessions.delete(e),Xu(e)}async start(e){let{task:r,agents:n,cwd:o,sharedConfig:s}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await wo(o);if(!i)throw new Error("Solo Mode requires a git repository");let a=r;if(s){let u=[];s.rules?.length&&u.push(`<rules>
547
547
  ${s.rules.join(`
548
548
  `)}
549
549
  </rules>`),s.memory?.length&&u.push(`<memory>
package/dist/index.js CHANGED
@@ -542,7 +542,7 @@ If no action needed, just respond with a progress update message to the user.`,e
542
542
  `)},onMcpToolCall:(a,c,l)=>this.handleMcpToolCall(a,c,l),sessionDir:eR.join(X(),"agent-logs")}),n=Yk({findTool:a=>this.toolCatalog.findTool(a),runAgent:async({agentId:a,prompt:c,signal:l})=>{let d=a??"self",p=this.acpDetector.buildExternalDescriptor(d);if(!p)throw new Error(`workflow agent node: agent "${d}" is not available`);let u=`workflow-agent-${tR().slice(0,8)}`;if(l?.aborted)throw new Error("workflow agent node aborted before dispatch");await r.spawn({memberId:u,name:`workflow-${d}`,cwd:t,prompt:c,external:p});try{let m=await r.sendTask(u,c);return typeof m=="string"?m:JSON.stringify(m)}finally{try{r.kill(u),r.remove(u)}catch(m){process.stderr.write(`[workflow:pm] WARN cleanup of ${u} failed: ${m instanceof Error?m.message:String(m)}
543
543
  `)}}},invokeMcp:({server:a,tool:c,args:l})=>this.handleMcpToolCall(`workflow-mcp:${a}`,c,l),sendChannel:async({channel:a,target:c,payload:l})=>(this.sendNotification("workflow.channel.send",{channel:a,target:c,payload:l}),{queued:!0})}),o=new mn;for(let[a,c]of Object.entries(ho))o.register(a,c);let s=tb({registry:o,host:n,budget:{maxNodeExecutions:vj}});this.workflowController=new ur(e,s),this.workflowStore=e,this.workflowProcessManager=r,ob(this.workflowController);let i=new Ei({controller:this.workflowController,onError:(a,c)=>{let l=a instanceof Error?a.message:String(a);process.stderr.write(`[workflow:scheduler] run error for ${c}: ${l}
544
544
  `),this.sendNotification("workflow.runFailed",{workflowId:c,triggerType:"schedule",error:l})}});this.workflowScheduler=i,i.start().catch(a=>{process.stderr.write(`[workflow:scheduler] start failed: ${a instanceof Error?a.message:String(a)}
545
- `)})}return this.workflowController}function tr(t){return t.params??{}}function rr(t,e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:e})}function bj(t){return{id:t.id,name:t.name,active:t.active,concurrency:t.concurrency,rev:t.rev,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.trigger!==void 0?{trigger:t.trigger}:{},def:t.def}}function Nu(t,e){this.sendNotification(t,{workflow:bj(e)})}function Lu(t,e){if(t.status==="failed"){this.sendNotification("workflow.runFailed",{workflowId:t.workflowId,triggerType:e,error:"Workflow run failed",outcome:t});return}this.sendNotification("workflow.runCompleted",{workflowId:t.workflowId,status:t.status,triggerType:e,outcome:t})}function kj(t){return t instanceof Error?t.message:String(t)}async function rR(t){let e=tr(t);if(!e.def)return rr.call(this,t,"workflow.create requires `def`");let r=Ft.call(this),n=String(e.id??`wf_${tR().slice(0,8)}`),o=await r.create({id:n,name:String(e.name??n),def:e.def,concurrency:e.concurrency,active:e.active===!0});o.active&&await this.workflowScheduler?.refresh(o.id),Nu.call(this,"workflow.created",o),t.id!==void 0&&this.sendResponse(t.id,o)}async function nR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.get requires `id`");let n=await Ft.call(this).get(String(e.id));t.id!==void 0&&this.sendResponse(t.id,n)}async function oR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.describe requires `id`");let n=await Ft.call(this).describe(String(e.id));t.id!==void 0&&this.sendResponse(t.id,{rendered:n})}async function sR(t){let e=tr(t);if(!e.id||!e.patch)return rr.call(this,t,"workflow.patch requires `id` and `patch`");let r=Ft.call(this),n={patch:e.patch,baseRev:e.baseRev,scope:e.scope},o=await r.patch(String(e.id),n);await this.workflowScheduler?.refresh(String(e.id)),o.ok&&Nu.call(this,"workflow.updated",await r.get(String(e.id))),t.id!==void 0&&this.sendResponse(t.id,o)}async function iR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.run requires `id`");let r=Ft.call(this),n=e.trigger??{type:"manual"},o=String(e.id);this.sendNotification("workflow.runStarted",{workflowId:o,triggerType:n.type});let s;try{s=await r.run(o,n),Lu.call(this,s,n.type)}catch(i){throw this.sendNotification("workflow.runFailed",{workflowId:o,triggerType:n.type,error:kj(i)}),i}t.id!==void 0&&this.sendResponse(t.id,s)}async function aR(t){let e=tr(t);if(!e.id||typeof e.active!="boolean")return rr.call(this,t,"workflow.setActive requires `id` and boolean `active`");let n=await Ft.call(this).setActive(String(e.id),e.active);await this.workflowScheduler?.refresh(n.id),Nu.call(this,"workflow.updated",n),t.id!==void 0&&this.sendResponse(t.id,n)}async function cR(t){Ft.call(this);let r=await this.workflowStore.list();t.id!==void 0&&this.sendResponse(t.id,{workflows:r})}async function lR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.delete requires `id`");Ft.call(this),await this.workflowStore.delete(String(e.id)),await this.workflowScheduler?.refresh(String(e.id)),this.sendNotification("workflow.deleted",{workflowId:String(e.id)}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function dR(t){let e=tr(t);if(!e.channel||typeof e.text!="string")return rr.call(this,t,"workflow.onImMessage requires `channel` and string `text`");Ft.call(this);let r=await this.workflowScheduler.onImMessage(String(e.channel),e.text,e.payload);for(let n of r)Lu.call(this,n,"im-message");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}async function uR(t){let e=tr(t);if(!e.path)return rr.call(this,t,"workflow.onWebhook requires `path`");Ft.call(this);let r=await this.workflowScheduler.onWebhook(String(e.path),e.payload);for(let n of r)Lu.call(this,n,"webhook");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}import*as Ce from"node:fs";import*as me from"node:path";G();import*as Hr from"node:fs";import*as Ou from"node:path";G();import*as xe from"node:fs";import*as Ao from"node:path";function Mi(t){let e=X(),r=De(t);xe.existsSync(r)||xe.mkdirSync(r,{recursive:!0});let n=Ao.join(e,"INSTRUCTIONS.md"),o=Ao.join(r,"INSTRUCTIONS.md");if(xe.existsSync(n)&&!xe.existsSync(o))try{xe.copyFileSync(n,o)}catch{}let s=$m(),i=Qr(t);if(xe.existsSync(s)&&!xe.existsSync(i))try{xe.mkdirSync(i,{recursive:!0});for(let a of xe.readdirSync(s)){if(!a.endsWith(".md"))continue;let c=Ao.join(s,a),l=Ao.join(i,a);xe.statSync(c).isFile()&&xe.copyFileSync(c,l)}}catch{}}var Rj=["creating","running","completed","cancelled"];function pR(t){return typeof t=="string"&&Rj.includes(t)}function mR(t,e){let r=I(),n=e.workspaceDir||Ou.join(r.getUserAgentHome(),"workspaces",e.name);if(e.groupId){let l=Ds(e.groupId);if(l)return{project:l,isAgentTeamProject:l.type==="solo"||l.type==="product",deduplicated:!0}}let s=z().find(l=>l.name===e.name);Sj(n);let i=_s({name:e.name,workspaceDir:n,type:e.type??"personal",groupId:e.groupId,skipAutoSwitch:e.type==="solo"||e.type==="product"}),a=i.type==="solo"||i.type==="product";a||(xt(i.id),t.setActiveWorkdir(i.workspaceDir)),Mi(i.workspaceDir);let c=t.projectMemoryStoreFactory.create(i.workspaceDir);return c.ensureInitialized(),a||(t.memdir=c,t.mediaPersistence.setProjectDir(i.workspaceDir)),Tj(i),{project:i,nameDuplicate:s,isAgentTeamProject:a}}function Sj(t){Hr.existsSync(t)||Hr.mkdirSync(t,{recursive:!0})}function Tj(t){let e=I();if(t.type!=="solo"&&t.type!=="product")return;let r=Ou.join(e.getProjectAgentDir(t.workspaceDir),t.type==="solo"?"solo-state.json":"product-state.json");if(Hr.existsSync(r))return;let n=t.type==="solo"?{agents:[],status:"idle",createdAt:new Date().toISOString()}:{tasks:[],instances:[],status:"idle",createdAt:new Date().toISOString()};Hr.writeFileSync(r,JSON.stringify(n,null,2))}function gR(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let r;try{r=mR(this,{name:e.name,workspaceDir:e.workspaceDir,type:e.type,groupId:e.groupId})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:a instanceof Error?a.message:`Cannot create workspace directory: ${e.workspaceDir??e.name}`});return}let{project:n,nameDuplicate:o,isAgentTeamProject:s,deduplicated:i}=r;if(i){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:n,deduplicated:!0});return}if(this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type}),s||this.sendNotification("project.switched",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),t.id!==void 0){let a={ok:!0,project:n};o&&(a.warning=`A project named "${o.name}" already exists at ${o.workspaceDir}. Consider renaming one of them to avoid ambiguity.`),this.sendResponse(t.id,a)}}function fR(t){let e=z();t.id!==void 0&&this.sendResponse(t.id,{projects:e})}function hR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Te(e.projectId),n=Ql(e.projectId);if(!n.deleted){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}let o=!1,s;if(r?.workspaceDir){let i=me.join(X(),"workspaces"),a=me.resolve(r.workspaceDir);if(a.startsWith(me.resolve(i)+me.sep)){try{this.mediaPersistence?.releaseProjectDir?.(a)}catch{}for(let c=0;c<3;c++)try{Ce.rmSync(a,{recursive:!0,force:!0}),o=!0;break}catch(l){if(c<2&&(l.code==="EBUSY"||l.code==="EPERM"||l.code==="ENOTEMPTY")){let d=Date.now();for(;Date.now()-d<200;);}else{s=l.message??String(l);break}}}else s="Project directory is outside the managed workspace root and was not deleted automatically."}this.sendNotification("project.deleted",{id:e.projectId}),n.switchedTo&&(this.setActiveWorkdir(n.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:n.switchedTo,dirDeleted:o,dirDeleteError:s})}function yR(t){let e=z(),r=me.join(X(),"workspaces"),n=me.resolve(r)+me.sep,o=0,s=[];for(let a of e)if(a.type!=="default"){if(Ql(a.id),o++,a.workspaceDir){let c=me.resolve(a.workspaceDir);try{this.mediaPersistence?.releaseProjectDir?.(c)}catch{}for(let l=0;l<3;l++)try{Ce.existsSync(c)&&Ce.rmSync(c,{recursive:!0,force:!0});break}catch(d){if(l<2&&(d.code==="EBUSY"||d.code==="EPERM"||d.code==="ENOTEMPTY")){let p=Date.now();for(;Date.now()-p<300;);}else{s.push(`${a.name}: ${d.message??d}`);break}}}this.sendNotification("project.deleted",{id:a.id})}if(Ce.existsSync(r)){let a=z().find(d=>d.type==="default"),c=new Set;a?.workspaceDir&&c.add(me.resolve(a.workspaceDir));let l=d=>{try{let p=Ce.readdirSync(d,{withFileTypes:!0});for(let u of p){if(!u.isDirectory())continue;let m=me.join(d,u.name);if(!c.has(me.resolve(m))){if(u.name==="groups"){l(m);try{Ce.readdirSync(m).length===0&&Ce.rmdirSync(m)}catch{}continue}try{Ce.rmSync(m,{recursive:!0,force:!0})}catch(f){s.push(`orphan:${u.name}: ${f.message??f}`)}}}}catch{}};l(r)}let i=z().find(a=>a.type==="default");i&&(this.setActiveWorkdir(i.workspaceDir),this.sendNotification("project.switched",{id:i.id,name:i.name,workspaceDir:i.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o,dirErrors:s.length?s:void 0})}function vR(t){let e=t.params;if(!e?.projectId||!e?.newName){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let r=Yf(e.projectId,e.newName);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}let n=me.join(X(),"workspaces"),o=me.resolve(r.workspaceDir);if(o.startsWith(me.resolve(n)+me.sep)){let s=me.join(n,e.newName);if(Ce.existsSync(o)&&!Ce.existsSync(s))try{Ce.renameSync(o,s),Jf(e.projectId,s),r.workspaceDir=s,this.getActiveProjectRoot()===o&&this.setActiveWorkdir(s)}catch{}}this.sendNotification("project.renamed",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function bR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Qf(e.projectId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:e.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:r.switchedTo})}function kR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Zf(e.projectId);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function RR(t){let e=t.params;if(!e?.groupId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: groupId"});return}let r=eh(e.groupId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:r.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:r.projectId})}function SR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"projectId is required"});return}let r={};if("planStatus"in e){if(e.planStatus!==void 0&&!pR(e.planStatus)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Invalid planStatus: ${e.planStatus}`});return}r.planStatus=e.planStatus}"planAgents"in e&&(r.planAgents=e.planAgents),"planWinnerId"in e&&(r.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(r.leaderSessionId=e.leaderSessionId);let n=Vf(e.projectId,r);t.id!==void 0&&this.sendResponse(t.id,{ok:n})}import{randomUUID as $u}from"node:crypto";import*as Ve from"node:fs";import*as Br from"node:path";var gr=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[r,n]of this._modelUsage)e[r]={...n};return e}addUsage(e,r){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(r);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(r,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,r,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||this._modelUsage.set(e,s),s.mediaCalls+=1,r){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break;case"per_token":s.outputTokens+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[r,n]of Object.entries(e.modelUsage))this._modelUsage.set(r,{...n});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as TR from"node:fs";import*as ju from"node:path";var fr=class{getSessionsRoot(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return I().getProjectSessionsRoot(r.workspaceDir)}getProjectWorkspaceDir(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return r.workspaceDir}getSessionDir(e,r){return ju.join(this.getSessionsRoot(e),r)}resolveWorkspaceDir(e,r){if(r)return this.getProjectWorkspaceDir(r);let n=z();for(let o of n){let s=I().getProjectSessionsRoot(o.workspaceDir),i=ju.join(s,e);try{if(TR.existsSync(i))return o.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=ne();if(e)return e.workspaceDir;let r=z();if(r.length>0)return r[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=ne();if(e)return e.id;let r=z();if(r.length>0)return r[0].id;throw new Error("No active project available")}};import{randomUUID as wR}from"node:crypto";async function AR(t,e){let r=new Date(t.lastActiveAt).getTime();if(Date.now()-r<Qp)return{split:!1,activeSessionId:t.sessionId};let s=wR(),i=new Date().toISOString();await Fe(t.sessionId,{sealedAt:i},e);let a=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${t.taskSummary}`:void 0;return await Fe(s,{sessionId:s,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:t.sessionId}}async function PR(t,e){if(t.type!=="group")return{split:!1,activeSessionId:t.sessionId};if(t.turnCount<Zp)return{split:!1,activeSessionId:t.sessionId};let r=wR(),n=new Date().toISOString();await Fe(t.sessionId,{sealedAt:n},e);let o=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${t.taskSummary}`:void 0;return await Fe(r,{sessionId:r,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:o},e),{split:!0,activeSessionId:r,sealedSessionId:t.sessionId}}G();import*as xR from"node:fs";import*as CR from"node:path";var _i=class{constructor(e=new fr,r=I()){this.locator=e;this.pathService=r}locator;pathService;getActiveProjectId(){return this.locator.getActiveProjectId()}getProjectWorkspaceDir(e){return this.locator.getProjectWorkspaceDir(e)}resolveWorkspaceDir(e,r){return this.locator.resolveWorkspaceDir(e,r)}async listThreads(e,r){let n=r??this.getActiveProjectId(),o=this.getProjectWorkspaceDir(n);return(await kt(e,o)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:i.createdAt,lastActiveAt:i.lastActiveAt}))}resolveSessionWorkspaceDir(e,r,n){if(n)return this.resolveWorkspaceDir(r,n);let o=e.getActiveProjectRoot();if(o){let s=CR.join(this.pathService.getProjectSessionsRoot(o),wj(r));try{if(xR.existsSync(s))return o}catch{}}return this.resolveWorkspaceDir(r)}};function wj(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}var Aj=new fr,tt=new _i(Aj);function ht(t,e="Unknown error"){return t instanceof Error?t.message:e}function bn(t,e,r){return tt.resolveSessionWorkspaceDir(t,e,r)}function IR(t){let e=t.params,r=e?.id??$u();this.log(`[thread.create] id=${r} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=r,this.sessionState=new gr(r),this.sessionTaskDomain=void 0,this.memoryPrefetchState=bt(),this.enableIdleDream(),t.id!==void 0&&this.sendResponse(t.id,{id:r,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function ER(t){let e=t.params,r=e?.limit??20;try{let n=await tt.listThreads(r,e?.projectId);t.id!==void 0&&this.sendResponse(t.id,{threads:n})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list threads: ${ht(n)}`})}}async function MR(t){let e=t.params,r=e?.sessionId??$u();try{let n=e?.projectId??tt.getActiveProjectId(),o=tt.getProjectWorkspaceDir(n);await Fe(r,{sessionId:r,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:n},o),t.id!==void 0&&this.sendResponse(t.id,{sessionId:r,title:e?.title})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to create session: ${ht(n)}`})}}async function _R(t){let e=t.params;if(t.id===void 0)return;let r=e?.platform??"desktop",n=e?.chatId,o=e?.chatType,s=e?.userId??"local";try{if(r==="desktop"&&n){let d=e?.projectId??tt.getActiveProjectId(),p=tt.getProjectWorkspaceDir(d),m=(await kt(500,p)).find(f=>f.sessionId===n);if(m){this.sendResponse(t.id,{sessionId:n,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await Fe(n,{sessionId:n,type:"personal",ownerId:s,projectId:d},p),this.sendResponse(t.id,{sessionId:n,type:"personal",ownerId:s,projectId:d});return}if(o==="group"&&n&&r){let d=`group:${r}:${n}`,p=z();for(let u of p){if(!u.workspaceDir)continue;let f=(await kt(500,u.workspaceDir)).find(g=>g.groupKey===d&&!g.sealedAt);if(f){let g=zt(f.sessionId,u.workspaceDir);if(g){let h=await AR(g,u.workspaceDir);if(h.split){this.sendResponse(t.id,{sessionId:h.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id,previousSessionId:h.sealedSessionId});return}}this.sendResponse(t.id,{sessionId:f.sessionId,title:f.title,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id});return}}}let i=$u(),a=tt.getActiveProjectId(),c=tt.getProjectWorkspaceDir(a),l=o==="group"?`group:${r}:${n}`:void 0;await Fe(i,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a},c),this.sendResponse(t.id,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resolve session: ${ht(i)}`})}}async function DR(t){let e=t.params,r=e?.limit??50;try{let n;if(e?.projectId){let s=Te(e.projectId);if(!s){t.id!==void 0&&this.sendResponse(t.id,{sessions:[]});return}let i=s.workspaceDir;n=await kt(r*2,i),n=n.filter(a=>a.projectId===e.projectId);for(let a of n)a.projectId=e.projectId}else{let s=z(),i=new Set,a=[];for(let c of s){if(!c.workspaceDir)continue;let l=await kt(r,c.workspaceDir);for(let d of l)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((c,l)=>c.lastActiveAt>l.lastActiveAt?-1:c.lastActiveAt<l.lastActiveAt?1:0),n=a}e?.archived===!0?n=n.filter(s=>s.archivedAt!=null):e?.archived===!1&&(n=n.filter(s=>s.archivedAt==null));let o=n.slice(0,r).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type??"personal",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}));t.id!==void 0&&this.sendResponse(t.id,{sessions:o})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list sessions: ${ht(n)}`})}}async function NR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId),o=(await kt(500,r)).find(s=>s.sessionId===e.sessionId);t.id!==void 0&&this.sendResponse(t.id,{session:o?{sessionId:o.sessionId,title:o.title,type:o.type,lastActiveAt:o.lastActiveAt,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:o.projectId}:null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get session: ${ht(r)}`})}}async function LR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId),n=await al(e.sessionId,r);if(!n){t.id!==void 0&&this.sendResponse(t.id,{messages:[],total:0});return}let o=n.messages,s=e.limit&&e.limit>0?e.limit:o.length,i=o.slice(-s);t.id!==void 0&&this.sendResponse(t.id,{messages:i,total:o.length})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get messages: ${ht(r)}`})}}async function OR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId),n=await Fe(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},r);n&&this.sendNotification("session.info",{sessionId:e.sessionId,title:n.title,pinnedAt:n.pinnedAt??null,archivedAt:n.archivedAt??null,projectId:e.projectId||void 0}),t.id!==void 0&&this.sendResponse(t.id,{ok:n!==null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to update session: ${ht(r)}`})}}async function jR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId);await cl(e.sessionId,r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete session: ${ht(r)}`})}}async function $R(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let r=tt.getProjectWorkspaceDir(e.projectId),n=(await kt(1e4,r)).filter(s=>s.projectId===e.projectId),o=0;for(let s of n)await cl(s.sessionId,r),o++;t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete all sessions: ${ht(r)}`})}}async function UR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId);await Fe(e.sessionId,{archivedAt:new Date().toISOString()},r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to archive session: ${ht(r)}`})}}async function FR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"sessionId is required"});return}try{let n=bn(this,r,e?.projectId),o=await al(r,n);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Session not found: ${r}`});return}o.messages&&o.messages.length>0&&this.sessionHistory.saveResumedSession(r,o.messages),t.id!==void 0&&this.sendResponse(t.id,{metadata:o.metadata,messages:o.messages})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resume session: ${ht(n)}`})}}function HR(t){let e=this.currentSessionId||"default",r=this.sessionState?.createSnapshot(),n,o=this.getActiveProjectRoot();o&&(n=Br.join(ss(o),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:n,agentHome:X(),settings:Ue()},usage:r?{turnCount:r.turnCount,inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens}:void 0};t.id!==void 0&&this.sendResponse(t.id,s)}function BR(t){let e=t.params,r=null;if(e?.projectId)r=Te(e.projectId);else if(e?.projectName){let s=z(),i=e.projectName.toLowerCase();if(r=s.find(a=>a.name.toLowerCase()===i)??null,r||(r=s.find(a=>a.name.toLowerCase().includes(i))??null),!r){let a=s.map(c=>c.name).slice(0,10);t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!r||r.status!=="active"){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let n=e.workspaceDir??r.workspaceDir;if(!Ve.existsSync(n)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Workspace directory does not exist: ${n}`});return}let o=xt(r.id);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(o.workspaceDir),this.sendNotification("project.switched",{id:o.id,name:o.name,workspaceDir:o.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:o})}function qR(t){let e=ne(),r=z();t.id!==void 0&&this.sendResponse(t.id,{sessionId:this.currentSessionId,activeProject:e,projects:r})}async function WR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,{ok:!1});return}let n=z();for(let o of n)try{let s=tt.getProjectWorkspaceDir(o.id),i=await zt(r,s);if(i&&i.projectId===o.id){xt(o.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} for session ${r}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}catch{}if(e?.projectName){let o=n.find(s=>s.name===e.projectName);if(o){let s=tt.getProjectWorkspaceDir(o.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} by name "${e.projectName}"`)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}t.id!==void 0&&this.sendResponse(t.id,{ok:!1})}async function GR(t){let e=t.params,{sessionId:r,fromProjectId:n,toProjectId:o}=e??{};if(!r||!n||!o){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(n===o){t.id!==void 0&&this.sendResponse(t.id,{ok:!0});return}let s=Te(n),i=Te(o);if(!s||!i){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"Source or target project not found");return}let a=Br.join(tt.getProjectWorkspaceDir(n),".qlogicagent","sessions",r),c=Br.join(tt.getProjectWorkspaceDir(o),".qlogicagent","sessions",r);if(!Ve.existsSync(a)){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,`Session ${r} not found in project ${n}`);return}try{Ve.mkdirSync(Br.dirname(c),{recursive:!0}),Ve.cpSync(a,c,{recursive:!0});let l=Br.join(c,"metadata.json");if(Ve.existsSync(l)){let d=JSON.parse(Ve.readFileSync(l,"utf-8"));d.projectId=o,Ve.writeFileSync(l,JSON.stringify(d,null,2))}Ve.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:r,projectId:o}),this.log(`[session.moveToProject] moved ${r}: ${n} \u2192 ${o}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o})}catch(l){let d=ht(l);this.log(`[session.moveToProject] error: ${d}`),t.id!==void 0&&this.sendError(t.id,y.INTERNAL_ERROR,`Move failed: ${d}`)}}He();function Pj(t){return t.length<=8?"****":`${t.slice(0,3)}***${t.slice(-4)}`}function Ne(t,e,r,n=y.INTERNAL_ERROR){if(e.id!==void 0){if(typeof t.sendError=="function"){t.sendError(e.id,n,r);return}t.sendResponse(e.id,void 0,{code:n,message:r})}}function Uu(t,e){Ne(t,e,us)}function xj(t){let e={};for(let r of t)for(let n of r.purposes)e[n]??=[],e[n].push(r);return e}async function Cj(){let t=D(),e=await Vn(t);return t.save(),e}async function KR(t){try{return await Cj(),!0}catch(e){if(t)throw e;return!1}}function Fu(t=D()){try{return rg()}catch{return t.getKnownProviderDef(Y)?.baseUrl??"https://www.qlogicagent.com"}}function Hu(t){return t.id===Y?Y:t.group?.trim()||t.id}function Ij(t){return t.id===Hu(t)}function zR(t){let e=Hu(t);return ml({...t,id:e})}function Ej(t){return{volcengine:"\u5E38\u89C4 Ark API Key","volcengine-plan":"\u8BA2\u9605 / Plan \u901A\u9053",qwen:"\u5E38\u89C4 DashScope API Key","qwen-coding":"Coding Plan \u901A\u9053",zhipu:"Anthropic \u901A\u9053","zhipu-openai":"OpenAI \u517C\u5BB9\u901A\u9053","zhipu-coding":"Coding \u901A\u9053"}[t.id]??ml(t)}function Mj(t){return t.authType==="none"?!1:t.apiKeyEnvVars===void 0||t.apiKeyEnvVars.length>0}function _j(t){return{id:t.id,displayName:Ej(t),baseUrl:zn(t)??"",modelCount:t.models?.length??0}}function Dj(t){let e=new Map;for(let r of t){if(!Mj(r))continue;let n=Hu(r);if(n===Y)continue;let o=r.models?.length??0,s=_j(r),i=e.get(n);if(!i){e.set(n,{id:n,displayName:zR(r),baseUrl:zn(r)??"",modelCount:o,variants:[s]});continue}i.modelCount+=o,i.variants??=[],i.variants.some(a=>a.id===s.id)||i.variants.push(s),Ij(r)&&(i.displayName=zR(r),i.baseUrl=zn(r)??i.baseUrl)}return Array.from(e.values()).map(r=>({...r,variants:r.variants&&r.variants.length>1?r.variants:void 0}))}async function VR(t){let e=D(),r=e.getKeyForProvider(Y);if(!r){if(t)throw new Error("LLMRouter API Key is required to fetch available models.");return!1}let n=e.getProviderStatus(Y)?.baseUrl??Fu(e);try{if((await gl(e,{baseUrl:n,apiKey:r})).length===0){if(t)throw new Error("LLMRouter did not return any available models for this API Key.");return!1}return e.save(),!0}catch(o){if(t)throw o;return!1}}async function XR(t=!1){let e=D();if(!!e.getProviderStatus(Y)?.keys.length)return await VR(!1)?!0:KR(t);let o=e.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId).some(s=>s!=="deepseek"&&s!==Y);return!t&&!o?!1:KR(t)}async function YR(t,e,r){let n=t===Y?ul(r):`${r.replace(/\/$/,"")}/models`;try{let o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)});if(o.ok)return{valid:!0,status:o.status};let s=await o.text().catch(()=>"");return{valid:!1,status:o.status,error:s.slice(0,500)}}catch(o){return{valid:!1,status:0,error:o instanceof Error?o.message:String(o)}}}async function Nj(t,e,r){let n=await YR(t,e,r);if(!n.valid){let o=n.error?`: ${n.error}`:"";throw new Error(`API Key validation failed (${n.status})${o}`)}}async function JR(t){try{let e=D(),r=["deepseek",Y].map(s=>e.getKnownProviderDef(s)).filter(s=>!!s).map(s=>({id:s.id,displayName:s.name,baseUrl:s.baseUrl,modelCount:s.models?.length??0})),n=await pl().catch(()=>[]),o=Dj(n);o.unshift({id:Y,displayName:dl,baseUrl:Fu(e),modelCount:n.reduce((s,i)=>s+(i.models?.length??0),0)});for(let s of r.reverse()){let i=o.findIndex(a=>a.id===s.id);if(i>=0){s.id!==Y&&o.splice(i,1,s);continue}o.unshift(s)}t.id!==void 0&&this.sendResponse(t.id,{providers:o})}catch(e){Ne(this,t,e instanceof Error?e.message:String(e))}}async function QR(t){let e=t.params;if(!e?.providerId||!e?.key){Ne(this,t,"Required: providerId (string), key (string)",y.INVALID_PARAMS);return}let{providerId:r,key:n,label:o}=e,s=D(),i,a=!1;try{let c=await lS(r);if(!c){Ne(this,t,`Unknown provider: ${r}`,y.INVALID_PARAMS);return}let l=s.getProviderStatus(r);if(l?.keys.some(d=>d.key===n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}if(a=!l,s.addProvider(r,{baseUrl:c}),i=s.addKey(r,n,{label:o}),r===Y){if((await gl(s,{baseUrl:c,apiKey:n})).length===0)throw new Error("LLMRouter did not return any available models for this API Key.")}else await Nj(r,n,c);for(let d of Kn)if(!s.getBinding(d)){let p=s.listModels({purpose:d,provider:r,enabledOnly:!0});p.length===0&&(p=s.listModels({purpose:d,provider:r}),p[0]&&s.enableModel(p[0].id)),p.length>0&&s.setBinding(d,p[0].id)}s.setKeyHealth(i,"healthy"),s.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,keyId:i,providerId:r})}catch(c){i&&(s.removeKey(i),a&&s.removeProvider(r));let l=c instanceof Error?c.message:us;Ne(this,t,l)}}function ZR(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D();r.removeKey(e.keyId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function eS(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D().getKeyById(e.keyId);if(!r){Ne(this,t,"API Key not found",y.INVALID_PARAMS);return}t.id!==void 0&&this.sendResponse(t.id,{key:r})}function tS(t){let e=t.params;if(!e?.keyId||typeof e.enabled!="boolean"){Ne(this,t,"Required: keyId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();r.updateKey(e.keyId,{enabled:e.enabled}),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function rS(t){let e=t.params;if(!e?.modelId||typeof e.enabled!="boolean"){Ne(this,t,"Required: modelId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();e.enabled?r.enableModel(e.modelId):r.disableModel(e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function nS(t){let e=t.params;try{await XR(!1);let r=D(),n=new Set(r.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),o=r.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>r.hasConfiguredKeyForProviderVariant(s.provider));t.id!==void 0&&this.sendResponse(t.id,{models:o,grouped:xj(o),configuredProviderIds:[...n]})}catch{Uu(this,t)}}function oS(t){let e=t.params;if(!e?.purpose||!e?.modelId){Ne(this,t,"Required: purpose (string), modelId (string)",y.INVALID_PARAMS);return}try{let r=D();r.setBinding(e.purpose,e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){Ne(this,t,r instanceof Error?r.message:String(r),y.INVALID_PARAMS)}}function sS(t){let e=t.params;if(!e?.purpose){Ne(this,t,"Required: purpose (string)",y.INVALID_PARAMS);return}let r=D(),n=r.getBinding(e.purpose);t.id!==void 0&&this.sendResponse(t.id,{model:n?{id:n.id,provider:n.provider,model:n.model,displayName:n.displayName,purposes:n.purposes,enabled:n.enabled}:null,available:r.isAvailable(e.purpose)})}async function iS(t){try{await XR(!1);let e=D(),r=e.getAllProviderStatus().map(s=>({providerId:s.providerId,displayName:s.providerId===Y?dl:s.providerId,baseUrl:s.baseUrl,keyCount:s.keys.length,healthyKeys:s.keys.filter(i=>i.healthStatus==="healthy"&&i.enabled).length,totalKeys:s.keys.length,keys:s.keys.map(i=>({id:i.id,label:i.label,maskedKey:Pj(i.key),enabled:i.enabled,health:i.healthStatus}))})),n=e.getAllBindings(),o={};for(let s of Kn){let i=n[s];o[s]={bound:!!i,modelId:i?.id,modelName:i?.displayName,available:e.isAvailable(s)}}t.id!==void 0&&this.sendResponse(t.id,{providers:r,purposes:o})}catch{Uu(this,t)}}async function aS(t){try{let e=D();e.load(),await VR(!1)||await Vn(e),e.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,catalogRefreshed:!0})}catch{Uu(this,t)}}async function cS(t){let e=t.params;if(!e?.providerId||!e?.apiKey){Ne(this,t,"providerId and apiKey required",y.INVALID_PARAMS);return}try{let r=e.baseUrl||await lS(e.providerId);if(!r){Ne(this,t,`Unknown provider: ${e.providerId}`,y.INVALID_PARAMS);return}let n=await YR(e.providerId,e.apiKey,r);t.id!==void 0&&this.sendResponse(t.id,n)}catch(r){let n=r instanceof Error?r.message:String(r);t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:0,error:n})}}async function lS(t){if(t===Y)return Fu();let e=D().getKnownProviderDef(t);if(e?.baseUrl)return e.baseUrl;let r=await og(t);return r?zn(r):void 0}G();import*as ce from"node:fs";import*as Le from"node:path";import{join as Lj}from"node:path";import{readFileSync as Oj,writeFileSync as jj,mkdirSync as $j}from"node:fs";var qr=null,Bu=!1;function dS(t){return Lj(t,"skill-stats.json")}function qu(t){if(qr)return qr;try{qr=JSON.parse(Oj(dS(t),"utf8"))}catch{qr={}}return qr}function Uj(t){if(!(!Bu||!qr))try{$j(t,{recursive:!0}),jj(dS(t),JSON.stringify(qr,null,2),"utf8"),Bu=!1}catch{}}function Wu(t,e,r){let n=qu(t);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),r?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Bu=!0,Uj(t)}function uS(t,e){return qu(t)[e]}function pS(t){return qu(t)}import*as Ht from"node:fs";import*as Di from"node:path";function Fj(t){try{let e=Ht.readFileSync(t,"utf8"),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),n=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:r?.[1],description:n?.[1]?.trim()}}catch{return{}}}function gS(t){let e=I(),r=[],n=t?e.getProjectSkillsDir(t):void 0,o=e.getUserSkillsDir();return n&&mS(r,n,"project"),mS(r,o,"global"),r}function mS(t,e,r){if(Ht.existsSync(e))for(let n of Ht.readdirSync(e)){let o=Di.join(e,n);try{if(!Ht.statSync(o).isDirectory())continue}catch{continue}let s=Di.join(o,"SKILL.md"),i=Di.join(o,"SKILL.md.disabled"),a=Ht.existsSync(s)?s:null;if(!a&&!Ht.existsSync(i))continue;let c=a?Fj(a):{};t.push({id:`${r}:${n}`,name:n,path:o,active:!!a,scope:r,category:"automation",displayName:Hj(n),displayDescription:Bj(n,c.description),fallbackName:n,fallbackDescription:c.description??"",systemGenerated:qj(n),version:c.version,description:c.description})}}function Hj(t){return{key:`capability.skill.${t}.name`,fallback:t}}function Bj(t,e){return{key:`capability.skill.${t}.description`,fallback:e??""}}function qj(t){return t.startsWith("auto-skill-")||t.startsWith("test-skill-")}function Wj(t){return t==="active"||t==="stale"||t==="archived"}function fS(t){let r=t.params?.projectId,n=this.getActiveProjectRoot();if(r&&this.projectLocator){let s=this.projectLocator.resolveProjectRoot(r);s&&(n=s)}let o=gS(n);t.id!==void 0&&this.sendResponse(t.id,{skills:o})}function hS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md.disabled"),a=Le.join(s,"SKILL.md");if(ce.existsSync(a)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}if(ce.existsSync(i))try{ce.renameSync(i,a);let c=B(),l=ue(c),d=Ct(l,r);d.state!=="active"&&(d.state="active",d.staleAt=void 0,d.archivedAt=void 0),he(c,l),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"activate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to activate skill: ${c instanceof Error?c.message:c}`})}else t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found`})}function yS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md"),a=Le.join(s,"SKILL.md.disabled");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}try{ce.renameSync(i,a),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"deactivate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to deactivate skill: ${c instanceof Error?c.message:c}`})}}function vS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=B(),o=ue(n);if(o.records[r]?.pinned){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Skill "${r}" is pinned. Unpin it first.`});return}let s=e?.scope??"project",i;if(s==="global")i=Le.join(sr(),r);else{let a=this.getActiveProjectRoot(),c=a?ir(a):void 0;if(!c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}i=Le.join(c,r)}if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in ${s} scope`});return}try{ce.rmSync(i,{recursive:!0,force:!0}),mt(),js(o,r),he(n,o),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deleted:r,scope:s}),this.sendNotification("skills.updated",{action:"delete",name:r})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete skill: ${a instanceof Error?a.message:a}`})}}function bS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in project scope`});return}let a=sr(),c=Le.join(a,r);try{ce.mkdirSync(c,{recursive:!0});let l=ce.readdirSync(s);for(let d of l){let p=ce.readFileSync(Le.join(s,d));ce.writeFileSync(Le.join(c,d),p)}e?.keepLocal||ce.rmSync(s,{recursive:!0,force:!0}),mt(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,promoted:r,globalPath:c,removedFromProject:!e?.keepLocal})}catch(l){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}function kS(t){let e=t.params,r=B();if(e?.name){let n=uS(r,e.name);t.id!==void 0&&this.sendResponse(t.id,{name:e.name,stats:n??null})}else{let n=pS(r);t.id!==void 0&&this.sendResponse(t.id,{stats:n})}}function RS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);Ct(n,e.name),ch(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!0})}function SS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);lh(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!1})}function TS(t){let e=B(),r=this.getActiveProjectRoot(),n=r?Le.join(r,".qlogicagent","skills"):sr(),o=dh(e,n);o.transitioned.length>0&&mt(),t.id!==void 0&&this.sendResponse(t.id,o)}function wS(t){let e=t.params,r=B(),n=ue(r);if(e?.name){let o=n.records[e.name]??null;t.id!==void 0&&this.sendResponse(t.id,{record:o})}else if(e?.state){if(!Wj(e.state)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Invalid skill lifecycle state"});return}let o=uh(n,e.state);t.id!==void 0&&this.sendResponse(t.id,{records:o})}else t.id!==void 0&&this.sendResponse(t.id,{records:Object.values(n.records)})}import*as IS from"node:path";import{randomUUID as Yj}from"node:crypto";import{join as Gu}from"node:path";import{mkdir as Gj,readdir as Kj}from"node:fs/promises";function zj(t){return t?.pathService??I()}function Vj(t,e){return t??e.getActiveProjectRoot()}function AS(t,e){let r=zj(e);return Gu(r.getProjectAgentDir(Vj(t,r)),"solos")}function Ku(t,e,r){return Gu(AS(e,r),t)}function PS(t,e,r){return Gu(Ku(t,e,r),"solo-state.json")}async function xS(t,e,r){let n=Ku(t.soloId,e,r);await Gj(n,{recursive:!0}),await pr(PS(t.soloId,e,r),t)}async function Xj(t,e,r){return Qt(PS(t,e,r))}async function CS(t,e){let r=AS(t,e),n;try{n=await Kj(r)}catch{return[]}let o=[];for(let s of n){let i=await Xj(s,t,e);i&&o.push(i)}return o}async function zu(t,e,r){let{rm:n}=await import("node:fs/promises"),o=Ku(t,e,r);try{return await n(o,{recursive:!0,force:!0}),!0}catch{return!1}}var Ni=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let r={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(n=>({agentId:n.agentId,memberId:n.memberId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,state:n.state,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,turns:n.turns})),evaluation:e.evaluation,createdAt:e.createdAt};xS(r,e.cwd).catch(()=>{})}async restoreFromDisk(e){let r=await CS(e);for(let n of r)this.sessions.has(n.soloId)||this.sessions.set(n.soloId,{soloId:n.soloId,state:n.state,task:n.task,cwd:n.cwd,gitRoot:n.gitRoot,agents:n.agents.map(o=>({...o,turns:o.turns??[]})),evaluation:n.evaluation,createdAt:n.createdAt});return r.length}async deleteSolo(e){return this.sessions.delete(e),zu(e)}async start(e){let{task:r,agents:n,cwd:o,sharedConfig:s}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await wo(o);if(!i)throw new Error("Solo Mode requires a git repository");let a=r;if(s){let u=[];s.rules?.length&&u.push(`<rules>
545
+ `)})}return this.workflowController}function tr(t){return t.params??{}}function rr(t,e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:e})}function bj(t){return{id:t.id,name:t.name,active:t.active,concurrency:t.concurrency,rev:t.rev,createdAt:t.createdAt,updatedAt:t.updatedAt,...t.trigger!==void 0?{trigger:t.trigger}:{},def:t.def}}function Nu(t,e){this.sendNotification(t,{workflow:bj(e)})}function Lu(t,e){if(t.status==="failed"){this.sendNotification("workflow.runFailed",{workflowId:t.workflowId,triggerType:e,error:"Workflow run failed",outcome:t});return}this.sendNotification("workflow.runCompleted",{workflowId:t.workflowId,status:t.status,triggerType:e,outcome:t})}function kj(t){return t instanceof Error?t.message:String(t)}async function rR(t){let e=tr(t);if(!e.def)return rr.call(this,t,"workflow.create requires `def`");let r=Ft.call(this),n=String(e.id??`wf_${tR().slice(0,8)}`),o=await r.create({id:n,name:String(e.name??n),def:e.def,concurrency:e.concurrency,active:e.active===!0});o.active&&await this.workflowScheduler?.refresh(o.id),Nu.call(this,"workflow.created",o),t.id!==void 0&&this.sendResponse(t.id,o)}async function nR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.get requires `id`");let n=await Ft.call(this).get(String(e.id));t.id!==void 0&&this.sendResponse(t.id,n)}async function oR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.describe requires `id`");let n=await Ft.call(this).describe(String(e.id));t.id!==void 0&&this.sendResponse(t.id,{rendered:n})}async function sR(t){let e=tr(t);if(!e.id||!e.patch)return rr.call(this,t,"workflow.patch requires `id` and `patch`");let r=Ft.call(this),n={patch:e.patch,baseRev:e.baseRev,scope:e.scope},o=await r.patch(String(e.id),n);await this.workflowScheduler?.refresh(String(e.id)),o.ok&&Nu.call(this,"workflow.updated",await r.get(String(e.id))),t.id!==void 0&&this.sendResponse(t.id,o)}async function iR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.run requires `id`");let r=Ft.call(this),n=e.trigger??{type:"manual"},o=String(e.id);this.sendNotification("workflow.runStarted",{workflowId:o,triggerType:n.type});let s;try{s=await r.run(o,n),Lu.call(this,s,n.type)}catch(i){throw this.sendNotification("workflow.runFailed",{workflowId:o,triggerType:n.type,error:kj(i)}),i}t.id!==void 0&&this.sendResponse(t.id,s)}async function aR(t){let e=tr(t);if(!e.id||typeof e.active!="boolean")return rr.call(this,t,"workflow.setActive requires `id` and boolean `active`");let n=await Ft.call(this).setActive(String(e.id),e.active);await this.workflowScheduler?.refresh(n.id),Nu.call(this,"workflow.updated",n),t.id!==void 0&&this.sendResponse(t.id,n)}async function cR(t){Ft.call(this);let r=await this.workflowStore.list();t.id!==void 0&&this.sendResponse(t.id,{workflows:r})}async function lR(t){let e=tr(t);if(!e.id)return rr.call(this,t,"workflow.delete requires `id`");Ft.call(this),await this.workflowStore.delete(String(e.id)),await this.workflowScheduler?.refresh(String(e.id)),this.sendNotification("workflow.deleted",{workflowId:String(e.id)}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function dR(t){let e=tr(t);if(!e.channel||typeof e.text!="string")return rr.call(this,t,"workflow.onImMessage requires `channel` and string `text`");Ft.call(this);let r=await this.workflowScheduler.onImMessage(String(e.channel),e.text,e.payload);for(let n of r)Lu.call(this,n,"im-message");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}async function uR(t){let e=tr(t);if(!e.path)return rr.call(this,t,"workflow.onWebhook requires `path`");Ft.call(this);let r=await this.workflowScheduler.onWebhook(String(e.path),e.payload);for(let n of r)Lu.call(this,n,"webhook");t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}import*as Ce from"node:fs";import*as me from"node:path";G();import*as Hr from"node:fs";import*as Ou from"node:path";G();import*as xe from"node:fs";import*as Ao from"node:path";function Mi(t){let e=X(),r=De(t);xe.existsSync(r)||xe.mkdirSync(r,{recursive:!0});let n=Ao.join(e,"INSTRUCTIONS.md"),o=Ao.join(r,"INSTRUCTIONS.md");if(xe.existsSync(n)&&!xe.existsSync(o))try{xe.copyFileSync(n,o)}catch{}let s=$m(),i=Qr(t);if(xe.existsSync(s)&&!xe.existsSync(i))try{xe.mkdirSync(i,{recursive:!0});for(let a of xe.readdirSync(s)){if(!a.endsWith(".md"))continue;let c=Ao.join(s,a),l=Ao.join(i,a);xe.statSync(c).isFile()&&xe.copyFileSync(c,l)}}catch{}}var Rj=["creating","running","completed","cancelled"];function pR(t){return typeof t=="string"&&Rj.includes(t)}function mR(t,e){let r=I(),n=e.workspaceDir||Ou.join(r.getUserAgentHome(),"workspaces",e.name);if(e.groupId){let l=Ds(e.groupId);if(l)return{project:l,isAgentTeamProject:l.type==="solo"||l.type==="product",deduplicated:!0}}let s=z().find(l=>l.name===e.name);Sj(n);let i=_s({name:e.name,workspaceDir:n,type:e.type??"personal",groupId:e.groupId,skipAutoSwitch:e.type==="solo"||e.type==="product"}),a=i.type==="solo"||i.type==="product";a||(xt(i.id),t.setActiveWorkdir(i.workspaceDir)),Mi(i.workspaceDir);let c=t.projectMemoryStoreFactory.create(i.workspaceDir);return c.ensureInitialized(),a||(t.memdir=c,t.mediaPersistence.setProjectDir(i.workspaceDir)),Tj(i),{project:i,nameDuplicate:s,isAgentTeamProject:a}}function Sj(t){Hr.existsSync(t)||Hr.mkdirSync(t,{recursive:!0})}function Tj(t){let e=I();if(t.type!=="solo"&&t.type!=="product")return;let r=Ou.join(e.getProjectAgentDir(t.workspaceDir),t.type==="solo"?"solo-state.json":"product-state.json");if(Hr.existsSync(r))return;let n=t.type==="solo"?{agents:[],status:"idle",createdAt:new Date().toISOString()}:{tasks:[],instances:[],status:"idle",createdAt:new Date().toISOString()};Hr.writeFileSync(r,JSON.stringify(n,null,2))}function gR(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let r;try{r=mR(this,{name:e.name,workspaceDir:e.workspaceDir,type:e.type,groupId:e.groupId})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:a instanceof Error?a.message:`Cannot create workspace directory: ${e.workspaceDir??e.name}`});return}let{project:n,nameDuplicate:o,isAgentTeamProject:s,deduplicated:i}=r;if(i){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:n,deduplicated:!0});return}if(this.sendNotification("project.created",{id:n.id,name:n.name,workspaceDir:n.workspaceDir,type:n.type}),s||this.sendNotification("project.switched",{id:n.id,name:n.name,workspaceDir:n.workspaceDir}),t.id!==void 0){let a={ok:!0,project:n};o&&(a.warning=`A project named "${o.name}" already exists at ${o.workspaceDir}. Consider renaming one of them to avoid ambiguity.`),this.sendResponse(t.id,a)}}function fR(t){let e=z();t.id!==void 0&&this.sendResponse(t.id,{projects:e})}function hR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Te(e.projectId),n=Ql(e.projectId);if(!n.deleted){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}let o=!1,s;if(r?.workspaceDir){let i=me.join(X(),"workspaces"),a=me.resolve(r.workspaceDir);if(a.startsWith(me.resolve(i)+me.sep)){try{this.mediaPersistence?.releaseProjectDir?.(a)}catch{}for(let c=0;c<3;c++)try{Ce.rmSync(a,{recursive:!0,force:!0}),o=!0;break}catch(l){if(c<2&&(l.code==="EBUSY"||l.code==="EPERM"||l.code==="ENOTEMPTY")){let d=Date.now();for(;Date.now()-d<200;);}else{s=l.message??String(l);break}}}else s="Project directory is outside the managed workspace root and was not deleted automatically."}this.sendNotification("project.deleted",{id:e.projectId}),n.switchedTo&&(this.setActiveWorkdir(n.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:n.switchedTo,dirDeleted:o,dirDeleteError:s})}function yR(t){let e=z(),r=me.join(X(),"workspaces"),n=me.resolve(r)+me.sep,o=0,s=[];for(let a of e)if(a.type!=="default"){if(Ql(a.id),o++,a.workspaceDir){let c=me.resolve(a.workspaceDir);try{this.mediaPersistence?.releaseProjectDir?.(c)}catch{}for(let l=0;l<3;l++)try{Ce.existsSync(c)&&Ce.rmSync(c,{recursive:!0,force:!0});break}catch(d){if(l<2&&(d.code==="EBUSY"||d.code==="EPERM"||d.code==="ENOTEMPTY")){let p=Date.now();for(;Date.now()-p<300;);}else{s.push(`${a.name}: ${d.message??d}`);break}}}this.sendNotification("project.deleted",{id:a.id})}if(Ce.existsSync(r)){let a=z().find(d=>d.type==="default"),c=new Set;a?.workspaceDir&&c.add(me.resolve(a.workspaceDir));let l=d=>{try{let p=Ce.readdirSync(d,{withFileTypes:!0});for(let u of p){if(!u.isDirectory())continue;let m=me.join(d,u.name);if(!c.has(me.resolve(m))){if(u.name==="groups"){l(m);try{Ce.readdirSync(m).length===0&&Ce.rmdirSync(m)}catch{}continue}try{Ce.rmSync(m,{recursive:!0,force:!0})}catch(f){s.push(`orphan:${u.name}: ${f.message??f}`)}}}}catch{}};l(r)}let i=z().find(a=>a.type==="default");i&&(this.setActiveWorkdir(i.workspaceDir),this.sendNotification("project.switched",{id:i.id,name:i.name,workspaceDir:i.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o,dirErrors:s.length?s:void 0})}function vR(t){let e=t.params;if(!e?.projectId||!e?.newName){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let r=Yf(e.projectId,e.newName);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}let n=me.join(X(),"workspaces"),o=me.resolve(r.workspaceDir);if(o.startsWith(me.resolve(n)+me.sep)){let s=me.join(n,e.newName);if(Ce.existsSync(o)&&!Ce.existsSync(s))try{Ce.renameSync(o,s),Jf(e.projectId,s),r.workspaceDir=s,this.getActiveProjectRoot()===o&&this.setActiveWorkdir(s)}catch{}}this.sendNotification("project.renamed",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function bR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Qf(e.projectId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:e.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:r.switchedTo})}function kR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Zf(e.projectId);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function RR(t){let e=t.params;if(!e?.groupId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: groupId"});return}let r=eh(e.groupId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:r.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:r.projectId})}function SR(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"projectId is required"});return}let r={};if("planStatus"in e){if(e.planStatus!==void 0&&!pR(e.planStatus)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Invalid planStatus: ${e.planStatus}`});return}r.planStatus=e.planStatus}"planAgents"in e&&(r.planAgents=e.planAgents),"planWinnerId"in e&&(r.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(r.leaderSessionId=e.leaderSessionId);let n=Vf(e.projectId,r);t.id!==void 0&&this.sendResponse(t.id,{ok:n})}import{randomUUID as $u}from"node:crypto";import*as Ve from"node:fs";import*as Br from"node:path";var gr=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[r,n]of this._modelUsage)e[r]={...n};return e}addUsage(e,r){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(r);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(r,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,r,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||this._modelUsage.set(e,s),s.mediaCalls+=1,r){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break;case"per_token":s.outputTokens+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[r,n]of Object.entries(e.modelUsage))this._modelUsage.set(r,{...n});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as TR from"node:fs";import*as ju from"node:path";var fr=class{getSessionsRoot(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return I().getProjectSessionsRoot(r.workspaceDir)}getProjectWorkspaceDir(e){let r=Te(e);if(!r)throw new Error(`Project not found: ${e}`);return r.workspaceDir}getSessionDir(e,r){return ju.join(this.getSessionsRoot(e),r)}resolveWorkspaceDir(e,r){if(r)return this.getProjectWorkspaceDir(r);let n=z();for(let o of n){let s=I().getProjectSessionsRoot(o.workspaceDir),i=ju.join(s,e);try{if(TR.existsSync(i))return o.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=ne();if(e)return e.workspaceDir;let r=z();if(r.length>0)return r[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=ne();if(e)return e.id;let r=z();if(r.length>0)return r[0].id;throw new Error("No active project available")}};import{randomUUID as wR}from"node:crypto";async function AR(t,e){let r=new Date(t.lastActiveAt).getTime();if(Date.now()-r<Qp)return{split:!1,activeSessionId:t.sessionId};let s=wR(),i=new Date().toISOString();await Fe(t.sessionId,{sealedAt:i},e);let a=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${t.taskSummary}`:void 0;return await Fe(s,{sessionId:s,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:t.sessionId}}async function PR(t,e){if(t.type!=="group")return{split:!1,activeSessionId:t.sessionId};if(t.turnCount<Zp)return{split:!1,activeSessionId:t.sessionId};let r=wR(),n=new Date().toISOString();await Fe(t.sessionId,{sealedAt:n},e);let o=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${t.taskSummary}`:void 0;return await Fe(r,{sessionId:r,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:o},e),{split:!0,activeSessionId:r,sealedSessionId:t.sessionId}}G();import*as xR from"node:fs";import*as CR from"node:path";var _i=class{constructor(e=new fr,r=I()){this.locator=e;this.pathService=r}locator;pathService;getActiveProjectId(){return this.locator.getActiveProjectId()}getProjectWorkspaceDir(e){return this.locator.getProjectWorkspaceDir(e)}resolveWorkspaceDir(e,r){return this.locator.resolveWorkspaceDir(e,r)}async listThreads(e,r){let n=r??this.getActiveProjectId(),o=this.getProjectWorkspaceDir(n);return(await kt(e,o)).map(i=>({id:i.sessionId,title:i.title,status:"active",turnCount:i.messageCount,createdAt:i.createdAt,lastActiveAt:i.lastActiveAt}))}resolveSessionWorkspaceDir(e,r,n){if(n)return this.resolveWorkspaceDir(r,n);let o=e.getActiveProjectRoot();if(o){let s=CR.join(this.pathService.getProjectSessionsRoot(o),wj(r));try{if(xR.existsSync(s))return o}catch{}}return this.resolveWorkspaceDir(r)}};function wj(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}var Aj=new fr,tt=new _i(Aj);function ht(t,e="Unknown error"){return t instanceof Error?t.message:e}function bn(t,e,r){return tt.resolveSessionWorkspaceDir(t,e,r)}function IR(t){let e=t.params,r=e?.id??$u();this.log(`[thread.create] id=${r} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=r,this.sessionState=new gr(r),this.sessionTaskDomain=void 0,this.memoryPrefetchState=bt(),this.enableIdleDream(),t.id!==void 0&&this.sendResponse(t.id,{id:r,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function ER(t){let e=t.params,r=e?.limit??20;try{let n=await tt.listThreads(r,e?.projectId);t.id!==void 0&&this.sendResponse(t.id,{threads:n})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list threads: ${ht(n)}`})}}async function MR(t){let e=t.params,r=e?.sessionId??$u();try{let n=e?.projectId??tt.getActiveProjectId(),o=tt.getProjectWorkspaceDir(n);await Fe(r,{sessionId:r,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:n},o),t.id!==void 0&&this.sendResponse(t.id,{sessionId:r,title:e?.title})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to create session: ${ht(n)}`})}}async function _R(t){let e=t.params;if(t.id===void 0)return;let r=e?.platform??"desktop",n=e?.chatId,o=e?.chatType,s=e?.userId??"local";try{if(r==="desktop"&&n){let d=e?.projectId??tt.getActiveProjectId(),p=tt.getProjectWorkspaceDir(d),m=(await kt(500,p)).find(f=>f.sessionId===n);if(m){this.sendResponse(t.id,{sessionId:n,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await Fe(n,{sessionId:n,type:"personal",ownerId:s,projectId:d},p),this.sendResponse(t.id,{sessionId:n,type:"personal",ownerId:s,projectId:d});return}if(o==="group"&&n&&r){let d=`group:${r}:${n}`,p=z();for(let u of p){if(!u.workspaceDir)continue;let f=(await kt(500,u.workspaceDir)).find(g=>g.groupKey===d&&!g.sealedAt);if(f){let g=zt(f.sessionId,u.workspaceDir);if(g){let h=await AR(g,u.workspaceDir);if(h.split){this.sendResponse(t.id,{sessionId:h.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id,previousSessionId:h.sealedSessionId});return}}this.sendResponse(t.id,{sessionId:f.sessionId,title:f.title,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:u.id});return}}}let i=$u(),a=tt.getActiveProjectId(),c=tt.getProjectWorkspaceDir(a),l=o==="group"?`group:${r}:${n}`:void 0;await Fe(i,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a},c),this.sendResponse(t.id,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resolve session: ${ht(i)}`})}}async function DR(t){let e=t.params,r=e?.limit??50;try{let n;if(e?.projectId){let s=Te(e.projectId);if(!s){t.id!==void 0&&this.sendResponse(t.id,{sessions:[]});return}let i=s.workspaceDir;n=await kt(r*2,i),n=n.filter(a=>a.projectId===e.projectId);for(let a of n)a.projectId=e.projectId}else{let s=z(),i=new Set,a=[];for(let c of s){if(!c.workspaceDir)continue;let l=await kt(r,c.workspaceDir);for(let d of l)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((c,l)=>c.lastActiveAt>l.lastActiveAt?-1:c.lastActiveAt<l.lastActiveAt?1:0),n=a}e?.archived===!0?n=n.filter(s=>s.archivedAt!=null):e?.archived===!1&&(n=n.filter(s=>s.archivedAt==null));let o=n.slice(0,r).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type??"personal",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}));t.id!==void 0&&this.sendResponse(t.id,{sessions:o})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list sessions: ${ht(n)}`})}}async function NR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId),o=(await kt(500,r)).find(s=>s.sessionId===e.sessionId);t.id!==void 0&&this.sendResponse(t.id,{session:o?{sessionId:o.sessionId,title:o.title,type:o.type,lastActiveAt:o.lastActiveAt,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:o.projectId}:null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get session: ${ht(r)}`})}}async function LR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId),n=await al(e.sessionId,r);if(!n){t.id!==void 0&&this.sendResponse(t.id,{messages:[],total:0});return}let o=n.messages,s=e.limit&&e.limit>0?e.limit:o.length,i=o.slice(-s);t.id!==void 0&&this.sendResponse(t.id,{messages:i,total:o.length})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get messages: ${ht(r)}`})}}async function OR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId),n=await Fe(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},r);n&&this.sendNotification("session.info",{sessionId:e.sessionId,title:n.title,pinnedAt:n.pinnedAt??null,archivedAt:n.archivedAt??null,projectId:e.projectId||void 0}),t.id!==void 0&&this.sendResponse(t.id,{ok:n!==null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to update session: ${ht(r)}`})}}async function jR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId);await cl(e.sessionId,r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete session: ${ht(r)}`})}}async function $R(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let r=tt.getProjectWorkspaceDir(e.projectId),n=(await kt(1e4,r)).filter(s=>s.projectId===e.projectId),o=0;for(let s of n)await cl(s.sessionId,r),o++;t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete all sessions: ${ht(r)}`})}}async function UR(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=bn(this,e.sessionId,e.projectId);await Fe(e.sessionId,{archivedAt:new Date().toISOString()},r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to archive session: ${ht(r)}`})}}async function FR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"sessionId is required"});return}try{let n=bn(this,r,e?.projectId),o=await al(r,n);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Session not found: ${r}`});return}o.messages&&o.messages.length>0&&this.sessionHistory.saveResumedSession(r,o.messages),t.id!==void 0&&this.sendResponse(t.id,{metadata:o.metadata,messages:o.messages})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resume session: ${ht(n)}`})}}function HR(t){let e=this.currentSessionId||"default",r=this.sessionState?.createSnapshot(),n,o=this.getActiveProjectRoot();o&&(n=Br.join(ss(o),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:n,agentHome:X(),settings:Ue()},usage:r?{turnCount:r.turnCount,inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens}:void 0};t.id!==void 0&&this.sendResponse(t.id,s)}function BR(t){let e=t.params,r=null;if(e?.projectId)r=Te(e.projectId);else if(e?.projectName){let s=z(),i=e.projectName.toLowerCase();if(r=s.find(a=>a.name.toLowerCase()===i)??null,r||(r=s.find(a=>a.name.toLowerCase().includes(i))??null),!r){let a=s.map(c=>c.name).slice(0,10);t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!r||r.status!=="active"){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let n=e.workspaceDir??r.workspaceDir;if(!Ve.existsSync(n)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Workspace directory does not exist: ${n}`});return}let o=xt(r.id);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(o.workspaceDir),this.sendNotification("project.switched",{id:o.id,name:o.name,workspaceDir:o.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:o})}function qR(t){let e=ne(),r=z();t.id!==void 0&&this.sendResponse(t.id,{sessionId:this.currentSessionId,activeProject:e,projects:r})}async function WR(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,{ok:!1});return}let n=z();for(let o of n)try{let s=tt.getProjectWorkspaceDir(o.id),i=await zt(r,s);if(i&&i.projectId===o.id){xt(o.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} for session ${r}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}catch{}if(e?.projectName){let o=n.find(s=>s.name===e.projectName);if(o){let s=tt.getProjectWorkspaceDir(o.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} by name "${e.projectName}"`)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}t.id!==void 0&&this.sendResponse(t.id,{ok:!1})}async function GR(t){let e=t.params,{sessionId:r,fromProjectId:n,toProjectId:o}=e??{};if(!r||!n||!o){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(n===o){t.id!==void 0&&this.sendResponse(t.id,{ok:!0});return}let s=Te(n),i=Te(o);if(!s||!i){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"Source or target project not found");return}let a=Br.join(tt.getProjectWorkspaceDir(n),".qlogicagent","sessions",r),c=Br.join(tt.getProjectWorkspaceDir(o),".qlogicagent","sessions",r);if(!Ve.existsSync(a)){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,`Session ${r} not found in project ${n}`);return}try{Ve.mkdirSync(Br.dirname(c),{recursive:!0}),Ve.cpSync(a,c,{recursive:!0});let l=Br.join(c,"metadata.json");if(Ve.existsSync(l)){let d=JSON.parse(Ve.readFileSync(l,"utf-8"));d.projectId=o,Ve.writeFileSync(l,JSON.stringify(d,null,2))}Ve.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:r,projectId:o}),this.log(`[session.moveToProject] moved ${r}: ${n} \u2192 ${o}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o})}catch(l){let d=ht(l);this.log(`[session.moveToProject] error: ${d}`),t.id!==void 0&&this.sendError(t.id,y.INTERNAL_ERROR,`Move failed: ${d}`)}}He();function Pj(t){return t.length<=8?"****":`${t.slice(0,3)}***${t.slice(-4)}`}function Ne(t,e,r,n=y.INTERNAL_ERROR){if(e.id!==void 0){if(typeof t.sendError=="function"){t.sendError(e.id,n,r);return}t.sendResponse(e.id,void 0,{code:n,message:r})}}function Uu(t,e){Ne(t,e,us)}function xj(t){let e={};for(let r of t)for(let n of r.purposes)e[n]??=[],e[n].push(r);return e}async function Cj(){let t=D(),e=await Vn(t);return t.save(),e}async function KR(t){try{return await Cj(),!0}catch(e){if(t)throw e;return!1}}function Fu(t=D()){try{return rg()}catch{return t.getKnownProviderDef(Y)?.baseUrl??"https://www.qlogicagent.com"}}function Hu(t){return t.id===Y?Y:t.group?.trim()||t.id}function Ij(t){return t.id===Hu(t)}function zR(t){let e=Hu(t);return ml({...t,id:e})}function Ej(t){return{volcengine:"\u5E38\u89C4 Ark API Key","volcengine-plan":"\u8BA2\u9605 / Plan \u901A\u9053",qwen:"\u5E38\u89C4 DashScope API Key","qwen-coding":"Coding Plan \u901A\u9053",zhipu:"Anthropic \u901A\u9053","zhipu-openai":"OpenAI \u517C\u5BB9\u901A\u9053","zhipu-coding":"Coding \u901A\u9053"}[t.id]??ml(t)}function Mj(t){return t.authType==="none"?!1:t.apiKeyEnvVars===void 0||t.apiKeyEnvVars.length>0}function _j(t){return{id:t.id,displayName:Ej(t),baseUrl:zn(t)??"",modelCount:t.models?.length??0}}function Dj(t){let e=new Map;for(let r of t){if(!Mj(r))continue;let n=Hu(r);if(n===Y)continue;let o=r.models?.length??0,s=_j(r),i=e.get(n);if(!i){e.set(n,{id:n,displayName:zR(r),baseUrl:zn(r)??"",modelCount:o,variants:[s]});continue}i.modelCount+=o,i.variants??=[],i.variants.some(a=>a.id===s.id)||i.variants.push(s),Ij(r)&&(i.displayName=zR(r),i.baseUrl=zn(r)??i.baseUrl)}return Array.from(e.values()).map(r=>({...r,variants:r.variants&&r.variants.length>1?r.variants:void 0}))}async function VR(t){let e=D(),r=e.getKeyForProvider(Y);if(!r){if(t)throw new Error("LLMRouter API Key is required to fetch available models.");return!1}let n=e.getProviderStatus(Y)?.baseUrl??Fu(e);try{if((await gl(e,{baseUrl:n,apiKey:r})).length===0){if(t)throw new Error("LLMRouter did not return any available models for this API Key.");return!1}return e.save(),!0}catch(o){if(t)throw o;return!1}}async function XR(t=!1){let e=D();if(!!e.getProviderStatus(Y)?.keys.length)return await VR(!1)?!0:KR(t);let o=e.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId).some(s=>s!=="deepseek"&&s!==Y);return!t&&!o?!1:KR(t)}async function YR(t,e,r){let n;if(t===Y)n=ul(r);else{let o=D().getKnownProviderDef(t)?.transport,s=r.replace(/\/$/,"");o==="anthropic-messages"&&(s=s.replace(/\/anthropic$/,"")),n=`${s}/models`}try{let o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)});if(o.ok)return{valid:!0,status:o.status};let s=await o.text().catch(()=>"");return{valid:!1,status:o.status,error:s.slice(0,500)}}catch(o){return{valid:!1,status:0,error:o instanceof Error?o.message:String(o)}}}async function Nj(t,e,r){let n=await YR(t,e,r);if(!n.valid){let o=n.error?`: ${n.error}`:"";throw new Error(`API Key validation failed (${n.status})${o}`)}}async function JR(t){try{let e=D(),r=["deepseek",Y].map(s=>e.getKnownProviderDef(s)).filter(s=>!!s).map(s=>({id:s.id,displayName:s.name,baseUrl:s.baseUrl,modelCount:s.models?.length??0})),n=await pl().catch(()=>[]),o=Dj(n);o.unshift({id:Y,displayName:dl,baseUrl:Fu(e),modelCount:n.reduce((s,i)=>s+(i.models?.length??0),0)});for(let s of r.reverse()){let i=o.findIndex(a=>a.id===s.id);if(i>=0){s.id!==Y&&o.splice(i,1,s);continue}o.unshift(s)}t.id!==void 0&&this.sendResponse(t.id,{providers:o})}catch(e){Ne(this,t,e instanceof Error?e.message:String(e))}}async function QR(t){let e=t.params;if(!e?.providerId||!e?.key){Ne(this,t,"Required: providerId (string), key (string)",y.INVALID_PARAMS);return}let{providerId:r,key:n,label:o}=e,s=D(),i,a=!1;try{let c=await lS(r);if(!c){Ne(this,t,`Unknown provider: ${r}`,y.INVALID_PARAMS);return}let l=s.getProviderStatus(r);if(l?.keys.some(d=>d.key===n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}if(a=!l,s.addProvider(r,{baseUrl:c}),i=s.addKey(r,n,{label:o}),r===Y){if((await gl(s,{baseUrl:c,apiKey:n})).length===0)throw new Error("LLMRouter did not return any available models for this API Key.")}else await Nj(r,n,c);for(let d of Kn)if(!s.getBinding(d)){let p=s.listModels({purpose:d,provider:r,enabledOnly:!0});p.length===0&&(p=s.listModels({purpose:d,provider:r}),p[0]&&s.enableModel(p[0].id)),p.length>0&&s.setBinding(d,p[0].id)}s.setKeyHealth(i,"healthy"),s.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,keyId:i,providerId:r})}catch(c){i&&(s.removeKey(i),a&&s.removeProvider(r));let l=c instanceof Error?c.message:us;Ne(this,t,l)}}function ZR(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D();r.removeKey(e.keyId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function eS(t){let e=t.params;if(!e?.keyId){Ne(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=D().getKeyById(e.keyId);if(!r){Ne(this,t,"API Key not found",y.INVALID_PARAMS);return}t.id!==void 0&&this.sendResponse(t.id,{key:r})}function tS(t){let e=t.params;if(!e?.keyId||typeof e.enabled!="boolean"){Ne(this,t,"Required: keyId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();r.updateKey(e.keyId,{enabled:e.enabled}),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function rS(t){let e=t.params;if(!e?.modelId||typeof e.enabled!="boolean"){Ne(this,t,"Required: modelId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=D();e.enabled?r.enableModel(e.modelId):r.disableModel(e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function nS(t){let e=t.params;try{await XR(!1);let r=D(),n=new Set(r.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),o=r.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>r.hasConfiguredKeyForProviderVariant(s.provider));t.id!==void 0&&this.sendResponse(t.id,{models:o,grouped:xj(o),configuredProviderIds:[...n]})}catch{Uu(this,t)}}function oS(t){let e=t.params;if(!e?.purpose||!e?.modelId){Ne(this,t,"Required: purpose (string), modelId (string)",y.INVALID_PARAMS);return}try{let r=D();r.setBinding(e.purpose,e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){Ne(this,t,r instanceof Error?r.message:String(r),y.INVALID_PARAMS)}}function sS(t){let e=t.params;if(!e?.purpose){Ne(this,t,"Required: purpose (string)",y.INVALID_PARAMS);return}let r=D(),n=r.getBinding(e.purpose);t.id!==void 0&&this.sendResponse(t.id,{model:n?{id:n.id,provider:n.provider,model:n.model,displayName:n.displayName,purposes:n.purposes,enabled:n.enabled}:null,available:r.isAvailable(e.purpose)})}async function iS(t){try{await XR(!1);let e=D(),r=e.getAllProviderStatus().map(s=>({providerId:s.providerId,displayName:s.providerId===Y?dl:s.providerId,baseUrl:s.baseUrl,keyCount:s.keys.length,healthyKeys:s.keys.filter(i=>i.healthStatus==="healthy"&&i.enabled).length,totalKeys:s.keys.length,keys:s.keys.map(i=>({id:i.id,label:i.label,maskedKey:Pj(i.key),enabled:i.enabled,health:i.healthStatus}))})),n=e.getAllBindings(),o={};for(let s of Kn){let i=n[s];o[s]={bound:!!i,modelId:i?.id,modelName:i?.displayName,available:e.isAvailable(s)}}t.id!==void 0&&this.sendResponse(t.id,{providers:r,purposes:o})}catch{Uu(this,t)}}async function aS(t){try{let e=D();e.load(),await VR(!1)||await Vn(e),e.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,catalogRefreshed:!0})}catch{Uu(this,t)}}async function cS(t){let e=t.params;if(!e?.providerId||!e?.apiKey){Ne(this,t,"providerId and apiKey required",y.INVALID_PARAMS);return}try{let r=e.baseUrl||await lS(e.providerId);if(!r){Ne(this,t,`Unknown provider: ${e.providerId}`,y.INVALID_PARAMS);return}let n=await YR(e.providerId,e.apiKey,r);t.id!==void 0&&this.sendResponse(t.id,n)}catch(r){let n=r instanceof Error?r.message:String(r);t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:0,error:n})}}async function lS(t){if(t===Y)return Fu();let e=D().getKnownProviderDef(t);if(e?.baseUrl)return e.baseUrl;let r=await og(t);return r?zn(r):void 0}G();import*as ce from"node:fs";import*as Le from"node:path";import{join as Lj}from"node:path";import{readFileSync as Oj,writeFileSync as jj,mkdirSync as $j}from"node:fs";var qr=null,Bu=!1;function dS(t){return Lj(t,"skill-stats.json")}function qu(t){if(qr)return qr;try{qr=JSON.parse(Oj(dS(t),"utf8"))}catch{qr={}}return qr}function Uj(t){if(!(!Bu||!qr))try{$j(t,{recursive:!0}),jj(dS(t),JSON.stringify(qr,null,2),"utf8"),Bu=!1}catch{}}function Wu(t,e,r){let n=qu(t);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),r?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Bu=!0,Uj(t)}function uS(t,e){return qu(t)[e]}function pS(t){return qu(t)}import*as Ht from"node:fs";import*as Di from"node:path";function Fj(t){try{let e=Ht.readFileSync(t,"utf8"),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),n=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:r?.[1],description:n?.[1]?.trim()}}catch{return{}}}function gS(t){let e=I(),r=[],n=t?e.getProjectSkillsDir(t):void 0,o=e.getUserSkillsDir();return n&&mS(r,n,"project"),mS(r,o,"global"),r}function mS(t,e,r){if(Ht.existsSync(e))for(let n of Ht.readdirSync(e)){let o=Di.join(e,n);try{if(!Ht.statSync(o).isDirectory())continue}catch{continue}let s=Di.join(o,"SKILL.md"),i=Di.join(o,"SKILL.md.disabled"),a=Ht.existsSync(s)?s:null;if(!a&&!Ht.existsSync(i))continue;let c=a?Fj(a):{};t.push({id:`${r}:${n}`,name:n,path:o,active:!!a,scope:r,category:"automation",displayName:Hj(n),displayDescription:Bj(n,c.description),fallbackName:n,fallbackDescription:c.description??"",systemGenerated:qj(n),version:c.version,description:c.description})}}function Hj(t){return{key:`capability.skill.${t}.name`,fallback:t}}function Bj(t,e){return{key:`capability.skill.${t}.description`,fallback:e??""}}function qj(t){return t.startsWith("auto-skill-")||t.startsWith("test-skill-")}function Wj(t){return t==="active"||t==="stale"||t==="archived"}function fS(t){let r=t.params?.projectId,n=this.getActiveProjectRoot();if(r&&this.projectLocator){let s=this.projectLocator.resolveProjectRoot(r);s&&(n=s)}let o=gS(n);t.id!==void 0&&this.sendResponse(t.id,{skills:o})}function hS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md.disabled"),a=Le.join(s,"SKILL.md");if(ce.existsSync(a)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}if(ce.existsSync(i))try{ce.renameSync(i,a);let c=B(),l=ue(c),d=Ct(l,r);d.state!=="active"&&(d.state="active",d.staleAt=void 0,d.archivedAt=void 0),he(c,l),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"activate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to activate skill: ${c instanceof Error?c.message:c}`})}else t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found`})}function yS(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md"),a=Le.join(s,"SKILL.md.disabled");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}try{ce.renameSync(i,a),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"deactivate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to deactivate skill: ${c instanceof Error?c.message:c}`})}}function vS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=B(),o=ue(n);if(o.records[r]?.pinned){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Skill "${r}" is pinned. Unpin it first.`});return}let s=e?.scope??"project",i;if(s==="global")i=Le.join(sr(),r);else{let a=this.getActiveProjectRoot(),c=a?ir(a):void 0;if(!c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}i=Le.join(c,r)}if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in ${s} scope`});return}try{ce.rmSync(i,{recursive:!0,force:!0}),mt(),js(o,r),he(n,o),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deleted:r,scope:s}),this.sendNotification("skills.updated",{action:"delete",name:r})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete skill: ${a instanceof Error?a.message:a}`})}}function bS(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=this.getActiveProjectRoot(),o=n?ir(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=Le.join(o,r),i=Le.join(s,"SKILL.md");if(!ce.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in project scope`});return}let a=sr(),c=Le.join(a,r);try{ce.mkdirSync(c,{recursive:!0});let l=ce.readdirSync(s);for(let d of l){let p=ce.readFileSync(Le.join(s,d));ce.writeFileSync(Le.join(c,d),p)}e?.keepLocal||ce.rmSync(s,{recursive:!0,force:!0}),mt(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,promoted:r,globalPath:c,removedFromProject:!e?.keepLocal})}catch(l){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}function kS(t){let e=t.params,r=B();if(e?.name){let n=uS(r,e.name);t.id!==void 0&&this.sendResponse(t.id,{name:e.name,stats:n??null})}else{let n=pS(r);t.id!==void 0&&this.sendResponse(t.id,{stats:n})}}function RS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);Ct(n,e.name),ch(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!0})}function SS(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=B(),n=ue(r);lh(n,e.name),he(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!1})}function TS(t){let e=B(),r=this.getActiveProjectRoot(),n=r?Le.join(r,".qlogicagent","skills"):sr(),o=dh(e,n);o.transitioned.length>0&&mt(),t.id!==void 0&&this.sendResponse(t.id,o)}function wS(t){let e=t.params,r=B(),n=ue(r);if(e?.name){let o=n.records[e.name]??null;t.id!==void 0&&this.sendResponse(t.id,{record:o})}else if(e?.state){if(!Wj(e.state)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Invalid skill lifecycle state"});return}let o=uh(n,e.state);t.id!==void 0&&this.sendResponse(t.id,{records:o})}else t.id!==void 0&&this.sendResponse(t.id,{records:Object.values(n.records)})}import*as IS from"node:path";import{randomUUID as Yj}from"node:crypto";import{join as Gu}from"node:path";import{mkdir as Gj,readdir as Kj}from"node:fs/promises";function zj(t){return t?.pathService??I()}function Vj(t,e){return t??e.getActiveProjectRoot()}function AS(t,e){let r=zj(e);return Gu(r.getProjectAgentDir(Vj(t,r)),"solos")}function Ku(t,e,r){return Gu(AS(e,r),t)}function PS(t,e,r){return Gu(Ku(t,e,r),"solo-state.json")}async function xS(t,e,r){let n=Ku(t.soloId,e,r);await Gj(n,{recursive:!0}),await pr(PS(t.soloId,e,r),t)}async function Xj(t,e,r){return Qt(PS(t,e,r))}async function CS(t,e){let r=AS(t,e),n;try{n=await Kj(r)}catch{return[]}let o=[];for(let s of n){let i=await Xj(s,t,e);i&&o.push(i)}return o}async function zu(t,e,r){let{rm:n}=await import("node:fs/promises"),o=Ku(t,e,r);try{return await n(o,{recursive:!0,force:!0}),!0}catch{return!1}}var Ni=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let r={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(n=>({agentId:n.agentId,memberId:n.memberId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,state:n.state,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,turns:n.turns})),evaluation:e.evaluation,createdAt:e.createdAt};xS(r,e.cwd).catch(()=>{})}async restoreFromDisk(e){let r=await CS(e);for(let n of r)this.sessions.has(n.soloId)||this.sessions.set(n.soloId,{soloId:n.soloId,state:n.state,task:n.task,cwd:n.cwd,gitRoot:n.gitRoot,agents:n.agents.map(o=>({...o,turns:o.turns??[]})),evaluation:n.evaluation,createdAt:n.createdAt});return r.length}async deleteSolo(e){return this.sessions.delete(e),zu(e)}async start(e){let{task:r,agents:n,cwd:o,sharedConfig:s}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await wo(o);if(!i)throw new Error("Solo Mode requires a git repository");let a=r;if(s){let u=[];s.rules?.length&&u.push(`<rules>
546
546
  ${s.rules.join(`
547
547
  `)}
548
548
  </rules>`),s.memory?.length&&u.push(`<memory>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qlogicagent",
3
- "version": "2.10.42",
3
+ "version": "2.10.44",
4
4
  "description": "XiaozhiClaw Agent CLI — subprocess architecture (JSON-RPC over stdio)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",