dsh-cwtools 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,93 +1,137 @@
1
- import { createToolCallHandler, getMcpToolRegistryMetadata, isMcpToolAvailable, listMcpToolSchemas } from "cwtools-shared";
2
1
  import z from "@deepseek-ai/schemastery";
2
+ import { createToolCallHandler, getMcpToolRegistryMetadata, isMcpToolAvailable, isMcpWriteToolName, listMcpToolSchemas } from "cwtools-shared";
3
3
  import path from "node:path";
4
- import { createNativeBridgeLspHost, createNodeHostServices, detectProjectSupport, discoverNativeBridge } from "cwtools-node";
4
+ import { createNativeBridgeIdeHost, createNativeBridgeLspHost, createNodeHostServices, detectProjectSupport, discoverNativeBridge } from "cwtools-node";
5
5
  // src/contract/toolCatalog.ts
6
- const CWTOOLS_READ_TOOL_GROUPS = {
7
- project: [
8
- "query_project_profile",
9
- "query_project_knowledge",
10
- "query_workspace_index",
11
- "explore_pdx_project",
12
- "analyze_pdx_flow",
13
- "query_inline_instantiation",
14
- "compare_definition_with_vanilla"
15
- ],
16
- localisation: ["query_localisation_index"],
17
- semantic: [
18
- "query_types",
19
- "query_rules",
20
- "query_cwt_schema",
21
- "search_rule_capabilities",
22
- "explain_scope",
23
- "parse_pdx_fragment",
24
- "query_scope",
25
- "query_scripted_effects",
26
- "query_scripted_triggers",
27
- "query_enums",
28
- "query_static_modifiers",
29
- "query_variables",
30
- "get_entity_info",
31
- "get_pdx_block",
32
- "query_targeting_weight"
33
- ],
34
- navigation: [
35
- "get_completion_at",
36
- "document_symbols",
37
- "workspace_symbols",
38
- "go_to_definition",
39
- "find_references"
40
- ],
41
- diagnostics: ["get_diagnostics", "analyze_diagnostic_error"],
42
- shader: [
43
- "query_shader_symbol",
44
- "query_shader_compile_unit",
45
- "query_shader_platform_variants",
46
- "query_shader_callers",
47
- "explain_shader_reachability",
48
- "validate_shader",
49
- "compare_shader_with_vanilla"
50
- ]
51
- };
52
- const CWTOOLS_READ_GROUP_ORDER = [
6
+ /**
7
+ * How the settings page groups the shared tool catalog.
8
+ *
9
+ * The catalog itself is owned by `cwtools-shared`: this module never keeps a
10
+ * copy of tool names. It only records which group a shared tool is presented
11
+ * under, so a tool added upstream appears in the page — and in the Host — on its
12
+ * own, with no edit here.
13
+ */
14
+ const CWTOOLS_READ_GROUPS = [
53
15
  "project",
54
16
  "localisation",
55
17
  "semantic",
56
18
  "navigation",
57
19
  "diagnostics",
58
- "shader"
20
+ "shader",
21
+ "ide"
59
22
  ];
60
- const CWTOOLS_READ_TOOL_NAMES = Object.freeze(CWTOOLS_READ_GROUP_ORDER.flatMap((group) => [...CWTOOLS_READ_TOOL_GROUPS[group]]));
61
- const CWTOOLS_WRITE_TOOL_NAMES = ["write_localisation"];
62
- const CWTOOLS_FIRST_RELEASE_TOOL_NAMES = [...CWTOOLS_READ_TOOL_NAMES, ...CWTOOLS_WRITE_TOOL_NAMES];
63
- const CWTOOLS_STELLARIS_ONLY_TOOLS = /* @__PURE__ */ new Set(["query_targeting_weight"]);
64
- const groupByTool = /* @__PURE__ */ new Map();
65
- for (const group of CWTOOLS_READ_GROUP_ORDER) for (const name of CWTOOLS_READ_TOOL_GROUPS[group]) groupByTool.set(name, group);
23
+ /** Groups in the order the settings page renders them. */
24
+ const CWTOOLS_READ_GROUP_ORDER = CWTOOLS_READ_GROUPS;
25
+ /**
26
+ * Tools that belong to a specific group rather than the group their shared
27
+ * effect implies. Only tools whose purpose the effect cannot express, or whose
28
+ * group assignment is otherwise surprising, need an entry; everything else
29
+ * falls back to {@link cwtoolsReadGroupForEffect}.
30
+ */
31
+ const GROUP_OVERRIDES = {
32
+ query_localisation_index: "localisation",
33
+ get_diagnostics: "diagnostics",
34
+ analyze_diagnostic_error: "diagnostics",
35
+ get_ide_context: "ide",
36
+ open_in_visual_editor: "ide",
37
+ query_shader_symbol: "shader",
38
+ query_shader_compile_unit: "shader",
39
+ query_shader_platform_variants: "shader",
40
+ query_shader_callers: "shader",
41
+ explain_shader_reachability: "shader",
42
+ validate_shader: "shader",
43
+ compare_shader_with_vanilla: "shader"
44
+ };
45
+ /**
46
+ * Tools that only answer inside a workspace with a full game model. Everything
47
+ * else a host cannot run is filtered per call by `isMcpToolAvailable`
48
+ * (CWT-only workspaces, write policy) instead of by name.
49
+ */
50
+ const GAME_MODEL_TOOLS = { query_targeting_weight: "stellaris" };
51
+ function readGroupForEffect(name, effect) {
52
+ const override = GROUP_OVERRIDES[name];
53
+ if (override !== void 0) return override;
54
+ switch (effect) {
55
+ case "workspace_read": return "semantic";
56
+ case "memory":
57
+ case "none": return "project";
58
+ default: return "semantic";
59
+ }
60
+ }
61
+ function buildCatalog() {
62
+ return listMcpToolSchemas({ includeWrites: true }).map((schema) => {
63
+ const metadata = getMcpToolRegistryMetadata(schema.name);
64
+ const isWrite = isMcpWriteToolName(schema.name) || metadata?.isWrite === true;
65
+ return {
66
+ name: schema.name,
67
+ description: schema.description,
68
+ inputSchema: schema.inputSchema,
69
+ isWrite,
70
+ group: readGroupForEffect(schema.name, metadata?.effect)
71
+ };
72
+ });
73
+ }
74
+ /** Every tool the shared catalog publishes, read once at load. */
75
+ const CWTOOLS_CATALOG = Object.freeze(buildCatalog());
76
+ const byName = new Map(CWTOOLS_CATALOG.map((entry) => [entry.name, entry]));
77
+ Object.freeze(CWTOOLS_READ_GROUP_ORDER.flatMap((group) => CWTOOLS_CATALOG.filter((entry) => !entry.isWrite && entry.group === group).map((entry) => entry.name)));
78
+ Object.freeze(CWTOOLS_READ_GROUP_ORDER.reduce((groups, group) => {
79
+ groups[group] = CWTOOLS_CATALOG.filter((entry) => !entry.isWrite && entry.group === group).map((entry) => entry.name);
80
+ return groups;
81
+ }, {}));
82
+ Object.freeze(CWTOOLS_CATALOG.filter((entry) => entry.isWrite).map((entry) => entry.name));
83
+ /** @returns the catalog entry of one tool, or undefined when the shared catalog has no such tool. */
84
+ function cwtoolsCatalogEntry(name) {
85
+ return byName.get(name);
86
+ }
87
+ /** @returns whether the shared catalog publishes this tool as read-only. */
66
88
  function isCwtoolsReadToolName(name) {
67
- return groupByTool.has(name);
89
+ const entry = byName.get(name);
90
+ return entry !== void 0 && !entry.isWrite;
68
91
  }
92
+ /** @returns whether the shared catalog publishes this tool as a write. */
69
93
  function isCwtoolsWriteToolName(name) {
70
- return CWTOOLS_WRITE_TOOL_NAMES.includes(name);
94
+ const entry = byName.get(name);
95
+ return entry === void 0 ? isMcpWriteToolName(name) : entry.isWrite;
71
96
  }
97
+ /**
98
+ * The catalog group a read tool is presented under.
99
+ * @throws when the shared catalog has no such read tool.
100
+ */
72
101
  function cwtoolsReadGroupFor(name) {
73
- const group = groupByTool.get(name);
74
- if (group === void 0) throw new Error("Unknown CWTools read tool: " + name);
75
- return group;
102
+ const entry = byName.get(name);
103
+ if (entry === void 0 || entry.isWrite) throw new Error("Unknown CWTools read tool: " + name);
104
+ return entry.group;
105
+ }
106
+ /**
107
+ * The game model a tool needs, when it only answers against a full game workspace.
108
+ * @returns the game identifier, or undefined when the tool works anywhere.
109
+ */
110
+ function cwtoolsGameModelFor(name) {
111
+ return GAME_MODEL_TOOLS[name];
76
112
  }
77
113
  // src/config.ts
78
114
  const timer = z.number().step(1).min(1).max(2147483647);
115
+ const defaultGroups = (enabled) => Object.fromEntries(CWTOOLS_READ_GROUPS.map((group) => [group, enabled]));
116
+ /**
117
+ * The tool ledger. Keys are not enumerated: the shared catalog publishes the
118
+ * tool set, and this schema only stores the grants someone overrode. A stored
119
+ * key for a tool the catalog no longer publishes is harmless.
120
+ */
121
+ const toolLedger = z.dict(z.boolean(), z.string()).default({});
79
122
  const Config = z.object({
80
- enabled: z.boolean().default(true),
123
+ enabled: z.boolean().default(true).volatile(),
81
124
  readGroups: z.object({
82
125
  project: z.boolean().default(true),
83
126
  localisation: z.boolean().default(true),
84
127
  semantic: z.boolean().default(true),
85
128
  navigation: z.boolean().default(true),
86
129
  diagnostics: z.boolean().default(true),
87
- shader: z.boolean().default(true)
88
- }).default({}),
89
- readTools: z.dict(z.boolean(), z.string()).default({}),
90
- writeTools: z.object({ write_localisation: z.boolean().default(false) }).default({}),
130
+ shader: z.boolean().default(true),
131
+ ide: z.boolean().default(true)
132
+ }).default({}).volatile(),
133
+ readTools: toolLedger.volatile(),
134
+ writeTools: toolLedger.volatile(),
91
135
  backend: z.object({
92
136
  serverPath: z.string().default(""),
93
137
  gamePath: z.string().default(""),
@@ -102,14 +146,63 @@ const Config = z.object({
102
146
  preferActiveBackend: z.boolean().default(true),
103
147
  activeManifestPath: z.string().default(""),
104
148
  debug: z.boolean().default(false)
105
- }).default({}),
106
- output: z.object({ maxResultChars: z.number().step(1).min(1e3).max(2e5).default(16e3) }).default({})
149
+ }).default({}).volatile(),
150
+ diagnostics: z.object({
151
+ ignoreCodes: z.array(z.string()).default([]),
152
+ ignoreFiles: z.array(z.string()).default([]),
153
+ localisationFilter: z.union([
154
+ z.const("off"),
155
+ z.const("problems"),
156
+ z.const("all")
157
+ ]).default("off")
158
+ }).default({}).volatile(),
159
+ output: z.object({ maxResultChars: z.number().step(1).min(1e3).max(2e5).default(16e3) }).default({}).volatile()
107
160
  });
