@cannbot-plugin/cannbot-dsh-server 0.0.0-stage → 1.0.0-alpha.5

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.
@@ -0,0 +1,1763 @@
1
+ import { createRequire } from "node:module";
2
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { spawn } from "node:child_process";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { cp, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
11
+ // plugin/backend/package-root.js
12
+ function packageRoot(start = import.meta.url) {
13
+ let directory = dirname(fileURLToPath(start));
14
+ while (true) {
15
+ const manifest = join(directory, "package.json");
16
+ if (existsSync(manifest)) try {
17
+ if (["@cannbot-plugin/cannbot-dsh", "@cannbot-plugin/cannbot-dsh-server"].includes(JSON.parse(readFileSync(manifest, "utf8")).name)) return directory;
18
+ } catch {}
19
+ const parent = dirname(directory);
20
+ if (parent === directory) throw new Error("Cannot locate the CANNBot DSH package");
21
+ directory = parent;
22
+ }
23
+ }
24
+ JSON.parse(readFileSync(join(packageRoot(), "package.json"), "utf8")).version;
25
+ // plugin/backend/process-runner.mjs
26
+ /** Wait for termination before callers release locks or remove staging files. */
27
+ function runProcess(command, args, { signal, timeoutMs, graceMs = 1e3, onData, ...options } = {}) {
28
+ signal?.throwIfAborted();
29
+ return new Promise((resolve, reject) => {
30
+ const child = spawn(command, args, {
31
+ ...options,
32
+ detached: process.platform !== "win32",
33
+ windowsHide: true
34
+ });
35
+ let stopped, escalation, timer, terminating;
36
+ const kill = (force) => {
37
+ if (!child.pid) return;
38
+ if (process.platform === "win32") {
39
+ if (terminating || child.exitCode !== null || child.signalCode !== null) return terminating;
40
+ terminating = new Promise((resolve) => {
41
+ const killer = spawn("taskkill.exe", [
42
+ "/PID",
43
+ String(child.pid),
44
+ "/T",
45
+ "/F"
46
+ ], {
47
+ stdio: "ignore",
48
+ windowsHide: true
49
+ });
50
+ const direct = () => {
51
+ try {
52
+ child.kill("SIGKILL");
53
+ } catch {}
54
+ };
55
+ killer.once("error", () => {
56
+ direct();
57
+ resolve();
58
+ });
59
+ killer.once("close", (code) => {
60
+ if (code !== 0) direct();
61
+ resolve();
62
+ });
63
+ });
64
+ return terminating;
65
+ }
66
+ try {
67
+ process.kill(-child.pid, force ? "SIGKILL" : "SIGTERM");
68
+ } catch {}
69
+ };
70
+ const stop = (reason) => {
71
+ if (stopped) return;
72
+ stopped = reason;
73
+ kill(false);
74
+ escalation = setTimeout(() => kill(true), graceMs);
75
+ };
76
+ const abort = () => stop(signal.reason ?? /* @__PURE__ */ new Error("Operation cancelled"));
77
+ const cleanup = () => {
78
+ clearTimeout(timer);
79
+ clearTimeout(escalation);
80
+ signal?.removeEventListener("abort", abort);
81
+ };
82
+ if (onData) {
83
+ child.stdout?.on("data", onData);
84
+ child.stderr?.on("data", onData);
85
+ }
86
+ signal?.addEventListener("abort", abort, { once: true });
87
+ if (signal?.aborted) abort();
88
+ if (timeoutMs !== void 0) timer = setTimeout(() => stop(/* @__PURE__ */ new Error("Initialization timed out")), timeoutMs);
89
+ child.on("error", (error) => {
90
+ cleanup();
91
+ reject(error);
92
+ });
93
+ child.on("close", async (code, exitSignal) => {
94
+ if (stopped) {
95
+ if (process.platform === "win32") await terminating;
96
+ else kill(true);
97
+ }
98
+ cleanup();
99
+ if (stopped) reject(stopped);
100
+ else if (code !== 0) reject(/* @__PURE__ */ new Error(`Command failed: ${command} (exit ${code ?? exitSignal})`));
101
+ else resolve();
102
+ });
103
+ });
104
+ }
105
+ // packages/install/lib/file-lock.mjs
106
+ /** Never unlink this inode. The kernel releases the SQLite transaction on exit.
107
+ * The suffix separates legacy JSON locks from the database format. */
108
+ async function acquireFileLock(path, timeout = 0) {
109
+ await mkdir(dirname(path), { recursive: true });
110
+ const file = path + ".sqlite3";
111
+ await (await open(file, "a", 384)).close();
112
+ const database = new DatabaseSync(file);
113
+ const deadline = Date.now() + timeout;
114
+ try {
115
+ for (;;) try {
116
+ database.exec("BEGIN EXCLUSIVE");
117
+ break;
118
+ } catch (error) {
119
+ if (error.errcode !== 5) throw error;
120
+ if (Date.now() >= deadline) throw new Error("Another installation or content operation is still running");
121
+ await new Promise((resolve) => setTimeout(resolve, Math.min(250, Math.max(1, deadline - Date.now()))));
122
+ }
123
+ } catch (error) {
124
+ database.close();
125
+ throw error;
126
+ }
127
+ let released = false;
128
+ return () => {
129
+ if (!released) {
130
+ released = true;
131
+ database.close();
132
+ }
133
+ };
134
+ }
135
+ // plugin/backend/content-lock.ts
136
+ async function withContentLock(path, action) {
137
+ const release = await acquireFileLock(path, 12e5);
138
+ try {
139
+ return await action();
140
+ } finally {
141
+ release();
142
+ }
143
+ }
144
+ // plugin/backend/initializer-transaction.ts
145
+ const transient = /* @__PURE__ */ new Set([
146
+ "EIO",
147
+ "EBUSY",
148
+ "EPERM",
149
+ "EACCES",
150
+ "ENOENT"
151
+ ]);
152
+ async function retry(action) {
153
+ for (let attempt = 0;; attempt++) try {
154
+ return await action();
155
+ } catch (error) {
156
+ if (!transient.has(error.code ?? "") || attempt === 6) throw error;
157
+ await new Promise((done) => setTimeout(done, Math.min(100 * 2 ** attempt, 800)));
158
+ }
159
+ }
160
+ function inside$1(root, path) {
161
+ const target = resolve(root, path), diff = relative(root, target);
162
+ if (!diff || diff === ".." || diff.startsWith(".." + sep) || isAbsolute(diff)) throw new Error("Invalid initialization recovery path");
163
+ return target;
164
+ }
165
+ async function present(path) {
166
+ try {
167
+ await lstat(path);
168
+ return true;
169
+ } catch (error) {
170
+ if (error.code === "ENOENT") return false;
171
+ throw error;
172
+ }
173
+ }
174
+ async function checkParent(workspace, path) {
175
+ let parent = resolve(path, "..");
176
+ while (parent !== workspace && !await present(parent)) parent = resolve(parent, "..");
177
+ if (parent !== workspace) inside$1(workspace, await realpath(parent));
178
+ }
179
+ /** Snapshot only installer-owned destinations; dependency repositories are never removed. */
180
+ async function initializeTransaction(workspace, recoveryRoot, descriptor, resources, initialize, extraPaths = [], committed, commitToken, recoverOnly = false) {
181
+ await mkdir(recoveryRoot, { recursive: true });
182
+ const journalPath = join(recoveryRoot, "recovery.json");
183
+ async function restore(journal) {
184
+ if (journal.workspace !== workspace || !relative(recoveryRoot, journal.directory).startsWith("snapshot-") || relative(recoveryRoot, journal.directory).includes(sep)) throw new Error("Invalid initialization recovery journal");
185
+ for (const entry of journal.entries) {
186
+ const destination = inside$1(workspace, entry.path), saved = inside$1(journal.directory, entry.slot);
187
+ const parent = resolve(destination, "..");
188
+ await checkParent(workspace, destination);
189
+ await retry(() => rm(destination, {
190
+ recursive: true,
191
+ force: true,
192
+ maxRetries: 3,
193
+ retryDelay: 100
194
+ }));
195
+ if (entry.present) {
196
+ await mkdir(parent, { recursive: true });
197
+ await retry(() => cp(saved, destination, {
198
+ recursive: true,
199
+ dereference: false,
200
+ verbatimSymlinks: true
201
+ }));
202
+ }
203
+ }
204
+ }
205
+ const previous = await readFile(journalPath, "utf8").catch((error) => {
206
+ if (error.code === "ENOENT") return "";
207
+ throw error;
208
+ });
209
+ if (previous) {
210
+ const journal = JSON.parse(previous);
211
+ if (journal.workspace !== workspace || !relative(recoveryRoot, journal.directory).startsWith("snapshot-") || relative(recoveryRoot, journal.directory).includes(sep)) throw Object.assign(/* @__PURE__ */ new Error("Invalid initialization recovery journal"), { recoveryFailed: true });
212
+ try {
213
+ if (!journal.committed && !await committed?.(journal.commitToken)) await restore(journal);
214
+ } catch (error) {
215
+ throw Object.assign(error, { recoveryFailed: true });
216
+ }
217
+ await rm(journalPath);
218
+ await rm(journal.directory, {
219
+ recursive: true,
220
+ force: true,
221
+ maxRetries: 3,
222
+ retryDelay: 100
223
+ }).catch(() => {});
224
+ }
225
+ if (recoverOnly) return;
226
+ const paths = new Set(descriptor.skills.map((skill) => `.dsh/skills/${skill.name}`));
227
+ for (const path of extraPaths) paths.add(path);
228
+ paths.add(`.cannbot/plugins/${descriptor.id}`);
229
+ for (const file of [
230
+ "AGENTS.md",
231
+ "CLAUDE.md",
232
+ ".dsh/cannbot-plugin.json",
233
+ ".cannbot/settings.json",
234
+ ".cannbot/permissions"
235
+ ]) paths.add(file);
236
+ const manifestPath = join(resources, ".claude-plugin/plugin.json");
237
+ if (await present(manifestPath)) {
238
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
239
+ for (const path of manifest.agents ?? []) {
240
+ const text = await readFile(inside$1(resources, path), "utf8");
241
+ const name = /^name:\s*([^\r\n]+)$/m.exec(text)?.[1]?.trim();
242
+ if (!name || !/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$/.test(name)) throw new Error("Invalid initializer agent name");
243
+ paths.add(`.dsh/agents/${name}.md`);
244
+ }
245
+ }
246
+ const directory = await mkdtemp(join(recoveryRoot, "snapshot-"));
247
+ const journal = {
248
+ workspace,
249
+ directory,
250
+ entries: [],
251
+ ...commitToken && { commitToken }
252
+ };
253
+ for (const path of paths) {
254
+ const source = inside$1(workspace, path);
255
+ await checkParent(workspace, source);
256
+ const exists = await present(source), slot = String(journal.entries.length);
257
+ if (exists) await retry(() => cp(source, join(directory, slot), {
258
+ recursive: true,
259
+ dereference: false,
260
+ verbatimSymlinks: true
261
+ }));
262
+ journal.entries.push({
263
+ path,
264
+ present: exists,
265
+ slot
266
+ });
267
+ }
268
+ const temporary = journalPath + ".tmp";
269
+ await writeFile(temporary, JSON.stringify(journal), { mode: 384 });
270
+ await rename(temporary, journalPath);
271
+ try {
272
+ await initialize();
273
+ } catch (error) {
274
+ try {
275
+ await restore(journal);
276
+ await rm(journalPath);
277
+ } catch (recovery) {
278
+ throw Object.assign(/* @__PURE__ */ new Error(`${error.message}\n自动恢复未完成,备份保留在 ${directory}:${recovery.message}`), { recoveryFailed: true });
279
+ }
280
+ await rm(directory, {
281
+ recursive: true,
282
+ force: true,
283
+ maxRetries: 3,
284
+ retryDelay: 100
285
+ }).catch(() => {});
286
+ throw new Error(`${error.message}\n已恢复本次初始化前的 Skills 和工作区配置。`);
287
+ }
288
+ journal.committed = true;
289
+ try {
290
+ await writeFile(temporary, JSON.stringify(journal), { mode: 384 });
291
+ await rename(temporary, journalPath);
292
+ await rm(journalPath);
293
+ } catch (error) {
294
+ if (!committed) throw error;
295
+ return;
296
+ }
297
+ await rm(directory, {
298
+ recursive: true,
299
+ force: true,
300
+ maxRetries: 3,
301
+ retryDelay: 100
302
+ }).catch(() => {});
303
+ }
304
+ /** Recover before reading the old workflow's registry to plan its retirement. */
305
+ async function recoverInitialization(workspace, recoveryRoot, committed) {
306
+ await initializeTransaction(workspace, recoveryRoot, {
307
+ schemaVersion: 1,
308
+ id: "recovery",
309
+ title: "",
310
+ version: "0.0.0",
311
+ skills: [],
312
+ initialization: { kind: "skill-native" },
313
+ source: {
314
+ repository: "",
315
+ commit: "",
316
+ skillsCommit: ""
317
+ }
318
+ }, recoveryRoot, async () => {}, [], committed, void 0, true);
319
+ }
320
+ // plugin/backend/initialization-jobs.ts
321
+ const initializationIO = new AsyncLocalStorage();
322
+ async function runInitializationTerminal(spawn, argv, cwd, io) {
323
+ const terminal = await spawn({
324
+ argv,
325
+ cwd,
326
+ env: {
327
+ TERM: "xterm-256color",
328
+ ...process.versions.electron ? { ELECTRON_RUN_AS_NODE: "1" } : {}
329
+ },
330
+ rows: 20,
331
+ cols: 86,
332
+ terminalType: "xterm-256color",
333
+ graceMs: 1e3,
334
+ signal: io.signal
335
+ });
336
+ let terminating;
337
+ const stop = () => {
338
+ terminating ??= terminal.terminate();
339
+ terminating.catch(() => {});
340
+ };
341
+ const timer = setTimeout(stop, 12e5);
342
+ io.signal.addEventListener("abort", stop, { once: true });
343
+ if (io.signal.aborted) stop();
344
+ terminal.output.setEncoding("utf8");
345
+ const output = (data) => io.output(data);
346
+ terminal.output.on("data", output);
347
+ io.input = (data) => terminal.write(data);
348
+ try {
349
+ const outcome = await terminal.done;
350
+ if (terminating) await terminating;
351
+ io.signal.throwIfAborted();
352
+ if (terminating || outcome.exitCode !== 0) throw new Error(terminating ? "初始化超时。" : `初始化退出(${outcome.exitCode ?? outcome.signal})。`);
353
+ } finally {
354
+ io.input = void 0;
355
+ clearTimeout(timer);
356
+ io.signal.removeEventListener("abort", stop);
357
+ await terminal.terminate();
358
+ terminal.output.off("data", output);
359
+ }
360
+ }
361
+ /** Authenticated Host routes only. IDs are unguessable, output bounded, input never persisted. */
362
+ var InitializationJobs = class {
363
+ jobs = /* @__PURE__ */ new Map();
364
+ run;
365
+ constructor(run) {
366
+ this.run = run;
367
+ }
368
+ async handle(request) {
369
+ if (request.action === "start-initialization") {
370
+ for (const [id, item] of this.jobs) if (item.phase !== "running" && Date.now() - item.touched > 18e5) this.jobs.delete(id);
371
+ const key = JSON.stringify(request.operation);
372
+ const previous = [...this.jobs.values()].find((item) => item.requestId === request.requestId);
373
+ if (previous) {
374
+ if (previous.key !== key) throw new Error("初始化请求内容已变化。");
375
+ return this.snapshot(previous, 0);
376
+ }
377
+ if (this.jobs.size >= 100 || [...this.jobs.values()].filter((item) => item.phase === "running").length >= 4) throw new Error("初始化任务较多,请稍后重试。");
378
+ const controller = new AbortController();
379
+ const job = {
380
+ id: randomUUID(),
381
+ key,
382
+ requestId: request.requestId,
383
+ controller,
384
+ output: "",
385
+ start: 0,
386
+ phase: "running",
387
+ sequence: 0,
388
+ touched: Date.now(),
389
+ io: {
390
+ signal: controller.signal,
391
+ output: (data) => {
392
+ job.output += data;
393
+ if (job.output.length > 256e3) {
394
+ job.start += job.output.length - 256e3;
395
+ job.output = job.output.slice(-256e3);
396
+ }
397
+ }
398
+ }
399
+ };
400
+ this.jobs.set(job.id, job);
401
+ initializationIO.run(job.io, async () => {
402
+ try {
403
+ controller.signal.throwIfAborted();
404
+ job.result = await this.run(request.operation);
405
+ job.phase = "ready";
406
+ } catch (error) {
407
+ job.phase = "error";
408
+ job.message = controller.signal.aborted && !error.recoveryFailed ? "已取消初始化,可以重试。" : String(error.message).slice(-2e3);
409
+ } finally {
410
+ job.touched = Date.now();
411
+ job.io.input = void 0;
412
+ }
413
+ });
414
+ return this.snapshot(job, 0);
415
+ }
416
+ const job = this.jobs.get(request.jobId);
417
+ if (!job) throw new Error("初始化任务已过期或服务已重启,请关闭后重试。");
418
+ job.touched = Date.now();
419
+ if (request.action === "cancel-initialization" && job.phase === "running") job.controller.abort(/* @__PURE__ */ new Error("初始化已取消。"));
420
+ if (request.action === "initialization-input") {
421
+ if (job.pending) await job.pending;
422
+ if (request.sequence > job.sequence) {
423
+ if (request.sequence !== job.sequence + 1 || job.phase !== "running" || !job.io.input || job.controller.signal.aborted) throw new Error("终端尚未就绪,请稍后重试。");
424
+ job.pending = job.io.input(request.data);
425
+ try {
426
+ await job.pending;
427
+ job.sequence = request.sequence;
428
+ } finally {
429
+ job.pending = void 0;
430
+ }
431
+ }
432
+ }
433
+ return this.snapshot(job, "offset" in request ? request.offset : job.start + job.output.length);
434
+ }
435
+ snapshot(job, offset) {
436
+ const start = Math.max(job.start, Math.min(offset, job.start + job.output.length));
437
+ return {
438
+ jobId: job.id,
439
+ phase: job.phase,
440
+ output: job.output.slice(start - job.start),
441
+ offset: start,
442
+ nextOffset: job.start + job.output.length,
443
+ inputSequence: job.sequence,
444
+ interactive: !!job.io.input,
445
+ ...job.message && { message: job.message },
446
+ ...job.phase === "ready" && { result: job.result }
447
+ };
448
+ }
449
+ dispose() {
450
+ for (const job of this.jobs.values()) if (job.phase === "running") job.controller.abort(/* @__PURE__ */ new Error("Host stopped"));
451
+ }
452
+ };
453
+ // plugin/backend/workflow-retirement.ts
454
+ /** Retire executable registrations only; repositories and project source stay put. */
455
+ async function workflowRetirement(workspace, descriptor) {
456
+ const paths = /* @__PURE__ */ new Set(), markers = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
457
+ let registry;
458
+ if (descriptor) {
459
+ markers.add(descriptor.id);
460
+ for (const skill of descriptor.skills) {
461
+ paths.add(`.dsh/skills/${skill.name}`);
462
+ names.add(skill.name);
463
+ }
464
+ paths.add(`.cannbot/plugins/${descriptor.id}`);
465
+ try {
466
+ registry = JSON.parse(await readFile(join(workspace, ".dsh/cannbot-plugin.json"), "utf8"));
467
+ } catch (error) {
468
+ if (error.code !== "ENOENT") throw error;
469
+ }
470
+ if (registry) {
471
+ if (registry.schemaVersion !== 2 || !Array.isArray(registry.plugins)) throw new Error("工作流安装记录无效,未修改工作区。");
472
+ for (const row of registry.plugins.filter((row) => row.plugin === descriptor.id)) {
473
+ for (const path of [...Array.isArray(row.skills) ? row.skills : [], ...Array.isArray(row.agents) ? row.agents : []]) {
474
+ if (typeof path !== "string" || !/^\.dsh\/(?:skills\/[\w.-]+|agents\/[\w.-]+\.md)$/.test(path.replaceAll("\\", "/"))) throw new Error("工作流安装记录包含无效的受管路径。");
475
+ paths.add(path.replaceAll("\\", "/"));
476
+ }
477
+ if (Array.isArray(row.dependencyAssets)) for (const asset of row.dependencyAssets) {
478
+ if (typeof asset.dependency === "string" && /^[\w.-]+$/.test(asset.dependency)) markers.add(asset.dependency);
479
+ for (const name of asset.skills ?? []) {
480
+ if (typeof name !== "string" || !/^[\w.-]+$/.test(name)) throw new Error("工作流依赖记录无效。");
481
+ paths.add(".dsh/skills/" + name);
482
+ names.add(name);
483
+ }
484
+ }
485
+ }
486
+ }
487
+ }
488
+ for (const path of paths) {
489
+ const target = resolve(workspace, path), diff = relative(workspace, target);
490
+ if (!diff || isAbsolute(diff) || diff === ".." || diff.startsWith(".." + sep)) throw new Error("受管路径超出工作区。");
491
+ let parent = dirname(target);
492
+ while (parent !== workspace) try {
493
+ const actual = await realpath(parent), rel = relative(workspace, actual);
494
+ if (isAbsolute(rel) || rel === ".." || rel.startsWith(".." + sep)) throw new Error("受管路径的父目录指向工作区外。");
495
+ break;
496
+ } catch (error) {
497
+ if (error.code !== "ENOENT") throw error;
498
+ parent = dirname(parent);
499
+ }
500
+ }
501
+ return {
502
+ paths: [...paths],
503
+ async retire() {
504
+ if (!descriptor) return;
505
+ for (const path of paths) await rm(join(workspace, path), {
506
+ recursive: true,
507
+ force: true
508
+ });
509
+ for (const file of ["AGENTS.md", "CLAUDE.md"]) {
510
+ const path = join(workspace, file);
511
+ let text;
512
+ try {
513
+ if ((await lstat(path)).isSymbolicLink()) throw new Error("指令文件为符号链接,未修改。");
514
+ text = await readFile(path, "utf8");
515
+ } catch (error) {
516
+ if (error.code === "ENOENT") continue;
517
+ throw error;
518
+ }
519
+ for (const marker of markers) {
520
+ const name = marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
521
+ text = text.replace(new RegExp(`<!-- cannbot:${name}:start -->[\\s\\S]*?<!-- cannbot:${name}:end -->`, "g"), "");
522
+ }
523
+ await writeFile(path, text);
524
+ }
525
+ if (registry) {
526
+ registry.plugins = registry.plugins.filter((row) => row.plugin !== descriptor.id);
527
+ await writeFile(join(workspace, ".dsh/cannbot-plugin.json"), JSON.stringify(registry, null, 2) + "\n");
528
+ }
529
+ const settings = join(workspace, ".cannbot/settings.json");
530
+ try {
531
+ if ((await lstat(settings)).isSymbolicLink()) throw new Error("工作流配置为符号链接,未修改。");
532
+ const data = JSON.parse(await readFile(settings, "utf8"));
533
+ for (const name of names) if (data.plugins && typeof data.plugins === "object") delete data.plugins[name];
534
+ await writeFile(settings, JSON.stringify(data, null, 2) + "\n");
535
+ } catch (error) {
536
+ if (error.code !== "ENOENT") throw error;
537
+ }
538
+ }
539
+ };
540
+ }
541
+ // plugin/contracts/newer-version.ts
542
+ function newerVersion(candidate, current) {
543
+ const next = /^(\d+)\.(\d+)\.(\d+)$/.exec(candidate);
544
+ const old = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(current);
545
+ if (!next || !old) return false;
546
+ for (let index = 1; index < 4; index++) {
547
+ const difference = Number(next[index]) - Number(old[index]);
548
+ if (difference) return difference > 0;
549
+ }
550
+ return /^\d+\.\d+\.\d+-/.test(current);
551
+ }
552
+ const CATALOG_PACKAGE = "@cannbot-plugin/workflow-catalog";
553
+ const REGISTRY = "https://registry.npmjs.org/";
554
+ const MIRROR = "https://registry.npmmirror.com/";
555
+ const validId = (id) => typeof id === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id);
556
+ const validVersion = (version) => typeof version === "string" && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version);
557
+ const npmFetcher = () => createRequire(import.meta.url)("pacote");
558
+ function validateTarball(manifest) {
559
+ if (!validVersion(manifest.version) || !/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(manifest.dist?.integrity ?? "")) throw new Error("Package version or integrity is invalid");
560
+ const url = new URL(manifest.dist.tarball);
561
+ if (url.protocol !== "https:" || !["registry.npmjs.org", "registry.npmmirror.com"].includes(url.hostname) || url.username || url.password || url.port) throw new Error("Unexpected package download origin");
562
+ }
563
+ // plugin/backend/workflow-package-manager.ts
564
+ function inside(root, path) {
565
+ const value = resolve(root, path), diff = relative(resolve(root), value);
566
+ if (diff === ".." || diff.startsWith(`..${sep}`) || isAbsolute(diff)) throw new Error("Workflow resource escapes its package");
567
+ return value;
568
+ }
569
+ function checkedEntry(value) {
570
+ const item = value;
571
+ if (!item || typeof item.id !== "string" || !validId(item.id) || item.package !== "@cannbot-plugin/workflow-" + item.id || typeof item.title !== "string" || item.title.length > 200 || typeof item.default !== "boolean") throw new Error("Invalid workflow catalog entry");
572
+ return item;
573
+ }
574
+ /** npm installs the baseline; a private cache supports independent updates and rollback. */
575
+ var ContentManager = class {
576
+ root;
577
+ index;
578
+ catalog = {
579
+ plugins: [],
580
+ exposedSkills: []
581
+ };
582
+ latest = /* @__PURE__ */ new Map();
583
+ errors = /* @__PURE__ */ new Map();
584
+ descriptors = /* @__PURE__ */ new Map();
585
+ pending;
586
+ pendingKey;
587
+ jobs = /* @__PURE__ */ new Map();
588
+ terminalSpawner;
589
+ setTerminalSpawner(spawn) {
590
+ this.terminalSpawner = spawn;
591
+ }
592
+ listeners = /* @__PURE__ */ new Set();
593
+ preparationGuard;
594
+ stamp = "";
595
+ fetcher;
596
+ registry = REGISTRY;
597
+ /** Workflows declared by the shipped defaults; registry catalogs may not reintroduce others. */
598
+ shipped;
599
+ state = {
600
+ phase: "idle",
601
+ message: "",
602
+ log: ""
603
+ };
604
+ constructor(defaults, root = process.env.CANNBOT_DSH_WORKFLOW_ROOT ?? join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), "cannbot-dsh-workflows"), fetcher = npmFetcher()) {
605
+ this.fetcher = fetcher;
606
+ this.root = resolve(root);
607
+ const entries = JSON.parse(readFileSync(defaults, "utf8")).workflows.map(checkedEntry);
608
+ this.shipped = new Set(entries.map((item) => item.id));
609
+ this.index = {
610
+ schemaVersion: 1,
611
+ entries,
612
+ records: {},
613
+ history: {},
614
+ pinned: []
615
+ };
616
+ try {
617
+ this.reload();
618
+ } catch {}
619
+ }
620
+ subscribe = (listener) => {
621
+ this.listeners.add(listener);
622
+ return () => {
623
+ this.listeners.delete(listener);
624
+ };
625
+ };
626
+ publish(patch) {
627
+ this.state = {
628
+ ...this.state,
629
+ ...patch
630
+ };
631
+ for (const listener of this.listeners) listener();
632
+ }
633
+ options() {
634
+ return {
635
+ registry: this.registry,
636
+ cache: join(this.root, "npm-cache"),
637
+ ignoreScripts: true,
638
+ fullMetadata: true,
639
+ preferOnline: true,
640
+ fetchRetries: 0,
641
+ fetchTimeout: 15e3
642
+ };
643
+ }
644
+ async manifest(spec) {
645
+ let last;
646
+ for (const registry of [this.registry, this.registry === "https://registry.npmjs.org/" ? MIRROR : REGISTRY]) try {
647
+ const value = await this.fetcher.manifest(spec, {
648
+ ...this.options(),
649
+ registry
650
+ });
651
+ this.registry = registry;
652
+ return value;
653
+ } catch (error) {
654
+ last = error;
655
+ }
656
+ throw last;
657
+ }
658
+ async extract(manifest, directory) {
659
+ const options = {
660
+ ...this.options(),
661
+ integrity: manifest.dist.integrity,
662
+ fetchTimeout: 18e4,
663
+ fetchRetries: 1
664
+ };
665
+ try {
666
+ await this.fetcher.extract(manifest.dist.tarball, directory, options);
667
+ return directory;
668
+ } catch (error) {
669
+ await rm(directory, {
670
+ recursive: true,
671
+ force: true
672
+ }).catch(() => {});
673
+ if (String(error.message).includes("EINTEGRITY") || error.code === "EINTEGRITY") throw error;
674
+ const registry = new URL(manifest.dist.tarball).hostname === "registry.npmjs.org" ? MIRROR : REGISTRY;
675
+ const alternative = await this.fetcher.manifest(`${manifest.name}@${manifest.version}`, {
676
+ ...this.options(),
677
+ registry
678
+ });
679
+ validateTarball(alternative);
680
+ if (alternative.name !== manifest.name || alternative.version !== manifest.version || alternative.dist.integrity !== manifest.dist.integrity) throw new Error("Registry mirror disagrees with the selected package integrity");
681
+ const fresh = await mkdtemp(join(dirname(directory), `${manifest.version}-mirror-`));
682
+ try {
683
+ await this.fetcher.extract(alternative.dist.tarball, fresh, options);
684
+ return fresh;
685
+ } catch (error) {
686
+ await rm(fresh, {
687
+ recursive: true,
688
+ force: true
689
+ }).catch(() => {});
690
+ throw error;
691
+ }
692
+ }
693
+ }
694
+ descriptor(record) {
695
+ const entry = this.index.entries.find((item) => item.id === record.id);
696
+ if (!entry || record.package !== entry.package || !validVersion(record.version)) throw new Error("Invalid installed workflow identity");
697
+ const root = inside(this.root, record.directory), manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
698
+ const data = JSON.parse(readFileSync(join(root, "workflow.json"), "utf8"));
699
+ if (manifest.name !== entry.package || manifest.version !== record.version || manifest.cannbotWorkflow?.schemaVersion !== 1 || manifest.cannbotWorkflow.id !== entry.id || data.schemaVersion !== 1 || data.id !== entry.id || data.version !== record.version || typeof data.title !== "string" || !Array.isArray(data.skills) || !data.skills.length) throw new Error("Incompatible workflow package");
700
+ if (Object.keys(manifest.dependencies ?? {}).length || Object.keys(manifest.optionalDependencies ?? {}).length || Object.keys(manifest.scripts ?? {}).length) throw new Error("Workflow packages must contain their own resources and no npm lifecycle scripts");
701
+ const check = (path) => {
702
+ const value = inside(root, path);
703
+ inside(realpathSync(root), realpathSync(value));
704
+ return value;
705
+ };
706
+ const names = /* @__PURE__ */ new Set();
707
+ for (const skill of data.skills) {
708
+ if (!validId(skill.name) || names.has(skill.name) || !/^[a-f0-9]{64}$/.test(skill.hash) || !statSync(check(join("resources", skill.path))).isFile()) throw new Error("Invalid packaged Skill");
709
+ names.add(skill.name);
710
+ }
711
+ if (data.skills.filter((item) => item.entry).length !== 1) throw new Error("Workflow entry Skill is missing");
712
+ if (data.initialization?.kind === "cannbot-cli") check(data.initialization.entry);
713
+ else if (data.initialization?.kind !== "skill-native") throw new Error("Unsupported workflow initializer");
714
+ return data;
715
+ }
716
+ compose() {
717
+ const plugins = [], exposedSkills = [], winners = /* @__PURE__ */ new Map();
718
+ this.descriptors.clear();
719
+ for (const entry of this.index.entries) {
720
+ const record = this.index.records[entry.id];
721
+ if (!record) continue;
722
+ const data = this.descriptor(record), aliases = {};
723
+ this.descriptors.set(entry.id, data);
724
+ const resources = join(record.directory, "resources");
725
+ for (const skill of data.skills) {
726
+ const previous = winners.get(skill.name);
727
+ const name = !previous || previous.hash === skill.hash ? previous?.name ?? skill.name : `${entry.id}-${skill.name}`;
728
+ if (name !== skill.name) aliases[skill.name] = name;
729
+ if (previous?.hash === skill.hash) continue;
730
+ if (exposedSkills.some((item) => item.name === name)) throw new Error("Conflicting workflow Skill aliases");
731
+ if (!previous) winners.set(skill.name, {
732
+ hash: skill.hash,
733
+ name
734
+ });
735
+ exposedSkills.push({
736
+ name,
737
+ originalName: skill.name,
738
+ pluginId: entry.id,
739
+ path: join(resources, skill.path),
740
+ entry: skill.entry
741
+ });
742
+ }
743
+ plugins.push({
744
+ id: entry.id,
745
+ title: data.title,
746
+ aliases,
747
+ version: record.version,
748
+ packageName: record.package,
749
+ resourceDirectory: resources
750
+ });
751
+ }
752
+ const revision = createHash("sha256").update(JSON.stringify(this.index.entries.map((item) => [
753
+ item.id,
754
+ this.index.records[item.id]?.version,
755
+ this.index.records[item.id]?.integrity
756
+ ]))).digest("hex");
757
+ this.catalog = {
758
+ revision,
759
+ plugins,
760
+ exposedSkills
761
+ };
762
+ }
763
+ reload() {
764
+ const file = join(this.root, "active.json"), stat = statSync(file), stamp = `${stat.mtimeMs}:${stat.size}`;
765
+ if (stamp === this.stamp) return;
766
+ const previous = this.index, parsed = JSON.parse(readFileSync(file, "utf8"));
767
+ if (parsed.schemaVersion !== 1 || !Array.isArray(parsed.entries) || !parsed.records || !parsed.history || !Array.isArray(parsed.pinned)) throw new Error("Invalid workflow index");
768
+ parsed.entries.forEach(checkedEntry);
769
+ this.index = parsed;
770
+ try {
771
+ this.compose();
772
+ this.stamp = stamp;
773
+ } catch (error) {
774
+ this.index = previous;
775
+ this.compose();
776
+ throw error;
777
+ }
778
+ }
779
+ refresh() {
780
+ const before = this.catalog.revision;
781
+ try {
782
+ this.reload();
783
+ } catch {}
784
+ if (before !== this.catalog.revision) this.publish({});
785
+ }
786
+ getSource() {
787
+ this.refresh();
788
+ return {
789
+ assets: this.root,
790
+ catalog: this.catalog,
791
+ revision: this.catalog.revision ?? "empty"
792
+ };
793
+ }
794
+ getStatus = () => {
795
+ this.refresh();
796
+ const workflows = this.index.entries.map((entry) => {
797
+ const current = this.index.records[entry.id];
798
+ const previous = (this.index.history[entry.id] ?? []).find((item) => current && newerVersion(current.version, item.version));
799
+ return {
800
+ ...entry,
801
+ installed: !!current,
802
+ version: current?.version,
803
+ latest: this.latest.get(entry.id)?.version,
804
+ previous: previous?.version,
805
+ pinned: this.index.pinned.includes(entry.id),
806
+ error: this.errors.get(entry.id)
807
+ };
808
+ });
809
+ return {
810
+ ...this.state,
811
+ plugins: this.catalog.plugins,
812
+ workflows,
813
+ fallback: !this.catalog.plugins.length,
814
+ busy: !!this.pending || !!this.jobs.size,
815
+ catalogVersion: this.index.catalogVersion
816
+ };
817
+ };
818
+ async save(next) {
819
+ const previous = this.index;
820
+ this.index = next;
821
+ try {
822
+ this.compose();
823
+ } finally {
824
+ this.index = previous;
825
+ this.compose();
826
+ }
827
+ await mkdir(this.root, { recursive: true });
828
+ const temporary = join(this.root, `active-${randomUUID()}.json`);
829
+ try {
830
+ await writeFile(temporary, JSON.stringify(next), { mode: 384 });
831
+ await rename(temporary, join(this.root, "active.json"));
832
+ this.stamp = "";
833
+ this.reload();
834
+ } catch (error) {
835
+ this.index = previous;
836
+ this.compose();
837
+ throw error;
838
+ }
839
+ this.publish({});
840
+ }
841
+ operation(key, action) {
842
+ if (this.pending) return this.pendingKey === key ? this.pending : this.pending.catch(() => {}).then(() => this.operation(key, action));
843
+ this.pendingKey = key;
844
+ this.pending = withContentLock(join(this.root, "operations.lock"), async () => {
845
+ this.refresh();
846
+ await action();
847
+ }).catch((error) => {
848
+ this.publish({
849
+ phase: "error",
850
+ message: String(error.message).slice(-1500)
851
+ });
852
+ throw error;
853
+ }).finally(() => {
854
+ this.pending = void 0;
855
+ this.pendingKey = void 0;
856
+ this.publish({});
857
+ });
858
+ return this.pending;
859
+ }
860
+ installDependencies(catalogFile, resolvePackage, replaceFromSource = false) {
861
+ return this.operation("dependencies", async () => {
862
+ const catalog = JSON.parse(await readFile(catalogFile, "utf8"));
863
+ if (catalog.name !== "@cannbot-plugin/workflow-catalog" || !validVersion(catalog.version) || catalog.cannbotWorkflowCatalog?.schemaVersion !== 1 || !Array.isArray(catalog.cannbotWorkflowCatalog.workflows)) throw new Error("Invalid installed workflow catalog");
864
+ const baseline = catalog.cannbotWorkflowCatalog.workflows.map(checkedEntry).filter((item) => this.shipped.has(item.id));
865
+ if (!baseline.length || new Set(baseline.map((item) => item.id)).size !== baseline.length) throw new Error("Invalid installed workflow entries");
866
+ const newerCatalog = !replaceFromSource && this.index.catalogVersion && newerVersion(this.index.catalogVersion, catalog.version);
867
+ const entries = (newerCatalog ? [...this.index.entries] : [...baseline]).filter((item) => this.shipped.has(item.id));
868
+ for (const old of this.index.entries) if (this.shipped.has(old.id) && !entries.some((item) => item.id === old.id)) entries.push(old);
869
+ const next = {
870
+ ...this.index,
871
+ entries,
872
+ catalogVersion: newerCatalog ? this.index.catalogVersion : catalog.version,
873
+ records: { ...this.index.records },
874
+ history: { ...this.index.history },
875
+ pinned: [...this.index.pinned]
876
+ };
877
+ const dropped = Object.keys(next.records).filter((id) => !this.shipped.has(id));
878
+ for (const id of dropped) delete next.records[id];
879
+ for (const id of Object.keys(next.history)) if (!this.shipped.has(id)) delete next.history[id];
880
+ next.pinned = next.pinned.filter((id) => this.shipped.has(id));
881
+ for (const entry of baseline.filter((item) => item.default)) {
882
+ if (!replaceFromSource && this.index.records[entry.id]) continue;
883
+ if (!catalog.dependencies?.[entry.package]) throw new Error(`Workflow dependency missing: ${entry.package}`);
884
+ const packageFile = resolvePackage(entry.package);
885
+ const manifest = JSON.parse(await readFile(packageFile, "utf8"));
886
+ if (manifest.name !== entry.package || !validVersion(manifest.version)) throw new Error("Incorrect installed workflow dependency");
887
+ const identity = (replaceFromSource ? "source:" : "dependency:") + createHash("sha512").update(await readFile(join(dirname(packageFile), "workflow.json"))).digest("base64");
888
+ if (replaceFromSource && this.index.records[entry.id]?.integrity === identity) continue;
889
+ const parent = join(this.root, "packages", entry.id);
890
+ await mkdir(parent, { recursive: true });
891
+ const directory = await mkdtemp(join(parent, `${manifest.version}-dependency-`));
892
+ await cp(dirname(packageFile), directory, {
893
+ recursive: true,
894
+ dereference: true
895
+ });
896
+ const integrity = identity;
897
+ const record = {
898
+ id: entry.id,
899
+ package: entry.package,
900
+ version: manifest.version,
901
+ integrity,
902
+ directory: relative(this.root, directory).split(sep).join("/"),
903
+ installedAt: (/* @__PURE__ */ new Date()).toISOString(),
904
+ dependency: true
905
+ };
906
+ const previous = this.index;
907
+ try {
908
+ this.index = next;
909
+ this.descriptor(record);
910
+ } finally {
911
+ this.index = previous;
912
+ }
913
+ next.records[entry.id] = record;
914
+ if (replaceFromSource) next.pinned = next.pinned.filter((id) => id !== entry.id);
915
+ }
916
+ await this.save(next);
917
+ for (const id of dropped) await rm(join(this.root, "packages", id), {
918
+ recursive: true,
919
+ force: true
920
+ }).catch(() => {});
921
+ this.publish({
922
+ phase: "ready",
923
+ message: "Installed workflow dependencies are ready."
924
+ });
925
+ });
926
+ }
927
+ async checkPackages() {
928
+ this.registry = REGISTRY;
929
+ this.publish({
930
+ phase: "syncing",
931
+ message: "Checking npm workflow packages…",
932
+ log: ""
933
+ });
934
+ const catalog = await this.manifest(`${CATALOG_PACKAGE}@latest`);
935
+ if (catalog.name !== "@cannbot-plugin/workflow-catalog" || !validVersion(catalog.version) || catalog.cannbotWorkflowCatalog?.schemaVersion !== 1 || !Array.isArray(catalog.cannbotWorkflowCatalog.workflows)) throw new Error("Unsupported workflow catalog");
936
+ const entries = catalog.cannbotWorkflowCatalog.workflows.map(checkedEntry).filter((item) => this.shipped.has(item.id));
937
+ if (!entries.length || new Set(entries.map((item) => item.id)).size !== entries.length) throw new Error("Invalid workflow catalog");
938
+ for (const old of this.index.entries) if (this.shipped.has(old.id) && this.index.records[old.id] && !entries.some((item) => item.id === old.id)) entries.push(old);
939
+ await this.save({
940
+ ...this.index,
941
+ entries,
942
+ catalogVersion: catalog.version
943
+ });
944
+ this.errors.clear();
945
+ for (const entry of entries) try {
946
+ const manifest = await this.manifest(`${entry.package}@latest`);
947
+ this.validateManifest(entry, manifest);
948
+ this.latest.set(entry.id, manifest);
949
+ } catch (error) {
950
+ this.latest.delete(entry.id);
951
+ this.errors.set(entry.id, String(error.message).slice(-300));
952
+ }
953
+ this.publish({
954
+ phase: "ready",
955
+ message: "Workflow versions checked."
956
+ });
957
+ }
958
+ validateManifest(entry, manifest) {
959
+ if (manifest.name !== entry.package || manifest.cannbotWorkflow?.id !== entry.id || manifest.cannbotWorkflow.schemaVersion !== 1) throw new Error("Unsupported workflow package format");
960
+ validateTarball(manifest);
961
+ }
962
+ check() {
963
+ return this.operation("check", () => this.checkPackages());
964
+ }
965
+ sync(id, version) {
966
+ if (version !== void 0 && !validVersion(version)) return Promise.reject(/* @__PURE__ */ new Error("Invalid workflow version"));
967
+ return this.operation(`update:${id ?? "*"}:${version ?? "latest"}`, async () => {
968
+ await this.checkPackages();
969
+ const entries = id ? this.index.entries.filter((item) => item.id === id) : this.index.entries.filter((item) => (item.default || this.index.records[item.id]) && !this.index.pinned.includes(item.id));
970
+ if (id && !entries.length) throw new Error("Unknown workflow");
971
+ const failures = [];
972
+ for (const entry of entries) try {
973
+ const manifest = version ? await this.manifest(`${entry.package}@${version}`) : this.latest.get(entry.id);
974
+ if (!manifest) throw new Error(this.errors.get(entry.id) ?? "Workflow package unavailable");
975
+ this.validateManifest(entry, manifest);
976
+ const previous = this.index.records[entry.id];
977
+ if (previous?.version === manifest.version) {
978
+ if (!previous.dependency && previous.integrity !== manifest.dist.integrity) throw new Error("A published workflow version changed integrity");
979
+ continue;
980
+ }
981
+ if (previous && !newerVersion(manifest.version, previous.version)) continue;
982
+ this.publish({
983
+ phase: "syncing",
984
+ message: `Installing ${entry.id}@${manifest.version}…`,
985
+ log: ""
986
+ });
987
+ const parent = join(this.root, "packages", entry.id);
988
+ await mkdir(parent, { recursive: true });
989
+ let directory = await mkdtemp(join(parent, `${manifest.version}-`));
990
+ let committed = false;
991
+ try {
992
+ directory = await this.extract(manifest, directory);
993
+ const record = {
994
+ id: entry.id,
995
+ package: entry.package,
996
+ version: manifest.version,
997
+ integrity: manifest.dist.integrity,
998
+ directory: relative(this.root, directory).split(sep).join("/"),
999
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
1000
+ };
1001
+ this.descriptor(record);
1002
+ const history = { ...this.index.history };
1003
+ if (previous) history[entry.id] = [previous, ...(history[entry.id] ?? []).filter((item) => item.version !== previous.version)];
1004
+ await this.save({
1005
+ ...this.index,
1006
+ records: {
1007
+ ...this.index.records,
1008
+ [entry.id]: record
1009
+ },
1010
+ history,
1011
+ pinned: this.index.pinned.filter((item) => item !== entry.id)
1012
+ });
1013
+ committed = true;
1014
+ } finally {
1015
+ if (!committed) {
1016
+ let retained = true;
1017
+ try {
1018
+ const active = JSON.parse(await readFile(join(this.root, "active.json"), "utf8"));
1019
+ retained = Object.values(active.records).some((record) => inside(this.root, record.directory) === directory);
1020
+ } catch (error) {
1021
+ if (error.code === "ENOENT") retained = false;
1022
+ }
1023
+ if (!retained) await rm(directory, {
1024
+ recursive: true,
1025
+ force: true
1026
+ }).catch(() => {});
1027
+ }
1028
+ }
1029
+ this.errors.delete(entry.id);
1030
+ } catch (error) {
1031
+ const message = String(error.message).slice(-500);
1032
+ this.errors.set(entry.id, message);
1033
+ failures.push(`${entry.id}: ${message}`);
1034
+ }
1035
+ if (failures.length) throw new Error(failures.join("\n"));
1036
+ this.publish({
1037
+ phase: "ready",
1038
+ message: "Workflow packages are ready."
1039
+ });
1040
+ });
1041
+ }
1042
+ rollback(id) {
1043
+ return this.operation(`rollback:${id}`, async () => {
1044
+ const current = this.index.records[id], previous = (this.index.history[id] ?? []).find((item) => current && newerVersion(current.version, item.version));
1045
+ if (!current || !previous) throw new Error("No earlier workflow version is available");
1046
+ this.descriptor(previous);
1047
+ await this.save({
1048
+ ...this.index,
1049
+ records: {
1050
+ ...this.index.records,
1051
+ [id]: previous
1052
+ },
1053
+ pinned: [.../* @__PURE__ */ new Set([...this.index.pinned, id])]
1054
+ });
1055
+ this.publish({
1056
+ phase: "ready",
1057
+ message: `${id} restored to ${previous.version} and pinned.`
1058
+ });
1059
+ });
1060
+ }
1061
+ async runInitializer(entry, args, cwd) {
1062
+ const io = initializationIO.getStore();
1063
+ if (io) {
1064
+ io.signal.throwIfAborted();
1065
+ if (!this.terminalSpawner) throw new Error("宿主的交互终端尚未就绪,请更新 DSH 后重试。");
1066
+ return runInitializationTerminal(this.terminalSpawner, [
1067
+ process.execPath,
1068
+ entry,
1069
+ ...args
1070
+ ], cwd, io);
1071
+ }
1072
+ let output = "";
1073
+ const controller = new AbortController();
1074
+ const interrupt = () => controller.abort(/* @__PURE__ */ new Error("初始化已取消。"));
1075
+ const interactive = !!process.stdin.isTTY;
1076
+ if (interactive) {
1077
+ process.on("SIGINT", interrupt);
1078
+ process.on("SIGTERM", interrupt);
1079
+ }
1080
+ try {
1081
+ await runProcess(process.execPath, [entry, ...args], {
1082
+ cwd,
1083
+ stdio: interactive ? "inherit" : [
1084
+ "ignore",
1085
+ "pipe",
1086
+ "pipe"
1087
+ ],
1088
+ timeoutMs: 12e5,
1089
+ signal: controller.signal,
1090
+ env: {
1091
+ ...process.env,
1092
+ ...process.versions.electron ? { ELECTRON_RUN_AS_NODE: "1" } : {},
1093
+ GIT_TERMINAL_PROMPT: "0",
1094
+ GCM_INTERACTIVE: "never"
1095
+ },
1096
+ onData: (data) => {
1097
+ output = (output + data).slice(-16e3);
1098
+ this.publish({ log: output.slice(-6e3) });
1099
+ }
1100
+ });
1101
+ } catch (error) {
1102
+ throw new Error(`${error.message}\n${output.slice(-1500)}`);
1103
+ } finally {
1104
+ if (interactive) {
1105
+ process.off("SIGINT", interrupt);
1106
+ process.off("SIGTERM", interrupt);
1107
+ }
1108
+ }
1109
+ }
1110
+ setPreparationGuard(guard) {
1111
+ this.preparationGuard = guard;
1112
+ }
1113
+ async switchWorkflow(cwd, previous, next, commit, committed, commitToken) {
1114
+ this.refresh();
1115
+ for (const id of [previous, next]) if (id !== "general" && !this.index.records[id]) await this.sync(id);
1116
+ const oldRecord = this.index.records[previous], nextRecord = this.index.records[next];
1117
+ const old = oldRecord && this.descriptor(oldRecord);
1118
+ const descriptor = nextRecord ? this.descriptor(nextRecord) : {
1119
+ schemaVersion: 1,
1120
+ id: "general",
1121
+ title: "空白工作区",
1122
+ version: "0.0.0",
1123
+ initialization: { kind: "skill-native" },
1124
+ skills: [],
1125
+ source: {
1126
+ repository: "",
1127
+ commit: "",
1128
+ skillsCommit: ""
1129
+ }
1130
+ };
1131
+ const workspace = await realpath(cwd), key = createHash("sha256").update(workspace).digest("hex");
1132
+ const base = join(this.root, "initialized", key), root = nextRecord ? inside(this.root, nextRecord.directory) : this.root;
1133
+ await withContentLock(join(base, "workspace.lock"), async () => {
1134
+ await recoverInitialization(workspace, join(base, "switch-recovery"), committed);
1135
+ const retirement = await workflowRetirement(workspace, old);
1136
+ const archive = join(base, "retired", randomUUID());
1137
+ for (const path of retirement.paths) if (existsSync(join(workspace, path))) {
1138
+ await mkdir(dirname(join(archive, path)), { recursive: true });
1139
+ await cp(join(workspace, path), join(archive, path), {
1140
+ recursive: true,
1141
+ dereference: false,
1142
+ verbatimSymlinks: true
1143
+ });
1144
+ }
1145
+ await initializeTransaction(workspace, join(base, "switch-recovery"), descriptor, join(root, "resources"), async () => {
1146
+ initializationIO.getStore()?.signal.throwIfAborted();
1147
+ await retirement.retire();
1148
+ if (descriptor.initialization.kind === "cannbot-cli") await this.runInitializer(inside(root, descriptor.initialization.entry), [
1149
+ "install",
1150
+ next,
1151
+ "--tool",
1152
+ "dsh",
1153
+ "--target",
1154
+ workspace,
1155
+ "--plugin-dir",
1156
+ join(root, "resources")
1157
+ ], workspace);
1158
+ initializationIO.getStore()?.signal.throwIfAborted();
1159
+ await commit();
1160
+ }, retirement.paths, committed, commitToken);
1161
+ for (const id of [previous, next]) await rm(join(base, id + ".json"), { force: true }).catch(() => {});
1162
+ if (nextRecord) await writeFile(join(base, next + ".json"), JSON.stringify({
1163
+ workspace,
1164
+ id: next,
1165
+ package: nextRecord.package,
1166
+ version: nextRecord.version,
1167
+ integrity: nextRecord.integrity
1168
+ }), { mode: 384 }).catch(() => {});
1169
+ });
1170
+ }
1171
+ async prepare(cwd, id) {
1172
+ const run = () => this.prepareContent(cwd, id);
1173
+ return this.preparationGuard ? this.preparationGuard(cwd, id, run) : run();
1174
+ }
1175
+ async prepareContent(cwd, id) {
1176
+ if (!validId(id)) throw new Error("Invalid workflow");
1177
+ this.refresh();
1178
+ if (!this.index.records[id]) {
1179
+ if (this.pending) await this.pending.catch(() => {});
1180
+ if (!this.index.records[id]) await this.sync(id);
1181
+ }
1182
+ const record = this.index.records[id];
1183
+ if (!record) throw new Error("Workflow package is not installed");
1184
+ const descriptor = this.descriptor(record), workspace = await realpath(cwd);
1185
+ const key = createHash("sha256").update(workspace).digest("hex"), receipt = JSON.stringify({
1186
+ workspace,
1187
+ id,
1188
+ package: record.package,
1189
+ version: record.version,
1190
+ integrity: record.integrity
1191
+ });
1192
+ const marker = join(this.root, "initialized", key, `${id}.json`), jobKey = `${key}:${id}:${record.version}:${record.integrity}`;
1193
+ let job = this.jobs.get(jobKey);
1194
+ if (!job) {
1195
+ job = withContentLock(join(this.root, "initialized", key, "workspace.lock"), async () => {
1196
+ const recoveryRoot = join(this.root, "initialized", key, "recovery");
1197
+ const skillsPresent = descriptor.skills.every((skill) => existsSync(join(workspace, ".dsh/skills", skill.name, "SKILL.md")));
1198
+ if (await readFile(marker, "utf8").catch(() => "") === receipt && !existsSync(join(recoveryRoot, "recovery.json")) && (descriptor.initialization.kind !== "cannbot-cli" || skillsPresent)) return;
1199
+ this.publish({
1200
+ phase: "initializing",
1201
+ message: `Preparing ${id}@${record.version} for this workspace…`,
1202
+ log: ""
1203
+ });
1204
+ if (descriptor.initialization.kind === "cannbot-cli") {
1205
+ const root = inside(this.root, record.directory);
1206
+ const entry = inside(root, descriptor.initialization.entry);
1207
+ await initializeTransaction(workspace, recoveryRoot, descriptor, join(root, "resources"), () => this.runInitializer(entry, [
1208
+ "install",
1209
+ id,
1210
+ "--tool",
1211
+ "dsh",
1212
+ "--target",
1213
+ workspace,
1214
+ "--plugin-dir",
1215
+ join(root, "resources")
1216
+ ], workspace));
1217
+ }
1218
+ initializationIO.getStore()?.signal.throwIfAborted();
1219
+ await writeFile(marker, receipt, { mode: 384 });
1220
+ this.publish({
1221
+ phase: "ready",
1222
+ message: `${id} is ready for this workspace.`
1223
+ });
1224
+ }).catch((error) => {
1225
+ this.publish({
1226
+ phase: "error",
1227
+ message: String(error.message).slice(-1500)
1228
+ });
1229
+ throw error;
1230
+ }).finally(() => {
1231
+ this.jobs.delete(jobKey);
1232
+ this.publish({});
1233
+ });
1234
+ this.jobs.set(jobKey, job);
1235
+ }
1236
+ await job;
1237
+ this.refresh();
1238
+ const current = this.index.records[id];
1239
+ if (current.version !== record.version || current.integrity !== record.integrity) await this.prepareContent(cwd, id);
1240
+ }
1241
+ };
1242
+ // plugin/contracts/workspace-mode-types.ts
1243
+ /** Shared wire contract. Unregistered workspaces and sessions belong to DeepSeek. */
1244
+ const CANNBOT_WORKSPACES_PATH = "api/cannbot-dsh/workspaces";
1245
+ function sessionActivity(value) {
1246
+ if (!Array.isArray(value)) return [];
1247
+ const clean = (value) => typeof value === "string" ? value.slice(0, 512).replace(/[\x00-\x1f\x7f]/g, "").replace(/https?:\/\/[^\s]+/gi, "[地址]").replace(/(token\s*[=:]\s*)[^\s&]+/gi, "$1[已隐藏]") : "";
1248
+ return value.slice(0, 100).flatMap((entry) => {
1249
+ if (!entry || typeof entry !== "object" || typeof entry.kind !== "string") return [];
1250
+ const kind = clean(entry.kind);
1251
+ if (!kind) return [];
1252
+ const items = Array.isArray(entry.items) ? entry.items.slice(0, 100).flatMap((item) => {
1253
+ if (!item || typeof item.id !== "string" || !clean(item.id)) return [];
1254
+ return [{
1255
+ id: clean(item.id),
1256
+ ...typeof item.label === "string" ? { label: clean(item.label) } : {}
1257
+ }];
1258
+ }) : void 0;
1259
+ return [{
1260
+ kind,
1261
+ ...items ? { items } : {}
1262
+ }];
1263
+ });
1264
+ }
1265
+ /** Project only the fixed operation contract; never forward arbitrary URL/body fields. */
1266
+ function workspaceOperation(value) {
1267
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
1268
+ const data = value;
1269
+ const id = (value) => typeof value === "string" && value.length > 0 && value.length <= 2e3 && !/[\s\x00-\x1f\x7f]/.test(value);
1270
+ const title = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= 2e3 && !/[\x00-\x1f\x7f]/.test(value);
1271
+ if (data.action === "rename-workspace" && id(data.workspaceId) && title(data.title)) return {
1272
+ action: data.action,
1273
+ workspaceId: data.workspaceId,
1274
+ title: data.title.trim()
1275
+ };
1276
+ if (data.action === "remove-workspace" && id(data.workspaceId)) return {
1277
+ action: data.action,
1278
+ workspaceId: data.workspaceId
1279
+ };
1280
+ if (data.action === "switch-workflow" && id(data.workspaceId) && typeof data.pluginId === "string" && /^[\w-]{1,100}$/.test(data.pluginId)) return {
1281
+ action: data.action,
1282
+ workspaceId: data.workspaceId,
1283
+ pluginId: data.pluginId
1284
+ };
1285
+ if (!id(data.sessionId)) return;
1286
+ if (data.action === "rename-session" && title(data.title)) return {
1287
+ action: data.action,
1288
+ sessionId: data.sessionId,
1289
+ title: data.title.trim()
1290
+ };
1291
+ if (data.action === "fork-session" && (data.allowMigration === void 0 || typeof data.allowMigration === "boolean")) return {
1292
+ action: data.action,
1293
+ sessionId: data.sessionId,
1294
+ ...typeof data.allowMigration === "boolean" ? { allowMigration: data.allowMigration } : {}
1295
+ };
1296
+ if (data.action === "pin-session" || data.action === "unpin-session" || data.action === "unarchive-session") return {
1297
+ action: data.action,
1298
+ sessionId: data.sessionId
1299
+ };
1300
+ if (data.action === "archive-session" && (data.stopActivity === void 0 || typeof data.stopActivity === "boolean")) return {
1301
+ action: data.action,
1302
+ sessionId: data.sessionId,
1303
+ ...data.stopActivity === true ? { stopActivity: true } : {}
1304
+ };
1305
+ }
1306
+ // plugin/backend/workspace-mode.ts
1307
+ var WorkspaceModeError = class extends Error {
1308
+ code;
1309
+ status;
1310
+ constructor(code, message, status = 409) {
1311
+ super(message);
1312
+ this.name = "WorkspaceModeError";
1313
+ this.code = code;
1314
+ this.status = status;
1315
+ }
1316
+ };
1317
+ const emptyState = () => ({
1318
+ schemaVersion: 1,
1319
+ workspaces: [],
1320
+ sessions: []
1321
+ });
1322
+ const pathKey = (path) => process.platform === "win32" ? path.toLowerCase() : path;
1323
+ const validString = (value) => typeof value === "string" && value.length > 0 && value.length <= 32768 && !value.includes("\0");
1324
+ const samePath = (left, right) => pathKey(left) === pathKey(right);
1325
+ /** Explicit view membership and directory ownership, shared by every plugin entry point.
1326
+ * Locks and receipts live in Host state, never in the selected empty directory.
1327
+ * A failed preparation retains its reservation so only the same plugin may retry.
1328
+ */
1329
+ var WorkspaceModes = class {
1330
+ root;
1331
+ dependencies;
1332
+ held = new AsyncLocalStorage();
1333
+ constructor(root, dependencies) {
1334
+ this.root = resolve(root);
1335
+ this.dependencies = dependencies;
1336
+ }
1337
+ async read() {
1338
+ let text;
1339
+ try {
1340
+ text = await readFile(join(this.root, "state.json"), "utf8");
1341
+ } catch (error) {
1342
+ if (error.code === "ENOENT") return emptyState();
1343
+ throw error;
1344
+ }
1345
+ try {
1346
+ const state = JSON.parse(text);
1347
+ if (state.schemaVersion !== 1 || !Array.isArray(state.workspaces) || !Array.isArray(state.sessions)) throw new Error();
1348
+ const paths = /* @__PURE__ */ new Set(), sessions = /* @__PURE__ */ new Set(), workspaces = /* @__PURE__ */ new Set();
1349
+ for (const item of state.workspaces) {
1350
+ if (item.generation !== void 0 && (!Number.isSafeInteger(item.generation) || item.generation < 0)) throw new Error();
1351
+ if (item.switchingTo !== void 0 && !validString(item.switchingTo)) throw new Error();
1352
+ if (!validString(item.path) || !isAbsolute(item.path) || !validString(item.identity) || !validString(item.pluginId) || !["preparing", "ready"].includes(item.status) || paths.has(pathKey(item.path))) throw new Error();
1353
+ paths.add(pathKey(item.path));
1354
+ if (item.status === "ready" && (!validString(item.workspaceId) || typeof item.sharedWithDeepSeek !== "boolean")) throw new Error();
1355
+ if (item.workspaceId) {
1356
+ if (workspaces.has(item.workspaceId)) throw new Error();
1357
+ workspaces.add(item.workspaceId);
1358
+ }
1359
+ }
1360
+ for (const item of state.sessions) {
1361
+ if (!validString(item.sessionId) || !validString(item.workspaceId) || !validString(item.pluginId) || sessions.has(item.sessionId)) throw new Error();
1362
+ const owner = state.workspaces.find((workspace) => workspace.workspaceId === item.workspaceId);
1363
+ if (!owner || owner.status !== "ready") throw new Error();
1364
+ if (item.generation !== void 0 && (!Number.isSafeInteger(item.generation) || item.generation < 0)) throw new Error();
1365
+ sessions.add(item.sessionId);
1366
+ }
1367
+ return state;
1368
+ } catch {
1369
+ throw new WorkspaceModeError("invalid-mode-state", "CANNBot workspace state is invalid; restore its backup before continuing.", 503);
1370
+ }
1371
+ }
1372
+ async change(action) {
1373
+ return withContentLock(join(this.root, "state.lock"), async () => {
1374
+ const state = await this.read(), result = action(state);
1375
+ await mkdir(this.root, { recursive: true });
1376
+ const temporary = join(this.root, `state-${randomUUID()}.tmp`);
1377
+ try {
1378
+ await writeFile(temporary, JSON.stringify(state), {
1379
+ encoding: "utf8",
1380
+ mode: 384,
1381
+ flush: true
1382
+ });
1383
+ await rename(temporary, join(this.root, "state.json"));
1384
+ } finally {
1385
+ await unlink(temporary).catch((error) => {
1386
+ if (error.code !== "ENOENT") throw error;
1387
+ });
1388
+ }
1389
+ return result;
1390
+ });
1391
+ }
1392
+ async directory(path) {
1393
+ if (!validString(path) || !isAbsolute(path)) throw new WorkspaceModeError("invalid-directory", "Choose an existing absolute directory.", 400);
1394
+ let canonical, info;
1395
+ try {
1396
+ canonical = await realpath(path);
1397
+ info = await stat(canonical);
1398
+ } catch {
1399
+ throw new WorkspaceModeError("invalid-directory", "The selected directory is unavailable.", 400);
1400
+ }
1401
+ if (!info.isDirectory()) throw new WorkspaceModeError("invalid-directory", "The selected path is not a directory.", 400);
1402
+ return {
1403
+ path: canonical,
1404
+ key: pathKey(canonical),
1405
+ identity: `${info.dev}:${info.ino}`
1406
+ };
1407
+ }
1408
+ checkWorkflowPlatform(pluginId) {
1409
+ if (pluginId !== "general" && (this.dependencies.platform ?? process.platform) !== "linux") throw new WorkspaceModeError("workflow-linux-only", "本工作流需要在 Linux 环境中初始化。", 400);
1410
+ }
1411
+ check(binding, directory, pluginId) {
1412
+ if (!binding) return;
1413
+ if (binding.identity !== directory.identity) throw new WorkspaceModeError("directory-replaced", "This path now identifies a different directory; choose a new empty directory.");
1414
+ if (binding.pluginId !== pluginId) throw new WorkspaceModeError("plugin-conflict", "This directory is bound to another CANNBot workflow. Choose a different empty directory.");
1415
+ }
1416
+ async locked(path, pluginId, action) {
1417
+ const directory = await this.directory(path), held = this.held.getStore();
1418
+ if (held?.key === directory.key) {
1419
+ if (held.pluginId !== pluginId) throw new WorkspaceModeError("plugin-conflict", "A different workflow is already initializing this directory.");
1420
+ return action(directory);
1421
+ }
1422
+ const key = createHash("sha256").update(directory.key).digest("hex");
1423
+ return withContentLock(join(this.root, "directories", key + ".lock"), async () => {
1424
+ const current = await this.directory(path);
1425
+ if (current.key !== directory.key || current.identity !== directory.identity) throw new WorkspaceModeError("directory-replaced", "The selected directory changed while waiting; choose it again.");
1426
+ return this.held.run({
1427
+ key: directory.key,
1428
+ pluginId
1429
+ }, () => action(current));
1430
+ });
1431
+ }
1432
+ /** Installed as ContentManager's preparation guard, including legacy routes and agent initialization. */
1433
+ async withPreparation(path, pluginId, prepare) {
1434
+ return this.locked(path, pluginId, async (directory) => {
1435
+ const binding = (await this.read()).workspaces.find((item) => samePath(item.path, directory.path));
1436
+ if (binding?.switchingTo === pluginId && this.held.getStore()?.pluginId === pluginId) this.check({
1437
+ ...binding,
1438
+ pluginId
1439
+ }, directory, pluginId);
1440
+ else {
1441
+ if (binding?.switchingTo) throw new WorkspaceModeError("workflow-switching", "工作流正在切换,请等待初始化完成。");
1442
+ this.check(binding, directory, pluginId);
1443
+ }
1444
+ this.checkWorkflowPlatform(pluginId);
1445
+ return prepare();
1446
+ });
1447
+ }
1448
+ async create(path, pluginId) {
1449
+ if (!validString(pluginId) || pluginId !== "general" && !this.dependencies.available(pluginId)) throw new WorkspaceModeError("invalid-plugin", "Choose one installed CANNBot workflow.", 400);
1450
+ this.checkWorkflowPlatform(pluginId);
1451
+ const selected = await this.directory(path), diff = relative(selected.path, this.root);
1452
+ if (!diff || !diff.startsWith(".." + sep) && diff !== ".." && !isAbsolute(diff)) throw new WorkspaceModeError("invalid-directory", "Choose a project directory outside CANNBot state.", 400);
1453
+ return this.locked(path, pluginId, async (directory) => {
1454
+ let binding = (await this.read()).workspaces.find((item) => samePath(item.path, directory.path));
1455
+ this.check(binding, directory, pluginId);
1456
+ if (!binding) {
1457
+ if ((await readdir(directory.path)).length) throw new WorkspaceModeError("directory-not-empty", "CANNBot setup requires an empty directory. Choose or create another directory.");
1458
+ binding = {
1459
+ path: directory.path,
1460
+ identity: directory.identity,
1461
+ pluginId,
1462
+ status: "preparing"
1463
+ };
1464
+ await this.change((state) => {
1465
+ state.workspaces.push(binding);
1466
+ });
1467
+ }
1468
+ if (pluginId !== "general") await this.dependencies.prepare(directory.path, pluginId);
1469
+ initializationIO.getStore()?.signal.throwIfAborted();
1470
+ const result = await this.dependencies.createWorkspace(directory.path);
1471
+ if (!samePath((await this.directory(result.workspace.path)).path, directory.path)) throw new WorkspaceModeError("workspace-mismatch", "Host registered a different workspace directory.", 500);
1472
+ const ready = {
1473
+ ...binding,
1474
+ awaitingHostRegistration: false,
1475
+ status: "ready",
1476
+ workspaceId: result.workspace.workspaceId,
1477
+ sharedWithDeepSeek: binding.sharedWithDeepSeek ?? !result.created
1478
+ };
1479
+ await this.change((state) => {
1480
+ const index = state.workspaces.findIndex((item) => samePath(item.path, directory.path));
1481
+ if (index < 0) throw new WorkspaceModeError("invalid-mode-state", "Workspace reservation disappeared.", 503);
1482
+ if (binding.workspaceId && binding.workspaceId !== ready.workspaceId) {
1483
+ for (const session of state.sessions) if (session.workspaceId === binding.workspaceId) session.workspaceId = ready.workspaceId;
1484
+ }
1485
+ state.workspaces[index] = ready;
1486
+ });
1487
+ return this.workspaceView(ready, result.workspace, (await this.read()).sessions);
1488
+ });
1489
+ }
1490
+ workspaceView(binding, workspace, sessions) {
1491
+ return {
1492
+ workspaceId: workspace.workspaceId,
1493
+ path: binding.path,
1494
+ title: workspace.title,
1495
+ pluginId: binding.pluginId,
1496
+ sharedWithDeepSeek: binding.sharedWithDeepSeek === true,
1497
+ sessionIds: sessions.filter((item) => item.workspaceId === workspace.workspaceId).map((item) => item.sessionId)
1498
+ };
1499
+ }
1500
+ async prepareBeforeLaunch(path, pluginId) {
1501
+ this.checkWorkflowPlatform(pluginId);
1502
+ if (pluginId !== "general" && !this.dependencies.available(pluginId)) throw new WorkspaceModeError("invalid-plugin", "请选择已安装的工作流。", 400);
1503
+ await this.locked(path, pluginId, async (directory) => {
1504
+ const binding = (await this.read()).workspaces.find((item) => samePath(item.path, directory.path));
1505
+ this.check(binding, directory, pluginId);
1506
+ if (binding?.status === "ready") throw new WorkspaceModeError("workspace-exists", "已有工作区请在 CANNBot 中切换工作流。");
1507
+ if (!binding) {
1508
+ if ((await readdir(directory.path)).length) throw new WorkspaceModeError("directory-not-empty", "请选择一个空目录。");
1509
+ await this.change((state) => {
1510
+ state.workspaces.push({
1511
+ path: directory.path,
1512
+ identity: directory.identity,
1513
+ pluginId,
1514
+ status: "preparing"
1515
+ });
1516
+ });
1517
+ }
1518
+ if (pluginId !== "general") await this.dependencies.prepare(directory.path, pluginId);
1519
+ await this.change((state) => {
1520
+ state.workspaces.find((item) => samePath(item.path, directory.path)).awaitingHostRegistration = true;
1521
+ });
1522
+ });
1523
+ }
1524
+ async registerPreparedWorkspaces() {
1525
+ for (const binding of (await this.read()).workspaces) if (binding.status === "preparing" && binding.awaitingHostRegistration) await this.create(binding.path, binding.pluginId);
1526
+ }
1527
+ async switchWorkflow(workspaceId, pluginId) {
1528
+ if (pluginId !== "general" && !this.dependencies.available(pluginId)) throw new WorkspaceModeError("invalid-plugin", "请选择已安装的工作流。", 400);
1529
+ this.checkWorkflowPlatform(pluginId);
1530
+ const original = (await this.read()).workspaces.find((item) => item.workspaceId === workspaceId && item.status === "ready");
1531
+ if (!original) throw new WorkspaceModeError("unknown-workspace", "工作区不存在。", 404);
1532
+ await this.locked(original.path, pluginId, async (directory) => {
1533
+ const binding = (await this.read()).workspaces.find((item) => item.workspaceId === workspaceId);
1534
+ this.check(binding, directory, binding.pluginId);
1535
+ if (binding.switchingTo && binding.switchingTo !== pluginId) throw new WorkspaceModeError("workflow-switching", "上次切换尚未完成,请先重试同一工作流以恢复配置。");
1536
+ if (binding.pluginId === pluginId && !binding.switchingTo) return;
1537
+ if (!this.dependencies.switchWorkflow || !this.dependencies.sessionActivity) throw new WorkspaceModeError("operation-unavailable", "当前宿主不支持安全切换工作流。", 503);
1538
+ const workspace = (await this.dependencies.listWorkspaces()).find((item) => item.workspaceId === workspaceId && samePath(resolve(item.path), binding.path));
1539
+ if (!workspace) throw new WorkspaceModeError("unknown-workspace", "工作区已被移除。", 404);
1540
+ await this.change((state) => {
1541
+ state.workspaces.find((item) => item.workspaceId === workspaceId).switchingTo = pluginId;
1542
+ });
1543
+ try {
1544
+ for (const id of workspace.sessionIds) if ((await this.dependencies.sessionActivity(id)).length) throw new WorkspaceModeError("workflow-active", "工作区仍有运行中的会话、后台任务或定时任务。请先停止或等待完成,再切换工作流。");
1545
+ initializationIO.getStore()?.signal.throwIfAborted();
1546
+ const commitToken = randomUUID();
1547
+ await this.dependencies.switchWorkflow(directory.path, binding.pluginId, pluginId, async () => {
1548
+ initializationIO.getStore()?.signal.throwIfAborted();
1549
+ await this.change((state) => {
1550
+ const current = state.workspaces.find((item) => item.workspaceId === workspaceId);
1551
+ current.pluginId = pluginId;
1552
+ current.generation = (current.generation ?? 0) + 1;
1553
+ current.switchToken = commitToken;
1554
+ delete current.switchingTo;
1555
+ });
1556
+ }, async (token) => {
1557
+ const current = (await this.read()).workspaces.find((item) => item.workspaceId === workspaceId);
1558
+ return !!token && current?.switchToken === token;
1559
+ }, commitToken);
1560
+ } catch (error) {
1561
+ if (!error.recoveryFailed) await this.change((state) => {
1562
+ delete state.workspaces.find((item) => item.workspaceId === workspaceId).switchingTo;
1563
+ });
1564
+ throw error;
1565
+ }
1566
+ });
1567
+ }
1568
+ async recordSession(workspaceId, sessionId) {
1569
+ if (!validString(workspaceId) || !validString(sessionId)) throw new WorkspaceModeError("invalid-session", "Workspace and session are required.", 400);
1570
+ let binding = (await this.read()).workspaces.find((item) => item.workspaceId === workspaceId && item.status === "ready");
1571
+ if (!binding) throw new WorkspaceModeError("unknown-workspace", "Create a CANNBot workspace before starting its session.", 404);
1572
+ return this.locked(binding.path, binding.pluginId, async (directory) => {
1573
+ binding = (await this.read()).workspaces.find((item) => item.workspaceId === workspaceId && item.status === "ready");
1574
+ if (!binding || binding.switchingTo) throw new WorkspaceModeError("workflow-switching", "工作流正在切换,请等待初始化完成。");
1575
+ this.check(binding, directory, binding.pluginId);
1576
+ const workspace = (await this.dependencies.listWorkspaces()).find((item) => item.workspaceId === workspaceId);
1577
+ if (!workspace || !samePath((await this.directory(workspace.path)).path, directory.path)) throw new WorkspaceModeError("unknown-workspace", "This CANNBot workspace is no longer registered.", 404);
1578
+ if (!workspace.sessionIds.includes(sessionId)) throw new WorkspaceModeError("session-workspace-mismatch", "Host has not registered this session in the selected workspace.");
1579
+ const session = await this.dependencies.readSession(sessionId);
1580
+ await this.workflowForSession(sessionId);
1581
+ if (session.sessionId !== sessionId || !samePath((await this.directory(session.cwd)).path, directory.path)) throw new WorkspaceModeError("session-workspace-mismatch", "The session does not belong to this workspace.");
1582
+ const record = {
1583
+ sessionId,
1584
+ workspaceId,
1585
+ pluginId: binding.pluginId,
1586
+ generation: binding.generation ?? 0
1587
+ };
1588
+ await this.change((current) => {
1589
+ const previous = current.sessions.find((item) => item.sessionId === sessionId);
1590
+ if (previous && (previous.generation ?? 0) !== record.generation) throw new WorkspaceModeError("session-frozen", "此会话已冻结,请新建会话。");
1591
+ if (previous && (previous.workspaceId !== workspaceId || previous.pluginId !== record.pluginId)) throw new WorkspaceModeError("session-conflict", "This session is already bound to another CANNBot workspace.");
1592
+ if (!previous) current.sessions.push(record);
1593
+ });
1594
+ return {
1595
+ ...record,
1596
+ title: session.title,
1597
+ updatedAt: session.updatedAt,
1598
+ archived: session.archived,
1599
+ pinned: session.pinned,
1600
+ ...typeof session.blank === "boolean" ? { blank: session.blank } : {},
1601
+ ...typeof session.running === "boolean" ? { running: session.running } : {},
1602
+ ...session.pinned === true && Number.isSafeInteger(session.pinOrder) && session.pinOrder >= 0 ? { pinOrder: session.pinOrder } : {}
1603
+ };
1604
+ });
1605
+ }
1606
+ /** Mutations require persisted CANNBot membership, never just a shared cwd.
1607
+ * Native deletion leaves our directory/plugin receipts and session ownership intact.
1608
+ */
1609
+ async operate(request) {
1610
+ if (request.action === "switch-workflow") {
1611
+ await this.switchWorkflow(request.workspaceId, request.pluginId);
1612
+ return { ok: true };
1613
+ }
1614
+ const state = await this.read();
1615
+ const unavailable = () => new WorkspaceModeError("operation-unavailable", "当前 DSH 不支持此操作,请更新后重试。", 503);
1616
+ if ("workspaceId" in request) {
1617
+ const binding = state.workspaces.find((item) => item.status === "ready" && item.workspaceId === request.workspaceId);
1618
+ if (!binding) throw new WorkspaceModeError("unknown-workspace", "该工作区不属于 CANNBot。", 404);
1619
+ const workspace = (await this.dependencies.listWorkspaces()).find((item) => item.workspaceId === request.workspaceId);
1620
+ if (!workspace || !samePath(resolve(workspace.path), binding.path)) throw new WorkspaceModeError("unknown-workspace", "该工作区已被移除,请刷新列表。", 404);
1621
+ if (request.action === "rename-workspace") {
1622
+ if (!this.dependencies.renameWorkspace) throw unavailable();
1623
+ await this.dependencies.renameWorkspace(request.workspaceId, request.title);
1624
+ } else {
1625
+ if (!this.dependencies.removeWorkspace) throw unavailable();
1626
+ await this.dependencies.removeWorkspace(request.workspaceId);
1627
+ }
1628
+ return { ok: true };
1629
+ }
1630
+ const record = state.sessions.find((item) => item.sessionId === request.sessionId);
1631
+ const binding = record && state.workspaces.find((item) => item.status === "ready" && item.workspaceId === record.workspaceId);
1632
+ if (!record || !binding) throw new WorkspaceModeError("unknown-session", "该会话不属于 CANNBot。", 404);
1633
+ const session = await this.dependencies.readSession(request.sessionId);
1634
+ if (session.sessionId !== record.sessionId || !samePath(resolve(session.cwd), binding.path)) throw new WorkspaceModeError("session-workspace-mismatch", "会话与其登记的工作区不一致。");
1635
+ switch (request.action) {
1636
+ case "rename-session":
1637
+ if (!this.dependencies.renameSession) throw unavailable();
1638
+ await this.dependencies.renameSession(request.sessionId, request.title);
1639
+ break;
1640
+ case "fork-session": {
1641
+ await this.workflowForSession(request.sessionId);
1642
+ if (!this.dependencies.forkSession) throw unavailable();
1643
+ const child = await this.dependencies.forkSession(request.sessionId, request.allowMigration);
1644
+ if (!validString(child?.sessionId) || child.sessionId === request.sessionId) throw new WorkspaceModeError("invalid-session", "DSH 未返回可用的分支会话。", 502);
1645
+ const observed = await this.dependencies.readSession(child.sessionId);
1646
+ if (observed.sessionId !== child.sessionId || !samePath(resolve(observed.cwd), binding.path)) throw new WorkspaceModeError("session-workspace-mismatch", "分支会话与原会话工作区不一致。");
1647
+ await this.change((current) => {
1648
+ const owner = current.sessions.find((item) => item.sessionId === record.sessionId);
1649
+ if (!owner || owner.workspaceId !== record.workspaceId || owner.pluginId !== record.pluginId) throw new WorkspaceModeError("session-conflict", "原会话归属已改变,请刷新后重试。");
1650
+ const previous = current.sessions.find((item) => item.sessionId === child.sessionId);
1651
+ if (previous && (previous.workspaceId !== record.workspaceId || previous.pluginId !== record.pluginId)) throw new WorkspaceModeError("session-conflict", "分支会话已有其他归属。");
1652
+ if (!previous) current.sessions.push({
1653
+ ...record,
1654
+ sessionId: child.sessionId
1655
+ });
1656
+ });
1657
+ if (session.title !== void 0) {
1658
+ if (!this.dependencies.renameSession) throw unavailable();
1659
+ const ascii = /^(.*?)\((\d+)\)$/u.exec(session.title), wide = /^(.*?)((\d+))$/u.exec(session.title);
1660
+ const title = ascii ? `${ascii[1]}(${BigInt(ascii[2]) + 1n})` : wide ? `${wide[1]}(${BigInt(wide[2]) + 1n})` : `${session.title} (1)`;
1661
+ await this.dependencies.renameSession(child.sessionId, title);
1662
+ }
1663
+ return {
1664
+ ok: true,
1665
+ sessionId: child.sessionId
1666
+ };
1667
+ }
1668
+ case "archive-session":
1669
+ if (!this.dependencies.archiveSession) throw unavailable();
1670
+ await this.dependencies.archiveSession(request.sessionId, request.stopActivity === true);
1671
+ break;
1672
+ case "unarchive-session":
1673
+ if (!this.dependencies.unarchiveSession) throw unavailable();
1674
+ await this.dependencies.unarchiveSession(request.sessionId);
1675
+ break;
1676
+ case "pin-session":
1677
+ if (!this.dependencies.pinSession) throw unavailable();
1678
+ await this.dependencies.pinSession(request.sessionId);
1679
+ break;
1680
+ case "unpin-session":
1681
+ if (!this.dependencies.unpinSession) throw unavailable();
1682
+ await this.dependencies.unpinSession(request.sessionId);
1683
+ }
1684
+ return { ok: true };
1685
+ }
1686
+ /** A persisted CANNBot session cannot switch its workflow through legacy settings. */
1687
+ async workflowForSession(sessionId, requested) {
1688
+ const state = await this.read();
1689
+ let record = state.sessions.find((item) => item.sessionId === sessionId);
1690
+ let id = sessionId;
1691
+ const visited = /* @__PURE__ */ new Set();
1692
+ for (let depth = 0; !record && depth < 128; depth++) {
1693
+ if (visited.has(id)) throw new WorkspaceModeError("session-conflict", "会话继承链无效。");
1694
+ visited.add(id);
1695
+ let session;
1696
+ try {
1697
+ session = await this.dependencies.readSession(id);
1698
+ } catch {
1699
+ break;
1700
+ }
1701
+ if (state.workspaces.find((item) => samePath(item.path, resolve(session.cwd)))?.switchingTo) throw new WorkspaceModeError("workflow-switching", "工作流正在切换,请等待初始化完成。");
1702
+ if (!session.parentSession) break;
1703
+ id = session.parentSession;
1704
+ record = state.sessions.find((item) => item.sessionId === id);
1705
+ if (depth === 127) throw new WorkspaceModeError("session-conflict", "会话继承链过长。");
1706
+ }
1707
+ const owner = record && state.workspaces.find((item) => item.workspaceId === record.workspaceId);
1708
+ if (owner?.switchingTo) throw new WorkspaceModeError("workflow-switching", "工作流正在切换,请等待初始化完成。");
1709
+ if (record && (!owner || (record.generation ?? 0) !== (owner.generation ?? 0) || record.pluginId !== owner.pluginId)) throw new WorkspaceModeError("session-frozen", "此会话所属的工作流已变更,历史记录已冻结。请在当前工作区新建会话。");
1710
+ if (record && requested && requested !== record.pluginId) throw new WorkspaceModeError("plugin-conflict", "A CANNBot session must use its workspace workflow.");
1711
+ return record?.pluginId === "general" ? void 0 : record?.pluginId ?? requested;
1712
+ }
1713
+ async assertSessionWorkflow(sessionId, cwd, pluginId) {
1714
+ await this.workflowForSession(sessionId, pluginId);
1715
+ const state = await this.read(), session = state.sessions.find((item) => item.sessionId === sessionId);
1716
+ if (!session) return;
1717
+ const binding = state.workspaces.find((item) => item.workspaceId === session.workspaceId);
1718
+ const directory = await this.directory(cwd);
1719
+ if (!binding || !samePath(binding.path, directory.path)) throw new WorkspaceModeError("session-workspace-mismatch", "A CANNBot session must stay in its bound workspace.");
1720
+ this.check(binding, directory, pluginId);
1721
+ }
1722
+ async tree() {
1723
+ const state = await this.read();
1724
+ const [native, summaries] = await Promise.all([this.dependencies.listWorkspaces(), this.dependencies.listSessionSummaries?.()]);
1725
+ const byId = new Map((summaries ?? []).map((summary) => [summary.sessionId, summary]));
1726
+ const workspaces = [], sessions = [];
1727
+ for (const binding of state.workspaces) {
1728
+ if (binding.status !== "ready") continue;
1729
+ const workspace = native.find((item) => item.workspaceId === binding.workspaceId);
1730
+ if (!workspace) continue;
1731
+ for (const record of state.sessions.filter((item) => item.workspaceId === binding.workspaceId)) try {
1732
+ const session = await this.dependencies.readSession(record.sessionId);
1733
+ if (session.sessionId !== record.sessionId || !samePath(resolve(session.cwd), binding.path)) continue;
1734
+ const summary = byId.get(record.sessionId);
1735
+ const blank = summary?.blank ?? session.blank, running = summary?.running ?? session.running;
1736
+ const time = summary?.updatedAt;
1737
+ const updatedAt = typeof time === "number" && Number.isFinite(time) && Math.abs(time) <= 864e13 ? new Date(time).toISOString() : session.updatedAt;
1738
+ sessions.push({
1739
+ ...record,
1740
+ frozen: (record.generation ?? 0) !== (binding.generation ?? 0) || record.pluginId !== binding.pluginId,
1741
+ title: session.title,
1742
+ updatedAt,
1743
+ archived: session.archived === true,
1744
+ pinned: session.pinned === true,
1745
+ ...typeof blank === "boolean" ? { blank } : {},
1746
+ ...typeof running === "boolean" ? { running } : {},
1747
+ ...session.pinned === true && Number.isSafeInteger(session.pinOrder) && session.pinOrder >= 0 ? { pinOrder: session.pinOrder } : {},
1748
+ ...!workspace ? { ungrouped: true } : {}
1749
+ });
1750
+ } catch (error) {
1751
+ if (error.code === "invalid-mode-state") throw error;
1752
+ }
1753
+ if (workspace) workspaces.push(this.workspaceView(binding, workspace, state.sessions));
1754
+ }
1755
+ return {
1756
+ mode: "cannbot",
1757
+ platform: process.platform,
1758
+ workspaces,
1759
+ sessions
1760
+ };
1761
+ }
1762
+ };
1763
+ export { workspaceOperation as a, InitializationJobs as c, sessionActivity as i, withContentLock as l, WorkspaceModes as n, ContentManager as o, CANNBOT_WORKSPACES_PATH as r, validVersion as s, WorkspaceModeError as t, packageRoot as u };