dsh-plugin-recipe 0.0.0-stage → 0.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,1297 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { randomUUID } from "node:crypto";
4
+ import { appendFile, chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
+ // src/config.ts
8
+ const Config = z.object({
9
+ maxSteps: z.natural().min(1).max(100).default(12),
10
+ allowExport: z.boolean().default(true),
11
+ capabilitiesFile: z.string().default(""),
12
+ defaultDelivery: z.string().default("present")
13
+ });
14
+ /** Defaults used when the loader starts the plugin without an explicit config. */
15
+ const DEFAULT_CONFIG = {
16
+ maxSteps: 12,
17
+ allowExport: true,
18
+ capabilitiesFile: "",
19
+ defaultDelivery: "present"
20
+ };
21
+ /** Merge a partial/undefined loader config over the defaults. */
22
+ function normalizeConfig(config) {
23
+ return {
24
+ ...DEFAULT_CONFIG,
25
+ ...config ?? {}
26
+ };
27
+ }
28
+ // ../shared-meta/src/ids.ts
29
+ /** Create a sortable, readable id such as `trim-20261108-091500-ab12cd34`. */
30
+ function newId(prefix, date = /* @__PURE__ */ new Date()) {
31
+ const pad = (n, width = 2) => String(n).padStart(width, "0");
32
+ return `${prefix}-${`${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`}-${randomUUID().slice(0, 8)}`;
33
+ }
34
+ // ../shared-meta/src/text.ts
35
+ /** Truncate without splitting surrogate pairs. */
36
+ function truncate(text, max) {
37
+ if (text.length <= max) return text;
38
+ if (max <= 1) return text.slice(0, max);
39
+ return `${text.slice(0, max - 1)}…`;
40
+ }
41
+ /** Filesystem/URL-safe slug with a bounded length. */
42
+ function slugify(text, max = 48) {
43
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, max) || "untitled";
44
+ }
45
+ function isRecord$1(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ function uniq(values) {
49
+ return [...new Set(values)];
50
+ }
51
+ /** Escape text for one Markdown table cell. */
52
+ function escapeMarkdownCell(text) {
53
+ return text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim();
54
+ }
55
+ /** Render a bounded fenced JSON block. */
56
+ function jsonBlock(value, maxChars = 12e3) {
57
+ return `\`\`\`json\n${truncate(JSON.stringify(value, null, 2), maxChars)}\n\`\`\``;
58
+ }
59
+ // ../shared-meta/src/store.ts
60
+ /** Local store failure with a stable code. */
61
+ var StoreError = class extends Error {
62
+ code;
63
+ constructor(code, message, options) {
64
+ super(message, options);
65
+ this.name = "StoreError";
66
+ this.code = code;
67
+ }
68
+ };
69
+ /** Resolve the DSH home: `$DSH_HOME`, else `~/.dsh`. */
70
+ function resolveDshHome(env = process.env) {
71
+ const configured = env.DSH_HOME?.trim();
72
+ return configured ? resolve(configured) : join(homedir(), ".dsh");
73
+ }
74
+ /** Join a path under `<dshHome>/experience-optimizer`. */
75
+ function dataDir(...segments) {
76
+ return join(resolveDshHome(), "experience-optimizer", ...segments);
77
+ }
78
+ /** Create a directory with owner-only permissions. */
79
+ async function ensureDir(path) {
80
+ await mkdir(path, {
81
+ recursive: true,
82
+ mode: 448
83
+ });
84
+ await chmod(path, 448).catch(() => void 0);
85
+ }
86
+ /** Read a UTF-8 text file with an optional byte cap. */
87
+ async function readTextFile(path, maxBytes = 5242880) {
88
+ try {
89
+ const info = await stat(path);
90
+ if (info.size > maxBytes) throw new StoreError("too-large", `${path} is ${info.size} bytes (limit ${maxBytes})`);
91
+ return await readFile(path, "utf8");
92
+ } catch (error) {
93
+ if (isNotFound(error)) return void 0;
94
+ throw error;
95
+ }
96
+ }
97
+ /** Read and parse JSON; missing files return undefined. */
98
+ async function readJson(path) {
99
+ const text = await readTextFile(path);
100
+ if (text === void 0) return void 0;
101
+ try {
102
+ return JSON.parse(text);
103
+ } catch (error) {
104
+ throw new StoreError("parse", `invalid JSON at ${path}`, { cause: error });
105
+ }
106
+ }
107
+ /** Atomically replace a JSON file. */
108
+ async function writeJsonAtomic(path, value, mode = 384) {
109
+ const directory = dirname(path);
110
+ await ensureDir(directory);
111
+ const temporary = join(directory, `.${randomUUID()}.tmp`);
112
+ try {
113
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, {
114
+ encoding: "utf8",
115
+ mode
116
+ });
117
+ await chmod(temporary, mode).catch(() => void 0);
118
+ await rename(temporary, path);
119
+ } catch (error) {
120
+ await unlink(temporary).catch(() => void 0);
121
+ throw new StoreError("write", `cannot write ${path}`, { cause: error });
122
+ }
123
+ }
124
+ /** Append JSON lines in one batch. */
125
+ async function appendJsonl(path, lines) {
126
+ if (lines.length === 0) return;
127
+ await ensureDir(dirname(path));
128
+ const text = lines.map((line) => `${JSON.stringify(line)}\n`).join("");
129
+ try {
130
+ await appendFile(path, text, {
131
+ encoding: "utf8",
132
+ mode: 384
133
+ });
134
+ } catch (error) {
135
+ throw new StoreError("write", `cannot append ${path}`, { cause: error });
136
+ }
137
+ }
138
+ /** Read JSON lines, skipping malformed records. */
139
+ async function readJsonl(path, limit) {
140
+ const text = await readTextFile(path);
141
+ if (text === void 0) return [];
142
+ const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
143
+ const selected = limit === void 0 ? lines : lines.slice(-limit);
144
+ const result = [];
145
+ for (const line of selected) try {
146
+ result.push(JSON.parse(line));
147
+ } catch {}
148
+ return result;
149
+ }
150
+ /** Replace a file atomically with arbitrary text. */
151
+ async function writeTextAtomic(path, text, mode = 384) {
152
+ const directory = dirname(path);
153
+ await ensureDir(directory);
154
+ const temporary = join(directory, `.${randomUUID()}.tmp`);
155
+ try {
156
+ await writeFile(temporary, text, {
157
+ encoding: "utf8",
158
+ mode
159
+ });
160
+ await chmod(temporary, mode).catch(() => void 0);
161
+ await rename(temporary, path);
162
+ } catch (error) {
163
+ await unlink(temporary).catch(() => void 0);
164
+ throw new StoreError("write", `cannot write ${path}`, { cause: error });
165
+ }
166
+ }
167
+ function isNotFound(error) {
168
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
169
+ }
170
+ // ../shared-meta/src/audit.ts
171
+ const DEFAULT_MAX_BYTES = 2097152;
172
+ /** Append-only audit log with one-size rotation. */
173
+ var AuditLog = class {
174
+ path;
175
+ rotatedPath;
176
+ maxBytes;
177
+ writes = 0;
178
+ constructor(path = dataDir("audit.jsonl"), maxBytes = DEFAULT_MAX_BYTES) {
179
+ this.path = path;
180
+ this.rotatedPath = path.replace(/\.jsonl$/, ".1.jsonl");
181
+ this.maxBytes = maxBytes;
182
+ }
183
+ /** Append one record; failures are the caller's to report. */
184
+ async append(record) {
185
+ await appendJsonl(this.path, [record]);
186
+ this.writes++;
187
+ if (this.writes % 25 === 0) await this.rotateIfNeeded();
188
+ }
189
+ /** Read the most recent records, oldest first. */
190
+ async read(limit = 50) {
191
+ return readJsonl(this.path, limit);
192
+ }
193
+ async rotateIfNeeded() {
194
+ try {
195
+ if ((await stat(this.path)).size <= this.maxBytes) return;
196
+ await unlink(this.rotatedPath).catch(() => void 0);
197
+ const { rename } = await import("node:fs/promises");
198
+ await rename(this.path, this.rotatedPath);
199
+ } catch {}
200
+ }
201
+ };
202
+ // ../shared-meta/src/http.ts
203
+ /** Reject cross-site browser requests; allow same-origin and non-browser callers without Origin. */
204
+ function isSameOrigin(req) {
205
+ if (req.headers["sec-fetch-site"] === "cross-site") return false;
206
+ const origin = req.headers.origin;
207
+ if (origin === void 0 || origin.length === 0) return true;
208
+ try {
209
+ return new URL(origin).host === req.headers.host;
210
+ } catch {
211
+ return false;
212
+ }
213
+ }
214
+ /** Read and parse a JSON request body with a bounded size. */
215
+ async function readJsonBody(req, maxBytes = 65536) {
216
+ const chunks = [];
217
+ let size = 0;
218
+ for await (const chunk of req) {
219
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
220
+ size += buffer.length;
221
+ if (size > maxBytes) throw new Error(`request body exceeds ${maxBytes} bytes`);
222
+ chunks.push(buffer);
223
+ }
224
+ const text = Buffer.concat(chunks).toString("utf8").trim();
225
+ if (text.length === 0) return {};
226
+ return JSON.parse(text);
227
+ }
228
+ /** Write a JSON response. */
229
+ function sendJson(res, status, body) {
230
+ const text = JSON.stringify(body);
231
+ res.writeHead(status, {
232
+ "content-type": "application/json; charset=utf-8",
233
+ "cache-control": "no-store",
234
+ "content-length": Buffer.byteLength(text)
235
+ });
236
+ res.end(text);
237
+ }
238
+ /** Write a structured error response. */
239
+ function sendError(res, status, message) {
240
+ sendJson(res, status, {
241
+ ok: false,
242
+ error: { message }
243
+ });
244
+ }
245
+ // src/capabilities.ts
246
+ /** Built-in capability seams. Tools are checked against the current agent scope at planning time. */
247
+ const BUILT_IN_CAPABILITIES = [
248
+ {
249
+ id: "git-history",
250
+ name: "读取 Git 历史",
251
+ purpose: "读取指定范围/分支的 commit、diff 与变更统计",
252
+ tools: ["bash"],
253
+ trigger: "manual",
254
+ permissions: ["shell"],
255
+ needsConfirm: false,
256
+ keywords: [
257
+ "git",
258
+ "commit",
259
+ "log",
260
+ "diff",
261
+ "分支",
262
+ "变更",
263
+ "提交"
264
+ ],
265
+ pluginIds: ["@deepseek-ai/dsh-tool-bash"]
266
+ },
267
+ {
268
+ id: "file-read",
269
+ name: "读取文件",
270
+ purpose: "读取、搜索和汇总工作区文件",
271
+ tools: [
272
+ "read",
273
+ "glob",
274
+ "grep"
275
+ ],
276
+ trigger: "manual",
277
+ permissions: ["fs-read"],
278
+ needsConfirm: false,
279
+ keywords: [
280
+ "读取",
281
+ "查看",
282
+ "文件",
283
+ "read",
284
+ "grep",
285
+ "搜索文件"
286
+ ],
287
+ pluginIds: ["@deepseek-ai/dsh-tool-fs", "@deepseek-ai/dsh-tool-fs-search"]
288
+ },
289
+ {
290
+ id: "file-write",
291
+ name: "写入文件",
292
+ purpose: "生成或修改 Markdown/文本产物",
293
+ tools: ["write", "edit"],
294
+ trigger: "manual",
295
+ permissions: ["fs-write"],
296
+ needsConfirm: false,
297
+ keywords: [
298
+ "生成",
299
+ "写入",
300
+ "保存",
301
+ "markdown",
302
+ "文档",
303
+ "报告",
304
+ "文件"
305
+ ],
306
+ pluginIds: ["@deepseek-ai/dsh-tool-fs"]
307
+ },
308
+ {
309
+ id: "web-research",
310
+ name: "联网检索",
311
+ purpose: "搜索网页并抓取资料",
312
+ tools: ["web_search", "web_fetch"],
313
+ trigger: "manual",
314
+ permissions: ["network"],
315
+ needsConfirm: false,
316
+ keywords: [
317
+ "搜索",
318
+ "调研",
319
+ "网页",
320
+ "资料",
321
+ "search",
322
+ "fetch",
323
+ "research"
324
+ ],
325
+ pluginIds: ["@deepseek-ai/dsh-tool-web"]
326
+ },
327
+ {
328
+ id: "schedule",
329
+ name: "定时触发",
330
+ purpose: "按周期创建并运行计划任务",
331
+ tools: ["schedule_create"],
332
+ trigger: "schedule",
333
+ permissions: ["schedule"],
334
+ needsConfirm: true,
335
+ keywords: [
336
+ "每周",
337
+ "每天",
338
+ "定时",
339
+ "自动",
340
+ "周期",
341
+ "cron",
342
+ "schedule"
343
+ ],
344
+ pluginIds: ["@deepseek-ai/dsh-tool-schedule"]
345
+ },
346
+ {
347
+ id: "present",
348
+ name: "交付文件",
349
+ purpose: "把生成的文件作为交付物展示/下载",
350
+ tools: ["present"],
351
+ trigger: "manual",
352
+ permissions: [],
353
+ needsConfirm: false,
354
+ keywords: [
355
+ "交付",
356
+ "展示",
357
+ "文件",
358
+ "下载",
359
+ "present"
360
+ ],
361
+ pluginIds: ["@deepseek-ai/dsh-tool-present"]
362
+ },
363
+ {
364
+ id: "subagent",
365
+ name: "并行/汇总",
366
+ purpose: "把独立分析委派给子代理并汇总",
367
+ tools: ["subagent", "subagent_fork"],
368
+ trigger: "manual",
369
+ permissions: ["delegation"],
370
+ needsConfirm: false,
371
+ keywords: [
372
+ "汇总",
373
+ "总结",
374
+ "并行",
375
+ "分析",
376
+ "subagent"
377
+ ],
378
+ pluginIds: ["@deepseek-ai/dsh-tool-subagent"]
379
+ },
380
+ {
381
+ id: "workflow",
382
+ name: "批量编排",
383
+ purpose: "用脚本编排多个子任务",
384
+ tools: ["workflow"],
385
+ trigger: "manual",
386
+ permissions: ["delegation"],
387
+ needsConfirm: false,
388
+ keywords: [
389
+ "批量",
390
+ "多步",
391
+ "编排",
392
+ "workflow"
393
+ ],
394
+ pluginIds: ["@deepseek-ai/dsh-tool-workflow"]
395
+ },
396
+ {
397
+ id: "model-summary",
398
+ name: "模型汇总",
399
+ purpose: "由模型直接阅读材料并生成汇总(不新增工具)",
400
+ tools: [],
401
+ trigger: "manual",
402
+ permissions: [],
403
+ needsConfirm: false,
404
+ keywords: [
405
+ "汇总",
406
+ "总结",
407
+ "摘要",
408
+ "生成"
409
+ ],
410
+ pluginIds: [],
411
+ modelOnly: true
412
+ }
413
+ ];
414
+ /** Load built-ins plus an optional user catalog from disk. */
415
+ async function loadCapabilities(path) {
416
+ const diagnostics = [];
417
+ const catalog = new Map(BUILT_IN_CAPABILITIES.map((capability) => [capability.id, capability]));
418
+ const file = path !== void 0 && path.length > 0 ? path : dataDir("capabilities.json");
419
+ const custom = await readJson(file).catch((error) => {
420
+ diagnostics.push(`capabilities file unreadable: ${error instanceof Error ? error.message : String(error)}`);
421
+ });
422
+ if (custom !== void 0) {
423
+ const list = Array.isArray(custom) ? custom : isRecord$1(custom) && Array.isArray(custom.capabilities) ? custom.capabilities : [];
424
+ if (list.length === 0) diagnostics.push(`capabilities file has no capabilities array: ${file}`);
425
+ for (const raw of list) {
426
+ const capability = normalizeCapability(raw);
427
+ if (capability === void 0) {
428
+ diagnostics.push(`ignored malformed capability in ${file}`);
429
+ continue;
430
+ }
431
+ catalog.set(capability.id, capability);
432
+ }
433
+ }
434
+ return {
435
+ capabilities: [...catalog.values()],
436
+ diagnostics
437
+ };
438
+ }
439
+ function normalizeCapability(value) {
440
+ if (!isRecord$1(value)) return void 0;
441
+ if (typeof value.id !== "string" || typeof value.name !== "string") return void 0;
442
+ return {
443
+ id: value.id,
444
+ name: value.name,
445
+ purpose: typeof value.purpose === "string" ? value.purpose : value.name,
446
+ tools: Array.isArray(value.tools) ? value.tools.filter((item) => typeof item === "string") : [],
447
+ trigger: value.trigger === "schedule" || value.trigger === "event" ? value.trigger : "manual",
448
+ permissions: Array.isArray(value.permissions) ? value.permissions.filter((item) => typeof item === "string") : [],
449
+ needsConfirm: value.needsConfirm === true,
450
+ keywords: Array.isArray(value.keywords) ? value.keywords.filter((item) => typeof item === "string") : [],
451
+ pluginIds: Array.isArray(value.pluginIds) ? value.pluginIds.filter((item) => typeof item === "string") : [],
452
+ modelOnly: value.modelOnly === true
453
+ };
454
+ }
455
+ /** Capabilities whose tools are currently available; model-only seams are always available. */
456
+ function availableCapabilities(capabilities, toolExists) {
457
+ return capabilities.filter((capability) => capability.modelOnly === true || capability.tools.length === 0 || capability.tools.some((tool) => toolExists(tool)));
458
+ }
459
+ // src/wizard.ts
460
+ const AUTOMATION_RE = /每周|每天|每日|定时|自动|周期|weekly|daily|schedule|cron|recurring/i;
461
+ const WORKFLOW_RE = /周报|日报|报告|汇总|总结|自动|定时|每周|每天|周期|流程|编排|workflow|report|summar|collect|发送|通知|调研/i;
462
+ /** Whether a goal looks like an automatable workflow rather than ordinary Q&A. */
463
+ function isWorkflowGoal(goal) {
464
+ return WORKFLOW_RE.test(goal);
465
+ }
466
+ /** Whether the goal or answers imply a schedule. */
467
+ function isAutomated(goal, answers) {
468
+ return AUTOMATION_RE.test(`${goal} ${answers.frequency ?? ""}`);
469
+ }
470
+ /** Fill defaults for the fields the user has not answered. */
471
+ function defaultsFor(goal, answers) {
472
+ const automated = isAutomated(goal, answers);
473
+ return {
474
+ goal,
475
+ scope: answers.scope ?? "当前工作区",
476
+ frequency: answers.frequency ?? (automated ? "每周一 09:00" : "手动触发"),
477
+ sources: answers.sources ?? (automated || /git|commit|代码|变更/i.test(goal) ? ["Git log"] : ["当前工作区文件"]),
478
+ outputFormat: answers.outputFormat ?? "Markdown",
479
+ delivery: answers.delivery ?? "对话内交付(present)",
480
+ onFailure: answers.onFailure ?? "保留草稿并在对话中通知",
481
+ acceptance: answers.acceptance ?? [
482
+ "时间范围正确",
483
+ "输出内容可读",
484
+ "失败可恢复"
485
+ ]
486
+ };
487
+ }
488
+ /** Return the next question group, or null when enough answers exist. */
489
+ function nextQuestion(goal, answers, options = {}) {
490
+ if (options.forceBlueprint === true) return null;
491
+ if (!isWorkflowGoal(goal)) return null;
492
+ if (answers.scope === void 0 || answers.frequency === void 0) return {
493
+ step: "scope-frequency",
494
+ question: "这个工作流覆盖哪个项目、什么时间范围,手动还是定时?",
495
+ defaults: [answers.scope ?? "当前工作区", answers.frequency ?? (isAutomated(goal, answers) ? "每周一 09:00" : "手动触发")],
496
+ allowSkip: false,
497
+ fields: ["scope", "frequency"]
498
+ };
499
+ if (answers.sources === void 0) return {
500
+ step: "sources",
501
+ question: "数据从哪来?例如 Git log、当前工作区文件、网页资料。",
502
+ defaults: answers.sources ?? (isAutomated(goal, answers) ? ["Git log"] : ["当前工作区文件"]),
503
+ allowSkip: false,
504
+ fields: ["sources"]
505
+ };
506
+ if (answers.outputFormat === void 0 || answers.delivery === void 0) return {
507
+ step: "output-delivery",
508
+ question: "输出什么格式、交付到哪里?",
509
+ defaults: [answers.outputFormat ?? "Markdown", answers.delivery ?? "对话内交付(present)"],
510
+ allowSkip: true,
511
+ fields: ["outputFormat", "delivery"]
512
+ };
513
+ if (answers.onFailure === void 0 || answers.acceptance === void 0) return {
514
+ step: "failure-acceptance",
515
+ question: "失败时怎么处理,怎样算验收通过?",
516
+ defaults: [answers.onFailure ?? "保留草稿并在对话中通知", "时间范围正确;输出内容可读;失败可恢复"],
517
+ allowSkip: true,
518
+ fields: ["onFailure", "acceptance"]
519
+ };
520
+ return null;
521
+ }
522
+ // src/translate.ts
523
+ /** Translate a business goal plus answers into a workflow blueprint. */
524
+ function translateGoal(goal, answers, capabilities, options) {
525
+ const filled = defaultsFor(goal, answers);
526
+ const weekly = /周报|weekly|report|汇报/i.test(goal) && /git|commit|代码|变更|项目/i.test(goal);
527
+ const steps = weekly ? weeklyReportSteps(filled, capabilities, options) : genericSteps(filled, capabilities, options);
528
+ const uncertainties = collectUncertainties(filled, steps, capabilities, options);
529
+ const permissions = uniq(capabilities.filter((capability) => steps.some((step) => step.capabilityId === capability.id)).flatMap((capability) => capability.permissions));
530
+ const acceptance = uniq([...filled.acceptance ?? [], ...weekly ? ["包含指定分支与时间范围", "发送前人工确认"] : []]);
531
+ return {
532
+ schemaVersion: 1,
533
+ id: newId("wf"),
534
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
535
+ goal,
536
+ template: weekly ? "weekly-report" : "generic",
537
+ answers: filled,
538
+ steps,
539
+ minPluginSet: uniq(steps.flatMap((step) => step.pluginIds)),
540
+ suggestedDisable: [...options.suggestedDisable ?? []],
541
+ permissions,
542
+ failurePolicy: [filled.onFailure ?? "保留草稿并在对话中通知", "采集步骤最多重试一次;外部发送不静默重试"].join(";"),
543
+ acceptance,
544
+ rollback: weekly ? "停用 schedule 任务;保留已生成的周报文件;不修改仓库;恢复原插件配置。" : "停用 schedule 任务;保留已生成文件;恢复原插件配置。",
545
+ uncertainties
546
+ };
547
+ }
548
+ function weeklyReportSteps(answers, capabilities, options) {
549
+ const steps = [];
550
+ const git = find(capabilities, "git-history");
551
+ if (git !== void 0 && options.available.has(git.id)) steps.push(toolStep("s1", "读取指定时间范围与分支的 Git log/diff", git, [], false, ["时间范围", "分支"], ["commit 列表", "diff 统计"]));
552
+ const summary = find(capabilities, "model-summary");
553
+ if (summary !== void 0) steps.push({
554
+ id: "s2",
555
+ intent: "按模块/作者汇总 commit、风险与待办",
556
+ kind: "model",
557
+ capabilityId: summary.id,
558
+ toolNames: [],
559
+ pluginIds: [],
560
+ dependsOn: steps.map((step) => step.id),
561
+ needsConfirm: false,
562
+ inputs: ["commit 列表", "diff 统计"],
563
+ outputs: ["周报正文草稿"],
564
+ onFailure: "保留上下文,提示用户补充数据"
565
+ });
566
+ const write = find(capabilities, "file-write");
567
+ if (write !== void 0 && options.available.has(write.id)) steps.push(toolStep("s3", "生成 Markdown 周报文件", write, lastIds(steps), false, ["周报正文草稿"], ["Markdown 文件"]));
568
+ const delivery = chooseDelivery(answers, capabilities, options);
569
+ if (delivery !== void 0) steps.push(toolStep("s4", "交付/发送周报", delivery, lastIds(steps), true, ["Markdown 文件"], ["交付结果"]));
570
+ if (isAutomated(answers.goal, answers)) {
571
+ const schedule = find(capabilities, "schedule");
572
+ if (schedule !== void 0 && options.available.has(schedule.id)) steps.push(toolStep("s5", "创建每周定时任务", schedule, lastIds(steps), true, ["完整工作流"], ["schedule 任务 id"]));
573
+ }
574
+ return steps;
575
+ }
576
+ function genericSteps(answers, capabilities, options) {
577
+ const steps = [];
578
+ const selected = capabilities.filter((capability) => capability.id !== "schedule" && capability.id !== "model-summary" && options.available.has(capability.id) && capability.keywords.some((keyword) => answers.goal.toLowerCase().includes(keyword.toLowerCase())));
579
+ for (const capability of selected.slice(0, 6)) steps.push(toolStep(`s${steps.length + 1}`, capability.purpose, capability, lastIds(steps), capability.needsConfirm, ["工作区/输入数据"], [capability.name]));
580
+ if (steps.length > 0 && /汇总|总结|报告|summary|report/i.test(answers.goal)) {
581
+ const summary = find(capabilities, "model-summary");
582
+ if (summary !== void 0) steps.push({
583
+ id: `s${steps.length + 1}`,
584
+ intent: "汇总上一步结果并生成可读内容",
585
+ kind: "model",
586
+ capabilityId: summary.id,
587
+ toolNames: [],
588
+ pluginIds: [],
589
+ dependsOn: lastIds(steps),
590
+ needsConfirm: false,
591
+ inputs: ["上一步输出"],
592
+ outputs: ["汇总文本"],
593
+ onFailure: "保留中间结果并提示用户"
594
+ });
595
+ }
596
+ if (isAutomated(answers.goal, answers)) {
597
+ const schedule = find(capabilities, "schedule");
598
+ if (schedule !== void 0 && options.available.has(schedule.id)) steps.push(toolStep(`s${steps.length + 1}`, "创建定时任务", schedule, lastIds(steps), true, ["完整工作流"], ["schedule 任务 id"]));
599
+ }
600
+ return steps;
601
+ }
602
+ function toolStep(id, intent, capability, dependsOn, needsConfirm, inputs, outputs) {
603
+ return {
604
+ id,
605
+ intent,
606
+ kind: capability.trigger === "schedule" ? "schedule" : "tool",
607
+ capabilityId: capability.id,
608
+ toolNames: [...capability.tools],
609
+ pluginIds: [...capability.pluginIds],
610
+ dependsOn: [...dependsOn],
611
+ needsConfirm: needsConfirm || capability.needsConfirm,
612
+ inputs,
613
+ outputs,
614
+ onFailure: capability.trigger === "schedule" ? "停用本次运行并通知用户" : "保留草稿;采集步骤最多重试一次"
615
+ };
616
+ }
617
+ function collectUncertainties(answers, steps, capabilities, options) {
618
+ const uncertainties = [];
619
+ if (steps.length === 0) uncertainties.push("没有匹配到可用能力;请补充目标、数据来源或安装对应工具插件");
620
+ if (find(capabilities, "git-history") === void 0 || !options.available.has("git-history")) {
621
+ if (/git|commit|代码|变更/i.test(answers.goal)) uncertainties.push("缺少 Git 读取能力(bash 工具不可用)");
622
+ }
623
+ if (find(capabilities, "file-write") === void 0 || !options.available.has("file-write")) {
624
+ if (/markdown|文档|报告|周报/i.test(answers.goal)) uncertainties.push("缺少文件写入能力(write/edit 工具不可用)");
625
+ }
626
+ if (isAutomated(answers.goal, answers) && !steps.some((step) => step.kind === "schedule")) uncertainties.push("用户要求自动化,但当前没有可用的 schedule 能力");
627
+ if (!steps.some((step) => step.needsConfirm) && /发送|通知|邮件|钉钉|delivery/i.test(answers.delivery ?? "")) uncertainties.push("外部发送步骤缺少人工确认");
628
+ uncertainties.push("agent preset 自带的工具由 preset 提供,trim 不能单独开关;蓝图按“当前可用”生成");
629
+ return uniq(uncertainties);
630
+ }
631
+ function chooseDelivery(answers, capabilities, options) {
632
+ const requested = (answers.delivery ?? "").toLowerCase();
633
+ const custom = capabilities.find((capability) => capability.id !== "present" && (requested.includes(capability.id.toLowerCase()) || requested.includes(capability.name.toLowerCase()) || capability.keywords.some((keyword) => requested.includes(keyword.toLowerCase()))));
634
+ if (custom !== void 0 && options.available.has(custom.id)) return custom;
635
+ const present = find(capabilities, "present");
636
+ if (present !== void 0 && options.available.has(present.id)) return present;
637
+ }
638
+ function find(capabilities, id) {
639
+ return capabilities.find((capability) => capability.id === id);
640
+ }
641
+ function lastIds(steps) {
642
+ if (steps.length === 0) return [];
643
+ const last = steps[steps.length - 1];
644
+ return last === void 0 ? [] : [last.id];
645
+ }
646
+ // src/validate.ts
647
+ /** Validate a blueprint for dependencies, capabilities, permissions, failure handling, and compat. */
648
+ function validateBlueprint(blueprint, deps) {
649
+ const issues = [];
650
+ const steps = Array.isArray(blueprint.steps) ? blueprint.steps : [];
651
+ if (steps.length === 0) issues.push({
652
+ level: "error",
653
+ code: "EMPTY_STEPS",
654
+ message: "蓝图没有步骤"
655
+ });
656
+ if (steps.length > deps.maxSteps) issues.push({
657
+ level: "warn",
658
+ code: "TOO_MANY_STEPS",
659
+ message: `步骤数 ${steps.length} 超过上限 ${deps.maxSteps},建议拆分`
660
+ });
661
+ const ids = /* @__PURE__ */ new Set();
662
+ for (const step of steps) {
663
+ if (ids.has(step.id)) issues.push({
664
+ level: "error",
665
+ code: "DUPLICATE_STEP_ID",
666
+ message: `重复步骤 id ${step.id}`,
667
+ stepId: step.id
668
+ });
669
+ ids.add(step.id);
670
+ }
671
+ const capabilityIds = new Set(deps.capabilities.map((capability) => capability.id));
672
+ for (const step of steps) {
673
+ for (const dependency of step.dependsOn) if (!ids.has(dependency)) issues.push({
674
+ level: "error",
675
+ code: "BAD_DEP",
676
+ message: `${step.id} 依赖不存在的 ${dependency}`,
677
+ stepId: step.id
678
+ });
679
+ if (step.capabilityId !== null && !capabilityIds.has(step.capabilityId)) issues.push({
680
+ level: "error",
681
+ code: "MISSING_CAPABILITY",
682
+ message: `${step.id} 使用未知能力 ${step.capabilityId}`,
683
+ stepId: step.id
684
+ });
685
+ for (const tool of step.toolNames) if (!deps.toolExists(tool)) issues.push({
686
+ level: "error",
687
+ code: "MISSING_TOOL",
688
+ message: `${step.id} 需要的工具 ${tool} 在当前 scope 不可用`,
689
+ stepId: step.id
690
+ });
691
+ for (const plugin of step.pluginIds) if (!deps.pluginKnown(plugin)) issues.push({
692
+ level: "warn",
693
+ code: "PLUGIN_NOT_FOUND",
694
+ message: `${step.id} 的插件 ${plugin} 不在当前 profile 中(可能由 preset 提供)`,
695
+ stepId: step.id
696
+ });
697
+ }
698
+ if (hasCycle(steps)) issues.push({
699
+ level: "error",
700
+ code: "CYCLE",
701
+ message: "步骤依赖存在环"
702
+ });
703
+ if (steps.some((step) => step.kind === "schedule") && !deps.scheduleAvailable) issues.push({
704
+ level: "error",
705
+ code: "NO_SCHEDULE_SERVICE",
706
+ message: "蓝图包含定时步骤,但当前 profile 没有 schedule 服务"
707
+ });
708
+ if (steps.some((step) => step.kind === "schedule") && blueprint.failurePolicy.trim().length === 0) issues.push({
709
+ level: "warn",
710
+ code: "SCHEDULE_NO_FAILURE",
711
+ message: "定时任务缺少失败策略"
712
+ });
713
+ if (steps.some((step) => /发送|交付|deliver|send|notify/i.test(step.intent)) && !steps.some((step) => step.needsConfirm)) issues.push({
714
+ level: "warn",
715
+ code: "SEND_NO_CONFIRM",
716
+ message: "发送/交付步骤建议人工确认"
717
+ });
718
+ if (steps.some((step) => /写入|生成|write|render/i.test(step.intent)) && blueprint.rollback.trim().length === 0) issues.push({
719
+ level: "warn",
720
+ code: "WRITE_NO_ROLLBACK",
721
+ message: "写文件步骤缺少回滚说明"
722
+ });
723
+ if (blueprint.acceptance.length === 0) issues.push({
724
+ level: "warn",
725
+ code: "NO_ACCEPTANCE",
726
+ message: "缺少验收标准"
727
+ });
728
+ if (blueprint.permissions.some((permission) => ["external-send", "shell"].includes(permission)) && !steps.some((step) => step.needsConfirm)) issues.push({
729
+ level: "warn",
730
+ code: "HIGH_RISK_PERMISSION",
731
+ message: "存在高权限步骤但没有人工确认点"
732
+ });
733
+ for (const finding of deps.compatFindings ?? []) {
734
+ if (!steps.some((step) => step.pluginIds.some((plugin) => finding.subjects.includes(plugin)) || step.toolNames.some((tool) => finding.subjects.includes(tool)))) continue;
735
+ issues.push({
736
+ level: finding.severity === "error" ? "error" : "warn",
737
+ code: finding.severity === "error" ? "COMPAT_CONFLICT" : "COMPAT_WARN",
738
+ message: `${finding.code}: ${finding.title}`
739
+ });
740
+ }
741
+ return issues;
742
+ }
743
+ function hasCycle(steps) {
744
+ const byId = new Map(steps.map((step) => [step.id, step]));
745
+ const state = /* @__PURE__ */ new Map();
746
+ const visit = (id) => {
747
+ const current = state.get(id);
748
+ if (current === "visiting") return true;
749
+ if (current === "done") return false;
750
+ const step = byId.get(id);
751
+ if (step === void 0) return false;
752
+ state.set(id, "visiting");
753
+ for (const dependency of step.dependsOn) if (visit(dependency)) return true;
754
+ state.set(id, "done");
755
+ return false;
756
+ };
757
+ for (const step of steps) if (visit(step.id)) return true;
758
+ return false;
759
+ }
760
+ /** Render a validation result as a compact Markdown report. */
761
+ function renderValidation(issues) {
762
+ if (issues.length === 0) return "✅ 校验通过:未发现 error 或 warn。";
763
+ const errors = issues.filter((issue) => issue.level === "error");
764
+ const warnings = issues.filter((issue) => issue.level === "warn");
765
+ const lines = [];
766
+ lines.push(`> ${errors.length} error / ${warnings.length} warn`);
767
+ lines.push("");
768
+ lines.push("| level | code | step | message |");
769
+ lines.push("|---|---|---|---|");
770
+ for (const issue of issues.slice(0, 50)) lines.push(`| ${issue.level} | ${issue.code} | ${issue.stepId ?? "—"} | ${issue.message.replace(/\|/g, "\\|")} |`);
771
+ return lines.join("\n");
772
+ }
773
+ // src/export.ts
774
+ /** Write a blueprint to the DSH data directory. */
775
+ async function exportBlueprint(blueprint, format = "both") {
776
+ const base = `${slugify(blueprint.id)}`;
777
+ const directory = dataDir("recipe", "blueprints");
778
+ const result = { id: blueprint.id };
779
+ if (format === "markdown" || format === "both") {
780
+ const path = `${directory}/${base}.md`;
781
+ await writeTextAtomic(path, renderBlueprintMarkdown(blueprint));
782
+ result.markdownPath = path;
783
+ }
784
+ if (format === "json" || format === "both") {
785
+ const path = `${directory}/${base}.json`;
786
+ await writeJsonAtomic(path, blueprint);
787
+ result.jsonPath = path;
788
+ }
789
+ return result;
790
+ }
791
+ /** Render the human runbook plus a machine-readable JSON block. */
792
+ function renderBlueprintMarkdown(blueprint) {
793
+ const lines = [];
794
+ lines.push(`# 工作流蓝图:${blueprint.goal}`);
795
+ lines.push("");
796
+ lines.push(`- 蓝图 id:\`${blueprint.id}\``);
797
+ lines.push(`- 模板:${blueprint.template}`);
798
+ lines.push(`- 生成时间:${blueprint.createdAt}`);
799
+ lines.push("");
800
+ lines.push("## 1. 目标复述");
801
+ lines.push("");
802
+ lines.push(blueprint.goal);
803
+ lines.push("");
804
+ lines.push("## 2. 步骤");
805
+ lines.push("");
806
+ lines.push("| # | 意图 | 类型 | 能力 | 工具/插件 | 依赖 | 人工确认 | 失败处理 |");
807
+ lines.push("|---|---|---|---|---|---|---|---|");
808
+ for (const step of blueprint.steps) lines.push(stepRow(step));
809
+ lines.push("");
810
+ lines.push("## 3. 数据流");
811
+ lines.push("");
812
+ for (const step of blueprint.steps) lines.push(`- ${step.id}:${step.inputs.join(" + ") || "—"} → ${step.outputs.join(" + ") || "—"}`);
813
+ lines.push("");
814
+ lines.push("## 4. 最小插件集");
815
+ lines.push("");
816
+ if (blueprint.minPluginSet.length === 0) lines.push("- (无)");
817
+ for (const plugin of blueprint.minPluginSet) lines.push(`- ${plugin}`);
818
+ lines.push("");
819
+ if (blueprint.suggestedDisable.length > 0) {
820
+ lines.push("### 建议禁用");
821
+ lines.push("");
822
+ for (const item of blueprint.suggestedDisable) lines.push(`- ${item}`);
823
+ lines.push("");
824
+ }
825
+ lines.push("## 5. 权限与风险");
826
+ lines.push("");
827
+ if (blueprint.permissions.length === 0) lines.push("- (无额外权限)");
828
+ for (const permission of blueprint.permissions) lines.push(`- ${permission}`);
829
+ lines.push("");
830
+ lines.push("## 6. 运行手册");
831
+ lines.push("");
832
+ lines.push("1. 确认上表的人工确认点与权限。");
833
+ lines.push("2. 先手动运行一次采集与生成步骤,检查时间范围、分支与输出内容。");
834
+ lines.push("3. 确认无误后再创建/启用定时任务。");
835
+ lines.push("4. 失败时按“失败处理”保留草稿并在对话中通知,不静默重试外部发送。");
836
+ lines.push("");
837
+ lines.push("## 7. 验收清单");
838
+ lines.push("");
839
+ for (const item of blueprint.acceptance) lines.push(`- [ ] ${item}`);
840
+ lines.push("");
841
+ lines.push("## 8. 回滚");
842
+ lines.push("");
843
+ lines.push(blueprint.rollback);
844
+ lines.push("");
845
+ lines.push("## 9. 不确定性");
846
+ lines.push("");
847
+ for (const item of blueprint.uncertainties) lines.push(`- ${item}`);
848
+ lines.push("");
849
+ lines.push("## 10. 机器可读蓝图");
850
+ lines.push("");
851
+ lines.push(jsonBlock(blueprint, 2e4));
852
+ return lines.join("\n");
853
+ }
854
+ function stepRow(step) {
855
+ const tools = step.toolNames.length > 0 ? step.toolNames.join(", ") : "(模型步骤)";
856
+ const plugins = step.pluginIds.length > 0 ? ` / ${step.pluginIds.join(", ")}` : "";
857
+ return `| ${step.id} | ${escapeMarkdownCell(step.intent)} | ${step.kind} | ${step.capabilityId ?? "—"} | ${escapeMarkdownCell(tools + plugins)} | ${step.dependsOn.join(", ") || "—"} | ${step.needsConfirm ? "yes" : "no"} | ${escapeMarkdownCell(step.onFailure)} |`;
858
+ }
859
+ // src/tools.ts
860
+ /** Register the recipe model-facing tools. */
861
+ function registerRecipeTools(ctx, config) {
862
+ ctx.tools.register(defineTool({
863
+ name: "recipe_plan_workflow",
864
+ description: "Translate a business goal into a validated DSH workflow blueprint through at most four concise questions. Returns one question at a time until enough answers exist, then a blueprint with steps, capability seams, minimum plugin set, permissions, failure policy, acceptance checklist, rollback, and uncertainties. Do not invent missing capabilities; report them in uncertainties. Read-only; never creates schedules or edits plugins.",
865
+ parameters: {
866
+ goal: {
867
+ type: "string",
868
+ required: true,
869
+ description: "The user business goal, in their own words."
870
+ },
871
+ answers: {
872
+ type: "json",
873
+ description: "Answers gathered so far: { scope?, frequency?, sources?, outputFormat?, delivery?, onFailure?, acceptance? }. Reuse the same goal across calls."
874
+ },
875
+ trimProfileId: {
876
+ type: "string",
877
+ description: "Optional trim slim-profile id whose suggested disables should be attached."
878
+ },
879
+ forceBlueprint: {
880
+ type: "boolean",
881
+ description: "Skip remaining questions and emit a draft with assumptions and uncertainties."
882
+ }
883
+ },
884
+ output: {
885
+ schema: { type: "string" },
886
+ render: (_args, value) => [{
887
+ type: "text",
888
+ text: value
889
+ }]
890
+ },
891
+ async execute(args, exec) {
892
+ const goal = args.goal.trim();
893
+ if (!isWorkflowGoal(goal) && args.forceBlueprint !== true) return [
894
+ "# 不需要编排",
895
+ "",
896
+ "这个目标更像普通问答或单步任务,建议直接在当前会话完成,不必生成工作流。",
897
+ "如果确实需要自动化,请补充“周期、数据来源、输出、交付方式”后重试。"
898
+ ].join("\n");
899
+ const partial = readAnswers(args.answers);
900
+ const question = nextQuestion(goal, {
901
+ goal,
902
+ ...partial
903
+ }, { forceBlueprint: args.forceBlueprint });
904
+ if (question !== null) return renderQuestion(goal, question, partial);
905
+ const catalog = await loadCapabilities(config.capabilitiesFile);
906
+ const toolExists = (name) => ctx.tools.get(name, exec.agent) !== void 0;
907
+ const known = await knownPlugins$1(ctx, catalog.capabilities, toolExists);
908
+ const compat = await readCompatReport$1();
909
+ const blocked = blockedSubjects$1(compat);
910
+ const capabilities = availableCapabilities(catalog.capabilities, toolExists).filter((capability) => !capability.pluginIds.some((plugin) => blocked.has(plugin)) && !capability.tools.some((tool) => blocked.has(tool)));
911
+ const available = new Set(capabilities.map((capability) => capability.id));
912
+ const filled = defaultsFor(goal, {
913
+ goal,
914
+ ...partial
915
+ });
916
+ const suggestedDisable = await readSuggestedDisable(args.trimProfileId);
917
+ const blueprint = translateGoal(goal, filled, catalog.capabilities, {
918
+ available,
919
+ suggestedDisable
920
+ });
921
+ if (blocked.size > 0) blueprint.uncertainties.push(`兼容性报告存在 error,以下主体被排除:${[...blocked].slice(0, 10).join(", ")}`);
922
+ for (const diagnostic of catalog.diagnostics) blueprint.uncertainties.push(diagnostic);
923
+ blueprint.uncertainties = [...new Set(blueprint.uncertainties)];
924
+ const issues = validateBlueprint(blueprint, {
925
+ toolExists,
926
+ pluginKnown: (name) => known.has(name),
927
+ scheduleAvailable: ctx.get("schedule") !== void 0,
928
+ maxSteps: config.maxSteps,
929
+ capabilities: catalog.capabilities,
930
+ compatFindings: compat?.findings
931
+ });
932
+ await audit("plan_workflow", "ok", `blueprint ${blueprint.id}: ${blueprint.steps.length} steps`);
933
+ return renderBlueprint(blueprint, issues);
934
+ },
935
+ presentCall: () => ({
936
+ card: "generic",
937
+ title: "Plan workflow",
938
+ kind: "read"
939
+ })
940
+ }));
941
+ ctx.tools.register(defineTool({
942
+ name: "recipe_validate_workflow",
943
+ description: "Validate a workflow blueprint for missing tools/capabilities, dependency cycles, schedule service availability, human confirmation, rollback, acceptance criteria, and compatibility conflicts. Read-only.",
944
+ parameters: { blueprint: {
945
+ type: "json",
946
+ required: true,
947
+ description: "The blueprint object returned by recipe_plan_workflow."
948
+ } },
949
+ output: {
950
+ schema: { type: "string" },
951
+ render: (_args, value) => [{
952
+ type: "text",
953
+ text: value
954
+ }]
955
+ },
956
+ async execute(args, exec) {
957
+ if (!isWorkflowBlueprint$1(args.blueprint)) return "❌ blueprint 缺少必要字段(schemaVersion/id/goal/steps)。";
958
+ const catalog = await loadCapabilities(config.capabilitiesFile);
959
+ const toolExists = (name) => ctx.tools.get(name, exec.agent) !== void 0;
960
+ const known = await knownPlugins$1(ctx, catalog.capabilities, toolExists);
961
+ const compat = await readCompatReport$1();
962
+ const issues = validateBlueprint(args.blueprint, {
963
+ toolExists,
964
+ pluginKnown: (name) => known.has(name),
965
+ scheduleAvailable: ctx.get("schedule") !== void 0,
966
+ maxSteps: config.maxSteps,
967
+ capabilities: catalog.capabilities,
968
+ compatFindings: compat?.findings
969
+ });
970
+ await audit("validate_workflow", issues.some((issue) => issue.level === "error") ? "fail" : "ok", `${issues.length} issues`);
971
+ return `# 蓝图校验\n\n${renderValidation(issues)}`;
972
+ },
973
+ presentCall: () => ({
974
+ card: "generic",
975
+ title: "Validate workflow",
976
+ kind: "read"
977
+ })
978
+ }));
979
+ ctx.tools.register(defineTool({
980
+ name: "recipe_export_workflow",
981
+ description: "Write a workflow blueprint and runbook to $DSH_HOME/experience-optimizer/recipe/blueprints as Markdown and/or JSON. Call only when the user asks to export. Does not create schedules or modify plugins.",
982
+ parameters: {
983
+ blueprint: {
984
+ type: "json",
985
+ required: true,
986
+ description: "The blueprint object returned by recipe_plan_workflow."
987
+ },
988
+ format: {
989
+ type: "string",
990
+ enum: [
991
+ "markdown",
992
+ "json",
993
+ "both"
994
+ ],
995
+ description: "Export format. Default both."
996
+ }
997
+ },
998
+ output: {
999
+ schema: { type: "string" },
1000
+ render: (_args, value) => [{
1001
+ type: "text",
1002
+ text: value
1003
+ }]
1004
+ },
1005
+ async execute(args) {
1006
+ if (config.allowExport !== true) return "❌ 当前配置禁止导出蓝图(allowExport: false)。";
1007
+ if (!isWorkflowBlueprint$1(args.blueprint)) return "❌ blueprint 缺少必要字段(schemaVersion/id/goal/steps)。";
1008
+ const format = args.format ?? "both";
1009
+ const result = await exportBlueprint(args.blueprint, format);
1010
+ await audit("export_workflow", "ok", `exported ${args.blueprint.id}`);
1011
+ return [
1012
+ "# 蓝图已导出",
1013
+ "",
1014
+ result.markdownPath === void 0 ? "" : `- Markdown:${result.markdownPath}`,
1015
+ result.jsonPath === void 0 ? "" : `- JSON:${result.jsonPath}`,
1016
+ "",
1017
+ "可用 `present` 工具把 Markdown 文件交付给用户。"
1018
+ ].filter((line) => line.length > 0).join("\n");
1019
+ },
1020
+ presentCall: () => ({
1021
+ card: "generic",
1022
+ title: "Export workflow",
1023
+ kind: "other"
1024
+ })
1025
+ }));
1026
+ }
1027
+ function renderQuestion(goal, question, partial) {
1028
+ const answered = Object.entries(partial).filter(([, value]) => value !== void 0).map(([key]) => key);
1029
+ return [
1030
+ "# 还需要确认",
1031
+ "",
1032
+ `目标:${goal}`,
1033
+ "",
1034
+ `**${question.question}**`,
1035
+ "",
1036
+ "默认推测(可直接确认或修正):",
1037
+ ...question.defaults.map((defaultValue) => `- ${defaultValue}`),
1038
+ "",
1039
+ `已回答字段:${answered.length === 0 ? "无" : answered.join(", ")}`,
1040
+ "",
1041
+ "请把用户回答填入 answers 后再次调用 `recipe_plan_workflow`;同一 goal 复用即可。"
1042
+ ].join("\n");
1043
+ }
1044
+ function renderBlueprint(blueprint, issues) {
1045
+ const lines = [];
1046
+ lines.push(`# 工作流蓝图:${blueprint.goal}`);
1047
+ lines.push("");
1048
+ lines.push(`- 模板:${blueprint.template}`);
1049
+ lines.push(`- 蓝图 id:\`${blueprint.id}\``);
1050
+ lines.push(`- 最小插件集:${blueprint.minPluginSet.length === 0 ? "(无)" : blueprint.minPluginSet.join(", ")}`);
1051
+ lines.push("");
1052
+ lines.push("## 步骤");
1053
+ lines.push("");
1054
+ lines.push("| # | 意图 | 类型 | 能力 | 工具 | 依赖 | 确认 |");
1055
+ lines.push("|---|---|---|---|---|---|---|");
1056
+ for (const step of blueprint.steps) lines.push(`| ${step.id} | ${escapeMarkdownCell(step.intent)} | ${step.kind} | ${step.capabilityId ?? "—"} | ${escapeMarkdownCell(step.toolNames.join(", "))} | ${step.dependsOn.join(", ") || "—"} | ${step.needsConfirm ? "yes" : "no"} |`);
1057
+ lines.push("");
1058
+ lines.push("## 权限与失败策略");
1059
+ lines.push("");
1060
+ lines.push(`- 权限:${blueprint.permissions.join(", ") || "无"}`);
1061
+ lines.push(`- 失败策略:${blueprint.failurePolicy}`);
1062
+ lines.push(`- 回滚:${blueprint.rollback}`);
1063
+ lines.push("");
1064
+ lines.push("## 验收");
1065
+ lines.push("");
1066
+ for (const item of blueprint.acceptance) lines.push(`- [ ] ${item}`);
1067
+ lines.push("");
1068
+ if (blueprint.uncertainties.length > 0) {
1069
+ lines.push("## 不确定性");
1070
+ lines.push("");
1071
+ for (const item of blueprint.uncertainties) lines.push(`- ${item}`);
1072
+ lines.push("");
1073
+ }
1074
+ lines.push("## 校验");
1075
+ lines.push("");
1076
+ lines.push(renderValidation(issues));
1077
+ lines.push("");
1078
+ lines.push("## 机器可读蓝图");
1079
+ lines.push("");
1080
+ lines.push(jsonBlock(blueprint, 2e4));
1081
+ lines.push("");
1082
+ lines.push("下一步:可以调用 `recipe_validate_workflow` 重新校验,或调用 `recipe_export_workflow` 导出运行手册。");
1083
+ return lines.join("\n");
1084
+ }
1085
+ function readAnswers(raw) {
1086
+ if (!isRecord$1(raw)) return {};
1087
+ const out = {};
1088
+ if (typeof raw.scope === "string") out.scope = raw.scope;
1089
+ if (typeof raw.frequency === "string") out.frequency = raw.frequency;
1090
+ if (Array.isArray(raw.sources)) out.sources = raw.sources.filter((item) => typeof item === "string");
1091
+ if (typeof raw.outputFormat === "string") out.outputFormat = raw.outputFormat;
1092
+ if (typeof raw.delivery === "string") out.delivery = raw.delivery;
1093
+ if (typeof raw.onFailure === "string") out.onFailure = raw.onFailure;
1094
+ if (Array.isArray(raw.acceptance)) out.acceptance = raw.acceptance.filter((item) => typeof item === "string");
1095
+ return out;
1096
+ }
1097
+ function isWorkflowBlueprint$1(value) {
1098
+ if (!isRecord$1(value)) return false;
1099
+ return value.schemaVersion === 1 && typeof value.id === "string" && typeof value.goal === "string" && Array.isArray(value.steps);
1100
+ }
1101
+ async function readCompatReport$1() {
1102
+ return readJson(dataDir("compat", "report.json")).catch(() => void 0);
1103
+ }
1104
+ async function knownPlugins$1(ctx, capabilities, toolExists) {
1105
+ const known = /* @__PURE__ */ new Set();
1106
+ for (const capability of capabilities) {
1107
+ if (!capability.tools.some((tool) => toolExists(tool))) continue;
1108
+ for (const plugin of capability.pluginIds) known.add(plugin);
1109
+ }
1110
+ const manager = ctx.get("pluginManager");
1111
+ if (typeof manager?.listBundles === "function") try {
1112
+ for (const bundle of await manager.listBundles()) if (typeof bundle.name === "string") known.add(bundle.name);
1113
+ } catch {}
1114
+ return known;
1115
+ }
1116
+ function blockedSubjects$1(report) {
1117
+ const set = /* @__PURE__ */ new Set();
1118
+ for (const finding of report?.findings ?? []) {
1119
+ if (finding.severity !== "error") continue;
1120
+ for (const subject of finding.subjects) set.add(subject);
1121
+ }
1122
+ return set;
1123
+ }
1124
+ async function readSuggestedDisable(profileId) {
1125
+ if (profileId === void 0 || profileId.length === 0) return [];
1126
+ const profile = await readJson(dataDir("trim", "profiles", `${profileId.replace(/[^a-zA-Z0-9._-]/g, "_")}.json`)).catch(() => void 0);
1127
+ if (profile === void 0) return [];
1128
+ return profile.items.filter((item) => item.action === "suggest-disable").map((item) => item.name);
1129
+ }
1130
+ async function audit(action, result, summary) {
1131
+ await new AuditLog().append({
1132
+ t: (/* @__PURE__ */ new Date()).toISOString(),
1133
+ actor: "recipe",
1134
+ action,
1135
+ subject: "recipe",
1136
+ result,
1137
+ summary
1138
+ }).catch(() => void 0);
1139
+ }
1140
+ // src/api.ts
1141
+ const API_PREFIX = "/api/dsh-experience-optimizer/recipe";
1142
+ /** Register the recipe panel API used by the Web client. */
1143
+ function registerRecipeApi(ctx, config) {
1144
+ if (typeof ctx.inject !== "function") return;
1145
+ ctx.inject(["webServer"], (webCtx) => {
1146
+ const server = webCtx.get("webServer");
1147
+ if (server === void 0) return;
1148
+ webCtx.effect(() => server.register({
1149
+ kind: "prefix",
1150
+ path: API_PREFIX,
1151
+ handler: (req, res) => handle(req, res, ctx, config)
1152
+ }), "recipe.webApi");
1153
+ });
1154
+ }
1155
+ async function handle(req, res, ctx, config) {
1156
+ const connection = ctx.get("connection");
1157
+ if (connection === void 0 || typeof connection.requestRejection !== "function") {
1158
+ sendError(res, 401, "authentication unavailable");
1159
+ return;
1160
+ }
1161
+ let rejection;
1162
+ try {
1163
+ rejection = connection.requestRejection({ headers: req.headers });
1164
+ } catch {
1165
+ sendError(res, 401, "authentication failed");
1166
+ return;
1167
+ }
1168
+ if (rejection !== void 0) {
1169
+ sendError(res, rejection, "authentication required");
1170
+ return;
1171
+ }
1172
+ if (!isSameOrigin(req)) {
1173
+ sendError(res, 403, "cross-site request rejected");
1174
+ return;
1175
+ }
1176
+ const path = new URL(req.url ?? "/", "http://localhost").pathname.slice(36) || "/";
1177
+ try {
1178
+ if (req.method === "POST" && path === "/plan") {
1179
+ sendJson(res, 200, {
1180
+ ok: true,
1181
+ data: await plan(ctx, config, await readJsonBody(req))
1182
+ });
1183
+ return;
1184
+ }
1185
+ if (req.method === "POST" && path === "/export") {
1186
+ sendJson(res, 200, {
1187
+ ok: true,
1188
+ data: await exportRunbook(ctx, config, await readJsonBody(req))
1189
+ });
1190
+ return;
1191
+ }
1192
+ sendError(res, 404, `unknown endpoint ${path}`);
1193
+ } catch (error) {
1194
+ sendError(res, 500, error instanceof Error ? error.message : String(error));
1195
+ }
1196
+ }
1197
+ async function plan(ctx, config, body) {
1198
+ const goal = typeof body.goal === "string" ? body.goal.trim() : "";
1199
+ if (goal.length === 0) throw new Error("goal is required");
1200
+ const rawAnswers = isRecord(body.answers) ? body.answers : {};
1201
+ const answers = defaultsFor(goal, {
1202
+ goal,
1203
+ scope: stringValue(rawAnswers.scope),
1204
+ frequency: stringValue(rawAnswers.frequency),
1205
+ sources: stringArray(rawAnswers.sources),
1206
+ outputFormat: stringValue(rawAnswers.outputFormat),
1207
+ delivery: stringValue(rawAnswers.delivery),
1208
+ onFailure: stringValue(rawAnswers.onFailure),
1209
+ acceptance: stringArray(rawAnswers.acceptance)
1210
+ });
1211
+ const catalog = await loadCapabilities(config.capabilitiesFile);
1212
+ const toolExists = (name) => catalog.capabilities.some((capability) => capability.tools.includes(name)) || ctx.tools.get(name) !== void 0;
1213
+ const compat = await readCompatReport();
1214
+ const blocked = blockedSubjects(compat);
1215
+ const capabilities = availableCapabilities(catalog.capabilities, toolExists).filter((capability) => !capability.pluginIds.some((plugin) => blocked.has(plugin)) && !capability.tools.some((tool) => blocked.has(tool)));
1216
+ const available = new Set(capabilities.map((capability) => capability.id));
1217
+ const blueprint = translateGoal(goal, answers, catalog.capabilities, {
1218
+ available,
1219
+ suggestedDisable: []
1220
+ });
1221
+ if (blocked.size > 0) blueprint.uncertainties.push(`兼容性报告存在 error,以下主体被排除:${[...blocked].slice(0, 10).join(", ")}`);
1222
+ for (const diagnostic of catalog.diagnostics) blueprint.uncertainties.push(diagnostic);
1223
+ blueprint.uncertainties = [...new Set(blueprint.uncertainties)];
1224
+ const known = await knownPlugins(ctx, catalog.capabilities, toolExists);
1225
+ const issues = validateBlueprint(blueprint, {
1226
+ toolExists,
1227
+ pluginKnown: (name) => known.has(name),
1228
+ scheduleAvailable: ctx.get("schedule") !== void 0,
1229
+ maxSteps: config.maxSteps,
1230
+ capabilities: catalog.capabilities,
1231
+ compatFindings: compat?.findings
1232
+ });
1233
+ return {
1234
+ goal,
1235
+ isWorkflow: isWorkflowGoal(goal),
1236
+ blueprint,
1237
+ issues,
1238
+ capabilities: capabilities.map((capability) => ({
1239
+ id: capability.id,
1240
+ name: capability.name,
1241
+ tools: capability.tools,
1242
+ permissions: capability.permissions
1243
+ })),
1244
+ note: "UI 预览按内置能力目录判断工具可用性;精确的 agent-scope 校验以 recipe_plan_workflow 工具为准。"
1245
+ };
1246
+ }
1247
+ async function exportRunbook(ctx, config, body) {
1248
+ if (!config.allowExport) throw new Error("export is disabled by config");
1249
+ if (!isWorkflowBlueprint(body.blueprint)) throw new Error("blueprint is invalid");
1250
+ const format = body.format === "markdown" || body.format === "json" || body.format === "both" ? body.format : "both";
1251
+ return exportBlueprint(body.blueprint, format);
1252
+ }
1253
+ async function readCompatReport() {
1254
+ return readJson(dataDir("compat", "report.json")).catch(() => void 0);
1255
+ }
1256
+ function blockedSubjects(report) {
1257
+ const set = /* @__PURE__ */ new Set();
1258
+ for (const finding of report?.findings ?? []) {
1259
+ if (finding.severity !== "error") continue;
1260
+ for (const subject of finding.subjects) set.add(subject);
1261
+ }
1262
+ return set;
1263
+ }
1264
+ async function knownPlugins(ctx, capabilities, toolExists) {
1265
+ const known = /* @__PURE__ */ new Set();
1266
+ for (const capability of capabilities) {
1267
+ if (!capability.tools.some((tool) => toolExists(tool))) continue;
1268
+ for (const plugin of capability.pluginIds) known.add(plugin);
1269
+ }
1270
+ const manager = ctx.get("pluginManager");
1271
+ if (typeof manager?.listBundles === "function") try {
1272
+ for (const bundle of await manager.listBundles()) if (typeof bundle.name === "string") known.add(bundle.name);
1273
+ } catch {}
1274
+ return known;
1275
+ }
1276
+ function isWorkflowBlueprint(value) {
1277
+ return typeof value === "object" && value !== null && value.schemaVersion === 1 && typeof value.id === "string" && typeof value.goal === "string" && Array.isArray(value.steps);
1278
+ }
1279
+ function isRecord(value) {
1280
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1281
+ }
1282
+ function stringValue(value) {
1283
+ return typeof value === "string" ? value : void 0;
1284
+ }
1285
+ function stringArray(value) {
1286
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : void 0;
1287
+ }
1288
+ // src/index.ts
1289
+ const name = "dsh-plugin-recipe";
1290
+ const inject = ["tools"];
1291
+ /** Register the workflow planner tools. */
1292
+ function apply(ctx, config) {
1293
+ const resolved = normalizeConfig(config);
1294
+ registerRecipeTools(ctx, resolved);
1295
+ registerRecipeApi(ctx, resolved);
1296
+ }
1297
+ export { BUILT_IN_CAPABILITIES, Config, apply, defaultsFor, exportBlueprint, inject, isWorkflowGoal, loadCapabilities, name, nextQuestion, renderBlueprintMarkdown, renderValidation, translateGoal, validateBlueprint };