cwtools-shared 0.2.9 → 0.4.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/dist/debug/zz.d.ts +1 -0
- package/dist/debug/zz.js +12 -0
- package/dist/generated/mcpTools.d.ts +49 -4
- package/dist/generated/mcpTools.js +94 -49
- package/dist/generated/workshopDetection.d.ts +22 -0
- package/dist/generated/workshopDetection.js +50 -0
- package/dist/generated/workspaceDetectionProfiles.d.ts +2 -0
- package/dist/generated/workspaceDetectionProfiles.js +84 -0
- package/dist/generated/workspaceGameDetection.d.ts +39 -0
- package/dist/generated/workspaceGameDetection.js +424 -0
- package/dist/host/capabilities.d.ts +39 -0
- package/dist/host/capabilities.js +128 -0
- package/dist/host/diagnostics.d.ts +8 -1
- package/dist/host/filesystem.d.ts +2 -0
- package/dist/host/hostServices.d.ts +47 -0
- package/dist/host/indexing.d.ts +3 -0
- package/dist/host/lsp.d.ts +9 -0
- package/dist/host/lsp.js +27 -0
- package/dist/host/readiness.js +10 -0
- package/dist/host/vanillaCache.js +1 -1
- package/dist/index.d.ts +16 -1
- package/dist/index.js +22 -1
- package/dist/knowledge/interfaceKnowledge.d.ts +8 -0
- package/dist/knowledge/interfaceKnowledge.js +222 -0
- package/dist/project/descriptor.d.ts +12 -0
- package/dist/project/descriptor.js +69 -0
- package/dist/project/init.d.ts +11 -0
- package/dist/project/init.js +356 -0
- package/dist/project/knowledge.d.ts +6 -0
- package/dist/project/knowledge.js +20 -8
- package/dist/project/profile.d.ts +62 -7
- package/dist/project/profile.js +4 -3
- package/dist/project/profileBuilder.d.ts +31 -0
- package/dist/project/profileBuilder.js +989 -0
- package/dist/tools/archetypeArtifacts.d.ts +29 -0
- package/dist/tools/archetypeArtifacts.js +136 -0
- package/dist/tools/archetypeSlots.d.ts +32 -0
- package/dist/tools/archetypeSlots.js +257 -0
- package/dist/tools/archetypeTools.d.ts +4 -0
- package/dist/tools/archetypeTools.js +118 -0
- package/dist/tools/callHandler.d.ts +10 -0
- package/dist/tools/callHandler.js +76 -0
- package/dist/tools/catalog.d.ts +4094 -0
- package/dist/tools/catalog.js +5031 -0
- package/dist/tools/domainTools.d.ts +8 -0
- package/dist/tools/domainTools.js +222 -0
- package/dist/tools/mcpSchema.d.ts +20 -3
- package/dist/tools/mcpSchema.js +55 -7
- package/dist/tools/mediaWrites.d.ts +52 -0
- package/dist/tools/mediaWrites.js +322 -0
- package/dist/tools/names.d.ts +4 -4
- package/dist/tools/names.js +14 -1
- package/dist/tools/pdxWriteCore.d.ts +51 -0
- package/dist/tools/pdxWriteCore.js +628 -0
- package/dist/tools/pdxWrites.d.ts +88 -0
- package/dist/tools/pdxWrites.js +629 -0
- package/dist/tools/registry.d.ts +1 -0
- package/dist/tools/scopeBridge.d.ts +36 -0
- package/dist/tools/scopeBridge.js +173 -0
- package/dist/tools/symbols.js +22 -2
- package/dist/tools/targetingWeights.d.ts +206 -0
- package/dist/tools/targetingWeights.js +350 -0
- package/dist/tools/toolHandlers.d.ts +5 -1
- package/dist/tools/toolHandlers.js +146 -33
- package/package.json +1 -1
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ArchetypePlaceholders, ArchetypeSlotValue, ArchetypeContract } from './archetypeSlots';
|
|
2
|
+
export interface HostArchetypeExtractArgs {
|
|
3
|
+
filePath: string;
|
|
4
|
+
definitionIdentity: string;
|
|
5
|
+
definitionPath: string;
|
|
6
|
+
placeholders: ArchetypePlaceholders;
|
|
7
|
+
scopeId: string;
|
|
8
|
+
}
|
|
9
|
+
export interface HostArchetypeArtifact {
|
|
10
|
+
artifactId: string;
|
|
11
|
+
definitionIdentity: string;
|
|
12
|
+
definitionPath: string;
|
|
13
|
+
sourceHash: string;
|
|
14
|
+
contract: ArchetypeContract;
|
|
15
|
+
expiresAt: string;
|
|
16
|
+
}
|
|
17
|
+
export declare class HostArchetypeArtifactStore {
|
|
18
|
+
private workspaceRoot;
|
|
19
|
+
private readonly now;
|
|
20
|
+
private readonly artifacts;
|
|
21
|
+
constructor(workspaceRoot: string, now?: () => number);
|
|
22
|
+
/** Re-point path resolution after the active project root changes (multi-root workspace). */
|
|
23
|
+
setWorkspaceRoot(workspaceRoot: string): void;
|
|
24
|
+
extract(args: HostArchetypeExtractArgs, verifyDefinition: (identity: string, canonicalRealpath: string) => Promise<{
|
|
25
|
+
content: string;
|
|
26
|
+
} | undefined>): Promise<HostArchetypeArtifact>;
|
|
27
|
+
instantiate(artifactId: string, values: Readonly<Record<string, ArchetypeSlotValue>>, scopeId: string): Promise<string>;
|
|
28
|
+
private prune;
|
|
29
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.HostArchetypeArtifactStore = void 0;
|
|
37
|
+
const crypto_1 = require("crypto");
|
|
38
|
+
const fs = __importStar(require("fs"));
|
|
39
|
+
const path = __importStar(require("path"));
|
|
40
|
+
const archetypeSlots_1 = require("./archetypeSlots");
|
|
41
|
+
const MAX_ARTIFACTS = 64;
|
|
42
|
+
const ARTIFACT_TTL_MS = 15 * 60 * 1000;
|
|
43
|
+
function sha256(text) {
|
|
44
|
+
return (0, crypto_1.createHash)('sha256').update(text, 'utf8').digest('hex');
|
|
45
|
+
}
|
|
46
|
+
function fail(message) {
|
|
47
|
+
throw new Error(`archetypeArtifact: ${message}`);
|
|
48
|
+
}
|
|
49
|
+
class HostArchetypeArtifactStore {
|
|
50
|
+
constructor(workspaceRoot, now = Date.now) {
|
|
51
|
+
this.workspaceRoot = workspaceRoot;
|
|
52
|
+
this.now = now;
|
|
53
|
+
this.artifacts = new Map();
|
|
54
|
+
}
|
|
55
|
+
/** Re-point path resolution after the active project root changes (multi-root workspace). */
|
|
56
|
+
setWorkspaceRoot(workspaceRoot) {
|
|
57
|
+
const next = workspaceRoot ? path.resolve(workspaceRoot) : '';
|
|
58
|
+
if (!next)
|
|
59
|
+
return;
|
|
60
|
+
this.workspaceRoot = next;
|
|
61
|
+
}
|
|
62
|
+
async extract(args, verifyDefinition) {
|
|
63
|
+
if (!args || typeof args.filePath !== 'string' || typeof args.definitionPath !== 'string'
|
|
64
|
+
|| typeof args.definitionIdentity !== 'string' || !args.definitionIdentity.trim() || typeof args.scopeId !== 'string' || !args.scopeId) {
|
|
65
|
+
fail('filePath, definitionIdentity, and definitionPath are required');
|
|
66
|
+
}
|
|
67
|
+
const canonicalWorkspace = await fs.promises.realpath(this.workspaceRoot);
|
|
68
|
+
const requested = path.resolve(this.workspaceRoot, args.filePath);
|
|
69
|
+
const declaredDefinitionPath = path.resolve(this.workspaceRoot, args.definitionPath);
|
|
70
|
+
const [canonicalSource, canonicalDefinitionPath] = await Promise.all([
|
|
71
|
+
fs.promises.realpath(requested),
|
|
72
|
+
fs.promises.realpath(declaredDefinitionPath),
|
|
73
|
+
]);
|
|
74
|
+
const relative = path.relative(canonicalWorkspace, canonicalSource);
|
|
75
|
+
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
76
|
+
fail('source must be a workspace file');
|
|
77
|
+
if (canonicalSource !== canonicalDefinitionPath)
|
|
78
|
+
fail('definitionPath does not identify the source file');
|
|
79
|
+
const stat = await fs.promises.stat(canonicalSource);
|
|
80
|
+
if (!stat.isFile())
|
|
81
|
+
fail('source must be a regular file');
|
|
82
|
+
const identity = args.definitionIdentity.trim();
|
|
83
|
+
const verified = await verifyDefinition(identity, canonicalSource);
|
|
84
|
+
if (!verified)
|
|
85
|
+
fail('definition identity/path was not verified by the host');
|
|
86
|
+
const fileText = await fs.promises.readFile(canonicalSource, 'utf8');
|
|
87
|
+
const archetype = (0, archetypeSlots_1.extractArchetypeSlots)(verified.content, args.placeholders);
|
|
88
|
+
const createdAt = this.now();
|
|
89
|
+
this.prune(createdAt);
|
|
90
|
+
while (this.artifacts.size >= MAX_ARTIFACTS)
|
|
91
|
+
this.artifacts.delete(this.artifacts.keys().next().value);
|
|
92
|
+
const artifactId = `arch_${(0, crypto_1.randomBytes)(24).toString('base64url')}`;
|
|
93
|
+
const stored = {
|
|
94
|
+
artifactId,
|
|
95
|
+
definitionIdentity: identity,
|
|
96
|
+
ownerScopeId: args.scopeId,
|
|
97
|
+
canonicalRealpath: canonicalSource,
|
|
98
|
+
sourceHash: sha256(fileText),
|
|
99
|
+
archetype,
|
|
100
|
+
createdAt,
|
|
101
|
+
expiresAt: createdAt + ARTIFACT_TTL_MS,
|
|
102
|
+
};
|
|
103
|
+
this.artifacts.set(artifactId, stored);
|
|
104
|
+
return {
|
|
105
|
+
artifactId,
|
|
106
|
+
definitionIdentity: identity,
|
|
107
|
+
definitionPath: path.relative(canonicalWorkspace, canonicalSource).replace(/\\/g, '/'),
|
|
108
|
+
sourceHash: stored.sourceHash,
|
|
109
|
+
contract: archetype.contract,
|
|
110
|
+
expiresAt: new Date(stored.expiresAt).toISOString(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
async instantiate(artifactId, values, scopeId) {
|
|
114
|
+
if (typeof artifactId !== 'string' || !/^arch_[A-Za-z0-9_-]{32}$/.test(artifactId))
|
|
115
|
+
fail('invalid artifactId');
|
|
116
|
+
const now = this.now();
|
|
117
|
+
this.prune(now);
|
|
118
|
+
const artifact = this.artifacts.get(artifactId);
|
|
119
|
+
if (!artifact || artifact.ownerScopeId !== scopeId)
|
|
120
|
+
fail('artifact is expired, unknown, or belongs to another session');
|
|
121
|
+
const canonicalCurrent = await fs.promises.realpath(artifact.canonicalRealpath);
|
|
122
|
+
if (canonicalCurrent !== artifact.canonicalRealpath)
|
|
123
|
+
fail('source realpath drift detected');
|
|
124
|
+
const text = await fs.promises.readFile(canonicalCurrent, 'utf8');
|
|
125
|
+
if (sha256(text) !== artifact.sourceHash)
|
|
126
|
+
fail('source hash drift detected');
|
|
127
|
+
return (0, archetypeSlots_1.instantiateArchetypeSlots)(artifact.archetype, values);
|
|
128
|
+
}
|
|
129
|
+
prune(now) {
|
|
130
|
+
for (const [id, artifact] of this.artifacts) {
|
|
131
|
+
if (artifact.expiresAt <= now)
|
|
132
|
+
this.artifacts.delete(id);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
exports.HostArchetypeArtifactStore = HostArchetypeArtifactStore;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export type ArchetypeSlotType = 'identifier' | 'string' | 'number' | 'boolean';
|
|
2
|
+
export type ArchetypePlaceholder = ArchetypeSlotType | {
|
|
3
|
+
type: ArchetypeSlotType;
|
|
4
|
+
required?: boolean;
|
|
5
|
+
};
|
|
6
|
+
export type ArchetypePlaceholders = Readonly<Record<string, ArchetypePlaceholder>>;
|
|
7
|
+
export type ArchetypeSlotValue = {
|
|
8
|
+
kind: 'identifier' | 'string';
|
|
9
|
+
value: string;
|
|
10
|
+
} | {
|
|
11
|
+
kind: 'number';
|
|
12
|
+
value: number;
|
|
13
|
+
} | {
|
|
14
|
+
kind: 'boolean';
|
|
15
|
+
value: boolean;
|
|
16
|
+
};
|
|
17
|
+
export interface ArchetypeSlotContract {
|
|
18
|
+
name: string;
|
|
19
|
+
required: boolean;
|
|
20
|
+
type: ArchetypeSlotType;
|
|
21
|
+
occurrences: number;
|
|
22
|
+
}
|
|
23
|
+
export interface ArchetypeContract {
|
|
24
|
+
slots: ArchetypeSlotContract[];
|
|
25
|
+
immutableHash: string;
|
|
26
|
+
}
|
|
27
|
+
export interface ExtractedArchetype {
|
|
28
|
+
text: string;
|
|
29
|
+
contract: ArchetypeContract;
|
|
30
|
+
}
|
|
31
|
+
export declare function extractArchetypeSlots(text: string, placeholders: ArchetypePlaceholders): ExtractedArchetype;
|
|
32
|
+
export declare function instantiateArchetypeSlots(archetype: ExtractedArchetype, values: Readonly<Record<string, ArchetypeSlotValue>>): string;
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.extractArchetypeSlots = extractArchetypeSlots;
|
|
4
|
+
exports.instantiateArchetypeSlots = instantiateArchetypeSlots;
|
|
5
|
+
const crypto_1 = require("crypto");
|
|
6
|
+
const MAX_TEXT_CHARS = 1000000;
|
|
7
|
+
const MAX_SLOTS = 64;
|
|
8
|
+
const MAX_OCCURRENCES = 512;
|
|
9
|
+
const MAX_DEPTH = 16;
|
|
10
|
+
const MAX_TOKEN_CHARS = 4096;
|
|
11
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_.:@-]*$/;
|
|
12
|
+
const PLACEHOLDER = /^\$[A-Za-z_][A-Za-z0-9_]*\$$/;
|
|
13
|
+
function fail(message) {
|
|
14
|
+
throw new Error(`archetypeSlots: ${message}`);
|
|
15
|
+
}
|
|
16
|
+
function normalizePlaceholders(input) {
|
|
17
|
+
const keys = Object.keys(input).sort();
|
|
18
|
+
if (keys.length === 0 || keys.length > MAX_SLOTS)
|
|
19
|
+
fail(`placeholders must contain 1-${MAX_SLOTS} slots`);
|
|
20
|
+
const result = new Map();
|
|
21
|
+
for (const name of keys) {
|
|
22
|
+
if (!PLACEHOLDER.test(name))
|
|
23
|
+
fail(`invalid placeholder ${name}`);
|
|
24
|
+
const raw = input[name];
|
|
25
|
+
const descriptor = typeof raw === 'string' ? { type: raw, required: true } : raw;
|
|
26
|
+
if (!descriptor || typeof descriptor !== 'object' || Array.isArray(descriptor))
|
|
27
|
+
fail(`invalid descriptor for ${name}`);
|
|
28
|
+
const record = descriptor;
|
|
29
|
+
if (Object.keys(record).some(key => key !== 'type' && key !== 'required'))
|
|
30
|
+
fail(`unsupported descriptor field for ${name}`);
|
|
31
|
+
if (!['identifier', 'string', 'number', 'boolean'].includes(String(record.type)))
|
|
32
|
+
fail(`invalid type for ${name}`);
|
|
33
|
+
if (record.required !== undefined && typeof record.required !== 'boolean')
|
|
34
|
+
fail(`required must be boolean for ${name}`);
|
|
35
|
+
result.set(name, { type: record.type, required: record.required !== false });
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
class Scanner {
|
|
40
|
+
constructor(text, slots) {
|
|
41
|
+
this.text = text;
|
|
42
|
+
this.slots = slots;
|
|
43
|
+
this.index = 0;
|
|
44
|
+
this.occurrences = [];
|
|
45
|
+
}
|
|
46
|
+
scan() {
|
|
47
|
+
this.skipTrivia();
|
|
48
|
+
if (this.text[this.index] === '{') {
|
|
49
|
+
this.index++;
|
|
50
|
+
this.scanSequence('}', 1);
|
|
51
|
+
this.skipTrivia();
|
|
52
|
+
if (this.index !== this.text.length)
|
|
53
|
+
fail('unexpected text after block');
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
this.scanSequence(undefined, 0);
|
|
57
|
+
}
|
|
58
|
+
return this.occurrences;
|
|
59
|
+
}
|
|
60
|
+
scanSequence(stop, depth) {
|
|
61
|
+
if (depth > MAX_DEPTH)
|
|
62
|
+
fail('block nesting exceeds safety limit');
|
|
63
|
+
while (true) {
|
|
64
|
+
this.skipTrivia();
|
|
65
|
+
if (this.index >= this.text.length) {
|
|
66
|
+
if (stop)
|
|
67
|
+
fail('unterminated block');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (this.text[this.index] === '}') {
|
|
71
|
+
if (!stop)
|
|
72
|
+
fail('unmatched closing brace');
|
|
73
|
+
this.index++;
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const start = this.index;
|
|
77
|
+
this.readScalar(false);
|
|
78
|
+
const afterFirst = this.index;
|
|
79
|
+
this.skipTrivia();
|
|
80
|
+
if (this.text[this.index] === '=') {
|
|
81
|
+
this.index++;
|
|
82
|
+
this.skipTrivia();
|
|
83
|
+
this.readValue(depth);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
this.index = afterFirst;
|
|
87
|
+
if (this.index === start)
|
|
88
|
+
fail(`invalid token at offset ${this.index}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
readValue(depth) {
|
|
93
|
+
if (this.text[this.index] === '{') {
|
|
94
|
+
this.index++;
|
|
95
|
+
this.scanSequence('}', depth + 1);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
this.readScalar(true);
|
|
99
|
+
}
|
|
100
|
+
readScalar(valuePosition) {
|
|
101
|
+
const start = this.index;
|
|
102
|
+
if (this.text[this.index] === '"') {
|
|
103
|
+
this.index++;
|
|
104
|
+
const contentStart = this.index;
|
|
105
|
+
let decoded = '';
|
|
106
|
+
while (this.index < this.text.length && this.text[this.index] !== '"') {
|
|
107
|
+
const char = this.text[this.index];
|
|
108
|
+
if (char === '\n' || char === '\r')
|
|
109
|
+
fail('newline in quoted scalar');
|
|
110
|
+
if (char === '\\') {
|
|
111
|
+
this.index++;
|
|
112
|
+
if (this.index >= this.text.length)
|
|
113
|
+
fail('unterminated escape');
|
|
114
|
+
decoded += this.text[this.index];
|
|
115
|
+
this.index++;
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
decoded += char;
|
|
119
|
+
this.index++;
|
|
120
|
+
}
|
|
121
|
+
if (this.index - contentStart > MAX_TOKEN_CHARS)
|
|
122
|
+
fail('scalar exceeds safety limit');
|
|
123
|
+
}
|
|
124
|
+
if (this.text[this.index] !== '"')
|
|
125
|
+
fail('unterminated quoted scalar');
|
|
126
|
+
const contentEnd = this.index;
|
|
127
|
+
this.index++;
|
|
128
|
+
if (valuePosition && this.slots.has(decoded))
|
|
129
|
+
this.addOccurrence(decoded, contentStart, contentEnd, true);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
while (this.index < this.text.length && !/[\s{}=#]/.test(this.text[this.index]))
|
|
133
|
+
this.index++;
|
|
134
|
+
if (this.index === start)
|
|
135
|
+
fail(`expected scalar at offset ${start}`);
|
|
136
|
+
if (this.index - start > MAX_TOKEN_CHARS)
|
|
137
|
+
fail('scalar exceeds safety limit');
|
|
138
|
+
const token = this.text.slice(start, this.index);
|
|
139
|
+
if (valuePosition && this.slots.has(token))
|
|
140
|
+
this.addOccurrence(token, start, this.index, false);
|
|
141
|
+
}
|
|
142
|
+
addOccurrence(name, start, end, quoted) {
|
|
143
|
+
const descriptor = this.slots.get(name);
|
|
144
|
+
if ((descriptor.type === 'string') !== quoted)
|
|
145
|
+
fail(`placeholder ${name} must be ${descriptor.type === 'string' ? 'quoted' : 'unquoted'}`);
|
|
146
|
+
if (this.occurrences.length >= MAX_OCCURRENCES)
|
|
147
|
+
fail('slot occurrences exceed safety limit');
|
|
148
|
+
this.occurrences.push({ name, start, end, quoted });
|
|
149
|
+
}
|
|
150
|
+
skipTrivia() {
|
|
151
|
+
while (this.index < this.text.length) {
|
|
152
|
+
if (/\s/.test(this.text[this.index])) {
|
|
153
|
+
this.index++;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (this.text[this.index] === '#') {
|
|
157
|
+
while (this.index < this.text.length && this.text[this.index] !== '\n')
|
|
158
|
+
this.index++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function findOccurrences(text, slots) {
|
|
166
|
+
if (typeof text !== 'string' || text.length > MAX_TEXT_CHARS)
|
|
167
|
+
fail(`text must not exceed ${MAX_TEXT_CHARS} characters`);
|
|
168
|
+
return new Scanner(text, slots).scan();
|
|
169
|
+
}
|
|
170
|
+
function immutableHash(text, occurrences, slots) {
|
|
171
|
+
const hash = (0, crypto_1.createHash)('sha256');
|
|
172
|
+
const frame = (value) => { hash.update(String(Buffer.byteLength(value, 'utf8'))).update(':').update(value); };
|
|
173
|
+
frame('cwtools.archetype-slots.v1');
|
|
174
|
+
for (const [name, descriptor] of slots) {
|
|
175
|
+
frame(name);
|
|
176
|
+
frame(descriptor.type);
|
|
177
|
+
frame(descriptor.required ? 'required' : 'optional');
|
|
178
|
+
frame(String(occurrences.filter(occurrence => occurrence.name === name).length));
|
|
179
|
+
}
|
|
180
|
+
let offset = 0;
|
|
181
|
+
for (const occurrence of occurrences) {
|
|
182
|
+
frame(text.slice(offset, occurrence.start));
|
|
183
|
+
frame(occurrence.name);
|
|
184
|
+
offset = occurrence.end;
|
|
185
|
+
}
|
|
186
|
+
frame(text.slice(offset));
|
|
187
|
+
return hash.digest('hex');
|
|
188
|
+
}
|
|
189
|
+
function extractArchetypeSlots(text, placeholders) {
|
|
190
|
+
const slots = normalizePlaceholders(placeholders);
|
|
191
|
+
const occurrences = findOccurrences(text, slots);
|
|
192
|
+
const contractSlots = [];
|
|
193
|
+
for (const [name, descriptor] of slots) {
|
|
194
|
+
const count = occurrences.reduce((total, occurrence) => total + Number(occurrence.name === name), 0);
|
|
195
|
+
if (descriptor.required && count === 0)
|
|
196
|
+
fail(`required placeholder ${name} does not occur in the archetype`);
|
|
197
|
+
contractSlots.push({ name, required: descriptor.required, type: descriptor.type, occurrences: count });
|
|
198
|
+
}
|
|
199
|
+
return { text, contract: { slots: contractSlots, immutableHash: immutableHash(text, occurrences, slots) } };
|
|
200
|
+
}
|
|
201
|
+
function renderSlot(value, slot, quoted) {
|
|
202
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
203
|
+
fail(`value for ${slot.name} must be a typed PdxValue`);
|
|
204
|
+
const record = value;
|
|
205
|
+
if (Object.keys(record).some(key => key !== 'kind' && key !== 'value'))
|
|
206
|
+
fail(`unsupported value field for ${slot.name}; raw is forbidden`);
|
|
207
|
+
if (record.kind !== slot.type)
|
|
208
|
+
fail(`value for ${slot.name} must have type ${slot.type}`);
|
|
209
|
+
switch (slot.type) {
|
|
210
|
+
case 'identifier':
|
|
211
|
+
if (typeof record.value !== 'string' || !IDENTIFIER.test(record.value))
|
|
212
|
+
fail(`invalid identifier for ${slot.name}`);
|
|
213
|
+
return record.value;
|
|
214
|
+
case 'string':
|
|
215
|
+
if (!quoted || typeof record.value !== 'string' || record.value.length > MAX_TOKEN_CHARS || [...record.value].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
|
|
216
|
+
fail(`invalid string for ${slot.name}`);
|
|
217
|
+
return JSON.stringify(record.value).slice(1, -1);
|
|
218
|
+
case 'number':
|
|
219
|
+
if (typeof record.value !== 'number' || !Number.isFinite(record.value))
|
|
220
|
+
fail(`invalid number for ${slot.name}`);
|
|
221
|
+
return String(record.value);
|
|
222
|
+
case 'boolean':
|
|
223
|
+
if (typeof record.value !== 'boolean')
|
|
224
|
+
fail(`invalid boolean for ${slot.name}`);
|
|
225
|
+
return record.value ? 'yes' : 'no';
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
function instantiateArchetypeSlots(archetype, values) {
|
|
229
|
+
if (!archetype || typeof archetype !== 'object' || typeof archetype.text !== 'string' || !archetype.contract || !Array.isArray(archetype.contract.slots))
|
|
230
|
+
fail('invalid archetype');
|
|
231
|
+
const descriptors = Object.fromEntries(archetype.contract.slots.map(slot => [slot.name, { type: slot.type, required: slot.required }]));
|
|
232
|
+
const slots = normalizePlaceholders(descriptors);
|
|
233
|
+
const occurrences = findOccurrences(archetype.text, slots);
|
|
234
|
+
if (immutableHash(archetype.text, occurrences, slots) !== archetype.contract.immutableHash)
|
|
235
|
+
fail('immutable hash drift detected');
|
|
236
|
+
for (const slot of archetype.contract.slots) {
|
|
237
|
+
const actual = occurrences.filter(occurrence => occurrence.name === slot.name).length;
|
|
238
|
+
if (actual !== slot.occurrences)
|
|
239
|
+
fail(`occurrence drift detected for ${slot.name}`);
|
|
240
|
+
if (slot.required && values[slot.name] === undefined)
|
|
241
|
+
fail(`missing required value for ${slot.name}`);
|
|
242
|
+
}
|
|
243
|
+
const allowed = new Set(archetype.contract.slots.map(slot => slot.name));
|
|
244
|
+
const extra = Object.keys(values).filter(name => !allowed.has(name));
|
|
245
|
+
if (extra.length)
|
|
246
|
+
fail(`unknown slot value(s): ${extra.join(', ')}`);
|
|
247
|
+
let result = '';
|
|
248
|
+
let offset = 0;
|
|
249
|
+
const byName = new Map(archetype.contract.slots.map(slot => [slot.name, slot]));
|
|
250
|
+
for (const occurrence of occurrences) {
|
|
251
|
+
result += archetype.text.slice(offset, occurrence.start);
|
|
252
|
+
const value = values[occurrence.name];
|
|
253
|
+
result += value === undefined ? archetype.text.slice(occurrence.start, occurrence.end) : renderSlot(value, byName.get(occurrence.name), occurrence.quoted);
|
|
254
|
+
offset = occurrence.end;
|
|
255
|
+
}
|
|
256
|
+
return result + archetype.text.slice(offset);
|
|
257
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { HostServices } from '../host/hostServices';
|
|
2
|
+
import type { SharedToolResult } from './schema';
|
|
3
|
+
export declare function extractArchetypeWithHost(host: HostServices, args: Record<string, unknown>): Promise<SharedToolResult>;
|
|
4
|
+
export declare function instantiateArchetypeWithHost(host: HostServices, args: Record<string, unknown>): Promise<SharedToolResult>;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.extractArchetypeWithHost = extractArchetypeWithHost;
|
|
37
|
+
exports.instantiateArchetypeWithHost = instantiateArchetypeWithHost;
|
|
38
|
+
const path = __importStar(require("path"));
|
|
39
|
+
const url_1 = require("url");
|
|
40
|
+
const archetypeArtifacts_1 = require("./archetypeArtifacts");
|
|
41
|
+
const pdxBlock_1 = require("./pdxBlock");
|
|
42
|
+
const symbols_1 = require("./symbols");
|
|
43
|
+
const stores = new WeakMap();
|
|
44
|
+
function storeFor(host) {
|
|
45
|
+
const existing = stores.get(host);
|
|
46
|
+
if (existing)
|
|
47
|
+
return existing;
|
|
48
|
+
const created = new archetypeArtifacts_1.HostArchetypeArtifactStore(host.workspaceRoot, host.now);
|
|
49
|
+
stores.set(host, created);
|
|
50
|
+
return created;
|
|
51
|
+
}
|
|
52
|
+
function asRecord(value) {
|
|
53
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
54
|
+
}
|
|
55
|
+
function canonicalKey(value) {
|
|
56
|
+
const resolved = path.resolve(value);
|
|
57
|
+
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
|
58
|
+
}
|
|
59
|
+
function responseMatches(value, identity, canonicalPath, depth = 0) {
|
|
60
|
+
if (depth > 8 || !value || typeof value !== 'object')
|
|
61
|
+
return false;
|
|
62
|
+
if (Array.isArray(value))
|
|
63
|
+
return value.slice(0, 200).some(item => responseMatches(item, identity, canonicalPath, depth + 1));
|
|
64
|
+
const record = asRecord(value);
|
|
65
|
+
const identityMatches = ['name', 'symbolName', 'identity', 'key', 'id']
|
|
66
|
+
.some(key => typeof record[key] === 'string' && String(record[key]).toLowerCase() === identity.toLowerCase());
|
|
67
|
+
const pathMatches = Object.values(record).slice(0, 200).some(item => {
|
|
68
|
+
if (typeof item !== 'string')
|
|
69
|
+
return false;
|
|
70
|
+
try {
|
|
71
|
+
const file = item.startsWith('file:') ? (0, url_1.fileURLToPath)(item) : item;
|
|
72
|
+
return path.isAbsolute(file) && canonicalKey(file) === canonicalKey(canonicalPath);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
if (identityMatches && pathMatches)
|
|
79
|
+
return true;
|
|
80
|
+
return Object.values(record).slice(0, 200).some(item => responseMatches(item, identity, canonicalPath, depth + 1));
|
|
81
|
+
}
|
|
82
|
+
async function verifiedContent(host, identity, canonicalPath) {
|
|
83
|
+
const definition = await (0, symbols_1.queryDefinitionByNameWithHost)(host, { symbolName: identity });
|
|
84
|
+
if (!definition.ok || !responseMatches(definition.data, identity, canonicalPath))
|
|
85
|
+
return undefined;
|
|
86
|
+
const block = await (0, pdxBlock_1.getPdxBlockWithHost)(host, { file: canonicalPath, symbol: identity });
|
|
87
|
+
return block.ok && block.data && !block.data.truncated ? block.data.content : undefined;
|
|
88
|
+
}
|
|
89
|
+
async function extractArchetypeWithHost(host, args) {
|
|
90
|
+
try {
|
|
91
|
+
const input = {
|
|
92
|
+
filePath: typeof args.filePath === 'string' ? args.filePath : '',
|
|
93
|
+
definitionIdentity: typeof args.definitionIdentity === 'string' ? args.definitionIdentity : '',
|
|
94
|
+
definitionPath: typeof args.definitionPath === 'string' ? args.definitionPath : '',
|
|
95
|
+
placeholders: (args.placeholders ?? {}),
|
|
96
|
+
scopeId: host.workspaceRoot,
|
|
97
|
+
};
|
|
98
|
+
const artifact = await storeFor(host).extract(input, async (identity, canonicalPath) => {
|
|
99
|
+
const content = await verifiedContent(host, identity, canonicalPath);
|
|
100
|
+
return content === undefined ? undefined : { content };
|
|
101
|
+
});
|
|
102
|
+
return { ok: true, status: 'ready', source: 'cwtools-archetypes', data: { success: true, artifact } };
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
return { ok: false, status: 'error', source: 'cwtools-archetypes', error: { code: 'archetype_extract_failed', message: error instanceof Error ? error.message : String(error) } };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function instantiateArchetypeWithHost(host, args) {
|
|
109
|
+
try {
|
|
110
|
+
const artifactId = typeof args.artifactId === 'string' ? args.artifactId : '';
|
|
111
|
+
const values = (args.values ?? {});
|
|
112
|
+
const content = await storeFor(host).instantiate(artifactId, values, host.workspaceRoot);
|
|
113
|
+
return { ok: true, status: 'ready', source: 'cwtools-archetypes', data: { success: true, content } };
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
return { ok: false, status: 'error', source: 'cwtools-archetypes', error: { code: 'archetype_instantiate_failed', message: error instanceof Error ? error.message : String(error) } };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { HostServices } from '../host/hostServices';
|
|
2
|
+
import { type SharedToolContext, type SharedToolDispatcher } from './toolHandlers';
|
|
3
|
+
import type { SharedToolResult } from './schema';
|
|
4
|
+
/** Per-call context. `signal` cancels the underlying backend work. */
|
|
5
|
+
export type ToolCallContext = SharedToolContext;
|
|
6
|
+
export type SharedToolHandler = (name: string, args?: Record<string, unknown>, context?: ToolCallContext) => Promise<SharedToolResult>;
|
|
7
|
+
export declare const GENERIC_PARADOX_WARNING = "Generic Paradox mode: the exact game is unknown; no game-specific rules or vanilla data are assumed. Pass --game to select a game.";
|
|
8
|
+
export declare function createToolCallHandler(host: HostServices, dispatcher?: SharedToolDispatcher): SharedToolHandler;
|
|
9
|
+
/** Convenience wrapper for hosts that keep one handler per host instance. */
|
|
10
|
+
export declare function bindToolCallHandler(host: HostServices, dispatcher?: SharedToolDispatcher): SharedToolHandler;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GENERIC_PARADOX_WARNING = void 0;
|
|
4
|
+
exports.createToolCallHandler = createToolCallHandler;
|
|
5
|
+
exports.bindToolCallHandler = bindToolCallHandler;
|
|
6
|
+
const lsp_1 = require("../host/lsp");
|
|
7
|
+
const readiness_1 = require("../host/readiness");
|
|
8
|
+
const vanillaCache_1 = require("../host/vanillaCache");
|
|
9
|
+
const mcpSchema_1 = require("./mcpSchema");
|
|
10
|
+
const toolHandlers_1 = require("./toolHandlers");
|
|
11
|
+
exports.GENERIC_PARADOX_WARNING = 'Generic Paradox mode: the exact game is unknown; no game-specific rules or vanilla data are assumed. Pass --game to select a game.';
|
|
12
|
+
function createToolCallHandler(host, dispatcher = toolHandlers_1.defaultSharedToolDispatcher) {
|
|
13
|
+
// The game stays loaded once ready, so a successful probe is cached — but only
|
|
14
|
+
// until a call reports the backend gone. A cached `ready` outliving the LSP is
|
|
15
|
+
// why degraded calls kept advertising `readiness.ready: true`.
|
|
16
|
+
let ready = false;
|
|
17
|
+
const probeReadiness = async (context, force = false) => {
|
|
18
|
+
if (ready && !force)
|
|
19
|
+
return { ready: true };
|
|
20
|
+
try {
|
|
21
|
+
const status = await host.lsp.executeCommand('cwtools.ai.getValidationStatus', [], {
|
|
22
|
+
timeoutMs: 8000,
|
|
23
|
+
...(context?.signal ? { signal: context.signal } : {}),
|
|
24
|
+
});
|
|
25
|
+
const verdict = (0, readiness_1.parseReadiness)(status);
|
|
26
|
+
ready = verdict.ready;
|
|
27
|
+
return verdict;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
// A cancelled probe is not an absent backend: surface the abort instead of
|
|
31
|
+
// reporting `lsp_unavailable`.
|
|
32
|
+
(0, lsp_1.throwIfAborted)(context?.signal);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
return async (name, args = {}, context) => {
|
|
37
|
+
(0, lsp_1.throwIfAborted)(context?.signal);
|
|
38
|
+
const writesEnabled = host.writesEnabled === true && host.readonlyMode === false;
|
|
39
|
+
const cwtOnly = host.projectKind === 'cwt-only';
|
|
40
|
+
if (!(0, mcpSchema_1.isMcpToolAvailable)(name, { includeWrites: writesEnabled, cwtOnly, capabilities: host.capabilities })) {
|
|
41
|
+
return {
|
|
42
|
+
ok: false,
|
|
43
|
+
status: 'denied',
|
|
44
|
+
source: 'cwtools-shared',
|
|
45
|
+
error: {
|
|
46
|
+
code: cwtOnly ? 'tool_not_available_in_cwt_only' : 'tool_not_available',
|
|
47
|
+
message: cwtOnly
|
|
48
|
+
? `Tool '${name}' requires a full Paradox game model and is not available in a CWT-only workspace.`
|
|
49
|
+
: `Tool '${name}' is not available under the current host write policy.`,
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const result = await dispatcher(host, name, args, context);
|
|
54
|
+
const withGenericWarning = host.projectGameId === 'paradox'
|
|
55
|
+
? {
|
|
56
|
+
...result,
|
|
57
|
+
warnings: [...(result.warnings ?? []), exports.GENERIC_PARADOX_WARNING],
|
|
58
|
+
}
|
|
59
|
+
: result;
|
|
60
|
+
// Tag vanilla-dependent results with cache provenance so clients never read a
|
|
61
|
+
// mod-only answer as complete.
|
|
62
|
+
const withVanilla = (0, vanillaCache_1.annotateVanillaCache)(name, withGenericWarning, host.vanillaCache);
|
|
63
|
+
// For load-dependent tools, mark results produced before the game is ready as
|
|
64
|
+
// `loading` so clients retry instead of trusting an empty answer.
|
|
65
|
+
if (!readiness_1.LOAD_DEPENDENT_TOOLS.has(name))
|
|
66
|
+
return withVanilla;
|
|
67
|
+
// Re-probe after a transport-shaped failure so a dead backend cannot keep
|
|
68
|
+
// riding on a cached `ready` from an earlier call.
|
|
69
|
+
const lostBackend = result.ok === false && result.status === 'unavailable';
|
|
70
|
+
return (0, readiness_1.annotateReadiness)(name, withVanilla, await probeReadiness(context, lostBackend));
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** Convenience wrapper for hosts that keep one handler per host instance. */
|
|
74
|
+
function bindToolCallHandler(host, dispatcher = toolHandlers_1.defaultSharedToolDispatcher) {
|
|
75
|
+
return createToolCallHandler(host, dispatcher);
|
|
76
|
+
}
|