shennian 0.5.16 → 0.5.17

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.
@@ -1091,8 +1091,8 @@
1091
1091
  },
1092
1092
  {
1093
1093
  "file": "src/session/handlers/chat-events.js",
1094
- "beforeBytes": 20196,
1095
- "afterBytes": 8099
1094
+ "beforeBytes": 20267,
1095
+ "afterBytes": 8130
1096
1096
  },
1097
1097
  {
1098
1098
  "file": "src/session/handlers/chat-recovery.js",
@@ -1146,8 +1146,8 @@
1146
1146
  },
1147
1147
  {
1148
1148
  "file": "src/session/handlers/steward.js",
1149
- "beforeBytes": 7468,
1150
- "afterBytes": 3596
1149
+ "beforeBytes": 8421,
1150
+ "afterBytes": 3939
1151
1151
  },
1152
1152
  {
1153
1153
  "file": "src/session/handlers/title.js",
@@ -1316,8 +1316,8 @@
1316
1316
  },
1317
1317
  {
1318
1318
  "file": "src/steward/failover.js",
1319
- "beforeBytes": 3819,
1320
- "afterBytes": 2378
1319
+ "beforeBytes": 4394,
1320
+ "afterBytes": 2607
1321
1321
  },
1322
1322
  {
1323
1323
  "file": "src/steward/session.js",
@@ -1,2 +1,2 @@
1
- import{buildApprovalPendingPayload as M}from"@shennian/wire";import{createHash as R}from"node:crypto";import{AgentEventTerminalGate as D}from"../../agents/event-terminal-gate.js";import{recordAcpAgentModels as k}from"../../agents/model-registry.js";import{reportLog as _}from"../../log-reporter.js";import{registerInternalNativeSource as P}from"../../native-fusion/source-visibility.js";import{requestSessionIndexPublish as c}from"../index-publisher.js";import{noteRunActivity as j}from"../run-stall.js";import{appendMessage as s,recordSession as I,upsertMessage as O}from"../store.js";import{writeToolDetail as C}from"../tool-detail-store.js";import{refreshMachineAgents as F}from"./agents.js";import{roomReplyFailureNotice as N}from"../room-reply-notice.js";import{commitStewardFallback as S,tryStewardFailover as B}from"./steward.js";import{resetStewardChain as H}from"../../steward/failover.js";function J(a){const r=a.indexOf(`
2
- `),o=r>0?Math.min(r,80):Math.min(a.length,80);return a.slice(0,o)}function A(a,r,o){return`${a}:${R("sha256").update(`${r}\0${o??""}`).digest("hex")}`}function L(a,r,o={}){if(a.state==="tool-call"||a.state==="tool-result"){const l={runId:a.runId,sourceSeq:a.seq};return{state:a.state,runId:a.runId,seq:a.seq,sessionId:r,detailRef:l,status:a.state==="tool-call"?"running":"completed",detailAvailable:!0,...a.durationMs!==void 0?{durationMs:a.durationMs}:{},...a.name?{name:a.name}:{},...a.source?{source:a.source}:{},...a.agentSessionId?{agentSessionId:a.agentSessionId}:{},...o}}return{...a,sessionId:r,...o}}const V=3e4;function Q(a){return a.state==="heartbeat"?a.runPhase??null:a.state==="tool-call"||a.state==="tool-result"?"tool_running":a.state==="approval-pending"?"waiting_approval":a.state==="delta"?a.thinking?"thinking":"streaming_text":a.state==="init"||a.state==="start"?"thinking":null}function w(a,r){return a!=="manager"?a:r==="claude"?"claude":"codex"}function y(a,r,o,l){if(l.state!=="error"){S(a,r,o,l);return}B(a,r,o,l).catch(()=>!1).then(g=>{g||S(a,r,o,l)})}function ot(a,r,o,l){let g=null;const E=new D;function x(t,n={}){a.client.sendAgentEvent({type:"event",event:"agent",payload:L(t,r,n),seq:t.seq,id:`agent-evt-${t.runId}-${t.seq}`})}o.startsWith("acp:")&&l.on("sessionOptions",()=>{try{const t=l.getSessionOptions?.().models??[];if(!k(o,t))return;const n=a.getAgentSnapshot?.();if(!n)return;a.client.sendEvent({type:"event",event:"machine.agents",payload:{agentList:n.map(e=>e.type),agents:n}})}catch{}});function $(t){t?.heartbeatTimer&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=null)}function b(t){if(!t.currentRunId||!t.currentRunPhase)return;const n=t.heartbeatSeq++;a.client.sendAgentEvent({type:"event",event:"agent",payload:{state:"heartbeat",sessionId:r,runId:t.currentRunId,seq:n,runPhase:t.currentRunPhase},seq:n,id:`agent-heartbeat-${t.currentRunId}-${n}-${Date.now()}`})}function T(t){!t||t.heartbeatTimer||(t.heartbeatTimer=setInterval(()=>{b(t)},V),t.heartbeatTimer.unref?.())}function f(t){const n=t?.pendingTextEvent;!t||!n||!n.text||(s(r,{id:`agent-${n.runId}-${n.seq}`,sessionId:r,role:"agent",ts:Date.now(),payload:n.text}),c(a.client),x({state:"delta",runId:n.runId,seq:n.seq,text:n.text,thinking:n.thinking||void 0}),t.sessionScope==="steward"&&(t.stewardLastText=n.text),t.pendingTextEvent=null)}l.on("agentEvent",t=>{if(!E.accept(t))return;let n=!1;t.errorCode==="acp_auth_required"&&F(a).catch(()=>{});const e=a.sessions.get(r),h=Q(t),u=t.state==="final"||t.state==="error"||t.state==="aborted";if(e&&j(r,e,u),e&&(e.nextEventSeq=t.seq+1,!u&&e.currentRunId!==t.runId&&e.sessionScope==="steward"&&(e.stewardSay={count:0},e.stewardLastText=""),u||(e.currentRunId=t.runId),!u&&h&&(e.currentRunPhase=h,T(e)),t.agentSessionId&&(e.agentSessionId=t.agentSessionId),e.journalRunId)){const i={agentSessionId:t.agentSessionId??e.agentSessionId,providerRunId:t.runId||null,lastObservedEventSeq:t.seq,...u?{}:{phase:h==="waiting_approval"?"waiting_approval":"running"}};a.runJournal?.update(r,e.journalRunId,i)}if(a.managerRuntime?.noteAgentEvent(r,t),t.state==="delta"&&t.thinking)return;t.state!=="delta"&&_({level:"info",sessionId:r,wsEvent:`agent.${t.state}`,wsDirection:"out",metadata:{runId:t.runId,seq:t.seq,agentType:o}});let p=!1;if(t.state==="tool-call"||t.state==="tool-result"){const i=t.toolCallId?`agent-tool-${R("sha256").update(`${t.runId}\0${t.toolCallId}`).digest("hex")}`:`agent-${t.runId}-${t.seq}`;C({sessionId:r,toolCallId:i,detailRevision:t.seq,ts:Date.now(),name:t.name??"tool",...t.args!==void 0?{args:t.args}:{},...t.result!==void 0?{result:t.result}:{},status:t.toolStatus??(t.state==="tool-call"?"running":"completed"),...t.durationMs!==void 0?{durationMs:t.durationMs}:{},detailRef:{runId:t.runId,sourceSeq:t.seq}}),(t.toolCallId?O:s)(r,{id:i,sessionId:r,role:"agent",ts:Date.now(),payload:JSON.stringify({v:1,type:t.state==="tool-call"?"tool_use":"tool_result",name:t.name,toolCallId:i,status:t.toolStatus??(t.state==="tool-call"?"running":"completed"),...t.durationMs!==void 0?{durationMs:t.durationMs}:{},detailRef:{runId:t.runId,sourceSeq:t.seq},detailRevision:t.seq,detailAvailable:!0,resultOmitted:t.state==="tool-result"})}),p=!0}else t.state==="approval-pending"?(s(r,{id:`agent-${t.runId||"run"}-${t.seq}`,sessionId:r,role:"agent",ts:Date.now(),payload:M({...t.approval,permission:t.permission})}),p=!0,e&&I({sessionId:r,agentType:o,workDir:e.workDir,agentSessionId:e.agentSessionId,attentionId:A("approval",t.runId,t.seq)})):(t.state==="error"||t.state==="aborted")&&t.message&&(s(r,{id:`agent-${t.runId||"run"}-${t.seq}`,sessionId:r,role:"agent",ts:Date.now(),payload:t.message}),p=!0);p&&c(a.client);const d=`${r}:${t.runId}`;if(t.state==="delta"&&!t.thinking&&t.text&&a.runTextAcc.set(d,(a.runTextAcc.get(d)??"")+t.text),t.agentSessionId&&t.agentSessionId!==g&&(e?.nativeSessionVisibility==="internal"&&P(r,w(o,t.source)??o,t.agentSessionId),g=t.agentSessionId,a.nativeFusion?.noteManagedSourceSession(r,w(o,t.source),t.agentSessionId),e&&I({sessionId:r,agentType:o,workDir:e.workDir,agentSessionId:t.agentSessionId}),a.client.sendEvent({type:"event",event:"session.update",payload:{session:{id:r,agentType:o,agentSessionId:t.agentSessionId}}})),t.state==="delta"){const i=t.text??"";if(!i)return;e?.pendingTextEvent&&e.pendingTextEvent.runId!==t.runId&&f(e),e&&!e.pendingTextEvent&&(e.pendingTextEvent={runId:t.runId,seq:t.seq,text:"",thinking:!1}),e?.pendingTextEvent&&(e.pendingTextEvent.text+=i,e.pendingTextEvent.seq=t.seq);return}let q={};if(t.state==="final"){f(e),e&&(S(a,r,e,t),H(r));const i=e?N(e):null;i&&(n=!0,s(r,{id:`room-reply-notice-${t.runId}`,sessionId:r,role:"agent",ts:Date.now(),payload:i}),c(a.client));const m=a.runTextAcc.get(d)??"";m&&(q={messageSummary:J(m)}),a.runTextAcc.delete(d)}else t.state==="error"||t.state==="aborted"?(f(e),e&&y(a,r,e,t),a.runTextAcc.delete(d)):(t.state==="tool-call"||t.state==="tool-result"||t.state==="approval-pending")&&f(e);u&&e?.currentRunId===t.runId&&(e.currentRunId=null,e.currentRunPhase=null,e.nextEventSeq=0,$(e),a.chatQueue?.noteTerminal(r),I({sessionId:r,agentType:o,workDir:e.workDir,agentSessionId:e.agentSessionId,status:t.state==="final"&&!n?"completed":"failed",attentionId:A("terminal",t.runId),lastActivityAt:new Date().toISOString()}),c(a.client),e.journalRunId&&(a.runJournal?.remove(r,e.journalRunId),a.recoveryBarrier?.end(r),e.journalRunId=null)),x(t,q)}),l.on("error",t=>{console.error(`[chat.send] adapter error sessionId=${r} agentType=${o}: ${t.message}`);const n=a.sessions.get(r);n&&y(a,r,n,{state:"error",runId:n.currentRunId??"",message:t.message}),n?.journalRunId&&(a.runJournal?.update(r,n.journalRunId,{phase:"terminal"}),a.runJournal?.remove(r,n.journalRunId),a.recoveryBarrier?.end(r),n.journalRunId=null),a.sessions.delete(r),a.chatQueue?.noteTerminal(r),a.chatQueue?.isDispatching?.(r)||(s(r,{id:`agent-error-${r}-${Date.now()}`,sessionId:r,role:"agent",ts:Date.now(),payload:t.message}),c(a.client)),a.client.sendEvent({type:"event",event:"agent",payload:{state:"error",sessionId:r,message:t.message,runId:"",seq:0}})})}export{ot as bindAdapterEvents,w as getNativeSourceAgentType};
1
+ import{buildApprovalPendingPayload as M}from"@shennian/wire";import{createHash as w}from"node:crypto";import{AgentEventTerminalGate as D}from"../../agents/event-terminal-gate.js";import{recordAcpAgentModels as k}from"../../agents/model-registry.js";import{reportLog as _}from"../../log-reporter.js";import{registerInternalNativeSource as P}from"../../native-fusion/source-visibility.js";import{requestSessionIndexPublish as c}from"../index-publisher.js";import{noteRunActivity as j}from"../run-stall.js";import{appendMessage as s,recordSession as I,upsertMessage as O}from"../store.js";import{writeToolDetail as C}from"../tool-detail-store.js";import{refreshMachineAgents as F}from"./agents.js";import{roomReplyFailureNotice as N}from"../room-reply-notice.js";import{commitStewardFallback as S,tryStewardFailover as B}from"./steward.js";import{clearStewardSwitched as H,resetStewardChain as J}from"../../steward/failover.js";function L(a){const r=a.indexOf(`
2
+ `),o=r>0?Math.min(r,80):Math.min(a.length,80);return a.slice(0,o)}function R(a,r,o){return`${a}:${w("sha256").update(`${r}\0${o??""}`).digest("hex")}`}function V(a,r,o={}){if(a.state==="tool-call"||a.state==="tool-result"){const l={runId:a.runId,sourceSeq:a.seq};return{state:a.state,runId:a.runId,seq:a.seq,sessionId:r,detailRef:l,status:a.state==="tool-call"?"running":"completed",detailAvailable:!0,...a.durationMs!==void 0?{durationMs:a.durationMs}:{},...a.name?{name:a.name}:{},...a.source?{source:a.source}:{},...a.agentSessionId?{agentSessionId:a.agentSessionId}:{},...o}}return{...a,sessionId:r,...o}}const Q=3e4;function G(a){return a.state==="heartbeat"?a.runPhase??null:a.state==="tool-call"||a.state==="tool-result"?"tool_running":a.state==="approval-pending"?"waiting_approval":a.state==="delta"?a.thinking?"thinking":"streaming_text":a.state==="init"||a.state==="start"?"thinking":null}function A(a,r){return a!=="manager"?a:r==="claude"?"claude":"codex"}function y(a,r,o,l){if(l.state!=="error"){S(a,r,o,l);return}B(a,r,o,l).catch(()=>!1).then(g=>{g||S(a,r,o,l)})}function lt(a,r,o,l){let g=null;const E=new D;function x(t,n={}){a.client.sendAgentEvent({type:"event",event:"agent",payload:V(t,r,n),seq:t.seq,id:`agent-evt-${t.runId}-${t.seq}`})}o.startsWith("acp:")&&l.on("sessionOptions",()=>{try{const t=l.getSessionOptions?.().models??[];if(!k(o,t))return;const n=a.getAgentSnapshot?.();if(!n)return;a.client.sendEvent({type:"event",event:"machine.agents",payload:{agentList:n.map(e=>e.type),agents:n}})}catch{}});function $(t){t?.heartbeatTimer&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=null)}function b(t){if(!t.currentRunId||!t.currentRunPhase)return;const n=t.heartbeatSeq++;a.client.sendAgentEvent({type:"event",event:"agent",payload:{state:"heartbeat",sessionId:r,runId:t.currentRunId,seq:n,runPhase:t.currentRunPhase},seq:n,id:`agent-heartbeat-${t.currentRunId}-${n}-${Date.now()}`})}function T(t){!t||t.heartbeatTimer||(t.heartbeatTimer=setInterval(()=>{b(t)},Q),t.heartbeatTimer.unref?.())}function f(t){const n=t?.pendingTextEvent;!t||!n||!n.text||(s(r,{id:`agent-${n.runId}-${n.seq}`,sessionId:r,role:"agent",ts:Date.now(),payload:n.text}),c(a.client),x({state:"delta",runId:n.runId,seq:n.seq,text:n.text,thinking:n.thinking||void 0}),t.sessionScope==="steward"&&(t.stewardLastText=n.text),t.pendingTextEvent=null)}l.on("agentEvent",t=>{if(!E.accept(t))return;let n=!1;t.errorCode==="acp_auth_required"&&F(a).catch(()=>{});const e=a.sessions.get(r),h=G(t),u=t.state==="final"||t.state==="error"||t.state==="aborted";if(e&&j(r,e,u),e&&(e.nextEventSeq=t.seq+1,!u&&e.currentRunId!==t.runId&&e.sessionScope==="steward"&&(e.stewardSay={count:0},e.stewardLastText="",H(r)),u||(e.currentRunId=t.runId),!u&&h&&(e.currentRunPhase=h,T(e)),t.agentSessionId&&(e.agentSessionId=t.agentSessionId),e.journalRunId)){const i={agentSessionId:t.agentSessionId??e.agentSessionId,providerRunId:t.runId||null,lastObservedEventSeq:t.seq,...u?{}:{phase:h==="waiting_approval"?"waiting_approval":"running"}};a.runJournal?.update(r,e.journalRunId,i)}if(a.managerRuntime?.noteAgentEvent(r,t),t.state==="delta"&&t.thinking)return;t.state!=="delta"&&_({level:"info",sessionId:r,wsEvent:`agent.${t.state}`,wsDirection:"out",metadata:{runId:t.runId,seq:t.seq,agentType:o}});let p=!1;if(t.state==="tool-call"||t.state==="tool-result"){const i=t.toolCallId?`agent-tool-${w("sha256").update(`${t.runId}\0${t.toolCallId}`).digest("hex")}`:`agent-${t.runId}-${t.seq}`;C({sessionId:r,toolCallId:i,detailRevision:t.seq,ts:Date.now(),name:t.name??"tool",...t.args!==void 0?{args:t.args}:{},...t.result!==void 0?{result:t.result}:{},status:t.toolStatus??(t.state==="tool-call"?"running":"completed"),...t.durationMs!==void 0?{durationMs:t.durationMs}:{},detailRef:{runId:t.runId,sourceSeq:t.seq}}),(t.toolCallId?O:s)(r,{id:i,sessionId:r,role:"agent",ts:Date.now(),payload:JSON.stringify({v:1,type:t.state==="tool-call"?"tool_use":"tool_result",name:t.name,toolCallId:i,status:t.toolStatus??(t.state==="tool-call"?"running":"completed"),...t.durationMs!==void 0?{durationMs:t.durationMs}:{},detailRef:{runId:t.runId,sourceSeq:t.seq},detailRevision:t.seq,detailAvailable:!0,resultOmitted:t.state==="tool-result"})}),p=!0}else t.state==="approval-pending"?(s(r,{id:`agent-${t.runId||"run"}-${t.seq}`,sessionId:r,role:"agent",ts:Date.now(),payload:M({...t.approval,permission:t.permission})}),p=!0,e&&I({sessionId:r,agentType:o,workDir:e.workDir,agentSessionId:e.agentSessionId,attentionId:R("approval",t.runId,t.seq)})):(t.state==="error"||t.state==="aborted")&&t.message&&(s(r,{id:`agent-${t.runId||"run"}-${t.seq}`,sessionId:r,role:"agent",ts:Date.now(),payload:t.message}),p=!0);p&&c(a.client);const d=`${r}:${t.runId}`;if(t.state==="delta"&&!t.thinking&&t.text&&a.runTextAcc.set(d,(a.runTextAcc.get(d)??"")+t.text),t.agentSessionId&&t.agentSessionId!==g&&(e?.nativeSessionVisibility==="internal"&&P(r,A(o,t.source)??o,t.agentSessionId),g=t.agentSessionId,a.nativeFusion?.noteManagedSourceSession(r,A(o,t.source),t.agentSessionId),e&&I({sessionId:r,agentType:o,workDir:e.workDir,agentSessionId:t.agentSessionId}),a.client.sendEvent({type:"event",event:"session.update",payload:{session:{id:r,agentType:o,agentSessionId:t.agentSessionId}}})),t.state==="delta"){const i=t.text??"";if(!i)return;e?.pendingTextEvent&&e.pendingTextEvent.runId!==t.runId&&f(e),e&&!e.pendingTextEvent&&(e.pendingTextEvent={runId:t.runId,seq:t.seq,text:"",thinking:!1}),e?.pendingTextEvent&&(e.pendingTextEvent.text+=i,e.pendingTextEvent.seq=t.seq);return}let q={};if(t.state==="final"){f(e),e&&(S(a,r,e,t),J(r));const i=e?N(e):null;i&&(n=!0,s(r,{id:`room-reply-notice-${t.runId}`,sessionId:r,role:"agent",ts:Date.now(),payload:i}),c(a.client));const m=a.runTextAcc.get(d)??"";m&&(q={messageSummary:L(m)}),a.runTextAcc.delete(d)}else t.state==="error"||t.state==="aborted"?(f(e),e&&y(a,r,e,t),a.runTextAcc.delete(d)):(t.state==="tool-call"||t.state==="tool-result"||t.state==="approval-pending")&&f(e);u&&e?.currentRunId===t.runId&&(e.currentRunId=null,e.currentRunPhase=null,e.nextEventSeq=0,$(e),a.chatQueue?.noteTerminal(r),I({sessionId:r,agentType:o,workDir:e.workDir,agentSessionId:e.agentSessionId,status:t.state==="final"&&!n?"completed":"failed",attentionId:R("terminal",t.runId),lastActivityAt:new Date().toISOString()}),c(a.client),e.journalRunId&&(a.runJournal?.remove(r,e.journalRunId),a.recoveryBarrier?.end(r),e.journalRunId=null)),x(t,q)}),l.on("error",t=>{console.error(`[chat.send] adapter error sessionId=${r} agentType=${o}: ${t.message}`);const n=a.sessions.get(r);n&&y(a,r,n,{state:"error",runId:n.currentRunId??"",message:t.message}),n?.journalRunId&&(a.runJournal?.update(r,n.journalRunId,{phase:"terminal"}),a.runJournal?.remove(r,n.journalRunId),a.recoveryBarrier?.end(r),n.journalRunId=null),a.sessions.delete(r),a.chatQueue?.noteTerminal(r),a.chatQueue?.isDispatching?.(r)||(s(r,{id:`agent-error-${r}-${Date.now()}`,sessionId:r,role:"agent",ts:Date.now(),payload:t.message}),c(a.client)),a.client.sendEvent({type:"event",event:"agent",payload:{state:"error",sessionId:r,message:t.message,runId:"",seq:0}})})}export{lt as bindAdapterEvents,A as getNativeSourceAgentType};
@@ -1 +1 @@
1
- import{createHash as T,randomUUID as m}from"node:crypto";import{buildStewardSayPayload as x,STEWARD_TERMINAL_OPEN_MESSAGE_ID_PREFIX as _}from"@shennian/wire";import{DaemonIpcError as $}from"../../daemon-ipc/protocol.js";import{STEWARD_SAY_MAX_CHARS as l,isStewardSessionId as p}from"../../steward/session.js";import{requestSessionIndexPublish as A}from"../index-publisher.js";import{appendMessage as y,getDaemonInstallationId as E,listSessionRecords as I,recordSession as g}from"../store.js";import{pinStewardWorkDir as h}from"../../steward/session.js";import{buildHandoverNote as D,carryStewardChain as M,classifyStewardFailure as R,lastStewardUserText as b,pickFailoverAgent as N,setStewardHandover as L,stewardFailureLabel as k,stewardTriedAgents as C}from"../../steward/failover.js";class c extends ${}function w(s,e,t,a="say",d){if(!p(e))throw new c("steward_session_required","This session is not a Shennian steward session.");const r=typeof t=="string"?t.trim():"";if(!r)throw new c("steward_say_empty","There is nothing to say.");if(r.length>l)throw new c("steward_say_too_long",`A message may hold at most ${l} characters.`);const n=d??`steward-say-${m()}`;y(e,{id:n,sessionId:e,role:"agent",ts:Date.now(),payload:x(r,a)});const o=s.sessions.get(e);return o&&a==="say"&&(o.stewardSay={count:(o.stewardSay?.count??0)+1}),A(s.client),{messageId:n}}function j(s,e,t,a){if(!p(e)||(t.stewardSay?.count??0)>0)return;const r=(t.stewardLastText?.trim()??"")||(a.state==="final"?"\u5DF2\u5904\u7406\uFF0C\u4F46\u6CA1\u6709\u53EF\u663E\u793A\u7684\u56DE\u590D\u3002":a.message?.trim()||"\u8FD9\u6B21\u5904\u7406\u6CA1\u6709\u5B8C\u6210\u3002");try{w(s,e,r.slice(0,l),"fallback",`steward-fallback-${a.runId||"run"}`)}catch{}}const F="\u6765\u81EA\u7EC8\u7AEF",q=new Set(["manager","pi"]);function W(s){const e=T("sha256").update(`${s}\0steward-terminal`).digest("hex"),t=(Number.parseInt(e[16],16)&3|8).toString(16);return`sess_${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-${t}${e.slice(17,20)}-${e.slice(20,32)}`}function z(s,e){const t=W(E()),a=I().find(d=>d.sessionId===t);if(a&&a.sessionScope!=="steward")throw new c("steward_scope_conflict","The terminal conversation id is already in use.");if(!a){const r=(s.getAgentSnapshot?.()??[]).find(n=>n.supportsStandardSession!==!1&&!q.has(n.type))?.type??"codex";g({sessionId:t,agentType:r,workDir:h(),sessionScope:"steward",sessionMode:"standard"}),y(t,{id:`${_}${t}`,sessionId:t,role:"user",ts:Date.now(),payload:F})}return{...w(s,t,e),sessionId:t}}const H={codex:"Codex",claude:"Claude Code",opencode:"OpenCode"},S=s=>H[s]??s.replace(/^acp:/,"");async function J(s,e,t,a,d){if(a.state!=="error"||!p(e)||(t.stewardSay?.count??0)>0||!s.chatQueue)return!1;const r=d||b(e);if(!r)return!1;const n=C(e,t.agentType),o=N(s.getAgentSnapshot?.()??[],n);if(!o)return!1;const f=R(a.message),i=`sess_${m()}`,u=h();g({sessionId:i,agentType:o,workDir:u,sessionScope:"steward",sessionMode:"standard"}),M(e,i,[...n,o]),L(i,D(S(t.agentType),f));try{if(!await s.chatQueue.handleEnqueue({type:"req",id:`steward-failover-${i}`,method:"chat.enqueue",params:{sessionId:i,text:r,agentType:o,workDir:u,sessionMode:"standard",sessionScope:"steward",clientMessageId:`steward-failover-user-${i}`}}))return!1}catch{return!1}return w(s,i,`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 ${S(o)}\uFF08\u539F\u56E0\uFF1A${S(t.agentType)}${k(f)}\uFF09`,"say",`steward-failover-note-${i}`),!0}export{F as STEWARD_TERMINAL_TITLE,c as StewardSayError,j as commitStewardFallback,w as commitStewardSay,z as commitTerminalStewardSay,W as stewardTerminalSessionId,J as tryStewardFailover};
1
+ import{createHash as T,randomUUID as m}from"node:crypto";import{buildStewardSayPayload as x,parseStewardSayPayload as E,STEWARD_FAILOVER_USER_MESSAGE_ID_PREFIX as A,STEWARD_TERMINAL_OPEN_MESSAGE_ID_PREFIX as $}from"@shennian/wire";import{DaemonIpcError as D}from"../../daemon-ipc/protocol.js";import{STEWARD_SAY_MAX_CHARS as l,isStewardSessionId as S}from"../../steward/session.js";import{requestSessionIndexPublish as R}from"../index-publisher.js";import{appendMessage as y,getDaemonInstallationId as I,listSessionRecords as M,readMessages as L,recordSession as g}from"../store.js";import{pinStewardWorkDir as h}from"../../steward/session.js";import{buildHandoverNote as b,carryStewardChain as N,classifyStewardFailure as k,clearStewardSwitched as _,lastStewardUserText as F,markStewardSwitched as C,pickFailoverAgent as P,setStewardHandover as U,wasStewardJustSwitched as W,stewardFailureLabel as q,stewardTriedAgents as H}from"../../steward/failover.js";class c extends D{}function w(t,e,a,r="say",d){if(!S(e))throw new c("steward_session_required","This session is not a Shennian steward session.");const s=typeof a=="string"?a.trim():"";if(!s)throw new c("steward_say_empty","There is nothing to say.");if(s.length>l)throw new c("steward_say_too_long",`A message may hold at most ${l} characters.`);const n=d??`steward-say-${m()}`;y(e,{id:n,sessionId:e,role:"agent",ts:Date.now(),payload:x(s,r)});const o=t.sessions.get(e);return o&&r==="say"&&(o.stewardSay={count:(o.stewardSay?.count??0)+1}),R(t.client),{messageId:n}}function O(t){for(const e of L(t,{limit:40})){if(e.role==="user")return!1;if(e.role==="agent"&&E(String(e.payload))?.source==="say")return!0}return!1}function te(t,e,a,r){if(!S(e)||(a.stewardSay?.count??0)>0||W(e)||O(e))return;const s=(a.stewardLastText?.trim()??"")||(r.state==="final"?"\u5DF2\u5904\u7406\uFF0C\u4F46\u6CA1\u6709\u53EF\u663E\u793A\u7684\u56DE\u590D\u3002":r.message?.trim()||"\u8FD9\u6B21\u5904\u7406\u6CA1\u6709\u5B8C\u6210\u3002");try{w(t,e,s.slice(0,l),"fallback",`steward-fallback-${r.runId||"run"}`)}catch{}}const G="\u6765\u81EA\u7EC8\u7AEF",X=new Set(["manager","pi"]);function v(t){const e=T("sha256").update(`${t}\0steward-terminal`).digest("hex"),a=(Number.parseInt(e[16],16)&3|8).toString(16);return`sess_${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-${a}${e.slice(17,20)}-${e.slice(20,32)}`}function ae(t,e){const a=v(I()),r=M().find(d=>d.sessionId===a);if(r&&r.sessionScope!=="steward")throw new c("steward_scope_conflict","The terminal conversation id is already in use.");if(!r){const s=(t.getAgentSnapshot?.()??[]).find(n=>n.supportsStandardSession!==!1&&!X.has(n.type))?.type??"codex";g({sessionId:a,agentType:s,workDir:h(),sessionScope:"steward",sessionMode:"standard"}),y(a,{id:`${$}${a}`,sessionId:a,role:"user",ts:Date.now(),payload:G})}return{...w(t,a,e),sessionId:a}}const Q={codex:"Codex",claude:"Claude Code",opencode:"OpenCode"},p=t=>Q[t]??t.replace(/^acp:/,"");async function re(t,e,a,r,d){if(r.state!=="error"||!S(e)||(a.stewardSay?.count??0)>0||!t.chatQueue)return!1;const s=d||F(e);if(!s)return!1;const n=H(e,a.agentType),o=P(t.getAgentSnapshot?.()??[],n);if(!o)return!1;const u=k(r.message);C(e);const i=`sess_${m()}`,f=h();g({sessionId:i,agentType:o,workDir:f,sessionScope:"steward",sessionMode:"standard"}),N(e,i,[...n,o]),U(i,b(p(a.agentType),u));try{if(!await t.chatQueue.handleEnqueue({type:"req",id:`steward-failover-${i}`,method:"chat.enqueue",params:{sessionId:i,text:s,agentType:o,workDir:f,sessionMode:"standard",sessionScope:"steward",clientMessageId:`${A}${i}`}}))return _(e),!1}catch{return _(e),!1}return w(t,i,`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 ${p(o)}\uFF08\u539F\u56E0\uFF1A${p(a.agentType)}${q(u)}\uFF09`,"say",`steward-failover-note-${i}`),!0}export{G as STEWARD_TERMINAL_TITLE,c as StewardSayError,te as commitStewardFallback,w as commitStewardSay,ae as commitTerminalStewardSay,v as stewardTerminalSessionId,re as tryStewardFailover};
@@ -1 +1 @@
1
- const s={not_installed:"\u6CA1\u6709\u5B89\u88C5\u6216\u627E\u4E0D\u5230\u7A0B\u5E8F",not_logged_in:"\u6CA1\u6709\u767B\u5F55\u6216\u6388\u6743\u5931\u6548",quota:"\u989D\u5EA6\u7528\u5B8C\u6216\u88AB\u9650\u6D41",crashed:"\u542F\u52A8\u5931\u8D25\u6216\u8FD0\u884C\u4E2D\u65AD"};function f(e){return s[e]}function p(e){const t=(e??"").toLowerCase();return/enoent|command not found|not installed|command_unavailable|runtime_unavailable|no such file|未找到|未安装/.test(t)?"not_installed":/log ?in|logged in|sign in|unauthori[sz]ed|\b401\b|\b403\b|auth(?:entication|_required)?\b|api key|credential|未登录|登录/.test(t)?"not_logged_in":/quota|usage limit|rate limit|too many requests|\b429\b|insufficient|credit|billing|exceeded|额度|用完|限流/.test(t)?"quota":"crashed"}const d=new Set(["manager","pi","pi-coding-agent"]);function x(e,t){const n=new Set(t);return e.find(r=>r.supportsStandardSession!==!1&&!d.has(r.type)&&r.authState!=="required"&&r.authState!=="error"&&!n.has(r.type))?.type??null}function w(e,t){return[`\u8FD9\u6BB5\u5BF9\u8BDD\u662F\u4ECE\u300C${e}\u300D\u81EA\u52A8\u5207\u6362\u8FC7\u6765\u7684\uFF08\u539F\u56E0\uFF1A${s[t]}\uFF09\u3002`,"\u4E0A\u4E00\u4E2A AI \u53EF\u80FD\u5DF2\u7ECF\u505A\u4E86\u4E00\u90E8\u5206\u64CD\u4F5C\uFF1A\u52A8\u624B\u524D\u5148\u6838\u5BF9\u73B0\u72B6\uFF08\u4F8B\u5982 shennian project task list \u770B\u5DF2\u5EFA\u7684\u4EFB\u52A1\uFF09\uFF0C","\u4E0D\u8981\u91CD\u590D\u6267\u884C\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\uFF0C\u4E5F\u4E0D\u8981\u91CD\u590D\u521B\u5EFA\u5DF2\u5B58\u5728\u7684\u4EFB\u52A1\uFF1B\u6838\u5BF9\u540E\u518D\u7EE7\u7EED\u56DE\u5E94\u7528\u6237\u7684\u8FD9\u6761\u6D88\u606F\u3002"].join("")}const u=new Map,o=new Map,i=new Map,l=200;function a(e){for(;e.size>l;)e.delete(e.keys().next().value);return e}function h(e,t){a(u).set(e,t)}function S(e){return u.get(e)??""}function b(e,t){const n=o.get(e)??[];return n.includes(t)?n:[...n,t]}function g(e,t,n){a(o).set(t,[...n]),o.delete(e)}function _(e,t){a(i).set(e,t)}function y(e){const t=i.get(e)??"";return i.delete(e),t}function A(e){o.delete(e)}export{w as buildHandoverNote,g as carryStewardChain,p as classifyStewardFailure,S as lastStewardUserText,x as pickFailoverAgent,h as rememberStewardTurn,A as resetStewardChain,_ as setStewardHandover,f as stewardFailureLabel,b as stewardTriedAgents,y as takeStewardHandover};
1
+ const d={not_installed:"\u6CA1\u6709\u5B89\u88C5\u6216\u627E\u4E0D\u5230\u7A0B\u5E8F",not_logged_in:"\u6CA1\u6709\u767B\u5F55\u6216\u6388\u6743\u5931\u6548",quota:"\u989D\u5EA6\u7528\u5B8C\u6216\u88AB\u9650\u6D41",crashed:"\u542F\u52A8\u5931\u8D25\u6216\u8FD0\u884C\u4E2D\u65AD"};function p(e){return d[e]}function S(e){const t=(e??"").toLowerCase();return/enoent|command not found|not installed|command_unavailable|runtime_unavailable|no such file|未找到|未安装/.test(t)?"not_installed":/log ?in|logged in|sign in|unauthori[sz]ed|\b401\b|\b403\b|auth(?:entication|_required)?\b|api key|credential|未登录|登录/.test(t)?"not_logged_in":/quota|usage limit|rate limit|too many requests|\b429\b|insufficient|credit|billing|exceeded|额度|用完|限流/.test(t)?"quota":"crashed"}const c=new Set(["manager","pi","pi-coding-agent"]);function x(e,t){const n=new Set(t);return e.find(r=>r.supportsStandardSession!==!1&&!c.has(r.type)&&r.authState!=="required"&&r.authState!=="error"&&!n.has(r.type))?.type??null}function h(e,t){return[`\u8FD9\u6BB5\u5BF9\u8BDD\u662F\u4ECE\u300C${e}\u300D\u81EA\u52A8\u5207\u6362\u8FC7\u6765\u7684\uFF08\u539F\u56E0\uFF1A${d[t]}\uFF09\u3002`,"\u4E0A\u4E00\u4E2A AI \u53EF\u80FD\u5DF2\u7ECF\u505A\u4E86\u4E00\u90E8\u5206\u64CD\u4F5C\uFF1A\u52A8\u624B\u524D\u5148\u6838\u5BF9\u73B0\u72B6\uFF08\u4F8B\u5982 shennian project task list \u770B\u5DF2\u5EFA\u7684\u4EFB\u52A1\uFF09\uFF0C","\u4E0D\u8981\u91CD\u590D\u6267\u884C\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\uFF0C\u4E5F\u4E0D\u8981\u91CD\u590D\u521B\u5EFA\u5DF2\u5B58\u5728\u7684\u4EFB\u52A1\uFF1B\u6838\u5BF9\u540E\u518D\u7EE7\u7EED\u56DE\u5E94\u7528\u6237\u7684\u8FD9\u6761\u6D88\u606F\u3002"].join("")}const u=new Map,o=new Map,a=new Map,l=200;function i(e){for(;e.size>l;)e.delete(e.keys().next().value);return e}function _(e,t){i(u).set(e,t)}function g(e){return u.get(e)??""}function b(e,t){const n=o.get(e)??[];return n.includes(t)?n:[...n,t]}function A(e,t,n){i(o).set(t,[...n]),o.delete(e)}function T(e,t){i(a).set(e,t)}function m(e){const t=a.get(e)??"";return a.delete(e),t}function y(e){o.delete(e)}const s=new Map,w=6e4;function v(e){i(s).set(e,Date.now())}function k(e){const t=s.get(e);return t!==void 0&&Date.now()-t<w}function E(e){s.delete(e)}export{h as buildHandoverNote,A as carryStewardChain,S as classifyStewardFailure,E as clearStewardSwitched,g as lastStewardUserText,v as markStewardSwitched,x as pickFailoverAgent,_ as rememberStewardTurn,y as resetStewardChain,T as setStewardHandover,p as stewardFailureLabel,b as stewardTriedAgents,m as takeStewardHandover,k as wasStewardJustSwitched};
@@ -1,8 +1,8 @@
1
- const E=/^\s*::git-[a-z-]+\{[^\n]*\}\s*$/gm,g=/^\s*\{\s*"v"\s*:\s*1\s*,\s*"type"\s*:\s*"(tool|tool_use|tool_result)"/,x=/^\s*<environment_context>\s*[^]*?<\/environment_context>\s*$/i,R=/<(cwd|shell|current_date|timezone)>[^<]*<\/\1>/gi,b=/^\s*<recommended_plugins>[^]*?<\/recommended_plugins>\s*/i,P=/^\s*<turn_aborted>[^]*?<\/turn_aborted>\s*$/i,S=/^\s*<codex_internal_context\b[^>]*>[^]*?<\/codex_internal_context>\s*$/i,T=/^\s*# AGENTS\.md instructions for [^\n]+\n+\s*<INSTRUCTIONS>\s*[^]*?<\/INSTRUCTIONS>\s*(?:<environment_context>[^]*?<\/environment_context>)?\s*$/i,h=/^\s*\{\s*"v"\s*:\s*1\s*,\s*"type"\s*:\s*"approval_pending"/,N=/(?:<\/?(?:environment_context|instructions|system|developer|codex_internal_context|recommended_plugins)\b|#\s*AGENTS\.md instructions\b)/i,A=/\bdata:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+/i,I=/(?:^|\s)(?=[A-Za-z0-9+/]{80,}={0,2}(?=\s|$))(?=[A-Za-z0-9+/]*[A-Z])(?=[A-Za-z0-9+/]*[a-z])(?=[A-Za-z0-9+/]*[0-9])[A-Za-z0-9+/]{80,}={0,2}(?=\s|$)/,v=new Set(["tool","tool_use","tool_result","thinking","system","developer","context","environment_context","channel_delivery_status"]),L="steward-terminal-open-";function O(e){return e.replace(/[[\]\\]/g,"\\$&")}function C(e){const t=O(e.name);return e.kind==="image"?`![${t}](<${e.path}>)`:`[${t}](<${e.path}>)`}function w(e,t){if(!t?.length)return e;const n=new Set(t.map(C));return e.split(`
1
+ const E=/^\s*::git-[a-z-]+\{[^\n]*\}\s*$/gm,g=/^\s*\{\s*"v"\s*:\s*1\s*,\s*"type"\s*:\s*"(tool|tool_use|tool_result)"/,R=/^\s*<environment_context>\s*[^]*?<\/environment_context>\s*$/i,S=/<(cwd|shell|current_date|timezone)>[^<]*<\/\1>/gi,x=/^\s*<recommended_plugins>[^]*?<\/recommended_plugins>\s*/i,P=/^\s*<turn_aborted>[^]*?<\/turn_aborted>\s*$/i,b=/^\s*<codex_internal_context\b[^>]*>[^]*?<\/codex_internal_context>\s*$/i,T=/^\s*# AGENTS\.md instructions for [^\n]+\n+\s*<INSTRUCTIONS>\s*[^]*?<\/INSTRUCTIONS>\s*(?:<environment_context>[^]*?<\/environment_context>)?\s*$/i,A=/^\s*\{\s*"v"\s*:\s*1\s*,\s*"type"\s*:\s*"approval_pending"/,I=/(?:<\/?(?:environment_context|instructions|system|developer|codex_internal_context|recommended_plugins)\b|#\s*AGENTS\.md instructions\b)/i,h=/\bdata:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+/i,N=/(?:^|\s)(?=[A-Za-z0-9+/]{80,}={0,2}(?=\s|$))(?=[A-Za-z0-9+/]*[A-Z])(?=[A-Za-z0-9+/]*[a-z])(?=[A-Za-z0-9+/]*[0-9])[A-Za-z0-9+/]{80,}={0,2}(?=\s|$)/,v=new Set(["tool","tool_use","tool_result","thinking","system","developer","context","environment_context","channel_delivery_status"]),L="steward-terminal-open-",G="steward-failover-user-";function O(e){return e.replace(/[[\]\\]/g,"\\$&")}function C(e){const t=O(e.name);return e.kind==="image"?`![${t}](<${e.path}>)`:`[${t}](<${e.path}>)`}function w(e,t){if(!t?.length)return e;const n=new Set(t.map(C));return e.split(`
2
2
  `).filter(s=>!n.has(s.trim())).join(`
3
3
  `).replace(/\n{3,}/g,`
4
4
 
5
- `).trim()}function u(e){if(!e||e[0]!=="{")return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t!==null)return t}catch{}return null}function D(e){if(typeof e!="object"||e===null)return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"",s=typeof t.mimeType=="string"?t.mimeType:"",l=t.kind==="image"||t.kind==="file"||t.kind==="folder"?t.kind:null;if(!n||!r||!s||!l)return null;const f=typeof t.previewData=="string"&&t.previewData.trim()?t.previewData.trim():void 0,p=typeof t.byteSize=="number"&&Number.isSafeInteger(t.byteSize)&&t.byteSize>=0?t.byteSize:void 0,d=typeof t.sha256=="string"&&/^[a-f0-9]{64}$/i.test(t.sha256)?t.sha256.toLowerCase():void 0;return{path:n,name:r,mimeType:s,kind:l,...p!==void 0?{byteSize:p}:{},...d?{sha256:d}:{},...f?{previewData:f}:{}}}function o(e){const t=u(e);if(!t||t.v!==1)return null;if(t.type==="user"&&typeof t.content=="string"){const n=Array.isArray(t.attachments)?t.attachments.map(D).filter(r=>r!=null):void 0;return{v:1,type:"user",content:t.content,...n?.length?{attachments:n}:{}}}return t}function z(e){const t=o(e);return t?.type==="user"?t:null}function G(e,t){return t?.length?JSON.stringify({v:1,type:"user",content:e,attachments:t}):e}function $(e){if(g.test(e))return!0;const t=o(e);return!t||typeof t!="object"?!1:t.type==="tool"||t.type==="tool_use"||t.type==="tool_result"}function k(e){return h.test(e)?!0:o(e)?.type==="approval_pending"}function j(e,t="say"){return JSON.stringify({v:1,type:"steward_say",content:e,source:t})}function J(e){const t=o(e);if(!t||t.type!=="steward_say")return null;const n=t;return typeof n.content!="string"||!n.content.trim()?null:{v:1,type:"steward_say",content:n.content,source:n.source==="fallback"?"fallback":"say"}}function F(e){return V(e)?.agentVisible===!1}function V(e){const t=o(e);if(!t||t.type!=="channel_delivery_status")return null;const n=t;if(n.v!==1||n.channel!=="wechat"||n.agentVisible!==!1)return null;const r=typeof n.status=="string"&&n.status.trim()?n.status.trim():"";if(!r)return null;const s=typeof n.content=="string"&&n.content.trim()?n.content:r==="manual_review"?"\u53D1\u9001\u72B6\u6001\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u68C0\u67E5\u5FAE\u4FE1":"\u672A\u80FD\u81EA\u52A8\u53D1\u9001\u5230\u5FAE\u4FE1";return{v:1,type:"channel_delivery_status",channel:"wechat",status:r,agentVisible:!1,content:s,replyId:i(n.replyId),idempotencyKey:i(n.idempotencyKey),bindingId:i(n.bindingId),reasonCode:i(n.reasonCode),copyText:i(n.copyText),copyableContentRef:i(n.copyableContentRef),errorSummary:i(n.errorSummary)}}function X(e){const t=e?.trim();return`${!t||t==="codex"?"Codex":t==="workbuddy"?"WorkBuddy":t} \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002`}function W(e){return JSON.stringify({v:1,type:"approval_pending",title:e?.title?.trim()||"\u9700\u8981\u7528\u6237\u786E\u8BA4",content:e?.content?.trim()||X(e?.source),source:e?.source?.trim()||"codex",actionHint:e?.permission?e?.actionHint?.trim():e?.actionHint?.trim()||"\u5F53\u524D\u795E\u5FF5\u6682\u4E0D\u652F\u6301\u8FDC\u7A0B\u786E\u8BA4\uFF0C\u8BF7\u56DE\u5230\u8FD0\u884C Codex \u7684\u7535\u8111/\u7EC8\u7AEF\u5B8C\u6210\u786E\u8BA4\u3002",...e?.permission?{permission:e.permission}:{}})}function _(e){if(!x.test(e))return!1;const t=new Set;for(const n of e.matchAll(R))n[1]&&t.add(n[1].toLowerCase());return t.has("current_date")&&t.has("timezone")&&e.includes("<workspace_roots>")?!0:t.has("cwd")&&t.has("shell")&&t.has("current_date")&&t.has("timezone")}function M(e){return P.test(e)}function y(e){return T.test(e)}function U(e){const t=e.match(b);if(t){const n=e.slice(t[0].length).trim();return!n||_(n)||y(n)}return _(e)||M(e)||S.test(e)||y(e)}function c(e){if(!e)return"";const t=e.replace(/\r\n/g,`
5
+ `).trim()}function u(e){if(!e||e[0]!=="{")return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t!==null)return t}catch{}return null}function D(e){if(typeof e!="object"||e===null)return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"",s=typeof t.mimeType=="string"?t.mimeType:"",l=t.kind==="image"||t.kind==="file"||t.kind==="folder"?t.kind:null;if(!n||!r||!s||!l)return null;const f=typeof t.previewData=="string"&&t.previewData.trim()?t.previewData.trim():void 0,p=typeof t.byteSize=="number"&&Number.isSafeInteger(t.byteSize)&&t.byteSize>=0?t.byteSize:void 0,d=typeof t.sha256=="string"&&/^[a-f0-9]{64}$/i.test(t.sha256)?t.sha256.toLowerCase():void 0;return{path:n,name:r,mimeType:s,kind:l,...p!==void 0?{byteSize:p}:{},...d?{sha256:d}:{},...f?{previewData:f}:{}}}function o(e){const t=u(e);if(!t||t.v!==1)return null;if(t.type==="user"&&typeof t.content=="string"){const n=Array.isArray(t.attachments)?t.attachments.map(D).filter(r=>r!=null):void 0;return{v:1,type:"user",content:t.content,...n?.length?{attachments:n}:{}}}return t}function z(e){const t=o(e);return t?.type==="user"?t:null}function F(e,t){return t?.length?JSON.stringify({v:1,type:"user",content:e,attachments:t}):e}function $(e){if(g.test(e))return!0;const t=o(e);return!t||typeof t!="object"?!1:t.type==="tool"||t.type==="tool_use"||t.type==="tool_result"}function k(e){return A.test(e)?!0:o(e)?.type==="approval_pending"}function j(e,t="say"){return JSON.stringify({v:1,type:"steward_say",content:e,source:t})}function J(e){const t=o(e);if(!t||t.type!=="steward_say")return null;const n=t;return typeof n.content!="string"||!n.content.trim()?null:{v:1,type:"steward_say",content:n.content,source:n.source==="fallback"?"fallback":"say"}}function W(e){return V(e)?.agentVisible===!1}function V(e){const t=o(e);if(!t||t.type!=="channel_delivery_status")return null;const n=t;if(n.v!==1||n.channel!=="wechat"||n.agentVisible!==!1)return null;const r=typeof n.status=="string"&&n.status.trim()?n.status.trim():"";if(!r)return null;const s=typeof n.content=="string"&&n.content.trim()?n.content:r==="manual_review"?"\u53D1\u9001\u72B6\u6001\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u68C0\u67E5\u5FAE\u4FE1":"\u672A\u80FD\u81EA\u52A8\u53D1\u9001\u5230\u5FAE\u4FE1";return{v:1,type:"channel_delivery_status",channel:"wechat",status:r,agentVisible:!1,content:s,replyId:i(n.replyId),idempotencyKey:i(n.idempotencyKey),bindingId:i(n.bindingId),reasonCode:i(n.reasonCode),copyText:i(n.copyText),copyableContentRef:i(n.copyableContentRef),errorSummary:i(n.errorSummary)}}function X(e){const t=e?.trim();return`${!t||t==="codex"?"Codex":t==="workbuddy"?"WorkBuddy":t} \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002`}function Z(e){return JSON.stringify({v:1,type:"approval_pending",title:e?.title?.trim()||"\u9700\u8981\u7528\u6237\u786E\u8BA4",content:e?.content?.trim()||X(e?.source),source:e?.source?.trim()||"codex",actionHint:e?.permission?e?.actionHint?.trim():e?.actionHint?.trim()||"\u5F53\u524D\u795E\u5FF5\u6682\u4E0D\u652F\u6301\u8FDC\u7A0B\u786E\u8BA4\uFF0C\u8BF7\u56DE\u5230\u8FD0\u884C Codex \u7684\u7535\u8111/\u7EC8\u7AEF\u5B8C\u6210\u786E\u8BA4\u3002",...e?.permission?{permission:e.permission}:{}})}function _(e){if(!R.test(e))return!1;const t=new Set;for(const n of e.matchAll(S))n[1]&&t.add(n[1].toLowerCase());return t.has("current_date")&&t.has("timezone")&&e.includes("<workspace_roots>")?!0:t.has("cwd")&&t.has("shell")&&t.has("current_date")&&t.has("timezone")}function M(e){return P.test(e)}function y(e){return T.test(e)}function U(e){const t=e.match(x);if(t){const n=e.slice(t[0].length).trim();return!n||_(n)||y(n)}return _(e)||M(e)||b.test(e)||y(e)}function c(e){if(!e)return"";const t=e.replace(/\r\n/g,`
6
6
  `);if(!/(^|\n)\s*::git-[a-z-]+\{[^\n]*\}\s*(?=\n|$)/.test(t))return t;const r=t.replace(E,"");return r.trim()?r.replace(/[ \t]+\n/g,`
7
7
  `).replace(/\n+$/g,""):""}function m(e){if(!e)return"";const t=z(e);if(t)return w(t.content,t.attachments);const n=o(e);if(n){if(typeof n.content=="string")return c(n.content);if("text"in n&&typeof n.text=="string")return c(n.text)}try{const r=JSON.parse(e);if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){const s=r;if(typeof s.content=="string")return c(s.content);if(typeof s.text=="string")return c(s.text)}}catch{}return c(e)}function a(e,t=160){if(typeof e!="string"||!Number.isSafeInteger(t)||t<1)return null;const n=e.replace(/\r\n/g,`
8
- `).trim();if(!n||N.test(n)||A.test(n)||I.test(n)||u(n))return null;const r=n.replace(/\s+/g," ");return r.length>t?`${r.slice(0,t)}\u2026`:r}function Z(e,t=160){if(!e||$(e)||U(e))return null;if(k(e))return a("\u9700\u8981\u7528\u6237\u786E\u8BA4",t);const n=o(e);if(n){const r=typeof n.type=="string"?n.type.toLowerCase():"";return!r||v.has(r)?null:a(m(e),t)}return u(e)?null:a(m(e),t)}function i(e){return typeof e=="string"&&e.trim()?e:void 0}export{L as STEWARD_TERMINAL_OPEN_MESSAGE_ID_PREFIX,W as buildApprovalPendingPayload,j as buildStewardSayPayload,G as buildUserMessagePayload,m as extractPayloadText,F as isAgentHiddenPayload,k as isApprovalPendingPayload,y as isCodexProjectInstructionsPayload,M as isCodexTurnAbortedPayload,U as isSystemControlPayload,_ as isSystemEnvironmentContextPayload,$ as isToolPayload,V as parseChannelDeliveryStatusPayload,J as parseStewardSayPayload,o as parseStructuredMessagePayload,z as parseUserMessagePayload,a as sanitizeSessionPreview,Z as sessionPreviewFromPayload,c as stripGitDirectiveArtifacts};
8
+ `).trim();if(!n||I.test(n)||h.test(n)||N.test(n)||u(n))return null;const r=n.replace(/\s+/g," ");return r.length>t?`${r.slice(0,t)}\u2026`:r}function B(e,t=160){if(!e||$(e)||U(e))return null;if(k(e))return a("\u9700\u8981\u7528\u6237\u786E\u8BA4",t);const n=o(e);if(n){const r=typeof n.type=="string"?n.type.toLowerCase():"";return!r||v.has(r)?null:a(m(e),t)}return u(e)?null:a(m(e),t)}function i(e){return typeof e=="string"&&e.trim()?e:void 0}export{G as STEWARD_FAILOVER_USER_MESSAGE_ID_PREFIX,L as STEWARD_TERMINAL_OPEN_MESSAGE_ID_PREFIX,Z as buildApprovalPendingPayload,j as buildStewardSayPayload,F as buildUserMessagePayload,m as extractPayloadText,W as isAgentHiddenPayload,k as isApprovalPendingPayload,y as isCodexProjectInstructionsPayload,M as isCodexTurnAbortedPayload,U as isSystemControlPayload,_ as isSystemEnvironmentContextPayload,$ as isToolPayload,V as parseChannelDeliveryStatusPayload,J as parseStewardSayPayload,o as parseStructuredMessagePayload,z as parseUserMessagePayload,a as sanitizeSessionPreview,B as sessionPreviewFromPayload,c as stripGitDirectiveArtifacts};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shennian",
3
- "version": "0.5.16",
3
+ "version": "0.5.17",
4
4
  "description": "Shennian \u2014 AI Agent Control Plane CLI",
5
5
  "type": "module",
6
6
  "bin": {