pi-web-ui 0.87.1 → 0.88.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.
@@ -17,8 +17,8 @@
17
17
  */
18
18
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
19
19
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
20
- import { readFile as fspReadFile, readdir as fspReaddir, rm as fspRm, mkdir as fspMkdir, writeFile as fspWriteFile, } from "node:fs/promises";
21
- import { dirname, join, resolve } from "node:path";
20
+ import { readFile as fspReadFile, readdir as fspReaddir, rm as fspRm, mkdir as fspMkdir, writeFile as fspWriteFile, appendFile as fspAppendFile, stat as fspStat, } from "node:fs/promises";
21
+ import { dirname, join, relative, resolve } from "node:path";
22
22
  import { createRequire } from "node:module";
23
23
  import { spawnSync } from "node:child_process";
24
24
  /** tmp+rename 原子写(错误由调用方隔离——插件设施的 IO 一律尽力而为)。 */
@@ -140,9 +140,19 @@ export class PluginSecrets {
140
140
  }
141
141
  return k;
142
142
  }
143
+ /** 同一密文文件的跨实例共享缓存(按绝对路径):设置面板的保存与插件运行时的
144
+ * 读取走的是两个实例(savePluginSettings 现场 new,host 闭包里一个),实例级缓存
145
+ * 会让“刚保存完立刻 getSettings”读到旧值。共享后同进程内永远一致;文件被删
146
+ * (卸载插件)时重置,避免重装同 id 读到旧机密。 */
147
+ static shared = new Map();
143
148
  load() {
144
149
  if (this.store)
145
150
  return this.store;
151
+ const hit = PluginSecrets.shared.get(this.file);
152
+ if (hit && existsSync(this.file)) {
153
+ this.store = hit;
154
+ return hit;
155
+ }
146
156
  try {
147
157
  const parsed = JSON.parse(readFileSync(this.file, "utf8"));
148
158
  this.store =
@@ -151,6 +161,7 @@ export class PluginSecrets {
151
161
  catch {
152
162
  this.store = { v: 1, items: {} };
153
163
  }
164
+ PluginSecrets.shared.set(this.file, this.store);
154
165
  return this.store;
155
166
  }
156
167
  set(name, value) {
@@ -268,6 +279,43 @@ export function ensurePluginDeps(pluginDir, specs, onProgress) {
268
279
  depInstallLocks.set(lockKey, p);
269
280
  return p;
270
281
  }
282
+ /** 深度/条数护栏:glob 递归遍历与结果都封顶,防大仓库扫爆内存。 */
283
+ const GLOB_MAX_WALK = 2000;
284
+ const GLOB_MAX_RESULTS = 500;
285
+ /** 极简 glob 转 RegExp:只支持 `*`(单段任意)/`?`(单字符)/`**`(跨段任意)。
286
+ * 纯函数,单测覆盖。 */
287
+ export function globToRegExp(pattern) {
288
+ const src = String(pattern ?? "")
289
+ .trim()
290
+ .replace(/\\/g, "/");
291
+ let re = "";
292
+ for (let i = 0; i < src.length; i++) {
293
+ const c = src[i];
294
+ if (c === "*") {
295
+ if (src[i + 1] === "*") {
296
+ // `**`:跨段;`/**/` 整体可省(根下也命中)。
297
+ if (src[i + 2] === "/") {
298
+ re += "(?:.*/)?";
299
+ i += 2;
300
+ }
301
+ else {
302
+ re += ".*";
303
+ i += 1;
304
+ }
305
+ }
306
+ else {
307
+ re += "[^/]*";
308
+ }
309
+ }
310
+ else if (c === "?") {
311
+ re += "[^/]";
312
+ }
313
+ else {
314
+ re += c.replace(/[.+^${}()|[\]\\]/, (m) => `\\${m}`);
315
+ }
316
+ }
317
+ return new RegExp(`^${re}$`);
318
+ }
271
319
  export class WorkspaceFS {
272
320
  root;
273
321
  /** root 是活值 getter(返回当前工作区绝对路径),跟随 set_cwd。 */
@@ -311,6 +359,71 @@ export class WorkspaceFS {
311
359
  await fspMkdir(dirname(target), { recursive: true });
312
360
  await fspWriteFile(target, data);
313
361
  }
362
+ /** 追加写文件(日志/队列场景;父目录自动补;越界拒绝与 write 同口径)。 */
363
+ async append(relPath, data) {
364
+ const target = this.abs(relPath);
365
+ await fspMkdir(dirname(target), { recursive: true });
366
+ await fspAppendFile(target, data);
367
+ }
368
+ /** 建目录(递归;已存在幂等成功;越界拒绝与 write 同口径)。 */
369
+ async mkdir(relDir) {
370
+ await fspMkdir(this.abs(relDir), { recursive: true });
371
+ }
372
+ /** 文件元信息(size/mtime 供同步/缓存判断;不存在抛错)。 */
373
+ async stat(relPath) {
374
+ const target = this.abs(relPath);
375
+ const st = await fspStat(target);
376
+ const base = target
377
+ .replace(/[/\\]+$/, "")
378
+ .split("/")
379
+ .pop() ?? String(relPath);
380
+ return {
381
+ name: base,
382
+ type: st.isDirectory() ? "dir" : "file",
383
+ size: st.isDirectory() ? 0 : st.size,
384
+ mtime: Number(st.mtimeMs) || 0,
385
+ };
386
+ }
387
+ /** 极简 glob 搜索(星号匹配如 `*.json`、双星匹配如 `foo/bar.md` 的父目录任意层):
388
+ * 相对路径(`/` 分隔)按 pattern 过滤。walk 与结果双封顶,目录本身也参与
389
+ * 匹配(`docs*` 能命中目录)。只返回相对路径字符串,调用方再 read/stat。 */
390
+ async glob(pattern, relDir = "") {
391
+ const pat = String(pattern ?? "")
392
+ .trim()
393
+ .replace(/\\/g, "/");
394
+ if (!pat)
395
+ throw new Error("glob: pattern 为空");
396
+ const re = globToRegExp(pat);
397
+ const base = this.abs(relDir);
398
+ const out = [];
399
+ const stack = [base];
400
+ let walked = 0;
401
+ while (stack.length && walked < GLOB_MAX_WALK && out.length < GLOB_MAX_RESULTS) {
402
+ const dir = stack.pop();
403
+ let ents;
404
+ try {
405
+ ents = await fspReaddir(dir, { withFileTypes: true });
406
+ }
407
+ catch {
408
+ continue; // 无权限/中途删除:跳过该分支,不整单失败
409
+ }
410
+ for (const e of ents) {
411
+ if (walked++ >= GLOB_MAX_WALK || out.length >= GLOB_MAX_RESULTS)
412
+ break;
413
+ const abs = join(dir, e.name);
414
+ const rel = relative(base, abs).replace(/\\/g, "/");
415
+ if (e.isDirectory()) {
416
+ if (re.test(rel) || re.test(`${rel}/`))
417
+ out.push(rel);
418
+ stack.push(abs);
419
+ }
420
+ else if (re.test(rel)) {
421
+ out.push(rel);
422
+ }
423
+ }
424
+ }
425
+ return out;
426
+ }
314
427
  /** 删除文件/目录(递归;只允许删工作区内的路径)。 */
315
428
  async remove(relPath) {
316
429
  await fspRm(this.abs(relPath), { recursive: true, force: false });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 插件直调模型(host.llm.complete 的底层):一次性的孤立无工具会话。
3
+ *
4
+ * 与审查循环的 reviewer 同一条 SDK 链路(createAgentSessionServices +
5
+ * ModelRuntime.create + createAgentSessionFromServices + prompt +
6
+ * getLastAssistantText + dispose),区别:
7
+ * - `noTools: true` + skills 全剥:纯补全,无副作用、可预测花费;
8
+ * - 调用方(agent-service.completeForPlugins)只给 cwd/agentDir/回落模型,
9
+ * 并发与预算门在本文件内收敛。
10
+ *
11
+ * 约束(fail-closed,一律结构化返回、绝不抛错):
12
+ * - 输入封顶:prompt ≤ 8000 字、system ≤ 4000 字;
13
+ * - 输出截断:maxChars 缺省 8000、上限 32000;
14
+ * - 超时:缺省 90s、范围 5s–5min,超时即 dispose 掉会话;
15
+ * - 并发:全局最多 4 路在飞,超了直接回 {ok:false}(插件侧重试,不排队——
16
+ * 排队会把插件的 await 变成不定等待,调用方超时兜底更难写)。
17
+ */
18
+ import { join } from "node:path";
19
+ import { createAgentSessionFromServices, createAgentSessionServices, ModelRuntime, SessionManager, } from "@earendil-works/pi-coding-agent";
20
+ import { parseModelSpec } from "./attachments.js";
21
+ const MAX_PROMPT_CHARS = 8000;
22
+ const MAX_SYSTEM_CHARS = 4000;
23
+ const DEFAULT_MAX_CHARS = 8000;
24
+ const MAX_MAX_CHARS = 32000;
25
+ const DEFAULT_TIMEOUT_MS = 90_000;
26
+ const MIN_TIMEOUT_MS = 5_000;
27
+ const MAX_TIMEOUT_MS = 300_000;
28
+ const MAX_INFLIGHT = 4;
29
+ let inflight = 0;
30
+ /** 当前在飞的孤立调用数(单测/诊断用)。 */
31
+ export function llmInflight() {
32
+ return inflight;
33
+ }
34
+ function fail(error) {
35
+ return { ok: false, error };
36
+ }
37
+ export async function completeWithIsolatedSession(env, req) {
38
+ const prompt = String(req?.prompt ?? "");
39
+ if (!prompt.trim())
40
+ return fail("llm.complete: prompt 为空");
41
+ if (prompt.length > MAX_PROMPT_CHARS)
42
+ return fail(`llm.complete: prompt 超长(${prompt.length} > ${MAX_PROMPT_CHARS} 字),请裁剪后重发`);
43
+ const system = String(req?.system ?? "");
44
+ if (system.length > MAX_SYSTEM_CHARS)
45
+ return fail(`llm.complete: system 超长(${system.length} > ${MAX_SYSTEM_CHARS} 字),请裁剪后重发`);
46
+ if (inflight >= MAX_INFLIGHT)
47
+ return fail(`llm.complete: 并发已满(${MAX_INFLIGHT} 路在飞),请稍后重试`);
48
+ const maxChars = Math.min(Math.max(Number(req?.maxChars ?? DEFAULT_MAX_CHARS) || DEFAULT_MAX_CHARS, 1), MAX_MAX_CHARS);
49
+ const timeoutMs = Math.min(Math.max(Number(req?.timeoutMs ?? DEFAULT_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);
50
+ inflight += 1;
51
+ try {
52
+ const run = (async () => {
53
+ let dispose;
54
+ try {
55
+ const services = await createAgentSessionServices({
56
+ cwd: env.cwd,
57
+ agentDir: env.agentDir,
58
+ // 技能全剥:纯补全不需要技能上下文(省 token,结果可预测)。
59
+ resourceLoaderOptions: {
60
+ skillsOverride: (res) => ({ ...res, skills: [] }),
61
+ },
62
+ modelRuntime: await ModelRuntime.create({
63
+ authPath: join(env.agentDir, "auth.json"),
64
+ modelsPath: join(env.agentDir, "models.json"),
65
+ }),
66
+ });
67
+ // 模型:显式指定 > 主会话回落 > 会话默认(与 reviewer 同优先级)。
68
+ let model;
69
+ let modelName = "default";
70
+ const spec = parseModelSpec(req?.model);
71
+ if (spec) {
72
+ model = services.modelRuntime.getModel(spec.provider, spec.id);
73
+ if (!model)
74
+ return fail(`llm.complete: 找不到模型 ${spec.spec}`);
75
+ modelName = spec.spec;
76
+ }
77
+ if (!model && env.fallbackModel) {
78
+ model = services.modelRuntime.getModel(env.fallbackModel.provider, env.fallbackModel.id);
79
+ if (model)
80
+ modelName = `${env.fallbackModel.provider}/${env.fallbackModel.id}`;
81
+ }
82
+ const srv = await createAgentSessionFromServices({
83
+ services,
84
+ sessionManager: SessionManager.inMemory(env.cwd),
85
+ ...(model ? { model } : {}),
86
+ // 全部工具关闭("all"):纯补全,无副作用(SDK 的 noTools 是 "builtin"|"all" 枚举)。
87
+ noTools: "all",
88
+ });
89
+ dispose = () => {
90
+ try {
91
+ srv.session.dispose();
92
+ }
93
+ catch {
94
+ /* dispose 尽力而为 */
95
+ }
96
+ };
97
+ const text = system.trim() ? `系统指令:${system.trim()}\n\n---\n\n任务:${prompt}` : prompt;
98
+ await srv.session.prompt(text, { expandPromptTemplates: false });
99
+ const raw = srv.session.getLastAssistantText() ?? "";
100
+ let usage;
101
+ try {
102
+ const stats = srv.session.getSessionStats();
103
+ usage = { input: stats.tokens.input, output: stats.tokens.output };
104
+ }
105
+ catch {
106
+ /* usage 尽力而为 */
107
+ }
108
+ return { ok: true, text: raw.slice(0, maxChars), model: modelName, ...(usage ? { usage } : {}) };
109
+ }
110
+ finally {
111
+ // 会话回收跟 run 走:超时竞速输了 run 还在飞,run 落定才 dispose,不留孤儿。
112
+ try {
113
+ dispose?.();
114
+ }
115
+ catch {
116
+ /* dispose 尽力而为 */
117
+ }
118
+ }
119
+ })();
120
+ const timer = new Promise((resolve) => setTimeout(() => resolve(fail(`llm.complete: 超时(约${Math.round(timeoutMs / 1000)}s)`)), timeoutMs));
121
+ return await Promise.race([run, timer]);
122
+ }
123
+ catch (err) {
124
+ return fail(`llm.complete: ${err.message}`);
125
+ }
126
+ finally {
127
+ inflight -= 1;
128
+ }
129
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * 插件能力动态授权表(host.requestPermission 的底层)。
3
+ *
4
+ * 定位:manifest.permissions 管“有没有这个能力族”(静态、装时定),这张表管
5
+ * “运行时的具体范围”(动态、用户随时批):
6
+ * - net:在 manifest netAllowlist 之外,用户额外批准的主机(免改 manifest 重装);
7
+ * - llm:用户批准的模型作用域(空 = 不限模型),花 token 前插件可主动来问一次。
8
+ * 基础族未声明时 requestPermission 直接回 false(不弹框)——与 requestAccess
9
+ * 要求 fs:read 同口径,fail-closed。
10
+ *
11
+ * 两层存储:
12
+ * - 磁盘 `<dataDir>/plugin-permissions.json`(记住的授权,设置面板可审计/撤销);
13
+ * - 内存 session 授权(仅本次运行,进程结束即失)。
14
+ * 读坏/形状不对当空表,且不在读路径回写;只有真正变更的写才落盘(tmp+rename 原子写)。
15
+ */
16
+ import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+ /** 主机匹配(与 manifest netAllowlist 同口径):全等或点号后缀。纯函数,单测覆盖。 */
19
+ export function permissionHostMatches(hostname, entry) {
20
+ const h = String(hostname ?? "").toLowerCase();
21
+ const e = String(entry ?? "")
22
+ .toLowerCase()
23
+ .trim();
24
+ if (!h || !e)
25
+ return false;
26
+ return h === e || h.endsWith(`.${e}`);
27
+ }
28
+ function normalizeHosts(hosts) {
29
+ if (!Array.isArray(hosts))
30
+ return undefined;
31
+ const out = [
32
+ ...new Set(hosts.filter((x) => typeof x === "string" && x.trim() !== "").map((x) => x.trim().toLowerCase())),
33
+ ];
34
+ return out.length > 0 ? out.slice(0, 32) : undefined;
35
+ }
36
+ function normalizeModels(models) {
37
+ if (!Array.isArray(models))
38
+ return undefined;
39
+ const out = [
40
+ ...new Set(models.filter((x) => typeof x === "string" && x.includes("/")).map((x) => x.trim())),
41
+ ];
42
+ return out.length > 0 ? out.slice(0, 32) : undefined;
43
+ }
44
+ export class PluginPermissionStore {
45
+ dataDir;
46
+ sessionGrants = [];
47
+ constructor(dataDir) {
48
+ this.dataDir = dataDir;
49
+ }
50
+ file() {
51
+ return join(this.dataDir, "plugin-permissions.json");
52
+ }
53
+ read() {
54
+ try {
55
+ const parsed = JSON.parse(readFileSync(this.file(), "utf8"));
56
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.grants))
57
+ return { v: 1, grants: [] };
58
+ return { v: 1, grants: parsed.grants };
59
+ }
60
+ catch {
61
+ return { v: 1, grants: [] };
62
+ }
63
+ }
64
+ write(grants) {
65
+ try {
66
+ mkdirSync(dirname(this.file()), { recursive: true });
67
+ const tmp = `${this.file()}.tmp-${process.pid}`;
68
+ writeFileSync(tmp, JSON.stringify({ v: 1, grants }));
69
+ renameSync(tmp, this.file());
70
+ }
71
+ catch (err) {
72
+ console.error(`[plugin-permissions] persist failed (${this.file()}):`, err);
73
+ }
74
+ }
75
+ static validId(id) {
76
+ return /^[A-Za-z0-9_-]+$/.test(id);
77
+ }
78
+ /** 是否有有效授权(磁盘 + 内存;host/model 命中才算)。 */
79
+ has(pluginId, family, scope) {
80
+ if (!PluginPermissionStore.validId(pluginId))
81
+ return false;
82
+ const all = [...this.read().grants, ...this.sessionGrants];
83
+ return all.some((g) => {
84
+ if (g.pluginId !== pluginId || g.family !== family)
85
+ return false;
86
+ if (family === "net") {
87
+ const host = String(scope?.host ?? "").toLowerCase();
88
+ if (!host || !g.hosts)
89
+ return false;
90
+ return g.hosts.some((entry) => permissionHostMatches(host, entry));
91
+ }
92
+ if (family === "llm" && scope?.model) {
93
+ if (!g.models || g.models.length === 0)
94
+ return true; // 不限模型
95
+ return g.models.includes(scope.model);
96
+ }
97
+ return true;
98
+ });
99
+ }
100
+ /** 写入一条授权(remember=true 落盘,false 只记内存)。同插件同族同范围覆盖旧条。 */
101
+ grant(pluginId, family, opts) {
102
+ if (!PluginPermissionStore.validId(pluginId))
103
+ throw new Error(`非法插件 id:${pluginId}`);
104
+ if (family !== "net" && family !== "llm")
105
+ throw new Error(`不支持的能力族:${String(family)}`);
106
+ const grant = {
107
+ pluginId,
108
+ family,
109
+ ...(family === "net" && normalizeHosts(opts?.hosts) ? { hosts: normalizeHosts(opts?.hosts) } : {}),
110
+ ...(family === "llm" && normalizeModels(opts?.models) ? { models: normalizeModels(opts?.models) } : {}),
111
+ ...(typeof opts?.reason === "string" && opts.reason.trim() ? { reason: opts.reason.trim().slice(0, 200) } : {}),
112
+ grantedAt: Date.now(),
113
+ };
114
+ if (opts?.remember === true) {
115
+ const grants = this.read().grants.filter((g) => !(g.pluginId === pluginId && g.family === family && sameScope(g, grant)));
116
+ grants.push(grant);
117
+ this.write(grants);
118
+ }
119
+ else {
120
+ this.sessionGrants = this.sessionGrants.filter((g) => !(g.pluginId === pluginId && g.family === family && sameScope(g, grant)));
121
+ this.sessionGrants.push(grant);
122
+ }
123
+ }
124
+ /** 撤销:都不给 = 清空整表;返回删掉的条数(磁盘 + 内存)。 */
125
+ revoke(pluginId, family, scope) {
126
+ let removed = 0;
127
+ const drop = (g) => {
128
+ if (pluginId && g.pluginId !== pluginId)
129
+ return false;
130
+ if (family && g.family !== family)
131
+ return false;
132
+ if (scope?.host && !(g.hosts ?? []).some((entry) => permissionHostMatches(scope.host, entry)))
133
+ return false;
134
+ if (scope?.model && g.models && g.models.length > 0 && !g.models.includes(scope.model))
135
+ return false;
136
+ return true;
137
+ };
138
+ const disk = this.read().grants;
139
+ const kept = disk.filter((g) => !drop(g));
140
+ if (kept.length !== disk.length) {
141
+ removed += disk.length - kept.length;
142
+ this.write(kept);
143
+ }
144
+ const before = this.sessionGrants.length;
145
+ this.sessionGrants = this.sessionGrants.filter((g) => !drop(g));
146
+ removed += before - this.sessionGrants.length;
147
+ return removed;
148
+ }
149
+ /** 模型是否在批准作用域内:无 llm 授权 → 不限(调用方先判声明);有授权时,
150
+ * 至少一条「不限模型」或命中模型才放行。空 model(走默认模型)不卡。 */
151
+ modelAllowed(pluginId, model) {
152
+ if (!PluginPermissionStore.validId(pluginId))
153
+ return false;
154
+ const scoped = [...this.read().grants, ...this.sessionGrants].filter((g) => g.pluginId === pluginId && g.family === "llm");
155
+ if (scoped.length === 0)
156
+ return true;
157
+ if (!model)
158
+ return true;
159
+ return scoped.some((g) => !g.models || g.models.length === 0 || g.models.includes(model));
160
+ }
161
+ /** 全量快照(设置面板审计用;session 授权带 session:true 标记)。 */
162
+ list() {
163
+ return [
164
+ ...this.read().grants.map((g) => ({ ...g })),
165
+ ...this.sessionGrants.map((g) => ({ ...g, session: true })),
166
+ ];
167
+ }
168
+ }
169
+ /** 同范围判定(撤销/覆盖时去重用;范围字段都为空 = 同族整单)。 */
170
+ function sameScope(a, b) {
171
+ const ah = [...(a.hosts ?? [])].sort().join(",");
172
+ const bh = [...(b.hosts ?? [])].sort().join(",");
173
+ const am = [...(a.models ?? [])].sort().join(",");
174
+ const bm = [...(b.models ?? [])].sort().join(",");
175
+ return ah === bh && am === bm;
176
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * 插件定时任务的 cron 解析与持久化(host.schedule 的底层,server/plugins.ts 调用)。
3
+ *
4
+ * 两部分:
5
+ * 1. 全 5 字段 cron(分 时 日 月 周):`"*"` / `"*\/n"` / `"a-b"` / `"a-b/n"` /
6
+ * `"a,b,c"` / 单数字;月/周支持英文名(jan/dec 不分大小写,sun..sat,7 视作 0)。
7
+ * 日-周按标准 cron OR 语义(都受限取并集,一侧 `*` 时另一侧说了算)。
8
+ * 时间一律按**服务器本地时区**算(文档写死,不做 TZ 配置)。
9
+ * 2. 持久记录 `<pluginDir>/schedules.json`:只存声明(spec/catchUp/label)+
10
+ * 上次触发 lastRun;fn 回调永远由插件代码在 activate 里重给(重启后重建)。
11
+ * 坏文件当空表(不回写,避免一次磁盘抖动清空全部定时)。
12
+ */
13
+ import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ const MONTH_NAMES = {
16
+ jan: 1,
17
+ feb: 2,
18
+ mar: 3,
19
+ apr: 4,
20
+ may: 5,
21
+ jun: 6,
22
+ jul: 7,
23
+ aug: 8,
24
+ sep: 9,
25
+ oct: 10,
26
+ nov: 11,
27
+ dec: 12,
28
+ };
29
+ const DOW_NAMES = {
30
+ sun: 0,
31
+ mon: 1,
32
+ tue: 2,
33
+ wed: 3,
34
+ thu: 4,
35
+ fri: 5,
36
+ sat: 6,
37
+ };
38
+ /** 单字段解析 → 升序去重数组;非法回 null。纯函数,单测覆盖。 */
39
+ export function parseCronField(raw, min, max, names) {
40
+ const src = String(raw ?? "")
41
+ .trim()
42
+ .toLowerCase();
43
+ if (!src)
44
+ return null;
45
+ const out = new Set();
46
+ const num = (tok) => {
47
+ const t = tok.trim();
48
+ if (!t)
49
+ return null;
50
+ if (names && t in names)
51
+ return names[t];
52
+ if (!/^\d+$/.test(t))
53
+ return null;
54
+ let n = Number(t);
55
+ if (n === 7 && min === 0 && max === 6)
56
+ n = 0; // 周日的 7 写法
57
+ if (!Number.isInteger(n) || n < min || n > max)
58
+ return null;
59
+ return n;
60
+ };
61
+ for (const part of src.split(",")) {
62
+ const p = part.trim();
63
+ if (!p)
64
+ return null;
65
+ // 步长:*/n 或 a-b/n(a 缺省 min,b 缺省 max)。
66
+ const step = p.split("/");
67
+ if (step.length === 2) {
68
+ const every = num(step[1]);
69
+ if (every === null || every <= 0)
70
+ return null;
71
+ let lo = min;
72
+ let hi = max;
73
+ if (step[0] !== "" && step[0] !== "*") {
74
+ const range = step[0].split("-");
75
+ if (range.length > 2)
76
+ return null;
77
+ const a = num(range[0]);
78
+ if (a === null)
79
+ return null;
80
+ lo = a;
81
+ if (range.length === 2) {
82
+ const b = num(range[1]);
83
+ if (b === null || b < a)
84
+ return null;
85
+ hi = b;
86
+ }
87
+ }
88
+ for (let v = lo; v <= hi; v += every)
89
+ out.add(v);
90
+ continue;
91
+ }
92
+ if (step.length > 2)
93
+ return null;
94
+ if (p === "*") {
95
+ for (let v = min; v <= max; v++)
96
+ out.add(v);
97
+ continue;
98
+ }
99
+ if (p.includes("-")) {
100
+ const range = p.split("-");
101
+ if (range.length !== 2)
102
+ return null;
103
+ const a = num(range[0]);
104
+ const b = num(range[1]);
105
+ if (a === null || b === null || b < a)
106
+ return null;
107
+ for (let v = a; v <= b; v++)
108
+ out.add(v);
109
+ continue;
110
+ }
111
+ const n = num(p);
112
+ if (n === null)
113
+ return null;
114
+ out.add(n);
115
+ }
116
+ if (out.size === 0)
117
+ return null;
118
+ return [...out].sort((a, b) => a - b);
119
+ }
120
+ /** 5 字段 cron 解析;非法回 null。纯函数,单测覆盖。 */
121
+ export function parseCronSpec(spec) {
122
+ const fields = String(spec ?? "")
123
+ .trim()
124
+ .split(/\s+/);
125
+ if (fields.length !== 5)
126
+ return null;
127
+ const minute = parseCronField(fields[0], 0, 59);
128
+ const hour = parseCronField(fields[1], 0, 23);
129
+ const dom = parseCronField(fields[2], 1, 31);
130
+ const month = parseCronField(fields[3], 1, 12, MONTH_NAMES);
131
+ const dow = parseCronField(fields[4], 0, 6, DOW_NAMES);
132
+ if (!minute || !hour || !dom || !month || !dow)
133
+ return null;
134
+ return { minute, hour, dom, month, dow };
135
+ }
136
+ function isFull(values, min, max) {
137
+ return values.length === max - min + 1;
138
+ }
139
+ /** 下一次触发毫秒时间戳(从 fromMs 的下一分钟开始扫,上限约一年)。纯函数,单测覆盖。 */
140
+ export function nextCronFire(parts, fromMs) {
141
+ const minuteSet = new Set(parts.minute);
142
+ const hourSet = new Set(parts.hour);
143
+ const monthSet = new Set(parts.month);
144
+ const domRestricted = !isFull(parts.dom, 1, 31);
145
+ const dowRestricted = !isFull(parts.dow, 0, 6);
146
+ const domSet = new Set(parts.dom);
147
+ const dowSet = new Set(parts.dow);
148
+ let t = Math.floor(Number(fromMs) / 60000) * 60000 + 60000;
149
+ const limit = t + 366 * 24 * 60 * 60000;
150
+ for (; t <= limit; t += 60000) {
151
+ const d = new Date(t);
152
+ if (!monthSet.has(d.getMonth() + 1))
153
+ continue;
154
+ const domHit = domSet.has(d.getDate());
155
+ const dowHit = dowSet.has(d.getDay());
156
+ // 标准 OR 语义:都受限取并集;一侧通配时另一侧说了算;都不受限天天跑。
157
+ const dayHit = domRestricted && dowRestricted ? domHit || dowHit : domRestricted ? domHit : dowRestricted ? dowHit : true;
158
+ if (!dayHit)
159
+ continue;
160
+ if (!hourSet.has(d.getHours()))
161
+ continue;
162
+ if (!minuteSet.has(d.getMinutes()))
163
+ continue;
164
+ return t;
165
+ }
166
+ return limit;
167
+ }
168
+ export function scheduleFile(pluginDir) {
169
+ return join(pluginDir, "schedules.json");
170
+ }
171
+ /** 读持久记录;坏文件/形状不对当空表(且不在读路径回写)。 */
172
+ export function loadScheduleRecords(pluginDir) {
173
+ try {
174
+ const parsed = JSON.parse(readFileSync(scheduleFile(pluginDir), "utf8"));
175
+ if (!parsed || typeof parsed !== "object" || parsed.schedules === null || typeof parsed.schedules !== "object") {
176
+ return {};
177
+ }
178
+ const out = {};
179
+ for (const [id, r] of Object.entries(parsed.schedules)) {
180
+ if (!r || typeof r !== "object")
181
+ continue;
182
+ const rec = r;
183
+ if (typeof rec.spec !== "string" || !rec.spec)
184
+ continue;
185
+ out[id] = {
186
+ spec: rec.spec,
187
+ catchUp: rec.catchUp === "once" ? "once" : "skip",
188
+ ...(typeof rec.label === "string" && rec.label ? { label: rec.label } : {}),
189
+ ...(typeof rec.lastRun === "number" && Number.isFinite(rec.lastRun) ? { lastRun: rec.lastRun } : {}),
190
+ createdAt: typeof rec.createdAt === "number" && Number.isFinite(rec.createdAt) ? rec.createdAt : Date.now(),
191
+ };
192
+ }
193
+ return out;
194
+ }
195
+ catch {
196
+ return {};
197
+ }
198
+ }
199
+ /** 写持久记录(tmp+rename 原子写;失败只记日志,内存态本次会话仍生效)。 */
200
+ export function saveScheduleRecords(pluginDir, records) {
201
+ try {
202
+ mkdirSync(pluginDir, { recursive: true });
203
+ const file = scheduleFile(pluginDir);
204
+ const tmp = `${file}.tmp-${process.pid}`;
205
+ writeFileSync(tmp, JSON.stringify({ v: 1, schedules: records }));
206
+ renameSync(tmp, file);
207
+ }
208
+ catch (err) {
209
+ console.error(`[plugin-schedule] persist failed (${pluginDir}):`, err);
210
+ }
211
+ }