cc-ding 1.1.0 → 1.1.1
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/src/biz/cc-ding-cli.js +48 -48
- package/dist/src/biz/claude-process.js +31 -31
- package/dist/src/biz/session.js +11 -11
- package/dist/src/biz/streaming.js +2 -2
- package/package.json +1 -1
|
@@ -1,52 +1,52 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Y=exports&&exports.__importDefault||function(_){return _&&_.__esModule?_:{default:_}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.DingClaude=void 0;const V=require("child_process"),ne=require("utils-ok"),S=Y(require("fs")),X=Y(require("os")),Q=Y(require("path")),oe=require("../common"),O=require("./quote"),Z=require("./messaging"),G=require("./image"),k=require("./commands"),j=require("./messaging"),H=require("./claude-process"),te=require("./recorder"),A=require("./menu"),c=require("./session"),P=require("./task"),b=require("./todo"),ae=require("./commands"),L=require("./api-key-manager"),re=require("./secrets"),M=require("./command-route"),J=require("./cron"),ee=require("./timer"),de=require("./send-queue"),B=require("./model"),F=require("./platform"),se=(0,oe.projUtil)().getPkgVersion();function ce(_,d){const o=[],a=[{key:"model",label:"model"},{key:"owner",label:"owner"},{key:"defaultDingToken",label:"defaultDingToken"},{key:"includeThinking",label:"includeThinking"},{key:"resultOnly",label:"resultOnly"},{key:"debug",label:"debug"},{key:"preBash",label:"preBash"},{key:"maxTurnTimeMins",label:"maxTurnTimeMins"},{key:"maxAutoRecovery",label:"maxAutoRecovery"},{key:"cardTemplateId",label:"cardTemplateId"},{key:"sessionMaxConcurrency",label:"sessionMaxConcurrency"},{key:"clientName",label:"clientName"},{key:"enableMsgToUser",label:"enableMsgToUser"}],r=[];for(const{key:v,label:q}of a){const h=_[v],R=d[v];if(JSON.stringify(h)!==JSON.stringify(R)){const N=C=>C==null?"(\u672A\u8BBE\u7F6E)":JSON.stringify(C);r.push(`${q}: ${N(h)} \u2192 ${N(R)}`)}}const s=new Set(_.conversations.map(v=>v.conversationId)),y=new Set(d.conversations.map(v=>v.conversationId)),n=new Map(_.conversations.map(v=>[v.conversationId,v])),m=new Map(d.conversations.map(v=>[v.conversationId,v])),T=[];for(const v of y)s.has(v)||T.push(v);const I=[];for(const v of s)y.has(v)||I.push(v);const U=[{key:"dingToken",label:"dingToken"},{key:"model",label:"model"},{key:"linkConversationId",label:"linkConversationId"},{key:"conversationTitle",label:"conversationTitle"},{key:"whiteUserList",label:"whiteUserList"},{key:"atSender",label:"atSender"},{key:"receiveReply",label:"receiveReply"},{key:"preBash",label:"preBash"},{key:"permissionMode",label:"permissionMode"},{key:"streaming",label:"streaming"},{key:"freedomMode",label:"freedomMode"},{key:"qaMode",label:"qaMode"},{key:"maxTurnTimeMins",label:"maxTurnTimeMins"}],u=[];for(const v of y){if(!s.has(v))continue;const q=n.get(v),h=m.get(v),R=[];for(const{key:N,label:C}of U)JSON.stringify(q[N])!==JSON.stringify(h[N])&&R.push(C);if(R.length>0){const N=h.conversationTitle||v;u.push(`${N}(${v}): ${R.join(", ")}`)}}return T.length>0&&o.push(`- \u65B0\u589E\u4F1A\u8BDD: ${T.map(v=>`{${v}}`).join(", ")}`),I.length>0&&o.push(`- \u79FB\u9664\u4F1A\u8BDD: ${I.map(v=>`{${v}}`).join(", ")}`),u.length>0&&o.push(`- \u53D8\u66F4\u4F1A\u8BDD: ${u.map(v=>`{${v}}`).join(", ")}`),r.length>0&&o.push(`- \u5168\u5C40\u53D8\u66F4: ${r.join(", ")}`),o}class ge{constructor(d){this.resolvedPhones={},this.activeSessions=new Map,this.pendingAuthRequests=new Map,this.recorderModeConversations=new Set,this.pendingFreedomConvs=new Map,this.pendingDestroyConfirmations=new Map,this.DEFAULT_SESSION_MAX_CONCURRENCY=5,this.DEFAULT_TASK_HANDLER_COUNT=1,this.DEFAULT_TASK_QUEUE_SIZE=50,this.sendDingMessage=o=>(0,j.sendDingMessage)(this,o),this.sendClaudeResponseToDing=(o,a,r,s)=>(0,j.sendClaudeResponseToDing)(this,o,a,r,s),this.parseClaudeStreamLine=H.parseClaudeStreamLine,this.interruptClaudeProcess=(o,a)=>(0,H.interruptClaudeProcess)(o,a),this.executeClaudeQuery=(o,a,r)=>(0,H.executeClaudeQuery)(this,o,a,r),this.getClientDir=()=>(0,c.getClientDir)(this),this.getClientConfig=()=>(0,c.getClientConfig)(this),this.authCheck=(o,a)=>(0,c.authCheck)(this,o,a),this.isOwner=o=>(0,c.isOwner)(this,o),this.isAdmin=o=>(0,c.isAdmin)(this,o),this.isOwnerOrAdmin=o=>(0,c.isOwnerOrAdmin)(this,o),this.debugLog=(o,...a)=>(0,c.debugLog)(this,o,...a),this.hashConversationId=o=>(0,c.hashConversationId)(this,o),this.getConversationConfig=o=>(0,c.getConversationConfig)(this,o),this.getConversationDir=o=>(0,c.getConversationDir)(this,o),this.getSessionsDir=o=>(0,c.getSessionsDir)(this,o),this.getTasksDir=o=>(0,c.getTasksDir)(this,o),this.getSessionDir=o=>(0,c.getSessionDir)(this,o),this.getSessionId=c.getSessionId,this.formatSessionInfo=o=>(0,c.formatSessionInfo)(this,o),this.readSessionLogTail=(o,a)=>(0,c.readSessionLogTail)(this,o,a),this.findActiveSession=o=>(0,c.findActiveSession)(this,o),this.findHistorySession=(o,a)=>(0,c.findHistorySession)(this,o,a),this.findLatestSession=o=>(0,c.findLatestSession)(this,o),this.updateSessionFile=(o,a)=>(0,c.updateSessionFile)(this,o,a),this.appendSessionLog=c.appendSessionLog,this.getActiveSessionsFile=o=>(0,c.getActiveSessionsFile)(this,o),this.saveActiveSession=o=>(0,c.saveActiveSession)(this,o),this.loadActiveSessions=()=>(0,c.loadActiveSessions)(this),this.endSession=(o,a)=>(0,c.endSession)(this,o,a),this.switchToSession=(o,a,r,s,y)=>(0,c.switchToSession)(this,o,a,r,s,y),this.startNewSession=o=>(0,c.startNewSession)(this,o),this.handleSessionMessage=o=>(0,c.handleSessionMessage)(this,o),this.cleanCache=(o,a=!0)=>(0,c.cleanCache)(this,o,a),this.formatTaskInfo=()=>(0,P.formatTaskInfo)(this),this.cancelTask=(o,a)=>(0,P.cancelTask)(this,o,a),this.countTodoTask=()=>(0,P.countTodoTask)(this),this.getOneTodoTask=()=>(0,P.getOneTodoTask)(this),this.finishTask=o=>(0,P.finishTask)(this,o),this.handleTask=()=>(0,P.handleTask)(this),this.runTaskHandlerLoop=()=>(0,P.runTaskHandlerLoop)(this),this.saveTask=o=>(0,P.saveTask)(this,o),this.clientId=d,this.config=(0,c.getClientConfig)(this);try{this.dingStreamClient=new ne.DingStreamClient({clientId:d,clientSecret:(0,re.resolveSecret)(this.config.clientSecret),keepAlive:!0,debug:this.config.debug??!1})}catch(o){console.error("Error: DingStreamClient init failed.",o),process.exit(1)}this.cronEngine=new J.CronEngine(this),this.timerEngine=new ee.TimerEngine(this),this.sendQueueProcessor=new de.SendQueueProcessor(this),(0,B.initModelOptions)(this)}async requireOwnerOrAdmin(d,o,a){return this.isOwner(a)||this.isAdmin(a)?!0:(await this.sendDingMessage({conversationId:d,sessionWebhook:o,content:"\u274C \u53EA\u6709\u673A\u5668\u4EBA owner \u6216\u7BA1\u7406\u5458\u624D\u80FD\u6267\u884C\u6B64\u64CD\u4F5C",msgType:"markdown"}),!1)}appendBashAudit(d,o,a){try{const r=Q.default.join(this.getClientDir(),"bash-audit.log"),s=`[${(0,c.timestamp)()}] conversation=${d} user=${o} cmd=${JSON.stringify(a)}
|
|
2
2
|
`;S.default.appendFileSync(r,s,{encoding:"utf-8",mode:(0,F.isWindows)()?void 0:384})}catch(r){console.error("\u5199\u5165 bash \u5BA1\u8BA1\u65E5\u5FD7\u5931\u8D25:",r)}}async requireOwner(d,o,a){return this.isOwner(a)?!0:(await this.sendDingMessage({conversationId:d,sessionWebhook:o,content:"\u274C \u53EA\u6709\u673A\u5668\u4EBA owner \u624D\u80FD\u6267\u884C\u6B64\u64CD\u4F5C",msgType:"markdown"}),!1)}async handleAuthRequest(d){const{senderStaffId:o,senderNick:a,conversationId:r,conversationType:s,conversationTitle:y,sessionWebhook:n}=d;if(!this.config.ownerConversationId){await this.sendDingMessage({conversationId:r,sessionWebhook:n,content:["\u62B1\u6B49,\u60A8\u6682\u65E0\u4F7F\u7528\u6743\u9650","\u8BF7\u8054\u7CFB\u673A\u5668\u4EBA owner \u7533\u8BF7\u6388\u6743"].join(`
|
|
3
|
-
`),msgType:"markdown"});return}for(const
|
|
4
|
-
`);await(0,Z.sendOwnerMessage)(this,I,"markdown")?await this.sendDingMessage({conversationId:r,sessionWebhook:n,content:"\u2705 \u5DF2\u5411\u7BA1\u7406\u5458\u53D1\u9001\u6388\u6743\u7533\u8BF7\uFF0C\u8BF7\u7B49\u5F85\u5BA1\u6279...",msgType:"markdown"}):(this.pendingAuthRequests.delete(
|
|
3
|
+
`),msgType:"markdown"});return}for(const u of this.pendingAuthRequests.values())if(u.senderStaffId===o&&u.conversationId===r){await this.sendDingMessage({conversationId:r,sessionWebhook:n,content:"\u23F3 \u6388\u6743\u7533\u8BF7\u5DF2\u53D1\u9001\uFF0C\u8BF7\u7B49\u5F85\u7BA1\u7406\u5458\u5BA1\u6279...",msgType:"markdown"});return}const m=`r${Date.now().toString(36)}`,T={id:m,senderStaffId:o,senderNick:a,conversationId:r,conversationType:s,conversationTitle:y,requestTime:Date.now()};this.pendingAuthRequests.set(m,T),console.log(`[${(0,c.timestamp)()}] \u65B0\u6388\u6743\u7533\u8BF7: id=${m}, userId=${o}, \u6635\u79F0=${a}, \u4F1A\u8BDD=${r}`);const I=["\u{1F4CB} **\u6536\u5230\u6388\u6743\u7533\u8BF7**",`- **\u7528\u6237ID:** ${o}`,`- **\u6635\u79F0:** ${a}`,`- **\u4F1A\u8BDDID:** ${r}`,y?`- **\u4F1A\u8BDD\u6807\u9898:** ${y}`:"",`- **\u4F1A\u8BDD\u7C7B\u578B:** ${s==="1"?"\u5355\u804A":s==="2"?"\u7FA4\u804A":s||"-"}`,"",`\u56DE\u590D \`/auth approve ${m}\` \u901A\u8FC7`,`\u56DE\u590D \`/auth reject ${m}\` \u62D2\u7EDD`].filter(Boolean).join(`
|
|
4
|
+
`);await(0,Z.sendOwnerMessage)(this,I,"markdown")?await this.sendDingMessage({conversationId:r,sessionWebhook:n,content:"\u2705 \u5DF2\u5411\u7BA1\u7406\u5458\u53D1\u9001\u6388\u6743\u7533\u8BF7\uFF0C\u8BF7\u7B49\u5F85\u5BA1\u6279...",msgType:"markdown"}):(this.pendingAuthRequests.delete(m),await this.sendDingMessage({conversationId:r,sessionWebhook:n,content:"\u274C \u6388\u6743\u7533\u8BF7\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u624B\u52A8\u6388\u6743",msgType:"markdown"}))}async handleCronCommand(d,o){const{conversationId:a,sessionWebhook:r,senderStaffId:s,senderNick:y,conversationConfig:n}=o;switch(d.type){case"list":{const m=await this.getOrCreateLogSession(a,r,s,y,n,!0),T=this.cronEngine.listJobs(a);m.sessionDir&&(this.appendSessionLog(m.sessionDir,"user","/cron list"),this.appendSessionLog(m.sessionDir,"assistant",`\u5217\u51FA ${T.length} \u4E2A\u5B9A\u65F6\u4EFB\u52A1`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,J.formatCronJobList)(T),msgType:"markdown"});return}case"delete":{const m=this.cronEngine.removeJob(d.id),T=await this.getOrCreateLogSession(a,r,s,y,n);T.sessionDir&&(this.appendSessionLog(T.sessionDir,"user",`/cron delete ${d.id}`),this.appendSessionLog(T.sessionDir,"assistant",m?`\u5220\u9664\u5B9A\u65F6\u4EFB\u52A1 ${d.id}`:`\u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${d.id}`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:m?`\u2705 \u5B9A\u65F6\u4EFB\u52A1 **${d.id}** \u5DF2\u5220\u9664`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${d.id}`,msgType:"markdown"});return}case"pause":{const m=this.cronEngine.toggleJob(d.id,!1),T=await this.getOrCreateLogSession(a,r,s,y,n);T.sessionDir&&(this.appendSessionLog(T.sessionDir,"user",`/cron pause ${d.id}`),this.appendSessionLog(T.sessionDir,"assistant",m?`\u6682\u505C\u5B9A\u65F6\u4EFB\u52A1 ${d.id}`:`\u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${d.id}`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:m?`\u23F8\uFE0F \u5B9A\u65F6\u4EFB\u52A1 **${d.id}** \u5DF2\u6682\u505C`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${d.id}`,msgType:"markdown"});return}case"resume":{const m=this.cronEngine.toggleJob(d.id,!0),T=await this.getOrCreateLogSession(a,r,s,y,n);T.sessionDir&&(this.appendSessionLog(T.sessionDir,"user",`/cron resume ${d.id}`),this.appendSessionLog(T.sessionDir,"assistant",m?`\u6062\u590D\u5B9A\u65F6\u4EFB\u52A1 ${d.id}`:`\u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${d.id}`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:m?`\u25B6\uFE0F \u5B9A\u65F6\u4EFB\u52A1 **${d.id}** \u5DF2\u6062\u590D`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${d.id}`,msgType:"markdown"});return}case"create_cron":{if(!(0,J.isValidCronExpression)(d.cronExpression)){await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u274C \u65E0\u6548\u7684cron\u8868\u8FBE\u5F0F: \`${d.cronExpression}\`
|
|
5
5
|
|
|
6
|
-
\u{1F4A1} \u683C\u5F0F: \`\u5206 \u65F6 \u65E5 \u6708 \u5468\`\uFF0C\u5982 \`0 9 * * *\``,msgType:"markdown"});return}if(!this.hasNotifyCapability(o.conversationConfig)){await this.sendCronNoNotifyError(a,r);return}const
|
|
6
|
+
\u{1F4A1} \u683C\u5F0F: \`\u5206 \u65F6 \u65E5 \u6708 \u5468\`\uFF0C\u5982 \`0 9 * * *\``,msgType:"markdown"});return}if(!this.hasNotifyCapability(o.conversationConfig)){await this.sendCronNoNotifyError(a,r);return}const m=this.cronEngine.addJob({conversationId:a,cronExpression:d.cronExpression,description:this.sanitizeLogContent(d.prompt.substring(0,50)),prompt:d.prompt,senderStaffId:s,senderNick:y}),T=await this.getOrCreateLogSession(a,r,s,y,n);T.sessionDir&&(this.appendSessionLog(T.sessionDir,"user",`/cron ${d.cronExpression} ${this.sanitizeLogContent(d.prompt)}`),this.appendSessionLog(T.sessionDir,"assistant",`\u521B\u5EFA\u5B9A\u65F6\u4EFB\u52A1: ${m.id} [${m.cronExpression}] ${m.description}`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,J.formatCronJobInfo)(m),msgType:"markdown"});return}case"create_nl":{if(!this.hasNotifyCapability(o.conversationConfig)){await this.sendCronNoNotifyError(a,r);return}await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:"\u23F3 \u6B63\u5728\u5206\u6790\u5B9A\u65F6\u4EFB\u52A1\u63CF\u8FF0..."});const m=await this.cronEngine.analyzeAndCreate(a,d.input,s,y),T=await this.getOrCreateLogSession(a,r,s,y,n);m.job?(T.sessionDir&&(this.appendSessionLog(T.sessionDir,"user",`/cron ${this.sanitizeLogContent(d.input)}`),this.appendSessionLog(T.sessionDir,"assistant",`\u521B\u5EFA\u5B9A\u65F6\u4EFB\u52A1: ${m.job.id} [${m.job.cronExpression}] ${m.job.description}`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,J.formatCronJobInfo)(m.job),msgType:"markdown"})):(T.sessionDir&&(this.appendSessionLog(T.sessionDir,"user",`/cron ${this.sanitizeLogContent(d.input)}`),this.appendSessionLog(T.sessionDir,"assistant",`\u5B9A\u65F6\u4EFB\u52A1\u5206\u6790\u5931\u8D25: ${m.error}`)),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u274C \u5B9A\u65F6\u4EFB\u52A1\u5206\u6790\u5931\u8D25: ${m.error}
|
|
7
7
|
|
|
8
|
-
\u{1F4A1} \u4F60\u4E5F\u53EF\u4EE5\u76F4\u63A5\u6307\u5B9Acron\u8868\u8FBE\u5F0F: \`/cron 0 9 * * * \u4EFB\u52A1\u63CF\u8FF0\``,msgType:"markdown"}));return}}}async handleTimerCommand(d,o){const{conversationId:a,sessionWebhook:r,senderStaffId:s,senderNick:y}=o;switch(d.action){case"list":{const n=this.timerEngine.listTimers(a);await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,ee.formatTimerList)(n),msgType:"markdown"});return}case"cancel":{const n=this.timerEngine.removeTimer(d.id);await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:n?`\u2705 \u5B9A\u65F6\u63D0\u9192 **${d.id}** \u5DF2\u53D6\u6D88`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u63D0\u9192: ${d.id}`,msgType:"markdown"});return}case"add":{const n=Date.now(),
|
|
8
|
+
\u{1F4A1} \u4F60\u4E5F\u53EF\u4EE5\u76F4\u63A5\u6307\u5B9Acron\u8868\u8FBE\u5F0F: \`/cron 0 9 * * * \u4EFB\u52A1\u63CF\u8FF0\``,msgType:"markdown"}));return}}}async handleTimerCommand(d,o){const{conversationId:a,sessionWebhook:r,senderStaffId:s,senderNick:y}=o;switch(d.action){case"list":{const n=this.timerEngine.listTimers(a);await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,ee.formatTimerList)(n),msgType:"markdown"});return}case"cancel":{const n=this.timerEngine.removeTimer(d.id);await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:n?`\u2705 \u5B9A\u65F6\u63D0\u9192 **${d.id}** \u5DF2\u53D6\u6D88`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u63D0\u9192: ${d.id}`,msgType:"markdown"});return}case"add":{const n=Date.now(),m=this.timerEngine.addTimer({id:`timer_${n}`,conversationId:a,delayMs:d.delayMs,fireAt:n+d.delayMs,prompt:d.prompt,description:d.description,createdAt:new Date(n).toLocaleString(),senderStaffId:s,senderNick:y});await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,ee.formatTimerInfo)(m),msgType:"markdown"});return}}}async handleMenuCommand(d,o){const{conversationId:a,sessionWebhook:r,senderStaffId:s}=o;if((d.type==="add"||d.type==="del")&&d.isGlobal&&!this.isOwnerOrAdmin(s)){await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:"\u274C \u5168\u5C40\u83DC\u5355\u4EC5 owner \u6216\u7BA1\u7406\u5458\u53EF\u7BA1\u7406",msgType:"markdown"});return}switch(d.type){case"show":{const y=(0,A.getMergedMenu)(this,a,s),n=(0,A.loadMenuData)(this).global.length;y.length>0&&(0,A.setPendingSelection)(a,s,r,y),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,A.formatMenuDisplay)(y,n),msgType:"markdown"});return}case"add":{const y=(0,A.addMenuItem)(this,a,s,d.isGlobal,"",d.command);await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u2705 \u5DF2\u6DFB\u52A0${d.isGlobal?"\u5168\u5C40":"\u4E2A\u4EBA"}\u5FEB\u6377\u6307\u4EE4: **${y.label}** \u2192 \`${y.command}\``,msgType:"markdown"});return}case"del":{const y=(0,A.deleteMenuItem)(this,a,s,d.isGlobal,String(d.index));await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:y.success?`\u2705 \u5DF2\u5220\u9664${d.isGlobal?"\u5168\u5C40":"\u4E2A\u4EBA"}\u5FEB\u6377\u6307\u4EE4: **${y.deletedItem.label}**`:`\u26A0\uFE0F ${y.error}`,msgType:"markdown"});return}case"list":{await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:(0,A.formatMenuList)(this,a,s,d.isGlobal),msgType:"markdown"});return}case"trigger":{(0,A.setUserTrigger)(this,s,d.word),await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u2705 \u83DC\u5355\u89E6\u53D1\u8BCD\u5DF2\u8BBE\u7F6E\u4E3A \`${d.word}\`\uFF0C\u53D1\u9001\u8BE5\u8BCD\u5373\u53EF\u5524\u8D77\u83DC\u5355`,msgType:"markdown"});return}}}async handleTodoCommand(d,o){const{conversationId:a,sessionWebhook:r,senderStaffId:s,senderNick:y}=o;if(d.type==="mode"){(0,b.setIdMode)(this,a,d.mode);const n=d.mode==="staffId"?"\u5DE5\u53F7(staffId)":"\u9489\u9489ID(dingtalkId)";await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u2705 \u7528\u6237\u6807\u8BC6\u6A21\u5F0F\u5DF2\u5207\u6362\u4E3A: **${n}**
|
|
9
9
|
|
|
10
|
-
\u65B0\u6DFB\u52A0\u7684\u5F85\u529E\u5C06\u4F7F\u7528\u6B64\u6A21\u5F0F\u8BB0\u5F55\u8D1F\u8D23\u4EBA`,msgType:"markdown"});return}if(d.type==="list"){const n=(0,b.getSortedTodoItems)(this,a),
|
|
10
|
+
\u65B0\u6DFB\u52A0\u7684\u5F85\u529E\u5C06\u4F7F\u7528\u6B64\u6A21\u5F0F\u8BB0\u5F55\u8D1F\u8D23\u4EBA`,msgType:"markdown"});return}if(d.type==="list"){const n=(0,b.getSortedTodoItems)(this,a),m=(0,b.getReminderHour)(this,a),I=(0,b.getIdMode)(this,a)==="staffId"?"\u5DE5\u53F7\u6A21\u5F0F":"\u9489\u9489ID\u6A21\u5F0F",U=(0,b.formatTodoList)(n,m),u=`\u{1F4CC} \u5F53\u524D\u6807\u8BC6\u6A21\u5F0F: **${I}**
|
|
11
11
|
|
|
12
|
-
${U}`;await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:
|
|
12
|
+
${U}`;await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:u,msgType:"markdown"});return}if(d.type==="remind"){(0,b.setReminderHour)(this,a,d.hour);const n=d.hour===null?"\u23F0 \u6BCF\u65E5\u63D0\u9192\u5DF2\u5173\u95ED":`\u23F0 \u6BCF\u65E5\u63D0\u9192\u5DF2\u8BBE\u7F6E\u4E3A ${d.hour}:00`;await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:n});return}if(d.type==="done"){const n=(0,b.doneTodoItem)(this,a,d.index);n.success&&n.item?await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u2705 \u5DF2\u5B8C\u6210: ~~${n.item.content}~~ _@${n.item.assigneeNick}_`,msgType:"markdown"}):await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u274C ${n.error}`});return}if(d.type==="remove"){if(d.index==="all"){const n=(0,b.clearAllTodoItems)(this,a);n.success?await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A ${n.count} \u6761\u5F85\u529E`}):await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u274C ${n.error}`})}else{const n=(0,b.deleteTodoItem)(this,a,d.index);n.success&&n.item?await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u{1F5D1}\uFE0F \u5DF2\u5220\u9664: ~~${n.item.content}~~`,msgType:"markdown"}):await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:`\u274C ${n.error}`})}return}if(d.type==="add"){const n=(0,b.getIdMode)(this,a),m=d.assigneeId||s,T=d.assigneeNick||y,I=d.deadline&&(0,b.parseDeadline)(d.deadline)||(0,b.getDefaultDeadline)(),U=(0,b.addTodoItem)(this,a,{content:d.content,assigneeStaffId:m,assigneeNick:T,deadline:I,assigneeIdType:n}),v=(0,b.getSortedTodoItems)(this,a).findIndex(h=>h.content===U.content&&h.createdAt===U.createdAt)+1,q=(0,b.formatTodoItemCreated)(U,v);await this.sendDingMessage({conversationId:a,sessionWebhook:r,content:q,msgType:"markdown"});return}}sanitizeLogContent(d){return d.replace(/\n/g,"\\n").replace(/\r/g,"\\r")}sanitizeOutput(d){const o=d.replace(/\r\n/g,`
|
|
13
13
|
`),a=8e3;return o.length>a?o.substring(0,a)+`
|
|
14
|
-
...(\u8F93\u51FA\u5DF2\u622A\u65AD)`:o}truncateMsg(d,o=100){const a=d.replace(/\n/g," ").trim();return a.length>o?a.slice(0,o)+"...":a}async getOrCreateLogSession(d,o,a,r,s,y=!1){const n=this.findActiveSession(d);if(n)return{sessionDir:this.getSessionDir(n.session.session),isNew:!1};if(y)return{sessionDir:null,isNew:!1};const
|
|
15
|
-
`,"utf-8"),{sessionDir:I,isNew:!0}}hasNotifyCapability(d){return!!(d.dingToken||this.config.defaultDingToken)}async sendCronNoNotifyError(d,o){await this.sendDingMessage({conversationId:d,sessionWebhook:o,content:"\u274C \u5F53\u524D\u7FA4\u672A\u914D\u7F6E dingToken \u4E14\u65E0\u5BA2\u6237\u7AEF\u7EA7 defaultDingToken, \u5B9A\u65F6\u4EFB\u52A1\u65E0\u6CD5\u4E3B\u52A8\u53D1\u9001\u6D88\u606F, \u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u914D\u7F6E",msgType:"markdown"})}async botMsgGetCallback(d){this.dingStreamClient.socketCallBackResponse(d.headers.messageId,"");const o=JSON.parse(d.data);console.log("rawData",o);const{senderNick:a,senderStaffId:r,conversationId:s,conversationTitle:y,sessionWebhook:n,msgtype:
|
|
14
|
+
...(\u8F93\u51FA\u5DF2\u622A\u65AD)`:o}truncateMsg(d,o=100){const a=d.replace(/\n/g," ").trim();return a.length>o?a.slice(0,o)+"...":a}async getOrCreateLogSession(d,o,a,r,s,y=!1){const n=this.findActiveSession(d);if(n)return{sessionDir:this.getSessionDir(n.session.session),isNew:!1};if(y)return{sessionDir:null,isNew:!1};const m=Date.now(),T={conversationId:d,sessionWebhook:o,startTime:m,startTimeStr:ne.dateUtil.mm(m).format("YYYY-MM-DD-HH-mm-ss"),startStaffId:a,startNickName:`[cron]${r}`},I=this.getSessionDir(T);return S.default.mkdirSync(I,{recursive:!0}),S.default.writeFileSync(`${I}/session.json`,JSON.stringify(T,null,2),"utf-8"),S.default.appendFileSync(`${I}/session.log`,`[${(0,c.timestamp)()}] [SYSTEM]: \u521B\u5EFA\u4F1A\u8BDD\u7528\u4E8E\u8BB0\u5F55 /cron \u547D\u4EE4\u64CD\u4F5C
|
|
15
|
+
`,"utf-8"),{sessionDir:I,isNew:!0}}hasNotifyCapability(d){return!!(d.dingToken||this.config.defaultDingToken)}async sendCronNoNotifyError(d,o){await this.sendDingMessage({conversationId:d,sessionWebhook:o,content:"\u274C \u5F53\u524D\u7FA4\u672A\u914D\u7F6E dingToken \u4E14\u65E0\u5BA2\u6237\u7AEF\u7EA7 defaultDingToken, \u5B9A\u65F6\u4EFB\u52A1\u65E0\u6CD5\u4E3B\u52A8\u53D1\u9001\u6D88\u606F, \u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u914D\u7F6E",msgType:"markdown"})}async botMsgGetCallback(d){this.dingStreamClient.socketCallBackResponse(d.headers.messageId,"");const o=JSON.parse(d.data);console.log("rawData",o);const{senderNick:a,senderStaffId:r,conversationId:s,conversationTitle:y,sessionWebhook:n,msgtype:m,conversationType:T}=o,I=o.text?.content?.trim()??"";if((0,j.cacheUserName)(r,a),o.atUsers)for(const e of o.atUsers){const i=e.staffId||e.dingtalkId,t=e.displayName;i&&t&&(0,j.cacheUserName)(i,t)}const U=o.text?.repliedMsg;if(U?.senderStaffId&&U.senderNick&&(0,j.cacheUserName)(U.senderStaffId,U.senderNick),this.debugLog(`\u6536\u5230\u6D88\u606F: \u7FA4=${y}(${s}), \u53D1\u9001\u8005=${a}(${r}), \u7C7B\u578B=${m}, \u5185\u5BB9=${I.substring(0,50)}`),!this.authCheck(r,s)){await this.handleAuthRequest({senderStaffId:r,senderNick:a,conversationId:s,conversationType:T,conversationTitle:o.conversationTitle,sessionWebhook:n});return}const u=this.getConversationConfig(s),v=(0,k.parseRecorderCommandEnhanced)(I);if(v!==null){if(!this.isOwnerOrAdmin(r)||T!=="1"){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C Recorder \u6A21\u5F0F\u4EC5\u9650 owner \u6216\u7BA1\u7406\u5458\u5355\u804A\u4F7F\u7528",msgType:"markdown"});return}if(v==="on"){this.recorderModeConversations.add(s);const e=(0,te.getRecorderDir)(this,s);console.log(`[${(0,c.timestamp)()}] [recorder] \u5F00\u542F recorder \u6A21\u5F0F: conversationId=${s}, dir=${e}`),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F534} Recorder \u6A21\u5F0F\u5DF2\u5F00\u542F
|
|
16
16
|
- \u6240\u6709\u6D88\u606F\u5C06\u88AB\u5206\u7C7B\u8BB0\u5F55\u5230\u672C\u5730
|
|
17
17
|
- \u4FDD\u5B58\u76EE\u5F55: \`${e}\`
|
|
18
18
|
- \u53D1\u9001 \`/recorder exit\` \u5173\u95ED`,msgType:"markdown"})}else this.recorderModeConversations.delete(s),console.log(`[${(0,c.timestamp)()}] [recorder] \u5173\u95ED recorder \u6A21\u5F0F: conversationId=${s}`),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2B1C Recorder \u6A21\u5F0F\u5DF2\u5173\u95ED\uFF0C\u6062\u590D\u6B63\u5E38\u5904\u7406",msgType:"markdown"});return}const q=this.pendingFreedomConvs.get(s);if(q&&Date.now()-q<6e4){const e=I.trim().toLowerCase();if(e==="\u786E\u8BA4"||e==="confirm"){this.pendingFreedomConvs.delete(s);const i=this.getConversationConfig(s);i&&(i.freedomMode=!0,(0,L.saveClientConfig)(this)),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u81EA\u7531\u6A21\u5F0F\u5DF2\u5F00\u542F
|
|
19
|
-
\u{1F4A1} \u6240\u6709\u7FA4\u6210\u5458\u73B0\u5728\u5747\u53EF\u4F7F\u7528\u673A\u5668\u4EBA`,msgType:"markdown"});return}}else q&&Date.now()-q>=6e4&&this.pendingFreedomConvs.delete(s);if(this.recorderModeConversations.has(s)){try{await(0,te.recordMessage)(this,o,s),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u8BB0\u5F55 ${
|
|
20
|
-
`),msgType:"markdown"});return}const i=e.conversationId||s,t=i!==s,g=t?this.config.conversations.find(
|
|
19
|
+
\u{1F4A1} \u6240\u6709\u7FA4\u6210\u5458\u73B0\u5728\u5747\u53EF\u4F7F\u7528\u673A\u5668\u4EBA`,msgType:"markdown"});return}}else q&&Date.now()-q>=6e4&&this.pendingFreedomConvs.delete(s);if(this.recorderModeConversations.has(s)){try{await(0,te.recordMessage)(this,o,s),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u8BB0\u5F55 ${m}`})}catch(e){console.error(`[${(0,c.timestamp)()}] [recorder] \u8BB0\u5F55\u6D88\u606F\u5931\u8D25:`,e),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u8BB0\u5F55\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`})}return}let h;if(m==="picture"&&o.pictureDownloadCode){const e=this.getConversationDir(s),i=u?.useLocalOcr!==!1,t=await(0,G.processPictureMessage)(this,o.pictureDownloadCode,o.robotCode,e,i,I||void 0);if(!t){await this.sendDingMessage({conversationId:s,sessionWebhook:n,atUserId:r,content:"\u26A0\uFE0F \u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u6216\u4F7F\u7528\u6587\u5B57\u63CF\u8FF0"});return}h=t}else if(m==="richText"&&o.content?.richText){const e=this.getConversationDir(s),i=u?.useLocalOcr!==!1;h=await(0,G.processRichTextMessage)(this,o.content.richText,o.robotCode,e,i)}else if(m==="file"){const e=(0,G.extractDownloadCode)(o);if(e){const i=this.getConversationDir(s),t=await(0,G.processFileMessage)(this,e,o.robotCode,i,I||void 0);if(!t){await this.sendDingMessage({conversationId:s,sessionWebhook:n,atUserId:r,content:"\u26A0\uFE0F \u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5"});return}h=t}else{await this.sendDingMessage({conversationId:s,sessionWebhook:n,atUserId:r,content:"\u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4E0B\u8F7D\u94FE\u63A5\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001"});return}}else{if(h=I,!h){const e=this.getConversationDir(s),i=u?.useLocalOcr!==!1,t=(0,O.extractQuoteInfo)(o);t&&(this.debugLog(`\u68C0\u6D4B\u5230\u5F15\u7528\u6D88\u606F(\u65E0\u6B63\u6587): quoteMessageId=${t.quoteMessageId}`),await(0,O.enrichQuoteInfo)(this,t,o,e,i),t.quoteText&&(h=(0,O.formatPromptWithQuote)("",t)))}if(!h)return}if(!h.startsWith("/")&&m==="text"&&I){const e=this.getConversationDir(s),i=u?.useLocalOcr!==!1,t=(0,O.extractQuoteInfo)(o);t&&(this.debugLog(`\u68C0\u6D4B\u5230\u5F15\u7528\u6D88\u606F: quoteMessageId=${t.quoteMessageId}`),await(0,O.enrichQuoteInfo)(this,t,o,e,i),t.quoteText&&(h=(0,O.formatPromptWithQuote)(h,t)))}if(m==="text"&&h&&!h.startsWith("/")){if(h.toLowerCase()===(0,A.getUserTrigger)(this,r).toLowerCase())h="/menu";else if(/^\d+$/.test(h)&&(0,A.hasPendingSelection)(s,r)){const e=(0,A.getPendingSelection)(s,r);(0,A.clearPendingSelection)(s,r);const i=parseInt(h,10);if(i<1||i>e.mergedItems.length){await this.sendDingMessage({conversationId:s,sessionWebhook:n,atUserId:r,content:`\u26A0\uFE0F \u5E8F\u53F7\u65E0\u6548\uFF0C\u83DC\u5355\u5171 ${e.mergedItems.length} \u9879`});return}const t=e.mergedItems[i-1];console.log(`[${(0,c.timestamp)()}] [menu] ${a} \u9009\u62E9\u5FEB\u6377\u6307\u4EE4: ${t.label} \u2192 ${t.command}`),h=t.command}}const R=[(0,M.route)("/cfg",()=>(0,k.parseCfgCommand)(h),async e=>{if(e.conversationId&&!this.isOwnerOrAdmin(r)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u53EA\u6709 owner \u6216\u7BA1\u7406\u5458\u624D\u80FD\u64CD\u4F5C\u5176\u4ED6\u7FA4\u7684\u914D\u7F6E",msgType:"markdown"});return}if(!await this.requireOwnerOrAdmin(s,n,r))return;if(e.reload){let D;try{const{config:x}=(0,c.reloadClientConfig)(this);D=x}catch(x){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u914D\u7F6E\u91CD\u8F7D\u5931\u8D25: ${x.message}`,msgType:"markdown"});return}const $=this.config,W=ce($,D);this.config=D,await(0,c.resolveAllPhonesInConfig)(this).catch(x=>{console.warn("[reload] \u624B\u673A\u53F7\u89E3\u6790\u5931\u8D25:",x)}),(0,B.initModelOptions)(this),console.log(`[${(0,c.timestamp)()}] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D`);const E=["\u2705 \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D"];if(W.length>0){E.push("","\u{1F4CB} \u53D8\u66F4\u6458\u8981:");for(const x of W)E.push(x)}else E.push("","\u2139\uFE0F \u914D\u7F6E\u65E0\u53D8\u66F4");await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:E.join(`
|
|
20
|
+
`),msgType:"markdown"});return}const i=e.conversationId||s,t=i!==s,g=t?this.config.conversations.find(D=>D.conversationId===i):u,w=!!(e.dingToken||e.linkConversationId||e.whiteUserList&&e.whiteUserList.length>0||e.conversationTitle||e.atSender!==void 0||e.receiveReply!==void 0||e.preBash!==void 0||e.permissionMode!==void 0||e.streaming!==void 0||e.cardTemplateId||e.model||e.enableMsgToUser!==void 0||e.ensureAt!==void 0);if(g&&w){if(e.conversationTitle&&(g.conversationTitle=e.conversationTitle),T&&!t&&(g.conversationType=T),e.dingToken&&(g.dingToken=e.dingToken),e.linkConversationId&&(g.linkConversationId=e.linkConversationId),e.atSender!==void 0&&(g.atSender=e.atSender),e.receiveReply!==void 0&&(g.receiveReply=e.receiveReply),e.preBash!==void 0&&(g.preBash=e.preBash),e.permissionMode!==void 0&&(g.permissionMode=e.permissionMode),e.streaming!==void 0&&(g.streaming=e.streaming),e.ensureAt!==void 0&&(g.ensureAt=e.ensureAt),e.model&&(g.model=e.model),e.cardTemplateId&&(this.config.cardTemplateId=e.cardTemplateId),e.enableMsgToUser!==void 0&&(this.config.enableMsgToUser=e.enableMsgToUser),e.whiteUserList&&e.whiteUserList.length>0){g.whiteUserList=e.whiteUserList;for(const D of e.whiteUserList)(0,c.isMobile)(D)&&await(0,c.resolveUserId)(this,D)}(0,L.saveClientConfig)(this),console.log(`[${(0,c.timestamp)()}] \u5237\u65B0\u7FA4\u914D\u7F6E: ${g.conversationTitle||i}(${i})`)}else if(!g){const D={conversationId:i,conversationType:t?"1":T,conversationTitle:e.conversationTitle||(t?"":y)};if(e.dingToken&&(D.dingToken=e.dingToken),e.linkConversationId&&(D.linkConversationId=e.linkConversationId),e.atSender!==void 0&&(D.atSender=e.atSender),e.receiveReply!==void 0&&(D.receiveReply=e.receiveReply),e.preBash!==void 0&&(D.preBash=e.preBash),e.permissionMode!==void 0&&(D.permissionMode=e.permissionMode),e.streaming!==void 0&&(D.streaming=e.streaming),e.ensureAt!==void 0&&(D.ensureAt=e.ensureAt),e.model&&(D.model=e.model),e.cardTemplateId&&(this.config.cardTemplateId=e.cardTemplateId),e.enableMsgToUser!==void 0&&(this.config.enableMsgToUser=e.enableMsgToUser),e.whiteUserList&&e.whiteUserList.length>0){D.whiteUserList=e.whiteUserList;for(const $ of e.whiteUserList)(0,c.isMobile)($)&&await(0,c.resolveUserId)(this,$)}this.config.conversations.push(D),(0,L.saveClientConfig)(this),console.log(`[${(0,c.timestamp)()}] \u6CE8\u518C\u65B0\u7FA4: ${D.conversationTitle||i}(${i}) \u7C7B\u578B=${D.conversationType||"-"}`)}const f=this.getConversationDir(i);S.default.existsSync(f)||(S.default.mkdirSync(f,{recursive:!0}),console.log(`[${(0,c.timestamp)()}] \u521B\u5EFA\u5DE5\u4F5C\u76EE\u5F55: ${f}`));const l=g||this.getConversationConfig(i),p=[g?"\u2705 \u7FA4\u914D\u7F6E\u5DF2\u5237\u65B0":"\u2705 \u7FA4\u5DF2\u6CE8\u518C",`- **\u7FA4\u540D\u79F0:** ${l?.conversationTitle||i}`,`- **\u7FA4ID:** ${i}`];if(l?.conversationType&&p.push(`- **\u4F1A\u8BDD\u7C7B\u578B:** ${l.conversationType==="1"?"\u5355\u804A":l.conversationType==="2"?"\u7FA4\u804A":l.conversationType}`),l?.dingToken?p.push(`- **dingToken:** ${l.dingToken.substring(0,8)}...`):p.push("- **dingToken:** (\u672A\u6307\u5B9A, \u4F7F\u7528 defaultDingToken)"),l?.linkConversationId&&p.push(`- **linkConversationId:** ${l.linkConversationId}`),l?.atSender===!1&&p.push("- **atSender:** false (\u4E0D @ \u53D1\u9001\u4EBA)"),l?.receiveReply===!1&&p.push("- **receiveReply:** false (\u4E0D\u56DE\u590D\u786E\u8BA4\u6D88\u606F)"),l?.permissionMode&&p.push(`- **permissionMode:** ${l.permissionMode}`),l?.streaming&&p.push("- **streaming:** true (AI Card \u6D41\u5F0F\u8F93\u51FA)"),l?.ensureAt&&p.push("- **ensureAt:** true (\u8FFD\u52A0 text \u6D88\u606F\u786E\u4FDD @ \u901A\u77E5\u751F\u6548)"),l?.model&&p.push(`- **model:** ${l.model}`),l?.whiteUserList?.length){const D=l.whiteUserList.map($=>(0,c.isMobile)($)?$:(0,c.userIdToPhone)(this,$)||$).join(", ");p.push(`- **whiteUserList:** ${D}`)}p.push(`- **\u5DE5\u4F5C\u76EE\u5F55:** ${f}`),p.push(`- **enableMsgToUser:** ${this.config.enableMsgToUser?"true":"false"} (\u79C1\u804A\u6D88\u606F\u5F00\u5173)`),p.push(`
|
|
21
21
|
\u{1F4A1} \u53EF\u7F16\u8F91 config.json \u8865\u5145\u66F4\u591A\u914D\u7F6E`),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:p.join(`
|
|
22
|
-
`),msgType:"markdown"})}),(0,M.route)("/help",()=>(0,
|
|
23
|
-
`);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:
|
|
22
|
+
`),msgType:"markdown"})}),(0,M.route)("/help",()=>(0,k.parseHelpCommand)(h),async()=>{await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:(0,k.formatHelpOverview)(se,this.isOwnerOrAdmin(r)),msgType:"markdown"})}),(0,M.route)("/version",()=>(0,k.parseVersionCommand)(h),async()=>{let e="\u672A\u5B89\u88C5";try{const{stdout:g}=await new Promise((w,f)=>{(0,V.exec)("claude --version",{timeout:5e3},(l,p,D)=>{l?f(l):w({stdout:p})})});e=(g.trim()||"\u672A\u77E5").replace(/\s*\(.*\)\s*$/,"")}catch{}let i="\u672A\u5B89\u88C5";try{const{stdout:g}=await new Promise((w,f)=>{(0,V.exec)("codex --version",{timeout:5e3},(l,p,D)=>{l?f(l):w({stdout:p})})});i=g.trim()||"\u672A\u77E5"}catch{}const t=["### \u{1F4E6} cc-ding \u7248\u672C\u4FE1\u606F","",`- **cc-ding:** ${se}`,`- **claude:** ${e}`,`- **codex:** ${i}`,`- **os:** ${X.default.hostname()} ${X.default.platform()} ${X.default.release()}`,`- **node:** ${process.version}`,`- **cardTemplateId:** ${this.config.cardTemplateId||"(\u672A\u914D\u7F6E)"}`,`- **model:** ${u?.model||this.config.model||"(\u9ED8\u8BA4)"}`].join(`
|
|
23
|
+
`);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:t,msgType:"markdown"})}),(0,M.route)("cmd-help",()=>(0,k.parseCommandHelp)(h),async e=>{const i=(0,k.getCommandByName)(e);i?await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:(0,k.formatCommandHelp)(i),msgType:"markdown"}):await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u672A\u627E\u5230\u547D\u4EE4: **${e}**
|
|
24
24
|
|
|
25
|
-
\u{1F4A1} \u8F93\u5165 \`/help\` \u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4`,msgType:"markdown"})}),(0,M.route)("/reboot",()=>(0,
|
|
25
|
+
\u{1F4A1} \u8F93\u5165 \`/help\` \u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4`,msgType:"markdown"})}),(0,M.route)("/reboot",()=>(0,k.parseRebootCommand)(h),async e=>{if(!await this.requireOwnerOrAdmin(s,n,r))return;if(e.tag&&!/^[\w.\-]+$/.test(e.tag)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u65E0\u6548\u7684 tag\uFF0C\u4EC5\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u70B9\u3001\u6A2A\u7EBF\u548C\u4E0B\u5212\u7EBF",msgType:"markdown"});return}const i=e.tag?`@${e.tag}`:"@latest",t=e.update?`npm install -g cc-ding${i}`:null,g=`cc-ding-${this.clientId}`;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:t?`\u2705 \u66F4\u65B0\u5E76\u91CD\u542F\uFF0C\u6B63\u5728\u6267\u884C ${t}...`:"\u2705 cc-ding \u6B63\u5728\u91CD\u542F\u4E2D...",msgType:"markdown"});const w=Q.default.join(this.getClientDir(),".reboot_pending");S.default.writeFileSync(w,JSON.stringify({conversationId:s,senderStaffId:r,sessionWebhook:n,update:e.update}),"utf-8"),setTimeout(()=>{console.log(`[${(0,c.timestamp)()}] \u6267\u884C pm2 restart ${g}${t?" (\u542B\u66F4\u65B0)":""}`),(0,V.exec)(`${t?`${t} && `:""}pm2 restart "${g}"`,{timeout:6e4},f=>{f&&console.error(`[${(0,c.timestamp)()}] pm2 restart \u5931\u8D25:`,f)})},1e3)})];for(const e of R)if(await e.tryHandle())return;if(!u){console.log(`\u672A\u6CE8\u518C\u7684\u673A\u5668\u4EBA,\u7FA4:${y},${s}`),this.isOwnerOrAdmin(r)?await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u8BE5\u7FA4\u672A\u6CE8\u518C\uFF0C\u8BF7\u5148\u4F7F\u7528 `/cfg` \u547D\u4EE4\u6CE8\u518C",msgType:"markdown"}):await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u62B1\u6B49,\u8BE5\u7FA4\u7684\u673A\u5668\u4EBA\u672A\u5728\u670D\u52A1\u7AEF\u6CE8\u518C,\u8BF7\u8054\u7CFB\u5E94\u7528\u673A\u5668\u4EBAowner\u6CE8\u518C(${s})...`});return}const N=[(0,M.route)("/destroy",()=>(0,k.parseDestroyCommand)(h),async e=>{if(!await this.requireOwnerOrAdmin(s,n,r))return;const i=e.conversationId||s;if(i!==s&&!this.isOwnerOrAdmin(r)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u53EA\u6709 owner \u6216\u7BA1\u7406\u5458\u624D\u80FD\u64CD\u4F5C\u5176\u4ED6\u7FA4\u7684\u914D\u7F6E",msgType:"markdown"});return}const g=this.config.conversations.findIndex($=>$.conversationId===i);if(g<0){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\uFE0F \u8BE5\u7FA4\u672A\u5728\u914D\u7F6E\u4E2D\u6CE8\u518C\uFF0C\u65E0\u9700\u6CE8\u9500",msgType:"markdown"});return}const f=this.config.conversations[g].conversationTitle||i,l=this.pendingDestroyConfirmations.get(i);if(l){clearTimeout(l),this.pendingDestroyConfirmations.delete(i),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u23F3 \u6B63\u5728\u6E05\u7406 ${f}(${i}) \u7684\u6240\u6709\u6570\u636E...`,msgType:"markdown"});const $=await(0,c.destroyConversation)(this,i);this.recorderModeConversations.delete(i),console.log(`[${(0,c.timestamp)()}] \u5DF2\u6CE8\u9500\u7FA4: ${f}(${i})`);const E=[`${$.success?"\u2705":"\uFE0F"} \u5DF2\u6CE8\u9500\u5E76\u6E05\u7406\u6240\u6709\u6570\u636E`,`- **\u7FA4\u540D\u79F0:** ${f}`,`- **\u7FA4ID:** ${i}`];for(const x of $.steps){const ie=x.ok?"\u2713":"";E.push(`${ie} ${x.label}${x.detail?`: ${x.detail}`:""}`)}E.push(`
|
|
26
26
|
\u26A0\uFE0F \u8BE5\u7FA4\u4E0B\u6B21\u53D1\u9001\u6D88\u606F\u65F6\u5C06\u6536\u5230"\u672A\u6CE8\u518C"\u63D0\u793A`),E.push("\u{1F4A1} \u5982\u9700\u91CD\u65B0\u6CE8\u518C\uFF0C\u8BF7\u4F7F\u7528 `/cfg` \u547D\u4EE4"),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:E.join(`
|
|
27
|
-
`),msgType:"markdown"});return}const p=setTimeout(()=>{this.pendingDestroyConfirmations.delete(i),console.log(`[${(0,c.timestamp)()}] \u9500\u6BC1\u786E\u8BA4\u8D85\u65F6: ${i}`)},6e4);this.pendingDestroyConfirmations.set(i,p);const
|
|
28
|
-
`),msgType:"markdown"})}),(0,M.route)("/freedom",()=>(0,
|
|
27
|
+
`),msgType:"markdown"});return}const p=setTimeout(()=>{this.pendingDestroyConfirmations.delete(i),console.log(`[${(0,c.timestamp)()}] \u9500\u6BC1\u786E\u8BA4\u8D85\u65F6: ${i}`)},6e4);this.pendingDestroyConfirmations.set(i,p);const D=["- \u4F1A\u8BDD\u5DE5\u4F5C\u76EE\u5F55\u53CA\u6240\u6709\u4F1A\u8BDD\u8BB0\u5F55","- \u5B9A\u65F6\u4EFB\u52A1\u914D\u7F6E (cron.json)","- Todo \u6570\u636E (todo.json)","- \u5FEB\u6377\u83DC\u5355\u6570\u636E (menu.json)","- \u5EF6\u65F6\u4EFB\u52A1\u6570\u636E (timers.json)","- \u7FA4\u914D\u7F6E (config.json \u4E2D\u8BE5\u7FA4\u7684\u6761\u76EE)"];await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:["\u26A0\uFE0F \u5373\u5C06\u6CE8\u9500\u7FA4\u673A\u5668\u4EBA\u5E76\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55\uFF01\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\u3002","","\u6570\u636E\u6E05\u7406\u8303\u56F4:",...D,"","\u8BF7\u5728 **60 \u79D2\u5185**\u518D\u6B21\u53D1\u9001 `/destroy` \u786E\u8BA4\u64CD\u4F5C\u3002"].join(`
|
|
28
|
+
`),msgType:"markdown"})}),(0,M.route)("/freedom",()=>(0,k.parseFreedomCommand)(h),async e=>{if(await this.requireOwnerOrAdmin(s,n,r)){if(e.action==="enter"){if(u?.freedomMode){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2139\uFE0F \u5F53\u524D\u5DF2\u5904\u4E8E\u81EA\u7531\u6A21\u5F0F",msgType:"markdown"});return}this.pendingFreedomConvs.set(s,Date.now()),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u5F00\u542F\u81EA\u7531\u6A21\u5F0F\u540E\uFF0C\u6240\u6709\u7FA4\u6210\u5458\u5747\u53EF\u4F7F\u7528\u673A\u5668\u4EBA\uFF08\u8DF3\u8FC7\u767D\u540D\u5355\u9650\u5236\uFF09
|
|
29
29
|
|
|
30
|
-
60 \u79D2\u5185\u56DE\u590D\u300C\u786E\u8BA4\u300D\u6216\u300Cconfirm\u300D\u5373\u53EF\u5F00\u542F`,msgType:"markdown"})}else if(e.action==="exit"){if(!
|
|
31
|
-
\u{1F512} \u5DF2\u6062\u590D\u767D\u540D\u5355\u9650\u5236`,msgType:"markdown"})}}}),(0,M.route)("/qa",()=>(0,
|
|
30
|
+
60 \u79D2\u5185\u56DE\u590D\u300C\u786E\u8BA4\u300D\u6216\u300Cconfirm\u300D\u5373\u53EF\u5F00\u542F`,msgType:"markdown"})}else if(e.action==="exit"){if(!u?.freedomMode){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2139\uFE0F \u5F53\u524D\u672A\u5F00\u542F\u81EA\u7531\u6A21\u5F0F",msgType:"markdown"});return}u.freedomMode=!1,(0,L.saveClientConfig)(this),this.pendingFreedomConvs.delete(s),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u81EA\u7531\u6A21\u5F0F\u5DF2\u5173\u95ED
|
|
31
|
+
\u{1F512} \u5DF2\u6062\u590D\u767D\u540D\u5355\u9650\u5236`,msgType:"markdown"})}}}),(0,M.route)("/qa",()=>(0,k.parseQaCommand)(h),async e=>{if(await this.requireOwnerOrAdmin(s,n,r)){if(e.action==="config"){if(!u?.qaMode){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u8BF7\u5148\u5F00\u542F\u95EE\u7B54\u6A21\u5F0F(/qa)\uFF0C\u518D\u914D\u7F6E QA \u53C2\u6570",msgType:"markdown"});return}u.qaCfg||(u.qaCfg={});const i=[];e.gitRepos?.length&&(u.qaCfg.gitRepos=e.gitRepos,i.push(`gitRepos: ${e.gitRepos.join(", ")}`)),e.docs?.length&&(u.qaCfg.docs=e.docs,i.push(`docs: ${e.docs.join(", ")}`)),e.autoPull!==void 0&&(u.qaCfg.autoPull=e.autoPull,i.push(`autoPull: ${e.autoPull?"\u5F00\u542F":"\u5173\u95ED"}`)),(0,L.saveClientConfig)(this),(0,H.refreshSessionContext)(this,s),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 QA \u914D\u7F6E\u5DF2\u66F4\u65B0
|
|
32
32
|
- ${i.join(`
|
|
33
|
-
- `)}`,msgType:"markdown"});return}if(e.action==="enter"){if(
|
|
33
|
+
- `)}`,msgType:"markdown"});return}if(e.action==="enter"){if(u?.qaMode){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2139\uFE0F \u5F53\u524D\u5DF2\u5904\u4E8E\u95EE\u7B54\u6A21\u5F0F",msgType:"markdown"});return}u.qaMode=!0,(0,L.saveClientConfig)(this),(0,H.refreshSessionContext)(this,s),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2705 \u95EE\u7B54\u6A21\u5F0F\u5DF2\u5F00\u542F\n- Claude \u5C06\u4EE5\u53EA\u8BFB plan \u6A21\u5F0F\u8FD0\u884C\n- \u6240\u6709\u7FA4\u6210\u5458\u5747\u53EF\u4F7F\u7528\n- \u4F7F\u7528 `/qa --gitRepos https://github.com/user/repo.git` \u914D\u7F6E\u4ED3\u5E93(\u9996\u6B21 clone\uFF0C\u540E\u7EED pull)\n- \u4F7F\u7528 `/qa --docs url1,url2` \u914D\u7F6E\u53C2\u8003\u6587\u6863\n- \u4F7F\u7528 `/qa --autoPull true` \u5F00\u542F\u81EA\u52A8\u62C9\u53D6",msgType:"markdown"})}else if(e.action==="exit"){if(!u?.qaMode){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2139\uFE0F \u5F53\u524D\u672A\u5F00\u542F\u95EE\u7B54\u6A21\u5F0F",msgType:"markdown"});return}u.qaMode=!1,(0,L.saveClientConfig)(this),(0,H.refreshSessionContext)(this,s),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2705 \u95EE\u7B54\u6A21\u5F0F\u5DF2\u5173\u95ED",msgType:"markdown"})}}}),(0,M.route)("/clean",()=>(0,k.parseCleanCommand)(h),async e=>{if(e==="all"&&u?.conversationType!=="1"&&!this.isOwnerOrAdmin(r)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u53EA\u6709 owner \u6216\u7BA1\u7406\u5458\u624D\u80FD\u6E05\u9664\u6240\u6709\u7FA4\u7F13\u5B58",msgType:"markdown"});return}if(!await this.requireOwnerOrAdmin(s,n,r))return;const i=e==="all"?null:s,t=this.cleanCache(i,!0),g=[];g.push("\u{1F9F9} \u7F13\u5B58\u6E05\u7406\u5B8C\u6210"),t.sessionsDeleted>0&&g.push(`- \u4F1A\u8BDD\u76EE\u5F55: ${t.sessionsDeleted} \u4E2A`),t.tasksDeleted>0&&g.push(`- \u4EFB\u52A1\u76EE\u5F55: ${t.tasksDeleted} \u4E2A`),t.imagesDeleted>0&&g.push(`- \u56FE\u7247\u6587\u4EF6: ${t.imagesDeleted} \u4E2A`),t.sessionsDeleted===0&&t.tasksDeleted===0&&t.imagesDeleted===0&&g.push("(\u65E0\u5386\u53F2\u6570\u636E)"),g.push(`
|
|
34
34
|
\u{1F4A1} \u6D3B\u8DC3\u4F1A\u8BDD\u5DF2\u4FDD\u7559`),t.errors.length>0&&g.push(`
|
|
35
35
|
\u26A0\uFE0F \u9519\u8BEF: ${t.errors.join("; ")}`),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:g.join(`
|
|
36
|
-
`),msgType:"markdown"})}),(0,M.route)("/reset-apikeycfg",()=>(0,
|
|
36
|
+
`),msgType:"markdown"})}),(0,M.route)("/reset-apikeycfg",()=>(0,k.parseResetApiKeyCfgCommand)(h),async()=>{if(!await this.requireOwnerOrAdmin(s,n,r))return;if(!this.config.apiKeyCfg){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u672A\u914D\u7F6E apiKeyCfg\uFF0C\u65E0\u9700\u91CD\u7F6E",msgType:"markdown"});return}(0,L.resetApiKeyCfg)(this);const e=this.config.apiKeyCfg.claudeSettings.filter(i=>i.isValid).length;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 apiKeyCfg \u5DF2\u91CD\u7F6E
|
|
37
37
|
- \u6709\u6548 Key \u6570: ${e}/${this.config.apiKeyCfg.claudeSettings.length}
|
|
38
|
-
- \u91CD\u7F6E\u65F6\u95F4: ${this.config.apiKeyCfg.resetTime||"-"}`,msgType:"markdown"})}),(0,M.route)("/auth",()=>(0,
|
|
38
|
+
- \u91CD\u7F6E\u65F6\u95F4: ${this.config.apiKeyCfg.resetTime||"-"}`,msgType:"markdown"})}),(0,M.route)("/auth",()=>(0,k.parseAuthCommand)(h),async e=>{if((e.type==="adminList"||e.type==="adminAdd"||e.type==="adminRm")&&!await this.requireOwner(s,n,r)||(e.type==="approve"||e.type==="reject"||e.type==="list"||e.type==="add"||e.type==="del")&&!await this.requireOwnerOrAdmin(s,n,r))return;if(e.type==="approve"||e.type==="reject"){const t=this.pendingAuthRequests.get(e.requestId);if(!t){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u672A\u627E\u5230\u6388\u6743\u7533\u8BF7: ${e.requestId}`,msgType:"markdown"});return}if(this.pendingAuthRequests.delete(e.requestId),e.type==="approve"){let g=this.config.conversations.find(w=>w.conversationId===t.conversationId);g||(g={conversationId:t.conversationId,conversationType:t.conversationType||"1",conversationTitle:t.conversationTitle},this.config.conversations.push(g)),g.whiteUserList||(g.whiteUserList=[]),g.whiteUserList.includes(t.senderStaffId)||g.whiteUserList.push(t.senderStaffId),(0,L.saveClientConfig)(this),console.log(`[${(0,c.timestamp)()}] \u6388\u6743\u7533\u8BF7\u901A\u8FC7\u5C06: id=${e.requestId}, userId=${t.senderStaffId}`),await(0,Z.sendMessageToUser)(this,t.senderStaffId,"\u2705 \u60A8\u7684\u6388\u6743\u7533\u8BF7\u5DF2\u901A\u8FC7\uFF0C\u73B0\u5728\u53EF\u4EE5\u5F00\u59CB\u4F7F\u7528\u4E86","markdown"),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u901A\u8FC7\u6388\u6743\u7533\u8BF7
|
|
39
39
|
- **\u7528\u6237ID:** ${t.senderStaffId}
|
|
40
40
|
- **\u6635\u79F0:** ${t.senderNick}
|
|
41
41
|
- **\u4F1A\u8BDDID:** ${t.conversationId}`,msgType:"markdown"})}else console.log(`[${(0,c.timestamp)()}] \u6388\u6743\u7533\u8BF7\u62D2\u7EDD: id=${e.requestId}, userId=${t.senderStaffId}`),await(0,Z.sendMessageToUser)(this,t.senderStaffId,"\u274C \u60A8\u7684\u6388\u6743\u7533\u8BF7\u5DF2\u88AB\u62D2\u7EDD","markdown"),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u62D2\u7EDD\u6388\u6743\u7533\u8BF7
|
|
42
42
|
- **\u7528\u6237ID:** ${t.senderStaffId}
|
|
43
|
-
- **\u6635\u79F0:** ${t.senderNick}`,msgType:"markdown"});return}const i=
|
|
43
|
+
- **\u6635\u79F0:** ${t.senderNick}`,msgType:"markdown"});return}const i=u.whiteUserList;if(e.type==="list"){const t=i&&i.length>0?i.map(g=>`- ${(0,c.userIdToPhone)(this,g)||g}`).join(`
|
|
44
44
|
`):"(\u672A\u914D\u7F6E\u7FA4\u7EA7\u767D\u540D\u5355\uFF0C\u4F7F\u7528\u5168\u5C40\u767D\u540D\u5355)";await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4CB} **\u5F53\u524D\u7FA4\u767D\u540D\u5355**
|
|
45
45
|
${t}`,msgType:"markdown"});return}if(e.type==="adminList"){const t=this.config.adminUserList&&this.config.adminUserList.length>0?this.config.adminUserList.map(g=>`- ${(0,c.userIdToPhone)(this,g)||g}`).join(`
|
|
46
46
|
`):"(\u672A\u914D\u7F6E\u7BA1\u7406\u5458)";await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F451} **\u7BA1\u7406\u5458\u5217\u8868**
|
|
47
|
-
${t}`,msgType:"markdown"});return}if(e.type==="adminAdd"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}if(this.config.adminUserList?.some(f=>(0,c.resolveToUserId)(this,f)===t)){const f=(0,c.userIdToPhone)(this,t)||t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F ${f} \u5DF2\u5728\u7BA1\u7406\u5458\u5217\u8868\u4E2D`,msgType:"markdown"});return}this.config.adminUserList||(this.config.adminUserList=[]),this.config.adminUserList.push(e.staffId),(0,L.saveClientConfig)(this);const w=(0,c.isMobile)(e.staffId)?e.staffId:(0,c.userIdToPhone)(this,e.staffId)||e.staffId;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u6DFB\u52A0 ${w} \u5230\u7BA1\u7406\u5458\u5217\u8868`,msgType:"markdown"});return}if(e.type==="adminRm"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}const g=this.config.adminUserList?.findIndex(
|
|
48
|
-
\u5F53\u524D\u767D\u540D\u5355: ${w.join(", ")}`,msgType:"markdown"});return}if(e.type==="del"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}const g=i?.findIndex(p=>(0,c.resolveToUserId)(this,p)===t)??-1;if(g<0){const p=(0,c.userIdToPhone)(this,t)||t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F ${p} \u4E0D\u5728\u5F53\u524D\u7FA4\u767D\u540D\u5355\u4E2D`,msgType:"markdown"});return}const w=
|
|
49
|
-
\u5F53\u524D\u767D\u540D\u5355: ${f}`,msgType:"markdown"});return}}),(0,M.route)("/open",()=>(0,
|
|
47
|
+
${t}`,msgType:"markdown"});return}if(e.type==="adminAdd"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}if(this.config.adminUserList?.some(f=>(0,c.resolveToUserId)(this,f)===t)){const f=(0,c.userIdToPhone)(this,t)||t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F ${f} \u5DF2\u5728\u7BA1\u7406\u5458\u5217\u8868\u4E2D`,msgType:"markdown"});return}this.config.adminUserList||(this.config.adminUserList=[]),this.config.adminUserList.push(e.staffId),(0,L.saveClientConfig)(this);const w=(0,c.isMobile)(e.staffId)?e.staffId:(0,c.userIdToPhone)(this,e.staffId)||e.staffId;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u6DFB\u52A0 ${w} \u5230\u7BA1\u7406\u5458\u5217\u8868`,msgType:"markdown"});return}if(e.type==="adminRm"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}const g=this.config.adminUserList?.findIndex(l=>(0,c.resolveToUserId)(this,l)===t)??-1;if(g<0){const l=(0,c.userIdToPhone)(this,t)||t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F ${l} \u4E0D\u5728\u7BA1\u7406\u5458\u5217\u8868\u4E2D`,msgType:"markdown"});return}const w=this.config.adminUserList[g];this.config.adminUserList.splice(g,1),this.config.adminUserList.length===0&&delete this.config.adminUserList,(0,L.saveClientConfig)(this);const f=(0,c.userIdToPhone)(this,t)||w;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u79FB\u9664 ${f}`,msgType:"markdown"});return}if(e.type==="add"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}if(i?.some(l=>(0,c.resolveToUserId)(this,l)===t)){const l=(0,c.userIdToPhone)(this,t)||t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F ${l} \u5DF2\u5728\u5F53\u524D\u7FA4\u767D\u540D\u5355\u4E2D`,msgType:"markdown"});return}u.whiteUserList||(u.whiteUserList=[]),u.whiteUserList.push(e.staffId),(0,L.saveClientConfig)(this);const w=u.whiteUserList.map(l=>{const p=(0,c.resolveToUserId)(this,l);return(0,c.userIdToPhone)(this,p)||l}),f=(0,c.isMobile)(e.staffId)?e.staffId:(0,c.userIdToPhone)(this,e.staffId)||e.staffId;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u6DFB\u52A0 ${f} \u5230\u5F53\u524D\u7FA4\u767D\u540D\u5355
|
|
48
|
+
\u5F53\u524D\u767D\u540D\u5355: ${w.join(", ")}`,msgType:"markdown"});return}if(e.type==="del"){let t=e.staffId;if((0,c.isMobile)(e.staffId)&&(t=await(0,c.resolveUserId)(this,e.staffId),!t)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${e.staffId}`,msgType:"markdown"});return}const g=i?.findIndex(p=>(0,c.resolveToUserId)(this,p)===t)??-1;if(g<0){const p=(0,c.userIdToPhone)(this,t)||t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F ${p} \u4E0D\u5728\u5F53\u524D\u7FA4\u767D\u540D\u5355\u4E2D`,msgType:"markdown"});return}const w=u.whiteUserList[g];u.whiteUserList.splice(g,1),u.whiteUserList.length===0&&delete u.whiteUserList,(0,L.saveClientConfig)(this);const f=u.whiteUserList?.length?u.whiteUserList.map(p=>{const D=(0,c.resolveToUserId)(this,p);return(0,c.userIdToPhone)(this,D)||p}).join(", "):"(\u7A7A\uFF0C\u4F7F\u7528\u5168\u5C40\u767D\u540D\u5355)",l=(0,c.userIdToPhone)(this,t)||w;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u79FB\u9664 ${l}
|
|
49
|
+
\u5F53\u524D\u767D\u540D\u5355: ${f}`,msgType:"markdown"});return}}),(0,M.route)("/open",()=>(0,k.parseOpenCommand)(h),async e=>{if(!await this.requireOwnerOrAdmin(s,n,r))return;const i=this.getConversationDir(s),t=process.platform,g=(w,f,l)=>new Promise((p,D)=>{const $=(0,F.spawnCommand)(w,f,{cwd:l,detached:!0,stdio:"ignore"});$.once("error",D),$.once("spawn",()=>{$.unref(),p()})});try{if(e==="folder"){if(t==="darwin")await g("open",[i]);else if((0,F.isWindowsPlatform)(t))await g("explorer.exe",[i]);else if((0,F.commandExists)("xdg-open"))await g("xdg-open",[i]);else throw new Error("\u672A\u68C0\u6D4B\u5230\u53EF\u7528\u7684\u6587\u4EF6\u7BA1\u7406\u5668\u6253\u5F00\u547D\u4EE4");await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4C2} \u5DF2\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u6253\u5F00:
|
|
50
50
|
\`\`\`
|
|
51
51
|
${i}
|
|
52
52
|
\`\`\``,msgType:"markdown"})}else if(e==="code"){if(!(0,F.commandExists)("code")){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u672A\u68C0\u6D4B\u5230 VS Code `code` \u547D\u4EE4\n\u8BF7\u5B89\u88C5 VS Code \u5E76\u786E\u8BA4 `code` \u5DF2\u52A0\u5165 PATH",msgType:"markdown"});return}await g("code",[i]),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4BB} \u5DF2\u5728 VS Code \u4E2D\u6253\u5F00:
|
|
@@ -55,51 +55,51 @@ ${i}
|
|
|
55
55
|
\`\`\``,msgType:"markdown"})}else{if(t==="darwin")await g("open",["-a","Terminal",i]);else if((0,F.isWindowsPlatform)(t))await g("cmd.exe",["/K","cd","/d",i]);else if((0,F.commandExists)("x-terminal-emulator"))await g("x-terminal-emulator",[],i);else throw new Error("\u672A\u68C0\u6D4B\u5230\u53EF\u7528\u7684\u7EC8\u7AEF\u6253\u5F00\u547D\u4EE4");await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4BB} \u5DF2\u5728\u7EC8\u7AEF\u4E2D\u6253\u5F00:
|
|
56
56
|
\`\`\`
|
|
57
57
|
${i}
|
|
58
|
-
\`\`\``,msgType:"markdown"})}}catch(w){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u6253\u5F00\u5931\u8D25: ${w instanceof Error?w.message:String(w)}`,msgType:"markdown"})}}),(0,M.route)("/cron",()=>(0,
|
|
58
|
+
\`\`\``,msgType:"markdown"})}}catch(w){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u6253\u5F00\u5931\u8D25: ${w instanceof Error?w.message:String(w)}`,msgType:"markdown"})}}),(0,M.route)("/cron",()=>(0,k.parseCronCommand)(h),async e=>{await this.handleCronCommand(e,{conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a,conversationConfig:u})}),(0,M.route)("/timer",()=>(0,k.parseTimerCommand)(h),async e=>{await this.handleTimerCommand(e,{conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a})}),(0,M.route)("/model",()=>(0,k.parseModelCommand)(h),async e=>{if(!await this.requireOwnerOrAdmin(s,n,r))return;const i=(0,B.loadModelOptions)(this),t=(0,B.resolveCurrentModel)(this,s),g=this.config.model||"(\u672A\u8BBE\u7F6E)",w=u?.model;if(e.action==="list"){const f=["### \u6A21\u578B\u8BBE\u7F6E","",`- **\u5F53\u524D\u751F\u6548\u6A21\u578B:** ${t||"(\u9ED8\u8BA4)"}`,`- **\u4F1A\u8BDD\u7EA7 model:** ${w||"(\u672A\u8BBE\u7F6E)"}`,`- **\u5168\u5C40 model:** ${g}`,"","**\u53EF\u7528\u6A21\u578B\u5217\u8868:**"];for(const l of i){const p=l===t?" \u2705":"";f.push(`- \`${l}\`${p}`)}f.push(""),f.push("\u{1F4A1} \u4F7F\u7528 `/model <model-name>` \u5207\u6362\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B"),f.push("\u{1F4A1} \u4F7F\u7528 `/model add <model-name>` \u6DFB\u52A0\u81EA\u5B9A\u4E49\u6A21\u578B"),f.push("\u{1F4A1} \u4F7F\u7528 `/model rm <model-name>` \u4ECE\u5217\u8868\u79FB\u9664\u6A21\u578B"),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:f.join(`
|
|
59
59
|
`),msgType:"markdown"})}else if(e.action==="set")(0,B.setConversationModel)(this,s,e.model),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u8BBE\u7F6E\u5F53\u524D\u4F1A\u8BDD\u6A21\u578B\u4E3A: \`${e.model}\`
|
|
60
60
|
|
|
61
|
-
\u{1F4A1} \u4EC5\u5F71\u54CD\u540E\u7EED\u65B0\u5EFA\u7684 Claude \u4F1A\u8BDD`,msgType:"markdown"});else if(e.action==="add"){const f=(0,B.addModelOptions)(this,[e.model]),
|
|
62
|
-
`),msgType:"markdown"})}else if(e.action==="remove"){if(["claude-sonnet-4-20250514","claude-opus-4-20250514","claude-haiku-4-20251001"].includes(e.model)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u65E0\u6CD5\u79FB\u9664\u9884\u8BBE\u6A21\u578B: \`${e.model}\``,msgType:"markdown"});return}const
|
|
63
|
-
`),msgType:"markdown"})}}),(0,M.route)("/todo",()=>(0,ae.parseTodoCommand)(
|
|
61
|
+
\u{1F4A1} \u4EC5\u5F71\u54CD\u540E\u7EED\u65B0\u5EFA\u7684 Claude \u4F1A\u8BDD`,msgType:"markdown"});else if(e.action==="add"){const f=(0,B.addModelOptions)(this,[e.model]),l=[`\u2705 \u5DF2\u6DFB\u52A0\u6A21\u578B: \`${e.model}\``,"","**\u5F53\u524D\u53EF\u7528\u6A21\u578B:**"];for(const p of f)l.push(`- \`${p}\``);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:l.join(`
|
|
62
|
+
`),msgType:"markdown"})}else if(e.action==="remove"){if(["claude-sonnet-4-20250514","claude-opus-4-20250514","claude-haiku-4-20251001"].includes(e.model)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u65E0\u6CD5\u79FB\u9664\u9884\u8BBE\u6A21\u578B: \`${e.model}\``,msgType:"markdown"});return}const l=(0,B.removeModelOptions)(this,[e.model]),p=[`\u2705 \u5DF2\u79FB\u9664\u6A21\u578B: \`${e.model}\``,"","**\u5F53\u524D\u53EF\u7528\u6A21\u578B:**"];for(const D of l)p.push(`- \`${D}\``);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:p.join(`
|
|
63
|
+
`),msgType:"markdown"})}}),(0,M.route)("/todo",()=>(0,ae.parseTodoCommand)(h,o.atUsers),async e=>{await this.handleTodoCommand(e,{conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a})}),(0,M.route)("/menu",()=>(0,k.parseMenuCommand)(h),async e=>{await this.handleMenuCommand(e,{conversationId:s,sessionWebhook:n,senderStaffId:r})}),(0,M.route)("/bash",()=>(0,k.parseBashCommand)(h),async e=>{if(!await this.requireOwnerOrAdmin(s,n,r))return;this.appendBashAudit(s,r,e);const i=this.getConversationDir(s),t=[];this.config.preBash&&t.push(this.config.preBash),u?.preBash&&t.push(u.preBash);const g=(0,F.isWindowsPlatform)()?" && ":" ; ",w=t.length>0?[...t,e].join(g):e,f=this;(0,V.exec)(w,{cwd:i,timeout:3e4,maxBuffer:1024*1024},async(l,p,D)=>{try{let $;if(l)$=`\u274C \u547D\u4EE4\u6267\u884C\u5931\u8D25
|
|
64
64
|
\`\`\`
|
|
65
|
-
${
|
|
66
|
-
|
|
65
|
+
${l.message}
|
|
66
|
+
\`\`\``,D&&($+=`
|
|
67
67
|
|
|
68
68
|
**stderr:**
|
|
69
69
|
\`\`\`
|
|
70
|
-
${f.sanitizeOutput(
|
|
71
|
-
\`\`\``);else{const W=p||"(\u65E0\u8F93\u51FA)"
|
|
70
|
+
${f.sanitizeOutput(D)}
|
|
71
|
+
\`\`\``);else{const W=p||"(\u65E0\u8F93\u51FA)";$=`\u2705 \u6267\u884C\u6210\u529F
|
|
72
72
|
\`\`\`
|
|
73
73
|
${f.sanitizeOutput(W)}
|
|
74
|
-
|
|
74
|
+
\`\`\``,D&&($+=`
|
|
75
75
|
|
|
76
76
|
**stderr:**
|
|
77
77
|
\`\`\`
|
|
78
|
-
${f.sanitizeOutput(
|
|
79
|
-
\`\`\``)}await f.sendDingMessage({conversationId:s,sessionWebhook:n,content
|
|
78
|
+
${f.sanitizeOutput(D)}
|
|
79
|
+
\`\`\``)}await f.sendDingMessage({conversationId:s,sessionWebhook:n,content:$,msgType:"markdown"})}catch($){console.error("[bash] \u53D1\u9001\u6D88\u606F\u5931\u8D25:",$)}})}),(0,M.route)("/new",()=>/^\/new(?:\s|$)/i.test(h),async()=>{const e=this.findActiveSession(s);e&&(console.log(`\u6536\u5230\u65B0\u4F1A\u8BDD\u547D\u4EE4\uFF0C\u7ED3\u675F\u65E7\u4F1A\u8BDD: \u7FA4=${e.session.session.conversationId}, \u4F1A\u8BDDID=${this.getSessionId(e.session.session)}`),e.session.agent?.interrupt(e.session,"\u65B0\u4F1A\u8BDD\u547D\u4EE4\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Agent \u8FDB\u7A0B"),this.activeSessions.delete(e.key),this.saveActiveSession(e.key));const i=h.replace(/^\/new\s*/i,"").trim();i?await this.startNewSession({conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a,message:i,conversationConfig:u}):await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F680} \u8BF7\u8F93\u5165\u60A8\u7684\u95EE\u9898\u5F00\u59CB\u65B0\u4F1A\u8BDD"})}),(0,M.route)("/resume",()=>(0,k.parseContinueSessionCommand)(h),async e=>{let i=e;if(!i){const t=(0,c.findLatestSession)(this,s);if(!t){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u672A\u627E\u5230\u5DF2\u7ED3\u675F\u7684\u4F1A\u8BDD",msgType:"markdown"});return}i=(0,c.getSessionId)(t)}await this.switchToSession(s,n,i,r,u)}),(0,M.route)("/log",()=>(0,k.parseLogCommand)(h),async e=>{const i=this.readSessionLogTail(s,e);i?await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4CB} \u6700\u8FD1 ${e} \u884C\u65E5\u5FD7:
|
|
80
80
|
\`\`\`
|
|
81
81
|
${i}
|
|
82
|
-
\`\`\``,msgType:"markdown"}):await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u5F53\u524D\u65E0\u6D3B\u8DC3\u4F1A\u8BDD\u6216\u6682\u65E0\u65E5\u5FD7"})}),(0,M.route)("/info",()=>(0,
|
|
83
|
-
`+(0,
|
|
84
|
-
`+(0,
|
|
82
|
+
\`\`\``,msgType:"markdown"}):await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u5F53\u524D\u65E0\u6D3B\u8DC3\u4F1A\u8BDD\u6216\u6682\u65E0\u65E5\u5FD7"})}),(0,M.route)("/info",()=>(0,k.parseInfoCommand)(h),async e=>{const i=[],t=this.getConversationDir(s);if((e==="all"||e==="robot")&&(i.push(`### \u{1F310} \u5168\u5C40\u6838\u5FC3\u914D\u7F6E
|
|
83
|
+
`+(0,k.formatGlobalConfig)(this.config)),i.push(`### \u{1F916} \u7FA4\u914D\u7F6E\u4FE1\u606F
|
|
84
|
+
`+(0,k.formatConversationInfo)(u,s,g=>(0,c.userIdToPhone)(this,g),t))),e==="all"||e==="session"){const g=this.formatSessionInfo(s);g?i.push(`### \u{1F4AC} \u5F53\u524D\u4F1A\u8BDD\u4FE1\u606F
|
|
85
85
|
`+g):i.push(`### \u{1F4AC} \u5F53\u524D\u4F1A\u8BDD\u4FE1\u606F
|
|
86
86
|
\u65E0\u6D3B\u8DC3\u4F1A\u8BDD`)}(e==="all"||e==="task")&&i.push(`### \u{1F4DD} \u4EFB\u52A1\u961F\u5217\u4FE1\u606F
|
|
87
87
|
`+this.formatTaskInfo()),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:i.join(`
|
|
88
88
|
|
|
89
|
-
`),msgType:"markdown"})}),(0,M.route)("/ls",()=>(0,
|
|
89
|
+
`),msgType:"markdown"})}),(0,M.route)("/ls",()=>(0,k.parseLsCommand)(h),async e=>{const{target:i,depth:t}=e,g=this.getConversationDir(s);let w=g,f="\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55";if(i&&i!=="root")if(i.startsWith("./")||i.startsWith("../")||i.startsWith("/")){const p=Q.default.resolve(g,i);if(S.default.existsSync(p)&&S.default.statSync(p).isDirectory()){if(!p.startsWith(g)){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u274C \u8DEF\u5F84\u8D85\u51FA\u5DE5\u4F5C\u76EE\u5F55\u8303\u56F4",msgType:"markdown"});return}w=p,f=i}else{await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u8DEF\u5F84\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u76EE\u5F55: **${i}**`,msgType:"markdown"});return}}else{const p=(0,k.findSubdirByName)(g,i);if(p)w=p,f=i;else{await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u274C \u672A\u627E\u5230\u540D\u4E3A **${i}** \u7684\u76EE\u5F55`,msgType:"markdown"});return}}const l=(0,k.getDirectoryStructure)(w,0,t);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4C2} ${f} (\u5C55\u5F00${t}\u5C42):
|
|
90
90
|
\`\`\`
|
|
91
|
-
${
|
|
92
|
-
\`\`\``,msgType:"markdown"})}),(0,M.route)("/task cancel",()=>(0,P.parseTaskCancelCommand)(
|
|
91
|
+
${l}
|
|
92
|
+
\`\`\``,msgType:"markdown"})}),(0,M.route)("/task cancel",()=>(0,P.parseTaskCancelCommand)(h)||null,async e=>{const i=this.cancelTask(e,s);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:i,msgType:"markdown"})}),(0,M.route)("/task",()=>h.startsWith("/task ")||null,async()=>{const e=h.substring(6).trim();e&&(await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F4CB} \u4EFB\u52A1\u5DF2\u6536\u5230,\u5B8C\u6210\u540E\u6211\u4F1A\u56DE\u590D"}),await this.saveTask({conversationId:s,prompt:e,senderStaffId:r,senderNickName:a,sessionWebhook:n}))}),(0,M.route)("/mq",()=>(0,k.parseMqCommand)(h),async e=>{const t=this.findActiveSession(s)?.session.messageQueue??[];switch(e.type){case"list":{if(t.length===0)await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});else{const g=t.map((w,f)=>`${f+1}. **${w.senderNick||w.senderStaffId}:** ${this.truncateMsg(w.message)}`);await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4E8} \u6D88\u606F\u961F\u5217 (${t.length} \u6761)
|
|
93
93
|
${g.join(`
|
|
94
94
|
`)}`,msgType:"markdown"})}return}case"front":{if(t.length===0){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});return}let g=t.length-1;for(let f=t.length-1;f>=0;f--)if(t[f].senderStaffId===r){g=f;break}if(g===0){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2139\uFE0F \u8BE5\u6D88\u606F\u5DF2\u5728\u961F\u9996\uFF0C\u65E0\u9700\u63D2\u961F",msgType:"markdown"});return}const[w]=t.splice(g,1);t.unshift(w),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u63D2\u961F\u5230\u961F\u9996
|
|
95
|
-
1. **${w.senderNick||w.senderStaffId}:** ${this.truncateMsg(w.message)}`,msgType:"markdown"});return}case"rm":{if(t.length===0){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});return}if(e.all){const
|
|
95
|
+
1. **${w.senderNick||w.senderStaffId}:** ${this.truncateMsg(w.message)}`,msgType:"markdown"});return}case"rm":{if(t.length===0){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});return}if(e.all){const $=t.length;t.length=0,await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u2705 \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u5171\u79FB\u9664 ${$} \u6761\u6D88\u606F`,msgType:"markdown"});return}const g=[...new Set(e.indices)],w=g.filter($=>$>=1&&$<=t.length).sort(($,W)=>W-$),f=g.filter($=>$<1||$>t.length);if(w.length===0){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u5E8F\u53F7\u65E0\u6548\uFF0C\u5F53\u524D\u961F\u5217\u5171 ${t.length} \u6761`,msgType:"markdown"});return}const l=[];for(const $ of w)l.unshift(t.splice($-1,1)[0]);const p=l.map($=>`- **${$.senderNick||$.senderStaffId}:** ${this.truncateMsg($.message)}`);let D=`\u2705 \u5DF2\u5220\u9664 ${l.length} \u6761\u6D88\u606F
|
|
96
96
|
${p.join(`
|
|
97
|
-
`)}`;f.length>0&&(
|
|
98
|
-
\u26A0\uFE0F \u5DF2\u5FFD\u7565\u65E0\u6548\u5E8F\u53F7: ${f.join(", ")}`),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content
|
|
97
|
+
`)}`;f.length>0&&(D+=`
|
|
98
|
+
\u26A0\uFE0F \u5DF2\u5FFD\u7565\u65E0\u6548\u5E8F\u53F7: ${f.join(", ")}`),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:D,msgType:"markdown"});return}}}),(0,M.route)("/!",()=>(0,k.parseInterruptCommand)(h),async e=>{const i=this.findActiveSession(s);if(!i){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u4F1A\u8BDD"});return}const t=i.session;if(!t.currentProcess){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u2139\uFE0F \u5F53\u524D\u6CA1\u6709\u6B63\u5728\u6267\u884C\u7684\u4EFB\u52A1"});return}const g=e===""?"":e.replace(/^[/!!]\s*/,"");t.agent?.interrupt(t,`/!: ${a} \u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1`);const w=t.messageQueue?.length??0;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:w>0?` \u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1\uFF0C\u5F00\u59CB\u5904\u7406\u961F\u5217\u4E2D\u7684 ${w} \u6761\u6D88\u606F`:" \u5DF2\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1"}),g&&await this.handleSessionMessage({conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a,message:g,conversationConfig:u})}),(0,M.route)("/goon",()=>(0,k.parseGoonCommand)(h),async()=>{const e=this.activeSessions.get(s);if(!e){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u4F1A\u8BDD"});return}(0,c.ensureAgent)(this,e);const i=e.agent;e.currentProcess?(console.log(`[${(0,c.timestamp)()}] /goon: \u7EC8\u6B62\u5F53\u524D Agent \u8FDB\u7A0B`),i.interrupt(e,"/goon: \u5F3A\u5236\u91CD\u542F Agent \u8FDB\u7A0B"),await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F504} \u6B63\u5728\u91CD\u542F ${i.getEntryCommand()} \u8FDB\u7A0B...`})):console.log(`[${(0,c.timestamp)()}] /goon: \u65E0\u8FD0\u884C\u4E2D\u8FDB\u7A0B\uFF0C\u76F4\u63A5\u53D1\u9001"\u7EE7\u7EED"`),e.goonPending=!1,e.isProcessing=!0;try{await i.executeQuery(this,e.session,{message:"\u7EE7\u7EED",senderNick:e.session.startNickName,senderStaffId:e.lastSenderStaffId})}finally{e.isProcessing=!1}}),(0,M.route)("/cc",()=>(0,k.parseCcCommand)(h),async e=>{const i=this.activeSessions.get(s);if(!i){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u26A0\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u5F00\u59CB\u4F1A\u8BDD"});return}if(i.isProcessing){await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u23F3 \u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7A0D\u7B49..."});return}i.isProcessing=!0;try{i.conversationConfig.receiveReply!==!1&&await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:"\u{1F4E5} \u5DF2\u6536\u5230\uFF0C\u6B63\u5728\u5904\u7406..."}).catch(()=>{}),(0,c.ensureAgent)(this,i),await i.agent.executeQuery(this,i.session,{message:e,senderNick:a,senderStaffId:r})}finally{i.isProcessing=!1}}),(0,M.route)("/claude.md",()=>(0,k.parseClaudeMdCommand)(h),async()=>{const e=this.getConversationDir(s),i=Q.default.join(e,".claude","CLAUDE.md");if(S.default.existsSync(i)){const t=S.default.readFileSync(i,"utf-8"),g=t.length>8e3?t.substring(0,8e3)+`
|
|
99
99
|
...(\u5185\u5BB9\u8FC7\u957F\u5DF2\u622A\u65AD)`:t;await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u{1F4C4} **CLAUDE.md**
|
|
100
100
|
\`\`\`
|
|
101
101
|
${g}
|
|
102
102
|
\`\`\``,msgType:"markdown"})}else await this.sendDingMessage({conversationId:s,sessionWebhook:n,content:`\u26A0\uFE0F \u672A\u627E\u5230 CLAUDE.md
|
|
103
|
-
\u8DEF\u5F84: \`${i}\``,msgType:"markdown"})})];for(const e of
|
|
104
|
-
${C}`),C.startsWith("/")&&!C.startsWith("/cc ")&&(C=` ${C}`),await this.handleSessionMessage({conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a,message:C,conversationConfig:
|
|
105
|
-
**\u7248\u672C:** ${se}`);let r;const s=this.activeSessions.get(o.conversationId);if(s)r=s.session.sessionWebhook;else if(o.sessionWebhook)r=o.sessionWebhook,console.log(`[${(0,c.timestamp)()}] \u91CD\u542F\u540E\u672A\u627E\u5230\u6D3B\u8DC3\u4F1A\u8BDD\uFF0C\u4F7F\u7528\u4FDD\u5B58\u7684 sessionWebhook \u53D1\u9001\u901A\u77E5`);else{console.log(`[${(0,c.timestamp)()}] \u91CD\u542F\u540E\u672A\u627E\u5230\u6D3B\u8DC3\u4F1A\u8BDD\u4E14\u65E0\u4FDD\u5B58\u7684 webhook\uFF0C\u8DF3\u8FC7\u901A\u77E5`);return}await this.sendDingMessage({conversationId:o.conversationId,sessionWebhook:r,content:a,msgType:"markdown",atUserId:o.senderStaffId}),console.log(`[${(0,c.timestamp)()}] \u91CD\u542F\u5B8C\u6210\u901A\u77E5\u5DF2\u53D1\u9001`)}catch(o){try{const a=S.default.readFileSync(d,"utf-8");console.error(`[${(0,c.timestamp)()}] .reboot_pending \u5185\u5BB9:`,a)}catch{}console.error(`[${(0,c.timestamp)()}] \u5904\u7406\u91CD\u542F\u901A\u77E5\u5931\u8D25:`,o);try{S.default.unlinkSync(d)}catch{}}}startConnectionWatchdog(){let a=Date.now();setInterval(()=>{const r=this.dingStreamClient;if(r.connected){a=Date.now();return}const s=Date.now()-a;if(s>=6e4){console.log(`[${(0,c.timestamp)()}] \u8FDE\u63A5\u76D1\u63A7: \u5DF2\u65AD\u5F00 ${s/1e3}s\uFF0C\u5F3A\u5236\u91CD\u65B0\u8FDE\u63A5`),a=Date.now();try{r.disconnect()}catch{}r.connect().catch(y=>{console.error(`[${(0,c.timestamp)()}] \u5F3A\u5236\u91CD\u8FDE\u5931\u8D25:`,y)})}else this.debugLog(`\u8FDE\u63A5\u76D1\u63A7: \u5DF2\u65AD\u5F00 ${s/1e3}s\uFF0C\u7B49\u5F85\u81EA\u52A8\u91CD\u8FDE...`)},3e4)}async run(){const d=Array.isArray(this.config.conversations)?this.config.conversations:[],o=this.config.taskHandlerCount??this.DEFAULT_TASK_HANDLER_COUNT,a=d.length>0;console.log(`[${(0,c.timestamp)()}] \u9489\u9489\u673A\u5668\u4EBA\u670D\u52A1\u542F\u52A8\uFF0CclientId: ${this.clientId}`),console.log(`[${(0,c.timestamp)()}] \u7FA4\u914D\u7F6E: ${d.map(n=>n.conversationTitle||n.conversationId).join(", ")}`),(0,L.startupCheck)(this),await(0,c.resolveAllPhonesInConfig)(this),this.config.apiKeyCfg&&((0,L.resetApiKeyCfg)(this),(0,L.scheduleApiKeyCfgDailyReset)(this)),this.loadActiveSessions(),(0,H.injectStartupContexts)(this),await this.notifyPendingReboot(),this.cronEngine.start(),this.timerEngine.start(),this.sendQueueProcessor.start(),(0,A.startSelectionCleanupTimer)(),this.startConnectionWatchdog(),a&&console.log(`[${(0,c.timestamp)()}] \u4EFB\u52A1\u5904\u7406\u5668\u6570\u91CF: ${o}`),this.dingStreamClient.registerCallbackListener("/v1.0/im/bot/messages/get",async n=>{console.log(`[${(0,c.timestamp)()}] [DEBUG] \u6536\u5230\u9489\u9489\u56DE\u8C03, messageId=${n.headers?.messageId}, eventType=${n.headers?.eventType}`),await this.botMsgGetCallback(n)});const r=[];if(a)for(let n=0;n<o;n++)console.log(`[${(0,c.timestamp)()}] \u542F\u52A8\u4EFB\u52A1\u5904\u7406\u5668 #${n+1}`),r.push(this.runTaskHandlerLoop().catch(
|
|
103
|
+
\u8DEF\u5F84: \`${i}\``,msgType:"markdown"})})];for(const e of N)if(await e.tryHandle())return;let C=h;const z=[],K=[];if(o.atUsers&&o.atUsers.length>0){const e=o.chatbotUserId;for(const i of o.atUsers){const t=i.staffId||i.dingtalkId;!t||t===r||t===e||t.startsWith("$:LWCP_v1:")||z.push(t)}}if(z.length>0){for(const e of z){let i=null;const t=(0,j.getCachedUserName)(e);if(t&&(i=t,K.push(`${i}(${e})`)),!i){const g=await(0,c.resolveUserIdName)(this,e);g&&(i=g,(0,j.cacheUserName)(e,g),K.push(`${i}(${e})`))}i&&(C=C.replace(/\u200b/g,`${i}(${e})`))}C=(0,j.restoreMentions)(C,o.atUsers||[])}K.length>0&&(C=`[\u88AB@\u7684\u7528\u6237: ${K.join(", ")}]
|
|
104
|
+
${C}`),C.startsWith("/")&&!C.startsWith("/cc ")&&(C=` ${C}`),await this.handleSessionMessage({conversationId:s,sessionWebhook:n,senderStaffId:r,senderNick:a,message:C,conversationConfig:u})}async notifyPendingReboot(){const d=Q.default.join(this.getClientDir(),".reboot_pending");if(S.default.existsSync(d))try{const o=JSON.parse(S.default.readFileSync(d,"utf-8"));S.default.unlinkSync(d);let a="\u2705 cc-ding \u5DF2\u91CD\u542F\u5B8C\u6210";o.update&&(a+=`
|
|
105
|
+
**\u7248\u672C:** ${se}`);let r;const s=this.activeSessions.get(o.conversationId);if(s)r=s.session.sessionWebhook;else if(o.sessionWebhook)r=o.sessionWebhook,console.log(`[${(0,c.timestamp)()}] \u91CD\u542F\u540E\u672A\u627E\u5230\u6D3B\u8DC3\u4F1A\u8BDD\uFF0C\u4F7F\u7528\u4FDD\u5B58\u7684 sessionWebhook \u53D1\u9001\u901A\u77E5`);else{console.log(`[${(0,c.timestamp)()}] \u91CD\u542F\u540E\u672A\u627E\u5230\u6D3B\u8DC3\u4F1A\u8BDD\u4E14\u65E0\u4FDD\u5B58\u7684 webhook\uFF0C\u8DF3\u8FC7\u901A\u77E5`);return}await this.sendDingMessage({conversationId:o.conversationId,sessionWebhook:r,content:a,msgType:"markdown",atUserId:o.senderStaffId}),console.log(`[${(0,c.timestamp)()}] \u91CD\u542F\u5B8C\u6210\u901A\u77E5\u5DF2\u53D1\u9001`)}catch(o){try{const a=S.default.readFileSync(d,"utf-8");console.error(`[${(0,c.timestamp)()}] .reboot_pending \u5185\u5BB9:`,a)}catch{}console.error(`[${(0,c.timestamp)()}] \u5904\u7406\u91CD\u542F\u901A\u77E5\u5931\u8D25:`,o);try{S.default.unlinkSync(d)}catch{}}}startConnectionWatchdog(){let a=Date.now();setInterval(()=>{const r=this.dingStreamClient;if(r.connected){a=Date.now();return}const s=Date.now()-a;if(s>=6e4){console.log(`[${(0,c.timestamp)()}] \u8FDE\u63A5\u76D1\u63A7: \u5DF2\u65AD\u5F00 ${s/1e3}s\uFF0C\u5F3A\u5236\u91CD\u65B0\u8FDE\u63A5`),a=Date.now();try{r.disconnect()}catch{}r.connect().catch(y=>{console.error(`[${(0,c.timestamp)()}] \u5F3A\u5236\u91CD\u8FDE\u5931\u8D25:`,y)})}else this.debugLog(`\u8FDE\u63A5\u76D1\u63A7: \u5DF2\u65AD\u5F00 ${s/1e3}s\uFF0C\u7B49\u5F85\u81EA\u52A8\u91CD\u8FDE...`)},3e4)}async run(){const d=Array.isArray(this.config.conversations)?this.config.conversations:[],o=this.config.taskHandlerCount??this.DEFAULT_TASK_HANDLER_COUNT,a=d.length>0;console.log(`[${(0,c.timestamp)()}] \u9489\u9489\u673A\u5668\u4EBA\u670D\u52A1\u542F\u52A8\uFF0CclientId: ${this.clientId}`),console.log(`[${(0,c.timestamp)()}] \u7FA4\u914D\u7F6E: ${d.map(n=>n.conversationTitle||n.conversationId).join(", ")}`),(0,L.startupCheck)(this),await(0,c.resolveAllPhonesInConfig)(this),this.config.apiKeyCfg&&((0,L.resetApiKeyCfg)(this),(0,L.scheduleApiKeyCfgDailyReset)(this)),this.loadActiveSessions(),(0,H.injectStartupContexts)(this),await this.notifyPendingReboot(),this.cronEngine.start(),this.timerEngine.start(),this.sendQueueProcessor.start(),(0,A.startSelectionCleanupTimer)(),this.startConnectionWatchdog(),a&&console.log(`[${(0,c.timestamp)()}] \u4EFB\u52A1\u5904\u7406\u5668\u6570\u91CF: ${o}`),this.dingStreamClient.registerCallbackListener("/v1.0/im/bot/messages/get",async n=>{console.log(`[${(0,c.timestamp)()}] [DEBUG] \u6536\u5230\u9489\u9489\u56DE\u8C03, messageId=${n.headers?.messageId}, eventType=${n.headers?.eventType}`),await this.botMsgGetCallback(n)});const r=[];if(a)for(let n=0;n<o;n++)console.log(`[${(0,c.timestamp)()}] \u542F\u52A8\u4EFB\u52A1\u5904\u7406\u5668 #${n+1}`),r.push(this.runTaskHandlerLoop().catch(m=>console.error(`\u4EFB\u52A1\u5904\u7406\u5668 #${n+1} \u9519\u8BEF:`,m)));const s=this.dingStreamClient.connect().catch(n=>{console.error("Fatal error",n),process.exit(1)}),y=()=>{this.timerEngine.destroy(),this.sendQueueProcessor.destroy()};process.on("SIGTERM",y),process.on("SIGINT",y),await Promise.all([s,...r])}}exports.DingClaude=ge;
|
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
"use strict";var Z=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.WatchdogTimeoutError=void 0,exports.resolveClaudeSettingsPath=te,exports.isRetryableApiError=ne,exports.parseClaudeStreamLine=fe,exports.interruptClaudeProcess=ge,exports.injectStartupContexts=xe,exports.injectSessionContextIfChanged=$e,exports.refreshSessionContext=De,exports.executeClaudeQuery=We;const a=Z(require("fs")),
|
|
1
|
+
"use strict";var Z=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.WatchdogTimeoutError=void 0,exports.resolveClaudeSettingsPath=te,exports.isRetryableApiError=ne,exports.parseClaudeStreamLine=fe,exports.interruptClaudeProcess=ge,exports.injectStartupContexts=xe,exports.injectSessionContextIfChanged=$e,exports.refreshSessionContext=De,exports.executeClaudeQuery=We;const a=Z(require("fs")),j=Z(require("path")),Ie=Z(require("readline")),Ce=require("child_process"),ve=require("util"),we=require("crypto"),ae=(0,ve.promisify)(Ce.exec),T=require("./messaging"),Re=require("./streaming"),n=require("./session"),h=require("./api-key-manager"),ce=require("./secrets"),J=require("./platform"),Te=require("./watchdog"),q=20,Q=1e4,de=1e4,ee=10,le=300*1e3,V=new Map;function te(e,t,o){const i=(0,h.getForceEnabledSettingsPath)(t);if(i)return i;if(e.config.apiKeyCfg){const u=(0,h.readApiKeyFromSettings)(t);let v=null;if(u&&(v=e.config.apiKeyCfg.claudeSettings.find(d=>(0,ce.resolveSecret)(d.apiKey)===u&&d.isValid)||null),v||(v=(0,h.pickValidApiKey)(e)),v)return(0,h.ensureSettingsWithApiKey)(t,v)}if(e.config.apiKeyCfg)return;if(o)return o;const g=j.default.join(t,".claude","settings.json");if(a.default.existsSync(g))return console.log(`[${(0,n.timestamp)()}] \u81EA\u52A8\u68C0\u6D4B\u5230 settings.json: ${g}`),g}function ne(e){if(/\b429\b/.test(e)&&!(0,h.isQuotaExhaustedError)(e)||/API\s*Error.*422/i.test(e)||/\b422\b.*(?:TPM|额度超限|rate\s*limit|tokens?\s*per\s*minute)/i.test(e)||/(?:TPM|额度超限).*\b422\b/i.test(e))return!0;const t=e.toLowerCase();return["rate limit","rate_limit","ratelimit","too many requests","tokens per minute","requests per minute","rpm limit","overloaded","capacity","temporarily unavailable"].some(i=>t.includes(i))}function Ee(e){return new Promise(t=>setTimeout(t,e))}class oe extends Error{constructor(t,o=""){super(`Retryable API error (TPM limit etc.)${t?" [fast fail]":""}`),this.name="RetryableApiError",this.isFastFail=t,this.output=o}}class ue extends Error{constructor(){super("Claude conversation not found"),this.name="ConversationNotFoundError"}}class H extends Error{constructor(){super("Watchdog timeout: process inactive for too long"),this.name="WatchdogTimeoutError"}}exports.WatchdogTimeoutError=H;class pe extends Error{constructor(){super("Context window exceeded: prompt tokens exceed maximum context window"),this.name="ContextWindowExceededError"}}function Me(e,t){try{return a.default.readFileSync(e,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean).slice(-t).join(`
|
|
3
|
-
`)}catch{return""}}function ke(e){return/prompt tokens?\s*\(\s*\d+\s*\)\s*exceeds/i.test(e)||/exceeds?.*maximum context window/i.test(e)}function Ae(e){const t=e.toLowerCase();return["permission denied","permission_required","needs permission","requires permission","authorization required","authorize","not authorized","access denied","\u9700\u8981\u6388\u6743","\u6743\u9650\u4E0D\u8DB3","\u6CA1\u6709\u6743\u9650"].some(i=>t.includes(i))}function be(e){return/no conversation found with session id/i.test(e)}function fe(e,t=!1){if(!e.trim())return null;try{const o=JSON.parse(e);if(o.type==="system"&&o.subtype==="init"&&o.session_id)return{type:"system",sessionId:o.session_id};if(o.type==="assistant"){const i=o.message?.content;if(Array.isArray(i)){const g=[];for(const
|
|
3
|
+
`)}catch{return""}}function ke(e){return/prompt tokens?\s*\(\s*\d+\s*\)\s*exceeds/i.test(e)||/exceeds?.*maximum context window/i.test(e)}function Ae(e){const t=e.toLowerCase();return["permission denied","permission_required","needs permission","requires permission","authorization required","authorize","not authorized","access denied","\u9700\u8981\u6388\u6743","\u6743\u9650\u4E0D\u8DB3","\u6CA1\u6709\u6743\u9650"].some(i=>t.includes(i))}function be(e){return/no conversation found with session id/i.test(e)}function fe(e,t=!1){if(!e.trim())return null;try{const o=JSON.parse(e);if(o.type==="system"&&o.subtype==="init"&&o.session_id)return{type:"system",sessionId:o.session_id};if(o.type==="assistant"){const i=o.message?.content;if(Array.isArray(i)){const g=[];for(const u of i)u.type==="text"&&u.text?g.push(u.text):u.type==="thinking"&&u.thinking&&t&&g.push(`\u{1F4AD} **\u601D\u8003\u8FC7\u7A0B**
|
|
4
4
|
\`\`\`
|
|
5
|
-
${
|
|
5
|
+
${u.thinking}
|
|
6
6
|
\`\`\``);if(g.length>0)return{type:"assistant",content:g.join(`
|
|
7
|
-
`)}}else if(o.content)return{type:"assistant",content:typeof o.content=="string"?o.content:JSON.stringify(o.content)};return{type:"assistant"}}if(o.type==="result"){const i=o.result||"";return{type:"result",content:typeof i=="string"?i:JSON.stringify(i)}}return{type:o.type||"unknown"}}catch{return{type:"text",content:e}}}function ge(e,t){return e.currentProcess?(console.log(`[${(0,n.timestamp)()}] ${t}`),e.interrupted=!0,(0,J.isWindows)()?e.currentProcess.kill():e.currentProcess.kill("SIGINT"),!0):!1}function me(e,t,o,i,g,
|
|
8
|
-
`,"utf-8"),y.stdin?.write(`${
|
|
9
|
-
`),y.stdin?.end();let X=!v&&!!t.claudeSessionId,b=[],P="",
|
|
10
|
-
`,"utf-8")}catch{}
|
|
11
|
-
`,"utf-8")}catch{}}},x);_.start(),Ie.default.createInterface({input:y.stdout}).on("line",c=>{if(
|
|
7
|
+
`)}}else if(o.content)return{type:"assistant",content:typeof o.content=="string"?o.content:JSON.stringify(o.content)};return{type:"assistant"}}if(o.type==="result"){const i=o.result||"";return{type:"result",content:typeof i=="string"?i:JSON.stringify(i)}}return{type:o.type||"unknown"}}catch{return{type:"text",content:e}}}function ge(e,t){return e.currentProcess?(console.log(`[${(0,n.timestamp)()}] ${t}`),e.interrupted=!0,(0,J.isWindows)()?e.currentProcess.kill():e.currentProcess.kill("SIGINT"),!0):!1}function me(e,t,o,i,g,u,v,d){let E=e.getSessionDir(t),S=`${E}/session.log`;a.default.existsSync(E)||a.default.mkdirSync(E,{recursive:!0});const x=Date.now();return new Promise((m,w)=>{const y=(0,J.spawnCommand)(i,o,{cwd:g,stdio:["pipe","pipe","pipe"]}),M=e.activeSessions.get(t.conversationId);M&&(M.currentProcess=y,M.lastActivityTime=Date.now()),a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [SYSTEM]: Claude \u67E5\u8BE2\u542F\u52A8${v?" (\u91CD\u8BD5)":""}
|
|
8
|
+
`,"utf-8"),y.stdin?.write(`${u}
|
|
9
|
+
`),y.stdin?.end();let X=!v&&!!t.claudeSessionId,b=[],P="",L="",Y=!1,O=!1;const B=new Set,z=()=>{M&&(M.lastActivityTime=Date.now())},_=new Te.AgentWatchdog(e,t,M,{killChild:()=>{M?.currentProcess&&ge(M,"Watchdog: \u81EA\u52A8\u7EC8\u6B62\u8D85\u65F6\u8FDB\u7A0B")},onTimeout:(c,r,l)=>{console.warn(`[${(0,n.timestamp)()}] Watchdog: Claude \u8FDB\u7A0B ${l}s \u65E0\u6D3B\u52A8\uFF0C\u6267\u884C\u81EA\u52A8\u6062\u590D`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [SYSTEM]: Watchdog \u8D85\u65F6\uFF0C${l}s \u65E0\u6D3B\u52A8\uFF0C\u81EA\u52A8 kill \u8FDB\u7A0B\u5E76\u6062\u590D
|
|
10
|
+
`,"utf-8")}catch{}O=!0,M?.currentProcess||w(new H)},onRecoveryFailed:c=>{console.warn(`[${(0,n.timestamp)()}] Watchdog: \u5DF2\u8FBE\u6700\u5927\u81EA\u52A8\u6062\u590D\u6B21\u6570 ${c}`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [SYSTEM]: Watchdog \u8D85\u65F6\uFF0C\u5DF2\u8FBE\u6700\u5927\u81EA\u52A8\u6062\u590D\u6B21\u6570 ${c}
|
|
11
|
+
`,"utf-8")}catch{}}},x);_.start(),Ie.default.createInterface({input:y.stdout}).on("line",c=>{if(L+=c+`
|
|
12
12
|
`,z(),e.debugLog(`Claude stdout: ${c.substring(0,200)}${c.length>200?"...":""}`),e.config.debug)try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [RAW]: ${c}
|
|
13
|
-
`,"utf-8")}catch{}const r=fe(c,e.config.includeThinking??!1);if(r){if(r.type==="system"&&r.sessionId&&!X&&(e.updateSessionFile(t,{claudeSessionId:r.sessionId}),X=!0,E=e.getSessionDir(t),S=`${E}/session.log`),r.type==="assistant"){try{const p=JSON.parse(c)?.message?.content;if(Array.isArray(p)){for(const s of p)if(s.type==="tool_use"&&s.id&&!B.has(s.id)){B.add(s.id);const R=s.name||"unknown";let I="";s.input&&(s.input.command?I=s.input.command.substring(0,200):s.input.file_path?I=s.input.file_path:s.input.pattern?I=s.input.pattern:s.input.query?I=s.input.query:s.input.description?I=s.input.description:s.input.prompt?I=s.input.prompt.substring(0,200):I=JSON.stringify(s.input).substring(0,200)),e.appendSessionLog(E,"tool",`${R}${I?": "+I:""}`)}}}catch{}if(r.content&&(b.push(r.content),d&&!d.failed)){const
|
|
14
|
-
`).trim();
|
|
15
|
-
`).trim(),R=
|
|
16
|
-
`,"utf-8")}catch{}const r=e.activeSessions.get(t.conversationId);if(r&&(r.currentProcess=void 0),
|
|
17
|
-
`).trim();if(p){try{e.appendSessionLog(E,"assistant",p)}catch{}if(d&&!d.permissionDenied)d.finalize(p).then(s=>{if(!s||d.failed||d.permissionDenied){const R=r?.lastSenderStaffId||t.startStaffId;
|
|
18
|
-
`,"utf-8")}catch{}const p=r?.lastSenderStaffId||t.startStaffId;(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:p,content:"\u26A0\uFE0F Claude \u5904\u7406\u5B8C\u6210\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5185\u5BB9"}).catch(s=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",s))}if(c===0){m(0);return}const
|
|
19
|
-
`+
|
|
13
|
+
`,"utf-8")}catch{}const r=fe(c,e.config.includeThinking??!1);if(r){if(r.type==="system"&&r.sessionId&&!X&&(e.updateSessionFile(t,{claudeSessionId:r.sessionId}),X=!0,E=e.getSessionDir(t),S=`${E}/session.log`),r.type==="assistant"){try{const p=JSON.parse(c)?.message?.content;if(Array.isArray(p)){for(const s of p)if(s.type==="tool_use"&&s.id&&!B.has(s.id)){B.add(s.id);const R=s.name||"unknown";let I="";s.input&&(s.input.command?I=s.input.command.substring(0,200):s.input.file_path?I=s.input.file_path:s.input.pattern?I=s.input.pattern:s.input.query?I=s.input.query:s.input.description?I=s.input.description:s.input.prompt?I=s.input.prompt.substring(0,200):I=JSON.stringify(s.input).substring(0,200)),e.appendSessionLog(E,"tool",`${R}${I?": "+I:""}`)}}}catch{}if(r.content&&(b.push(r.content),d&&!d.failed)){const l=b.join(`
|
|
14
|
+
`).trim();l&&d.update(l).catch(()=>{})}}if(r.type==="result"){const l=e.config.resultOnly??!0,p=(r.content||"").trim(),s=b.join(`
|
|
15
|
+
`).trim(),R=l&&p||s;if(R&&!M?.interrupted){try{e.appendSessionLog(E,"assistant",R)}catch{}if(d&&!d.permissionDenied)Y=!0,d.finalize(R).then(I=>{if(!I||d.failed||d.permissionDenied){const f=e.activeSessions.get(t.conversationId)?.lastSenderStaffId||t.startStaffId;(0,T.sendClaudeResponseToDing)(e,(0,n.getReplyConversationId)(t),(0,n.getReplyWebhook)(t),f,R).catch(k=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",k))}}).catch(()=>{const K=e.activeSessions.get(t.conversationId)?.lastSenderStaffId||t.startStaffId;(0,T.sendClaudeResponseToDing)(e,(0,n.getReplyConversationId)(t),(0,n.getReplyWebhook)(t),K,R).catch(f=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",f))});else{const K=e.activeSessions.get(t.conversationId)?.lastSenderStaffId||t.startStaffId;Y=!0,(0,T.sendClaudeResponseToDing)(e,(0,n.getReplyConversationId)(t),(0,n.getReplyWebhook)(t),K,R).catch(f=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",f))}}else console.warn(`[${(0,n.timestamp)()}] Claude \u8FD4\u56DE\u4E86\u7A7A\u7684 result \u4E14 responseBuffer \u4E5F\u4E3A\u7A7A\uFF0C\u65E0\u5185\u5BB9\u53EF\u53D1\u9001`);b=[]}}}),y.stderr?.on("data",c=>{const r=c.toString();if(P+=r,z(),(0,h.isQuotaExhaustedError)(r)){console.log(`[${(0,n.timestamp)()}] [Claude stderr] \u914D\u989D\u8017\u5C3D\u9519\u8BEF(429): ${r.trim()}`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [WARN]: ${r}`,"utf-8")}catch{}}else if(ne(r)){console.log(`[${(0,n.timestamp)()}] [Claude stderr] \u53EF\u91CD\u8BD5API\u9519\u8BEF(422 TPM\u9650\u6D41): ${r.trim()}`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [WARN]: ${r}`,"utf-8")}catch{}}else{console.error(`[Claude stderr]: ${r}`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [ERROR]: ${r}`,"utf-8")}catch{}}}),y.on("close",c=>{_.markSettled(),_.markSettled(),_.stop(),console.log(`[${(0,n.timestamp)()}] Claude \u8FDB\u7A0B\u9000\u51FA\uFF0C\u4EE3\u7801: ${c}`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [SYSTEM]: Claude \u67E5\u8BE2\u7ED3\u675F\uFF0C\u9000\u51FA\u7801: ${c}
|
|
16
|
+
`,"utf-8")}catch{}const r=e.activeSessions.get(t.conversationId);if(r&&(r.currentProcess=void 0),O){console.log(`[${(0,n.timestamp)()}] Watchdog \u89E6\u53D1\u7684\u8FDB\u7A0B\u9000\u51FA\uFF0Creject WatchdogTimeoutError`),w(new H);return}if(r?.interrupted){console.log(`[${(0,n.timestamp)()}] \u7528\u6237\u4E3B\u52A8\u4E2D\u65AD\uFF0C\u4E22\u5F03 responseBuffer (${b.length} \u6BB5)`),r.interrupted=!1,b=[],m(0);return}if(b.length>0){const p=b.join(`
|
|
17
|
+
`).trim();if(p){try{e.appendSessionLog(E,"assistant",p)}catch{}if(d&&!d.permissionDenied)Y=!0,d.finalize(p).then(s=>{if(!s||d.failed||d.permissionDenied){const R=r?.lastSenderStaffId||t.startStaffId;(0,T.sendClaudeResponseToDing)(e,(0,n.getReplyConversationId)(t),(0,n.getReplyWebhook)(t),R,p).catch(I=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",I))}}).catch(()=>{const s=r?.lastSenderStaffId||t.startStaffId;(0,T.sendClaudeResponseToDing)(e,(0,n.getReplyConversationId)(t),(0,n.getReplyWebhook)(t),s,p).catch(R=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",R))});else{const s=r?.lastSenderStaffId||t.startStaffId;Y=!0,(0,T.sendClaudeResponseToDing)(e,(0,n.getReplyConversationId)(t),(0,n.getReplyWebhook)(t),s,p).catch(R=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",R))}}}if(c===0&&!Y&&!r?.interrupted){console.warn(`[${(0,n.timestamp)()}] Claude \u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA\u4F46\u672A\u4EA7\u751F\u4EFB\u4F55\u56DE\u590D\u5185\u5BB9`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [WARN]: Claude \u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA\u4F46\u672A\u4EA7\u751F\u4EFB\u4F55\u56DE\u590D\u5185\u5BB9
|
|
18
|
+
`,"utf-8")}catch{}const p=r?.lastSenderStaffId||t.startStaffId;(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:p,content:"\u26A0\uFE0F Claude \u5904\u7406\u5B8C\u6210\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5185\u5BB9"}).catch(s=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",s))}if(c===0){m(0);return}const l=P+`
|
|
19
|
+
`+L;if((0,h.isQuotaExhaustedError)(l)){const s=Date.now()-x<de;console.log(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230\u914D\u989D\u8017\u5C3D\u9519\u8BEF(429)\uFF0Cstdout\u5339\u914D=${(0,h.isQuotaExhaustedError)(L)}, stderr\u5339\u914D=${(0,h.isQuotaExhaustedError)(P)}`),w(new oe(s,l));return}if((0,h.isAuthenticationError)(l)){console.log(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230\u8BA4\u8BC1\u9519\u8BEF(401)\uFF0C\u901A\u77E5\u7528\u6237`);const p=r?.lastSenderStaffId||t.startStaffId;(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:p,content:"\u26A0\uFE0F \u8BA4\u8BC1\u5931\u8D25(401)\uFF0CAPI Key \u65E0\u6548\u6216\u670D\u52A1\u672A\u6388\u6743\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E"}).catch(s=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",s)),m(c??1);return}if(ne(l)){const s=Date.now()-x<de;w(new oe(s,l));return}if(Ae(l)){console.log(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230\u9700\u8981\u6388\u6743\uFF0C\u901A\u77E5\u7528\u6237`);const p=r?.lastSenderStaffId||t.startStaffId;(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:p,content:"\u26A0\uFE0F Claude \u9700\u8981\u6388\u6743\uFF0C\u8BF7\u4EBA\u5DE5\u4ECB\u5165"}).catch(s=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",s)),m(c??1);return}if(t.claudeSessionId&&be(l)){console.log(`[${(0,n.timestamp)()}] Claude \u4F1A\u8BDD\u5DF2\u5931\u6548: ${t.claudeSessionId}\uFF0C\u901A\u77E5\u5916\u5C42\u91CD\u65B0\u53D1\u8D77\u65B0\u4F1A\u8BDD`),w(new ue);return}if(ke(l)){console.log(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230\u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\u9519\u8BEF(400)\uFF0C\u5C06\u81EA\u52A8\u53D1\u9001 /compact \u538B\u7F29\u4E0A\u4E0B\u6587`);try{a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [SYSTEM]: \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u5C06\u81EA\u52A8 /compact
|
|
20
20
|
`,"utf-8")}catch{}w(new pe);return}w(new Error(`Claude \u8FDB\u7A0B\u9000\u51FA\uFF0C\u4EE3\u7801: ${c}`))}),y.on("error",c=>{_.markSettled(),_.markSettled(),_.stop(),console.error("Claude \u8FDB\u7A0B\u9519\u8BEF:",c),a.default.appendFileSync(S,`[${(0,n.timestamp)()}] [ERROR]: \u8FDB\u7A0B\u9519\u8BEF: ${c.message}
|
|
21
21
|
`,"utf-8"),w(c)})})}const Se="<!-- cc-ding:session-context-start (DO NOT EDIT) -->",ie="<!-- cc-ding:session-context-end (DO NOT EDIT) -->";function se(e,t){const o=e.getConversationConfig(t),i=e.config;return[Se,"# cc-ding Session Context","## Client",`- clientId: \`${e.clientId}\``,i.clientName?`- clientName: ${i.clientName}`:"",`- owner: ${i.owner}`,"## Conversation",`- conversationId: \`${t}\``,o?.conversationType?`- conversationType: ${o.conversationType==="1"?"\u5355\u804A":"\u7FA4\u804A"}`:"",o?.conversationTitle?`- conversationTitle: ${o.conversationTitle}`:"",o?.linkConversationId?`- linkConversationId: \`${o.linkConversationId}\` (\u5173\u8054\u7FA4\uFF0C\u5171\u4EAB\u5DE5\u4F5C\u76EE\u5F55)`:"","## Settings",o?.permissionMode?`- permissionMode: ${o.permissionMode}`:"",o?.agent?`- agent: ${o.agent}`:"",o?.taskCfg?.skill?`- taskCfg.skill: ${o.taskCfg.skill}`:"",i.resultOnly!==void 0?`- resultOnly: ${i.resultOnly}`:"",i.includeThinking!==void 0?`- includeThinking: ${i.includeThinking}`:"",i.preBash?`- preBash(\u5168\u5C40): \`${i.preBash}\``:"",o?.preBash?`- preBash(\u7FA4): \`${o.preBash}\``:"",o?.qaMode?"- qaMode: true (\u95EE\u7B54\u6A21\u5F0F\uFF0C\u4EC5\u56DE\u7B54\u95EE\u9898\uFF0C\u7981\u6B62\u6267\u884C\u547D\u4EE4\u3001\u5199\u5165\u6587\u4EF6\u6216\u8FD0\u884C\u4EE3\u7801)":"",o?.qaMode&&o.qaCfg?.docs?.length?`- qaDocs: ${o.qaCfg.docs.join(", ")}`:"","## DingTalk Context",'\u5F53 prompt \u4E2D\u5305\u542B "\u6D88\u606F\u6765\u81EA: xxx(\u7528\u6237ID)" \u65F6\uFF0C\u8BF4\u660E\u6D88\u606F\u6765\u81EA\u9489\u9489\u7528\u6237\u3002',"- \u56DE\u7B54\u65F6\u8981\u8003\u8651\u7528\u6237\u7684\u4F7F\u7528\u573A\u666F\uFF08\u9489\u9489\u804A\u5929\u754C\u9762\uFF0C\u975E\u7EC8\u7AEF\u73AF\u5883\uFF09","- \u7528\u6237\u4E00\u822C\u60C5\u51B5\u4E0B\u53EA\u80FD\u901A\u8FC7 cc-ding \u8FDB\u884C\u64CD\u4F5C","- cc-ding \u6587\u6863: https://github.com/yihuineng/cc-ding",ie].filter(Boolean).join(`
|
|
22
22
|
`)+`
|
|
23
|
-
`}function ye(e,t,o){const i=e.getConversationDir(t),g=
|
|
24
|
-
`+v,"utf-8"),console.log(`[${(0,n.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u8FFD\u52A0\u5230\u73B0\u6709 CLAUDE.md: ${
|
|
25
|
-
`,"utf-8"),await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:d||t.startStaffId,content:`\u274C ${f}`});return}let
|
|
23
|
+
`}function ye(e,t,o){const i=e.getConversationDir(t),g=j.default.join(i,".claude");a.default.existsSync(g)||a.default.mkdirSync(g,{recursive:!0});const u=j.default.join(g,"CLAUDE.md");if(!a.default.existsSync(u)){a.default.writeFileSync(u,o,"utf-8"),console.log(`[${(0,n.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u6CE8\u5165 CLAUDE.md: ${u}`);return}const v=a.default.readFileSync(u,"utf-8"),d=v.indexOf(Se),E=v.indexOf(ie);if(d!==-1&&E!==-1&&E>d){const S=v.substring(0,d),x=v.substring(E+ie.length),m=S+o+x;a.default.writeFileSync(u,m,"utf-8"),console.log(`[${(0,n.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u66F4\u65B0: ${u}`)}else a.default.writeFileSync(u,o+`
|
|
24
|
+
`+v,"utf-8"),console.log(`[${(0,n.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u8FFD\u52A0\u5230\u73B0\u6709 CLAUDE.md: ${u}`)}function xe(e){const t=Array.isArray(e.config.conversations)?e.config.conversations:[];for(const o of t){const i=se(e,o.conversationId);V.set(o.conversationId,i),ye(e,o.conversationId,i)}}function $e(e,t){const o=t.conversationId,i=se(e,o);V.get(o)!==i&&(V.set(o,i),ye(e,o,i))}function De(e,t){V.delete(t);const o=se(e,t),i=e.getConversationDir(t),g=j.default.join(i,".claude");a.default.existsSync(g)||a.default.mkdirSync(g,{recursive:!0});const u=j.default.join(g,"CLAUDE.md");a.default.writeFileSync(u,o,"utf-8"),console.log(`[${(0,n.timestamp)()}] QA \u6A21\u5F0F\u5207\u6362\uFF0CCLAUDE.md \u5DF2\u5237\u65B0: ${u}`)}async function We(e,t,o,i){const{skill:g,agent:u,senderNick:v,senderStaffId:d,newSessionId:E,conversationConfig:S}=i||{};let x=e.getSessionDir(t),m=`${x}/session.log`;const w=e.getConversationDir(t.conversationId);$e(e,t),a.default.mkdirSync(x,{recursive:!0});let y=null;const M=(0,h.readApiKeyFromSettings)(w);if(M&&e.config.apiKeyCfg&&(y=e.config.apiKeyCfg.claudeSettings.find(f=>(0,ce.resolveSecret)(f.apiKey)===M&&f.isValid)||null,y&&console.log(`[${(0,n.timestamp)()}] \u4ECE settings-ding.json \u6062\u590D Claude Setting: ${(0,h.settingLabel)(y)}`)),!(0,h.getForceEnabledSettingsPath)(w)&&e.config.apiKeyCfg&&(y=(0,h.pickValidApiKey)(e),!y)){const f=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:f,content:"\u26A0\uFE0F \u5F53\u524D\u65E0\u53EF\u7528\u914D\u989D\uFF08\u65E0\u53EF\u7528 API Key\uFF09\uFF0C\u8BF7\u660E\u5929\u518D\u8BD5\u6216\u8054\u7CFB\u7BA1\u7406\u5458"});return}const b=v&&d?`${o} \u2500\u2500 \u6D88\u606F\u6765\u81EA: ${v}(${d})`:o;e.appendSessionLog(x,"user",b);const P="claude";if(!(0,J.commandExists)(P)){const f=(0,J.formatClaudeCommandMissingMessage)(P);console.error(`[${(0,n.timestamp)()}] ${f.replace(/\n/g," ")}`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [ERROR]: ${f}
|
|
25
|
+
`,"utf-8"),await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:d||t.startStaffId,content:`\u274C ${f}`});return}let L=g?`/${g} ${b}`:b;if(S?.qaMode){if(i.permissionMode="plan",S.qaCfg?.autoPull&&S.qaCfg.gitRepos?.length)try{for(const D of S.qaCfg.gitRepos){const C=D.replace(/\/$/,"").replace(/\.git$/,"").split("/").pop()||D,$=j.default.join(w,C);a.default.existsSync(j.default.join($,".git"))?(await ae("git pull",{cwd:$,timeout:6e4}),console.log(`[${(0,n.timestamp)()}] QA \u6A21\u5F0F git pull: ${C}`)):(await ae(`git clone ${D}`,{cwd:w,timeout:12e4}),console.log(`[${(0,n.timestamp)()}] QA \u6A21\u5F0F git clone: ${D} -> ${C}`))}}catch(D){console.error(`[${(0,n.timestamp)()}] QA \u6A21\u5F0F git \u64CD\u4F5C\u5931\u8D25:`,D)}const f=`\u3010\u91CD\u8981\u89C4\u5219\u3011\u5F53\u524D\u4E3A\u95EE\u7B54\u6A21\u5F0F\uFF0C\u8BF7\u4E25\u683C\u9075\u5B88\uFF1A
|
|
26
26
|
1. \u4EC5\u56DE\u7B54\u95EE\u9898\uFF0C\u4E0D\u8981\u6267\u884C\u4EFB\u4F55\u547D\u4EE4
|
|
27
27
|
2. \u4E0D\u8981\u4FEE\u6539\u6216\u5199\u5165\u4EFB\u4F55\u6587\u4EF6
|
|
28
28
|
3. \u4E0D\u8981\u5C1D\u8BD5\u8FD0\u884C\u4EE3\u7801\u3001\u811A\u672C\u6216\u5DE5\u5177
|
|
29
29
|
4. \u4E0D\u8981\u8FDB\u884C git push\u3001commit \u7B49\u5199\u64CD\u4F5C`,k=S.qaCfg?.docs?.length?`
|
|
30
30
|
|
|
31
31
|
\u3010\u53C2\u8003\u8D44\u6599\u94FE\u63A5\u3011
|
|
32
|
-
${S.qaCfg.docs.map((D,
|
|
32
|
+
${S.qaCfg.docs.map((D,U)=>`${U+1}. ${D}`).join(`
|
|
33
33
|
`)}
|
|
34
|
-
\u4F60\u53EF\u4EE5\u4F7F\u7528 WebFetch \u5DE5\u5177\u8BBF\u95EE\u4E0A\u8FF0\u94FE\u63A5\u83B7\u53D6\u8BE6\u7EC6\u5185\u5BB9`:"";
|
|
34
|
+
\u4F60\u53EF\u4EE5\u4F7F\u7528 WebFetch \u5DE5\u5177\u8BBF\u95EE\u4E0A\u8FF0\u94FE\u63A5\u83B7\u53D6\u8BE6\u7EC6\u5185\u5BB9`:"";L=`${f}${k}
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
38
|
\u7528\u6237\u95EE\u9898\uFF1A
|
|
39
|
-
${
|
|
39
|
+
${L}`}const O=["--permission-mode",i?.permissionMode??"bypassPermissions","--print","--output-format","stream-json","--verbose"];u&&O.push("--agent",u);const B=i?.model,z=e.getConversationConfig(t.conversationId)?.model,_=e.config.model,G=B||z||_;G&&O.push("--model",G);let c=0,r=0,l=0;const p=[],s=e.activeSessions.get(t.conversationId);s&&(s.autoRecoveryAttempts=0);const R=f=>{const k=e.activeSessions.get(t.conversationId);return!k||k!==s?(console.log(`[${(0,n.timestamp)()}] \u4F1A\u8BDD\u5DF2\u88AB\u7EC8\u6B62\uFF0C${f}`),!1):k.goonPending?(console.log(`[${(0,n.timestamp)()}] \u6536\u5230 /goon \u8BF7\u6C42\uFF0C${f}`),!1):!0},I=e.getConversationConfig(t.conversationId);let K=null;for(I?.streaming&&e.config.cardTemplateId&&s&&(K=await Re.StreamingCard.create({self:e,cardTemplateId:e.config.cardTemplateId,cardTemplateKey:e.config.cardTemplateKey,conversationId:t.conversationId,conversationType:I.conversationType,senderStaffId:s.lastSenderStaffId||t.startStaffId}),K||console.log(`[${(0,n.timestamp)()}] StreamingCard \u521B\u5EFA\u5931\u8D25\uFF0C\u4F7F\u7528\u666E\u901A\u6D88\u606F\u6A21\u5F0F`));;){if(!R("\u505C\u6B62\u91CD\u8BD5"))return;const f=c>0;if(r>=ee||r>=3&&l>0&&Date.now()-l>le){const C=r>=ee?`\u603B\u91CD\u8BD5\u6B21\u6570\u5DF2\u8FBE ${ee} \u6B21`:`\u91CD\u8BD5\u6301\u7EED\u65F6\u95F4\u8D85\u8FC7 ${le/1e3}s\uFF08\u5DF2\u91CD\u8BD5 ${r} \u6B21\uFF09`;console.error(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230\u65E0\u9650\u91CD\u8BD5\u5FAA\u73AF: ${C}`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: \u68C0\u6D4B\u5230\u65E0\u9650\u91CD\u8BD5\u5FAA\u73AF\uFF0C${C}\uFF0C\u7EC8\u6B62\u91CD\u8BD5
|
|
40
40
|
`,"utf-8");const $=Me(m,1),W=p.slice(-1)[0]||"",A=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:A,content:`\u{1F504} \u68C0\u6D4B\u5230 Claude \u9677\u5165\u65E0\u9650\u91CD\u8BD5\uFF0C\u5DF2\u7EC8\u6B62\uFF08${C}\uFF09
|
|
41
41
|
|
|
42
42
|
\u{1F4CB} \u6700\u8FD1\u91CD\u8BD5\u8BB0\u5F55\uFF1A
|
|
@@ -47,15 +47,15 @@ ${W}
|
|
|
47
47
|
${$}
|
|
48
48
|
\`\`\`
|
|
49
49
|
|
|
50
|
-
\u{1F4A1} \u53EF\u5C1D\u8BD5\u53D1\u9001 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u6216 /end \u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD`});return}const k=[...
|
|
51
|
-
`,"utf-8")):
|
|
52
|
-
`,"utf-8");continue}}const $=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:$,content:"\u26A0\uFE0F \u5F53\u524D\u65E0\u53EF\u7528\u914D\u989D/API Key\uFF0C\u8BF7\u660E\u5929\u518D\u8BD5\u6216\u8054\u7CFB\u7BA1\u7406\u5458"});return}if(C.isFastFail){if(c++,c>=
|
|
53
|
-
`,"utf-8");continue}}throw console.log(`[${(0,n.timestamp)()}] TPM \u9650\u6D41\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${
|
|
54
|
-
`,"utf-8"),new Error(`TPM \u9650\u6D41\uFF0C\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED ${
|
|
55
|
-
`,"utf-8"),p.push(`[${(0,n.timestamp)()}] TPM \u9650\u6D41\uFF0C${Q/1e3}s \u540E\u91CD\u8BD5`),await Ee(Q),!R("\u505C\u6B62\u5F53\u524D\u91CD\u8BD5"))return;continue}if(C instanceof
|
|
56
|
-
`,"utf-8"),t.claudeSessionId&&(t.claudeSessionId=void 0,e.updateSessionFile(t,{})),c=0;continue}if(C instanceof H){const $=e.activeSessions.get(t.conversationId),W=e.getConversationConfig(t.conversationId),A=e.config.maxAutoRecovery??2,F=W?.maxTurnTimeMins??e.config.maxTurnTimeMins??5,re=$?.autoRecoveryAttempts??0;if(re<A){const
|
|
57
|
-
`,"utf-8");const he=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:he,content:` Claude \u8FDB\u7A0B\u8D85\u8FC7 ${F} \u5206\u949F\u65E0\u54CD\u5E94\uFF0C\u5DF2\u81EA\u52A8\u91CD\u542F\u6062\u590D\uFF08${
|
|
58
|
-
`,"utf-8");const
|
|
59
|
-
`,"utf-8");const $=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:$,content:"\u{1F4E6} \u4E0A\u4E0B\u6587\u8D85\u957F\uFF0C\u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587(/compact)\u540E\u7EE7\u7EED..."});const W=[...
|
|
50
|
+
\u{1F4A1} \u53EF\u5C1D\u8BD5\u53D1\u9001 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u6216 /end \u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD`});return}const k=[...O];if(t.claudeSessionId)k.push("--resume",t.claudeSessionId),f||console.log(`[${(0,n.timestamp)()}] \u6062\u590D Claude \u4F1A\u8BDD: ${t.claudeSessionId}`);else if(!f){const C=E||(0,we.randomUUID)();k.push("--session-id",C),console.log(`[${(0,n.timestamp)()}] \u521B\u5EFA Claude \u4F1A\u8BDD(\u663E\u5F0F session-id): ${C}`)}const D=te(e,w,i?.settings);D&&k.push("--settings",D);let U;f?(U="\u7EE7\u7EED",console.log(`[${(0,n.timestamp)()}] \u53D1\u9001"\u7EE7\u7EED"\u91CD\u8BD5 (\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${c}/${q}\u6B21)`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\uFF0C\u53D1\u9001"\u7EE7\u7EED"\u91CD\u8BD5 (\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${c}/${q})
|
|
51
|
+
`,"utf-8")):U=L,console.log(`[${(0,n.timestamp)()}] \u6267\u884C Claude \u67E5\u8BE2[\u539F\u751Fclaude \u6A21\u5F0F]: ${P} ${k.join(" ")}`),e.debugLog(`\u53D1\u9001\u6D88\u606F: ${U.substring(0,100)}...`);try{await me(e,t,k,P,w,U,f,K);return}catch(C){if(x=e.getSessionDir(t),m=`${x}/session.log`,C instanceof oe){if(r++,l=l||Date.now(),(0,h.isQuotaExhaustedError)(C.output)&&e.config.apiKeyCfg){if(p.push(`[${(0,n.timestamp)()}] 429 \u914D\u989D\u8017\u5C3D\uFF0C\u5C1D\u8BD5\u8F6E\u6362 Key`),y){const W=(0,h.rotateApiKey)(e,y.apiKey);if(W){y=W,c=0,console.log(`[${(0,n.timestamp)()}] API Key \u914D\u989D\u8017\u5C3D(429)\uFF0C\u5207\u6362\u5230\u65B0 Key: ${(0,h.settingLabel)(W)}`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: API Key \u914D\u989D\u8017\u5C3D(429)\uFF0C\u5207\u6362\u5230\u65B0 Key
|
|
52
|
+
`,"utf-8");continue}}const $=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:$,content:"\u26A0\uFE0F \u5F53\u524D\u65E0\u53EF\u7528\u914D\u989D/API Key\uFF0C\u8BF7\u660E\u5929\u518D\u8BD5\u6216\u8054\u7CFB\u7BA1\u7406\u5458"});return}if(C.isFastFail){if(c++,c>=q){if(y&&e.config.apiKeyCfg){const $=(0,h.rotateApiKey)(e,y.apiKey);if($){y=$,c=0,console.log(`[${(0,n.timestamp)()}] TPM \u9650\u6D41\u8FDE\u7EED\u5FEB\u901F\u5931\u8D25 ${q} \u6B21\uFF0C\u5207\u6362\u5230\u65B0 Key: ${(0,h.settingLabel)($)}`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\u8FDE\u7EED\u5FEB\u901F\u5931\u8D25\uFF0C\u5207\u6362\u5230\u65B0 Key
|
|
53
|
+
`,"utf-8");continue}}throw console.log(`[${(0,n.timestamp)()}] TPM \u9650\u6D41\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${q}\u6B21\uFF0C\u653E\u5F03`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${q}\u6B21\uFF0C\u653E\u5F03
|
|
54
|
+
`,"utf-8"),new Error(`TPM \u9650\u6D41\uFF0C\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED ${q} \u6B21`)}console.log(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230 TPM \u9650\u6D41(\u5FEB\u901F\u5931\u8D25)\uFF0C${Q/1e3}s \u540E\u91CD\u8BD5 (${c}/${q})`)}else c=0,console.log(`[${(0,n.timestamp)()}] \u68C0\u6D4B\u5230 TPM \u9650\u6D41(\u8FDB\u7A0B\u5DF2\u8FD0\u884C\u4E00\u6BB5\u65F6\u95F4)\uFF0C\u91CD\u7F6E\u5FEB\u901F\u5931\u8D25\u8BA1\u6570\uFF0C${Q/1e3}s \u540E\u91CD\u8BD5`);if(a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\uFF0C${Q/1e3}s \u540E\u91CD\u8BD5
|
|
55
|
+
`,"utf-8"),p.push(`[${(0,n.timestamp)()}] TPM \u9650\u6D41\uFF0C${Q/1e3}s \u540E\u91CD\u8BD5`),await Ee(Q),!R("\u505C\u6B62\u5F53\u524D\u91CD\u8BD5"))return;continue}if(C instanceof ue){r++,l=l||Date.now(),p.push(`[${(0,n.timestamp)()}] \u4F1A\u8BDD\u5931\u6548\uFF0C\u6E05\u9664\u65E7\u4F1A\u8BDD`),console.log(`[${(0,n.timestamp)()}] Claude \u4F1A\u8BDD\u5931\u6548\uFF0C\u6E05\u9664 claudeSessionId \u5E76\u91CD\u65B0\u53D1\u8D77`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: Claude \u4F1A\u8BDD\u5DF2\u5931\u6548\uFF0C\u6E05\u9664\u65E7\u4F1A\u8BDD\u5E76\u91CD\u65B0\u53D1\u8D77
|
|
56
|
+
`,"utf-8"),t.claudeSessionId&&(t.claudeSessionId=void 0,e.updateSessionFile(t,{})),c=0;continue}if(C instanceof H){const $=e.activeSessions.get(t.conversationId),W=e.getConversationConfig(t.conversationId),A=e.config.maxAutoRecovery??2,F=W?.maxTurnTimeMins??e.config.maxTurnTimeMins??5,re=$?.autoRecoveryAttempts??0;if(re<A){const N=re+1;$&&($.autoRecoveryAttempts=N),r++,l=l||Date.now(),p.push(`[${(0,n.timestamp)()}] Watchdog \u8D85\u65F6\uFF0C\u81EA\u52A8\u6062\u590D ${N}/${A}`),console.log(`[${(0,n.timestamp)()}] Watchdog \u8D85\u65F6\uFF0C\u81EA\u52A8\u6062\u590D ${N}/${A}\uFF0C\u53D1\u9001"\u7EE7\u7EED"`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: Watchdog \u8D85\u65F6\uFF0C\u81EA\u52A8\u6062\u590D ${N}/${A}
|
|
57
|
+
`,"utf-8");const he=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:he,content:` Claude \u8FDB\u7A0B\u8D85\u8FC7 ${F} \u5206\u949F\u65E0\u54CD\u5E94\uFF0C\u5DF2\u81EA\u52A8\u91CD\u542F\u6062\u590D\uFF08${N}/${A}\uFF09\uFF0C\u7EE7\u7EED\u6267\u884C\u4E2D...`}),c=0,$&&($.interrupted=!1);continue}else{console.log(`[${(0,n.timestamp)()}] Watchdog \u8D85\u65F6\uFF0C\u5DF2\u8FBE\u6700\u5927\u81EA\u52A8\u6062\u590D\u6B21\u6570 ${A}\uFF0C\u901A\u77E5\u7528\u6237`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: Watchdog \u8D85\u65F6\uFF0C\u5DF2\u8FBE\u6700\u5927\u81EA\u52A8\u6062\u590D\u6B21\u6570 ${A}
|
|
58
|
+
`,"utf-8");const N=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:N,content:`\u23F0 Claude \u8FDB\u7A0B\u5DF2\u8D85\u8FC7 ${F} \u5206\u949F\u65E0\u54CD\u5E94\uFF0C\u5DF2\u5C1D\u8BD5\u81EA\u52A8\u6062\u590D ${A} \u6B21\u4F46\u4ECD\u8D85\u65F6\u3002\u8BF7\u53D1\u9001 /goon \u624B\u52A8\u91CD\u542F\uFF0C\u6216 /end \u7ED3\u675F\u4F1A\u8BDD`});return}}if(C instanceof pe){r++,l=l||Date.now(),p.push(`[${(0,n.timestamp)()}] \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u81EA\u52A8 /compact`),console.log(`[${(0,n.timestamp)()}] \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u81EA\u52A8\u53D1\u9001 /compact \u538B\u7F29\u4E0A\u4E0B\u6587`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u81EA\u52A8\u53D1\u9001 /compact \u538B\u7F29\u4E0A\u4E0B\u6587
|
|
59
|
+
`,"utf-8");const $=d||t.startStaffId;await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:$,content:"\u{1F4E6} \u4E0A\u4E0B\u6587\u8D85\u957F\uFF0C\u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587(/compact)\u540E\u7EE7\u7EED..."});const W=[...O];t.claudeSessionId&&W.push("--resume",t.claudeSessionId);const A=te(e,w,i?.settings);A&&W.push("--settings",A);try{await me(e,t,W,P,w,"/compact",!1),console.log(`[${(0,n.timestamp)()}] /compact \u6267\u884C\u6210\u529F\uFF0C\u53D1\u9001"\u7EE7\u7EED"\u6062\u590D\u6267\u884C`),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: /compact \u6267\u884C\u6210\u529F\uFF0C\u53D1\u9001"\u7EE7\u7EED"\u6062\u590D\u6267\u884C
|
|
60
60
|
`,"utf-8")}catch(F){throw console.error(`[${(0,n.timestamp)()}] /compact \u6267\u884C\u5931\u8D25:`,F),a.default.appendFileSync(m,`[${(0,n.timestamp)()}] [SYSTEM]: /compact \u6267\u884C\u5931\u8D25: ${F instanceof Error?F.message:String(F)}
|
|
61
61
|
`,"utf-8"),await(0,T.sendDingMessage)(e,{conversationId:(0,n.getReplyConversationId)(t),sessionWebhook:(0,n.getReplyWebhook)(t),atUserId:$,content:"\u274C \u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587(/compact)\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u53D1\u9001 /compact \u6216 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD"}),new Error(`\u4E0A\u4E0B\u6587\u8D85\u957F\u4E14 /compact \u5931\u8D25: ${F instanceof Error?F.message:String(F)}`)}c=0;continue}throw C}}}
|
package/dist/src/biz/session.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var P=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.timestamp=$,exports.getHomeDir=T,exports.getClientDir=D,exports.initClientDir=Y,exports.ensureClientDir=
|
|
2
|
-
`)}function we(e,t,n){const s=I(e,t);if(!s)return null;const o=s.session,
|
|
1
|
+
"use strict";var P=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.timestamp=$,exports.getHomeDir=T,exports.getClientDir=D,exports.initClientDir=Y,exports.ensureClientDir=ae,exports.getClientConfig=ce,exports.reloadClientConfig=ue,exports.resolveToUserId=E,exports.authCheck=le,exports.isOwner=H,exports.isAdmin=B,exports.isOwnerOrAdmin=z,exports.debugLog=G,exports.isMobile=k,exports.isJobNumber=U,exports.getPhoneMapFile=_,exports.loadPhoneMap=X,exports.savePhoneMap=J,exports.userIdToPhone=de,exports.getUserIdNameMapFile=L,exports.loadUserIdNameMap=K,exports.saveUserIdNameMap=Z,exports.resolveUserIdName=ge,exports.resolveUserId=Se,exports.resolveAllPhonesInConfig=he,exports.hashConversationId=V,exports.getReplyWebhook=ye,exports.getReplyConversationId=me,exports.findActiveSession=I,exports.getConversationConfig=O,exports.getConversationDir=N,exports.getSessionsDir=j,exports.getTasksDir=ee,exports.getImagesDir=ne,exports.getSessionDir=v,exports.getSessionId=p,exports.formatSessionInfo=$e,exports.readSessionLogTail=we,exports.findHistorySession=te,exports.findLatestSession=ve,exports.updateSessionFile=Q,exports.appendSessionLog=pe,exports.getActiveSessionsFile=A,exports.saveActiveSession=C,exports.loadActiveSessions=ke,exports.endSession=se,exports.switchToSession=Ce,exports.ensureAgent=F,exports.startNewSession=ie,exports.processMessageQueue=M,exports.handleSessionMessage=De,exports.cleanCache=Ie,exports.destroyConversation=be;const w=require("utils-ok"),a=P(require("fs")),oe=P(require("os")),x=P(require("assert")),q=P(require("crypto")),g=P(require("path")),re=require("./commands"),h=require("./messaging"),W=require("./agent-registry"),R=require("./platform");function $(){return w.dateUtil.mm(Date.now()).format("YYYY-MM-DD HH:mm:ss")}function T(){return oe.default.homedir()}function D(e){return g.default.join(T(),".cc-ding",e.clientId)}function Y(e,t){const n=g.default.join(T(),".cc-ding",e),s=g.default.join(n,"config.json");return a.default.mkdirSync(n,{recursive:!0}),a.default.writeFileSync(s,JSON.stringify(t,null,2),{encoding:"utf-8",mode:(0,R.isWindows)()?void 0:384}),(0,R.isWindows)()||a.default.chmodSync(s,384),s}function ae(e){const t=g.default.join(T(),".cc-ding",e),n=g.default.join(t,"config.json");if(a.default.existsSync(n))return;console.log(`[${$()}] \u5BA2\u6237\u7AEF\u76EE\u5F55\u672A\u521D\u59CB\u5316: ${t}`),console.log(`[${$()}] \u6B63\u5728\u81EA\u52A8\u521D\u59CB\u5316...`),Y(e,{clientName:"cc\u52A9\u624B",owner:"<owner\u624B\u673A\u53F7>",whiteUserList:[],clientSecret:"<clientSecret-\u9489\u9489Stream\u8FDE\u63A5\u5BC6\u94A5>",defaultDingToken:"<\u515C\u5E95\u9489\u9489\u673A\u5668\u4EBAToken>",conversations:[]}),console.log(`[${$()}] \u5DF2\u751F\u6210\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6: ${n}`),console.log(`[${$()}] \u8BF7\u7F16\u8F91 config.json \u586B\u5199\u5FC5\u8981\u7684\u914D\u7F6E\u9879\u540E\u91CD\u65B0\u542F\u52A8`),process.exit(1)}function ce(e){const t=g.default.join(D(e),"config.json");(0,x.default)(a.default.existsSync(t),`Could not find client config file: ${t}`);const n=w.fileUtil.getJSON(t);return(0,x.default)(n.clientSecret,"config.json missing required field: clientSecret"),(0,x.default)(n.whiteUserList,"config.json missing required field: whiteUserList"),n}function ue(e){const t=g.default.join(D(e),"config.json");if(!a.default.existsSync(t))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`);let n;try{n=w.fileUtil.getJSON(t)}catch(o){throw new Error(`\u914D\u7F6E\u6587\u4EF6 JSON \u89E3\u6790\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`)}const s=[];if(n.clientSecret||s.push("clientSecret"),n.whiteUserList||s.push("whiteUserList"),n.owner||s.push("owner"),n.defaultDingToken||s.push("defaultDingToken"),Array.isArray(n.conversations)||s.push("conversations"),s.length>0)throw new Error(`config.json \u7F3A\u5C11\u5FC5\u8981\u5B57\u6BB5: ${s.join(", ")}`);return{config:n,configPath:t}}function E(e,t){return k(t)&&e.resolvedPhones[t]||t}function le(e,t,n){if(z(e,t))return!0;if(n){const s=e.config.conversations.find(o=>o.conversationId===n);if(s?.freedomMode||s?.qaMode)return!0;if(s?.whiteUserList&&s.whiteUserList.length>0)return s.whiteUserList.some(o=>E(e,o)===t)}return e.config.whiteUserList.some(s=>E(e,s)===t)}function H(e,t){const n=e.config.owner;if(!n)return!1;const s=e.resolvedPhones[n];return!!s&&s===t}function B(e,t){return e.config.adminUserList?.length?e.config.adminUserList.some(n=>E(e,n)===t):!1}function z(e,t){return H(e,t)||B(e,t)}function G(e,t,...n){e.config.debug&&console.log(`[DEBUG] ${t}`,...n)}const fe=/^1\d{10}$/;function k(e){return fe.test(e)}function U(e){return!k(e)&&!e.includes("_")&&e.length<=15&&/^[A-Za-z0-9]+$/.test(e)}function _(e){return g.default.join(D(e),"user-map.json")}function X(e){const t=_(e);if(!a.default.existsSync(t))return{};try{const n=JSON.parse(a.default.readFileSync(t,"utf-8"));if(typeof n=="object"&&n!==null)return n}catch{}return{}}function J(e,t){const n=_(e);try{a.default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8")}catch(s){console.error("\u4FDD\u5B58 user-map.json \u5931\u8D25:",s)}}function de(e,t){for(const[n,s]of Object.entries(e.resolvedPhones))if(s===t)return n;return null}function L(e){return g.default.join(D(e),"user-id-name-map.json")}function K(e){const t=L(e);if(!a.default.existsSync(t))return{};try{const n=JSON.parse(a.default.readFileSync(t,"utf-8"));if(typeof n=="object"&&n!==null)return n}catch{}return{}}function Z(e,t){const n=L(e);try{a.default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8")}catch(s){console.error("\u4FDD\u5B58 user-id-name-map.json \u5931\u8D25:",s)}}async function ge(e,t){if(!t)return null;const n=K(e);if(n[t])return n[t];const s=await(0,h.queryDingUser)(e,t);return s&&s.name?(n[t]=s.name,Z(e,n),s.name):null}async function Se(e,t){if(!t)return null;if(!k(t)&&!U(t))return t;if(e.resolvedPhones[t])return e.resolvedPhones[t];let n=null;return k(t)?n=await(0,h.queryUserIdByMobile)(e,t):U(t)&&(n=await(0,h.queryUserIdByJobNumber)(e,t)),n&&(e.resolvedPhones[t]=n,J(e,e.resolvedPhones)),n}async function he(e){e.resolvedPhones=X(e);const t=[],n=async s=>{if(e.resolvedPhones[s])return;let o=null;k(s)?o=await(0,h.queryUserIdByMobile)(e,s):U(s)&&(o=await(0,h.queryUserIdByJobNumber)(e,s)),o&&(e.resolvedPhones[s]=o,t.push(s))};e.config.owner&&(k(e.config.owner)||U(e.config.owner)?(await n(e.config.owner),e.resolvedPhones[e.config.owner]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790 owner: ${e.config.owner}`)):console.warn(`[WARN] owner \u683C\u5F0F\u65E0\u6548(\u9700\u4E3A\u624B\u673A\u53F7\u6216\u5DE5\u53F7): ${e.config.owner}`));for(const s of e.config.whiteUserList)(k(s)||U(s))&&(await n(s),e.resolvedPhones[s]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790 whiteUserList: ${s}`));for(const s of e.config.conversations)if(s.whiteUserList)for(const o of s.whiteUserList)(k(o)||U(o))&&(await n(o),e.resolvedPhones[o]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790\u7FA4\u767D\u540D\u5355: ${o}`));t.length>0&&J(e,e.resolvedPhones),console.log(`[\u7528\u6237\u89E3\u6790] \u5DF2\u52A0\u8F7D ${Object.keys(e.resolvedPhones).length} \u6761\u8BB0\u5F55 (${t.length} \u6761\u65B0\u89E3\u6790)`)}function V(e,t){const s=O(e,t)?.linkConversationId||t;return q.default.createHash("md5").update(s).digest("hex")}function ye(e){return e.currentWebhook||e.sessionWebhook}function me(e){return e.currentConversationId||e.conversationId}function I(e,t){const n=e.activeSessions.get(t);if(n)return{key:t,session:n};const s=O(e,t);if(s?.linkConversationId){for(const o of e.activeSessions)if(O(e,o[0])?.linkConversationId===s.linkConversationId)return{key:o[0],session:o[1]}}}function O(e,t){return e.config.conversations.find(n=>n.conversationId===t)}function N(e,t){const n=V(e,t);return g.default.join(D(e),n)}function j(e,t){return g.default.join(N(e,t),".sessions")}function ee(e,t){return g.default.join(N(e,t),".tasks")}function ne(e,t){return g.default.join(N(e,t),".images")}function v(e,t){const n=t.claudeSessionId||t.startTimeStr;return g.default.join(j(e,t.conversationId),n)}function p(e){return e.claudeSessionId||e.startTimeStr}function $e(e,t){const n=I(e,t);if(!n)return null;const{session:s,isProcessing:o,messageQueue:c}=n.session;return[`- **\u4F1A\u8BDDID:** ${p(s)}`,`- **\u53D1\u8D77\u8005:** ${s.startNickName}(${s.startStaffId})`,`- **\u5F00\u59CB\u65F6\u95F4:** ${s.startTimeStr}`,`- **\u6700\u540E\u53D1\u9001\u8005:** ${n.session.lastSenderStaffId}`,`- **\u5904\u7406\u4E2D:** ${o}`,`- **\u6392\u961F\u6D88\u606F:** ${c?.length||0} \u6761`].join(`
|
|
2
|
+
`)}function we(e,t,n){const s=I(e,t);if(!s)return null;const o=s.session,c=`${v(e,o.session)}/session.log`;if(!a.default.existsSync(c))return null;try{return a.default.readFileSync(c,"utf-8").split(`
|
|
3
3
|
`).filter(i=>i.length>0).slice(-n).join(`
|
|
4
|
-
`)}catch{return null}}function te(e,t,n){const s=j(e,t),o=`${s}/${n}/session.json`;try{return w.fileUtil.getJSON(o)}catch{}const
|
|
5
|
-
`;try{
|
|
6
|
-
\u53EF\u4EE5\u901A\u8FC7 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002`});return}const{key:o,session:
|
|
7
|
-
`,"utf-8");const r=
|
|
4
|
+
`)}catch{return null}}function te(e,t,n){const s=j(e,t),o=`${s}/${n}/session.json`;try{return w.fileUtil.getJSON(o)}catch{}const c=parseInt(n,10);if(!isNaN(c)&&c>0){const f=w.dateUtil.mm(c).format("YYYY-MM-DD-HH-mm-ss"),d=`${s}/${f}/session.json`;try{return w.fileUtil.getJSON(d)}catch{}}return null}function ve(e,t){const n=j(e,t);if(!a.default.existsSync(n))return null;const s=I(e,t),o=s?p(s.session.session):null;let c=null,f=0;try{const d=a.default.readdirSync(n,{withFileTypes:!0});for(const i of d){if(!i.isDirectory())continue;const l=g.default.join(n,i.name,"session.json");if(a.default.existsSync(l))try{const r=w.fileUtil.getJSON(l);if(o&&p(r)===o)continue;r.startTime>f&&(f=r.startTime,c=r)}catch{continue}}}catch{}return c}function Q(e,t,n){if(n.claudeSessionId&&!t.claudeSessionId){const o=v(e,t);t.claudeSessionId=n.claudeSessionId;const c=v(e,t);o!==c&&a.default.existsSync(o)&&(a.default.renameSync(o,c),console.log(`[${$()}] \u4F1A\u8BDD\u76EE\u5F55\u91CD\u547D\u540D: ${g.default.basename(o)} -> ${g.default.basename(c)}`))}n.agentSessionId&&!t.agentSessionId&&(t.agentSessionId=n.agentSessionId);const s=`${v(e,t)}/session.json`;try{n.sessionWebhook&&(t.sessionWebhook=n.sessionWebhook),n.currentWebhook!==void 0&&(t.currentWebhook=n.currentWebhook||void 0),n.currentConversationId!==void 0&&(t.currentConversationId=n.currentConversationId||void 0),a.default.writeFileSync(s,JSON.stringify(t,null,2),"utf-8");const o=n.claudeSessionId?"claudeSessionId":n.agentSessionId?"agentSessionId":n.currentWebhook!==void 0?"currentWebhook":"sessionWebhook";console.log(`[${$()}] \u4F1A\u8BDD\u6587\u4EF6\u5DF2\u4FDD\u5B58: ${o}`),C(e,t.conversationId)}catch(o){console.error("\u66F4\u65B0 session.json \u5931\u8D25:",o)}}function pe(e,t,n){const s=`${e}/session.log`,c=`[${$()}] [${t.toUpperCase()}]: ${n}
|
|
5
|
+
`;try{a.default.appendFileSync(s,c,"utf-8")}catch{}}function A(e,t){return`${j(e,t)}/active.json`}function C(e,t){const n=e.activeSessions.get(t),s=A(e,t);try{if(!n){a.default.existsSync(s)&&a.default.unlinkSync(s);return}const o={session:n.session,lastSenderStaffId:n.lastSenderStaffId,conversationConfig:n.conversationConfig};a.default.mkdirSync(g.default.dirname(s),{recursive:!0}),a.default.writeFileSync(s,JSON.stringify(o,null,2),"utf-8"),G(e,`\u6D3B\u8DC3\u4F1A\u8BDD\u5DF2\u6301\u4E45\u5316: \u7FA4=${t}`)}catch(o){console.error(`\u6301\u4E45\u5316\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: \u7FA4=${t}`,o)}}function ke(e){for(const t of e.config.conversations){const n=A(e,t.conversationId);if(a.default.existsSync(n))try{const s=w.fileUtil.getJSON(n);if(!s?.session){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u65E0\u6548\uFF0C\u8DF3\u8FC7: ${n}`);continue}const o=v(e,s.session);if(!a.default.existsSync(o)){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728\uFF0C\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6: ${n}`),a.default.unlinkSync(n);continue}e.activeSessions.set(t.conversationId,{session:s.session,lastSenderStaffId:s.lastSenderStaffId||s.session.startStaffId,isProcessing:!1,messageQueue:[],conversationConfig:s.conversationConfig}),console.log(`\u6062\u590D\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${t.conversationId}, \u4F1A\u8BDDID=${p(s.session)}`)}catch(s){console.error(`\u52A0\u8F7D\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: ${n}`,s)}}}async function se(e,t,n){const s=I(e,t);if(!s){console.log(`\u7FA4 ${t} \u65E0\u6D3B\u8DC3\u4F1A\u8BDD`),await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u26A0\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD\uFF0C\u65E0\u9700\u7ED3\u675F\u3002
|
|
6
|
+
\u53EF\u4EE5\u901A\u8FC7 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002`});return}const{key:o,session:c}=s,{session:f}=c,d=v(e,f),i=p(f);console.log(`\u7ED3\u675F\u4F1A\u8BDD: \u7FA4=${t}, \u4F1A\u8BDDID=${i}`),c.agent?.interrupt(c,"\u7ED3\u675F\u4F1A\u8BDD\u65F6\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Agent \u8FDB\u7A0B")&&a.default.appendFileSync(`${d}/session.log`,`[${$()}] [SYSTEM]: \u7ED3\u675F\u4F1A\u8BDD\u65F6\u4E2D\u65AD Claude \u8FDB\u7A0B
|
|
7
|
+
`,"utf-8");const r=c.messageQueue?.length??0;r>0&&(c.messageQueue=[],console.log(`[${$()}] \u7ED3\u675F\u4F1A\u8BDD\u65F6\u6E05\u7A7A\u6D88\u606F\u961F\u5217: \u7FA4=${t}, \u6E05\u7A7A${r}\u6761\u6D88\u606F`)),await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u{1F4AC} \u4F1A\u8BDD\u5DF2\u7ED3\u675F
|
|
8
8
|
\u{1F194} ${i}${r>0?`
|
|
9
|
-
\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u4E22\u5F03${r}\u6761\u5F85\u5904\u7406\u6D88\u606F`:""}`}),e.activeSessions.delete(o),C(e,o),
|
|
10
|
-
`,"utf-8")}async function Ce(e,t,n,s,o,
|
|
11
|
-
`,"utf-8")),e.activeSessions.set(t,{session:f,lastSenderStaffId:o,isProcessing:!1,messageQueue:[],conversationConfig:
|
|
9
|
+
\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u4E22\u5F03${r}\u6761\u5F85\u5904\u7406\u6D88\u606F`:""}`}),e.activeSessions.delete(o),C(e,o),a.default.appendFileSync(`${d}/session.log`,`[${$()}] [SYSTEM]: \u7528\u6237\u8BF7\u6C42\u7ED3\u675F\u4F1A\u8BDD
|
|
10
|
+
`,"utf-8")}async function Ce(e,t,n,s,o,c){const f=te(e,t,s);if(!f)return await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u274C \u672A\u627E\u5230\u4F1A\u8BDD ${s}\uFF0C\u8BE5\u4F1A\u8BDD\u53EF\u80FD\u5DF2\u88AB\u6E05\u7406\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u59CB\u65B0\u4F1A\u8BDD`}),!1;const d=v(e,f);if(!a.default.existsSync(d))return await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u274C \u4F1A\u8BDD ${s} \u7684\u6570\u636E\u5DF2\u88AB\u6E05\u7406\uFF0C\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u59CB\u65B0\u4F1A\u8BDD`}),!1;const i=I(e,t);i&&(console.log(`\u5207\u6362\u4F1A\u8BDD\uFF0C\u5148\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD: ${p(i.session.session)}`),i.session.agent?.interrupt(i.session,"\u5207\u6362\u4F1A\u8BDD\u65F6\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Agent \u8FDB\u7A0B"),e.activeSessions.delete(i.key),C(e,i.key),a.default.appendFileSync(`${v(e,i.session.session)}/session.log`,`[${$()}] [SYSTEM]: \u4F1A\u8BDD\u88AB\u5207\u6362\u5230 ${s}\uFF0C\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD
|
|
11
|
+
`,"utf-8")),e.activeSessions.set(t,{session:f,lastSenderStaffId:o,isProcessing:!1,messageQueue:[],conversationConfig:c}),C(e,t);const l=!!f.claudeSessionId,r=p(f);return await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u2705 \u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD (\u{1F194} ${r})
|
|
12
12
|
${l?"\u{1F504} \u5DF2\u6062\u590D\u5BF9\u8BDD\u4E0A\u4E0B\u6587":"\u26A0\uFE0F \u8BE5\u4F1A\u8BDD\u65E0\u5386\u53F2\u4E0A\u4E0B\u6587\uFF0C\u5C06\u4ECE\u5934\u5F00\u59CB"}
|
|
13
|
-
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`}),console.log(`\u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD: \u7FA4=${t}, \u4F1A\u8BDDID=${r}, \u6709Claude\u4E0A\u4E0B\u6587=${l}`),!0}function F(e,t){t.agent||(t.agent=(0,W.createAgent)(t.conversationConfig.agent||"claude"))}async function ie(e,t){const{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:
|
|
14
|
-
\u{1F194} ${r}`});try{await S.executeQuery(e,u,{message:f,skill:d.taskCfg?.skill,senderNick:
|
|
13
|
+
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`}),console.log(`\u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD: \u7FA4=${t}, \u4F1A\u8BDDID=${r}, \u6709Claude\u4E0A\u4E0B\u6587=${l}`),!0}function F(e,t){t.agent||(t.agent=(0,W.createAgent)(t.conversationConfig.agent||"claude"))}async function ie(e,t){const{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:c,message:f,conversationConfig:d}=t,i=e.config.sessionMaxConcurrency??e.DEFAULT_SESSION_MAX_CONCURRENCY;if(e.activeSessions.size>=i){console.log(`\u8FBE\u5230\u6700\u5927\u5E76\u53D1\u6570 (${i})\uFF0C\u62D2\u7EDD\u65B0\u4F1A\u8BDD: \u7FA4=${n}`),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:"\u{1F92F} \u5F53\u524D\u7E41\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5..."});return}const l=Date.now(),r=q.default.randomUUID(),u={conversationId:n,sessionWebhook:s,startTime:l,startTimeStr:w.dateUtil.mm(l).format("YYYY-MM-DD-HH-mm-ss"),startStaffId:o,startNickName:c};console.log(`\u521B\u5EFA\u65B0\u4F1A\u8BDD: \u7FA4=${n}, \u4F1A\u8BDDID=${r}, \u53D1\u8D77\u8005=${o}, \u5F53\u524D\u5E76\u53D1=${e.activeSessions.size+1}/${i}`);const y=v(e,u);a.default.mkdirSync(y,{recursive:!0}),a.default.writeFileSync(`${y}/session.json`,JSON.stringify(u,null,2),"utf-8");const S=(0,W.createAgent)(d.agent||"claude");e.activeSessions.set(n,{session:u,lastSenderStaffId:o,isProcessing:!0,messageQueue:[],conversationConfig:d,agent:S}),C(e,n),d.receiveReply!==!1&&!d.streaming&&await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:`\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406...
|
|
14
|
+
\u{1F194} ${r}`});try{await S.executeQuery(e,u,{message:f,skill:d.taskCfg?.skill,senderNick:c,senderStaffId:o,newSessionId:r})}catch(b){console.error("\u6267\u884C Agent \u67E5\u8BE2\u5931\u8D25:",b),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${b instanceof Error?b.message:String(b)}`})}finally{const b=e.activeSessions.get(n);b&&(b.isProcessing=!1)}const m=e.activeSessions.get(n);m&&m.messageQueue.length>0&&await M(e,n)}async function M(e,t){const n=e.activeSessions.get(t);if(!n||!n.messageQueue||n.messageQueue.length===0)return;const s=n.messageQueue.shift(),{message:o,senderStaffId:c,senderNick:f,sessionWebhook:d,conversationId:i,enqueueTime:l}=s,r=600*1e3;if(Date.now()-l>r){console.log(`\u961F\u5217\u6D88\u606F\u5DF2\u8FC7\u671F\uFF0C\u8DF3\u8FC7: \u5165\u961F\u65F6\u95F4=${new Date(l).toLocaleString()}, \u7FA4=${i}`),n.messageQueue.length>0&&await M(e,t);return}if(console.log(`\u5904\u7406\u961F\u5217\u6D88\u606F: \u7FA4=${i}, \u5269\u4F59 ${n.messageQueue.length} \u6761`),n.isProcessing=!0,n.lastSenderStaffId=c,C(e,t),n.conversationConfig.receiveReply!==!1){const u=o.length>50?o.substring(0,50)+"\u2026":o;await(0,h.sendDingMessage)(e,{conversationId:i,sessionWebhook:d,atUserId:c,content:`\u{1F680} \u5F00\u59CB\u5904\u7406\u6D88\u606F\u300C${u}\u300D`}).catch(()=>{})}try{F(e,n),await n.agent.executeQuery(e,n.session,{message:o,skill:n.conversationConfig.taskCfg?.skill,senderNick:f,senderStaffId:c})}catch(u){console.error("\u6267\u884C\u961F\u5217 Agent \u67E5\u8BE2\u5931\u8D25:",u),await(0,h.sendDingMessage)(e,{conversationId:i,sessionWebhook:d,atUserId:c,content:` \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${u instanceof Error?u.message:String(u)}`})}finally{n.isProcessing=!1}if(n.goonPending){n.goonPending=!1,n.interrupted=!1,n.isProcessing=!0;try{F(e,n),await n.agent.executeQuery(e,n.session,{message:"\u7EE7\u7EED",senderNick:n.session.startNickName,senderStaffId:n.lastSenderStaffId})}catch(u){console.error("goonPending \u6062\u590D\u6267\u884C\u5931\u8D25:",u)}finally{n.isProcessing=!1}}n.messageQueue&&n.messageQueue.length>0&&await M(e,t)}async function De(e,t){const{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:c,message:f,conversationConfig:d}=t,i=f.replace(/^\[提及用户: .+\]\n/,"");if((0,re.parseEndCommand)(i)){await se(e,n,s);return}const l=I(e,n),r=l?.session;if(r){const u=v(e,r.session);if(a.default.existsSync(u)||(a.default.mkdirSync(u,{recursive:!0}),a.default.writeFileSync(`${u}/session.json`,JSON.stringify(r.session,null,2),"utf-8"),console.log(`\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u91CD\u5EFA: \u7FA4=${n}, \u8DEF\u5F84=${u}`)),r.isProcessing){const S={message:f,senderStaffId:o,senderNick:c,sessionWebhook:s,conversationId:n,enqueueTime:Date.now()};r.messageQueue||(r.messageQueue=[]),r.messageQueue.push(S);const m=r.messageQueue.length;console.log(`\u4F1A\u8BDD ${n} \u6D88\u606F\u5DF2\u5165\u961F\uFF0C\u6392\u961F\u7B2C ${m} \u6761`),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:`\u23F3 \u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u5DF2\u52A0\u5165\u961F\u5217\uFF08\u6392\u961F\u7B2C ${m} \u6761\uFF09`});return}const y=r.session.conversationId===n;console.log(`\u8FFD\u52A0\u6D88\u606F\u5230\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${n}, \u4F1A\u8BDDID=${p(r.session)}${y?"":`(\u5173\u8054\u7FA4,\u4F1A\u8BDD\u5F52\u5C5E=${r.session.conversationId})`}`),r.lastSenderStaffId=o,r.isProcessing=!0,C(e,l.key),y&&s!==r.session.sessionWebhook&&(r.session.sessionWebhook=s,Q(e,r.session,{sessionWebhook:s})),r.session.currentWebhook=s,r.session.currentConversationId=n,Q(e,r.session,{currentWebhook:s,currentConversationId:n}),d.receiveReply!==!1&&!d.streaming&&await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:"\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406..."});try{F(e,r),await r.agent.executeQuery(e,r.session,{message:f,skill:d.taskCfg?.skill,senderNick:c,senderStaffId:o})}catch(S){if(r.session.claudeSessionId){console.log(`[\u4F1A\u8BDD\u6062\u590D\u5931\u8D25] \u6E05\u9664 claudeSessionId \u5E76\u91CD\u65B0\u53D1\u8D77: ${r.session.claudeSessionId}`),r.session.claudeSessionId=void 0,e.updateSessionFile(r.session,{});try{F(e,r),await r.agent.executeQuery(e,r.session,{message:f,skill:d.taskCfg?.skill,senderNick:c,senderStaffId:o});return}catch(m){console.error("\u91CD\u8BD5\u6267\u884C Agent \u67E5\u8BE2\u5931\u8D25:",m),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${m instanceof Error?m.message:String(m)}`}),r.isProcessing=!1,await M(e,n);return}}console.error("\u6267\u884C Agent \u67E5\u8BE2\u5931\u8D25:",S),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${S instanceof Error?S.message:String(S)}`})}finally{r.isProcessing=!1}await M(e,n)}else await ie(e,{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:c,message:f,conversationConfig:d})}function Ie(e,t,n=!0){const s={sessionsDeleted:0,tasksDeleted:0,imagesDeleted:0,errors:[]},o=t?[t]:e.config.conversations.map(c=>c.conversationId);for(const c of o){let f=null;if(n){const u=I(e,c);u&&(f=p(u.session.session))}const d=j(e,c);if(a.default.existsSync(d))try{const u=a.default.readdirSync(d,{withFileTypes:!0});for(const y of u){if(!y.isDirectory()||f&&y.name===f)continue;const S=g.default.join(d,y.name);try{a.default.rmSync(S,{recursive:!0,force:!0}),s.sessionsDeleted++}catch{s.errors.push(`\u5220\u9664\u4F1A\u8BDD\u76EE\u5F55\u5931\u8D25: ${S}`)}}}catch{s.errors.push(`\u8BFB\u53D6sessions\u76EE\u5F55\u5931\u8D25: ${d}`)}const i=ee(e,c);if(a.default.existsSync(i))try{const u=a.default.readdirSync(i,{withFileTypes:!0});for(const y of u){if(!y.isDirectory())continue;const S=g.default.join(i,y.name);try{a.default.rmSync(S,{recursive:!0,force:!0}),s.tasksDeleted++}catch{s.errors.push(`\u5220\u9664\u4EFB\u52A1\u76EE\u5F55\u5931\u8D25: ${S}`)}}}catch{s.errors.push(`\u8BFB\u53D6tasks\u76EE\u5F55\u5931\u8D25: ${i}`)}const l=ne(e,c);if(a.default.existsSync(l))try{const u=a.default.readdirSync(l,{withFileTypes:!0});for(const y of u){const S=g.default.join(l,y.name);try{a.default.unlinkSync(S),s.imagesDeleted++}catch{s.errors.push(`\u5220\u9664\u56FE\u7247\u5931\u8D25: ${S}`)}}}catch{s.errors.push(`\u8BFB\u53D6images\u76EE\u5F55\u5931\u8D25: ${l}`)}const r=g.default.join(N(e,c),".playwright-cli");if(a.default.existsSync(r))try{a.default.rmSync(r,{recursive:!0,force:!0})}catch{s.errors.push(`\u5220\u9664 playwright-cli \u7F13\u5B58\u5931\u8D25: ${r}`)}if(!n){const u=A(e,c);if(a.default.existsSync(u))try{a.default.unlinkSync(u)}catch{s.errors.push(`\u5220\u9664\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u5931\u8D25: ${u}`)}e.activeSessions.has(c)&&e.activeSessions.delete(c)}}return s}async function be(e,t){const n=[],s=e.getConversationConfig(t),o=!!s?.linkConversationId,c=e.activeSessions.get(t);if(c?.currentProcess)try{c.currentProcess.kill("SIGTERM")}catch{}e.activeSessions.delete(t),n.push({label:"\u505C\u6B62\u6D3B\u8DC3\u4F1A\u8BDD",ok:!0,detail:c?"\u5DF2\u6E05\u9664":"\u65E0\u6D3B\u8DC3\u4F1A\u8BDD"});try{const i=e.cronEngine?.listJobs(t)||[];let l=0;for(const r of i)e.cronEngine?.removeJob(r.id)&&l++;n.push({label:"\u6E05\u7406\u5B9A\u65F6\u4EFB\u52A1",ok:!0,detail:`\u79FB\u9664 ${l} \u4E2A`})}catch(i){n.push({label:"\u6E05\u7406\u5B9A\u65F6\u4EFB\u52A1",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=g.default.join(D(e),"todo.json");if(a.default.existsSync(i)){const l=w.fileUtil.getJSON(i);l?.conversations?.[t]&&(delete l.conversations[t],a.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"))}n.push({label:"\u6E05\u7406 Todo \u6570\u636E",ok:!0})}catch(i){n.push({label:"\u6E05\u7406 Todo \u6570\u636E",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=g.default.join(D(e),"menu.json");if(a.default.existsSync(i)){const l=w.fileUtil.getJSON(i);if(l?.user){const r=Object.keys(l.user).filter(u=>u.startsWith(`${t}:`));for(const u of r)delete l.user[u];a.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8")}}n.push({label:"\u6E05\u7406\u5FEB\u6377\u83DC\u5355",ok:!0})}catch(i){n.push({label:"\u6E05\u7406\u5FEB\u6377\u83DC\u5355",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=e.timerEngine?.listTimers(t)||[];let l=0;for(const r of i)e.timerEngine?.removeTimer(r.id)&&l++;n.push({label:"\u6E05\u7406\u5EF6\u65F6\u4EFB\u52A1",ok:!0,detail:`\u79FB\u9664 ${l} \u4E2A`})}catch(i){n.push({label:"\u6E05\u7406\u5EF6\u65F6\u4EFB\u52A1",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=N(e,t);a.default.existsSync(i)?(a.default.rmSync(i,{recursive:!0,force:!0}),n.push({label:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55",ok:!0})):n.push({label:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55",ok:!0,detail:"\u76EE\u5F55\u4E0D\u5B58\u5728"}),o&&n.push({label:"\u5173\u8054\u76EE\u5F55",ok:!0,detail:`\u4FDD\u7559 (linkConversationId=${s.linkConversationId})`})}catch(i){n.push({label:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55",ok:!1,detail:i instanceof Error?i.message:String(i)})}const f=e.config.conversations.findIndex(i=>i.conversationId===t);f>=0?(e.config.conversations.splice(f,1),n.push({label:"\u79FB\u9664\u914D\u7F6E",ok:!0})):n.push({label:"\u79FB\u9664\u914D\u7F6E",ok:!0,detail:"\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230"});try{C(e,t),n.push({label:"\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6",ok:!0})}catch(i){n.push({label:"\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const{saveClientConfig:i}=require("./api-key-manager");i(e)}catch(i){console.error(`[${$()}] \u9500\u6BC1\u540E\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25:`,i)}return{success:n.every(i=>i.ok),steps:n}}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var f=exports&&exports.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.StreamingCard=void 0;const m=f(require("urllib")),p=f(require("crypto")),h=require("./session"),d=500,y=30,g=2e3,T="https://api.dingtalk.com";class u{constructor(t,e){this.state="processing",this.lastSentContent="",this.lastSentAt=0,this.pendingContent="",this.timer=null,this.inFlight=!1,this._permissionDenied=!1,this._missingScopes="",this.self=t.self,this.outTrackId=e,this.templateKey=t.cardTemplateKey||"content"}static async create(t){const e=`card_${Date.now()}_${p.default.randomBytes(4).toString("hex")}`,s=new u(t,e),i=await t.self.dingStreamClient.getAccessToken(),c=t.conversationType!=="1",n=c?`dtv1.card//IM_GROUP.${t.conversationId}`:`dtv1.card//IM_ROBOT.${t.senderStaffId}`,l=t.self.clientId,a={cardTemplateId:t.cardTemplateId,outTrackId:e,cardData:{cardParamMap:{config:'{"autoLayout":true,"enableForward":true}',[s.templateKey]:""}},callbackType:"STREAM",openSpaceId:n,userIdType:1,imGroupOpenSpaceModel:{supportForward:!0},imRobotOpenSpaceModel:{supportForward:!0}};c?a.imGroupOpenDeliverModel={robotCode:l}:a.imRobotOpenDeliverModel={spaceType:"IM_ROBOT",robotCode:l};try{const r=await m.default.request(`${T}/v1.0/card/instances/createAndDeliver`,{method:"POST",data:a,contentType:"json",headers:{"x-acs-dingtalk-access-token":i},dataType:"json",timeout:1e4});if(r.status!==200)return console.warn(`[${(0,h.timestamp)()}] StreamingCard \u521B\u5EFA\u5931\u8D25: status=${r.status}, body=${JSON.stringify(r.data)}`),null;const S=r.data;return s.checkPermissionError(S)?null:(s.lastSentAt=Date.now(),s)}catch(r){return console.warn(`[${(0,h.timestamp)()}] StreamingCard \u521B\u5EFA\u5F02\u5E38:`,r),null}}async update(t){this.state==="failed"||this._permissionDenied||(this.pendingContent=t,this.scheduleFlush(!1))}async finalize(t){return this._permissionDenied?!1:(this.pendingContent=t,this.timer&&(clearTimeout(this.timer),this.timer=null),await this.flush(!0))}get failed(){return this.state==="failed"}get permissionDenied(){return this._permissionDenied}get missingScopes(){return this._missingScopes}scheduleFlush(t){if(this.inFlight)return;const s=Date.now()-this.lastSentAt;if(s<d){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.flush(t).catch(()=>{})},d-s);return}const i=this.pendingContent.length-this.lastSentContent.length;if(!t&&i<y&&i>0){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.flush(t).catch(()=>{})},d);return}this.flush(t).catch(()=>{})}async flush(t){if(this.inFlight)return!1;this.inFlight=!0;const e=this.pendingContent;this.pendingContent="";let s=e;e.length>g&&(s=e.substring(0,g)+`
|
|
2
2
|
|
|
3
|
-
...`);const i=await this.getAccessToken();if(!i)return this.inFlight=!1,this.state="failed",!1;const
|
|
3
|
+
...`);const i=await this.getAccessToken();if(!i)return this.inFlight=!1,this.state="failed",!1;const c={outTrackId:this.outTrackId,key:this.templateKey,content:s,isFull:!0,isFinalize:t,isError:!1,guid:p.default.randomUUID()};try{const n=await m.default.request(`${T}/v1.0/card/streaming`,{method:"PUT",data:c,contentType:"json",headers:{"x-acs-dingtalk-access-token":i},dataType:"json",timeout:1e4});if(this.lastSentContent=e,this.lastSentAt=Date.now(),n.status!==200){const a=n.data;return this.checkPermissionError(a)?(this.state="failed",this.inFlight=!1,!1):(this.state="failed",this.inFlight=!1,!1)}const l=n.data;return this.checkPermissionError(l)?(this.state="failed",this.inFlight=!1,!1):(t&&(this.state="finished"),this.inFlight=!1,!0)}catch(n){return console.warn(`[${(0,h.timestamp)()}] StreamingCard \u66F4\u65B0\u5F02\u5E38:`,n),this.state="failed",this.inFlight=!1,!1}}checkPermissionError(t){const e=t.errorCode||t.errmsg||"";if(e.includes("AccessTokenPermissionDenied")||e.includes("AccessDenied")){this._permissionDenied=!0;const s=t.accessDeniedDetail;return s&&(this._missingScopes=JSON.stringify(s)),console.warn(`[${(0,h.timestamp)()}] StreamingCard \u6743\u9650\u4E0D\u8DB3: ${e}`),!0}return!1}async getAccessToken(){try{return await this.self.dingStreamClient.getAccessToken()}catch{return null}}}exports.StreamingCard=u;
|