dsh-cwtools 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,592 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { createToolCallHandler, getMcpToolRegistryMetadata, isMcpToolAvailable, listMcpToolSchemas } from "cwtools-shared";
3
+ import path from "node:path";
4
+ import { createNativeBridgeLspHost, createNodeHostServices, detectProjectSupport, discoverNativeBridge } from "cwtools-node";
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 = [
53
+ "project",
54
+ "localisation",
55
+ "semantic",
56
+ "navigation",
57
+ "diagnostics",
58
+ "shader"
59
+ ];
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);
66
+ function isCwtoolsReadToolName(name) {
67
+ return groupByTool.has(name);
68
+ }
69
+ function isCwtoolsWriteToolName(name) {
70
+ return CWTOOLS_WRITE_TOOL_NAMES.includes(name);
71
+ }
72
+ 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;
76
+ }
77
+ // src/config.ts
78
+ const timer = z.number().step(1).min(1).max(2147483647);
79
+ const Config = z.object({
80
+ enabled: z.boolean().default(true).volatile(),
81
+ readGroups: z.object({
82
+ project: z.boolean().default(true),
83
+ localisation: z.boolean().default(true),
84
+ semantic: z.boolean().default(true),
85
+ navigation: z.boolean().default(true),
86
+ diagnostics: z.boolean().default(true),
87
+ shader: z.boolean().default(true)
88
+ }).default({}).volatile(),
89
+ readTools: z.dict(z.boolean(), z.string()).default({}).volatile(),
90
+ writeTools: z.object({ write_localisation: z.boolean().default(false) }).default({}).volatile(),
91
+ backend: z.object({
92
+ serverPath: z.string().default(""),
93
+ gamePath: z.string().default(""),
94
+ rulesPath: z.string().default(""),
95
+ cachePath: z.string().default(""),
96
+ game: z.string().default(""),
97
+ forceStart: z.boolean().default(false),
98
+ startupTimeoutMs: timer.default(3e4),
99
+ requestTimeoutMs: timer.default(2e4),
100
+ idleShutdownMs: timer.default(6e5),
101
+ maxWorkspaceRuntimes: z.number().step(1).min(1).max(8).default(2),
102
+ preferActiveBackend: z.boolean().default(true),
103
+ activeManifestPath: z.string().default(""),
104
+ debug: z.boolean().default(false)
105
+ }).default({}).volatile(),
106
+ diagnostics: z.object({
107
+ ignoreCodes: z.array(z.string()).default([]),
108
+ ignoreFiles: z.array(z.string()).default([]),
109
+ localisationFilter: z.union([
110
+ z.const("off"),
111
+ z.const("problems"),
112
+ z.const("all")
113
+ ]).default("off")
114
+ }).default({}).volatile(),
115
+ output: z.object({ maxResultChars: z.number().step(1).min(1e3).max(2e5).default(16e3) }).default({}).volatile()
116
+ });
117
+ /** Read every live section once so one operation sees one consistent configuration.
118
+ * @param config - the Host-provided live configuration.
119
+ * @returns plain values for the runtime, tools and their snapshots.
120
+ */
121
+ function snapshotConfig(config) {
122
+ return {
123
+ enabled: config.enabled.get(),
124
+ readGroups: { ...config.readGroups.get() },
125
+ readTools: { ...config.readTools.get() },
126
+ writeTools: { ...config.writeTools.get() },
127
+ backend: { ...config.backend.get() },
128
+ diagnostics: {
129
+ ignoreCodes: [...config.diagnostics.get().ignoreCodes],
130
+ ignoreFiles: [...config.diagnostics.get().ignoreFiles],
131
+ localisationFilter: config.diagnostics.get().localisationFilter
132
+ },
133
+ output: { ...config.output.get() }
134
+ };
135
+ }
136
+ function isReadToolEnabled(config, name) {
137
+ return config.enabled && config.readGroups[cwtoolsReadGroupFor(name)] && config.readTools[name] !== false;
138
+ }
139
+ function isWriteLocalisationEnabled(config) {
140
+ return config.enabled && config.writeTools.write_localisation === true;
141
+ }
142
+ // src/host/errors.ts
143
+ var CwtoolsToolError = class extends Error {
144
+ code;
145
+ nextSteps;
146
+ name = "CwtoolsToolError";
147
+ constructor(code, message, nextSteps = []) {
148
+ super(nextSteps.length === 0 ? message : message + "\nNext steps:\n- " + nextSteps.join("\n- "));
149
+ this.code = code;
150
+ this.nextSteps = nextSteps;
151
+ }
152
+ };
153
+ function abortError(reason) {
154
+ const error = reason instanceof Error ? reason : new Error(reason === void 0 ? "Operation cancelled." : String(reason));
155
+ error.name = "AbortError";
156
+ return error;
157
+ }
158
+ function throwIfAborted(signal) {
159
+ if (signal?.aborted === true) throw abortError(signal.reason);
160
+ }
161
+ async function awaitWithAbort(promise, signal) {
162
+ if (signal === void 0) return await promise;
163
+ throwIfAborted(signal);
164
+ let listener;
165
+ const aborted = new Promise((_, reject) => {
166
+ listener = () => {
167
+ reject(abortError(signal.reason));
168
+ };
169
+ signal.addEventListener("abort", listener, { once: true });
170
+ });
171
+ try {
172
+ return await Promise.race([promise, aborted]);
173
+ } finally {
174
+ if (listener !== void 0) signal.removeEventListener("abort", listener);
175
+ }
176
+ }
177
+ // src/host/results.ts
178
+ const SUCCESS_STATUSES = /* @__PURE__ */ new Set([
179
+ "ready",
180
+ "partial",
181
+ "success",
182
+ "loading",
183
+ "stale"
184
+ ]);
185
+ function normalizeJson(value, seen, path) {
186
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
187
+ if (typeof value === "number") {
188
+ if (!Number.isFinite(value)) throw new CwtoolsToolError("invalid_result", path + " contains a non-finite number.");
189
+ return value;
190
+ }
191
+ if (Array.isArray(value)) {
192
+ if (seen.has(value)) throw new CwtoolsToolError("invalid_result", path + " contains a cycle.");
193
+ seen.add(value);
194
+ const result = value.map((entry, index) => {
195
+ if (entry === void 0) throw new CwtoolsToolError("invalid_result", path + "[" + index + "] is undefined.");
196
+ return normalizeJson(entry, seen, path + "[" + index + "]");
197
+ });
198
+ seen.delete(value);
199
+ return result;
200
+ }
201
+ if (typeof value === "object" && value !== null) {
202
+ const prototype = Object.getPrototypeOf(value);
203
+ if (prototype !== Object.prototype && prototype !== null) throw new CwtoolsToolError("invalid_result", path + " contains a non-plain object.");
204
+ if (seen.has(value)) throw new CwtoolsToolError("invalid_result", path + " contains a cycle.");
205
+ seen.add(value);
206
+ const result = {};
207
+ for (const key of Object.keys(value).sort()) {
208
+ const entry = value[key];
209
+ if (entry === void 0) continue;
210
+ result[key] = normalizeJson(entry, seen, path + "." + key);
211
+ }
212
+ seen.delete(value);
213
+ return result;
214
+ }
215
+ throw new CwtoolsToolError("invalid_result", path + " contains a non-JSON value of type " + typeof value + ".");
216
+ }
217
+ function normalizeSuccessfulResult(result) {
218
+ const normalized = normalizeJson(result, /* @__PURE__ */ new WeakSet(), "$");
219
+ if (normalized.ok !== true || !SUCCESS_STATUSES.has(normalized.status) || typeof normalized.source !== "string") throw new CwtoolsToolError("invalid_result", "CWTools returned an invalid success envelope.");
220
+ return normalized;
221
+ }
222
+ function errorFromSharedResult(result) {
223
+ return new CwtoolsToolError(result.error?.code ?? result.status, result.error?.message ?? "CWTools tool call failed with status " + result.status + ".", result.nextSteps ?? []);
224
+ }
225
+ function renderCwtoolsResult(value, maxResultChars) {
226
+ const text = JSON.stringify(value, null, 2) ?? "null";
227
+ if (text.length <= maxResultChars) return text;
228
+ const omitted = text.length - maxResultChars;
229
+ return text.slice(0, maxResultChars) + "\n… [truncated " + omitted + " characters; canonical tool result is unchanged]";
230
+ }
231
+ const SUCCESS_OUTPUT_SCHEMA = {
232
+ type: "object",
233
+ additionalProperties: false,
234
+ properties: {
235
+ ok: { type: "boolean" },
236
+ status: {
237
+ type: "string",
238
+ enum: [
239
+ "ready",
240
+ "partial",
241
+ "success",
242
+ "loading",
243
+ "stale"
244
+ ]
245
+ },
246
+ source: { type: "string" },
247
+ data: {},
248
+ warnings: {
249
+ type: "array",
250
+ items: { type: "string" }
251
+ },
252
+ nextSteps: {
253
+ type: "array",
254
+ items: { type: "string" }
255
+ },
256
+ vanillaCache: {
257
+ type: "object",
258
+ additionalProperties: true
259
+ },
260
+ readiness: {
261
+ type: "object",
262
+ additionalProperties: true
263
+ }
264
+ },
265
+ required: [
266
+ "ok",
267
+ "status",
268
+ "source"
269
+ ]
270
+ };
271
+ // src/host/nativeTools.ts
272
+ function registerNativeCwtoolsTools(ctx, config, runtime) {
273
+ const disposers = [];
274
+ const schemas = listMcpToolSchemas({ includeWrites: true });
275
+ for (const schema of schemas) {
276
+ if (!CWTOOLS_FIRST_RELEASE_TOOL_NAMES.includes(schema.name)) continue;
277
+ if (isCwtoolsReadToolName(schema.name) && !isReadToolEnabled(config, schema.name)) continue;
278
+ if (schema.name === "write_localisation" && !isWriteLocalisationEnabled(config)) continue;
279
+ const definition = createNativeDefinition(ctx, config, runtime, schema);
280
+ disposers.push(ctx.tools.register(definition, { when: async ({ agent, signal }) => {
281
+ const workspaceRoot = await ctx.workingDirectory.ensure(agent, signal);
282
+ return runtime.canExpose(schema.name, workspaceRoot);
283
+ } }));
284
+ }
285
+ return () => {
286
+ for (const dispose of disposers.reverse()) dispose();
287
+ };
288
+ }
289
+ function createNativeDefinition(ctx, config, runtime, schema) {
290
+ return {
291
+ name: schema.name,
292
+ description: schema.description,
293
+ parameters: schema.inputSchema,
294
+ timeoutMs: Math.min(2147483647, config.backend.startupTimeoutMs + config.backend.requestTimeoutMs),
295
+ output: {
296
+ schema: SUCCESS_OUTPUT_SCHEMA,
297
+ render: (_args, value) => [{
298
+ type: "text",
299
+ text: renderCwtoolsResult(value, config.output.maxResultChars)
300
+ }]
301
+ },
302
+ isConcurrencySafe: () => getMcpToolRegistryMetadata(schema.name)?.concurrencyClass === "parallel",
303
+ async execute(args, exec) {
304
+ if (exec.agent === void 0) throw new CwtoolsToolError("workspace_required", "CWTools tools require an Agent Session working directory.");
305
+ const workspaceRoot = await ctx.workingDirectory.ensure(exec.agent, exec.signal);
306
+ const record = typeof args === "object" && args !== null && !Array.isArray(args) ? args : {};
307
+ const result = await runtime.execute(schema.name, record, workspaceRoot, exec.signal);
308
+ if (!result.ok) throw errorFromSharedResult(result);
309
+ return normalizeSuccessfulResult(result);
310
+ },
311
+ presentCall: () => ({
312
+ card: "generic",
313
+ title: "CWTools: " + schema.name
314
+ })
315
+ };
316
+ }
317
+ // src/host/prompt.ts
318
+ const CWTOOLS_SYSTEM_PROMPT = `CWTools provides native semantic and explicitly allowed domain-write tools for Paradox mods. Ground claims about the mod in these tools rather than memory: PDX identifiers and syntax are easy to hallucinate.
319
+
320
+ When working in a Paradox mod:
321
+ - Start structural and dependency questions with explore_pdx_project.
322
+ - Verify game IDs with query_types and the appropriate scripted effect/trigger, enum, modifier, or variable query before using them.
323
+ - Check trigger/effect/scope/modifier syntax with query_rules and query_scope; check block and entity schemas with query_cwt_schema before writing.
324
+ - Navigate with go_to_definition/find_references/document_symbols/workspace_symbols and use get_pdx_block for structured blocks.
325
+ - Respect readiness and freshness. A loading result or an empty result while readiness.ready is false is not authoritative; retry after loading.
326
+ - Respect vanillaCache provenance. When vanilla is unavailable, results are mod-only and vanilla references may produce incomplete answers or false errors.
327
+ - Review get_diagnostics before declaring code correct. After an allowed write, re-check fresh diagnostics.
328
+ - Only whitelisted domain writes may be used, and only when enabled by the user. Never treat a denied write as completed.`;
329
+ // src/host/activeBackend.ts
330
+ /** Resolve a healthy active host only for the exact current mod root. */
331
+ async function resolveActiveBackend(config, workspaceRoot, signal) {
332
+ const manifestPath = config.backend.activeManifestPath.trim() || void 0;
333
+ const discovery = await discoverNativeBridge(workspaceRoot, {
334
+ manifestPath,
335
+ timeoutMs: config.backend.requestTimeoutMs,
336
+ signal
337
+ });
338
+ if (discovery.kind === "incompatible") throw new CwtoolsToolError("backend_incompatible", discovery.reason);
339
+ if (discovery.kind === "unavailable") return void 0;
340
+ return {
341
+ lspHost: createNativeBridgeLspHost(discovery.manifest, discovery.readyAtMs),
342
+ ...discovery.readyAtMs === void 0 ? {} : { readyAtMs: discovery.readyAtMs }
343
+ };
344
+ }
345
+ // src/host/runtime.ts
346
+ function optional(value) {
347
+ const trimmed = value.trim();
348
+ return trimmed === "" ? void 0 : trimmed;
349
+ }
350
+ var CwtoolsRuntimePool = class {
351
+ config;
352
+ entries = /* @__PURE__ */ new Map();
353
+ pendingEntries = /* @__PURE__ */ new Map();
354
+ disposed = false;
355
+ constructor(config) {
356
+ this.config = config;
357
+ }
358
+ get workspaceCount() {
359
+ return this.entries.size;
360
+ }
361
+ canExpose(name, workspaceRoot) {
362
+ return this.exposureReason(name, workspaceRoot) === void 0;
363
+ }
364
+ exposureReason(name, workspaceRoot) {
365
+ if (this.disposed || !this.config.enabled) return "CWTools is disabled by configuration.";
366
+ if (isCwtoolsReadToolName(name)) {
367
+ if (!isReadToolEnabled(this.config, name)) return "Tool " + name + " is disabled by read-group or per-tool configuration.";
368
+ } else if (isCwtoolsWriteToolName(name)) {
369
+ if (!isWriteLocalisationEnabled(this.config)) return "Tool " + name + " requires an explicit write allowlist entry.";
370
+ } else return "Tool " + name + " is outside the first-release CWTools catalog.";
371
+ const project = this.resolveProject(workspaceRoot);
372
+ if (!project.supported) return project.reason;
373
+ const cwtOnly = project.kind === "cwt-only";
374
+ if (!isMcpToolAvailable(name, {
375
+ includeWrites: isWriteLocalisationEnabled(this.config),
376
+ cwtOnly
377
+ })) return cwtOnly ? "Tool " + name + " is unavailable in a CWT-only workspace." : "Tool " + name + " is unavailable under the current write policy.";
378
+ if (CWTOOLS_STELLARIS_ONLY_TOOLS.has(name) && project.game !== "stellaris") return "Tool " + name + " requires a Stellaris full-mod workspace.";
379
+ }
380
+ async execute(name, args, workspaceRoot, signal) {
381
+ throwIfAborted(signal);
382
+ if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
383
+ const denied = this.exposureReason(name, workspaceRoot);
384
+ if (denied !== void 0) throw new CwtoolsToolError("tool_not_available", denied);
385
+ const entry = await this.entryFor(workspaceRoot, signal);
386
+ if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
387
+ const controller = new AbortController();
388
+ const abort = () => {
389
+ controller.abort(signal.reason);
390
+ };
391
+ if (signal.aborted) abort();
392
+ else signal.addEventListener("abort", abort, { once: true });
393
+ entry.controllers.add(controller);
394
+ entry.active++;
395
+ this.clearIdle(entry);
396
+ try {
397
+ const run = () => entry.handler(name, args, { signal: controller.signal });
398
+ const result = getMcpToolRegistryMetadata(name)?.concurrencyClass === "parallel" ? await awaitWithAbort(run(), controller.signal) : await this.serial(entry, run, controller.signal);
399
+ if (result.source === "cwtools-mcp") return {
400
+ ...result,
401
+ source: "cwtools-dsh"
402
+ };
403
+ return result;
404
+ } finally {
405
+ signal.removeEventListener("abort", abort);
406
+ entry.controllers.delete(controller);
407
+ entry.active--;
408
+ entry.lastUsed = Date.now();
409
+ this.scheduleIdle(entry);
410
+ }
411
+ }
412
+ dispose() {
413
+ if (this.disposed) return;
414
+ this.disposed = true;
415
+ for (const entry of this.entries.values()) this.disposeEntry(entry);
416
+ this.entries.clear();
417
+ }
418
+ resolveProject(workspaceRoot) {
419
+ const requested = path.resolve(workspaceRoot);
420
+ const support = detectProjectSupport(requested, {
421
+ game: optional(this.config.backend.game),
422
+ gamePath: optional(this.config.backend.gamePath)
423
+ });
424
+ const enabled = support.supported || this.config.backend.forceStart;
425
+ const kind = support.supported ? support.kind : this.config.backend.forceStart ? "mod" : support.kind;
426
+ return {
427
+ root: path.resolve(support.supported ? support.matchedAt ?? requested : requested),
428
+ supported: enabled,
429
+ reason: support.reason,
430
+ kind,
431
+ game: kind === "cwt-only" ? "cwt" : optional(this.config.backend.game) ?? support.gameId ?? "paradox"
432
+ };
433
+ }
434
+ async entryFor(workspaceRoot, signal) {
435
+ if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
436
+ const project = this.resolveProject(workspaceRoot);
437
+ if (!project.supported) throw new CwtoolsToolError("project_not_supported", project.reason);
438
+ const existing = this.entries.get(project.root);
439
+ if (existing !== void 0) {
440
+ existing.lastUsed = Date.now();
441
+ this.clearIdle(existing);
442
+ return existing;
443
+ }
444
+ const pending = this.pendingEntries.get(project.root);
445
+ if (pending !== void 0) return await pending;
446
+ const created = this.createEntry(project, signal);
447
+ this.pendingEntries.set(project.root, created);
448
+ try {
449
+ const entry = await created;
450
+ if (this.disposed) {
451
+ this.entries.delete(project.root);
452
+ if (!entry.disposed) entry.host.dispose?.();
453
+ throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime was disposed while the workspace host was starting.");
454
+ }
455
+ return entry;
456
+ } finally {
457
+ this.pendingEntries.delete(project.root);
458
+ }
459
+ }
460
+ async createEntry(project, signal) {
461
+ const active = this.config.backend.preferActiveBackend ? await resolveActiveBackend(this.config, project.root, signal) : void 0;
462
+ if (this.disposed) {
463
+ if (active && "dispose" in active.lspHost && typeof active.lspHost.dispose === "function") active.lspHost.dispose();
464
+ throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
465
+ }
466
+ const writes = isWriteLocalisationEnabled(this.config);
467
+ const hostOptions = {
468
+ workspaceRoot: project.root,
469
+ game: project.game === "paradox" || project.game === "cwt" ? void 0 : project.game,
470
+ serverPath: optional(this.config.backend.serverPath),
471
+ gamePath: optional(this.config.backend.gamePath),
472
+ cachePath: optional(this.config.backend.cachePath),
473
+ rulesPath: optional(this.config.backend.rulesPath),
474
+ errorIgnoreCodes: this.config.diagnostics.ignoreCodes,
475
+ errorIgnoreFiles: this.config.diagnostics.ignoreFiles,
476
+ localisationDiagnosticFilter: this.config.diagnostics.localisationFilter,
477
+ enableWrites: writes,
478
+ allowedTools: writes ? ["write_localisation"] : [],
479
+ forceStart: this.config.backend.forceStart,
480
+ startupTimeoutMs: this.config.backend.startupTimeoutMs,
481
+ requestTimeoutMs: this.config.backend.requestTimeoutMs,
482
+ debug: this.config.backend.debug,
483
+ honorWorkspaceIgnoreList: true,
484
+ ...active === void 0 ? {} : {
485
+ lspHost: active.lspHost,
486
+ readyAtMs: active.readyAtMs
487
+ }
488
+ };
489
+ const host = createNodeHostServices(hostOptions);
490
+ const entry = {
491
+ root: project.root,
492
+ host,
493
+ handler: createToolCallHandler(host),
494
+ controllers: /* @__PURE__ */ new Set(),
495
+ queue: Promise.resolve(),
496
+ active: 0,
497
+ lastUsed: Date.now(),
498
+ disposed: false
499
+ };
500
+ this.entries.set(project.root, entry);
501
+ this.enforceCapacity(entry);
502
+ return entry;
503
+ }
504
+ enforceCapacity(created) {
505
+ if (this.entries.size <= this.config.backend.maxWorkspaceRuntimes) return;
506
+ const candidate = [...this.entries.values()].filter((entry) => entry !== created && entry.active === 0).sort((left, right) => left.lastUsed - right.lastUsed)[0];
507
+ if (candidate === void 0) {
508
+ this.entries.delete(created.root);
509
+ this.disposeEntry(created);
510
+ throw new CwtoolsToolError("workspace_capacity", "All configured CWTools workspace runtimes are active.", ["Retry after an active call finishes, close an idle workspace, or increase backend.maxWorkspaceRuntimes."]);
511
+ }
512
+ this.entries.delete(candidate.root);
513
+ this.disposeEntry(candidate);
514
+ }
515
+ async serial(entry, run, signal) {
516
+ const queued = entry.queue.then(async () => {
517
+ throwIfAborted(signal);
518
+ if (entry.disposed) throw new CwtoolsToolError("runtime_disposed", "The workspace CWTools runtime was disposed before the call started.");
519
+ return await run();
520
+ });
521
+ entry.queue = queued.then(() => void 0, () => void 0);
522
+ return await awaitWithAbort(queued, signal);
523
+ }
524
+ clearIdle(entry) {
525
+ if (entry.idleTimer !== void 0) clearTimeout(entry.idleTimer);
526
+ entry.idleTimer = void 0;
527
+ }
528
+ scheduleIdle(entry) {
529
+ if (entry.disposed || entry.active !== 0 || this.disposed) return;
530
+ this.clearIdle(entry);
531
+ entry.idleTimer = setTimeout(() => {
532
+ if (entry.active !== 0 || entry.disposed || this.disposed) return;
533
+ this.entries.delete(entry.root);
534
+ this.disposeEntry(entry);
535
+ }, this.config.backend.idleShutdownMs);
536
+ entry.idleTimer.unref();
537
+ }
538
+ disposeEntry(entry) {
539
+ if (entry.disposed) return;
540
+ entry.disposed = true;
541
+ this.clearIdle(entry);
542
+ for (const controller of entry.controllers) controller.abort(abortError("The CWTools workspace runtime was disposed."));
543
+ entry.controllers.clear();
544
+ entry.host.dispose?.();
545
+ }
546
+ };
547
+ // src/index.ts
548
+ const name = "cwtools";
549
+ const inject = [
550
+ "tools",
551
+ "systemPrompt",
552
+ "workingDirectory"
553
+ ];
554
+ /** Register native CWTools tools and own every runtime resource in one effect.
555
+ * A settings save commits volatile values into this running instance, so the
556
+ * resources that capture them are rebuilt instead of waiting for a restart.
557
+ * @param ctx - the Host plugin context.
558
+ * @param config - the live configuration sections this entry owns.
559
+ */
560
+ function apply(ctx, config) {
561
+ let dispose;
562
+ const mount = () => {
563
+ const values = snapshotConfig(config);
564
+ if (!values.enabled) return;
565
+ const runtime = new CwtoolsRuntimePool(values);
566
+ const removePrompt = ctx.systemPrompt.section({
567
+ name: "tool:cwtools",
568
+ order: 2210,
569
+ text: CWTOOLS_SYSTEM_PROMPT
570
+ });
571
+ const removeTools = registerNativeCwtoolsTools(ctx, values, runtime);
572
+ dispose = () => {
573
+ removeTools();
574
+ removePrompt();
575
+ runtime.dispose();
576
+ };
577
+ };
578
+ const unmount = () => {
579
+ const current = dispose;
580
+ dispose = void 0;
581
+ current?.();
582
+ };
583
+ ctx.effect(() => {
584
+ mount();
585
+ return unmount;
586
+ }, "cwtools: native tools and workspace runtimes");
587
+ ctx.on("loader/volatile-update", () => {
588
+ unmount();
589
+ mount();
590
+ });
591
+ }
592
+ export { Config, apply, inject, name };
@@ -0,0 +1,10 @@
1
+ import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
2
+ import type { CwtoolsSectionFace } from './cwtools-controller.ts';
3
+ /** Props assembled by the settings renderer for this section. */
4
+ export type CwtoolsSectionProps = PropsRuntime<'settings.section'> & PropsLocale<'settings.cwtools'> & InjectFace<CwtoolsSectionFace>;
5
+ /**
6
+ * Render the CWTools settings section.
7
+ * @param props - the section snapshot, its staged actions, and localized copy.
8
+ * @returns the page inside the shared settings form frame.
9
+ */
10
+ export declare function CwtoolsSection(props: CwtoolsSectionProps): import("react").JSX.Element;
@@ -0,0 +1,8 @@
1
+ /** The CWTools section's navigation mark: a stylized C over the rule braces. */
2
+ import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
3
+ /**
4
+ * Render the CWTools navigation icon.
5
+ * @param props - requested edge in pixels and whether this section is selected.
6
+ * @returns a decorative SVG in the current text color.
7
+ */
8
+ export declare function CwtoolsSectionIcon({ size, active }: PropsRuntime<'settings.section.icon'>): import("react").JSX.Element;