@leviyuan/lodestar 0.21.6 → 0.21.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,7 +42,7 @@ lodestar-setup
42
42
 
43
43
  - [多模型协作](docs/usage.md#多模型任务):Lodestar Agent 支持多模型并发与后续追问;不支持 Claude 订阅,遵守 Claude 用户协议,中转站等第三方 Claude 模型仍可调用。
44
44
  - [飞书任务清单](docs/usage.md#飞书任务清单):在项目群创建、绑定和删除任务清单。
45
- - [脚本通知](docs/usage.md#本机通知):让本机脚本向群里推送通知,支持图片、交互按钮和文字回复。
45
+ - [脚本通知](docs/usage.md#本机通知):让本机脚本向项目绑定的对话推送通知,支持图片、交互按钮和文字回复。
46
46
 
47
47
  ## 详细文档
48
48
 
package/dist/lodestar.js CHANGED
@@ -79,7 +79,7 @@ ${F.bold}启动 daemon...${F.reset}`);let z=await Vz(),H=process.platform==="win
79
79
  `))>=0){let J=this.stdoutBuf.slice(0,Z).trim();if(this.stdoutBuf=this.stdoutBuf.slice(Z+1),!J)continue;let Q;try{Q=JSON.parse(J)}catch(Y){j(`codex-process: bad json: ${J.slice(0,200)} (${Y})`);continue}try{this.handleMessage(Q)}catch(Y){j(`codex-process: dispatch error: ${JSON.stringify(Q).slice(0,200)} (${Y})`)}}}flushStdoutTail(){if(!this.stdoutBuf)return;this.onStdout(Buffer.from(`
80
80
  `))}onStderr($){this.stderrBuf+=$.toString();let Z;while((Z=this.stderrBuf.indexOf(`
81
81
  `))>=0){let J=this.stderrBuf.slice(0,Z);if(this.stderrBuf=this.stderrBuf.slice(Z+1),J.trim())j(`codex-process[stderr]: ${J}`)}}flushStderrTail(){let $=this.stderrBuf;if(this.stderrBuf="",$.trim())j(`codex-process[stderr]: ${$}`)}handleMessage($){if(Object.prototype.hasOwnProperty.call($,"id")&&!$.method){let J=this.pending.get($.id);if(!J){j(`codex-process: response for unknown id=${$.id}`);return}if(this.pending.delete($.id),clearTimeout(J.timeout),$.error){let Q=typeof $.error?.code==="number"?$.error.code:null,Y=typeof $.error==="string"?$.error:typeof $.error?.message==="string"?$.error.message:JSON.stringify($.error);J.reject(new L2(J.method,$.id,Q,Y,$.error?.data))}else J.resolve($.result);return}if(Object.prototype.hasOwnProperty.call($,"id")&&$.method){this.handleServerRequest($);return}if($.method){this.handleNotification($.method,$.params??{});return}let Z=_5($);if(Z){let J=this.withSessionId(Z);B5(Z.sourceMethod??"raw_message",$,J),this.emit("context_compacted",J);return}V$("RAW_MESSAGE",$),this.emit("raw",$)}handleNotification($,Z){if(this.isSubagentThread(Z)){if($==="thread/status/changed")this.handleThreadStatusChanged(Z);else if($==="item/started")this.handleSubagentItemStarted(Z);else if($==="item/completed")this.handleSubagentItemCompleted(Z);return}let J=j5($,Z);if(J){let Q=this.withSessionId(J);B5($,Z,Q),this.emit("context_compacted",Q);return}switch($){case"thread/started":{let Q=Z.thread;if(Q?.id)this.sessionId=Q.id;return}case"thread/settings/updated":{let Q=Z.threadSettings;if(typeof Q?.model==="string")this.lastModel=Q.model;if(U$(Q?.effort))this.lastEffort=Q.effort;if(Q?.collaborationMode)this.usesCustomDefaultModeInstructions=Q.collaborationMode.mode==="default"&&typeof Q.collaborationMode.settings?.developer_instructions==="string";return}case"thread/tokenUsage/updated":{let Q=O4(Z.tokenUsage?.last);if(Q)this.lastUsage=Q,this.lastResult.usage=this.lastUsage;else j("codex-process: tokenUsage notification missing last breakdown");this.lastTotalUsage=O4(Z.tokenUsage?.total);let Y=Z.tokenUsage?.modelContextWindow;if(typeof Y==="number"&&Y>0)this.lastContextWindow=Y;this.emit("token_usage",{usage:this.lastUsage,totalUsage:this.lastTotalUsage,contextWindow:this.lastContextWindow,threadId:Z.threadId,turnId:Z.turnId});return}case"turn/started":{if(typeof Z.threadId!=="string"||Z.threadId!==this.sessionId){V$("TURN_STARTED_THREAD_MISMATCH",{method:$,params:Z});return}this.recordTurnStarted(Z.turn,Z.threadId,"turn/started notification"),this.markConversationMaterialized("turn/started notification");return}case"turn/completed":{if(typeof Z.threadId!=="string"||Z.threadId!==this.sessionId){V$("TURN_COMPLETED_THREAD_MISMATCH",{method:$,params:Z});return}let Q=Z.turn??{},Y=typeof Q.id==="string"&&Q.id?Q.id:null;if(Y){if(this.finishedTurnIds?.has(Y)){j(`codex-process: duplicate turn/completed ignored turn=${Y}`);return}if(this.currentTurnId&&this.currentTurnId!==Y){this.markTurnStartTerminal(Y),this.rememberFinishedTurn(Y),j(`codex-process: stale turn/completed ignored turn=${Y} current=${this.currentTurnId}`);return}this.flushRolloutImageGenerations(),this.markConversationMaterialized("turn/completed notification"),this.markTurnStartTerminal(Y),this.rememberFinishedTurn(Y)}else V$("TURN_COMPLETED_MISSING_ID",{method:$,params:Z});let V=Q.status,X=V==="failed"&&this.turnError&&this.turnError.turnId===Y?this.turnError.error:null,z=Q.error&&X&&typeof Q.error.message==="string"&&Q.error.message===X.message?{...X,...Q.error,codexErrorInfo:Q.error.codexErrorInfo??X.codexErrorInfo,additionalDetails:Q.error.additionalDetails??X.additionalDetails}:Q.error??X;this.turnError=null;let H=V==="failed"||!!z,G=V==="completed"&&!H&&!!Y;this.lastCompletedTurnId=G?Y:null,this.currentTurnId=null,this.inputConsumptionOpen=!1;let W=A5(z,!!Y&&this.routingTimeoutTurnId===Y);if(this.routingTimeoutTurnId=null,V==="failed"&&Y&&W&&this.scheduleTurnRetry(z.message,PF[W],W))return;this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1;let K=H?z?.type??z?.message??"failed":"success";this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:typeof Q.durationMs==="number"?Q.durationMs:null,num_turns:1,usage:this.lastUsage,subtype:K,is_error:H};for(let[B,_]of this.steeringInputs??[])if(_===Y)this.steeringInputs.delete(B);this.emit("result",{subtype:K,is_error:H,...H&&typeof z?.message==="string"?{error:z.message}:{},...V==="failed"&&Y&&T4(z)?{codexQuotaFailure:{accepted:!0}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,turn_id:Y,checkpoint:G&&this.sessionId?{provider:"codex",kind:"turn",id:Y,source:{provider:"codex",sessionId:this.sessionId,cwd:this.opts.workDir}}:null});return}case"turn/plan/updated":{this.emit("turn_plan_updated",Z);return}case"item/plan/delta":{this.emit("plan_delta",Z);return}case"thread/goal/updated":{if(Z.goal)this.emit("thread_goal_updated",Z.goal);else j("codex-process: thread/goal/updated missing goal");return}case"thread/goal/cleared":{this.emit("thread_goal_cleared",Z);return}case"thread/status/changed":{this.handleThreadStatusChanged(Z);return}case"item/agentMessage/delta":{if(typeof Z.delta==="string"&&Z.delta.length>0)this.emit("assistant_text",{uuid:Z.itemId,text:Z.delta,parentToolUseId:null});else V$("AGENT_MESSAGE_DELTA_EMPTY",{method:$,params:Z});return}case"item/started":{this.handleItemStarted(Z);return}case"item/completed":{this.handleItemCompleted(Z);return}case"mcpServer/startupStatus/updated":{j(`codex-process: mcp ${Z.name} ${Z.status}${Z.error?`: ${Z.error}`:""}`);return}case"account/rateLimits/updated":{this.emit("rate_limits_updated",Z.rateLimits);return}case"configWarning":case"warning":case"guardianWarning":case"deprecationNotice":{j(`codex-process: ${$}: ${Z.summary??Z.message??JSON.stringify(Z).slice(0,200)}`);return}case"error":{j(`codex-process: server error: ${JSON.stringify(Z).slice(0,500)}`);let Q=Z.error??Z;if(typeof Z.turnId==="string"&&Z.threadId===this.sessionId&&!this.finishedTurnIds?.has(Z.turnId)&&(!this.currentTurnId||this.currentTurnId===Z.turnId)){if(this.turnError={turnId:Z.turnId,error:Q},Z.willRetry===!0&&[Q.message,Q.additionalDetails].some((Y)=>typeof Y==="string"&&/^workspace routing discovery timed out$/i.test(Y.trim())&&A5({...Q,message:Y,additionalDetails:Y===Q.additionalDetails?Q.message:Q.additionalDetails})!==null))this.routingTimeoutTurnId=Z.turnId}this.emit("error",Error(Q.message??Q.summary??"codex app-server error"));return}}V$("NOTIFICATION",{method:$,params:Z}),this.emit("raw",{method:$,params:Z})}handleItemStarted($){let Z=$?.item;if(!Z?.id){V$("ITEM_STARTED_MISSING_ID",{method:"item/started",params:$});return}if(Z.type==="userMessage"){let Q=Z.clientId;if(typeof Q==="string"&&$.threadId===this.sessionId&&this.steeringInputs?.get(Q)===$.turnId)this.steeringInputs.delete(Q),this.inputConsumptionOpen=!0,this.emit("user_input_consumed",{inputId:Q});return}if(this.inputConsumptionOpen&&$.turnId===this.currentTurnId)this.inputConsumptionOpen=!1,this.emit("input_batch_end",{itemId:Z.id});if(this.feedCollabItem(Z,"started"))return;let J=R5(Z,this.opts.workDir);if(!J){V$("ITEM_STARTED_UNMAPPED",{method:"item/started",params:$});return}this.emit("tool_use",{id:Z.id,name:J.name,input:J.input})}handleSubagentItemStarted($){let Z=$?.item;if(!Z?.id)return;if(this.feedCollabItem(Z,"started"))return;this.emitSubagentStep(Z,"started",$)}handleSubagentItemCompleted($){let Z=$?.item;if(!Z?.id)return;if(Z.type==="agentMessage"){let J=typeof Z.text==="string"?Z.text:"";if(J){let Q=typeof $?.threadId==="string"?$.threadId:"";this.collabAgentSummaries.set(Q,J)}return}if(this.feedCollabItem(Z,"completed"))return;this.emitSubagentStep(Z,"completed",$)}handleItemCompleted($){let Z=$?.item;if(!Z?.id){V$("ITEM_COMPLETED_MISSING_ID",{method:"item/completed",params:$});return}if(Z.type==="userMessage")return;if(Z.type==="agentMessage"){this.lastAssistantUuid=Z.id,this.emit("assistant_block_stop",{index:Z.id,parentToolUseId:null});return}if(this.feedCollabItem(Z,"completed"))return;let J=uz(Z,this.opts.workDir,this.sessionId??void 0);if(!J){V$("ITEM_COMPLETED_UNMAPPED",{method:"item/completed",params:$});return}if(this.emit("tool_result",{tool_use_id:Z.id,content:J.output,is_error:J.isError,...Z.type==="imageGeneration"?{input:T5(Z)}:{}}),Z.type==="imageGeneration")this.emittedImageGenerationIds.add(Z.id)}isSubagentThread($){let Z=typeof $?.threadId==="string"?$.threadId:"";return!!this.sessionId&&!!Z&&Z!==this.sessionId}handleThreadStatusChanged($){let Z=typeof $?.threadId==="string"?$.threadId:"",J=$?.status?.type;if(!Z||typeof J!=="string")return;if(!this.collabAgentNames?.has(Z))return;if(J==="active"){if(this.collabAgentWasActive.add(Z),this.collabAgentSettled.has(Z))this.collabAgentSettled.delete(Z),this.emit("bg_task_started",{task_id:Z,task_type:"local_agent",description:this.collabAgentNames.get(Z)??h0(Z)}),this.emit("bg_task_updated",{task_id:Z,patch:{is_backgrounded:!0}});this.emit("bg_task_updated",{task_id:Z,patch:{status:"running"}});return}if(J==="idle"||J==="systemError"){if(!this.collabAgentWasActive.has(Z))return;if(this.collabAgentSettled.has(Z))return;this.collabAgentSettled.add(Z),this.emit("bg_task_settled",{task_id:Z,status:J==="systemError"?"failed":"completed",summary:this.collabAgentSummaries.get(Z)??void 0})}}emitSubagentStep($,Z,J){let Q=typeof J?.threadId==="string"?J.threadId:"",Y=Z==="started"?R5($,this.opts.workDir):uz($,this.opts.workDir,this.sessionId??void 0);if(!Y)return;let V="output"in Y&&typeof Y.output==="string"?Y.output:void 0;this.emit("subagent_step",{thread_id:Q,item_id:$.id,tool:Y.name,phase:Z,brief:RF(Y.name,Y.input,V)})}feedCollabItem($,Z){if($.type==="subAgentActivity"){let J=typeof $.agentThreadId==="string"?$.agentThreadId:"";if(!J)return!0;if($.kind==="started"&&!this.collabAgentNames.has(J)){let Q=l3($.agentPath,J);this.collabAgentNames.set(J,Q),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Q}),this.emit("bg_task_updated",{task_id:J,patch:{is_backgrounded:!0}})}else if($.kind==="started"){let Q=this.collabAgentNames.get(J),Y=l3($.agentPath,J);if(Q!==Y&&!this.collabAgentSettled.has(J))this.collabAgentNames.set(J,Y),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Y})}else if($.kind==="interrupted")this.emit("bg_task_updated",{task_id:J,patch:{status:"paused"}});return!0}if($.type==="collabAgentToolCall"){let J=$.agentsStates;if(J&&typeof J==="object")for(let[Q,Y]of Object.entries(J))this.translateAgentState(Q,Y,$);if($.tool==="closeAgent"&&Z==="completed"&&$.status!=="failed"){let Q=nz($);for(let Y of Q){if(this.collabAgentSettled.has(Y))continue;if(this.collabAgentSettled.add(Y),!this.collabAgentNames.has(Y))this.collabAgentNames.set(Y,l3(null,Y));this.emit("bg_task_settled",{task_id:Y,status:"stopped"})}}if($.tool==="spawnAgent"){if(Z==="started")this.emit("tool_use",{id:$.id,name:"Agent",input:{tool:"spawnAgent",prompt:lz($.prompt),description:TF($),model:typeof $.model==="string"?$.model:void 0}});else if($.status!=="inProgress")this.emit("tool_result",{tool_use_id:$.id,content:EF($),is_error:$.status==="failed"})}return!0}return!1}translateAgentState($,Z,J){let Q=Z?.status;if(typeof Q!=="string")return;if(this.collabAgentSettled.has($)){if(Q!=="running"&&Q!=="pendingInit"){if(Q==="errored"||Q==="shutdown"||Q==="notFound"||Q==="interrupted")this.emit("bg_task_updated",{task_id:$,patch:{status:Q==="errored"?"failed":"killed",error:typeof Z?.message==="string"&&Z.message?Z.message:void 0}});return}this.collabAgentSettled.delete($);let V=this.collabAgentNames.get($)??l3(null,$);this.emit("bg_task_started",{task_id:$,task_type:"local_agent",description:V}),this.emit("bg_task_updated",{task_id:$,patch:{is_backgrounded:!0}})}if(!this.collabAgentNames.has($)){this.collabAgentNames.set($,"子 agent");let X={task_id:$,task_type:"local_agent",description:"子 agent",prompt:lz(J.prompt)};this.emit("bg_task_started",X);let z={task_id:$,patch:{is_backgrounded:!0}};this.emit("bg_task_updated",z)}if(Q==="running"||Q==="pendingInit"||Q==="interrupted"){let V={task_id:$,patch:{status:Q==="pendingInit"?"pending":Q==="interrupted"?"paused":"running"}};this.emit("bg_task_updated",V);return}if(this.collabAgentSettled.size>=5000)this.collabAgentSettled.clear();this.collabAgentSettled.add($);let Y={task_id:$,status:Q==="completed"?"completed":Q==="errored"?"failed":"stopped",summary:typeof Z?.message==="string"&&Z.message?Z.message:void 0};this.emit("bg_task_settled",Y)}primeRolloutImageGenerationScan(){if(this.rolloutFilePath=null,this.rolloutReadOffset=0,this.rolloutLineRemainder="",this.rolloutDecoder=new hz("utf8"),this.emittedImageGenerationIds.clear(),!this.sessionId)return;let $=pz(this.sessionId);if(!$)return;this.rolloutFilePath=$;try{this.rolloutReadOffset=d3($).size,j(`codex-process: image generation rollout scan primed ${$} offset=${this.rolloutReadOffset}`)}catch(Z){j(`codex-process: image generation rollout stat failed ${$}: ${Z instanceof Error?Z.message:Z}`),this.rolloutFilePath=null,this.rolloutReadOffset=0}}flushRolloutImageGenerations(){if(!this.sessionId)return;let $=this.rolloutFilePath??pz(this.sessionId);if(!$){j(`codex-process: image generation rollout file not found for thread=${this.sessionId}`);return}this.rolloutFilePath=$;let Z;try{let Y=d3($).size;if(Y<=this.rolloutReadOffset)return;let V=Y-this.rolloutReadOffset;Z=Buffer.allocUnsafe(V);let X=JF($,"r"),z=0;try{while(z<V){let H=YF(X,Z,z,V-z,this.rolloutReadOffset+z);if(H===0)break;z+=H}}finally{eD(X)}Z=Z.subarray(0,z),this.rolloutReadOffset+=z}catch(Y){j(`codex-process: image generation rollout read failed ${$}: ${Y instanceof Error?Y.message:Y}`);return}let J=this.rolloutLineRemainder+this.rolloutDecoder.write(Z),Q=J.split(/\r?\n/);this.rolloutLineRemainder=J.endsWith(`
82
- `)?"":Q.pop()??"";for(let Y of Q){if(!Y.trim())continue;let V;try{V=JSON.parse(Y)}catch(H){j(`codex-process: image generation rollout JSON parse failed ${$}: ${H instanceof Error?H.message:H}`);continue}let X=V?.payload,z=X?.type;if(z!=="image_generation_end"&&z!=="image_generation_call")continue;this.emitRolloutImageGeneration(X)}}emitRolloutImageGeneration($){let Z=typeof $?.call_id==="string"?$.call_id:typeof $?.id==="string"?$.id:"";if(!Z||this.emittedImageGenerationIds.has(Z))return;let J=dz($,this.sessionId??void 0);if(!J)return;let Q=$?.status==="failed",Y=$?.status==="generating"&&fz(J)?"completed":$?.status;this.emittedImageGenerationIds.add(Z),this.emit("tool_use",{id:Z,name:"ImageGeneration",input:T5({...$,status:Y})}),this.emit("tool_result",{tool_use_id:Z,content:J,is_error:Q})}withSessionId($){let Z=$.sessionId??this.sessionId??void 0;return Z?{...$,sessionId:Z}:$}handleServerRequest($){let Z=String($.id);switch(this.serverRequests.set(Z,{id:$.id,method:$.method,params:$.params}),$.method){case"item/commandExecution/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"Bash",input:{command:J.command,cwd:J.cwd,reason:J.reason},tool_use_id:J.itemId});return}case"item/fileChange/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"FileChange",input:{reason:J.reason,grantRoot:J.grantRoot},tool_use_id:J.itemId});return}case"item/tool/requestUserInput":{let J=$.params??{},Q={questions:(J.questions??[]).map((Y)=>({id:Y.id,header:Y.header,question:Y.question,options:Array.isArray(Y.options)&&Y.options.length?Y.options.map((V)=>({label:V.label,description:V.description})):[{label:"自定义回答",description:Y.isSecret?"请直接在群里回复":"可直接在群里回复"}]}))};this.emit("tool_use",{id:J.itemId,name:"AskUserQuestion",input:Q}),this.emit("can_use_tool",{request_id:Z,tool_name:"AskUserQuestion",input:Q,tool_use_id:J.itemId});return}case"item/permissions/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"PermissionProfile",input:{cwd:J.cwd,reason:J.reason,permissions:J.permissions},tool_use_id:J.itemId});return}case"item/tool/call":{let J=$.params??{};this.emit("tool_use",{id:J.callId,name:J.namespace?`${J.namespace}.${J.tool}`:J.tool,input:J.arguments}),this.respond(Z,{contentItems:[{type:"inputText",text:"Lodestar does not implement this dynamic tool."}],success:!1});return}case"account/chatgptAuthTokens/refresh":case"attestation/generate":case"applyPatchApproval":case"execCommandApproval":default:V$("SERVER_REQUEST_UNSUPPORTED",$),this.respondError(Z,`unsupported server request: ${$.method}`)}}write($,Z){let J=(Q)=>{let Y=Q instanceof Error?Q:Error(String(Q));return j(`codex-process: stdin write failed: ${Y.message}`),Z?.(Y),!1};if(!this.alive)return J(Error(`write to dead process: ${JSON.stringify($).slice(0,200)}`));if(!this.proc||this.proc.stdin.destroyed||this.proc.stdin.writableEnded||!this.proc.stdin.writable)return J(Error("stdin is not writable"));try{return this.proc.stdin.write(JSON.stringify($)+`
82
+ `)?"":Q.pop()??"";for(let Y of Q){if(!Y.trim())continue;let V;try{V=JSON.parse(Y)}catch(H){j(`codex-process: image generation rollout JSON parse failed ${$}: ${H instanceof Error?H.message:H}`);continue}let X=V?.payload,z=X?.type;if(z!=="image_generation_end"&&z!=="image_generation_call")continue;this.emitRolloutImageGeneration(X)}}emitRolloutImageGeneration($){let Z=typeof $?.call_id==="string"?$.call_id:typeof $?.id==="string"?$.id:"";if(!Z||this.emittedImageGenerationIds.has(Z))return;let J=dz($,this.sessionId??void 0);if(!J)return;let Q=$?.status==="failed",Y=$?.status==="generating"&&fz(J)?"completed":$?.status;this.emittedImageGenerationIds.add(Z),this.emit("tool_use",{id:Z,name:"ImageGeneration",input:T5({...$,status:Y})}),this.emit("tool_result",{tool_use_id:Z,content:J,is_error:Q})}withSessionId($){let Z=$.sessionId??this.sessionId??void 0;return Z?{...$,sessionId:Z}:$}handleServerRequest($){let Z=String($.id);switch(this.serverRequests.set(Z,{id:$.id,method:$.method,params:$.params}),$.method){case"item/commandExecution/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"Bash",input:{command:J.command,cwd:J.cwd,reason:J.reason},tool_use_id:J.itemId});return}case"item/fileChange/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"FileChange",input:{reason:J.reason,grantRoot:J.grantRoot},tool_use_id:J.itemId});return}case"item/tool/requestUserInput":{let J=$.params??{},Q={questions:(J.questions??[]).map((Y)=>({id:Y.id,header:Y.header,question:Y.question,options:Array.isArray(Y.options)&&Y.options.length?Y.options.map((V)=>({label:V.label,description:V.description})):[{label:"自定义回答",description:Y.isSecret?"请直接在当前对话中回复":"可直接在当前对话中回复"}]}))};this.emit("tool_use",{id:J.itemId,name:"AskUserQuestion",input:Q}),this.emit("can_use_tool",{request_id:Z,tool_name:"AskUserQuestion",input:Q,tool_use_id:J.itemId});return}case"item/permissions/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"PermissionProfile",input:{cwd:J.cwd,reason:J.reason,permissions:J.permissions},tool_use_id:J.itemId});return}case"item/tool/call":{let J=$.params??{};this.emit("tool_use",{id:J.callId,name:J.namespace?`${J.namespace}.${J.tool}`:J.tool,input:J.arguments}),this.respond(Z,{contentItems:[{type:"inputText",text:"Lodestar does not implement this dynamic tool."}],success:!1});return}case"account/chatgptAuthTokens/refresh":case"attestation/generate":case"applyPatchApproval":case"execCommandApproval":default:V$("SERVER_REQUEST_UNSUPPORTED",$),this.respondError(Z,`unsupported server request: ${$.method}`)}}write($,Z){let J=(Q)=>{let Y=Q instanceof Error?Q:Error(String(Q));return j(`codex-process: stdin write failed: ${Y.message}`),Z?.(Y),!1};if(!this.alive)return J(Error(`write to dead process: ${JSON.stringify($).slice(0,200)}`));if(!this.proc||this.proc.stdin.destroyed||this.proc.stdin.writableEnded||!this.proc.stdin.writable)return J(Error("stdin is not writable"));try{return this.proc.stdin.write(JSON.stringify($)+`
83
83
  `,(Q)=>{if(Q)J(Q)}),!0}catch(Q){return J(Q)}}request($,Z,J=KF){let Q=++this.requestCounter;return new Promise((Y,V)=>{let X=setTimeout(()=>{let H=this.pending.get(Q);if(!H)return;this.pending.delete(Q),H.reject(Error(`codex app-server ${$} request timed out after ${J}ms (id=${Q})`))},Math.max(0,J)),z={resolve:Y,reject:V,method:$,timeout:X};this.pending.set(Q,z),this.write({id:Q,method:$,params:Z},(H)=>{if(this.pending.get(Q)!==z)return;this.pending.delete(Q),clearTimeout(X),V(Error(`codex app-server ${$} request write failed (id=${Q}): ${H.message}`,{cause:H}))})})}rejectPendingRequests($){for(let[Z,J]of this.pending)clearTimeout(J.timeout),J.reject($(Z,J));this.pending.clear()}respond($,Z){let J=String($),Q=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Q?.id??$,result:Z})}respondError($,Z){let J=String($),Q=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Q?.id??$,error:{code:-32601,message:Z}})}sendInitialize(){if(!this.readyPromise)this.readyPromise=this.initializeAndStartThread(),this.readyPromise.catch(($)=>{j(`codex-process: initialize failed: ${$}`),this.emit("error",$)})}initializationPromise(){if(!this.readyPromise)this.sendInitialize();return this.readyPromise}isConversationResumable(){return this.conversationResumable}conversationMaterializationBarrier(){return this.conversationMaterializationVerification?this.drainConversationMaterialization():null}conversationMaterializationFailure(){return this.lastConversationMaterializationFailure}async drainConversationMaterialization(){while(this.conversationMaterializationVerification){let $=this.conversationMaterializationVerification;try{await $}catch{}await Promise.resolve()}if(!this.conversationResumable&&this.lastConversationMaterializationFailure)throw this.lastConversationMaterializationFailure}async readRateLimits(){return await this.ensureInitialized(),this.request("account/rateLimits/read",{})}initializeParams(){return{clientInfo:{name:"lodestar",version:"0.0.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}}}async ensureInitialized(){if(this.startupPromise)await this.startupPromise;if(!this.initializePromise)this.initializePromise=this.request("initialize",this.initializeParams()).then(()=>{if(!this.write({method:"initialized"}))throw Error("codex app-server initialized notification write failed")});await this.initializePromise}async initializeAndStartThread(){let $=this.conversationLaunch();await this.ensureInitialized();let Z=this.threadParams(),J,Q;if($.kind==="resume")J="thread/resume",Q=await this.request(J,{threadId:$.source.sessionId,...Z,excludeTurns:!0,persistExtendedHistory:!1});else if($.kind==="fork")J="thread/fork",Q=await this.request(J,{threadId:$.source.sessionId,...$.through?{lastTurnId:$.through.id}:{},...Z,excludeTurns:!0});else J="thread/start",Q=await this.request(J,{...Z,experimentalRawEvents:!1,persistExtendedHistory:!1});let Y=Q?.thread;if(typeof Y?.id!=="string"||!Y.id)throw Error(`codex app-server ${J} returned no thread.id`);let V=typeof Y.cwd==="string"?Y.cwd:typeof Q?.cwd==="string"?Q.cwd:null;if(V!==this.opts.workDir)throw Error(`codex app-server ${J} returned cwd=${V??"MISS"}, expected ${this.opts.workDir}`);if($.kind==="fork"&&Y.id===$.source.sessionId)throw Error(`codex app-server thread/fork returned source thread id ${Y.id}`);if($.kind==="resume"&&Y.id!==$.source.sessionId)throw Error(`codex app-server thread/resume returned thread id ${Y.id}, expected ${$.source.sessionId}`);let X=typeof Y.path==="string"&&Y.path?Y.path:null;if(!X||!fz(X)||!X.endsWith(`${Y.id}.jsonl`))throw Error(`codex app-server ${J} returned invalid thread.path=${X??"MISS"}`);if(this.sessionId=Y.id,this.conversationRolloutPath=X,this.conversationResumable=!1,$.kind!=="fresh")await this.verifyConversationMaterialized(`${J} response`),this.conversationResumable=!0;if(Q?.model)this.lastModel=Q.model;if(this.usesCustomDefaultModeInstructions=Q?.collaborationMode?.mode==="default"&&typeof Q.collaborationMode.settings?.developer_instructions==="string",U$(Q?.reasoningEffort))this.lastEffort=Q.reasoningEffort;else this.lastEffort=this.opts.effort??null;j(`codex-process: thread=${this.sessionId}`),this.primeRolloutImageGenerationScan(),this.emit("init",{session_id:this.sessionId,thread:Y})}markConversationMaterialized($){if(this.conversationResumable)return;if(!this.sessionId)throw Error(`codex ${$} arrived before thread initialization`);if(this.conversationMaterializationVerification){this.conversationMaterializationRetrySource=$;return}let Z=this.sessionId,J=this.verifyConversationMaterialized($);this.conversationMaterializationVerification=J,J.then(()=>{if(this.sessionId!==Z||this.conversationResumable)return;this.lastConversationMaterializationFailure=null,this.conversationResumable=!0,j(`codex-process: conversation materialized thread=${Z} source=${$}`),this.emit("conversation_materialized",{session_id:Z,source:$})},(Q)=>{let Y=Q instanceof Error?Q:Error(String(Q));this.lastConversationMaterializationFailure=Y,j(`codex-process: conversation materialization check failed thread=${Z} source=${$}: ${Y.message}`),this.emit("conversation_materialization_failed",{session_id:Z,path:this.conversationRolloutPath,source:$,error:Y})}).finally(()=>{if(this.conversationMaterializationVerification===J)this.conversationMaterializationVerification=null;let Q=this.conversationMaterializationRetrySource;if(this.conversationMaterializationRetrySource=null,!this.conversationResumable&&Q)this.markConversationMaterialized(Q)})}async verifyConversationMaterialized($){let Z=this.sessionId,J=this.conversationRolloutPath;if(!Z||!J)throw Error(`codex ${$} has no initialized rollout identity`);let Y=(await this.request("thread/read",{threadId:Z,includeTurns:!0},BF))?.thread;if(Y?.id!==Z||Y.cwd!==this.opts.workDir||Y.path!==J||!Array.isArray(Y.turns))throw Error(`codex ${$} thread/read returned an invalid materialized thread`);this.assertConversationRolloutMaterialized($)}assertConversationRolloutMaterialized($){let Z=this.conversationRolloutPath;if(!Z)throw Error(`codex ${$} has no authoritative rollout path`);let J;try{J=d3(Z)}catch(Q){throw Error(`codex ${$} rollout is not readable at ${Z}: ${Q instanceof Error?Q.message:Q}`,{cause:Q})}if(!J.isFile())throw Error(`codex ${$} rollout path is not a file: ${Z}`)}conversationLaunch(){let $=this.opts.launch??{kind:"fresh"};if(T0($,"codex",this.opts.workDir),$.kind!=="fresh"&&(typeof $.source.sessionId!=="string"||!$.source.sessionId))throw Error(`codex ${$.kind} launch requires a source session id`);if($.kind==="fork"&&$.through){if($.through.provider!=="codex"||$.through.kind!=="turn")throw Error("codex fork through checkpoint must be a codex turn checkpoint");if(typeof $.through.id!=="string"||!$.through.id)throw Error("codex fork through checkpoint requires a turn id")}return $}threadParams(){return{cwd:this.opts.workDir,runtimeWorkspaceRoots:[this.opts.workDir],approvalPolicy:"never",sandbox:"danger-full-access",config:{"tools.experimental_request_user_input.enabled":this.opts.allowUserInput!==!1,"features.default_mode_request_user_input":this.opts.allowUserInput!==!1,...this.opts.effort?{model_reasoning_effort:this.opts.effort}:{}},...this.opts.model?{model:this.opts.model}:{},...this.opts.apiProvider?{modelProvider:this.opts.apiProvider.id}:this.opts.tokenSourceId==="codex-sub"?{modelProvider:"openai"}:{},...this.opts.appendSystemPrompt?{developerInstructions:this.opts.appendSystemPrompt}:{},serviceName:this.opts.serviceName??"lodestar"}}sendUserText($,Z=[]){let J=Z.length?Z.map((Y)=>`[file: ${Y}]`).join(" ")+`
