cc-ding 0.1.0 → 0.2.0
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 +249 -85
- package/dist/bin/cc-ding.js +1 -1
- package/dist/src/biz/cc-ding-cli.js +40 -40
- package/dist/src/biz/claude-process.js +27 -27
- package/dist/src/biz/commands.js +6 -6
- package/dist/src/biz/image.js +11 -10
- package/dist/src/biz/menu.js +3 -0
- package/dist/src/biz/messaging.js +5 -5
- package/dist/src/biz/quote.js +7 -3
- package/dist/src/biz/recorder.js +9 -9
- package/dist/src/biz/session.js +12 -11
- package/dist/src/biz/todo.js +8 -0
- package/package.json +1 -1
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;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(\u6392\u961F\u4E2D\u7684\u6D88\u606F)",usage:"/mq | /mq -n <\u6570\u91CF> | /mq -all",examples:["/mq","/mq -n 1","/mq -n 3","/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\u5F53\u524D\u7FA4\u767D\u540D\u5355(add/del/approve/reject,\u9ED8\u8BA4list)",usage:"/auth [add|del <\u624B\u673A\u53F7\u6216userId>] | /auth [approve|reject <requestId>]",examples:["/auth","/auth add 13800138000","/auth del 13800138000","/auth approve r1234","/auth reject r1234"],category:"\u7BA1\u7406",ownerOnly:!0},{name:"/recorder",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"],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 s=e.trim().match(/^(\/\w+)\s+--help$/i);return s?s[1].toLowerCase():null}function getCommandByName(e){const t=e.toLowerCase();return COMMAND_REGISTRY.find(s=>s.name.toLowerCase()===t||s.aliases?.some(r=>r.toLowerCase()===t))}function formatHelpOverview(e,t){const s=COMMAND_REGISTRY.filter(n=>t||!n.ownerOnly),r=["### \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 a=s.filter(i=>i.category===n);if(a.length!==0){r.push(`${o} **${n}**`);for(const i of a)r.push(`- \`${i.name}\` ${i.description}`);r.push("")}}return r.push("\u{1F4A1} \u8F93\u5165 `/{\u547D\u4EE4} --help` \u67E5\u770B\u547D\u4EE4\u8BE6\u7EC6\u7528\u6CD5"),r.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,s
|
|
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.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 r of e.examples)t.push(`- \`${r}\``);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,r,s){const n=[`- **\u7FA4ID:** ${t}`];if(e.conversationTitle&&n.push(`- **\u7FA4\u540D\u79F0:** ${e.conversationTitle}`),e.conversationType&&n.push(`- **\u4F1A\u8BDD\u7C7B\u578B:** ${e.conversationType==="1"?"\u5355\u804A":e.conversationType==="2"?"\u7FA4\u804A":e.conversationType}`),s&&n.push(`- **\u5DE5\u4F5C\u76EE\u5F55:** \`${s}\``),e.linkConversationId&&n.push(`- **\u5173\u8054\u4F1A\u8BDDID:** ${e.linkConversationId}`),e.agent&&n.push(`- **agent:** ${e.agent}`),e.dingToken&&n.push(`- **dingToken:** ${e.dingToken.substring(0,8)}...`),e.whiteUserList?.length){const o=e.whiteUserList.map(i=>r?.(i)||i).join(", ");n.push(`- **\u7FA4\u767D\u540D\u5355:** ${o}`)}return e.atSender===!1&&n.push("- **atSender:** false"),e.receiveReply===!1&&n.push("- **receiveReply:** false (\u4E0D\u56DE\u590D\u786E\u8BA4\u6D88\u606F)"),e.useLocalOcr===!1&&n.push("- **\u672C\u5730OCR:** \u5173\u95ED"),e.taskCfg?.skill&&n.push(`- **taskSkill:** ${e.taskCfg.skill}`),e.preBash&&n.push(`- **preBash:** \`${e.preBash}\``),n.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 r=e.apiKeyCfg.claudeSettings.filter(s=>s.isValid).length;t.push(`- **apiKeyCfg:** ${r}/${e.apiKeyCfg.claudeSettings.length} \u6709\u6548`),t.push(` - **\u6700\u8FD1\u91CD\u7F6E:** ${e.apiKeyCfg.resetTime||"-"}`)}return t.join(`
|
|
5
|
+
`)}function parseLogCommand(e){const r=e.trim().match(/^\/log(?:\s+(\d+))?$/i);if(!r)return null;const s=parseInt(r[1],10);return isNaN(s)||s<=0?10:s}function parseLsCommand(e){const r=e.trim().match(/^\/ls(?:\s+(.+))?$/i);if(!r)return null;if(r[1]===void 0)return{target:"",depth:1};const s=r[1].trim().split(/\s+/),n=s[0]||"",o=s[1]?parseInt(s[1],10):1;return{target:n,depth:isNaN(o)||o<0?1:Math.min(o,5)}}function findSubdirByName(e,t,r=3){const s=[{dir:e,depth:0}];for(;s.length>0;){const{dir:n,depth:o}=s.shift();if(!(o>r))try{const i=fs_1.default.readdirSync(n,{withFileTypes:!0});for(const a of i)if(!(!a.isDirectory()||a.name.startsWith("."))){if(a.name===t)return path_1.default.join(n,a.name);s.push({dir:path_1.default.join(n,a.name),depth:o+1})}}catch{continue}}return null}function getDirectoryStructure(e,t=0,r=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 n=[],o=". ".repeat(t);for(const i of s){const a=i.isDirectory()?"\u{1F4C1} ":"\u{1F4C4} ",d=i.isDirectory()?"/":"";if(n.push(`${o}${a}${i.name}${d}`),i.isDirectory()&&t<r){const c=path_1.default.join(e,i.name),m=getDirectoryStructure(c,t+1,r);m&&n.push(m)}}return n.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(r=>/^[\d*/\-]+$/.test(r))}function parseCronCommand(e){const t=e.trim();if(!t.toLowerCase().startsWith("/cron"))return null;const r=t.substring(5).trim();if(!r)return null;if(/^(list|ls)$/i.test(r))return{type:"list"};const s=r.match(/^(?:delete|rm)\s+(\S+)$/i);if(s)return{type:"delete",id:s[1]};const n=r.match(/^pause\s+(\S+)$/i);if(n)return{type:"pause",id:n[1]};const o=r.match(/^resume\s+(\S+)$/i);if(o)return{type:"resume",id:o[1]};const i=r.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:r}}function parsePwdCommand(e){return e.trim()==="/pwd"}function parseVersionCommand(e){return e.trim()==="/version"}function parsePathCommand(e,t){const s=e.trim().match(new RegExp(`^\\/${t}\\s+(.+)$`));return s&&s[1].trim()||null}function parseMkdirCommand(e){return parsePathCommand(e,"mkdir")}function parseTouchCommand(e){return parsePathCommand(e,"touch")}function parseRmCommand(e){return parsePathCommand(e,"rm")}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 r=t.substring(4).trim();if(!r)return{};if(/^--help$/i.test(r))return null;const s={},n=r.split(/\s+/);for(let o=0;o<n.length;o++){const i=n[o];if(i==="--dingToken"&&n[o+1])s.dingToken=n[++o];else if(i==="--linkConversationId"&&n[o+1])s.linkConversationId=n[++o];else if(i==="--conversationId"&&n[o+1])s.conversationId=n[++o];else if(i==="--whiteUserList"&&n[o+1])s.whiteUserList=n[++o].split(",").map(a=>a.trim()).filter(Boolean);else if(i==="--conversationTitle"&&n[o+1]){const a=[];for(;o+1<n.length&&!n[o+1].startsWith("--");)a.push(n[++o]);a.length>0&&(s.conversationTitle=a.join(" "))}else if(i==="--atSender"&&n[o+1]){const a=n[++o].toLowerCase();s.atSender=a==="true"||a==="1"||a==="yes"}else if(i==="--receiveReply"&&n[o+1]){const a=n[++o].toLowerCase();s.receiveReply=a==="true"||a==="1"||a==="yes"}else if(i==="--preBash"&&n[o+1]){const a=[];for(;o+1<n.length&&!n[o+1].startsWith("--");)a.push(n[++o]);a.length>0&&(s.preBash=a.join(" ").replace(/^["']|["']$/g,""))}}return s}function parseBashCommand(e){const r=e.trim().match(/^\/bash\s+(.+)$/i);return r&&r[1].trim()||null}function parseMqCommand(e){const t=e.trim();if(!/^\/mq(?:\s|$)/i.test(t)&&t.toLowerCase()!=="/mq")return null;const r=t.substring(3).trim();if(!r)return{type:"list"};if(/^front$/i.test(r))return{type:"front"};const s=r.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 c=parseInt(a[1],10),m=parseInt(a[2],10);if(c>0&&m>=c){for(let u=c;u<=m;u++)i.push(u);return{type:"rm",indices:i}}}const d=o.split(/\s+/);for(const c of d){const m=parseInt(c,10);m>0&&i.push(m)}if(i.length>0)return{type:"rm",indices:i}}const n=r.match(/^-n\s+(\d+)$/i);if(n){const o=parseInt(n[1],10);return o>0?{type:"cancel",count:o}:{type:"list"}}return/^-all$/i.test(r)?{type:"cancelAll"}:null}function parseAuthCommand(e){const t=e.trim(),r=t.match(/^\/auth\s+admin\s+add\s+(\S+)$/i);if(r)return{type:"adminAdd",staffId:r[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 n=t.match(/^\/auth\s+add\s+(\S+)$/i);if(n)return{type:"add",staffId:n[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 r=e.trim().match(/^\/cc\s+(.+)$/i);if(!r)return null;const s=r[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 r=t.substring(5).trim();if(/^list$/i.test(r))return{type:"list"};if(!r)return{type:"list"};const s=r.match(/^done\s+(\d+)$/i);if(s)return{type:"done",index:parseInt(s[1],10)};if(/^rm\s+all$/i.test(r))return{type:"remove",index:"all"};const n=r.match(/^rm\s+(\d+)$/i);if(n)return{type:"remove",index:parseInt(n[1],10)};if(/^remind\s+-1$/i.test(r))return{type:"remind",hour:null};const o=r.match(/^remind\s+(\d+)$/i);if(o){const u=parseInt(o[1],10);return u>=0&&u<=23?{type:"remind",hour:u}:null}let i=r,a,d;const c=i.match(/@(\S+)/);c&&(a=c[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 r=t.substring(5).trim(),s=r.startsWith("-g "),n=s?r.substring(3).trim():r;if(!r)return{type:"show"};if(s&&!n)return{type:"list",isGlobal:!0};const o=n.match(/^trigger\s+(\S+)$/i);if(o&&!s)return{type:"trigger",word:o[1]};const i=n.match(/^add\s+(.+)$/i);if(i)return{type:"add",command:i[1].trim(),isGlobal:s};const a=n.match(/^del(?:ete)?\s+(\d+)$/i);return a?{type:"del",index:parseInt(a[1],10),isGlobal:s}:/^list$/i.test(n)?{type:"list",isGlobal:s}:s?null:{type:"show"}}function parseRebootCommand(e){const t=e.trim();if(!/^\/reboot(?:\s|$)/i.test(t))return null;const r=t.substring(7).trim();if(!r)return{update:!1};const s=r.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/image.js
CHANGED
|
@@ -1,12 +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;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,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(
|
|
2
|
-
${n}
|
|
3
|
-
---
|
|
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(g){return console.warn(`[${(0,session_1.timestamp)()}] \u56FE\u7247\u4FDD\u5B58\u5931\u8D25: ${c}`,g),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}
|
|
4
2
|
${s}
|
|
5
|
-
---`}console.warn(`[${(0,session_1.timestamp)()}] OCR \u5931\u8D25\uFF0C\u4EC5\u4F20\u539F\u56FE\u8DEF\u5F84: ${e.filePath}`)}return`${a} ${e.filePath}`}async function processPictureMessage(e,t,o,a,s=!0,n){const l=await downloadAndProcessImage(e,t,o,a);if(!l)return null;const f=await buildImagePrompt(l,s),u=[];return s&&u.push(OCR_PREAMBLE),n&&u.push(n),u.push(f),u.join(`
|
|
6
|
-
`)}async function processRichTextMessage(e,t,o,a,s=!0){const n=t.filter(r=>r.type==="picture"&&(r.downloadCode||r.pictureDownloadCode)).length,l=t.map(async(r,i)=>{if(r.type==="picture"){const m=r.downloadCode||r.pictureDownloadCode;if(m){const c=await downloadAndProcessImage(e,m,o,a);return{index:i,result:c}}}return{index:i,result:null}}),f=await Promise.all(l),u=new Map;for(const{index:r,result:i}of f)u.set(r,i);const g=new Map;if(s&&n>0){const r=[];for(const[m,c]of u)c&&r.push(runOcr(c.filePath).then(w=>({index:m,ocrText:w})));const i=await Promise.all(r);for(const{index:m,ocrText:c}of i)g.set(m,c)}const d=[];let p=0;for(let r=0;r<t.length;r++){const i=t[r];if(i.type==="text"&&i.text){if(/^@\S+$/.test(i.text.trim()))continue;d.push(i.text)}else if(i.type==="mention"&&i.userId)d.push(`@${i.userId}`);else if(i.type==="picture"){const m=u.get(r);if(m){p++;const c=n>1?p:void 0,w=s?g.get(r):null,h=c!=null?`[\u56FE\u7247 ${c}]`:"[\u56FE\u7247]";if(w){const x=c!=null?`[\u56FE\u7247 ${c} OCR]`:"[\u56FE\u7247 OCR]";d.push(`${h} ${m.filePath}
|
|
7
|
-
${x}
|
|
8
3
|
---
|
|
9
|
-
${
|
|
10
|
-
---`)}
|
|
11
|
-
`)||"[\
|
|
12
|
-
${
|
|
4
|
+
${t}
|
|
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 x=i.downloadCode||i.pictureDownloadCode;if(x){const p=await downloadAndProcessImage(e,x,r,o);return{index:l,result:p}}}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[x,p]of f)p&&i.push(runOcr(p.filePath).then($=>({index:x,ocrText:$})));const l=await Promise.all(i);for(const{index:x,ocrText:p}of l)d.set(x,p)}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)m.push(`@${l.userId}`);else if(l.type==="picture"){const x=f.get(i);if(x){c++;const p=s>1?c:void 0,$=t?d.get(i):null,w=p!=null?`[\u56FE\u7247 ${p}]`:"[\u56FE\u7247]";if($){const y=p!=null?`[\u56FE\u7247 ${p} OCR]`:"[\u56FE\u7247 OCR]";m.push(`${w} ${x.filePath}
|
|
7
|
+
${y}
|
|
8
|
+
---
|
|
9
|
+
${$}
|
|
10
|
+
---`)}else m.push(`${w} ${x.filePath}`)}else(l.downloadCode||l.pictureDownloadCode)&&m.push("[\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25]")}}const g=m.join(`
|
|
11
|
+
`)||"[\u5BCC\u6587\u672C\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A]";return t&&c>0?`${OCR_PREAMBLE}
|
|
12
|
+
${g}`:g}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("."),g=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,`${g}_${l}${i}`));)l++;d=`${g}_${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 g=(a.length/1024).toFixed(1);console.log(`[${(0,session_1.timestamp)()}] \u6587\u4EF6\u5DF2\u4FDD\u5B58: ${c} (${g}KB${u?`, ${u}`:""})`);const i=[];return i.push(`[\u6587\u4EF6] \u6536\u5230\u4E00\u4E2A\u6587\u4EF6${u?`\uFF08${u}\uFF09`:""}\uFF0C\u5927\u5C0F ${g}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
|
+
`)}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadMenuData=loadMenuData,exports.setPendingSelection=setPendingSelection,exports.getPendingSelection=getPendingSelection,exports.clearPendingSelection=clearPendingSelection,exports.hasPendingSelection=hasPendingSelection,exports.startSelectionCleanupTimer=startSelectionCleanupTimer,exports.getUserTrigger=getUserTrigger,exports.setUserTrigger=setUserTrigger,exports.getAllTriggerWords=getAllTriggerWords,exports.getMergedMenu=getMergedMenu,exports.addMenuItem=addMenuItem,exports.deleteMenuItem=deleteMenuItem,exports.formatMenuDisplay=formatMenuDisplay,exports.formatMenuList=formatMenuList;const fs_1=__importDefault(require("fs")),utils_ok_1=require("utils-ok"),session_1=require("./session");function getMenuFile(e){return`${(0,session_1.getClientDir)(e)}/menu.json`}function loadMenuData(e){const t=getMenuFile(e);try{const n=JSON.parse(fs_1.default.readFileSync(t,"utf-8"));return{global:Array.isArray(n.global)?n.global:[],user:n.user&&typeof n.user=="object"?n.user:{},triggers:n.triggers&&typeof n.triggers=="object"?n.triggers:{}}}catch{return{global:[],user:{},triggers:{}}}}function saveMenuData(e,t){const n=getMenuFile(e);fs_1.default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8")}const pendingSelections=new Map,SELECTION_TIMEOUT_MS=6e4;function getPendingKey(e,t){return`${e}:${t}`}function setPendingSelection(e,t,n,r){pendingSelections.set(getPendingKey(e,t),{staffId:t,conversationId:e,sessionWebhook:n,mergedItems:r,createdAt:Date.now()})}function getPendingSelection(e,t){return pendingSelections.get(getPendingKey(e,t))}function clearPendingSelection(e,t){pendingSelections.delete(getPendingKey(e,t))}function hasPendingSelection(e,t){const n=pendingSelections.get(getPendingKey(e,t));return n?Date.now()-n.createdAt>SELECTION_TIMEOUT_MS?(pendingSelections.delete(getPendingKey(e,t)),!1):!0:!1}function startSelectionCleanupTimer(){setInterval(()=>{const e=Date.now();for(const[t,n]of pendingSelections)e-n.createdAt>SELECTION_TIMEOUT_MS&&pendingSelections.delete(t)},15e3)}function getUserTrigger(e,t){return loadMenuData(e).triggers?.[t]||"cc"}function setUserTrigger(e,t,n){const r=loadMenuData(e);r.triggers||(r.triggers={}),r.triggers[t]=n,saveMenuData(e,r)}function getAllTriggerWords(e){const t=loadMenuData(e),n=new Set(["cc"]);if(t.triggers)for(const r of Object.values(t.triggers))r&&n.add(r.toLowerCase());return n}function getUserMenuKey(e,t){return`${e}:${t}`}function generateId(){return`m_${Date.now().toString(36)}`}function getMergedMenu(e,t,n){const r=loadMenuData(e),u=getUserMenuKey(t,n),s=r.user[u]||[];return[...r.global,...s]}function addMenuItem(e,t,n,r,u,s){const o=loadMenuData(e),a=u.trim()||s.trim().substring(0,20),l={id:generateId(),label:a,command:s.trim(),createdAt:utils_ok_1.dateUtil.mm().format("YYYY-MM-DD HH:mm:ss")};if(r)o.global.push(l);else{const i=getUserMenuKey(t,n);o.user[i]||(o.user[i]=[]),o.user[i].push(l)}return saveMenuData(e,o),console.log(`[${(0,session_1.timestamp)()}] [menu] \u6DFB\u52A0\u83DC\u5355: ${r?"\u5168\u5C40":"\u4E2A\u4EBA"} label=${l.label} id=${l.id}`),l}function deleteMenuItem(e,t,n,r,u){const s=loadMenuData(e),o=parseInt(u,10);if(r){if(isNaN(o)||o<1||o>s.global.length)return{success:!1,error:`\u5E8F\u53F7\u65E0\u6548\uFF0C\u5168\u5C40\u83DC\u5355\u5171 ${s.global.length} \u9879`};const[g]=s.global.splice(o-1,1);return saveMenuData(e,s),console.log(`[${(0,session_1.timestamp)()}] [menu] \u5220\u9664\u5168\u5C40\u83DC\u5355: label=${g.label} id=${g.id}`),{success:!0,deletedItem:g}}const a=getUserMenuKey(t,n),l=s.user[a]||[];if(isNaN(o)||o<1||o>l.length)return{success:!1,error:`\u5E8F\u53F7\u65E0\u6548\uFF0C\u4E2A\u4EBA\u83DC\u5355\u5171 ${l.length} \u9879`};const[i]=l.splice(o-1,1);return l.length===0&&delete s.user[a],saveMenuData(e,s),console.log(`[${(0,session_1.timestamp)()}] [menu] \u5220\u9664\u4E2A\u4EBA\u83DC\u5355: label=${i.label} id=${i.id}`),{success:!0,deletedItem:i}}function formatMenuDisplay(e,t){if(e.length===0)return"\u{1F4ED} \u6682\u65E0\u5FEB\u6377\u6307\u4EE4\n\n\u{1F4A1} \u4F7F\u7528 `/menu add <\u6307\u4EE4>` \u6DFB\u52A0";const n=["### \u{1F4CB} \u5FEB\u6377\u6307\u4EE4",""];if(t>0){n.push("\u{1F310} **\u5168\u5C40**");for(let r=0;r<t;r++)n.push(`${r+1}. ${e[r].label}`)}if(e.length>t){t>0&&n.push(""),n.push("\u{1F464} **\u6211\u7684**");for(let r=t;r<e.length;r++)n.push(`${r+1}. ${e[r].label}`)}return n.push("","---","\u{1F4A1} \u56DE\u590D\u5E8F\u53F7\u6267\u884C (60s) | `/menu add/del/list` \u7BA1\u7406"),n.join(`
|
|
2
|
+
`)}function formatMenuList(e,t,n,r){const u=loadMenuData(e),s=[];if(r)if(s.push("### \u{1F4CB} \u5168\u5C40\u5FEB\u6377\u6307\u4EE4\u7BA1\u7406",""),u.global.length>0)for(let o=0;o<u.global.length;o++)s.push(`${o+1}. **${u.global[o].label}** \u2192 \`${u.global[o].command}\``);else s.push("\u{1F4ED} \u6682\u65E0\u5168\u5C40\u83DC\u5355\u9879\uFF0C\u4F7F\u7528 `/menu -g add <\u6307\u4EE4>` \u6DFB\u52A0");else{s.push("### \u{1F4CB} \u4E2A\u4EBA\u5FEB\u6377\u6307\u4EE4\u7BA1\u7406","");const o=getUserMenuKey(t,n),a=u.user[o]||[];if(a.length>0)for(let i=0;i<a.length;i++)s.push(`${i+1}. **${a[i].label}** \u2192 \`${a[i].command}\``);else s.push("\u{1F4ED} \u6682\u65E0\u4E2A\u4EBA\u83DC\u5355\u9879\uFF0C\u4F7F\u7528 `/menu add <\u6307\u4EE4>` \u6DFB\u52A0");s.push("");const l=getUserTrigger(e,n);s.push(`\u5F53\u524D\u89E6\u53D1\u8BCD: \`${l}\` (\u4F7F\u7528 \`/menu trigger <\u8BCD>\` \u4FEE\u6539)`)}return s.join(`
|
|
3
|
+
`)}
|
|
@@ -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.fetchQuotedMessage=fetchQuotedMessage,exports.queryDingUser=queryDingUser,exports.queryUserIdByMobile=queryUserIdByMobile,exports.filterToolUseContent=filterToolUseContent,exports.splitMessage=splitMessage,exports.sendDingMessage=sendDingMessage,exports.sendClaudeResponseToDing=sendClaudeResponseToDing,exports.sendMessageToUser=sendMessageToUser,exports.sendOwnerMessage=sendOwnerMessage;const utils_ok_1=require("utils-ok"),urllib_1=__importDefault(require("urllib")),DING_API_BASE="https://api.dingtalk.com",DING_OAPI_BASE="https://oapi.dingtalk.com";async function fetchQuotedMessage(e,t){try{const r=await e.dingStreamClient.getAccessToken(),
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.fetchQuotedMessage=fetchQuotedMessage,exports.queryDingUser=queryDingUser,exports.queryUserIdByMobile=queryUserIdByMobile,exports.filterToolUseContent=filterToolUseContent,exports.splitMessage=splitMessage,exports.sendDingMessage=sendDingMessage,exports.sendClaudeResponseToDing=sendClaudeResponseToDing,exports.sendMessageToUser=sendMessageToUser,exports.sendOwnerMessage=sendOwnerMessage;const utils_ok_1=require("utils-ok"),urllib_1=__importDefault(require("urllib")),DING_API_BASE="https://api.dingtalk.com",DING_OAPI_BASE="https://oapi.dingtalk.com";async function fetchQuotedMessage(e,t){try{const r=await e.dingStreamClient.getAccessToken(),n=`${DING_API_BASE}/v1.0/im/api/messages/${encodeURIComponent(t)}`,o=await urllib_1.default.request(n,{method:"GET",headers:{"x-acs-dingtalk-access-token":r},dataType:"json",timeout:5e3});if(o.status!==200||!o.data)return e.debugLog(`fetchQuotedMessage API \u8FD4\u56DE\u975E200: status=${o.status}, data=${JSON.stringify(o.data)}`),null;const s=o.data;if(s.text&&typeof s.text=="object"){const a=s.text.content;if(typeof a=="string"&&a)return a.trim()}if(typeof s.content=="string"&&s.content)try{const a=JSON.parse(s.content);if(typeof a=="string")return a.trim();if(a.text)return String(a.text).trim();if(a.content)return String(a.content).trim()}catch{return s.content.trim()}if(s.body&&typeof s.body=="object"){const a=s.body;if(typeof a.content=="string"&&a.content)return a.content.trim()}return e.debugLog(`fetchQuotedMessage \u65E0\u6CD5\u4ECE\u54CD\u5E94\u4E2D\u63D0\u53D6\u6587\u672C: keys=${Object.keys(s).join(",")}`),null}catch(r){return console.warn("fetchQuotedMessage \u8BF7\u6C42\u5931\u8D25:",r),null}}async function queryDingUser(e,t){try{const r=await e.dingStreamClient.getAccessToken(),n=`${DING_OAPI_BASE}/topapi/v2/user/get?access_token=${r}`,o=await urllib_1.default.request(n,{method:"POST",data:{userid:t},contentType:"json",dataType:"json",timeout:5e3});if(o.status!==200||!o.data)return e.debugLog(`queryDingUser API \u8FD4\u56DE\u975E200: status=${o.status}, data=${JSON.stringify(o.data)}`),null;const s=o.data;return s.errcode!==0?(console.warn(`queryDingUser \u63A5\u53E3\u8FD4\u56DE\u9519\u8BEF: errcode=${s.errcode}, errmsg=${s.errmsg}`),null):s.result||null}catch(r){return console.warn("queryDingUser \u8BF7\u6C42\u5931\u8D25:",r),null}}async function queryUserIdByMobile(e,t){try{const r=await e.dingStreamClient.getAccessToken(),n=`${DING_OAPI_BASE}/topapi/v2/user/getbymobile?access_token=${r}`,o=await urllib_1.default.request(n,{method:"POST",data:{mobile:t},contentType:"json",dataType:"json",timeout:5e3});if(o.status!==200||!o.data)return e.debugLog(`queryUserIdByMobile API \u8FD4\u56DE\u975E200: status=${o.status}, data=${JSON.stringify(o.data)}`),null;const s=o.data;return s.errcode!==0?(console.warn(`queryUserIdByMobile \u63A5\u53E3\u8FD4\u56DE\u9519\u8BEF: errcode=${s.errcode}, errmsg=${s.errmsg}`),null):s.result?.userid||null}catch(r){return console.warn("queryUserIdByMobile \u8BF7\u6C42\u5931\u8D25:",r),null}}const TOOL_TAGS=["Write","Read","Edit","Bash","Grep","Glob","Agent","Skill","WebFetch","WebSearch","TaskOutput","AskUserQuestion","EnterPlanMode","ExitPlanMode","TaskCreate","TaskGet","TaskUpdate","TaskList","EnterWorktree","ExitWorktree","CronCreate","CronDelete","CronList","LSP","NotebookEdit"].join("|"),TOOL_USE_SELF_CLOSE_RE=new RegExp(`<(${TOOL_TAGS})[^>]*\\/>`,"g"),TOOL_USE_OPEN_CLOSE_RE=new RegExp(`<(${TOOL_TAGS})[^>]*>[\\s\\S]*?<\\/\\1>`,"g"),MULTI_NEWLINE_RE=/\n{3,}/g;function filterToolUseContent(e){let t=e.replace(TOOL_USE_SELF_CLOSE_RE,"");return t=t.replace(TOOL_USE_OPEN_CLOSE_RE,""),t=t.replace(MULTI_NEWLINE_RE,`
|
|
2
2
|
|
|
3
|
-
`),t.trim()}function splitMessage(e,t){const r=[];for(;e.length>t;){let
|
|
4
|
-
`,t);(
|
|
5
|
-
@${c}`);const f=a==="markdown"?{msgtype:"markdown",markdown:{title:g,text:g},at:{atUserIds:l,isAtAll:!1}}:{msgtype:"text",text:{content:
|
|
6
|
-
`:"";await sendDingMessage(e,{conversationId:t,sessionWebhook:r,atUserId:c===i.length-1?
|
|
3
|
+
`),t.trim()}function splitMessage(e,t){const r=[];for(;e.length>t;){let n=e.lastIndexOf(`
|
|
4
|
+
`,t);(n===-1||n<t*.5)&&(n=e.lastIndexOf("\u3002",t)),(n===-1||n<t*.5)&&(n=e.lastIndexOf(" ",t)),n===-1||n<t*.5?n=t:n+=1,r.push(e.substring(0,n).trim()),e=e.substring(n).trim()}return e.length>0&&r.push(e),r}async function sendDingMessage(e,t){const{conversationId:r,sessionWebhook:n,atUserId:o,content:s,msgType:a="text"}=t,i=e.config.conversations.find(d=>d.conversationId===r);let c=o;(i?.atSender===!1||i?.conversationType==="1")&&(c=void 0);const l=c?[c]:[],p=i?.dingToken;let g=s;c&&a==="markdown"&&(g=`${s}
|
|
5
|
+
@${c}`);const f=a==="markdown"?{msgtype:"markdown",markdown:{title:g,text:g},at:{atUserIds:l,isAtAll:!1}}:{msgtype:"text",text:{content:s},at:{atUserIds:l,isAtAll:!1}};if(p){const d=await e.dingStreamClient.getAccessToken(),u=`https://oapi.dingtalk.com/robot/send?access_token=${p}`;try{await urllib_1.default.request(u,{method:"POST",data:f,contentType:"json",headers:{"x-acs-dingtalk-access-token":d},dataType:"json"})}catch(y){console.error("\u901A\u8FC7 dingToken \u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",y)}}else if(n){const d=await e.dingStreamClient.getAccessToken();try{await urllib_1.default.request(n,{method:"POST",data:f,contentType:"json",headers:{"x-acs-dingtalk-access-token":d},dataType:"json"})}catch(u){console.error("\u901A\u8FC7 sessionWebhook \u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",u)}}else if(e.config.defaultDingToken){const d=await e.dingStreamClient.getAccessToken(),u=`https://oapi.dingtalk.com/robot/send?access_token=${e.config.defaultDingToken}`;try{await urllib_1.default.request(u,{method:"POST",data:f,contentType:"json",headers:{"x-acs-dingtalk-access-token":d},dataType:"json"})}catch(y){console.error("\u901A\u8FC7 defaultDingToken \u53D1\u9001\u9489\u9489\u6D88\u606F\u5931\u8D25:",y)}}else console.error("\u672A\u80FD\u83B7\u53D6\u673A\u5668\u4EBA\u4FE1\u606F\u53D1\u9001\u9014\u5F84")}async function sendClaudeResponseToDing(e,t,r,n,o){const a=filterToolUseContent(o);if(!a){e.debugLog("\u8FC7\u6EE4\u540E\u5185\u5BB9\u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u53D1\u9001");return}if(a.length<=18e3)await sendDingMessage(e,{conversationId:t,sessionWebhook:r,atUserId:n,content:a,msgType:"markdown"});else{const i=splitMessage(a,18e3);for(let c=0;c<i.length;c++){const l=i.length>1?`**[${c+1}/${i.length}]**
|
|
6
|
+
`:"";await sendDingMessage(e,{conversationId:t,sessionWebhook:r,atUserId:c===i.length-1?n:"",content:l+i[c],msgType:"markdown"}),c<i.length-1&&await utils_ok_1.baseUtil.sleep(500)}}}async function sendMessageToUser(e,t,r,n="text"){if(!e.config.enableMsgToUser)return console.log(`[sendMessageToUser] enableMsgToUser \u672A\u5F00\u542F\uFF0C\u8DF3\u8FC7\u53D1\u9001 (userId=${t})`),!1;try{const o=await e.dingStreamClient.getAccessToken(),s=n==="markdown"?"sampleMarkdown":"sampleText",a=JSON.stringify(n==="markdown"?{title:"notification",text:r}:{content:r}),i=await urllib_1.default.request(`${DING_API_BASE}/v1.0/robot/oToMessages/batchSend`,{method:"POST",data:{robotCode:e.clientId,userIds:[t],msgKey:s,msgParam:a},contentType:"json",headers:{"x-acs-dingtalk-access-token":o},dataType:"json"});return i.status===200?!0:(console.error(`sendMessageToUser API \u8FD4\u56DE\u975E200: status=${i.status}, userId=${t}`),!1)}catch(o){return console.error(`sendMessageToUser \u5931\u8D25 (userId=${t}):`,o),!1}}async function sendOwnerMessage(e,t,r="text"){const{ownerConversationId:n,owner:o}=e.config;if(!n||!o)return!1;const s=await queryUserIdByMobile(e,o);return s?sendMessageToUser(e,s,t,r):(console.error(`sendOwnerMessage: \u65E0\u6CD5\u5C06\u624B\u673A\u53F7 ${o} \u89E3\u6790\u4E3A Ding userId`),!1)}
|
package/dist/src/biz/quote.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.extractQuoteInfo=extractQuoteInfo,exports.formatPromptWithQuote=formatPromptWithQuote;
|
|
2
|
-
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.extractQuoteInfo=extractQuoteInfo,exports.enrichQuoteInfo=enrichQuoteInfo,exports.extractDownloadCode=extractDownloadCode,exports.extractFileName=extractFileName,exports.detectExtFromBuffer=detectExtFromBuffer,exports.processFileMessage=processFileMessage,exports.formatPromptWithQuote=formatPromptWithQuote;const messaging_1=require("./messaging"),image_1=require("./image");function extractTextQuote(e){return e?typeof e.text=="string"?e.text.trim():typeof e=="string"?e.trim():"":""}function extractRichTextQuote(e){if(!e?.richText||!Array.isArray(e.richText))return"";const t=[];for(const i of e.richText)i.type==="text"&&i.text?t.push(i.text):i.type==="picture"&&t.push("[\u56FE\u7247]");return t.join(`
|
|
2
|
+
`).trim()}function extractChatRecordQuote(e){if(!e?.chatRecords||!Array.isArray(e.chatRecords))return"";const t=e.chatRecords;if(t.length===0)return"";const i=[`[\u804A\u5929\u8BB0\u5F55 - ${t.length}\u6761]`];for(const r of t){const n=r.senderNick??r.senderName??"\u672A\u77E5",s=r.content??r.text??"",c=r.msgtype??r.msgType??"text";c!=="text"&&!s?i.push(`${n}: [${c}\u6D88\u606F]`):i.push(`${n}: ${s}`)}return i.join(`
|
|
3
|
+
`)}function extractCardQuote(e){if(!e)return"";const t=[];return typeof e.title=="string"&&t.push(`[\u5361\u7247: ${e.title}]`),typeof e.markdown=="string"?t.push(e.markdown):typeof e.text=="string"&&t.push(e.text),t.join(`
|
|
4
|
+
`).trim()}function extractQuoteInfo(e){const t=e.text;if(!t?.repliedMsg)return null;const i=t.repliedMsg,r=i.msgId,n=i.senderNick,s=i.msgType||"text",c=i.content;let o="",d,a,u;switch(s){case"text":o=extractTextQuote(c);break;case"picture":{d=c?.pictureDownloadCode||c?.downloadCode||void 0,o="[\u56FE\u7247\u6D88\u606F]";break}case"richText":{const l=c;o=extractRichTextQuote(l),o||(o="[\u5BCC\u6587\u672C\u6D88\u606F]"),l?.richText&&(u=l.richText);break}case"chatRecord":o=extractChatRecordQuote(c),o||(o="[\u804A\u5929\u8BB0\u5F55]");break;case"file":a=c?.fileName,d=c?.downloadCode||void 0,o=a?`[\u6587\u4EF6: ${a}]`:"[\u6587\u4EF6\u6D88\u606F]";break;case"video":o="[\u89C6\u9891\u6D88\u606F]",d=c?.downloadCode||void 0;break;case"audio":o="[\u8BED\u97F3\u6D88\u606F]",d=c?.downloadCode||void 0;break;case"actionCard":case"interactiveCard":o=extractCardQuote(c),o||(o=`[${s}\u6D88\u606F]`);break;default:{o=extractTextQuote(c),o||(o=`[${s}\u6D88\u606F]`);break}}return!o&&!r?null:{quoteText:o,quoteMessageId:r,quoteSenderNick:n,quoteMsgType:s,quoteDownloadCode:d,quoteFileName:a,quoteRichText:u}}async function enrichQuoteInfo(e,t,i,r,n){const s=t.quoteMsgType,c=t.quoteDownloadCode;if(s==="picture"&&c){const o=await(0,image_1.processPictureMessage)(e,c,i.robotCode,r,n);if(o){t.quoteText=o;return}}if(s==="richText"&&t.quoteRichText){const o=await(0,image_1.processRichTextMessage)(e,t.quoteRichText,i.robotCode,r,n);if(o&&o!=="[\u5BCC\u6587\u672C\u6D88\u606F\u5185\u5BB9\u4E3A\u7A7A]"){t.quoteText=o;return}}if((s==="file"||s==="video"||s==="audio")&&c){const o=await(0,image_1.downloadToFilesDir)(e,c,i.robotCode,r,s,t.quoteFileName);if(o){const d=t.quoteFileName?`[${s}: ${t.quoteFileName}]`:`[${s}]`;t.quoteText=`${d} ${o}`;return}}if(t.quoteText.startsWith("[")&&t.quoteMessageId){const o=await(0,messaging_1.fetchQuotedMessage)(e,t.quoteMessageId);o&&(t.quoteText=o)}}function extractDownloadCode(e){if(e.downloadCode)return e.downloadCode;if(e.pictureDownloadCode)return e.pictureDownloadCode;if(e.fileDownloadCode)return e.fileDownloadCode;const t=e;if(t.extensions&&typeof t.extensions=="object"){const r=t.extensions;if(r.downloadCode)return r.downloadCode}const i=["image_content","file_content","video_content","audio_content"];for(const r of i){const n=t[r];if(n&&typeof n=="object"){const s=n;if(s.download_code)return s.download_code;if(s.downloadCode)return s.downloadCode}}return null}function extractFileName(e){if(e.fileName)return e.fileName;const t=e;for(const i of["content","file_content","image_content"]){const r=t[i];if(r&&typeof r=="object"){const n=r;if(n.fileName&&typeof n.fileName=="string")return n.fileName;if(n.file_name&&typeof n.file_name=="string")return n.file_name;if(n.name&&typeof n.name=="string")return n.name}}return typeof t.fileName=="string"?t.fileName:null}function detectExtFromBuffer(e){return e.length>=5&&e[0]===37&&e[1]===80&&e[2]===68&&e[3]===70&&e[4]===45?"pdf":e.length>=4&&e[0]===80&&e[1]===75&&e[2]===3&&e[3]===4?"docx":e.length>=8&&e[0]===208&&e[1]===207&&e[2]===17&&e[3]===224?"xls":"bin"}async function processFileMessage(e,t,i){const r=extractDownloadCode(t);if(!r)return null;const n=extractFileName(t),s=await(0,image_1.downloadToFilesDir)(e,r,t.robotCode,i,"file",n||void 0);return s?`${n?`\u6587\u4EF6: ${n}`:"\u6587\u4EF6\u6D88\u606F"}
|
|
5
|
+
\u8DEF\u5F84: ${s}`:null}function formatPromptWithQuote(e,t){if(!t.quoteText)return e;const i=[];if(t.quoteSenderNick&&i.push(`\u6765\u81EA: ${t.quoteSenderNick}`),t.quoteMsgType&&t.quoteMsgType!=="text"){const n={picture:"\u56FE\u7247",richText:"\u5BCC\u6587\u672C",chatRecord:"\u804A\u5929\u8BB0\u5F55",file:"\u6587\u4EF6",video:"\u89C6\u9891",audio:"\u8BED\u97F3",actionCard:"\u5361\u7247",interactiveCard:"\u5361\u7247"};i.push(`\u7C7B\u578B: ${n[t.quoteMsgType]||t.quoteMsgType}`)}return`\u2500\u2500 \u5F15\u7528\u6D88\u606F${i.length>0?` (${i.join(", ")})`:""} \u2500\u2500
|
|
6
|
+
${t.quoteText}
|
|
3
7
|
\u2500\u2500 \u5F15\u7528\u7ED3\u675F \u2500\u2500
|
|
4
8
|
|
|
5
|
-
${
|
|
9
|
+
${e}`}
|
package/dist/src/biz/recorder.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(
|
|
2
|
-
`)}function saveRecordFile(t,
|
|
3
|
-
`))}async function recordFileMessage(t,
|
|
4
|
-
`))}function recordChatRecord(t,
|
|
5
|
-
`);for(const
|
|
6
|
-
`))}async function recordRichText(t,
|
|
7
|
-
`))}function recordCard(t,
|
|
8
|
-
`))}function recordUnknown(t,
|
|
9
|
-
`))}async function recordMessage(t,
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRecorderDir=getRecorderDir,exports.recordMessage=recordMessage;const fs_1=__importDefault(require("fs")),path_1=__importDefault(require("path")),utils_ok_1=require("utils-ok"),image_1=require("./image"),session_1=require("./session");function getRecorderDir(o,t){return o.config.recorderCfg?.dist?o.config.recorderCfg.dist:path_1.default.join((0,session_1.getConversationDir)(o,t),".recorder")}function fileTimestamp(o=Date.now()){return utils_ok_1.dateUtil.mm(o).format("YYYY-MM-DD_HH-mm-ss-SSS")}function buildFrontmatter(o,t,u,s){return["---",`msgType: ${o}`,`sender: ${t} (${u})`,`time: ${utils_ok_1.dateUtil.mm(s).format("YYYY-MM-DD HH:mm:ss")}`,"---",""].join(`
|
|
2
|
+
`)}function saveRecordFile(o,t,u){const s=path_1.default.join(o,t);fs_1.default.mkdirSync(s,{recursive:!0});const i=`${fileTimestamp()}.md`,n=path_1.default.join(s,i);return fs_1.default.writeFileSync(n,u,"utf-8"),n}async function downloadAttachment(o,t,u,s,i=""){try{const n=await(0,image_1.getImageDownloadUrl)(o,t,u);if(!n)return null;const e=await(0,image_1.downloadImageBuffer)(n);if(!e)return null;const c=path_1.default.join(s,"attachments");fs_1.default.mkdirSync(c,{recursive:!0});const r=i?`.${i}`:(0,image_1.detectExtFromBuffer)(e),l=`${fileTimestamp()}-${t.slice(-8)}${r}`,d=path_1.default.join(c,l);return fs_1.default.writeFileSync(d,e),console.log(`[${(0,session_1.timestamp)()}] [recorder] \u9644\u4EF6\u5DF2\u4FDD\u5B58: ${d} (${e.length} bytes)`),d}catch(n){return console.warn(`[${(0,session_1.timestamp)()}] [recorder] \u9644\u4EF6\u4E0B\u8F7D\u5931\u8D25:`,n),null}}function recordText(o,t,u,s){const i=Date.now(),n=o.text?.content?.trim()??"",e=buildFrontmatter("text",u,s,i)+n;return saveRecordFile(t,"text",e)}async function recordPicture(o,t,u,s,i){const n=Date.now(),e=t.pictureDownloadCode||(0,image_1.extractDownloadCode)(t),c=[buildFrontmatter("picture",s,i,n)];if(e){const r=await downloadAttachment(o,e,t.robotCode,u);r?c.push(``):c.push(`[\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25] downloadCode: ${e}`)}else c.push("[\u56FE\u7247\u6D88\u606F - \u65E0\u6CD5\u83B7\u53D6\u4E0B\u8F7D\u7801]"),c.push("","```json",JSON.stringify(t,null,2),"```");return saveRecordFile(u,"picture",c.join(`
|
|
3
|
+
`))}async function recordFileMessage(o,t,u,s,i,n){const e=Date.now(),c=(0,image_1.extractDownloadCode)(t),r=[buildFrontmatter(n,s,i,e)];if(c){const l=await downloadAttachment(o,c,t.robotCode,u);l?r.push(`[${n}] ${l}`):r.push(`[${n}\u4E0B\u8F7D\u5931\u8D25] downloadCode: ${c}`)}else r.push(`[${n}\u6D88\u606F - \u65E0\u6CD5\u83B7\u53D6\u4E0B\u8F7D\u7801\uFF0C\u5DF2\u4FDD\u5B58\u539F\u59CB\u6570\u636E]`),r.push("","```json",JSON.stringify(t,null,2),"```");return saveRecordFile(u,n,r.join(`
|
|
4
|
+
`))}function recordChatRecord(o,t,u,s){const i=Date.now(),n=[buildFrontmatter("chatRecord",u,s,i)],e=o;let c=null;if(e.chatRecords&&Array.isArray(e.chatRecords))c=e.chatRecords;else if(e.extensions&&typeof e.extensions=="object"){const r=e.extensions;r.chatRecords&&Array.isArray(r.chatRecords)&&(c=r.chatRecords)}if(c&&c.length>0){n.push(`\u5171 ${c.length} \u6761\u6D88\u606F:
|
|
5
|
+
`);for(const r of c){const l=r.senderNick??r.senderName??"\u672A\u77E5",d=r.content??r.text??"",a=r.msgtype??r.msgType??"text";n.push(`**${l}** (${a}):`),n.push(d),n.push("")}}else n.push("[\u804A\u5929\u8BB0\u5F55 - \u5DF2\u4FDD\u5B58\u539F\u59CB\u6570\u636E]"),n.push("","```json",JSON.stringify(o,null,2),"```");return saveRecordFile(t,"chatRecord",n.join(`
|
|
6
|
+
`))}async function recordRichText(o,t,u,s,i){const n=Date.now(),e=[buildFrontmatter("richText",s,i,n)],c=t.content?.richText;if(c&&Array.isArray(c)){const r=c,l=await Promise.all(r.map(async d=>{if(d.type!=="picture")return null;const a=d.downloadCode||d.pictureDownloadCode;return a?downloadAttachment(o,a,t.robotCode,u):null}));for(let d=0;d<r.length;d++){const a=r[d];if(a.type==="text"&&a.text)e.push(a.text);else if(a.type==="picture"){if(a.downloadCode||a.pictureDownloadCode){const f=l[d];f?e.push(``):e.push("[\u5185\u5D4C\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25]")}}else a.type==="mention"&&a.userId&&e.push(`@${a.userId}`)}}else e.push("[\u5BCC\u6587\u672C\u6D88\u606F - \u5DF2\u4FDD\u5B58\u539F\u59CB\u6570\u636E]"),e.push("","```json",JSON.stringify(t,null,2),"```");return saveRecordFile(u,"richText",e.join(`
|
|
7
|
+
`))}function recordCard(o,t,u,s,i){const n=Date.now(),e=[buildFrontmatter(i,u,s,n)],c=o,r=c.actionCard??c.interactiveCard??c.content??c;return typeof r.text=="string"?e.push(r.text):typeof r.title=="string"&&(e.push(`**${r.title}**`),typeof r.markdown=="string"&&e.push(r.markdown)),e.push("","---","\u539F\u59CB\u6570\u636E:","```json",JSON.stringify(o,null,2),"```"),saveRecordFile(t,i,e.join(`
|
|
8
|
+
`))}function recordUnknown(o,t,u,s,i){const n=Date.now(),e=[buildFrontmatter(i,u,s,n)];return e.push(`[\u672A\u77E5\u6D88\u606F\u7C7B\u578B: ${i}]`),e.push("","```json",JSON.stringify(o,null,2),"```"),saveRecordFile(t,"unknown",e.join(`
|
|
9
|
+
`))}async function recordMessage(o,t,u){const s=getRecorderDir(o,u),i=t.msgtype||"unknown",n=t.senderNick??"\u672A\u77E5",e=t.senderStaffId??"";switch(console.log(`[${(0,session_1.timestamp)()}] [recorder] \u8BB0\u5F55\u6D88\u606F: type=${i}, sender=${n}(${e})`),i){case"text":return recordText(t,s,n,e);case"picture":return recordPicture(o,t,s,n,e);case"file":case"video":case"audio":return recordFileMessage(o,t,s,n,e,i);case"chatRecord":return recordChatRecord(t,s,n,e);case"richText":return recordRichText(o,t,s,n,e);case"actionCard":case"interactiveCard":return recordCard(t,s,n,e,i);default:return recordUnknown(t,s,n,e,i)}}
|
package/dist/src/biz/session.js
CHANGED
|
@@ -1,13 +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.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,n
|
|
3
|
-
`).filter(c=>c.length>0).slice(-
|
|
4
|
-
`)}catch{return null}}function findHistorySession(e,n
|
|
5
|
-
`;try{fs_1.default.appendFileSync(t,i,"utf-8")}catch{}}function getActiveSessionsFile(e,
|
|
6
|
-
`,"utf-8"),await(0,messaging_1.sendDingMessage)(e,{conversationId:
|
|
7
|
-
\u{1F4CB} \u4F1A\u8BDDID: ${c}
|
|
8
|
-
|
|
9
|
-
`,"utf-8")
|
|
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,s){const n=path_1.default.join(getHomeDir(),".cc-ding",e),t=path_1.default.join(n,"config.json");return fs_1.default.mkdirSync(n,{recursive:!0}),fs_1.default.writeFileSync(t,JSON.stringify(s,null,2),"utf-8"),t}function ensureClientDir(e){const s=path_1.default.join(getHomeDir(),".cc-ding",e),n=path_1.default.join(s,"config.json");if(fs_1.default.existsSync(n))return;console.log(`[${timestamp()}] \u5BA2\u6237\u7AEF\u76EE\u5F55\u672A\u521D\u59CB\u5316: ${s}`),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: ${n}`),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 s=`${getClientDir(e)}/config.json`;(0,assert_1.default)(fs_1.default.existsSync(s),`Could not find client config file: ${s}`);const n=utils_ok_1.fileUtil.getJSON(s);return(0,assert_1.default)(n.clientSecret,"config.json missing required field: clientSecret"),(0,assert_1.default)(n.whiteUserList,"config.json missing required field: whiteUserList"),n}function resolveToUserId(e,s){return isMobile(s)&&e.resolvedPhones[s]||s}function authCheck(e,s,n){if(isOwnerOrAdmin(e,s))return!0;if(n){const t=e.config.conversations.find(o=>o.conversationId===n);if(t?.whiteUserList&&t.whiteUserList.length>0)return t.whiteUserList.some(o=>resolveToUserId(e,o)===s)}return e.config.whiteUserList.some(t=>resolveToUserId(e,t)===s)}function isOwner(e,s){const n=e.config.owner;if(!n||!isMobile(n))return!1;const t=e.resolvedPhones[n];return!!t&&t===s}function isAdmin(e,s){return e.config.adminUserList?.length?e.config.adminUserList.some(n=>resolveToUserId(e,n)===s):!1}function isOwnerOrAdmin(e,s){return isOwner(e,s)||isAdmin(e,s)}function debugLog(e,s,...n){e.config.debug&&console.log(`[DEBUG] ${s}`,...n)}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 s=getPhoneMapFile(e);if(!fs_1.default.existsSync(s))return{};try{const n=JSON.parse(fs_1.default.readFileSync(s,"utf-8"));if(typeof n=="object"&&n!==null)return n}catch{}return{}}function savePhoneMap(e,s){const n=getPhoneMapFile(e);try{fs_1.default.writeFileSync(n,JSON.stringify(s,null,2),"utf-8")}catch(t){console.error("\u4FDD\u5B58 phone-map.json \u5931\u8D25:",t)}}function userIdToPhone(e,s){for(const[n,t]of Object.entries(e.resolvedPhones))if(t===s)return n;return null}async function resolveUserId(e,s){if(!s)return null;if(!isMobile(s))return s;if(e.resolvedPhones[s])return e.resolvedPhones[s];const n=await(0,messaging_1.queryUserIdByMobile)(e,s);return n&&(e.resolvedPhones[s]=n,savePhoneMap(e,e.resolvedPhones)),n}async function resolveAllPhonesInConfig(e){e.resolvedPhones=loadPhoneMap(e);const s=[],n=async t=>{if(e.resolvedPhones[t])return;const o=await(0,messaging_1.queryUserIdByMobile)(e,t);o&&(e.resolvedPhones[t]=o,s.push(t))};e.config.owner&&(isMobile(e.config.owner)?(await n(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 n(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 n(o),e.resolvedPhones[o]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790\u7FA4\u767D\u540D\u5355\u624B\u673A\u53F7: ${o}`));s.length>0&&savePhoneMap(e,e.resolvedPhones),console.log(`[\u624B\u673A\u89E3\u6790] \u5DF2\u52A0\u8F7D ${Object.keys(e.resolvedPhones).length} \u6761\u8BB0\u5F55 (${s.length} \u6761\u65B0\u89E3\u6790)`)}function hashConversationId(e,s){const t=getConversationConfig(e,s)?.linkConversationId||s;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,s){const n=e.activeSessions.get(s);if(n)return{key:s,session:n};const t=getConversationConfig(e,s);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,s){return e.config.conversations.find(n=>n.conversationId===s)}function getConversationDir(e,s){const n=hashConversationId(e,s);return`${getClientDir(e)}/${n}`}function getSessionsDir(e,s){return`${getConversationDir(e,s)}/.sessions`}function getTasksDir(e,s){return`${getConversationDir(e,s)}/.tasks`}function getImagesDir(e,s){return`${getConversationDir(e,s)}/.images`}function getSessionDir(e,s){const n=s.claudeSessionId||s.startTimeStr;return`${getSessionsDir(e,s.conversationId)}/${n}`}function getSessionId(e){return e.claudeSessionId||e.startTimeStr}function formatSessionInfo(e,s){const n=findActiveSession(e,s);if(!n)return null;const{session:t,isProcessing:o,messageQueue:i}=n.session;return[`- **\u4F1A\u8BDDID:** ${getSessionId(t)}`,`- **\u53D1\u8D77\u8005:** ${t.startNickName}(${t.startStaffId})`,`- **\u5F00\u59CB\u65F6\u95F4:** ${t.startTimeStr}`,`- **\u6700\u540E\u53D1\u9001\u8005:** ${n.session.lastSenderStaffId}`,`- **\u5904\u7406\u4E2D:** ${o}`,`- **\u6392\u961F\u6D88\u606F:** ${i?.length||0} \u6761`].join(`
|
|
2
|
+
`)}function readSessionLogTail(e,s,n){const t=findActiveSession(e,s);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(-n).join(`
|
|
4
|
+
`)}catch{return null}}function findHistorySession(e,s,n){const t=getSessionsDir(e,s),o=`${t}/${n}/session.json`;try{return utils_ok_1.fileUtil.getJSON(o)}catch{}const i=parseInt(n,10);if(!isNaN(i)&&i>0){const a=utils_ok_1.dateUtil.mm(i).format("YYYY-MM-DD-HH-mm-ss"),u=`${t}/${a}/session.json`;try{return utils_ok_1.fileUtil.getJSON(u)}catch{}}return null}function findLatestSession(e,s){const n=getSessionsDir(e,s);if(!fs_1.default.existsSync(n))return null;const t=findActiveSession(e,s),o=t?getSessionId(t.session.session):null;let i=null,a=0;try{const u=fs_1.default.readdirSync(n,{withFileTypes:!0});for(const c of u){if(!c.isDirectory())continue;const r=path_1.default.join(n,c.name,"session.json");if(fs_1.default.existsSync(r))try{const d=utils_ok_1.fileUtil.getJSON(r);if(o&&getSessionId(d)===o)continue;d.startTime>a&&(a=d.startTime,i=d)}catch{continue}}}catch{}return i}function updateSessionFile(e,s,n){if(n.claudeSessionId&&!s.claudeSessionId){const o=getSessionDir(e,s);s.claudeSessionId=n.claudeSessionId;const i=getSessionDir(e,s);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,s)}/session.json`;try{n.sessionWebhook&&(s.sessionWebhook=n.sessionWebhook),n.currentWebhook!==void 0&&(s.currentWebhook=n.currentWebhook||void 0),n.currentConversationId!==void 0&&(s.currentConversationId=n.currentConversationId||void 0),fs_1.default.writeFileSync(t,JSON.stringify(s,null,2),"utf-8");const o=n.claudeSessionId?"claudeSessionId":n.currentWebhook!==void 0?"currentWebhook":"sessionWebhook";console.log(`[${timestamp()}] \u4F1A\u8BDD\u6587\u4EF6\u5DF2\u4FDD\u5B58: ${o}`),saveActiveSession(e,s.conversationId)}catch(o){console.error("\u66F4\u65B0 session.json \u5931\u8D25:",o)}}function appendSessionLog(e,s,n){const t=`${e}/session.log`,i=`[${timestamp()}] [${s.toUpperCase()}]: ${n}
|
|
5
|
+
`;try{fs_1.default.appendFileSync(t,i,"utf-8")}catch{}}function getActiveSessionsFile(e,s){return`${getSessionsDir(e,s)}/active.json`}function saveActiveSession(e,s){const n=e.activeSessions.get(s),t=getActiveSessionsFile(e,s);try{if(!n){fs_1.default.existsSync(t)&&fs_1.default.unlinkSync(t);return}const o={session:n.session,lastSenderStaffId:n.lastSenderStaffId,conversationConfig:n.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=${s}`)}catch(o){console.error(`\u6301\u4E45\u5316\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: \u7FA4=${s}`,o)}}function loadActiveSessions(e){for(const s of e.config.conversations){const n=getActiveSessionsFile(e,s.conversationId);if(fs_1.default.existsSync(n))try{const t=utils_ok_1.fileUtil.getJSON(n);if(!t?.session){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u65E0\u6548\uFF0C\u8DF3\u8FC7: ${n}`);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: ${n}`),fs_1.default.unlinkSync(n);continue}e.activeSessions.set(s.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=${s.conversationId}, \u4F1A\u8BDDID=${getSessionId(t.session)}`)}catch(t){console.error(`\u52A0\u8F7D\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: ${n}`,t)}}}async function endSession(e,s,n){const t=findActiveSession(e,s);if(!t){console.log(`\u7FA4 ${s} \u65E0\u6D3B\u8DC3\u4F1A\u8BDD`);return}const{key:o,session:i}=t,{session:a}=i,u=getSessionDir(e,a),c=getSessionId(a);console.log(`\u7ED3\u675F\u4F1A\u8BDD: \u7FA4=${s}, \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(`${u}/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=${s}, \u6E05\u7A7A${r}\u6761\u6D88\u606F`)),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:n,atUserId:a.startStaffId,content:`\u{1F4AC} \u4F1A\u8BDD\u5DF2\u7ED3\u675F
|
|
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(`${u}/session.log`,`[${timestamp()}] [SYSTEM]: \u7528\u6237\u8BF7\u6C42\u7ED3\u675F\u4F1A\u8BDD
|
|
9
|
+
`,"utf-8")}async function switchToSession(e,s,n,t,o,i){const a=findHistorySession(e,s,t);if(!a)return await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:n,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 u=getSessionDir(e,a);if(!fs_1.default.existsSync(u))return await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:n,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,s);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(s,{session:a,lastSenderStaffId:o,isProcessing:!1,messageQueue:[],conversationConfig:i}),saveActiveSession(e,s);const r=!!a.claudeSessionId,d=getSessionId(a);return await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:n,atUserId:o,content:`\u2705 \u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD (\u4F1A\u8BDDID: ${d})
|
|
10
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"}
|
|
11
|
-
\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=${s}, \u4F1A\u8BDDID=${d}, \u6709Claude\u4E0A\u4E0B\u6587=${r}`),!0}async function startNewSession(e,s){const{conversationId:n,sessionWebhook:t,senderStaffId:o,senderNick:i,message:a,conversationConfig:u}=s,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=${n}`),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:t,atUserId:o,content:"\u{1F92F} \u5F53\u524D\u7E41\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5..."});return}const r=Date.now(),d={conversationId:n,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=${n}, \u4F1A\u8BDDID=${getSessionId(d)}, \u53D1\u8D77\u8005=${o}, \u5F53\u524D\u5E76\u53D1=${e.activeSessions.size+1}/${c}`);const f=getSessionDir(e,d);fs_1.default.mkdirSync(f,{recursive:!0}),fs_1.default.writeFileSync(`${f}/session.json`,JSON.stringify(d,null,2),"utf-8"),e.activeSessions.set(n,{session:d,lastSenderStaffId:o,isProcessing:!0,messageQueue:[],conversationConfig:u}),saveActiveSession(e,n),u.receiveReply!==!1&&await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:t,atUserId:o,content:`\u{1F680} \u4F1A\u8BDD\u5DF2\u5F00\u59CB\uFF01
|
|
12
13
|
\u5904\u7406\u4E2D...
|
|
13
|
-
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`});try{await(0,claude_process_1.executeClaudeQuery)(e,d,a,{skill:u.taskCfg?.skill,agent:u.agent,senderNick:i,senderStaffId:o})}catch(l){console.error("\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",l),await(0,messaging_1.sendDingMessage)(e,{conversationId:
|
|
14
|
+
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`});try{await(0,claude_process_1.executeClaudeQuery)(e,d,a,{skill:u.taskCfg?.skill,agent:u.agent,senderNick:i,senderStaffId:o})}catch(l){console.error("\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",l),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:t,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${l instanceof Error?l.message:String(l)}`})}finally{const l=e.activeSessions.get(n);l&&(l.isProcessing=!1)}const g=e.activeSessions.get(n);g&&g.messageQueue.length>0&&await processMessageQueue(e,n)}async function processMessageQueue(e,s){const n=e.activeSessions.get(s);if(!n||n.messageQueue.length===0)return;const t=n.messageQueue.shift(),{message:o,senderStaffId:i,senderNick:a}=t,u=n.session.sessionWebhook;console.log(`\u5904\u7406\u961F\u5217\u6D88\u606F: \u7FA4=${s}, \u5269\u4F59 ${n.messageQueue.length} \u6761`),n.isProcessing=!0,n.lastSenderStaffId=i,saveActiveSession(e,s),n.conversationConfig.receiveReply!==!1&&await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:u,atUserId:i,content:"\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406..."}).catch(()=>{});try{await(0,claude_process_1.executeClaudeQuery)(e,n.session,o,{skill:n.conversationConfig.taskCfg?.skill,agent:n.conversationConfig.agent,senderNick:a,senderStaffId:i})}catch(c){console.error("\u6267\u884C\u961F\u5217 Claude \u67E5\u8BE2\u5931\u8D25:",c),await(0,messaging_1.sendDingMessage)(e,{conversationId:s,sessionWebhook:u,atUserId:i,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${c instanceof Error?c.message:String(c)}`})}finally{n.isProcessing=!1}if(n.goonPending){n.goonPending=!1,n.interrupted=!1,n.isProcessing=!0;try{await(0,claude_process_1.executeClaudeQuery)(e,n.session,"\u7EE7\u7EED",{senderNick:n.session.startNickName,senderStaffId:n.lastSenderStaffId})}catch(c){console.error("goonPending \u6062\u590D\u6267\u884C\u5931\u8D25:",c)}finally{n.isProcessing=!1}}n.messageQueue.length>0&&await processMessageQueue(e,s)}async function handleSessionMessage(e,s){const{conversationId:n,sessionWebhook:t,senderStaffId:o,senderNick:i,message:a,conversationConfig:u}=s;if((0,commands_1.parseEndCommand)(a)){await endSession(e,n,t);return}const c=findActiveSession(e,n),r=c?.session;if(r){const d=getSessionDir(e,r.session);if(fs_1.default.existsSync(d)||(fs_1.default.mkdirSync(d,{recursive:!0}),fs_1.default.writeFileSync(`${d}/session.json`,JSON.stringify(r.session,null,2),"utf-8"),console.log(`\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u91CD\u5EFA: \u7FA4=${n}, \u8DEF\u5F84=${d}`)),r.isProcessing){const g={message:a,senderStaffId:o,senderNick:i};r.messageQueue.push(g);const l=r.messageQueue.length;console.log(`\u4F1A\u8BDD ${n} \u6D88\u606F\u5DF2\u5165\u961F\uFF0C\u6392\u961F\u7B2C ${l} \u6761`),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:t,atUserId:o,content:`\u23F3 \u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u5DF2\u52A0\u5165\u961F\u5217\uFF08\u6392\u961F\u7B2C ${l} \u6761\uFF09`});return}const f=r.session.conversationId===n;console.log(`\u8FFD\u52A0\u6D88\u606F\u5230\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${n}, \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=n,updateSessionFile(e,r.session,{currentWebhook:t,currentConversationId:n}),u.receiveReply!==!1&&await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:t,atUserId:o,content:"\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406..."});try{await(0,claude_process_1.executeClaudeQuery)(e,r.session,a,{skill:u.taskCfg?.skill,agent:u.agent,senderNick:i,senderStaffId:o})}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,a,{skill:u.taskCfg?.skill,agent:u.agent,senderNick:i,senderStaffId:o});return}catch(l){console.error("\u91CD\u8BD5\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",l),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,sessionWebhook:t,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${l instanceof Error?l.message:String(l)}`}),r.isProcessing=!1,await processMessageQueue(e,n);return}}console.error("\u6267\u884C Claude \u67E5\u8BE2\u5931\u8D25:",g),await(0,messaging_1.sendDingMessage)(e,{conversationId:n,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,n)}else await startNewSession(e,{conversationId:n,sessionWebhook:t,senderStaffId:o,senderNick:i,message:a,conversationConfig:u})}function cleanCache(e,s,n=!0){const t={sessionsDeleted:0,tasksDeleted:0,imagesDeleted:0,errors:[]},o=s?[s]:e.config.conversations.map(i=>i.conversationId);for(const i of o){let a=null;if(n){const f=findActiveSession(e,i);f&&(a=getSessionId(f.session.session))}const u=getSessionsDir(e,i);if(fs_1.default.existsSync(u))try{const f=fs_1.default.readdirSync(u,{withFileTypes:!0});for(const g of f){if(!g.isDirectory()||a&&g.name===a)continue;const l=path_1.default.join(u,g.name);try{fs_1.default.rmSync(l,{recursive:!0,force:!0}),t.sessionsDeleted++}catch{t.errors.push(`\u5220\u9664\u4F1A\u8BDD\u76EE\u5F55\u5931\u8D25: ${l}`)}}}catch{t.errors.push(`\u8BFB\u53D6sessions\u76EE\u5F55\u5931\u8D25: ${u}`)}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 l=path_1.default.join(c,g.name);try{fs_1.default.rmSync(l,{recursive:!0,force:!0}),t.tasksDeleted++}catch{t.errors.push(`\u5220\u9664\u4EFB\u52A1\u76EE\u5F55\u5931\u8D25: ${l}`)}}}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 l=path_1.default.join(r,g.name);try{fs_1.default.unlinkSync(l),t.imagesDeleted++}catch{t.errors.push(`\u5220\u9664\u56FE\u7247\u5931\u8D25: ${l}`)}}}catch{t.errors.push(`\u8BFB\u53D6images\u76EE\u5F55\u5931\u8D25: ${r}`)}const d=path_1.default.join(getConversationDir(e,i),".playwright-cli");if(fs_1.default.existsSync(d))try{fs_1.default.rmSync(d,{recursive:!0,force:!0})}catch{t.errors.push(`\u5220\u9664 playwright-cli \u7F13\u5B58\u5931\u8D25: ${d}`)}if(!n){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}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TodoEngine=void 0,exports.loadTodoData=loadTodoData,exports.getSortedTodoItems=getSortedTodoItems,exports.addTodoItem=addTodoItem,exports.doneTodoItem=doneTodoItem,exports.deleteTodoItem=deleteTodoItem,exports.clearAllTodoItems=clearAllTodoItems,exports.getReminderHour=getReminderHour,exports.setReminderHour=setReminderHour,exports.formatDate=formatDate,exports.getDefaultDeadline=getDefaultDeadline,exports.parseDeadline=parseDeadline,exports.formatDeadlineDisplay=formatDeadlineDisplay,exports.formatTodoList=formatTodoList,exports.formatTodoItemCreated=formatTodoItemCreated;const fs_1=__importDefault(require("fs")),utils_ok_1=require("utils-ok"),session_1=require("./session"),messaging_1=require("./messaging");function getTodoFile(n){return`${(0,session_1.getClientDir)(n)}/todo.json`}function loadTodoData(n){const e=getTodoFile(n);try{const o=fs_1.default.readFileSync(e,"utf-8"),t=JSON.parse(o);return{conversations:t.conversations&&typeof t.conversations=="object"?t.conversations:{},reminders:t.reminders&&typeof t.reminders=="object"?t.reminders:{}}}catch{return{conversations:{},reminders:{}}}}function saveTodoData(n,e){const o=getTodoFile(n);fs_1.default.writeFileSync(o,JSON.stringify(e,null,2),"utf-8")}function sortTodoItems(n){const e=n.filter(t=>!t.completed).sort(todoSortByDeadline),o=n.filter(t=>t.completed).sort((t,s)=>(s.completedAt||"").localeCompare(t.completedAt||""));return[...e,...o]}function getSortedTodoItems(n,e){const o=loadTodoData(n);return sortTodoItems(o.conversations[e]||[])}function todoSortByDeadline(n,e){return!n.deadline&&!e.deadline?0:n.deadline?e.deadline?n.deadline.localeCompare(e.deadline):-1:1}function addTodoItem(n,e,o){const t=loadTodoData(n);t.conversations[e]||(t.conversations[e]=[]);const s={content:o.content,assigneeStaffId:o.assigneeStaffId,assigneeNick:o.assigneeNick,deadline:o.deadline,createdAt:utils_ok_1.dateUtil.mm(Date.now()).format("YYYY-MM-DD HH:mm:ss"),completed:!1};return t.conversations[e].push(s),saveTodoData(n,t),console.log(`[${(0,session_1.timestamp)()}] [todo] \u6DFB\u52A0\u5F85\u529E in ${e}: ${o.content}`),s}function doneTodoItem(n,e,o){const t=loadTodoData(n),s=t.conversations[e]||[],r=sortTodoItems(s);if(r.length===0)return{success:!1,error:"\u5F53\u524D\u65E0\u5F85\u529E\u4E8B\u9879"};if(o<1||o>r.length)return{success:!1,error:`\u5E8F\u53F7\u65E0\u6548\uFF0C\u8303\u56F4 1-${r.length}`};const i=r[o-1];if(i.completed)return{success:!1,error:`#${o} \u5DF2\u5B8C\u6210`};const c=s.findIndex(l=>l.content===i.content&&l.createdAt===i.createdAt&&l.assigneeStaffId===i.assigneeStaffId);return c===-1?{success:!1,error:"\u672A\u627E\u5230\u5F85\u529E\u9879"}:(s[c].completed=!0,s[c].completedAt=(0,session_1.timestamp)(),saveTodoData(n,t),console.log(`[${(0,session_1.timestamp)()}] [todo] \u5B8C\u6210\u5F85\u529E in ${e}: ${i.content}`),{success:!0,item:i})}function deleteTodoItem(n,e,o){const t=loadTodoData(n),s=t.conversations[e]||[],r=sortTodoItems(s);if(r.length===0)return{success:!1,error:"\u5F53\u524D\u65E0\u5F85\u529E\u4E8B\u9879"};if(o<1||o>r.length)return{success:!1,error:`\u5E8F\u53F7\u65E0\u6548\uFF0C\u8303\u56F4 1-${r.length}`};const i=r[o-1],c=s.findIndex(u=>u.content===i.content&&u.createdAt===i.createdAt&&u.assigneeStaffId===i.assigneeStaffId);if(c===-1)return{success:!1,error:"\u672A\u627E\u5230\u5F85\u529E\u9879"};const[l]=s.splice(c,1);return s.length===0&&delete t.conversations[e],saveTodoData(n,t),console.log(`[${(0,session_1.timestamp)()}] [todo] \u5220\u9664\u5F85\u529E in ${e}: ${l.content}`),{success:!0,item:l}}function clearAllTodoItems(n,e){const o=loadTodoData(n),t=o.conversations[e]||[];if(t.length===0)return{success:!1,count:0,error:"\u5F53\u524D\u65E0\u5F85\u529E\u4E8B\u9879"};const s=t.length;return delete o.conversations[e],saveTodoData(n,o),console.log(`[${(0,session_1.timestamp)()}] [todo] \u6E05\u7A7A\u5F85\u529E in ${e}: ${s} \u6761`),{success:!0,count:s}}function getReminderHour(n,e){const t=loadTodoData(n).reminders?.[e];return t===!1?null:typeof t=="number"?t:10}function setReminderHour(n,e,o){const t=loadTodoData(n);t.reminders||(t.reminders={}),o===null?t.reminders[e]=!1:t.reminders[e]=o,saveTodoData(n,t)}function addDays(n,e){const o=new Date(n);return o.setDate(o.getDate()+e),o}function formatDate(n){const e=n.getFullYear(),o=String(n.getMonth()+1).padStart(2,"0"),t=String(n.getDate()).padStart(2,"0");return`${e}-${o}-${t}`}function getNextWeekday(n,e,o){const t=n.getDay()===0?7:n.getDay();let s=e-t;return o?s<=0&&(s+=7):(s<0&&(s+=7),s===0&&(s=7)),formatDate(addDays(n,s))}function getDefaultDeadline(){return formatDate(addDays(new Date,7))}function parseDeadline(n){const e=new Date,o=new Date(e.getFullYear(),e.getMonth(),e.getDate()),t=n.trim(),s=t.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/);if(s)return`${s[1]}-${s[2].padStart(2,"0")}-${s[3].padStart(2,"0")}`;const r=t.match(/^(\d{1,2})[-/](\d{1,2})$/);if(r){const a=parseInt(r[1],10),f=parseInt(r[2],10);let m=new Date(e.getFullYear(),a-1,f);return m<o&&(m=new Date(e.getFullYear()+1,a-1,f)),formatDate(m)}const i=t.match(/^(\d{2})(\d{2})$/);if(i){const a=parseInt(i[1],10),f=parseInt(i[2],10);if(a>=1&&a<=12&&f>=1&&f<=31){let m=new Date(e.getFullYear(),a-1,f);return m<o&&(m=new Date(e.getFullYear()+1,a-1,f)),formatDate(m)}}const c={\u4E00:1,\u4E8C:2,\u4E09:3,\u56DB:4,\u4E94:5,\u516D:6,\u65E5:7,\u5929:7};if(t==="\u4ECA\u5929")return formatDate(o);if(t==="\u660E\u5929")return formatDate(addDays(o,1));if(t==="\u540E\u5929")return formatDate(addDays(o,2));if(t==="\u5927\u540E\u5929")return formatDate(addDays(o,3));const l=t.match(/^(这|下)周([一二三四五六日天])$/);if(l){const a=c[l[2]];if(a!==void 0)return getNextWeekday(o,a,l[1]==="\u4E0B")}const u=t.match(/^(?:周|星期)([一二三四五六日天])$/);if(u){const a=c[u[1]];if(a!==void 0)return getNextWeekday(o,a,!1)}return""}function getDeadlineDiffDays(n){const e=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()),o=new Date(n+"T00:00:00");return Math.floor((o.getTime()-e.getTime())/(1440*60*1e3))}function formatDeadlineDisplay(n){if(!n)return"";const e=getDeadlineDiffDays(n);return e<0?`${n} \u{1F534}\u5DF2\u903E\u671F${Math.abs(e)}\u5929`:e===0?`${n} \u26A1\u4ECA\u5929`:e===1?`${n} \u{1F7E1}\u660E\u5929`:e<=3?`${n} \u{1F7E1}${e}\u5929\u540E`:e<=7?`${n} ${e}\u5929\u540E`:n}function formatTodoList(n,e){if(n.length===0)return`\u{1F4ED} \u6682\u65E0\u5F85\u529E\u4E8B\u9879${e===null?"":`
|
|
2
|
+
\u23F0 \u6BCF\u65E5\u63D0\u9192: ${e}:00`}
|
|
3
|
+
|
|
4
|
+
\u{1F4A1} \`/todo <\u5185\u5BB9> ddl \u660E\u5929\` \u6DFB\u52A0\uFF08\u9ED8\u8BA47\u5929\u5230\u671F\uFF09`;const o=n.filter(r=>!r.completed),t=n.filter(r=>r.completed),s=[];if(o.length>0){s.push("### \u{1F4CB} \u8FDB\u884C\u4E2D","");for(let r=0;r<o.length;r++){const i=o[r],c=i.deadline?` \u{1F4C5}${formatDeadlineDisplay(i.deadline)}`:"";s.push(`${r+1}. ${i.content} _@${i.assigneeNick}_${c}`)}}if(t.length>0){o.length>0&&s.push(""),s.push("### \u2705 \u5DF2\u5B8C\u6210","");for(let r=0;r<t.length;r++){const i=t[r],c=o.length+r+1;s.push(`${c}. ~~${i.content}~~ _@${i.assigneeNick}_`)}}if(s.push("","---","\u{1F4A1} `/todo done <\u5E8F\u53F7>` \u5B8C\u6210 | `/todo rm <\u5E8F\u53F7>` \u5220\u9664 | `/todo <\u5185\u5BB9> ddl \u660E\u5929`"),e!==void 0){const r=e===null?"\u23F0 \u6BCF\u65E5\u63D0\u9192: \u5DF2\u5173\u95ED":`\u23F0 \u6BCF\u65E5\u63D0\u9192: ${e}:00`;s.push(r)}return s.join(`
|
|
5
|
+
`)}function formatTodoItemCreated(n,e){const o=n.deadline?`
|
|
6
|
+
- **\u622A\u6B62:** ${formatDeadlineDisplay(n.deadline)}`:"";return[`\u2705 \u5DF2\u6DFB\u52A0\u5F85\u529E #${e}`,"",`- **\u5185\u5BB9:** ${n.content}`,`- **\u8D1F\u8D23\u4EBA:** @${n.assigneeNick}${o}`].join(`
|
|
7
|
+
`)}const AUTO_CLEAN_DAYS=1;class TodoEngine{constructor(e){this.timer=null,this.dc=e}start(){this.scheduleNext(),console.log(`[${(0,session_1.timestamp)()}] Todo\u5F15\u64CE\u5DF2\u542F\u52A8`)}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=null)}scheduleNext(){const e=new Date,o=this.findNextReminderHour(e),t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),o,0,0,0);t.getTime()<=e.getTime()&&t.setDate(t.getDate()+1);const s=t.getTime()-e.getTime();this.timer=setTimeout(()=>{console.log(`[${(0,session_1.timestamp)()}] [todo] \u5B9A\u65F6\u89E6\u53D1 (${o}:00)`),this.cleanExpiredItems(),this.sendReminders(o),this.scheduleNext()},s),console.log(`[${(0,session_1.timestamp)()}] [todo] \u4E0B\u6B21\u89E6\u53D1: ${t.toISOString()}`)}findNextReminderHour(e){const o=e.getHours(),t=loadTodoData(this.dc),s=new Set;for(const i of Object.keys(t.reminders)){const c=t.reminders[i];if(c!==!1){if(typeof c=="number"){s.add(c);continue}s.add(10)}}s.size===0&&s.add(10);const r=Array.from(s).sort((i,c)=>i-c);for(const i of r)if(i>o)return i;return r[0]}cleanExpiredItems(){const e=loadTodoData(this.dc),o=Date.now();let t=0;for(const s of Object.keys(e.conversations)){const r=e.conversations[s],i=r.length,c=r.filter(l=>{if(!l.completed||!l.completedAt)return!0;const u=new Date(l.completedAt).getTime();return isNaN(u)?!0:(o-u)/(1440*60*1e3)<AUTO_CLEAN_DAYS});c.length<i&&(e.conversations[s]=c,t+=i-c.length,c.length===0&&delete e.conversations[s])}t>0&&(saveTodoData(this.dc,e),console.log(`[${(0,session_1.timestamp)()}] [todo] \u81EA\u52A8\u6E05\u7406 ${t} \u6761\u5DF2\u5B8C\u6210\u5F85\u529E`))}async sendReminders(e){const o=loadTodoData(this.dc),t=Object.keys(o.conversations);for(const s of t){const r=o.reminders?.[s];if((r===!1?null:typeof r=="number"?r:10)!==e)continue;const c=(o.conversations[s]||[]).filter(d=>!d.completed);if(c.length===0)continue;const l=this.dc.getConversationConfig(s);if(!l||!(l.dingToken||this.dc.config.defaultDingToken||this.dc.config.ownerConversationId))continue;const u=[],a=[];for(const d of c){if(!d.deadline)continue;const g=getDeadlineDiffDays(d.deadline);g<0?u.push(d):g<=3&&a.push(d)}if(u.length===0&&a.length===0)continue;const f=["### \u23F0 \u6BCF\u65E5\u5F85\u529E\u63D0\u9192",""],m=new Set;if(u.length>0){f.push("\u{1F534} **\u5DF2\u903E\u671F:**");for(const d of u)f.push(`- ${d.content} _@${d.assigneeNick}_ \u{1F4C5}${formatDeadlineDisplay(d.deadline)}`),m.add(d.assigneeStaffId);f.push("")}if(a.length>0){f.push("\u{1F7E1} **\u5373\u5C06\u5230\u671F (3\u5929\u5185):**");for(const d of a)f.push(`- ${d.content} _@${d.assigneeNick}_ \u{1F4C5}${formatDeadlineDisplay(d.deadline)}`),m.add(d.assigneeStaffId);f.push("")}f.push("---"),f.push("\u{1F4A1} `/todo done <\u5E8F\u53F7>` \u5B8C\u6210 | `/todo` \u67E5\u770B\u5168\u90E8");try{await(0,messaging_1.sendDingMessage)(this.dc,{conversationId:s,sessionWebhook:"",content:f.join(`
|
|
8
|
+
`),msgType:"markdown"}),console.log(`[${(0,session_1.timestamp)()}] [todo] \u5DF2\u53D1\u9001\u63D0\u9192\u5230 ${s}, \u6D89\u53CA ${m.size} \u4EBA`)}catch(d){console.error(`[${(0,session_1.timestamp)()}] [todo] \u53D1\u9001\u63D0\u9192\u5931\u8D25 ${s}:`,d)}}}}exports.TodoEngine=TodoEngine;
|