cc-ding 1.0.6 → 1.1.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 +56 -2
- package/dist/bin/cc-ding.js +5 -5
- package/dist/src/biz/agent-registry.js +1 -0
- package/dist/src/biz/agent.js +1 -0
- package/dist/src/biz/cc-ding-cli.js +69 -59
- package/dist/src/biz/claude-agent.js +1 -0
- package/dist/src/biz/claude-process.js +41 -37
- package/dist/src/biz/codex-agent.js +6 -0
- package/dist/src/biz/commands.js +6 -6
- package/dist/src/biz/messaging.js +5 -5
- package/dist/src/biz/model.js +1 -0
- package/dist/src/biz/send-queue.js +11 -0
- package/dist/src/biz/session.js +14 -14
- package/dist/src/biz/streaming.js +3 -0
- package/dist/src/biz/task.js +19 -18
- package/dist/src/biz/timer.js +15 -0
- package/dist/src/biz/watchdog.js +1 -0
- package/package.json +1 -1
package/dist/src/biz/session.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}function
|
|
3
|
-
`).filter(
|
|
4
|
-
`)}catch{return null}}function
|
|
5
|
-
`;try{
|
|
6
|
-
\u53EF\u4EE5\u901A\u8FC7 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002`});return}const{key:
|
|
7
|
-
`,"utf-8");const
|
|
8
|
-
\u{1F194} ${
|
|
9
|
-
\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u4E22\u5F03${
|
|
10
|
-
`,"utf-8")}async function
|
|
11
|
-
`,"utf-8")),e.activeSessions.set(
|
|
12
|
-
${
|
|
13
|
-
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`}),console.log(`\u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD: \u7FA4=${
|
|
14
|
-
\u{1F194} ${
|
|
1
|
+
"use strict";var P=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.timestamp=$,exports.getHomeDir=T,exports.getClientDir=D,exports.initClientDir=Y,exports.ensureClientDir=ce,exports.getClientConfig=ae,exports.reloadClientConfig=ue,exports.resolveToUserId=E,exports.authCheck=le,exports.isOwner=H,exports.isAdmin=B,exports.isOwnerOrAdmin=z,exports.debugLog=G,exports.isMobile=k,exports.isJobNumber=U,exports.getPhoneMapFile=_,exports.loadPhoneMap=X,exports.savePhoneMap=J,exports.userIdToPhone=de,exports.getUserIdNameMapFile=L,exports.loadUserIdNameMap=K,exports.saveUserIdNameMap=Z,exports.resolveUserIdName=ge,exports.resolveUserId=Se,exports.resolveAllPhonesInConfig=he,exports.hashConversationId=V,exports.getReplyWebhook=ye,exports.getReplyConversationId=me,exports.findActiveSession=I,exports.getConversationConfig=O,exports.getConversationDir=N,exports.getSessionsDir=j,exports.getTasksDir=ee,exports.getImagesDir=ne,exports.getSessionDir=v,exports.getSessionId=p,exports.formatSessionInfo=$e,exports.readSessionLogTail=we,exports.findHistorySession=te,exports.findLatestSession=ve,exports.updateSessionFile=Q,exports.appendSessionLog=pe,exports.getActiveSessionsFile=A,exports.saveActiveSession=C,exports.loadActiveSessions=ke,exports.endSession=se,exports.switchToSession=Ce,exports.ensureAgent=F,exports.startNewSession=ie,exports.processMessageQueue=M,exports.handleSessionMessage=De,exports.cleanCache=Ie,exports.destroyConversation=be;const w=require("utils-ok"),c=P(require("fs")),oe=P(require("os")),x=P(require("assert")),q=P(require("crypto")),g=P(require("path")),re=require("./commands"),h=require("./messaging"),W=require("./agent-registry"),R=require("./platform");function $(){return w.dateUtil.mm(Date.now()).format("YYYY-MM-DD HH:mm:ss")}function T(){return oe.default.homedir()}function D(e){return g.default.join(T(),".cc-ding",e.clientId)}function Y(e,t){const n=g.default.join(T(),".cc-ding",e),s=g.default.join(n,"config.json");return c.default.mkdirSync(n,{recursive:!0}),c.default.writeFileSync(s,JSON.stringify(t,null,2),{encoding:"utf-8",mode:(0,R.isWindows)()?void 0:384}),(0,R.isWindows)()||c.default.chmodSync(s,384),s}function ce(e){const t=g.default.join(T(),".cc-ding",e),n=g.default.join(t,"config.json");if(c.default.existsSync(n))return;console.log(`[${$()}] \u5BA2\u6237\u7AEF\u76EE\u5F55\u672A\u521D\u59CB\u5316: ${t}`),console.log(`[${$()}] \u6B63\u5728\u81EA\u52A8\u521D\u59CB\u5316...`),Y(e,{clientName:"cc\u52A9\u624B",owner:"<owner\u624B\u673A\u53F7>",whiteUserList:[],clientSecret:"<clientSecret-\u9489\u9489Stream\u8FDE\u63A5\u5BC6\u94A5>",defaultDingToken:"<\u515C\u5E95\u9489\u9489\u673A\u5668\u4EBAToken>",conversations:[]}),console.log(`[${$()}] \u5DF2\u751F\u6210\u9ED8\u8BA4\u914D\u7F6E\u6587\u4EF6: ${n}`),console.log(`[${$()}] \u8BF7\u7F16\u8F91 config.json \u586B\u5199\u5FC5\u8981\u7684\u914D\u7F6E\u9879\u540E\u91CD\u65B0\u542F\u52A8`),process.exit(1)}function ae(e){const t=g.default.join(D(e),"config.json");(0,x.default)(c.default.existsSync(t),`Could not find client config file: ${t}`);const n=w.fileUtil.getJSON(t);return(0,x.default)(n.clientSecret,"config.json missing required field: clientSecret"),(0,x.default)(n.whiteUserList,"config.json missing required field: whiteUserList"),n}function ue(e){const t=g.default.join(D(e),"config.json");if(!c.default.existsSync(t))throw new Error(`\u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728: ${t}`);let n;try{n=w.fileUtil.getJSON(t)}catch(o){throw new Error(`\u914D\u7F6E\u6587\u4EF6 JSON \u89E3\u6790\u5931\u8D25: ${o instanceof Error?o.message:String(o)}`)}const s=[];if(n.clientSecret||s.push("clientSecret"),n.whiteUserList||s.push("whiteUserList"),n.owner||s.push("owner"),n.defaultDingToken||s.push("defaultDingToken"),Array.isArray(n.conversations)||s.push("conversations"),s.length>0)throw new Error(`config.json \u7F3A\u5C11\u5FC5\u8981\u5B57\u6BB5: ${s.join(", ")}`);return{config:n,configPath:t}}function E(e,t){return k(t)&&e.resolvedPhones[t]||t}function le(e,t,n){if(z(e,t))return!0;if(n){const s=e.config.conversations.find(o=>o.conversationId===n);if(s?.freedomMode||s?.qaMode)return!0;if(s?.whiteUserList&&s.whiteUserList.length>0)return s.whiteUserList.some(o=>E(e,o)===t)}return e.config.whiteUserList.some(s=>E(e,s)===t)}function H(e,t){const n=e.config.owner;if(!n)return!1;const s=e.resolvedPhones[n];return!!s&&s===t}function B(e,t){return e.config.adminUserList?.length?e.config.adminUserList.some(n=>E(e,n)===t):!1}function z(e,t){return H(e,t)||B(e,t)}function G(e,t,...n){e.config.debug&&console.log(`[DEBUG] ${t}`,...n)}const fe=/^1\d{10}$/;function k(e){return fe.test(e)}function U(e){return!k(e)&&!e.includes("_")&&e.length<=15&&/^[A-Za-z0-9]+$/.test(e)}function _(e){return g.default.join(D(e),"user-map.json")}function X(e){const t=_(e);if(!c.default.existsSync(t))return{};try{const n=JSON.parse(c.default.readFileSync(t,"utf-8"));if(typeof n=="object"&&n!==null)return n}catch{}return{}}function J(e,t){const n=_(e);try{c.default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8")}catch(s){console.error("\u4FDD\u5B58 user-map.json \u5931\u8D25:",s)}}function de(e,t){for(const[n,s]of Object.entries(e.resolvedPhones))if(s===t)return n;return null}function L(e){return g.default.join(D(e),"user-id-name-map.json")}function K(e){const t=L(e);if(!c.default.existsSync(t))return{};try{const n=JSON.parse(c.default.readFileSync(t,"utf-8"));if(typeof n=="object"&&n!==null)return n}catch{}return{}}function Z(e,t){const n=L(e);try{c.default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8")}catch(s){console.error("\u4FDD\u5B58 user-id-name-map.json \u5931\u8D25:",s)}}async function ge(e,t){if(!t)return null;const n=K(e);if(n[t])return n[t];const s=await(0,h.queryDingUser)(e,t);return s&&s.name?(n[t]=s.name,Z(e,n),s.name):null}async function Se(e,t){if(!t)return null;if(!k(t)&&!U(t))return t;if(e.resolvedPhones[t])return e.resolvedPhones[t];let n=null;return k(t)?n=await(0,h.queryUserIdByMobile)(e,t):U(t)&&(n=await(0,h.queryUserIdByJobNumber)(e,t)),n&&(e.resolvedPhones[t]=n,J(e,e.resolvedPhones)),n}async function he(e){e.resolvedPhones=X(e);const t=[],n=async s=>{if(e.resolvedPhones[s])return;let o=null;k(s)?o=await(0,h.queryUserIdByMobile)(e,s):U(s)&&(o=await(0,h.queryUserIdByJobNumber)(e,s)),o&&(e.resolvedPhones[s]=o,t.push(s))};e.config.owner&&(k(e.config.owner)||U(e.config.owner)?(await n(e.config.owner),e.resolvedPhones[e.config.owner]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790 owner: ${e.config.owner}`)):console.warn(`[WARN] owner \u683C\u5F0F\u65E0\u6548(\u9700\u4E3A\u624B\u673A\u53F7\u6216\u5DE5\u53F7): ${e.config.owner}`));for(const s of e.config.whiteUserList)(k(s)||U(s))&&(await n(s),e.resolvedPhones[s]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790 whiteUserList: ${s}`));for(const s of e.config.conversations)if(s.whiteUserList)for(const o of s.whiteUserList)(k(o)||U(o))&&(await n(o),e.resolvedPhones[o]||console.warn(`[WARN] \u65E0\u6CD5\u89E3\u6790\u7FA4\u767D\u540D\u5355: ${o}`));t.length>0&&J(e,e.resolvedPhones),console.log(`[\u7528\u6237\u89E3\u6790] \u5DF2\u52A0\u8F7D ${Object.keys(e.resolvedPhones).length} \u6761\u8BB0\u5F55 (${t.length} \u6761\u65B0\u89E3\u6790)`)}function V(e,t){const s=O(e,t)?.linkConversationId||t;return q.default.createHash("md5").update(s).digest("hex")}function ye(e){return e.currentWebhook||e.sessionWebhook}function me(e){return e.currentConversationId||e.conversationId}function I(e,t){const n=e.activeSessions.get(t);if(n)return{key:t,session:n};const s=O(e,t);if(s?.linkConversationId){for(const o of e.activeSessions)if(O(e,o[0])?.linkConversationId===s.linkConversationId)return{key:o[0],session:o[1]}}}function O(e,t){return e.config.conversations.find(n=>n.conversationId===t)}function N(e,t){const n=V(e,t);return g.default.join(D(e),n)}function j(e,t){return g.default.join(N(e,t),".sessions")}function ee(e,t){return g.default.join(N(e,t),".tasks")}function ne(e,t){return g.default.join(N(e,t),".images")}function v(e,t){const n=t.claudeSessionId||t.startTimeStr;return g.default.join(j(e,t.conversationId),n)}function p(e){return e.claudeSessionId||e.startTimeStr}function $e(e,t){const n=I(e,t);if(!n)return null;const{session:s,isProcessing:o,messageQueue:a}=n.session;return[`- **\u4F1A\u8BDDID:** ${p(s)}`,`- **\u53D1\u8D77\u8005:** ${s.startNickName}(${s.startStaffId})`,`- **\u5F00\u59CB\u65F6\u95F4:** ${s.startTimeStr}`,`- **\u6700\u540E\u53D1\u9001\u8005:** ${n.session.lastSenderStaffId}`,`- **\u5904\u7406\u4E2D:** ${o}`,`- **\u6392\u961F\u6D88\u606F:** ${a?.length||0} \u6761`].join(`
|
|
2
|
+
`)}function we(e,t,n){const s=I(e,t);if(!s)return null;const o=s.session,a=`${v(e,o.session)}/session.log`;if(!c.default.existsSync(a))return null;try{return c.default.readFileSync(a,"utf-8").split(`
|
|
3
|
+
`).filter(i=>i.length>0).slice(-n).join(`
|
|
4
|
+
`)}catch{return null}}function te(e,t,n){const s=j(e,t),o=`${s}/${n}/session.json`;try{return w.fileUtil.getJSON(o)}catch{}const a=parseInt(n,10);if(!isNaN(a)&&a>0){const f=w.dateUtil.mm(a).format("YYYY-MM-DD-HH-mm-ss"),d=`${s}/${f}/session.json`;try{return w.fileUtil.getJSON(d)}catch{}}return null}function ve(e,t){const n=j(e,t);if(!c.default.existsSync(n))return null;const s=I(e,t),o=s?p(s.session.session):null;let a=null,f=0;try{const d=c.default.readdirSync(n,{withFileTypes:!0});for(const i of d){if(!i.isDirectory())continue;const l=g.default.join(n,i.name,"session.json");if(c.default.existsSync(l))try{const r=w.fileUtil.getJSON(l);if(o&&p(r)===o)continue;r.startTime>f&&(f=r.startTime,a=r)}catch{continue}}}catch{}return a}function Q(e,t,n){if(n.claudeSessionId&&!t.claudeSessionId){const o=v(e,t);t.claudeSessionId=n.claudeSessionId;const a=v(e,t);o!==a&&c.default.existsSync(o)&&(c.default.renameSync(o,a),console.log(`[${$()}] \u4F1A\u8BDD\u76EE\u5F55\u91CD\u547D\u540D: ${g.default.basename(o)} -> ${g.default.basename(a)}`))}n.agentSessionId&&!t.agentSessionId&&(t.agentSessionId=n.agentSessionId);const s=`${v(e,t)}/session.json`;try{n.sessionWebhook&&(t.sessionWebhook=n.sessionWebhook),n.currentWebhook!==void 0&&(t.currentWebhook=n.currentWebhook||void 0),n.currentConversationId!==void 0&&(t.currentConversationId=n.currentConversationId||void 0),c.default.writeFileSync(s,JSON.stringify(t,null,2),"utf-8");const o=n.claudeSessionId?"claudeSessionId":n.agentSessionId?"agentSessionId":n.currentWebhook!==void 0?"currentWebhook":"sessionWebhook";console.log(`[${$()}] \u4F1A\u8BDD\u6587\u4EF6\u5DF2\u4FDD\u5B58: ${o}`),C(e,t.conversationId)}catch(o){console.error("\u66F4\u65B0 session.json \u5931\u8D25:",o)}}function pe(e,t,n){const s=`${e}/session.log`,a=`[${$()}] [${t.toUpperCase()}]: ${n}
|
|
5
|
+
`;try{c.default.appendFileSync(s,a,"utf-8")}catch{}}function A(e,t){return`${j(e,t)}/active.json`}function C(e,t){const n=e.activeSessions.get(t),s=A(e,t);try{if(!n){c.default.existsSync(s)&&c.default.unlinkSync(s);return}const o={session:n.session,lastSenderStaffId:n.lastSenderStaffId,conversationConfig:n.conversationConfig};c.default.mkdirSync(g.default.dirname(s),{recursive:!0}),c.default.writeFileSync(s,JSON.stringify(o,null,2),"utf-8"),G(e,`\u6D3B\u8DC3\u4F1A\u8BDD\u5DF2\u6301\u4E45\u5316: \u7FA4=${t}`)}catch(o){console.error(`\u6301\u4E45\u5316\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: \u7FA4=${t}`,o)}}function ke(e){for(const t of e.config.conversations){const n=A(e,t.conversationId);if(c.default.existsSync(n))try{const s=w.fileUtil.getJSON(n);if(!s?.session){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u65E0\u6548\uFF0C\u8DF3\u8FC7: ${n}`);continue}const o=v(e,s.session);if(!c.default.existsSync(o)){console.log(`\u6D3B\u8DC3\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728\uFF0C\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6: ${n}`),c.default.unlinkSync(n);continue}e.activeSessions.set(t.conversationId,{session:s.session,lastSenderStaffId:s.lastSenderStaffId||s.session.startStaffId,isProcessing:!1,messageQueue:[],conversationConfig:s.conversationConfig}),console.log(`\u6062\u590D\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${t.conversationId}, \u4F1A\u8BDDID=${p(s.session)}`)}catch(s){console.error(`\u52A0\u8F7D\u6D3B\u8DC3\u4F1A\u8BDD\u5931\u8D25: ${n}`,s)}}}async function se(e,t,n){const s=I(e,t);if(!s){console.log(`\u7FA4 ${t} \u65E0\u6D3B\u8DC3\u4F1A\u8BDD`),await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u26A0\uFE0F \u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD\uFF0C\u65E0\u9700\u7ED3\u675F\u3002
|
|
6
|
+
\u53EF\u4EE5\u901A\u8FC7 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD\u3002`});return}const{key:o,session:a}=s,{session:f}=a,d=v(e,f),i=p(f);console.log(`\u7ED3\u675F\u4F1A\u8BDD: \u7FA4=${t}, \u4F1A\u8BDDID=${i}`),a.agent?.interrupt(a,"\u7ED3\u675F\u4F1A\u8BDD\u65F6\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Agent \u8FDB\u7A0B")&&c.default.appendFileSync(`${d}/session.log`,`[${$()}] [SYSTEM]: \u7ED3\u675F\u4F1A\u8BDD\u65F6\u4E2D\u65AD Claude \u8FDB\u7A0B
|
|
7
|
+
`,"utf-8");const r=a.messageQueue?.length??0;r>0&&(a.messageQueue=[],console.log(`[${$()}] \u7ED3\u675F\u4F1A\u8BDD\u65F6\u6E05\u7A7A\u6D88\u606F\u961F\u5217: \u7FA4=${t}, \u6E05\u7A7A${r}\u6761\u6D88\u606F`)),await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u{1F4AC} \u4F1A\u8BDD\u5DF2\u7ED3\u675F
|
|
8
|
+
\u{1F194} ${i}${r>0?`
|
|
9
|
+
\u{1F5D1}\uFE0F \u5DF2\u6E05\u7A7A\u6D88\u606F\u961F\u5217\uFF0C\u4E22\u5F03${r}\u6761\u5F85\u5904\u7406\u6D88\u606F`:""}`}),e.activeSessions.delete(o),C(e,o),c.default.appendFileSync(`${d}/session.log`,`[${$()}] [SYSTEM]: \u7528\u6237\u8BF7\u6C42\u7ED3\u675F\u4F1A\u8BDD
|
|
10
|
+
`,"utf-8")}async function Ce(e,t,n,s,o,a){const f=te(e,t,s);if(!f)return await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u274C \u672A\u627E\u5230\u4F1A\u8BDD ${s}\uFF0C\u8BE5\u4F1A\u8BDD\u53EF\u80FD\u5DF2\u88AB\u6E05\u7406\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u59CB\u65B0\u4F1A\u8BDD`}),!1;const d=v(e,f);if(!c.default.existsSync(d))return await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u274C \u4F1A\u8BDD ${s} \u7684\u6570\u636E\u5DF2\u88AB\u6E05\u7406\uFF0C\u65E0\u6CD5\u6062\u590D\uFF0C\u8BF7\u53D1\u9001\u65B0\u6D88\u606F\u5F00\u59CB\u65B0\u4F1A\u8BDD`}),!1;const i=I(e,t);i&&(console.log(`\u5207\u6362\u4F1A\u8BDD\uFF0C\u5148\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD: ${p(i.session.session)}`),i.session.agent?.interrupt(i.session,"\u5207\u6362\u4F1A\u8BDD\u65F6\u4E2D\u65AD\u6B63\u5728\u6267\u884C\u7684 Agent \u8FDB\u7A0B"),e.activeSessions.delete(i.key),C(e,i.key),c.default.appendFileSync(`${v(e,i.session.session)}/session.log`,`[${$()}] [SYSTEM]: \u4F1A\u8BDD\u88AB\u5207\u6362\u5230 ${s}\uFF0C\u7ED3\u675F\u5F53\u524D\u4F1A\u8BDD
|
|
11
|
+
`,"utf-8")),e.activeSessions.set(t,{session:f,lastSenderStaffId:o,isProcessing:!1,messageQueue:[],conversationConfig:a}),C(e,t);const l=!!f.claudeSessionId,r=p(f);return await(0,h.sendDingMessage)(e,{conversationId:t,sessionWebhook:n,content:`\u2705 \u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD (\u{1F194} ${r})
|
|
12
|
+
${l?"\u{1F504} \u5DF2\u6062\u590D\u5BF9\u8BDD\u4E0A\u4E0B\u6587":"\u26A0\uFE0F \u8BE5\u4F1A\u8BDD\u65E0\u5386\u53F2\u4E0A\u4E0B\u6587\uFF0C\u5C06\u4ECE\u5934\u5F00\u59CB"}
|
|
13
|
+
\u{1F4A1} \u56DE\u590D /end \u53EF\u7ED3\u675F\u672C\u8F6E\u5BF9\u8BDD`}),console.log(`\u5DF2\u5207\u6362\u5230\u5386\u53F2\u4F1A\u8BDD: \u7FA4=${t}, \u4F1A\u8BDDID=${r}, \u6709Claude\u4E0A\u4E0B\u6587=${l}`),!0}function F(e,t){t.agent||(t.agent=(0,W.createAgent)(t.conversationConfig.agent||"claude"))}async function ie(e,t){const{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:a,message:f,conversationConfig:d}=t,i=e.config.sessionMaxConcurrency??e.DEFAULT_SESSION_MAX_CONCURRENCY;if(e.activeSessions.size>=i){console.log(`\u8FBE\u5230\u6700\u5927\u5E76\u53D1\u6570 (${i})\uFF0C\u62D2\u7EDD\u65B0\u4F1A\u8BDD: \u7FA4=${n}`),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:"\u{1F92F} \u5F53\u524D\u7E41\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5..."});return}const l=Date.now(),r=q.default.randomUUID(),u={conversationId:n,sessionWebhook:s,startTime:l,startTimeStr:w.dateUtil.mm(l).format("YYYY-MM-DD-HH-mm-ss"),startStaffId:o,startNickName:a};console.log(`\u521B\u5EFA\u65B0\u4F1A\u8BDD: \u7FA4=${n}, \u4F1A\u8BDDID=${r}, \u53D1\u8D77\u8005=${o}, \u5F53\u524D\u5E76\u53D1=${e.activeSessions.size+1}/${i}`);const y=v(e,u);c.default.mkdirSync(y,{recursive:!0}),c.default.writeFileSync(`${y}/session.json`,JSON.stringify(u,null,2),"utf-8");const S=(0,W.createAgent)(d.agent||"claude");e.activeSessions.set(n,{session:u,lastSenderStaffId:o,isProcessing:!0,messageQueue:[],conversationConfig:d,agent:S}),C(e,n),d.receiveReply!==!1&&await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:`\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406...
|
|
14
|
+
\u{1F194} ${r}`});try{await S.executeQuery(e,u,{message:f,skill:d.taskCfg?.skill,senderNick:a,senderStaffId:o,newSessionId:r})}catch(b){console.error("\u6267\u884C Agent \u67E5\u8BE2\u5931\u8D25:",b),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${b instanceof Error?b.message:String(b)}`})}finally{const b=e.activeSessions.get(n);b&&(b.isProcessing=!1)}const m=e.activeSessions.get(n);m&&m.messageQueue.length>0&&await M(e,n)}async function M(e,t){const n=e.activeSessions.get(t);if(!n||!n.messageQueue||n.messageQueue.length===0)return;const s=n.messageQueue.shift(),{message:o,senderStaffId:a,senderNick:f,sessionWebhook:d,conversationId:i,enqueueTime:l}=s,r=600*1e3;if(Date.now()-l>r){console.log(`\u961F\u5217\u6D88\u606F\u5DF2\u8FC7\u671F\uFF0C\u8DF3\u8FC7: \u5165\u961F\u65F6\u95F4=${new Date(l).toLocaleString()}, \u7FA4=${i}`),n.messageQueue.length>0&&await M(e,t);return}if(console.log(`\u5904\u7406\u961F\u5217\u6D88\u606F: \u7FA4=${i}, \u5269\u4F59 ${n.messageQueue.length} \u6761`),n.isProcessing=!0,n.lastSenderStaffId=a,C(e,t),n.conversationConfig.receiveReply!==!1){const u=o.length>50?o.substring(0,50)+"\u2026":o;await(0,h.sendDingMessage)(e,{conversationId:i,sessionWebhook:d,atUserId:a,content:`\u{1F680} \u5F00\u59CB\u5904\u7406\u6D88\u606F\u300C${u}\u300D`}).catch(()=>{})}try{F(e,n),await n.agent.executeQuery(e,n.session,{message:o,skill:n.conversationConfig.taskCfg?.skill,senderNick:f,senderStaffId:a})}catch(u){console.error("\u6267\u884C\u961F\u5217 Agent \u67E5\u8BE2\u5931\u8D25:",u),await(0,h.sendDingMessage)(e,{conversationId:i,sessionWebhook:d,atUserId:a,content:` \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${u instanceof Error?u.message:String(u)}`})}finally{n.isProcessing=!1}if(n.goonPending){n.goonPending=!1,n.interrupted=!1,n.isProcessing=!0;try{F(e,n),await n.agent.executeQuery(e,n.session,{message:"\u7EE7\u7EED",senderNick:n.session.startNickName,senderStaffId:n.lastSenderStaffId})}catch(u){console.error("goonPending \u6062\u590D\u6267\u884C\u5931\u8D25:",u)}finally{n.isProcessing=!1}}n.messageQueue&&n.messageQueue.length>0&&await M(e,t)}async function De(e,t){const{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:a,message:f,conversationConfig:d}=t,i=f.replace(/^\[提及用户: .+\]\n/,"");if((0,re.parseEndCommand)(i)){await se(e,n,s);return}const l=I(e,n),r=l?.session;if(r){const u=v(e,r.session);if(c.default.existsSync(u)||(c.default.mkdirSync(u,{recursive:!0}),c.default.writeFileSync(`${u}/session.json`,JSON.stringify(r.session,null,2),"utf-8"),console.log(`\u4F1A\u8BDD\u76EE\u5F55\u5DF2\u91CD\u5EFA: \u7FA4=${n}, \u8DEF\u5F84=${u}`)),r.isProcessing){const S={message:f,senderStaffId:o,senderNick:a,sessionWebhook:s,conversationId:n,enqueueTime:Date.now()};r.messageQueue||(r.messageQueue=[]),r.messageQueue.push(S);const m=r.messageQueue.length;console.log(`\u4F1A\u8BDD ${n} \u6D88\u606F\u5DF2\u5165\u961F\uFF0C\u6392\u961F\u7B2C ${m} \u6761`),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:`\u23F3 \u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u5DF2\u52A0\u5165\u961F\u5217\uFF08\u6392\u961F\u7B2C ${m} \u6761\uFF09`});return}const y=r.session.conversationId===n;console.log(`\u8FFD\u52A0\u6D88\u606F\u5230\u6D3B\u8DC3\u4F1A\u8BDD: \u7FA4=${n}, \u4F1A\u8BDDID=${p(r.session)}${y?"":`(\u5173\u8054\u7FA4,\u4F1A\u8BDD\u5F52\u5C5E=${r.session.conversationId})`}`),r.lastSenderStaffId=o,r.isProcessing=!0,C(e,l.key),y&&s!==r.session.sessionWebhook&&(r.session.sessionWebhook=s,Q(e,r.session,{sessionWebhook:s})),r.session.currentWebhook=s,r.session.currentConversationId=n,Q(e,r.session,{currentWebhook:s,currentConversationId:n}),d.receiveReply!==!1&&await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,content:"\u2705 \u6536\u5230\uFF0C\u6211\u6765\u5904\u7406..."});try{F(e,r),await r.agent.executeQuery(e,r.session,{message:f,skill:d.taskCfg?.skill,senderNick:a,senderStaffId:o})}catch(S){if(r.session.claudeSessionId){console.log(`[\u4F1A\u8BDD\u6062\u590D\u5931\u8D25] \u6E05\u9664 claudeSessionId \u5E76\u91CD\u65B0\u53D1\u8D77: ${r.session.claudeSessionId}`),r.session.claudeSessionId=void 0,e.updateSessionFile(r.session,{});try{F(e,r),await r.agent.executeQuery(e,r.session,{message:f,skill:d.taskCfg?.skill,senderNick:a,senderStaffId:o});return}catch(m){console.error("\u91CD\u8BD5\u6267\u884C Agent \u67E5\u8BE2\u5931\u8D25:",m),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${m instanceof Error?m.message:String(m)}`}),r.isProcessing=!1,await M(e,n);return}}console.error("\u6267\u884C Agent \u67E5\u8BE2\u5931\u8D25:",S),await(0,h.sendDingMessage)(e,{conversationId:n,sessionWebhook:s,atUserId:o,content:`\u274C \u5904\u7406\u6D88\u606F\u65F6\u53D1\u751F\u9519\u8BEF: ${S instanceof Error?S.message:String(S)}`})}finally{r.isProcessing=!1}await M(e,n)}else await ie(e,{conversationId:n,sessionWebhook:s,senderStaffId:o,senderNick:a,message:f,conversationConfig:d})}function Ie(e,t,n=!0){const s={sessionsDeleted:0,tasksDeleted:0,imagesDeleted:0,errors:[]},o=t?[t]:e.config.conversations.map(a=>a.conversationId);for(const a of o){let f=null;if(n){const u=I(e,a);u&&(f=p(u.session.session))}const d=j(e,a);if(c.default.existsSync(d))try{const u=c.default.readdirSync(d,{withFileTypes:!0});for(const y of u){if(!y.isDirectory()||f&&y.name===f)continue;const S=g.default.join(d,y.name);try{c.default.rmSync(S,{recursive:!0,force:!0}),s.sessionsDeleted++}catch{s.errors.push(`\u5220\u9664\u4F1A\u8BDD\u76EE\u5F55\u5931\u8D25: ${S}`)}}}catch{s.errors.push(`\u8BFB\u53D6sessions\u76EE\u5F55\u5931\u8D25: ${d}`)}const i=ee(e,a);if(c.default.existsSync(i))try{const u=c.default.readdirSync(i,{withFileTypes:!0});for(const y of u){if(!y.isDirectory())continue;const S=g.default.join(i,y.name);try{c.default.rmSync(S,{recursive:!0,force:!0}),s.tasksDeleted++}catch{s.errors.push(`\u5220\u9664\u4EFB\u52A1\u76EE\u5F55\u5931\u8D25: ${S}`)}}}catch{s.errors.push(`\u8BFB\u53D6tasks\u76EE\u5F55\u5931\u8D25: ${i}`)}const l=ne(e,a);if(c.default.existsSync(l))try{const u=c.default.readdirSync(l,{withFileTypes:!0});for(const y of u){const S=g.default.join(l,y.name);try{c.default.unlinkSync(S),s.imagesDeleted++}catch{s.errors.push(`\u5220\u9664\u56FE\u7247\u5931\u8D25: ${S}`)}}}catch{s.errors.push(`\u8BFB\u53D6images\u76EE\u5F55\u5931\u8D25: ${l}`)}const r=g.default.join(N(e,a),".playwright-cli");if(c.default.existsSync(r))try{c.default.rmSync(r,{recursive:!0,force:!0})}catch{s.errors.push(`\u5220\u9664 playwright-cli \u7F13\u5B58\u5931\u8D25: ${r}`)}if(!n){const u=A(e,a);if(c.default.existsSync(u))try{c.default.unlinkSync(u)}catch{s.errors.push(`\u5220\u9664\u6D3B\u8DC3\u4F1A\u8BDD\u6587\u4EF6\u5931\u8D25: ${u}`)}e.activeSessions.has(a)&&e.activeSessions.delete(a)}}return s}async function be(e,t){const n=[],s=e.getConversationConfig(t),o=!!s?.linkConversationId,a=e.activeSessions.get(t);if(a?.currentProcess)try{a.currentProcess.kill("SIGTERM")}catch{}e.activeSessions.delete(t),n.push({label:"\u505C\u6B62\u6D3B\u8DC3\u4F1A\u8BDD",ok:!0,detail:a?"\u5DF2\u6E05\u9664":"\u65E0\u6D3B\u8DC3\u4F1A\u8BDD"});try{const i=e.cronEngine?.listJobs(t)||[];let l=0;for(const r of i)e.cronEngine?.removeJob(r.id)&&l++;n.push({label:"\u6E05\u7406\u5B9A\u65F6\u4EFB\u52A1",ok:!0,detail:`\u79FB\u9664 ${l} \u4E2A`})}catch(i){n.push({label:"\u6E05\u7406\u5B9A\u65F6\u4EFB\u52A1",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=g.default.join(D(e),"todo.json");if(c.default.existsSync(i)){const l=w.fileUtil.getJSON(i);l?.conversations?.[t]&&(delete l.conversations[t],c.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"))}n.push({label:"\u6E05\u7406 Todo \u6570\u636E",ok:!0})}catch(i){n.push({label:"\u6E05\u7406 Todo \u6570\u636E",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=g.default.join(D(e),"menu.json");if(c.default.existsSync(i)){const l=w.fileUtil.getJSON(i);if(l?.user){const r=Object.keys(l.user).filter(u=>u.startsWith(`${t}:`));for(const u of r)delete l.user[u];c.default.writeFileSync(i,JSON.stringify(l,null,2),"utf-8")}}n.push({label:"\u6E05\u7406\u5FEB\u6377\u83DC\u5355",ok:!0})}catch(i){n.push({label:"\u6E05\u7406\u5FEB\u6377\u83DC\u5355",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=e.timerEngine?.listTimers(t)||[];let l=0;for(const r of i)e.timerEngine?.removeTimer(r.id)&&l++;n.push({label:"\u6E05\u7406\u5EF6\u65F6\u4EFB\u52A1",ok:!0,detail:`\u79FB\u9664 ${l} \u4E2A`})}catch(i){n.push({label:"\u6E05\u7406\u5EF6\u65F6\u4EFB\u52A1",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const i=N(e,t);c.default.existsSync(i)?(c.default.rmSync(i,{recursive:!0,force:!0}),n.push({label:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55",ok:!0})):n.push({label:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55",ok:!0,detail:"\u76EE\u5F55\u4E0D\u5B58\u5728"}),o&&n.push({label:"\u5173\u8054\u76EE\u5F55",ok:!0,detail:`\u4FDD\u7559 (linkConversationId=${s.linkConversationId})`})}catch(i){n.push({label:"\u5220\u9664\u5DE5\u4F5C\u76EE\u5F55",ok:!1,detail:i instanceof Error?i.message:String(i)})}const f=e.config.conversations.findIndex(i=>i.conversationId===t);f>=0?(e.config.conversations.splice(f,1),n.push({label:"\u79FB\u9664\u914D\u7F6E",ok:!0})):n.push({label:"\u79FB\u9664\u914D\u7F6E",ok:!0,detail:"\u672A\u5728\u914D\u7F6E\u4E2D\u627E\u5230"});try{C(e,t),n.push({label:"\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6",ok:!0})}catch(i){n.push({label:"\u6E05\u7406\u6301\u4E45\u5316\u6587\u4EF6",ok:!1,detail:i instanceof Error?i.message:String(i)})}try{const{saveClientConfig:i}=require("./api-key-manager");i(e)}catch(i){console.error(`[${$()}] \u9500\u6BC1\u540E\u4FDD\u5B58\u914D\u7F6E\u5931\u8D25:`,i)}return{success:n.every(i=>i.ok),steps:n}}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var d=exports&&exports.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.StreamingCard=void 0;const f=d(require("urllib")),m=d(require("crypto")),c=require("./session"),h=500,T=30,g=2e3,p="https://api.dingtalk.com";class u{constructor(t,e){this.state="processing",this.lastSentContent="",this.lastSentAt=0,this.pendingContent="",this.timer=null,this.inFlight=!1,this._permissionDenied=!1,this._missingScopes="",this.self=t.self,this.outTrackId=e,this.templateKey=t.cardTemplateKey||"content"}static async create(t){const e=`card_${Date.now()}_${m.default.randomBytes(4).toString("hex")}`,s=new u(t,e),i=await t.self.dingStreamClient.getAccessToken(),o=t.conversationType!=="1"?`dtv1.card//IM_GROUP.${t.conversationId}`:`dtv1.card//IM_ROBOT.${t.senderStaffId}`,n={cardTemplateId:t.cardTemplateId,outTrackId:e,cardData:{cardParamMap:{config:'{"autoLayout":true,"enableForward":true}',[s.templateKey]:""}},callbackType:"STREAM",openSpaceId:o,imGroupOpenSpaceModel:{supportForward:!0},imRobotOpenSpaceModel:{spaceType:"IM_ROBOT",supportForward:!0},userIdType:1};try{const r=await f.default.request(`${p}/v1.0/card/instances/createAndDeliver`,{method:"POST",data:n,contentType:"json",headers:{"x-acs-dingtalk-access-token":i},dataType:"json",timeout:1e4});if(r.status!==200)return console.warn(`[${(0,c.timestamp)()}] StreamingCard \u521B\u5EFA\u5931\u8D25: status=${r.status}`),null;const l=r.data;return s.checkPermissionError(l)?null:(s.lastSentAt=Date.now(),s)}catch(r){return console.warn(`[${(0,c.timestamp)()}] StreamingCard \u521B\u5EFA\u5F02\u5E38:`,r),null}}async update(t){this.state==="failed"||this._permissionDenied||(this.pendingContent=t,this.scheduleFlush(!1))}async finalize(t){return this._permissionDenied?!1:(this.pendingContent=t,this.timer&&(clearTimeout(this.timer),this.timer=null),await this.flush(!0))}get failed(){return this.state==="failed"}get permissionDenied(){return this._permissionDenied}get missingScopes(){return this._missingScopes}scheduleFlush(t){if(this.inFlight)return;const s=Date.now()-this.lastSentAt;if(s<h){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.flush(t).catch(()=>{})},h-s);return}const i=this.pendingContent.length-this.lastSentContent.length;if(!t&&i<T&&i>0){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null,this.flush(t).catch(()=>{})},h);return}this.flush(t).catch(()=>{})}async flush(t){if(this.inFlight)return!1;this.inFlight=!0;const e=this.pendingContent;this.pendingContent="";let s=e;e.length>g&&(s=e.substring(0,g)+`
|
|
2
|
+
|
|
3
|
+
...`);const i=await this.getAccessToken();if(!i)return this.inFlight=!1,this.state="failed",!1;const o={outTrackId:this.outTrackId,key:this.templateKey,content:s,isFull:!0,isFinalize:t,isError:!1,guid:m.default.randomUUID()};try{const n=await f.default.request(`${p}/v1.0/card/streaming`,{method:"PUT",data:o,contentType:"json",headers:{"x-acs-dingtalk-access-token":i},dataType:"json",timeout:1e4});if(this.lastSentContent=e,this.lastSentAt=Date.now(),n.status!==200){const l=n.data;return this.checkPermissionError(l)?(this.state="failed",this.inFlight=!1,!1):(this.state="failed",this.inFlight=!1,!1)}const r=n.data;return this.checkPermissionError(r)?(this.state="failed",this.inFlight=!1,!1):(t&&(this.state="finished"),this.inFlight=!1,!0)}catch(n){return console.warn(`[${(0,c.timestamp)()}] StreamingCard \u66F4\u65B0\u5F02\u5E38:`,n),this.state="failed",this.inFlight=!1,!1}}checkPermissionError(t){const e=t.errorCode||t.errmsg||"";if(e.includes("AccessTokenPermissionDenied")||e.includes("AccessDenied")){this._permissionDenied=!0;const s=t.accessDeniedDetail;return s&&(this._missingScopes=JSON.stringify(s)),console.warn(`[${(0,c.timestamp)()}] StreamingCard \u6743\u9650\u4E0D\u8DB3: ${e}`),!0}return!1}async getAccessToken(){try{return await this.self.dingStreamClient.getAccessToken()}catch{return null}}}exports.StreamingCard=u;
|
package/dist/src/biz/task.js
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${
|
|
1
|
+
"use strict";var B=exports&&exports.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.notifyTaskQueue=R,exports.formatTaskInfo=mt,exports.countTodoTask=pt,exports.getOneTodoTask=Z,exports.finishTask=tt,exports.cancelTask=gt,exports.parseTaskCancelCommand=$t,exports.handleTask=et,exports.runTaskHandlerLoop=kt,exports.saveTask=ht;const g=require("utils-ok"),f=B(require("fs")),x=B(require("path")),at=require("../common"),J=require("./messaging"),z=require("./claude-process"),rt=require("./claude-sdk"),s=require("./session"),S=require("./api-key-manager"),Y=require("./platform"),H=3,ct=1e4,lt=6e4,W=[];function R(){for(;W.length>0;)W.shift()()}function ut(t){return new Promise(e=>{const o=()=>{clearTimeout(i),e()},i=setTimeout(()=>{const r=W.indexOf(o);r!==-1&&W.splice(r,1),e()},t);i.unref?.(),W.push(o)})}function mt(t){const e=[],o=[],i=[],r=[];for(const a of t.config.conversations){const c=(0,s.getTasksDir)(t,a.conversationId);if(!f.default.existsSync(c))continue;const m=g.fileUtil.dirWalker(c);for(const d of m){const l=x.default.basename(d);try{const y=g.fileUtil.getJSON(d);if(!y)continue;l==="task.json"?e.push(y):l==="task-doing.json"?o.push(y):l==="task-done.json"?i.push(y):l==="task-failed.json"&&r.push(y)}catch{}}}e.sort((a,c)=>a.startTime-c.startTime),o.sort((a,c)=>a.startTime-c.startTime),i.sort((a,c)=>c.startTime-a.startTime),r.sort((a,c)=>c.startTime-a.startTime);const u=[];if(o.length>0){const a=o.map(c=>`#${c.startTime} ${c.senderNickName||c.senderStaffId}: ${F(c)}`);u.push(`**\u23F3 \u5904\u7406\u4E2D (${o.length})**
|
|
2
|
+
${a.join(`
|
|
3
3
|
`)}`)}else u.push(`**\u23F3 \u5904\u7406\u4E2D**
|
|
4
|
-
\u65E0`);if(e.length>0){const
|
|
5
|
-
${
|
|
4
|
+
\u65E0`);if(e.length>0){const a=e.map(c=>`#${c.startTime} ${c.senderNickName||c.senderStaffId}: ${F(c)}`);u.push(`**\u{1F4CB} \u5F85\u529E\u961F\u5217 (${e.length})**
|
|
5
|
+
${a.join(`
|
|
6
6
|
`)}`)}else u.push(`**\u{1F4CB} \u5F85\u529E\u961F\u5217**
|
|
7
|
-
\u65E0`);const n=
|
|
8
|
-
${
|
|
7
|
+
\u65E0`);const n=i.slice(0,5);if(n.length>0){const a=n.map(c=>`#${c.startTime} ${c.senderNickName||c.senderStaffId}: ${F(c)}`);u.push(`**\u2705 \u6700\u8FD1\u5B8C\u6210 (top ${n.length}/${i.length})**
|
|
8
|
+
${a.join(`
|
|
9
9
|
`)}`)}else u.push(`**\u2705 \u6700\u8FD1\u5B8C\u6210**
|
|
10
|
-
\u65E0`);if(
|
|
11
|
-
${
|
|
10
|
+
\u65E0`);if(r.length>0){const a=r.map(c=>`#${c.startTime} ${c.senderNickName||c.senderStaffId}: ${F(c)}${c.retryCount?` (\u91CD\u8BD5${c.retryCount}\u6B21)`:""}`);u.push(`**\u274C \u5931\u8D25 (${r.length})**
|
|
11
|
+
${a.join(`
|
|
12
12
|
`)}`)}return u.join(`
|
|
13
13
|
|
|
14
|
-
`)}function
|
|
15
|
-
`),n=await(0,
|
|
16
|
-
\u539F\u56E0: ${
|
|
17
|
-
`),
|
|
14
|
+
`)}function ft(t,e=80){const o=t.replace(/\n/g," ").trim();return o.length>e?o.slice(0,e)+"...":o}function F(t){return t.title?t.title:ft(t.prompt)}async function dt(t,e,o){const i=(0,s.getConversationDir)(t,e),r=(0,z.resolveClaudeSettingsPath)(t,i),u=["\u8BF7\u5BF9\u4EE5\u4E0B\u4EFB\u52A1\u9700\u6C42\u8FDB\u884C\u9884\u5904\u7406\uFF0C\u751F\u6210\u7B80\u77ED\u6807\u9898\u548C\u4F18\u5316\u540E\u7684\u9700\u6C42\u63CF\u8FF0\u3002","\u76F4\u63A5\u8FD4\u56DEJSON\uFF0C\u4E0D\u8981markdown\u4EE3\u7801\u5757\u6216\u5176\u4ED6\u5185\u5BB9\u3002",'\u683C\u5F0F: {"title":"\u7B80\u77ED\u6807\u9898(15\u5B57\u4EE5\u5185)","promptSimply":"\u4F18\u5316\u540E\u7684\u9700\u6C42\u63CF\u8FF0\uFF0C\u4FDD\u7559\u539F\u59CB\u9700\u6C42\u7684\u6240\u6709\u5173\u952E\u4FE1\u606F\uFF0C\u4F7F\u63CF\u8FF0\u66F4\u6E05\u6670\u3001\u7ED3\u6784\u5316"}',"",`\u539F\u59CB\u9700\u6C42: ${o}`].join(`
|
|
15
|
+
`),n=await(0,rt.runOneShotPrompt)(u,{cwd:i,settingsPath:r,timeoutMs:3e4});if(!n.ok||!n.text.trim()){const a=n.timedOut?"\u8D85\u65F6":n.errorOutput.trim().substring(0,100)||"\u65E0\u8F93\u51FA";return console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u9884\u5904\u7406\u5931\u8D25(${a})\uFF0C\u4F7F\u7528\u539F\u59CBprompt`),null}try{let a=n.text.trim();const c=a.match(/\{[\s\S]*\}/);c&&(a=c[0]);const m=JSON.parse(a);return m.title&&m.promptSimply?(console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u9884\u5904\u7406\u5B8C\u6210: title="${m.title}"`),{title:String(m.title),promptSimply:String(m.promptSimply)}):(console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u9884\u5904\u7406\u8FD4\u56DE\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F7F\u7528\u539F\u59CBprompt`),null)}catch(a){return console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u9884\u5904\u7406JSON\u89E3\u6790\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u59CBprompt: ${a}`),null}}function pt(t){let e=0;for(const o of t.config.conversations){const i=(0,s.getTasksDir)(t,o.conversationId);if(f.default.existsSync(i)){const u=g.fileUtil.dirWalker(i).filter(n=>x.default.basename(n)==="task.json");e+=u.length}}return e}async function Z(t){for(const e of t.config.conversations){const o=(0,s.getTasksDir)(t,e.conversationId);if(!f.default.existsSync(o))continue;const r=g.fileUtil.dirWalker(o).filter(n=>x.default.basename(n)==="task.json");if(r.length===0)continue;const u=r.map(n=>{try{const a=g.fileUtil.getJSON(n);return a?{file:n,task:a}:null}catch{return console.error(`\u4EFB\u52A1\u6587\u4EF6\u89E3\u6790\u5931\u8D25\uFF0C\u8DF3\u8FC7: ${n}`),null}}).filter(n=>n!==null).sort((n,a)=>n.task.startTime-a.task.startTime);if(u.length>0){const{file:n,task:a}=u[0];return at.utils.addSuffixToFile(n,"-doing"),a}}}async function tt(t,e){const o=`${e}/task-doing.json`;let i;try{i=g.fileUtil.getJSON(o)}catch(a){console.error(`\u8BFB\u53D6\u4EFB\u52A1\u6587\u4EF6\u5931\u8D25: ${o}`,a);return}const r=`${e}/result.md`,u=f.default.existsSync(r)?g.fileUtil.getFileStr(r):"\u62B1\u6B49,\u4EFB\u52A1\u5904\u7406\u5F02\u5E38...";await(0,J.sendDingMessage)(t,{conversationId:i.conversationId,sessionWebhook:i.sessionWebhook,atUserId:i.senderStaffId,content:u,msgType:"markdown"});const n=o.replace("-doing.json","-done.json");g.fileUtil.rename(o,n)}async function b(t,e,o){const i=`${e}/task-doing.json`;let r;try{r=g.fileUtil.getJSON(i)}catch(n){console.error(`\u8BFB\u53D6\u4EFB\u52A1\u6587\u4EF6\u5931\u8D25: ${i}`,n);return}await(0,J.sendDingMessage)(t,{conversationId:r.conversationId,sessionWebhook:r.sessionWebhook,atUserId:r.senderStaffId,content:`\u274C \u4EFB\u52A1\u5931\u8D25: ${F(r)}
|
|
16
|
+
\u539F\u56E0: ${o}`,msgType:"markdown"});const u=i.replace("-doing.json","-failed.json");g.fileUtil.rename(i,u)}async function L(t,e,o){const i=`${e}/task-doing.json`,r=`${e}/task.json`;if(!f.default.existsSync(i))return!1;try{const n=g.fileUtil.getJSON(i),a=(n.retryCount||0)+1;if(a>=H)return console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u91CD\u8BD5\u6B21\u6570\u5DF2\u8FBE\u4E0A\u9650(${a}/${H})\uFF0C\u6807\u8BB0\u4E3A\u5931\u8D25: ${n.title||n.prompt}`),n.retryCount=a,f.default.writeFileSync(i,JSON.stringify(n,null,2),"utf-8"),await b(t,e,`${o} (\u5DF2\u91CD\u8BD5${a}\u6B21)`),!1;n.retryCount=a,f.default.writeFileSync(i,JSON.stringify(n,null,2),"utf-8"),console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u91CD\u7F6E\u4E3A\u5F85\u529E (\u91CD\u8BD5${a}/${H}): ${n.title||n.prompt}`)}catch(n){console.error(`[${(0,s.timestamp)()}] \u66F4\u65B0\u4EFB\u52A1\u91CD\u8BD5\u8BA1\u6570\u5931\u8D25:`,n)}return f.default.existsSync(i)&&g.fileUtil.rename(i,r),setTimeout(()=>R(),ct).unref?.(),!0}function gt(t,e,o){const i=[],r=e.trim(),u=o?t.config.conversations.filter(m=>m.conversationId===o):t.config.conversations;for(const m of u){const d=(0,s.getTasksDir)(t,m.conversationId);if(!f.default.existsSync(d))continue;const y=g.fileUtil.dirWalker(d).filter(k=>x.default.basename(k)==="task.json");for(const k of y)try{const T=g.fileUtil.getJSON(k);if(!T)continue;if(String(T.startTime)===r){i.push({file:k,task:T});continue}if(T.title&&T.title.includes(r)){i.push({file:k,task:T});continue}}catch{}}if(i.length===0)return`\u672A\u627E\u5230\u5339\u914D\u7684\u5F85\u529E\u4EFB\u52A1: ${r}`;let n=0;for(const{file:m,task:d}of i)try{f.default.unlinkSync(m),n++,console.log(`[${(0,s.timestamp)()}] \u5DF2\u53D6\u6D88\u4EFB\u52A1: #${d.startTime} ${d.title||d.prompt}`)}catch(l){console.error(`[${(0,s.timestamp)()}] \u53D6\u6D88\u4EFB\u52A1\u5931\u8D25: ${m}`,l)}const a=i.slice(0,5).map(m=>`#${m.task.startTime} ${F(m.task)}`).join(`
|
|
17
|
+
`),c=n>5?`
|
|
18
18
|
...\u5171\u53D6\u6D88 ${n} \u4E2A\u4EFB\u52A1`:"";return`\u5DF2\u53D6\u6D88 ${n} \u4E2A\u5F85\u529E\u4EFB\u52A1:
|
|
19
|
-
${
|
|
20
|
-
`);return f.default.writeFileSync(n
|
|
21
|
-
`);return f.default.writeFileSync(n
|
|
22
|
-
`);return f.default.writeFileSync(n
|
|
23
|
-
`);return f.default.writeFileSync(n
|
|
24
|
-
`);
|
|
19
|
+
${a}${c}`}function $t(t){const o=t.trim().match(/^\/task\s+cancel\s+(.+)$/i);return o?o[1].trim():null}function Q(t,e){const o=t.indexOf("--settings");o!==-1&&t.splice(o,2),e&&t.push("--settings",e)}async function et(t){const e=await Z(t);if(!e)return(0,s.debugLog)(t,"\u672A\u53D1\u73B0\u5F85\u529E\u4EFB\u52A1..."),!1;const o=(0,s.getConversationConfig)(t,e.conversationId),i=(0,s.getConversationDir)(t,e.conversationId),r=`${(0,s.getTasksDir)(t,e.conversationId)}/${e.startTimeStr}`;if(!f.default.existsSync(r))return console.error(`\u4EFB\u52A1\u76EE\u5F55\u4E0D\u5B58\u5728: ${r}`),!0;e.type!=="cron"&&await(0,J.sendDingMessage)(t,{conversationId:e.conversationId,sessionWebhook:e.sessionWebhook,atUserId:e.senderStaffId,content:`\u{1F504} \u5F00\u59CB\u5904\u7406\u4EFB\u52A1: ${F(e)}`});const u=`${r}/result.md`,n=`${r}/task.log`;console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u5904\u7406\u4E2D: ${e.title||e.prompt}`);const a=e.senderNickName&&e.senderStaffId?`${e.senderNickName}(${e.senderStaffId}), `:"unknown",c=t.config.apiKeyCfg,m=(0,S.getForceEnabledSettingsPath)(i);let d=!1,l=null;if(m)console.log(`[${(0,s.timestamp)()}] \u68C0\u6D4B\u5230 FORCE_ENABLE\uFF0C\u5F3A\u5236\u4F7F\u7528 settings-ding.json`);else if(c){if(l=(0,S.pickValidApiKey)(t),!l)return console.log(`[${(0,s.timestamp)()}] \u65E0\u53EF\u7528\u914D\u989D\uFF0C\u4EFB\u52A1\u91CD\u7F6E\u4E3A\u5F85\u529E`),await L(t,r,"\u65E0\u53EF\u7528\u914D\u989D"),!1;d=!0,console.log(`[${(0,s.timestamp)()}] \u5207\u6362\u5230 API Key \u6A21\u5F0F`)}const y=o?.taskCfg?.skill,k=o?.agent,T=e.promptSimply||e.prompt,M=`${y?`/${y}`:""} \u7528\u6237: ${a}, \u9700\u6C42: ${T}; \u6700\u540E\u5C06\u56DE\u590D\u5185\u5BB9\u4FDD\u5B58\u81F3: ${u}`.trim(),p=["--permission-mode",o?.permissionMode||"acceptEdits","--print",M];if(m)p.push("--settings",m);else if(d&&l){const h=(0,S.ensureSettingsWithApiKey)(i,l);p.push("--settings",h)}else if(!c){const h=x.default.join(i,".claude","settings.json");f.default.existsSync(h)&&(p.push("--settings",h),console.log(`[${(0,s.timestamp)()}] \u81EA\u52A8\u68C0\u6D4B\u5230 settings.json: ${h}`))}k&&p.push("--agent",k),(0,s.debugLog)(t,`\u6267\u884C\u547D\u4EE4: claude ${p.join(" ")}`);const O=20,P=1e4,V=1e4,U=o?.maxTurnTimeMins??t.config.maxTurnTimeMins??5,nt=U*60*1e3,st=60*1e3;let q=!1;const j="claude";if(!(0,Y.commandExists)(j)){const h=(0,Y.formatClaudeCommandMissingMessage)(j),$=[`[${(0,s.timestamp)()}] \u6267\u884C\u547D\u4EE4: ${j} ${p.join(" ")}`,`[${(0,s.timestamp)()}] \u9000\u51FA\u7801: 127`,h].join(`
|
|
20
|
+
`);return f.default.writeFileSync(n,$),await b(t,r,h),!0}const ot=h=>{const $=Date.now();return new Promise(I=>{const N=[];let E=!1,G=Date.now();const A=(0,Y.spawnCommand)(j,h,{cwd:i,stdio:["ignore","pipe","pipe"]}),K=setInterval(()=>{if(E){clearInterval(K);return}Date.now()-G>=nt&&(console.warn(`[${(0,s.timestamp)()}] \u4EFB\u52A1 Watchdog: ${U} \u5206\u949F\u65E0\u65E5\u5FD7\u8F93\u51FA\uFF0C\u81EA\u52A8 kill \u8FDB\u7A0B\u5E76\u91CD\u7F6E\u4E3A\u5F85\u529E`),clearInterval(K),E=!0,q=!0,A.kill("SIGINT"),(0,J.sendDingMessage)(t,{conversationId:e.conversationId,sessionWebhook:e.sessionWebhook,atUserId:e.senderStaffId,content:` \u4EFB\u52A1\u8D85\u8FC7 ${U} \u5206\u949F\u65E0\u54CD\u5E94\uFF0C\u5DF2\u81EA\u52A8\u7EC8\u6B62\u5E76\u91CD\u7F6E\u4E3A\u5F85\u529E\uFF0C\u5C06\u91CD\u65B0\u5C1D\u8BD5`}).catch(D=>console.error("\u53D1\u9001\u4EFB\u52A1 Watchdog \u901A\u77E5\u5931\u8D25:",D)))},st),X=()=>{G=Date.now()};A.stdout.on("data",C=>{const D=C.toString();process.stdout.write(D),N.push(D),X()}),A.stderr.on("data",C=>{const D=C.toString();process.stderr.write(D),N.push(D),X()}),A.on("close",C=>{E=!0,clearInterval(K),I({exitCode:C??1,output:N.join(""),elapsed:Date.now()-$})}),A.on("error",C=>{E=!0,clearInterval(K),console.error("\u8FDB\u7A0B\u6267\u884C\u9519\u8BEF:",C),N.push(`\u8FDB\u7A0B\u6267\u884C\u9519\u8BEF: ${C.message}`),I({exitCode:1,output:N.join(""),elapsed:Date.now()-$})})})};let w,v,_=0;for(;;){q=!1;const h=await ot(p);if(w=h.exitCode,v=h.output,q){const $=[`[${(0,s.timestamp)()}] \u6267\u884C\u547D\u4EE4: ${j} ${p.join(" ")}`,`[${(0,s.timestamp)()}] \u9000\u51FA\u7801: ${w}`,v].join(`
|
|
21
|
+
`);return f.default.writeFileSync(n,$),await L(t,r,`Watchdog \u8D85\u65F6\uFF08${U} \u5206\u949F\u65E0\u54CD\u5E94\uFF09`),!1}if(w!==0){if((0,S.isQuotaExhaustedError)(v)&&c){if(d){if(l){const I=(0,S.rotateApiKey)(t,l.apiKey);if(I){l=I,_=0;const N=(0,S.ensureSettingsWithApiKey)(i,l);Q(p,N),console.log(`[${(0,s.timestamp)()}] API Key \u914D\u989D\u8017\u5C3D(429)\uFF0C\u5207\u6362\u5230\u65B0 Key: ${(0,S.settingLabel)(I)}`);continue}}}else if(l=(0,S.pickValidApiKey)(t),l){d=!0,_=0;const I=(0,S.ensureSettingsWithApiKey)(i,l);Q(p,I),console.log(`[${(0,s.timestamp)()}] \u5207\u6362\u5230 API Key \u6A21\u5F0F`);continue}console.log(`[${(0,s.timestamp)()}] \u65E0\u53EF\u7528\u914D\u989D\uFF0C\u4EFB\u52A1\u91CD\u7F6E\u4E3A\u5F85\u529E`);const $=[`[${(0,s.timestamp)()}] \u6267\u884C\u547D\u4EE4: ${j} ${p.join(" ")}`,`[${(0,s.timestamp)()}] \u9000\u51FA\u7801: ${w}`,v].join(`
|
|
22
|
+
`);return f.default.writeFileSync(n,$),await L(t,r,"\u65E0\u53EF\u7528\u914D\u989D(429)"),!1}if((0,S.isAuthenticationError)(v)){console.log(`[${(0,s.timestamp)()}] \u68C0\u6D4B\u5230\u8BA4\u8BC1\u9519\u8BEF(401)\uFF0C\u6807\u8BB0\u4EFB\u52A1\u5931\u8D25`);const $=[`[${(0,s.timestamp)()}] \u6267\u884C\u547D\u4EE4: ${j} ${p.join(" ")}`,`[${(0,s.timestamp)()}] \u9000\u51FA\u7801: ${w}`,v].join(`
|
|
23
|
+
`);return f.default.writeFileSync(n,$),await b(t,r,"\u8BA4\u8BC1\u5931\u8D25(401)\uFF0CAPI Key \u65E0\u6548\u6216\u670D\u52A1\u672A\u6388\u6743"),!0}if((0,z.isRetryableApiError)(v)){if(h.elapsed<V&&d&&l&&c){if(_++,_>=O){const $=(0,S.rotateApiKey)(t,l.apiKey);if($){l=$,_=0;const I=(0,S.ensureSettingsWithApiKey)(i,l);Q(p,I),console.log(`[${(0,s.timestamp)()}] TPM \u9650\u6D41\u8FDE\u7EED\u5FEB\u901F\u5931\u8D25 ${O} \u6B21\uFF0C\u5207\u6362\u5230\u65B0 Key: ${(0,S.settingLabel)($)}`),await g.asyncUtil.sleep(P);continue}}}else if(h.elapsed<V){if(_++,_>=O){console.log(`[${(0,s.timestamp)()}] TPM \u9650\u6D41\u5FEB\u901F\u5931\u8D25\u8FDE\u7EED${O}\u6B21\uFF0C\u91CD\u7F6E\u4EFB\u52A1\u4E3A\u5F85\u529E`);const $=[`[${(0,s.timestamp)()}] \u6267\u884C\u547D\u4EE4: ${j} ${p.join(" ")}`,`[${(0,s.timestamp)()}] \u9000\u51FA\u7801: ${w}`,v].join(`
|
|
24
|
+
`);return f.default.writeFileSync(n,$),await L(t,r,"TPM\u9650\u6D41\u5FEB\u901F\u5931\u8D25\u6B21\u6570\u8FC7\u591A"),!1}console.log(`[${(0,s.timestamp)()}] \u68C0\u6D4B\u5230 TPM \u9650\u6D41(\u5FEB\u901F\u5931\u8D25)\uFF0C${P/1e3}s \u540E\u91CD\u8BD5 (${_}/${O})`)}else _=0,console.log(`[${(0,s.timestamp)()}] \u68C0\u6D4B\u5230 TPM \u9650\u6D41(\u8FDB\u7A0B\u5DF2\u8FD0\u884C\u4E00\u6BB5\u65F6\u95F4)\uFF0C\u91CD\u7F6E\u5FEB\u901F\u5931\u8D25\u8BA1\u6570\uFF0C${P/1e3}s \u540E\u91CD\u8BD5`);await g.asyncUtil.sleep(P);continue}}break}const it=[`[${(0,s.timestamp)()}] \u6267\u884C\u547D\u4EE4: ${j} ${p.join(" ")}`,`[${(0,s.timestamp)()}] \u9000\u51FA\u7801: ${w}`,v].join(`
|
|
25
|
+
`);if(f.default.writeFileSync(n,it),w!==0)return console.error(`\u547D\u4EE4\u6267\u884C\u5931\u8D25, \u9000\u51FA\u7801: ${w}`),await b(t,r,`\u6267\u884C\u5931\u8D25(\u9000\u51FA\u7801: ${w})`),!0;if(f.default.existsSync(u))console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u5904\u7406\u5B8C\u6210`);else return console.error("\u4EFB\u52A1\u672A\u6309\u9884\u671F\u5904\u7406"),await b(t,r,"\u672A\u751F\u6210\u7ED3\u679C\u6587\u4EF6"),!0;return await tt(t,r),!0}async function kt(t){for(;;)await et(t).catch(o=>(console.error(o),!1))||await ut(lt)}async function ht(t,e){const{conversationId:o,prompt:i,senderStaffId:r,senderNickName:u,sessionWebhook:n,type:a="normal"}=e,c=Date.now(),m=g.dateUtil.mm(c).format("YYYY-MM-DD-HH-mm-ss"),d=`${(0,s.getTasksDir)(t,o)}/${m}`,l=`${d}/task.json`,y={conversationId:o,startTime:c,startTimeStr:m,prompt:i,senderStaffId:r,senderNickName:u||"",sessionWebhook:n,type:a};await g.fileUtil.saveFileStr(JSON.stringify(y,null,2),l),(0,s.debugLog)(t,`\u4EFB\u52A1\u5DF2\u4FDD\u5B58: ${l}`),R(),dt(t,o,i).then(k=>{if(k)try{const T=`${d}/task-doing.json`,M=f.default.existsSync(T)?T:f.default.existsSync(l)?l:null;if(!M){console.log(`[${(0,s.timestamp)()}] \u9884\u5904\u7406\u5B8C\u6210\u4F46\u4EFB\u52A1\u6587\u4EF6\u5DF2\u4E0D\u5B58\u5728: ${d}`);return}const p=g.fileUtil.getJSON(M);p.title=k.title,p.promptSimply=k.promptSimply,f.default.writeFileSync(M,JSON.stringify(p,null,2),"utf-8"),console.log(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u9884\u5904\u7406\u7ED3\u679C\u5DF2\u66F4\u65B0: ${k.title}`)}catch(T){console.error(`[${(0,s.timestamp)()}] \u66F4\u65B0\u4EFB\u52A1\u9884\u5904\u7406\u7ED3\u679C\u5931\u8D25:`,T)}}).catch(k=>{console.error(`[${(0,s.timestamp)()}] \u4EFB\u52A1\u9884\u5904\u7406\u5F02\u5E38:`,k)})}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";var l=exports&&exports.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.TimerEngine=void 0,exports.parseDelay=T,exports.formatDelay=d,exports.formatTimerList=I,exports.formatTimerInfo=y;const c=l(require("fs")),h=l(require("path")),m=require("./messaging"),p=require("./claude-process"),$=require("./task"),a=require("./session");function T(n){const e=n.trim();if(!e)return null;const t=/^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/,s=e.match(t);if(!s)return null;const i=parseInt(s[1]||"0",10),o=parseInt(s[2]||"0",10),r=parseInt(s[3]||"0",10),u=parseInt(s[4]||"0",10);return i===0&&o===0&&r===0&&u===0?null:((i*24+o)*60+r)*60*1e3+u*1e3}function d(n){const e=Math.floor(n/1e3),t=Math.floor(e/86400),s=Math.floor(e%86400/3600),i=Math.floor(e%3600/60),o=e%60,r=[];return t>0&&r.push(`${t}\u5929`),s>0&&r.push(`${s}\u5C0F\u65F6`),i>0&&r.push(`${i}\u5206\u949F`),o>0&&r.push(`${o}\u79D2`),r.join("")||"0\u79D2"}function I(n){if(n.length===0)return" \u6682\u65E0\u5F85\u6267\u884C\u7684\u5B9A\u65F6\u4EFB\u52A1";const e=n.map(t=>{const s=t.fireAt-Date.now(),i=s>0?d(s):"\u5DF2\u5230\u671F";return`- \`${t.id}\` ${i}\u540E\u89E6\u53D1 \u2014 ${t.description}`});return`**\u23F0 \u5F85\u6267\u884C\u5B9A\u65F6\u4EFB\u52A1 (${n.length})**
|
|
2
|
+
|
|
3
|
+
${e.join(`
|
|
4
|
+
`)}`}function y(n){return`\u2705 \u5B9A\u65F6\u63D0\u9192\u5DF2\u8BBE\u7F6E
|
|
5
|
+
|
|
6
|
+
- ID: \`${n.id}\`
|
|
7
|
+
- \u5EF6\u65F6: ${d(n.delayMs)}
|
|
8
|
+
- \u89E6\u53D1\u65F6\u95F4: ${new Date(n.fireAt).toLocaleString()}
|
|
9
|
+
- \u5185\u5BB9: ${n.description}`}function g(n){return h.default.join((0,a.getClientDir)(n),"timers.json")}function v(n){const e=g(n);if(!c.default.existsSync(e))return[];try{const t=JSON.parse(c.default.readFileSync(e,"utf-8"));return Array.isArray(t)?t:[]}catch{return[]}}function f(n,e){const t=g(n),s=h.default.dirname(t);c.default.existsSync(s)||c.default.mkdirSync(s,{recursive:!0});const i=e.filter(o=>!o.fired);c.default.writeFileSync(t,JSON.stringify(i,null,2),"utf-8")}class S{constructor(e){this.jobs=[],this.handles=new Map,this.dc=e,this.jobs=v(this.dc)}start(){const e=Date.now();for(const t of this.jobs){if(t.fired)continue;const s=t.fireAt-e;s<=0?(console.log(`[${(0,a.timestamp)()}] Timer \u4EFB\u52A1 ${t.id} \u5DF2\u8FC7\u671F\uFF0C\u7ACB\u5373\u6267\u884C`),this.executeJob(t)):this.scheduleJob(t,s)}}destroy(){for(const[,e]of this.handles)clearTimeout(e);this.handles.clear()}addTimer(e){return this.jobs.push(e),f(this.dc,this.jobs),this.scheduleJob(e,e.delayMs),e}removeTimer(e){const t=this.jobs.findIndex(o=>o.id===e);if(t===-1)return!1;const s=this.jobs[t];s.fired=!0;const i=this.handles.get(e);return i&&(clearTimeout(i),this.handles.delete(e)),f(this.dc,this.jobs),!0}listTimers(e){return this.jobs.filter(t=>t.fired?!1:e?t.conversationId===e:!0)}scheduleJob(e,t){const s=setTimeout(()=>{this.handles.delete(e.id),this.executeJob(e)},t);s.unref?.(),this.handles.set(e.id,s)}async executeJob(e){e.fired=!0,f(this.dc,this.jobs);const t=this.dc.config.conversations.find(i=>i.conversationId===e.conversationId);if(!t){console.log(`[${(0,a.timestamp)()}] Timer \u4EFB\u52A1 ${e.id} \u7684\u4F1A\u8BDD ${e.conversationId} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7`);return}if((0,a.findActiveSession)(this.dc,e.conversationId))console.log(`[${(0,a.timestamp)()}] Timer ${e.id}: \u4F1A\u8BDD\u6D3B\u8DC3\u4E2D\uFF0C\u964D\u7EA7\u5230 task \u961F\u5217`),await(0,$.saveTask)(this.dc,{conversationId:e.conversationId,prompt:this.buildTimerPrompt(e),senderStaffId:e.senderStaffId,senderNickName:e.senderNick,sessionWebhook:(t.dingToken,""),type:"cron"}),await(0,m.sendDingMessage)(this.dc,{conversationId:e.conversationId,sessionWebhook:t.dingToken||"",atUserId:e.senderStaffId,content:`\u23F0 \u5B9A\u65F6\u63D0\u9192\u89E6\u53D1: ${e.description}
|
|
10
|
+
\u5DF2\u52A0\u5165\u4EFB\u52A1\u961F\u5217\uFF0C\u5B8C\u6210\u540E\u901A\u77E5\u4F60`}).catch(()=>{});else{console.log(`[${(0,a.timestamp)()}] Timer ${e.id}: \u65E0\u6D3B\u8DC3\u4F1A\u8BDD\uFF0C\u521B\u5EFA\u65B0 session \u6267\u884C`);const i=Date.now(),o={conversationId:e.conversationId,sessionWebhook:t.dingToken||"",startTime:i,startTimeStr:new Date(i).toISOString().replace(/[:.]/g,"-"),startStaffId:e.senderStaffId,startNickName:e.senderNick};try{await(0,p.executeClaudeQuery)(this.dc,o,this.buildTimerPrompt(e),{senderNick:e.senderNick,senderStaffId:e.senderStaffId,permissionMode:t.permissionMode,conversationConfig:{qaMode:t.qaMode,qaCfg:t.qaCfg}}),console.log(`[${(0,a.timestamp)()}] Timer ${e.id} \u6267\u884C\u5B8C\u6210`)}catch(r){console.error(`[${(0,a.timestamp)()}] Timer ${e.id} \u6267\u884C\u5931\u8D25:`,r),await(0,m.sendDingMessage)(this.dc,{conversationId:e.conversationId,sessionWebhook:t.dingToken||"",atUserId:e.senderStaffId,content:`\u23F0 \u5B9A\u65F6\u63D0\u9192\u89E6\u53D1: ${e.description}
|
|
11
|
+
\u4F46\u6267\u884C\u5931\u8D25: ${r instanceof Error?r.message:String(r)}`}).catch(()=>{})}}}buildTimerPrompt(e){return`[\u7CFB\u7EDF] \u8FD9\u662F\u4E00\u4E2A\u5B9A\u65F6\u63D0\u9192\u901A\u77E5\uFF0C\u4E0D\u662F\u65B0\u7684\u7528\u6237\u6307\u4EE4\u3002
|
|
12
|
+
\u7528\u6237 ${e.senderNick} \u5728 ${e.createdAt} \u8BBE\u7F6E\u4E86 ${d(e.delayMs)} \u540E\u7684\u63D0\u9192\uFF0C\u73B0\u5728\u65F6\u95F4\u5DF2\u5230\u3002
|
|
13
|
+
\u63D0\u9192\u5185\u5BB9: ${e.prompt}
|
|
14
|
+
|
|
15
|
+
\u8BF7\u76F4\u63A5\u7528\u7B80\u77ED\u53CB\u597D\u7684\u65B9\u5F0F\u901A\u77E5\u7528\u6237\u8BE5\u63D0\u9192\u5185\u5BB9\uFF0C\u4E0D\u8981\u521B\u5EFA\u65B0\u7684\u5B9A\u65F6\u4EFB\u52A1\u3001\u65E5\u5386\u4E8B\u4EF6\u6216\u5176\u4ED6\u64CD\u4F5C\u3002`}}exports.TimerEngine=S;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AgentWatchdog=void 0,exports.defaultWatchdogOnTimeout=g,exports.defaultWatchdogOnRecoveryFailed=v;const r=require("./messaging"),a=require("./session"),d=30*1e3,l=2;class u{constructor(t,s,e,i,n){this.dc=t,this.session=s,this.activeSession=e,this.opts=i,this.timer=null,this.settled=!1,this.startTime=n??Date.now()}start(){const s=((this.dc.getConversationConfig(this.session.conversationId)?.maxTurnTimeMins??this.dc.config.maxTurnTimeMins)||5)*60*1e3,e=this.dc.config.maxAutoRecovery??l;this.timer=setInterval(()=>{if(this.settled){this.stop();return}const i=this.activeSession?.lastActivityTime??this.startTime;if(Date.now()-i>=s){this.stop();const c=this.activeSession?.autoRecoveryAttempts??0,h=Math.round(s/1e3);this.activeSession&&c<e?(this.activeSession.autoRecoveryAttempts=c+1,this.activeSession.goonPending=!0,this.activeSession.interrupted=!0,this.opts.killChild(),this.opts.onTimeout(c,e,h)):this.opts.onRecoveryFailed(e)}},d)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}markSettled(){this.settled=!0}get isSettled(){return this.settled}}exports.AgentWatchdog=u;function g(o,t,s,e,i,n){(0,r.sendDingMessage)(o,{conversationId:(0,a.getReplyConversationId)(t),sessionWebhook:(0,a.getReplyWebhook)(t),atUserId:t.startStaffId,content:` ${n} \u8FDB\u7A0B\u8D85\u65F6 (${i}s \u65E0\u6D3B\u52A8)\uFF0C\u81EA\u52A8\u6062\u590D\u4E2D (${s+1}/${e})...`}).catch(()=>{})}function v(o,t,s,e){(0,r.sendDingMessage)(o,{conversationId:(0,a.getReplyConversationId)(t),sessionWebhook:(0,a.getReplyWebhook)(t),atUserId:t.startStaffId,content:`\u23F0 ${e} \u8FDB\u7A0B\u5DF2\u8FDE\u7EED ${s} \u6B21\u8D85\u65F6\u81EA\u52A8\u6062\u590D\u5931\u8D25\uFF0C\u8BF7\u53D1\u9001 /goon \u624B\u52A8\u6062\u590D\u6216 /new \u5F00\u59CB\u65B0\u4F1A\u8BDD`}).catch(()=>{})}
|