84
84
 
85
85
  `:"";this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1,this.turnRetryEnabled=!0,this.turnError=null,this.routingTimeoutTurnId=null;let Q=this.beginTurnStart(J+$);this.startTurn(J+$,Q).catch((Y)=>this.failTurnStart(Y,Q))}async steerUserText($,Z=[],J=zF()){if(!this.alive||this.expectedExit)throw Error("Codex 进程已关闭");let Q=this.currentTurnId;if(!Q)return!1;let Y=Z.length?Z.map((X)=>`[file: ${X}]`).join(" ")+`
@@ -347,24 +347,26 @@ ${L}`:P,D=[],M=(O)=>{D.push(O)},U=await F0(V,C.footer,this.footerElement(q),{onF
347
347
  ${F9(D)}`)}for(let O of z.values())await this.sendAssistantTextFallback(O,"CardKit 元素未落地");if((J.forcePush||!Z)&&Q.userOpenId&&Q.messageId&&!Q.cardRotationFailed)v2(Q.messageId,[Q.userOpenId])}}});function C$($){return{card:{type:"raw",data:$}}}import{randomUUID as _E}from"node:crypto";function IV($){return{session_name:$.sessionName,chat_id:$.chatId,status:$.status,running:$.isRunning(),translation:{enabled:$.proc?.translationEnabled===!0},native_session_id:$.proc?.sessionId??null,codex_account:$.proc?.provider==="codex"&&$.proc.isAlive()?{name:v.get(M$($.proc)).name,mode:$.proc.codexAccountSelectionMode?.()??"native",policy:"highest-score-plus-5h-ultra-pro-0.5"}:null,busy:!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount||$.pendingMidTurnMsgs.length),awaiting_model_input:!!$.modelCustomPrompt,last_result:$.proc?{anchor:$.proc.lastAssistantUuid,subtype:$.proc.lastResult.subtype,is_error:$.proc.lastResult.is_error}:null,selection:{provider:$.selectedProvider,source_id:$.selectedTokenSourceId,model:$.selectedModel,effort:$.selectedEffort},panels:[...$.modelPanels].map(([Z,J])=>({panel_id:Z,message_id:J.messageId,source_id:J.sourceId,mode:J.mode,editable:J.editable,total_models:J.catalog?.length,page:J.page,total_pages:J.totalPages,models:J.models.map((Q)=>({model:Q.model,provider:Q.provider,source_id:Q.sourceId,efforts:Q.efforts.map((Y)=>Y.effort),origin:Q.origin}))})),sources:s0().map((Z)=>({id:Z.id,display:Z.display,agent:Z.agent,enabled:Z.enabled,validates_custom_model:!!Z.verifyModel,status:Z.modelCatalogState?.status,error:Z.modelCatalogState?.error,models:Z.models.map((J)=>({model:J.model,efforts:J.efforts,default_effort:J.defaultEffort,unavailable_reason:J.unavailableReason,origin:J.origin}))}))}}function n_($,Z,J,Q,Y){if(!$||typeof $!=="object"||Array.isArray($))throw Error("bad action body");let V=$;if(!Z.chat_id.startsWith("oc_")||!Z.sender_open_id.startsWith("ou_"))throw Error("invalid debug context");if(V.chat_id!==Z.chat_id)throw Error("debug chat mismatch");if(typeof V.message_id!=="string"||!V.message_id.startsWith("om_"))throw Error("message_id required");if(!Y||V.message_id!==Y)throw Error("stale or mismatched model panel");if(!J||J.message_id!==V.message_id||J.chat_id!==Z.chat_id||J.msg_type!=="interactive"||J.sender?.sender_type!=="app"||J.sender.id!==Q)throw Error("model card must belong to this app and debug chat");if(!V.value||typeof V.value!=="object"||Array.isArray(V.value))throw Error("action value required");let X={};for(let[z,H]of Object.entries(V.value)){if(!LE.has(z))throw Error(`unsupported model action field: ${z}`);if(z==="page"){if(typeof H!=="number"||!Number.isSafeInteger(H)||H<0)throw Error("invalid page");X.page=H}else{if(typeof H!=="string"||!H.trim()||H.length>1024)throw Error(`invalid ${z}`);X[z]=H.trim()}}if(!PE.has(String(X.kind)))throw Error("only model panel actions are supported");for(let z of["panel_id","source_id"])if(!X[z])throw Error(`${z} required`);if(["model_select","model_effort_select","model_add","model_remove","model_custom_remove"].includes(String(X.kind))&&!X.model)throw Error("model required");if(X.kind==="model_effort_select"&&!X.effort)throw Error("effort required");if(X.kind==="model_page"&&X.page===void 0)throw Error("page required");if(X.kind==="model_list_open"&&X.mode!=="select"&&X.mode!=="add")throw Error("invalid model list mode");if(X.provider!==void 0&&!n$(X.provider))throw Error("invalid provider");return{event_id:`debug-model-${_E()}`,operator:{open_id:Z.sender_open_id},context:{open_chat_id:Z.chat_id,open_message_id:V.message_id},action:{tag:"button",value:X}}}var PE,LE;var a_=R(()=>{L0();H0();M0();PE=new Set(["provider_select","model_select","model_effort_select","model_page","model_list_open","model_add","model_remove","model_custom_remove","model_custom_prompt","model_panel_cancel"]),LE=new Set(["kind","panel_id","source_id","model","effort","provider","page","mode"])});import{createServer as qE}from"node:http";import{randomUUID as DE}from"node:crypto";function t_($){if($.allowReply&&$.buttons?.length)throw Error(s_);let Z=$.level==="error"?"red":$.level==="warn"?"yellow":"blue",J=$.level==="error"?"❌":$.level==="warn"?"⚠️":"\uD83D\uDD14",Q=!!(($.buttons?.length||$.allowReply)&&$.notifyId),Y=new Date,V=`${String(Y.getHours()).padStart(2,"0")}:${String(Y.getMinutes()).padStart(2,"0")}`,X=[];for(let H of $.images??[])if(H.key)X.push({tag:"img",img_key:H.key,alt:{tag:"plain_text",content:"screenshot"}});else{let G=H.error?`
348
348
  ${G0(H.error)}`:"";X.push({tag:"markdown",content:`<font color='red'>\uD83D\uDCF7 图片上传失败: ${H.src}${G}</font>`})}if(X.push({tag:"markdown",content:FJ($.text??"")||"_(空消息)_"}),$.resolution){let H=$.resolution,G=H.kind==="text"?"已回复":`已选择:${H.text}`,W;if(H.status==="processing")W=`<font color='blue'>⏳ ${G} · 推送中…</font>`;else if(H.status==="failed")W=`<font color='red'>⚠️ ${H.kind==="text"?G:`已选:${H.text}`} · 回调失败:${G0(H.detail??"未知")} · ${V}</font>`;else if(H.status==="delivered")W=`<font color='green'>✅ ${G} · 反馈已送达 · ${V}</font>`;else if(H.status==="unknown")W=`<font color='red'>⚠️ ${G} · 送达状态未知,禁止自动重试 · ${V}</font>`;else W=`<font color='green'>✅ ${G} · ${V}</font>`;if(X.push({tag:"markdown",content:W}),H.status==="delivered"&&H.reply)X.push({tag:"markdown",content:G0(H.reply)})}let z=Q&&(!$.resolution||$.resolution.status==="failed");if(z&&$.buttons?.length)X.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:$.buttons.map((H)=>({tag:"button",text:{tag:"plain_text",content:H.text},type:H.type,behaviors:[{type:"callback",value:{kind:"notify_callback",notify_id:$.notifyId,button_id:H.id}}]}))}]});if(X.push({tag:"hr"}),X.push({tag:"markdown",content:`<font color='grey'>via notify · ${V}</font>`}),z&&$.allowReply)X.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"回复"},type:"primary",behaviors:[{type:"callback",value:{kind:"notify_reply",notify_id:$.notifyId}}]}]}]});return{schema:"2.0",config:Q?{update_multi:!0}:{},header:{title:{tag:"plain_text",content:`${J} ${$.title}`},template:Z},body:{elements:X}}}function Q2($,Z,J){let Q=J?.status??Z.status,Y={waiting:"等待用户输入",sending:"正在发送回复",processing:"正在发送回复",delivered:"回复已送达",done:"回复已记录",failed:"回复发送失败",cancelled:"已取消回复",unknown:"回复送达状态未知"},V=[{tag:"markdown",content:`通知:${G0($.title)}`}];if(Z.response)V.push({tag:"markdown",content:G0(Z.response.text)});if(Q==="waiting")V.push({tag:"markdown",content:`<at id=${Z.openId}></at> 请在群里发送一条文字消息作为回复。
349
349
  你的下一条文字优先用于这条通知,完成后再回答 Agent 的提问。点击其他通知的「回复」会放弃本次回复;群控制命令仍然优先。`}),V.push({tag:"button",text:{tag:"plain_text",content:"取消回复"},type:"default",behaviors:[{type:"callback",value:{kind:"notify_reply_cancel",notify_id:$.notifyId,reply_id:Z.id}}]});if(Q==="cancelled"&&Z.cancelReason==="switched")V.push({tag:"markdown",content:"已切换到另一条通知,本次回复已放弃。"});let X=J?.detail??Z.error;if(X)V.push({tag:"markdown",content:`<font color='red'>${G0(X)}</font>`});if(Q==="failed")V.push({tag:"markdown",content:"请点击原通知的「回复」按钮后重新输入。"});if(Q==="unknown")V.push({tag:"markdown",content:"无法确认是否已送达,请联系通知发起方核实;已禁止自动重试。"});if(J?.reply)V.push({tag:"markdown",content:G0(J.reply)});return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:Y[Q]},template:Q==="failed"||Q==="unknown"?"red":Q==="delivered"||Q==="done"?"green":"blue"},body:{elements:V}}}function OE($){if($===void 0||$===null)return{buttons:[]};if(!Array.isArray($))return{error:'"buttons" must be an array'};if($.length===0)return{buttons:[]};let Z=new Set,J=[];for(let Q of $){if(!Q||typeof Q!=="object")return{error:"each button must be an object"};let Y=String(Q.id??"").trim(),V=String(Q.text??"").trim();if(!UE.test(Y))return{error:`button id "${Y.slice(0,32)}" invalid (need ^[A-Za-z0-9_-]{1,64}$)`};if(!V)return{error:`button "${Y}" missing text`};if(V.length>o_)return{error:`button "${Y}" text > ${o_} chars`};if(Z.has(Y))return{error:`button id "${Y}" duplicated`};Z.add(Y);let X=String(Q.type??"default").toLowerCase(),z=ME.has(X)?X:"default";J.push({id:Y,text:V,type:z})}return{buttons:J}}function NE($){if($===void 0||$===null)return{};let Z=String($).trim();if(!Z)return{};let J;try{J=new URL(Z)}catch{return{error:`"callback" bad URL: "${Z.slice(0,64)}"`}}if(J.protocol!=="http:")return{error:`"callback" must be http (本机内), got "${J.protocol}"`};let Q=J.hostname.replace(/^\[|]$/g,"");if(Q!=="127.0.0.1"&&Q!=="localhost"&&Q!=="::1")return{error:`"callback" must be loopback (本机内), got "${J.hostname}"`};return{url:Z}}function r_($){try{let Z=qE((J,Q)=>{Promise.resolve().then(async()=>{let V;try{V=new URL(J.url??"/","http://localhost")}catch{Q.statusCode=400,Q.end("bad request URL");return}if(!await $.extraHandler?.(J,Q,V))await AE(J,Q)}).catch((V)=>{if(j(`notify: handler crash: ${V?.message??V}`),!Q.headersSent)Q.statusCode=500,Q.setHeader("content-type","text/plain; charset=utf-8"),Q.end(V instanceof l0?w(V):"internal error");else try{Q.end()}catch{}})});return Z.on("error",(J)=>{j(`notify: server bind failed (${$.bind}:${$.port}): ${J.message}`)}),Z.listen($.port,$.bind,()=>{j(`notify: HTTP listening at http://${$.bind}:${$.port}/notify`)}),Z}catch(Z){j(`notify: server bind failed (${$.bind}:${$.port}): ${Z}`)}}async function AE($,Z,J=X0){let Q=new URL($.url??"/","http://localhost"),Y=(l,y)=>{Z.statusCode=l,Z.setHeader("content-type","text/plain; charset=utf-8"),Z.end(y)},V=(l,y)=>{Z.statusCode=l,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(y))};if($.method==="GET"&&Q.pathname==="/")return Y(200,`lodestar notify
350
- `+`POST /notify body={project,text,title?,level?,images?,buttons?,allow_reply?,callback?} → push card to group
350
+ `+`POST /notify body={project,text,title?,level?,images?,buttons?,allow_reply?,callback?} → push card to the project's bound conversation ID (chat_id)
351
351
  `+`GET /notify/result/<notify_id> → poll a button choice or text reply (pull mode, no callback server)
352
352
  `+`GET /agents/identities; POST/GET/DELETE /agents/runs[/<id>] → capability-protected delegated Agents
353
353
  `+`levels: info|warn|error (default info); images=[/abs/*.png] uploaded + embedded
354
354
  card types: plain (neither field), selection (buttons), text reply (allow_reply:true); do not combine buttons and allow_reply:true
355
355
  `+`all types support text + images; callback=http://127.0.0.1:PORT/path optional for selection/reply (push) — omit to poll
356
- `);if($.method==="GET"&&Q.pathname.startsWith("/notify/result/")){let l;try{l=decodeURIComponent(Q.pathname.slice(15)).trim()}catch{return Y(400,"invalid notify_id encoding")}if(!l)return Y(400,"missing notify_id in path");let y=T1(l);if(!y)return V(404,{error:"unknown notify_id",notify_id:l});return V(200,Mj(y))}if($.method!=="POST"||Q.pathname!=="/notify")return Y(405,"use POST /notify");let X="",z=0;$.setEncoding("utf8");for await(let l of $)if(z+=Buffer.byteLength(l),z<=gV)X+=l;else X="";if(z>gV)return Y(413,`request body exceeds ${gV} bytes`);let H={};try{H=JSON.parse(X)}catch{return Y(400,"bad json")}if(!H||typeof H!=="object"||Array.isArray(H))return Y(400,"body must be an object");if(H.allow_reply!==void 0&&typeof H.allow_reply!=="boolean")return Y(400,'"allow_reply" must be a boolean');let G=H.allow_reply===!0,W=String(H.project??"").trim(),K=String(H.text??""),B=String(H.title??"").trim(),_=String(H.level??"info").toLowerCase();if(!W)return Y(400,'missing "project"');if(!K)return Y(400,'missing "text"');let{buttons:P,error:L}=OE(H.buttons);if(L)return Y(400,L);let{url:q,error:D}=NE(H.callback);if(D)return Y(400,D);let M=!!(P&&P.length);if(M&&G)return Y(400,s_);let U=M||G,N=q??"",O=FE.has(_)?_:"info",A=B||W,S=J.sanitizeSessionName(W),T=J.chatIdForSession(S);if(!T)return j(`notify: project "${W}" (sanitized "${S}") has no chat binding → 404`),Y(404,`project "${W}" not bound — send any message in that Feishu group at least once after the daemon started, then retry`);let f=Array.isArray(H.images)?H.images:[],m=[];for(let l of f){let y=String(l??"").trim();if(!y)continue;let Q0,t=await J.uploadImageKey(y,(K0)=>{Q0=K0});m.push({key:t??"",src:y,...Q0===void 0?{}:{error:w(Q0)}})}let k=U?`nf_${DE()}`:"",p=t_({title:A,text:K,level:O,images:m,buttons:P,allowReply:G,notifyId:k}),c,J0=await J.sendCard(T,p,(l)=>{c=l});if(!J0)return j(`notify: sendCard failed → 502 (project="${W}" chat=${T.slice(0,8)}…)`),Y(502,`feishu sendCard failed: ${w(c)}`);if(U&&k){let l={notifyId:k,callbackUrl:N,chatId:T,messageId:J0,project:W,title:A,text:K,level:O,imageKeys:m,buttons:P,allowReply:G,createdAt:Date.now()};Lj(l)}j(`notify: → ${W} (${T.slice(0,8)}…) level=${O} bytes=${K.length} images=${m.length} buttons=${P?.length??0} allowReply=${G} push=${U&&!!N?1:0} msg=${J0}`),V(200,{ok:!0,chat_id:T,message_id:J0,...k?{notify_id:k}:{}})}function Y2($,Z){return t_({title:$.title,text:$.text,level:$.level,images:$.imageKeys,buttons:$.buttons,allowReply:$.allowReply,notifyId:$.notifyId,resolution:Z})}var FE,ME,UE,o_=64,s_='"buttons" and "allow_reply":true are mutually exclusive; choose button selection or text reply',gV=4194304;var BZ=R(()=>{g();Y0();_4();d0();Q3();FE=new Set(["info","warn","error"]),ME=new Set(["default","primary","danger"]),UE=/^[A-Za-z0-9_-]{1,64}$/});var ZP=QX((rp,$P)=>{var{readFileSync:RE,rmSync:TE}=H4("node:fs"),{homedir:e_}=H4("node:os"),{join:G3}=H4("node:path"),{managedClaudePluginDir:EE}=CZ();function SE($,Z,J=console.log){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){J(`skill: sync disabled, skip removal ${$}`);return}let Q=Z??[G3(e_(),".codex","skills"),G3(e_(),".claude","skills"),G3(EE(),"skills")],Y=[];for(let V of Q){let X=G3(V,$),z=G3(X,"SKILL.md"),H;try{H=RE(z,"utf8")}catch(K){if(K.code==="ENOENT")continue;let B=Error(`skill: obsolete removal failed (${z}): ${K}`,{cause:K});J(B.message),Y.push(B);continue}let G=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(H)?.[1],W=/^name:[ \t]*(?:"([^"]*)"|'([^']*)'|([^\s#]+))[ \t]*$/m.exec(G??"");if(!W||(W[1]??W[2]??W[3])!==$){J(`skill: obsolete path preserved because ownership is unclear ${z}`);continue}try{TE(X,{recursive:!0,force:!1}),J(`skill: removed obsolete ${X}`)}catch(K){let B=Error(`skill: obsolete removal failed (${X}): ${K}`,{cause:K});J(B.message),Y.push(B)}}if(Y.length)throw AggregateError(Y,`Failed to remove obsolete Skill ${$}`)}$P.exports={removeManagedSkill:SE}});import{existsSync as QP,readFileSync as YP}from"node:fs";import{homedir as JP}from"node:os";import{join as W3}from"node:path";function jZ($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip ${$.name}`);return}let J=Z??[W3(JP(),".codex","skills"),W3(JP(),".claude","skills")];for(let Q of J){let Y=W3(Q,$.name,"SKILL.md");try{let V=QP(Y)?YP(Y,"utf8"):null;if(V===$.body)continue;Q$(Y,$.body),j(`skill: ${V===null?"installed":"updated"} ${Y}`)}catch(V){j(`skill: sync failed (${Y}): ${V}`)}}if(!Z)CE($,W4)}function CE($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip Claude plugin ${$.name}`);return}let J=W3(Z,".claude-plugin","plugin.json"),Q=W3(Z,"skills",$.name,"SKILL.md"),Y=JSON.stringify({name:"lodestar-managed",description:"Lodestar daemon-managed Skills for Claude Agent SDK sessions",version:"1.0.0",author:{name:"Lodestar"}},null,2)+`
357
- `;for(let[V,X]of[[J,Y],[Q,$.body]])try{let z=QP(V)?YP(V,"utf8"):null;if(z===X)continue;Q$(V,X),j(`skill: ${z===null?"installed":"updated"} ${V}`)}catch(z){j(`skill: Claude plugin sync failed (${V}): ${z}`)}}function _Z($,Z){VP.removeManagedSkill($,Z,j)}var VP;var PZ=R(()=>{g();x0();z0();VP=JX(ZP(),1)});function xE($){let Z=`Push a one-shot notification card to a Feishu (Lark) group via the local lodestar daemon's HTTP endpoint. Auto-trigger whenever the user asks to "通知飞书", "推送到飞书", "推到飞书群", "飞书推送", "发到飞书", "脚本跑完通知我", "进程完成发个消息", "send to feishu", "feishu notify", "lodestar notify", "post to lark group", or wants any local script / cron / long-running process to ping a Feishu group (build done, deploy finished, trade filled, monitor alert, error caught). Encodes the call shape — POST http://127.0.0.1:${$}/notify with \`{project, text, level}\` — so consumers do not have to re-derive it. Also covers interactive buttons: add \`buttons\` and either pledge a loopback \`callback\` URL (daemon POSTs the click back) or omit it and poll \`GET /notify/result/NOTIFY_ID\`; all on localhost.`;return`---
356
+ `);if($.method==="GET"&&Q.pathname.startsWith("/notify/result/")){let l;try{l=decodeURIComponent(Q.pathname.slice(15)).trim()}catch{return Y(400,"invalid notify_id encoding")}if(!l)return Y(400,"missing notify_id in path");let y=T1(l);if(!y)return V(404,{error:"unknown notify_id",notify_id:l});return V(200,Mj(y))}if($.method!=="POST"||Q.pathname!=="/notify")return Y(405,"use POST /notify");let X="",z=0;$.setEncoding("utf8");for await(let l of $)if(z+=Buffer.byteLength(l),z<=gV)X+=l;else X="";if(z>gV)return Y(413,`request body exceeds ${gV} bytes`);let H={};try{H=JSON.parse(X)}catch{return Y(400,"bad json")}if(!H||typeof H!=="object"||Array.isArray(H))return Y(400,"body must be an object");if(H.allow_reply!==void 0&&typeof H.allow_reply!=="boolean")return Y(400,'"allow_reply" must be a boolean');let G=H.allow_reply===!0,W=String(H.project??"").trim(),K=String(H.text??""),B=String(H.title??"").trim(),_=String(H.level??"info").toLowerCase();if(!W)return Y(400,'missing "project"');if(!K)return Y(400,'missing "text"');let{buttons:P,error:L}=OE(H.buttons);if(L)return Y(400,L);let{url:q,error:D}=NE(H.callback);if(D)return Y(400,D);let M=!!(P&&P.length);if(M&&G)return Y(400,s_);let U=M||G,N=q??"",O=FE.has(_)?_:"info",A=B||W,S=J.sanitizeSessionName(W),T=J.chatIdForSession(S);if(!T)return j(`notify: project "${W}" (sanitized "${S}") has no chat binding → 404`),Y(404,`project "${W}" has no conversation ID (chat_id) binding — send a message in the intended Feishu conversation, then retry`);let f=Array.isArray(H.images)?H.images:[],m=[];for(let l of f){let y=String(l??"").trim();if(!y)continue;let Q0,t=await J.uploadImageKey(y,(K0)=>{Q0=K0});m.push({key:t??"",src:y,...Q0===void 0?{}:{error:w(Q0)}})}let k=U?`nf_${DE()}`:"",p=t_({title:A,text:K,level:O,images:m,buttons:P,allowReply:G,notifyId:k}),c,J0=await J.sendCard(T,p,(l)=>{c=l});if(!J0)return j(`notify: sendCard failed → 502 (project="${W}" chat=${T.slice(0,8)}…)`),Y(502,`feishu sendCard failed: ${w(c)}`);if(U&&k){let l={notifyId:k,callbackUrl:N,chatId:T,messageId:J0,project:W,title:A,text:K,level:O,imageKeys:m,buttons:P,allowReply:G,createdAt:Date.now()};Lj(l)}j(`notify: → ${W} (${T.slice(0,8)}…) level=${O} bytes=${K.length} images=${m.length} buttons=${P?.length??0} allowReply=${G} push=${U&&!!N?1:0} msg=${J0}`),V(200,{ok:!0,chat_id:T,message_id:J0,...k?{notify_id:k}:{}})}function Y2($,Z){return t_({title:$.title,text:$.text,level:$.level,images:$.imageKeys,buttons:$.buttons,allowReply:$.allowReply,notifyId:$.notifyId,resolution:Z})}var FE,ME,UE,o_=64,s_='"buttons" and "allow_reply":true are mutually exclusive; choose button selection or text reply',gV=4194304;var BZ=R(()=>{g();Y0();_4();d0();Q3();FE=new Set(["info","warn","error"]),ME=new Set(["default","primary","danger"]),UE=/^[A-Za-z0-9_-]{1,64}$/});var ZP=QX((rp,$P)=>{var{readFileSync:RE,rmSync:TE}=H4("node:fs"),{homedir:e_}=H4("node:os"),{join:G3}=H4("node:path"),{managedClaudePluginDir:EE}=CZ();function SE($,Z,J=console.log){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){J(`skill: sync disabled, skip removal ${$}`);return}let Q=Z??[G3(e_(),".codex","skills"),G3(e_(),".claude","skills"),G3(EE(),"skills")],Y=[];for(let V of Q){let X=G3(V,$),z=G3(X,"SKILL.md"),H;try{H=RE(z,"utf8")}catch(K){if(K.code==="ENOENT")continue;let B=Error(`skill: obsolete removal failed (${z}): ${K}`,{cause:K});J(B.message),Y.push(B);continue}let G=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(H)?.[1],W=/^name:[ \t]*(?:"([^"]*)"|'([^']*)'|([^\s#]+))[ \t]*$/m.exec(G??"");if(!W||(W[1]??W[2]??W[3])!==$){J(`skill: obsolete path preserved because ownership is unclear ${z}`);continue}try{TE(X,{recursive:!0,force:!1}),J(`skill: removed obsolete ${X}`)}catch(K){let B=Error(`skill: obsolete removal failed (${X}): ${K}`,{cause:K});J(B.message),Y.push(B)}}if(Y.length)throw AggregateError(Y,`Failed to remove obsolete Skill ${$}`)}$P.exports={removeManagedSkill:SE}});import{existsSync as QP,readFileSync as YP}from"node:fs";import{homedir as JP}from"node:os";import{join as W3}from"node:path";function jZ($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip ${$.name}`);return}let J=Z??[W3(JP(),".codex","skills"),W3(JP(),".claude","skills")];for(let Q of J){let Y=W3(Q,$.name,"SKILL.md");try{let V=QP(Y)?YP(Y,"utf8"):null;if(V===$.body)continue;Q$(Y,$.body),j(`skill: ${V===null?"installed":"updated"} ${Y}`)}catch(V){j(`skill: sync failed (${Y}): ${V}`)}}if(!Z)CE($,W4)}function CE($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip Claude plugin ${$.name}`);return}let J=W3(Z,".claude-plugin","plugin.json"),Q=W3(Z,"skills",$.name,"SKILL.md"),Y=JSON.stringify({name:"lodestar-managed",description:"Lodestar daemon-managed Skills for Claude Agent SDK sessions",version:"1.0.0",author:{name:"Lodestar"}},null,2)+`
357
+ `;for(let[V,X]of[[J,Y],[Q,$.body]])try{let z=QP(V)?YP(V,"utf8"):null;if(z===X)continue;Q$(V,X),j(`skill: ${z===null?"installed":"updated"} ${V}`)}catch(z){j(`skill: Claude plugin sync failed (${V}): ${z}`)}}function _Z($,Z){VP.removeManagedSkill($,Z,j)}var VP;var PZ=R(()=>{g();x0();z0();VP=JX(ZP(),1)});function xE($){let Z=`Send a one-shot notification card to a project's bound Feishu (Lark) conversation through the local Lodestar daemon. Use for "通知飞书", "推送到飞书", "推送到对话", "飞书推送", "发到飞书", "脚本跑完通知我", "进程完成发个消息", "send to feishu", "feishu notify", "lodestar notify", "post to lark conversation", or notifications from scripts, cron jobs, and services. POST http://127.0.0.1:${$}/notify accepts {project, text, level}; project is a name resolved to a conversation ID (chat_id). Supports local images, interactive buttons: supply buttons, and free-text replies: set allow_reply:true for a fixed 回复 button. Receive results through a loopback callback or GET /notify/result/NOTIFY_ID.`;return`---
358
358
  name: ${XP}
359
- description: ${JSON.stringify(Z+" Also receive free-text replies with allow_reply:true: a fixed 回复 button opens a waiting card, then the user types in the group and the daemon returns the text through the same callback or result endpoint.")}
359
+ description: ${JSON.stringify(Z)}
360
360
  ---
361
361
 
362
362
  # feishu-notify
363
363
 
364
- Push a one-shot card into a Feishu (Lark) group via the local lodestar
365
- daemon. The daemon binds each group to a project name (= group name);
366
- once the daemon has seen at least one inbound message in that group,
367
- \`POST /notify\` with the project name routes a card to it.
364
+ Push a one-shot card into a Feishu (Lark) conversation via the local lodestar
365
+ daemon. The daemon resolves a project/session name to its bound conversation
366
+ ID (\`chat_id\`); \`POST /notify\` with that project name routes a card to
367
+ the conversation. The \`project\` request field remains a name, not a
368
+ conversation ID. \`chat_id\` identifies the notification destination and
369
+ is distinct from an Agent backend's native session ID (\`session_id\`).
368
370
 
369
371
  ## Three card types
370
372
 
@@ -390,18 +392,18 @@ Body (JSON):
390
392
 
391
393
  | field | required | meaning |
392
394
  |---|---|---|
393
- | \`project\` | ✅ | Feishu group name (= session name = working-directory name) |
395
+ | \`project\` | ✅ | Project/session name used to resolve the bound conversation ID (\`chat_id\`); do not pass a \`chat_id\` here |
394
396
  | \`text\` | ✅ | Feishu schema-2.0 markdown — \`**bold**\`, \`\` \`code\` \`\`, \`[link](url)\`, \`<font color='red'>…</font>\` |
395
397
  | \`title\` | | Card header, defaults to \`project\` |
396
398
  | \`level\` | | \`info\` (blue, default) / \`warn\` (yellow) / \`error\` (red) |
397
399
  | \`images\` | | Array of local image paths \`["/abs/a.png"]\` — uploaded to Feishu and embedded above the text (failed uploads surface inline in red, never dropped silently) |
398
400
  | \`buttons\` | | Array of \`{id, text, type?}\` — renders one button per row (vertical stack, any count). \`id\`: \`^[A-Za-z0-9_-]{1,64}$\`, unique. \`text\`: ≤ 64 chars (a short phrase is fine — each button owns its full row). \`type\`: \`default\` / \`primary\` / \`danger\` (default \`default\`). |
399
- | \`allow_reply\` | | Boolean, default false. Selects the custom text reply type; cannot be combined with nonempty \`buttons\`. Only this type has a fixed 「回复」 button at the bottom. Clicking sends a separate 「等待用户输入」 card; the clicker's next text in that group is returned to the caller. |
401
+ | \`allow_reply\` | | Boolean, default false. Selects the custom text reply type; cannot be combined with nonempty \`buttons\`. Only this type has a fixed 「回复」 button at the bottom. Clicking sends a separate 「等待用户输入」 card; the clicker's next text in that conversation is returned to the caller. |
400
402
  | \`callback\` | | Optional loopback HTTP URL (e.g. \`http://127.0.0.1:9999/hook\`) — **push mode**: the daemon POSTs the button choice or submitted text here. Must be \`http://\` on \`127.0.0.1\` / \`localhost\` / \`::1\`. Omit for **pull mode** (see below). |
401
403
 
402
404
  Response: \`200 {ok, chat_id, message_id, notify_id?}\` (notify_id returned
403
- when buttons are present or allow_reply is true) / \`400\` bad params / \`404\` group not
404
- bound / \`413\` JSON body exceeds 4 MiB / \`502\` Feishu API rejected.
405
+ when buttons are present or allow_reply is true) / \`400\` bad params / \`404\` project not
406
+ bound to a conversation ID / \`413\` JSON body exceeds 4 MiB / \`502\` Feishu API rejected.
405
407
 
406
408
  \`GET /notify/result/<notify_id>\` — pull the verdict with no callback
407
409
  server: \`{notify_id, project, message_id, resolved, unknown, button?,
@@ -549,7 +551,7 @@ curl -fsS -X POST http://127.0.0.1:${$}/notify \\
549
551
 
550
552
  Only this custom-reply card places 「回复」 at the bottom. Clicking it
551
553
  sends a separate 「等待用户输入」 card mentioning the clicker. Their
552
- next text message in the same group becomes the response. This new
554
+ next text message in the same conversation becomes the response. This new
553
555
  card updates in place to show the entered text and delivery outcome;
554
556
  the original notification also shows completion.
555
557
 
@@ -579,21 +581,21 @@ In pull mode, the result contains the same \`response\`, plus
579
581
  body described above; it is displayed on the receipt card. That body
580
582
  is the script's acknowledgement, distinct from the user's response.
581
583
 
582
- - Each group has one current notification reply. Clicking another
584
+ - Each conversation ID has one current notification reply. Clicking another
583
585
  notification's 「回复」 abandons the previous waiting reply and updates
584
586
  its card; only the newest clicker's input is accepted. Abandonment
585
587
  does not POST an answer. Repeated clicks on the current reply do not
586
588
  create duplicate waiting cards. A reply already sending cannot be switched.
587
589
  - Plain text and text-only rich-text messages work. The current reply
588
590
  takes precedence even if the message quotes an older card. Attachments
589
- keep their normal route; group control commands retain priority.
591
+ keep their normal route; conversation control commands retain priority.
590
592
  - Text input priority is notification reply → Agent question → ordinary
591
593
  Agent input. Agent questions wait while a notification reply is pending,
592
594
  then resume after it ends. One question is answerable at a time; further
593
595
  questions queue. An input is never submitted to two destinations.
594
- - Only the current reply's clicker can submit or cancel it. A different
595
- group member can select another notification's reply, replacing the
596
- current waiting reply. Old cancel buttons cannot affect a newer attempt.
596
+ - Only the current reply's clicker can submit or cancel it. Another
597
+ participant in the same conversation can select another notification's
598
+ reply, replacing the current waiting reply. Old cancel buttons cannot affect a newer attempt.
597
599
  - The waiting card includes 「取消回复」. A click alone does not POST
598
600
  anything. A completed custom-reply notification accepts one text response.
599
601
  - Callback failure stays visible on the receipt; click 「回复」 on the
@@ -607,9 +609,9 @@ is the script's acknowledgement, distinct from the user's response.
607
609
 
608
610
  - For free-text input, use \`allow_reply:true\` as above; do not manufacture
609
611
  a caller-defined button named "reply" or ask users to type before clicking.
610
- - The group must have received at least one message after the daemon
611
- started (the daemon learns chat_id → name binding from inbound
612
- events). If you see \`404\` send any message in the group and retry.
612
+ - The project must have a known conversation ID (\`chat_id\`) binding.
613
+ The daemon records the binding from inbound messages. If you see
614
+ \`404\`, send a message in the intended conversation and retry.
613
615
  - This skill is auto-installed by the lodestar daemon on every boot.
614
616
  Hand-edits will be overwritten — set
615
617
  \`LODESTAR_DISABLE_SKILL_SYNC=1\` and restart the daemon if you want
package/docs/usage.md CHANGED
@@ -185,7 +185,7 @@ HTTP 使用原 `/agents/…` 路径并增加 `?project=<项目名>`,Bearer 凭
185
185
 
186
186
  ## 本机通知
187
187
 
188
- 脚本可通过 HTTP 向项目群发送通知,支持 `info`、`warn`、`error`,以及本地图片、交互按钮或文字回复:
188
+ 脚本可通过 HTTP 向项目绑定的对话发送通知,支持 `info`、`warn`、`error`,以及本地图片、交互按钮或文字回复:
189
189
 
190
190
  ```bash
191
191
  curl -sS -X POST http://127.0.0.1:9876/notify \
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leviyuan/lodestar",
3
- "version": "0.21.6",
3
+ "version": "0.21.7",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },