dsh-desktop-kit 2.23.2 → 2.23.17

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.
Files changed (31) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +255 -245
  3. package/client.js +119 -2
  4. package/docs/AGENT-HARNESS.md +9 -0
  5. package/index.js +2 -0
  6. package/package.json +3 -3
  7. package/plugins/dsh-agent-extensions/README.md +5 -0
  8. package/plugins/dsh-agent-extensions/client.js +118 -1
  9. package/plugins/dsh-agent-extensions/index.js +24 -5
  10. package/plugins/dsh-agent-extensions/lib/agents.js +26 -3
  11. package/plugins/dsh-agent-extensions/lib/api.js +55 -1
  12. package/plugins/dsh-agent-extensions/lib/board.js +8 -2
  13. package/plugins/dsh-agent-extensions/lib/findings.js +67 -0
  14. package/plugins/dsh-agent-extensions/lib/project.js +2 -0
  15. package/plugins/dsh-agent-extensions/lib/routing.js +72 -0
  16. package/plugins/dsh-agent-extensions/lib/scaffold.js +120 -21
  17. package/plugins/dsh-agent-extensions/lib/settings.js +94 -0
  18. package/plugins/dsh-agent-extensions/lib/swarm.js +10 -5
  19. package/plugins/dsh-mcp-manager/README.md +10 -0
  20. package/plugins/dsh-mcp-manager/index.js +62 -2
  21. package/plugins/dsh-mcp-manager/lib/bootstrap.js +94 -0
  22. package/plugins/dsh-mcp-manager/lib/catalog.js +128 -0
  23. package/plugins/dsh-research-ledger/README.md +48 -0
  24. package/plugins/dsh-research-ledger/cordis.patch.yml +3 -0
  25. package/plugins/dsh-research-ledger/index.js +145 -0
  26. package/plugins/dsh-research-ledger/lib/ledger.js +346 -0
  27. package/plugins/dsh-research-ledger/package.json +25 -0
  28. package/plugins/dsh-skill-autopilot/index.js +65 -13
  29. package/skills/manifest.json +8 -8
  30. package/skills/research-first/SKILL.md +1 -0
  31. package/skills-baseline.json +480 -0
@@ -11,6 +11,8 @@
11
11
  import path from "node:path";
12
12
  import fs from "node:fs";
13
13
  import { loadConfig, writeTemplate, globalConfigPath } from "./lib/config.js";
14
+ import { catalogText, installCatalog, listCatalog } from "./lib/catalog.js";
15
+ import { BOOTSTRAP_IDS, bootstrapStatus, runBootstrap, setBootstrap, setBootstrapTrusted } from "./lib/bootstrap.js";
14
16
  import { McpManager } from "./lib/manager.js";
15
17
  import { registerApi } from "./lib/api.js";
16
18
 
