shennian 0.2.132 → 0.2.133

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.
@@ -131,8 +131,8 @@
131
131
  },
132
132
  {
133
133
  "file": "src/agents/pi.js",
134
- "beforeBytes": 31585,
135
- "afterBytes": 14905
134
+ "beforeBytes": 31836,
135
+ "afterBytes": 15039
136
136
  },
137
137
  {
138
138
  "file": "src/agents/platform-instructions.js",
@@ -321,8 +321,8 @@
321
321
  },
322
322
  {
323
323
  "file": "src/channels/wechat-rpa/product-channel.js",
324
- "beforeBytes": 18332,
325
- "afterBytes": 9837
324
+ "beforeBytes": 20794,
325
+ "afterBytes": 10908
326
326
  },
327
327
  {
328
328
  "file": "src/channels/wechat-rpa-session-sync.js",
@@ -526,8 +526,8 @@
526
526
  },
527
527
  {
528
528
  "file": "src/manager/runtime.js",
529
- "beforeBytes": 68071,
530
- "afterBytes": 34702
529
+ "beforeBytes": 68372,
530
+ "afterBytes": 34842
531
531
  },
532
532
  {
533
533
  "file": "src/native-fusion/config.js",
@@ -641,8 +641,8 @@
641
641
  },
642
642
  {
643
643
  "file": "src/session/queue.js",
644
- "beforeBytes": 12692,
645
- "afterBytes": 6156
644
+ "beforeBytes": 14160,
645
+ "afterBytes": 6773
646
646
  },
647
647
  {
648
648
  "file": "src/session/remote-attachments.js",
@@ -35,6 +35,12 @@ export declare class PiAdapter extends AgentAdapter {
35
35
  }): void;
36
36
  start(sessionId: string, workDir: string, _agentSessionId?: string | null): Promise<void>;
37
37
  send(text: string, modelId?: string): Promise<void>;
38
+ getStatus(): Promise<{
39
+ active: boolean;
40
+ runId?: string | null;
41
+ runPhase?: null;
42
+ canStop?: boolean;
43
+ }>;
38
44
  private initAgent;
