shennian 0.3.52 → 0.3.54

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.
@@ -306,8 +306,8 @@
306
306
  },
307
307
  {
308
308
  "file": "src/native-fusion/codex-parser.js",
309
- "beforeBytes": 29910,
310
- "afterBytes": 12631
309
+ "beforeBytes": 30367,
310
+ "afterBytes": 12930
311
311
  },
312
312
  {
313
313
  "file": "src/native-fusion/config.js",
@@ -591,8 +591,8 @@
591
591
  },
592
592
  {
593
593
  "file": "src/session/queue.js",
594
- "beforeBytes": 17581,
595
- "afterBytes": 8290
594
+ "beforeBytes": 18893,
595
+ "afterBytes": 8613
596
596
  },
597
597
  {
598
598
  "file": "src/session/store.js",
@@ -1,6 +1,6 @@
1
- import j from"node:fs";import $ from"node:os";import I from"node:path";import{createHash as Z}from"node:crypto";import{buildApprovalPendingPayload as P,buildUserMessagePayload as N,isSystemControlPayload as M,isToolPayload as q}from"@shennian/wire";import{buildImagePayload as D,buildToolPayload as K,inferMimeType as W,makeCursor as U,makeEventKey as w,normalizeText as h,parseStructuredString as O,readJsonlLines as F,readTimestamp as tt,safeParse as k}from"./parser-common.js";function et(e){if(typeof e=="string"){const i=e.trim();return i?{path:i,name:I.basename(i)||"image.png",mimeType:W(i),kind:"image"}:null}if(typeof e!="object"||e===null)return null;const r=e,n=typeof r.path=="string"?r.path:typeof r.file_path=="string"?r.file_path:typeof r.saved_path=="string"?r.saved_path:"";if(!n.trim())return null;const t=typeof r.name=="string"&&r.name.trim()?r.name:I.basename(n)||"image.png",o=typeof r.mimeType=="string"&&r.mimeType.trim()?r.mimeType:W(n);return{path:n,name:t,mimeType:o,kind:"image"}}function H(e){return Array.isArray(e)?e.map(n=>{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){const t=n;return typeof t.text=="string"?t.text:""}return""}).map(n=>h(n)).filter(Boolean).join(`
1
+ import j from"node:fs";import w from"node:os";import I from"node:path";import{createHash as Z}from"node:crypto";import{buildApprovalPendingPayload as P,buildUserMessagePayload as k,isSystemControlPayload as M,isToolPayload as W}from"@shennian/wire";import{buildImagePayload as D,buildToolPayload as K,inferMimeType as N,makeCursor as q,makeEventKey as H,normalizeText as h,parseStructuredString as O,readJsonlLines as U,readTimestamp as tt,safeParse as R}from"./parser-common.js";const et=new Set(["untitled","new chat","new conversation","new task","new thread","codex","\u65E0\u6807\u9898","\u672A\u547D\u540D","\u65B0\u4EFB\u52A1","\u65B0\u4F1A\u8BDD","\u65B0\u5BF9\u8BDD"]);function nt(t){if(typeof t=="string"){const i=t.trim();return i?{path:i,name:I.basename(i)||"image.png",mimeType:N(i),kind:"image"}:null}if(typeof t!="object"||t===null)return null;const r=t,n=typeof r.path=="string"?r.path:typeof r.file_path=="string"?r.file_path:typeof r.saved_path=="string"?r.saved_path:"";if(!n.trim())return null;const e=typeof r.name=="string"&&r.name.trim()?r.name:I.basename(n)||"image.png",o=typeof r.mimeType=="string"&&r.mimeType.trim()?r.mimeType:N(n);return{path:n,name:e,mimeType:o,kind:"image"}}function z(t){return Array.isArray(t)?t.map(n=>{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){const e=n;return typeof e.text=="string"?e.text:""}return""}).map(n=>h(n)).filter(Boolean).join(`
2
2
 
3
- `):""}function z(e){const r=h(e);if(!r)return{text:"",strippedWrapper:!1};const n=r.match(/My request for Codex:\s*([\s\S]*)$/i);return n&&n[1]?{text:nt(n[1]),strippedWrapper:!0}:{text:r,strippedWrapper:!1}}function nt(e){return h(e.replace(/<image>\s*<\/image>/gi,""))}function B(e){const r=h(e);if(!r)return!1;if(M(r)||/^<environment_context>[\s\S]*<\/environment_context>$/i.test(r)&&r.includes("<current_date>")&&r.includes("<timezone>")&&r.includes("<workspace_roots>"))return!0;const n=r.startsWith("<recommended_plugins>")&&r.includes("</recommended_plugins>"),t=r.includes("# AGENTS.md instructions for ")&&r.includes("<INSTRUCTIONS>")&&r.includes("</INSTRUCTIONS>"),o=r.includes("<environment_context>")&&r.includes("</environment_context>");return t&&o&&(r.startsWith("# AGENTS.md instructions for ")||n)}function L(e){const r=H(e.text_elements),n=Array.isArray(e.input)?H(e.input):"",t=typeof e.message=="string"?z(e.message):{text:"",strippedWrapper:!1},o=t.text,i=r||n||o,u=t.strippedWrapper?"codex_app_context_wrapper":void 0,a=Array.isArray(e.local_images)?e.local_images.map(et).filter(f=>f!=null):[];return!i&&a.length===0||M(i)&&a.length===0||B(i)&&a.length===0?null:a.length>0?{payload:N(i,a),titleText:i,repairHint:u}:{payload:i,titleText:i,repairHint:u}}function rt(e){return e==="turn_completed"||e==="turn_complete"||e==="task_complete"}function ot(e){return/approval|permission|confirm|user[_-]?input|input[_-]?required/i.test(e)}function it(e){const r=typeof e.command=="string"?e.command:Array.isArray(e.command)?e.command.join(" "):"",n=typeof e.prompt=="string"?e.prompt:typeof e.reason=="string"?e.reason:typeof e.message=="string"?e.message:r?`Codex \u8BF7\u6C42\u6267\u884C\u547D\u4EE4\uFF1A${r}`:"Codex \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002";return P({title:"\u9700\u8981\u7528\u6237\u786E\u8BA4",content:n,source:"codex",actionHint:"\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"})}function G(e,r){return Array.isArray(e)?h(e.map(n=>{if(typeof n=="string")return n;if(typeof n!="object"||n===null)return"";const t=n;return t.type!==r?"":typeof t.text=="string"?t.text:""}).filter(Boolean).join(`
3
+ `):""}function F(t){const r=h(t);if(!r)return{text:"",strippedWrapper:!1};const n=r.match(/My request for Codex:\s*([\s\S]*)$/i);return n&&n[1]?{text:rt(n[1]),strippedWrapper:!0}:{text:r,strippedWrapper:!1}}function rt(t){return h(t.replace(/<image>\s*<\/image>/gi,""))}function L(t){const r=h(t);if(!r)return!1;if(M(r)||/^<environment_context>[\s\S]*<\/environment_context>$/i.test(r)&&r.includes("<current_date>")&&r.includes("<timezone>")&&r.includes("<workspace_roots>"))return!0;const n=r.startsWith("<recommended_plugins>")&&r.includes("</recommended_plugins>"),e=r.includes("# AGENTS.md instructions for ")&&r.includes("<INSTRUCTIONS>")&&r.includes("</INSTRUCTIONS>"),o=r.includes("<environment_context>")&&r.includes("</environment_context>");return e&&o&&(r.startsWith("# AGENTS.md instructions for ")||n)}function B(t){const r=z(t.text_elements),n=Array.isArray(t.input)?z(t.input):"",e=typeof t.message=="string"?F(t.message):{text:"",strippedWrapper:!1},o=e.text,i=r||n||o,u=e.strippedWrapper?"codex_app_context_wrapper":void 0,a=Array.isArray(t.local_images)?t.local_images.map(nt).filter(f=>f!=null):[];return!i&&a.length===0||M(i)&&a.length===0||L(i)&&a.length===0?null:a.length>0?{payload:k(i,a),titleText:i,repairHint:u}:{payload:i,titleText:i,repairHint:u}}function ot(t){return t==="turn_completed"||t==="turn_complete"||t==="task_complete"}function it(t){return/approval|permission|confirm|user[_-]?input|input[_-]?required/i.test(t)}function st(t){const r=typeof t.command=="string"?t.command:Array.isArray(t.command)?t.command.join(" "):"",n=typeof t.prompt=="string"?t.prompt:typeof t.reason=="string"?t.reason:typeof t.message=="string"?t.message:r?`Codex \u8BF7\u6C42\u6267\u884C\u547D\u4EE4\uFF1A${r}`:"Codex \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002";return P({title:"\u9700\u8981\u7528\u6237\u786E\u8BA4",content:n,source:"codex",actionHint:"\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"})}function G(t,r){return Array.isArray(t)?h(t.map(n=>{if(typeof n=="string")return n;if(typeof n!="object"||n===null)return"";const e=n;return e.type!==r?"":typeof e.text=="string"?e.text:""}).filter(Boolean).join(`
4
4
 
5
- `)):""}function st(e){if(!Array.isArray(e))return[];const r=[];for(const n of e){if(typeof n!="object"||n===null)continue;const t=n;if(t.type!=="input_image")continue;const o=typeof t.path=="string"?t.path:typeof t.file_path=="string"?t.file_path:typeof t.saved_path=="string"?t.saved_path:typeof t.image_path=="string"?t.image_path:"";o.trim()&&r.push({path:o,name:I.basename(o)||"image.png",mimeType:W(o),kind:"image"})}return r}function J(e){if(e.type!=="message")return null;const r=e.role==="assistant"?"agent":e.role==="user"?"user":null;if(!r)return null;if(r==="agent"){const i=G(e.content,"output_text");return M(i)?null:i?{role:r,payload:i,titleText:i}:null}const n=z(G(e.content,"input_text")),t=n.text,o=st(e.content);return!t&&o.length===0||M(t)&&o.length===0||B(t)&&o.length===0?null:{role:r,payload:o.length>0?N(t,o):t,titleText:t,repairHint:n.strippedWrapper?"codex_app_context_wrapper":void 0}}function Q(e){if(!e)return"";try{const r=JSON.parse(e);if(typeof r=="object"&&r!==null){const n=r;if(n.type==="user"&&typeof n.content=="string")return h(n.content)}}catch{}return h(e)}function ct(e,r,n,t){return e.agentType!=="codex"||e.role!==r||q(e.payload)||Math.abs(e.ts-t)>300*1e3?!1:Q(e.payload)===Q(n)}function R(e,r,n,t){for(let o=e.length-1;o>=0;o-=1){const i=e[o];if(i){if(ct(i,r,n,t))return o;if(i.agentType==="codex"&&Math.abs(i.ts-t)>300*1e3)break}}return-1}function v(e,r,n,t,o,i,u,a,f,c,s="agent",l=!1,m){u&&e.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:w(r,n,t),cursor:U(r,n),role:s,ts:i,payload:u,title:a,modelId:f,workDir:c,terminal:l,repairHint:m})}function x(e,r,n,t,o,i,u,a,f,c,s,l,m){const A=w(r,n,t),y=typeof m?.callId=="string"&&m.callId.trim()?m.callId.trim():null,T=y?Z("sha256").update(`${o}\0${y}`).digest("hex").slice(0,32):null,p=T?`tool:${T}`:void 0,b=T?`native:tool:${T}`:`native:${A}`,g=m?.completed&&T?2:1,S=l!==void 0?"completed":"running";e.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:A,cursor:U(r,n),role:"agent",ts:i,payload:K({name:u,toolCallId:b,detailRevision:g,status:S}),title:a,modelId:f,workDir:c,...p?{canonicalMessageKey:p,canonicalMutation:m?.completed?"upsert":"append"}:{},localToolDetail:{toolCallId:b,detailRevision:g,name:u,...s!==void 0?{args:s}:{},...l!==void 0?{result:l}:{},status:S}})}function ut(e,r,n,t,o,i,u,a,f){const c=typeof t.type=="string"?t.type:"";if(c){if(c==="message"){const s=J(t);if(!s||R(e,s.role,s.payload,i)>=0)return;v(e,r,n,`${c}:${s.role}`,o,i,s.payload,u,a,f,s.role,!1,s.repairHint);return}if(c==="function_call"){const s=typeof t.name=="string"?t.name:"function_call";x(e,r,n,c,o,i,s,u,a,f,O(t.arguments),void 0,{callId:t.call_id});return}if(c==="function_call_output"){x(e,r,n,c,o,i,"function_call_output",u,a,f,void 0,t.output,{callId:t.call_id,completed:!0});return}if(c==="custom_tool_call"){const s=typeof t.name=="string"?t.name:"custom_tool_call",l=t.input!==void 0?{input:t.input}:void 0;x(e,r,n,c,o,i,s,u,a,f,l,void 0,{callId:t.call_id});return}if(c==="custom_tool_call_output"){const s=typeof t.name=="string"?t.name:"custom_tool_call_output",l=t.output??t.result??t.content;x(e,r,n,c,o,i,s,u,a,f,void 0,l,{callId:t.call_id,completed:!0});return}if(c==="web_search_call"){const s=typeof t.action=="object"&&t.action!==null?t.action:null;x(e,r,n,c,o,i,"web_search",u,a,f,s??t.query);return}}}function at(e,r,n,t,o,i,u,a,f){const c=typeof t.type=="string"?t.type:"";if(c){if(c==="user_message"){const s=L(t);if(!s)return;v(e,r,n,c,o,i,s.payload,u,a,f,"user",!1,s.repairHint);return}if(c==="agent_message"){const s=typeof t.message=="string"?h(t.message):"";if(!s||M(s))return;v(e,r,n,c,o,i,s,u,a,f);return}if(c==="turn_aborted"||c==="error"){const s=typeof t.message=="string"?h(t.message):typeof t.error=="string"?h(t.error):"";if(!s)return;v(e,r,n,c,o,i,s,u,a,f,"agent",!0);return}if(ot(c)){v(e,r,n,c,o,i,it(t),u,a,f,"agent");return}if(c==="exec_command_end"){const s=Array.isArray(t.command)?t.command:t.parsed_cmd??t.command,l=t.exit_code??t.exitCode,m=[typeof t.aggregated_output=="string"?t.aggregated_output:"",l!=null?`
6
- (exit ${String(l)})`:""].join("");x(e,r,n,c,o,i,"command_execution",u,a,f,{command:s},m);return}if(c==="patch_apply_end"){x(e,r,n,c,o,i,"apply_patch",u,a,f,t.changes,{success:t.success,stdout:t.stdout,stderr:t.stderr});return}if(c==="mcp_tool_call_end"){const s=typeof t.invocation=="object"&&t.invocation!==null?t.invocation:null,l=typeof s?.tool=="string"?s.tool:"mcp_tool_call",m={server:s?.server,...typeof s?.arguments=="object"&&s.arguments!==null?s.arguments:{}};x(e,r,n,c,o,i,l,u,a,f,m,t.result);return}if(c==="dynamic_tool_call_request"){const s=typeof t.tool=="string"?t.tool:"dynamic_tool_call";x(e,r,n,c,o,i,s,u,a,f,t.arguments,void 0,{callId:t.callId??t.call_id});return}if(c==="dynamic_tool_call_response"){const s=typeof t.tool=="string"?t.tool:"dynamic_tool_call";x(e,r,n,c,o,i,s,u,a,f,void 0,t.result??t.output,{callId:t.callId??t.call_id,completed:!0});return}if(c==="web_search_end"){const s=typeof t.action=="object"&&t.action!==null?t.action:null;x(e,r,n,c,o,i,"web_search",u,a,f,s??t.query,t.query);return}if(c==="image_generation_end"){const s=typeof t.saved_path=="string"?t.saved_path.trim():"";if(!s)return;v(e,r,n,c,o,i,D(s),u,a,f);return}c==="view_image_tool_call"&&x(e,r,n,c,o,i,"view_image",u,a,f,t.path??t.image_path??t)}}function E(e=!1){return{sourceSessionKey:"",workDir:"",modelId:null,title:"",skipImport:e}}function V(e){if((typeof e.thread_source=="string"?e.thread_source.trim().toLowerCase():"")==="subagent")return!0;const n=typeof e.source=="object"&&e.source!==null?e.source:null;if(n&&typeof n.subagent=="object"&&n.subagent!==null)return!0;const t=typeof e.parent_thread_id=="string"&&e.parent_thread_id.trim().length>0,o=typeof e.agent_nickname=="string"||typeof e.agent_role=="string"||typeof e.multi_agent_version=="string";return t&&o}function ft(e){const r=j.openSync(e,"r");try{const n=[];let t=0,o="";for(;t<1024*1024;){const f=Buffer.alloc(16384),c=j.readSync(r,f,0,f.length,t);if(c<=0)break;const s=f.subarray(0,c);n.push(s),t+=c;const l=Buffer.concat(n),m=l.indexOf(10);if(m>=0){o=l.subarray(0,m).toString("utf8");break}}!o&&n.length>0&&(o=Buffer.concat(n).toString("utf8"));const i=k(o);if(!i||i.type!=="session_meta")return E();const u=typeof i.payload=="object"&&i.payload!==null?i.payload:null;if(!u)return E();if(V(u))return E(!0);const a=typeof u.id=="string"?u.id:"";return{sourceSessionKey:a,workDir:typeof u.cwd=="string"?u.cwd:"",modelId:X(u),title:Y(a)??"",skipImport:!1}}finally{j.closeSync(r)}return E()}function X(e){return(typeof e.model=="string"?e.model.trim():"")||null}function lt(e,r){if((typeof e.id=="string"?e.id:typeof e.thread_id=="string"?e.thread_id:typeof e.session_id=="string"?e.session_id:"")!==r)return null;const o=(typeof e.thread_name=="string"?e.thread_name:typeof e.title=="string"?e.title:"").trim();return o?o.slice(0,120):null}function Y(e){if(!e)return null;const r=I.join($.homedir(),".codex","session_index.jsonl");if(!j.existsSync(r))return null;let n=null;return F(r,0,t=>{if(!t.trim())return;const o=k(t);if(!o)return;const i=lt(o,e);i&&(n=i)}),n}function ht(){const e=[I.join($.homedir(),".codex","sessions"),I.join($.homedir(),".codex","archived_sessions")],r=[],n=t=>{for(const o of j.readdirSync(t,{withFileTypes:!0})){const i=I.join(t,o.name);o.isDirectory()?n(i):o.isFile()&&o.name.endsWith(".jsonl")&&r.push(i)}};for(const t of e)j.existsSync(t)&&n(t);return[...new Set(r)].sort()}function yt(e,r){const n=[],t=ft(e);let{sourceSessionKey:o,workDir:i,modelId:u,title:a,skipImport:f}=t,c=t.title;if(f)return{nextOffset:j.statSync(e).size,events:[]};let s=!1;const l=F(e,r,(m,A)=>{const y=k(m);if(!y)return;const T=typeof y.type=="string"?y.type:"",p=typeof y.payload=="object"&&y.payload!==null?y.payload:null,b=tt(y.timestamp);if(!(!p||!b)){if(T==="session_meta"){if(V(p)){n.length=0,f=!0;return}o=typeof p.id=="string"?p.id:o,i=typeof p.cwd=="string"?p.cwd:i,u=X(p)??u;const g=Y(o);g&&(c=g,a=g);return}if(!f&&o){if(T==="response_item"){const g=J(p);g?.role==="user"&&g.titleText&&!a&&(a=g.titleText.slice(0,80)),ut(n,e,A,p,o,b,a,u,i);return}if(T==="event_msg"){const g=typeof p.type=="string"?p.type:"";if(rt(g)){let d=!1;for(let _=n.length-1;_>=0;_-=1){const C=n[_];if(C?.agentType==="codex"&&C.role==="agent"&&!q(C.payload)){C.terminal=!0,d=!0,s=!1;break}}if(!d)for(let _=n.length-1;_>=0;_-=1){const C=n[_];if(!(C?.agentType!=="codex"||C.role!=="agent")){C.terminal=!0,d=!0,s=!1;break}}d||(s=!0);return}if(g==="user_message"){const d=L(p);if(d?.titleText&&!a&&(a=d.titleText.slice(0,80)),d){const _=R(n,"user",d.payload,b);_>=0&&n.splice(_,1)}}else if(g==="agent_message"){const d=typeof p.message=="string"?h(p.message):"";if(d&&!M(d)){const _=R(n,"agent",d,b);_>=0&&n.splice(_,1)}}const S=n.length;at(n,e,A,p,o,b,a,u,i),s&&n.length>S&&(n[n.length-1].terminal=!0,s=!1)}}}});for(const m of n)m.titleSource=c&&m.title===c?"agent_native":"first_user_fallback";return{nextOffset:l,events:n}}export{ht as listCodexRolloutFiles,Y as lookupCodexThreadName,yt as parseCodexRolloutChunk};
5
+ `)):""}function ct(t){if(!Array.isArray(t))return[];const r=[];for(const n of t){if(typeof n!="object"||n===null)continue;const e=n;if(e.type!=="input_image")continue;const o=typeof e.path=="string"?e.path:typeof e.file_path=="string"?e.file_path:typeof e.saved_path=="string"?e.saved_path:typeof e.image_path=="string"?e.image_path:"";o.trim()&&r.push({path:o,name:I.basename(o)||"image.png",mimeType:N(o),kind:"image"})}return r}function J(t){if(t.type!=="message")return null;const r=t.role==="assistant"?"agent":t.role==="user"?"user":null;if(!r)return null;if(r==="agent"){const i=G(t.content,"output_text");return M(i)?null:i?{role:r,payload:i,titleText:i}:null}const n=F(G(t.content,"input_text")),e=n.text,o=ct(t.content);return!e&&o.length===0||M(e)&&o.length===0||L(e)&&o.length===0?null:{role:r,payload:o.length>0?k(e,o):e,titleText:e,repairHint:n.strippedWrapper?"codex_app_context_wrapper":void 0}}function X(t){if(!t)return"";try{const r=JSON.parse(t);if(typeof r=="object"&&r!==null){const n=r;if(n.type==="user"&&typeof n.content=="string")return h(n.content)}}catch{}return h(t)}function ut(t,r,n,e){return t.agentType!=="codex"||t.role!==r||W(t.payload)||Math.abs(t.ts-e)>300*1e3?!1:X(t.payload)===X(n)}function $(t,r,n,e){for(let o=t.length-1;o>=0;o-=1){const i=t[o];if(i){if(ut(i,r,n,e))return o;if(i.agentType==="codex"&&Math.abs(i.ts-e)>300*1e3)break}}return-1}function v(t,r,n,e,o,i,u,a,f,c,s="agent",l=!1,m){u&&t.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:H(r,n,e),cursor:q(r,n),role:s,ts:i,payload:u,title:a,modelId:f,workDir:c,terminal:l,repairHint:m})}function x(t,r,n,e,o,i,u,a,f,c,s,l,m){const A=H(r,n,e),y=typeof m?.callId=="string"&&m.callId.trim()?m.callId.trim():null,T=y?Z("sha256").update(`${o}\0${y}`).digest("hex").slice(0,32):null,p=T?`tool:${T}`:void 0,C=T?`native:tool:${T}`:`native:${A}`,g=m?.completed&&T?2:1,E=l!==void 0?"completed":"running";t.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:A,cursor:q(r,n),role:"agent",ts:i,payload:K({name:u,toolCallId:C,detailRevision:g,status:E}),title:a,modelId:f,workDir:c,...p?{canonicalMessageKey:p,canonicalMutation:m?.completed?"upsert":"append"}:{},localToolDetail:{toolCallId:C,detailRevision:g,name:u,...s!==void 0?{args:s}:{},...l!==void 0?{result:l}:{},status:E}})}function at(t,r,n,e,o,i,u,a,f){const c=typeof e.type=="string"?e.type:"";if(c){if(c==="message"){const s=J(e);if(!s||$(t,s.role,s.payload,i)>=0)return;v(t,r,n,`${c}:${s.role}`,o,i,s.payload,u,a,f,s.role,!1,s.repairHint);return}if(c==="function_call"){const s=typeof e.name=="string"?e.name:"function_call";x(t,r,n,c,o,i,s,u,a,f,O(e.arguments),void 0,{callId:e.call_id});return}if(c==="function_call_output"){x(t,r,n,c,o,i,"function_call_output",u,a,f,void 0,e.output,{callId:e.call_id,completed:!0});return}if(c==="custom_tool_call"){const s=typeof e.name=="string"?e.name:"custom_tool_call",l=e.input!==void 0?{input:e.input}:void 0;x(t,r,n,c,o,i,s,u,a,f,l,void 0,{callId:e.call_id});return}if(c==="custom_tool_call_output"){const s=typeof e.name=="string"?e.name:"custom_tool_call_output",l=e.output??e.result??e.content;x(t,r,n,c,o,i,s,u,a,f,void 0,l,{callId:e.call_id,completed:!0});return}if(c==="web_search_call"){const s=typeof e.action=="object"&&e.action!==null?e.action:null;x(t,r,n,c,o,i,"web_search",u,a,f,s??e.query);return}}}function ft(t,r,n,e,o,i,u,a,f){const c=typeof e.type=="string"?e.type:"";if(c){if(c==="user_message"){const s=B(e);if(!s)return;v(t,r,n,c,o,i,s.payload,u,a,f,"user",!1,s.repairHint);return}if(c==="agent_message"){const s=typeof e.message=="string"?h(e.message):"";if(!s||M(s))return;v(t,r,n,c,o,i,s,u,a,f);return}if(c==="turn_aborted"||c==="error"){const s=typeof e.message=="string"?h(e.message):typeof e.error=="string"?h(e.error):"";if(!s)return;v(t,r,n,c,o,i,s,u,a,f,"agent",!0);return}if(it(c)){v(t,r,n,c,o,i,st(e),u,a,f,"agent");return}if(c==="exec_command_end"){const s=Array.isArray(e.command)?e.command:e.parsed_cmd??e.command,l=e.exit_code??e.exitCode,m=[typeof e.aggregated_output=="string"?e.aggregated_output:"",l!=null?`
6
+ (exit ${String(l)})`:""].join("");x(t,r,n,c,o,i,"command_execution",u,a,f,{command:s},m);return}if(c==="patch_apply_end"){x(t,r,n,c,o,i,"apply_patch",u,a,f,e.changes,{success:e.success,stdout:e.stdout,stderr:e.stderr});return}if(c==="mcp_tool_call_end"){const s=typeof e.invocation=="object"&&e.invocation!==null?e.invocation:null,l=typeof s?.tool=="string"?s.tool:"mcp_tool_call",m={server:s?.server,...typeof s?.arguments=="object"&&s.arguments!==null?s.arguments:{}};x(t,r,n,c,o,i,l,u,a,f,m,e.result);return}if(c==="dynamic_tool_call_request"){const s=typeof e.tool=="string"?e.tool:"dynamic_tool_call";x(t,r,n,c,o,i,s,u,a,f,e.arguments,void 0,{callId:e.callId??e.call_id});return}if(c==="dynamic_tool_call_response"){const s=typeof e.tool=="string"?e.tool:"dynamic_tool_call";x(t,r,n,c,o,i,s,u,a,f,void 0,e.result??e.output,{callId:e.callId??e.call_id,completed:!0});return}if(c==="web_search_end"){const s=typeof e.action=="object"&&e.action!==null?e.action:null;x(t,r,n,c,o,i,"web_search",u,a,f,s??e.query,e.query);return}if(c==="image_generation_end"){const s=typeof e.saved_path=="string"?e.saved_path.trim():"";if(!s)return;v(t,r,n,c,o,i,D(s),u,a,f);return}c==="view_image_tool_call"&&x(t,r,n,c,o,i,"view_image",u,a,f,e.path??e.image_path??e)}}function S(t=!1){return{sourceSessionKey:"",workDir:"",modelId:null,title:"",skipImport:t}}function Q(t){if((typeof t.thread_source=="string"?t.thread_source.trim().toLowerCase():"")==="subagent")return!0;const n=typeof t.source=="object"&&t.source!==null?t.source:null;if(n&&typeof n.subagent=="object"&&n.subagent!==null)return!0;const e=typeof t.parent_thread_id=="string"&&t.parent_thread_id.trim().length>0,o=typeof t.agent_nickname=="string"||typeof t.agent_role=="string"||typeof t.multi_agent_version=="string";return e&&o}function lt(t){const r=j.openSync(t,"r");try{const n=[];let e=0,o="";for(;e<1024*1024;){const f=Buffer.alloc(16384),c=j.readSync(r,f,0,f.length,e);if(c<=0)break;const s=f.subarray(0,c);n.push(s),e+=c;const l=Buffer.concat(n),m=l.indexOf(10);if(m>=0){o=l.subarray(0,m).toString("utf8");break}}!o&&n.length>0&&(o=Buffer.concat(n).toString("utf8"));const i=R(o);if(!i||i.type!=="session_meta")return S();const u=typeof i.payload=="object"&&i.payload!==null?i.payload:null;if(!u)return S();if(Q(u))return S(!0);const a=typeof u.id=="string"?u.id:"";return{sourceSessionKey:a,workDir:typeof u.cwd=="string"?u.cwd:"",modelId:V(u),title:Y(a)??"",skipImport:!1}}finally{j.closeSync(r)}return S()}function V(t){return(typeof t.model=="string"?t.model.trim():"")||null}function mt(t,r){if((typeof t.id=="string"?t.id:typeof t.thread_id=="string"?t.thread_id:typeof t.session_id=="string"?t.session_id:"")!==r)return null;const o=(typeof t.thread_name=="string"?t.thread_name:typeof t.title=="string"?t.title:"").trim();return o&&!pt(o)?o.slice(0,120):null}function pt(t){const r=t.trim().toLocaleLowerCase().replace(/[\s_-]+/g," ");return et.has(r)}function Y(t){if(!t)return null;const r=I.join(w.homedir(),".codex","session_index.jsonl");if(!j.existsSync(r))return null;let n=null;return U(r,0,e=>{if(!e.trim())return;const o=R(e);if(!o)return;const i=mt(o,t);i&&(n=i)}),n}function Tt(){const t=[I.join(w.homedir(),".codex","sessions"),I.join(w.homedir(),".codex","archived_sessions")],r=[],n=e=>{for(const o of j.readdirSync(e,{withFileTypes:!0})){const i=I.join(e,o.name);o.isDirectory()?n(i):o.isFile()&&o.name.endsWith(".jsonl")&&r.push(i)}};for(const e of t)j.existsSync(e)&&n(e);return[...new Set(r)].sort()}function Ct(t,r){const n=[],e=lt(t);let{sourceSessionKey:o,workDir:i,modelId:u,title:a,skipImport:f}=e,c=e.title;if(f)return{nextOffset:j.statSync(t).size,events:[]};let s=!1;const l=U(t,r,(m,A)=>{const y=R(m);if(!y)return;const T=typeof y.type=="string"?y.type:"",p=typeof y.payload=="object"&&y.payload!==null?y.payload:null,C=tt(y.timestamp);if(!(!p||!C)){if(T==="session_meta"){if(Q(p)){n.length=0,f=!0;return}o=typeof p.id=="string"?p.id:o,i=typeof p.cwd=="string"?p.cwd:i,u=V(p)??u;const g=Y(o);g&&(c=g,a=g);return}if(!f&&o){if(T==="response_item"){const g=J(p);g?.role==="user"&&g.titleText&&!a&&(a=g.titleText.slice(0,80)),at(n,t,A,p,o,C,a,u,i);return}if(T==="event_msg"){const g=typeof p.type=="string"?p.type:"";if(ot(g)){let d=!1;for(let _=n.length-1;_>=0;_-=1){const b=n[_];if(b?.agentType==="codex"&&b.role==="agent"&&!W(b.payload)){b.terminal=!0,d=!0,s=!1;break}}if(!d)for(let _=n.length-1;_>=0;_-=1){const b=n[_];if(!(b?.agentType!=="codex"||b.role!=="agent")){b.terminal=!0,d=!0,s=!1;break}}d||(s=!0);return}if(g==="user_message"){const d=B(p);if(d?.titleText&&!a&&(a=d.titleText.slice(0,80)),d){const _=$(n,"user",d.payload,C);_>=0&&n.splice(_,1)}}else if(g==="agent_message"){const d=typeof p.message=="string"?h(p.message):"";if(d&&!M(d)){const _=$(n,"agent",d,C);_>=0&&n.splice(_,1)}}const E=n.length;ft(n,t,A,p,o,C,a,u,i),s&&n.length>E&&(n[n.length-1].terminal=!0,s=!1)}}}});for(const m of n)m.titleSource=c&&m.title===c?"agent_native":"first_user_fallback";return{nextOffset:l,events:n}}export{Tt as listCodexRolloutFiles,Y as lookupCodexThreadName,Ct as parseCodexRolloutChunk};
@@ -1,5 +1,5 @@
1
- import c from"node:fs";import{randomUUID as p}from"node:crypto";import{buildUserMessagePayload as R}from"@shennian/wire";import{mergeProjectedSessions as T}from"./projection.js";import{parsePersonalAttachmentReferences as m}from"./attachment-reference.js";import{assertFinishedAttachmentReferences as S,markAttachmentReferences as k}from"./attachment-transfer-store.js";import{resolvePersonalSyncV1Path as q}from"../personal-sync/paths.js";import{appendMessage as b,getMessageDeliveryStatus as v,recordSession as E,tombstoneMessage as P,upsertMessage as w}from"./store.js";import{requestSessionIndexPublish as y}from"./index-publisher.js";function A(){return{sessions:{}}}function I(){return new Date().toISOString()}function $(s){return`enqueue-send-${s}-${p()}`}function l(){try{const s=JSON.parse(c.readFileSync(D(),"utf-8"));return{sessions:s.sessions&&typeof s.sessions=="object"?s.sessions:{}}}catch(s){if(s.code==="ENOENT"||s instanceof Error&&s.message.startsWith("ENOENT:"))return A();throw s}}function h(s){const e=q();c.mkdirSync(e,{recursive:!0,mode:448});const n=D(),t=`${n}.tmp-${process.pid}-${p()}`;try{c.writeFileSync(t,`${JSON.stringify(s,null,2)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"});const i=c.openSync(t,"r");if(typeof i=="number")try{c.fsyncSync(i)}finally{c.closeSync(i)}c.renameSync(t,n)}finally{try{c.unlinkSync(t)}catch{}}}function D(){return q("outbound-queue.json")}function Q(s){const e=I();return{id:s.queueMessageId||s.clientMessageId||`queue-${p()}`,sessionId:s.sessionId,text:s.text,agentType:s.agentType,sessionMode:s.sessionMode,managerConfig:s.managerConfig,workDir:s.workDir,agentSessionId:s.agentSessionId??null,modelId:s.modelId??null,systemPrompt:s.systemPrompt??null,managerDefaultWorkerAgentType:s.managerDefaultWorkerAgentType??null,managerDefaultWorkerModelId:s.managerDefaultWorkerModelId??null,reasoningEffort:s.reasoningEffort??null,clientMessageId:s.clientMessageId??null,attachments:m(s.attachments),externalChannel:s.externalChannel??null,replyTarget:s.replyTarget??null,origin:s.origin,createdAt:e,updatedAt:e}}function M(s){return{id:s.clientMessageId??s.id,sessionId:s.sessionId,role:"user",ts:Date.parse(s.createdAt),payload:R(s.text,s.attachments)}}class H{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:l().sessions[e]??[]}}async handleEnqueue(e){const n=this.opts.getRuntime(),t=e.params;if(T(t.sessionListProjection),!t.sessionId||!t.text||!t.agentType||!t.workDir){n.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId, text, agentType and workDir are required"});return}const i=n.resolvePath(t.workDir),o=m(t.attachments);o?.length&&S(i,o);const r={text:t.text,attachments:o,localized:!1},d=await this.isSessionBusy(t.sessionId),u=l(),f=u.sessions[t.sessionId]??[];if(!d&&!f.length){await this.opts.dispatchReq({...e,id:$(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 a=Q({...t,text:r.text,attachments:r.attachments}),g=t.origin==="external"?C(f,a):null;g||(u.sessions[t.sessionId]=[...f,a],h(u),E({sessionId:a.sessionId,agentType:a.agentType,sessionMode:a.sessionMode,managerConfig:a.managerConfig,workDir:a.workDir,agentSessionId:a.agentSessionId,modelId:a.modelId}),b(a.sessionId,M(a),"queued"),k(i,a.attachments??[]),y(n.client)),this.broadcast(t.sessionId),n.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queued:!0,queueMessageId:g?.id??a.id,...v(t.sessionId,g?.clientMessageId??g?.id??a.clientMessageId??a.id),queue:this.getSnapshot(t.sessionId),...r.localized?{localizedAttachments:!0}:{}}}),d||this.drainNext(t.sessionId)}async handleGet(e){const n=this.opts.getRuntime(),t=e.params;if(!t.sessionId){n.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId is required"});return}n.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 n=this.opts.getRuntime(),t=e.params;if(!t.sessionId||!t.queueMessageId||!t.text){n.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId, queueMessageId and text are required"});return}const i=l(),o=i.sessions[t.sessionId]??[],r=o.findIndex(f=>f.id===t.queueMessageId);if(r<0){n.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}const d=m(t.attachments),u=n.resolvePath(o[r].workDir);d?.length&&S(u,d),o[r]={...o[r],text:t.text,attachments:d,updatedAt:I()},i.sessions[t.sessionId]=o,h(i),w(t.sessionId,M(o[r]),"queued"),o[r].attachments?.length&&k(u,o[r].attachments??[]),y(n.client),this.broadcast(t.sessionId),n.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}})}async handleDelete(e){const n=this.opts.getRuntime(),t=e.params;if(!t.sessionId||!t.queueMessageId){n.client.sendRes({type:"res",id:e.id,ok:!1,error:"sessionId and queueMessageId are required"});return}const i=l(),o=i.sessions[t.sessionId]??[],r=o.find(u=>u.id===t.queueMessageId),d=o.filter(u=>u.id!==t.queueMessageId);if(d.length===o.length){n.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}d.length?i.sessions[t.sessionId]=d:delete i.sessions[t.sessionId],h(i),P(t.sessionId,r?.clientMessageId??r?.id??t.queueMessageId),y(n.client),this.broadcast(t.sessionId),n.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queue:this.getSnapshot(t.sessionId)}})}noteTerminal(e){this.drainNext(e)}purgeSession(e){const n=l();n.sessions[e]&&(delete n.sessions[e],h(n),this.draining.delete(e))}drainIdleQueues(){const e=l();for(const n of Object.keys(e.sessions))this.drainNext(n)}async drainNext(e){if(this.draining.has(e)||await this.isSessionBusy(e))return;const i=(l().sessions[e]??[])[0];if(!i){this.broadcast(e);return}const o=i;this.draining.add(e);try{w(e,M(o),"queued"),await this.dispatchQueuedMessage(o);const r=l(),d=(r.sessions[e]??[]).filter(u=>u.id!==i.id);d.length?r.sessions[e]=d:delete r.sessions[e],h(r),this.broadcast(e)}finally{this.draining.delete(e)}}mergeExternalMessages(e,n){const t=[e];for(;n[0]?.origin==="external";)t.push(n.shift());const i=W(t);return i.length===1?i[0]:{...e,id:`external-batch-${e.id}`,text:i.map(o=>o.text).filter(Boolean).join(`
1
+ import l from"node:fs";import{randomUUID as y}from"node:crypto";import{buildUserMessagePayload as A}from"@shennian/wire";import{mergeProjectedSessions as E}from"./projection.js";import{parsePersonalAttachmentReferences as I}from"./attachment-reference.js";import{assertFinishedAttachmentReferences as D,markAttachmentReferences as w}from"./attachment-transfer-store.js";import{resolvePersonalSyncV1Path as R}from"../personal-sync/paths.js";import{appendMessage as $,getMessageDeliveryStatus as T,recordSession as Q,tombstoneMessage as W,upsertMessage as b}from"./store.js";import{requestSessionIndexPublish as M}from"./index-publisher.js";function C(){return{sessions:{}}}function x(){return new Date().toISOString()}function N(n){return`enqueue-send-${n}-${y()}`}function f(){try{const n=JSON.parse(l.readFileSync(v(),"utf-8"));return{sessions:n.sessions&&typeof n.sessions=="object"?n.sessions:{}}}catch(n){if(n.code==="ENOENT"||n instanceof Error&&n.message.startsWith("ENOENT:"))return C();throw n}}function p(n){const e=R();l.mkdirSync(e,{recursive:!0,mode:448});const s=v(),t=`${s}.tmp-${process.pid}-${y()}`;try{l.writeFileSync(t,`${JSON.stringify(n,null,2)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"});const i=l.openSync(t,"r");if(typeof i=="number")try{l.fsyncSync(i)}finally{l.closeSync(i)}l.renameSync(t,s)}finally{try{l.unlinkSync(t)}catch{}}}function v(){return R("outbound-queue.json")}function B(n){const e=x();return{id:n.queueMessageId||n.clientMessageId||`queue-${y()}`,sessionId:n.sessionId,text:n.text,agentType:n.agentType,sessionMode:n.sessionMode,managerConfig:n.managerConfig,workDir:n.workDir,agentSessionId:n.agentSessionId??null,modelId:n.modelId??null,systemPrompt:n.systemPrompt??null,managerDefaultWorkerAgentType:n.managerDefaultWorkerAgentType??null,managerDefaultWorkerModelId:n.managerDefaultWorkerModelId??null,reasoningEffort:n.reasoningEffort??null,clientMessageId:n.clientMessageId??null,attachments:I(n.attachments),externalChannel:n.externalChannel??null,replyTarget:n.replyTarget??null,origin:n.origin,createdAt:e,updatedAt:e}}function S(n){return{id:n.clientMessageId??n.id,sessionId:n.sessionId,role:"user",ts:Date.parse(n.createdAt),payload:A(n.text,n.attachments)}}class Y{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:f().sessions[e]??[]}}async handleEnqueue(e){const s=this.opts.getRuntime(),t=e.params;if(E(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=s.resolvePath(t.workDir),o=I(t.attachments);o?.length&&D(i,o);const r={text:t.text,attachments:o,localized:!1},a=await this.isSessionBusy(t.sessionId),d=f(),h=d.sessions[t.sessionId]??[];if(!a&&!h.length){await this.opts.dispatchReq({...e,id:N(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 c=B({...t,text:r.text,attachments:r.attachments}),P=c.clientMessageId??c.id,m=T(t.sessionId,P);if(m.state!=="not_found"){s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queued:m.state==="queued",queueMessageId:c.id,...m,queue:this.getSnapshot(t.sessionId)}});return}const g=z(h,c);g||(d.sessions[t.sessionId]=[...h,c],p(d));const u=g??c;Q({sessionId:u.sessionId,agentType:u.agentType,sessionMode:u.sessionMode,managerConfig:u.managerConfig,workDir:u.workDir,agentSessionId:u.agentSessionId,modelId:u.modelId}),$(u.sessionId,S(u),"queued"),w(s.resolvePath(u.workDir),u.attachments??[]),M(s.client),this.broadcast(t.sessionId),s.client.sendRes({type:"res",id:e.id,ok:!0,payload:{queued:!0,queueMessageId:g?.id??c.id,...T(t.sessionId,g?.clientMessageId??g?.id??c.clientMessageId??c.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=f(),o=i.sessions[t.sessionId]??[],r=o.findIndex(h=>h.id===t.queueMessageId);if(r<0){s.client.sendRes({type:"res",id:e.id,ok:!1,error:"Queued message not found"});return}const a=I(t.attachments),d=s.resolvePath(o[r].workDir);a?.length&&D(d,a),o[r]={...o[r],text:t.text,attachments:a,updatedAt:x()},i.sessions[t.sessionId]=o,p(i),b(t.sessionId,S(o[r]),"queued"),o[r].attachments?.length&&w(d,o[r].attachments??[]),M(s.client),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=f(),o=i.sessions[t.sessionId]??[],r=o.find(d=>d.id===t.queueMessageId),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?i.sessions[t.sessionId]=a:delete i.sessions[t.sessionId],p(i),W(t.sessionId,r?.clientMessageId??r?.id??t.queueMessageId),M(s.client),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)}purgeSession(e){const s=f();s.sessions[e]&&(delete s.sessions[e],p(s),this.draining.delete(e))}drainIdleQueues(){const e=f();for(const s of Object.keys(e.sessions))this.drainNext(s)}async drainNext(e){if(this.draining.has(e)||await this.isSessionBusy(e))return;const i=(f().sessions[e]??[])[0];if(!i){this.broadcast(e);return}const o=i;this.draining.add(e);try{b(e,S(o),"queued"),await this.dispatchQueuedMessage(o);const r=f(),a=(r.sessions[e]??[]).filter(d=>d.id!==i.id);a.length?r.sessions[e]=a:delete r.sessions[e],p(r),this.broadcast(e)}finally{this.draining.delete(e)}}mergeExternalMessages(e,s){const t=[e];for(;s[0]?.origin==="external";)t.push(s.shift());const i=j(t);return i.length===1?i[0]:{...e,id:`external-batch-${e.id}`,text:i.map(o=>o.text).filter(Boolean).join(`
3
3
 
4
- `),attachments:B(i.flatMap(o=>o.attachments??[])),updatedAt:I()}}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,sessionMode:e.sessionMode,managerConfig:e.managerConfig,workDir:e.workDir,agentSessionId:e.agentSessionId??null,modelId:e.modelId??void 0,systemPrompt:e.systemPrompt??null,managerDefaultWorkerAgentType:e.managerDefaultWorkerAgentType,managerDefaultWorkerModelId:e.managerDefaultWorkerModelId,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 n=this.opts.getRuntime().sessions.get(e);if(!n)return!1;if(n.currentRunId)return!0;if(!n.adapter.getStatus)return!1;const t=await n.adapter.getStatus().catch(()=>null);return t?.active?(t.runId&&(n.currentRunId=t.runId,n.currentRunPhase=t.runPhase??n.currentRunPhase),!0):!1}broadcast(e){this.opts.getRuntime().client.sendEvent({type:"event",event:"session.queue.update",payload:{queue:this.getSnapshot(e)}})}}function W(s){const e=new Set,n=[];for(const t of s){const i=x(t);e.has(i)||(e.add(i),n.push(t))}return n}function C(s,e){const n=x(e);return s.find(t=>x(t)===n)??null}function x(s){const e=N(s);return e?`id:${e}`:["body",j(s.text),...(s.attachments??[]).map(n=>n.path||`${n.name}:${n.mimeType}`)].join(`
5
- `)}function N(s){const e=typeof s.clientMessageId=="string"?s.clientMessageId.trim():"";if(e)return e;const n=typeof s.id=="string"?s.id.trim():"";return n&&!n.startsWith("queue-")?n:""}function B(s){const e=new Set,n=[];for(const t of s){const i=t.path||`${t.name}:${t.mimeType}`;e.has(i)||(e.add(i),n.push(t))}return n.length?n:void 0}function j(s){return String(s||"").replace(/\s+/g," ").trim()}export{H as ChatQueueManager};
4
+ `),attachments:F(i.flatMap(o=>o.attachments??[])),updatedAt:x()}}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,sessionMode:e.sessionMode,managerConfig:e.managerConfig,workDir:e.workDir,agentSessionId:e.agentSessionId??null,modelId:e.modelId??void 0,systemPrompt:e.systemPrompt??null,managerDefaultWorkerAgentType:e.managerDefaultWorkerAgentType,managerDefaultWorkerModelId:e.managerDefaultWorkerModelId,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 j(n){const e=new Set,s=[];for(const t of n){const i=k(t);e.has(i)||(e.add(i),s.push(t))}return s}function z(n,e){const s=q(e);if(s)return n.find(i=>q(i)===s)??null;if(e.origin!=="external")return null;const t=k(e);return n.find(i=>k(i)===t)??null}function k(n){const e=q(n);return e?`id:${e}`:["body",O(n.text),...(n.attachments??[]).map(s=>s.path||`${s.name}:${s.mimeType}`)].join(`
5
+ `)}function q(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 F(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 O(n){return String(n||"").replace(/\s+/g," ").trim()}export{Y as ChatQueueManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shennian",
3
- "version": "0.3.52",
3
+ "version": "0.3.54",
4
4
  "description": "Shennian — AI Agent Control Plane CLI",
5
5
  "type": "module",
6
6
  "bin": {