161
+ /** Read every live section once so one operation sees one consistent configuration.
162
+ * @param config - the Host-provided live configuration.
163
+ * @returns plain values for the runtime, tools and their snapshots.
164
+ */
165
+ function snapshotConfig(config) {
166
+ return {
167
+ enabled: config.enabled.get(),
168
+ readGroups: {
169
+ ...defaultGroups(true),
170
+ ...config.readGroups.get()
171
+ },
172
+ readTools: { ...config.readTools.get() },
173
+ writeTools: { ...config.writeTools.get() },
174
+ backend: { ...config.backend.get() },
175
+ diagnostics: {
176
+ ignoreCodes: [...config.diagnostics.get().ignoreCodes],
177
+ ignoreFiles: [...config.diagnostics.get().ignoreFiles],
178
+ localisationFilter: config.diagnostics.get().localisationFilter
179
+ },
180
+ output: { ...config.output.get() }
181
+ };
182
+ }
183
+ /**
184
+ * Whether a read tool may run. A tool unknown to this build is not granted:
185
+ * the value must come from the shared catalog so a stale name cannot open a
186
+ * gate, and a stored `false` is the only per-tool opt-out.
187
+ * @param config - the snapshot the current operation runs against.
188
+ * @param name - the tool the model called.
189
+ * @returns whether the master switch, its group, and its own entry all allow it.
190
+ */
108
191
  function isReadToolEnabled(config, name) {
109
- return config.enabled && config.readGroups[cwtoolsReadGroupFor(name)] && config.readTools[name] !== false;
192
+ return config.enabled && isCwtoolsReadToolName(name) && config.readGroups[cwtoolsReadGroupFor(name)] === true && config.readTools[name] !== false;
110
193
  }
