jbc-dssi 1.1.95 → 1.1.97
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/index.js +58 -0
- package/lib/schedules.js +339 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -23,6 +23,7 @@ import { watchUiConfig } from './lib/ui-config-push.js';
|
|
|
23
23
|
import { parseUiTuning, formatTuning, resolveRotateConfig } from './lib/ui-tuning.js';
|
|
24
24
|
import { createRestartAutocheck } from './lib/restart-autocheck.js';
|
|
25
25
|
import { createGroupsEventBuffer } from './lib/groups-event-buffer.js';
|
|
26
|
+
import { createScheduleEngine } from './lib/schedules.js';
|
|
26
27
|
|
|
27
28
|
/*
|
|
28
29
|
* ★ 协议层与瘦身层**直接引用 core**,本目录不再保有自己的副本。
|
|
@@ -390,6 +391,20 @@ export function activateRelay(ctx, opts) {
|
|
|
390
391
|
botsMeta,
|
|
391
392
|
dssAgent,
|
|
392
393
|
groups,
|
|
394
|
+
/*
|
|
395
|
+
* ★ 定时任务引擎(2026-11-08 事故根因):这里少一行,中继路径就整条哑掉。
|
|
396
|
+
*
|
|
397
|
+
* ensureConnection() 建业务通道时要把 capabilities 全量交给 BridgeConnection,
|
|
398
|
+
* 其中包含 `schedules`。它引用的是**本函数作用域**里的名字 —— 漏解构就是
|
|
399
|
+
* `ReferenceError: schedules is not defined`,而 onAdmitted 回调把这个异常
|
|
400
|
+
* "已兜住"吞掉,于是:设备准入通过、中继连接正常、**业务通道永远不建**,
|
|
401
|
+
* 手机侧表现为"连上了但智能体列表一直连接中"(HELLO/SESSIONS 一帧都没有)。
|
|
402
|
+
*
|
|
403
|
+
* 直连路径(activate 里的 onConnection)直接闭包了同一个变量,所以只有
|
|
404
|
+
* 中继路径坏 —— 这正是"DSH 重启后手机才坏"的原因:重启把插件换成了带
|
|
405
|
+
* schedules 的版本,准入一通过就撞上这个 ReferenceError。
|
|
406
|
+
*/
|
|
407
|
+
schedules,
|
|
393
408
|
log,
|
|
394
409
|
onChannelReady,
|
|
395
410
|
onChannelClosed,
|
|
@@ -561,6 +576,7 @@ export function activateRelay(ctx, opts) {
|
|
|
561
576
|
botsMeta,
|
|
562
577
|
dssAgent,
|
|
563
578
|
groups,
|
|
579
|
+
schedules,
|
|
564
580
|
log,
|
|
565
581
|
});
|
|
566
582
|
log('业务通路已就绪');
|
|
@@ -1111,6 +1127,28 @@ function activate(ctx, config) {
|
|
|
1111
1127
|
} else {
|
|
1112
1128
|
log('[dssAgent] 智能体能力未启用(模块缺失或配置关闭)');
|
|
1113
1129
|
}
|
|
1130
|
+
/*
|
|
1131
|
+
* 定时任务(2026-11-08 老谢定):任务落在 DSH Host 自带的 `schedule` 服务里,
|
|
1132
|
+
* 这里只做手机侧的增删改查。挂在 dssAgent 上(要用它建"定时任务专用会话"),
|
|
1133
|
+
* dssAgent 没启用时整个能力关闭、命令明确报错。
|
|
1134
|
+
*/
|
|
1135
|
+
let schedules = null;
|
|
1136
|
+
if (dssAgent && config.schedules?.enabled !== false) {
|
|
1137
|
+
try {
|
|
1138
|
+
schedules = createScheduleEngine({
|
|
1139
|
+
ctx,
|
|
1140
|
+
dssAgent,
|
|
1141
|
+
log,
|
|
1142
|
+
file: typeof config.schedules?.file === 'string' ? config.schedules.file : undefined,
|
|
1143
|
+
});
|
|
1144
|
+
log('[schedules] 定时任务能力已启用(DSS_AGENT_CMD: schedule_*)');
|
|
1145
|
+
} catch (err) {
|
|
1146
|
+
log(`[schedules] 初始化失败:${err?.message ?? err}`);
|
|
1147
|
+
schedules = null;
|
|
1148
|
+
}
|
|
1149
|
+
} else {
|
|
1150
|
+
log('[schedules] 定时任务能力未启用(dssAgent 未启用或配置关闭)');
|
|
1151
|
+
}
|
|
1114
1152
|
// 插件卸载:退订 session/event、清掉 500ms 合并定时器(否则会往死连接写帧)
|
|
1115
1153
|
if (typeof ctx.effect === 'function') ctx.effect(() => () => dssAgent?.dispose?.());
|
|
1116
1154
|
|
|
@@ -1228,6 +1266,7 @@ function activate(ctx, config) {
|
|
|
1228
1266
|
botsMeta,
|
|
1229
1267
|
dssAgent,
|
|
1230
1268
|
groups,
|
|
1269
|
+
schedules,
|
|
1231
1270
|
log,
|
|
1232
1271
|
});
|
|
1233
1272
|
} catch (err) {
|
|
@@ -1318,6 +1357,7 @@ function activate(ctx, config) {
|
|
|
1318
1357
|
botsMeta,
|
|
1319
1358
|
dssAgent,
|
|
1320
1359
|
groups,
|
|
1360
|
+
schedules,
|
|
1321
1361
|
deviceAuthFile,
|
|
1322
1362
|
log,
|
|
1323
1363
|
// 中继业务通道的登记/摘除回调(界面配置推送要靠它拿到通道)
|
|
@@ -1729,6 +1769,7 @@ class BridgeConnection {
|
|
|
1729
1769
|
this.teamMemberSessions = new Set();
|
|
1730
1770
|
this.botsMeta = opts.botsMeta ?? null;
|
|
1731
1771
|
this.dssAgent = opts.dssAgent ?? null;
|
|
1772
|
+
this.schedules = opts.schedules ?? null;
|
|
1732
1773
|
/** 群聊能力(GROUPS_* / ROOM_SNAPSHOT 帧);随群模块/配置开关启用。 */
|
|
1733
1774
|
this.groups = opts.groups ?? null;
|
|
1734
1775
|
this.botsSeq = 0;
|
|
@@ -2259,6 +2300,23 @@ class BridgeConnection {
|
|
|
2259
2300
|
this.fail('dssAgent 命令缺少 op');
|
|
2260
2301
|
return;
|
|
2261
2302
|
}
|
|
2303
|
+
/*
|
|
2304
|
+
* 定时任务(2026-11-08):复用 DSS_AGENT_CMD 帧、以 `schedule_` 前缀路由到
|
|
2305
|
+
* schedules 引擎(它再调 DSH Host 的 schedule 服务),不新增帧类型。
|
|
2306
|
+
*/
|
|
2307
|
+
if (op.startsWith('schedule_')) {
|
|
2308
|
+
if (!this.schedules) {
|
|
2309
|
+
this.fail('定时任务能力未启用(电脑侧 DSH 未提供调度服务,或插件已关闭该能力)');
|
|
2310
|
+
return;
|
|
2311
|
+
}
|
|
2312
|
+
try {
|
|
2313
|
+
const result = await this.schedules.command(op, payload);
|
|
2314
|
+
this.send(FRAME.DSS_AGENT_EVENT, { type: 'ack', op, ...(result ?? {}) });
|
|
2315
|
+
} catch (err) {
|
|
2316
|
+
this.fail(`定时任务操作失败:${err?.message ?? err}`);
|
|
2317
|
+
}
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2262
2320
|
try {
|
|
2263
2321
|
const result = await this.dssAgent.command(op, payload);
|
|
2264
2322
|
this.send(FRAME.DSS_AGENT_EVENT, { type: 'ack', op, ...(result ?? {}) });
|
package/lib/schedules.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `jbc-dssi/lib/schedules.js` —— 智能体「定时任务」(2026-11-08 老谢定)。
|
|
3
|
+
*
|
|
4
|
+
* 设计口径(对齐时已确认):
|
|
5
|
+
* · **不新造调度器**:任务全部落在 DSH Host 自带的 `schedule` 服务里
|
|
6
|
+
* (持久化、到点投递、投递历史都由它负责),插件只做"手机能用的那层增删改查"。
|
|
7
|
+
* · **任务绑在智能体的一个专用会话上**:每个智能体自动建一个会话做它的
|
|
8
|
+
* 「定时任务」会话(第一次建任务时创建),到点提醒与智能体的回答都落在那里,
|
|
9
|
+
* 不往用户的主对话里插队。会话 id 记在 `~/.dsh/jbc-dssi/schedules.json`。
|
|
10
|
+
* · **手机零计算**:频率文案、下次运行时间等都在电脑侧算好下发(L0 铁律)。
|
|
11
|
+
* · 与 DSH 的 `schedule` 服务一一对应:手机看到的列表就是 Host 里的任务,
|
|
12
|
+
* 不额外存一份任务副本(避免两份数据源)。
|
|
13
|
+
*
|
|
14
|
+
* 已知边界(与 DSH 调度器能力对齐,不假装支持):
|
|
15
|
+
* · 调度器没有"暂停/启用"语义 → 列表里只提供删除;想停就删(对齐时已说明)。
|
|
16
|
+
* · 电脑/插件离线时到点算错过,调度器按自己的规则跳过,不补跑。
|
|
17
|
+
*/
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import { join, dirname } from 'node:path';
|
|
20
|
+
import { homedir } from 'node:os';
|
|
21
|
+
|
|
22
|
+
/** 每个智能体的任务数上限(对齐时定的默认值)。 */
|
|
23
|
+
const MAX_TASKS = 50;
|
|
24
|
+
/** 任务名上限(DSH 自己也是 120)。 */
|
|
25
|
+
const MAX_TITLE = 120;
|
|
26
|
+
/** 提示词上限(对齐时定的默认值)。 */
|
|
27
|
+
const MAX_PROMPT = 2000;
|
|
28
|
+
|
|
29
|
+
/** 四种频率(对齐时定的四档;cron 不暴露给手机)。 */
|
|
30
|
+
const KINDS = new Set(['once', 'every', 'daily', 'weekly']);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 造「定时任务」引擎。
|
|
34
|
+
*
|
|
35
|
+
* @param {object} deps
|
|
36
|
+
* @param {object} deps.ctx cordis 上下文(取 schedule / sessionController 服务)
|
|
37
|
+
* @param {object} deps.dssAgent dssAgent 引擎(只用它的 create_session 命令)
|
|
38
|
+
* @param {(line:string)=>void} [deps.log]
|
|
39
|
+
* @param {string} [deps.file] 会话映射文件(默认 ~/.dsh/jbc-dssi/schedules.json)
|
|
40
|
+
*/
|
|
41
|
+
export function createScheduleEngine({ ctx, dssAgent, log = () => {}, file = null }) {
|
|
42
|
+
const target = file || join(homedir(), '.dsh', 'jbc-dssi', 'schedules.json');
|
|
43
|
+
/** entityId -> 定时任务会话 id(这是唯一一份"哪个会话属于哪个智能体"的记录)。 */
|
|
44
|
+
let state = { v: 1, agents: {} };
|
|
45
|
+
try {
|
|
46
|
+
if (fs.existsSync(target)) {
|
|
47
|
+
const parsed = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
48
|
+
if (parsed && typeof parsed === 'object' && parsed.agents && typeof parsed.agents === 'object') {
|
|
49
|
+
state = { v: 1, agents: { ...parsed.agents } };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
} catch (err) {
|
|
53
|
+
log(`[schedules] 读取会话映射失败(回退空表):${err?.message ?? err}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 串行写盘:同一时刻只可能有一个写,写失败只记日志(绝不因此让命令报错)。 */
|
|
57
|
+
let saveChain = Promise.resolve();
|
|
58
|
+
function save() {
|
|
59
|
+
saveChain = saveChain
|
|
60
|
+
.then(async () => {
|
|
61
|
+
await fs.promises.mkdir(dirname(target), { recursive: true });
|
|
62
|
+
const tmp = `${target}.tmp`;
|
|
63
|
+
await fs.promises.writeFile(tmp, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
|
|
64
|
+
await fs.promises.rename(tmp, target);
|
|
65
|
+
})
|
|
66
|
+
.catch((err) => log(`[schedules] 保存会话映射失败(已忽略):${err?.message ?? err}`));
|
|
67
|
+
return saveChain;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 取 DSH 的调度服务(没装/没启用 → null,调用方明确报"能力未启用")。 */
|
|
71
|
+
function service() {
|
|
72
|
+
const svc = (typeof ctx.get === 'function' ? ctx.get('schedule') : null) ?? ctx.schedule ?? null;
|
|
73
|
+
return svc && typeof svc.create === 'function' ? svc : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 会话控制器(用于确认映射的会话还在;拿不到就当还在,避免每次列表都新建)。 */
|
|
77
|
+
function sessionController() {
|
|
78
|
+
return (typeof ctx.get === 'function' ? ctx.get('sessionController') : null) ?? ctx.sessionController ?? null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 智能体 → 定时任务会话。
|
|
83
|
+
*
|
|
84
|
+
* 已有映射且会话还在 → 直接复用(**绝不在列表时建会话**);
|
|
85
|
+
* 没有/已失效 → 用 dssAgent 的 create_session 建一个(只在"建任务"时发生)。
|
|
86
|
+
*/
|
|
87
|
+
async function ensureSession(entityId, { create = false } = {}) {
|
|
88
|
+
const known = state.agents[entityId];
|
|
89
|
+
if (known) {
|
|
90
|
+
const sc = sessionController();
|
|
91
|
+
if (sc && typeof sc.list === 'function') {
|
|
92
|
+
try {
|
|
93
|
+
const list = await sc.list();
|
|
94
|
+
if (!Array.isArray(list) || list.some((row) => (row?.sessionId ?? row?.id ?? row) === known)) {
|
|
95
|
+
return known;
|
|
96
|
+
}
|
|
97
|
+
} catch (err) {
|
|
98
|
+
log(`[schedules] 校验会话失败(当作仍有效):${err?.message ?? err}`);
|
|
99
|
+
return known;
|
|
100
|
+
}
|
|
101
|
+
} else {
|
|
102
|
+
return known;
|
|
103
|
+
}
|
|
104
|
+
delete state.agents[entityId];
|
|
105
|
+
void save();
|
|
106
|
+
}
|
|
107
|
+
if (!create) return null;
|
|
108
|
+
if (!dssAgent || typeof dssAgent.command !== 'function') throw new Error('智能体能力未启用');
|
|
109
|
+
const created = await dssAgent.command('create_session', { entityId });
|
|
110
|
+
const sessionId = created?.sessionId;
|
|
111
|
+
if (typeof sessionId !== 'string' || sessionId === '') throw new Error('创建定时任务会话失败');
|
|
112
|
+
state.agents[entityId] = sessionId;
|
|
113
|
+
await save();
|
|
114
|
+
return sessionId;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 取实体 id:手机必带 entityId;兼容 entity.id。 */
|
|
118
|
+
function entityIdOf(payload) {
|
|
119
|
+
const raw = payload?.entityId ?? payload?.id;
|
|
120
|
+
const id = typeof raw === 'string' ? raw.trim() : '';
|
|
121
|
+
if (id === '') throw new Error('缺少智能体 id');
|
|
122
|
+
return id;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 任务名/提示词校验(与 DSH 自己的上限一致,超了明确报错而不是悄悄截断)。 */
|
|
126
|
+
function normalizeText(payload) {
|
|
127
|
+
const title = String(payload?.title ?? '').trim();
|
|
128
|
+
const prompt = String(payload?.prompt ?? '').trim();
|
|
129
|
+
if (title === '') throw new Error('任务名不能为空');
|
|
130
|
+
if (Array.from(title).length > MAX_TITLE) throw new Error(`任务名最多 ${MAX_TITLE} 字`);
|
|
131
|
+
if (prompt === '') throw new Error('要它做什么不能为空');
|
|
132
|
+
if (Array.from(prompt).length > MAX_PROMPT) throw new Error(`提示词最多 ${MAX_PROMPT} 字`);
|
|
133
|
+
return { title, prompt };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 频率(手机传扁平结构,这里换成 DSH 的 selector)。 */
|
|
137
|
+
function normalizeRule(payload) {
|
|
138
|
+
const kind = String(payload?.kind ?? '').trim();
|
|
139
|
+
if (!KINDS.has(kind)) throw new Error('频率类型不支持(只支持一次/每隔 N 小时/每天/每周)');
|
|
140
|
+
if (kind === 'once') {
|
|
141
|
+
const date = String(payload?.date ?? '').trim();
|
|
142
|
+
const time = String(payload?.time ?? '').trim();
|
|
143
|
+
if (!/^\d{4}-\d{2}-\d{2}$/u.test(date)) throw new Error('一次性任务的日期格式应为 YYYY-MM-DD');
|
|
144
|
+
if (!/^\d{2}:\d{2}(:\d{2})?$/u.test(time)) throw new Error('时间格式应为 HH:mm');
|
|
145
|
+
return { kind, date, time: withSeconds(time), timeZone: zoneOf(payload) };
|
|
146
|
+
}
|
|
147
|
+
if (kind === 'every') {
|
|
148
|
+
const hours = Number(payload?.everyHours);
|
|
149
|
+
if (!Number.isFinite(hours) || hours <= 0) throw new Error('间隔小时数必须大于 0');
|
|
150
|
+
const seconds = Math.round(hours * 3600);
|
|
151
|
+
if (seconds < 60) throw new Error('间隔不能小于 1 分钟');
|
|
152
|
+
return { kind, everySeconds: seconds };
|
|
153
|
+
}
|
|
154
|
+
if (kind === 'daily') {
|
|
155
|
+
return { kind, time: timeOf(payload), timeZone: zoneOf(payload) };
|
|
156
|
+
}
|
|
157
|
+
// weekly
|
|
158
|
+
const rawWeekdays = Array.isArray(payload?.weekdays) ? payload.weekdays : [];
|
|
159
|
+
const weekdays = [...new Set(rawWeekdays.map((n) => Number(n)).filter((n) => Number.isInteger(n) && n >= 1 && n <= 7))].sort(
|
|
160
|
+
(a, b) => a - b,
|
|
161
|
+
);
|
|
162
|
+
if (weekdays.length === 0) throw new Error('每周任务至少要选一天');
|
|
163
|
+
return { kind, time: timeOf(payload), timeZone: zoneOf(payload), weekdays };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function zoneOf(payload) {
|
|
167
|
+
const zone = String(payload?.timeZone ?? '').trim();
|
|
168
|
+
if (zone === '') throw new Error('缺少时区');
|
|
169
|
+
return zone;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function timeOf(payload) {
|
|
173
|
+
const time = String(payload?.time ?? '').trim();
|
|
174
|
+
if (!/^\d{2}:\d{2}(:\d{2})?$/u.test(time)) throw new Error('时间格式应为 HH:mm');
|
|
175
|
+
return withSeconds(time);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function withSeconds(time) {
|
|
179
|
+
return time.length === 5 ? `${time}:00` : time;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 手机侧频率 -> DSH `schedule_create` 请求体。 */
|
|
183
|
+
function createRequest(rule, text) {
|
|
184
|
+
const base = { title: text.title, prompt: text.prompt };
|
|
185
|
+
switch (rule.kind) {
|
|
186
|
+
case 'once':
|
|
187
|
+
return { ...base, at: { date: rule.date, time: rule.time, time_zone: rule.timeZone } };
|
|
188
|
+
case 'every':
|
|
189
|
+
return { ...base, every_seconds: rule.everySeconds };
|
|
190
|
+
case 'daily':
|
|
191
|
+
return { ...base, daily: { time: rule.time, time_zone: rule.timeZone } };
|
|
192
|
+
default:
|
|
193
|
+
return { ...base, weekly: { time: rule.time, time_zone: rule.timeZone, weekdays: rule.weekdays } };
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** 手机侧频率 -> DSH `schedule_update` 的 timing change。 */
|
|
198
|
+
function timingChange(rule) {
|
|
199
|
+
switch (rule.kind) {
|
|
200
|
+
case 'once':
|
|
201
|
+
return { kind: 'at', at: { date: rule.date, time: rule.time, time_zone: rule.timeZone } };
|
|
202
|
+
case 'every':
|
|
203
|
+
return { kind: 'every', every_seconds: rule.everySeconds };
|
|
204
|
+
case 'daily':
|
|
205
|
+
return { kind: 'daily', daily: { time: rule.time, time_zone: rule.timeZone } };
|
|
206
|
+
default:
|
|
207
|
+
return { kind: 'weekly', weekly: { time: rule.time, time_zone: rule.timeZone, weekdays: rule.weekdays } };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 频率文案(电脑侧算好,手机直接显示)。
|
|
213
|
+
*
|
|
214
|
+
* 例:`每天 09:00`、`每周一、三 20:30`、`每隔 2 小时`、`2026-11-09 07:00`。
|
|
215
|
+
* 一次性任务用**本地日期时间**显示,不做"还剩多久"这种会过期的话术。
|
|
216
|
+
*/
|
|
217
|
+
function describe(record) {
|
|
218
|
+
const clock = typeof record?.time === 'string' ? record.time.slice(0, 5) : '';
|
|
219
|
+
switch (record?.kind) {
|
|
220
|
+
case 'daily':
|
|
221
|
+
return `每天 ${clock}`;
|
|
222
|
+
case 'weekly': {
|
|
223
|
+
const names = ['一', '二', '三', '四', '五', '六', '日'];
|
|
224
|
+
const days = (record.weekdays ?? []).map((n) => names[n - 1] ?? '').filter(Boolean).join('、');
|
|
225
|
+
return `每周${days} ${clock}`;
|
|
226
|
+
}
|
|
227
|
+
case 'every': {
|
|
228
|
+
const seconds = Number(record.everySeconds) || 0;
|
|
229
|
+
if (seconds % 3600 === 0) return `每隔 ${seconds / 3600} 小时`;
|
|
230
|
+
if (seconds % 60 === 0) return `每隔 ${seconds / 60} 分钟`;
|
|
231
|
+
return `每隔 ${seconds} 秒`;
|
|
232
|
+
}
|
|
233
|
+
default: {
|
|
234
|
+
const at = typeof record?.scheduledAt === 'string' ? record.scheduledAt : '';
|
|
235
|
+
return at === '' ? '一次性' : `一次 · ${at.slice(0, 16).replace('T', ' ')}`;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 把 DSH 的 record 变成手机要的形状(字段名保持和 Host 一致,少一层翻译)。 */
|
|
241
|
+
function viewOf(record) {
|
|
242
|
+
return {
|
|
243
|
+
id: String(record?.id ?? ''),
|
|
244
|
+
title: String(record?.title ?? ''),
|
|
245
|
+
prompt: String(record?.prompt ?? ''),
|
|
246
|
+
kind: String(record?.kind ?? ''),
|
|
247
|
+
describe: describe(record),
|
|
248
|
+
scheduledAt: String(record?.scheduledAt ?? ''),
|
|
249
|
+
// 下次运行时刻(毫秒);解析失败给 0,手机侧就不显示,绝不瞎编
|
|
250
|
+
nextAtMs: Number.isFinite(Date.parse(record?.scheduledAt)) ? Date.parse(record.scheduledAt) : 0,
|
|
251
|
+
state: record?.state === 'overdue' ? 'overdue' : 'scheduled',
|
|
252
|
+
time: typeof record?.time === 'string' ? record.time : '',
|
|
253
|
+
timeZone: typeof record?.timeZone === 'string' ? record.timeZone : '',
|
|
254
|
+
weekdays: Array.isArray(record?.weekdays) ? record.weekdays : [],
|
|
255
|
+
everySeconds: Number(record?.everySeconds) || 0,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function listRecords(entityId) {
|
|
260
|
+
const svc = service();
|
|
261
|
+
if (!svc) throw new Error('定时任务能力未启用(电脑侧 DSH 未提供调度服务)');
|
|
262
|
+
const sessionId = await ensureSession(entityId);
|
|
263
|
+
if (!sessionId) return [];
|
|
264
|
+
const records = await svc.list({ sessionId });
|
|
265
|
+
return Array.isArray(records) ? records : [];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 命令入口(插件 `#dssAgentCommand` 里以 `schedule_` 前缀转发过来)。 */
|
|
269
|
+
async function command(op, payload = {}) {
|
|
270
|
+
const svc = service();
|
|
271
|
+
if (!svc) throw new Error('定时任务能力未启用(电脑侧 DSH 未提供调度服务)');
|
|
272
|
+
|
|
273
|
+
if (op === 'schedule_list') {
|
|
274
|
+
const entityId = entityIdOf(payload);
|
|
275
|
+
const records = await listRecords(entityId);
|
|
276
|
+
return {
|
|
277
|
+
entityId,
|
|
278
|
+
sessionId: state.agents[entityId] ?? '',
|
|
279
|
+
schedules: records.map(viewOf),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (op === 'schedule_create') {
|
|
284
|
+
const entityId = entityIdOf(payload);
|
|
285
|
+
const text = normalizeText(payload);
|
|
286
|
+
const rule = normalizeRule(payload);
|
|
287
|
+
const existing = await listRecords(entityId);
|
|
288
|
+
if (existing.length >= MAX_TASKS) throw new Error(`每个智能体最多 ${MAX_TASKS} 个定时任务`);
|
|
289
|
+
const sessionId = await ensureSession(entityId, { create: true });
|
|
290
|
+
const record = await svc.create(sessionId, createRequest(rule, text));
|
|
291
|
+
log(`[schedules] 新建定时任务「${text.title}」(${describe(record)})`);
|
|
292
|
+
return { entityId, sessionId, schedule: viewOf(record) };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (op === 'schedule_update') {
|
|
296
|
+
const entityId = entityIdOf(payload);
|
|
297
|
+
const id = String(payload?.scheduleId ?? '').trim();
|
|
298
|
+
if (id === '') throw new Error('缺少任务 id');
|
|
299
|
+
const text = payload?.title !== undefined || payload?.prompt !== undefined
|
|
300
|
+
? normalizeText({ title: payload?.title, prompt: payload?.prompt })
|
|
301
|
+
: {};
|
|
302
|
+
const rule = payload?.kind !== undefined ? normalizeRule(payload) : null;
|
|
303
|
+
const sessionId = await ensureSession(entityId);
|
|
304
|
+
if (!sessionId) throw new Error('定时任务不存在');
|
|
305
|
+
const records = await listRecords(entityId);
|
|
306
|
+
const expected = records.find((row) => String(row?.id) === id);
|
|
307
|
+
if (!expected) throw new Error('定时任务不存在');
|
|
308
|
+
const result = await svc.update({
|
|
309
|
+
sessionId,
|
|
310
|
+
id,
|
|
311
|
+
expected,
|
|
312
|
+
...(text.title !== undefined ? { title: text.title } : {}),
|
|
313
|
+
...(text.prompt !== undefined ? { prompt: text.prompt } : {}),
|
|
314
|
+
...(rule !== null ? { change: timingChange(rule) } : {}),
|
|
315
|
+
});
|
|
316
|
+
if (!result || result.updated !== true) {
|
|
317
|
+
throw new Error(result?.code === 'schedule_ended' ? '任务已经结束,无法修改' : '任务已被别处修改,请刷新后再试');
|
|
318
|
+
}
|
|
319
|
+
log(`[schedules] 修改定时任务「${result.record?.title ?? id}」`);
|
|
320
|
+
return { entityId, sessionId, schedule: viewOf(result.record ?? expected) };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (op === 'schedule_delete') {
|
|
324
|
+
const entityId = entityIdOf(payload);
|
|
325
|
+
const id = String(payload?.scheduleId ?? '').trim();
|
|
326
|
+
if (id === '') throw new Error('缺少任务 id');
|
|
327
|
+
const sessionId = await ensureSession(entityId);
|
|
328
|
+
if (!sessionId) throw new Error('定时任务不存在');
|
|
329
|
+
const result = await svc.delete({ sessionId, id });
|
|
330
|
+
if (!result || result.deleted !== true) throw new Error('定时任务不存在');
|
|
331
|
+
log(`[schedules] 删除定时任务 ${id}`);
|
|
332
|
+
return { entityId, sessionId, scheduleId: id };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
throw new Error(`未知的定时任务命令:${op}`);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
return { command };
|
|
339
|
+
}
|