cc-ding 0.2.0 → 0.3.0-beta.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/README.md +12 -12
- package/dist/bin/cc-ding.js +1 -1
- package/dist/src/biz/cc-ding-cli.js +52 -57
- package/dist/src/biz/claude-process.js +33 -30
- package/dist/src/biz/commands.js +6 -6
- package/dist/src/biz/cron.js +3 -3
- package/dist/src/biz/image.js +5 -5
- package/dist/src/biz/session.js +11 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -96,9 +96,8 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
96
96
|
|
|
97
97
|
| 命令 | 说明 |
|
|
98
98
|
|------|------|
|
|
99
|
-
| `/pwd` | 显示工作目录 |
|
|
100
99
|
| `/ls [目录] [层数]` | 查看目录结构 |
|
|
101
|
-
| `/
|
|
100
|
+
| `/bash <命令>` | 执行任意命令(覆盖 pwd/mkdir/touch/rm 等) |
|
|
102
101
|
|
|
103
102
|
#### 管理命令(仅 owner)
|
|
104
103
|
|
|
@@ -109,7 +108,7 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
109
108
|
| `/open [shell]` | 打开工作目录 |
|
|
110
109
|
| `/clean [all]` | 清除历史和缓存 |
|
|
111
110
|
| `/reset-apikeycfg` | 重置 API Key 配置 |
|
|
112
|
-
| `/cfg` |
|
|
111
|
+
| `/cfg` | 注册当前群到配置(支持 `--permissionMode` 设置权限模式) |
|
|
113
112
|
| `/auth [add\|del <用户>]` | 管理群级白名单 |
|
|
114
113
|
|
|
115
114
|
### 配置说明
|
|
@@ -131,6 +130,7 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
131
130
|
"whiteUserList": ["工号1", "工号2"],
|
|
132
131
|
"agent": "指定agent(可选)",
|
|
133
132
|
"useLocalOcr": true,
|
|
133
|
+
"permissionMode": "bypassPermissions",
|
|
134
134
|
"taskCfg": { "skill": "指定技能(可选)" }
|
|
135
135
|
}
|
|
136
136
|
],
|
|
@@ -139,8 +139,7 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
139
139
|
"sessionMaxConcurrency": 20,
|
|
140
140
|
"includeThinking": false,
|
|
141
141
|
"resultOnly": true,
|
|
142
|
-
"debug": false
|
|
143
|
-
"skipSandbox": false
|
|
142
|
+
"debug": false
|
|
144
143
|
}
|
|
145
144
|
```
|
|
146
145
|
|
|
@@ -153,7 +152,8 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
153
152
|
| `apiKeyCfg` | API Key 池化:429 自动切换、每日 0 点重置 |
|
|
154
153
|
| `useLocalOcr` | 图片本地 OCR(默认 `true`),模型支持图片时可设 `false` |
|
|
155
154
|
| `linkConversationId` | 关联群 ID,多群共享同一 Claude 会话上下文 |
|
|
156
|
-
| `
|
|
155
|
+
| `permissionMode` | Claude 进程权限模式(默认 `bypassPermissions`),可选: `default`、`acceptEdits`、`plan`、`auto`、`bypassPermissions`、`dontAsk` |
|
|
156
|
+
| `preBash` | 全局 `/bash` 前置命令 |
|
|
157
157
|
|
|
158
158
|
### 数据存储
|
|
159
159
|
|
|
@@ -262,9 +262,8 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
262
262
|
|
|
263
263
|
| Command | Description |
|
|
264
264
|
|---------|-------------|
|
|
265
|
-
| `/pwd` | Show working directory |
|
|
266
265
|
| `/ls [dir] [depth]` | View directory structure |
|
|
267
|
-
| `/
|
|
266
|
+
| `/bash <cmd>` | Execute arbitrary commands (covers pwd/mkdir/touch/rm etc.) |
|
|
268
267
|
|
|
269
268
|
#### Admin (owner only)
|
|
270
269
|
|
|
@@ -275,7 +274,7 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
275
274
|
| `/open [shell]` | Open working directory |
|
|
276
275
|
| `/clean [all]` | Clear history and cache |
|
|
277
276
|
| `/reset-apikeycfg` | Reset API Key configuration |
|
|
278
|
-
| `/cfg` | Register current group to config |
|
|
277
|
+
| `/cfg` | Register current group to config (supports `--permissionMode` to set permission mode) |
|
|
279
278
|
| `/auth [add\|del <user>]` | Manage group whitelist |
|
|
280
279
|
|
|
281
280
|
### Configuration
|
|
@@ -297,6 +296,7 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
297
296
|
"whiteUserList": ["emp_id_1", "emp_id_2"],
|
|
298
297
|
"agent": "specified_agent (optional)",
|
|
299
298
|
"useLocalOcr": true,
|
|
299
|
+
"permissionMode": "bypassPermissions",
|
|
300
300
|
"taskCfg": { "skill": "specified_skill (optional)" }
|
|
301
301
|
}
|
|
302
302
|
],
|
|
@@ -305,8 +305,7 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
305
305
|
"sessionMaxConcurrency": 20,
|
|
306
306
|
"includeThinking": false,
|
|
307
307
|
"resultOnly": true,
|
|
308
|
-
"debug": false
|
|
309
|
-
"skipSandbox": false
|
|
308
|
+
"debug": false
|
|
310
309
|
}
|
|
311
310
|
```
|
|
312
311
|
|
|
@@ -319,7 +318,8 @@ pm2 start --name "cc-ding-{clientId}" npx -- -p cc-ding cc-ding run -ci {clientI
|
|
|
319
318
|
| `apiKeyCfg` | API Key pooling: auto-switch on 429, daily reset at midnight |
|
|
320
319
|
| `useLocalOcr` | Local image OCR (default `true`); set `false` if model supports images natively |
|
|
321
320
|
| `linkConversationId` | Link groups to share one Claude session context |
|
|
322
|
-
| `
|
|
321
|
+
| `permissionMode` | Claude process permission mode (default `bypassPermissions`), options: `default`, `acceptEdits`, `plan`, `auto`, `bypassPermissions`, `dontAsk` |
|
|
322
|
+
| `preBash` | Global pre-bash command for `/bash` |
|
|
323
323
|
|
|
324
324
|
### Data Storage
|
|
325
325
|
|
package/dist/bin/cc-ding.js
CHANGED
|
@@ -8,7 +8,7 @@ Examples:
|
|
|
8
8
|
`).version((0,common_1.projUtil)().getPkgVersion()),program.command("init").description("\u521D\u59CB\u5316cc-ding\u914D\u7F6E\u6587\u4EF6, \u751F\u6210\u6700\u7B80config.json").requiredOption("-ci, --clientId <value>","clientId").requiredOption("-cs, --clientSecret <value>","clientSecret (\u9489\u9489Stream\u8FDE\u63A5\u5BC6\u94A5)").requiredOption("-m, --mobile <value>","mobile (\u81EA\u5DF1\u7684\u624B\u673A\u53F7, \u81EA\u52A8\u52A0\u5165\u767D\u540D\u5355)").option("-cn, --clientName <value>","clientName (\u673A\u5668\u4EBA\u540D\u79F0, \u53EF\u9009)").action(async e=>{const n=process.version.slice(1);parseInt(n.split(".")[0],10)<24&&(console.log(`
|
|
9
9
|
\u274C Node \u7248\u672C\u8FC7\u4F4E\uFF0C\u65E0\u6CD5\u6267\u884C init \u547D\u4EE4`),console.log(` \u5F53\u524D\u7248\u672C\uFF1A${n}`),console.log(" \u8981\u6C42\uFF1ANode >= 24"),console.log(`
|
|
10
10
|
\u{1F4A1} \u8BF7\u5347\u7EA7 Node \u7248\u672C\u540E\u91CD\u65B0\u8FD0\u884C
|
|
11
|
-
`),process.exit(1));const i=`${`${(0,session_1.getHomeDir)()}/.cc-ding/${e.clientId}`}/config.json`;fs_1.default.existsSync(i)&&(console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728: ${i}`),console.log("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316, \u8BF7\u5148\u5220\u9664\u5DF2\u6709\u914D\u7F6E\u6587\u4EF6"),process.exit(1));const t={clientName:e.clientName||"cc\u52A9\u624B",owner:e.mobile,whiteUserList:[e.mobile],clientSecret:e.clientSecret,defaultDingToken:"<\u515C\u5E95\u9489\u9489\u673A\u5668\u4EBAToken-\u7528\u4E8E\u65E0dingToken\u7FA4\u7684\u6D88\u606F\u63A5\u6536>",conversations:[],includeThinking:!1,resultOnly:!0,debug:!1,taskQueueSize:10,taskHandlerCount:1,sessionMaxConcurrency:20
|
|
11
|
+
`),process.exit(1));const i=`${`${(0,session_1.getHomeDir)()}/.cc-ding/${e.clientId}`}/config.json`;fs_1.default.existsSync(i)&&(console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728: ${i}`),console.log("\u5982\u9700\u91CD\u65B0\u521D\u59CB\u5316, \u8BF7\u5148\u5220\u9664\u5DF2\u6709\u914D\u7F6E\u6587\u4EF6"),process.exit(1));const t={clientName:e.clientName||"cc\u52A9\u624B",owner:e.mobile,whiteUserList:[e.mobile],clientSecret:e.clientSecret,defaultDingToken:"<\u515C\u5E95\u9489\u9489\u673A\u5668\u4EBAToken-\u7528\u4E8E\u65E0dingToken\u7FA4\u7684\u6D88\u606F\u63A5\u6536>",conversations:[],includeThinking:!1,resultOnly:!0,debug:!1,taskQueueSize:10,taskHandlerCount:1,sessionMaxConcurrency:20};(0,session_1.initClientDir)(e.clientId,t),console.log("\u914D\u7F6E\u6587\u4EF6\u5DF2\u751F\u6210:",i),console.log(""),console.log("\u540E\u7EED\u6B65\u9AA4:"),console.log(" 1. \u7F16\u8F91 config.json \u6DFB\u52A0 conversations \u914D\u7F6E(\u7FA4\u804A\u9700\u914D\u7F6EdingToken)"),console.log(" 2. \u542F\u52A8\u673A\u5668\u4EBA: cc-ding run -ci",e.clientId),console.log(" 3. \u63A8\u8350PM2\u542F\u52A8:"),console.log(` pm2 start --name "cc-ding-${e.clientId}" npx -- -p cc-ding cc-ding run -ci ${e.clientId}`)}),program.command("run").description(`
|
|
12
12
|
- \u529F\u80FD: \u9489\u9489\u673A\u5668\u4EBA\u5BF9\u63A5\u672C\u5730Claude, \u652F\u6301\u4F1A\u8BDD\u6A21\u5F0F\u548C\u4EFB\u52A1\u961F\u5217\u6A21\u5F0F
|
|
13
13
|
- \u4F1A\u8BDD\u6570\u636E\u8DEF\u5F84: ~/.cc-ding/{clientId}/{MD5}/.sessions/{claudeSessionId}/session.{json|log}
|
|
14
14
|
- \u4EFB\u52A1\u6570\u636E\u8DEF\u5F84: ~/.cc-ding/{clientId}/{MD5}/.tasks/{\u65F6\u95F4\u6233}/task.{json|log}
|
|
@@ -1,52 +1,45 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(T,
|
|
2
|
-
`),msgType:"markdown"});return}for(const
|
|
3
|
-
`);await(0,messaging_1.sendOwnerMessage)(this,
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(T,a,t,i){i===void 0&&(i=t);var o=Object.getOwnPropertyDescriptor(a,t);(!o||("get"in o?!a.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return a[t]}}),Object.defineProperty(T,i,o)}):(function(T,a,t,i){i===void 0&&(i=t),T[i]=a[t]})),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(T,a){Object.defineProperty(T,"default",{enumerable:!0,value:a})}):function(T,a){T.default=a}),__importStar=this&&this.__importStar||(function(){var T=function(a){return T=Object.getOwnPropertyNames||function(t){var i=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(i[i.length]=o);return i},T(a)};return function(a){if(a&&a.__esModule)return a;var t={};if(a!=null)for(var i=T(a),o=0;o<i.length;o++)i[o]!=="default"&&__createBinding(t,a,i[o]);return __setModuleDefault(t,a),t}})(),__importDefault=this&&this.__importDefault||function(T){return T&&T.__esModule?T:{default:T}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.DingClaude=void 0;const child_process_1=require("child_process"),utils_ok_1=require("utils-ok"),fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),common_1=require("../common"),quote_1=require("./quote"),messaging_1=require("./messaging"),image_1=require("./image"),commands_1=require("./commands"),messaging_2=require("./messaging"),claude_process_1=require("./claude-process"),recorder_1=require("./recorder"),session_1=require("./session"),task_1=require("./task"),api_key_manager_1=require("./api-key-manager"),cron_1=require("./cron"),TOOL_VERSION=(0,common_1.projUtil)().getPkgVersion();class DingClaude{constructor(a){this.resolvedPhones={},this.activeSessions=new Map,this.pendingAuthRequests=new Map,this.recorderModeConversations=new Set,this.DEFAULT_SESSION_MAX_CONCURRENCY=5,this.DEFAULT_TASK_HANDLER_COUNT=1,this.DEFAULT_TASK_QUEUE_SIZE=50,this.sendDingMessage=t=>(0,messaging_2.sendDingMessage)(this,t),this.sendClaudeResponseToDing=(t,i,o,s)=>(0,messaging_2.sendClaudeResponseToDing)(this,t,i,o,s),this.parseClaudeStreamLine=claude_process_1.parseClaudeStreamLine,this.interruptClaudeProcess=(t,i)=>(0,claude_process_1.interruptClaudeProcess)(t,i),this.executeClaudeQuery=(t,i,o)=>(0,claude_process_1.executeClaudeQuery)(this,t,i,o),this.getClientDir=()=>(0,session_1.getClientDir)(this),this.getClientConfig=()=>(0,session_1.getClientConfig)(this),this.authCheck=(t,i)=>(0,session_1.authCheck)(this,t,i),this.isOwner=t=>(0,session_1.isOwner)(this,t),this.debugLog=(t,...i)=>(0,session_1.debugLog)(this,t,...i),this.hashConversationId=t=>(0,session_1.hashConversationId)(this,t),this.getConversationConfig=t=>(0,session_1.getConversationConfig)(this,t),this.getConversationDir=t=>(0,session_1.getConversationDir)(this,t),this.getSessionsDir=t=>(0,session_1.getSessionsDir)(this,t),this.getTasksDir=t=>(0,session_1.getTasksDir)(this,t),this.getSessionDir=t=>(0,session_1.getSessionDir)(this,t),this.getSessionId=session_1.getSessionId,this.formatSessionInfo=t=>(0,session_1.formatSessionInfo)(this,t),this.readSessionLogTail=(t,i)=>(0,session_1.readSessionLogTail)(this,t,i),this.findActiveSession=t=>(0,session_1.findActiveSession)(this,t),this.findHistorySession=(t,i)=>(0,session_1.findHistorySession)(this,t,i),this.findLatestSession=t=>(0,session_1.findLatestSession)(this,t),this.updateSessionFile=(t,i)=>(0,session_1.updateSessionFile)(this,t,i),this.appendSessionLog=session_1.appendSessionLog,this.getActiveSessionsFile=t=>(0,session_1.getActiveSessionsFile)(this,t),this.saveActiveSession=t=>(0,session_1.saveActiveSession)(this,t),this.loadActiveSessions=()=>(0,session_1.loadActiveSessions)(this),this.endSession=(t,i)=>(0,session_1.endSession)(this,t,i),this.switchToSession=(t,i,o,s,u)=>(0,session_1.switchToSession)(this,t,i,o,s,u),this.startNewSession=t=>(0,session_1.startNewSession)(this,t),this.handleSessionMessage=t=>(0,session_1.handleSessionMessage)(this,t),this.cleanCache=(t,i=!0)=>(0,session_1.cleanCache)(this,t,i),this.formatTaskInfo=()=>(0,task_1.formatTaskInfo)(this),this.cancelTask=(t,i)=>(0,task_1.cancelTask)(this,t,i),this.countTodoTask=()=>(0,task_1.countTodoTask)(this),this.getOneTodoTask=()=>(0,task_1.getOneTodoTask)(this),this.finishTask=t=>(0,task_1.finishTask)(this,t),this.handleTask=()=>(0,task_1.handleTask)(this),this.runTaskHandlerLoop=()=>(0,task_1.runTaskHandlerLoop)(this),this.saveTask=t=>(0,task_1.saveTask)(this,t),this.clientId=a,this.config=(0,session_1.getClientConfig)(this);try{this.dingStreamClient=new utils_ok_1.DingStreamClient({clientId:a,clientSecret:this.config.clientSecret,keepAlive:!0,debug:this.config.debug??!1})}catch(t){console.error("Error: DingStreamClient init failed.",t),process.exit(1)}this.cronEngine=new cron_1.CronEngine(this)}async requireOwner(a,t,i){return this.isOwner(i)?!0:(await this.sendDingMessage({conversationId:a,sessionWebhook:t,content:"\u274C \u53EA\u6709\u673A\u5668\u4EBA owner \u624D\u80FD\u6267\u884C\u6B64\u64CD\u4F5C",msgType:"markdown"}),!1)}async requireOwnerOrSingleChat(a,t,i,o){return this.isOwner(i)||o?.conversationType==="1"?!0:(await this.sendDingMessage({conversationId:a,sessionWebhook:t,content:"\u274C \u53EA\u6709\u673A\u5668\u4EBA owner \u624D\u80FD\u6267\u884C\u6B64\u64CD\u4F5C",msgType:"markdown"}),!1)}async handleAuthRequest(a){const{senderStaffId:t,senderNick:i,conversationId:o,conversationType:s,conversationTitle:u,sessionWebhook:r}=a;if(!this.config.ownerConversationId){await this.sendDingMessage({conversationId:o,sessionWebhook:r,content:["\u62B1\u6B49,\u60A8\u6682\u65E0\u4F7F\u7528\u6743\u9650","\u8BF7\u5C06\u4EE5\u4E0B\u4FE1\u606F\u53D1\u9001\u7ED9\u673A\u5668\u4EBA\u7BA1\u7406\u5458,\u7531\u7BA1\u7406\u5458\u901A\u8FC7\u547D\u4EE4\u6CE8\u518C:",`- **\u4F1A\u8BDDID:** \`${o}\``,`- **\u6CE8\u518C\u547D\u4EE4:** \`/cfg --conversationId ${o}\``].join(`
|
|
2
|
+
`),msgType:"markdown"});return}for(const I of this.pendingAuthRequests.values())if(I.senderStaffId===t&&I.conversationId===o){await this.sendDingMessage({conversationId:o,sessionWebhook:r,content:"\u23F3 \u6388\u6743\u7533\u8BF7\u5DF2\u53D1\u9001\uFF0C\u8BF7\u7B49\u5F85\u7BA1\u7406\u5458\u5BA1\u6279...",msgType:"markdown"});return}const g=`r${Date.now().toString(36)}`,h={id:g,senderStaffId:t,senderNick:i,conversationId:o,conversationType:s,conversationTitle:u,requestTime:Date.now()};this.pendingAuthRequests.set(g,h),console.log(`[${(0,session_1.timestamp)()}] \u65B0\u6388\u6743\u7533\u8BF7: id=${g}, userId=${t}, \u6635\u79F0=${i}, \u4F1A\u8BDD=${o}`);const y=["\u{1F4CB} **\u6536\u5230\u6388\u6743\u7533\u8BF7**",`- **\u7528\u6237ID:** ${t}`,`- **\u6635\u79F0:** ${i}`,`- **\u4F1A\u8BDDID:** ${o}`,u?`- **\u4F1A\u8BDD\u6807\u9898:** ${u}`:"",`- **\u4F1A\u8BDD\u7C7B\u578B:** ${s==="1"?"\u5355\u804A":s==="2"?"\u7FA4\u804A":s||"-"}`,"",`\u56DE\u590D \`/auth approve ${g}\` \u901A\u8FC7`,`\u56DE\u590D \`/auth reject ${g}\` \u62D2\u7EDD`].filter(Boolean).join(`
|
|
3
|
+
`);await(0,messaging_1.sendOwnerMessage)(this,y,"markdown")?await this.sendDingMessage({conversationId:o,sessionWebhook:r,content:"\u2705 \u5DF2\u5411\u7BA1\u7406\u5458\u53D1\u9001\u6388\u6743\u7533\u8BF7\uFF0C\u8BF7\u7B49\u5F85\u5BA1\u6279...",msgType:"markdown"}):(this.pendingAuthRequests.delete(g),await this.sendDingMessage({conversationId:o,sessionWebhook:r,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(a,t){const{conversationId:i,sessionWebhook:o,senderStaffId:s,senderNick:u,conversationConfig:r}=t;switch(a.type){case"list":{const g=await this.getOrCreateLogSession(i,o,s,u,r,!0),h=this.cronEngine.listJobs(i);g.sessionDir&&(this.appendSessionLog(g.sessionDir,"user","/cron list"),this.appendSessionLog(g.sessionDir,"assistant",`\u5217\u51FA ${h.length} \u4E2A\u5B9A\u65F6\u4EFB\u52A1`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:(0,cron_1.formatCronJobList)(h),msgType:"markdown"});return}case"delete":{const g=this.cronEngine.removeJob(a.id),h=await this.getOrCreateLogSession(i,o,s,u,r);h.sessionDir&&(this.appendSessionLog(h.sessionDir,"user",`/cron delete ${a.id}`),this.appendSessionLog(h.sessionDir,"assistant",g?`\u5220\u9664\u5B9A\u65F6\u4EFB\u52A1 ${a.id}`:`\u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${a.id}`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:g?`\u2705 \u5B9A\u65F6\u4EFB\u52A1 **${a.id}** \u5DF2\u5220\u9664`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${a.id}`,msgType:"markdown"});return}case"pause":{const g=this.cronEngine.toggleJob(a.id,!1),h=await this.getOrCreateLogSession(i,o,s,u,r);h.sessionDir&&(this.appendSessionLog(h.sessionDir,"user",`/cron pause ${a.id}`),this.appendSessionLog(h.sessionDir,"assistant",g?`\u6682\u505C\u5B9A\u65F6\u4EFB\u52A1 ${a.id}`:`\u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${a.id}`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:g?`\u23F8\uFE0F \u5B9A\u65F6\u4EFB\u52A1 **${a.id}** \u5DF2\u6682\u505C`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${a.id}`,msgType:"markdown"});return}case"resume":{const g=this.cronEngine.toggleJob(a.id,!0),h=await this.getOrCreateLogSession(i,o,s,u,r);h.sessionDir&&(this.appendSessionLog(h.sessionDir,"user",`/cron resume ${a.id}`),this.appendSessionLog(h.sessionDir,"assistant",g?`\u6062\u590D\u5B9A\u65F6\u4EFB\u52A1 ${a.id}`:`\u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${a.id}`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:g?`\u25B6\uFE0F \u5B9A\u65F6\u4EFB\u52A1 **${a.id}** \u5DF2\u6062\u590D`:`\u274C \u672A\u627E\u5230\u5B9A\u65F6\u4EFB\u52A1: ${a.id}`,msgType:"markdown"});return}case"create_cron":{if(!(0,cron_1.isValidCronExpression)(a.cronExpression)){await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:`\u274C \u65E0\u6548\u7684cron\u8868\u8FBE\u5F0F: \`${a.cronExpression}\`
|
|
4
4
|
|
|
5
|
-
\u{1F4A1} \u683C\u5F0F: \`\u5206 \u65F6 \u65E5 \u6708 \u5468\`\uFF0C\u5982 \`0 9 * * *\``,msgType:"markdown"});return}if(!this.hasNotifyCapability(
|
|
5
|
+
\u{1F4A1} \u683C\u5F0F: \`\u5206 \u65F6 \u65E5 \u6708 \u5468\`\uFF0C\u5982 \`0 9 * * *\``,msgType:"markdown"});return}if(!this.hasNotifyCapability(t.conversationConfig)){await this.sendCronNoNotifyError(i,o);return}const g=this.cronEngine.addJob({conversationId:i,cronExpression:a.cronExpression,description:this.sanitizeLogContent(a.prompt.substring(0,50)),prompt:a.prompt,senderStaffId:s,senderNick:u}),h=await this.getOrCreateLogSession(i,o,s,u,r);h.sessionDir&&(this.appendSessionLog(h.sessionDir,"user",`/cron ${a.cronExpression} ${this.sanitizeLogContent(a.prompt)}`),this.appendSessionLog(h.sessionDir,"assistant",`\u521B\u5EFA\u5B9A\u65F6\u4EFB\u52A1: ${g.id} [${g.cronExpression}] ${g.description}`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:(0,cron_1.formatCronJobInfo)(g),msgType:"markdown"});return}case"create_nl":{if(!this.hasNotifyCapability(t.conversationConfig)){await this.sendCronNoNotifyError(i,o);return}await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:"\u23F3 \u6B63\u5728\u5206\u6790\u5B9A\u65F6\u4EFB\u52A1\u63CF\u8FF0..."});const g=await this.cronEngine.analyzeAndCreate(i,a.input,s,u),h=await this.getOrCreateLogSession(i,o,s,u,r);g.job?(h.sessionDir&&(this.appendSessionLog(h.sessionDir,"user",`/cron ${this.sanitizeLogContent(a.input)}`),this.appendSessionLog(h.sessionDir,"assistant",`\u521B\u5EFA\u5B9A\u65F6\u4EFB\u52A1: ${g.job.id} [${g.job.cronExpression}] ${g.job.description}`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:(0,cron_1.formatCronJobInfo)(g.job),msgType:"markdown"})):(h.sessionDir&&(this.appendSessionLog(h.sessionDir,"user",`/cron ${this.sanitizeLogContent(a.input)}`),this.appendSessionLog(h.sessionDir,"assistant",`\u5B9A\u65F6\u4EFB\u52A1\u5206\u6790\u5931\u8D25: ${g.error}`)),await this.sendDingMessage({conversationId:i,sessionWebhook:o,content:`\u274C \u5B9A\u65F6\u4EFB\u52A1\u5206\u6790\u5931\u8D25: ${g.error}
|
|
6
6
|
|
|
7
|
-
\u{1F4A1} \u4F60\u4E5F\u53EF\u4EE5\u76F4\u63A5\u6307\u5B9Acron\u8868\u8FBE\u5F0F: \`/cron 0 9 * * * \u4EFB\u52A1\u63CF\u8FF0\``,msgType:"markdown"}));return}}}sanitizeLogContent(
|
|
8
|
-
`),
|
|
9
|
-
...(\u8F93\u51FA\u5DF2\u622A\u65AD)`:
|
|
10
|
-
`,"utf-8"),{sessionDir:
|
|
11
|
-
\u539F\u56E0: ${c instanceof Error?c.message:String(c)}`,msgType:"markdown"})}}async handleRmCommand(o,s,n){const{absolutePath:r,error:e}=this.resolveAndValidatePath(o,n);if(e){await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:e,msgType:"markdown"});return}let c;try{c=fs_1.default.statSync(r)}catch{await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u274C \u8DEF\u5F84\u4E0D\u5B58\u5728: \`${n}\``,msgType:"markdown"});return}const a=c.isDirectory();try{a?fs_1.default.rmSync(r,{recursive:!0,force:!0}):fs_1.default.unlinkSync(r),await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u2705 \u5DF2\u5220\u9664${a?"\u76EE\u5F55":"\u6587\u4EF6"}: \`${n}\``,msgType:"markdown"})}catch(g){await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u274C \u5220\u9664\u5931\u8D25: \`${n}\`
|
|
12
|
-
\u539F\u56E0: ${g instanceof Error?g.message:String(g)}`,msgType:"markdown"})}}async handleTouchCommand(o,s,n){const{absolutePath:r,error:e}=this.resolveAndValidatePath(o,n);if(e){await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:e,msgType:"markdown"});return}try{const c=fs_1.default.statSync(r);c.isFile()?await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u26A0\uFE0F \u6587\u4EF6\u5DF2\u5B58\u5728: \`${n}\`
|
|
13
|
-
\u6700\u540E\u4FEE\u6539\u65F6\u95F4: ${utils_ok_1.dateUtil.mm(c.mtime).format("YYYY-MM-DD HH:mm:ss")}`,msgType:"markdown"}):await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u274C \u8DEF\u5F84\u5DF2\u5B58\u5728\u4F46\u4E0D\u662F\u6587\u4EF6: \`${n}\``,msgType:"markdown"});return}catch{}try{const c=path_1.default.dirname(r);fs_1.default.mkdirSync(c,{recursive:!0}),fs_1.default.writeFileSync(r,"","utf-8"),await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u2705 \u6587\u4EF6\u521B\u5EFA\u6210\u529F: \`${n}\``,msgType:"markdown"})}catch(c){await this.sendDingMessage({conversationId:o,sessionWebhook:s,content:`\u274C \u6587\u4EF6\u521B\u5EFA\u5931\u8D25: \`${n}\`
|
|
14
|
-
\u539F\u56E0: ${c instanceof Error?c.message:String(c)}`,msgType:"markdown"})}}async botMsgGetCallback(o){this.dingStreamClient.socketCallBackResponse(o.headers.messageId,"");const s=JSON.parse(o.data),{senderNick:n,senderStaffId:r,conversationId:e,conversationTitle:c,sessionWebhook:a,msgtype:g,conversationType:u}=s,v=s.text?.content?.trim()??"";if(this.debugLog(`\u6536\u5230\u6D88\u606F: \u7FA4=${c}(${e}), \u53D1\u9001\u8005=${n}(${r}), \u7C7B\u578B=${g}, \u5185\u5BB9=${v.substring(0,50)}`),!this.authCheck(r,e)){await this.handleAuthRequest({senderStaffId:r,senderNick:n,conversationId:e,conversationType:u,conversationTitle:s.conversationTitle,sessionWebhook:a});return}const w=this.getConversationConfig(e),k=(0,commands_1.parseRecorderCommand)(v);if(k!==null){if(!this.isOwner(r)||u!=="1"){await this.sendDingMessage({conversationId:e,sessionWebhook:a,content:"\u274C Recorder \u6A21\u5F0F\u4EC5\u9650 owner \u5355\u804A\u4F7F\u7528",msgType:"markdown"});return}if(k==="on"){this.recorderModeConversations.add(e);const t=(0,recorder_1.getRecorderDir)(this,e);console.log(`[${(0,session_1.timestamp)()}] [recorder] \u5F00\u542F recorder \u6A21\u5F0F: conversationId=${e}, dir=${t}`),await this.sendDingMessage({conversationId:e,sessionWebhook:a,content:`\u{1F534} Recorder \u6A21\u5F0F\u5DF2\u5F00\u542F
|
|
7
|
+
\u{1F4A1} \u4F60\u4E5F\u53EF\u4EE5\u76F4\u63A5\u6307\u5B9Acron\u8868\u8FBE\u5F0F: \`/cron 0 9 * * * \u4EFB\u52A1\u63CF\u8FF0\``,msgType:"markdown"}));return}}}sanitizeLogContent(a){return a.replace(/\n/g,"\\n").replace(/\r/g,"\\r")}sanitizeOutput(a){const t=a.replace(/\r\n/g,`
|
|
8
|
+
`),i=8e3;return t.length>i?t.substring(0,i)+`
|
|
9
|
+
...(\u8F93\u51FA\u5DF2\u622A\u65AD)`:t}truncateMsg(a,t=100){const i=a.replace(/\n/g," ").trim();return i.length>t?i.slice(0,t)+"...":i}async getOrCreateLogSession(a,t,i,o,s,u=!1){const r=this.findActiveSession(a);if(r)return{sessionDir:this.getSessionDir(r.session.session),isNew:!1};if(u)return{sessionDir:null,isNew:!1};const g=Date.now(),h={conversationId:a,sessionWebhook:t,startTime:g,startTimeStr:utils_ok_1.dateUtil.mm(g).format("YYYY-MM-DD-HH-mm-ss"),startStaffId:i,startNickName:`[cron]${o}`},y=this.getSessionDir(h);return fs_1.default.mkdirSync(y,{recursive:!0}),fs_1.default.writeFileSync(`${y}/session.json`,JSON.stringify(h,null,2),"utf-8"),fs_1.default.appendFileSync(`${y}/session.log`,`[${(0,session_1.timestamp)()}] [SYSTEM]: \u521B\u5EFA\u4F1A\u8BDD\u7528\u4E8E\u8BB0\u5F55 /cron \u547D\u4EE4\u64CD\u4F5C
|
|
10
|
+
`,"utf-8"),{sessionDir:y,isNew:!0}}hasNotifyCapability(a){return!!(a.dingToken||this.config.defaultDingToken)}async sendCronNoNotifyError(a,t){await this.sendDingMessage({conversationId:a,sessionWebhook:t,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(a){this.dingStreamClient.socketCallBackResponse(a.headers.messageId,"");const t=JSON.parse(a.data),{senderNick:i,senderStaffId:o,conversationId:s,conversationTitle:u,sessionWebhook:r,msgtype:g,conversationType:h}=t,y=t.text?.content?.trim()??"";if(this.debugLog(`\u6536\u5230\u6D88\u606F: \u7FA4=${u}(${s}), \u53D1\u9001\u8005=${i}(${o}), \u7C7B\u578B=${g}, \u5185\u5BB9=${y.substring(0,50)}`),!this.authCheck(o,s)){await this.handleAuthRequest({senderStaffId:o,senderNick:i,conversationId:s,conversationType:h,conversationTitle:t.conversationTitle,sessionWebhook:r});return}const w=this.getConversationConfig(s),I=(0,commands_1.parseRecorderCommand)(y);if(I!==null){if(!this.isOwner(o)||h!=="1"){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u274C Recorder \u6A21\u5F0F\u4EC5\u9650 owner \u5355\u804A\u4F7F\u7528",msgType:"markdown"});return}if(I==="on"){this.recorderModeConversations.add(s);const e=(0,recorder_1.getRecorderDir)(this,s);console.log(`[${(0,session_1.timestamp)()}] [recorder] \u5F00\u542F recorder \u6A21\u5F0F: conversationId=${s}, dir=${e}`),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F534} Recorder \u6A21\u5F0F\u5DF2\u5F00\u542F
|
|
15
11
|
- \u6240\u6709\u6D88\u606F\u5C06\u88AB\u5206\u7C7B\u8BB0\u5F55\u5230\u672C\u5730
|
|
16
|
-
- \u4FDD\u5B58\u76EE\u5F55: \`${
|
|
17
|
-
- \u53D1\u9001 \`/recorder exit\` \u5173\u95ED`,msgType:"markdown"})}else this.recorderModeConversations.delete(
|
|
18
|
-
\u{1F4A1} \u53EF\u7F16\u8F91 config.json \u8865\u5145\u66F4\u591A\u914D\u7F6E`),await this.sendDingMessage({conversationId:
|
|
19
|
-
`),msgType:"markdown"});return}if((0,commands_1.parseHelpCommand)(l)){await this.sendDingMessage({conversationId:
|
|
12
|
+
- \u4FDD\u5B58\u76EE\u5F55: \`${e}\`
|
|
13
|
+
- \u53D1\u9001 \`/recorder exit\` \u5173\u95ED`,msgType:"markdown"})}else this.recorderModeConversations.delete(s),console.log(`[${(0,session_1.timestamp)()}] [recorder] \u5173\u95ED recorder \u6A21\u5F0F: conversationId=${s}`),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u2B1C Recorder \u6A21\u5F0F\u5DF2\u5173\u95ED\uFF0C\u6062\u590D\u6B63\u5E38\u5904\u7406",msgType:"markdown"});return}if(this.recorderModeConversations.has(s)){try{await(0,recorder_1.recordMessage)(this,t,s),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 \u5DF2\u8BB0\u5F55 ${g}`})}catch(e){console.error(`[${(0,session_1.timestamp)()}] [recorder] \u8BB0\u5F55\u6D88\u606F\u5931\u8D25:`,e),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u274C \u8BB0\u5F55\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`})}return}let l;if(g==="picture"&&t.pictureDownloadCode){const e=this.getConversationDir(s),n=w?.useLocalOcr!==!1,d=await(0,image_1.processPictureMessage)(this,t.pictureDownloadCode,t.robotCode,e,n,y||void 0);if(!d){await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,content:"\u26A0\uFE0F \u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u6216\u4F7F\u7528\u6587\u5B57\u63CF\u8FF0"});return}l=d}else if(g==="richText"&&t.content?.richText){const e=this.getConversationDir(s),n=w?.useLocalOcr!==!1;l=await(0,image_1.processRichTextMessage)(this,t.content.richText,t.robotCode,e,n)}else if(g==="file"){const e=(0,image_1.extractDownloadCode)(t);if(e){const n=this.getConversationDir(s),d=await(0,image_1.processFileMessage)(this,e,t.robotCode,n,y||void 0);if(!d){await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,content:"\u26A0\uFE0F \u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5"});return}l=d}else{await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,content:"\u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u4E0B\u8F7D\u94FE\u63A5\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001"});return}}else{if(l=y,!l){const e=(0,quote_1.extractQuoteInfo)(t);if(e){if(this.debugLog(`\u68C0\u6D4B\u5230\u5F15\u7528\u6D88\u606F(\u65E0\u6B63\u6587): quoteMessageId=${e.quoteMessageId}`),e.quoteMessageId&&!e.quoteText){const n=await(0,messaging_1.fetchQuotedMessage)(this,e.quoteMessageId);n&&(e.quoteText=n)}e.quoteText&&(l=(0,quote_1.formatPromptWithQuote)("",e))}}if(!l)return}if(!l.startsWith("/")&&g==="text"&&y){const e=(0,quote_1.extractQuoteInfo)(t);if(e){if(this.debugLog(`\u68C0\u6D4B\u5230\u5F15\u7528\u6D88\u606F: quoteMessageId=${e.quoteMessageId}`),e.quoteMessageId&&!e.quoteText){const n=await(0,messaging_1.fetchQuotedMessage)(this,e.quoteMessageId);n&&(e.quoteText=n)}e.quoteText&&(l=(0,quote_1.formatPromptWithQuote)(l,e))}}const c=(0,commands_1.parseCfgCommand)(l);if(c!==null){if(c.conversationId&&!this.isOwner(o)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u274C \u53EA\u6709\u673A\u5668\u4EBA owner \u624D\u80FD\u64CD\u4F5C\u5176\u4ED6\u7FA4\u7684\u914D\u7F6E",msgType:"markdown"});return}if(!await this.requireOwnerOrSingleChat(s,r,o,w))return;const e=c.conversationId||s,n=e!==s,d=n?this.config.conversations.find(C=>C.conversationId===e):w,p=!!(c.dingToken||c.linkConversationId||c.whiteUserList&&c.whiteUserList.length>0||c.conversationTitle||c.atSender!==void 0||c.receiveReply!==void 0||c.preBash!==void 0||c.permissionMode!==void 0);if(d&&p){if(c.conversationTitle&&(d.conversationTitle=c.conversationTitle),h&&!n&&(d.conversationType=h),c.dingToken&&(d.dingToken=c.dingToken),c.linkConversationId&&(d.linkConversationId=c.linkConversationId),c.atSender!==void 0&&(d.atSender=c.atSender),c.receiveReply!==void 0&&(d.receiveReply=c.receiveReply),c.preBash!==void 0&&(d.preBash=c.preBash),c.permissionMode!==void 0&&(d.permissionMode=c.permissionMode),c.whiteUserList&&c.whiteUserList.length>0){d.whiteUserList=c.whiteUserList;for(const C of c.whiteUserList)(0,session_1.isMobile)(C)&&await(0,session_1.resolveUserId)(this,C)}(0,api_key_manager_1.saveClientConfig)(this),console.log(`[${(0,session_1.timestamp)()}] \u5237\u65B0\u7FA4\u914D\u7F6E: ${d.conversationTitle||e}(${e})`)}else if(!d){const C={conversationId:e,conversationType:n?"1":h,conversationTitle:c.conversationTitle||(n?"":u)};if(c.dingToken&&(C.dingToken=c.dingToken),c.linkConversationId&&(C.linkConversationId=c.linkConversationId),c.atSender!==void 0&&(C.atSender=c.atSender),c.receiveReply!==void 0&&(C.receiveReply=c.receiveReply),c.preBash!==void 0&&(C.preBash=c.preBash),c.permissionMode!==void 0&&(C.permissionMode=c.permissionMode),c.whiteUserList&&c.whiteUserList.length>0){C.whiteUserList=c.whiteUserList;for(const $ of c.whiteUserList)(0,session_1.isMobile)($)&&await(0,session_1.resolveUserId)(this,$)}this.config.conversations.push(C),(0,api_key_manager_1.saveClientConfig)(this),console.log(`[${(0,session_1.timestamp)()}] \u6CE8\u518C\u65B0\u7FA4: ${C.conversationTitle||e}(${e}) \u7C7B\u578B=${C.conversationType||"-"}`)}const D=this.getConversationDir(e);fs_1.default.existsSync(D)||(fs_1.default.mkdirSync(D,{recursive:!0}),console.log(`[${(0,session_1.timestamp)()}] \u521B\u5EFA\u5DE5\u4F5C\u76EE\u5F55: ${D}`));const m=d||this.getConversationConfig(e),f=[d?"\u2705 \u7FA4\u914D\u7F6E\u5DF2\u5237\u65B0":"\u2705 \u7FA4\u5DF2\u6CE8\u518C",`- **\u7FA4\u540D\u79F0:** ${m?.conversationTitle||e}`,`- **\u7FA4ID:** ${e}`];if(m?.conversationType&&f.push(`- **\u4F1A\u8BDD\u7C7B\u578B:** ${m.conversationType==="1"?"\u5355\u804A":m.conversationType==="2"?"\u7FA4\u804A":m.conversationType}`),m?.dingToken?f.push(`- **dingToken:** ${m.dingToken.substring(0,8)}...`):f.push("- **dingToken:** (\u672A\u6307\u5B9A, \u4F7F\u7528 defaultDingToken)"),m?.linkConversationId&&f.push(`- **linkConversationId:** ${m.linkConversationId}`),m?.atSender===!1&&f.push("- **atSender:** false (\u4E0D @ \u53D1\u9001\u4EBA)"),m?.receiveReply===!1&&f.push("- **receiveReply:** false (\u4E0D\u56DE\u590D\u786E\u8BA4\u6D88\u606F)"),m?.permissionMode&&f.push(`- **permissionMode:** ${m.permissionMode}`),m?.whiteUserList?.length){const C=m.whiteUserList.map($=>(0,session_1.isMobile)($)?$:(0,session_1.userIdToPhone)(this,$)||$).join(", ");f.push(`- **whiteUserList:** ${C}`)}f.push(`- **\u5DE5\u4F5C\u76EE\u5F55:** ${D}`),f.push(`
|
|
14
|
+
\u{1F4A1} \u53EF\u7F16\u8F91 config.json \u8865\u5145\u66F4\u591A\u914D\u7F6E`),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:f.join(`
|
|
15
|
+
`),msgType:"markdown"});return}if((0,commands_1.parseHelpCommand)(l)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:(0,commands_1.formatHelpOverview)(TOOL_VERSION,this.isOwner(o)),msgType:"markdown"});return}if((0,commands_1.parseVersionCommand)(l)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`**\u7248\u672C:** ${TOOL_VERSION}`,msgType:"markdown"});return}const M=(0,commands_1.parseCommandHelp)(l);if(M){const e=(0,commands_1.getCommandByName)(M);e?await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:(0,commands_1.formatCommandHelp)(e),msgType:"markdown"}):await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u274C \u672A\u627E\u5230\u547D\u4EE4: **${M}**
|
|
20
16
|
|
|
21
|
-
\u{1F4A1} \u8F93\u5165 \`/help\` \u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4`,msgType:"markdown"});return}if(!w){console.log(`\u672A\u6CE8\u518C\u7684\u673A\u5668\u4EBA,\u7FA4:${
|
|
22
|
-
\u{1F4A1} \u6D3B\u8DC3\u4F1A\u8BDD\u5DF2\u4FDD\u7559`),
|
|
23
|
-
\u26A0\uFE0F \u9519\u8BEF: ${
|
|
24
|
-
`),msgType:"markdown"});return}if((0,commands_1.parseResetApiKeyCfgCommand)(l)){if(!await this.requireOwner(
|
|
25
|
-
- \u6709\u6548 Key \u6570: ${
|
|
26
|
-
- \u91CD\u7F6E\u65F6\u95F4: ${this.config.apiKeyCfg.resetTime||"-"}`,msgType:"markdown"});return}const
|
|
27
|
-
- **\u7528\u6237ID:** ${
|
|
28
|
-
- **\u6635\u79F0:** ${
|
|
29
|
-
- **\u4F1A\u8BDDID:** ${
|
|
30
|
-
- **\u7528\u6237ID:** ${
|
|
31
|
-
- **\u6635\u79F0:** ${
|
|
32
|
-
`):"(\u672A\u914D\u7F6E\u7FA4\u7EA7\u767D\u540D\u5355\uFF0C\u4F7F\u7528\u5168\u5C40\u767D\u540D\u5355)";await this.sendDingMessage({conversationId:
|
|
33
|
-
${
|
|
34
|
-
\u5F53\u524D\u767D\u540D\u5355: ${p.join(", ")}`,msgType:"markdown"});return}if(
|
|
35
|
-
\u5F53\u524D\u767D\u540D\u5355: ${
|
|
17
|
+
\u{1F4A1} \u8F93\u5165 \`/help\` \u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4`,msgType:"markdown"});return}const S=(0,commands_1.parseRebootCommand)(l);if(S){if(!await this.requireOwner(s,r,o))return;if(S.tag&&!/^[\w.\-]+$/.test(S.tag)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,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 e=S.tag?`@${S.tag}`:"",n=S.update?`pnpm add -g cc-ding${e}`:null,d=`cc-ding-${this.clientId}`;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:n?`\u2705 \u66F4\u65B0\u5E76\u91CD\u542F\uFF0C\u6B63\u5728\u6267\u884C ${n}...`:"\u2705 cc-ding \u6B63\u5728\u91CD\u542F\u4E2D...",msgType:"markdown"});const p=path_1.default.join(this.getClientDir(),".reboot_pending");fs_1.default.writeFileSync(p,JSON.stringify({conversationId:s,senderStaffId:o,sessionWebhook:r,update:S.update}),"utf-8"),setTimeout(()=>{console.log(`[${(0,session_1.timestamp)()}] \u6267\u884C pm2 restart ${d}${n?" (\u542B\u66F4\u65B0)":""}`),(0,child_process_1.exec)(`${n?`${n} && `:""}pm2 restart "${d}"`,{timeout:6e4},D=>{D&&console.error(`[${(0,session_1.timestamp)()}] pm2 restart \u5931\u8D25:`,D)})},1e3);return}if(!w){console.log(`\u672A\u6CE8\u518C\u7684\u673A\u5668\u4EBA,\u7FA4:${u},${s}`),this.isOwner(o)?await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,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:r,atUserId:o,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 L=(0,commands_1.parseCleanCommand)(l);if(L!==null){if(L==="all"&&w?.conversationType!=="1"&&!this.isOwner(o)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u274C \u53EA\u6709\u673A\u5668\u4EBA owner \u624D\u80FD\u6E05\u9664\u6240\u6709\u7FA4\u7F13\u5B58",msgType:"markdown"});return}if(!await this.requireOwnerOrSingleChat(s,r,o,w))return;const e=L==="all"?null:s,n=this.cleanCache(e,!0),d=[];d.push("\u{1F9F9} \u7F13\u5B58\u6E05\u7406\u5B8C\u6210"),n.sessionsDeleted>0&&d.push(`- \u4F1A\u8BDD\u76EE\u5F55: ${n.sessionsDeleted} \u4E2A`),n.tasksDeleted>0&&d.push(`- \u4EFB\u52A1\u76EE\u5F55: ${n.tasksDeleted} \u4E2A`),n.imagesDeleted>0&&d.push(`- \u56FE\u7247\u6587\u4EF6: ${n.imagesDeleted} \u4E2A`),n.sessionsDeleted===0&&n.tasksDeleted===0&&n.imagesDeleted===0&&d.push("(\u65E0\u5386\u53F2\u6570\u636E)"),d.push(`
|
|
18
|
+
\u{1F4A1} \u6D3B\u8DC3\u4F1A\u8BDD\u5DF2\u4FDD\u7559`),n.errors.length>0&&d.push(`
|
|
19
|
+
\u26A0\uFE0F \u9519\u8BEF: ${n.errors.join("; ")}`),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:d.join(`
|
|
20
|
+
`),msgType:"markdown"});return}if((0,commands_1.parseResetApiKeyCfgCommand)(l)){if(!await this.requireOwner(s,r,o))return;if(!this.config.apiKeyCfg){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u26A0\uFE0F \u672A\u914D\u7F6E apiKeyCfg\uFF0C\u65E0\u9700\u91CD\u7F6E",msgType:"markdown"});return}(0,api_key_manager_1.resetApiKeyCfg)(this);const e=this.config.apiKeyCfg.claudeSettings.filter(n=>n.isValid).length;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 apiKeyCfg \u5DF2\u91CD\u7F6E
|
|
21
|
+
- \u6709\u6548 Key \u6570: ${e}/${this.config.apiKeyCfg.claudeSettings.length}
|
|
22
|
+
- \u91CD\u7F6E\u65F6\u95F4: ${this.config.apiKeyCfg.resetTime||"-"}`,msgType:"markdown"});return}const v=(0,commands_1.parseAuthCommand)(l);if(v){if(!await this.requireOwner(s,r,o))return;if(v.type==="approve"||v.type==="reject"){const n=this.pendingAuthRequests.get(v.requestId);if(!n){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u274C \u672A\u627E\u5230\u6388\u6743\u7533\u8BF7: ${v.requestId}`,msgType:"markdown"});return}if(this.pendingAuthRequests.delete(v.requestId),v.type==="approve"){let d=this.config.conversations.find(p=>p.conversationId===n.conversationId);d||(d={conversationId:n.conversationId,conversationType:n.conversationType||"1",conversationTitle:n.conversationTitle},this.config.conversations.push(d)),d.whiteUserList||(d.whiteUserList=[]),d.whiteUserList.includes(n.senderStaffId)||d.whiteUserList.push(n.senderStaffId),(0,api_key_manager_1.saveClientConfig)(this),console.log(`[${(0,session_1.timestamp)()}] \u6388\u6743\u7533\u8BF7\u901A\u8FC7\u5C06: id=${v.requestId}, userId=${n.senderStaffId}`),await(0,messaging_1.sendMessageToUser)(this,n.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:r,content:`\u2705 \u5DF2\u901A\u8FC7\u6388\u6743\u7533\u8BF7
|
|
23
|
+
- **\u7528\u6237ID:** ${n.senderStaffId}
|
|
24
|
+
- **\u6635\u79F0:** ${n.senderNick}
|
|
25
|
+
- **\u4F1A\u8BDDID:** ${n.conversationId}`,msgType:"markdown"})}else console.log(`[${(0,session_1.timestamp)()}] \u6388\u6743\u7533\u8BF7\u62D2\u7EDD: id=${v.requestId}, userId=${n.senderStaffId}`),await(0,messaging_1.sendMessageToUser)(this,n.senderStaffId,"\u274C \u60A8\u7684\u6388\u6743\u7533\u8BF7\u5DF2\u88AB\u62D2\u7EDD","markdown"),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 \u5DF2\u62D2\u7EDD\u6388\u6743\u7533\u8BF7
|
|
26
|
+
- **\u7528\u6237ID:** ${n.senderStaffId}
|
|
27
|
+
- **\u6635\u79F0:** ${n.senderNick}`,msgType:"markdown"});return}const e=w.whiteUserList;if(v.type==="list"){const n=e&&e.length>0?e.map(d=>`- ${(0,session_1.userIdToPhone)(this,d)||d}`).join(`
|
|
28
|
+
`):"(\u672A\u914D\u7F6E\u7FA4\u7EA7\u767D\u540D\u5355\uFF0C\u4F7F\u7528\u5168\u5C40\u767D\u540D\u5355)";await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4CB} **\u5F53\u524D\u7FA4\u767D\u540D\u5355**
|
|
29
|
+
${n}`,msgType:"markdown"});return}if(v.type==="add"){let n=v.staffId;if((0,session_1.isMobile)(v.staffId)&&(n=await(0,session_1.resolveUserId)(this,v.staffId),!n)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${v.staffId}`,msgType:"markdown"});return}if(e?.some(m=>(0,session_1.resolveToUserId)(this,m)===n)){const m=(0,session_1.userIdToPhone)(this,n)||n;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u26A0\uFE0F ${m} \u5DF2\u5728\u5F53\u524D\u7FA4\u767D\u540D\u5355\u4E2D`,msgType:"markdown"});return}w.whiteUserList||(w.whiteUserList=[]),w.whiteUserList.push(v.staffId),(0,api_key_manager_1.saveClientConfig)(this);const p=w.whiteUserList.map(m=>{const f=(0,session_1.resolveToUserId)(this,m);return(0,session_1.userIdToPhone)(this,f)||m}),D=(0,session_1.isMobile)(v.staffId)?v.staffId:(0,session_1.userIdToPhone)(this,v.staffId)||v.staffId;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 \u5DF2\u6DFB\u52A0 ${D} \u5230\u5F53\u524D\u7FA4\u767D\u540D\u5355
|
|
30
|
+
\u5F53\u524D\u767D\u540D\u5355: ${p.join(", ")}`,msgType:"markdown"});return}if(v.type==="del"){let n=v.staffId;if((0,session_1.isMobile)(v.staffId)&&(n=await(0,session_1.resolveUserId)(this,v.staffId),!n)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u26A0\uFE0F \u65E0\u6CD5\u89E3\u6790\u624B\u673A\u53F7: ${v.staffId}`,msgType:"markdown"});return}const d=e?.findIndex(f=>(0,session_1.resolveToUserId)(this,f)===n)??-1;if(d<0){const f=(0,session_1.userIdToPhone)(this,n)||n;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u26A0\uFE0F ${f} \u4E0D\u5728\u5F53\u524D\u7FA4\u767D\u540D\u5355\u4E2D`,msgType:"markdown"});return}const p=w.whiteUserList[d];w.whiteUserList.splice(d,1),w.whiteUserList.length===0&&delete w.whiteUserList,(0,api_key_manager_1.saveClientConfig)(this);const D=w.whiteUserList?.length?w.whiteUserList.map(f=>{const C=(0,session_1.resolveToUserId)(this,f);return(0,session_1.userIdToPhone)(this,C)||f}).join(", "):"(\u7A7A\uFF0C\u4F7F\u7528\u5168\u5C40\u767D\u540D\u5355)",m=(0,session_1.userIdToPhone)(this,n)||p;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 \u5DF2\u79FB\u9664 ${m}
|
|
31
|
+
\u5F53\u524D\u767D\u540D\u5355: ${D}`,msgType:"markdown"});return}}const b=(0,commands_1.parseOpenCommand)(l);if(b!==null){if(!await this.requireOwner(s,r,o))return;const e=this.getConversationDir(s),{exec:n}=await Promise.resolve().then(()=>__importStar(require("child_process"))),d=process.platform;try{b==="folder"?(n(d==="darwin"?`open "${e}"`:`explorer "${e}"`),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4C2} \u5DF2\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u6253\u5F00:
|
|
36
32
|
\`\`\`
|
|
37
|
-
${
|
|
38
|
-
\`\`\``,msgType:"markdown"})):
|
|
33
|
+
${e}
|
|
34
|
+
\`\`\``,msgType:"markdown"})):b==="code"?n("which code",p=>{if(p){this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u274C \u672A\u68C0\u6D4B\u5230 VS Code `code` \u547D\u4EE4\n\u8BF7\u5B89\u88C5 VS Code \u5E76\u901A\u8FC7 Command Palette \u5B89\u88C5 Shell Command",msgType:"markdown"});return}n(`code "${e}"`),this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4BB} \u5DF2\u5728 VS Code \u4E2D\u6253\u5F00:
|
|
39
35
|
\`\`\`
|
|
40
|
-
${
|
|
41
|
-
\`\`\``,msgType:"markdown"})}):(d==="darwin"?
|
|
36
|
+
${e}
|
|
37
|
+
\`\`\``,msgType:"markdown"})}):(d==="darwin"?n(`open -a Terminal "${e}"`):n(`start cmd /k "cd /d ${e}"`,{shell:"cmd.exe"}),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4BB} \u5DF2\u5728\u7EC8\u7AEF\u4E2D\u6253\u5F00:
|
|
42
38
|
\`\`\`
|
|
43
|
-
${
|
|
44
|
-
\`\`\``,msgType:"markdown"}))}catch(p){await this.sendDingMessage({conversationId:
|
|
39
|
+
${e}
|
|
40
|
+
\`\`\``,msgType:"markdown"}))}catch(p){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u274C \u6253\u5F00\u5931\u8D25: ${p instanceof Error?p.message:String(p)}`,msgType:"markdown"})}return}const x=(0,commands_1.parseCronCommand)(l);if(x){await this.handleCronCommand(x,{conversationId:s,sessionWebhook:r,senderStaffId:o,senderNick:i,conversationConfig:w});return}const U=(0,commands_1.parseBashCommand)(l);if(U!==null){const e=this.getConversationDir(s),n=[];this.config.preBash&&n.push(this.config.preBash),w?.preBash&&n.push(w.preBash);const d=n.length>0?`${n.join(" ; ")} ; ${U}`:U,p=this;(0,child_process_1.exec)(d,{cwd:e,timeout:3e4,maxBuffer:1024*1024},async(D,m,f)=>{try{let C;if(D)C=`\u274C \u547D\u4EE4\u6267\u884C\u5931\u8D25
|
|
45
41
|
\`\`\`
|
|
46
|
-
${
|
|
47
|
-
\`\`\``,msgType:"markdown"});return}const O=(0,commands_1.parseMkdirCommand)(l);if(O!==null){await this.handleMkdirCommand(e,a,O);return}const A=(0,commands_1.parseTouchCommand)(l);if(A!==null){await this.handleTouchCommand(e,a,A);return}const P=(0,commands_1.parseRmCommand)(l);if(P!==null){await this.handleRmCommand(e,a,P);return}const U=(0,commands_1.parseBashCommand)(l);if(U!==null){const t=this.getConversationDir(e),i=[];this.config.preBash&&i.push(this.config.preBash),w?.preBash&&i.push(w.preBash);const d=i.length>0?`${i.join(" ; ")} ; ${U}`:U,p=this;(0,child_process_1.exec)(d,{cwd:t,timeout:3e4,maxBuffer:1024*1024},async(y,m,f)=>{try{let C;if(y)C=`\u274C \u547D\u4EE4\u6267\u884C\u5931\u8D25
|
|
48
|
-
\`\`\`
|
|
49
|
-
${y.message}
|
|
42
|
+
${D.message}
|
|
50
43
|
\`\`\``,f&&(C+=`
|
|
51
44
|
|
|
52
45
|
**stderr:**
|
|
@@ -60,26 +53,28 @@ ${p.sanitizeOutput($)}
|
|
|
60
53
|
**stderr:**
|
|
61
54
|
\`\`\`
|
|
62
55
|
${p.sanitizeOutput(f)}
|
|
63
|
-
\`\`\``)}await p.sendDingMessage({conversationId:
|
|
56
|
+
\`\`\``)}await p.sendDingMessage({conversationId:s,sessionWebhook:r,content:C,msgType:"markdown"})}catch(C){console.error("[bash] \u53D1\u9001\u6D88\u606F\u5931\u8D25:",C)}});return}if(/^\/new(?:\s|$)/i.test(l)){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)}`),this.interruptClaudeProcess(e.session,"\u65B0\u4F1A\u8BDD\u547D\u4EE4\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Claude \u8FDB\u7A0B"),this.activeSessions.delete(e.key),this.saveActiveSession(e.key));const n=l.replace(/^\/new\s*/i,"").trim();n?await this.startNewSession({conversationId:s,sessionWebhook:r,senderStaffId:o,senderNick:i,message:n,conversationConfig:w}):await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,content:"\u{1F680} \u8BF7\u8F93\u5165\u60A8\u7684\u95EE\u9898\u5F00\u59CB\u65B0\u4F1A\u8BDD"});return}const N=(0,commands_1.parseContinueSessionCommand)(l);if(N!==null&&w){let e=N;if(!e){const n=(0,session_1.findLatestSession)(this,s);if(!n){await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,content:"\u26A0\uFE0F \u672A\u627E\u5230\u5DF2\u7ED3\u675F\u7684\u4F1A\u8BDD",msgType:"markdown"});return}e=(0,session_1.getSessionId)(n)}await this.switchToSession(s,r,e,o,w);return}const _=(0,commands_1.parseLogCommand)(l);if(_!==null){const e=this.readSessionLogTail(s,_);e?await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4CB} \u6700\u8FD1 ${_} \u884C\u65E5\u5FD7:
|
|
64
57
|
\`\`\`
|
|
65
|
-
${
|
|
66
|
-
\`\`\``,msgType:"markdown"}):await this.sendDingMessage({conversationId:
|
|
67
|
-
`+(0,commands_1.formatGlobalConfig)(this.config)),
|
|
68
|
-
`+(0,commands_1.formatConversationInfo)(w,
|
|
69
|
-
`+d):
|
|
70
|
-
\u65E0\u6D3B\u8DC3\u4F1A\u8BDD`)}(
|
|
71
|
-
`+this.formatTaskInfo()),await this.sendDingMessage({conversationId:
|
|
58
|
+
${e}
|
|
59
|
+
\`\`\``,msgType:"markdown"}):await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u26A0\uFE0F \u5F53\u524D\u65E0\u6D3B\u8DC3\u4F1A\u8BDD\u6216\u6682\u65E0\u65E5\u5FD7"});return}const k=(0,commands_1.parseInfoCommand)(l);if(k!==null){const e=[],n=this.getConversationDir(s);if((k==="all"||k==="robot")&&(e.push(`### \u{1F310} \u5168\u5C40\u6838\u5FC3\u914D\u7F6E
|
|
60
|
+
`+(0,commands_1.formatGlobalConfig)(this.config)),e.push(`### \u{1F916} \u7FA4\u914D\u7F6E\u4FE1\u606F
|
|
61
|
+
`+(0,commands_1.formatConversationInfo)(w,s,d=>(0,session_1.userIdToPhone)(this,d),n))),k==="all"||k==="session"){const d=this.formatSessionInfo(s);d?e.push(`### \u{1F4AC} \u5F53\u524D\u4F1A\u8BDD\u4FE1\u606F
|
|
62
|
+
`+d):e.push(`### \u{1F4AC} \u5F53\u524D\u4F1A\u8BDD\u4FE1\u606F
|
|
63
|
+
\u65E0\u6D3B\u8DC3\u4F1A\u8BDD`)}(k==="all"||k==="task")&&e.push(`### \u{1F4DD} \u4EFB\u52A1\u961F\u5217\u4FE1\u606F
|
|
64
|
+
`+this.formatTaskInfo()),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:e.join(`
|
|
72
65
|
|
|
73
|
-
`),msgType:"markdown"});return}const
|
|
66
|
+
`),msgType:"markdown"});return}const P=(0,commands_1.parseLsCommand)(l);if(P!==null){const{target:e,depth:n}=P,d=this.getConversationDir(s);let p=d,D="\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55";if(e&&e!=="root")if(e.startsWith("./")||e.startsWith("../")||e.startsWith("/")){const f=path_1.default.resolve(d,e);if(fs_1.default.existsSync(f)&&fs_1.default.statSync(f).isDirectory()){if(!f.startsWith(d)){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u274C \u8DEF\u5F84\u8D85\u51FA\u5DE5\u4F5C\u76EE\u5F55\u8303\u56F4",msgType:"markdown"});return}p=f,D=e}else{await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u274C \u8DEF\u5F84\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u76EE\u5F55: **${e}**`,msgType:"markdown"});return}}else{const f=(0,commands_1.findSubdirByName)(d,e);if(f)p=f,D=e;else{await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u274C \u672A\u627E\u5230\u540D\u4E3A **${e}** \u7684\u76EE\u5F55`,msgType:"markdown"});return}}const m=(0,commands_1.getDirectoryStructure)(p,0,n);await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4C2} ${D} (\u5C55\u5F00${n}\u5C42):
|
|
74
67
|
\`\`\`
|
|
75
68
|
${m}
|
|
76
|
-
\`\`\``,msgType:"markdown"});return}const
|
|
69
|
+
\`\`\``,msgType:"markdown"});return}const A=(0,task_1.parseTaskCancelCommand)(l);if(A){const e=this.cancelTask(A,s);await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:e,msgType:"markdown"});return}if(l.startsWith("/task ")){const e=l.substring(6).trim();e&&(await this.sendDingMessage({conversationId:s,sessionWebhook:r,atUserId:o,content:"\u{1F4CB} \u4EFB\u52A1\u5DF2\u6536\u5230,\u5B8C\u6210\u540E\u6211\u4F1A\u56DE\u590D"}),await this.saveTask({conversationId:s,prompt:e,senderStaffId:o,senderNickName:i,sessionWebhook:r}));return}const O=(0,commands_1.parseMqCommand)(l);if(O){const n=this.findActiveSession(s)?.session.messageQueue??[];switch(O.type){case"list":{if(n.length===0)await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});else{const d=n.map((p,D)=>`${D+1}. **${p.senderNick||p.senderStaffId}:** ${this.truncateMsg(p.message)}`);await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4E8} \u6D88\u606F\u961F\u5217 (${n.length} \u6761)
|
|
77
70
|
${d.join(`
|
|
78
|
-
`)}`,msgType:"markdown"})}return}case"cancel":{if(
|
|
79
|
-
${
|
|
80
|
-
`)}`,msgType:"markdown"});return}case"cancelAll":{if(
|
|
81
|
-
...(\u5185\u5BB9\u8FC7\u957F\u5DF2\u622A\u65AD)`:d;await this.sendDingMessage({conversationId:
|
|
71
|
+
`)}`,msgType:"markdown"})}return}case"cancel":{if(n.length===0){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});return}const d=Math.min(O.count,n.length),D=n.splice(n.length-d,d).map((m,f)=>`${f+1}. **${m.senderNick||m.senderStaffId}:** ${this.truncateMsg(m.message)}`);await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 \u5DF2\u4ECE\u961F\u5C3E\u79FB\u9664 ${d} \u6761\u6D88\u606F
|
|
72
|
+
${D.join(`
|
|
73
|
+
`)}`,msgType:"markdown"});return}case"cancelAll":{if(n.length===0){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u{1F4ED} \u5F53\u524D\u65E0\u6392\u961F\u6D88\u606F",msgType:"markdown"});return}const d=n.length;n.length=0,await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u2705 \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u5171\u79FB\u9664 ${d} \u6761\u6D88\u606F`,msgType:"markdown"});return}}}if((0,commands_1.parseGoonCommand)(l)){const e=this.activeSessions.get(s);if(!e){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u26A0\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u4F1A\u8BDD"});return}if(e.currentProcess){console.log(`[${(0,session_1.timestamp)()}] /goon: \u7EC8\u6B62\u5F53\u524D Claude \u8FDB\u7A0B`),e.interrupted=!0,e.currentProcess.kill("SIGINT"),await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u{1F504} \u6B63\u5728\u91CD\u542F Claude \u8FDB\u7A0B..."}),e.goonPending=!1,e.isProcessing=!0;try{await(0,claude_process_1.executeClaudeQuery)(this,e.session,"\u7EE7\u7EED",{senderNick:e.session.startNickName,senderStaffId:e.lastSenderStaffId,permissionMode:e.conversationConfig.permissionMode})}finally{e.isProcessing=!1}}else{console.log(`[${(0,session_1.timestamp)()}] /goon: \u65E0\u8FD0\u884C\u4E2D\u8FDB\u7A0B\uFF0C\u76F4\u63A5\u53D1\u9001"\u7EE7\u7EED"`),e.isProcessing=!0;try{await(0,claude_process_1.executeClaudeQuery)(this,e.session,"\u7EE7\u7EED",{senderNick:i,senderStaffId:o,permissionMode:e.conversationConfig.permissionMode})}finally{e.isProcessing=!1}}return}const E=(0,commands_1.parseCcCommand)(l);if(E!==null){const e=this.activeSessions.get(s);if(!e){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u26A0\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u4F1A\u8BDD\uFF0C\u8BF7\u5148\u53D1\u9001\u6D88\u606F\u5F00\u59CB\u4F1A\u8BDD"});return}if(e.isProcessing){await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:"\u23F3 \u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7A0D\u7B49..."});return}e.isProcessing=!0;try{await(0,claude_process_1.executeClaudeQuery)(this,e.session,E,{senderNick:i,senderStaffId:o,permissionMode:e.conversationConfig.permissionMode})}finally{e.isProcessing=!1}return}if((0,commands_1.parseClaudeMdCommand)(l)){const e=this.getConversationDir(s),n=path_1.default.join(e,".claude","CLAUDE.md");if(fs_1.default.existsSync(n)){const d=fs_1.default.readFileSync(n,"utf-8"),p=d.length>8e3?d.substring(0,8e3)+`
|
|
74
|
+
...(\u5185\u5BB9\u8FC7\u957F\u5DF2\u622A\u65AD)`:d;await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u{1F4C4} **CLAUDE.md**
|
|
82
75
|
\`\`\`
|
|
83
76
|
${p}
|
|
84
|
-
\`\`\``,msgType:"markdown"})}else await this.sendDingMessage({conversationId:
|
|
85
|
-
\u8DEF\u5F84: \`${
|
|
77
|
+
\`\`\``,msgType:"markdown"})}else await this.sendDingMessage({conversationId:s,sessionWebhook:r,content:`\u26A0\uFE0F \u672A\u627E\u5230 CLAUDE.md
|
|
78
|
+
\u8DEF\u5F84: \`${n}\``,msgType:"markdown"});return}let q=l;if(t.atUsers&&t.atUsers.length>0){const e=t.atUsers.filter(n=>n.staffId!==o).map(n=>`@${n.staffId}`).join(", ");e&&(q=`[\u63D0\u53CA\u7528\u6237: ${e}]
|
|
79
|
+
${q}`)}await this.handleSessionMessage({conversationId:s,sessionWebhook:r,senderStaffId:o,senderNick:i,message:q,conversationConfig:w})}async notifyPendingReboot(){const a=path_1.default.join(this.getClientDir(),".reboot_pending");if(fs_1.default.existsSync(a))try{const t=JSON.parse(fs_1.default.readFileSync(a,"utf-8"));fs_1.default.unlinkSync(a);let i="\u2705 cc-ding \u5DF2\u91CD\u542F\u5B8C\u6210";t.update&&(i+=`
|
|
80
|
+
**\u7248\u672C:** ${TOOL_VERSION}`);let o;const s=this.activeSessions.get(t.conversationId);if(s)o=s.session.sessionWebhook;else if(t.sessionWebhook)o=t.sessionWebhook,console.log(`[${(0,session_1.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,session_1.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:t.conversationId,sessionWebhook:o,content:i,msgType:"markdown",atUserId:t.senderStaffId}),console.log(`[${(0,session_1.timestamp)()}] \u91CD\u542F\u5B8C\u6210\u901A\u77E5\u5DF2\u53D1\u9001`)}catch(t){try{const i=fs_1.default.readFileSync(a,"utf-8");console.error(`[${(0,session_1.timestamp)()}] .reboot_pending \u5185\u5BB9:`,i)}catch{}console.error(`[${(0,session_1.timestamp)()}] \u5904\u7406\u91CD\u542F\u901A\u77E5\u5931\u8D25:`,t);try{fs_1.default.unlinkSync(a)}catch{}}}async run(){const a=Array.isArray(this.config.conversations)?this.config.conversations:[],t=this.config.taskHandlerCount??this.DEFAULT_TASK_HANDLER_COUNT,i=a.length>0;console.log(`[${(0,session_1.timestamp)()}] \u9489\u9489\u673A\u5668\u4EBA\u670D\u52A1\u542F\u52A8\uFF0CclientId: ${this.clientId}`),console.log(`[${(0,session_1.timestamp)()}] \u7FA4\u914D\u7F6E: ${a.map(u=>u.conversationTitle||u.conversationId).join(", ")}`),(0,api_key_manager_1.startupCheck)(this),await(0,session_1.resolveAllPhonesInConfig)(this),this.config.apiKeyCfg&&((0,api_key_manager_1.resetApiKeyCfg)(this),(0,api_key_manager_1.scheduleApiKeyCfgDailyReset)(this)),this.loadActiveSessions(),await this.notifyPendingReboot(),this.cronEngine.start(),i&&console.log(`[${(0,session_1.timestamp)()}] \u4EFB\u52A1\u5904\u7406\u5668\u6570\u91CF: ${t}`),this.dingStreamClient.registerCallbackListener("/v1.0/im/bot/messages/get",async u=>{await this.botMsgGetCallback(u)});const o=[];if(i)for(let u=0;u<t;u++)console.log(`[${(0,session_1.timestamp)()}] \u542F\u52A8\u4EFB\u52A1\u5904\u7406\u5668 #${u+1}`),o.push(this.runTaskHandlerLoop().catch(r=>console.error(`\u4EFB\u52A1\u5904\u7406\u5668 #${u+1} \u9519\u8BEF:`,r)));const s=this.dingStreamClient.connect().catch(u=>{console.error("Fatal error",u),process.exit(1)});await Promise.all([s,...o])}}exports.DingClaude=DingClaude;
|
|
@@ -1,39 +1,42 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(
|
|
2
|
-
`).filter(Boolean).slice(-
|
|
3
|
-
`)}catch{return""}}function isContextWindowExceededError(
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveClaudeSettingsPath=resolveClaudeSettingsPath,exports.isRetryableApiError=isRetryableApiError,exports.parseClaudeStreamLine=parseClaudeStreamLine,exports.interruptClaudeProcess=interruptClaudeProcess,exports.executeClaudeQuery=executeClaudeQuery;const fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),readline_1=__importDefault(require("readline")),child_process_1=require("child_process"),messaging_1=require("./messaging"),session_1=require("./session"),api_key_manager_1=require("./api-key-manager"),MAX_FAST_FAIL=20,API_RETRY_DELAY_MS=1e4,FAST_FAIL_THRESHOLD_MS=1e4,MAX_TOTAL_RETRIES=10,MAX_RETRY_DURATION_MS=300*1e3,WATCHDOG_TIMEOUT_MS=300*1e3,WATCHDOG_CHECK_INTERVAL_MS=30*1e3;function resolveClaudeSettingsPath(e,t,i){const r=(0,api_key_manager_1.getForceEnabledSettingsPath)(t);if(r)return r;if(e.config.apiKeyCfg){const c=(0,api_key_manager_1.readApiKeyFromSettings)(t);let I=null;if(c&&(I=e.config.apiKeyCfg.claudeSettings.find(u=>u.apiKey===c&&u.isValid)||null),I||(I=(0,api_key_manager_1.pickValidApiKey)(e)),I)return(0,api_key_manager_1.ensureSettingsWithApiKey)(t,I)}if(e.config.apiKeyCfg)return;if(i)return i;const s=path_1.default.join(t,".claude","settings.json");if(fs_1.default.existsSync(s))return console.log(`[${(0,session_1.timestamp)()}] \u81EA\u52A8\u68C0\u6D4B\u5230 settings.json: ${s}`),s}function isRetryableApiError(e){if(/\b429\b/.test(e)&&!(0,api_key_manager_1.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(r=>t.includes(r))}function sleep(e){return new Promise(t=>setTimeout(t,e))}class RetryableApiError extends Error{constructor(t,i=""){super(`Retryable API error (TPM limit etc.)${t?" [fast fail]":""}`),this.name="RetryableApiError",this.isFastFail=t,this.output=i}}class ConversationNotFoundError extends Error{constructor(){super("Claude conversation not found"),this.name="ConversationNotFoundError"}}class ContextWindowExceededError extends Error{constructor(){super("Context window exceeded: prompt tokens exceed maximum context window"),this.name="ContextWindowExceededError"}}function readLastLogLines(e,t){try{return fs_1.default.readFileSync(e,"utf-8").split(`
|
|
2
|
+
`).filter(Boolean).slice(-t).join(`
|
|
3
|
+
`)}catch{return""}}function isContextWindowExceededError(e){return/prompt tokens?\s*\(\s*\d+\s*\)\s*exceeds/i.test(e)||/exceeds?.*maximum context window/i.test(e)}function isPermissionError(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(r=>t.includes(r))}function isConversationNotFoundError(e){return/no conversation found with session id/i.test(e)}function parseClaudeStreamLine(e,t=!1){if(!e.trim())return null;try{const i=JSON.parse(e);if(i.type==="system"&&i.subtype==="init"&&i.session_id)return{type:"system",sessionId:i.session_id};if(i.type==="assistant"){const r=i.message?.content;if(Array.isArray(r)){const s=[];for(const c of r)c.type==="text"&&c.text?s.push(c.text):c.type==="thinking"&&c.thinking&&t&&s.push(`\u{1F4AD} **\u601D\u8003\u8FC7\u7A0B**
|
|
4
4
|
\`\`\`
|
|
5
|
-
${
|
|
6
|
-
\`\`\``);if(
|
|
7
|
-
`)}}else if(i.content)return{type:"assistant",content:typeof i.content=="string"?i.content:JSON.stringify(i.content)};return{type:"assistant"}}if(i.type==="result"){const
|
|
8
|
-
`,"utf-8"),
|
|
9
|
-
`),
|
|
10
|
-
`,"utf-8")}catch{}
|
|
11
|
-
`,
|
|
12
|
-
`,"utf-8")}catch{}const
|
|
13
|
-
`).trim()
|
|
14
|
-
`,"utf-8")}catch{}const
|
|
15
|
-
`).trim();if(
|
|
16
|
-
`,"utf-8")}catch{}const
|
|
17
|
-
`+
|
|
18
|
-
`,"utf-8")}catch{}
|
|
19
|
-
`,"utf-8"),
|
|
20
|
-
|
|
5
|
+
${c.thinking}
|
|
6
|
+
\`\`\``);if(s.length>0)return{type:"assistant",content:s.join(`
|
|
7
|
+
`)}}else if(i.content)return{type:"assistant",content:typeof i.content=="string"?i.content:JSON.stringify(i.content)};return{type:"assistant"}}if(i.type==="result"){const r=i.result||"";return{type:"result",content:typeof r=="string"?r:JSON.stringify(r)}}return{type:i.type||"unknown"}}catch{return{type:"text",content:e}}}function interruptClaudeProcess(e,t){return e.currentProcess?(console.log(`[${(0,session_1.timestamp)()}] ${t}`),e.interrupted=!0,e.currentProcess.kill("SIGINT"),!0):!1}function runClaudeOnce(e,t,i,r,s,c,I){let u=e.getSessionDir(t),S=`${u}/session.log`;fs_1.default.existsSync(u)||fs_1.default.mkdirSync(u,{recursive:!0});const m=Date.now();return new Promise((g,d)=>{const C=(0,child_process_1.spawn)(r,i,{cwd:s,stdio:["pipe","pipe","pipe"]}),v=e.activeSessions.get(t.conversationId);v&&(v.currentProcess=C,v.lastActivityTime=Date.now()),fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [SYSTEM]: Claude \u67E5\u8BE2\u542F\u52A8${I?" (\u91CD\u8BD5)":""}
|
|
8
|
+
`,"utf-8"),C.stdin?.write(`${c}
|
|
9
|
+
`),C.stdin?.end();let A=!I&&!!t.claudeSessionId,w=[],k="",R="",P=!1,h=!1,y=null;const E=new Set,M=()=>{v&&(v.lastActivityTime=Date.now())};y=setInterval(()=>{if(h){y&&clearInterval(y);return}const a=v?.lastActivityTime??m;if(Date.now()-a>=WATCHDOG_TIMEOUT_MS){console.warn(`[${(0,session_1.timestamp)()}] Watchdog: Claude \u8FDB\u7A0B ${WATCHDOG_TIMEOUT_MS/1e3}s \u65E0\u6D3B\u52A8\uFF0C\u901A\u77E5\u7528\u6237`);try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [SYSTEM]: Watchdog \u8D85\u65F6\uFF0C${WATCHDOG_TIMEOUT_MS/1e3}s \u65E0\u6D3B\u52A8\uFF0C\u5DF2\u901A\u77E5\u7528\u6237
|
|
10
|
+
`,"utf-8")}catch{}y&&clearInterval(y),y=null;const l=v?.lastSenderStaffId||t.startStaffId;(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:l,content:`\u23F0 Claude \u8FDB\u7A0B\u8D85\u8FC7 ${WATCHDOG_TIMEOUT_MS/1e3}s \u65E0\u54CD\u5E94\uFF0C\u53EF\u53D1\u9001 /goon \u5F3A\u5236\u91CD\u542F\u6062\u590D\uFF0C\u6216 /end \u7ED3\u675F\u4F1A\u8BDD`}).catch(p=>console.error("\u53D1\u9001 Watchdog \u901A\u77E5\u5931\u8D25:",p))}},WATCHDOG_CHECK_INTERVAL_MS),readline_1.default.createInterface({input:C.stdout}).on("line",a=>{if(R+=a+`
|
|
11
|
+
`,M(),e.debugLog(`Claude stdout: ${a.substring(0,200)}${a.length>200?"...":""}`),e.config.debug)try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [RAW]: ${a}
|
|
12
|
+
`,"utf-8")}catch{}const n=parseClaudeStreamLine(a,e.config.includeThinking??!1);if(n){if(n.type==="system"&&n.sessionId&&!A&&(e.updateSessionFile(t,{claudeSessionId:n.sessionId}),A=!0,u=e.getSessionDir(t),S=`${u}/session.log`),n.type==="assistant"){try{const p=JSON.parse(a)?.message?.content;if(Array.isArray(p)){for(const o of p)if(o.type==="tool_use"&&o.id&&!E.has(o.id)){E.add(o.id);const $=o.name||"unknown";let f="";o.input&&(o.input.command?f=o.input.command.substring(0,200):o.input.file_path?f=o.input.file_path:o.input.pattern?f=o.input.pattern:o.input.query?f=o.input.query:o.input.description?f=o.input.description:o.input.prompt?f=o.input.prompt.substring(0,200):f=JSON.stringify(o.input).substring(0,200)),e.appendSessionLog(u,"tool",`${$}${f?": "+f:""}`)}}}catch{}n.content&&w.push(n.content)}if(n.type==="result"){const l=e.config.resultOnly??!0,p=(n.content||"").trim(),o=w.join(`
|
|
13
|
+
`).trim(),$=l&&p||o;if($&&!v?.interrupted){try{e.appendSessionLog(u,"assistant",$)}catch{}const T=e.activeSessions.get(t.conversationId)?.lastSenderStaffId||t.startStaffId;P=!0,(0,messaging_1.sendClaudeResponseToDing)(e,(0,session_1.getReplyConversationId)(t),(0,session_1.getReplyWebhook)(t),T,$).catch(x=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",x))}else console.warn(`[${(0,session_1.timestamp)()}] Claude \u8FD4\u56DE\u4E86\u7A7A\u7684 result \u4E14 responseBuffer \u4E5F\u4E3A\u7A7A\uFF0C\u65E0\u5185\u5BB9\u53EF\u53D1\u9001`);w=[]}}}),C.stderr?.on("data",a=>{const n=a.toString();if(k+=n,M(),(0,api_key_manager_1.isQuotaExhaustedError)(n)){console.log(`[${(0,session_1.timestamp)()}] [Claude stderr] \u914D\u989D\u8017\u5C3D\u9519\u8BEF(429): ${n.trim()}`);try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [WARN]: ${n}`,"utf-8")}catch{}}else if(isRetryableApiError(n)){console.log(`[${(0,session_1.timestamp)()}] [Claude stderr] \u53EF\u91CD\u8BD5API\u9519\u8BEF(422 TPM\u9650\u6D41): ${n.trim()}`);try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [WARN]: ${n}`,"utf-8")}catch{}}else{console.error(`[Claude stderr]: ${n}`);try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [ERROR]: ${n}`,"utf-8")}catch{}}}),C.on("close",a=>{h=!0,y&&(clearInterval(y),y=null),console.log(`[${(0,session_1.timestamp)()}] Claude \u8FDB\u7A0B\u9000\u51FA\uFF0C\u4EE3\u7801: ${a}`);try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [SYSTEM]: Claude \u67E5\u8BE2\u7ED3\u675F\uFF0C\u9000\u51FA\u7801: ${a}
|
|
14
|
+
`,"utf-8")}catch{}const n=e.activeSessions.get(t.conversationId);if(n&&(n.currentProcess=void 0),n?.interrupted){console.log(`[${(0,session_1.timestamp)()}] \u7528\u6237\u4E3B\u52A8\u4E2D\u65AD\uFF0C\u4E22\u5F03 responseBuffer (${w.length} \u6BB5)`),n.interrupted=!1,w=[],g(0);return}if(w.length>0){const p=w.join(`
|
|
15
|
+
`).trim();if(p){try{e.appendSessionLog(u,"assistant",p)}catch{}const o=n?.lastSenderStaffId||t.startStaffId;P=!0,(0,messaging_1.sendClaudeResponseToDing)(e,(0,session_1.getReplyConversationId)(t),(0,session_1.getReplyWebhook)(t),o,p).catch($=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",$))}}if(a===0&&!P&&!n?.interrupted){console.warn(`[${(0,session_1.timestamp)()}] Claude \u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA\u4F46\u672A\u4EA7\u751F\u4EFB\u4F55\u56DE\u590D\u5185\u5BB9`);try{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [WARN]: Claude \u8FDB\u7A0B\u6B63\u5E38\u9000\u51FA\u4F46\u672A\u4EA7\u751F\u4EFB\u4F55\u56DE\u590D\u5185\u5BB9
|
|
16
|
+
`,"utf-8")}catch{}const p=n?.lastSenderStaffId||t.startStaffId;(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:p,content:"\u26A0\uFE0F Claude \u5904\u7406\u5B8C\u6210\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5185\u5BB9\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6362\u79CD\u65B9\u5F0F\u63D0\u95EE"}).catch(o=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",o))}if(a===0){g(0);return}const l=k+`
|
|
17
|
+
`+R;if((0,api_key_manager_1.isQuotaExhaustedError)(l)){const o=Date.now()-m<FAST_FAIL_THRESHOLD_MS;console.log(`[${(0,session_1.timestamp)()}] \u68C0\u6D4B\u5230\u914D\u989D\u8017\u5C3D\u9519\u8BEF(429)\uFF0Cstdout\u5339\u914D=${(0,api_key_manager_1.isQuotaExhaustedError)(R)}, stderr\u5339\u914D=${(0,api_key_manager_1.isQuotaExhaustedError)(k)}`),d(new RetryableApiError(o,l));return}if((0,api_key_manager_1.isAuthenticationError)(l)){console.log(`[${(0,session_1.timestamp)()}] \u68C0\u6D4B\u5230\u8BA4\u8BC1\u9519\u8BEF(401)\uFF0C\u901A\u77E5\u7528\u6237`);const p=n?.lastSenderStaffId||t.startStaffId;(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.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(o=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",o)),g(a??1);return}if(isRetryableApiError(l)){const o=Date.now()-m<FAST_FAIL_THRESHOLD_MS;d(new RetryableApiError(o,l));return}if(isPermissionError(l)){console.log(`[${(0,session_1.timestamp)()}] \u68C0\u6D4B\u5230\u9700\u8981\u6388\u6743\uFF0C\u901A\u77E5\u7528\u6237`);const p=n?.lastSenderStaffId||t.startStaffId;(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:p,content:"\u26A0\uFE0F Claude \u9700\u8981\u6388\u6743\uFF0C\u8BF7\u4EBA\u5DE5\u4ECB\u5165"}).catch(o=>console.error("\u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",o)),g(a??1);return}if(t.claudeSessionId&&isConversationNotFoundError(l)){console.log(`[${(0,session_1.timestamp)()}] Claude \u4F1A\u8BDD\u5DF2\u5931\u6548: ${t.claudeSessionId}\uFF0C\u901A\u77E5\u5916\u5C42\u91CD\u65B0\u53D1\u8D77\u65B0\u4F1A\u8BDD`),d(new ConversationNotFoundError);return}if(isContextWindowExceededError(l)){console.log(`[${(0,session_1.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{fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [SYSTEM]: \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u5C06\u81EA\u52A8 /compact
|
|
18
|
+
`,"utf-8")}catch{}d(new ContextWindowExceededError);return}d(new Error(`Claude \u8FDB\u7A0B\u9000\u51FA\uFF0C\u4EE3\u7801: ${a}`))}),C.on("error",a=>{h=!0,y&&(clearInterval(y),y=null),console.error("Claude \u8FDB\u7A0B\u9519\u8BEF:",a),fs_1.default.appendFileSync(S,`[${(0,session_1.timestamp)()}] [ERROR]: \u8FDB\u7A0B\u9519\u8BEF: ${a.message}
|
|
19
|
+
`,"utf-8"),d(a)})})}function injectSessionContext(e,t){const i=e.getConversationDir(t.conversationId),r=path_1.default.join(i,".claude");fs_1.default.existsSync(r)||fs_1.default.mkdirSync(r,{recursive:!0});const s=e.getConversationConfig(t.conversationId),c=e.config,I="<!-- cc-ding:session-context-start (DO NOT EDIT) -->",u="<!-- cc-ding:session-context-end (DO NOT EDIT) -->",m=[I,"# cc-ding Session Context","","## Client",`- clientId: \`${e.clientId}\``,c.clientName?`- clientName: ${c.clientName}`:"",`- owner: ${c.owner}`,"","## Conversation",`- conversationId: \`${t.conversationId}\``,s?.conversationType?`- conversationType: ${s.conversationType==="1"?"\u5355\u804A":"\u7FA4\u804A"}`:"",s?.conversationTitle?`- conversationTitle: ${s.conversationTitle}`:"",s?.linkConversationId?`- linkConversationId: \`${s.linkConversationId}\` (\u5173\u8054\u7FA4\uFF0C\u5171\u4EAB\u5DE5\u4F5C\u76EE\u5F55)`:"","","## Settings",s?.permissionMode?`- permissionMode: ${s.permissionMode}`:"",s?.agent?`- agent: ${s.agent}`:"",s?.taskCfg?.skill?`- taskCfg.skill: ${s.taskCfg.skill}`:"",c.resultOnly!==void 0?`- resultOnly: ${c.resultOnly}`:"",c.includeThinking!==void 0?`- includeThinking: ${c.includeThinking}`:"",c.preBash?`- preBash(\u5168\u5C40): \`${c.preBash}\``:"",s?.preBash?`- preBash(\u7FA4): \`${s.preBash}\``:"",u].filter(Boolean).join(`
|
|
20
|
+
`)+`
|
|
21
|
+
`,g=path_1.default.join(r,"CLAUDE.md");if(!fs_1.default.existsSync(g)){fs_1.default.writeFileSync(g,m,"utf-8"),console.log(`[${(0,session_1.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u5199\u5165 CLAUDE.md: ${g}`);return}const d=fs_1.default.readFileSync(g,"utf-8"),C=d.indexOf(I),v=d.indexOf(u);if(C!==-1&&v!==-1&&v>C){const A=d.substring(0,C),w=d.substring(v+u.length),k=A+m+w;fs_1.default.writeFileSync(g,k,"utf-8"),console.log(`[${(0,session_1.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u66F4\u65B0: ${g}`)}else fs_1.default.writeFileSync(g,m+`
|
|
22
|
+
`+d,"utf-8"),console.log(`[${(0,session_1.timestamp)()}] cc-ding \u4E0A\u4E0B\u6587\u5DF2\u8FFD\u52A0\u5230\u73B0\u6709 CLAUDE.md: ${g}`)}async function executeClaudeQuery(e,t,i,r){const{skill:s,agent:c,senderNick:I,senderStaffId:u}=r||{};let S=e.getSessionDir(t),m=`${S}/session.log`;const g=e.getConversationDir(t.conversationId);injectSessionContext(e,t),fs_1.default.mkdirSync(S,{recursive:!0});let d=null;const C=(0,api_key_manager_1.readApiKeyFromSettings)(g);if(C&&e.config.apiKeyCfg&&(d=e.config.apiKeyCfg.claudeSettings.find(n=>n.apiKey===C&&n.isValid)||null,d&&console.log(`[${(0,session_1.timestamp)()}] \u4ECE settings-ding.json \u6062\u590D Claude Setting: ${(0,api_key_manager_1.settingLabel)(d)}`)),!(0,api_key_manager_1.getForceEnabledSettingsPath)(g)&&e.config.apiKeyCfg&&(d=(0,api_key_manager_1.pickValidApiKey)(e),!d)){const n=u||t.startStaffId;await(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:n,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 A=I&&u?`${i} \u2500\u2500 \u6D88\u606F\u6765\u81EA: ${I}(${u})`:i;e.appendSessionLog(S,"user",A);const w="claude",R=["--permission-mode",r?.permissionMode??"bypassPermissions","--print","--output-format","stream-json","--verbose"];c&&R.push("--agent",c);const P=s?`/${s} ${A}`:A;let h=0,y=0,E=0;const M=[],F=e.activeSessions.get(t.conversationId),a=n=>{const l=e.activeSessions.get(t.conversationId);return!l||l!==F?(console.log(`[${(0,session_1.timestamp)()}] \u4F1A\u8BDD\u5DF2\u88AB\u7EC8\u6B62\uFF0C${n}`),!1):l.goonPending?(console.log(`[${(0,session_1.timestamp)()}] \u6536\u5230 /goon \u8BF7\u6C42\uFF0C${n}`),!1):!0};for(;;){if(!a("\u505C\u6B62\u91CD\u8BD5"))return;const n=h>0;if(y>=MAX_TOTAL_RETRIES||y>=3&&E>0&&Date.now()-E>MAX_RETRY_DURATION_MS){const $=y>=MAX_TOTAL_RETRIES?`\u603B\u91CD\u8BD5\u6B21\u6570\u5DF2\u8FBE ${MAX_TOTAL_RETRIES} \u6B21`:`\u91CD\u8BD5\u6301\u7EED\u65F6\u95F4\u8D85\u8FC7 ${MAX_RETRY_DURATION_MS/1e3}s\uFF08\u5DF2\u91CD\u8BD5 ${y} \u6B21\uFF09`;console.error(`[${(0,session_1.timestamp)()}] \u68C0\u6D4B\u5230\u65E0\u9650\u91CD\u8BD5\u5FAA\u73AF: ${$}`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: \u68C0\u6D4B\u5230\u65E0\u9650\u91CD\u8BD5\u5FAA\u73AF\uFF0C${$}\uFF0C\u7EC8\u6B62\u91CD\u8BD5
|
|
23
|
+
`,"utf-8");const f=readLastLogLines(m,1),T=M.slice(-1)[0]||"",x=u||t.startStaffId;await(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:x,content:`\u{1F504} \u68C0\u6D4B\u5230 Claude \u9677\u5165\u65E0\u9650\u91CD\u8BD5\uFF0C\u5DF2\u7EC8\u6B62\uFF08${$}\uFF09
|
|
21
24
|
|
|
22
25
|
\u{1F4CB} \u6700\u8FD1\u91CD\u8BD5\u8BB0\u5F55\uFF1A
|
|
23
|
-
${
|
|
26
|
+
${T}
|
|
24
27
|
|
|
25
28
|
\u{1F4DD} \u6700\u8FD1\u65E5\u5FD7\uFF1A
|
|
26
29
|
\`\`\`
|
|
27
|
-
${
|
|
30
|
+
${f}
|
|
28
31
|
\`\`\`
|
|
29
32
|
|
|
30
|
-
\u{1F4A1} \u53EF\u5C1D\u8BD5\u53D1\u9001 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u6216 /end \u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD`});return}const
|
|
31
|
-
`,"utf-8")):
|
|
32
|
-
`,"utf-8");continue}}const
|
|
33
|
+
\u{1F4A1} \u53EF\u5C1D\u8BD5\u53D1\u9001 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u6216 /end \u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD`});return}const l=[...R];t.claudeSessionId&&(l.push("--resume",t.claudeSessionId),n||console.log(`[${(0,session_1.timestamp)()}] \u6062\u590D Claude \u4F1A\u8BDD: ${t.claudeSessionId}`));const p=resolveClaudeSettingsPath(e,g,r?.settings);p&&l.push("--settings",p);let o;n?(o="\u7EE7\u7EED",console.log(`[${(0,session_1.timestamp)()}] \u53D1\u9001"\u7EE7\u7EED"\u91CD\u8BD5 (\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${h}/${MAX_FAST_FAIL}\u6B21)`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\uFF0C\u53D1\u9001"\u7EE7\u7EED"\u91CD\u8BD5 (\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${h}/${MAX_FAST_FAIL})
|
|
34
|
+
`,"utf-8")):o=P,console.log(`[${(0,session_1.timestamp)()}] \u6267\u884C Claude \u67E5\u8BE2[\u539F\u751Fclaude \u6A21\u5F0F]: ${w} ${l.join(" ")}`),e.debugLog(`\u53D1\u9001\u6D88\u606F: ${o.substring(0,100)}...`);try{await runClaudeOnce(e,t,l,w,g,o,n);return}catch($){if(S=e.getSessionDir(t),m=`${S}/session.log`,$ instanceof RetryableApiError){if(y++,E=E||Date.now(),(0,api_key_manager_1.isQuotaExhaustedError)($.output)&&e.config.apiKeyCfg){if(M.push(`[${(0,session_1.timestamp)()}] 429 \u914D\u989D\u8017\u5C3D\uFF0C\u5C1D\u8BD5\u8F6E\u6362 Key`),d){const T=(0,api_key_manager_1.rotateApiKey)(e,d.apiKey);if(T){d=T,h=0,console.log(`[${(0,session_1.timestamp)()}] API Key \u914D\u989D\u8017\u5C3D(429)\uFF0C\u5207\u6362\u5230\u65B0 Key: ${(0,api_key_manager_1.settingLabel)(T)}`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: API Key \u914D\u989D\u8017\u5C3D(429)\uFF0C\u5207\u6362\u5230\u65B0 Key
|
|
35
|
+
`,"utf-8");continue}}const f=u||t.startStaffId;await(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:f,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($.isFastFail){if(h++,h>=MAX_FAST_FAIL){if(d&&e.config.apiKeyCfg){const f=(0,api_key_manager_1.rotateApiKey)(e,d.apiKey);if(f){d=f,h=0,console.log(`[${(0,session_1.timestamp)()}] TPM \u9650\u6D41\u8FDE\u7EED\u5FEB\u901F\u5931\u8D25 ${MAX_FAST_FAIL} \u6B21\uFF0C\u5207\u6362\u5230\u65B0 Key: ${(0,api_key_manager_1.settingLabel)(f)}`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\u8FDE\u7EED\u5FEB\u901F\u5931\u8D25\uFF0C\u5207\u6362\u5230\u65B0 Key
|
|
33
36
|
`,"utf-8");continue}}throw console.log(`[${(0,session_1.timestamp)()}] TPM \u9650\u6D41\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${MAX_FAST_FAIL}\u6B21\uFF0C\u653E\u5F03`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${MAX_FAST_FAIL}\u6B21\uFF0C\u653E\u5F03
|
|
34
|
-
`,"utf-8"),new Error(`TPM \u9650\u6D41\uFF0C\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED ${MAX_FAST_FAIL} \u6B21`)}console.log(`[${(0,session_1.timestamp)()}] \u68C0\u6D4B\u5230 TPM \u9650\u6D41(\u5FEB\u901F\u5931\u8D25)\uFF0C${API_RETRY_DELAY_MS/1e3}s \u540E\u91CD\u8BD5 (${
|
|
35
|
-
`,"utf-8"),
|
|
36
|
-
`,"utf-8"),
|
|
37
|
-
`,"utf-8");const
|
|
38
|
-
`,"utf-8")}catch(
|
|
39
|
-
`,"utf-8"),await(0,messaging_1.sendDingMessage)(
|
|
37
|
+
`,"utf-8"),new Error(`TPM \u9650\u6D41\uFF0C\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED ${MAX_FAST_FAIL} \u6B21`)}console.log(`[${(0,session_1.timestamp)()}] \u68C0\u6D4B\u5230 TPM \u9650\u6D41(\u5FEB\u901F\u5931\u8D25)\uFF0C${API_RETRY_DELAY_MS/1e3}s \u540E\u91CD\u8BD5 (${h}/${MAX_FAST_FAIL})`)}else h=0,console.log(`[${(0,session_1.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${API_RETRY_DELAY_MS/1e3}s \u540E\u91CD\u8BD5`);if(fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: TPM \u9650\u6D41\uFF0C${API_RETRY_DELAY_MS/1e3}s \u540E\u91CD\u8BD5
|
|
38
|
+
`,"utf-8"),M.push(`[${(0,session_1.timestamp)()}] TPM \u9650\u6D41\uFF0C${API_RETRY_DELAY_MS/1e3}s \u540E\u91CD\u8BD5`),await sleep(API_RETRY_DELAY_MS),!a("\u505C\u6B62\u5F53\u524D\u91CD\u8BD5"))return;continue}if($ instanceof ConversationNotFoundError){y++,E=E||Date.now(),M.push(`[${(0,session_1.timestamp)()}] \u4F1A\u8BDD\u5931\u6548\uFF0C\u6E05\u9664\u65E7\u4F1A\u8BDD`),console.log(`[${(0,session_1.timestamp)()}] Claude \u4F1A\u8BDD\u5931\u6548\uFF0C\u6E05\u9664 claudeSessionId \u5E76\u91CD\u65B0\u53D1\u8D77`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: Claude \u4F1A\u8BDD\u5DF2\u5931\u6548\uFF0C\u6E05\u9664\u65E7\u4F1A\u8BDD\u5E76\u91CD\u65B0\u53D1\u8D77
|
|
39
|
+
`,"utf-8"),t.claudeSessionId&&(t.claudeSessionId=void 0,e.updateSessionFile(t,{})),h=0;continue}if($ instanceof ContextWindowExceededError){y++,E=E||Date.now(),M.push(`[${(0,session_1.timestamp)()}] \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u81EA\u52A8 /compact`),console.log(`[${(0,session_1.timestamp)()}] \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u81EA\u52A8\u53D1\u9001 /compact \u538B\u7F29\u4E0A\u4E0B\u6587`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: \u4E0A\u4E0B\u6587\u7A97\u53E3\u8D85\u957F\uFF0C\u81EA\u52A8\u53D1\u9001 /compact \u538B\u7F29\u4E0A\u4E0B\u6587
|
|
40
|
+
`,"utf-8");const f=u||t.startStaffId;await(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:f,content:"\u{1F4E6} \u4E0A\u4E0B\u6587\u8D85\u957F\uFF0C\u6B63\u5728\u81EA\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587(/compact)\u540E\u7EE7\u7EED..."});const T=[...R];t.claudeSessionId&&T.push("--resume",t.claudeSessionId);const x=resolveClaudeSettingsPath(e,g,r?.settings);x&&T.push("--settings",x);try{await runClaudeOnce(e,t,T,w,g,"/compact",!1),console.log(`[${(0,session_1.timestamp)()}] /compact \u6267\u884C\u6210\u529F\uFF0C\u53D1\u9001"\u7EE7\u7EED"\u6062\u590D\u6267\u884C`),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: /compact \u6267\u884C\u6210\u529F\uFF0C\u53D1\u9001"\u7EE7\u7EED"\u6062\u590D\u6267\u884C
|
|
41
|
+
`,"utf-8")}catch(b){throw console.error(`[${(0,session_1.timestamp)()}] /compact \u6267\u884C\u5931\u8D25:`,b),fs_1.default.appendFileSync(m,`[${(0,session_1.timestamp)()}] [SYSTEM]: /compact \u6267\u884C\u5931\u8D25: ${b instanceof Error?b.message:String(b)}
|
|
42
|
+
`,"utf-8"),await(0,messaging_1.sendDingMessage)(e,{conversationId:(0,session_1.getReplyConversationId)(t),sessionWebhook:(0,session_1.getReplyWebhook)(t),atUserId:f,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: ${b instanceof Error?b.message:String(b)}`)}h=0;continue}throw $}}}
|
package/dist/src/biz/commands.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseHelpCommand=parseHelpCommand,exports.parseCommandHelp=parseCommandHelp,exports.getCommandByName=getCommandByName,exports.formatHelpOverview=formatHelpOverview,exports.formatCommandHelp=formatCommandHelp,exports.parseEndCommand=parseEndCommand,exports.parseInfoCommand=parseInfoCommand,exports.formatConversationInfo=formatConversationInfo,exports.formatGlobalConfig=formatGlobalConfig,exports.parseLogCommand=parseLogCommand,exports.parseLsCommand=parseLsCommand,exports.findSubdirByName=findSubdirByName,exports.getDirectoryStructure=getDirectoryStructure,exports.parseContinueSessionCommand=parseContinueSessionCommand,exports.parseCronCommand=parseCronCommand,exports.parsePwdCommand=parsePwdCommand,exports.parseVersionCommand=parseVersionCommand,exports.parseMkdirCommand=parseMkdirCommand,exports.parseTouchCommand=parseTouchCommand,exports.parseRmCommand=parseRmCommand,exports.parseOpenCommand=parseOpenCommand,exports.parseCleanCommand=parseCleanCommand,exports.parseResetApiKeyCfgCommand=parseResetApiKeyCfgCommand,exports.parseCfgCommand=parseCfgCommand,exports.parseBashCommand=parseBashCommand,exports.parseMqCommand=parseMqCommand,exports.parseAuthCommand=parseAuthCommand,exports.parseRecorderCommand=parseRecorderCommand,exports.parseGoonCommand=parseGoonCommand,exports.parseCcCommand=parseCcCommand,exports.parseClaudeMdCommand=parseClaudeMdCommand,exports.parseInterruptCommand=parseInterruptCommand,exports.parseTodoCommand=parseTodoCommand,exports.parseMenuCommand=parseMenuCommand,exports.parseRebootCommand=parseRebootCommand,exports.parseRecorderCommandEnhanced=parseRecorderCommandEnhanced;const fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),COMMAND_REGISTRY=[{name:"/help",description:"\u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4",usage:"/help",examples:["/help"],category:"\u7CFB\u7EDF"},{name:"/info",description:"\u67E5\u770B\u7FA4\u914D\u7F6E\u3001\u4F1A\u8BDD\u548C\u4EFB\u52A1\u4FE1\u606F",usage:"/info [robot|session|task]",examples:["/info","/info robot","/info session","/info task"],category:"\u7CFB\u7EDF"},{name:"/log",description:"\u67E5\u770B\u6700\u8FD1\u4F1A\u8BDD\u65E5\u5FD7",usage:"/log [\u884C\u6570]",examples:["/log","/log 20"],category:"\u4F1A\u8BDD"},{name:"/new",description:"\u5F00\u59CB\u65B0\u7684\u5BF9\u8BDD\u4F1A\u8BDD(\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD)",usage:"/new [\u521D\u59CB\u6D88\u606F]",examples:["/new","/new \u5E2E\u6211\u5206\u6790\u4E00\u4E0B\u8FD9\u4E2A\u9879\u76EE"],category:"\u4F1A\u8BDD"},{name:"/resume",description:"\u7EE7\u7EED\u6307\u5B9A\u7684\u5386\u53F2\u4F1A\u8BDD(\u53EF\u6307\u5B9A\u4F1A\u8BDDID,\u4E0D\u6307\u5B9A\u5219\u6062\u590D\u6700\u8FD1\u4E00\u4E2A)",usage:"/resume [\u4F1A\u8BDDID]",examples:["/resume","/resume abc123"],category:"\u4F1A\u8BDD"},{name:"/end",description:"\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD",usage:"/end",examples:["/end"],category:"\u4F1A\u8BDD"},{name:"/goon",description:'\u5F3A\u5236\u91CD\u542F Claude \u8FDB\u7A0B\u5E76\u53D1\u9001"\u7EE7\u7EED"\u6062\u590D\u6267\u884C',usage:"/goon",examples:["/goon"],category:"\u4F1A\u8BDD"},{name:"/cc",description:"\u76F4\u63A5\u900F\u4F20\u6D88\u606F\u7ED9 Claude\uFF08\u4E0D\u9644\u52A0\u53D1\u9001\u4EBA\u4FE1\u606F\uFF09",usage:"/cc <\u6D88\u606F>",examples:["/cc \u7EE7\u7EED","/cc /compact"],category:"\u4F1A\u8BDD"},{name:"/task",description:"\u63D0\u4EA4\u4EFB\u52A1\u5230\u961F\u5217",usage:"/task <\u4EFB\u52A1\u63CF\u8FF0>",examples:["/task \u5E2E\u6211\u91CD\u6784\u767B\u5F55\u6A21\u5757"],category:"\u4EFB\u52A1"},{name:"/mq",description:"\u67E5\u770B\u548C\u7BA1\u7406\u5F53\u524D\u4F1A\u8BDD\u6D88\u606F\u961F\u5217",usage:"/mq | /mq front | /mq rm <\u5E8F\u53F7> | /mq rm <1-3> | /mq -n <\u6570\u91CF> | /mq -all",examples:["/mq","/mq front","/mq rm 1","/mq rm 1-3","/mq rm 1 3 5","/mq -n 1","/mq -all"],category:"\u4EFB\u52A1"},{name:"/cron",description:"\u521B\u5EFA\u548C\u7BA1\u7406\u5B9A\u65F6\u4EFB\u52A1(Claude\u81EA\u52A8\u5206\u6790\u81EA\u7136\u8BED\u8A00)",usage:"/cron <\u81EA\u7136\u8BED\u8A00\u63CF\u8FF0> | /cron <cron\u8868\u8FBE\u5F0F> <\u4EFB\u52A1\u63CF\u8FF0> | /cron list|pause|resume|delete <id>",examples:["/cron \u6BCF\u5929\u65E9\u4E0A9\u70B9\u67E5\u770Bdima\u4EFB\u52A1","/cron 0 9 * * * \u67E5\u770Bdima\u4EFB\u52A1","/cron list","/cron pause cron_123","/cron delete cron_123"],category:"\u4EFB\u52A1"},{name:"/pwd",description:"\u663E\u793A\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u7684\u7EDD\u5BF9\u8DEF\u5F84",usage:"/pwd",examples:["/pwd"],category:"\u6587\u4EF6"},{name:"/ls",description:"\u67E5\u770B\u5DE5\u4F5C\u76EE\u5F55\u7ED3\u6784",usage:"/ls [\u76EE\u6807\u76EE\u5F55] [\u5C55\u5F00\u5C42\u6570]",examples:["/ls","/ls root 2","/ls product 1"],category:"\u6587\u4EF6"},{name:"/mkdir",description:"\u5728\u5DE5\u4F5C\u76EE\u5F55\u4E0B\u521B\u5EFA\u6587\u4EF6\u5939\uFF08\u652F\u6301\u76F8\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u8D85\u51FA\u5DE5\u4F5C\u76EE\u5F55\u8303\u56F4\uFF09",usage:"/mkdir <\u76F8\u5BF9\u8DEF\u5F84>",examples:["/mkdir src","/mkdir src/components","/mkdir ./docs"],category:"\u6587\u4EF6"},{name:"/touch",description:"\u5728\u5DE5\u4F5C\u76EE\u5F55\u4E0B\u521B\u5EFA\u7A7A\u6587\u4EF6\uFF08\u652F\u6301\u76F8\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u8D85\u51FA\u5DE5\u4F5C\u76EE\u5F55\u8303\u56F4\uFF09",usage:"/touch <\u76F8\u5BF9\u8DEF\u5F84>",examples:["/touch README.md","/touch src/cc-ding-cli.ts","/touch ./config.json"],category:"\u6587\u4EF6"},{name:"/rm",description:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55\u4E0B\u7684\u6587\u4EF6\u6216\u76EE\u5F55\uFF08\u652F\u6301\u76F8\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u8D85\u51FA\u5DE5\u4F5C\u76EE\u5F55\u8303\u56F4\uFF09",usage:"/rm <\u76F8\u5BF9\u8DEF\u5F84>",examples:["/rm temp.txt","/rm src/old.ts","/rm ./docs/obsolete/"],category:"\u6587\u4EF6"},{name:"/claude.md",description:"\u67E5\u770B\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u7684 CLAUDE.md \u6587\u4EF6\u5185\u5BB9",usage:"/claude.md",examples:["/claude.md"],category:"\u6587\u4EF6"},{name:"/version",description:"\u67E5\u770B\u5DE5\u5177\u7248\u672C\u4FE1\u606F",usage:"/version",examples:["/version"],category:"\u7CFB\u7EDF"},{name:"/open",description:"\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u3001\u7EC8\u7AEF\u6216VS Code\u4E2D\u6253\u5F00\u5DE5\u4F5C\u76EE\u5F55",usage:"/open [shell|code]",examples:["/open","/open shell","/open code"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/clean",description:"\u6E05\u9664\u5386\u53F2\u4F1A\u8BDD\u548C\u7F13\u5B58(.sessions/.tasks/.images/.playwright-cli)",usage:"/clean",examples:["/clean"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/reset-apikeycfg",description:"\u91CD\u7F6EAPI Key\u914D\u7F6E(\u5C06\u6240\u6709Key\u6807\u8BB0\u4E3A\u6709\u6548)",usage:"/reset-apikeycfg",examples:["/reset-apikeycfg"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/cfg",description:"\u6CE8\u518C\u5F53\u524D\u7FA4\u5230\u914D\u7F6E\uFF0C\u6216\u5237\u65B0\u6307\u5B9A\u5B57\u6BB5(\u5DF2\u6CE8\u518C\u7FA4)",usage:'/cfg [--conversationId xxx] [--dingToken xxx] [--linkConversationId yyy] [--whiteUserList 138xxxx,139xxxx] [--conversationTitle \u540D\u79F0] [--atSender true|false] [--receiveReply true|false] [--preBash "\u547D\u4EE4"]',examples:["/cfg","/cfg --dingToken myToken --whiteUserList 13800138000,13900139000","/cfg --conversationTitle \u5DE5\u4F5C\u7FA4","/cfg --whiteUserList 13800138000","/cfg --atSender false","/cfg --receiveReply false",'/cfg --preBash "source .env"',"/cfg --conversationId targetConvId --dingToken xxx --conversationTitle \u76EE\u6807\u7FA4"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/bash",description:"\u5728\u5DE5\u4F5C\u76EE\u5F55\u6267\u884C bash \u547D\u4EE4\uFF08\u5982\u914D\u7F6E\u4E86 preBash \u5168\u5C40/\u7FA4\u7EA7\u522B\uFF0C\u5C06\u53E0\u52A0\u524D\u7F6E\u6267\u884C\uFF09",usage:"/bash <\u547D\u4EE4>",examples:["/bash ls -la","/bash pwd","/bash git status"],category:"\u6587\u4EF6"},{name:"/auth",description:"\u7BA1\u7406\u767D\u540D\u5355\u548C\u7BA1\u7406\u5458(add/del/rm/admin,\u9ED8\u8BA4list)",usage:"/auth [add|del|rm <\u624B\u673A\u53F7\u6216userId>] | /auth admin [add|rm <\u624B\u673A\u53F7\u6216userId>] | /auth [approve|reject <requestId>]",examples:["/auth","/auth add 13800138000","/auth rm 13800138000","/auth admin add 13800138000","/auth admin rm 13800138000","/auth admin","/auth approve r1234"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/recorder",aliases:["/r"],description:"Recorder \u6A21\u5F0F\uFF1A\u8BB0\u5F55\u6240\u6709\u6D88\u606F\u5230\u672C\u5730\uFF08\u4EC5 owner \u5355\u804A\uFF09",usage:"/recorder [on|exit]",examples:["/recorder on","/recorder exit","/r on","/r exit"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/todo",description:"\u5F85\u529E\u7BA1\u7406\uFF1A\u6DFB\u52A0/\u5B8C\u6210/\u5220\u9664/\u5217\u8868/\u63D0\u9192",usage:"/todo <\u5185\u5BB9> [@\u4EBA] [ddl \u622A\u6B62\u65F6\u95F4] | /todo done <\u5E8F\u53F7> | /todo rm <\u5E8F\u53F7|all> | /todo list | /todo remind <0-23>",examples:["/todo \u5B8C\u6210\u62A5\u544A ddl \u660E\u5929","/todo \u4FEE\u590Dbug @\u5F20\u4E09 ddl \u4E0B\u5468\u4E94","/todo done 1","/todo rm 2","/todo rm all","/todo list","/todo remind 9","/todo remind -1"],category:"\u4EFB\u52A1"},{name:"/menu",description:"\u5FEB\u6377\u6307\u4EE4\u83DC\u5355\uFF1A\u81EA\u5B9A\u4E49\u5E38\u7528\u6307\u4EE4\uFF0C\u56DE\u590D\u5E8F\u53F7\u6267\u884C",usage:"/menu add <\u6307\u4EE4> | /menu del <\u5E8F\u53F7> | /menu list | /menu trigger <\u8BCD> | /menu -g add/del/list",examples:["/menu add /help","/menu add /cron \u6BCF\u5929\u65E9\u4E0A9\u70B9\u67E5\u770Bdima","/menu del 1","/menu list","/menu trigger go","/menu -g add /info robot","/menu -g del 1"],category:"\u7CFB\u7EDF"},{name:"/!",description:"\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1\u5E76\u7ACB\u5373\u5904\u7406\u65B0\u6D88\u606F",usage:"/!",examples:["/!"],category:"\u4F1A\u8BDD"},{name:"/reboot",description:"\u91CD\u542F cc-ding \u5E94\u7528\uFF08\u9700 pm2 \u90E8\u7F72\uFF09",usage:"/reboot [--update [tag]]",examples:["/reboot","/reboot --update","/reboot --update beta"],category:"\u7BA1\u7406",ownerOnly:!0}],CATEGORY_DISPLAY=[{category:"\u4F1A\u8BDD",icon:"\u{1F4AC}"},{category:"\u4EFB\u52A1",icon:"\u{1F4CB}"},{category:"\u6587\u4EF6",icon:"\u{1F4C2}"},{category:"\u7CFB\u7EDF",icon:"\u2699\uFE0F"},{category:"\u7BA1\u7406",icon:"\u{1F527}"}];function parseHelpCommand(e){return e.trim().toLowerCase()==="/help"}function parseCommandHelp(e){const r=e.trim().match(/^(\/\w+)\s+--help$/i);return r?r[1].toLowerCase():null}function getCommandByName(e){const t=e.toLowerCase();return COMMAND_REGISTRY.find(r=>r.name.toLowerCase()===t||r.aliases?.some(s=>s.toLowerCase()===t))}function formatHelpOverview(e,t){const r=COMMAND_REGISTRY.filter(n=>t||!n.ownerOnly),s=["### \u{1F917}","----",`- **\u7248\u672C:** ${e}`,"- **\u4F5C\u8005:** yihuineng","- **Github:** https://github.com/yihuineng/cc-ding","----"];for(const{category:n,icon:o}of CATEGORY_DISPLAY){const i=r.filter(a=>a.category===n);if(i.length!==0){s.push(`${o} **${n}**`);for(const a of i)s.push(`- \`${a.name}\` ${a.description}`);s.push("")}}return s.push("\u{1F4A1} \u8F93\u5165 `/{\u547D\u4EE4} --help` \u67E5\u770B\u547D\u4EE4\u8BE6\u7EC6\u7528\u6CD5"),s.join(`
|
|
2
|
-
`)}function formatCommandHelp(e){const t=[`### \u{1F4D6} ${e.name}`,"",`**\u63CF\u8FF0:** ${e.description}`,"",`**\u7528\u6CD5:** \`${e.usage}\``];e.aliases?.length&&t.push("",`**\u522B\u540D:** ${e.aliases.join(", ")}`),t.push("","**\u793A\u4F8B:**");for(const
|
|
3
|
-
`)}function parseEndCommand(e){return e.trim().toLowerCase()==="/end"}function parseInfoCommand(e){const t=e.trim().toLowerCase();return t==="/info"?"all":t==="/info robot"?"robot":t==="/info session"?"session":t==="/info task"?"task":null}function formatConversationInfo(e,t,
|
|
4
|
-
`)}function formatGlobalConfig(e){const t=[`- **clientName:** ${e.clientName||"-"}`,`- **sessionMaxConcurrency:** ${e.sessionMaxConcurrency??5}`,`- **taskHandlerCount:** ${e.taskHandlerCount??1}`,`- **taskQueueSize:** ${e.taskQueueSize??50}`,`- **includeThinking:** ${e.includeThinking??!1}`,`- **resultOnly:** ${e.resultOnly??!0}`];if(e.defaultDingToken&&t.push(`- **defaultDingToken:** ${e.defaultDingToken.substring(0,8)}...`),e.owner&&t.push(`- **owner:** ${e.owner}`),e.whiteUserList?.length&&t.push(`- **\u5168\u5C40\u767D\u540D\u5355:** ${e.whiteUserList.join(", ")}`),e.apiKeyCfg){const
|
|
5
|
-
`)}function parseLogCommand(e){const
|
|
6
|
-
`)}catch{return t===0?"\u274C \u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55":""}}function parseContinueSessionCommand(e){const t=e.trim().match(/^\/resume(?:\s+(\S+))?$/i);return t?t[1]!==void 0?t[1]:"":null}function looksLikeCronExpression(e){const t=e.trim().split(/\s+/);return t.length!==5?!1:t.every(
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseHelpCommand=parseHelpCommand,exports.parseCommandHelp=parseCommandHelp,exports.getCommandByName=getCommandByName,exports.formatHelpOverview=formatHelpOverview,exports.formatCommandHelp=formatCommandHelp,exports.parseEndCommand=parseEndCommand,exports.parseInfoCommand=parseInfoCommand,exports.formatConversationInfo=formatConversationInfo,exports.formatGlobalConfig=formatGlobalConfig,exports.parseLogCommand=parseLogCommand,exports.parseLsCommand=parseLsCommand,exports.findSubdirByName=findSubdirByName,exports.getDirectoryStructure=getDirectoryStructure,exports.parseContinueSessionCommand=parseContinueSessionCommand,exports.parseCronCommand=parseCronCommand,exports.parseVersionCommand=parseVersionCommand,exports.parseOpenCommand=parseOpenCommand,exports.parseCleanCommand=parseCleanCommand,exports.parseResetApiKeyCfgCommand=parseResetApiKeyCfgCommand,exports.parseCfgCommand=parseCfgCommand,exports.parseBashCommand=parseBashCommand,exports.parseMqCommand=parseMqCommand,exports.parseAuthCommand=parseAuthCommand,exports.parseRecorderCommand=parseRecorderCommand,exports.parseGoonCommand=parseGoonCommand,exports.parseCcCommand=parseCcCommand,exports.parseClaudeMdCommand=parseClaudeMdCommand,exports.parseInterruptCommand=parseInterruptCommand,exports.parseTodoCommand=parseTodoCommand,exports.parseMenuCommand=parseMenuCommand,exports.parseRebootCommand=parseRebootCommand,exports.parseRecorderCommandEnhanced=parseRecorderCommandEnhanced;const fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),COMMAND_REGISTRY=[{name:"/help",description:"\u67E5\u770B\u6240\u6709\u53EF\u7528\u547D\u4EE4",usage:"/help",examples:["/help"],category:"\u7CFB\u7EDF"},{name:"/info",description:"\u67E5\u770B\u7FA4\u914D\u7F6E\u3001\u4F1A\u8BDD\u548C\u4EFB\u52A1\u4FE1\u606F",usage:"/info [robot|session|task]",examples:["/info","/info robot","/info session","/info task"],category:"\u7CFB\u7EDF"},{name:"/log",description:"\u67E5\u770B\u6700\u8FD1\u4F1A\u8BDD\u65E5\u5FD7",usage:"/log [\u884C\u6570]",examples:["/log","/log 20"],category:"\u4F1A\u8BDD"},{name:"/new",description:"\u5F00\u59CB\u65B0\u7684\u5BF9\u8BDD\u4F1A\u8BDD(\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD)",usage:"/new [\u521D\u59CB\u6D88\u606F]",examples:["/new","/new \u5E2E\u6211\u5206\u6790\u4E00\u4E0B\u8FD9\u4E2A\u9879\u76EE"],category:"\u4F1A\u8BDD"},{name:"/resume",description:"\u7EE7\u7EED\u6307\u5B9A\u7684\u5386\u53F2\u4F1A\u8BDD(\u53EF\u6307\u5B9A\u4F1A\u8BDDID,\u4E0D\u6307\u5B9A\u5219\u6062\u590D\u6700\u8FD1\u4E00\u4E2A)",usage:"/resume [\u4F1A\u8BDDID]",examples:["/resume","/resume abc123"],category:"\u4F1A\u8BDD"},{name:"/end",description:"\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD",usage:"/end",examples:["/end"],category:"\u4F1A\u8BDD"},{name:"/goon",description:'\u5F3A\u5236\u91CD\u542F Claude \u8FDB\u7A0B\u5E76\u53D1\u9001"\u7EE7\u7EED"\u6062\u590D\u6267\u884C',usage:"/goon",examples:["/goon"],category:"\u4F1A\u8BDD"},{name:"/cc",description:"\u76F4\u63A5\u900F\u4F20\u6D88\u606F\u7ED9 Claude\uFF08\u4E0D\u9644\u52A0\u53D1\u9001\u4EBA\u4FE1\u606F\uFF09",usage:"/cc <\u6D88\u606F>",examples:["/cc \u7EE7\u7EED","/cc /compact"],category:"\u4F1A\u8BDD"},{name:"/task",description:"\u63D0\u4EA4\u4EFB\u52A1\u5230\u961F\u5217",usage:"/task <\u4EFB\u52A1\u63CF\u8FF0>",examples:["/task \u5E2E\u6211\u91CD\u6784\u767B\u5F55\u6A21\u5757"],category:"\u4EFB\u52A1"},{name:"/mq",description:"\u67E5\u770B\u548C\u7BA1\u7406\u5F53\u524D\u4F1A\u8BDD\u6D88\u606F\u961F\u5217",usage:"/mq | /mq front | /mq rm <\u5E8F\u53F7> | /mq rm <1-3> | /mq -n <\u6570\u91CF> | /mq -all",examples:["/mq","/mq front","/mq rm 1","/mq rm 1-3","/mq rm 1 3 5","/mq -n 1","/mq -all"],category:"\u4EFB\u52A1"},{name:"/cron",description:"\u521B\u5EFA\u548C\u7BA1\u7406\u5B9A\u65F6\u4EFB\u52A1(Claude\u81EA\u52A8\u5206\u6790\u81EA\u7136\u8BED\u8A00)",usage:"/cron <\u81EA\u7136\u8BED\u8A00\u63CF\u8FF0> | /cron <cron\u8868\u8FBE\u5F0F> <\u4EFB\u52A1\u63CF\u8FF0> | /cron list|pause|resume|delete <id>",examples:["/cron \u6BCF\u5929\u65E9\u4E0A9\u70B9\u67E5\u770Bdima\u4EFB\u52A1","/cron 0 9 * * * \u67E5\u770Bdima\u4EFB\u52A1","/cron list","/cron pause cron_123","/cron delete cron_123"],category:"\u4EFB\u52A1"},{name:"/ls",description:"\u67E5\u770B\u5DE5\u4F5C\u76EE\u5F55\u7ED3\u6784",usage:"/ls [\u76EE\u6807\u76EE\u5F55] [\u5C55\u5F00\u5C42\u6570]",examples:["/ls","/ls root 2","/ls product 1"],category:"\u6587\u4EF6"},{name:"/claude.md",description:"\u67E5\u770B\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u7684 CLAUDE.md \u6587\u4EF6\u5185\u5BB9",usage:"/claude.md",examples:["/claude.md"],category:"\u6587\u4EF6"},{name:"/version",description:"\u67E5\u770B\u5DE5\u5177\u7248\u672C\u4FE1\u606F",usage:"/version",examples:["/version"],category:"\u7CFB\u7EDF"},{name:"/open",description:"\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u3001\u7EC8\u7AEF\u6216VS Code\u4E2D\u6253\u5F00\u5DE5\u4F5C\u76EE\u5F55",usage:"/open [shell|code]",examples:["/open","/open shell","/open code"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/clean",description:"\u6E05\u9664\u5386\u53F2\u4F1A\u8BDD\u548C\u7F13\u5B58(.sessions/.tasks/.images/.playwright-cli)",usage:"/clean",examples:["/clean"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/reset-apikeycfg",description:"\u91CD\u7F6EAPI Key\u914D\u7F6E(\u5C06\u6240\u6709Key\u6807\u8BB0\u4E3A\u6709\u6548)",usage:"/reset-apikeycfg",examples:["/reset-apikeycfg"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/cfg",description:"\u6CE8\u518C\u5F53\u524D\u7FA4\u5230\u914D\u7F6E\uFF0C\u6216\u5237\u65B0\u6307\u5B9A\u5B57\u6BB5(\u5DF2\u6CE8\u518C\u7FA4)",usage:'/cfg [--conversationId xxx] [--dingToken xxx] [--linkConversationId yyy] [--whiteUserList 138xxxx,139xxxx] [--conversationTitle \u540D\u79F0] [--atSender true|false] [--receiveReply true|false] [--preBash "\u547D\u4EE4"] [--permissionMode mode]',examples:["/cfg","/cfg --dingToken myToken --whiteUserList 13800138000,13900139000","/cfg --conversationTitle \u5DE5\u4F5C\u7FA4","/cfg --whiteUserList 13800138000","/cfg --atSender false","/cfg --receiveReply false",'/cfg --preBash "source .env"',"/cfg --permissionMode auto","/cfg --conversationId targetConvId --dingToken xxx --conversationTitle \u76EE\u6807\u7FA4"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/bash",description:"\u5728\u5DE5\u4F5C\u76EE\u5F55\u6267\u884C bash \u547D\u4EE4\uFF08\u5982\u914D\u7F6E\u4E86 preBash \u5168\u5C40/\u7FA4\u7EA7\u522B\uFF0C\u5C06\u53E0\u52A0\u524D\u7F6E\u6267\u884C\uFF09",usage:"/bash <\u547D\u4EE4>",examples:["/bash ls -la","/bash pwd","/bash git status"],category:"\u6587\u4EF6"},{name:"/auth",description:"\u7BA1\u7406\u767D\u540D\u5355\u548C\u7BA1\u7406\u5458(add/del/rm/admin,\u9ED8\u8BA4list)",usage:"/auth [add|del|rm <\u624B\u673A\u53F7\u6216userId>] | /auth admin [add|rm <\u624B\u673A\u53F7\u6216userId>] | /auth [approve|reject <requestId>]",examples:["/auth","/auth add 13800138000","/auth rm 13800138000","/auth admin add 13800138000","/auth admin rm 13800138000","/auth admin","/auth approve r1234"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/recorder",aliases:["/r"],description:"Recorder \u6A21\u5F0F\uFF1A\u8BB0\u5F55\u6240\u6709\u6D88\u606F\u5230\u672C\u5730\uFF08\u4EC5 owner \u5355\u804A\uFF09",usage:"/recorder [on|exit]",examples:["/recorder on","/recorder exit","/r on","/r exit"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/todo",description:"\u5F85\u529E\u7BA1\u7406\uFF1A\u6DFB\u52A0/\u5B8C\u6210/\u5220\u9664/\u5217\u8868/\u63D0\u9192",usage:"/todo <\u5185\u5BB9> [@\u4EBA] [ddl \u622A\u6B62\u65F6\u95F4] | /todo done <\u5E8F\u53F7> | /todo rm <\u5E8F\u53F7|all> | /todo list | /todo remind <0-23>",examples:["/todo \u5B8C\u6210\u62A5\u544A ddl \u660E\u5929","/todo \u4FEE\u590Dbug @\u5F20\u4E09 ddl \u4E0B\u5468\u4E94","/todo done 1","/todo rm 2","/todo rm all","/todo list","/todo remind 9","/todo remind -1"],category:"\u4EFB\u52A1"},{name:"/menu",description:"\u5FEB\u6377\u6307\u4EE4\u83DC\u5355\uFF1A\u81EA\u5B9A\u4E49\u5E38\u7528\u6307\u4EE4\uFF0C\u56DE\u590D\u5E8F\u53F7\u6267\u884C",usage:"/menu add <\u6307\u4EE4> | /menu del <\u5E8F\u53F7> | /menu list | /menu trigger <\u8BCD> | /menu -g add/del/list",examples:["/menu add /help","/menu add /cron \u6BCF\u5929\u65E9\u4E0A9\u70B9\u67E5\u770Bdima","/menu del 1","/menu list","/menu trigger go","/menu -g add /info robot","/menu -g del 1"],category:"\u7CFB\u7EDF"},{name:"/!",description:"\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1\u5E76\u7ACB\u5373\u5904\u7406\u65B0\u6D88\u606F",usage:"/!",examples:["/!"],category:"\u4F1A\u8BDD"},{name:"/reboot",description:"\u91CD\u542F cc-ding \u5E94\u7528\uFF08\u9700 pm2 \u90E8\u7F72\uFF09",usage:"/reboot [--update [tag]]",examples:["/reboot","/reboot --update","/reboot --update beta"],category:"\u7BA1\u7406",ownerOnly:!0}],CATEGORY_DISPLAY=[{category:"\u4F1A\u8BDD",icon:"\u{1F4AC}"},{category:"\u4EFB\u52A1",icon:"\u{1F4CB}"},{category:"\u6587\u4EF6",icon:"\u{1F4C2}"},{category:"\u7CFB\u7EDF",icon:"\u2699\uFE0F"},{category:"\u7BA1\u7406",icon:"\u{1F527}"}];function parseHelpCommand(e){return e.trim().toLowerCase()==="/help"}function parseCommandHelp(e){const n=e.trim().match(/^(\/\w+)\s+--help$/i);return n?n[1].toLowerCase():null}function getCommandByName(e){const t=e.toLowerCase();return COMMAND_REGISTRY.find(n=>n.name.toLowerCase()===t||n.aliases?.some(s=>s.toLowerCase()===t))}function formatHelpOverview(e,t){const n=COMMAND_REGISTRY.filter(r=>t||!r.ownerOnly),s=["### \u{1F917}","----",`- **\u7248\u672C:** ${e}`,"- **\u4F5C\u8005:** yihuineng","- **Github:** https://github.com/yihuineng/cc-ding","----"];for(const{category:r,icon:o}of CATEGORY_DISPLAY){const i=n.filter(a=>a.category===r);if(i.length!==0){s.push(`${o} **${r}**`);for(const a of i)s.push(`- \`${a.name}\` ${a.description}`);s.push("")}}return s.push("\u{1F4A1} \u8F93\u5165 `/{\u547D\u4EE4} --help` \u67E5\u770B\u547D\u4EE4\u8BE6\u7EC6\u7528\u6CD5"),s.join(`
|
|
2
|
+
`)}function formatCommandHelp(e){const t=[`### \u{1F4D6} ${e.name}`,"",`**\u63CF\u8FF0:** ${e.description}`,"",`**\u7528\u6CD5:** \`${e.usage}\``];e.aliases?.length&&t.push("",`**\u522B\u540D:** ${e.aliases.join(", ")}`),t.push("","**\u793A\u4F8B:**");for(const n of e.examples)t.push(`- \`${n}\``);return t.join(`
|
|
3
|
+
`)}function parseEndCommand(e){return e.trim().toLowerCase()==="/end"}function parseInfoCommand(e){const t=e.trim().toLowerCase();return t==="/info"?"all":t==="/info robot"?"robot":t==="/info session"?"session":t==="/info task"?"task":null}function formatConversationInfo(e,t,n,s){const r=[`- **\u7FA4ID:** ${t}`];if(e.conversationTitle&&r.push(`- **\u7FA4\u540D\u79F0:** ${e.conversationTitle}`),e.conversationType&&r.push(`- **\u4F1A\u8BDD\u7C7B\u578B:** ${e.conversationType==="1"?"\u5355\u804A":e.conversationType==="2"?"\u7FA4\u804A":e.conversationType}`),s&&r.push(`- **\u5DE5\u4F5C\u76EE\u5F55:** \`${s}\``),e.linkConversationId&&r.push(`- **\u5173\u8054\u4F1A\u8BDDID:** ${e.linkConversationId}`),e.agent&&r.push(`- **agent:** ${e.agent}`),e.dingToken&&r.push(`- **dingToken:** ${e.dingToken.substring(0,8)}...`),e.whiteUserList?.length){const o=e.whiteUserList.map(i=>n?.(i)||i).join(", ");r.push(`- **\u7FA4\u767D\u540D\u5355:** ${o}`)}return e.atSender===!1&&r.push("- **atSender:** false"),e.receiveReply===!1&&r.push("- **receiveReply:** false (\u4E0D\u56DE\u590D\u786E\u8BA4\u6D88\u606F)"),e.useLocalOcr===!1&&r.push("- **\u672C\u5730OCR:** \u5173\u95ED"),e.permissionMode&&r.push(`- **permissionMode:** ${e.permissionMode}`),e.taskCfg?.skill&&r.push(`- **taskSkill:** ${e.taskCfg.skill}`),e.preBash&&r.push(`- **preBash:** \`${e.preBash}\``),r.join(`
|
|
4
|
+
`)}function formatGlobalConfig(e){const t=[`- **clientName:** ${e.clientName||"-"}`,`- **sessionMaxConcurrency:** ${e.sessionMaxConcurrency??5}`,`- **taskHandlerCount:** ${e.taskHandlerCount??1}`,`- **taskQueueSize:** ${e.taskQueueSize??50}`,`- **includeThinking:** ${e.includeThinking??!1}`,`- **resultOnly:** ${e.resultOnly??!0}`];if(e.defaultDingToken&&t.push(`- **defaultDingToken:** ${e.defaultDingToken.substring(0,8)}...`),e.owner&&t.push(`- **owner:** ${e.owner}`),e.whiteUserList?.length&&t.push(`- **\u5168\u5C40\u767D\u540D\u5355:** ${e.whiteUserList.join(", ")}`),e.apiKeyCfg){const n=e.apiKeyCfg.claudeSettings.filter(s=>s.isValid).length;t.push(`- **apiKeyCfg:** ${n}/${e.apiKeyCfg.claudeSettings.length} \u6709\u6548`),t.push(` - **\u6700\u8FD1\u91CD\u7F6E:** ${e.apiKeyCfg.resetTime||"-"}`)}return t.join(`
|
|
5
|
+
`)}function parseLogCommand(e){const n=e.trim().match(/^\/log(?:\s+(\d+))?$/i);if(!n)return null;const s=parseInt(n[1],10);return isNaN(s)||s<=0?10:s}function parseLsCommand(e){const n=e.trim().match(/^\/ls(?:\s+(.+))?$/i);if(!n)return null;if(n[1]===void 0)return{target:"",depth:1};const s=n[1].trim().split(/\s+/),r=s[0]||"",o=s[1]?parseInt(s[1],10):1;return{target:r,depth:isNaN(o)||o<0?1:Math.min(o,5)}}function findSubdirByName(e,t,n=3){const s=[{dir:e,depth:0}];for(;s.length>0;){const{dir:r,depth:o}=s.shift();if(!(o>n))try{const i=fs_1.default.readdirSync(r,{withFileTypes:!0});for(const a of i)if(!(!a.isDirectory()||a.name.startsWith("."))){if(a.name===t)return path_1.default.join(r,a.name);s.push({dir:path_1.default.join(r,a.name),depth:o+1})}}catch{continue}}return null}function getDirectoryStructure(e,t=0,n=1){try{const s=fs_1.default.readdirSync(e,{withFileTypes:!0}).filter(i=>!i.name.startsWith("."));if(s.length===0)return t===0?"\u{1F4C2} \u76EE\u5F55\u4E3A\u7A7A":"";s.sort((i,a)=>i.isDirectory()!==a.isDirectory()?i.isDirectory()?-1:1:i.name.localeCompare(a.name));const r=[],o=". ".repeat(t);for(const i of s){const a=i.isDirectory()?"\u{1F4C1} ":"\u{1F4C4} ",d=i.isDirectory()?"/":"";if(r.push(`${o}${a}${i.name}${d}`),i.isDirectory()&&t<n){const u=path_1.default.join(e,i.name),m=getDirectoryStructure(u,t+1,n);m&&r.push(m)}}return r.join(`
|
|
6
|
+
`)}catch{return t===0?"\u274C \u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55":""}}function parseContinueSessionCommand(e){const t=e.trim().match(/^\/resume(?:\s+(\S+))?$/i);return t?t[1]!==void 0?t[1]:"":null}function looksLikeCronExpression(e){const t=e.trim().split(/\s+/);return t.length!==5?!1:t.every(n=>/^[\d*/\-]+$/.test(n))}function parseCronCommand(e){const t=e.trim();if(!t.toLowerCase().startsWith("/cron"))return null;const n=t.substring(5).trim();if(!n)return null;if(/^(list|ls)$/i.test(n))return{type:"list"};const s=n.match(/^(?:delete|rm)\s+(\S+)$/i);if(s)return{type:"delete",id:s[1]};const r=n.match(/^pause\s+(\S+)$/i);if(r)return{type:"pause",id:r[1]};const o=n.match(/^resume\s+(\S+)$/i);if(o)return{type:"resume",id:o[1]};const i=n.match(/^(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.+)$/);return i&&looksLikeCronExpression(i[1])?{type:"create_cron",cronExpression:i[1],prompt:i[2]}:{type:"create_nl",input:n}}function parseVersionCommand(e){return e.trim()==="/version"}function parseOpenCommand(e){const t=e.trim().toLowerCase();return t==="/open"?"folder":t==="/open shell"?"shell":t==="/open code"?"code":null}function parseCleanCommand(e){const t=e.trim().toLowerCase();return t==="/clean"?"current":t==="/clean all"?"all":null}function parseResetApiKeyCfgCommand(e){return e.trim().toLowerCase()==="/reset-apikeycfg"}function parseCfgCommand(e){const t=e.trim();if(!/^\/cfg(?:\s|$)/i.test(t))return null;const n=t.substring(4).trim();if(!n)return{};if(/^--help$/i.test(n))return null;const s={},r=n.split(/\s+/);for(let o=0;o<r.length;o++){const i=r[o];if(i==="--dingToken"&&r[o+1])s.dingToken=r[++o];else if(i==="--linkConversationId"&&r[o+1])s.linkConversationId=r[++o];else if(i==="--conversationId"&&r[o+1])s.conversationId=r[++o];else if(i==="--whiteUserList"&&r[o+1])s.whiteUserList=r[++o].split(",").map(a=>a.trim()).filter(Boolean);else if(i==="--conversationTitle"&&r[o+1]){const a=[];for(;o+1<r.length&&!r[o+1].startsWith("--");)a.push(r[++o]);a.length>0&&(s.conversationTitle=a.join(" "))}else if(i==="--atSender"&&r[o+1]){const a=r[++o].toLowerCase();s.atSender=a==="true"||a==="1"||a==="yes"}else if(i==="--receiveReply"&&r[o+1]){const a=r[++o].toLowerCase();s.receiveReply=a==="true"||a==="1"||a==="yes"}else if(i==="--preBash"&&r[o+1]){const a=[];for(;o+1<r.length&&!r[o+1].startsWith("--");)a.push(r[++o]);a.length>0&&(s.preBash=a.join(" ").replace(/^["']|["']$/g,""))}else i==="--permissionMode"&&r[o+1]&&(s.permissionMode=r[++o])}return s}function parseBashCommand(e){const n=e.trim().match(/^\/bash\s+(.+)$/i);return n&&n[1].trim()||null}function parseMqCommand(e){const t=e.trim();if(!/^\/mq(?:\s|$)/i.test(t)&&t.toLowerCase()!=="/mq")return null;const n=t.substring(3).trim();if(!n)return{type:"list"};if(/^front$/i.test(n))return{type:"front"};const s=n.match(/^rm\s+(.+)$/i);if(s){const o=s[1].trim();if(/^all$/i.test(o))return{type:"cancelAll"};const i=[],a=o.match(/^(\d+)\s*-\s*(\d+)$/);if(a){const u=parseInt(a[1],10),m=parseInt(a[2],10);if(u>0&&m>=u){for(let c=u;c<=m;c++)i.push(c);return{type:"rm",indices:i}}}const d=o.split(/\s+/);for(const u of d){const m=parseInt(u,10);m>0&&i.push(m)}if(i.length>0)return{type:"rm",indices:i}}const r=n.match(/^-n\s+(\d+)$/i);if(r){const o=parseInt(r[1],10);return o>0?{type:"cancel",count:o}:{type:"list"}}return/^-all$/i.test(n)?{type:"cancelAll"}:null}function parseAuthCommand(e){const t=e.trim(),n=t.match(/^\/auth\s+admin\s+add\s+(\S+)$/i);if(n)return{type:"adminAdd",staffId:n[1]};const s=t.match(/^\/auth\s+admin\s+(?:rm|del)\s+(\S+)$/i);if(s)return{type:"adminRm",staffId:s[1]};if(/^\/auth\s+admin(?:\s+list)?$/i.test(t))return{type:"adminList"};const r=t.match(/^\/auth\s+add\s+(\S+)$/i);if(r)return{type:"add",staffId:r[1]};const o=t.match(/^\/auth\s+(?:del(?:ete)?|rm)\s+(\S+)$/i);if(o)return{type:"del",staffId:o[1]};const i=t.match(/^\/auth\s+approve\s+(\S+)$/i);if(i)return{type:"approve",requestId:i[1]};const a=t.match(/^\/auth\s+reject\s+(\S+)$/i);return a?{type:"reject",requestId:a[1]}:/^\/auth(?:\s+list)?$/i.test(t)?{type:"list"}:null}function parseRecorderCommand(e){const t=e.trim();return/^\/recorder\s+on$/i.test(t)?"on":/^\/recorder\s+exit$/i.test(t)?"exit":null}function parseGoonCommand(e){return/^\/goon$/i.test(e.trim())}function parseCcCommand(e){const n=e.trim().match(/^\/cc\s+(.+)$/i);if(!n)return null;const s=n[1].trim();return s.startsWith("/")?s:`/${s}`}function parseClaudeMdCommand(e){return/^\/claude\.md$/i.test(e.trim())}function parseInterruptCommand(e){return e.trim()==="/!"}function parseTodoCommand(e){const t=e.trim();if(!/^\/todo(?:\s|$)/i.test(t)&&t.toLowerCase()!=="/todo")return null;const n=t.substring(5).trim();if(/^list$/i.test(n))return{type:"list"};if(!n)return{type:"list"};const s=n.match(/^done\s+(\d+)$/i);if(s)return{type:"done",index:parseInt(s[1],10)};if(/^rm\s+all$/i.test(n))return{type:"remove",index:"all"};const r=n.match(/^rm\s+(\d+)$/i);if(r)return{type:"remove",index:parseInt(r[1],10)};if(/^remind\s+-1$/i.test(n))return{type:"remind",hour:null};const o=n.match(/^remind\s+(\d+)$/i);if(o){const c=parseInt(o[1],10);return c>=0&&c<=23?{type:"remind",hour:c}:null}let i=n,a,d;const u=i.match(/@(\S+)/);u&&(a=u[1],i=i.replace(/@\S+/,"").trim());const m=i.match(/\bddl\s+(.+)$/i);return m&&(d=m[1].trim(),i=i.replace(/\bddl\s+.+$/i,"").trim()),i?{type:"add",content:i,assigneeStaffId:a,deadline:d}:null}function parseMenuCommand(e){const t=e.trim();if(!/^\/menu(?:\s|$)/i.test(t)&&t.toLowerCase()!=="/menu")return null;const n=t.substring(5).trim(),s=n.startsWith("-g "),r=s?n.substring(3).trim():n;if(!n)return{type:"show"};if(s&&!r)return{type:"list",isGlobal:!0};const o=r.match(/^trigger\s+(\S+)$/i);if(o&&!s)return{type:"trigger",word:o[1]};const i=r.match(/^add\s+(.+)$/i);if(i)return{type:"add",command:i[1].trim(),isGlobal:s};const a=r.match(/^del(?:ete)?\s+(\d+)$/i);return a?{type:"del",index:parseInt(a[1],10),isGlobal:s}:/^list$/i.test(r)?{type:"list",isGlobal:s}:s?null:{type:"show"}}function parseRebootCommand(e){const t=e.trim();if(!/^\/reboot(?:\s|$)/i.test(t))return null;const n=t.substring(7).trim();if(!n)return{update:!1};const s=n.match(/^--update(?:\s+(\S+))?$/i);return s?{update:!0,tag:s[1]}:null}function parseRecorderCommandEnhanced(e){const t=e.trim().toLowerCase();return/^\/(?:recorder|r)\s+on$/i.test(t)?"on":/^\/(?:recorder|r)\s+(?:exit|e)$/i.test(t)||/^\/(?:exit|e)$/i.test(t)?"exit":null}
|
package/dist/src/biz/cron.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CronEngine=void 0,exports.isValidCronExpression=isValidCronExpression,exports.formatCronJobList=formatCronJobList,exports.formatCronJobInfo=formatCronJobInfo;const fs_1=__importDefault(require("fs")),readline_1=__importDefault(require("readline")),child_process_1=require("child_process"),utils_ok_1=require("utils-ok"),messaging_1=require("./messaging"),claude_process_1=require("./claude-process"),task_1=require("./task"),session_1=require("./session");function getCronFile(s){return`${(0,session_1.getClientDir)(s)}/cron.json`}function loadCronJobs(s){const t=getCronFile(s);try{const e=JSON.parse(fs_1.default.readFileSync(t,"utf-8"));return Array.isArray(e)?e:e.jobs||[]}catch{return[]}}function saveCronJobs(s,t){const e=getCronFile(s);fs_1.default.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}function matchesCronField(s,t,e,r){if(s==="*")return!0;if(s.includes(","))return s.split(",").some(n=>matchesCronField(n.trim(),t,e,r));if(s.includes("/")){const n=s.indexOf("/"),o=s.substring(0,n),d=parseInt(s.substring(n+1),10);if(isNaN(d)||d<=0)return!1;let a=e,c=r;if(o!=="*")if(o.includes("-")){const u=o.split("-").map(Number);a=u[0],c=u[1]}else a=parseInt(o,10),c=r;return t<a||t>c?!1:(t-a)%d===0}if(s.includes("-")){const n=s.split("-").map(Number);return t>=n[0]&&t<=n[1]}const i=parseInt(s,10);return!isNaN(i)&&t===i}function matchesCron(s,t){const e=s.trim().split(/\s+/);if(e.length!==5)return!1;const r=t.getMinutes(),i=t.getHours(),n=t.getDate(),o=t.getMonth()+1,d=t.getDay();if(!matchesCronField(e[0],r,0,59)||!matchesCronField(e[1],i,0,23)||!matchesCronField(e[3],o,1,12))return!1;const a=matchesCronField(e[2],n,1,31),c=matchesCronField(e[4],d,0,7)||d===0&&matchesCronField(e[4],7,0,7),u=e[2]==="*",
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CronEngine=void 0,exports.isValidCronExpression=isValidCronExpression,exports.formatCronJobList=formatCronJobList,exports.formatCronJobInfo=formatCronJobInfo;const fs_1=__importDefault(require("fs")),readline_1=__importDefault(require("readline")),child_process_1=require("child_process"),utils_ok_1=require("utils-ok"),messaging_1=require("./messaging"),claude_process_1=require("./claude-process"),task_1=require("./task"),session_1=require("./session");function getCronFile(s){return`${(0,session_1.getClientDir)(s)}/cron.json`}function loadCronJobs(s){const t=getCronFile(s);try{const e=JSON.parse(fs_1.default.readFileSync(t,"utf-8"));return Array.isArray(e)?e:e.jobs||[]}catch{return[]}}function saveCronJobs(s,t){const e=getCronFile(s);fs_1.default.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}function matchesCronField(s,t,e,r){if(s==="*")return!0;if(s.includes(","))return s.split(",").some(n=>matchesCronField(n.trim(),t,e,r));if(s.includes("/")){const n=s.indexOf("/"),o=s.substring(0,n),d=parseInt(s.substring(n+1),10);if(isNaN(d)||d<=0)return!1;let a=e,c=r;if(o!=="*")if(o.includes("-")){const u=o.split("-").map(Number);a=u[0],c=u[1]}else a=parseInt(o,10),c=r;return t<a||t>c?!1:(t-a)%d===0}if(s.includes("-")){const n=s.split("-").map(Number);return t>=n[0]&&t<=n[1]}const i=parseInt(s,10);return!isNaN(i)&&t===i}function matchesCron(s,t){const e=s.trim().split(/\s+/);if(e.length!==5)return!1;const r=t.getMinutes(),i=t.getHours(),n=t.getDate(),o=t.getMonth()+1,d=t.getDay();if(!matchesCronField(e[0],r,0,59)||!matchesCronField(e[1],i,0,23)||!matchesCronField(e[3],o,1,12))return!1;const a=matchesCronField(e[2],n,1,31),c=matchesCronField(e[4],d,0,7)||d===0&&matchesCronField(e[4],7,0,7),u=e[2]==="*",m=e[4]==="*";return u&&m?!0:u?c:m?a:a||c}function isValidCronExpression(s){const t=s.trim().split(/\s+/);if(t.length!==5)return!1;const e=/^(\*|\d+|\d+-\d+|\*\/\d+|\d+\/\d+|\d+-\d+\/\d+|\d+(,\d+)+)$/;return t.every(r=>e.test(r))}const ANALYSIS_PROMPT=`\u5206\u6790\u4EE5\u4E0B\u5B9A\u65F6\u4EFB\u52A1\u63CF\u8FF0\uFF0C\u63D0\u53D6cron\u8868\u8FBE\u5F0F\u548C\u4EFB\u52A1\u5185\u5BB9\u3002
|
|
2
2
|
|
|
3
3
|
\u7528\u6237\u8F93\u5165: {INPUT}
|
|
4
4
|
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
- \u6BCF\u5929\u4E2D\u534812\u70B9: "0 12 * * *"
|
|
15
15
|
- \u6BCF\u67081\u53F7\u65E9\u4E0A9\u70B9: "0 9 1 * *"
|
|
16
16
|
- \u6BCF\u5468\u4E94\u4E0B\u53483\u70B9: "0 15 * * 5"`;async function analyzeCronWithClaude(s,t,e){const r=s.getConversationDir(t),i="claude",n=ANALYSIS_PROMPT.replace("{INPUT}",e),o=["--permission-mode","bypassPermissions","--print","--output-format","stream-json","--verbose"],d=(0,claude_process_1.resolveClaudeSettingsPath)(s,r);return d&&o.push("--settings",d),console.log(`[${(0,session_1.timestamp)()}] Cron\u5206\u6790: ${i} ${o.join(" ")}`),new Promise((a,c)=>{const u=(0,child_process_1.spawn)(i,o,{cwd:r,stdio:["pipe","pipe","pipe"]});u.stdin?.write(`${n}
|
|
17
|
-
`),u.stdin?.end();let
|
|
17
|
+
`),u.stdin?.end();let m="",h="";readline_1.default.createInterface({input:u.stdout}).on("line",l=>{const f=(0,claude_process_1.parseClaudeStreamLine)(l);f?.type==="result"&&f.content&&(m=f.content)}),u.stderr?.on("data",l=>{h+=l.toString()});const g=setTimeout(()=>{u.kill(),c(new Error("\u5206\u6790\u8D85\u65F6(60s)"))},6e4);u.on("close",l=>{if(clearTimeout(g),l===0&&m)try{const f=m.match(/\{[\s\S]*\}/);if(f){const p=JSON.parse(f[0]);if(p.cron&&p.prompt){a(p);return}}c(new Error("Claude \u8FD4\u56DE\u683C\u5F0F\u4E0D\u6B63\u786E"))}catch{c(new Error("JSON \u89E3\u6790\u5931\u8D25"))}else{const f=h.trim()?` (${h.trim().substring(0,200)})`:"";console.error(`[${(0,session_1.timestamp)()}] Cron\u5206\u6790\u8FDB\u7A0B\u9000\u51FA(${l})${f}`);const p=h;/\b429\b/.test(p)?c(new Error("Claude \u914D\u989D\u5DF2\u8017\u5C3D(429)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6216\u660E\u5929\u518D\u8BD5")):/\b422\b/.test(p)||/TPM|额度超限/i.test(p)?c(new Error("Claude TPM \u9650\u6D41(422)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")):/\b401\b/.test(p)||/auth|认证|permission/i.test(p)?c(new Error("Claude \u8BA4\u8BC1\u5931\u8D25(401)\uFF0C\u8BF7\u68C0\u67E5 API Key \u914D\u7F6E")):l===1&&!m&&!h.trim()?c(new Error("Claude \u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA\uFF0C\u65E0\u8F93\u51FA\u3002\u8BF7\u68C0\u67E5 claude \u547D\u4EE4\u662F\u5426\u53EF\u7528")):c(new Error(`\u5206\u6790\u5931\u8D25 (\u9000\u51FA\u7801: ${l})${f}`))}}),u.on("error",l=>{clearTimeout(g),c(new Error(`\u542F\u52A8 Claude \u8FDB\u7A0B\u5931\u8D25: ${l.message}`))})})}function formatCronJobList(s){if(s.length===0)return"\u{1F4ED} \u6682\u65E0\u5B9A\u65F6\u4EFB\u52A1";const t=[`### \u23F0 \u5B9A\u65F6\u4EFB\u52A1\u5217\u8868
|
|
18
18
|
`];for(const e of s){const r=e.enabled?"\u2705":"\u23F8\uFE0F",i=e.lastRunAt||"-";t.push(`**${r} ${e.id}**`),t.push(`- Cron: \`${e.cronExpression}\``),t.push(`- \u63CF\u8FF0: ${e.description}`),t.push(`- \u4EFB\u52A1: ${e.prompt}`),t.push(`- \u521B\u5EFA\u8005: ${e.senderNick}`),t.push(`- \u4E0A\u6B21\u6267\u884C: ${i}`),t.push("")}return t.push("\u{1F4A1} `/cron pause <id>` \u6682\u505C | `/cron resume <id>` \u6062\u590D | `/cron delete <id>` \u5220\u9664"),t.join(`
|
|
19
19
|
`)}function formatCronJobInfo(s){const t=s.enabled?"\u2705 \u542F\u7528":"\u23F8\uFE0F \u6682\u505C";return[`### \u23F0 \u5B9A\u65F6\u4EFB\u52A1 ${s.id}`,"",`- **\u72B6\u6001:** ${t}`,`- **Cron:** \`${s.cronExpression}\``,`- **\u63CF\u8FF0:** ${s.description}`,`- **\u4EFB\u52A1:** ${s.prompt}`,`- **\u521B\u5EFA\u8005:** ${s.senderNick}`,`- **\u521B\u5EFA\u65F6\u95F4:** ${s.createdAt}`,`- **\u4E0A\u6B21\u6267\u884C:** ${s.lastRunAt||"-"}`].join(`
|
|
20
20
|
`)}class CronEngine{constructor(t){this.jobs=[],this.timer=null,this.lastCheckedTime=-1,this.runningJobIds=new Set,this.MAX_CONCURRENT_JOBS=3,this.dc=t,this.jobs=loadCronJobs(t)}start(){this.startScheduler();const t=this.jobs.filter(e=>e.enabled).length;console.log(`[${(0,session_1.timestamp)()}] Cron\u5F15\u64CE\u5DF2\u542F\u52A8, \u5171 ${this.jobs.length} \u4E2A\u4EFB\u52A1 (${t} \u542F\u7528)`)}destroy(){this.stopScheduler()}addJob(t){const e={id:`cron_${Date.now()}`,conversationId:t.conversationId,cronExpression:t.cronExpression,description:t.description,prompt:t.prompt,enabled:!0,createdAt:(0,session_1.timestamp)(),senderStaffId:t.senderStaffId,senderNick:t.senderNick};return this.jobs.push(e),this.persist(),console.log(`[${(0,session_1.timestamp)()}] \u65B0\u589E\u5B9A\u65F6\u4EFB\u52A1: ${e.id} [${e.cronExpression}] ${e.description}`),e}removeJob(t){const e=this.jobs.findIndex(i=>i.id===t);if(e===-1)return!1;const r=this.jobs.splice(e,1)[0];return this.persist(),console.log(`[${(0,session_1.timestamp)()}] \u5220\u9664\u5B9A\u65F6\u4EFB\u52A1: ${r.id}`),!0}toggleJob(t,e){const r=this.jobs.find(i=>i.id===t);return r?(r.enabled=e,this.persist(),console.log(`[${(0,session_1.timestamp)()}] \u5B9A\u65F6\u4EFB\u52A1 ${r.id} ${e?"\u5DF2\u6062\u590D":"\u5DF2\u6682\u505C"}`),!0):!1}listJobs(t){return t?this.jobs.filter(e=>e.conversationId===t):[...this.jobs]}getJob(t){return this.jobs.find(e=>e.id===t)}async analyzeAndCreate(t,e,r,i){try{const n=await analyzeCronWithClaude(this.dc,t,e);return isValidCronExpression(n.cron)?{job:this.addJob({conversationId:t,cronExpression:n.cron,description:n.desc||e.substring(0,50),prompt:n.prompt,senderStaffId:r,senderNick:i})}:{error:`Claude \u8FD4\u56DE\u7684cron\u8868\u8FBE\u5F0F\u65E0\u6548: ${n.cron}`}}catch(n){return{error:n instanceof Error?n.message:String(n)}}}persist(){saveCronJobs(this.dc,this.jobs)}startScheduler(){const e=6e4-Date.now()%6e4;setTimeout(()=>{this.tick(),this.timer=setInterval(()=>this.tick(),6e4)},e)}stopScheduler(){this.timer&&(clearInterval(this.timer),this.timer=null)}tick(){const t=Date.now(),e=this.lastCheckedTime<0?t-t%6e4:this.lastCheckedTime+6e4-this.lastCheckedTime%6e4,r=t-t%6e4;for(let i=e;i<=r;i+=6e4){const n=new Date(i);if(!this.checkJobsAt(n))break}this.lastCheckedTime=t}checkJobsAt(t){if(this.runningJobIds.size>=this.MAX_CONCURRENT_JOBS)return console.warn(`[${(0,session_1.timestamp)()}] Cron\u5E76\u53D1\u4E0A\u9650(${this.MAX_CONCURRENT_JOBS}), \u8DF3\u8FC7 ${t.toISOString()} \u7684\u68C0\u67E5`),!1;for(const e of this.jobs)if(e.enabled&&!this.runningJobIds.has(e.id)){if(this.runningJobIds.size>=this.MAX_CONCURRENT_JOBS)break;matchesCron(e.cronExpression,t)&&(console.log(`[${(0,session_1.timestamp)()}] Cron\u89E6\u53D1: ${e.id} [${e.cronExpression}] ${e.description}`),this.executeJob(e).catch(r=>{console.error(`[${(0,session_1.timestamp)()}] Cron\u6267\u884C\u5931\u8D25: ${e.id}`,r)}))}return!0}async executeJob(t){this.runningJobIds.add(t.id);try{const e=this.dc.getConversationConfig(t.conversationId);if(!e){console.warn(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u7684\u4F1A\u8BDD\u914D\u7F6E\u4E0D\u5B58\u5728, \u8DF3\u8FC7\u6267\u884C`);return}if(!!!(e.dingToken||this.dc.config.defaultDingToken)){console.warn(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u65E0\u901A\u77E5\u80FD\u529B(\u65E0dingToken\u4E14\u65E0defaultDingToken), \u8DF3\u8FC7\u6267\u884C`);return}if((0,session_1.findActiveSession)(this.dc,t.conversationId)){console.log(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u7684\u4F1A\u8BDD\u6709\u6D3B\u8DC3session, \u964D\u7EA7\u5230\u4EFB\u52A1\u961F\u5217`),await this.enqueueAsTask(t);return}const n=Date.now(),o={conversationId:t.conversationId,sessionWebhook:"",startTime:n,startTimeStr:utils_ok_1.dateUtil.mm(n).format("YYYY-MM-DD-HH-mm-ss"),startStaffId:t.senderStaffId,startNickName:`[cron]${t.senderNick}`},d=(0,session_1.getSessionDir)(this.dc,o);fs_1.default.mkdirSync(d,{recursive:!0}),fs_1.default.writeFileSync(`${d}/session.json`,JSON.stringify(o,null,2),"utf-8"),this.dc.activeSessions.set(t.conversationId,{session:o,lastSenderStaffId:t.senderStaffId,isProcessing:!0,messageQueue:[],conversationConfig:e}),(0,session_1.saveActiveSession)(this.dc,t.conversationId),console.log(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u5F00\u59CB\u6267\u884C: ${t.description}`),fs_1.default.appendFileSync(`${d}/session.log`,`[${(0,session_1.timestamp)()}] [SYSTEM]: \u5B9A\u65F6\u4EFB\u52A1\u89E6\u53D1: ${t.description}
|
|
21
|
-
`,"utf-8");try{await(0,claude_process_1.executeClaudeQuery)(this.dc,o,t.prompt,{skill:e.taskCfg?.skill,agent:e.agent,senderNick:t.senderNick,senderStaffId:t.senderStaffId})}catch(a){console.error(`[${(0,session_1.timestamp)()}] Cron\u6267\u884CClaude\u67E5\u8BE2\u5931\u8D25: ${t.id}`,a),await(0,messaging_1.sendDingMessage)(this.dc,{conversationId:t.conversationId,sessionWebhook:"",atUserId:t.senderStaffId,content:`\u274C \u5B9A\u65F6\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`})}finally{this.dc.activeSessions.delete(t.conversationId),(0,session_1.saveActiveSession)(this.dc,t.conversationId)}t.lastRunAt=(0,session_1.timestamp)(),this.persist()}finally{this.runningJobIds.delete(t.id)}}async enqueueAsTask(t){try{await(0,task_1.saveTask)(this.dc,{conversationId:t.conversationId,prompt:t.prompt,senderStaffId:t.senderStaffId,senderNickName:`[cron]${t.senderNick}`,sessionWebhook:"",type:"cron"}),console.log(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u5DF2\u964D\u7EA7\u5230\u4EFB\u52A1\u961F\u5217: ${t.description}`)}catch(e){console.error(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u964D\u7EA7\u5230\u4EFB\u52A1\u961F\u5217\u5931\u8D25:`,e)}t.lastRunAt=(0,session_1.timestamp)(),this.persist()}}exports.CronEngine=CronEngine;
|
|
21
|
+
`,"utf-8");try{await(0,claude_process_1.executeClaudeQuery)(this.dc,o,t.prompt,{skill:e.taskCfg?.skill,agent:e.agent,senderNick:t.senderNick,senderStaffId:t.senderStaffId,permissionMode:e.permissionMode})}catch(a){console.error(`[${(0,session_1.timestamp)()}] Cron\u6267\u884CClaude\u67E5\u8BE2\u5931\u8D25: ${t.id}`,a),await(0,messaging_1.sendDingMessage)(this.dc,{conversationId:t.conversationId,sessionWebhook:"",atUserId:t.senderStaffId,content:`\u274C \u5B9A\u65F6\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${a instanceof Error?a.message:String(a)}`})}finally{this.dc.activeSessions.delete(t.conversationId),(0,session_1.saveActiveSession)(this.dc,t.conversationId)}t.lastRunAt=(0,session_1.timestamp)(),this.persist()}finally{this.runningJobIds.delete(t.id)}}async enqueueAsTask(t){try{await(0,task_1.saveTask)(this.dc,{conversationId:t.conversationId,prompt:t.prompt,senderStaffId:t.senderStaffId,senderNickName:`[cron]${t.senderNick}`,sessionWebhook:"",type:"cron"}),console.log(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u5DF2\u964D\u7EA7\u5230\u4EFB\u52A1\u961F\u5217: ${t.description}`)}catch(e){console.error(`[${(0,session_1.timestamp)()}] Cron\u4EFB\u52A1 ${t.id} \u964D\u7EA7\u5230\u4EFB\u52A1\u961F\u5217\u5931\u8D25:`,e)}t.lastRunAt=(0,session_1.timestamp)(),this.persist()}}exports.CronEngine=CronEngine;
|
package/dist/src/biz/image.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.runOcr=runOcr,exports.getImageDownloadUrl=getImageDownloadUrl,exports.downloadImageBuffer=downloadImageBuffer,exports.processPictureMessage=processPictureMessage,exports.processRichTextMessage=processRichTextMessage,exports.detectExtFromBuffer=detectExtFromBuffer,exports.extractDownloadCode=extractDownloadCode,exports.extractFileName=extractFileName,exports.downloadToFilesDir=downloadToFilesDir,exports.processFileMessage=processFileMessage;const child_process_1=require("child_process"),fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),urllib_1=__importDefault(require("urllib")),session_1=require("./session"),common_1=require("../common"),MAX_IMAGE_SIZE=10*1024*1024,MAX_FILE_SIZE=20*1024*1024,DING_API_BASE="https://api.dingtalk.com",OCR_PREAMBLE="\u4EE5\u4E0B\u56FE\u7247 OCR \u8BC6\u522B\u7ED3\u679C\u6765\u81EA\u5BF9\u7528\u6237\u6D88\u606F\u4E2D\u56FE\u7247\u7684\u9884\u5904\u7406(\u975E\u7528\u6237\u539F\u59CB\u8F93\u5165)\uFF0C\u5982\u8BC6\u522B\u4E0D\u51C6\u786E\u53EF\u76F4\u63A5\u67E5\u770B\u539F\u56FE\u8DEF\u5F84",OCR_BIN_DIR=(0,common_1.projUtil)().getResourcePath(),cachedOcrBinPath=(()=>{if(process.platform==="win32")return null;const e=process.arch;return e==="arm64"?path_1.default.join(OCR_BIN_DIR,"ocr-arm64"):e==="x64"?path_1.default.join(OCR_BIN_DIR,"ocr-x64"):null})();let ocrBinExists=null;async function runOcr(e){return cachedOcrBinPath?(ocrBinExists===null&&(ocrBinExists=fs_1.default.existsSync(cachedOcrBinPath),ocrBinExists||console.warn(`[${(0,session_1.timestamp)()}] OCR \u4E8C\u8FDB\u5236\u4E0D\u5B58\u5728: ${cachedOcrBinPath}`)),ocrBinExists?new Promise(n=>{(0,child_process_1.execFile)(cachedOcrBinPath,[e],{timeout:3e4,maxBuffer:5*1024*1024},(r,o,t)=>{if(r){console.warn(`[${(0,session_1.timestamp)()}] OCR \u6267\u884C\u5931\u8D25: ${r.message}`),t&&console.warn(`[${(0,session_1.timestamp)()}] OCR stderr: ${t.substring(0,200)}`),n(null);return}try{const s=JSON.parse(o);if(!Array.isArray(s)||s.length===0){console.log(`[${(0,session_1.timestamp)()}] OCR \u65E0\u8BC6\u522B\u7ED3\u679C`),n(null);return}const a=s.map(u=>u.word).filter(Boolean).join(" ");console.log(`[${(0,session_1.timestamp)()}] OCR \u8BC6\u522B\u7ED3\u679C: ${a.substring(0,200)}${a.length>200?"...":""}`),n(a||null)}catch{console.warn(`[${(0,session_1.timestamp)()}] OCR \u8F93\u51FA\u89E3\u6790\u5931\u8D25: ${o.substring(0,200)}`),n(null)}})}):null):(console.log(`[${(0,session_1.timestamp)()}] \u5F53\u524D\u5E73\u53F0(${process.platform}/${process.arch})\u4E0D\u652F\u6301\u672C\u5730OCR\uFF0C\u4F7F\u7528\u6A21\u578B\u8BC6\u522B`),null)}const MAGIC_NUMBERS=[{bytes:[137,80,78,71],mediaType:"image/png",ext:"png"},{bytes:[255,216,255],mediaType:"image/jpeg",ext:"jpg"},{bytes:[71,73,70],mediaType:"image/gif",ext:"gif"},{bytes:[82,73,70,70],mediaType:"image/webp",ext:"webp"}];function detectImageMediaType(e){for(const{bytes:n,mediaType:r,ext:o}of MAGIC_NUMBERS)if(e.length>=n.length&&n.every((t,s)=>e[s]===t))return{mediaType:r,ext:o};return{mediaType:"image/jpeg",ext:"jpg"}}async function getImageDownloadUrl(e,n,r){try{const o=await e.dingStreamClient.getAccessToken(),t=`${DING_API_BASE}/v1.0/robot/messageFiles/download`,s=await urllib_1.default.request(t,{method:"POST",headers:{"x-acs-dingtalk-access-token":o,"Content-Type":"application/json"},data:{downloadCode:n,robotCode:r},dataType:"json",timeout:1e4});if(s.status!==200||!s.data)return e.debugLog(`getImageDownloadUrl API \u8FD4\u56DE\u975E200: status=${s.status}, data=${JSON.stringify(s.data)}`),null;const a=s.data,u=a?.downloadUrl;return u||(e.debugLog(`getImageDownloadUrl \u54CD\u5E94\u65E0 downloadUrl: ${JSON.stringify(a)}`),null)}catch(o){return console.warn(`[${(0,session_1.timestamp)()}] getImageDownloadUrl \u8BF7\u6C42\u5931\u8D25:`,o),null}}async function downloadImageBuffer(e,n=MAX_IMAGE_SIZE){try{const r=await urllib_1.default.request(e,{method:"GET",dataType:"buffer",timeout:3e4});if(r.status!==200)return console.warn(`[${(0,session_1.timestamp)()}] downloadImageBuffer \u4E0B\u8F7D\u5931\u8D25: status=${r.status}`),null;const o=r.data;return!o||o.length===0?(console.warn(`[${(0,session_1.timestamp)()}] downloadImageBuffer \u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A`),null):o.length>n?(console.warn(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u5927\u5C0F ${o.length} \u8D85\u8FC7\u9650\u5236 ${n}`),null):o}catch(r){return console.warn(`[${(0,session_1.timestamp)()}] downloadImageBuffer \u4E0B\u8F7D\u5931\u8D25:`,r),null}}async function downloadAndProcessImage(e,n,r,o){const t=await getImageDownloadUrl(e,n,r);if(!t)return null;const s=await downloadImageBuffer(t);if(!s)return null;const{mediaType:a,ext:u}=detectImageMediaType(s),f=path_1.default.join(o,".images"),d=n.slice(-8).replace(/[/\\:*?"<>|+= ]/g,"_"),m=`${Date.now()}-${d}.${u}`,c=path_1.default.join(f,m);try{fs_1.default.mkdirSync(f,{recursive:!0}),fs_1.default.writeFileSync(c,s)}catch(
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.runOcr=runOcr,exports.getImageDownloadUrl=getImageDownloadUrl,exports.downloadImageBuffer=downloadImageBuffer,exports.processPictureMessage=processPictureMessage,exports.processRichTextMessage=processRichTextMessage,exports.detectExtFromBuffer=detectExtFromBuffer,exports.extractDownloadCode=extractDownloadCode,exports.extractFileName=extractFileName,exports.downloadToFilesDir=downloadToFilesDir,exports.processFileMessage=processFileMessage;const child_process_1=require("child_process"),fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),urllib_1=__importDefault(require("urllib")),session_1=require("./session"),common_1=require("../common"),MAX_IMAGE_SIZE=10*1024*1024,MAX_FILE_SIZE=20*1024*1024,DING_API_BASE="https://api.dingtalk.com",OCR_PREAMBLE="\u4EE5\u4E0B\u56FE\u7247 OCR \u8BC6\u522B\u7ED3\u679C\u6765\u81EA\u5BF9\u7528\u6237\u6D88\u606F\u4E2D\u56FE\u7247\u7684\u9884\u5904\u7406(\u975E\u7528\u6237\u539F\u59CB\u8F93\u5165)\uFF0C\u5982\u8BC6\u522B\u4E0D\u51C6\u786E\u53EF\u76F4\u63A5\u67E5\u770B\u539F\u56FE\u8DEF\u5F84",OCR_BIN_DIR=(0,common_1.projUtil)().getResourcePath(),cachedOcrBinPath=(()=>{if(process.platform==="win32")return null;const e=process.arch;return e==="arm64"?path_1.default.join(OCR_BIN_DIR,"ocr-arm64"):e==="x64"?path_1.default.join(OCR_BIN_DIR,"ocr-x64"):null})();let ocrBinExists=null;async function runOcr(e){return cachedOcrBinPath?(ocrBinExists===null&&(ocrBinExists=fs_1.default.existsSync(cachedOcrBinPath),ocrBinExists||console.warn(`[${(0,session_1.timestamp)()}] OCR \u4E8C\u8FDB\u5236\u4E0D\u5B58\u5728: ${cachedOcrBinPath}`)),ocrBinExists?new Promise(n=>{(0,child_process_1.execFile)(cachedOcrBinPath,[e],{timeout:3e4,maxBuffer:5*1024*1024},(r,o,t)=>{if(r){console.warn(`[${(0,session_1.timestamp)()}] OCR \u6267\u884C\u5931\u8D25: ${r.message}`),t&&console.warn(`[${(0,session_1.timestamp)()}] OCR stderr: ${t.substring(0,200)}`),n(null);return}try{const s=JSON.parse(o);if(!Array.isArray(s)||s.length===0){console.log(`[${(0,session_1.timestamp)()}] OCR \u65E0\u8BC6\u522B\u7ED3\u679C`),n(null);return}const a=s.map(u=>u.word).filter(Boolean).join(" ");console.log(`[${(0,session_1.timestamp)()}] OCR \u8BC6\u522B\u7ED3\u679C: ${a.substring(0,200)}${a.length>200?"...":""}`),n(a||null)}catch{console.warn(`[${(0,session_1.timestamp)()}] OCR \u8F93\u51FA\u89E3\u6790\u5931\u8D25: ${o.substring(0,200)}`),n(null)}})}):null):(console.log(`[${(0,session_1.timestamp)()}] \u5F53\u524D\u5E73\u53F0(${process.platform}/${process.arch})\u4E0D\u652F\u6301\u672C\u5730OCR\uFF0C\u4F7F\u7528\u6A21\u578B\u8BC6\u522B`),null)}const MAGIC_NUMBERS=[{bytes:[137,80,78,71],mediaType:"image/png",ext:"png"},{bytes:[255,216,255],mediaType:"image/jpeg",ext:"jpg"},{bytes:[71,73,70],mediaType:"image/gif",ext:"gif"},{bytes:[82,73,70,70],mediaType:"image/webp",ext:"webp"}];function detectImageMediaType(e){for(const{bytes:n,mediaType:r,ext:o}of MAGIC_NUMBERS)if(e.length>=n.length&&n.every((t,s)=>e[s]===t))return{mediaType:r,ext:o};return{mediaType:"image/jpeg",ext:"jpg"}}async function getImageDownloadUrl(e,n,r){try{const o=await e.dingStreamClient.getAccessToken(),t=`${DING_API_BASE}/v1.0/robot/messageFiles/download`,s=await urllib_1.default.request(t,{method:"POST",headers:{"x-acs-dingtalk-access-token":o,"Content-Type":"application/json"},data:{downloadCode:n,robotCode:r},dataType:"json",timeout:1e4});if(s.status!==200||!s.data)return e.debugLog(`getImageDownloadUrl API \u8FD4\u56DE\u975E200: status=${s.status}, data=${JSON.stringify(s.data)}`),null;const a=s.data,u=a?.downloadUrl;return u||(e.debugLog(`getImageDownloadUrl \u54CD\u5E94\u65E0 downloadUrl: ${JSON.stringify(a)}`),null)}catch(o){return console.warn(`[${(0,session_1.timestamp)()}] getImageDownloadUrl \u8BF7\u6C42\u5931\u8D25:`,o),null}}async function downloadImageBuffer(e,n=MAX_IMAGE_SIZE){try{const r=await urllib_1.default.request(e,{method:"GET",dataType:"buffer",timeout:3e4});if(r.status!==200)return console.warn(`[${(0,session_1.timestamp)()}] downloadImageBuffer \u4E0B\u8F7D\u5931\u8D25: status=${r.status}`),null;const o=r.data;return!o||o.length===0?(console.warn(`[${(0,session_1.timestamp)()}] downloadImageBuffer \u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A`),null):o.length>n?(console.warn(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u5927\u5C0F ${o.length} \u8D85\u8FC7\u9650\u5236 ${n}`),null):o}catch(r){return console.warn(`[${(0,session_1.timestamp)()}] downloadImageBuffer \u4E0B\u8F7D\u5931\u8D25:`,r),null}}async function downloadAndProcessImage(e,n,r,o){const t=await getImageDownloadUrl(e,n,r);if(!t)return null;const s=await downloadImageBuffer(t);if(!s)return null;const{mediaType:a,ext:u}=detectImageMediaType(s),f=path_1.default.join(o,".images"),d=n.slice(-8).replace(/[/\\:*?"<>|+= ]/g,"_"),m=`${Date.now()}-${d}.${u}`,c=path_1.default.join(f,m);try{fs_1.default.mkdirSync(f,{recursive:!0}),fs_1.default.writeFileSync(c,s)}catch(x){return console.warn(`[${(0,session_1.timestamp)()}] \u56FE\u7247\u4FDD\u5B58\u5931\u8D25: ${c}`,x),null}return console.log(`[${(0,session_1.timestamp)()}] \u56FE\u7247\u5DF2\u4FDD\u5B58: ${c} (${a}, ${s.length} bytes)`),{mediaType:a,filePath:c,sizeBytes:s.length}}async function buildImagePrompt(e,n,r){const o=r!=null?`[\u56FE\u7247 ${r}]`:"[\u56FE\u7247]";if(n){const t=await runOcr(e.filePath);if(t){const s=r!=null?`[\u56FE\u7247 ${r} OCR]`:"[\u56FE\u7247 OCR]";return`${o} ${e.filePath}
|
|
2
2
|
${s}
|
|
3
3
|
---
|
|
4
4
|
${t}
|
|
5
5
|
---`}console.warn(`[${(0,session_1.timestamp)()}] OCR \u5931\u8D25\uFF0C\u4EC5\u4F20\u539F\u56FE\u8DEF\u5F84: ${e.filePath}`)}return`${o} ${e.filePath}`}async function processPictureMessage(e,n,r,o,t=!0,s){const a=await downloadAndProcessImage(e,n,r,o);if(!a)return null;const u=await buildImagePrompt(a,t),f=[];return t&&f.push(OCR_PREAMBLE),s&&f.push(s),f.push(u),f.join(`
|
|
6
|
-
`)}async function processRichTextMessage(e,n,r,o,t=!0){const s=n.filter(i=>i.type==="picture"&&(i.downloadCode||i.pictureDownloadCode)).length,a=n.map(async(i,l)=>{if(i.type==="picture"){const
|
|
7
|
-
${
|
|
6
|
+
`)}async function processRichTextMessage(e,n,r,o,t=!0){const s=n.filter(i=>i.type==="picture"&&(i.downloadCode||i.pictureDownloadCode)).length,a=n.map(async(i,l)=>{if(i.type==="picture"){const p=i.downloadCode||i.pictureDownloadCode;if(p){const g=await downloadAndProcessImage(e,p,r,o);return{index:l,result:g}}}return{index:l,result:null}}),u=await Promise.all(a),f=new Map;for(const{index:i,result:l}of u)f.set(i,l);const d=new Map;if(t&&s>0){const i=[];for(const[p,g]of f)g&&i.push(runOcr(g.filePath).then($=>({index:p,ocrText:$})));const l=await Promise.all(i);for(const{index:p,ocrText:g}of l)d.set(p,g)}const m=[];let c=0;for(let i=0;i<n.length;i++){const l=n[i];if(l.type==="text"&&l.text){if(/^@\S+$/.test(l.text.trim()))continue;m.push(l.text)}else if(l.type==="mention"&&l.userId){const p=l.displayName?`${l.displayName}(${l.userId})`:l.userId;m.push(`[@\u63D0\u53CA: ${p}]`)}else if(l.type==="picture"){const p=f.get(i);if(p){c++;const g=s>1?c:void 0,$=t?d.get(i):null,y=g!=null?`[\u56FE\u7247 ${g}]`:"[\u56FE\u7247]";if($){const w=g!=null?`[\u56FE\u7247 ${g} OCR]`:"[\u56FE\u7247 OCR]";m.push(`${y} ${p.filePath}
|
|
7
|
+
${w}
|
|
8
8
|
---
|
|
9
9
|
${$}
|
|
10
|
-
---`)}else m.push(`${
|
|
10
|
+
---`)}else m.push(`${y} ${p.filePath}`)}else(l.downloadCode||l.pictureDownloadCode)&&m.push("[\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25]")}}const x=m.join(`
|
|
11
11
|
`)||"[\u5BCC\u6587\u672C\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A]";return t&&c>0?`${OCR_PREAMBLE}
|
|
12
|
-
${
|
|
12
|
+
${x}`:x}const FILE_MAGIC_BYTES=[{bytes:[37,80,68,70],ext:"pdf"},{bytes:[80,75,3,4],ext:"zip"},{bytes:[80,75,5,6],ext:"zip"}];function detectExtFromBuffer(e){if((detectImageMediaType(e).mediaType!=="image/jpeg"||e.length<2||e[0]===255&&e[1]===216)&&e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return".jpg";for(const{bytes:r,ext:o}of FILE_MAGIC_BYTES)if(e.length>=r.length&&r.every((t,s)=>e[s]===t)){if(o==="zip"&&e.length>=30){const t=e.toString("latin1",0,Math.min(e.length,2e3));if(t.includes("word/"))return".docx";if(t.includes("xl/"))return".xlsx";if(t.includes("ppt/"))return".pptx"}return`.${o}`}return""}function extractDownloadCode(e){const n=e;if(e.downloadCode)return e.downloadCode;if(n.pictureDownloadCode)return n.pictureDownloadCode;if(n.extensions&&typeof n.extensions=="object"){const o=n.extensions;if(o.downloadCode)return o.downloadCode}const r=["image_content","file_content","video_content","audio_content"];for(const o of r){const t=n[o];if(t&&typeof t=="object"){const s=t;if(s.download_code)return s.download_code;if(s.downloadCode)return s.downloadCode}}return null}function extractFileName(e){const n=e;if(e.fileName&&typeof e.fileName=="string")return e.fileName;for(const r of["content","file_content","image_content"]){const o=n[r];if(o&&typeof o=="object"){const t=o;if(t.fileName&&typeof t.fileName=="string")return t.fileName;if(t.file_name&&typeof t.file_name=="string")return t.file_name;if(t.name&&typeof t.name=="string")return t.name}}return null}async function downloadToFilesDir(e,n,r,o,t,s){const a=await getImageDownloadUrl(e,n,r);if(!a)return null;const u=await downloadImageBuffer(a);if(!u)return null;const f=path_1.default.join(o,".files",t);fs_1.default.mkdirSync(f,{recursive:!0});let d;if(s)d=s;else{const{ext:c}=detectImageMediaType(u);d=`file.${c}`}if(fs_1.default.existsSync(path_1.default.join(f,d))){const c=d.lastIndexOf("."),x=c>0?d.substring(0,c):d,i=c>0?d.substring(c):"";let l=1;for(;fs_1.default.existsSync(path_1.default.join(f,`${x}_${l}${i}`));)l++;d=`${x}_${l}${i}`}const m=path_1.default.join(f,d);try{fs_1.default.writeFileSync(m,u)}catch(c){return console.warn(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u4FDD\u5B58\u5931\u8D25: ${m}`,c),null}return console.log(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u5DF2\u4FDD\u5B58: ${m} (${u.length} bytes)`),m}async function processFileMessage(e,n,r,o,t){const s=await getImageDownloadUrl(e,n,r);if(!s)return null;const a=await downloadImageBuffer(s,MAX_FILE_SIZE);if(!a)return null;const u=detectExtFromBuffer(a),f=path_1.default.join(o,".files"),d=n.slice(-8).replace(/[/\\:*?"<>|+= ]/g,"_"),m=`${Date.now()}-${d}${u}`,c=path_1.default.join(f,m);try{fs_1.default.mkdirSync(f,{recursive:!0}),fs_1.default.writeFileSync(c,a)}catch(l){return console.warn(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u4FDD\u5B58\u5931\u8D25: ${c}`,l),null}const x=(a.length/1024).toFixed(1);console.log(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u5DF2\u4FDD\u5B58: ${c} (${x}KB${u?`, ${u}`:""})`);const i=[];return i.push(`[\u6587\u4EF6] \u6536\u5230\u4E00\u4E2A\u6587\u4EF6${u?`\uFF08${u}\uFF09`:""}\uFF0C\u5927\u5C0F ${x}KB`),t&&i.push(t),i.push(`\u6587\u4EF6\u8DEF\u5F84: ${c}`),i.push("\u4F60\u53EF\u4EE5\u4F7F\u7528 Read \u5DE5\u5177\u67E5\u770B\u6587\u4EF6\u5185\u5BB9\u3002"),i.join(`
|
|
13
13
|
`)}
|
package/dist/src/biz/session.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.timestamp=timestamp,exports.getHomeDir=getHomeDir,exports.getClientDir=getClientDir,exports.initClientDir=initClientDir,exports.ensureClientDir=ensureClientDir,exports.getClientConfig=getClientConfig,exports.resolveToUserId=resolveToUserId,exports.authCheck=authCheck,exports.isOwner=isOwner,exports.isAdmin=isAdmin,exports.isOwnerOrAdmin=isOwnerOrAdmin,exports.debugLog=debugLog,exports.isMobile=isMobile,exports.getPhoneMapFile=getPhoneMapFile,exports.loadPhoneMap=loadPhoneMap,exports.savePhoneMap=savePhoneMap,exports.userIdToPhone=userIdToPhone,exports.resolveUserId=resolveUserId,exports.resolveAllPhonesInConfig=resolveAllPhonesInConfig,exports.hashConversationId=hashConversationId,exports.getReplyWebhook=getReplyWebhook,exports.getReplyConversationId=getReplyConversationId,exports.findActiveSession=findActiveSession,exports.getConversationConfig=getConversationConfig,exports.getConversationDir=getConversationDir,exports.getSessionsDir=getSessionsDir,exports.getTasksDir=getTasksDir,exports.getImagesDir=getImagesDir,exports.getSessionDir=getSessionDir,exports.getSessionId=getSessionId,exports.formatSessionInfo=formatSessionInfo,exports.readSessionLogTail=readSessionLogTail,exports.findHistorySession=findHistorySession,exports.findLatestSession=findLatestSession,exports.updateSessionFile=updateSessionFile,exports.appendSessionLog=appendSessionLog,exports.getActiveSessionsFile=getActiveSessionsFile,exports.saveActiveSession=saveActiveSession,exports.loadActiveSessions=loadActiveSessions,exports.endSession=endSession,exports.switchToSession=switchToSession,exports.startNewSession=startNewSession,exports.processMessageQueue=processMessageQueue,exports.handleSessionMessage=handleSessionMessage,exports.cleanCache=cleanCache;const utils_ok_1=require("utils-ok"),fs_1=__importDefault(require("fs")),os_1=__importDefault(require("os")),assert_1=__importDefault(require("assert")),crypto_1=__importDefault(require("crypto")),path_1=__importDefault(require("path")),commands_1=require("./commands"),messaging_1=require("./messaging"),claude_process_1=require("./claude-process");function timestamp(){return utils_ok_1.dateUtil.mm(Date.now()).format("YYYY-MM-DD HH:mm:ss")}function getHomeDir(){return os_1.default.homedir()}function getClientDir(e){return path_1.default.join(getHomeDir(),".cc-ding",e.clientId)}function initClientDir(e,
|
|
2
|
-
`)}function readSessionLogTail(e,s
|
|
3
|
-
`).filter(c=>c.length>0).slice(-
|
|
4
|
-
`)}catch{return null}}function findHistorySession(e,s
|
|
5
|
-
`;try{fs_1.default.appendFileSync(t,i,"utf-8")}catch{}}function getActiveSessionsFile(e,
|
|
6
|
-
`,"utf-8");const r=i.messageQueue?.length??0;r>0&&(i.messageQueue=[],console.log(`[${timestamp()}] \u7ED3\u675F\u4F1A\u8BDD\u65F6\u6E05\u7A7A\u6D88\u606F\u961F\u5217: \u7FA4=${
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.timestamp=timestamp,exports.getHomeDir=getHomeDir,exports.getClientDir=getClientDir,exports.initClientDir=initClientDir,exports.ensureClientDir=ensureClientDir,exports.getClientConfig=getClientConfig,exports.resolveToUserId=resolveToUserId,exports.authCheck=authCheck,exports.isOwner=isOwner,exports.isAdmin=isAdmin,exports.isOwnerOrAdmin=isOwnerOrAdmin,exports.debugLog=debugLog,exports.isMobile=isMobile,exports.getPhoneMapFile=getPhoneMapFile,exports.loadPhoneMap=loadPhoneMap,exports.savePhoneMap=savePhoneMap,exports.userIdToPhone=userIdToPhone,exports.resolveUserId=resolveUserId,exports.resolveAllPhonesInConfig=resolveAllPhonesInConfig,exports.hashConversationId=hashConversationId,exports.getReplyWebhook=getReplyWebhook,exports.getReplyConversationId=getReplyConversationId,exports.findActiveSession=findActiveSession,exports.getConversationConfig=getConversationConfig,exports.getConversationDir=getConversationDir,exports.getSessionsDir=getSessionsDir,exports.getTasksDir=getTasksDir,exports.getImagesDir=getImagesDir,exports.getSessionDir=getSessionDir,exports.getSessionId=getSessionId,exports.formatSessionInfo=formatSessionInfo,exports.readSessionLogTail=readSessionLogTail,exports.findHistorySession=findHistorySession,exports.findLatestSession=findLatestSession,exports.updateSessionFile=updateSessionFile,exports.appendSessionLog=appendSessionLog,exports.getActiveSessionsFile=getActiveSessionsFile,exports.saveActiveSession=saveActiveSession,exports.loadActiveSessions=loadActiveSessions,exports.endSession=endSession,exports.switchToSession=switchToSession,exports.startNewSession=startNewSession,exports.processMessageQueue=processMessageQueue,exports.handleSessionMessage=handleSessionMessage,exports.cleanCache=cleanCache;const utils_ok_1=require("utils-ok"),fs_1=__importDefault(require("fs")),os_1=__importDefault(require("os")),assert_1=__importDefault(require("assert")),crypto_1=__importDefault(require("crypto")),path_1=__importDefault(require("path")),commands_1=require("./commands"),messaging_1=require("./messaging"),claude_process_1=require("./claude-process");function timestamp(){return utils_ok_1.dateUtil.mm(Date.now()).format("YYYY-MM-DD HH:mm:ss")}function getHomeDir(){return os_1.default.homedir()}function getClientDir(e){return path_1.default.join(getHomeDir(),".cc-ding",e.clientId)}function initClientDir(e,n){const s=path_1.default.join(getHomeDir(),".cc-ding",e),t=path_1.default.join(s,"config.json");return fs_1.default.mkdirSync(s,{recursive:!0}),fs_1.default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),t}function ensureClientDir(e){const n=path_1.default.join(getHomeDir(),".cc-ding",e),s=path_1.default.join(n,"config.json");if(fs_1.default.existsSync(s))return;console.log(`[${timestamp()}] \u5BA2\u6237\u7AEF\u76EE\u5F55\u672A\u521D\u59CB\u5316: ${n}`),console.log(`[${timestamp()}] \u6B63\u5728\u81EA\u52A8\u521D\u59CB\u5316...`),initClientDir(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(`[${timestamp()}] \u5DF2\u751F\u6210\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6: ${s}`),console.log(`[${timestamp()}] \u8BF7\u7F16\u8F91 config.json \u586B\u5199\u5FC5\u8981\u7684\u914D\u7F6E\u9879\u540E\u91CD\u65B0\u542F\u52A8`),process.exit(1)}function getClientConfig(e){const n=`${getClientDir(e)}/config.json`;(0,assert_1.default)(fs_1.default.existsSync(n),`Could not find client config file: ${n}`);const s=utils_ok_1.fileUtil.getJSON(n);return(0,assert_1.default)(s.clientSecret,"config.json missing required field: clientSecret"),(0,assert_1.default)(s.whiteUserList,"config.json missing required field: whiteUserList"),s}function resolveToUserId(e,n){return isMobile(n)&&e.resolvedPhones[n]||n}function authCheck(e,n,s){if(isOwnerOrAdmin(e,n))return!0;if(s){const t=e.config.conversations.find(o=>o.conversationId===s);if(t?.whiteUserList&&t.whiteUserList.length>0)return t.whiteUserList.some(o=>resolveToUserId(e,o)===n)}return e.config.whiteUserList.some(t=>resolveToUserId(e,t)===n)}function isOwner(e,n){const s=e.config.owner;if(!s||!isMobile(s))return!1;const t=e.resolvedPhones[s];return!!t&&t===n}function isAdmin(e,n){return e.config.adminUserList?.length?e.config.adminUserList.some(s=>resolveToUserId(e,s)===n):!1}function isOwnerOrAdmin(e,n){return isOwner(e,n)||isAdmin(e,n)}function debugLog(e,n,...s){e.config.debug&&console.log(`[DEBUG] ${n}`,...s)}const PHONE_RE=/^1\d{10}$/;function isMobile(e){return PHONE_RE.test(e)}function getPhoneMapFile(e){return path_1.default.join(getClientDir(e),"phone-map.json")}function loadPhoneMap(e){const n=getPhoneMapFile(e);if(!fs_1.default.existsSync(n))return{};try{const s=JSON.parse(fs_1.default.readFileSync(n,"utf-8"));if(typeof s=="object"&&s!==null)return s}catch{}return{}}function savePhoneMap(e,n){const s=getPhoneMapFile(e);try{fs_1.default.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}catch(t){console.error("\u4FDD\u5B58 phone-map.json \u5931\u8D25:",t)}}function userIdToPhone(e,n){for(const[s,t]of Object.entries(e.resolvedPhones))if(t===n)return s;return null}async function resolveUserId(e,n){if(!n)return null;if(!isMobile(n))return n;if(e.resolvedPhones[n])return e.resolvedPhones[n];const s=await(0,messaging_1.queryUserIdByMobile)(e,n);return s&&(e.resolvedPhones[n]=s,savePhoneMap(e,e.resolvedPhones)),s}async function resolveAllPhonesInConfig(e){e.resolvedPhones=loadPhoneMap(e);const n=[],s=async t=>{if(e.resolvedPhones[t])return;const o=await(0,messaging_1.queryUserIdByMobile)(e,t);o&&(e.resolvedPhones[t]=o,n.push(t))};e.config.owner&&(isMobile(e.config.owner)?(await s(e.config.owner),e.resolvedPhones[e.config.owner]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790 owner \u624B\u673A\u53F7: ${e.config.owner}`)):console.warn(`[WARN] owner \u5FC5\u987B\u4E3A\u624B\u673A\u53F7\uFF0C\u5F53\u524D\u503C\u65E0\u6548: ${e.config.owner}`));for(const t of e.config.whiteUserList)isMobile(t)&&(await s(t),e.resolvedPhones[t]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790 whiteUserList \u624B\u673A\u53F7: ${t}`));for(const t of e.config.conversations)if(t.whiteUserList)for(const o of t.whiteUserList)isMobile(o)&&(await s(o),e.resolvedPhones[o]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790\u7FA4\u767D\u540D\u5355\u624B\u673A\u53F7: ${o}`));n.length>0&&savePhoneMap(e,e.resolvedPhones),console.log(`[\u624B\u673A\u89E3\u6790] \u5DF2\u52A0\u8F7D ${Object.keys(e.resolvedPhones).length} \u6761\u8BB0\u5F55 (${n.length} \u6761\u65B0\u89E3\u6790)`)}function hashConversationId(e,n){const t=getConversationConfig(e,n)?.linkConversationId||n;return crypto_1.default.createHash("md5").update(t).digest("hex")}function getReplyWebhook(e){return e.currentWebhook||e.sessionWebhook}function getReplyConversationId(e){return e.currentConversationId||e.conversationId}function findActiveSession(e,n){const s=e.activeSessions.get(n);if(s)return{key:n,session:s};const t=getConversationConfig(e,n);if(t?.linkConversationId){for(const o of e.activeSessions)if(getConversationConfig(e,o[0])?.linkConversationId===t.linkConversationId)return{key:o[0],session:o[1]}}}function getConversationConfig(e,n){return e.config.conversations.find(s=>s.conversationId===n)}function getConversationDir(e,n){const s=hashConversationId(e,n);return`${getClientDir(e)}/${s}`}function getSessionsDir(e,n){return`${getConversationDir(e,n)}/.sessions`}function getTasksDir(e,n){return`${getConversationDir(e,n)}/.tasks`}function getImagesDir(e,n){return`${getConversationDir(e,n)}/.images`}function getSessionDir(e,n){const s=n.claudeSessionId||n.startTimeStr;return`${getSessionsDir(e,n.conversationId)}/${s}`}function getSessionId(e){return e.claudeSessionId||e.startTimeStr}function formatSessionInfo(e,n){const s=findActiveSession(e,n);if(!s)return null;const{session:t,isProcessing:o,messageQueue:i}=s.session;return[`- **\u4F1A\u8BDDID:** ${getSessionId(t)}`,`- **\u53D1\u8D77\u8005:** ${t.startNickName}(${t.startStaffId})`,`- **\u5F00\u59CB\u65F6\u95F4:** ${t.startTimeStr}`,`- **\u6700\u540E\u53D1\u9001\u8005:** ${s.session.lastSenderStaffId}`,`- **\u5904\u7406\u4E2D:** ${o}`,`- **\u6392\u961F\u6D88\u606F:** ${i?.length||0} \u6761`].join(`
|
|
2
|
+
`)}function readSessionLogTail(e,n,s){const t=findActiveSession(e,n);if(!t)return null;const o=t.session,i=`${getSessionDir(e,o.session)}/session.log`;if(!fs_1.default.existsSync(i))return null;try{return fs_1.default.readFileSync(i,"utf-8").split(`
|
|
3
|
+
`).filter(c=>c.length>0).slice(-s).join(`
|
|
4
|
+
`)}catch{return null}}function findHistorySession(e,n,s){const t=getSessionsDir(e,n),o=`${t}/${s}/session.json`;try{return utils_ok_1.fileUtil.getJSON(o)}catch{}const i=parseInt(s,10);if(!isNaN(i)&&i>0){const u=utils_ok_1.dateUtil.mm(i).format("YYYY-MM-DD-HH-mm-ss"),a=`${t}/${u}/session.json`;try{return utils_ok_1.fileUtil.getJSON(a)}catch{}}return null}function findLatestSession(e,n){const s=getSessionsDir(e,n);if(!fs_1.default.existsSync(s))return null;const t=findActiveSession(e,n),o=t?getSessionId(t.session.session):null;let i=null,u=0;try{const a=fs_1.default.readdirSync(s,{withFileTypes:!0});for(const c of a){if(!c.isDirectory())continue;const r=path_1.default.join(s,c.name,"session.json");if(fs_1.default.existsSync(r))try{const l=utils_ok_1.fileUtil.getJSON(r);if(o&&getSessionId(l)===o)continue;l.startTime>u&&(u=l.startTime,i=l)}catch{continue}}}catch{}return i}function updateSessionFile(e,n,s){if(s.claudeSessionId&&!n.claudeSessionId){const o=getSessionDir(e,n);n.claudeSessionId=s.claudeSessionId;const i=getSessionDir(e,n);o!==i&&fs_1.default.existsSync(o)&&(fs_1.default.renameSync(o,i),console.log(`[${timestamp()}] \u4F1A\u8BDD\u76EE\u5F55\u91CD\u547D\u540D: ${path_1.default.basename(o)} -> ${path_1.default.basename(i)}`))}const t=`${getSessionDir(e,n)}/session.json`;try{s.sessionWebhook&&(n.sessionWebhook=s.sessionWebhook),s.currentWebhook!==void 0&&(n.currentWebhook=s.currentWebhook||void 0),s.currentConversationId!==void 0&&(n.currentConversationId=s.currentConversationId||void 0),fs_1.default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8");const o=s.claudeSessionId?"claudeSessionId":s.currentWebhook!==void 0?"currentWebhook":"sessionWebhook";console.log(`[${timestamp()}] \u4F1A\u8BDD\u6587\u4EF6\u5DF2\u4FDD\u5B58: ${o}`),saveActiveSession(e,n.conversationId)}catch(o){console.error("\u66F4\u65B0 session.json \u5931\u8D25:",o)}}function appendSessionLog(e,n,s){const t=`${e}/session.log`,i=`[${timestamp()}] [${n.toUpperCase()}]: ${s}
|
|
5
|
+
`;try{fs_1.default.appendFileSync(t,i,"utf-8")}catch{}}function getActiveSessionsFile(e,n){return`${getSessionsDir(e,n)}/active.json`}function saveActiveSession(e,n){const s=e.activeSessions.get(n),t=getActiveSessionsFile(e,n);try{if(!s){fs_1.default.existsSync(t)&&fs_1.default.unlinkSync(t);return}const o={session:s.session,lastSenderStaffId:s.lastSenderStaffId,conversationConfig:s.conversationConfig};fs_1.default.mkdirSync(path_1.default.dirname(t),{recursive:!0}),fs_1.default.writeFileSync(t,JSON.stringify(o,null,2),"utf-8"),debugLog(e,`\u6D3B\u8DC3\u4F1A\u8BDD\u5DF2\u6301\u4E45\u5316: \u7FA4=${n}`)}catch(o){console.error(`\u6301\u4E45\u5316\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: \u7FA4=${n}`,o)}}function loadActiveSessions(e){for(const n of e.config.conversations){const s=getActiveSessionsFile(e,n.conversationId);if(fs_1.default.existsSync(s))try{const t=utils_ok_1.fileUtil.getJSON(s);if(!t?.session){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u65E0\u6548\uFF0C\u8DF3\u8FC7: ${s}`);continue}const o=getSessionDir(e,t.session);if(!fs_1.default.existsSync(o)){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728\uFF0C\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6: ${s}`),fs_1.default.unlinkSync(s);continue}e.activeSessions.set(n.conversationId,{session:t.session,lastSenderStaffId:t.lastSenderStaffId||t.session.startStaffId,isProcessing:!1,messageQueue:[],conversationConfig:t.conversationConfig}),console.log(`\u6062\u590D\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${n.conversationId}, \u4F1A\u8BDDID=${getSessionId(t.session)}`)}catch(t){console.error(`\u52A0\u8F7D\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: ${s}`,t)}}}async function endSession(e,n,s){const t=findActiveSession(e,n);if(!t){console.log(`\u7FA4 ${n} \u65E0\u6D3B\u8DC3\u4F1A\u8BDD`);return}const{key:o,session:i}=t,{session:u}=i,a=getSessionDir(e,u),c=getSessionId(u);console.log(`\u7ED3\u675F\u4F1A\u8BDD: \u7FA4=${n}, \u4F1A\u8BDDID=${c}`),(0,claude_process_1.interruptClaudeProcess)(i,"\u7ED3\u675F\u4F1A\u8BDD\u65F6\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Claude \u8FDB\u7A0B")&&fs_1.default.appendFileSync(`${a}/session.log`,`[${timestamp()}] [SYSTEM]: \u7ED3\u675F\u4F1A\u8BDD\u65F6\u4E2D\u65AD Claude \u8FDB\u7A0B
|
|
6
|
+
`,"utf-8");const r=i.messageQueue?.length??0;r>0&&(i.messageQueue=[],console.log(`[${timestamp()}] \u7ED3\u675F\u4F1A\u8BDD\u65F6\u6E05\u7A7A\u6D88\u606F\u961F\u5217: \u7FA4=${n}, \u6E05\u7A7A${r}\u6761\u6D88\u606F`)),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:u.startStaffId,content:`\u{1F4AC} \u4F1A\u8BDD\u5DF2\u7ED3\u675F
|
|
7
7
|
\u{1F4CB} \u4F1A\u8BDDID: ${c}${r>0?`
|
|
8
|
-
\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u4E22\u5F03${r}\u6761\u5F85\u5904\u7406\u6D88\u606F`:""}`}),e.activeSessions.delete(o),saveActiveSession(e,o),fs_1.default.appendFileSync(`${
|
|
9
|
-
`,"utf-8")}async function switchToSession(e,s,
|
|
10
|
-
`,"utf-8")),e.activeSessions.set(
|
|
8
|
+
\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u4E22\u5F03${r}\u6761\u5F85\u5904\u7406\u6D88\u606F`:""}`}),e.activeSessions.delete(o),saveActiveSession(e,o),fs_1.default.appendFileSync(`${a}/session.log`,`[${timestamp()}] [SYSTEM]: \u7528\u6237\u8BF7\u6C42\u7ED3\u675F\u4F1A\u8BDD
|
|
9
|
+
`,"utf-8")}async function switchToSession(e,n,s,t,o,i){const u=findHistorySession(e,n,t);if(!u)return await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u672A\u627E\u5230\u4F1A\u8BDD ${t}\uFF0C\u8BE5\u4F1A\u8BDD\u53EF\u80FD\u5DF2\u88AB\u6E05\u7406\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u59CB\u65B0\u4F1A\u8BDD`}),!1;const a=getSessionDir(e,u);if(!fs_1.default.existsSync(a))return await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u4F1A\u8BDD ${t} \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 c=findActiveSession(e,n);c&&(console.log(`\u5207\u6362\u4F1A\u8BDD\uFF0C\u5148\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD: ${getSessionId(c.session.session)}`),(0,claude_process_1.interruptClaudeProcess)(c.session,"\u5207\u6362\u4F1A\u8BDD\u65F6\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Claude \u8FDB\u7A0B"),e.activeSessions.delete(c.key),saveActiveSession(e,c.key),fs_1.default.appendFileSync(`${getSessionDir(e,c.session.session)}/session.log`,`[${timestamp()}] [SYSTEM]: \u4F1A\u8BDD\u88AB\u5207\u6362\u5230 ${t}\uFF0C\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD
|
|
10
|
+
`,"utf-8")),e.activeSessions.set(n,{session:u,lastSenderStaffId:o,isProcessing:!1,messageQueue:[],conversationConfig:i}),saveActiveSession(e,n);const r=!!u.claudeSessionId,l=getSessionId(u);return await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u2705 \u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD (\u4F1A\u8BDDID: ${l})
|
|
11
11
|
${r?"\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"}
|
|
12
|
-
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`}),console.log(`\u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD: \u7FA4=${
|
|
12
|
+
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`}),console.log(`\u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD: \u7FA4=${n}, \u4F1A\u8BDDID=${l}, \u6709Claude\u4E0A\u4E0B\u6587=${r}`),!0}async function startNewSession(e,n){const{conversationId:s,sessionWebhook:t,senderStaffId:o,senderNick:i,message:u,conversationConfig:a}=n,c=e.config.sessionMaxConcurrency??e.DEFAULT_SESSION_MAX_CONCURRENCY;if(e.activeSessions.size>=c){console.log(`\u8FBE\u5230\u6700\u5927\u5E76\u53D1\u6570 (${c})\uFF0C\u62D2\u7EDD\u65B0\u4F1A\u8BDD: \u7FA4=${s}`),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:"\u{1F92F} \u5F53\u524D\u7E41\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5..."});return}const r=Date.now(),l={conversationId:s,sessionWebhook:t,startTime:r,startTimeStr:utils_ok_1.dateUtil.mm(r).format("YYYY-MM-DD-HH-mm-ss"),startStaffId:o,startNickName:i};console.log(`\u521B\u5EFA\u65B0\u4F1A\u8BDD: \u7FA4=${s}, \u4F1A\u8BDDID=${getSessionId(l)}, \u53D1\u8D77\u8005=${o}, \u5F53\u524D\u5E76\u53D1=${e.activeSessions.size+1}/${c}`);const f=getSessionDir(e,l);fs_1.default.mkdirSync(f,{recursive:!0}),fs_1.default.writeFileSync(`${f}/session.json`,JSON.stringify(l,null,2),"utf-8"),e.activeSessions.set(s,{session:l,lastSenderStaffId:o,isProcessing:!0,messageQueue:[],conversationConfig:a}),saveActiveSession(e,s),a.receiveReply!==!1&&await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:`\u{1F680} \u4F1A\u8BDD\u5DF2\u5F00\u59CB\uFF01
|
|
13
13
|
\u5904\u7406\u4E2D...
|
|
14
|
-
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`});try{await(0,claude_process_1.executeClaudeQuery)(e,
|
|
14
|
+
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`});try{await(0,claude_process_1.executeClaudeQuery)(e,l,u,{skill:a.taskCfg?.skill,agent:a.agent,senderNick:i,senderStaffId:o,permissionMode:a.permissionMode})}catch(d){console.error("\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",d),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${d instanceof Error?d.message:String(d)}`})}finally{const d=e.activeSessions.get(s);d&&(d.isProcessing=!1)}const g=e.activeSessions.get(s);g&&g.messageQueue.length>0&&await processMessageQueue(e,s)}async function processMessageQueue(e,n){const s=e.activeSessions.get(n);if(!s||s.messageQueue.length===0)return;const t=s.messageQueue.shift(),{message:o,senderStaffId:i,senderNick:u}=t,a=s.session.sessionWebhook;console.log(`\u5904\u7406\u961F\u5217\u6D88\u606F: \u7FA4=${n}, \u5269\u4F59 ${s.messageQueue.length} \u6761`),s.isProcessing=!0,s.lastSenderStaffId=i,saveActiveSession(e,n),s.conversationConfig.receiveReply!==!1&&await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:a,atUserId:i,content:"\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406..."}).catch(()=>{});try{await(0,claude_process_1.executeClaudeQuery)(e,s.session,o,{skill:s.conversationConfig.taskCfg?.skill,agent:s.conversationConfig.agent,senderNick:u,senderStaffId:i,permissionMode:s.conversationConfig.permissionMode})}catch(c){console.error("\u6267\u884C\u961F\u5217 Claude \u67E5\u8BE2\u5931\u8D25:",c),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:a,atUserId:i,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${c instanceof Error?c.message:String(c)}`})}finally{s.isProcessing=!1}if(s.goonPending){s.goonPending=!1,s.interrupted=!1,s.isProcessing=!0;try{await(0,claude_process_1.executeClaudeQuery)(e,s.session,"\u7EE7\u7EED",{senderNick:s.session.startNickName,senderStaffId:s.lastSenderStaffId,permissionMode:s.conversationConfig.permissionMode})}catch(c){console.error("goonPending \u6062\u590D\u6267\u884C\u5931\u8D25:",c)}finally{s.isProcessing=!1}}s.messageQueue.length>0&&await processMessageQueue(e,n)}async function handleSessionMessage(e,n){const{conversationId:s,sessionWebhook:t,senderStaffId:o,senderNick:i,message:u,conversationConfig:a}=n;if((0,commands_1.parseEndCommand)(u)){await endSession(e,s,t);return}const c=findActiveSession(e,s),r=c?.session;if(r){const l=getSessionDir(e,r.session);if(fs_1.default.existsSync(l)||(fs_1.default.mkdirSync(l,{recursive:!0}),fs_1.default.writeFileSync(`${l}/session.json`,JSON.stringify(r.session,null,2),"utf-8"),console.log(`\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u91CD\u5EFA: \u7FA4=${s}, \u8DEF\u5F84=${l}`)),r.isProcessing){const g={message:u,senderStaffId:o,senderNick:i};r.messageQueue.push(g);const d=r.messageQueue.length;console.log(`\u4F1A\u8BDD ${s} \u6D88\u606F\u5DF2\u5165\u961F\uFF0C\u6392\u961F\u7B2C ${d} \u6761`),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:`\u23F3 \u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u5DF2\u52A0\u5165\u961F\u5217\uFF08\u6392\u961F\u7B2C ${d} \u6761\uFF09`});return}const f=r.session.conversationId===s;console.log(`\u8FFD\u52A0\u6D88\u606F\u5230\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${s}, \u4F1A\u8BDDID=${getSessionId(r.session)}${f?"":`(\u5173\u8054\u7FA4,\u4F1A\u8BDD\u5F52\u5C5E=${r.session.conversationId})`}`),r.lastSenderStaffId=o,r.isProcessing=!0,saveActiveSession(e,c.key),f&&t!==r.session.sessionWebhook&&(r.session.sessionWebhook=t,updateSessionFile(e,r.session,{sessionWebhook:t})),r.session.currentWebhook=t,r.session.currentConversationId=s,updateSessionFile(e,r.session,{currentWebhook:t,currentConversationId:s}),a.receiveReply!==!1&&await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:"\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406..."});try{await(0,claude_process_1.executeClaudeQuery)(e,r.session,u,{skill:a.taskCfg?.skill,agent:a.agent,senderNick:i,senderStaffId:o,permissionMode:a.permissionMode})}catch(g){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{await(0,claude_process_1.executeClaudeQuery)(e,r.session,u,{skill:a.taskCfg?.skill,agent:a.agent,senderNick:i,senderStaffId:o,permissionMode:a.permissionMode});return}catch(d){console.error("\u91CD\u8BD5\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",d),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${d instanceof Error?d.message:String(d)}`}),r.isProcessing=!1,await processMessageQueue(e,s);return}}console.error("\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",g),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:t,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${g instanceof Error?g.message:String(g)}`})}finally{r.isProcessing=!1}await processMessageQueue(e,s)}else await startNewSession(e,{conversationId:s,sessionWebhook:t,senderStaffId:o,senderNick:i,message:u,conversationConfig:a})}function cleanCache(e,n,s=!0){const t={sessionsDeleted:0,tasksDeleted:0,imagesDeleted:0,errors:[]},o=n?[n]:e.config.conversations.map(i=>i.conversationId);for(const i of o){let u=null;if(s){const f=findActiveSession(e,i);f&&(u=getSessionId(f.session.session))}const a=getSessionsDir(e,i);if(fs_1.default.existsSync(a))try{const f=fs_1.default.readdirSync(a,{withFileTypes:!0});for(const g of f){if(!g.isDirectory()||u&&g.name===u)continue;const d=path_1.default.join(a,g.name);try{fs_1.default.rmSync(d,{recursive:!0,force:!0}),t.sessionsDeleted++}catch{t.errors.push(`\u5220\u9664\u4F1A\u8BDD\u76EE\u5F55\u5931\u8D25: ${d}`)}}}catch{t.errors.push(`\u8BFB\u53D6sessions\u76EE\u5F55\u5931\u8D25: ${a}`)}const c=getTasksDir(e,i);if(fs_1.default.existsSync(c))try{const f=fs_1.default.readdirSync(c,{withFileTypes:!0});for(const g of f){if(!g.isDirectory())continue;const d=path_1.default.join(c,g.name);try{fs_1.default.rmSync(d,{recursive:!0,force:!0}),t.tasksDeleted++}catch{t.errors.push(`\u5220\u9664\u4EFB\u52A1\u76EE\u5F55\u5931\u8D25: ${d}`)}}}catch{t.errors.push(`\u8BFB\u53D6tasks\u76EE\u5F55\u5931\u8D25: ${c}`)}const r=getImagesDir(e,i);if(fs_1.default.existsSync(r))try{const f=fs_1.default.readdirSync(r,{withFileTypes:!0});for(const g of f){const d=path_1.default.join(r,g.name);try{fs_1.default.unlinkSync(d),t.imagesDeleted++}catch{t.errors.push(`\u5220\u9664\u56FE\u7247\u5931\u8D25: ${d}`)}}}catch{t.errors.push(`\u8BFB\u53D6images\u76EE\u5F55\u5931\u8D25: ${r}`)}const l=path_1.default.join(getConversationDir(e,i),".playwright-cli");if(fs_1.default.existsSync(l))try{fs_1.default.rmSync(l,{recursive:!0,force:!0})}catch{t.errors.push(`\u5220\u9664 playwright-cli \u7F13\u5B58\u5931\u8D25: ${l}`)}if(!s){const f=getActiveSessionsFile(e,i);if(fs_1.default.existsSync(f))try{fs_1.default.unlinkSync(f)}catch{t.errors.push(`\u5220\u9664\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u5931\u8D25: ${f}`)}e.activeSessions.has(i)&&e.activeSessions.delete(i)}}return t}
|