dsh-cwtools 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +100 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +7 -0
- package/lib/client.js +1097 -0
- package/lib/index.js +539 -0
- package/lib/types/client/CwtoolsSection.d.ts +10 -0
- package/lib/types/client/CwtoolsSectionIcon.d.ts +8 -0
- package/lib/types/client/cwtools-controller.d.ts +82 -0
- package/lib/types/client/index.d.ts +27 -0
- package/lib/types/client/locales.d.ts +25 -0
- package/lib/types/config.d.ts +7 -0
- package/lib/types/contract/configTypes.d.ts +37 -0
- package/lib/types/contract/toolCatalog.d.ts +19 -0
- package/lib/types/host/activeBackend.d.ts +8 -0
- package/lib/types/host/contracts.d.ts +22 -0
- package/lib/types/host/errors.d.ts +9 -0
- package/lib/types/host/nativeTools.d.ts +4 -0
- package/lib/types/host/prompt.d.ts +1 -0
- package/lib/types/host/results.d.ts +7 -0
- package/lib/types/host/runtime.d.ts +22 -0
- package/lib/types/index.d.ts +7 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +91 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
import { createToolCallHandler, getMcpToolRegistryMetadata, isMcpToolAvailable, listMcpToolSchemas } from "cwtools-shared";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
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),
|
|
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({}),
|
|
89
|
+
readTools: z.dict(z.boolean(), z.string()).default({}),
|
|
90
|
+
writeTools: z.object({ write_localisation: z.boolean().default(false) }).default({}),
|
|
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({}),
|
|
106
|
+
output: z.object({ maxResultChars: z.number().step(1).min(1e3).max(2e5).default(16e3) }).default({})
|
|
107
|
+
});
|
|
108
|
+
function isReadToolEnabled(config, name) {
|
|
109
|
+
return config.enabled && config.readGroups[cwtoolsReadGroupFor(name)] && config.readTools[name] !== false;
|
|
110
|
+
}
|
|
111
|
+
function isWriteLocalisationEnabled(config) {
|
|
112
|
+
return config.enabled && config.writeTools.write_localisation === true;
|
|
113
|
+
}
|
|
114
|
+
// src/host/errors.ts
|
|
115
|
+
var CwtoolsToolError = class extends Error {
|
|
116
|
+
code;
|
|
117
|
+
nextSteps;
|
|
118
|
+
name = "CwtoolsToolError";
|
|
119
|
+
constructor(code, message, nextSteps = []) {
|
|
120
|
+
super(nextSteps.length === 0 ? message : message + "\nNext steps:\n- " + nextSteps.join("\n- "));
|
|
121
|
+
this.code = code;
|
|
122
|
+
this.nextSteps = nextSteps;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
function abortError(reason) {
|
|
126
|
+
const error = reason instanceof Error ? reason : new Error(reason === void 0 ? "Operation cancelled." : String(reason));
|
|
127
|
+
error.name = "AbortError";
|
|
128
|
+
return error;
|
|
129
|
+
}
|
|
130
|
+
function throwIfAborted(signal) {
|
|
131
|
+
if (signal?.aborted === true) throw abortError(signal.reason);
|
|
132
|
+
}
|
|
133
|
+
async function awaitWithAbort(promise, signal) {
|
|
134
|
+
if (signal === void 0) return await promise;
|
|
135
|
+
throwIfAborted(signal);
|
|
136
|
+
let listener;
|
|
137
|
+
const aborted = new Promise((_, reject) => {
|
|
138
|
+
listener = () => {
|
|
139
|
+
reject(abortError(signal.reason));
|
|
140
|
+
};
|
|
141
|
+
signal.addEventListener("abort", listener, { once: true });
|
|
142
|
+
});
|
|
143
|
+
try {
|
|
144
|
+
return await Promise.race([promise, aborted]);
|
|
145
|
+
} finally {
|
|
146
|
+
if (listener !== void 0) signal.removeEventListener("abort", listener);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
// src/host/results.ts
|
|
150
|
+
const SUCCESS_STATUSES = /* @__PURE__ */ new Set([
|
|
151
|
+
"ready",
|
|
152
|
+
"partial",
|
|
153
|
+
"success",
|
|
154
|
+
"loading",
|
|
155
|
+
"stale"
|
|
156
|
+
]);
|
|
157
|
+
function normalizeJson(value, seen, path) {
|
|
158
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
159
|
+
if (typeof value === "number") {
|
|
160
|
+
if (!Number.isFinite(value)) throw new CwtoolsToolError("invalid_result", path + " contains a non-finite number.");
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
if (Array.isArray(value)) {
|
|
164
|
+
if (seen.has(value)) throw new CwtoolsToolError("invalid_result", path + " contains a cycle.");
|
|
165
|
+
seen.add(value);
|
|
166
|
+
const result = value.map((entry, index) => {
|
|
167
|
+
if (entry === void 0) throw new CwtoolsToolError("invalid_result", path + "[" + index + "] is undefined.");
|
|
168
|
+
return normalizeJson(entry, seen, path + "[" + index + "]");
|
|
169
|
+
});
|
|
170
|
+
seen.delete(value);
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
if (typeof value === "object" && value !== null) {
|
|
174
|
+
const prototype = Object.getPrototypeOf(value);
|
|
175
|
+
if (prototype !== Object.prototype && prototype !== null) throw new CwtoolsToolError("invalid_result", path + " contains a non-plain object.");
|
|
176
|
+
if (seen.has(value)) throw new CwtoolsToolError("invalid_result", path + " contains a cycle.");
|
|
177
|
+
seen.add(value);
|
|
178
|
+
const result = {};
|
|
179
|
+
for (const key of Object.keys(value).sort()) {
|
|
180
|
+
const entry = value[key];
|
|
181
|
+
if (entry === void 0) continue;
|
|
182
|
+
result[key] = normalizeJson(entry, seen, path + "." + key);
|
|
183
|
+
}
|
|
184
|
+
seen.delete(value);
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
throw new CwtoolsToolError("invalid_result", path + " contains a non-JSON value of type " + typeof value + ".");
|
|
188
|
+
}
|
|
189
|
+
function normalizeSuccessfulResult(result) {
|
|
190
|
+
const normalized = normalizeJson(result, /* @__PURE__ */ new WeakSet(), "$");
|
|
191
|
+
if (normalized.ok !== true || !SUCCESS_STATUSES.has(normalized.status) || typeof normalized.source !== "string") throw new CwtoolsToolError("invalid_result", "CWTools returned an invalid success envelope.");
|
|
192
|
+
return normalized;
|
|
193
|
+
}
|
|
194
|
+
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 ?? []);
|
|
196
|
+
}
|
|
197
|
+
function renderCwtoolsResult(value, maxResultChars) {
|
|
198
|
+
const text = JSON.stringify(value, null, 2) ?? "null";
|
|
199
|
+
if (text.length <= maxResultChars) return text;
|
|
200
|
+
const omitted = text.length - maxResultChars;
|
|
201
|
+
return text.slice(0, maxResultChars) + "\n… [truncated " + omitted + " characters; canonical tool result is unchanged]";
|
|
202
|
+
}
|
|
203
|
+
const SUCCESS_OUTPUT_SCHEMA = {
|
|
204
|
+
type: "object",
|
|
205
|
+
additionalProperties: false,
|
|
206
|
+
properties: {
|
|
207
|
+
ok: { type: "boolean" },
|
|
208
|
+
status: {
|
|
209
|
+
type: "string",
|
|
210
|
+
enum: [
|
|
211
|
+
"ready",
|
|
212
|
+
"partial",
|
|
213
|
+
"success",
|
|
214
|
+
"loading",
|
|
215
|
+
"stale"
|
|
216
|
+
]
|
|
217
|
+
},
|
|
218
|
+
source: { type: "string" },
|
|
219
|
+
data: {},
|
|
220
|
+
warnings: {
|
|
221
|
+
type: "array",
|
|
222
|
+
items: { type: "string" }
|
|
223
|
+
},
|
|
224
|
+
nextSteps: {
|
|
225
|
+
type: "array",
|
|
226
|
+
items: { type: "string" }
|
|
227
|
+
},
|
|
228
|
+
vanillaCache: {
|
|
229
|
+
type: "object",
|
|
230
|
+
additionalProperties: true
|
|
231
|
+
},
|
|
232
|
+
readiness: {
|
|
233
|
+
type: "object",
|
|
234
|
+
additionalProperties: true
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
required: [
|
|
238
|
+
"ok",
|
|
239
|
+
"status",
|
|
240
|
+
"source"
|
|
241
|
+
]
|
|
242
|
+
};
|
|
243
|
+
// src/host/nativeTools.ts
|
|
244
|
+
function registerNativeCwtoolsTools(ctx, config, runtime) {
|
|
245
|
+
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);
|
|
252
|
+
disposers.push(ctx.tools.register(definition, { when: async ({ agent, signal }) => {
|
|
253
|
+
const workspaceRoot = await ctx.workingDirectory.ensure(agent, signal);
|
|
254
|
+
return runtime.canExpose(schema.name, workspaceRoot);
|
|
255
|
+
} }));
|
|
256
|
+
}
|
|
257
|
+
return () => {
|
|
258
|
+
for (const dispose of disposers.reverse()) dispose();
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function createNativeDefinition(ctx, config, runtime, schema) {
|
|
262
|
+
return {
|
|
263
|
+
name: schema.name,
|
|
264
|
+
description: schema.description,
|
|
265
|
+
parameters: schema.inputSchema,
|
|
266
|
+
timeoutMs: Math.min(2147483647, config.backend.startupTimeoutMs + config.backend.requestTimeoutMs),
|
|
267
|
+
output: {
|
|
268
|
+
schema: SUCCESS_OUTPUT_SCHEMA,
|
|
269
|
+
render: (_args, value) => [{
|
|
270
|
+
type: "text",
|
|
271
|
+
text: renderCwtoolsResult(value, config.output.maxResultChars)
|
|
272
|
+
}]
|
|
273
|
+
},
|
|
274
|
+
isConcurrencySafe: () => getMcpToolRegistryMetadata(schema.name)?.concurrencyClass === "parallel",
|
|
275
|
+
async execute(args, exec) {
|
|
276
|
+
if (exec.agent === void 0) throw new CwtoolsToolError("workspace_required", "CWTools tools require an Agent Session working directory.");
|
|
277
|
+
const workspaceRoot = await ctx.workingDirectory.ensure(exec.agent, exec.signal);
|
|
278
|
+
const record = typeof args === "object" && args !== null && !Array.isArray(args) ? args : {};
|
|
279
|
+
const result = await runtime.execute(schema.name, record, workspaceRoot, exec.signal);
|
|
280
|
+
if (!result.ok) throw errorFromSharedResult(result);
|
|
281
|
+
return normalizeSuccessfulResult(result);
|
|
282
|
+
},
|
|
283
|
+
presentCall: () => ({
|
|
284
|
+
card: "generic",
|
|
285
|
+
title: "CWTools: " + schema.name
|
|
286
|
+
})
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
// src/host/prompt.ts
|
|
290
|
+
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.
|
|
291
|
+
|
|
292
|
+
When working in a Paradox mod:
|
|
293
|
+
- Start structural and dependency questions with explore_pdx_project.
|
|
294
|
+
- Verify game IDs with query_types and the appropriate scripted effect/trigger, enum, modifier, or variable query before using them.
|
|
295
|
+
- Check trigger/effect/scope/modifier syntax with query_rules and query_scope; check block and entity schemas with query_cwt_schema before writing.
|
|
296
|
+
- Navigate with go_to_definition/find_references/document_symbols/workspace_symbols and use get_pdx_block for structured blocks.
|
|
297
|
+
- Respect readiness and freshness. A loading result or an empty result while readiness.ready is false is not authoritative; retry after loading.
|
|
298
|
+
- Respect vanillaCache provenance. When vanilla is unavailable, results are mod-only and vanilla references may produce incomplete answers or false errors.
|
|
299
|
+
- Review get_diagnostics before declaring code correct. After an allowed write, re-check fresh diagnostics.
|
|
300
|
+
- Only whitelisted domain writes may be used, and only when enabled by the user. Never treat a denied write as completed.`;
|
|
301
|
+
// src/host/activeBackend.ts
|
|
302
|
+
/** Resolve a healthy active host only for the exact current mod root. */
|
|
303
|
+
async function resolveActiveBackend(config, workspaceRoot, signal) {
|
|
304
|
+
const manifestPath = config.backend.activeManifestPath.trim() || void 0;
|
|
305
|
+
const discovery = await discoverNativeBridge(workspaceRoot, {
|
|
306
|
+
manifestPath,
|
|
307
|
+
timeoutMs: config.backend.requestTimeoutMs,
|
|
308
|
+
signal
|
|
309
|
+
});
|
|
310
|
+
if (discovery.kind === "incompatible") throw new CwtoolsToolError("backend_incompatible", discovery.reason);
|
|
311
|
+
if (discovery.kind === "unavailable") return void 0;
|
|
312
|
+
return {
|
|
313
|
+
lspHost: createNativeBridgeLspHost(discovery.manifest, discovery.readyAtMs),
|
|
314
|
+
...discovery.readyAtMs === void 0 ? {} : { readyAtMs: discovery.readyAtMs }
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
// src/host/runtime.ts
|
|
318
|
+
function optional(value) {
|
|
319
|
+
const trimmed = value.trim();
|
|
320
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
321
|
+
}
|
|
322
|
+
var CwtoolsRuntimePool = class {
|
|
323
|
+
config;
|
|
324
|
+
entries = /* @__PURE__ */ new Map();
|
|
325
|
+
pendingEntries = /* @__PURE__ */ new Map();
|
|
326
|
+
disposed = false;
|
|
327
|
+
constructor(config) {
|
|
328
|
+
this.config = config;
|
|
329
|
+
}
|
|
330
|
+
get workspaceCount() {
|
|
331
|
+
return this.entries.size;
|
|
332
|
+
}
|
|
333
|
+
canExpose(name, workspaceRoot) {
|
|
334
|
+
return this.exposureReason(name, workspaceRoot) === void 0;
|
|
335
|
+
}
|
|
336
|
+
exposureReason(name, workspaceRoot) {
|
|
337
|
+
if (this.disposed || !this.config.enabled) return "CWTools is disabled by configuration.";
|
|
338
|
+
if (isCwtoolsReadToolName(name)) {
|
|
339
|
+
if (!isReadToolEnabled(this.config, name)) return "Tool " + name + " is disabled by read-group or per-tool configuration.";
|
|
340
|
+
} 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.";
|
|
343
|
+
const project = this.resolveProject(workspaceRoot);
|
|
344
|
+
if (!project.supported) return project.reason;
|
|
345
|
+
const cwtOnly = project.kind === "cwt-only";
|
|
346
|
+
if (!isMcpToolAvailable(name, {
|
|
347
|
+
includeWrites: isWriteLocalisationEnabled(this.config),
|
|
348
|
+
cwtOnly
|
|
349
|
+
})) 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.";
|
|
351
|
+
}
|
|
352
|
+
async execute(name, args, workspaceRoot, signal) {
|
|
353
|
+
throwIfAborted(signal);
|
|
354
|
+
if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
|
|
355
|
+
const denied = this.exposureReason(name, workspaceRoot);
|
|
356
|
+
if (denied !== void 0) throw new CwtoolsToolError("tool_not_available", denied);
|
|
357
|
+
const entry = await this.entryFor(workspaceRoot, signal);
|
|
358
|
+
if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
|
|
359
|
+
const controller = new AbortController();
|
|
360
|
+
const abort = () => {
|
|
361
|
+
controller.abort(signal.reason);
|
|
362
|
+
};
|
|
363
|
+
if (signal.aborted) abort();
|
|
364
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
365
|
+
entry.controllers.add(controller);
|
|
366
|
+
entry.active++;
|
|
367
|
+
this.clearIdle(entry);
|
|
368
|
+
try {
|
|
369
|
+
const run = () => entry.handler(name, args, { signal: controller.signal });
|
|
370
|
+
const result = getMcpToolRegistryMetadata(name)?.concurrencyClass === "parallel" ? await awaitWithAbort(run(), controller.signal) : await this.serial(entry, run, controller.signal);
|
|
371
|
+
if (result.source === "cwtools-mcp") return {
|
|
372
|
+
...result,
|
|
373
|
+
source: "cwtools-dsh"
|
|
374
|
+
};
|
|
375
|
+
return result;
|
|
376
|
+
} finally {
|
|
377
|
+
signal.removeEventListener("abort", abort);
|
|
378
|
+
entry.controllers.delete(controller);
|
|
379
|
+
entry.active--;
|
|
380
|
+
entry.lastUsed = Date.now();
|
|
381
|
+
this.scheduleIdle(entry);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
dispose() {
|
|
385
|
+
if (this.disposed) return;
|
|
386
|
+
this.disposed = true;
|
|
387
|
+
for (const entry of this.entries.values()) this.disposeEntry(entry);
|
|
388
|
+
this.entries.clear();
|
|
389
|
+
}
|
|
390
|
+
resolveProject(workspaceRoot) {
|
|
391
|
+
const requested = path.resolve(workspaceRoot);
|
|
392
|
+
const support = detectProjectSupport(requested, {
|
|
393
|
+
game: optional(this.config.backend.game),
|
|
394
|
+
gamePath: optional(this.config.backend.gamePath)
|
|
395
|
+
});
|
|
396
|
+
const enabled = support.supported || this.config.backend.forceStart;
|
|
397
|
+
const kind = support.supported ? support.kind : this.config.backend.forceStart ? "mod" : support.kind;
|
|
398
|
+
return {
|
|
399
|
+
root: path.resolve(support.supported ? support.matchedAt ?? requested : requested),
|
|
400
|
+
supported: enabled,
|
|
401
|
+
reason: support.reason,
|
|
402
|
+
kind,
|
|
403
|
+
game: kind === "cwt-only" ? "cwt" : optional(this.config.backend.game) ?? support.gameId ?? "paradox"
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
async entryFor(workspaceRoot, signal) {
|
|
407
|
+
if (this.disposed) throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
|
|
408
|
+
const project = this.resolveProject(workspaceRoot);
|
|
409
|
+
if (!project.supported) throw new CwtoolsToolError("project_not_supported", project.reason);
|
|
410
|
+
const existing = this.entries.get(project.root);
|
|
411
|
+
if (existing !== void 0) {
|
|
412
|
+
existing.lastUsed = Date.now();
|
|
413
|
+
this.clearIdle(existing);
|
|
414
|
+
return existing;
|
|
415
|
+
}
|
|
416
|
+
const pending = this.pendingEntries.get(project.root);
|
|
417
|
+
if (pending !== void 0) return await pending;
|
|
418
|
+
const created = this.createEntry(project, signal);
|
|
419
|
+
this.pendingEntries.set(project.root, created);
|
|
420
|
+
try {
|
|
421
|
+
const entry = await created;
|
|
422
|
+
if (this.disposed) {
|
|
423
|
+
this.entries.delete(project.root);
|
|
424
|
+
if (!entry.disposed) entry.host.dispose?.();
|
|
425
|
+
throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime was disposed while the workspace host was starting.");
|
|
426
|
+
}
|
|
427
|
+
return entry;
|
|
428
|
+
} finally {
|
|
429
|
+
this.pendingEntries.delete(project.root);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
async createEntry(project, signal) {
|
|
433
|
+
const active = this.config.backend.preferActiveBackend ? await resolveActiveBackend(this.config, project.root, signal) : void 0;
|
|
434
|
+
if (this.disposed) {
|
|
435
|
+
if (active && "dispose" in active.lspHost && typeof active.lspHost.dispose === "function") active.lspHost.dispose();
|
|
436
|
+
throw new CwtoolsToolError("runtime_disposed", "The CWTools runtime has been disposed.");
|
|
437
|
+
}
|
|
438
|
+
const writes = isWriteLocalisationEnabled(this.config);
|
|
439
|
+
const host = createNodeHostServices({
|
|
440
|
+
workspaceRoot: project.root,
|
|
441
|
+
game: project.game === "paradox" || project.game === "cwt" ? void 0 : project.game,
|
|
442
|
+
serverPath: optional(this.config.backend.serverPath),
|
|
443
|
+
gamePath: optional(this.config.backend.gamePath),
|
|
444
|
+
cachePath: optional(this.config.backend.cachePath),
|
|
445
|
+
rulesPath: optional(this.config.backend.rulesPath),
|
|
446
|
+
enableWrites: writes,
|
|
447
|
+
allowedTools: writes ? ["write_localisation"] : [],
|
|
448
|
+
forceStart: this.config.backend.forceStart,
|
|
449
|
+
startupTimeoutMs: this.config.backend.startupTimeoutMs,
|
|
450
|
+
requestTimeoutMs: this.config.backend.requestTimeoutMs,
|
|
451
|
+
debug: this.config.backend.debug,
|
|
452
|
+
...active === void 0 ? {} : {
|
|
453
|
+
lspHost: active.lspHost,
|
|
454
|
+
readyAtMs: active.readyAtMs
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
const entry = {
|
|
458
|
+
root: project.root,
|
|
459
|
+
host,
|
|
460
|
+
handler: createToolCallHandler(host),
|
|
461
|
+
controllers: /* @__PURE__ */ new Set(),
|
|
462
|
+
queue: Promise.resolve(),
|
|
463
|
+
active: 0,
|
|
464
|
+
lastUsed: Date.now(),
|
|
465
|
+
disposed: false
|
|
466
|
+
};
|
|
467
|
+
this.entries.set(project.root, entry);
|
|
468
|
+
this.enforceCapacity(entry);
|
|
469
|
+
return entry;
|
|
470
|
+
}
|
|
471
|
+
enforceCapacity(created) {
|
|
472
|
+
if (this.entries.size <= this.config.backend.maxWorkspaceRuntimes) return;
|
|
473
|
+
const candidate = [...this.entries.values()].filter((entry) => entry !== created && entry.active === 0).sort((left, right) => left.lastUsed - right.lastUsed)[0];
|
|
474
|
+
if (candidate === void 0) {
|
|
475
|
+
this.entries.delete(created.root);
|
|
476
|
+
this.disposeEntry(created);
|
|
477
|
+
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."]);
|
|
478
|
+
}
|
|
479
|
+
this.entries.delete(candidate.root);
|
|
480
|
+
this.disposeEntry(candidate);
|
|
481
|
+
}
|
|
482
|
+
async serial(entry, run, signal) {
|
|
483
|
+
const queued = entry.queue.then(async () => {
|
|
484
|
+
throwIfAborted(signal);
|
|
485
|
+
if (entry.disposed) throw new CwtoolsToolError("runtime_disposed", "The workspace CWTools runtime was disposed before the call started.");
|
|
486
|
+
return await run();
|
|
487
|
+
});
|
|
488
|
+
entry.queue = queued.then(() => void 0, () => void 0);
|
|
489
|
+
return await awaitWithAbort(queued, signal);
|
|
490
|
+
}
|
|
491
|
+
clearIdle(entry) {
|
|
492
|
+
if (entry.idleTimer !== void 0) clearTimeout(entry.idleTimer);
|
|
493
|
+
entry.idleTimer = void 0;
|
|
494
|
+
}
|
|
495
|
+
scheduleIdle(entry) {
|
|
496
|
+
if (entry.disposed || entry.active !== 0 || this.disposed) return;
|
|
497
|
+
this.clearIdle(entry);
|
|
498
|
+
entry.idleTimer = setTimeout(() => {
|
|
499
|
+
if (entry.active !== 0 || entry.disposed || this.disposed) return;
|
|
500
|
+
this.entries.delete(entry.root);
|
|
501
|
+
this.disposeEntry(entry);
|
|
502
|
+
}, this.config.backend.idleShutdownMs);
|
|
503
|
+
entry.idleTimer.unref();
|
|
504
|
+
}
|
|
505
|
+
disposeEntry(entry) {
|
|
506
|
+
if (entry.disposed) return;
|
|
507
|
+
entry.disposed = true;
|
|
508
|
+
this.clearIdle(entry);
|
|
509
|
+
for (const controller of entry.controllers) controller.abort(abortError("The CWTools workspace runtime was disposed."));
|
|
510
|
+
entry.controllers.clear();
|
|
511
|
+
entry.host.dispose?.();
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
// src/index.ts
|
|
515
|
+
const name = "cwtools";
|
|
516
|
+
const inject = [
|
|
517
|
+
"tools",
|
|
518
|
+
"systemPrompt",
|
|
519
|
+
"workingDirectory"
|
|
520
|
+
];
|
|
521
|
+
/** Register native CWTools tools and own every runtime resource in one effect. */
|
|
522
|
+
function apply(ctx, config) {
|
|
523
|
+
if (!config.enabled) return;
|
|
524
|
+
ctx.effect(() => {
|
|
525
|
+
const runtime = new CwtoolsRuntimePool(config);
|
|
526
|
+
const removePrompt = ctx.systemPrompt.section({
|
|
527
|
+
name: "tool:cwtools",
|
|
528
|
+
order: 2210,
|
|
529
|
+
text: CWTOOLS_SYSTEM_PROMPT
|
|
530
|
+
});
|
|
531
|
+
const removeTools = registerNativeCwtoolsTools(ctx, config, runtime);
|
|
532
|
+
return () => {
|
|
533
|
+
removeTools();
|
|
534
|
+
removePrompt();
|
|
535
|
+
runtime.dispose();
|
|
536
|
+
};
|
|
537
|
+
}, "cwtools: native tools and workspace runtimes");
|
|
538
|
+
}
|
|
539
|
+
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;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client';
|
|
2
|
+
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store';
|
|
3
|
+
import { type SettingsFieldState, type SettingsFormActions, type SettingsFormShell } from '@deepseek-ai/dsh-client-ui-primitives';
|
|
4
|
+
import type { CwtoolsConfig } from '../contract/configTypes.ts';
|
|
5
|
+
import { type CwtoolsReadGroup, type CwtoolsReadToolName } from '../contract/toolCatalog.ts';
|
|
6
|
+
/** Settings namespace of the Host entry this section edits. */
|
|
7
|
+
export declare const CWTOOLS_SETTINGS_NAMESPACE = "cwtools";
|
|
8
|
+
/** Configuration block a leaf belongs to. */
|
|
9
|
+
type CwtoolsBlock = 'enabled' | 'backend' | 'readGroups' | 'readTools' | 'writeTools' | 'output';
|
|
10
|
+
/** One leaf field of the section, addressed inside the Host document. */
|
|
11
|
+
export interface CwtoolsFieldRef {
|
|
12
|
+
/** Dotted path inside the namespace section. */
|
|
13
|
+
field: string;
|
|
14
|
+
/** Configuration block the leaf belongs to. */
|
|
15
|
+
block: CwtoolsBlock;
|
|
16
|
+
}
|
|
17
|
+
/** A value the Host holds for one field after a save it did not accept. */
|
|
18
|
+
export interface CwtoolsAcceptedValue {
|
|
19
|
+
/** Dotted path of the field. */
|
|
20
|
+
field: string;
|
|
21
|
+
/** The value the Host kept, rendered as that field's draft text. */
|
|
22
|
+
text: string;
|
|
23
|
+
}
|
|
24
|
+
/** What the section renders: shared form state plus this entry's fields. */
|
|
25
|
+
export interface CwtoolsSectionState extends SettingsFormShell {
|
|
26
|
+
/** Every control's draft text and validity, keyed by dotted path. */
|
|
27
|
+
fields: Record<string, SettingsFieldState>;
|
|
28
|
+
/** Effective on-state of each read group. */
|
|
29
|
+
groups: Record<CwtoolsReadGroup, boolean>;
|
|
30
|
+
/** Effective on-state of each tool: its own grant AND its group's. */
|
|
31
|
+
tools: Record<CwtoolsReadToolName, boolean>;
|
|
32
|
+
/** Whether the refused save lost a revision race with an edit made elsewhere. */
|
|
33
|
+
conflict: boolean;
|
|
34
|
+
/** Values the Host still holds after a refused save; empty otherwise. */
|
|
35
|
+
accepted: readonly CwtoolsAcceptedValue[];
|
|
36
|
+
}
|
|
37
|
+
/** Actions and observable state the slot renderer binds. */
|
|
38
|
+
export interface CwtoolsSectionFace extends SettingsFormActions {
|
|
39
|
+
hooks: {
|
|
40
|
+
cwtoolsSection: SnapshotStore<CwtoolsSectionState>;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Stage one switch.
|
|
44
|
+
* @param field - dotted path of the switch.
|
|
45
|
+
* @param next - the value the user asked for.
|
|
46
|
+
*/
|
|
47
|
+
toggle: (field: string, next: boolean) => void;
|
|
48
|
+
}
|
|
49
|
+
/** Every control on the page, in rendering order. */
|
|
50
|
+
export declare const CWTOOLS_FIELDS: readonly CwtoolsFieldRef[];
|
|
51
|
+
/**
|
|
52
|
+
* Bind the whole CWTools section to one staged form.
|
|
53
|
+
*
|
|
54
|
+
* Every control is staged; a save writes the staged edits together; leaving the
|
|
55
|
+
* page drops them. A refused save keeps its drafts, reports the values the Host
|
|
56
|
+
* still holds, and says whether the document moved underneath.
|
|
57
|
+
*/
|
|
58
|
+
export declare class CwtoolsSettingsController {
|
|
59
|
+
private readonly scope;
|
|
60
|
+
private readonly form;
|
|
61
|
+
private readonly store;
|
|
62
|
+
/** @param form - the shared configuration form of the `cwtools` entry. */
|
|
63
|
+
constructor(form: ConfigForm<CwtoolsConfig>);
|
|
64
|
+
/**
|
|
65
|
+
* Bind the section to the slot renderer.
|
|
66
|
+
* @returns the section snapshot and its staged actions.
|
|
67
|
+
*/
|
|
68
|
+
inject(): CwtoolsSectionFace;
|
|
69
|
+
/** Release the accepted-value subscription and the flattened view. */
|
|
70
|
+
dispose(): void;
|
|
71
|
+
/** Rebuild everything the component renders from the current reads and drafts. */
|
|
72
|
+
private project;
|
|
73
|
+
/** Whether the refused write lost a revision race rather than failing validation. */
|
|
74
|
+
private conflict;
|
|
75
|
+
/**
|
|
76
|
+
* The values the Host still holds for the fields the refused save tried to
|
|
77
|
+
* write. Read from the accepted section, never from the draft, so the notice
|
|
78
|
+
* shows what a reload would restore.
|
|
79
|
+
*/
|
|
80
|
+
private acceptedValues;
|
|
81
|
+
}
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CWTools settings partition, browser half.
|
|
3
|
+
*
|
|
4
|
+
* The section edits the `cwtools` Host entry through the shared `configForms`
|
|
5
|
+
* service. It owns no permission state of its own: the read groups, the tool
|
|
6
|
+
* grants, the single write this release ships, and every backend bound are the
|
|
7
|
+
* same document the Host validates and the same values the tool surfaces read.
|
|
8
|
+
* The page therefore appears only while the Host actually serves that entry.
|
|
9
|
+
*/
|
|
10
|
+
import type { Context as ClientContext } from '@deepseek-ai/cordis';
|
|
11
|
+
import { type CwtoolsLocaleKey } from './locales.ts';
|
|
12
|
+
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
|
13
|
+
interface LocaleNamespaceMap {
|
|
14
|
+
/** CWTools settings section copy. */
|
|
15
|
+
'settings.cwtools': CwtoolsLocaleKey;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export type { CwtoolsLocaleKey } from './locales.ts';
|
|
19
|
+
export type { CwtoolsSectionProps } from './CwtoolsSection.tsx';
|
|
20
|
+
export type { CwtoolsAcceptedValue, CwtoolsFieldRef, CwtoolsSectionFace, CwtoolsSectionState, } from './cwtools-controller.ts';
|
|
21
|
+
/** Required services (cordis fiber inject). */
|
|
22
|
+
export declare const inject: string[];
|
|
23
|
+
/**
|
|
24
|
+
* Mount the settings section while the Host serves the `cwtools` entry.
|
|
25
|
+
* @param ctx - the browser plugin context.
|
|
26
|
+
*/
|
|
27
|
+
export declare function apply(ctx: ClientContext): void;
|