@@ -47,8 +49,8 @@ function commandCwd(ctx) {
47
49
  function registerCommand(ctx, manager) {
48
50
  ctx.commands.register({
49
51
  name: "mcp",
50
- description: "MCP-серверы: список, инструменты, prompts, resources, reload",
51
- input: { hint: "list | trust | untrust | tools [server] | prompts [server] | prompt <server> <name> [json] | call <server> <tool> [json] | resources <server> | read <server> <uri> | reload | init" },
52
+ description: "MCP-серверы: каталог, установка, bootstrap, список, инструменты, prompts, resources, reload",
53
+ input: { hint: "catalog | install <id> [--force] | bootstrap [status|on|off|run] | list | trust | untrust | tools [server] | prompts [server] | prompt <server> <name> [json] | call <server> <tool> [json] | resources <server> | read <server> <uri> | reload | init" },
52
54
  recordInput: false,
53
55
  async handler({ rawInput }) {
54
56
  const input = String(rawInput ?? "").trim();
@@ -58,6 +60,58 @@ function registerCommand(ctx, manager) {
58
60
  const result = writeTemplate();
59
61
  return { kind: "success", text: result.created ? `Создан ${result.file}` : `Уже существует: ${result.file}` };
60
62
  }
63
+ if (action === "catalog") {
64
+ return { kind: "success", text: catalogText(commandCwd(ctx)) };
65
+ }
66
+ if (action === "install") {
67
+ const id = rest[0];
68
+ if (!id) return { kind: "error", text: `/mcp install: укажите id (${listCatalog().map((entry) => entry.id).join(", ")})` };
69
+ try {
70
+ const result = installCatalog(id, { cwd: commandCwd(ctx), force: rest.includes("--force") });
71
+ return {
72
+ kind: "success",
73
+ text: `Установлен ${result.entry.id} → ${result.configPath}\ntrusted=false; включите и доверьте сервер в Settings → MCP (или mcp.json).${result.tokenRequired ? "\nНужен GitHub token в ~/.dsh/mcp.secrets.json." : ""}`,
74
+ };
75
+ } catch (error) {
76
+ return { kind: "error", text: `/mcp install: ${error instanceof Error ? error.message : String(error)}` };
77
+ }
78
+ }
79
+ if (action === "bootstrap") {
80
+ const sub = rest[0] ?? "status";
81
+ if (sub === "on") {
82
+ setBootstrap(true);
83
+ const result = runBootstrap({ cwd: commandCwd(ctx) });
84
+ return {
85
+ kind: "success",
86
+ text: `MCP bootstrap включён. Добавлено: ${result.installed.join(", ") || "—"}${result.skipped.length ? ` · уже есть/пропущено: ${result.skipped.join(", ")}` : ""}\ntrusted=false; включите серверы в Settings → MCP.`,
87
+ };
88
+ }
89
+ if (sub === "off") {
90
+ setBootstrap(false);
91
+ return { kind: "success", text: "MCP bootstrap выключен. Серверы и их настройки не удалены." };
92
+ }
93
+ if (sub === "run") {
94
+ const result = runBootstrap({ cwd: commandCwd(ctx) });
95
+ return { kind: "success", text: `MCP bootstrap: enabled=${result.enabled} · trusted=${result.trusted} · добавлено: ${result.installed.join(", ") || "—"} · пропущено: ${result.skipped.join(", ") || "—"}` };
96
+ }
97
+ if (sub === "trust" || sub === "untrust") {
98
+ const trusted = sub === "trust";
99
+ const result = setBootstrapTrusted(trusted);
100
+ const next = loadConfig({ cwd: commandCwd(ctx) });
101
+ await manager.close();
102
+ const connected = await manager.connectAll(next.servers.filter((server) => server.enabled && server.trusted));
103
+ manager.registerTools();
104
+ return {
105
+ kind: "success",
106
+ text: `MCP bootstrap: trusted=${trusted} · затронуто: ${result.affected.join(", ") || "—"} · подключено: ${connected.filter((item) => item.status === "fulfilled" && item.value.client).length}/${connected.length}\n${formatStatus(manager)}`,
107
+ };
108
+ }
109
+ const status = bootstrapStatus();
110
+ return {
111
+ kind: "success",
112
+ text: `MCP bootstrap: ${status.enabled ? "включён" : "выключен"} · trusted=${status.trusted}\nФайл: ${status.file}\nСерверы: ${BOOTSTRAP_IDS.join(", ")}\nНе установлено: ${status.pending.join(", ") || "—"}\nВключить: /mcp bootstrap on · доверять: /mcp bootstrap trust`,
113
+ };
114
+ }
61
115
  const config = loadConfig({ cwd: commandCwd(ctx) });
62
116
  if (action === "trust" || action === "untrust") {
63
117
  if (!config.projectConfig) return { kind: "error", text: "Нет .dsh/mcp.json в проекте." };
@@ -155,6 +209,12 @@ function registerCommand(ctx, manager) {
155
209
  }
156
210
 
157
211
  export function apply(ctx) {
212
+ try {
213
+ const boot = runBootstrap();
214
+ if (boot.installed.length > 0) ctx.logger?.info?.(`[mcp] bootstrap installed: ${boot.installed.join(", ")}`);
215
+ } catch (error) {
216
+ ctx.logger?.warn?.(`[mcp] bootstrap skipped: ${error instanceof Error ? error.message : String(error)}`);
217
+ }
158
218
  const manager = new McpManager(ctx);
159
219
  ctx.effect(() => () => manager.close(), "dsh-mcp-manager: connections");
160
220
  try {
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Opt-in MCP catalog bootstrap.
3
+ *
4
+ * The bootstrap only writes configuration. It never marks a server trusted and
5
+ * never starts a process, so enabling it is safe; the user still enables/trusts
6
+ * each server in Settings → MCP.
7
+ *
8
+ * State: ~/.dsh/mcp.bootstrap.json (0600). Env override: DSH_MCP_BOOTSTRAP=on.
9
+ */
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+
14
+ import { CATALOG, installCatalog } from "./catalog.js";
15
+ import { readGlobalConfig, setGlobalServerFlags } from "./config.js";
16
+
17
+ export const BOOTSTRAP_IDS = ["memory", "sequential-thinking", "github"];
18
+
19
+ function dshHome() {
20
+ return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
21
+ }
22
+
23
+ function statePath() {
24
+ return path.join(dshHome(), "mcp.bootstrap.json");
25
+ }
26
+
27
+ export function readBootstrap() {
28
+ try {
29
+ const parsed = JSON.parse(fs.readFileSync(statePath(), "utf8"));
30
+ return { enabled: parsed?.enabled === true, trusted: parsed?.trusted === true, installedAt: parsed?.installedAt ?? null, servers: Array.isArray(parsed?.servers) ? parsed.servers : [] };
31
+ } catch {
32
+ return { enabled: process.env.DSH_MCP_BOOTSTRAP === "on", trusted: false, installedAt: null, servers: [] };
33
+ }
34
+ }
35
+
36
+ export function writeBootstrap(state) {
37
+ const file = statePath();
38
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
39
+ fs.writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600, encoding: "utf8" });
40
+ return file;
41
+ }
42
+
43
+ export function setBootstrap(enabled) {
44
+ const current = readBootstrap();
45
+ return writeBootstrap({ ...current, enabled: enabled === true });
46
+ }
47
+
48
+ /** Explicit bulk trust switch for servers that bootstrap itself installed. */
49
+ export function setBootstrapTrusted(enabled) {
50
+ const current = readBootstrap();
51
+ const config = readGlobalConfig();
52
+ const affected = [];
53
+ for (const id of BOOTSTRAP_IDS) {
54
+ if (!config.mcpServers?.[id]) continue;
55
+ setGlobalServerFlags(id, { trusted: enabled === true, enabled: true });
56
+ affected.push(id);
57
+ }
58
+ writeBootstrap({ ...current, trusted: enabled === true });
59
+ return { trusted: enabled === true, affected };
60
+ }
61
+
62
+ export function bootstrapStatus() {
63
+ const state = readBootstrap();
64
+ return {
65
+ ...state,
66
+ file: statePath(),
67
+ pending: BOOTSTRAP_IDS.filter((id) => !readGlobalConfig().mcpServers?.[id]),
68
+ catalog: BOOTSTRAP_IDS.map((id) => CATALOG.find((entry) => entry.id === id)).filter(Boolean),
69
+ };
70
+ }
71
+
72
+ export function runBootstrap({ cwd = process.cwd() } = {}) {
73
+ const state = readBootstrap();
74
+ if (!state.enabled) return { enabled: false, installed: [], skipped: [], file: statePath() };
75
+ const config = readGlobalConfig();
76
+ const installed = [];
77
+ const skipped = [];
78
+ for (const id of BOOTSTRAP_IDS) {
79
+ if (config.mcpServers?.[id]) {
80
+ skipped.push(id);
81
+ continue;
82
+ }
83
+ try {
84
+ installCatalog(id, { cwd, trusted: state.trusted === true });
85
+ installed.push(id);
86
+ } catch (error) {
87
+ skipped.push(`${id} (${error instanceof Error ? error.message : String(error)})`);
88
+ }
89
+ }
90
+ if (installed.length > 0) {
91
+ writeBootstrap({ ...state, installedAt: new Date().toISOString(), servers: [...new Set([...(state.servers ?? []), ...installed])] });
92
+ }
93
+ return { enabled: true, trusted: state.trusted === true, installed, skipped, file: statePath() };
94
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Local, pinned MCP marketplace.
3
+ *
4
+ * A catalog entry is a reviewed stdio server, not an arbitrary command. Install
5
+ * writes it to the global config with `trusted:false`; starting it remains an
6
+ * explicit user decision in Settings → MCP.
7
+ */
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+
12
+ import { globalConfigPath, readGlobalConfig, upsertGlobalServer } from "./config.js";
13
+
14
+ export const CATALOG_SCHEMA = 1;
15
+
16
+ export const CATALOG = [
17
+ {
18
+ id: "filesystem",
19
+ title: "Filesystem",
20
+ description: "Secure file operations for one workspace directory.",
21
+ package: "@modelcontextprotocol/server-filesystem@2.3.0",
22
+ command: "cmd",
23
+ args: ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem@2.3.0", "{cwd}"],
24
+ env: {},
25
+ docs: "https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem",
26
+ risk: "read/write in the selected workspace",
27
+ needsToken: false,
28
+ },
29
+ {
30
+ id: "memory",
31
+ title: "Memory",
32
+ description: "Knowledge graph stored locally at ~/.dsh/mcp-memory.json.",
33
+ package: "@modelcontextprotocol/server-memory@2.1.1",
34
+ command: "cmd",
35
+ args: ["/c", "npx", "-y", "@modelcontextprotocol/server-memory@2.1.1"],
36
+ env: { MEMORY_FILE_PATH: "{home}/mcp-memory.json" },
37
+ docs: "https://github.com/modelcontextprotocol/servers/tree/main/src/memory",
38
+ risk: "local graph file",
39
+ needsToken: false,
40
+ },
41
+ {
42
+ id: "sequential-thinking",
43
+ title: "Sequential Thinking",
44
+ description: "Step-by-step reasoning scratchpad.",
45
+ package: "@modelcontextprotocol/server-sequential-thinking@2.1.1",
46
+ command: "cmd",
47
+ args: ["/c", "npx", "-y", "@modelcontextprotocol/server-sequential-thinking@2.1.1"],
48
+ env: {},
49
+ docs: "https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking",
50
+ risk: "no filesystem access",
51
+ needsToken: false,
52
+ },
53
+ {
54
+ id: "github",
55
+ title: "GitHub",
56
+ description: "GitHub API tools: repositories, issues and pull requests.",
57
+ package: "@modelcontextprotocol/server-github@2025.4.8",
58
+ command: "cmd",
59
+ args: ["/c", "npx", "-y", "@modelcontextprotocol/server-github@2025.4.8"],
60
+ env: {
61
+ GITHUB_PERSONAL_ACCESS_TOKEN: "${secret:github.token}",
62
+ GITHUB_TOKEN: "${secret:github.token}",
63
+ },
64
+ docs: "https://github.com/modelcontextprotocol/servers-archived/tree/main/src/github",
65
+ risk: "uses a GitHub token; grant minimum scopes",
66
+ needsToken: true,
67
+ },
68
+ ];
69
+
70
+ function homeDir() {
71
+ return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
72
+ }
73
+
74
+ export function listCatalog() {
75
+ return CATALOG.map((entry) => ({
76
+ id: entry.id,
77
+ title: entry.title,
78
+ description: entry.description,
79
+ package: entry.package,
80
+ risk: entry.risk,
81
+ needsToken: entry.needsToken,
82
+ docs: entry.docs,
83
+ }));
84
+ }
85
+
86
+ function resolve(value, cwd) {
87
+ return String(value)
88
+ .replaceAll("{cwd}", path.resolve(cwd))
89
+ .replaceAll("{home}", homeDir().replaceAll("\\", "/"));
90
+ }
91
+
92
+ export function catalogText(cwd = process.cwd()) {
93
+ return [
94
+ `MCP marketplace (${CATALOG.length} pinned servers):`,
95
+ ...listCatalog().map((entry) => `- ${entry.id} · ${entry.title}${entry.needsToken ? " · token" : ""} — ${entry.description}\n ${entry.risk} · ${entry.docs}`),
96
+ "",
97
+ "Установить: /mcp install <id> [--force]",
98
+ "После установки: Settings → MCP → включить/доверить (trusted=false по умолчанию).",
99
+ ].join("\n");
100
+ }
101
+
102
+ export function installCatalog(id, { cwd = process.cwd(), force = false, trusted = false } = {}) {
103
+ const entry = CATALOG.find((item) => item.id === String(id));
104
+ if (!entry) throw new Error(`MCP catalog: unknown id "${id}"`);
105
+ const current = readGlobalConfig();
106
+ if (current.mcpServers?.[entry.id] && !force) throw new Error(`MCP ${entry.id} уже установлен; используйте --force`);
107
+ const env = Object.fromEntries(Object.entries(entry.env).map(([key, value]) => [key, resolve(value, cwd)]));
108
+ const server = {
109
+ command: entry.command,
110
+ args: entry.args.map((arg) => resolve(arg, cwd)),
111
+ ...(Object.keys(env).length > 0 ? { env } : {}),
112
+ trusted: trusted === true,
113
+ enabled: true,
114
+ timeoutMs: 30_000,
115
+ };
116
+ const config = upsertGlobalServer(entry.id, server);
117
+ return {
118
+ entry,
119
+ configPath: globalConfigPath(),
120
+ server: config.mcpServers[entry.id],
121
+ tokenRequired: entry.needsToken,
122
+ file: globalConfigPath(),
123
+ };
124
+ }
125
+
126
+ export function catalogEntry(id) {
127
+ return CATALOG.find((item) => item.id === String(id)) ?? null;
128
+ }
@@ -0,0 +1,48 @@
1
+ # dsh-research-ledger
2
+
3
+ Доказательный журнал для веб-исследований: каждое внешнее утверждение получает
4
+ источник, дату, цитату и статус проверки.
5
+
6
+ ## Инструмент `research_ledger`
7
+
8
+ ```text
9
+ research_ledger action=plan question="..." freshness=week domains=["api-docs.deepseek.com"]
10
+ research_ledger action=record claim="..." url="https://..." sourceDate=2026-11-12
11
+ topic="pricing" quote="..." confidence=high
12
+ research_ledger action=verify
13
+ research_ledger action=summary
14
+ research_ledger action=list
15
+ research_ledger action=clear confirm=true
16
+ ```
17
+
18
+ `plan` строит 4–8 запросов: исходный вопрос, official documentation, changelog,
19
+ `site:github.com`, указанные домены; плюс checklist и freshness policy.
20
+ `verify` кэширует проверку на 7 дней; `force=true` проверяет заново.
21
+
22
+ `plan` также создаёт DAG: `q1… → verify → synthesize`. Двигай статусы:
23
+
24
+ ```text
25
+ research_ledger action=progress node=q1 status=done evidence="2 sources checked"
26
+ ```
27
+
28
+
29
+ ## Что проверяет
30
+
31
+ - URL только публичный `http(s)`; `localhost`, приватные IP и credentials
32
+ запрещены (защита от SSRF);
33
+ - нет даты источника, дата старше 365 дней;
34
+ - ссылка недоступна при `verify`;
35
+ - claim без второго источника по `topic`;
36
+ - `contested` — источник(и) противоречат друг другу;
37
+ - нет цитаты.
38
+
39
+ Ledger: `.dsh/research/ledger.json` (до 300 claim). Системный промпт получает
40
+ короткую сводку, чтобы модель видела пробелы до финального ответа.
41
+
42
+ ## Ограничения
43
+
44
+ - Проверка ссылки — сетевой GET с таймаутом 8 секунд; 403/бот-защита считается
45
+ недоступной, а не «ложью».
46
+ - Противоречия помечаются вручную/агентом через `contested`; это не NLP-анализ.
47
+ - Не храните секреты, токены и приватные URL.
48
+
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-research-ledger
3
+ name: dsh-research-ledger
@@ -0,0 +1,145 @@
1
+ /**
2
+ * dsh-research-ledger — external claims with sources, dates and verification.
3
+ */
4
+ import path from "node:path";
5
+
6
+ import { addClaim, buildResearchPlan, ledgerText, planText, readLedger, summarize, updatePlanProgress, verifyClaims, writeLedger, writeResearchPlan } from "./lib/ledger.js";
7
+
8
+ export const inject = ["tools", "systemPrompt"];
9
+
10
+ function rootOf(exec) {
11
+ const cwd = exec?.agent?.session?.header?.cwd;
12
+ return path.resolve(typeof cwd === "string" && cwd.length > 0 ? cwd : process.cwd());
13
+ }
14
+
15
+ function text(value, max = 24_000) {
16
+ const result = String(value ?? "");
17
+ return result.length <= max ? result : `${result.slice(0, max)}\n…`;
18
+ }
19
+
20
+ function summaryText(summary) {
21
+ return [
22
+ `claims: ${summary.total} · verified: ${summary.verified} · unverified: ${summary.unverified}`,
23
+ ...(summary.warnings.length > 0 ? ["warnings:", ...summary.warnings.map((warning) => `- ${warning}`)] : ["warnings: нет"]),
24
+ ].join("\n");
25
+ }
26
+
27
+ export function apply(ctx) {
28
+ ctx.tools.register({
29
+ name: "research_ledger",
30
+ description:
31
+ "Evidence ledger and search planner for web research. Plan multi-query searches; record every external claim with a public URL, source date and quote; verify links with TTL; summarize missing/stale/single-source/contested evidence before the final answer. Never store secrets or private URLs.",
32
+ parameters: {
33
+ type: "object",
34
+ additionalProperties: false,
35
+ properties: {
36
+ action: { type: "string", enum: ["plan", "progress", "record", "list", "verify", "summary", "clear"], description: "plan | progress | record | list | verify | summary | clear" },
37
+ claim: { type: "string", description: "The factual claim being recorded (>= 8 chars)." },
38
+ question: { type: "string", description: "Research question for action=plan." },
39
+ node: { type: "string", description: "Plan node id for action=progress." },
40
+ status: { type: "string", enum: ["pending", "in_progress", "done", "blocked"], description: "Plan node status." },
41
+ evidence: { type: "string", description: "Evidence for plan progress." },
42
+ freshness: { type: "string", enum: ["day", "week", "month", "year", "any"], description: "Freshness policy for plan, default month." },
43
+ domains: { type: "array", items: { type: "string" }, description: "Optional source domains for plan." },
44
+ force: { type: "boolean", description: "Verify even when the cached check is fresh." },
45
+ url: { type: "string", description: "Public http(s) source URL." },
46
+ sourceDate: { type: "string", description: "Source publication date (YYYY-MM-DD or ISO)." },
47
+ quote: { type: "string", description: "Short supporting quote from the source." },
48
+ topic: { type: "string", description: "Topic/group key for duplicate and single-source checks." },
49
+ confidence: { type: "string", enum: ["low", "medium", "high"], description: "Author confidence, default medium." },
50
+ contested: { type: "boolean", description: "Mark a claim as contested by sources." },
51
+ tags: { type: "array", items: { type: "string" }, description: "Optional tags." },
52
+ id: { type: "string", description: "Claim id for verify (prefix allowed); omit to verify all." },
53
+ confirm: { type: "boolean", description: "Required for clear." },
54
+ },
55
+ required: ["action"],
56
+ },
57
+ timeoutMs: 120_000,
58
+ output: {
59
+ schema: { type: "object", additionalProperties: true },
60
+ render(_args, value) {
61
+ return [{ type: "text", text: text(typeof value?.text === "string" ? value.text : JSON.stringify(value)) }];
62
+ },
63
+ },
64
+ async execute(args, exec) {
65
+ const root = rootOf(exec);
66
+ const action = String(args?.action ?? "summary");
67
+ if (action === "plan") {
68
+ try {
69
+ const plan = buildResearchPlan(args?.question ?? "", { freshness: args?.freshness, domains: args?.domains });
70
+ const file = writeResearchPlan(root, plan);
71
+ return { ok: true, plan, file, text: `${planText(plan)}\n\nСохранено: ${file}` };
72
+ } catch (error) {
73
+ return { ok: false, text: `research_ledger plan: ${error instanceof Error ? error.message : String(error)}` };
74
+ }
75
+ }
76
+ if (action === "progress") {
77
+ try {
78
+ const result = updatePlanProgress(root, args?.node ?? "", { status: args?.status, evidence: args?.evidence });
79
+ return { ok: true, ...result, text: `plan ${result.node.id}: ${result.node.status} · осталось ${result.remaining}\n${planText(result.plan)}` };
80
+ } catch (error) {
81
+ return { ok: false, text: `research_ledger progress: ${error instanceof Error ? error.message : String(error)}` };
82
+ }
83
+ }
84
+ if (action === "record") {
85
+ try {
86
+ const result = addClaim(root, args);
87
+ const summary = summarize(result.ledger);
88
+ return {
89
+ ok: true,
90
+ duplicate: result.duplicate,
91
+ claim: result.claim,
92
+ summary,
93
+ text: `${result.duplicate ? "Уже записано" : "Записано"}: ${result.claim.id} · ${result.claim.claim}\n${summaryText(summary)}`,
94
+ };
95
+ } catch (error) {
96
+ return { ok: false, text: `research_ledger record: ${error instanceof Error ? error.message : String(error)}` };
97
+ }
98
+ }
99
+ if (action === "verify") {
100
+ const result = await verifyClaims(root, String(args?.id ?? "").trim(), { force: args?.force === true });
101
+ const summary = summarize(result.ledger);
102
+ return {
103
+ ok: true,
104
+ checked: result.checked,
105
+ skipped: result.skipped,
106
+ summary,
107
+ text: `Проверено: ${result.checked} · пропущено по TTL: ${result.skipped}\n${summaryText(summary)}`,
108
+ };
109
+ }
110
+ if (action === "list") {
111
+ const ledger = readLedger(root);
112
+ return { ok: true, total: ledger.claims.length, text: ledgerText(ledger) };
113
+ }
114
+ if (action === "clear") {
115
+ if (args?.confirm !== true) return { ok: false, text: "research_ledger clear: нужен confirm=true" };
116
+ writeLedger(root, { schema: 1, root, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), claims: [] });
117
+ return { ok: true, text: "Ledger очищен." };
118
+ }
119
+ const ledger = readLedger(root);
120
+ const summary = summarize(ledger);
121
+ return { ok: true, summary, text: `${ledgerText(ledger)}\n\n${summaryText(summary)}` };
122
+ },
123
+ });
124
+
125
+ ctx.systemPrompt.context({
126
+ name: "dsh-desktop-kit:research-ledger",
127
+ order: 134,
128
+ interpolate: false,
129
+ required: false,
130
+ text: (assemblyContext) => {
131
+ try {
132
+ const cwd = assemblyContext?.agent?.session?.header?.cwd;
133
+ if (typeof cwd !== "string" || cwd.length === 0) return "";
134
+ const ledger = readLedger(cwd);
135
+ if (ledger.claims.length === 0) return "";
136
+ const summary = summarize(ledger);
137
+ const warnings = summary.warnings.length > 0 ? summary.warnings.join("; ") : "нет";
138
+ return `<research-ledger claims="${summary.total}" verified="${summary.verified}" unverified="${summary.unverified}">${warnings}. Record claims with research_ledger; verify links; cite source date and URL in the final answer.</research-ledger>`;
139
+ } catch {
140
+ return "";
141
+ }
142
+ },
143
+ });
144
+ ctx.logger?.info?.("[research-ledger] tool + prompt context ready");
145
+ }