shennian 0.3.31 → 0.3.33

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.
@@ -136,8 +136,8 @@
136
136
  },
137
137
  {
138
138
  "file": "src/agents/workbuddy.js",
139
- "beforeBytes": 14157,
140
- "afterBytes": 7328
139
+ "beforeBytes": 14907,
140
+ "afterBytes": 7558
141
141
  },
142
142
  {
143
143
  "file": "src/commands/agent.js",
@@ -601,8 +601,8 @@
601
601
  },
602
602
  {
603
603
  "file": "src/session/manager.js",
604
- "beforeBytes": 21419,
605
- "afterBytes": 11034
604
+ "beforeBytes": 21721,
605
+ "afterBytes": 11139
606
606
  },
607
607
  {
608
608
  "file": "src/session/projection.js",
@@ -4,6 +4,7 @@ import { AgentAdapter, type AgentSendContext } from './adapter.js';
4
4
  export declare function normalizeWorkBuddyModelId(modelId?: string | null): string | undefined;
5
5
  export declare function normalizeWorkBuddyReasoningEffort(value?: string | null): string | undefined;
6
6
  export declare function workBuddySystemPromptArgs(systemPrompt: string | null, platform: NodeJS.Platform, promptFile?: string): string[];
7
+ export declare function workBuddyRoomActivationText(text: string): string;
7
8
  export declare function terminateWorkBuddyProcess(proc: Pick<ChildProcess, 'pid' | 'kill'>, platform?: NodeJS.Platform, terminateWindowsTree?: (pid: number) => boolean): void;
8
9
  export declare class WorkBuddyAdapter extends AgentAdapter {
9
10
  readonly type: "workbuddy";
@@ -1,3 +1,3 @@
1
- import{spawnSync as w}from"node:child_process";import{createInterface as k}from"node:readline";import{randomUUID as I}from"node:crypto";import S from"node:path";import{AgentAdapter as x,registerAgent as _}from"./adapter.js";import{resolveBuiltinCommand as E,spawnAgentCommand as B}from"./command-spec.js";import{buildAgentProcessEnv as P}from"../agent-env.js";import{buildPlatformInstructions as T,ensurePlatformInstructionsFile as W}from"./platform-instructions.js";import{ensureWorkBuddyRoomPluginBundle as C}from"../integrations/workbuddy-plugin-bundle.js";import{roomMcpHostToolName as A}from"../integrations/room-plugin-shared.js";import{resolveWindowsSystemRoot as D}from"../windows-shell.js";const O=new Set(["minimal","low","medium","high","xhigh","max"]);function R(n){const t=n?.trim();return t&&t!=="auto"?t:void 0}function q(n){const t=n?.trim();if(t){if(O.has(t))return t;throw new Error(`Unsupported WorkBuddy reasoning effort "${t}". Supported values: minimal, low, medium, high, xhigh, max.`)}}function $(n,t,e){if(!n)return[];if(t==="win32"){if(!e)throw new Error("WorkBuddy system prompt file is required on Windows.");return["--system-prompt-file",e]}return["--append-system-prompt",n]}function c(n,t=process.platform,e=F){t==="win32"&&n.pid&&e(n.pid)||n.kill("SIGTERM")}function F(n){const t=S.win32.join(D(),"System32","taskkill.exe");return w(t,["/pid",String(n),"/T","/F"],{stdio:"ignore",windowsHide:!0,timeout:5e3}).status===0}class N extends x{type="workbuddy";process=null;agentSessionId=null;workDir=null;seq=0;runId="";terminalState="open";hasEmittedText=!1;runPhase=null;externalChannel=null;shennianSessionId=null;extraEnv={};configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,s){this.workDir=e,this.seq=0,s&&(this.agentSessionId=s)}async send(t,e,s,o,a,i){await this.killProcess(),this.runId=I(),this.resetRunState();const u=i?.source==="room_activation",r=["-p",t,"--output-format","stream-json","--verbose","--permission-mode",u?"dontAsk":"auto","--setting-sources","user,project,local"],h=R(e);h&&r.push("--model",h);const m=C(),l=A("workbuddy");u?r.push("--allowedTools",l,"--tools",`NoDefer(${l})`,"--mcp-config",m.mcpFile,"--strict-mcp-config","--disallowedTools","mcp__shennian_room__shennian_agent","--max-turns","2"):r.push("--allowedTools",l,"--tools",`*,NoDefer(${l})`),r.push("--plugin-dir",m.pluginRoot);const p=this.shennianSessionId?.startsWith("room-managed-")&&!this.agentSessionId&&!u?null:T(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,a);if(p){const y=process.platform==="win32"?W(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,a):void 0;r.push(...$(p,process.platform,y))}const f=q(s);f&&r.push("--effort",f),this.agentSessionId&&r.push("--resume",this.agentSessionId),this.spawnAndParse(r)}async resume(t){await this.killProcess(),this.agentSessionId=t,this.resetRunState()}async stop(){await this.killProcess()}async getStatus(){return{active:this.process!=null&&this.terminalState==="open",runId:this.runId||null,runPhase:this.runPhase,canStop:this.process!=null&&this.terminalState==="open"}}spawnAndParse(t){const e=E("workbuddy");if(!e){this.emit("error",new Error("WorkBuddy was not found. Install WorkBuddy Desktop or the CodeBuddy CLI, then retry."));return}const s=B(e,t,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:P(this.extraEnv)});this.process=s,k({input:s.stdout}).on("line",i=>{if(i.trim())try{this.handleStreamEvent(JSON.parse(i))}catch{}});let a="";s.stderr?.on("data",i=>{a=`${a}${i.toString()}`.slice(-8e3)}),s.on("close",i=>{this.process===s&&(this.process=null,this.runPhase=null,this.handleProcessClose(i,a))}),s.on("error",i=>{if(this.process!==s)return;this.process=null,this.runPhase=null;const u=i.code==="ENOENT";this.emitErrorIfOpen({state:"error",message:u?"WorkBuddy was not found. Install WorkBuddy Desktop or the CodeBuddy CLI, then retry.":d(i.message)})})}handleStreamEvent(t){if(t.type==="system"&&t.subtype==="init"&&t.session_id){this.agentSessionId=t.session_id,this.runPhase="thinking",this.emitEvent({state:"start",agentSessionId:t.session_id});return}if(t.type==="control_request"&&t.request?.subtype==="can_use_tool"){this.runPhase="waiting_approval",this.emitEvent({state:"approval-pending",name:t.request.tool_name,args:t.request.input,approval:{title:`WorkBuddy \u8BF7\u6C42\u4F7F\u7528 ${t.request.tool_name||"\u5DE5\u5177"}`,source:"workbuddy",actionHint:"\u8BF7\u5728 WorkBuddy \u6216\u795E\u5FF5\u4E2D\u786E\u8BA4\u540E\u7EE7\u7EED\u3002"}});return}if(t.type==="assistant"){const s=t.message?.content;if(s?.length)for(const o of s)this.handleContentBlock(o);else t.text&&this.emitText(t.text,!!t.thinking);return}if(t.type!=="result")return;if(t.subtype==="tool_result"){this.runPhase="tool_running",this.emitEvent({state:"tool-result",name:t.name,result:g(t.content)});return}if(t.subtype==="error"||t.error){this.emitErrorIfOpen({state:"error",message:d(t.error||t.result||"WorkBuddy failed.")});return}!this.hasEmittedText&&t.result&&this.emitText(t.result,!1),t.session_id&&(this.agentSessionId=t.session_id);const e=t.usage??t.message?.usage;this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0,usage:e?{inputTokens:e.input_tokens??0,outputTokens:e.output_tokens??0}:void 0})}handleContentBlock(t){t.type==="text"&&t.text?this.emitText(t.text,!1):t.type==="thinking"&&t.thinking?this.emitText(t.thinking,!0):t.type==="tool_use"?(this.runPhase="tool_running",this.emitEvent({state:"tool-call",name:t.name,args:t.input})):t.type==="tool_result"&&this.emitEvent({state:"tool-result",name:t.name,result:g(t.content)})}emitText(t,e){this.runPhase=e?"thinking":"streaming_text";const s=!e&&this.hasEmittedText?`
1
+ import{spawnSync as w}from"node:child_process";import{createInterface as k}from"node:readline";import{randomUUID as I}from"node:crypto";import S from"node:path";import{AgentAdapter as x,registerAgent as _}from"./adapter.js";import{resolveBuiltinCommand as E,spawnAgentCommand as B}from"./command-spec.js";import{buildAgentProcessEnv as P}from"../agent-env.js";import{buildPlatformInstructions as T,ensurePlatformInstructionsFile as W}from"./platform-instructions.js";import{ensureWorkBuddyRoomPluginBundle as C}from"../integrations/workbuddy-plugin-bundle.js";import{roomMcpHostToolName as A}from"../integrations/room-plugin-shared.js";import{resolveWindowsSystemRoot as R}from"../windows-shell.js";const D=new Set(["minimal","low","medium","high","xhigh","max"]);function O(s){const t=s?.trim();return t&&t!=="auto"?t:void 0}function q(s){const t=s?.trim();if(t){if(D.has(t))return t;throw new Error(`Unsupported WorkBuddy reasoning effort "${t}". Supported values: minimal, low, medium, high, xhigh, max.`)}}function $(s,t,e){if(!s)return[];if(t==="win32"){if(!e)throw new Error("WorkBuddy system prompt file is required on Windows.");return["--system-prompt-file",e]}return["--append-system-prompt",s]}function F(s){const t=s.split(/\n\n(?=<[^>\n]+>\n)/);return(t[t.length-1]??s).replace(/^\[群消息\][ \t]+<[^>\n]+>\n/,"").replace(/^\[群消息\]\n?/,"").replace(/^<[^>\n]+>\n/,"").trim()}function f(s,t=process.platform,e=N){t==="win32"&&s.pid&&e(s.pid)||s.kill("SIGTERM")}function N(s){const t=S.win32.join(R(),"System32","taskkill.exe");return w(t,["/pid",String(s),"/T","/F"],{stdio:"ignore",windowsHide:!0,timeout:5e3}).status===0}class z extends x{type="workbuddy";process=null;agentSessionId=null;workDir=null;seq=0;runId="";terminalState="open";hasEmittedText=!1;runPhase=null;externalChannel=null;shennianSessionId=null;extraEnv={};configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,n){this.workDir=e,this.seq=0,n&&(this.agentSessionId=n)}async send(t,e,n,o,a,r){await this.killProcess(),this.runId=I(),this.resetRunState();const u=r?.source==="room_activation",i=["-p",u?F(t):t,"--output-format","stream-json","--verbose","--permission-mode",u?"dontAsk":"auto","--setting-sources","user,project,local"],h=O(e);h&&i.push("--model",h);const m=C(),l=A("workbuddy");u?i.push("--allowedTools",l,"--tools",`NoDefer(${l})`,"--mcp-config",m.mcpFile,"--strict-mcp-config","--disallowedTools","mcp__shennian_room__shennian_agent","--max-turns","2"):i.push("--allowedTools",l,"--tools",`*,NoDefer(${l})`),i.push("--plugin-dir",m.pluginRoot);const p=this.shennianSessionId?.startsWith("room-managed-")&&!this.agentSessionId&&!u?null:T(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,a);if(p){const y=process.platform==="win32"?W(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,a):void 0;i.push(...$(p,process.platform,y))}const c=q(n);c&&i.push("--effort",c),this.agentSessionId&&i.push("--resume",this.agentSessionId),this.spawnAndParse(i)}async resume(t){await this.killProcess(),this.agentSessionId=t,this.resetRunState()}async stop(){await this.killProcess()}async getStatus(){return{active:this.process!=null&&this.terminalState==="open",runId:this.runId||null,runPhase:this.runPhase,canStop:this.process!=null&&this.terminalState==="open"}}spawnAndParse(t){const e=E("workbuddy");if(!e){this.emit("error",new Error("WorkBuddy was not found. Install WorkBuddy Desktop or the CodeBuddy CLI, then retry."));return}const n=B(e,t,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:P(this.extraEnv)});this.process=n,k({input:n.stdout}).on("line",r=>{if(r.trim())try{this.handleStreamEvent(JSON.parse(r))}catch{}});let a="";n.stderr?.on("data",r=>{a=`${a}${r.toString()}`.slice(-8e3)}),n.on("close",r=>{this.process===n&&(this.process=null,this.runPhase=null,this.handleProcessClose(r,a))}),n.on("error",r=>{if(this.process!==n)return;this.process=null,this.runPhase=null;const u=r.code==="ENOENT";this.emitErrorIfOpen({state:"error",message:u?"WorkBuddy was not found. Install WorkBuddy Desktop or the CodeBuddy CLI, then retry.":d(r.message)})})}handleStreamEvent(t){if(t.type==="system"&&t.subtype==="init"&&t.session_id){this.agentSessionId=t.session_id,this.runPhase="thinking",this.emitEvent({state:"start",agentSessionId:t.session_id});return}if(t.type==="control_request"&&t.request?.subtype==="can_use_tool"){this.runPhase="waiting_approval",this.emitEvent({state:"approval-pending",name:t.request.tool_name,args:t.request.input,approval:{title:`WorkBuddy \u8BF7\u6C42\u4F7F\u7528 ${t.request.tool_name||"\u5DE5\u5177"}`,source:"workbuddy",actionHint:"\u8BF7\u5728 WorkBuddy \u6216\u795E\u5FF5\u4E2D\u786E\u8BA4\u540E\u7EE7\u7EED\u3002"}});return}if(t.type==="assistant"){const n=t.message?.content;if(n?.length)for(const o of n)this.handleContentBlock(o);else t.text&&this.emitText(t.text,!!t.thinking);return}if(t.type!=="result")return;if(t.subtype==="tool_result"){this.runPhase="tool_running",this.emitEvent({state:"tool-result",name:t.name,result:g(t.content)});return}if(t.subtype==="error"||t.error){this.emitErrorIfOpen({state:"error",message:d(t.error||t.result||"WorkBuddy failed.")});return}!this.hasEmittedText&&t.result&&this.emitText(t.result,!1),t.session_id&&(this.agentSessionId=t.session_id);const e=t.usage??t.message?.usage;this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0,usage:e?{inputTokens:e.input_tokens??0,outputTokens:e.output_tokens??0}:void 0})}handleContentBlock(t){t.type==="text"&&t.text?this.emitText(t.text,!1):t.type==="thinking"&&t.thinking?this.emitText(t.thinking,!0):t.type==="tool_use"?(this.runPhase="tool_running",this.emitEvent({state:"tool-call",name:t.name,args:t.input})):t.type==="tool_result"&&this.emitEvent({state:"tool-result",name:t.name,result:g(t.content)})}emitText(t,e){this.runPhase=e?"thinking":"streaming_text";const n=!e&&this.hasEmittedText?`
2
2
 
3
- `:"";this.emitEvent({state:"delta",text:s+t,thinking:e||void 0}),e||(this.hasEmittedText=!0)}handleProcessClose(t,e){if(t!==0&&t!==null){this.emitErrorIfOpen({state:"error",message:d(e)||`WorkBuddy exited with code ${t}.`});return}this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0})}emitFinalIfOpen(t){this.terminalState==="open"&&(this.terminalState="final",this.runPhase=null,this.emitEvent(t))}emitErrorIfOpen(t){this.terminalState==="open"&&(this.terminalState="error",this.runPhase=null,this.emitEvent(t))}emitEvent(t){this.emit("agentEvent",{...t,runId:this.runId,seq:this.seq++})}resetRunState(){this.seq=0,this.terminalState="open",this.hasEmittedText=!1,this.runPhase=null}async killProcess(){const t=this.process;t&&(this.process=null,this.runPhase=null,c(t),await new Promise(e=>{let s=!1;const o=()=>{s||(s=!0,e())};t.once("close",o),setTimeout(()=>{c(t),o()},3e3).unref?.()}))}}function g(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return"[unserializable WorkBuddy tool result]"}}function d(n){return n.replace(/(Authorization\s*:\s*)Bearer\s+[A-Za-z0-9._~+/-]+/gi,"$1Bearer [redacted]").replace(/(api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|connector[-_ ]?token)(\s*[:=]\s*)[^\s,;]+/gi,"$1$2[redacted]").trim().slice(0,2e3)}_("workbuddy",()=>new N);export{N as WorkBuddyAdapter,R as normalizeWorkBuddyModelId,q as normalizeWorkBuddyReasoningEffort,d as sanitizeWorkBuddyError,c as terminateWorkBuddyProcess,$ as workBuddySystemPromptArgs};
3
+ `:"";this.emitEvent({state:"delta",text:n+t,thinking:e||void 0}),e||(this.hasEmittedText=!0)}handleProcessClose(t,e){if(t!==0&&t!==null){this.emitErrorIfOpen({state:"error",message:d(e)||`WorkBuddy exited with code ${t}.`});return}this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0})}emitFinalIfOpen(t){this.terminalState==="open"&&(this.terminalState="final",this.runPhase=null,this.emitEvent(t))}emitErrorIfOpen(t){this.terminalState==="open"&&(this.terminalState="error",this.runPhase=null,this.emitEvent(t))}emitEvent(t){this.emit("agentEvent",{...t,runId:this.runId,seq:this.seq++})}resetRunState(){this.seq=0,this.terminalState="open",this.hasEmittedText=!1,this.runPhase=null}async killProcess(){const t=this.process;t&&(this.process=null,this.runPhase=null,f(t),await new Promise(e=>{let n=!1;const o=()=>{n||(n=!0,e())};t.once("close",o),setTimeout(()=>{f(t),o()},3e3).unref?.()}))}}function g(s){if(typeof s=="string")return s;try{return JSON.stringify(s)}catch{return"[unserializable WorkBuddy tool result]"}}function d(s){return s.replace(/(Authorization\s*:\s*)Bearer\s+[A-Za-z0-9._~+/-]+/gi,"$1Bearer [redacted]").replace(/(api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|connector[-_ ]?token)(\s*[:=]\s*)[^\s,;]+/gi,"$1$2[redacted]").trim().slice(0,2e3)}_("workbuddy",()=>new z);export{z as WorkBuddyAdapter,O as normalizeWorkBuddyModelId,q as normalizeWorkBuddyReasoningEffort,d as sanitizeWorkBuddyError,f as terminateWorkBuddyProcess,F as workBuddyRoomActivationText,$ as workBuddySystemPromptArgs};
@@ -1 +1 @@
1
- import h from"node:crypto";import{getRegisteredAgents as f,unregisterAgent as p}from"../agents/adapter.js";import{loadConfig as w}from"../config/index.js";import{handleUpgradeStart as b,handleUpgradeStatus as v}from"../commands/upgrade.js";import{handleAgentsRefresh as R,handleModelsRefresh as y}from"./handlers/agents.js";import{handleAgentCapabilitiesList as k}from"./handlers/agent-capabilities.js";import{handleAgentConfigClear as S,handleAgentConfigGet as I,handleAgentConfigTest as A,handleAgentConfigUpsert as T}from"./handlers/agent-config.js";import{handleChatAbort as u,handleChatSend as c,sendSessionUpdateEvent as P}from"./handlers/chat.js";import{handleSessionRefresh as M}from"./handlers/session-refresh.js";import{handleSessionToolDetail as _}from"./handlers/tool-detail.js";import{handleSessionTitleSet as C}from"./handlers/title.js";import{cleanupPendingTransfers as F,handleFsLs as x,handleFsRead as D,handleFsRename as E,handleFsWrite as O,handleFsTransfer as Q,handleFsTransferAbort as j,handleFsTransferChunk as U,handleFsTransferFinish as z,handleFsTransferStart as $,handleFsExportMarkdownPdf as V,handleFsExportMarkdownPdfSetup as B,handleFsArchiveZip as W}from"./handlers/fs.js";import{handleRegionProbe as L,handleRegionSwitch as G,handleUpgradeSetPolicy as K}from"./handlers/control.js";import{ManagerRuntimeService as N,setManagerRuntimeService as m}from"../manager/runtime.js";import{ChatQueueManager as H}from"./queue.js";import{createAuthorizedFsRoot as X,resolveAuthorizedPath as Z,resolveSessionWorkDir as J}from"../fs/boundary.js";import"../agents/claude.js";import"../agents/codex.js";import"../agents/workbuddy.js";import"../agents/gemini.js";import"../agents/cursor.js";import"../agents/opencode.js";import"../agents/manager.js";import{registerCustomAgent as Y}from"../agents/custom.js";import{handleManagedRoomBind as q,handleManagedRoomRestart as ee}from"./handlers/room-managed.js";import{listSessionRecords as d}from"./store.js";const te=50;import{resolveSessionWorkDir as xe}from"../fs/boundary.js";class _e{client;nativeFusion;cliVersion;upgradePolicyController;managedRoomBinder;sessions=new Map;processedReqIds=new Set;runTextAcc=new Map;pendingTransfers=new Map;managerRuntime;chatQueue;activityProbeTimer=null;activeRequests=0;constructor(e,t=null,s,n=null,a=null){this.client=e,this.nativeFusion=t,this.cliVersion=s,this.upgradePolicyController=n,this.managedRoomBinder=a,this.managerRuntime=new N({getRuntime:()=>this.getRuntime(),dispatchReq:i=>this.handleReq(i)}),this.chatQueue=new H({getRuntime:()=>this.getRuntime(),dispatchReq:i=>this.handleReq(i)}),m(this.managerRuntime),this.managerRuntime.start(),this.reloadCustomAgents(),this.activityProbeTimer=setInterval(()=>{this.publishManagedActivitySnapshots().catch(i=>{console.error("[session.activity] managed probe failed",i)})},15e3),this.activityProbeTimer.unref?.()}getRuntime(){return{client:this.client,pendingTransfers:this.pendingTransfers,processedReqIds:this.processedReqIds,reloadCustomAgents:()=>this.reloadCustomAgents(),resolvePath:e=>this.resolvePath(e),resolveAuthorizedPath:(e,t)=>this.resolveAuthorizedPath(e,t),runTextAcc:this.runTextAcc,sessions:this.sessions,evictIdleSessions:()=>this.evictIdleSessions(),nativeFusion:this.nativeFusion,managerRuntime:this.managerRuntime,chatQueue:this.chatQueue,activityPublisher:{publish:(e,t)=>this.publishSessionActivity(e,t)},upgradePolicyController:this.upgradePolicyController}}getUpgradeIdleState(){const e=[];return[...this.sessions.values()].some(t=>t.currentRunId!==null)&&e.push("active-agent-turn"),this.pendingTransfers.size>0&&e.push("file-transfer"),this.activeRequests>0&&e.push("active-daemon-request"),{idle:e.length===0,reasons:e}}async createManagedRoomSession(e){const t=h.createHash("sha256").update(e.creationKey,"utf8").digest("hex"),s=`room-managed-${t.slice(0,48)}`,n=d().find(r=>r.sessionId===s);if(n&&(n.agentType!==e.agentType||n.workDir!==e.workDir))throw Object.assign(new Error("Managed Room Session identity conflicts with local state."),{code:"managed_room_session_conflict"});if(n?.agentSessionId)return{nianSessionId:s};const a={value:null},i=new Proxy(this.client,{get:(r,l)=>{if(l==="sendRes")return g=>{a.value=g};const o=Reflect.get(r,l,r);return typeof o=="function"?o.bind(r):o}});if(await c({...this.getRuntime(),client:i},{type:"req",id:`managed-create-${t.slice(0,32)}`,method:"chat.send",params:{sessionId:s,text:e.initialMessage,agentType:e.agentType,workDir:e.workDir,modelId:e.modelId??void 0,clientMessageId:`managed-bootstrap-${t.slice(0,32)}`,waitForDispatch:!0}}),a.value?.ok!==!0)throw Object.assign(new Error(a.value?.error||"Managed Agent failed to start."),{code:"managed_agent_start_failed"});return{nianSessionId:s}}async waitForManagedNativeSession(e){const t=Date.now();for(;Date.now()-t<e.timeoutMs;){const s=this.sessions.get(e.nianSessionId);if(s&&s.agentType!==e.agentType)throw Object.assign(new Error("Managed Agent runtime does not match the created session."),{code:"managed_room_session_conflict"});const n=d().find(i=>i.sessionId===e.nianSessionId),a=s?.agentSessionId??n?.agentSessionId;if(a)return{sourceSessionKey:a};await new Promise(i=>setTimeout(i,100))}throw Object.assign(new Error("Timed out waiting for the exact native Agent Session."),{code:"native_session_timeout"})}publishManagedRoomSession(e){const t=d().find(s=>s.sessionId===e.nianSessionId);if(!t?.agentSessionId||t.agentType!==e.agentType)throw Object.assign(new Error("Managed Agent Session is unavailable for publication."),{code:"managed_room_session_unavailable"});if(this.client.getState()!=="connected")throw Object.assign(new Error("Shennian Relay is disconnected."),{code:"managed_room_relay_disconnected"});P(this.getRuntime(),{sessionId:t.sessionId,agentType:t.agentType,workDir:t.workDir,agentSessionId:t.agentSessionId,modelId:t.modelId??void 0})}async activateRoomSession(e){const t={value:null},s=new Proxy(this.client,{get:(n,a)=>{if(a==="sendRes")return r=>{t.value=r};const i=Reflect.get(n,a,n);return typeof i=="function"?i.bind(n):i}});return await c({...this.getRuntime(),client:s},{type:"req",id:e.clientMessageId,method:"chat.send",params:{...e,waitForDispatch:!0,suppressExternalOwnerEcho:!0}},{source:"room_activation"}),{externalOwnerQueued:t.value?.ok===!0&&t.value.payload?.deliveryMode==="external_owner_queue"}}async abortRoomSession(e){const t=new Proxy(this.client,{get:(s,n)=>{if(n==="sendRes")return()=>{};const a=Reflect.get(s,n,s);return typeof a=="function"?a.bind(s):a}});await u({...this.getRuntime(),client:t},{type:"req",id:`room-activation-abort-${h.randomUUID()}`,method:"chat.abort",params:{sessionId:e.sessionId}})}publishSessionActivity(e,t){this.client.sendEvent({type:"event",event:"session.activity",payload:{sessionId:e,activity:t}})}async publishManagedActivitySnapshots(){for(const[e,t]of this.sessions.entries()){if(t.heartbeatTimer||!t.currentRunId||!t.adapter.getStatus)continue;const s=await t.adapter.getStatus().catch(()=>null);if(!s?.active||!s.runPhase)continue;const n=new Date().toISOString();this.publishSessionActivity(e,{sessionId:e,runId:s.runId||t.currentRunId,runPhase:s.runPhase,startedAt:new Date(t.lastActiveAt).toISOString(),updatedAt:n,canStop:s.canStop??!0});const a=t.heartbeatSeq++;this.client.sendAgentEvent({type:"event",event:"agent",payload:{state:"heartbeat",sessionId:e,runId:s.runId||t.currentRunId,seq:a,runPhase:s.runPhase,canStop:s.canStop??!0},seq:a,id:`agent-status-${s.runId||t.currentRunId}-${Date.now()}`})}}reloadCustomAgents(){for(const t of f())t.startsWith("custom:")&&p(t);const e=w();for(const[t,s]of Object.entries(e.customAgents??{}))Y(t,s)}async handleReq(e){const t=this.getRuntime();this.activeRequests++;try{switch(e.method){case"chat.send":await c(t,e);break;case"chat.enqueue":await this.chatQueue.handleEnqueue(e);break;case"chat.queue.get":await this.chatQueue.handleGet(e);break;case"chat.queue.edit":await this.chatQueue.handleEdit(e);break;case"chat.queue.delete":await this.chatQueue.handleDelete(e);break;case"chat.abort":await u(t,e);break;case"session.refresh":await M(t,e);break;case"session.tool.detail":await _(t,e);break;case"session.title.set":await C(t,e);break;case"room.agent.bind-managed":await q(t,this.managedRoomBinder,e);break;case"room.agent.restart-managed":await ee(t,this.managedRoomBinder,e);break;case"fs.ls":await x(t,e);break;case"fs.read":await D(t,e);break;case"fs.write":await O(t,e);break;case"fs.export.markdown-pdf":await V(t,e);break;case"fs.export.markdown-pdf.setup":await B(t,e);break;case"fs.archive.zip":await W(t,e);break;case"fs.rename":await E(t,e);break;case"fs.transfer":await Q(t,e);break;case"fs.transfer.start":await $(t,e);break;case"fs.transfer.chunk":await U(t,e);break;case"fs.transfer.finish":await z(t,e);break;case"fs.transfer.abort":await j(t,e);break;case"region.probe":await L(t,e);break;case"region.switch":await G(t,e);break;case"upgrade.start":await b(this.client,e.id,e.params.version,{currentVersion:this.cliVersion,confirmedMajor:e.params.confirmedMajor===!0});break;case"upgrade.status":await v(this.client,e.id,{currentVersion:this.cliVersion});break;case"upgrade.set-policy":await K(t,e);break;case"agents.refresh":await R(t,e);break;case"models.refresh":await y(t,e);break;case"agent.config.get":await I(t,e);break;case"agent.config.upsert":await T(t,e);break;case"agent.config.clear":await S(t,e);break;case"agent.config.test":await A(t,e);break;case"agent.capabilities.list":await k(t,e);break;case"skill.list":case"skill.install":case"skill.doctor":case"skill.setup":case"skill.use":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;case"session.wechat-rpa.channel.get":case"session.wechat-rpa.channel.upsert":case"session.wechat-rpa.channel.sync":case"manager.wechat-rpa.channel.get":case"manager.wechat-rpa.channel.upsert":case"manager.wechat-rpa.channel.sync":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;default:this.client.sendRes({type:"res",id:e.id,ok:!1,error:`Unknown method: ${e.method}`})}}catch(s){this.client.sendRes({type:"res",id:e.id,ok:!1,error:s instanceof Error?s.message:String(s)})}finally{this.activeRequests--}}evictIdleSessions(){if(this.sessions.size<te)return;let e=null;for(const[t,s]of this.sessions)(!e||s.lastActiveAt<e.session.lastActiveAt)&&(e={key:t,session:s});e&&(e.session.heartbeatTimer&&(clearInterval(e.session.heartbeatTimer),e.session.heartbeatTimer=null),e.session.adapter.removeAllListeners(),e.session.adapter.stop().catch(()=>{}),this.sessions.delete(e.key))}resolvePath(e){return J(e)}resolveAuthorizedPath(e,t){return Z(e,X(t))}async cleanup(){this.activityProbeTimer&&(clearInterval(this.activityProbeTimer),this.activityProbeTimer=null);for(const[,e]of this.sessions)e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null),await e.adapter.stop().catch(()=>{});this.sessions.clear(),this.runTextAcc.clear(),F(this.getRuntime()),await this.managerRuntime.stop(),m(null)}}export{_e as SessionManager,xe as resolveSessionWorkDir};
1
+ import h from"node:crypto";import{getRegisteredAgents as f,unregisterAgent as p}from"../agents/adapter.js";import{loadConfig as w}from"../config/index.js";import{handleUpgradeStart as b,handleUpgradeStatus as v}from"../commands/upgrade.js";import{handleAgentsRefresh as R,handleModelsRefresh as y}from"./handlers/agents.js";import{handleAgentCapabilitiesList as k}from"./handlers/agent-capabilities.js";import{handleAgentConfigClear as S,handleAgentConfigGet as I,handleAgentConfigTest as A,handleAgentConfigUpsert as T}from"./handlers/agent-config.js";import{handleChatAbort as u,handleChatSend as l,sendSessionUpdateEvent as P}from"./handlers/chat.js";import{handleSessionRefresh as M}from"./handlers/session-refresh.js";import{handleSessionToolDetail as _}from"./handlers/tool-detail.js";import{handleSessionTitleSet as C}from"./handlers/title.js";import{cleanupPendingTransfers as F,handleFsLs as x,handleFsRead as D,handleFsRename as E,handleFsWrite as O,handleFsTransfer as Q,handleFsTransferAbort as j,handleFsTransferChunk as U,handleFsTransferFinish as z,handleFsTransferStart as $,handleFsExportMarkdownPdf as V,handleFsExportMarkdownPdfSetup as B,handleFsArchiveZip as W}from"./handlers/fs.js";import{handleRegionProbe as L,handleRegionSwitch as G,handleUpgradeSetPolicy as K}from"./handlers/control.js";import{ManagerRuntimeService as N,setManagerRuntimeService as m}from"../manager/runtime.js";import{ChatQueueManager as H}from"./queue.js";import{createAuthorizedFsRoot as X,resolveAuthorizedPath as Z,resolveSessionWorkDir as J}from"../fs/boundary.js";import"../agents/claude.js";import"../agents/codex.js";import"../agents/workbuddy.js";import"../agents/gemini.js";import"../agents/cursor.js";import"../agents/opencode.js";import"../agents/manager.js";import{registerCustomAgent as Y}from"../agents/custom.js";import{handleManagedRoomBind as q,handleManagedRoomRestart as ee}from"./handlers/room-managed.js";import{listSessionRecords as d}from"./store.js";const te=50;import{resolveSessionWorkDir as xe}from"../fs/boundary.js";class _e{client;nativeFusion;cliVersion;upgradePolicyController;managedRoomBinder;sessions=new Map;processedReqIds=new Set;runTextAcc=new Map;pendingTransfers=new Map;managerRuntime;chatQueue;activityProbeTimer=null;activeRequests=0;constructor(e,t=null,s,a=null,n=null){this.client=e,this.nativeFusion=t,this.cliVersion=s,this.upgradePolicyController=a,this.managedRoomBinder=n,this.managerRuntime=new N({getRuntime:()=>this.getRuntime(),dispatchReq:i=>this.handleReq(i)}),this.chatQueue=new H({getRuntime:()=>this.getRuntime(),dispatchReq:i=>this.handleReq(i)}),m(this.managerRuntime),this.managerRuntime.start(),this.reloadCustomAgents(),this.activityProbeTimer=setInterval(()=>{this.publishManagedActivitySnapshots().catch(i=>{console.error("[session.activity] managed probe failed",i)})},15e3),this.activityProbeTimer.unref?.()}getRuntime(){return{client:this.client,pendingTransfers:this.pendingTransfers,processedReqIds:this.processedReqIds,reloadCustomAgents:()=>this.reloadCustomAgents(),resolvePath:e=>this.resolvePath(e),resolveAuthorizedPath:(e,t)=>this.resolveAuthorizedPath(e,t),runTextAcc:this.runTextAcc,sessions:this.sessions,evictIdleSessions:()=>this.evictIdleSessions(),nativeFusion:this.nativeFusion,managerRuntime:this.managerRuntime,chatQueue:this.chatQueue,activityPublisher:{publish:(e,t)=>this.publishSessionActivity(e,t)},upgradePolicyController:this.upgradePolicyController}}getUpgradeIdleState(){const e=[];return[...this.sessions.values()].some(t=>t.currentRunId!==null)&&e.push("active-agent-turn"),this.pendingTransfers.size>0&&e.push("file-transfer"),this.activeRequests>0&&e.push("active-daemon-request"),{idle:e.length===0,reasons:e}}async createManagedRoomSession(e){const t=h.createHash("sha256").update(e.creationKey,"utf8").digest("hex"),s=`room-managed-${t.slice(0,48)}`,a=d().find(r=>r.sessionId===s);if(a&&(a.agentType!==e.agentType||a.workDir!==e.workDir))throw Object.assign(new Error("Managed Room Session identity conflicts with local state."),{code:"managed_room_session_conflict"});if(a?.agentSessionId)return{nianSessionId:s};const n={value:null},i=new Proxy(this.client,{get:(r,o)=>{if(o==="sendRes")return g=>{n.value=g};const c=Reflect.get(r,o,r);return typeof c=="function"?c.bind(r):c}});if(await l({...this.getRuntime(),client:i},{type:"req",id:`managed-create-${t.slice(0,32)}`,method:"chat.send",params:{sessionId:s,text:e.initialMessage,agentType:e.agentType,workDir:e.workDir,modelId:e.modelId??void 0,clientMessageId:`managed-bootstrap-${t.slice(0,32)}`,waitForDispatch:!0}}),n.value?.ok!==!0)throw Object.assign(new Error(n.value?.error||"Managed Agent failed to start."),{code:"managed_agent_start_failed"});return{nianSessionId:s}}async waitForManagedNativeSession(e){const t=Date.now();for(;Date.now()-t<e.timeoutMs;){const s=this.sessions.get(e.nianSessionId);if(s&&s.agentType!==e.agentType)throw Object.assign(new Error("Managed Agent runtime does not match the created session."),{code:"managed_room_session_conflict"});const a=d().find(i=>i.sessionId===e.nianSessionId),n=s?.agentSessionId??a?.agentSessionId;if(n)return{sourceSessionKey:n};await new Promise(i=>setTimeout(i,100))}throw Object.assign(new Error("Timed out waiting for the exact native Agent Session."),{code:"native_session_timeout"})}publishManagedRoomSession(e){const t=d().find(s=>s.sessionId===e.nianSessionId);if(!t?.agentSessionId||t.agentType!==e.agentType)throw Object.assign(new Error("Managed Agent Session is unavailable for publication."),{code:"managed_room_session_unavailable"});if(this.client.getState()!=="connected")throw Object.assign(new Error("Shennian Relay is disconnected."),{code:"managed_room_relay_disconnected"});P(this.getRuntime(),{sessionId:t.sessionId,agentType:t.agentType,workDir:t.workDir,agentSessionId:t.agentSessionId,modelId:t.modelId??void 0})}async activateRoomSession(e){const t=d().find(i=>i.sessionId===e.sessionId),s=t?.agentType===e.agentType?t.modelId??void 0:void 0,a={value:null},n=new Proxy(this.client,{get:(i,r)=>{if(r==="sendRes")return c=>{a.value=c};const o=Reflect.get(i,r,i);return typeof o=="function"?o.bind(i):o}});return await l({...this.getRuntime(),client:n},{type:"req",id:e.clientMessageId,method:"chat.send",params:{...e,modelId:s,waitForDispatch:!0,suppressExternalOwnerEcho:!0}},{source:"room_activation"}),{externalOwnerQueued:a.value?.ok===!0&&a.value.payload?.deliveryMode==="external_owner_queue"}}async abortRoomSession(e){const t=new Proxy(this.client,{get:(s,a)=>{if(a==="sendRes")return()=>{};const n=Reflect.get(s,a,s);return typeof n=="function"?n.bind(s):n}});await u({...this.getRuntime(),client:t},{type:"req",id:`room-activation-abort-${h.randomUUID()}`,method:"chat.abort",params:{sessionId:e.sessionId}})}publishSessionActivity(e,t){this.client.sendEvent({type:"event",event:"session.activity",payload:{sessionId:e,activity:t}})}async publishManagedActivitySnapshots(){for(const[e,t]of this.sessions.entries()){if(t.heartbeatTimer||!t.currentRunId||!t.adapter.getStatus)continue;const s=await t.adapter.getStatus().catch(()=>null);if(!s?.active||!s.runPhase)continue;const a=new Date().toISOString();this.publishSessionActivity(e,{sessionId:e,runId:s.runId||t.currentRunId,runPhase:s.runPhase,startedAt:new Date(t.lastActiveAt).toISOString(),updatedAt:a,canStop:s.canStop??!0});const n=t.heartbeatSeq++;this.client.sendAgentEvent({type:"event",event:"agent",payload:{state:"heartbeat",sessionId:e,runId:s.runId||t.currentRunId,seq:n,runPhase:s.runPhase,canStop:s.canStop??!0},seq:n,id:`agent-status-${s.runId||t.currentRunId}-${Date.now()}`})}}reloadCustomAgents(){for(const t of f())t.startsWith("custom:")&&p(t);const e=w();for(const[t,s]of Object.entries(e.customAgents??{}))Y(t,s)}async handleReq(e){const t=this.getRuntime();this.activeRequests++;try{switch(e.method){case"chat.send":await l(t,e);break;case"chat.enqueue":await this.chatQueue.handleEnqueue(e);break;case"chat.queue.get":await this.chatQueue.handleGet(e);break;case"chat.queue.edit":await this.chatQueue.handleEdit(e);break;case"chat.queue.delete":await this.chatQueue.handleDelete(e);break;case"chat.abort":await u(t,e);break;case"session.refresh":await M(t,e);break;case"session.tool.detail":await _(t,e);break;case"session.title.set":await C(t,e);break;case"room.agent.bind-managed":await q(t,this.managedRoomBinder,e);break;case"room.agent.restart-managed":await ee(t,this.managedRoomBinder,e);break;case"fs.ls":await x(t,e);break;case"fs.read":await D(t,e);break;case"fs.write":await O(t,e);break;case"fs.export.markdown-pdf":await V(t,e);break;case"fs.export.markdown-pdf.setup":await B(t,e);break;case"fs.archive.zip":await W(t,e);break;case"fs.rename":await E(t,e);break;case"fs.transfer":await Q(t,e);break;case"fs.transfer.start":await $(t,e);break;case"fs.transfer.chunk":await U(t,e);break;case"fs.transfer.finish":await z(t,e);break;case"fs.transfer.abort":await j(t,e);break;case"region.probe":await L(t,e);break;case"region.switch":await G(t,e);break;case"upgrade.start":await b(this.client,e.id,e.params.version,{currentVersion:this.cliVersion,confirmedMajor:e.params.confirmedMajor===!0});break;case"upgrade.status":await v(this.client,e.id,{currentVersion:this.cliVersion});break;case"upgrade.set-policy":await K(t,e);break;case"agents.refresh":await R(t,e);break;case"models.refresh":await y(t,e);break;case"agent.config.get":await I(t,e);break;case"agent.config.upsert":await T(t,e);break;case"agent.config.clear":await S(t,e);break;case"agent.config.test":await A(t,e);break;case"agent.capabilities.list":await k(t,e);break;case"skill.list":case"skill.install":case"skill.doctor":case"skill.setup":case"skill.use":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;case"session.wechat-rpa.channel.get":case"session.wechat-rpa.channel.upsert":case"session.wechat-rpa.channel.sync":case"manager.wechat-rpa.channel.get":case"manager.wechat-rpa.channel.upsert":case"manager.wechat-rpa.channel.sync":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;default:this.client.sendRes({type:"res",id:e.id,ok:!1,error:`Unknown method: ${e.method}`})}}catch(s){this.client.sendRes({type:"res",id:e.id,ok:!1,error:s instanceof Error?s.message:String(s)})}finally{this.activeRequests--}}evictIdleSessions(){if(this.sessions.size<te)return;let e=null;for(const[t,s]of this.sessions)(!e||s.lastActiveAt<e.session.lastActiveAt)&&(e={key:t,session:s});e&&(e.session.heartbeatTimer&&(clearInterval(e.session.heartbeatTimer),e.session.heartbeatTimer=null),e.session.adapter.removeAllListeners(),e.session.adapter.stop().catch(()=>{}),this.sessions.delete(e.key))}resolvePath(e){return J(e)}resolveAuthorizedPath(e,t){return Z(e,X(t))}async cleanup(){this.activityProbeTimer&&(clearInterval(this.activityProbeTimer),this.activityProbeTimer=null);for(const[,e]of this.sessions)e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null),await e.adapter.stop().catch(()=>{});this.sessions.clear(),this.runTextAcc.clear(),F(this.getRuntime()),await this.managerRuntime.stop(),m(null)}}export{_e as SessionManager,xe as resolveSessionWorkDir};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shennian",
3
- "version": "0.3.31",
3
+ "version": "0.3.33",
4
4
  "description": "Shennian — AI Agent Control Plane CLI",
5
5
  "type": "module",
6
6
  "bin": {