aws-runtime-bridge 1.9.124 → 1.9.126
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/README.md +23 -2
- package/dist/adapter/AcodeSdkAdapter.js +4 -4
- package/dist/adapter/OpencodeSdkAdapter.js +2 -2
- package/dist/adapter/types.js +1 -1
- package/dist/config.d.ts +30 -4
- package/dist/config.js +3 -1
- package/dist/index.js +1 -1
- package/dist/routes/acode-todos.js +1 -1
- package/dist/routes/background-tasks.js +1 -1
- package/dist/routes/dashboard.js +58 -3
- package/dist/routes/git.d.ts +28 -0
- package/dist/routes/git.js +32 -31
- package/dist/routes/terminal.js +24 -24
- package/dist/services/auto-register.d.ts +2 -2
- package/dist/services/auto-register.js +1 -1
- package/dist/services/aws-client-agent-mcp.d.ts +2 -1
- package/dist/services/aws-client-agent-mcp.js +2 -2
- package/dist/services/cc-switch-sdk.js +1 -1
- package/dist/services/cli-commands.js +5 -5
- package/dist/services/fileSnapshotStore.js +1 -1
- package/dist/services/instance-ai-config-service.js +1 -1
- package/dist/services/instance-features.d.ts +2 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/panel-auth.d.ts +2 -0
- package/dist/services/panel-auth.js +1 -1
- package/dist/services/startup-config-wizard.js +6 -6
- package/dist/services/tunnel-client.js +1 -1
- package/dist/services/update-notifier.js +2 -2
- package/package/acode/dist/ask-user-question-tool.js +2 -2
- package/package/acode/dist/background-command-store.js +1 -1
- package/package/acode/dist/builtins/commandArtifacts.js +3 -3
- package/package/acode/dist/mcpToolNames.d.ts +2 -0
- package/package/acode/dist/mcpToolNames.js +1 -1
- package/package/acode/dist/meeting-debug-log.d.ts +1 -0
- package/package/acode/dist/meeting-debug-log.js +3 -0
- package/package/acode/dist/paths.d.ts +2 -0
- package/package/acode/dist/paths.js +2 -0
- package/package/acode/dist/runtime.d.ts +4 -0
- package/package/acode/dist/runtime.js +20 -20
- package/package/acode/dist/sub-agent-manager.d.ts +1 -0
- package/package/acode/dist/sub-agent-manager.js +1 -1
- package/package/acode/dist/sub-agent-store.js +3 -3
- package/package/acode/dist/sub-agent-tools.js +27 -31
- package/package/acode/dist/sub-agent-types.d.ts +1 -1
- package/package/acode/dist/todo-store.js +1 -1
- package/package/acode/dist/tool-allocation.d.ts +18 -4
- package/package/acode/dist/tool-allocation.js +1 -1
- package/package/acode/dist/types.d.ts +0 -3
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +17 -0
- package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.js +251 -1
- package/package/aws-client-agent-mcp/dist/config.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/config.js +1 -1
- package/package/aws-client-agent-mcp/dist/config.test.js +93 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +6 -2
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +21 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -28
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js +628 -7
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +10 -0
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +12 -10
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +38 -0
- package/package/aws-client-agent-mcp/dist/meeting-debug-log.d.ts +13 -0
- package/package/aws-client-agent-mcp/dist/meeting-debug-log.js +3 -0
- package/package/aws-client-agent-mcp/dist/message-buffer.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/message-buffer.js +1 -1
- package/package/aws-client-agent-mcp/dist/message-buffer.test.js +60 -0
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.d.ts +14 -0
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.js +1 -1
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +39 -1
- package/package/aws-client-agent-mcp/dist/types.d.ts +11 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.js +1 -1
- package/package/aws-client-agent-mcp/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomUUID as S}from"node:crypto";import{ACodeRuntime as w}from"./runtime.js";const T=30*60*1e3,m=2*60*1e3,f=12*60*1e3,b=5e3,c=[100,500,2e3,8e3],E=6e4,A=10*60*1e3;class _{constructor(t){this.subAgents=new Map,this.parentToSubs=new Map,this.subscribers=new Map,this.cleanupTimer=null,this.completionQueue=[],this.completionWaiterResolve=null,this.pendingPersists=new Set,this.store=t.store,this.maxConcurrent=t.maxConcurrent??5,this.cleanupTimer=setInterval(()=>{this.cleanupCompletedEntries(),this.recoverZombieEntries()},5*60*1e3),this.cleanupTimer.unref&&this.cleanupTimer.unref(),this.store.reconcileZombies().catch(()=>{})}async spawn(t){if(this.countByStatus(t.parentAgentId,"running","pending")>=this.maxConcurrent)throw new Error(`concurrent sub-agent limit reached (${this.maxConcurrent}) for agent ${t.parentAgentId}`);const s=`sub-${S()}`,n=Date.now(),i=new AbortController,o={...t.parentConfig,sessionId:s,workingDirectory:t.workingDirectory,agentId:`${t.parentAgentId}__sub__${s}`,initialPrompt:void 0,subAgentManager:void 0,subagentType:t.subagentType,subAgentAllowedTools:t.allowedTools&&t.allowedTools.length>0?t.allowedTools:void 0,...t.parentConfig.subAgentModel?{model:t.parentConfig.subAgentModel}:{},...t.parentConfig.subAgentEffort?{effort:t.parentConfig.subAgentEffort}:{},subAgentModel:void 0,subAgentEffort:void 0},r=new w(o),a={subId:s,parentAgentId:t.parentAgentId,parentSessionId:t.parentSessionId,subagentType:t.subagentType,description:t.description,prompt:t.prompt,status:"pending",startedAt:n,runtime:r,abortController:i,silent:t.silent,contextSnapshot:{tokenUsage:{input:0,output:0},messageCount:0,updatedAt:new Date().toISOString()},availableTools:[],...t.allowedTools&&t.allowedTools.length>0?{allocatedTools:t.allowedTools}:{}};this.subAgents.set(s,a),this.addToParentMap(t.parentAgentId,s);const u=this.toRecord(a);return await this.store.upsert(t.parentAgentId,u),r.on("event",l=>{this.handleRuntimeEvent(s,l)}),this.emitEvent(s,"spawned",{}),s}async start(t){const e=this.subAgents.get(t);if(!e)throw new Error(`sub-agent not found: ${t}`);if(e.status!=="pending")throw new Error(`sub-agent ${t} cannot start from status: ${e.status}`);e.completionPromise=new Promise((s,n)=>{e.completionResolve=s,e.completionReject=n}),this.runEntryToCompletion(e).catch(()=>{})}async startWithRecheck(t,e,s=3){const n=this.subAgents.get(t);if(!n)throw new Error(`sub-agent not found: ${t}`);if(n.status!=="pending")throw new Error(`sub-agent ${t} cannot start from status: ${n.status}`);n.completionPromise=new Promise((i,o)=>{n.completionResolve=i,n.completionReject=o}),this.runEntryToCompletionWithRecheck(n,e,s).catch(()=>{})}async awaitCompletion(t,e=0){if(t.length===0)return[];const s=[],n=t.map(async o=>{const r=this.subAgents.get(o);if(!r){const u=await this.findRecordInStore(o);u?s.push({subId:o,output:u.result??"",error:u.errorMessage,status:u.status}):s.push({subId:o,output:"",error:`sub-agent not found: ${o}`,status:"failed"});return}r.awaited=!0,r.status==="pending"&&await this.start(o);const a=r.completionPromise??Promise.resolve({output:"",error:"not started"});try{const u=await a;s.push({subId:o,output:u.output,error:u.error,status:r.status})}catch(u){s.push({subId:o,output:"",error:u instanceof Error?u.message:String(u),status:r.status})}}),i=new Set(t);for(let o=this.completionQueue.length-1;o>=0;o--)i.has(this.completionQueue[o].subId)&&this.completionQueue.splice(o,1);return e>0?await Promise.race([Promise.allSettled(n),new Promise(o=>setTimeout(()=>o(),e))]):await Promise.allSettled(n),s}async runEntryToCompletion(t){const e=[];let s=!1,n;const i=o=>{if(o)switch(o.type){case"assistant_delta":typeof o.data?.text=="string"&&e.push(o.data.text);break;case"turn_complete":o.data?.failed&&(s=!0);break;case"error":typeof o.data?.message=="string"&&(n=o.data.message);break}};t.runtime.on("event",i),t.status="running",t.contextSnapshot.currentTool="[starting]",t.contextSnapshot.updatedAt=new Date().toISOString(),this.emitEvent(t.subId,"running",{snapshot:{...t.contextSnapshot}});try{await d(this.store.updateStatus(t.parentAgentId,t.subId,{status:"running"}),b,`sub-agent ${t.subId} store.updateStatus(running)`)}catch(o){console.error(`[SubAgentManager] store.updateStatus(running) failed for subId=${t.subId}: ${o instanceof Error?o.message:String(o)}`)}try{if(await t.runtime.start(),t.availableTools=t.runtime.getAvailableTools(),await t.runtime.submit(t.prompt),s)throw new Error(n??"sub-agent turn failed");const o=e.join("");t.status="completed",t.result=o,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"completed",{result:o}),t.completionResolve?.({output:o}),this.enqueueCompletion(t,o,void 0),this.persistFinalStatus(t,{status:"completed",result:o,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}catch(o){const r=o instanceof Error?o.message:String(o);t.status="failed",t.errorMessage=r,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"failed",{error:r}),t.completionResolve?.({output:"",error:r}),this.enqueueCompletion(t,"",r),this.persistFinalStatus(t,{status:"failed",errorMessage:r,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}finally{try{t.runtime.removeListener?.("event",i)}catch{}try{await t.runtime.stop()}catch{}}}async runEntryToCompletionWithRecheck(t,e,s){const n=[];let i=!1,o;const r=a=>{if(a)switch(a.type){case"assistant_delta":typeof a.data?.text=="string"&&n.push(a.data.text);break;case"turn_complete":a.data?.failed&&(i=!0);break;case"error":typeof a.data?.message=="string"&&(o=a.data.message);break}};t.runtime.on("event",r),t.status="running",t.contextSnapshot.currentTool="[starting]",t.contextSnapshot.updatedAt=new Date().toISOString(),this.emitEvent(t.subId,"running",{snapshot:{...t.contextSnapshot}});try{await d(this.store.updateStatus(t.parentAgentId,t.subId,{status:"running"}),b,`sub-agent ${t.subId} store.updateStatus(running)`)}catch(a){console.error(`[SubAgentManager] store.updateStatus(running) failed for subId=${t.subId}: ${a instanceof Error?a.message:String(a)}`)}try{if(await d(t.runtime.start(),E,`sub-agent ${t.subId} runtime.start()`),t.contextSnapshot.currentTool="[submitting]",t.contextSnapshot.updatedAt=new Date().toISOString(),t.availableTools=t.runtime.getAvailableTools(),this.emitEvent(t.subId,"progress",{snapshot:{...t.contextSnapshot}}),await d(t.runtime.submit(t.prompt),A,`sub-agent ${t.subId} runtime.submit() turn=1`),i)throw new Error(o??"sub-agent turn failed");let a=1;for(;a<=s;){let l;try{l=await e(n.join(""),a)}catch(g){console.error(`[SubAgentManager] recheck threw error for subId=${t.subId} turn=${a}, treating as done:`,g instanceof Error?g.message:String(g));break}if(l.done)break;const h=l.continueMessage??"\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5904\u7406\uFF0C\u8BF7\u7EE7\u7EED\u3002";if(i=!1,o=void 0,console.error(`[SubAgentManager] recheck not done for subId=${t.subId} turn=${a}/${s}, injecting continue message (${h.length} chars)`),await d(t.runtime.submit(h),A,`sub-agent ${t.subId} runtime.submit() recheck turn=${a+1}`),i)throw new Error(o??`sub-agent turn ${a+1} failed during recheck continuation`);a++}a>s&&console.error(`[SubAgentManager] recheck reached maxRetries=${s} for subId=${t.subId}, completing with potentially unfinished work`);const u=n.join("");t.status="completed",t.result=u,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"completed",{result:u}),t.completionResolve?.({output:u}),this.enqueueCompletion(t,u,void 0),this.persistFinalStatus(t,{status:"completed",result:u,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}catch(a){const u=a instanceof Error?a.message:String(a);t.status="failed",t.errorMessage=u,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"failed",{error:u}),t.completionResolve?.({output:"",error:u}),this.enqueueCompletion(t,"",u),this.persistFinalStatus(t,{status:"failed",errorMessage:u,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}finally{try{t.runtime.removeListener?.("event",r)}catch{}try{await t.runtime.stop()}catch{}}}async runToCompletion(t){const e=this.subAgents.get(t);if(!e)throw new Error(`sub-agent not found: ${t}`);if(e.status==="running")throw new Error(`sub-agent already running: ${t}`);return e.status!=="pending"&&(e.status="pending"),await this.start(t),await e.completionPromise??{output:"",error:"not started"}}async abort(t){const e=this.subAgents.get(t);if(e&&!(e.status==="completed"||e.status==="failed"||e.status==="cancelled")){e.abortController.abort();try{await e.runtime.abort()}catch{}e.status="cancelled",e.endedAt=Date.now(),e.durationMs=e.endedAt-e.startedAt,this.emitEvent(t,"cancelled",{}),e.completionResolve?.({output:"",error:"aborted"}),this.enqueueCompletion(e,"","aborted"),this.persistFinalStatus(e,{status:"cancelled",endedAt:e.endedAt,durationMs:e.durationMs,availableTools:e.availableTools,contextSnapshot:void 0})}}getSubAgent(t){return this.subAgents.get(t)}listByParent(t){const e=this.parentToSubs.get(t);return e?Array.from(e).map(s=>this.subAgents.get(s)).filter(s=>s!==void 0):[]}listActiveByParent(t){return this.listByParent(t).filter(e=>(e.status==="pending"||e.status==="running")&&!e.silent)}takeCompletedSubAgents(){return this.completionQueue.length===0?[]:this.completionQueue.splice(0)}waitForAnyCompletion(){if(this.completionQueue.length>0){const n=this.completionQueue.shift();return{promise:Promise.resolve(n),cancel:()=>{}}}let t=!1;return{promise:new Promise(n=>{this.completionWaiterResolve=i=>{t||n(i)}}),cancel:()=>{t=!0,this.completionWaiterResolve=null}}}subscribe(t,e){let s=this.subscribers.get(t);return s||(s=new Set,this.subscribers.set(t,s)),s.add(e),()=>{s?.delete(e),s&&s.size===0&&this.subscribers.delete(t)}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null);const t=Array.from(this.subAgents.values());await Promise.allSettled(t.map(e=>this.abort(e.subId))),await this.flushPendingPersists(),this.subAgents.clear(),this.parentToSubs.clear(),this.subscribers.clear()}persistFinalStatus(t,e){const s=(async()=>{let n;for(let i=0;i<=c.length;i++)try{await this.store.updateStatus(t.parentAgentId,t.subId,e);return}catch(o){n=o,i<c.length&&await new Promise(r=>setTimeout(r,c[i]))}console.error(`[SubAgentManager] persistFinalStatus(${e.status}) failed after ${c.length+1} attempts for subId=${t.subId}: ${n instanceof Error?n.message:String(n)}`)})();return this.pendingPersists.add(s),s.finally(()=>this.pendingPersists.delete(s)),s}async flushPendingPersists(){this.pendingPersists.size!==0&&await Promise.allSettled(Array.from(this.pendingPersists))}enqueueCompletion(t,e,s){if(t.silent||t.awaited)return;const n={subId:t.subId,subagentType:t.subagentType,description:t.description,status:t.status,output:e,error:s,durationMs:t.durationMs};if(this.completionQueue.push(n),this.completionWaiterResolve){const i=this.completionWaiterResolve;this.completionWaiterResolve=null;const o=this.completionQueue.pop();i(o??n)}}countByStatus(t,...e){return this.listByParent(t).filter(s=>e.includes(s.status)).length}addToParentMap(t,e){let s=this.parentToSubs.get(t);s||(s=new Set,this.parentToSubs.set(t,s)),s.add(e)}removeFromParentMap(t,e){const s=this.parentToSubs.get(t);s&&(s.delete(e),s.size===0&&this.parentToSubs.delete(t))}cleanupCompletedEntries(){const t=Date.now();for(const[e,s]of this.subAgents)(s.status==="completed"||s.status==="failed"||s.status==="cancelled")&&s.endedAt&&t-s.endedAt>T&&(this.subAgents.delete(e),this.removeFromParentMap(s.parentAgentId,e))}recoverZombieEntries(){const t=Date.now();for(const[e,s]of this.subAgents)s.status==="pending"&&t-s.startedAt>m?this.recoverZombie(s,`stuck in pending >${m}ms (never started)`):s.status==="running"&&t-s.startedAt>f&&this.recoverZombie(s,`stuck in running >${f}ms (no completion)`)}async recoverZombie(t,e){if(t.status!=="pending"&&t.status!=="running")return;const s=`zombie recovered: ${e}`;t.status="failed",t.errorMessage=s,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"failed",{error:s}),t.completionResolve?.({output:"",error:s}),this.enqueueCompletion(t,"",s),this.persistFinalStatus(t,{status:"failed",errorMessage:s,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0});try{await t.runtime.stop()}catch{}}async findRecordInStore(t){for(const e of this.parentToSubs.keys()){const n=(await this.store.read(e)).subAgents.find(i=>i.subId===t);if(n)return n}}handleRuntimeEvent(t,e){const s=this.subAgents.get(t);if(!s)return;const n=s.contextSnapshot;switch(n.updatedAt=new Date().toISOString(),e?.type){case"session_started":n.currentTool="[starting]",this.emitEvent(t,"progress",{snapshot:{...n}});break;case"startup_phase":n.currentTool=`[startup:${e.data?.phase??"unknown"}]`,this.emitEvent(t,"progress",{snapshot:{...n}});break;case"mcp_status":e.data?.action==="call_tool"?(n.currentTool=e.data?.tool,this.emitEvent(t,"tool_start",{tool:n.currentTool,snapshot:{...n}})):e.data?.action==="tool_result"?(this.emitEvent(t,"tool_end",{tool:n.currentTool,snapshot:{...n}}),n.currentTool=void 0):(n.currentTool="[mcp_init]",this.emitEvent(t,"progress",{snapshot:{...n}}));break;case"skill_status":n.currentTool="[skill_loaded]",this.emitEvent(t,"progress",{snapshot:{...n}});break;case"ai_request":e.data?.estimatedContextTokens!=null&&(n.tokenUsage.input=e.data.estimatedContextTokens??n.tokenUsage.input),n.currentTool="[model_request]",this.emitEvent(t,"progress",{snapshot:{...n}});break;case"context_compaction":e.data?.action==="start"?(n.currentTool="[context_compaction]",this.emitEvent(t,"progress",{snapshot:{...n}})):e.data?.action==="end"&&n.currentTool==="[context_compaction]"&&(n.currentTool=void 0,this.emitEvent(t,"progress",{snapshot:{...n}}));break;case"turn_complete":e.data?.usage?(n.tokenUsage.input=e.data.usage.inputTokens??n.tokenUsage.input,n.tokenUsage.output=e.data.usage.outputTokens??n.tokenUsage.output,this.emitEvent(t,"progress",{snapshot:{...n}})):(e.data?.failed||e.data?.aborted)&&(n.tokenUsage.output=0);break;case"assistant_delta":n.lastAssistantText=((n.lastAssistantText??"")+(e.data?.text??"")).slice(-500),n.messageCount+=1,this.emitEvent(t,"delta",{text:e.data?.text});break;case"session_complete":n.messageCount+=1;break}}emitEvent(t,e,s){const n={type:e,subId:t,timestamp:new Date().toISOString(),data:s},i=this.subscribers.get(t);if(i)for(const r of i)try{r(n)}catch{}const o=this.subscribers.get("*");if(o)for(const r of o)try{r(n)}catch{}if(e==="tool_start"||e==="tool_end"){const r=this.subAgents.get(t);r?(console.error(`[SubAgentManager] appendEvent: subId=${t} type=${e} tool=${s.tool??"?"} parentAgentId=${r.parentAgentId}`),this.store.appendEvent(r.parentAgentId,t,n).catch(a=>{console.error(`[SubAgentManager] appendEvent FAILED: subId=${t} error=${a instanceof Error?a.message:String(a)}`)})):console.error(`[SubAgentManager] appendEvent SKIPPED (entry not found): subId=${t} type=${e}`)}}toRecord(t){return{subId:t.subId,parentAgentId:t.parentAgentId,parentSessionId:t.parentSessionId,subagentType:t.subagentType,description:t.description,prompt:t.prompt,status:t.status,result:t.result,errorMessage:t.errorMessage,startedAt:t.startedAt,endedAt:t.endedAt,durationMs:t.durationMs,contextSnapshot:t.status==="running"?t.contextSnapshot:void 0,availableTools:t.availableTools,allocatedTools:t.allocatedTools}}getContextSnapshot(t){return this.subAgents.get(t)?.contextSnapshot}}async function d(p,t,e){if(t<=0)return await p;let s;try{return await new Promise((n,i)=>{s=setTimeout(()=>i(new Error(`${e} timed out after ${t}ms`)),t),p.then(n,i)})}finally{s&&clearTimeout(s)}}export{_ as SubAgentManager};
|
|
1
|
+
import{randomUUID as S}from"node:crypto";import{ACodeRuntime as w}from"./runtime.js";const T=30*60*1e3,m=2*60*1e3,f=12*60*1e3,b=5e3,c=[100,500,2e3,8e3],E=6e4,A=10*60*1e3;class _{constructor(t){this.subAgents=new Map,this.parentToSubs=new Map,this.subscribers=new Map,this.cleanupTimer=null,this.completionQueue=[],this.completionWaiterResolve=null,this.pendingPersists=new Set,this.store=t.store,this.maxConcurrent=t.maxConcurrent??5,this.cleanupTimer=setInterval(()=>{this.cleanupCompletedEntries(),this.recoverZombieEntries()},5*60*1e3),this.cleanupTimer.unref&&this.cleanupTimer.unref(),this.store.reconcileZombies().catch(()=>{})}async spawn(t){if(this.countByStatus(t.parentAgentId,"running","pending")>=this.maxConcurrent)throw new Error(`concurrent sub-agent limit reached (${this.maxConcurrent}) for agent ${t.parentAgentId}`);const s=`sub-${S()}`,n=Date.now(),i=new AbortController,o={...t.parentConfig,sessionId:s,workingDirectory:t.workingDirectory,agentId:`${t.parentAgentId}__sub__${s}`,initialPrompt:void 0,subAgentManager:void 0,subAgentAllowedTools:t.allowedTools&&t.allowedTools.length>0?t.allowedTools:void 0,...t.parentConfig.subAgentModel?{model:t.parentConfig.subAgentModel}:{},...t.parentConfig.subAgentEffort?{effort:t.parentConfig.subAgentEffort}:{},subAgentModel:void 0,subAgentEffort:void 0},r=new w(o),a={subId:s,parentAgentId:t.parentAgentId,parentSessionId:t.parentSessionId,subagentType:t.subagentType,description:t.description,prompt:t.prompt,status:"pending",startedAt:n,runtime:r,abortController:i,silent:t.silent,contextSnapshot:{tokenUsage:{input:0,output:0},messageCount:0,updatedAt:new Date().toISOString()},availableTools:[],...t.allowedTools&&t.allowedTools.length>0?{allocatedTools:t.allowedTools}:{}};this.subAgents.set(s,a),this.addToParentMap(t.parentAgentId,s);const u=this.toRecord(a);return await this.store.upsert(t.parentAgentId,u),r.on("event",l=>{this.handleRuntimeEvent(s,l)}),this.emitEvent(s,"spawned",{}),s}async start(t){const e=this.subAgents.get(t);if(!e)throw new Error(`sub-agent not found: ${t}`);if(e.status!=="pending")throw new Error(`sub-agent ${t} cannot start from status: ${e.status}`);e.completionPromise=new Promise((s,n)=>{e.completionResolve=s,e.completionReject=n}),this.runEntryToCompletion(e).catch(()=>{})}async startWithRecheck(t,e,s=3){const n=this.subAgents.get(t);if(!n)throw new Error(`sub-agent not found: ${t}`);if(n.status!=="pending")throw new Error(`sub-agent ${t} cannot start from status: ${n.status}`);n.completionPromise=new Promise((i,o)=>{n.completionResolve=i,n.completionReject=o}),this.runEntryToCompletionWithRecheck(n,e,s).catch(()=>{})}async awaitCompletion(t,e=0){if(t.length===0)return[];const s=[],n=t.map(async o=>{const r=this.subAgents.get(o);if(!r){const u=await this.findRecordInStore(o);u?s.push({subId:o,output:u.result??"",error:u.errorMessage,status:u.status}):s.push({subId:o,output:"",error:`sub-agent not found: ${o}`,status:"failed"});return}r.awaited=!0,r.status==="pending"&&await this.start(o);const a=r.completionPromise??Promise.resolve({output:"",error:"not started"});try{const u=await a;s.push({subId:o,output:u.output,error:u.error,status:r.status})}catch(u){s.push({subId:o,output:"",error:u instanceof Error?u.message:String(u),status:r.status})}}),i=new Set(t);for(let o=this.completionQueue.length-1;o>=0;o--)i.has(this.completionQueue[o].subId)&&this.completionQueue.splice(o,1);return e>0?await Promise.race([Promise.allSettled(n),new Promise(o=>setTimeout(()=>o(),e))]):await Promise.allSettled(n),s}async runEntryToCompletion(t){const e=[];let s=!1,n;const i=o=>{if(o)switch(o.type){case"assistant_delta":typeof o.data?.text=="string"&&e.push(o.data.text);break;case"turn_complete":o.data?.failed&&(s=!0);break;case"error":typeof o.data?.message=="string"&&(n=o.data.message);break}};t.runtime.on("event",i),t.status="running",t.contextSnapshot.currentTool="[starting]",t.contextSnapshot.updatedAt=new Date().toISOString(),this.emitEvent(t.subId,"running",{snapshot:{...t.contextSnapshot}});try{await d(this.store.updateStatus(t.parentAgentId,t.subId,{status:"running"}),b,`sub-agent ${t.subId} store.updateStatus(running)`)}catch(o){console.error(`[SubAgentManager] store.updateStatus(running) failed for subId=${t.subId}: ${o instanceof Error?o.message:String(o)}`)}try{if(await t.runtime.start(),t.availableTools=t.runtime.getAvailableTools(),await t.runtime.submit(t.prompt),s)throw new Error(n??"sub-agent turn failed");const o=e.join("");t.status="completed",t.result=o,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"completed",{result:o}),t.completionResolve?.({output:o}),this.enqueueCompletion(t,o,void 0),this.persistFinalStatus(t,{status:"completed",result:o,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}catch(o){const r=o instanceof Error?o.message:String(o);t.status="failed",t.errorMessage=r,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"failed",{error:r}),t.completionResolve?.({output:"",error:r}),this.enqueueCompletion(t,"",r),this.persistFinalStatus(t,{status:"failed",errorMessage:r,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}finally{try{t.runtime.removeListener?.("event",i)}catch{}try{await t.runtime.stop()}catch{}}}async runEntryToCompletionWithRecheck(t,e,s){const n=[];let i=!1,o;const r=a=>{if(a)switch(a.type){case"assistant_delta":typeof a.data?.text=="string"&&n.push(a.data.text);break;case"turn_complete":a.data?.failed&&(i=!0);break;case"error":typeof a.data?.message=="string"&&(o=a.data.message);break}};t.runtime.on("event",r),t.status="running",t.contextSnapshot.currentTool="[starting]",t.contextSnapshot.updatedAt=new Date().toISOString(),this.emitEvent(t.subId,"running",{snapshot:{...t.contextSnapshot}});try{await d(this.store.updateStatus(t.parentAgentId,t.subId,{status:"running"}),b,`sub-agent ${t.subId} store.updateStatus(running)`)}catch(a){console.error(`[SubAgentManager] store.updateStatus(running) failed for subId=${t.subId}: ${a instanceof Error?a.message:String(a)}`)}try{if(await d(t.runtime.start(),E,`sub-agent ${t.subId} runtime.start()`),t.contextSnapshot.currentTool="[submitting]",t.contextSnapshot.updatedAt=new Date().toISOString(),t.availableTools=t.runtime.getAvailableTools(),this.emitEvent(t.subId,"progress",{snapshot:{...t.contextSnapshot}}),await d(t.runtime.submit(t.prompt),A,`sub-agent ${t.subId} runtime.submit() turn=1`),i)throw new Error(o??"sub-agent turn failed");let a=1;for(;a<=s;){let l;try{l=await e(n.join(""),a)}catch(g){console.error(`[SubAgentManager] recheck threw error for subId=${t.subId} turn=${a}, treating as done:`,g instanceof Error?g.message:String(g));break}if(l.done)break;const h=l.continueMessage??"\u7ECF\u68C0\u67E5\uFF0C\u672A\u5B8C\u6210\u5904\u7406\uFF0C\u8BF7\u7EE7\u7EED\u3002";if(i=!1,o=void 0,console.error(`[SubAgentManager] recheck not done for subId=${t.subId} turn=${a}/${s}, injecting continue message (${h.length} chars)`),await d(t.runtime.submit(h),A,`sub-agent ${t.subId} runtime.submit() recheck turn=${a+1}`),i)throw new Error(o??`sub-agent turn ${a+1} failed during recheck continuation`);a++}a>s&&console.error(`[SubAgentManager] recheck reached maxRetries=${s} for subId=${t.subId}, completing with potentially unfinished work`);const u=n.join("");t.status="completed",t.result=u,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"completed",{result:u}),t.completionResolve?.({output:u}),this.enqueueCompletion(t,u,void 0),this.persistFinalStatus(t,{status:"completed",result:u,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}catch(a){const u=a instanceof Error?a.message:String(a);t.status="failed",t.errorMessage=u,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"failed",{error:u}),t.completionResolve?.({output:"",error:u}),this.enqueueCompletion(t,"",u),this.persistFinalStatus(t,{status:"failed",errorMessage:u,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0})}finally{try{t.runtime.removeListener?.("event",r)}catch{}try{await t.runtime.stop()}catch{}}}async runToCompletion(t){const e=this.subAgents.get(t);if(!e)throw new Error(`sub-agent not found: ${t}`);if(e.status==="running")throw new Error(`sub-agent already running: ${t}`);return e.status!=="pending"&&(e.status="pending"),await this.start(t),await e.completionPromise??{output:"",error:"not started"}}async abort(t){const e=this.subAgents.get(t);if(e&&!(e.status==="completed"||e.status==="failed"||e.status==="cancelled")){e.abortController.abort();try{await e.runtime.abort()}catch{}e.status="cancelled",e.endedAt=Date.now(),e.durationMs=e.endedAt-e.startedAt,this.emitEvent(t,"cancelled",{}),e.completionResolve?.({output:"",error:"aborted"}),this.enqueueCompletion(e,"","aborted"),this.persistFinalStatus(e,{status:"cancelled",endedAt:e.endedAt,durationMs:e.durationMs,availableTools:e.availableTools,contextSnapshot:void 0})}}getSubAgent(t){return this.subAgents.get(t)}listByParent(t){const e=this.parentToSubs.get(t);return e?Array.from(e).map(s=>this.subAgents.get(s)).filter(s=>s!==void 0):[]}listActiveByParent(t){return this.listByParent(t).filter(e=>(e.status==="pending"||e.status==="running")&&!e.silent)}takeCompletedSubAgents(){return this.completionQueue.length===0?[]:this.completionQueue.splice(0)}waitForAnyCompletion(){if(this.completionQueue.length>0){const n=this.completionQueue.shift();return{promise:Promise.resolve(n),cancel:()=>{}}}let t=!1;return{promise:new Promise(n=>{this.completionWaiterResolve=i=>{t||n(i)}}),cancel:()=>{t=!0,this.completionWaiterResolve=null}}}subscribe(t,e){let s=this.subscribers.get(t);return s||(s=new Set,this.subscribers.set(t,s)),s.add(e),()=>{s?.delete(e),s&&s.size===0&&this.subscribers.delete(t)}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null);const t=Array.from(this.subAgents.values());await Promise.allSettled(t.map(e=>this.abort(e.subId))),await this.flushPendingPersists(),this.subAgents.clear(),this.parentToSubs.clear(),this.subscribers.clear()}persistFinalStatus(t,e){const s=(async()=>{let n;for(let i=0;i<=c.length;i++)try{await this.store.updateStatus(t.parentAgentId,t.subId,e);return}catch(o){n=o,i<c.length&&await new Promise(r=>setTimeout(r,c[i]))}console.error(`[SubAgentManager] persistFinalStatus(${e.status}) failed after ${c.length+1} attempts for subId=${t.subId}: ${n instanceof Error?n.message:String(n)}`)})();return this.pendingPersists.add(s),s.finally(()=>this.pendingPersists.delete(s)),s}async flushPendingPersists(){this.pendingPersists.size!==0&&await Promise.allSettled(Array.from(this.pendingPersists))}enqueueCompletion(t,e,s){if(t.silent||t.awaited)return;const n={subId:t.subId,subagentType:t.subagentType,description:t.description,status:t.status,output:e,error:s,durationMs:t.durationMs};if(this.completionQueue.push(n),this.completionWaiterResolve){const i=this.completionWaiterResolve;this.completionWaiterResolve=null;const o=this.completionQueue.pop();i(o??n)}}countByStatus(t,...e){return this.listByParent(t).filter(s=>e.includes(s.status)).length}addToParentMap(t,e){let s=this.parentToSubs.get(t);s||(s=new Set,this.parentToSubs.set(t,s)),s.add(e)}removeFromParentMap(t,e){const s=this.parentToSubs.get(t);s&&(s.delete(e),s.size===0&&this.parentToSubs.delete(t))}cleanupCompletedEntries(){const t=Date.now();for(const[e,s]of this.subAgents)(s.status==="completed"||s.status==="failed"||s.status==="cancelled")&&s.endedAt&&t-s.endedAt>T&&(this.subAgents.delete(e),this.removeFromParentMap(s.parentAgentId,e))}recoverZombieEntries(){const t=Date.now();for(const[e,s]of this.subAgents)s.status==="pending"&&t-s.startedAt>m?this.recoverZombie(s,`stuck in pending >${m}ms (never started)`):s.status==="running"&&t-s.startedAt>f&&this.recoverZombie(s,`stuck in running >${f}ms (no completion)`)}async recoverZombie(t,e){if(t.status!=="pending"&&t.status!=="running")return;const s=`zombie recovered: ${e}`;t.status="failed",t.errorMessage=s,t.endedAt=Date.now(),t.durationMs=t.endedAt-t.startedAt,this.emitEvent(t.subId,"failed",{error:s}),t.completionResolve?.({output:"",error:s}),this.enqueueCompletion(t,"",s),this.persistFinalStatus(t,{status:"failed",errorMessage:s,endedAt:t.endedAt,durationMs:t.durationMs,availableTools:t.availableTools,contextSnapshot:void 0});try{await t.runtime.stop()}catch{}}async findRecordInStore(t){for(const e of this.parentToSubs.keys()){const n=(await this.store.read(e)).subAgents.find(i=>i.subId===t);if(n)return n}}handleRuntimeEvent(t,e){const s=this.subAgents.get(t);if(!s)return;const n=s.contextSnapshot;switch(n.updatedAt=new Date().toISOString(),e?.type){case"session_started":n.currentTool="[starting]",this.emitEvent(t,"progress",{snapshot:{...n}});break;case"startup_phase":n.currentTool=`[startup:${e.data?.phase??"unknown"}]`,this.emitEvent(t,"progress",{snapshot:{...n}});break;case"mcp_status":e.data?.action==="call_tool"?(n.currentTool=e.data?.tool,this.emitEvent(t,"tool_start",{tool:n.currentTool,snapshot:{...n}})):e.data?.action==="tool_result"?(this.emitEvent(t,"tool_end",{tool:n.currentTool,snapshot:{...n}}),n.currentTool=void 0):(n.currentTool="[mcp_init]",this.emitEvent(t,"progress",{snapshot:{...n}}));break;case"skill_status":n.currentTool="[skill_loaded]",this.emitEvent(t,"progress",{snapshot:{...n}});break;case"ai_request":e.data?.estimatedContextTokens!=null&&(n.tokenUsage.input=e.data.estimatedContextTokens??n.tokenUsage.input),n.currentTool="[model_request]",this.emitEvent(t,"progress",{snapshot:{...n}});break;case"context_compaction":e.data?.action==="start"?(n.currentTool="[context_compaction]",this.emitEvent(t,"progress",{snapshot:{...n}})):e.data?.action==="end"&&n.currentTool==="[context_compaction]"&&(n.currentTool=void 0,this.emitEvent(t,"progress",{snapshot:{...n}}));break;case"turn_complete":e.data?.usage?(n.tokenUsage.input=e.data.usage.inputTokens??n.tokenUsage.input,n.tokenUsage.output=e.data.usage.outputTokens??n.tokenUsage.output,this.emitEvent(t,"progress",{snapshot:{...n}})):(e.data?.failed||e.data?.aborted)&&(n.tokenUsage.output=0);break;case"assistant_delta":n.lastAssistantText=((n.lastAssistantText??"")+(e.data?.text??"")).slice(-500),n.messageCount+=1,this.emitEvent(t,"delta",{text:e.data?.text});break;case"session_complete":n.messageCount+=1;break}}emitEvent(t,e,s){const n={type:e,subId:t,timestamp:new Date().toISOString(),data:s},i=this.subscribers.get(t);if(i)for(const r of i)try{r(n)}catch{}const o=this.subscribers.get("*");if(o)for(const r of o)try{r(n)}catch{}if(e==="tool_start"||e==="tool_end"){const r=this.subAgents.get(t);r?(console.error(`[SubAgentManager] appendEvent: subId=${t} type=${e} tool=${s.tool??"?"} parentAgentId=${r.parentAgentId}`),this.store.appendEvent(r.parentAgentId,t,n).catch(a=>{console.error(`[SubAgentManager] appendEvent FAILED: subId=${t} error=${a instanceof Error?a.message:String(a)}`)})):console.error(`[SubAgentManager] appendEvent SKIPPED (entry not found): subId=${t} type=${e}`)}}toRecord(t){return{subId:t.subId,parentAgentId:t.parentAgentId,parentSessionId:t.parentSessionId,subagentType:t.subagentType,description:t.description,prompt:t.prompt,status:t.status,result:t.result,errorMessage:t.errorMessage,startedAt:t.startedAt,endedAt:t.endedAt,durationMs:t.durationMs,contextSnapshot:t.status==="running"?t.contextSnapshot:void 0,availableTools:t.availableTools,allocatedTools:t.allocatedTools}}getContextSnapshot(t){return this.subAgents.get(t)?.contextSnapshot}}async function d(p,t,e){if(t<=0)return await p;let s;try{return await new Promise((n,i)=>{s=setTimeout(()=>i(new Error(`${e} timed out after ${t}ms`)),t),p.then(n,i)})}finally{s&&clearTimeout(s)}}export{_ as SubAgentManager};
|
|
2
2
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{promises as c}from"node:fs";import
|
|
2
|
-
`,"utf-8")}async readEvents(e,r){const s=this.eventsFilePath(e,r);try{const t=await c.readFile(s,"utf-8"),
|
|
3
|
-
`)){const
|
|
1
|
+
import{promises as c}from"node:fs";import u from"node:path";import{renameWithRetry as f}from"./fs-utils.js";import{resolveAcodeHome as p}from"./paths.js";class w{constructor(){this.writeChain=Promise.resolve(),this.dir=u.join(p(),"sub-agents")}filePath(e){const r=String(e).replace(/[^a-zA-Z0-9_-]/g,"_");return u.join(this.dir,`${r}.json`)}eventsFilePath(e,r){const s=String(e).replace(/[^a-zA-Z0-9_-]/g,"_"),t=String(r).replace(/[^a-zA-Z0-9_-]/g,"_");return u.join(this.dir,`${s}.${t}.events.jsonl`)}async read(e){const r={agentId:e,updatedAt:"",subAgents:[]};try{const s=await c.readFile(this.filePath(e),"utf-8"),t=JSON.parse(s);return{agentId:e,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:"",subAgents:Array.isArray(t.subAgents)?t.subAgents.filter(h).sort((n,o)=>o.startedAt-n.startedAt):[]}}catch(s){if(s&&s.code==="ENOENT"||s instanceof SyntaxError)return r;throw s}}async get(e,r){return(await this.read(e)).subAgents.find(t=>t.subId===r)??null}async write(e,r){const s=this.filePath(e),t=this.writeChain.then(async()=>{await c.mkdir(this.dir,{recursive:!0});const n={agentId:e,updatedAt:new Date().toISOString(),subAgents:r.map(({events:i,...d})=>d).sort((i,d)=>d.startedAt-i.startedAt)},o=`${s}.tmp`;await c.writeFile(o,JSON.stringify(n,null,2),"utf-8"),await f(o,s)});this.writeChain=t.catch(()=>{}),await t}async upsert(e,r){const s=await this.read(e),t=s.subAgents.findIndex(n=>n.subId===r.subId);t>=0?s.subAgents[t]=r:s.subAgents.unshift(r),await this.write(e,s.subAgents)}async updateStatus(e,r,s){const t=await this.read(e),n=t.subAgents.findIndex(o=>o.subId===r);n<0||(t.subAgents[n]={...t.subAgents[n],...s},await this.write(e,t.subAgents))}async list(e){return(await this.read(e)).subAgents}async appendEvent(e,r,s){const t=this.eventsFilePath(e,r);await c.mkdir(this.dir,{recursive:!0}),await c.appendFile(t,JSON.stringify(s)+`
|
|
2
|
+
`,"utf-8")}async readEvents(e,r){const s=this.eventsFilePath(e,r);try{const t=await c.readFile(s,"utf-8"),n=[];for(const o of t.split(`
|
|
3
|
+
`)){const i=o.trim();if(i)try{n.push(JSON.parse(i))}catch{}}return n}catch(t){if(t&&t.code==="ENOENT"){const n=await this.get(e,r);return Array.isArray(n?.events)?n.events:[]}throw t}}async reconcileZombies(){let e=0,r;try{r=await c.readdir(this.dir)}catch{return 0}for(const s of r){if(!s.endsWith(".json"))continue;const t=s.replace(/\.json$/,"");try{const n=await this.read(t);let o=!1;for(const i of n.subAgents)(i.status==="running"||i.status==="pending")&&(i.status="failed",i.errorMessage=i.errorMessage??"bridge restarted (zombie reconcile)",i.endedAt||(i.endedAt=i.startedAt,i.durationMs=0),o=!0,e++);o&&await this.write(t,n.subAgents)}catch{}}return e}}function h(a){return a!==null&&typeof a=="object"&&typeof a.subId=="string"&&typeof a.parentAgentId=="string"&&typeof a.parentSessionId=="string"&&typeof a.subagentType=="string"&&typeof a.description=="string"&&typeof a.prompt=="string"&&typeof a.status=="string"&&typeof a.startedAt=="number"}export{w as SubAgentStore};
|
|
4
4
|
|
|
@@ -1,26 +1,20 @@
|
|
|
1
|
-
import{resolveToolAllocation as
|
|
1
|
+
import{PRESET_CORE as d,PRESET_EXPLORE as c,resolveToolAllocation as g,ToolAllocationError as b}from"./tool-allocation.js";const h=`Launch a new sub-agent to handle a task autonomously (non-blocking).
|
|
2
2
|
|
|
3
3
|
Use this tool to:
|
|
4
4
|
1. Delegate research, exploration, or implementation work to a specialized sub-agent
|
|
5
5
|
2. Run multiple independent tasks in parallel (multiple tool calls in one message)
|
|
6
6
|
3. Keep the main context window focused by offloading detailed work
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
-
|
|
10
|
-
- "
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
- Custom allocation: each item is a category (whole suite, e.g. "office",
|
|
19
|
-
"browser", "desktop") or an exact tool path (e.g. "default.read_file").
|
|
20
|
-
Call list_sub_agent_tools to see all allocatable categories and tool paths.
|
|
21
|
-
- Templates can mix with custom items: ["general", "browser"]
|
|
22
|
-
When 'tools' is provided without subagent_type, the type defaults to "general"
|
|
23
|
-
("explore" template defaults to "explore").
|
|
8
|
+
Tool allocation (the 'tools' parameter) \u2014 elements combine by union:
|
|
9
|
+
- Presets (start with '@'):
|
|
10
|
+
- "${c}": read-only set (read/grep/Bash/symbols etc., plus memory MCP tools).
|
|
11
|
+
Omitting 'tools' means ["${c}"] \u2014 read-only default
|
|
12
|
+
- "${d}": all core default tools (read/write/edit/grep/Bash/todo/terminal; no suites/MCP)
|
|
13
|
+
- Category name allocates a whole suite: "office", "browser", "desktop"
|
|
14
|
+
- Exact tool path allocates one tool: "default.read_file"
|
|
15
|
+
- Mix freely: ["${d}", "browser"]
|
|
16
|
+
- Unknown presets/categories are rejected with an error listing what is available;
|
|
17
|
+
call list_sub_agent_tools to see all allocatable categories and tool paths first.
|
|
24
18
|
|
|
25
19
|
This tool is NON-BLOCKING: it returns immediately with a subId after spawn.
|
|
26
20
|
The sub-agent starts automatically and runs in the background.
|
|
@@ -33,13 +27,13 @@ Guidelines:
|
|
|
33
27
|
- Write a clear, self-contained prompt (the sub-agent starts with a fresh context)
|
|
34
28
|
- Launch multiple agents concurrently when possible (multiple tool calls in one message)
|
|
35
29
|
- Sub-agents cannot spawn further sub-agents (no nesting)
|
|
36
|
-
- Always call await_complete (with this subId in 'sub_agent_ids') before reporting completion to the user`;function
|
|
37
|
-
tool allocation: ${
|
|
38
|
-
mode:
|
|
39
|
-
|
|
30
|
+
- Always call await_complete (with this subId in 'sub_agent_ids') before reporting completion to the user`;function m(n){return{kind:"builtin",toolName:"sub_agent",exposedName:"sub_agent",description:h,inputSchema:{type:"object",properties:{description:{type:"string",description:"A short (3-5 words) description of the task."},prompt:{type:"string",description:"The task for the sub-agent to perform (self-contained, fresh context)."},tools:{type:"array",items:{type:"string"},description:`Optional tool allocation, elements combine by union. Presets: '${c}' (read-only default), '${d}' (all core default tools). Or category names ('office', 'browser') / exact tool paths ('default.read_file'). Omit for read-only mode. See list_sub_agent_tools for the full catalog.`}},required:["description","prompt"]},async execute(r){if("subagent_type"in r)return{title:"sub_agent validation error",output:"Invalid input: 'subagent_type' has been removed. Use 'tools' instead: omit for read-only mode, or pass presets ('@explore', '@core') / categories / exact tool paths.",metadata:{error:!0}};const e=typeof r.description=="string"?r.description.trim():"",t=typeof r.prompt=="string"?r.prompt.trim():"";if(!e)return{title:"sub_agent validation error",output:"Invalid input: 'description' is required and must be non-empty.",metadata:{error:!0}};if(!t)return{title:"sub_agent validation error",output:"Invalid input: 'prompt' is required and must be non-empty.",metadata:{error:!0}};const o=r.tools,s=typeof o=="string"?[o]:Array.isArray(o)?o.filter(i=>typeof i=="string"):[];let a,l;try{const i=await n.listSubAgentToolCatalog(),u=g(s,i);a=u.patterns,l=u.label}catch(i){if(i instanceof b)return{title:"sub_agent validation error",output:`Invalid input: ${i.message}`,metadata:{error:!0}};throw i}const p=a.length>0;try{const{subId:i}=await n.spawnSubAgent({subagentType:l,description:e,prompt:t,...p?{allowedTools:a}:{}}),u=p?`
|
|
31
|
+
tool allocation (${l}): ${a.join(", ")} (whitelist mode \u2014 only matching tools are exposed)`:`
|
|
32
|
+
mode: ${l} (no allocatable tools found in catalog)`;return{title:e,output:`sub_agent spawned: ${i}
|
|
33
|
+
type: ${l}${u}
|
|
40
34
|
|
|
41
35
|
Call await_complete with this subId in 'sub_agent_ids' to get the result.
|
|
42
|
-
Call get_sub_agent_status to check progress.`,metadata:{subId:i,spawned:!0,...
|
|
36
|
+
Call get_sub_agent_status to check progress.`,metadata:{subId:i,spawned:!0,typeLabel:l,...p?{allocatedTools:a}:{}}}}catch(i){const u=i instanceof Error?i.message:String(i);return{title:e,output:`Failed to spawn sub-agent: ${u}`,metadata:{error:!0}}}}}}const _=`List all sub-agents for the current agent.
|
|
43
37
|
|
|
44
38
|
Returns two arrays:
|
|
45
39
|
- running: sub-agents currently in pending/running state
|
|
@@ -48,8 +42,8 @@ Returns two arrays:
|
|
|
48
42
|
Use this to:
|
|
49
43
|
1. Check which sub-agents are still running
|
|
50
44
|
2. Review completed sub-agent history
|
|
51
|
-
3. Find a subId before calling await_complete (sub_agent_ids) or get_sub_agent_status`;function
|
|
52
|
-
`),metadata:{runningCount:e.length,historyCount:t.length}}}catch(e){return{title:"list_sub_agents error",output:`Failed to list sub-agents: ${e instanceof Error?e.message:String(e)}`,metadata:{error:!0}}}}}}const
|
|
45
|
+
3. Find a subId before calling await_complete (sub_agent_ids) or get_sub_agent_status`;function f(n){return{kind:"builtin",toolName:"list_sub_agents",exposedName:"list_sub_agents",description:_,inputSchema:{type:"object",properties:{}},async execute(r){try{const{running:e,history:t}=await n.listSubAgents(),o=a=>{const l=a.durationMs!==void 0?`${(a.durationMs/1e3).toFixed(1)}s`:a.endedAt?`${((a.endedAt-a.startedAt)/1e3).toFixed(1)}s`:"ongoing";return` - ${a.subId} [${a.status}] (${l}) ${a.description}`},s=[];return s.push(`Running (${e.length}):`),e.length===0?s.push(" (none)"):e.forEach(a=>s.push(o(a))),s.push(""),s.push(`History (${t.length}):`),t.length===0?s.push(" (none)"):t.forEach(a=>s.push(o(a))),{title:"sub-agents list",output:s.join(`
|
|
46
|
+
`),metadata:{runningCount:e.length,historyCount:t.length}}}catch(e){return{title:"list_sub_agents error",output:`Failed to list sub-agents: ${e instanceof Error?e.message:String(e)}`,metadata:{error:!0}}}}}}const y=`Get the current status and context snapshot of a sub-agent.
|
|
53
47
|
|
|
54
48
|
Returns:
|
|
55
49
|
- status: pending/running/completed/failed/cancelled
|
|
@@ -60,9 +54,9 @@ Returns:
|
|
|
60
54
|
- result: final output (if completed)
|
|
61
55
|
- error: error message (if failed)
|
|
62
56
|
|
|
63
|
-
Use this to check progress of a running sub-agent before awaiting it.`;function
|
|
57
|
+
Use this to check progress of a running sub-agent before awaiting it.`;function w(n){return{kind:"builtin",toolName:"get_sub_agent_status",exposedName:"get_sub_agent_status",description:y,inputSchema:{type:"object",properties:{sub_id:{type:"string",description:"The sub-agent ID returned by sub_agent tool."}},required:["sub_id"]},async execute(r){const e=typeof r.sub_id=="string"?r.sub_id.trim():"";if(!e)return{title:"get_sub_agent_status validation error",output:"Invalid input: 'sub_id' is required.",metadata:{error:!0}};try{const t=await n.getSubAgentStatus(e);if(!t)return{title:"sub-agent not found",output:`sub-agent not found: ${e}`,metadata:{subId:e,error:!0}};const o=[];if(o.push(`subId: ${t.subId}`),o.push(`type: ${t.subagentType}`),o.push(`description: ${t.description}`),o.push(`status: ${t.status}`),t.startedAt&&o.push(`startedAt: ${new Date(t.startedAt).toISOString()}`),t.endedAt&&o.push(`endedAt: ${new Date(t.endedAt).toISOString()}`),t.durationMs!==void 0&&o.push(`duration: ${(t.durationMs/1e3).toFixed(2)}s`),t.contextSnapshot){if(o.push(""),o.push("Context:"),t.contextSnapshot.currentTool&&o.push(` currentTool: ${t.contextSnapshot.currentTool}`),t.contextSnapshot.lastAssistantText){const s=t.contextSnapshot.lastAssistantText;o.push(` lastOutput: ${s.length>200?s.slice(-200)+"...":s}`)}o.push(` tokens: input=${t.contextSnapshot.tokenUsage.input}, output=${t.contextSnapshot.tokenUsage.output}`),o.push(` messages: ${t.contextSnapshot.messageCount}`),o.push(` updatedAt: ${t.contextSnapshot.updatedAt}`)}if(t.result){o.push(""),o.push("Result:");const s=t.result;o.push(s.length>500?s.slice(0,500)+`
|
|
64
58
|
... (truncated)`:s)}return t.errorMessage&&(o.push(""),o.push(`Error: ${t.errorMessage}`)),{title:`status: ${t.description}`,output:o.join(`
|
|
65
|
-
`),metadata:{subId:t.subId,status:t.status}}}catch(t){return{title:"get_sub_agent_status error",output:`Failed to get status: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:e,error:!0}}}}}}const
|
|
59
|
+
`),metadata:{subId:t.subId,status:t.status}}}catch(t){return{title:"get_sub_agent_status error",output:`Failed to get status: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:e,error:!0}}}}}}const S=`Abort a running sub-agent.
|
|
66
60
|
|
|
67
61
|
Use this to cancel a sub-agent that is taking too long or is no longer needed.
|
|
68
62
|
Only pending or running sub-agents can be aborted; completed/failed/cancelled are no-ops.
|
|
@@ -70,19 +64,21 @@ Only pending or running sub-agents can be aborted; completed/failed/cancelled ar
|
|
|
70
64
|
After abort:
|
|
71
65
|
- The sub-agent's status becomes 'cancelled'
|
|
72
66
|
- Its completionPromise resolves with error='aborted'
|
|
73
|
-
- Any await_complete waiting on it (with this subId in 'sub_agent_ids') will return immediately`;function
|
|
67
|
+
- Any await_complete waiting on it (with this subId in 'sub_agent_ids') will return immediately`;function $(n){return{kind:"builtin",toolName:"abort_sub_agent",exposedName:"abort_sub_agent",description:S,inputSchema:{type:"object",properties:{sub_id:{type:"string",description:"The sub-agent ID to abort."}},required:["sub_id"]},async execute(r){const e=typeof r.sub_id=="string"?r.sub_id.trim():"";if(!e)return{title:"abort_sub_agent validation error",output:"Invalid input: 'sub_id' is required.",metadata:{error:!0}};try{return await n.abortSubAgent(e),{title:"sub-agent aborted",output:`sub-agent ${e} has been aborted.`,metadata:{subId:e,aborted:!0}}}catch(t){return{title:"abort_sub_agent error",output:`Failed to abort sub-agent: ${t instanceof Error?t.message:String(t)}`,metadata:{subId:e,error:!0}}}}}}const T=`List all tool presets, categories and tools that can be allocated to sub-agents.
|
|
74
68
|
|
|
75
|
-
|
|
69
|
+
Output starts with the built-in '@' presets, then categories (suite). Each category
|
|
70
|
+
line shows its tool short names:
|
|
76
71
|
- default: core file/shell tools (read_file, write_file, grep, Bash, ...)
|
|
77
72
|
- <suite>: suite tools (e.g. browser: launch, navigate, click, ...)
|
|
78
73
|
- <mcp-server>: MCP tools under that server (e.g. memory: read_memory, ...)
|
|
79
74
|
|
|
80
75
|
Use this before spawning a sub-agent with the 'tools' parameter:
|
|
76
|
+
- Pass a preset to use a built-in bundle: tools: ["@explore"] or ["@core"]
|
|
81
77
|
- Pass a category name to allocate the whole suite: tools: ["office"]
|
|
82
78
|
- Pass an exact tool path for one tool: tools: ["default.read_file"]
|
|
83
|
-
-
|
|
79
|
+
- Elements combine by union: ["@core", "browser"]
|
|
84
80
|
|
|
85
81
|
If a tool you need is not listed, it cannot be allocated (the sub-agent pool
|
|
86
|
-
equals the current agent's tool set).`;function
|
|
87
|
-
`),metadata:{categories:e.length}}}catch(e){return{title:"list_sub_agent_tools error",output:`Failed to list allocatable tools: ${e instanceof Error?e.message:String(e)}`,metadata:{error:!0}}}}}}function
|
|
82
|
+
equals the current agent's tool set).`;function x(n){return{kind:"builtin",toolName:"list_sub_agent_tools",exposedName:"list_sub_agent_tools",description:T,inputSchema:{type:"object",properties:{}},async execute(r){try{const e=await n.listSubAgentToolCatalog();if(e.length===0)return{title:"allocatable tools",output:"No allocatable tools found (tool catalog is empty).",metadata:{categories:0}};const t=["Presets (for sub_agent 'tools' param):",` ${c} \u2014 read-only set (default category minus write tools + memory MCP tools); omitting 'tools' means ["${c}"]`,` ${d} \u2014 all core default tools (no suites/MCP)`,"","Allocatable tool categories:",""];for(const o of e)t.push(`[${o.category}] ${o.kind} (${o.tools.length}):`),t.push(` ${o.tools.join(", ")}`);return t.push(""),t.push("Usage:"),t.push(`- tools: ["${d}"] \u2192 all core default tools`),t.push(`- tools: ["<category>"] \u2192 all tools in that category (e.g. ["${e[0].category}"])`),t.push(`- tools: ["<category>.<tool>"] \u2192 exactly that tool (e.g. ["${e[0].category}.${e[0].tools[0]??"tool"}"])`),t.push('- elements combine by union, e.g. ["@core", "browser"]'),t.push(`- omit tools \u2192 read-only mode (\u2261 ["${c}"])`),{title:"allocatable tools",output:t.join(`
|
|
83
|
+
`),metadata:{categories:e.length}}}catch(e){return{title:"list_sub_agent_tools error",output:`Failed to list allocatable tools: ${e instanceof Error?e.message:String(e)}`,metadata:{error:!0}}}}}}function I(n){return[m(n),f(n),w(n),$(n),x(n)]}export{$ as createAbortSubAgentTool,w as createGetSubAgentStatusTool,x as createListSubAgentToolsTool,f as createListSubAgentsTool,m as createSubAgentTool,I as createSubAgentTools};
|
|
88
84
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{promises as e}from"node:fs";import
|
|
1
|
+
import{promises as e}from"node:fs";import n from"node:path";import{renameWithRetry as d}from"./fs-utils.js";import{resolveAcodeHome as h}from"./paths.js";class y{constructor(){this.writeChain=Promise.resolve(),this.todosDir=n.join(h(),"todos")}filePath(r){const i=String(r).replace(/[^a-zA-Z0-9_-]/g,"_");return n.join(this.todosDir,`${i}.json`)}async read(r){const i={agentId:r,updatedAt:"",background:"",todos:[]};try{const o=await e.readFile(this.filePath(r),"utf-8"),t=JSON.parse(o);return{agentId:r,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:"",background:typeof t.background=="string"?t.background:"",todos:Array.isArray(t.todos)?t.todos:[]}}catch(o){if(o&&o.code==="ENOENT"||o instanceof SyntaxError)return i;throw o}}async write(r,i,o){const t=this.filePath(r),s=this.writeChain.then(async()=>{await e.mkdir(this.todosDir,{recursive:!0});const c={agentId:r,updatedAt:new Date().toISOString(),background:i,todos:o},a=`${t}.tmp`;await e.writeFile(a,JSON.stringify(c,null,2),"utf-8"),await d(a,t)});this.writeChain=s.catch(()=>{}),await s}}export{y as TodoStore};
|
|
2
2
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
|
|
2
|
+
import type { SubAgentType } from "./sub-agent-types.js";
|
|
2
3
|
|
|
3
4
|
export declare const DEFAULT_TOOL_CATEGORY = "default";
|
|
4
5
|
|
|
@@ -43,13 +44,26 @@ export interface ToolCatalogEntry {
|
|
|
43
44
|
|
|
44
45
|
export declare function buildToolCatalog(tools: readonly AllocatableToolShape[]): ToolCatalogEntry[];
|
|
45
46
|
|
|
46
|
-
export declare const
|
|
47
|
+
export declare const EXPLORE_READONLY_DENIED_TOOLS: Set<string>;
|
|
48
|
+
|
|
49
|
+
export declare const SUB_AGENT_ALLOWED_MCP_TOOLS: Set<string>;
|
|
50
|
+
|
|
51
|
+
export declare const PRESET_EXPLORE = "@explore";
|
|
52
|
+
|
|
53
|
+
export declare const PRESET_CORE = "@core";
|
|
54
|
+
|
|
55
|
+
export declare const TYPE_LABEL_CUSTOM = "custom";
|
|
56
|
+
|
|
57
|
+
export declare class ToolAllocationError extends Error {
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export declare function deriveTypeLabel(rawTokens: readonly string[]): SubAgentType;
|
|
47
61
|
|
|
48
62
|
export interface ResolvedToolAllocation {
|
|
49
63
|
|
|
50
|
-
patterns: string[]
|
|
64
|
+
patterns: string[];
|
|
51
65
|
|
|
52
|
-
|
|
66
|
+
label: SubAgentType;
|
|
53
67
|
}
|
|
54
68
|
|
|
55
|
-
export declare function resolveToolAllocation(raw: readonly string[]): ResolvedToolAllocation;
|
|
69
|
+
export declare function resolveToolAllocation(raw: readonly string[], catalog: readonly ToolCatalogEntry[]): ResolvedToolAllocation;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
1
|
+
const i="default",h=new Set(["sub_agent","list_sub_agents","get_sub_agent_status","abort_sub_agent","list_sub_agent_tools"]),g=new Set(["poll_message","get_message","send_group","send_private","create_task_instance_comment","submit_task_result","start_task_rollback","finish_task_rollback","reject_task","terminate_task","hire_colleague","hire_colleagues_batch","abandon_memory_update"]);function p(e){return e.kind==="mcp"&&g.has(e.toolName)}function S(e,r){if(r.length===0)return[...e];const n=new Set(e.map(t=>t.exposedName)),o=[...e];for(const t of r)n.has(t.exposedName)||(n.add(t.exposedName),o.push(t));return o}function x(e){return e.kind==="mcp"?e.serverName||"mcp":e.category||i}function O(e,r){return!r||e.length===0?[...e]:e.map(n=>{if(n.kind!=="builtin")return n;const t=n.execute;return typeof t!="function"?n:{...n,execute:(s,c)=>{const a=s&&typeof s=="object"&&s.agentId==null?{...s,agentId:r}:s;return t(a,c)}}})}function y(e){if(e.kind==="mcp"){const t=e.serverName||"mcp",s=[`${t}.${e.toolName}`];return e.exposedName&&e.exposedName!==e.toolName&&s.push(`${t}.${e.exposedName}`),s}const r=e.category||i,n=[`${r}.${e.exposedName}`],o=`${r}_`;return r!==i&&e.exposedName.startsWith(o)&&n.push(`${r}.${e.exposedName.slice(o.length)}`),n}function m(e){let r=e.trim();for(;r.length>0&&(r.endsWith("*")||r.endsWith("."));)r=r.slice(0,-1).trimEnd();return r}function w(e,r){if(p(e))return!1;const n=r.map(t=>typeof t=="string"?m(t):"").filter(t=>t.length>0);if(n.length===0)return!1;const o=y(e);return n.some(t=>o.some(s=>s===t||s.startsWith(`${t}.`)))}function L(e){const r=[],n=new Map;for(const o of e){if(h.has(o.exposedName)||p(o))continue;const t=x(o);let s=n.get(t);s||(s={kind:o.kind,names:[],seen:new Set},n.set(t,s),r.push(t));const c=E(o);s.seen.has(c)||(s.seen.add(c),s.names.push(c))}return r.sort((o,t)=>o===i?-1:t===i?1:o<t?-1:o>t?1:0).map(o=>{const t=n.get(o);return{category:o,kind:t.kind,tools:t.names}})}function E(e){if(e.kind==="mcp")return e.toolName;const r=e.category||i,n=`${r}_`;return r!==i&&e.exposedName.startsWith(n)?e.exposedName.slice(n.length):e.exposedName}const N=new Set(["write_file","edit_file","delete_file"]),A=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","memory_recurrence","memory_recurrence_complete"]),l="@explore",u="@core",T="custom",_={explore:l,general:u};class d extends Error{}function $(e){const r=e.map(n=>n.trim()).filter(n=>n.length>0).map(n=>_[n]??n);return r.length===0||r.every(n=>n===l)?l:r.every(n=>n===u)?u:T}function b(e,r){if(e===u)return[i];const n=[],o=r.find(t=>t.category===i);if(o)for(const t of o.tools)N.has(t)||n.push(`${i}.${t}`);for(const t of r)if(t.kind==="mcp")for(const s of t.tools)A.has(s)&&n.push(`${t.category}.${s}`);return n}function k(e,r,n){for(const o of n){if(o.category===r)return;for(const t of o.tools){const s=`${o.category}.${t}`;if(s===r||s.startsWith(`${r}.`))return}}throw new d(`Unknown tool allocation '${e}'. Allocatable categories: ${n.map(o=>o.category).join(", ")}. Call list_sub_agent_tools to see all allocatable categories and tool paths.`)}function C(e,r){const n=e.map(a=>typeof a=="string"?a.trim():"").filter(a=>a.length>0),o=n.map(a=>_[a]??a);o.length===0&&o.push(l);const t=[];for(const a of o){if(a.startsWith("@")){if(a!==l&&a!==u)throw new d(`Unknown tool preset '${a}'. Available presets: ${l} (read-only default), ${u} (all core default tools).`);t.push(...b(a,r));continue}const f=m(a);k(a,f,r),t.push(f)}const s=new Set,c=[];for(const a of t)a.length===0||s.has(a)||(s.add(a),c.push(a));return{patterns:c,label:$(n)}}export{g as AGENT_IDENTITY_MCP_RESTRICTED_TOOLS,i as DEFAULT_TOOL_CATEGORY,N as EXPLORE_READONLY_DENIED_TOOLS,u as PRESET_CORE,l as PRESET_EXPLORE,A as SUB_AGENT_ALLOWED_MCP_TOOLS,h as SUB_AGENT_MANAGEMENT_TOOL_NAMES,T as TYPE_LABEL_CUSTOM,d as ToolAllocationError,L as buildToolCatalog,$ as deriveTypeLabel,p as isAgentIdentityRestrictedTool,w as matchesToolAllocation,S as mergeAllocatableTools,m as normalizeAllocationPattern,O as rebindDefaultAgentId,C as resolveToolAllocation,y as toolAllocationAliases,x as toolAllocationCategory};
|
|
2
2
|
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { SubAgentManager } from "./sub-agent-manager.js";
|
|
2
|
-
import type { SubAgentType } from "./sub-agent-types.js";
|
|
3
2
|
import type { ACodeMcpConnection } from "./runtime.js";
|
|
4
3
|
import type { TerminalManager } from "./terminal-types.js";
|
|
5
4
|
export interface ACodeMcpServerSpec {
|
|
@@ -129,8 +128,6 @@ export interface ACodeRuntimeConfig {
|
|
|
129
128
|
|
|
130
129
|
subAgentEffort?: string;
|
|
131
130
|
|
|
132
|
-
subagentType?: SubAgentType;
|
|
133
|
-
|
|
134
131
|
subAgentAllowedTools?: string[];
|
|
135
132
|
|
|
136
133
|
onFileChange?: import("./built-in-file-tools.js").OnAgentFileChange;
|
|
@@ -4,6 +4,11 @@ import { StatusReporter } from "./status-reporter.js";
|
|
|
4
4
|
import type { AgentConfig, BrowserListenerEvent, DirectMessage, DmHistoryResponse, FetchUnreadMessagesOptions, FinishTaskRollbackArgs, GroupHistoryResponse, GroupRoomsResponse, HireBatchResult, HireColleagueArgs, HireColleaguesBatchArgs, HiredColleagueResult, MessageHandler, OnlineListResponse, ProfileInfo, RegisterResult, ServerConfig, SendDmResult, SendMessageResult, StartTaskRollbackArgs, TaskInstanceCommentArgs, UnreadMessagesResult } from "./types.js";
|
|
5
5
|
export type ProfileHandler = (profile: ProfileInfo) => void;
|
|
6
6
|
export type AgentConfigHandler = (data: Record<string, unknown>) => void;
|
|
7
|
+
export type SystemNotifyHandler = (data: Record<string, unknown>) => void;
|
|
8
|
+
|
|
9
|
+
export declare class PollLongPollTimeoutError extends Error {
|
|
10
|
+
constructor(message: string);
|
|
11
|
+
}
|
|
7
12
|
export declare class AgentClient {
|
|
8
13
|
private wsClient;
|
|
9
14
|
private httpClient;
|
|
@@ -17,15 +22,21 @@ export declare class AgentClient {
|
|
|
17
22
|
private messageHandler;
|
|
18
23
|
private profileHandler;
|
|
19
24
|
private configHandler;
|
|
25
|
+
private systemNotifyHandler;
|
|
20
26
|
private pollTimer;
|
|
21
27
|
private statusReporter;
|
|
22
28
|
private newCharacterHandler;
|
|
23
29
|
|
|
24
30
|
private runtimeTokenRefreshTimer;
|
|
25
31
|
|
|
32
|
+
private pendingLaunchBindingClaim;
|
|
33
|
+
|
|
26
34
|
private cachedProfile;
|
|
27
35
|
constructor();
|
|
28
36
|
initialize(): Promise<void>;
|
|
37
|
+
private applyLaunchBinding;
|
|
38
|
+
|
|
39
|
+
private retryPendingLaunchBindingClaim;
|
|
29
40
|
private setupWebSocketListeners;
|
|
30
41
|
|
|
31
42
|
register(): Promise<RegisterResult>;
|
|
@@ -67,6 +78,10 @@ export declare class AgentClient {
|
|
|
67
78
|
|
|
68
79
|
markGroupRead(roomId: string, msgIds: number[]): Promise<Set<number>>;
|
|
69
80
|
|
|
81
|
+
markNotificationRead(msgIds: string[]): Promise<void>;
|
|
82
|
+
|
|
83
|
+
markMeetingRead(msgIds: Array<string | number>): Promise<void>;
|
|
84
|
+
|
|
70
85
|
fetchBrowserListenerEvents(): Promise<BrowserListenerEvent[]>;
|
|
71
86
|
|
|
72
87
|
notifyBridgeForceMessage(): Promise<void>;
|
|
@@ -126,12 +141,14 @@ export declare class AgentClient {
|
|
|
126
141
|
pollMode?: boolean;
|
|
127
142
|
profileHandler?: ProfileHandler;
|
|
128
143
|
configHandler?: AgentConfigHandler;
|
|
144
|
+
systemNotifyHandler?: SystemNotifyHandler;
|
|
129
145
|
}): void;
|
|
130
146
|
|
|
131
147
|
stop(): void;
|
|
132
148
|
private messageLoop;
|
|
133
149
|
private handleIncomingDm;
|
|
134
150
|
private handleIncomingGroup;
|
|
151
|
+
private handleIncomingMeeting;
|
|
135
152
|
|
|
136
153
|
private handleProfileInfo;
|
|
137
154
|
private processMessage;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{configManager as g}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as m}from"./constants.js";import{HttpClient as f}from"./http-client.js";import{logger as s,setMcpNodeLogSink as C,updateStartupLogIdentity as u}from"./logger.js";import{claimRuntimeLaunchBinding as I}from"./runtime-launch-binding.js";import{StatusReporter as y}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class b{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;cachedProfile=null;constructor(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await I(this.agentConfig,this.serverConfig);if(!e){this.serverConfig.runtimeBridgeBaseUrl=void 0;return}g.applyRuntimeLaunchBinding(e),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("profileInfo",e=>{s.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{s.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{s.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";s.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{s.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{s.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()}),this.wsClient.on("tokenRejected",()=>{s.error("[AgentClient] runtime token \u88AB 1008 \u62D2\u7EDD\u4E14\u5237\u65B0\u65E0\u53D8\u5316\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85\u65B0 token \u7B7E\u53D1: agentId=%s",this.agentId)}),this.wsClient.on("tokenRefreshFailed",e=>{s.error("[AgentClient] runtime token \u5237\u65B0\u8FDE\u7EED\u5931\u8D25 %s \u6B21\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85 bridge \u6062\u590D: agentId=%s",e,this.agentId)})}async register(){return s.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(i){throw s.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,i instanceof Error?i.message:String(i)),i}this.displayName=t.displayName,this.projectId=t.projectId||null,s.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(i){throw s.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,i instanceof Error?i.message:String(i)),i}s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,u(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,u(this.agentConfig.roleName||"unknown-role",e.instanceName||t),s.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u72B6\u6001: ${e.status}`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){s.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,s.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{agentId:this.agentId,...e})}async hireColleaguesBatch(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleagues_batch",{agentId:this.agentId,...e})}async callAgentScopedTool(e,t){return this.ensureRegistered(),await this.httpClient.callTool(e,{agentId:this.agentId,...t})}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n){this.ensureRegistered();const i=t||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:i,roomId:n,content:e})}async sendDirectMessage(e,t,n=!1,i,r){this.ensureRegistered();const a={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:i};if(typeof r=="number"&&r>0&&(a.timeoutMs=r),n){const h=typeof r=="number"&&r>0?r+3e4:0;return await this.httpClient.callToolOnce("send_dm",a,h)}return await this.httpClient.callTool("send_dm",a)}async sendCallAndWaitReply(e,t,n=6e4){const i=await this.sendDirectMessage(e,t,!0,void 0,n);if(i.reply)return i.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async getDmHistory(e,t=50,n){this.ensureRegistered();const i={agentId:this.agentId,targetUserId:e,limit:t};return n&&(i.since=n),await this.httpClient.callTool("get_dm_history",i)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const i=await this.discoverGroupRooms(),r=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(i,r);if(a.length===0)return{messages:[],count:0};const c=(await Promise.all(a.map(async o=>{const l={projectId:r,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:c,count:c.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs);const i=e.includePipelineTasks?"poll_message":"get_dm_messages",r=await this.fetchDirectMessagesWithRecovery(i,n),a=await this.discoverGroupRooms(),h=this.collectRoomIds(a,t),c=await Promise.all(h.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(d){return s.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,d instanceof Error?d.message:String(d)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(r.messages)?r.messages:[],groupMessages:c.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async markDmRead(e){if(e.length===0)return new Set;this.ensureRegistered();const t=await this.httpClient.callTool("mark_dm_read",{agentId:this.agentId,msgIds:e});return new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[])}async markGroupRead(e,t){if(t.length===0)return new Set;this.ensureRegistered();const n=await this.httpClient.callTool("mark_group_read",{agentId:this.agentId,roomId:e,msgIds:t});return new Set(Array.isArray(n?.deliverableMsgIds)?n.deliverableMsgIds:[])}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return s.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,i=this.serverConfig.runtimeAccessToken||"";s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,i.length);const r=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":i},signal:AbortSignal.timeout(3e3)});if(!r.ok)return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",r.status,n),[];const a=await r.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!(!e||!t))try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/notify-force-message`,i=this.serverConfig.runtimeAccessToken||"",r=await fetch(n,{method:"POST",headers:{"X-Runtime-Token":i},signal:AbortSignal.timeout(3e3)});r.ok||s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",r.status,n)}catch(n){s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",n instanceof Error?n.message:String(n))}}async fetchDirectMessagesWithRecovery(e,t){if(e==="poll_message")try{return await this.httpClient.callToolOnce(e,t)}catch(n){if(this.isRecoverableLongPollError(n))return s.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",n),{messages:[]};throw n}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(i=>i.projectId===t).map(i=>i.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n){this.ensureRegistered();const i={agentId:this.agentId,nodeId:e,outputPayload:t};return n&&Array.isArray(n)&&n.length>0&&(i.changeLog=n),await this.httpClient.callTool("submit_task_result",i)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async rejectTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("reject_task",{agentId:this.agentId,nodeId:e,reason:t})}async terminateTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("terminate_task",{agentId:this.agentId,taskInstanceId:e,reason:t})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}async getRuntimeFeatures(){return await this.httpClient.fetchRuntimeFeatures()}async listLaunchConfigs(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_list",{})}async createLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_create",{...e})}async updateLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_update",{...e})}async deleteLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_delete",{configId:e})}async startLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_start",e,t+6e4):await this.httpClient.callTool("launch_config_start",{...e})}async restartLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_restart",e,t+6e4):await this.httpClient.callTool("launch_config_restart",{...e})}async stopLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_stop",{configId:e})}async getLaunchLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_logs",{...e})}async listLaunchRuns(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_status",{})}start(e,t){if(this.isRunning){s.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.isRunning=!0,s.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(s.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(s.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):s.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),s.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(m)}catch(e){s.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleProfileInfo(e){s.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,s.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(s.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&u(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(s.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";s.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const i=e;i.requireReply&&i.callId&&await this.replyToCall(i.callId,i.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const i=typeof e.msgId=="string";if(s.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",i?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),i){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),s.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,s.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,s.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const r=await this.register();s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${r.displayName} (${r.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(r){n++;const a=r instanceof Error?r.message:String(r);if(s.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(h=>setTimeout(h,e))}})().catch(r=>{s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",r instanceof Error?r.message:String(r),r instanceof Error?r.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){s.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new y({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),C(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),s.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){s.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){s.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&s.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),this.runtimeTokenRefreshTimer.unref?.(),s.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{b as AgentClient};
|
|
1
|
+
import{configManager as g}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as y}from"./constants.js";import{HttpClient as f}from"./http-client.js";import{logger as s,setMcpNodeLogSink as w,updateStartupLogIdentity as u}from"./logger.js";import{claimRuntimeLaunchBindingDetailed as m}from"./runtime-launch-binding.js";import{StatusReporter as A}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class T extends Error{constructor(e){super(e),this.name="PollLongPollTimeoutError"}}const C=27e4;class v{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;systemNotifyHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;pendingLaunchBindingClaim=!1;cachedProfile=null;constructor(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed"){this.applyLaunchBinding(e.binding);return}if(e.status==="unreachable"){this.pendingLaunchBindingClaim=!0,s.warn("[AgentClient] runtime-bridge \u672A\u5C31\u7EEA\uFF0C\u542F\u52A8\u7ED1\u5B9A\u8BA4\u9886\u5DF2\u6302\u8D77\uFF0C\u5C06\u5728\u6CE8\u518C\u91CD\u8BD5\u4E2D\u91CD\u65B0\u8BA4\u9886: %s",e.message);return}this.serverConfig.runtimeBridgeBaseUrl=void 0}applyLaunchBinding(e){g.applyRuntimeLaunchBinding(e),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async retryPendingLaunchBindingClaim(){if(!this.pendingLaunchBindingClaim)return!0;const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed")return this.pendingLaunchBindingClaim=!1,s.info("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u6210\u529F\uFF0C\u7EE7\u7EED\u6CE8\u518C\u6D41\u7A0B"),this.applyLaunchBinding(e.binding),!0;if(e.status==="missing")return this.pendingLaunchBindingClaim=!1,this.serverConfig.runtimeBridgeBaseUrl=void 0,s.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u672A\u627E\u5230\u5F85\u8BA4\u9886\u8BB0\u5F55\uFF0C\u6309\u65E0\u7ED1\u5B9A\u6A21\u5F0F\u7EE7\u7EED\u6CE8\u518C"),!1;const t=e.status==="unreachable"?e.message:e.reason;return s.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u5931\u8D25\uFF0C\u4FDD\u7559\u6302\u8D77\u72B6\u6001\u7B49\u5F85\u4E0B\u6B21\u6CE8\u518C\u91CD\u8BD5: %s",t),!1}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("meetingMessage",e=>{this.handleIncomingMeeting(e)}),this.wsClient.on("systemNotify",e=>{this.systemNotifyHandler?.(e)}),this.wsClient.on("profileInfo",e=>{s.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{s.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{s.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";s.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{s.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{s.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()}),this.wsClient.on("tokenRejected",()=>{s.error("[AgentClient] runtime token \u88AB 1008 \u62D2\u7EDD\u4E14\u5237\u65B0\u65E0\u53D8\u5316\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85\u65B0 token \u7B7E\u53D1: agentId=%s",this.agentId)}),this.wsClient.on("tokenRefreshFailed",e=>{s.error("[AgentClient] runtime token \u5237\u65B0\u8FDE\u7EED\u5931\u8D25 %s \u6B21\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85 bridge \u6062\u590D: agentId=%s",e,this.agentId)})}async register(){return s.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),await this.retryPendingLaunchBindingClaim(),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(r){throw s.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}this.displayName=t.displayName,this.projectId=t.projectId||null,s.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(r){throw s.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,u(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,u(this.agentConfig.roleName||"unknown-role",e.instanceName||t),s.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u72B6\u6001: ${e.status}`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){s.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,s.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{...e,agentId:this.agentId})}async hireColleaguesBatch(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleagues_batch",{...e,agentId:this.agentId})}async callAgentScopedTool(e,t){this.ensureRegistered();const n={...t,agentId:this.agentId};if(e==="create_meeting"){const r=typeof t.waitTimeoutMs=="number"?t.waitTimeoutMs:Number.NaN,i=Number.isFinite(r)&&r>0?Math.min(r,C):C;return await this.httpClient.callToolOnce(e,{...n,waitTimeoutMs:i},0)}return await this.httpClient.callTool(e,n)}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n){this.ensureRegistered();const r=t||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:r,roomId:n,content:e})}async sendDirectMessage(e,t,n=!1,r,i){this.ensureRegistered();const a={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:r};if(typeof i=="number"&&i>0&&(a.timeoutMs=i),n){const h=typeof i=="number"&&i>0?i+3e4:0;return await this.httpClient.callToolOnce("send_dm",a,h)}return await this.httpClient.callTool("send_dm",a)}async sendCallAndWaitReply(e,t,n=6e4){const r=await this.sendDirectMessage(e,t,!0,void 0,n);if(r.reply)return r.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async getDmHistory(e,t=50,n){this.ensureRegistered();const r={agentId:this.agentId,targetUserId:e,limit:t};return n&&(r.since=n),await this.httpClient.callTool("get_dm_history",r)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const r=await this.discoverGroupRooms(),i=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(r,i);if(a.length===0)return{messages:[],count:0};const c=(await Promise.all(a.map(async o=>{const l={projectId:i,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:c,count:c.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs),e.preemptiveJoinWaitMs!==void 0&&e.preemptiveJoinWaitMs!==null&&e.preemptiveJoinWaitMs>=0&&(n.preemptiveJoinWaitMs=e.preemptiveJoinWaitMs);const r=e.includePipelineTasks?"poll_message":"get_dm_messages";s.info("[AgentClient] fetchUnreadMessages \u5165\u53E3: tool=%s, blockIfEmpty=%s, blockTimeoutMs=%s, pollMessageTimeoutMs=%s, skipGroupMessages=%s, preemptiveJoinWaitMs=%s, agentId=%s",r,String(e.blockIfEmpty??!1),String(e.blockTimeoutMs??"-"),String(e.pollMessageTimeoutMs??"-"),String(e.skipGroupMessages??!1),String(e.preemptiveJoinWaitMs??"-"),this.agentId);const i=await this.fetchDirectMessagesWithRecovery(r,n,e.pollMessageTimeoutMs,e.propagatePollTimeout===!0);if(s.info("[AgentClient] fetchUnreadMessages \u79C1\u4FE1\u9636\u6BB5\u8FD4\u56DE: %s \u6761",Array.isArray(i.messages)?i.messages.length:0),e.skipGroupMessages)return s.info("[AgentClient] \u4F1A\u8BAE\u5FEB\u901F hydrate \u5DF2\u53D6\u5F97\u79C1\u4FE1\u54CD\u5E94\uFF0C\u8DF3\u8FC7\u7FA4\u804A\u53D1\u73B0\u5E76\u7ACB\u5373\u8FD4\u56DE: directMessages=%s",Array.isArray(i.messages)?i.messages.length:0),{directMessages:Array.isArray(i.messages)?i.messages:[],groupMessages:[]};let a;try{a=await this.discoverGroupRooms()}catch(o){s.warn("[AgentClient] \u53D1\u73B0\u7FA4\u623F\u95F4\u5931\u8D25\uFF0C\u672C\u6B21\u6309\u65E0\u7FA4\u6D88\u606F\u5904\u7406\uFF08\u5DF2\u53D6\u5230\u7684\u79C1\u4FE1\u4E0D\u53D7\u5F71\u54CD\uFF09: %s",o instanceof Error?o.message:String(o)),a={groups:[]}}const h=this.collectRoomIds(a,t),c=await Promise.all(h.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(d){return s.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,d instanceof Error?d.message:String(d)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(i.messages)?i.messages:[],groupMessages:c.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async markDmRead(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_dm_read",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(i=>!n.has(i));return r.length>0?s.warn("[AgentClient] mark_dm_read \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s, \u88AB\u4E22\u5F03=%s",r.length,JSON.stringify(e),JSON.stringify([...n]),JSON.stringify(r)):s.info("[AgentClient] mark_dm_read \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5168\u90E8\u53EF\u4EA4\u4ED8",e.length),n}catch(t){throw s.warn("[AgentClient] mark_dm_read \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markGroupRead(e,t){if(t.length===0)return new Set;this.ensureRegistered();const n=await this.httpClient.callTool("mark_group_read",{agentId:this.agentId,roomId:e,msgIds:t});return new Set(Array.isArray(n?.deliverableMsgIds)?n.deliverableMsgIds:[])}async markNotificationRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_notification_read",{agentId:this.agentId,msgIds:e})}catch{}}}async markMeetingRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_meeting_read",{agentId:this.agentId,msgIds:e})}catch{}}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return s.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"";s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,r.length);const i=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!i.ok)return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",i.status,n),[];const a=await i.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!(!e||!t))try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/notify-force-message`,r=this.serverConfig.runtimeAccessToken||"",i=await fetch(n,{method:"POST",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});i.ok||s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",i.status,n)}catch(n){s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",n instanceof Error?n.message:String(n))}}async fetchDirectMessagesWithRecovery(e,t,n,r=!1){if(e==="poll_message"){s.info("[AgentClient] fetchDirectMessagesWithRecovery \u5165\u53E3: tool=poll_message, pollMessageTimeoutMs=%s, agentId=%s",String(n??"(\u9ED8\u8BA4)"),String(t?.agentId??""));try{const i=await this.httpClient.callToolOnce(e,t,n);return s.info("[AgentClient] fetchDirectMessagesWithRecovery poll_message \u6210\u529F\u8FD4\u56DE: %s \u6761",Array.isArray(i?.messages)?i.messages.length:0),i}catch(i){if(this.isRecoverableLongPollError(i)){if(r)throw new T(i instanceof Error?i.message:String(i));return s.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",i),{messages:[]}}throw i}}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(r=>r.projectId===t).map(r=>r.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n){this.ensureRegistered();const r={agentId:this.agentId,nodeId:e,outputPayload:t};return n&&Array.isArray(n)&&n.length>0&&(r.changeLog=n),await this.httpClient.callTool("submit_task_result",r)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async rejectTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("reject_task",{agentId:this.agentId,nodeId:e,reason:t})}async terminateTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("terminate_task",{agentId:this.agentId,taskInstanceId:e,reason:t})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}async getRuntimeFeatures(){return await this.httpClient.fetchRuntimeFeatures()}async listLaunchConfigs(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_list",{})}async createLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_create",{...e})}async updateLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_update",{...e})}async deleteLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_delete",{configId:e})}async startLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_start",e,t+6e4):await this.httpClient.callTool("launch_config_start",{...e})}async restartLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_restart",e,t+6e4):await this.httpClient.callTool("launch_config_restart",{...e})}async stopLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_stop",{configId:e})}async getLaunchLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_logs",{...e})}async listLaunchRuns(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_status",{})}start(e,t){if(this.isRunning){s.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.systemNotifyHandler=t?.systemNotifyHandler||null,this.isRunning=!0,s.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(s.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(s.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):s.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),s.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(y)}catch(e){s.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingMeeting(e){!e||e.senderId===this.agentId||this.processMessage(e)}handleProfileInfo(e){s.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,s.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(s.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&u(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(s.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";s.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const r=typeof e.msgId=="string";if(s.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",r?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),r){const i=e;i.requireReply&&i.callId&&await this.replyToCall(i.callId,i.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),s.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,s.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,s.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const i=await this.register();s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${i.displayName} (${i.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(i){n++;const a=i instanceof Error?i.message:String(i);if(s.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(h=>setTimeout(h,e))}})().catch(i=>{s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",i instanceof Error?i.message:String(i),i instanceof Error?i.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){s.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new A({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),w(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),s.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){s.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){s.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&s.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),this.runtimeTokenRefreshTimer.unref?.(),s.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{v as AgentClient,T as PollLongPollTimeoutError};
|
|
2
2
|
|