111
- function isWriteLocalisationEnabled(config) {
112
- return config.enabled && config.writeTools.write_localisation === true;
194
+ /**
195
+ * Whether the write allowlist names this tool.
196
+ * @param config - the snapshot the current operation runs against.
197
+ * @param name - the write tool the model called.
198
+ * @returns whether the operator explicitly allowed it.
199
+ */
200
+ function isWriteToolEnabled(config, name) {
201
+ return config.enabled && config.writeTools[name] === true;
202
+ }
203
+ /** @returns the write tools this configuration allows, in catalog order. */
204
+ function allowedWriteTools(config) {
205
+ return Object.keys(config.writeTools).filter((name) => isWriteToolEnabled(config, name));
113
206
  }
114
207
  // src/host/errors.ts
115
208
  var CwtoolsToolError = class extends Error {
@@ -192,7 +285,9 @@ function normalizeSuccessfulResult(result) {
192
285
  return normalized;
193
286
  }
194
287
  function errorFromSharedResult(result) {
195
- return new CwtoolsToolError(result.error?.code ?? result.status, result.error?.message ?? "CWTools tool call failed with status " + result.status + ".", result.nextSteps ?? []);
288
+ const code = result.error?.code ?? result.status;
289
+ const message = result.error?.message ?? "CWTools tool call failed with status " + result.status + ".";
290
+ return new CwtoolsToolError(code, result.error?.code ? message + " (" + result.error.code + ")" : message, result.nextSteps ?? []);
196
291
  }
197
292
  function renderCwtoolsResult(value, maxResultChars) {
198
293
  const text = JSON.stringify(value, null, 2) ?? "null";
@@ -241,17 +336,23 @@ const SUCCESS_OUTPUT_SCHEMA = {
241
336
  ]
242
337
  };
243
338
  // src/host/nativeTools.ts
339
+ /**
340
+ * Register one native DSH tool per shared-catalog entry.
341
+ *
342
+ * Every published tool is registered; whether it is exposed to a session is
343
+ * decided at call time by `runtime.canExpose`, which applies the configuration
344
+ * gate, the project shape and the host capability check. Registration therefore
345
+ * never encodes the catalog — a tool added upstream is registered by this loop
346
+ * with no change here.
347
+ */
244
348
  function registerNativeCwtoolsTools(ctx, config, runtime) {
245
349
  const disposers = [];
246
- const schemas = listMcpToolSchemas({ includeWrites: true });
247
- for (const schema of schemas) {
248
- if (!CWTOOLS_FIRST_RELEASE_TOOL_NAMES.includes(schema.name)) continue;
249
- if (isCwtoolsReadToolName(schema.name) && !isReadToolEnabled(config, schema.name)) continue;
250
- if (schema.name === "write_localisation" && !isWriteLocalisationEnabled(config)) continue;
251
- const definition = createNativeDefinition(ctx, config, runtime, schema);
350
+ for (const entry of CWTOOLS_CATALOG) {
351
+ if (isCwtoolsWriteToolName(entry.name) ? !isWriteToolEnabled(config, entry.name) : !isReadToolEnabled(config, entry.name)) continue;
352
+ const definition = createNativeDefinition(ctx, config, runtime, entry);
252
353
  disposers.push(ctx.tools.register(definition, { when: async ({ agent, signal }) => {
253
354
  const workspaceRoot = await ctx.workingDirectory.ensure(agent, signal);
254
- return runtime.canExpose(schema.name, workspaceRoot);
355
+ return runtime.canExposeWithHost(entry.name, workspaceRoot, signal);
255
356
  } }));
256
357
  }
257
358
  return () => {
@@ -311,10 +412,16 @@ async function resolveActiveBackend(config, workspaceRoot, signal) {
311
412
  if (discovery.kind === "unavailable") return void 0;
312
413
  return {
313
414
  lspHost: createNativeBridgeLspHost(discovery.manifest, discovery.readyAtMs),
415
+ ideHost: createNativeBridgeIdeHost(discovery.manifest),
314
416
  ...discovery.readyAtMs === void 0 ? {} : { readyAtMs: discovery.readyAtMs }
315
417
  };
316
418
  }
317
419
  // src/host/runtime.ts
420
+ function isActiveBackendLost(result) {
421
+ if (result.ok !== false || result.status !== "unavailable") return false;
422
+ const code = result.error?.code;
423
+ return code === "active_unavailable" || code === "bridge_unavailable";
424
+ }
318
425
  function optional(value) {
319
426
  const trimmed = value.trim();
320
427
  return trimmed === "" ? void 0 : trimmed;
@@ -333,21 +440,48 @@ var CwtoolsRuntimePool = class {
333
440
  canExpose(name, workspaceRoot) {
334
441
  return this.exposureReason(name, workspaceRoot) === void 0;
335
442
  }
443
+ async canExposeWithHost(name, workspaceRoot, signal) {
444
+ if (!this.canExpose(name, workspaceRoot)) return false;
445
+ if (cwtoolsCatalogEntry(name)?.group !== "ide") return true;
446
+ const project = this.resolveProject(workspaceRoot);
447
+ const existing = this.entries.get(project.root);
448
+ if (existing) return isMcpToolAvailable(name, {
449
+ includeWrites: this.config.writeTools[name] === true,
450
+ cwtOnly: project.kind === "cwt-only",
451
+ capabilities: existing.host.capabilities
452
+ });
453
+ if (!this.config.backend.preferActiveBackend) return false;
454
+ try {
455
+ return await resolveActiveBackend(this.config, project.root, signal) !== void 0;
456
+ } catch {
457
+ return false;
458
+ }
459
+ }
460
+ /**
461
+ * Why a tool may not run in this workspace, or undefined when it may.
462
+ *
463
+ * The shared catalog, not this package, owns the tool set: a name the catalog
464
+ * does not publish is refused here, and a published one is filtered by its
465
+ * group grant, the write allowlist and the host capability check instead of by
466
+ * a compiled list of first-release names.
467
+ */
336
468
  exposureReason(name, workspaceRoot) {
337
469
  if (this.disposed || !this.config.enabled) return "CWTools is disabled by configuration.";
338
470
  if (isCwtoolsReadToolName(name)) {
339
471
  if (!isReadToolEnabled(this.config, name)) return "Tool " + name + " is disabled by read-group or per-tool configuration.";
340
472
  } else if (isCwtoolsWriteToolName(name)) {
341
- if (!isWriteLocalisationEnabled(this.config)) return "Tool " + name + " requires an explicit write allowlist entry.";
342
- } else return "Tool " + name + " is outside the first-release CWTools catalog.";
473
+ if (!isWriteToolEnabled(this.config, name)) return "Tool " + name + " requires an explicit write allowlist entry.";
474
+ } else return "Tool " + name + " is not published by the active cwtools-shared catalog.";
343
475
  const project = this.resolveProject(workspaceRoot);
344
476
  if (!project.supported) return project.reason;
345
477
  const cwtOnly = project.kind === "cwt-only";
478
+ const writes = this.config.writeTools[name] === true;
346
479
  if (!isMcpToolAvailable(name, {
347
- includeWrites: isWriteLocalisationEnabled(this.config),
480
+ includeWrites: writes,
348
481
  cwtOnly
349
482
  })) return cwtOnly ? "Tool " + name + " is unavailable in a CWT-only workspace." : "Tool " + name + " is unavailable under the current write policy.";
350
- if (CWTOOLS_STELLARIS_ONLY_TOOLS.has(name) && project.game !== "stellaris") return "Tool " + name + " requires a Stellaris full-mod workspace.";
483
+ const gameModel = cwtoolsGameModelFor(name);
484
+ if (gameModel !== void 0 && project.game !== gameModel) return "Tool " + name + " requires a full " + gameModel + " game workspace.";
351
485
  }
352
486
  async execute(name, args, workspaceRoot, signal) {
353
487
  throwIfAborted(signal);
@@ -355,6 +489,15 @@ var CwtoolsRuntimePool = class {
355
489
  const denied = this.exposureReason(name, workspaceRoot);
356
490
  if (denied !== void 0) throw new CwtoolsToolError("tool_not_available", denied);
357
491
  const entry = await this.entryFor(workspaceRoot, signal);
492
+ const result = await this.invoke(entry, name, args, signal);
493
+ if (this.disposed || !entry.usedActiveBackend || !isActiveBackendLost(result)) return result;
494
+ this.entries.delete(entry.root);
495
+ this.disposeEntry(entry);
496
+ const retried = await this.entryFor(workspaceRoot, signal);
497
+ if (retried === entry) return result;
498
+ return await this.invoke(retried, name, args, signal);
499
+ }
500
+ async invoke(entry, name, args, signal) {
358
501
  if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
359
502
  const controller = new AbortController();
360
503
  const abort = () => {
@@ -435,25 +578,32 @@ var CwtoolsRuntimePool = class {
435
578
  if (active && "dispose" in active.lspHost && typeof active.lspHost.dispose === "function") active.lspHost.dispose();
436
579
  throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
437
580
  }
438
- const writes = isWriteLocalisationEnabled(this.config);
439
- const host = createNodeHostServices({
581
+ const allowedTools = allowedWriteTools(this.config);
582
+ const writes = allowedTools.length > 0;
583
+ const hostOptions = {
440
584
  workspaceRoot: project.root,
441
585
  game: project.game === "paradox" || project.game === "cwt" ? void 0 : project.game,
442
586
  serverPath: optional(this.config.backend.serverPath),
443
587
  gamePath: optional(this.config.backend.gamePath),
444
588
  cachePath: optional(this.config.backend.cachePath),
445
589
  rulesPath: optional(this.config.backend.rulesPath),
590
+ errorIgnoreCodes: this.config.diagnostics.ignoreCodes,
591
+ errorIgnoreFiles: this.config.diagnostics.ignoreFiles,
592
+ localisationDiagnosticFilter: this.config.diagnostics.localisationFilter,
446
593
  enableWrites: writes,
447
- allowedTools: writes ? ["write_localisation"] : [],
594
+ allowedTools,
448
595
  forceStart: this.config.backend.forceStart,
449
596
  startupTimeoutMs: this.config.backend.startupTimeoutMs,
450
597
  requestTimeoutMs: this.config.backend.requestTimeoutMs,
451
598
  debug: this.config.backend.debug,
599
+ honorWorkspaceIgnoreList: true,
452
600
  ...active === void 0 ? {} : {
453
601
  lspHost: active.lspHost,
602
+ ideHost: active.ideHost,
454
603
  readyAtMs: active.readyAtMs
455
604
  }
456
- });
605
+ };
606
+ const host = createNodeHostServices(hostOptions);
457
607
  const entry = {
458
608
  root: project.root,
459
609
  host,
@@ -462,7 +612,8 @@ var CwtoolsRuntimePool = class {
462
612
  queue: Promise.resolve(),
463
613
  active: 0,
464
614
  lastUsed: Date.now(),
465
- disposed: false
615
+ disposed: false,
616
+ usedActiveBackend: active !== void 0
466
617
  };
467
618
  this.entries.set(project.root, entry);
468
619
  this.enforceCapacity(entry);
@@ -518,22 +669,42 @@ const inject = [
518
669
  "systemPrompt",
519
670
  "workingDirectory"
520
671
  ];
521
- /** Register native CWTools tools and own every runtime resource in one effect. */
672
+ /** Register native CWTools tools and own every runtime resource in one effect.
673
+ * A settings save commits volatile values into this running instance, so the
674
+ * resources that capture them are rebuilt instead of waiting for a restart.
675
+ * @param ctx - the Host plugin context.
676
+ * @param config - the live configuration sections this entry owns.
677
+ */
522
678
  function apply(ctx, config) {
523
- if (!config.enabled) return;
524
- ctx.effect(() => {
525
- const runtime = new CwtoolsRuntimePool(config);
679
+ let dispose;
680
+ const mount = () => {
681
+ const values = snapshotConfig(config);
682
+ if (!values.enabled) return;
683
+ const runtime = new CwtoolsRuntimePool(values);
526
684
  const removePrompt = ctx.systemPrompt.section({
527
685
  name: "tool:cwtools",
528
686
  order: 2210,
529
687
  text: CWTOOLS_SYSTEM_PROMPT
530
688
  });
531
- const removeTools = registerNativeCwtoolsTools(ctx, config, runtime);
532
- return () => {
689
+ const removeTools = registerNativeCwtoolsTools(ctx, values, runtime);
690
+ dispose = () => {
533
691
  removeTools();
534
692
  removePrompt();
535
693
  runtime.dispose();
536
694
  };
695
+ };
696
+ const unmount = () => {
697
+ const current = dispose;
698
+ dispose = void 0;
699
+ current?.();
700
+ };
701
+ ctx.effect(() => {
702
+ mount();
703
+ return unmount;
537
704
  }, "cwtools: native tools and workspace runtimes");
705
+ ctx.on("loader/volatile-update", () => {
706
+ unmount();
707
+ mount();
708
+ });
538
709
  }
539
710
  export { Config, apply, inject, name };
@@ -2,11 +2,11 @@ import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client';
2
2
  import type { SnapshotStore } from '@deepseek-ai/dsh-client-store';
3
3
  import { type SettingsFieldState, type SettingsFormActions, type SettingsFormShell } from '@deepseek-ai/dsh-client-ui-primitives';
4
4
  import type { CwtoolsConfig } from '../contract/configTypes.ts';
5
- import { type CwtoolsReadGroup, type CwtoolsReadToolName } from '../contract/toolCatalog.ts';
5
+ import { type CwtoolsReadGroup } from '../contract/toolCatalog.ts';
6
6
  /** Settings namespace of the Host entry this section edits. */
7
7
  export declare const CWTOOLS_SETTINGS_NAMESPACE = "cwtools";
8
8
  /** Configuration block a leaf belongs to. */
9
- type CwtoolsBlock = 'enabled' | 'backend' | 'readGroups' | 'readTools' | 'writeTools' | 'output';
9
+ type CwtoolsBlock = 'enabled' | 'backend' | 'diagnostics' | 'readGroups' | 'readTools' | 'writeTools' | 'output';
10
10
  /** One leaf field of the section, addressed inside the Host document. */
11
11
  export interface CwtoolsFieldRef {
12
12
  /** Dotted path inside the namespace section. */
@@ -27,8 +27,8 @@ export interface CwtoolsSectionState extends SettingsFormShell {
27
27
  fields: Record<string, SettingsFieldState>;
28
28
  /** Effective on-state of each read group. */
29
29
  groups: Record<CwtoolsReadGroup, boolean>;
30
- /** Effective on-state of each tool: its own grant AND its group's. */
31
- tools: Record<CwtoolsReadToolName, boolean>;
30
+ /** Effective on-state of each read tool: its own grant AND its group's. */
31
+ tools: Record<string, boolean>;
32
32
  /** Whether the refused save lost a revision race with an edit made elsewhere. */
33
33
  conflict: boolean;
34
34
  /** Values the Host still holds after a refused save; empty otherwise. */
@@ -46,6 +46,8 @@ export interface CwtoolsSectionFace extends SettingsFormActions {
46
46
  */
47
47
  toggle: (field: string, next: boolean) => void;
48
48
  }
49
+ /** The three values the Host accepts for the localisation diagnostic filter. */
50
+ export declare const CWTOOLS_LOCALISATION_FILTERS: readonly ["off", "problems", "all"];
49
51
  /** Every control on the page, in rendering order. */
50
52
  export declare const CWTOOLS_FIELDS: readonly CwtoolsFieldRef[];
51
53
  /**
@@ -6,7 +6,7 @@
6
6
  * never translated.
7
7
  */
8
8
  /** Every key this section renders. */
9
- export type CwtoolsLocaleKey = 'nav' | 'title' | 'intro' | 'sectionBackend' | 'sectionReadAccess' | 'sectionWriteAccess' | 'sectionOutput' | 'enabled' | 'enabledHint' | 'serverPath' | 'serverPathHint' | 'gamePath' | 'gamePathHint' | 'rulesPath' | 'rulesPathHint' | 'cachePath' | 'cachePathHint' | 'activeManifestPath' | 'activeManifestPathHint' | 'preferActiveBackend' | 'preferActiveBackendHint' | 'game' | 'gameHint' | 'forceStart' | 'forceStartHint' | 'debug' | 'debugHint' | 'startupTimeoutMs' | 'startupTimeoutMsHint' | 'requestTimeoutMs' | 'requestTimeoutMsHint' | 'idleShutdownMs' | 'idleShutdownMsHint' | 'maxWorkspaceRuntimes' | 'maxWorkspaceRuntimesHint' | 'maxResultChars' | 'maxResultCharsHint' | 'writeLocalisation' | 'writeLocalisationHint' | 'writePolicyNote' | 'groupProject' | 'groupLocalisation' | 'groupSemantic' | 'groupNavigation' | 'groupDiagnostics' | 'groupShader' | 'groupDisabledNote' | 'readAccessIntro' | 'overridden' | 'reset' | 'invalidNumber' | 'readOnly' | 'unavailable' | 'save' | 'saving' | 'saveFailed' | 'failedTitle' | 'acceptedValue' | 'retryHint' | 'conflictNotice' | 'emptyValue' | 'on' | 'off';
9
+ export type CwtoolsLocaleKey = 'nav' | 'title' | 'intro' | 'sectionProject' | 'sectionBackend' | 'sectionReadAccess' | 'sectionDiagnostics' | 'sectionWriteAccess' | 'sectionOutput' | 'tabProject' | 'tabBackend' | 'tabRead' | 'tabOutput' | 'enabled' | 'enabledHint' | 'serverPath' | 'serverPathHint' | 'gamePath' | 'gamePathHint' | 'rulesPath' | 'rulesPathHint' | 'cachePath' | 'cachePathHint' | 'activeManifestPath' | 'activeManifestPathHint' | 'preferActiveBackend' | 'preferActiveBackendHint' | 'game' | 'gameHint' | 'forceStart' | 'forceStartHint' | 'debug' | 'debugHint' | 'startupTimeoutMs' | 'startupTimeoutMsHint' | 'requestTimeoutMs' | 'requestTimeoutMsHint' | 'idleShutdownMs' | 'idleShutdownMsHint' | 'maxWorkspaceRuntimes' | 'maxWorkspaceRuntimesHint' | 'maxResultChars' | 'maxResultCharsHint' | 'writeLocalisation' | 'writeLocalisationHint' | 'writePolicyNote' | 'groupProject' | 'groupLocalisation' | 'groupSemantic' | 'groupNavigation' | 'groupDiagnostics' | 'groupShader' | 'groupIde' | 'groupDisabledNote' | 'readAccessIntro' | 'ignoreCodes' | 'ignoreCodesHint' | 'ignoreFiles' | 'ignoreFilesHint' | 'localisationFilter' | 'localisationFilterHint' | 'localisationFilterOff' | 'localisationFilterProblems' | 'localisationFilterAll' | 'overridden' | 'reset' | 'invalidNumber' | 'readOnly' | 'unavailable' | 'save' | 'saving' | 'saveFailed' | 'failedTitle' | 'acceptedValue' | 'retryHint' | 'conflictNotice' | 'emptyValue' | 'on' | 'off';
10
10
  /** English copy. */
11
11
  export declare const en: Record<CwtoolsLocaleKey, string>;
12
12
  /** Simplified Chinese copy, checked against the English keys. */
@@ -1,7 +1,49 @@
1
+ import type { Volatile } from '@deepseek-ai/cordis';
1
2
  import z from '@deepseek-ai/schemastery';
2
- import type { CwtoolsConfig, CwtoolsConfigInput } from './contract/configTypes.ts';
3
- import { type CwtoolsReadToolName } from './contract/toolCatalog.ts';
3
+ import type { CwtoolsBackendConfig, CwtoolsConfig, CwtoolsConfigInput, CwtoolsDiagnosticsConfig } from './contract/configTypes.ts';
4
+ import { type CwtoolsReadGroup } from './contract/toolCatalog.ts';
5
+ /** Plain, unwrapped values the runtime consumes. */
4
6
  export type Config = CwtoolsConfig;
5
- export declare const Config: z<CwtoolsConfigInput, Config>;
6
- export declare function isReadToolEnabled(config: Config, name: CwtoolsReadToolName): boolean;
7
+ /**
8
+ * Host-provided live surface: the Host passes every editable section as a
9
+ * volatile reference, so a saved settings change reaches the running instance
10
+ * without remounting it. Sections without a volatile reference never appear in
11
+ * the Host settings page at all.
12
+ */
13
+ export interface CwtoolsLiveConfig {
14
+ enabled: Volatile<boolean>;
15
+ readGroups: Volatile<Record<CwtoolsReadGroup, boolean>>;
16
+ readTools: Volatile<Record<string, boolean>>;
17
+ writeTools: Volatile<Record<string, boolean>>;
18
+ backend: Volatile<CwtoolsBackendConfig>;
19
+ diagnostics: Volatile<CwtoolsDiagnosticsConfig>;
20
+ output: Volatile<{
21
+ maxResultChars: number;
22
+ }>;
23
+ }
24
+ export declare const Config: z<CwtoolsConfigInput, CwtoolsLiveConfig>;
25
+ /** Read every live section once so one operation sees one consistent configuration.
26
+ * @param config - the Host-provided live configuration.
27
+ * @returns plain values for the runtime, tools and their snapshots.
28
+ */
29
+ export declare function snapshotConfig(config: CwtoolsLiveConfig): Config;
30
+ /**
31
+ * Whether a read tool may run. A tool unknown to this build is not granted:
32
+ * the value must come from the shared catalog so a stale name cannot open a
33
+ * gate, and a stored `false` is the only per-tool opt-out.
34
+ * @param config - the snapshot the current operation runs against.
35
+ * @param name - the tool the model called.
36
+ * @returns whether the master switch, its group, and its own entry all allow it.
37
+ */
38
+ export declare function isReadToolEnabled(config: Config, name: string): boolean;
39
+ /**
40
+ * Whether the write allowlist names this tool.
41
+ * @param config - the snapshot the current operation runs against.
42
+ * @param name - the write tool the model called.
43
+ * @returns whether the operator explicitly allowed it.
44
+ */
45
+ export declare function isWriteToolEnabled(config: Config, name: string): boolean;
46
+ /** @deprecated Prefer {@link isWriteToolEnabled}; kept for the localisation settings path. */
7
47
  export declare function isWriteLocalisationEnabled(config: Config): boolean;
48
+ /** @returns the write tools this configuration allows, in catalog order. */
49
+ export declare function allowedWriteTools(config: Config): string[];
@@ -1,4 +1,4 @@
1
- import type { CwtoolsReadGroup, CwtoolsReadToolName, CwtoolsWriteToolName } from './toolCatalog.ts';
1
+ import type { CwtoolsReadGroup } from './toolCatalog.ts';
2
2
  export interface CwtoolsBackendConfig {
3
3
  serverPath: string;
4
4
  gamePath: string;
@@ -14,12 +14,29 @@ export interface CwtoolsBackendConfig {
14
14
  activeManifestPath: string;
15
15
  debug: boolean;
16
16
  }
17
+ /** How localisation diagnostics are filtered, mirroring the server's `errors.localisationFilter`. */
18
+ export type CwtoolsLocalisationFilter = 'off' | 'problems' | 'all';
19
+ /** Diagnostic noise controls forwarded to the backend. */
20
+ export interface CwtoolsDiagnosticsConfig {
21
+ /** Error codes (or message fragments) the backend never reports. */
22
+ ignoreCodes: string[];
23
+ /** File names whose diagnostics are dropped. */
24
+ ignoreFiles: string[];
25
+ /** Localisation diagnostic filter mode. */
26
+ localisationFilter: CwtoolsLocalisationFilter;
27
+ }
28
+ /**
29
+ * Read grants. Tool names are open strings: the shared catalog, not this
30
+ * package, decides which tools exist, so a tool published upstream is granted
31
+ * by its group until someone stores `readTools[name] = false`.
32
+ */
17
33
  export interface CwtoolsConfig {
18
34
  enabled: boolean;
19
35
  readGroups: Record<CwtoolsReadGroup, boolean>;
20
- readTools: Partial<Record<CwtoolsReadToolName, boolean>>;
21
- writeTools: Partial<Record<CwtoolsWriteToolName, boolean>>;
36
+ readTools: Record<string, boolean>;
37
+ writeTools: Record<string, boolean>;
22
38
  backend: CwtoolsBackendConfig;
39
+ diagnostics: CwtoolsDiagnosticsConfig;
23
40
  output: {
24
41
  maxResultChars: number;
25
42
  };
@@ -28,9 +45,10 @@ export interface CwtoolsConfig {
28
45
  export interface CwtoolsConfigInput {
29
46
  enabled?: boolean;
30
47
  readGroups?: Partial<Record<CwtoolsReadGroup, boolean>>;
31
- readTools?: Partial<Record<CwtoolsReadToolName, boolean>>;
32
- writeTools?: Partial<Record<CwtoolsWriteToolName, boolean>>;
48
+ readTools?: Record<string, boolean>;
49
+ writeTools?: Record<string, boolean>;
33
50
  backend?: Partial<CwtoolsBackendConfig>;
51
+ diagnostics?: Partial<CwtoolsDiagnosticsConfig>;
34
52
  output?: {
35
53
  maxResultChars?: number;
36
54
  };