@leviyuan/lodestar 0.18.1 → 0.18.2
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/dist/lodestar.js +1 -1
- package/package.json +1 -1
package/dist/lodestar.js
CHANGED
|
@@ -267,7 +267,7 @@ ${V}`,card:B9({slug:"wt",branch:"work/*",status:J,body:V,template:"red"})}}}asyn
|
|
|
267
267
|
|
|
268
268
|
${J}`)}completedAssistantElement($,Z){if(RZ(Z))return this.mathAssistantContainer($,[{type:"markdown",text:Z}]);return{tag:"markdown",element_id:$,content:this.cleanAssistantTextForDisplay(Z).trim()||" "}}mathAssistantContainer($,Z){let J=Z.map((Y)=>Y.type==="markdown"?{tag:"markdown",content:this.cleanAssistantTextForDisplay(Y.text).trim()||" "}:{...Y.element});return{tag:"column_set",element_id:$,flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:J.length?J:[{tag:"markdown",content:" "}]}]}}async replaceSegmentWithMathImgs($,Z,J,Y){let Q=await qX(Y);if(!await M0(Z,J,this.mathAssistantContainer(J,Q.blocks),{notifyCardFailure:!1})){K(`session "${this.sessionName}": math render ${J} write dropped (card closed/element dead) — raw text stays`);return}$.mathRendered??=new Map,$.mathRendered.get(Z)??$.mathRendered.set(Z,new Set),$.mathRendered.get(Z).add(J),K(`session "${this.sessionName}": math rendered ${J} (${Q.renderedImageCount} img, ${Q.blocks.length} blocks)`)}addCompletedAssistantSegment($,Z,J){let Y=$.cardId,Q=O0($),V=(async()=>{if(!await Y1(Y,this.completedAssistantElement(Z,J),{type:"insert_before",targetElementId:Q}))return K(`session "${this.sessionName}": assistant segment ${Z} raw write failed on card=${Y}`),!1;if(RZ(J)){let X=this.replaceSegmentWithMathImgs($,Y,Z,J).catch((z)=>K(`session "${this.sessionName}": math render ${Z} failed: ${z}`));$.mathRenderInflight??=new Map,$.mathRenderInflight.get(Y)??$.mathRenderInflight.set(Y,new Set),$.mathRenderInflight.get(Y).add(X),X.finally(()=>$.mathRenderInflight?.get(Y)?.delete(X))}return!0})();return $.assistantWriteInflight??=new Map,$.assistantWriteInflight.get(Y)??$.assistantWriteInflight.set(Y,new Set),$.assistantWriteInflight.get(Y).add(V),V.finally(()=>$.assistantWriteInflight?.get(Y)?.delete(V)),V}async sendAssistantTextFallback($,Z){let J=$.trim();if(!J)return;let Y=`⚠️ 对话卡片正文写入失败(${Z}),以下为 agent 原始回复:
|
|
269
269
|
|
|
270
|
-
${J}`;if(!await E(this.chatId,Y))K(`session "${this.sessionName}": ASSISTANT_TEXT_PRESERVATION_FAILED (${Z}, ${J.length} chars)`)}finalizeCurrentAssistantSegment(){let $=this.currentTurn;if(!$){if(this.orphanAssistantCurrent.trim())this.orphanAssistantSegments.push(this.orphanAssistantCurrent);this.orphanAssistantCurrent="";return}if($.cardRotationFailed)this.maybeMidTurnRotate();if($.rotating)return;let Z=$.currentAssistantSegmentId,J=$.currentAssistantText??"";if(Z&&J.trim())this.addCompletedAssistantSegment($,Z,J),this.startWorkingFooter($);$.currentAssistantSegmentId=null,$.currentAssistantText=""}processOutboundMarkers($){for(let Z of tH($))this.sendOutboundPath(Z,"send marker")}cleanAssistantTextForDisplay($){return Z0($)}sendOutboundPath($,Z){let J=M6($.trim());if(!J)return;let Y=this.currentTurn;if(Y?.outboundSeenPaths.has(J))return;if(Y?.outboundSeenPaths.add(J),!JM(J)){K(`session "${this.sessionName}": ignore non-absolute outbound path from ${Z}: ${J}`);return}K(`session "${this.sessionName}": outbound send from ${Z}: ${J}`);try{let Q=Y?.fileDeliveryMode??(this.proc?this.procFileDeliveryModes.get(this.proc):void 0)??this.getFileDeliveryMode();if(Y)Y.fileDeliveryMode=Q;if(Q==="chat"){Y?.outboundSentPaths.add(J),o4(this.chatId,J);return}if(!Y)throw Error("当前没有可关联的交付轮次");if(!Y.fileDelivery)Y.fileDelivery=this.createFileDeliveryForTurn(Y),this.fileDeliveries.add(Y.fileDelivery);Y.fileDelivery.add(J)}catch(Q){K(`session "${this.sessionName}": file delivery rejected: ${O(Q)}`),E(this.chatId,`❌ 文件交付失败:${O(Q)}`)}}createFileDeliveryForTurn($){return iz({chatId:this.chatId,managerOpenId:$.userOpenId,projectName:this.sessionName,createdAt:$.startedAt})}startFooterStatus($,Z){if($.cardRotationFailed)return;let J=$.provider==="codex"?this.proc?.turnRetry:null;if(J)Z=J.reason==="quota"?`⏳ ${J.message}`:J.phase==="waiting"?`⏳ 模型满载 · ${J.delayMs/1000}s 后重试 #${J.attempt}`:`⏳ 模型满载 · 正在重试 #${J.attempt}`;if($.footerStatusHandle&&$.footerStatusLabel===Z)return;this.stopFooterStatus($),$.footerStatusLabel=Z,$.footerStatusStartedAt=Date.now();let Y=()=>{if($.footerStatusLabel!==Z)return;let{label:V}=t$(Date.now()-$.footerStatusStartedAt,s1()),H=Z===hW?this.proc?.lastThinkingTokens:null,X=typeof H==="number"?` · 约 ${H} tokens`:"";this.replaceFooterContent($.cardId,this.withModel(`${Z}${X} (${V})`))},Q=()=>{if($.footerStatusLabel!==Z)return;let{nextDelayMs:V}=t$(Date.now()-$.footerStatusStartedAt,s1());$.footerStatusHandle=setTimeout(()=>{Y(),Q()},Math.max(1,Math.ceil(V)))};Y(),Q()}startThinkingFooter($){this.startFooterStatus($,hW)}startWritingFooter($){this.startFooterStatus($,HM)}startWorkingFooter($){this.startFooterStatus($,XM)}stopFooterStatus($){if(!$)return;if($.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null,$.footerStatusStartedAt=0,$.footerStatusLabel=null}async footerUsageSuffix($,Z,J,Y,Q){if(J&&(!Y||!Y.enabled||Y.agent!==$))return" | 额度 MISS";if(Y?.agent===$&&Y.enabled&&($==="claude"||$==="dsh")){let V=await Y.readUsage();if(V.state==="ok"&&V.kind!=="balance"){let H=V.windows.find((z)=>z.kind==="fiveHour"),X=V.windows.find((z)=>z.kind==="weekly");if(H||X)return this.fmtDualWindowSuffix(H??null,X??null)}return` | ${K6(V)}`}if($==="codex"){let V=Z?.isAlive()&&Z.provider==="codex"&&Z.readRateLimits?Z:null,H=V?await O8(()=>V.readRateLimits(),r0(V)):null,X=V?H:Q;return X?.state==="ok"?this.fmtDualWindowSuffix(X.fiveHour??null,X.weekly??null):" | 额度 MISS"}return" | 额度 MISS"}fmtDualWindowSuffix($,Z){let J=(V)=>{if(!V)return null;if(V.percent==null)return"MISS";let H=V.resetsAt&&V.resetsAt.getTime()>Date.now()?R2(V.resetsAt):"",X=`${Math.round(V.percent)}%`;return H?`${H}·${X}`:X},Y=J($),Q=J(Z);if(Y&&Q)return` | ${Y}·[${Q}]`;if(Y)return` | ${Y}`;if(Q)return` | [${Q}]`;return" | 额度 MISS"}waitForTurnCloses(){let $=[...this.turnCloseInflight];if($.length===0)return Promise.resolve();return Promise.allSettled($).then((Z)=>{let J=Z.filter((Y)=>Y.status==="rejected").map((Y)=>Y.reason);if(J.length===1)throw J[0];if(J.length>1)throw AggregateError(J,`turn close failed: ${J.map(O).join("; ")}`)})}releaseTurnCloseReactions($){for(let[Z,J]of[...$.currentBatchReactionIds.entries(),...$.pendingReactionIds.entries()])if(J)C0(Z,J)}closeTurnCard($,Z={}){let J=this.currentTurn;if(!J)return this.waitForTurnCloses();if(
|
|
270
|
+
${J}`;if(!await E(this.chatId,Y))K(`session "${this.sessionName}": ASSISTANT_TEXT_PRESERVATION_FAILED (${Z}, ${J.length} chars)`)}finalizeCurrentAssistantSegment(){let $=this.currentTurn;if(!$){if(this.orphanAssistantCurrent.trim())this.orphanAssistantSegments.push(this.orphanAssistantCurrent);this.orphanAssistantCurrent="";return}if($.cardRotationFailed)this.maybeMidTurnRotate();if($.rotating)return;let Z=$.currentAssistantSegmentId,J=$.currentAssistantText??"";if(Z&&J.trim())this.addCompletedAssistantSegment($,Z,J),this.startWorkingFooter($);$.currentAssistantSegmentId=null,$.currentAssistantText=""}processOutboundMarkers($){for(let Z of tH($))this.sendOutboundPath(Z,"send marker")}cleanAssistantTextForDisplay($){return Z0($)}sendOutboundPath($,Z){let J=M6($.trim());if(!J)return;let Y=this.currentTurn;if(Y?.outboundSeenPaths.has(J))return;if(Y?.outboundSeenPaths.add(J),!JM(J)){K(`session "${this.sessionName}": ignore non-absolute outbound path from ${Z}: ${J}`);return}K(`session "${this.sessionName}": outbound send from ${Z}: ${J}`);try{let Q=Y?.fileDeliveryMode??(this.proc?this.procFileDeliveryModes.get(this.proc):void 0)??this.getFileDeliveryMode();if(Y)Y.fileDeliveryMode=Q;if(Q==="chat"){Y?.outboundSentPaths.add(J),o4(this.chatId,J);return}if(!Y)throw Error("当前没有可关联的交付轮次");if(!Y.fileDelivery)Y.fileDelivery=this.createFileDeliveryForTurn(Y),this.fileDeliveries.add(Y.fileDelivery);Y.fileDelivery.add(J)}catch(Q){K(`session "${this.sessionName}": file delivery rejected: ${O(Q)}`),E(this.chatId,`❌ 文件交付失败:${O(Q)}`)}}createFileDeliveryForTurn($){return iz({chatId:this.chatId,managerOpenId:$.userOpenId,projectName:this.sessionName,createdAt:$.startedAt})}startFooterStatus($,Z){if($.cardRotationFailed)return;let J=$.provider==="codex"?this.proc?.turnRetry:null;if(J)Z=J.reason==="quota"?`⏳ ${J.message}`:J.phase==="waiting"?`⏳ 模型满载 · ${J.delayMs/1000}s 后重试 #${J.attempt}`:`⏳ 模型满载 · 正在重试 #${J.attempt}`;if($.footerStatusHandle&&$.footerStatusLabel===Z)return;this.stopFooterStatus($),$.footerStatusLabel=Z,$.footerStatusStartedAt=Date.now();let Y=()=>{if($.footerStatusLabel!==Z)return;let{label:V}=t$(Date.now()-$.footerStatusStartedAt,s1()),H=Z===hW?this.proc?.lastThinkingTokens:null,X=typeof H==="number"?` · 约 ${H} tokens`:"";this.replaceFooterContent($.cardId,this.withModel(`${Z}${X} (${V})`))},Q=()=>{if($.footerStatusLabel!==Z)return;let{nextDelayMs:V}=t$(Date.now()-$.footerStatusStartedAt,s1());$.footerStatusHandle=setTimeout(()=>{Y(),Q()},Math.max(1,Math.ceil(V)))};Y(),Q()}startThinkingFooter($){this.startFooterStatus($,hW)}startWritingFooter($){this.startFooterStatus($,HM)}startWorkingFooter($){this.startFooterStatus($,XM)}stopFooterStatus($){if(!$)return;if($.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null,$.footerStatusStartedAt=0,$.footerStatusLabel=null}async footerUsageSuffix($,Z,J,Y,Q){if(J&&(!Y||!Y.enabled||Y.agent!==$))return" | 额度 MISS";if(Y?.agent===$&&Y.enabled&&($==="claude"||$==="dsh")){let V=await Y.readUsage();if(V.state==="ok"&&V.kind!=="balance"){let H=V.windows.find((z)=>z.kind==="fiveHour"),X=V.windows.find((z)=>z.kind==="weekly");if(H||X)return this.fmtDualWindowSuffix(H??null,X??null)}return` | ${K6(V)}`}if($==="codex"){let V=Z?.isAlive()&&Z.provider==="codex"&&Z.readRateLimits?Z:null,H=V?await O8(()=>V.readRateLimits(),r0(V)):null,X=V?H:Q;return X?.state==="ok"?this.fmtDualWindowSuffix(X.fiveHour??null,X.weekly??null):" | 额度 MISS"}return" | 额度 MISS"}fmtDualWindowSuffix($,Z){let J=(V)=>{if(!V)return null;if(V.percent==null)return"MISS";let H=V.resetsAt&&V.resetsAt.getTime()>Date.now()?R2(V.resetsAt):"",X=`${Math.round(V.percent)}%`;return H?`${H}·${X}`:X},Y=J($),Q=J(Z);if(Y&&Q)return` | ${Y}·[${Q}]`;if(Y)return` | ${Y}`;if(Q)return` | [${Q}]`;return" | 额度 MISS"}waitForTurnCloses(){let $=[...this.turnCloseInflight];if($.length===0)return Promise.resolve();return Promise.allSettled($).then((Z)=>{let J=Z.filter((Y)=>Y.status==="rejected").map((Y)=>Y.reason);if(J.length===1)throw J[0];if(J.length>1)throw AggregateError(J,`turn close failed: ${J.map(O).join("; ")}`)})}releaseTurnCloseReactions($){for(let[Z,J]of[...$.currentBatchReactionIds.entries(),...$.pendingReactionIds.entries()])if(J)C0(Z,J)}closeTurnCard($,Z={}){let J=this.currentTurn;if(!J)return this.waitForTurnCloses();if(!$&&J.cardRotationFailed)this.maybeMidTurnRotate();this.currentTurn=null,this.stopFooterStatus(J);let Y=this.proc,Q={turn:J,proc:Y,procEpoch:this.procEpoch,contextTokens:this.currentContextTokens(Y),contextLimit:this.contextLimitForDisplay(Y),lastTurnDelta:this.lastTurnDelta?{...this.lastTurnDelta}:null,lastTurnUsage:this.lastTurnUsage?{...this.lastTurnUsage}:null,tokenSourceId:this.selectedTokenSourceId,tokenSource:Y?.provider==="codex"?H0(Y.tokenSourceId??this.selectedTokenSourceId,r0(Y)):this.currentTokenSource(),codexUsage:oQ(r0(Y)),currentBatchReactionIds:this.currentBatchReactionIds,pendingReactionIds:this.pendingReactionIds};this.currentBatchReactionIds=new Map,this.pendingReactionIds=new Map;let V=this.finishTurnCardClose(Q,$,Z).finally(()=>this.releaseTurnCloseReactions(Q));return this.turnCloseInflight.add(V),V.then(()=>{this.turnCloseInflight.delete(V)},()=>{this.turnCloseInflight.delete(V)}),V}async finishTurnCardClose($,Z,J={}){let{turn:Y}=$;if(Y.rotating)await Y.rotating;if(await yZ(Y),Y.fileDelivery)try{for(let A of await Y.fileDelivery.finish())Y.outboundSentPaths.add(A)}catch(A){K(`session "${this.sessionName}": file delivery close failed: ${O(A)}`),await w(this.chatId,`❌ 文件交付收尾失败:${O(A)}`)}finally{this.fileDeliveries.delete(Y.fileDelivery)}this.stopFooterStatus(Y);let Q=(Date.now()-Y.startedAt)/1000,V=Y.cardId,H=Y.segmentTexts;await O$(V);let X=new Map;if(Y.currentAssistantSegmentId&&Y.currentAssistantText.trim()){let{currentAssistantSegmentId:A,currentAssistantText:U}=Y;if(!await this.addCompletedAssistantSegment(Y,A,U))X.set(A,U);Y.currentAssistantSegmentId=null,Y.currentAssistantText=""}let z=Y.assistantWriteInflight?.get(V);if(z?.size)await Promise.allSettled([...z]);let W=Y.mathRenderInflight?.get(V);if(W?.size)await Promise.allSettled([...W]);let G=Y.mathRendered?.get(V);for(let[A,U]of H){if(k2(V,A)){X.set(A,U);continue}if(G?.has(A))continue;await J0(V,A,this.completedAssistantElement(A,U))}if(Y.cardRotationFailed)for(let[A,U]of H)X.set(A,U);let B=Z?Z:"✅",_=[`${B} ⏱ ${G0(Q)}`];if(J.hasFreshResult){let{contextTokens:A,contextLimit:U}=$,S=Y.provider==="claude",b=N5(A,U,S?0:void 0);if(b)_.push(`\uD83E\uDDE0 ${b}`);let v=$.lastTurnDelta?.costUsd??0;if(v>0)_.push(`\uD83D\uDCB0 $${v.toFixed(3)}`)}if(Y.contextCompactCount>0)_.push(`\uD83D\uDEA8 压缩×${Y.contextCompactCount}`);if(Y.outboundSentPaths.size>0)_.push(`\uD83D\uDCCE ${Y.outboundSentPaths.size}`);let j=this.modelLine(Y);if(j)_.push(j);let q=_.join(" | "),P=J.hasFreshResult?T5($.lastTurnUsage)+(Y.cardRotationFailed?"":await this.footerUsageSuffix(Y.provider,$.proc,$.tokenSourceId,$.tokenSource,$.codexUsage)):"",F=P?`${q}
|
|
271
271
|
${P}`:q,T=await M0(V,N.footer,this.footerElement(F));A0(V);let M=await P0(V,h$({durationSec:Q,outputTokens:J.hasFreshResult?$.lastTurnUsage?.output_tokens:void 0,suffix:Z}));if(T&&M)await v0(V);else{let A=`footer=${T?"ok":"MISS"}, settings=${M?"ok":"MISS"}`;K(`session "${this.sessionName}": terminal card transaction incomplete card=${V.slice(0,12)} ${A}`),await w(this.chatId,`⚠️ 对话卡片终态写入失败 (${A})。本轮已结束: ${B}`)}for(let A of X.values())await this.sendAssistantTextFallback(A,"CardKit 元素未落地");if((J.forcePush||!Z)&&Y.userOpenId&&Y.messageId&&!Y.cardRotationFailed)C1(Y.messageId,[Y.userOpenId])}}});function Q$($){return{card:{type:"raw",data:$}}}import{randomUUID as GM}from"node:crypto";function RJ($){return{session_name:$.sessionName,chat_id:$.chatId,status:$.status,running:$.isRunning(),native_session_id:$.proc?.sessionId??null,codex_account:$.proc?.provider==="codex"&&$.proc.isAlive()?{name:k.get(r0($.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((Y)=>({model:Y.model,provider:Y.provider,source_id:Y.sourceId,efforts:Y.efforts.map((Q)=>Q.effort),origin:Y.origin}))})),sources:y$().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 mW($,Z,J,Y,Q){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(!Q||V.message_id!==Q)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!==Y)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 H={};for(let[X,z]of Object.entries(V.value)){if(!BM.has(X))throw Error(`unsupported model action field: ${X}`);if(X==="page"){if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)throw Error("invalid page");H.page=z}else{if(typeof z!=="string"||!z.trim()||z.length>1024)throw Error(`invalid ${X}`);H[X]=z.trim()}}if(!KM.has(String(H.kind)))throw Error("only model panel actions are supported");for(let X of["panel_id","source_id"])if(!H[X])throw Error(`${X} required`);if(["model_select","model_effort_select","model_add","model_remove","model_custom_remove"].includes(String(H.kind))&&!H.model)throw Error("model required");if(H.kind==="model_effort_select"&&!H.effort)throw Error("effort required");if(H.kind==="model_page"&&H.page===void 0)throw Error("page required");if(H.kind==="model_list_open"&&H.mode!=="select"&&H.mode!=="add")throw Error("invalid model list mode");if(H.provider!==void 0&&!B$(H.provider))throw Error("invalid provider");return{event_id:`debug-model-${GM()}`,operator:{open_id:Z.sender_open_id},context:{open_chat_id:Z.chat_id,open_message_id:V.message_id},action:{tag:"button",value:H}}}var KM,BM;var pW=R(()=>{F0();V0();p0();KM=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"]),BM=new Set(["kind","panel_id","source_id","model","effort","provider","page","mode"])});import{createServer as _M}from"node:http";import{randomUUID as jM}from"node:crypto";function dW($){if($.allowReply&&$.buttons?.length)throw Error(lW);let Z=$.level==="error"?"red":$.level==="warn"?"yellow":"blue",J=$.level==="error"?"❌":$.level==="warn"?"⚠️":"\uD83D\uDD14",Y=!!(($.buttons?.length||$.allowReply)&&$.notifyId),Q=new Date,V=`${String(Q.getHours()).padStart(2,"0")}:${String(Q.getMinutes()).padStart(2,"0")}`,H=[];for(let z of $.images??[])if(z.key)H.push({tag:"img",img_key:z.key,alt:{tag:"plain_text",content:"screenshot"}});else H.push({tag:"markdown",content:`<font color='red'>\uD83D\uDCF7 图片上传失败: ${z.src}</font>`});if(H.push({tag:"markdown",content:$3($.text??"")||"_(空消息)_"}),$.resolution){let z=$.resolution,W=z.kind==="text"?"已回复":`已选择:${z.text}`,G;if(z.status==="processing")G=`<font color='blue'>⏳ ${W} · 推送中…</font>`;else if(z.status==="failed")G=`<font color='red'>⚠️ ${z.kind==="text"?W:`已选:${z.text}`} · 回调失败:${Z0(z.detail??"未知")} · ${V}</font>`;else if(z.status==="delivered")G=`<font color='green'>✅ ${W} · 反馈已送达 · ${V}</font>`;else if(z.status==="unknown")G=`<font color='red'>⚠️ ${W} · ${z.kind==="text"?"送达状态未知,禁止自动重试":"外部回调已成功,但本地确认状态未知,禁止自动重试"} · ${V}</font>`;else G=`<font color='green'>✅ ${W} · ${V}</font>`;if(H.push({tag:"markdown",content:G}),z.status==="delivered"&&z.reply)H.push({tag:"markdown",content:Z0(z.reply)})}let X=Y&&(!$.resolution||$.resolution.status==="failed");if(X&&$.buttons?.length)H.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:$.buttons.map((z)=>({tag:"button",text:{tag:"plain_text",content:z.text},type:z.type,behaviors:[{type:"callback",value:{kind:"notify_callback",notify_id:$.notifyId,button_id:z.id}}]}))}]});if(H.push({tag:"hr"}),H.push({tag:"markdown",content:`<font color='grey'>via notify · ${V}</font>`}),X&&$.allowReply)H.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:Y?{update_multi:!0}:{},header:{title:{tag:"plain_text",content:`${J} ${$.title}`},template:Z},body:{elements:H}}}function _1($,Z,J){let Y=J?.status??Z.status,Q={waiting:"等待用户输入",sending:"正在发送回复",processing:"正在发送回复",delivered:"回复已送达",done:"回复已记录",failed:"回复发送失败",cancelled:"已取消回复",unknown:"回复送达状态未知"},V=[{tag:"markdown",content:`通知:${Z0($.title)}`}];if(Z.response)V.push({tag:"markdown",content:Z0(Z.response.text)});if(Y==="waiting")V.push({tag:"markdown",content:`<at id=${Z.openId}></at> 请在群里发送一条文字消息作为回复。
|
|
272
272
|
你的下一条文字优先用于这条通知,完成后再回答 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(Y==="cancelled"&&Z.cancelReason==="switched")V.push({tag:"markdown",content:"已切换到另一条通知,本次回复已放弃。"});let H=J?.detail??Z.error;if(H)V.push({tag:"markdown",content:`<font color='red'>${Z0(H)}</font>`});if(Y==="failed")V.push({tag:"markdown",content:"请点击原通知的「回复」按钮后重新输入。"});if(Y==="unknown")V.push({tag:"markdown",content:"无法确认是否已送达,请联系通知发起方核实;已禁止自动重试。"});if(J?.reply)V.push({tag:"markdown",content:Z0(J.reply)});return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:Q[Y]},template:Y==="failed"||Y==="unknown"?"red":Y==="delivered"||Y==="done"?"green":"blue"},body:{elements:V}}}function FM($){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 Y of $){if(!Y||typeof Y!=="object")return{error:"each button must be an object"};let Q=String(Y.id??"").trim(),V=String(Y.text??"").trim();if(!PM.test(Q))return{error:`button id "${Q.slice(0,32)}" invalid (need ^[A-Za-z0-9_-]{1,64}$)`};if(!V)return{error:`button "${Q}" missing text`};if(V.length>cW)return{error:`button "${Q}" text > ${cW} chars`};if(Z.has(Q))return{error:`button id "${Q}" duplicated`};Z.add(Q);let H=String(Y.type??"default").toLowerCase(),X=qM.has(H)?H:"default";J.push({id:Q,text:V,type:X})}return{buttons:J}}function DM($){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 Y=J.hostname.replace(/^\[|]$/g,"");if(Y!=="127.0.0.1"&&Y!=="localhost"&&Y!=="::1")return{error:`"callback" must be loopback (本机内), got "${J.hostname}"`};return{url:Z}}function iW($){try{let Z=_M((J,Y)=>{let Q=new URL(J.url??"/",`http://${J.headers.host??"localhost"}`);($.extraHandler?$.extraHandler(J,Y,Q).then((H)=>H?void 0:uW(J,Y)):uW(J,Y)).catch((H)=>{if(K(`notify: handler crash: ${H?.message??H}`),!Y.headersSent)Y.statusCode=500,Y.setHeader("content-type","text/plain; charset=utf-8"),Y.end("internal error");else try{Y.end()}catch{}})});Z.on("error",(J)=>{K(`notify: server bind failed (${$.bind}:${$.port}): ${J.message}`)}),Z.listen($.port,$.bind,()=>{K(`notify: HTTP listening at http://${$.bind}:${$.port}/notify`)})}catch(Z){K(`notify: server bind failed (${$.bind}:${$.port}): ${Z}`)}}async function uW($,Z,J=Y0){let Y=new URL($.url??"/",`http://${$.headers.host??"localhost"}`),Q=(l,D)=>{Z.statusCode=l,Z.setHeader("content-type","text/plain; charset=utf-8"),Z.end(D)},V=(l,D)=>{Z.statusCode=l,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(D))};if($.method==="GET"&&Y.pathname==="/")return Q(200,`lodestar notify
|
|
273
273
|
`+`POST /notify body={project,text,title?,level?,images?,buttons?,allow_reply?,callback?} → push card to group
|