39
45
  /**
40
46
  * After each turn, compress old messages and actually replace them in the
@@ -1,12 +1,12 @@
1
- import{randomUUID as b}from"node:crypto";import l from"node:fs";import g from"node:path";import{execFile as _}from"node:child_process";import{promisify as A}from"node:util";import{Agent as T,streamProxy as I}from"@mariozechner/pi-agent-core";import{streamOpenAICompletions as j}from"@mariozechner/pi-ai/openai-completions";import{Type as p}from"@sinclair/typebox";import{AgentAdapter as D,registerAgent as $}from"./adapter.js";import{buildExternalChannelInstructions as F}from"./external-channel-instructions.js";import{loadConfig as L}from"../config/index.js";import{getManagedAgentProviderConfig as O}from"./config-status.js";import{SERVERS as N}from"../region.js";import{buildAgentProcessEnv as q}from"../agent-env.js";import{buildRollingSummary as E,buildShellCommandSpec as P,cloneMessages as S,CONTEXT_TOKEN_THRESHOLD as v,createPiModel as M,estimateTokens as w,getSessionDir as z,KEEP_RECENT_MESSAGES as k,LEGACY_SUMMARY_FILENAME as R,loadAgentsMdInstructions as U,longestCommonPrefixLength as B,MESSAGES_FILENAME as K,messagesToText as G,PI_DEFAULT_MODEL_ID as J,requestProxySummary as H,SNAPSHOT_FILENAME as Y,SYSTEM_PROMPT as W,SUMMARY_FILENAME as V}from"./pi-context.js";import{buildShellCommandSpec as Mt}from"./pi-context.js";const X=A(_),Q="https://dashscope.aliyuncs.com/compatible-mode/v1";function y(o,t){return g.resolve(o,t)}async function Z(o,t,e,s){const n=P(t),{stdout:i,stderr:a}=await X(n.file,n.args,{cwd:o,env:q(e),timeout:3e4,signal:s,maxBuffer:1024*1024,windowsHide:!0});return{stdout:i,stderr:a,shell:n.shell}}function C(o){return typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf8"):""}function tt(o){if(!o||typeof o!="object")return String(o);const t=o,e=[t.message||String(o)],s=C(t.stdout).trim(),n=C(t.stderr).trim();return s&&e.push(`---stdout---
1
+ import{randomUUID as b}from"node:crypto";import l from"node:fs";import g from"node:path";import{execFile as _}from"node:child_process";import{promisify as A}from"node:util";import{Agent as I,streamProxy as T}from"@mariozechner/pi-agent-core";import{streamOpenAICompletions as j}from"@mariozechner/pi-ai/openai-completions";import{Type as p}from"@sinclair/typebox";import{AgentAdapter as D,registerAgent as $}from"./adapter.js";import{buildExternalChannelInstructions as F}from"./external-channel-instructions.js";import{loadConfig as L}from"../config/index.js";import{getManagedAgentProviderConfig as O}from"./config-status.js";import{SERVERS as N}from"../region.js";import{buildAgentProcessEnv as q}from"../agent-env.js";import{buildRollingSummary as E,buildShellCommandSpec as P,cloneMessages as S,CONTEXT_TOKEN_THRESHOLD as v,createPiModel as M,estimateTokens as w,getSessionDir as z,KEEP_RECENT_MESSAGES as k,LEGACY_SUMMARY_FILENAME as R,loadAgentsMdInstructions as U,longestCommonPrefixLength as B,MESSAGES_FILENAME as K,messagesToText as G,PI_DEFAULT_MODEL_ID as J,requestProxySummary as H,SNAPSHOT_FILENAME as Y,SYSTEM_PROMPT as W,SUMMARY_FILENAME as V}from"./pi-context.js";import{buildShellCommandSpec as Mt}from"./pi-context.js";const X=A(_),Q="https://dashscope.aliyuncs.com/compatible-mode/v1";function y(o,t){return g.resolve(o,t)}async function Z(o,t,e,s){const n=P(t),{stdout:i,stderr:a}=await X(n.file,n.args,{cwd:o,env:q(e),timeout:3e4,signal:s,maxBuffer:1024*1024,windowsHide:!0});return{stdout:i,stderr:a,shell:n.shell}}function C(o){return typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf8"):""}function tt(o){if(!o||typeof o!="object")return String(o);const t=o,e=[t.message||String(o)],s=C(t.stdout).trim(),n=C(t.stderr).trim();return s&&e.push(`---stdout---
2
2
  ${s}`),n&&e.push(`---stderr---
3
3
  ${n}`),t.code!==void 0&&e.push(`exitCode: ${String(t.code)}`),t.signal&&e.push(`signal: ${t.signal}`),e.join(`
4
4
  `)}function et(o,t={}){return[{name:"read_file",label:"\u8BFB\u53D6\u6587\u4EF6",description:"Read the full content of a file at the given path.",parameters:p.Object({path:p.String({description:"Absolute or relative file path"})}),async execute(e,{path:s}){let n="";try{return n=y(o,s),{content:[{type:"text",text:l.readFileSync(n,"utf-8")}],details:{path:n}}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:String(i)}`}],details:{path:n}}}}},{name:"write_file",label:"\u5199\u5165\u6587\u4EF6",description:"Write content to a file, creating it or overwriting if it exists.",parameters:p.Object({path:p.String({description:"Absolute or relative file path"}),content:p.String({description:"File content to write"})}),async execute(e,{path:s,content:n}){let i="";try{return i=y(o,s),l.mkdirSync(g.dirname(i),{recursive:!0}),l.writeFileSync(i,n,"utf-8"),{content:[{type:"text",text:`Written ${n.length} bytes to ${i}`}],details:{path:i}}}catch(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],details:{path:i}}}}},{name:"list_directory",label:"\u5217\u51FA\u76EE\u5F55",description:"List files and directories at the given path.",parameters:p.Object({path:p.String({description:"Directory path to list",default:"."})}),async execute(e,{path:s}){let n="";try{return n=y(o,s),{content:[{type:"text",text:l.readdirSync(n,{withFileTypes:!0}).map(h=>`${h.isDirectory()?"d":"f"} ${h.name}`).join(`
5
5
  `)||"(empty)"}],details:{path:n}}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:String(i)}`}],details:{path:n}}}}},{name:"bash",label:"\u6267\u884C\u547D\u4EE4",description:"Execute a shell command in the working directory. Uses PowerShell on Windows and bash on macOS/Linux. Timeout: 30s.",parameters:p.Object({command:p.String({description:"Shell command to execute"})}),async execute(e,{command:s},n){try{const{stdout:i,stderr:a,shell:h}=await Z(o,s,t,n);return{content:[{type:"text",text:[i,a].filter(Boolean).join(`
6
6
  ---stderr---
7
- `)||"(no output)"}],details:{command:s,shell:h}}}catch(i){return{content:[{type:"text",text:`Error: ${tt(i)}`}],details:{command:s,shell:P(s).shell}}}}},{name:"read_image",label:"\u8BFB\u53D6\u56FE\u7247",description:"Read an image file and return its content for visual analysis. Supports png, jpg, jpeg, gif, webp. Max 10 MB.",parameters:p.Object({path:p.String({description:"Absolute or relative path to the image file"})}),async execute(e,{path:s}){let n;try{n=y(o,s)}catch(r){return{content:[{type:"text",text:`Error: ${r instanceof Error?r.message:String(r)}`}],details:{path:s}}}const i=g.extname(n).toLowerCase().slice(1),h={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"}[i];if(!h)return{content:[{type:"text",text:`Error: unsupported image type ".${i}". Supported: png, jpg, jpeg, gif, webp`}],details:{path:n}};try{const r=l.statSync(n);return r.size>10*1024*1024?{content:[{type:"text",text:`Error: image too large (${(r.size/1024/1024).toFixed(1)} MB, max 10 MB)`}],details:{path:n}}:{content:[{type:"image",data:l.readFileSync(n).toString("base64"),mimeType:h}],details:{path:n,mimeType:h,size:r.size}}}catch(r){return{content:[{type:"text",text:`Error: ${r instanceof Error?r.message:String(r)}`}],details:{path:n}}}}}]}class st extends D{type="pi";agent=null;sessionId=null;workDir=null;seq=0;runId="";emittedLengths=new Map;terminalState="open";authToken=null;proxyUrl=null;providerConfig;sessionDir=null;messagesPath=null;snapshotPath=null;summaryPath=null;cachedSummary=null;restoredMessages=[];compressing=!1;lastSummaryMsgCount=0;pendingBaseMessages=[];finalizePromise=Promise.resolve();sendGeneration=0;externalChannel=null;shennianSessionId=null;extraEnv={};pendingSendStart=null;configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,s){this.sessionId=t,this.workDir=e,this.seq=0,this.sessionDir=z(t),this.messagesPath=g.join(this.sessionDir,K),this.snapshotPath=g.join(this.sessionDir,Y),this.summaryPath=g.join(this.sessionDir,V),this.loadSnapshot(),this.loadSummary()}async send(t,e){const s=++this.sendGeneration,n=this.agent&&this.terminalState==="open"?S(this.pendingBaseMessages):null;n&&(this.agent?.abort(),this.agent=null,this.restoredMessages=n,this.finalizePromise=Promise.resolve());const i=L(),a=i.machineToken??i.accessToken;if(!a){this.emit("agentEvent",{state:"error",runId:this.runId,seq:++this.seq,message:"\u672A\u914D\u5BF9\uFF0C\u8BF7\u5148\u8FD0\u884C shennian \u5B8C\u6210\u673A\u5668\u914D\u5BF9"});return}this.authToken=a,this.proxyUrl=(i.serverUrl??N.cn.url).replace(/\/$/,"");const h=O("pi"),r=i.apiKeys?.dashscope?.trim();this.providerConfig=h??(r?{agent:"pi",token:r,updatedAt:""}:void 0),this.runId=b(),this.seq=0,this.emittedLengths.clear(),this.terminalState="open",this.agent||this.initAgent(),await this.finalizePromise.catch(()=>{}),this.agent?.setModel(M(e??J)),this.pendingBaseMessages=S(this.agent?.state.messages??[]);const d=this.runId,m=new Promise((c,u)=>{this.pendingSendStart={runId:d,resolve:c,reject:u}});this.emit("agentEvent",{state:"init",runId:d,seq:++this.seq}),this.agent.prompt(t).then(async()=>{s===this.sendGeneration&&(this.resolvePendingSendStart(d),await this.finalizePromise.catch(()=>{}))}).catch(c=>{if(s!==this.sendGeneration||(this.rejectPendingSendStart(d,c),this.terminalState!=="open"))return;this.terminalState="error";const u=c instanceof Error?c.message:String(c);u.includes("429")||u.includes("daily_quota_exceeded")||u.includes("nian_quota_exceeded")?this.emit("agentEvent",{state:"error",runId:d,seq:++this.seq,message:"Nian \u4ECA\u65E5\u989D\u5EA6\u5DF2\u7528\u5B8C\uFF0C\u6B21\u65E5\u81EA\u52A8\u6062\u590D\u3002"}):this.emit("agentEvent",{state:"error",runId:d,seq:++this.seq,message:u})}),await m}initAgent(){const t=this.workDir??process.cwd(),e=et(t,this.extraEnv),s=U(t),n=new T({initialState:{systemPrompt:[W,s,`\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\uFF1A${t}`,F(this.externalChannel,t,this.shennianSessionId??void 0)].filter(Boolean).join(`
7
+ `)||"(no output)"}],details:{command:s,shell:h}}}catch(i){return{content:[{type:"text",text:`Error: ${tt(i)}`}],details:{command:s,shell:P(s).shell}}}}},{name:"read_image",label:"\u8BFB\u53D6\u56FE\u7247",description:"Read an image file and return its content for visual analysis. Supports png, jpg, jpeg, gif, webp. Max 10 MB.",parameters:p.Object({path:p.String({description:"Absolute or relative path to the image file"})}),async execute(e,{path:s}){let n;try{n=y(o,s)}catch(r){return{content:[{type:"text",text:`Error: ${r instanceof Error?r.message:String(r)}`}],details:{path:s}}}const i=g.extname(n).toLowerCase().slice(1),h={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"}[i];if(!h)return{content:[{type:"text",text:`Error: unsupported image type ".${i}". Supported: png, jpg, jpeg, gif, webp`}],details:{path:n}};try{const r=l.statSync(n);return r.size>10*1024*1024?{content:[{type:"text",text:`Error: image too large (${(r.size/1024/1024).toFixed(1)} MB, max 10 MB)`}],details:{path:n}}:{content:[{type:"image",data:l.readFileSync(n).toString("base64"),mimeType:h}],details:{path:n,mimeType:h,size:r.size}}}catch(r){return{content:[{type:"text",text:`Error: ${r instanceof Error?r.message:String(r)}`}],details:{path:n}}}}}]}class st extends D{type="pi";agent=null;sessionId=null;workDir=null;seq=0;runId="";emittedLengths=new Map;terminalState="open";authToken=null;proxyUrl=null;providerConfig;sessionDir=null;messagesPath=null;snapshotPath=null;summaryPath=null;cachedSummary=null;restoredMessages=[];compressing=!1;lastSummaryMsgCount=0;pendingBaseMessages=[];finalizePromise=Promise.resolve();sendGeneration=0;externalChannel=null;shennianSessionId=null;extraEnv={};pendingSendStart=null;configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,s){this.sessionId=t,this.workDir=e,this.seq=0,this.sessionDir=z(t),this.messagesPath=g.join(this.sessionDir,K),this.snapshotPath=g.join(this.sessionDir,Y),this.summaryPath=g.join(this.sessionDir,V),this.loadSnapshot(),this.loadSummary()}async send(t,e){const s=++this.sendGeneration,n=this.agent&&this.terminalState==="open"?S(this.pendingBaseMessages):null;n&&(this.agent?.abort(),this.agent=null,this.restoredMessages=n,this.finalizePromise=Promise.resolve());const i=L(),a=i.machineToken??i.accessToken;if(!a){this.emit("agentEvent",{state:"error",runId:this.runId,seq:++this.seq,message:"\u672A\u914D\u5BF9\uFF0C\u8BF7\u5148\u8FD0\u884C shennian \u5B8C\u6210\u673A\u5668\u914D\u5BF9"});return}this.authToken=a,this.proxyUrl=(i.serverUrl??N.cn.url).replace(/\/$/,"");const h=O("pi"),r=i.apiKeys?.dashscope?.trim();this.providerConfig=h??(r?{agent:"pi",token:r,updatedAt:""}:void 0),this.runId=b(),this.seq=0,this.emittedLengths.clear(),this.terminalState="open",this.agent||this.initAgent(),await this.finalizePromise.catch(()=>{}),this.agent?.setModel(M(e??J)),this.pendingBaseMessages=S(this.agent?.state.messages??[]);const d=this.runId,m=new Promise((c,u)=>{this.pendingSendStart={runId:d,resolve:c,reject:u}});this.emit("agentEvent",{state:"init",runId:d,seq:++this.seq}),this.agent.prompt(t).then(async()=>{s===this.sendGeneration&&(this.resolvePendingSendStart(d),await this.finalizePromise.catch(()=>{}))}).catch(c=>{if(s!==this.sendGeneration||(this.rejectPendingSendStart(d,c),this.terminalState!=="open"))return;this.terminalState="error";const u=c instanceof Error?c.message:String(c);u.includes("429")||u.includes("daily_quota_exceeded")||u.includes("nian_quota_exceeded")?this.emit("agentEvent",{state:"error",runId:d,seq:++this.seq,message:"Nian \u4ECA\u65E5\u989D\u5EA6\u5DF2\u7528\u5B8C\uFF0C\u6B21\u65E5\u81EA\u52A8\u6062\u590D\u3002"}):this.emit("agentEvent",{state:"error",runId:d,seq:++this.seq,message:u})}),await m}async getStatus(){const t=!!(this.runId&&this.terminalState==="open");return{active:t,runId:this.runId||null,runPhase:null,canStop:t}}initAgent(){const t=this.workDir??process.cwd(),e=et(t,this.extraEnv),s=U(t),n=new I({initialState:{systemPrompt:[W,s,`\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\uFF1A${t}`,F(this.externalChannel,t,this.shennianSessionId??void 0)].filter(Boolean).join(`
8
8
 
9
- `),model:M(),tools:e},streamFn:(i,a,h)=>{const r=this.providerConfig;return r?.token?j(M(i.id,{provider:"dashscope",baseUrl:r.baseUrl||Q,compat:{supportsDeveloperRole:!1,supportsStore:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",thinkingFormat:"qwen"}}),a,{...h,apiKey:r.token}):I(i,a,{...h,authToken:this.authToken,proxyUrl:this.proxyUrl})},transformContext:i=>this.compressContext(i)});this.agent=n,this.restoredMessages.length>0?n.replaceMessages(S(this.restoredMessages)):this.cachedSummary&&(n.appendMessage({role:"user",content:[{type:"text",text:`[\u4E4B\u524D\u7684\u5BF9\u8BDD\u6458\u8981]
9
+ `),model:M(),tools:e},streamFn:(i,a,h)=>{const r=this.providerConfig;return r?.token?j(M(i.id,{provider:"dashscope",baseUrl:r.baseUrl||Q,compat:{supportsDeveloperRole:!1,supportsStore:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",thinkingFormat:"qwen"}}),a,{...h,apiKey:r.token}):T(i,a,{...h,authToken:this.authToken,proxyUrl:this.proxyUrl})},transformContext:i=>this.compressContext(i)});this.agent=n,this.restoredMessages.length>0?n.replaceMessages(S(this.restoredMessages)):this.cachedSummary&&(n.appendMessage({role:"user",content:[{type:"text",text:`[\u4E4B\u524D\u7684\u5BF9\u8BDD\u6458\u8981]
10
10
  ${this.cachedSummary}`}],timestamp:Date.now()}),n.appendMessage({role:"assistant",content:[{type:"text",text:"\u597D\u7684\uFF0C\u6211\u5DF2\u4E86\u89E3\u4E4B\u524D\u7684\u5BF9\u8BDD\u4E0A\u4E0B\u6587\uFF0C\u8BF7\u7EE7\u7EED\u3002"}],timestamp:Date.now()})),n.subscribe(i=>{if(this.agent!==n||this.terminalState!=="open")return;const a=++this.seq,h=this.runId;switch(i.type){case"agent_start":this.resolvePendingSendStart(h),this.emit("agentEvent",{state:"start",runId:h,seq:a});break;case"message_update":{const r=i.message;if(r.role!=="assistant")break;const d=r.content??[];for(let m=0;m<d.length;m++){const c=d[m];if(c.type==="text"&&c.text){const u=`text:${m}`,f=this.emittedLengths.get(u)??0;if(c.text.length>f){const x=c.text.slice(f);this.emittedLengths.set(u,c.text.length),this.emit("agentEvent",{state:"delta",runId:h,seq:a,text:x})}}else if(c.type==="thinking"&&c.thinking){const u=`thinking:${m}`,f=this.emittedLengths.get(u)??0;if(c.thinking.length>f){const x=c.thinking.slice(f);this.emittedLengths.set(u,c.thinking.length),this.emit("agentEvent",{state:"delta",runId:h,seq:a,text:x,thinking:!0})}}}break}case"tool_execution_start":this.emit("agentEvent",{state:"tool-call",runId:h,seq:a,name:i.toolName,args:i.args});break;case"tool_execution_end":this.emit("agentEvent",{state:"tool-result",runId:h,seq:a,name:i.toolName,result:typeof i.result=="string"?i.result:JSON.stringify(i.result)});break;case"agent_end":{this.terminalState="final";const r=i.messages,m=[...r].reverse().find(c=>c.role==="assistant")?.usage;this.emit("agentEvent",{state:"final",runId:h,seq:a,usage:m?{inputTokens:m.input??0,outputTokens:m.output??0}:void 0}),this.finalizePromise=this.finalizeTurn(r);break}}})}async compressAndReplace(){if(!this.agent||this.compressing)return;const t=this.agent.state.messages;if(w(t)<v)return;const s=this.splitMessages(t);if(!s)return;const n=await this.generateSummary(s.toCompress);if(!n)return;this.cachedSummary=n,this.lastSummaryMsgCount+=s.toCompress.length;const i=[{role:"user",content:[{type:"text",text:`[\u5386\u53F2\u5BF9\u8BDD\u6458\u8981]
11
11
  ${n}`}],timestamp:Date.now()},{role:"assistant",content:[{type:"text",text:"\u597D\u7684\uFF0C\u6211\u5DF2\u4E86\u89E3\u4E0A\u4E0B\u6587\u3002"}],timestamp:Date.now()},...s.toKeep];this.agent.replaceMessages(i)}async compressContext(t){if(w(t)<v||!this.cachedSummary)return t;const s=this.splitMessages(t);return s?[{role:"user",content:[{type:"text",text:`[\u5386\u53F2\u5BF9\u8BDD\u6458\u8981]
12
12
  ${this.cachedSummary}`}],timestamp:Date.now()},...s.toKeep]:t}splitMessages(t){const e=t.filter(n=>n.role!=="system");if(e.length<=k)return null;let s=e.length-k;for(;s>0&&e[s].role==="toolResult";)s--;return s<=0?null:{toCompress:e.slice(0,s),toKeep:e.slice(s)}}async generateSummary(t){if(!this.authToken||!this.proxyUrl||this.compressing)return this.cachedSummary;this.compressing=!0;try{const e=G(t);if(e.length<100)return null;const s=e.length>1e4?e.slice(0,1e4)+`
@@ -73,3 +73,4 @@ export declare function weChatChannelOutboundLedgerPath(workDir: string, runtime
73
73
  export declare function weChatChannelHelperTracePath(workDir: string, runtimeId: string): string;
74
74
  export declare function safeWeChatChannelRuntimePathSegment(runtimeId: string): string;
75
75
  export declare function observedMessageToExternalEvent(config: ExternalChannelConfig, binding: WeChatChannelBindingConfig, message: WeChatChannelObservedMessage): ExternalMessageEvent | null;
76
+ export declare function observedMessagesToExternalEvent(config: ExternalChannelConfig, binding: WeChatChannelBindingConfig, messages: WeChatChannelObservedMessage[]): ExternalMessageEvent | null;
@@ -1,9 +1,16 @@
1
- import w from"node:crypto";import m from"node:fs";import f from"node:path";import{loadConfig as N}from"../../config/index.js";import{createWeChatChannelProductRunner as O}from"../wechat-channel/runner.js";import{createWeChatChannelApiClient as k}from"../wechat-channel/client.js";import{createWeChatAutomationLane as $}from"../wechat-channel/automation-lane.js";import{createWeChatChannelRuntime as D}from"../wechat-channel/runtime.js";import{cancelWeChatOutboundRecord as T,enqueueWeChatOutboundReply as K,loadWeChatChannelOutboundLedger as h,saveWeChatChannelOutboundLedger as I}from"../wechat-channel/outbound-ledger.js";import{loadWeChatChannelLedger as S}from"../wechat-channel/ledger.js";const z="wechat-channel";function de(e){const t=D({runtimeId:e.config.id,machineId:Q(),pollIntervalMs:e.secret.pollIntervalMs,foregroundPolicy:j(e.secret.forceForeground),bindings:B(e.config,e.secret)}),n=P(e.config.workDir,t.runtimeId),a=u(e.config.workDir,t.runtimeId),r=F(e.config.workDir,t.runtimeId),o=[];m.mkdirSync(f.dirname(r),{recursive:!0}),m.writeFileSync(r,"");const s=e.createRunner??O,c=L(),d=s({runtime:t,workDir:e.config.workDir,api:c,ledgerPath:n,outboundLedgerPath:a,lane:$(),helperRequestLogger:H(r),onInboundMessages:(C,A)=>{const M=t.bindings.find(p=>p.bindingId===C.bindingId)??C;for(const p of A){const y=x(e.config,M,p);if(!y)continue;const W=e.onMessage?.({...y,managerSessionId:e.config.managerSessionId})??y;o.push(W)}}});return{runtime:t,runner:d,emitted:o,ledgerPath:n,outboundLedgerPath:a,helperTracePath:r}}function L(){let e=null;const t=()=>(e??=k(),e);return{observe:(...n)=>t().observe(...n),structureWindow:(...n)=>t().structureWindow(...n),embedVisual:(...n)=>t().embedVisual(...n),classifyWindow:(...n)=>t().classifyWindow(...n),upsertRuntime:async(...n)=>(await Promise.resolve().then(()=>t().upsertRuntime(...n)).catch(()=>null),{ok:!0}),ingest:async(...n)=>(await Promise.resolve().then(()=>t().ingest(...n)).catch(()=>null),{ok:!0}),reportRunStatus:async(...n)=>(await Promise.resolve().then(()=>t().reportRunStatus(...n)).catch(()=>null),{ok:!0}),reportOutboundStatus:async(...n)=>(await Promise.resolve().then(()=>t().reportOutboundStatus(...n)).catch(()=>null),{ok:!0})}}function j(e){return e===!1?"polite":"work"}function ue(e){const t=e.config.id,n=R(e.config,e.conversationName),a=S(P(e.config.workDir,t),t),r=u(e.config.workDir,t),o=h(r,t),s=e.reply.attachment?[J(e.reply.attachment)]:[],c=K({ledger:o,replyId:e.reply.messageId||e.reply.idempotencyKey||l("wechat-channel-reply",`${Date.now()}:${e.reply.text}`),idempotencyKey:e.reply.idempotencyKey||l("wechat-channel-send",`${e.config.id}
1
+ import C from"node:crypto";import p from"node:fs";import y from"node:path";import{loadConfig as W}from"../../config/index.js";import{createWeChatChannelProductRunner as $}from"../wechat-channel/runner.js";import{createWeChatChannelApiClient as O}from"../wechat-channel/client.js";import{createWeChatAutomationLane as k}from"../wechat-channel/automation-lane.js";import{createWeChatChannelRuntime as D}from"../wechat-channel/runtime.js";import{cancelWeChatOutboundRecord as T,enqueueWeChatOutboundReply as K,loadWeChatChannelOutboundLedger as b,saveWeChatChannelOutboundLedger as S}from"../wechat-channel/outbound-ledger.js";import{loadWeChatChannelLedger as P}from"../wechat-channel/ledger.js";const j="wechat-channel";function fe(e){const t=D({runtimeId:e.config.id,machineId:ee(),pollIntervalMs:e.secret.pollIntervalMs,foregroundPolicy:E(e.secret.forceForeground),bindings:q(e.config,e.secret)}),n=x(e.config.workDir,t.runtimeId),o=f(e.config.workDir,t.runtimeId),r=F(e.config.workDir,t.runtimeId),a=[];p.mkdirSync(y.dirname(r),{recursive:!0}),p.writeFileSync(r,"");const c=e.createRunner??$,l=z(),u=c({runtime:t,workDir:e.config.workDir,api:l,ledgerPath:n,outboundLedgerPath:o,lane:k(),helperRequestLogger:B(r),onInboundMessages:(h,s)=>{const m=t.bindings.find(N=>N.bindingId===h.bindingId)??h,g=v(e.config,m,s);if(!g)return;const R=e.onMessage?.({...g,managerSessionId:e.config.managerSessionId})??g;a.push(R)}});return{runtime:t,runner:u,emitted:a,ledgerPath:n,outboundLedgerPath:o,helperTracePath:r}}function z(){let e=null;const t=()=>(e??=O(),e);return{observe:(...n)=>t().observe(...n),structureWindow:(...n)=>t().structureWindow(...n),embedVisual:(...n)=>t().embedVisual(...n),classifyWindow:(...n)=>t().classifyWindow(...n),upsertRuntime:async(...n)=>(await Promise.resolve().then(()=>t().upsertRuntime(...n)).catch(()=>null),{ok:!0}),ingest:async(...n)=>(await Promise.resolve().then(()=>t().ingest(...n)).catch(()=>null),{ok:!0}),reportRunStatus:async(...n)=>(await Promise.resolve().then(()=>t().reportRunStatus(...n)).catch(()=>null),{ok:!0}),reportOutboundStatus:async(...n)=>(await Promise.resolve().then(()=>t().reportOutboundStatus(...n)).catch(()=>null),{ok:!0})}}function E(e){return e===!1?"polite":"work"}function he(e){const t=e.config.id,n=A(e.config,e.conversationName),o=P(x(e.config.workDir,t),t),r=f(e.config.workDir,t),a=b(r,t),c=e.reply.attachment?[X(e.reply.attachment)]:[],l=K({ledger:a,replyId:e.reply.messageId||e.reply.idempotencyKey||d("wechat-channel-reply",`${Date.now()}:${e.reply.text}`),idempotencyKey:e.reply.idempotencyKey||d("wechat-channel-send",`${e.config.id}
2
2
  ${e.reply.conversationId}
3
3
  ${e.reply.text}
4
- ${s.join(`
5
- `)}`),bindingId:n,runtimeId:t,sessionId:e.config.sessionId||e.config.managerSessionId,conversationName:e.conversationName,replyBaseRevision:a.bindings[n]?.revision??0,text:e.reply.text,attachmentLocalRefs:s});return I(r,o),c}function me(e){return h(u(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).length}function fe(e){return h(u(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).slice(0,100).map(n=>({replyId:n.replyId,idempotencyKey:n.idempotencyKey,status:n.sendStatus,conversationName:n.conversationName,reasonCode:n.deferReason||n.failureCode||null,nextAttemptAt:n.nextAttemptAt??null,queuedAt:n.queuedAt??n.createdAt,lastAttemptAt:n.lastAttemptAt??null,attemptCount:n.attemptCount??0,commitStage:n.commitStage??null}))}function he(e){const t=Y(e.limit,20,1,100),n=S(e.product.ledgerPath,e.product.runtime.runtimeId),a=[];for(const r of e.product.runtime.bindings){const o=n.bindings[r.bindingId]?.recent??[];for(const s of o.slice(-t)){const c=x(e.config,r,s);c&&a.push(c)}}return a}function ge(e){const t=u(e.config.workDir,e.config.id),n=h(t,e.config.id),a=String(e.idempotencyKey??"").trim(),r=String(e.replyId??"").trim();if(!a&&!r)return{cancelled:!1};const o=n.records.find(c=>a&&c.idempotencyKey===a||r&&c.replyId===r);if(!o)return{cancelled:!1};const s=o.sendStatus;return T(o,e.reason||"user_cancelled"),o.sendStatus!==s?(I(t,n),{cancelled:!0,status:o.sendStatus,record:o}):{cancelled:!1,status:o.sendStatus,record:o}}function pe(e){return e===z}function E(e){return l("wechat-conversation",i(e))}function _(e,t){return l("wechat-channel-binding",`${e}
6
- ${i(t)}`)}function P(e,t){return f.join(e,"wechat-channel",`${b(t)}.ledger.json`)}function u(e,t){return f.join(e,"wechat-channel",`${b(t)}.outbound-ledger.json`)}function F(e,t){return f.join(e,"wechat-channel",`${b(t)}.helper-trace.jsonl`)}function b(e){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"wechat-channel-runtime"}function H(e){return t=>{m.appendFileSync(e,`${JSON.stringify(q(t))}
7
- `)}}function q(e){const t={phase:e.phase,at:e.at,id:e.id,command:e.command};return e.traceId&&(t.traceId=e.traceId),e.timeoutMs!=null&&(t.timeoutMs=e.timeoutMs),e.durationMs!=null&&(t.durationMs=e.durationMs),e.params!==void 0&&(t.params=g(e.params)),e.ok!==void 0&&(t.ok=e.ok),e.errorCode&&(t.errorCode=e.errorCode),e.errorSummary&&(t.errorSummary=e.errorSummary),e.latencyMs!=null&&(t.latencyMs=e.latencyMs),e.result!==void 0&&(t.result=g(e.result)),t}function g(e,t="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return e.length>240||/(base64|bytes|data|image|screenshot|png|jpeg|jpg|buffer)/i.test(t)&&e.length>48?{type:"string",length:e.length,sha256:w.createHash("sha256").update(e).digest("hex").slice(0,16),preview:e.slice(0,120)}:e;if(Array.isArray(e)){const o=e.slice(0,10).map(s=>g(s,t,n+1));return e.length>o.length?{type:"array",length:e.length,items:o}:o}if(typeof e!="object")return String(e);if(n>=5)return{type:"object",truncated:!0};const a=e,r={};for(const[o,s]of Object.entries(a))r[o]=g(s,o,n+1);return r}function B(e,t){return Z(t).map(n=>({bindingId:R(e,n),sessionId:e.sessionId||e.managerSessionId,conversationDisplayName:n,enabled:!0,allowReply:t.canReply!==!1,downloadMedia:t.downloadAttachments!==!1,selfTriggerMarker:i(t.selfTriggerMarker||"")||null}))}function R(e,t){return e.managedBy==="session-sync"||e.id.startsWith("wechat-binding:")?e.id:_(e.id,t)}function x(e,t,n){const a=i(n.normalizedText||n.anchorText||n.textExcerpt||""),r=V(n);if(!a&&r.length===0)return null;const o=i(n.senderName||"");return{type:"external.message",channelId:e.id,channelType:"wechat-rpa",conversationId:E(t.conversationDisplayName),conversationName:t.conversationDisplayName,messageId:l("wechat-message",`${t.bindingId}
8
- ${n.stableMessageKey}`),sender:{id:l("wechat-sender",`${t.bindingId}
9
- ${o||n.senderRole}`),name:o||null},text:a,attachments:r,receivedAt:X(n.observedAt),isMentioned:!1,replyTarget:"",rawRef:n.stableMessageKey}}function V(e){const t=e.mediaMetadata;return v(t).map(a=>{const r=a,o=typeof r.localPath=="string"?i(r.localPath):"",s=typeof r.thumbnailPath=="string"?i(r.thumbnailPath):"",c=typeof r.url=="string"?i(r.url):"",d=Number(r.size??r.sizeBytes??0);return{type:i(String(r.type||r.kind||e.kind||"file"))||"file",...r.name||r.fileName?{name:i(String(r.name||r.fileName))}:{},...c?{url:c}:{},...typeof r.mimeType=="string"?{mimeType:i(r.mimeType)}:{},...typeof r.extension=="string"?{extension:i(r.extension)}:{},...Number.isFinite(d)&&d>0?{size:d}:{},...o?{localPath:o}:{},...s?{thumbnailPath:s}:{},...typeof r.hash=="string"||typeof r.sha256=="string"?{hash:i(String(r.hash||r.sha256))}:{},availability:U(r.availability,{localPath:o,url:c}),...typeof r.providerError=="string"?{providerError:i(r.providerError)}:{},...typeof r.sourceAction=="string"?{sourceAction:i(r.sourceAction)}:{},...G(r.materializationKind)?{materializationKind:r.materializationKind}:{},...typeof r.isOriginal=="boolean"?{isOriginal:r.isOriginal}:{},...typeof r.mimeKindMatches=="boolean"?{mimeKindMatches:r.mimeKindMatches}:{}}})}function v(e){if(!e||typeof e!="object")return[];const t=e;return Array.isArray(t.attachments)?t.attachments:t.attachment&&typeof t.attachment=="object"?[t.attachment]:t.localPath||t.url||t.name||t.fileName||t.availability?[t]:[]}function U(e,t){return e==="edge-local"||e==="server-url"||e==="pending-download"||e==="metadata-only"||e==="unavailable-large"?e:t.localPath?"edge-local":t.url?"server-url":"metadata-only"}function G(e){return e==="original-file"||e==="clipboard-image"||e==="preview-crop"||e==="metadata"}function J(e){const t=i(e.localPath||"");if(!t)throw new Error("WeChat channel product send requires a local attachment path on this machine");if(!m.statSync(t).isFile())throw new Error(`WeChat channel product attachment is not a file: ${t}`);return t}function Z(e){return Array.isArray(e.groups)?e.groups.map(t=>i(t?.name||"")).filter(Boolean):[]}function Q(){return process.env.SHENNIAN_MACHINE_ID?.trim()||N().machineId||"local"}function X(e){if(!e)return new Date().toISOString();const t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function i(e){return e.replace(/\s+/g," ").trim()}function Y(e,t,n,a){const r=Number(e);return Number.isFinite(r)?Math.max(n,Math.min(a,Math.floor(r))):t}function l(e,t){return`${e}:${w.createHash("sha256").update(t).digest("hex").slice(0,24)}`}export{z as WECHAT_RPA_PRODUCT_SOURCE,ge as cancelWeChatRpaProductOutboundReply,me as countPendingWeChatRpaProductOutbound,de as createWeChatRpaProductSourceConnection,ue as enqueueWeChatRpaProductOutboundReply,pe as isWeChatRpaProductSource,fe as listPendingWeChatRpaProductOutbound,he as listWeChatRpaProductRecentMessages,x as observedMessageToExternalEvent,b as safeWeChatChannelRuntimePathSegment,_ as weChatChannelBindingId,E as weChatChannelConversationId,F as weChatChannelHelperTracePath,P as weChatChannelLedgerPath,u as weChatChannelOutboundLedgerPath};
4
+ ${c.join(`
5
+ `)}`),bindingId:n,runtimeId:t,sessionId:e.config.sessionId||e.config.managerSessionId,conversationName:e.conversationName,replyBaseRevision:o.bindings[n]?.revision??0,text:e.reply.text,attachmentLocalRefs:c});return S(r,a),l}function ge(e){return b(f(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).length}function pe(e){return b(f(e.config.workDir,e.config.id),e.config.id).records.filter(n=>["queued","sending","sent_unconfirmed"].includes(n.sendStatus)).slice(0,100).map(n=>({replyId:n.replyId,idempotencyKey:n.idempotencyKey,status:n.sendStatus,conversationName:n.conversationName,reasonCode:n.deferReason||n.failureCode||null,nextAttemptAt:n.nextAttemptAt??null,queuedAt:n.queuedAt??n.createdAt,lastAttemptAt:n.lastAttemptAt??null,attemptCount:n.attemptCount??0,commitStage:n.commitStage??null}))}function ye(e){const t=ne(e.limit,20,1,100),n=P(e.product.ledgerPath,e.product.runtime.runtimeId),o=[];for(const r of e.product.runtime.bindings){const a=n.bindings[r.bindingId]?.recent??[];for(const c of a.slice(-t)){const l=M(e.config,r,c);l&&o.push(l)}}return o}function be(e){const t=f(e.config.workDir,e.config.id),n=b(t,e.config.id),o=String(e.idempotencyKey??"").trim(),r=String(e.replyId??"").trim();if(!o&&!r)return{cancelled:!1};const a=n.records.find(l=>o&&l.idempotencyKey===o||r&&l.replyId===r);if(!a)return{cancelled:!1};const c=a.sendStatus;return T(a,e.reason||"user_cancelled"),a.sendStatus!==c?(S(t,n),{cancelled:!0,status:a.sendStatus,record:a}):{cancelled:!1,status:a.sendStatus,record:a}}function we(e){return e===j}function L(e){return d("wechat-conversation",i(e))}function _(e,t){return d("wechat-channel-binding",`${e}
6
+ ${i(t)}`)}function x(e,t){return y.join(e,"wechat-channel",`${I(t)}.ledger.json`)}function f(e,t){return y.join(e,"wechat-channel",`${I(t)}.outbound-ledger.json`)}function F(e,t){return y.join(e,"wechat-channel",`${I(t)}.helper-trace.jsonl`)}function I(e){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"wechat-channel-runtime"}function B(e){return t=>{p.appendFileSync(e,`${JSON.stringify(H(t))}
7
+ `)}}function H(e){const t={phase:e.phase,at:e.at,id:e.id,command:e.command};return e.traceId&&(t.traceId=e.traceId),e.timeoutMs!=null&&(t.timeoutMs=e.timeoutMs),e.durationMs!=null&&(t.durationMs=e.durationMs),e.params!==void 0&&(t.params=w(e.params)),e.ok!==void 0&&(t.ok=e.ok),e.errorCode&&(t.errorCode=e.errorCode),e.errorSummary&&(t.errorSummary=e.errorSummary),e.latencyMs!=null&&(t.latencyMs=e.latencyMs),e.result!==void 0&&(t.result=w(e.result)),t}function w(e,t="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string")return e.length>240||/(base64|bytes|data|image|screenshot|png|jpeg|jpg|buffer)/i.test(t)&&e.length>48?{type:"string",length:e.length,sha256:C.createHash("sha256").update(e).digest("hex").slice(0,16),preview:e.slice(0,120)}:e;if(Array.isArray(e)){const a=e.slice(0,10).map(c=>w(c,t,n+1));return e.length>a.length?{type:"array",length:e.length,items:a}:a}if(typeof e!="object")return String(e);if(n>=5)return{type:"object",truncated:!0};const o=e,r={};for(const[a,c]of Object.entries(o))r[a]=w(c,a,n+1);return r}function q(e,t){return Y(t).map(n=>({bindingId:A(e,n),sessionId:e.sessionId||e.managerSessionId,conversationDisplayName:n,enabled:!0,allowReply:t.canReply!==!1,downloadMedia:t.downloadAttachments!==!1,selfTriggerMarker:i(t.selfTriggerMarker||"")||null}))}function A(e,t){return e.managedBy==="session-sync"||e.id.startsWith("wechat-binding:")?e.id:_(e.id,t)}function M(e,t,n){const o=i(n.normalizedText||n.anchorText||n.textExcerpt||""),r=V(n);if(!o&&r.length===0)return null;const a=i(n.senderName||"");return{type:"external.message",channelId:e.id,channelType:"wechat-rpa",conversationId:L(t.conversationDisplayName),conversationName:t.conversationDisplayName,messageId:d("wechat-message",`${t.bindingId}
8
+ ${n.stableMessageKey}`),sender:{id:d("wechat-sender",`${t.bindingId}
9
+ ${a||n.senderRole}`),name:a||null},text:o,attachments:r,receivedAt:te(n.observedAt),isMentioned:!1,replyTarget:"",rawRef:n.stableMessageKey}}function v(e,t,n){const o=n.map(s=>M(e,t,s)).filter(s=>s!=null);if(o.length<=1)return o[0]??null;const r=o[0],a=n.map(s=>i(s.stableMessageKey||"")).filter(Boolean),l=new Set(o.map(s=>i(s.sender.name||""))).size===1?r.sender.name??null:null,u=new Set(o.map(s=>s.sender.id)).size===1?r.sender.id:d("wechat-sender-batch",`${t.bindingId}
10
+ ${a.join(`
11
+ `)}`),h=o.map(s=>{const m=i(s.text);return m?l!==null?m:`${i(s.sender.name||"")||"\u5BF9\u65B9"}: ${m}`:""}).filter(Boolean).join(`
12
+ `);return{...r,messageId:d("wechat-message-batch",`${t.bindingId}
13
+ ${a.join(`
14
+ `)}`),sender:{id:u,name:l},text:h,attachments:G(o.flatMap(s=>s.attachments)),receivedAt:J(o.map(s=>s.receivedAt)),rawRef:a.join(`
15
+ `)}}function V(e){const t=e.mediaMetadata;return U(t).map(o=>{const r=o,a=typeof r.localPath=="string"?i(r.localPath):"",c=typeof r.thumbnailPath=="string"?i(r.thumbnailPath):"",l=typeof r.url=="string"?i(r.url):"",u=Number(r.size??r.sizeBytes??0);return{type:i(String(r.type||r.kind||e.kind||"file"))||"file",...r.name||r.fileName?{name:i(String(r.name||r.fileName))}:{},...l?{url:l}:{},...typeof r.mimeType=="string"?{mimeType:i(r.mimeType)}:{},...typeof r.extension=="string"?{extension:i(r.extension)}:{},...Number.isFinite(u)&&u>0?{size:u}:{},...a?{localPath:a}:{},...c?{thumbnailPath:c}:{},...typeof r.hash=="string"||typeof r.sha256=="string"?{hash:i(String(r.hash||r.sha256))}:{},availability:Z(r.availability,{localPath:a,url:l}),...typeof r.providerError=="string"?{providerError:i(r.providerError)}:{},...typeof r.sourceAction=="string"?{sourceAction:i(r.sourceAction)}:{},...Q(r.materializationKind)?{materializationKind:r.materializationKind}:{},...typeof r.isOriginal=="boolean"?{isOriginal:r.isOriginal}:{},...typeof r.mimeKindMatches=="boolean"?{mimeKindMatches:r.mimeKindMatches}:{}}})}function U(e){if(!e||typeof e!="object")return[];const t=e;return Array.isArray(t.attachments)?t.attachments:t.attachment&&typeof t.attachment=="object"?[t.attachment]:t.localPath||t.url||t.name||t.fileName||t.availability?[t]:[]}function G(e){const t=new Set,n=[];for(const o of e){const r=[o.localPath||"",o.url||"",o.thumbnailPath||"",o.hash||"",o.name||"",o.mimeType||"",o.type||""].join(`
16
+ `);t.has(r)||(t.add(r),n.push(o))}return n}function J(e){let t=0;for(const n of e){const o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t?new Date(t).toISOString():new Date().toISOString()}function Z(e,t){return e==="edge-local"||e==="server-url"||e==="pending-download"||e==="metadata-only"||e==="unavailable-large"?e:t.localPath?"edge-local":t.url?"server-url":"metadata-only"}function Q(e){return e==="original-file"||e==="clipboard-image"||e==="preview-crop"||e==="metadata"}function X(e){const t=i(e.localPath||"");if(!t)throw new Error("WeChat channel product send requires a local attachment path on this machine");if(!p.statSync(t).isFile())throw new Error(`WeChat channel product attachment is not a file: ${t}`);return t}function Y(e){return Array.isArray(e.groups)?e.groups.map(t=>i(t?.name||"")).filter(Boolean):[]}function ee(){return process.env.SHENNIAN_MACHINE_ID?.trim()||W().machineId||"local"}function te(e){if(!e)return new Date().toISOString();const t=new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function i(e){return e.replace(/\s+/g," ").trim()}function ne(e,t,n,o){const r=Number(e);return Number.isFinite(r)?Math.max(n,Math.min(o,Math.floor(r))):t}function d(e,t){return`${e}:${C.createHash("sha256").update(t).digest("hex").slice(0,24)}`}export{j as WECHAT_RPA_PRODUCT_SOURCE,be as cancelWeChatRpaProductOutboundReply,ge as countPendingWeChatRpaProductOutbound,fe as createWeChatRpaProductSourceConnection,he as enqueueWeChatRpaProductOutboundReply,we as isWeChatRpaProductSource,pe as listPendingWeChatRpaProductOutbound,ye as listWeChatRpaProductRecentMessages,M as observedMessageToExternalEvent,v as observedMessagesToExternalEvent,I as safeWeChatChannelRuntimePathSegment,_ as weChatChannelBindingId,L as weChatChannelConversationId,F as weChatChannelHelperTracePath,x as weChatChannelLedgerPath,f as weChatChannelOutboundLedgerPath};
@@ -1,24 +1,24 @@
1
- import J from"node:http";import{randomBytes as Y,randomUUID as m}from"node:crypto";import k from"node:fs";import N from"node:os";import y from"node:path";import{AVAILABLE_BUILTIN_AGENT_TYPES as V,extractPayloadText as Q,formatExternalConversationText as X,formatExternalMessageLine as Z,formatExternalAttachmentReference as ee,isAgentHiddenPayload as te,isToolPayload as ne}from"@shennian/wire";import{ManagerRegistry as re}from"./registry.js";import{readMessages as ae}from"../session/store.js";import{listProjectedSessions as se}from"../session/projection.js";import{ChannelRuntime as ie}from"../channels/runtime.js";import{WeChatRpaSessionBindingSync as oe}from"../channels/wechat-rpa-session-sync.js";import{splitExternalReplyText as ce}from"../channels/reply-split.js";import{loadConfig as b,resolveShennianPath as le}from"../config/index.js";import{weChatChannelConversationId as de}from"../channels/wechat-rpa/product-channel.js";import{buildExternalChannelInstructions as ue}from"../agents/external-channel-instructions.js";import{readDirectWeChatLatestOnce as he,sendDirectWeChatMessageOnce as P}from"../commands/wechat.js";import{createWeChatChannelApiClient as pe}from"../channels/wechat-channel/client.js";import{createWeChatAutomationLane as me}from"../channels/wechat-channel/automation-lane.js";const M=Number(process.env.SHENNIAN_MANAGER_IPC_BODY_MAX_BYTES||2*1024*1024),A=12*6e4;let $=null;function Qe(a){$=a}function Xe(){return $}function R(a){return y.resolve(a||N.homedir())}function u(a,e,r){a.writeHead(e,{"content-type":"application/json; charset=utf-8"}),a.end(JSON.stringify(r))}function ge(a){return/^agent-(.+)-\d+$/.exec(a)?.[1]??null}function fe(a){return a==="manager"?!1:a.startsWith("custom:")?!0:V.includes(a)}function ye(a){const e=/^agent-.+-(\d+)$/.exec(a);if(!e)return null;const r=Number(e[1]);return Number.isInteger(r)&&r>=0?r:null}function _(a){return a.replace(/\r\n/g,`
2
- `).trim()}function we(a){try{const e=JSON.parse(a),r=e.type==="tool_result"||e.result?"tool_result":"tool_call",t=e.name||"tool",n=typeof e.result=="string"?e.result.replace(/\s+/g," ").trim():"",s=n.length>220?`${n.slice(0,220)}...`:n;return s?`[${r}] ${t}: ${s}`:`[${r}] ${t}`}catch{return"[tool]"}}function B(a){if(!a||typeof a!="object")return;const e=a,r=String(e.kind||""),t=String(e.name||""),n=String(e.mimeType||""),s=String(e.dataBase64||""),o=String(e.localPath||""),i=String(e.url||""),c=Number(e.size||0);if(s)throw new Error("Manager IPC external attachments must use localPath or url; dataBase64 is not accepted");if(!(r!=="image"&&r!=="video"&&r!=="file")&&!(!t||!n||!Number.isFinite(c)||c<0)&&!(!o&&!i))return{kind:r,name:t,mimeType:n,size:c,...o?{localPath:o}:{},...i?{url:i}:{}}}function L(a){const e=a.binding&&typeof a.binding=="object"&&!Array.isArray(a.binding)?a.binding:{},r=String(e.sessionId||a.managerSessionId||"").trim(),t=String(e.channelId||"").trim(),n=String(e.conversationId||"").trim(),s=String(e.conversationName||a.conversation||"").trim(),o=String(e.workDir||a.workDir||"").trim();if(!r)throw new Error("WeChat tool sessionId is required");if(!t)throw new Error("WeChat tool channelId is required");if(!n)throw new Error("WeChat tool conversationId is required");if(!s)throw new Error("WeChat tool conversationName is required");if(!o)throw new Error("WeChat tool workDir is required");return{sessionId:r,channelId:t,conversationId:n,conversationName:s,workDir:o}}function Ie(a,e){const r=[...a].sort((d,l)=>d.ts-l.ts),t=[];let n=null,s=null,o=null,i="";const c=()=>{if(!n)return;const d=i.trim();d&&t.push({...n,id:`${n.id}-compact`,payload:d}),n=null,s=null,o=null,i=""};for(const d of r){if(te(d.payload)){c();continue}if(d.role==="user"){c(),t.push(d);continue}if(ne(d.payload)){c(),t.push({...d,payload:we(d.payload)});continue}const l=Q(d.payload);if(!l.trim())continue;const h=ge(d.id),p=ye(d.id);n&&n.role===d.role&&s===h&&h&&p!==null&&o!==null&&p===o+1?(i+=l,n.ts=d.ts,o=p):(c(),n=d,s=h,o=p,i=l)}return c(),t.slice(-e).sort((d,l)=>l.ts-d.ts)}async function Se(a){const e=[];let r=0;for await(const n of a){const s=Buffer.from(n);if(r+=s.byteLength,Number.isFinite(M)&&M>0&&r>M)throw new Error(`Manager IPC request body is too large. Max: ${M} bytes.`);e.push(s)}const t=Buffer.concat(e).toString("utf-8");return t?JSON.parse(t):{}}function w(a,e,r,t){a.client.sendRes({type:"res",id:e,ok:r,...r?{payload:t}:{error:String(t.error||"unknown error")}})}function q(a){return/binding not found|unknown method|not supported|relay is not connected|no external channel/i.test(a)}function F(){return ke()?y.join(N.tmpdir(),"shennian-vitest-runtime",String(process.pid),"manager-ipc.json"):le("runtime","manager-ipc.json")}function ke(){return(process.env.VITEST==="true"||!!process.env.VITEST_WORKER_ID)&&!process.env.SHENNIAN_HOME?.trim()}class Ze{opts;registry=new re;channelRuntime;weChatRpaSessionSync;server=null;ipcUrl=null;ipcToken=Y(24).toString("hex");healthTimer=null;startPromise=null;workerTextAcc=new Map;weChatAutomationLane;constructor(e){this.opts=e,this.weChatAutomationLane=e.weChatAutomationLane??me(),this.channelRuntime=e.channelRuntime??new ie((r,t)=>{this.handleExternalMessage(r,t)},r=>this.registry.createReplyTarget(r).replyTarget,{createWeChatRpaProductRunner:e.createWeChatRpaProductRunner,weChatAutomationLane:this.weChatAutomationLane}),this.weChatRpaSessionSync=new oe({channelRuntime:this.channelRuntime,getLocalMachineId:()=>process.env.SHENNIAN_MACHINE_ID||b().machineId||"",listSessions:()=>this.listWeChatRpaSessionContexts(),listAuthoritativeSessions:()=>this.listAuthoritativeWeChatRpaSessionContexts()})}*listWeChatRpaSessionContexts(){const e=this.opts.getRuntime().sessions;for(const[r,t]of e)yield{sessionId:r,workDir:t.workDir,agentType:t.agentType,agentSessionId:t.agentSessionId,externalChannel:t.externalChannel??null}}async listAuthoritativeWeChatRpaSessionContexts(){const e=b(),r=process.env.SHENNIAN_MACHINE_ID||e.machineId||"";if(!e.machineToken||!r)return null;const t=this.listLocalWeChatRpaSessionContexts(r);return(await pe({serverUrl:e.serverUrl,machineToken:e.machineToken}).listBindings({machineId:r})).bindings.filter(s=>s.enabled!==!1).map(s=>{const o=t.get(s.sessionId);return{sessionId:s.sessionId,workDir:s.sessionWorkDir?.trim()||o?.workDir?.trim()||N.homedir(),agentType:s.sessionAgentType?.trim()||o?.agentType||void 0,agentSessionId:s.sessionAgentSessionId??o?.agentSessionId??null,modelId:s.sessionModelId??o?.modelId??null,externalChannel:{connected:!0,configured:!0,type:"wechat-rpa",channelId:s.id,machineId:s.machineId,name:s.conversationName,canReply:s.allowReply!==!1,systemPrompt:null,wechatRpaSource:"wechat-channel",wechatRpaGroups:[{name:s.conversationName}],downloadAttachments:s.downloadMedia!==!1}}})}listLocalWeChatRpaSessionContexts(e){const r=new Map;for(const t of this.listWeChatRpaSessionContexts())r.set(t.sessionId,t);for(const t of se())!t?.id||t.deletedAt||t.machineId&&e&&t.machineId!==e||r.has(t.id)||r.set(t.id,{sessionId:t.id,workDir:t.workDir,agentType:t.agentType,agentSessionId:t.agentSessionId,modelId:t.modelId,externalChannel:t.externalChannel??null});return r}async notifyWeChatRpaSessionBinding(e){await this.weChatRpaSessionSync.reconcileSession(e).catch(r=>{console.error(`[wechat-rpa-sync] reconcileSession failed sessionId=${e.sessionId}: ${r instanceof Error?r.message:String(r)}`)})}async reconcileWeChatRpaSessionBindings(){await this.weChatRpaSessionSync.reconcileAll().catch(e=>{console.error(`[wechat-rpa-sync] reconcileAll failed: ${e instanceof Error?e.message:String(e)}`)})}async start(){return this.startPromise?this.startPromise:(this.startPromise=this.doStart(),this.startPromise)}async doStart(){if(this.server)return;this.server=J.createServer((r,t)=>{this.handleIpc(r,t)}),this.server.requestTimeout=A,this.server.timeout=A,this.server.keepAliveTimeout=A,this.server.headersTimeout=A+5e3,await new Promise((r,t)=>{this.server.once("error",t),this.server.listen(0,"127.0.0.1",()=>r())});const e=this.server.address();typeof e=="object"&&e&&(this.ipcUrl=`http://127.0.0.1:${e.port}`,this.writeIpcRuntimeFile()),this.server.unref(),await this.channelRuntime.start(),this.reconcileWeChatRpaSessionBindings(),this.broadcastConfiguredChannelStatuses(),this.healthTimer=setInterval(()=>this.scanWorkerHealth(),6e4),this.healthTimer.unref()}async ready(){await this.start()}async stop(){this.healthTimer&&clearInterval(this.healthTimer),this.healthTimer=null,await this.channelRuntime.stop(),await new Promise(e=>{if(!this.server)return e();this.server.close(()=>e())}),this.server=null,this.ipcUrl=null,this.removeIpcRuntimeFile()}writeIpcRuntimeFile(){if(this.ipcUrl)try{const e=F();k.mkdirSync(y.dirname(e),{recursive:!0}),k.writeFileSync(e,JSON.stringify({url:this.ipcUrl,token:this.ipcToken,pid:process.pid,updatedAt:new Date().toISOString()},null,2),{mode:384}),k.chmodSync(e,384)}catch{}}removeIpcRuntimeFile(){try{const e=F(),r=JSON.parse(k.readFileSync(e,"utf-8"));(r.url===this.ipcUrl||r.token===this.ipcToken)&&k.unlinkSync(e)}catch{}}getInjectedEnv(e,r,t,n){return this.ipcUrl?{SHENNIAN_MANAGER_SESSION_ID:e,SHENNIAN_MANAGER_AGENT_SESSION_ID:r??"",SHENNIAN_MANAGER_WORKDIR:R(t),SHENNIAN_MANAGER_MODEL:n,SHENNIAN_MANAGER_IPC_URL:this.ipcUrl,SHENNIAN_MANAGER_IPC_TOKEN:this.ipcToken}:{}}registerManager(e){this.registry.upsertManager({...e,workDir:R(e.workDir),machineId:process.env.SHENNIAN_MACHINE_ID??null})}setManagerWorkerDefaults(e,r,t){const n=this.registry.getManager(e);n&&this.registry.upsertManager({...n,defaultWorkerAgentType:r??null,defaultWorkerModelId:t??null})}getManagerWorkerDefaults(e){const r=this.registry.getManager(e);return{agentType:r?.defaultWorkerAgentType??null,modelId:r?.defaultWorkerModelId??null}}noteManagerAgentSession(e,r,t,n){this.registry.upsertManager({sessionId:e,agentSessionId:r,workDir:R(t),machineId:process.env.SHENNIAN_MACHINE_ID??null,modelId:n})}noteAgentEvent(e,r){if(!this.findWorker(e))return;const n={lastActivityAt:new Date().toISOString(),runId:r.runId};r.agentSessionId&&(n.agentSessionId=r.agentSessionId);const s=`${e}:${r.runId}`;if(r.state==="delta"&&r.text&&!r.thinking){const i=(this.workerTextAcc.get(s)??"")+r.text;this.workerTextAcc.set(s,i);const c=_(i);c&&(n.summary=c.length>160?`${c.slice(0,160)}...`:c)}if(r.state==="final"||r.state==="error"||r.state==="aborted"){n.status=r.state;const i=_(this.workerTextAcc.get(s)??"");i&&(n.summary=i.length>240?`${i.slice(0,240)}...`:i),this.workerTextAcc.delete(s)}else r.state==="start"&&(n.status="running");const o=this.registry.updateWorker(e,n);o&&(r.state==="final"||r.state==="error"||r.state==="aborted")&&this.wakeManagerForWorker(o.managedBy,o,r.state,r.message)}findWorker(e){return this.registry.load().workers[e]}async handleAppReq(e){const r=this.opts.getRuntime(),t=e.params??{};try{const n=String(t.managerSessionId||t.sessionId||"");if(!n)throw new Error("sessionId is required");const s=this.registry.getManager(n),o=e.method==="session.wechat-rpa.channel.get"||e.method==="manager.wechat-rpa.channel.get",i=e.method==="session.wechat-rpa.channel.upsert"||e.method==="manager.wechat-rpa.channel.upsert",c=e.method==="session.wechat-rpa.channel.sync"||e.method==="manager.wechat-rpa.channel.sync",d=e.method==="session.wechat-rpa.outbound.cancel"||e.method==="manager.wechat-rpa.outbound.cancel";if(e.method==="manager.channel.get"){w(r,e.id,!0,{channel:this.channelRuntime.getManagerChannel(n,"websocket",{includeSecret:!0})});return}if(e.method==="manager.channel.upsert"){const l=await this.channelRuntime.upsertManagerChannel({id:String(t.id||`websocket:${n}`),managerSessionId:n,sessionId:n,workDir:String(t.workDir||s?.workDir||""),type:"websocket",name:typeof t.name=="string"?t.name:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,agentSessionId:typeof t.agentSessionId=="string"?t.agentSessionId:null,modelId:typeof t.modelId=="string"?t.modelId:null,enabled:!!t.enabled,wsUrl:typeof t.wsUrl=="string"?t.wsUrl:void 0,token:typeof t.token=="string"?t.token:void 0,canReply:t.canReply===void 0?void 0:!!t.canReply,systemPrompt:typeof t.systemPrompt=="string"?t.systemPrompt:void 0});this.broadcastManagerChannelStatus(n),w(r,e.id,!0,{channel:l});return}if(o){w(r,e.id,!0,{channel:this.channelRuntime.getManagerChannel(n,"wechat-rpa",{includeSecret:!0})});return}if(i){const l=await this.channelRuntime.upsertManagerWeChatRpaChannel({id:String(t.id||`wechat-rpa:${n}`),managerSessionId:n,sessionId:n,workDir:R(String(t.workDir||s?.workDir||"")),name:typeof t.name=="string"?t.name:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,agentSessionId:typeof t.agentSessionId=="string"?t.agentSessionId:null,modelId:typeof t.modelId=="string"?t.modelId:null,enabled:!!t.enabled,groups:O(t.groups),canReply:t.canReply===void 0?void 0:!!t.canReply,systemPrompt:typeof t.systemPrompt=="string"?t.systemPrompt:void 0,source:U(t.source),pollIntervalMs:g(t.pollIntervalMs),recentLimit:g(t.recentLimit),idleSeconds:g(t.idleSeconds),forceForeground:t.forceForeground===void 0?void 0:!!t.forceForeground,noRestore:t.noRestore===void 0?void 0:!!t.noRestore,downloadAttachments:t.downloadAttachments===void 0?void 0:!!t.downloadAttachments,downloadAttachmentsDir:typeof t.downloadAttachmentsDir=="string"?t.downloadAttachmentsDir:void 0,selfNickname:typeof t.selfNickname=="string"?t.selfNickname:void 0,selfTriggerMarker:typeof t.selfTriggerMarker=="string"?t.selfTriggerMarker:void 0,deferInitialPoll:t.deferInitialPoll===void 0?void 0:!!t.deferInitialPoll,privacyConsentAccepted:t.privacyConsentAccepted===void 0?void 0:!!t.privacyConsentAccepted,flowScriptPath:typeof t.flowScriptPath=="string"?t.flowScriptPath:void 0});this.broadcastManagerChannelStatus(n),w(r,e.id,!0,{channel:l});return}if(c){const l=await this.channelRuntime.syncManagerWeChatRpaChannel(n);this.broadcastManagerChannelStatus(n),w(r,e.id,!0,l);return}if(d){const l=await this.channelRuntime.cancelManagerWeChatRpaOutbound({managerSessionId:n,idempotencyKey:typeof t.idempotencyKey=="string"?t.idempotencyKey:null,replyId:typeof t.replyId=="string"?t.replyId:null,reason:typeof t.reason=="string"?t.reason:"user_cancelled"});this.broadcastManagerChannelStatus(n),w(r,e.id,!0,l);return}throw new Error(`Unsupported manager app method: ${e.method}`)}catch(n){w(r,e.id,!1,{error:n instanceof Error?n.message:String(n)})}}broadcastConfiguredChannelStatuses(){for(const e of this.channelRuntime.listManagerChannelStatuses())this.broadcastManagerChannelStatus(e.managerSessionId)}broadcastManagerChannelStatus(e){const r=this.opts.getRuntime();if(!r.client?.sendEvent)return;const t=this.registry.getManager(e),n=this.channelRuntime.getManagerChannelStatus(e),s=this.channelRuntime.getManagerChannel(e,"wechat-rpa")??this.channelRuntime.getManagerChannel(e,"websocket");r.client.sendEvent({type:"event",event:"session.update",payload:{session:{id:e,agentType:t?"manager":s?.agentType,agentSessionId:t?.agentSessionId??s?.agentSessionId??null,modelId:t?.modelId??s?.modelId??null,workDir:t?.workDir??s?.workDir,externalChannel:n}}})}async handleIpc(e,r){if(e.headers.authorization!==`Bearer ${this.ipcToken}`){u(r,401,{ok:!1,error:"Unauthorized"});return}try{const t=new URL(e.url??"/","http://127.0.0.1"),n=await Se(e),s=String(n.managerSessionId||e.headers["x-shennian-manager-session-id"]||"");if(!s)throw new Error("managerSessionId is required");const o=this.registry.getManager(s);if(t.pathname==="/sessions/list"){if(!o)throw new Error("Manager runtime is not registered");const i=new Set(this.opts.getRuntime().sessions.keys());u(r,200,{ok:!0,sessions:this.registry.listWorkers(s,{runningSessionIds:i})});return}if(t.pathname==="/sessions/start"){if(!o)throw new Error("Manager runtime is not registered");const i=String(n.agentType||n.agent||o.defaultWorkerAgentType||"codex");if(!fe(i))throw new Error(`Unsupported manager worker agent: ${i}`);const c=R(String(n.workDir||o.workDir));if(c!==o.workDir)throw new Error("Manager can only start workers in the same workDir");const d=String(n.message||"");if(!d)throw new Error("message is required");const l=this.registry.addWorker({managerSessionId:s,agentType:i,workDir:c,summary:d.slice(0,120)}),h=String(n.modelId||(i===o.defaultWorkerAgentType?o.defaultWorkerModelId??"":""));await this.dispatchChatSend(l.sessionId,i,c,d,null,h),u(r,200,{ok:!0,session:l});return}if(t.pathname==="/sessions/send"){const i=String(n.sessionId||""),c=String(n.message||""),d=n.enqueue===void 0?!0:!!n.enqueue,l=this.registry.getWorkerForManager(s,i);if(!l)throw new Error("Worker not found in this manager scope");const h=String(n.modelId||(l.agentType===o?.defaultWorkerAgentType?o.defaultWorkerModelId??"":""));d?await this.dispatchChatEnqueue(l.sessionId,l.agentType,l.workDir,c,l.agentSessionId??null,h):await this.dispatchChatSend(l.sessionId,l.agentType,l.workDir,c,l.agentSessionId??null,h),u(r,200,{ok:!0});return}if(t.pathname==="/sessions/queue"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");const d=this.opts.getRuntime().chatQueue?.getSnapshot(i);u(r,200,{ok:!0,queue:d});return}if(t.pathname==="/sessions/queue/edit"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");await this.opts.dispatchReq({type:"req",id:`manager-queue-edit-${m()}`,method:"chat.queue.edit",params:{sessionId:i,queueMessageId:String(n.queueMessageId||n.messageId||""),text:String(n.message||n.text||"")}}),u(r,200,{ok:!0,queue:this.opts.getRuntime().chatQueue?.getSnapshot(i)});return}if(t.pathname==="/sessions/queue/delete"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");await this.opts.dispatchReq({type:"req",id:`manager-queue-delete-${m()}`,method:"chat.queue.delete",params:{sessionId:i,queueMessageId:String(n.queueMessageId||n.messageId||"")}}),u(r,200,{ok:!0,queue:this.opts.getRuntime().chatQueue?.getSnapshot(i)});return}if(t.pathname==="/sessions/stop"||t.pathname==="/sessions/terminate"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");await this.opts.dispatchReq({type:"req",id:`manager-abort-${m()}`,method:"chat.abort",params:{sessionId:i}}),this.registry.updateWorker(i,{status:"aborted"}),u(r,200,{ok:!0});return}if(t.pathname==="/sessions/read"){const i=String(n.sessionId||""),c=Number(n.limit||200);if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");const l=ae(i,{limit:Math.max(c*20,c)});u(r,200,{ok:!0,messages:Ie(l,c),rawMessageCount:l.length});return}if(t.pathname==="/memory/path"){if(!o)throw new Error("Manager runtime is not registered");u(r,200,{ok:!0,path:y.join(o.workDir,".shennian")});return}if(t.pathname==="/external/reply"){const i=typeof n.replyTarget=="string"?this.registry.getReplyTarget(n.replyTarget):this.registry.getLatestReplyTargetForManager(s),c=String(n.text||""),d=B(n.attachment),l=String(n.idempotencyKey||m()),h=String(n.channelId||""),p=String(n.conversationId||""),C=!i&&(!h||!p)?await this.channelRuntime.getDefaultReplyTarget(s).catch(()=>null):null,I=i?.channelId||h||C?.channelId||"",E=i?.conversationId||p||C?.conversationId||"",W=I?this.channelRuntime.getChannelById(I):void 0,z=W&&(!!(i||h)||W.managedBy!=="session-sync");if(I&&z){if(!E)throw new Error("No external channel target is available for this Manager");const f=await this.channelRuntime.reply({managerSessionId:s,channelId:I,conversationId:E,messageId:i?.messageId??void 0,text:c,attachment:d,idempotencyKey:l});u(r,f.ok?200:400,f);return}const x=await this.tryDirectWeChatRpaReply(s,c,d);if(x){u(r,x.ok?200:400,x);return}let S;try{S=await this.sendManagedWeComReply({managerSessionId:s,text:c,attachment:d,idempotencyKey:l})}catch(f){const v=f instanceof Error?f.message:String(f);if(!q(v))throw f;S={ok:!1,error:v}}if(S.ok){u(r,200,{ok:!0,payload:S.payload});return}if(!q(S.error||"")||!I||!E){u(r,400,{ok:!1,error:S.error||"External send failed"});return}u(r,400,{ok:!1,error:`No local external channel is configured for ${I}`});return}if(t.pathname==="/channel/get"){u(r,200,{ok:!0,channel:this.channelRuntime.getManagerChannel(s,"websocket")});return}if(t.pathname==="/channel/upsert"){if(!o)throw new Error("Manager runtime is not registered");const i=await this.channelRuntime.upsertManagerChannel({id:String(n.id||`websocket:${s}`),managerSessionId:s,workDir:o.workDir,type:"websocket",name:typeof n.name=="string"?n.name:void 0,enabled:!!n.enabled,wsUrl:typeof n.wsUrl=="string"?n.wsUrl:void 0,token:typeof n.token=="string"?n.token:void 0,canReply:n.canReply===void 0?void 0:!!n.canReply,systemPrompt:typeof n.systemPrompt=="string"?n.systemPrompt:void 0});this.registry.upsertManager({...o,status:o.status}),this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,channel:i});return}if(t.pathname==="/wechat-rpa/tool/read"){const i=L(n),c=g(n.limit)??10,d=typeof n.traceId=="string"?n.traceId:void 0;let l;try{l=await this.weChatAutomationLane.run(`wechat-tool:read:${i.channelId}`,()=>he(i,{conversation:i.conversationName,workDir:i.workDir,sessionId:i.sessionId,limit:c,recentLimit:c,download:n.download==="never"?"never":"auto",traceId:d,timeoutMs:g(n.timeoutMs)}))}catch(h){u(r,400,{ok:!1,...j(h,d)});return}u(r,200,{ok:!0,messages:l.messages,outDir:l.outDir,helperTracePath:l.helperTracePath,activityGuardPath:l.activityGuardPath});return}if(t.pathname==="/wechat-rpa/tool/send"){const i=L(n),c=String(n.text||""),d=B(n.attachment),l=typeof n.traceId=="string"?n.traceId:void 0;let h;try{h=await this.weChatAutomationLane.run(`wechat-tool:send:${i.channelId}`,()=>P(i,{conversation:i.conversationName,workDir:i.workDir,sessionId:i.sessionId,text:c,attachment:d,traceId:l,timeoutMs:g(n.timeoutMs)}))}catch(p){u(r,400,{ok:!1,...j(p,l)});return}u(r,200,{ok:!0,...h});return}if(t.pathname==="/wechat-rpa/channel/get"){u(r,200,{ok:!0,channel:this.channelRuntime.getManagerChannel(s,"wechat-rpa",{includeSecret:!0})});return}if(t.pathname==="/wechat-rpa/channel/upsert"){const i=R(String(n.workDir||o?.workDir||""));if(!i)throw new Error("workDir is required");const c=await this.channelRuntime.upsertManagerWeChatRpaChannel({id:String(n.id||`wechat-rpa:${s}`),managerSessionId:s,sessionId:s,workDir:i,name:typeof n.name=="string"?n.name:void 0,agentType:typeof n.agentType=="string"?n.agentType:void 0,agentSessionId:typeof n.agentSessionId=="string"?n.agentSessionId:null,modelId:typeof n.modelId=="string"?n.modelId:null,enabled:!!n.enabled,groups:O(n.groups),canReply:n.canReply===void 0?void 0:!!n.canReply,systemPrompt:typeof n.systemPrompt=="string"?n.systemPrompt:void 0,source:U(n.source),pollIntervalMs:g(n.pollIntervalMs),recentLimit:g(n.recentLimit),idleSeconds:g(n.idleSeconds),forceForeground:n.forceForeground===void 0?void 0:!!n.forceForeground,noRestore:n.noRestore===void 0?void 0:!!n.noRestore,downloadAttachments:n.downloadAttachments===void 0?void 0:!!n.downloadAttachments,downloadAttachmentsDir:typeof n.downloadAttachmentsDir=="string"?n.downloadAttachmentsDir:void 0,selfNickname:typeof n.selfNickname=="string"?n.selfNickname:void 0,selfTriggerMarker:typeof n.selfTriggerMarker=="string"?n.selfTriggerMarker:void 0,deferInitialPoll:n.deferInitialPoll===void 0?void 0:!!n.deferInitialPoll,privacyConsentAccepted:n.privacyConsentAccepted===void 0?void 0:!!n.privacyConsentAccepted,flowScriptPath:typeof n.flowScriptPath=="string"?n.flowScriptPath:void 0});o&&this.registry.upsertManager({...o,status:o.status}),this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,channel:c});return}if(t.pathname==="/wechat-rpa/channel/sync"){const{channel:i,messages:c}=await this.channelRuntime.syncManagerWeChatRpaChannel(s);this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,channel:i,messages:c});return}if(t.pathname==="/wechat-rpa/outbound/cancel"){const i=await this.channelRuntime.cancelManagerWeChatRpaOutbound({managerSessionId:s,idempotencyKey:typeof n.idempotencyKey=="string"?n.idempotencyKey:null,replyId:typeof n.replyId=="string"?n.replyId:null,reason:typeof n.reason=="string"?n.reason:"user_cancelled"});this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,...i});return}u(r,404,{ok:!1,error:`Unknown manager IPC path: ${t.pathname}`})}catch(t){u(r,400,{ok:!1,error:t instanceof Error?t.message:String(t)})}}async dispatchChatSend(e,r,t,n,s,o){await this.opts.dispatchReq({type:"req",id:`manager-send-${m()}`,method:"chat.send",params:{sessionId:e,text:n,agentType:r,workDir:t,agentSessionId:s,modelId:o}})}async dispatchChatEnqueue(e,r,t,n,s,o){await this.opts.dispatchReq({type:"req",id:`manager-enqueue-${m()}`,method:"chat.enqueue",params:{sessionId:e,text:n,agentType:r,workDir:t,agentSessionId:s,modelId:o}})}async tryDirectWeChatRpaReply(e,r,t){const n=this.opts.getRuntime().sessions.get(e),s=n?.externalChannel;if(!s||s.type!=="wechat-rpa"||!s.channelId||!s.name)return null;const o=process.env.SHENNIAN_MACHINE_ID||b().machineId||"";if(s.machineId&&o&&s.machineId!==o)return{ok:!1,error:`WeChat \u7ED1\u5B9A\u5C5E\u4E8E\u5176\u4ED6\u673A\u5668 (${s.machineId})\uFF0C\u8BF7\u5728\u7ED1\u5B9A\u673A\u5668\u4E0A\u53D1\u9001\u3002`};if(!r.trim()&&!t)return{ok:!1,error:"text or attachment is required"};const i=n?.workDir||process.cwd(),c={sessionId:e,channelId:s.channelId,conversationId:de(s.name),conversationName:s.name,workDir:i};try{return{ok:!0,payload:await this.weChatAutomationLane.run(`wechat-tool:send:${c.channelId}`,()=>P(c,{conversation:c.conversationName,workDir:c.workDir,sessionId:c.sessionId,text:r,attachment:t}))}}catch(d){return{ok:!1,error:d instanceof Error?d.message:String(d)}}}async sendManagedWeComReply(e){const r=ce(e.text);if(!r.length&&!e.attachment)return{ok:!1,error:"text or attachment is required"};const t=this.opts.getRuntime().client;if(!t||typeof t.sendReq!="function")return{ok:!1,error:"Relay is not connected"};const n=[];for(const[s,o]of r.entries()){const i=await t.sendReq({type:"req",id:`external-send-${m()}`,method:"external.send",params:{managerSessionId:e.managerSessionId,text:o,idempotencyKey:r.length>1?`${e.idempotencyKey}:${s+1}`:e.idempotencyKey}});if(!i.ok)return{ok:!1,error:i.error||"External send failed"};n.push(i.payload)}if(e.attachment){const s=await t.sendReq({type:"req",id:`external-send-${m()}`,method:"external.send",params:{managerSessionId:e.managerSessionId,attachment:e.attachment,idempotencyKey:r.length?`${e.idempotencyKey}:attachment`:e.idempotencyKey}});if(!s.ok)return{ok:!1,error:s.error||"External send failed"};n.push(s.payload)}return{ok:!0,payload:n.length===1?n[0]:n}}wakeManagerForWorker(e,r,t,n){const s=this.registry.getManager(e);if(!s)return;const o=`\u4F60\u7BA1\u7406\u7684 worker \u5DF2\u7ED3\u675F\u3002
1
+ import J from"node:http";import{randomBytes as Y,randomUUID as p}from"node:crypto";import k from"node:fs";import N from"node:os";import y from"node:path";import{AVAILABLE_BUILTIN_AGENT_TYPES as V,extractPayloadText as Q,formatExternalConversationText as X,formatExternalMessageLine as Z,formatExternalAttachmentReference as ee,isAgentHiddenPayload as te,isToolPayload as ne}from"@shennian/wire";import{ManagerRegistry as re}from"./registry.js";import{readMessages as ae}from"../session/store.js";import{listProjectedSessions as se}from"../session/projection.js";import{ChannelRuntime as ie}from"../channels/runtime.js";import{WeChatRpaSessionBindingSync as oe}from"../channels/wechat-rpa-session-sync.js";import{splitExternalReplyText as ce}from"../channels/reply-split.js";import{loadConfig as b,resolveShennianPath as le}from"../config/index.js";import{weChatChannelConversationId as de}from"../channels/wechat-rpa/product-channel.js";import{buildExternalChannelInstructions as ue}from"../agents/external-channel-instructions.js";import{readDirectWeChatLatestOnce as he,sendDirectWeChatMessageOnce as P}from"../commands/wechat.js";import{createWeChatChannelApiClient as me}from"../channels/wechat-channel/client.js";import{createWeChatAutomationLane as pe}from"../channels/wechat-channel/automation-lane.js";const M=Number(process.env.SHENNIAN_MANAGER_IPC_BODY_MAX_BYTES||2*1024*1024),A=12*6e4;let $=null;function Qe(a){$=a}function Xe(){return $}function R(a){return y.resolve(a||N.homedir())}function u(a,e,r){a.writeHead(e,{"content-type":"application/json; charset=utf-8"}),a.end(JSON.stringify(r))}function ge(a){return/^agent-(.+)-\d+$/.exec(a)?.[1]??null}function fe(a){return a==="manager"?!1:a.startsWith("custom:")?!0:V.includes(a)}function ye(a){const e=/^agent-.+-(\d+)$/.exec(a);if(!e)return null;const r=Number(e[1]);return Number.isInteger(r)&&r>=0?r:null}function _(a){return a.replace(/\r\n/g,`
2
+ `).trim()}function we(a){try{const e=JSON.parse(a),r=e.type==="tool_result"||e.result?"tool_result":"tool_call",t=e.name||"tool",n=typeof e.result=="string"?e.result.replace(/\s+/g," ").trim():"",s=n.length>220?`${n.slice(0,220)}...`:n;return s?`[${r}] ${t}: ${s}`:`[${r}] ${t}`}catch{return"[tool]"}}function B(a){if(!a||typeof a!="object")return;const e=a,r=String(e.kind||""),t=String(e.name||""),n=String(e.mimeType||""),s=String(e.dataBase64||""),o=String(e.localPath||""),i=String(e.url||""),c=Number(e.size||0);if(s)throw new Error("Manager IPC external attachments must use localPath or url; dataBase64 is not accepted");if(!(r!=="image"&&r!=="video"&&r!=="file")&&!(!t||!n||!Number.isFinite(c)||c<0)&&!(!o&&!i))return{kind:r,name:t,mimeType:n,size:c,...o?{localPath:o}:{},...i?{url:i}:{}}}function L(a){const e=a.binding&&typeof a.binding=="object"&&!Array.isArray(a.binding)?a.binding:{},r=String(e.sessionId||a.managerSessionId||"").trim(),t=String(e.channelId||"").trim(),n=String(e.conversationId||"").trim(),s=String(e.conversationName||a.conversation||"").trim(),o=String(e.workDir||a.workDir||"").trim();if(!r)throw new Error("WeChat tool sessionId is required");if(!t)throw new Error("WeChat tool channelId is required");if(!n)throw new Error("WeChat tool conversationId is required");if(!s)throw new Error("WeChat tool conversationName is required");if(!o)throw new Error("WeChat tool workDir is required");return{sessionId:r,channelId:t,conversationId:n,conversationName:s,workDir:o}}function Ie(a,e){const r=[...a].sort((d,l)=>d.ts-l.ts),t=[];let n=null,s=null,o=null,i="";const c=()=>{if(!n)return;const d=i.trim();d&&t.push({...n,id:`${n.id}-compact`,payload:d}),n=null,s=null,o=null,i=""};for(const d of r){if(te(d.payload)){c();continue}if(d.role==="user"){c(),t.push(d);continue}if(ne(d.payload)){c(),t.push({...d,payload:we(d.payload)});continue}const l=Q(d.payload);if(!l.trim())continue;const h=ge(d.id),m=ye(d.id);n&&n.role===d.role&&s===h&&h&&m!==null&&o!==null&&m===o+1?(i+=l,n.ts=d.ts,o=m):(c(),n=d,s=h,o=m,i=l)}return c(),t.slice(-e).sort((d,l)=>l.ts-d.ts)}async function Se(a){const e=[];let r=0;for await(const n of a){const s=Buffer.from(n);if(r+=s.byteLength,Number.isFinite(M)&&M>0&&r>M)throw new Error(`Manager IPC request body is too large. Max: ${M} bytes.`);e.push(s)}const t=Buffer.concat(e).toString("utf-8");return t?JSON.parse(t):{}}function w(a,e,r,t){a.client.sendRes({type:"res",id:e,ok:r,...r?{payload:t}:{error:String(t.error||"unknown error")}})}function q(a){return/binding not found|unknown method|not supported|relay is not connected|no external channel/i.test(a)}function F(){return ke()?y.join(N.tmpdir(),"shennian-vitest-runtime",String(process.pid),"manager-ipc.json"):le("runtime","manager-ipc.json")}function ke(){return(process.env.VITEST==="true"||!!process.env.VITEST_WORKER_ID)&&!process.env.SHENNIAN_HOME?.trim()}class Ze{opts;registry=new re;channelRuntime;weChatRpaSessionSync;server=null;ipcUrl=null;ipcToken=Y(24).toString("hex");healthTimer=null;startPromise=null;workerTextAcc=new Map;weChatAutomationLane;constructor(e){this.opts=e,this.weChatAutomationLane=e.weChatAutomationLane??pe(),this.channelRuntime=e.channelRuntime??new ie((r,t)=>{this.handleExternalMessage(r,t)},r=>this.registry.createReplyTarget(r).replyTarget,{createWeChatRpaProductRunner:e.createWeChatRpaProductRunner,weChatAutomationLane:this.weChatAutomationLane}),this.weChatRpaSessionSync=new oe({channelRuntime:this.channelRuntime,getLocalMachineId:()=>process.env.SHENNIAN_MACHINE_ID||b().machineId||"",listSessions:()=>this.listWeChatRpaSessionContexts(),listAuthoritativeSessions:()=>this.listAuthoritativeWeChatRpaSessionContexts()})}*listWeChatRpaSessionContexts(){const e=this.opts.getRuntime().sessions;for(const[r,t]of e)yield{sessionId:r,workDir:t.workDir,agentType:t.agentType,agentSessionId:t.agentSessionId,externalChannel:t.externalChannel??null}}async listAuthoritativeWeChatRpaSessionContexts(){const e=b(),r=process.env.SHENNIAN_MACHINE_ID||e.machineId||"";if(!e.machineToken||!r)return null;const t=this.listLocalWeChatRpaSessionContexts(r);return(await me({serverUrl:e.serverUrl,machineToken:e.machineToken}).listBindings({machineId:r})).bindings.filter(s=>s.enabled!==!1).map(s=>{const o=t.get(s.sessionId);return{sessionId:s.sessionId,workDir:s.sessionWorkDir?.trim()||o?.workDir?.trim()||N.homedir(),agentType:s.sessionAgentType?.trim()||o?.agentType||void 0,agentSessionId:s.sessionAgentSessionId??o?.agentSessionId??null,modelId:s.sessionModelId??o?.modelId??null,externalChannel:{connected:!0,configured:!0,type:"wechat-rpa",channelId:s.id,machineId:s.machineId,name:s.conversationName,canReply:s.allowReply!==!1,systemPrompt:null,wechatRpaSource:"wechat-channel",wechatRpaGroups:[{name:s.conversationName}],downloadAttachments:s.downloadMedia!==!1}}})}listLocalWeChatRpaSessionContexts(e){const r=new Map;for(const t of this.listWeChatRpaSessionContexts())r.set(t.sessionId,t);for(const t of se())!t?.id||t.deletedAt||t.machineId&&e&&t.machineId!==e||r.has(t.id)||r.set(t.id,{sessionId:t.id,workDir:t.workDir,agentType:t.agentType,agentSessionId:t.agentSessionId,modelId:t.modelId,externalChannel:t.externalChannel??null});return r}async notifyWeChatRpaSessionBinding(e){await this.weChatRpaSessionSync.reconcileSession(e).catch(r=>{console.error(`[wechat-rpa-sync] reconcileSession failed sessionId=${e.sessionId}: ${r instanceof Error?r.message:String(r)}`)})}async reconcileWeChatRpaSessionBindings(){await this.weChatRpaSessionSync.reconcileAll().catch(e=>{console.error(`[wechat-rpa-sync] reconcileAll failed: ${e instanceof Error?e.message:String(e)}`)})}async start(){return this.startPromise?this.startPromise:(this.startPromise=this.doStart(),this.startPromise)}async doStart(){if(this.server)return;this.server=J.createServer((r,t)=>{this.handleIpc(r,t)}),this.server.requestTimeout=A,this.server.timeout=A,this.server.keepAliveTimeout=A,this.server.headersTimeout=A+5e3,await new Promise((r,t)=>{this.server.once("error",t),this.server.listen(0,"127.0.0.1",()=>r())});const e=this.server.address();typeof e=="object"&&e&&(this.ipcUrl=`http://127.0.0.1:${e.port}`,this.writeIpcRuntimeFile()),this.server.unref(),await this.channelRuntime.start(),this.reconcileWeChatRpaSessionBindings(),this.broadcastConfiguredChannelStatuses(),this.healthTimer=setInterval(()=>this.scanWorkerHealth(),6e4),this.healthTimer.unref()}async ready(){await this.start()}async stop(){this.healthTimer&&clearInterval(this.healthTimer),this.healthTimer=null,await this.channelRuntime.stop(),await new Promise(e=>{if(!this.server)return e();this.server.close(()=>e())}),this.server=null,this.ipcUrl=null,this.removeIpcRuntimeFile()}writeIpcRuntimeFile(){if(this.ipcUrl)try{const e=F();k.mkdirSync(y.dirname(e),{recursive:!0}),k.writeFileSync(e,JSON.stringify({url:this.ipcUrl,token:this.ipcToken,pid:process.pid,updatedAt:new Date().toISOString()},null,2),{mode:384}),k.chmodSync(e,384)}catch{}}removeIpcRuntimeFile(){try{const e=F(),r=JSON.parse(k.readFileSync(e,"utf-8"));(r.url===this.ipcUrl||r.token===this.ipcToken)&&k.unlinkSync(e)}catch{}}getInjectedEnv(e,r,t,n){return this.ipcUrl?{SHENNIAN_MANAGER_SESSION_ID:e,SHENNIAN_MANAGER_AGENT_SESSION_ID:r??"",SHENNIAN_MANAGER_WORKDIR:R(t),SHENNIAN_MANAGER_MODEL:n,SHENNIAN_MANAGER_IPC_URL:this.ipcUrl,SHENNIAN_MANAGER_IPC_TOKEN:this.ipcToken}:{}}registerManager(e){this.registry.upsertManager({...e,workDir:R(e.workDir),machineId:process.env.SHENNIAN_MACHINE_ID??null})}setManagerWorkerDefaults(e,r,t){const n=this.registry.getManager(e);n&&this.registry.upsertManager({...n,defaultWorkerAgentType:r??null,defaultWorkerModelId:t??null})}getManagerWorkerDefaults(e){const r=this.registry.getManager(e);return{agentType:r?.defaultWorkerAgentType??null,modelId:r?.defaultWorkerModelId??null}}noteManagerAgentSession(e,r,t,n){this.registry.upsertManager({sessionId:e,agentSessionId:r,workDir:R(t),machineId:process.env.SHENNIAN_MACHINE_ID??null,modelId:n})}noteAgentEvent(e,r){if(!this.findWorker(e))return;const n={lastActivityAt:new Date().toISOString(),runId:r.runId};r.agentSessionId&&(n.agentSessionId=r.agentSessionId);const s=`${e}:${r.runId}`;if(r.state==="delta"&&r.text&&!r.thinking){const i=(this.workerTextAcc.get(s)??"")+r.text;this.workerTextAcc.set(s,i);const c=_(i);c&&(n.summary=c.length>160?`${c.slice(0,160)}...`:c)}if(r.state==="final"||r.state==="error"||r.state==="aborted"){n.status=r.state;const i=_(this.workerTextAcc.get(s)??"");i&&(n.summary=i.length>240?`${i.slice(0,240)}...`:i),this.workerTextAcc.delete(s)}else r.state==="start"&&(n.status="running");const o=this.registry.updateWorker(e,n);o&&(r.state==="final"||r.state==="error"||r.state==="aborted")&&this.wakeManagerForWorker(o.managedBy,o,r.state,r.message)}findWorker(e){return this.registry.load().workers[e]}async handleAppReq(e){const r=this.opts.getRuntime(),t=e.params??{};try{const n=String(t.managerSessionId||t.sessionId||"");if(!n)throw new Error("sessionId is required");const s=this.registry.getManager(n),o=e.method==="session.wechat-rpa.channel.get"||e.method==="manager.wechat-rpa.channel.get",i=e.method==="session.wechat-rpa.channel.upsert"||e.method==="manager.wechat-rpa.channel.upsert",c=e.method==="session.wechat-rpa.channel.sync"||e.method==="manager.wechat-rpa.channel.sync",d=e.method==="session.wechat-rpa.outbound.cancel"||e.method==="manager.wechat-rpa.outbound.cancel";if(e.method==="manager.channel.get"){w(r,e.id,!0,{channel:this.channelRuntime.getManagerChannel(n,"websocket",{includeSecret:!0})});return}if(e.method==="manager.channel.upsert"){const l=await this.channelRuntime.upsertManagerChannel({id:String(t.id||`websocket:${n}`),managerSessionId:n,sessionId:n,workDir:String(t.workDir||s?.workDir||""),type:"websocket",name:typeof t.name=="string"?t.name:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,agentSessionId:typeof t.agentSessionId=="string"?t.agentSessionId:null,modelId:typeof t.modelId=="string"?t.modelId:null,enabled:!!t.enabled,wsUrl:typeof t.wsUrl=="string"?t.wsUrl:void 0,token:typeof t.token=="string"?t.token:void 0,canReply:t.canReply===void 0?void 0:!!t.canReply,systemPrompt:typeof t.systemPrompt=="string"?t.systemPrompt:void 0});this.broadcastManagerChannelStatus(n),w(r,e.id,!0,{channel:l});return}if(o){w(r,e.id,!0,{channel:this.channelRuntime.getManagerChannel(n,"wechat-rpa",{includeSecret:!0})});return}if(i){const l=await this.channelRuntime.upsertManagerWeChatRpaChannel({id:String(t.id||`wechat-rpa:${n}`),managerSessionId:n,sessionId:n,workDir:R(String(t.workDir||s?.workDir||"")),name:typeof t.name=="string"?t.name:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,agentSessionId:typeof t.agentSessionId=="string"?t.agentSessionId:null,modelId:typeof t.modelId=="string"?t.modelId:null,enabled:!!t.enabled,groups:O(t.groups),canReply:t.canReply===void 0?void 0:!!t.canReply,systemPrompt:typeof t.systemPrompt=="string"?t.systemPrompt:void 0,source:U(t.source),pollIntervalMs:g(t.pollIntervalMs),recentLimit:g(t.recentLimit),idleSeconds:g(t.idleSeconds),forceForeground:t.forceForeground===void 0?void 0:!!t.forceForeground,noRestore:t.noRestore===void 0?void 0:!!t.noRestore,downloadAttachments:t.downloadAttachments===void 0?void 0:!!t.downloadAttachments,downloadAttachmentsDir:typeof t.downloadAttachmentsDir=="string"?t.downloadAttachmentsDir:void 0,selfNickname:typeof t.selfNickname=="string"?t.selfNickname:void 0,selfTriggerMarker:typeof t.selfTriggerMarker=="string"?t.selfTriggerMarker:void 0,deferInitialPoll:t.deferInitialPoll===void 0?void 0:!!t.deferInitialPoll,privacyConsentAccepted:t.privacyConsentAccepted===void 0?void 0:!!t.privacyConsentAccepted,flowScriptPath:typeof t.flowScriptPath=="string"?t.flowScriptPath:void 0});this.broadcastManagerChannelStatus(n),w(r,e.id,!0,{channel:l});return}if(c){const l=await this.channelRuntime.syncManagerWeChatRpaChannel(n);this.broadcastManagerChannelStatus(n),w(r,e.id,!0,l);return}if(d){const l=await this.channelRuntime.cancelManagerWeChatRpaOutbound({managerSessionId:n,idempotencyKey:typeof t.idempotencyKey=="string"?t.idempotencyKey:null,replyId:typeof t.replyId=="string"?t.replyId:null,reason:typeof t.reason=="string"?t.reason:"user_cancelled"});this.broadcastManagerChannelStatus(n),w(r,e.id,!0,l);return}throw new Error(`Unsupported manager app method: ${e.method}`)}catch(n){w(r,e.id,!1,{error:n instanceof Error?n.message:String(n)})}}broadcastConfiguredChannelStatuses(){for(const e of this.channelRuntime.listManagerChannelStatuses())this.broadcastManagerChannelStatus(e.managerSessionId)}broadcastManagerChannelStatus(e){const r=this.opts.getRuntime();if(!r.client?.sendEvent)return;const t=this.registry.getManager(e),n=this.channelRuntime.getManagerChannelStatus(e),s=this.channelRuntime.getManagerChannel(e,"wechat-rpa")??this.channelRuntime.getManagerChannel(e,"websocket");r.client.sendEvent({type:"event",event:"session.update",payload:{session:{id:e,agentType:t?"manager":s?.agentType,agentSessionId:t?.agentSessionId??s?.agentSessionId??null,modelId:t?.modelId??s?.modelId??null,workDir:t?.workDir??s?.workDir,externalChannel:n}}})}async handleIpc(e,r){if(e.headers.authorization!==`Bearer ${this.ipcToken}`){u(r,401,{ok:!1,error:"Unauthorized"});return}try{const t=new URL(e.url??"/","http://127.0.0.1"),n=await Se(e),s=String(n.managerSessionId||e.headers["x-shennian-manager-session-id"]||"");if(!s)throw new Error("managerSessionId is required");const o=this.registry.getManager(s);if(t.pathname==="/sessions/list"){if(!o)throw new Error("Manager runtime is not registered");const i=new Set(this.opts.getRuntime().sessions.keys());u(r,200,{ok:!0,sessions:this.registry.listWorkers(s,{runningSessionIds:i})});return}if(t.pathname==="/sessions/start"){if(!o)throw new Error("Manager runtime is not registered");const i=String(n.agentType||n.agent||o.defaultWorkerAgentType||"codex");if(!fe(i))throw new Error(`Unsupported manager worker agent: ${i}`);const c=R(String(n.workDir||o.workDir));if(c!==o.workDir)throw new Error("Manager can only start workers in the same workDir");const d=String(n.message||"");if(!d)throw new Error("message is required");const l=this.registry.addWorker({managerSessionId:s,agentType:i,workDir:c,summary:d.slice(0,120)}),h=String(n.modelId||(i===o.defaultWorkerAgentType?o.defaultWorkerModelId??"":""));await this.dispatchChatSend(l.sessionId,i,c,d,null,h),u(r,200,{ok:!0,session:l});return}if(t.pathname==="/sessions/send"){const i=String(n.sessionId||""),c=String(n.message||""),d=n.enqueue===void 0?!0:!!n.enqueue,l=this.registry.getWorkerForManager(s,i);if(!l)throw new Error("Worker not found in this manager scope");const h=String(n.modelId||(l.agentType===o?.defaultWorkerAgentType?o.defaultWorkerModelId??"":""));d?await this.dispatchChatEnqueue(l.sessionId,l.agentType,l.workDir,c,l.agentSessionId??null,h):await this.dispatchChatSend(l.sessionId,l.agentType,l.workDir,c,l.agentSessionId??null,h),u(r,200,{ok:!0});return}if(t.pathname==="/sessions/queue"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");const d=this.opts.getRuntime().chatQueue?.getSnapshot(i);u(r,200,{ok:!0,queue:d});return}if(t.pathname==="/sessions/queue/edit"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");await this.opts.dispatchReq({type:"req",id:`manager-queue-edit-${p()}`,method:"chat.queue.edit",params:{sessionId:i,queueMessageId:String(n.queueMessageId||n.messageId||""),text:String(n.message||n.text||"")}}),u(r,200,{ok:!0,queue:this.opts.getRuntime().chatQueue?.getSnapshot(i)});return}if(t.pathname==="/sessions/queue/delete"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");await this.opts.dispatchReq({type:"req",id:`manager-queue-delete-${p()}`,method:"chat.queue.delete",params:{sessionId:i,queueMessageId:String(n.queueMessageId||n.messageId||"")}}),u(r,200,{ok:!0,queue:this.opts.getRuntime().chatQueue?.getSnapshot(i)});return}if(t.pathname==="/sessions/stop"||t.pathname==="/sessions/terminate"){const i=String(n.sessionId||"");if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");await this.opts.dispatchReq({type:"req",id:`manager-abort-${p()}`,method:"chat.abort",params:{sessionId:i}}),this.registry.updateWorker(i,{status:"aborted"}),u(r,200,{ok:!0});return}if(t.pathname==="/sessions/read"){const i=String(n.sessionId||""),c=Number(n.limit||200);if(!this.registry.getWorkerForManager(s,i))throw new Error("Worker not found in this manager scope");const l=ae(i,{limit:Math.max(c*20,c)});u(r,200,{ok:!0,messages:Ie(l,c),rawMessageCount:l.length});return}if(t.pathname==="/memory/path"){if(!o)throw new Error("Manager runtime is not registered");u(r,200,{ok:!0,path:y.join(o.workDir,".shennian")});return}if(t.pathname==="/external/reply"){const i=typeof n.replyTarget=="string"?this.registry.getReplyTarget(n.replyTarget):this.registry.getLatestReplyTargetForManager(s),c=String(n.text||""),d=B(n.attachment),l=String(n.idempotencyKey||p()),h=String(n.channelId||""),m=String(n.conversationId||""),C=!i&&(!h||!m)?await this.channelRuntime.getDefaultReplyTarget(s).catch(()=>null):null,I=i?.channelId||h||C?.channelId||"",E=i?.conversationId||m||C?.conversationId||"",W=I?this.channelRuntime.getChannelById(I):void 0,z=W&&(!!(i||h)||W.managedBy!=="session-sync");if(I&&z){if(!E)throw new Error("No external channel target is available for this Manager");const f=await this.channelRuntime.reply({managerSessionId:s,channelId:I,conversationId:E,messageId:i?.messageId??void 0,text:c,attachment:d,idempotencyKey:l});u(r,f.ok?200:400,f);return}const x=await this.tryDirectWeChatRpaReply(s,c,d);if(x){u(r,x.ok?200:400,x);return}let S;try{S=await this.sendManagedWeComReply({managerSessionId:s,text:c,attachment:d,idempotencyKey:l})}catch(f){const v=f instanceof Error?f.message:String(f);if(!q(v))throw f;S={ok:!1,error:v}}if(S.ok){u(r,200,{ok:!0,payload:S.payload});return}if(!q(S.error||"")||!I||!E){u(r,400,{ok:!1,error:S.error||"External send failed"});return}u(r,400,{ok:!1,error:`No local external channel is configured for ${I}`});return}if(t.pathname==="/channel/get"){u(r,200,{ok:!0,channel:this.channelRuntime.getManagerChannel(s,"websocket")});return}if(t.pathname==="/channel/upsert"){if(!o)throw new Error("Manager runtime is not registered");const i=await this.channelRuntime.upsertManagerChannel({id:String(n.id||`websocket:${s}`),managerSessionId:s,workDir:o.workDir,type:"websocket",name:typeof n.name=="string"?n.name:void 0,enabled:!!n.enabled,wsUrl:typeof n.wsUrl=="string"?n.wsUrl:void 0,token:typeof n.token=="string"?n.token:void 0,canReply:n.canReply===void 0?void 0:!!n.canReply,systemPrompt:typeof n.systemPrompt=="string"?n.systemPrompt:void 0});this.registry.upsertManager({...o,status:o.status}),this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,channel:i});return}if(t.pathname==="/wechat-rpa/tool/read"){const i=L(n),c=g(n.limit)??10,d=typeof n.traceId=="string"?n.traceId:void 0;let l;try{l=await this.weChatAutomationLane.run(`wechat-tool:read:${i.channelId}`,()=>he(i,{conversation:i.conversationName,workDir:i.workDir,sessionId:i.sessionId,limit:c,recentLimit:c,download:n.download==="never"?"never":"auto",traceId:d,timeoutMs:g(n.timeoutMs)}))}catch(h){u(r,400,{ok:!1,...j(h,d)});return}u(r,200,{ok:!0,messages:l.messages,outDir:l.outDir,helperTracePath:l.helperTracePath,activityGuardPath:l.activityGuardPath});return}if(t.pathname==="/wechat-rpa/tool/send"){const i=L(n),c=String(n.text||""),d=B(n.attachment),l=typeof n.traceId=="string"?n.traceId:void 0;let h;try{h=await this.weChatAutomationLane.run(`wechat-tool:send:${i.channelId}`,()=>P(i,{conversation:i.conversationName,workDir:i.workDir,sessionId:i.sessionId,text:c,attachment:d,traceId:l,timeoutMs:g(n.timeoutMs)}))}catch(m){u(r,400,{ok:!1,...j(m,l)});return}u(r,200,{ok:!0,...h});return}if(t.pathname==="/wechat-rpa/channel/get"){u(r,200,{ok:!0,channel:this.channelRuntime.getManagerChannel(s,"wechat-rpa",{includeSecret:!0})});return}if(t.pathname==="/wechat-rpa/channel/upsert"){const i=R(String(n.workDir||o?.workDir||""));if(!i)throw new Error("workDir is required");const c=await this.channelRuntime.upsertManagerWeChatRpaChannel({id:String(n.id||`wechat-rpa:${s}`),managerSessionId:s,sessionId:s,workDir:i,name:typeof n.name=="string"?n.name:void 0,agentType:typeof n.agentType=="string"?n.agentType:void 0,agentSessionId:typeof n.agentSessionId=="string"?n.agentSessionId:null,modelId:typeof n.modelId=="string"?n.modelId:null,enabled:!!n.enabled,groups:O(n.groups),canReply:n.canReply===void 0?void 0:!!n.canReply,systemPrompt:typeof n.systemPrompt=="string"?n.systemPrompt:void 0,source:U(n.source),pollIntervalMs:g(n.pollIntervalMs),recentLimit:g(n.recentLimit),idleSeconds:g(n.idleSeconds),forceForeground:n.forceForeground===void 0?void 0:!!n.forceForeground,noRestore:n.noRestore===void 0?void 0:!!n.noRestore,downloadAttachments:n.downloadAttachments===void 0?void 0:!!n.downloadAttachments,downloadAttachmentsDir:typeof n.downloadAttachmentsDir=="string"?n.downloadAttachmentsDir:void 0,selfNickname:typeof n.selfNickname=="string"?n.selfNickname:void 0,selfTriggerMarker:typeof n.selfTriggerMarker=="string"?n.selfTriggerMarker:void 0,deferInitialPoll:n.deferInitialPoll===void 0?void 0:!!n.deferInitialPoll,privacyConsentAccepted:n.privacyConsentAccepted===void 0?void 0:!!n.privacyConsentAccepted,flowScriptPath:typeof n.flowScriptPath=="string"?n.flowScriptPath:void 0});o&&this.registry.upsertManager({...o,status:o.status}),this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,channel:c});return}if(t.pathname==="/wechat-rpa/channel/sync"){const{channel:i,messages:c}=await this.channelRuntime.syncManagerWeChatRpaChannel(s);this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,channel:i,messages:c});return}if(t.pathname==="/wechat-rpa/outbound/cancel"){const i=await this.channelRuntime.cancelManagerWeChatRpaOutbound({managerSessionId:s,idempotencyKey:typeof n.idempotencyKey=="string"?n.idempotencyKey:null,replyId:typeof n.replyId=="string"?n.replyId:null,reason:typeof n.reason=="string"?n.reason:"user_cancelled"});this.broadcastManagerChannelStatus(s),u(r,200,{ok:!0,...i});return}u(r,404,{ok:!1,error:`Unknown manager IPC path: ${t.pathname}`})}catch(t){u(r,400,{ok:!1,error:t instanceof Error?t.message:String(t)})}}async dispatchChatSend(e,r,t,n,s,o){await this.opts.dispatchReq({type:"req",id:`manager-send-${p()}`,method:"chat.send",params:{sessionId:e,text:n,agentType:r,workDir:t,agentSessionId:s,modelId:o}})}async dispatchChatEnqueue(e,r,t,n,s,o){await this.opts.dispatchReq({type:"req",id:`manager-enqueue-${p()}`,method:"chat.enqueue",params:{sessionId:e,text:n,agentType:r,workDir:t,agentSessionId:s,modelId:o}})}async tryDirectWeChatRpaReply(e,r,t){const n=this.opts.getRuntime().sessions.get(e),s=n?.externalChannel;if(!s||s.type!=="wechat-rpa"||!s.channelId||!s.name)return null;const o=process.env.SHENNIAN_MACHINE_ID||b().machineId||"";if(s.machineId&&o&&s.machineId!==o)return{ok:!1,error:`WeChat \u7ED1\u5B9A\u5C5E\u4E8E\u5176\u4ED6\u673A\u5668 (${s.machineId})\uFF0C\u8BF7\u5728\u7ED1\u5B9A\u673A\u5668\u4E0A\u53D1\u9001\u3002`};if(!r.trim()&&!t)return{ok:!1,error:"text or attachment is required"};const i=n?.workDir||process.cwd(),c={sessionId:e,channelId:s.channelId,conversationId:de(s.name),conversationName:s.name,workDir:i};try{return{ok:!0,payload:await this.weChatAutomationLane.run(`wechat-tool:send:${c.channelId}`,()=>P(c,{conversation:c.conversationName,workDir:c.workDir,sessionId:c.sessionId,text:r,attachment:t}))}}catch(d){return{ok:!1,error:d instanceof Error?d.message:String(d)}}}async sendManagedWeComReply(e){const r=ce(e.text);if(!r.length&&!e.attachment)return{ok:!1,error:"text or attachment is required"};const t=this.opts.getRuntime().client;if(!t||typeof t.sendReq!="function")return{ok:!1,error:"Relay is not connected"};const n=[];for(const[s,o]of r.entries()){const i=await t.sendReq({type:"req",id:`external-send-${p()}`,method:"external.send",params:{managerSessionId:e.managerSessionId,text:o,idempotencyKey:r.length>1?`${e.idempotencyKey}:${s+1}`:e.idempotencyKey}});if(!i.ok)return{ok:!1,error:i.error||"External send failed"};n.push(i.payload)}if(e.attachment){const s=await t.sendReq({type:"req",id:`external-send-${p()}`,method:"external.send",params:{managerSessionId:e.managerSessionId,attachment:e.attachment,idempotencyKey:r.length?`${e.idempotencyKey}:attachment`:e.idempotencyKey}});if(!s.ok)return{ok:!1,error:s.error||"External send failed"};n.push(s.payload)}return{ok:!0,payload:n.length===1?n[0]:n}}wakeManagerForWorker(e,r,t,n){const s=this.registry.getManager(e);if(!s)return;const o=`\u4F60\u7BA1\u7406\u7684 worker \u5DF2\u7ED3\u675F\u3002
3
3
 
4
4
  Worker: ${r.sessionId}
5
5
  \u72B6\u6001\uFF1A${t}
6
6
  \u6700\u7EC8\u7ED3\u679C\uFF1A
7
7
  ${n||r.summary||"(\u65E0\u53EF\u89C1\u6458\u8981)"}
8
8
 
9
- \u8BF7\u51B3\u5B9A\u4E0B\u4E00\u6B65\uFF1A\u7EE7\u7EED\u7B49\u5F85\u3001\u521B\u5EFA/\u6307\u6D3E worker\u3001\u505C\u6B62 worker\u3001\u8BE2\u95EE\u7528\u6237\uFF0C\u6216\u5411\u7528\u6237\u6C47\u62A5\u3002`;this.interruptAndResumeManager(s,o,t==="final"?"worker.final":`worker.${t}`)}handleExternalMessage(e,r){const t=this.channelRuntime.getChannelById(r.channelId)??this.channelRuntime.getManagerChannel(e,r.channelType),n=this.channelRuntime.getChannelStatusById(r.channelId)??this.channelRuntime.getManagerChannelStatus(e),s=this.registry.getManager(e),o=t?.agentType||(s?"manager":"codex"),i=t?.workDir||s?.workDir||process.cwd(),c=t?.agentSessionId??s?.agentSessionId??null,d=t?.modelId||s?.modelId||"",l=Re(r.attachments,r.channelType),h=Me(r);this.dispatchExternalMessage({sessionId:e,agentType:o,workDir:i,agentSessionId:c,modelId:d,text:h,attachments:l,externalChannel:Ee(n),replyTarget:r.replyTarget})}async dispatchExternalMessage(e){await this.opts.dispatchReq({type:"req",id:`external-enqueue-${m()}`,method:"chat.enqueue",params:{sessionId:e.sessionId,text:e.text,agentType:e.agentType,workDir:e.workDir,agentSessionId:e.agentSessionId,modelId:e.modelId,origin:"external",attachments:e.attachments,externalChannel:e.externalChannel??null,replyTarget:e.replyTarget}})}scanWorkerHealth(){const e=Date.now(),r=this.registry.load();for(const t of Object.values(r.workers)){if(t.status!=="running")continue;const n=e-Date.parse(t.createdAt);if(n<10*6e4)continue;const s=t.healthNotifiedAt?Date.parse(t.healthNotifiedAt):0;if(s&&e-s<10*6e4)continue;const o=r.managers[t.managedBy];if(!o)continue;const i=Math.max(0,Math.floor((e-Date.parse(t.lastActivityAt))/6e4)),c=`Worker ${t.sessionId} \u5DF2\u8FD0\u884C ${Math.floor(n/6e4)} \u5206\u949F\uFF0C\u5C1A\u672A\u7ED3\u675F\u3002
9
+ \u8BF7\u51B3\u5B9A\u4E0B\u4E00\u6B65\uFF1A\u7EE7\u7EED\u7B49\u5F85\u3001\u521B\u5EFA/\u6307\u6D3E worker\u3001\u505C\u6B62 worker\u3001\u8BE2\u95EE\u7528\u6237\uFF0C\u6216\u5411\u7528\u6237\u6C47\u62A5\u3002`;this.interruptAndResumeManager(s,o,t==="final"?"worker.final":`worker.${t}`)}handleExternalMessage(e,r){const t=this.channelRuntime.getChannelById(r.channelId)??this.channelRuntime.getManagerChannel(e,r.channelType),n=this.channelRuntime.getChannelStatusById(r.channelId)??this.channelRuntime.getManagerChannelStatus(e),s=this.registry.getManager(e),o=t?.agentType||(s?"manager":"codex"),i=t?.workDir||s?.workDir||process.cwd(),c=t?.agentSessionId??s?.agentSessionId??null,d=t?.modelId||s?.modelId||"",l=Re(r.attachments,r.channelType),h=Me(r);this.dispatchExternalMessage({sessionId:e,agentType:o,workDir:i,agentSessionId:c,modelId:d,text:h,messageId:r.messageId,attachments:l,externalChannel:Ee(n),replyTarget:r.replyTarget})}async dispatchExternalMessage(e){const r=typeof e.messageId=="string"&&e.messageId.trim()?e.messageId.trim():void 0;await this.opts.dispatchReq({type:"req",id:`external-enqueue-${p()}`,method:"chat.enqueue",params:{sessionId:e.sessionId,text:e.text,agentType:e.agentType,workDir:e.workDir,agentSessionId:e.agentSessionId,modelId:e.modelId,origin:"external",queueMessageId:r,clientMessageId:r,attachments:e.attachments,externalChannel:e.externalChannel??null,replyTarget:e.replyTarget}})}scanWorkerHealth(){const e=Date.now(),r=this.registry.load();for(const t of Object.values(r.workers)){if(t.status!=="running")continue;const n=e-Date.parse(t.createdAt);if(n<10*6e4)continue;const s=t.healthNotifiedAt?Date.parse(t.healthNotifiedAt):0;if(s&&e-s<10*6e4)continue;const o=r.managers[t.managedBy];if(!o)continue;const i=Math.max(0,Math.floor((e-Date.parse(t.lastActivityAt))/6e4)),c=`Worker ${t.sessionId} \u5DF2\u8FD0\u884C ${Math.floor(n/6e4)} \u5206\u949F\uFF0C\u5C1A\u672A\u7ED3\u675F\u3002
10
10
 
11
11
  \u5F53\u524D\u53EF\u89C1\u8FDB\u5C55\uFF1A
12
12
  - \u6700\u8FD1\u6587\u672C\u6458\u8981\uFF1A${t.summary||"(\u65E0\u53EF\u89C1\u6458\u8981)"}
13
13
  - \u6700\u8FD1\u6D3B\u52A8\u65F6\u95F4\uFF1A${t.lastActivityAt}
14
14
  - \u6700\u8FD1 ${i} \u5206\u949F\u6CA1\u6709\u65B0\u6D3B\u52A8\u3002
15
15
 
16
- \u8BF7\u51B3\u5B9A\u662F\u5426\u7EE7\u7EED\u7B49\u5F85\u3001\u8BE2\u95EE\u7528\u6237\u3001\u505C\u6B62 worker\u3001\u6216\u521B\u5EFA\u5176\u4ED6 worker \u534F\u52A9\u3002`;this.registry.updateWorker(t.sessionId,{healthNotifiedAt:new Date(e).toISOString(),lastHealthSummary:c}),o.status==="idle"&&this.dispatchChatSend(o.sessionId,"manager",o.workDir,c,o.agentSessionId,o.modelId)}}async interruptAndResumeManager(e,r,t){this.opts.getRuntime().sessions.get(e.sessionId)?.currentRunId&&(this.registry.upsertManager({...e,status:"interrupting"}),await this.opts.dispatchReq({type:"req",id:`manager-interrupt-${m()}`,method:"chat.abort",params:{sessionId:e.sessionId}}));const o=t?`\u4E8B\u4EF6\u7C7B\u578B\uFF1A${t}
16
+ \u8BF7\u51B3\u5B9A\u662F\u5426\u7EE7\u7EED\u7B49\u5F85\u3001\u8BE2\u95EE\u7528\u6237\u3001\u505C\u6B62 worker\u3001\u6216\u521B\u5EFA\u5176\u4ED6 worker \u534F\u52A9\u3002`;this.registry.updateWorker(t.sessionId,{healthNotifiedAt:new Date(e).toISOString(),lastHealthSummary:c}),o.status==="idle"&&this.dispatchChatSend(o.sessionId,"manager",o.workDir,c,o.agentSessionId,o.modelId)}}async interruptAndResumeManager(e,r,t){this.opts.getRuntime().sessions.get(e.sessionId)?.currentRunId&&(this.registry.upsertManager({...e,status:"interrupting"}),await this.opts.dispatchReq({type:"req",id:`manager-interrupt-${p()}`,method:"chat.abort",params:{sessionId:e.sessionId}}));const o=t?`\u4E8B\u4EF6\u7C7B\u578B\uFF1A${t}
17
17
 
18
18
  ${r}`:r;await this.dispatchChatSend(e.sessionId,"manager",e.workDir,o,e.agentSessionId,e.modelId)}bindManagerAdapterEvents(e,r){r.on("agentEvent",t=>{if(t.state==="start"&&t.agentSessionId){const n=this.registry.getManager(e);n&&this.noteManagerAgentSession(e,t.agentSessionId,n.workDir,n.modelId)}t.state==="start"&&this.updateManagerStatus(e,"running"),(t.state==="final"||t.state==="error"||t.state==="aborted")&&this.updateManagerStatus(e,"idle")})}updateManagerStatus(e,r){const t=this.registry.getManager(e);t&&this.registry.upsertManager({...t,status:r})}getExternalChannelStatus(e){return this.channelRuntime.getManagerChannelStatus(e)}getManagerExternalChannelSystemPrompt(e){return this.channelRuntime.listManagerExternalChannels(e).map(r=>ue(r,void 0,e,"manager")).join(`
19
19
 
20
20
  `).trim()}}function O(a){return Array.isArray(a)?a.map(e=>({name:String(e?.name||"").trim()})).filter(e=>e.name):[]}function U(a){return a==="wechat-channel"||a==="macos-flow"||a==="macos-probe"||a==="windows-visual-flow"||a==="wechat-rpa-lab"||a==="fixture-jsonl"?a:void 0}function Re(a,e){const r=a.map(t=>H(t,e)).filter(t=>t!=null);return r.length?r:void 0}function Ce(a,e,r,t){const n=e||"",s=new Set;return a.map((i,c)=>{const d=H(i,t),l=ee({type:i.type,name:d?.name||i.name,path:d?.path,mimeType:d?.mimeType||i.mimeType,availability:i.availability,providerError:i.providerError||Te(i)},c),h=d?.path||"";if(h){const C=`${l}
21
- ${h}`;return s.has(C)||n.includes(h)?"":(s.add(C),`${r}: ${l}`)}const p=l;return s.has(p)?"":(s.add(p),`${r}: ${l}`)}).filter(i=>!n.includes(i)).join(`
21
+ ${h}`;return s.has(C)||n.includes(h)?"":(s.add(C),`${r}: ${l}`)}const m=l;return s.has(m)?"":(s.add(m),`${r}: ${l}`)}).filter(i=>!n.includes(i)).join(`
22
22
  `)}function Me(a){const r=(a.channelType==="wechat-rpa"?Ae(a.sender.name):a.sender.name||a.sender.id)||(a.channelType==="wechat-rpa"?"\u5BF9\u65B9":a.sender.id)||"\u5BF9\u65B9",t=Ce(a.attachments,a.text,r,a.channelType),s=[a.text?Z({senderName:r,senderId:a.sender.id,text:a.text}):t?"":`${r}:`,t].filter(Boolean).join(`
23
23
  `);return[X({conversationName:a.conversationName||a.conversationId,messages:[]}),s].filter(Boolean).join(`
24
24
  `)}function Ae(a){const e=a?.trim()||"";return!e||/^(contact|self|system|unknown)$/i.test(e)||/^wechat-sender:/i.test(e)?"":e}function Te(a){return!a.localPath||a.availability&&a.availability!=="edge-local"||D(a.localPath)?"":"edge-local-unavailable"}function H(a,e){return a.localPath&&xe(a,e)&&D(a.localPath)?{path:a.localPath,name:a.name||y.basename(a.localPath)||"attachment",mimeType:a.mimeType||K(a)}:a.url&&Ne(a)?{path:a.url,name:a.name||a.url.split("/").filter(Boolean).at(-1)||"attachment",mimeType:a.mimeType||K(a)}:a.thumbnailPath&&!G(a,e)&&D(a.thumbnailPath)?{path:a.thumbnailPath,name:a.name?`${a.name}-preview.png`:y.basename(a.thumbnailPath)||"preview.png",mimeType:"image/png"}:null}function Ee(a){return a?a.type!=="wechat-rpa"?a:{configured:a.configured,connected:a.connected,type:a.type,channelId:a.channelId,name:a.name,canReply:a.canReply,systemPrompt:a.systemPrompt,wechatRpaSource:a.wechatRpaSource,wechatRpaGroups:a.wechatRpaGroups,pollIntervalMs:a.pollIntervalMs,recentLimit:a.recentLimit,idleSeconds:a.idleSeconds,forceForeground:a.forceForeground,noRestore:a.noRestore,downloadAttachments:a.downloadAttachments,selfNickname:a.selfNickname,wechatRpaPrivacyConsentAccepted:a.wechatRpaPrivacyConsentAccepted,wechatRpaServerDecisionAvailable:a.wechatRpaServerDecisionAvailable,wechatRpaPreflightChecks:a.wechatRpaPreflightChecks,wechatRpaRuntimeState:a.wechatRpaRuntimeState,wechatRpaLastMessageAt:a.wechatRpaLastMessageAt,wechatRpaPendingReplyCount:a.wechatRpaPendingReplyCount,wechatRpaLastError:a.wechatRpaLastError}:null}function xe(a,e){return a.providerError||a.availability&&a.availability!=="edge-local"?!1:G(a,e)?a.materializationKind==="original-file"&&a.isOriginal===!0&&a.mimeKindMatches===!0&&!be(a.localPath):!0}function Ne(a){return!a.providerError&&(!a.availability||a.availability==="server-url")}function G(a,e){if(e!=="wechat-rpa")return!1;const r=String(a.type||"").toLowerCase();return r==="file"||r==="video"||r==="video-file"}function be(a){const e=String(a||"").replace(/\\/g,"/"),r=y.basename(e).toLowerCase();return/(^|\/)\.uploads(\/|$)/.test(e)||/(^|-)preview([-.]|$)/i.test(r)}function D(a){try{return k.statSync(a).isFile()}catch{return!1}}function K(a){return a.type==="image"?"image/*":a.type==="video"?"video/*":a.type==="audio"?"audio/*":"application/octet-stream"}function g(a){const e=Number(a);return Number.isFinite(e)?e:void 0}function j(a,e){const r=T(a,"reasonCode")||De(a),t=T(a,"outDir"),n=T(a,"helperTracePath"),s=T(a,"activityGuardPath");return{error:a instanceof Error?a.message:String(a||r),reasonCode:r,...t?{outDir:t}:{},...n?{helperTracePath:n}:{},...s?{activityGuardPath:s}:{},...e?{traceId:e}:{}}}function T(a,e){if(!a||typeof a!="object")return"";const r=a[e];return typeof r=="string"&&r.trim()?r.trim():""}function De(a){const e=a instanceof Error?a.message:String(a||"");return/^([a-z][a-z0-9_]*)(?::|\b)/i.exec(e.trim())?.[1]||"wechat_tool_failed"}export{Ze as ManagerRuntimeService,Xe as getManagerRuntimeService,Qe as setManagerRuntimeService};
@@ -18,5 +18,6 @@ export declare class ChatQueueManager {
18
18
  private drainNext;
19
19
  private mergeExternalMessages;
20
20
  private dispatchQueuedMessage;
21
+ private isSessionBusy;
21
22
  private broadcast;
22
23
  }
@@ -1,4 +1,4 @@
1
- import l from"node:fs";import{randomUUID as m}from"node:crypto";import{resolveShennianPath as f}from"../config/index.js";import{mergeProjectedSessions as I}from"./projection.js";import{materializeRemoteChatAttachments as x}from"./remote-attachments.js";const y=f("chat-queue.json");function w(){return{sessions:{}}}function h(){return new Date().toISOString()}function S(i){return`enqueue-send-${i}-${m()}`}function r(){try{const i=JSON.parse(l.readFileSync(y,"utf-8"));return{sessions:i.sessions&&typeof i.sessions=="object"?i.sessions:{}}}catch{return w()}}function u(i){l.mkdirSync(f(""),{recursive:!0}),l.writeFileSync(y,JSON.stringify(i,null,2))}function p(i){if(!Array.isArray(i))return;const e=i.map(s=>{if(!s||typeof s!="object")return null;const t=s,n={path:typeof t.path=="string"?t.path:"",name:typeof t.name=="string"?t.name:"",mimeType:typeof t.mimeType=="string"?t.mimeType:"",...typeof t.previewData=="string"&&t.previewData.trim()?{previewData:t.previewData.trim()}:{}};return n.path&&n.name&&n.mimeType?n:null}).filter(s=>s!=null);return e.length?e:void 0}function M(i){const e=h();return{id:i.queueMessageId||i.clientMessageId||`queue-${m()}`,sessionId:i.sessionId,text:i.text,agentType:i.agentType,workDir:i.workDir,agentSessionId:i.agentSessionId??null,modelId:i.modelId??null,reasoningEffort:i.reasoningEffort??null,clientMessageId:i.clientMessageId??null,attachments:p(i.attachments),externalChannel:i.externalChannel??null,replyTarget:i.replyTarget??null,origin:i.origin,createdAt:e,updatedAt:e}}class Q{opts;draining=new Set;constructor(e){this.opts=e,setTimeout(()=>this.drainIdleQueues(),0).unref?.()}getSnapshot(e){return{sessionId:e,busy:!!this.opts.getRuntime().sessions.get(e)?.currentRunId,pending:r().sessions[e]??[]}}async handleEnqueue(e){const s=this.opts.getRuntime(),t=e.params;if(I(t.sessionListProjection),!t.sessionId||!t.text||!t.agentType||!t.workDir){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId, text, agentType and workDir are required"});return}const n=p(t.attachments),o=n?.length?await x({text:t.text,attachments:n,workDir:t.workDir}):{text:t.text,attachments:n,localized:!1},d=!!s.sessions.get(t.sessionId)?.currentRunId;if(!d&&!r().sessions[t.sessionId]?.length){await this.opts.dispatchReq({...e,id:S(e.id),method:"chat.send",params:{...t,text:o.text,responseId:e.id,clientMessageId:t.clientMessageId??t.queueMessageId,waitForDispatch:!0,attachments:o.attachments}});return}const c=r(),g=M({...t,text:o.text,attachments:o.attachments});c.sessions[t.sessionId]=[...c.sessions[t.sessionId]??[],g],u(c),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queued:!0,queueMessageId:g.id,queue:this.getSnapshot(t.sessionId),...o.localized?{localizedAttachments:!0}:{}}}),d||this.drainNext(t.sessionId)}async handleGet(e){const s=this.opts.getRuntime(),t=e.params;if(!t.sessionId){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId is required"});return}s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}}),this.getSnapshot(t.sessionId).busy||this.drainNext(t.sessionId)}async handleEdit(e){const s=this.opts.getRuntime(),t=e.params;if(!t.sessionId||!t.queueMessageId||!t.text){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId, queueMessageId and text are required"});return}const n=r(),o=n.sessions[t.sessionId]??[],a=o.findIndex(d=>d.id===t.queueMessageId);if(a<0){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}o[a]={...o[a],text:t.text,attachments:p(t.attachments),updatedAt:h()},n.sessions[t.sessionId]=o,u(n),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}})}async handleDelete(e){const s=this.opts.getRuntime(),t=e.params;if(!t.sessionId||!t.queueMessageId){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId and queueMessageId are required"});return}const n=r(),o=n.sessions[t.sessionId]??[],a=o.filter(d=>d.id!==t.queueMessageId);if(a.length===o.length){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}a.length?n.sessions[t.sessionId]=a:delete n.sessions[t.sessionId],u(n),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}})}noteTerminal(e){this.drainNext(e)}drainIdleQueues(){const e=r();for(const s of Object.keys(e.sessions))this.getSnapshot(s).busy||this.drainNext(s)}async drainNext(e){if(this.draining.has(e)||this.opts.getRuntime().sessions.get(e)?.currentRunId)return;const t=r(),n=t.sessions[e]??[],o=n.shift();if(!o){this.broadcast(e);return}const a=o.origin==="external"?this.mergeExternalMessages(o,n):o;n.length?t.sessions[e]=n:delete t.sessions[e],u(t),this.broadcast(e),this.draining.add(e);try{await this.dispatchQueuedMessage(a)}finally{this.draining.delete(e)}}mergeExternalMessages(e,s){const t=[e];for(;s[0]?.origin==="external";)t.push(s.shift());const n=R(t);return n.length===1?n[0]:{...e,id:`external-batch-${e.id}`,text:n.map(o=>o.text).filter(Boolean).join(`
1
+ import h from"node:fs";import{randomUUID as y}from"node:crypto";import{resolveShennianPath as I}from"../config/index.js";import{mergeProjectedSessions as w}from"./projection.js";import{materializeRemoteChatAttachments as S}from"./remote-attachments.js";const x=I("chat-queue.json");function M(){return{sessions:{}}}function p(){return new Date().toISOString()}function R(n){return`enqueue-send-${n}-${y()}`}function u(){try{const n=JSON.parse(h.readFileSync(x,"utf-8"));return{sessions:n.sessions&&typeof n.sessions=="object"?n.sessions:{}}}catch{return M()}}function d(n){h.mkdirSync(I(""),{recursive:!0}),h.writeFileSync(x,JSON.stringify(n,null,2))}function f(n){if(!Array.isArray(n))return;const e=n.map(s=>{if(!s||typeof s!="object")return null;const t=s,i={path:typeof t.path=="string"?t.path:"",name:typeof t.name=="string"?t.name:"",mimeType:typeof t.mimeType=="string"?t.mimeType:"",...typeof t.previewData=="string"&&t.previewData.trim()?{previewData:t.previewData.trim()}:{}};return i.path&&i.name&&i.mimeType?i:null}).filter(s=>s!=null);return e.length?e:void 0}function q(n){const e=p();return{id:n.queueMessageId||n.clientMessageId||`queue-${y()}`,sessionId:n.sessionId,text:n.text,agentType:n.agentType,workDir:n.workDir,agentSessionId:n.agentSessionId??null,modelId:n.modelId??null,reasoningEffort:n.reasoningEffort??null,clientMessageId:n.clientMessageId??null,attachments:f(n.attachments),externalChannel:n.externalChannel??null,replyTarget:n.replyTarget??null,origin:n.origin,createdAt:e,updatedAt:e}}class B{opts;draining=new Set;constructor(e){this.opts=e,setTimeout(()=>this.drainIdleQueues(),0).unref?.()}getSnapshot(e){return{sessionId:e,busy:!!this.opts.getRuntime().sessions.get(e)?.currentRunId,pending:u().sessions[e]??[]}}async handleEnqueue(e){const s=this.opts.getRuntime(),t=e.params;if(w(t.sessionListProjection),!t.sessionId||!t.text||!t.agentType||!t.workDir){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId, text, agentType and workDir are required"});return}const i=f(t.attachments),r=i?.length?await S({text:t.text,attachments:i,workDir:t.workDir}):{text:t.text,attachments:i,localized:!1},a=await this.isSessionBusy(t.sessionId),o=u(),c=o.sessions[t.sessionId]??[];if(!a&&!c.length){await this.opts.dispatchReq({...e,id:R(e.id),method:"chat.send",params:{...t,text:r.text,responseId:e.id,clientMessageId:t.clientMessageId??t.queueMessageId,waitForDispatch:!0,attachments:r.attachments}});return}const l=q({...t,text:r.text,attachments:r.attachments}),m=t.origin==="external"?D(c,l):null;m||(o.sessions[t.sessionId]=[...c,l],d(o)),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queued:!0,queueMessageId:m?.id??l.id,queue:this.getSnapshot(t.sessionId),...r.localized?{localizedAttachments:!0}:{}}}),a||this.drainNext(t.sessionId)}async handleGet(e){const s=this.opts.getRuntime(),t=e.params;if(!t.sessionId){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId is required"});return}s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}}),this.getSnapshot(t.sessionId).busy||this.drainNext(t.sessionId)}async handleEdit(e){const s=this.opts.getRuntime(),t=e.params;if(!t.sessionId||!t.queueMessageId||!t.text){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId, queueMessageId and text are required"});return}const i=u(),r=i.sessions[t.sessionId]??[],a=r.findIndex(o=>o.id===t.queueMessageId);if(a<0){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}r[a]={...r[a],text:t.text,attachments:f(t.attachments),updatedAt:p()},i.sessions[t.sessionId]=r,d(i),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}})}async handleDelete(e){const s=this.opts.getRuntime(),t=e.params;if(!t.sessionId||!t.queueMessageId){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId and queueMessageId are required"});return}const i=u(),r=i.sessions[t.sessionId]??[],a=r.filter(o=>o.id!==t.queueMessageId);if(a.length===r.length){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}a.length?i.sessions[t.sessionId]=a:delete i.sessions[t.sessionId],d(i),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}})}noteTerminal(e){this.drainNext(e)}drainIdleQueues(){const e=u();for(const s of Object.keys(e.sessions))this.drainNext(s)}async drainNext(e){if(this.draining.has(e))return;const s=this.opts.getRuntime();if(await this.isSessionBusy(e))return;const t=u(),i=t.sessions[e]??[],r=i.shift();if(!r){this.broadcast(e);return}const a=r.origin==="external"?this.mergeExternalMessages(r,i):r;i.length?t.sessions[e]=i:delete t.sessions[e],d(t),this.broadcast(e),this.draining.add(e);try{await this.dispatchQueuedMessage(a)}finally{this.draining.delete(e)}}mergeExternalMessages(e,s){const t=[e];for(;s[0]?.origin==="external";)t.push(s.shift());const i=k(t);return i.length===1?i[0]:{...e,id:`external-batch-${e.id}`,text:i.map(r=>r.text).filter(Boolean).join(`
2
2
 
3
- `),attachments:q(n.flatMap(o=>o.attachments??[])),updatedAt:h()}}async dispatchQueuedMessage(e){await this.opts.dispatchReq({type:"req",id:`queue-send-${e.id}-${Date.now()}`,method:"chat.send",params:{sessionId:e.sessionId,text:e.text,agentType:e.agentType,workDir:e.workDir,agentSessionId:e.agentSessionId??null,modelId:e.modelId??void 0,reasoningEffort:e.reasoningEffort??void 0,clientMessageId:e.clientMessageId??e.id,attachments:e.attachments,externalChannel:e.externalChannel,replyTarget:e.replyTarget,waitForDispatch:!0}})}broadcast(e){this.opts.getRuntime().client.sendEvent({type:"event",event:"session.queue.update",payload:{queue:this.getSnapshot(e)}})}}function R(i){const e=new Set,s=[];for(const t of i){const n=[k(t.text),...(t.attachments??[]).map(o=>o.path||`${o.name}:${o.mimeType}`)].join(`
4
- `);e.has(n)||(e.add(n),s.push(t))}return s}function q(i){const e=new Set,s=[];for(const t of i){const n=t.path||`${t.name}:${t.mimeType}`;e.has(n)||(e.add(n),s.push(t))}return s.length?s:void 0}function k(i){return String(i||"").replace(/\s+/g," ").trim()}export{Q as ChatQueueManager};
3
+ `),attachments:b(i.flatMap(r=>r.attachments??[])),updatedAt:p()}}async dispatchQueuedMessage(e){await this.opts.dispatchReq({type:"req",id:`queue-send-${e.id}-${Date.now()}`,method:"chat.send",params:{sessionId:e.sessionId,text:e.text,agentType:e.agentType,workDir:e.workDir,agentSessionId:e.agentSessionId??null,modelId:e.modelId??void 0,reasoningEffort:e.reasoningEffort??void 0,clientMessageId:e.clientMessageId??e.id,attachments:e.attachments,externalChannel:e.externalChannel,replyTarget:e.replyTarget,waitForDispatch:!0}})}async isSessionBusy(e){const s=this.opts.getRuntime().sessions.get(e);if(!s)return!1;if(s.currentRunId)return!0;if(!s.adapter.getStatus)return!1;const t=await s.adapter.getStatus().catch(()=>null);return t?.active?(t.runId&&(s.currentRunId=t.runId,s.currentRunPhase=t.runPhase??s.currentRunPhase),!0):!1}broadcast(e){this.opts.getRuntime().client.sendEvent({type:"event",event:"session.queue.update",payload:{queue:this.getSnapshot(e)}})}}function k(n){const e=new Set,s=[];for(const t of n){const i=g(t);e.has(i)||(e.add(i),s.push(t))}return s}function D(n,e){const s=g(e);return n.find(t=>g(t)===s)??null}function g(n){const e=T(n);return e?`id:${e}`:["body",E(n.text),...(n.attachments??[]).map(s=>s.path||`${s.name}:${s.mimeType}`)].join(`
4
+ `)}function T(n){const e=typeof n.clientMessageId=="string"?n.clientMessageId.trim():"";if(e)return e;const s=typeof n.id=="string"?n.id.trim():"";return s&&!s.startsWith("queue-")?s:""}function b(n){const e=new Set,s=[];for(const t of n){const i=t.path||`${t.name}:${t.mimeType}`;e.has(i)||(e.add(i),s.push(t))}return s.length?s:void 0}function E(n){return String(n||"").replace(/\s+/g," ").trim()}export{B as ChatQueueManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shennian",
3
- "version": "0.2.132",
3
+ "version": "0.2.133",
4
4
  "description": "Shennian — AI Agent Control Plane CLI",
5
5
  "type": "module",
6
6
  "bin": {