tokensafe-ui 0.1.1 → 0.1.3

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.
@@ -0,0 +1,566 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __dirnameFunc } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __dirnameFunc(__filename);
7
+ import {
8
+ buildDependencyGraph
9
+ } from "./chunk-DC5DUO6P.js";
10
+ import {
11
+ testAction
12
+ } from "./chunk-KAQKTPPN.js";
13
+ import {
14
+ applyPatch
15
+ } from "./chunk-R6O2VMCZ.js";
16
+
17
+ // ../mcp/dist/index.js
18
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
19
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
20
+ import {
21
+ CallToolRequestSchema,
22
+ ListToolsRequestSchema
23
+ } from "@modelcontextprotocol/sdk/types.js";
24
+ import fs3 from "fs";
25
+ import path3 from "path";
26
+ import crypto2 from "crypto";
27
+ import * as parser2 from "@babel/parser";
28
+ import _traverse from "@babel/traverse";
29
+ import * as t from "@babel/types";
30
+ import fs from "fs";
31
+ import path from "path";
32
+ import fs2 from "fs";
33
+ import path2 from "path";
34
+ import crypto from "crypto";
35
+ import * as parser from "@babel/parser";
36
+ import ts from "typescript";
37
+ function validateWorkspacePath(inputPath, projectRoot) {
38
+ let canonicalRoot = path.resolve(projectRoot);
39
+ try {
40
+ if (fs.existsSync(canonicalRoot)) {
41
+ canonicalRoot = fs.realpathSync(canonicalRoot);
42
+ }
43
+ } catch {
44
+ }
45
+ let resolvedTarget = path.isAbsolute(inputPath) ? path.resolve(inputPath) : path.resolve(canonicalRoot, inputPath);
46
+ try {
47
+ if (fs.existsSync(resolvedTarget)) {
48
+ resolvedTarget = fs.realpathSync(resolvedTarget);
49
+ }
50
+ } catch {
51
+ }
52
+ const rootWithSep = canonicalRoot.endsWith(path.sep) ? canonicalRoot : canonicalRoot + path.sep;
53
+ if (resolvedTarget !== canonicalRoot && !resolvedTarget.startsWith(rootWithSep)) {
54
+ throw new Error(
55
+ `Security Violation: Path traversal blocked. Target '${inputPath}' escapes workspace root '${projectRoot}'.`
56
+ );
57
+ }
58
+ return resolvedTarget;
59
+ }
60
+ function checkSecretLeak(content) {
61
+ if (content.includes("BEGIN PRIVATE KEY") || content.includes("BEGIN RSA PRIVATE KEY")) {
62
+ return {
63
+ hasLeak: true,
64
+ reason: "Hardcoded private key detected in source payload"
65
+ };
66
+ }
67
+ const secretPatterns = [
68
+ /ghp_[a-zA-Z0-9]{36}/,
69
+ // GitHub personal access token
70
+ /gho_[a-zA-Z0-9]{36}/,
71
+ // GitHub OAuth token
72
+ /sk-[a-zA-Z0-9]{32,}/,
73
+ // OpenAI / API secret keys
74
+ /xox[baprs]-[0-9a-zA-Z]{10,}/,
75
+ // Slack tokens
76
+ /AIza[0-9A-Za-z-_]{35}/
77
+ // Google API keys
78
+ ];
79
+ for (const pattern of secretPatterns) {
80
+ if (pattern.test(content)) {
81
+ return {
82
+ hasLeak: true,
83
+ reason: `Potential secret or API token matching pattern '${pattern.source}' detected`
84
+ };
85
+ }
86
+ }
87
+ return { hasLeak: false };
88
+ }
89
+ function validateSourceSyntaxAndTypes(source, fileName = "component.tsx") {
90
+ try {
91
+ parser.parse(source, {
92
+ sourceType: "module",
93
+ plugins: ["typescript", "jsx"]
94
+ });
95
+ } catch (err) {
96
+ const loc = err.loc ? `line ${err.loc.line}, column ${err.loc.column}` : "unknown";
97
+ throw new Error(`SYNTAX_ERROR: TypeScript/JSX parse failed at ${loc}: ${err.message}`);
98
+ }
99
+ const sourceFile = ts.createSourceFile(
100
+ fileName,
101
+ source,
102
+ ts.ScriptTarget.Latest,
103
+ true,
104
+ fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
105
+ );
106
+ const diagnostics = sourceFile.parseDiagnostics || [];
107
+ if (diagnostics.length > 0) {
108
+ const first = diagnostics[0];
109
+ const message = ts.flattenDiagnosticMessageText(first.messageText, "\n");
110
+ throw new Error(`TYPESCRIPT_DIAGNOSTIC_ERROR: ${message}`);
111
+ }
112
+ const leak = checkSecretLeak(source);
113
+ if (leak.hasLeak) {
114
+ throw new Error(`SECURITY_VIOLATION: ${leak.reason}`);
115
+ }
116
+ }
117
+ function atomicApplySourceEdit(targetFilePath, newSource, options = {}) {
118
+ if (!fs2.existsSync(targetFilePath)) {
119
+ throw new Error(`File not found: ${targetFilePath}`);
120
+ }
121
+ const currentContent = fs2.readFileSync(targetFilePath, "utf-8");
122
+ const currentVersion = "sha256:" + crypto.createHash("sha256").update(currentContent).digest("hex");
123
+ if (options.expectedVersion && currentVersion !== options.expectedVersion) {
124
+ throw new Error(
125
+ `CONFLICT_DETECTED: File was modified concurrently. Expected version '${options.expectedVersion}', but disk version is '${currentVersion}'. Re-inspect before retrying.`
126
+ );
127
+ }
128
+ if (options.validateTypeScript !== false) {
129
+ validateSourceSyntaxAndTypes(newSource, path2.basename(targetFilePath));
130
+ } else {
131
+ const leak = checkSecretLeak(newSource);
132
+ if (leak.hasLeak) {
133
+ throw new Error(`SECURITY_VIOLATION: ${leak.reason}`);
134
+ }
135
+ }
136
+ const dir = path2.dirname(targetFilePath);
137
+ const base = path2.basename(targetFilePath);
138
+ const tmpPath = path2.join(dir, `.${base}.tmp.${Date.now()}.${process.pid}`);
139
+ const backupPath = path2.join(dir, `.${base}.bak.${Date.now()}`);
140
+ try {
141
+ fs2.writeFileSync(tmpPath, newSource, "utf-8");
142
+ const writtenContent = fs2.readFileSync(tmpPath, "utf-8");
143
+ if (writtenContent !== newSource) {
144
+ throw new Error(
145
+ "ATOMIC_WRITE_VERIFICATION_FAILED: Written temporary content does not match payload."
146
+ );
147
+ }
148
+ fs2.copyFileSync(targetFilePath, backupPath);
149
+ fs2.renameSync(tmpPath, targetFilePath);
150
+ if (!options.createBackup && fs2.existsSync(backupPath)) {
151
+ try {
152
+ fs2.unlinkSync(backupPath);
153
+ } catch {
154
+ }
155
+ }
156
+ const newVersion = "sha256:" + crypto.createHash("sha256").update(newSource).digest("hex");
157
+ return {
158
+ success: true,
159
+ filePath: targetFilePath,
160
+ version: newVersion,
161
+ backupPath: options.createBackup ? backupPath : void 0,
162
+ message: `Successfully applied atomic source edit with verified syntax and types.`
163
+ };
164
+ } catch (err) {
165
+ if (fs2.existsSync(tmpPath)) {
166
+ try {
167
+ fs2.unlinkSync(tmpPath);
168
+ } catch {
169
+ }
170
+ }
171
+ if (fs2.existsSync(backupPath)) {
172
+ try {
173
+ fs2.copyFileSync(backupPath, targetFilePath);
174
+ fs2.unlinkSync(backupPath);
175
+ } catch {
176
+ }
177
+ }
178
+ throw err;
179
+ }
180
+ }
181
+ var traverse = _traverse.default || _traverse;
182
+ function createAgentDomMcpServer(config = {}) {
183
+ const devServerUrl = config.devServerUrl || "http://localhost:5173";
184
+ const projectRoot = config.projectRoot || process.cwd();
185
+ const server = new Server(
186
+ {
187
+ name: "agent-dom-mcp",
188
+ version: "0.2.0"
189
+ },
190
+ {
191
+ capabilities: {
192
+ tools: {}
193
+ }
194
+ }
195
+ );
196
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
197
+ return {
198
+ tools: [
199
+ {
200
+ name: "agent_dom_observe",
201
+ description: "OBSERVE (Pillar 1): Progressive context disclosure query (L0 Pulse <25t, L1 Surface <150t, L2 Contract, L3 Source, L4 Traces).",
202
+ inputSchema: {
203
+ type: "object",
204
+ properties: {
205
+ level: {
206
+ type: "string",
207
+ enum: ["L0", "L1", "L2", "L3", "L4"],
208
+ default: "L1",
209
+ description: "Observation level (L0: Pulse, L1: Surface, L2: Contract, L3: Source, L4: Traces)"
210
+ },
211
+ format: {
212
+ type: "string",
213
+ enum: ["yaml", "sexp", "json"],
214
+ default: "yaml"
215
+ },
216
+ componentId: {
217
+ type: "string",
218
+ description: "Optional target component ID for L2/L3/L4 drill-down"
219
+ }
220
+ }
221
+ }
222
+ },
223
+ {
224
+ name: "agent_dom_understand",
225
+ description: 'UNDERSTAND (Pillar 2): Dynamic impact analysis and runtime causality telemetry. Answers "What breaks if I change this?" or "Why is UI in this state?".',
226
+ inputSchema: {
227
+ type: "object",
228
+ properties: {
229
+ query: {
230
+ type: "string",
231
+ enum: ["impact", "dependencies", "causality", "why_state"],
232
+ description: "Type of understanding query (impact, dependencies, or causality/why_state)"
233
+ },
234
+ target: {
235
+ type: "string",
236
+ description: 'State key, element ID, or Component ID to analyze (e.g. "counter-card.count")'
237
+ }
238
+ },
239
+ required: ["query"]
240
+ }
241
+ },
242
+ {
243
+ name: "agent_dom_get_component_source",
244
+ description: "MUTATE (Pillar 3): Symbol-level source code retrieval with line mapping, AST bounds, and OCC version token for safe, isolated edits.",
245
+ inputSchema: {
246
+ type: "object",
247
+ properties: {
248
+ componentId: { type: "string", description: 'Component ID, e.g. "task-board"' },
249
+ filePath: { type: "string", description: "Relative path to component file" }
250
+ },
251
+ required: ["componentId", "filePath"]
252
+ }
253
+ },
254
+ {
255
+ name: "agent_dom_apply_source_edit",
256
+ description: "MUTATE (Pillar 3): Applies symbol-level TypeScript source edits with Optimistic Concurrency Control (OCC), TypeScript/JSX syntax verification, and secret leak prevention.",
257
+ inputSchema: {
258
+ type: "object",
259
+ properties: {
260
+ filePath: { type: "string", description: "Relative path to component file" },
261
+ source: { type: "string", description: "Complete updated source code of the component" },
262
+ expectedVersion: {
263
+ type: "string",
264
+ description: "Required OCC version token (sha256:...) from agent_dom_get_component_source to prevent lost updates"
265
+ }
266
+ },
267
+ required: ["filePath", "source", "expectedVersion"]
268
+ }
269
+ },
270
+ {
271
+ name: "agent_dom_test_action",
272
+ description: "VERIFY (Pillar 4): Low-millisecond Local Action Verification. Executes an action or effect in memory and returns a structured before/after state diff and surface diff without a browser.",
273
+ inputSchema: {
274
+ type: "object",
275
+ properties: {
276
+ componentId: { type: "string", description: "Target component ID" },
277
+ action: { type: "string", description: "Action or effect name to trigger" },
278
+ payload: { description: "Optional action payload" }
279
+ },
280
+ required: ["componentId", "action"]
281
+ }
282
+ },
283
+ {
284
+ name: "agent_dom_apply_patch",
285
+ description: "MUTATE Macro: Applies a surgical AST patch (add action, update state schema, insert JSX, or bind event) with instant HMR.",
286
+ inputSchema: {
287
+ type: "object",
288
+ properties: {
289
+ filePath: { type: "string", description: "Path to component file to patch" },
290
+ patch: { type: "object", description: "Component patch specification" }
291
+ },
292
+ required: ["filePath", "patch"]
293
+ }
294
+ },
295
+ {
296
+ name: "agent_dom_get_errors",
297
+ description: "Returns structured, machine-actionable compiler or runtime error payloads without minified stack traces.",
298
+ inputSchema: {
299
+ type: "object",
300
+ properties: {}
301
+ }
302
+ }
303
+ ]
304
+ };
305
+ });
306
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
307
+ const { name, arguments: args = {} } = request.params;
308
+ switch (name) {
309
+ case "agent_dom_observe": {
310
+ const { level = "L1", format = "yaml", componentId } = args;
311
+ try {
312
+ const res = await fetch(`${devServerUrl}/__agent_dom/rpc`, {
313
+ method: "POST",
314
+ headers: { "Content-Type": "application/json" },
315
+ body: JSON.stringify({ method: "observe", params: { level, format, componentId } })
316
+ });
317
+ if (res.ok) {
318
+ const data = await res.json();
319
+ return {
320
+ content: [{ type: "text", text: data.result?.payload || "level: empty" }]
321
+ };
322
+ }
323
+ } catch {
324
+ }
325
+ return {
326
+ content: [
327
+ {
328
+ type: "text",
329
+ text: `level: ${level}
330
+ status: dev_server_offline
331
+ note: Vite DevServer is not running. Use agent_dom_get_component_source to inspect files directly on disk.`
332
+ }
333
+ ]
334
+ };
335
+ }
336
+ case "agent_dom_understand": {
337
+ const { query, target = "" } = args;
338
+ const graph = buildDependencyGraph();
339
+ if (query === "impact") {
340
+ const impact = graph.analyzeImpact(target);
341
+ return {
342
+ content: [{ type: "text", text: JSON.stringify(impact, null, 2) }]
343
+ };
344
+ }
345
+ if (query === "causality" || query === "why_state") {
346
+ const causality = graph.traceCausality(target);
347
+ if (!causality) {
348
+ return {
349
+ content: [
350
+ {
351
+ type: "text",
352
+ text: `No active causality trace found for '${target}'. Active components: [${Object.keys(graph.components).join(", ")}]`
353
+ }
354
+ ]
355
+ };
356
+ }
357
+ return {
358
+ content: [{ type: "text", text: JSON.stringify(causality, null, 2) }]
359
+ };
360
+ }
361
+ return {
362
+ content: [{ type: "text", text: graph.toYaml() }]
363
+ };
364
+ }
365
+ case "agent_dom_get_component_source": {
366
+ const { componentId, filePath } = args;
367
+ let resolved;
368
+ try {
369
+ resolved = validateWorkspacePath(filePath, projectRoot);
370
+ } catch (err) {
371
+ return { isError: true, content: [{ type: "text", text: err.message }] };
372
+ }
373
+ if (!fs3.existsSync(resolved)) {
374
+ return { isError: true, content: [{ type: "text", text: `File not found: ${resolved}` }] };
375
+ }
376
+ const source = fs3.readFileSync(resolved, "utf-8");
377
+ const version = "sha256:" + crypto2.createHash("sha256").update(source).digest("hex");
378
+ const contract = inspectComponentContract(source, componentId);
379
+ const lines = source.split("\n").map((l, i) => `${String(i + 1).padStart(2, "0")} | ${l}`);
380
+ return {
381
+ content: [
382
+ {
383
+ type: "text",
384
+ text: JSON.stringify(
385
+ {
386
+ componentId,
387
+ filePath: path3.relative(projectRoot, resolved),
388
+ version,
389
+ contract,
390
+ annotatedSource: lines.join("\n")
391
+ },
392
+ null,
393
+ 2
394
+ )
395
+ }
396
+ ]
397
+ };
398
+ }
399
+ case "agent_dom_apply_source_edit": {
400
+ const { filePath, source, expectedVersion } = args;
401
+ let resolved;
402
+ try {
403
+ resolved = validateWorkspacePath(filePath, projectRoot);
404
+ } catch (err) {
405
+ return { isError: true, content: [{ type: "text", text: err.message }] };
406
+ }
407
+ try {
408
+ const result = atomicApplySourceEdit(resolved, source, {
409
+ expectedVersion,
410
+ validateTypeScript: true
411
+ });
412
+ return {
413
+ content: [
414
+ {
415
+ type: "text",
416
+ text: JSON.stringify(
417
+ {
418
+ success: true,
419
+ filePath: path3.relative(projectRoot, result.filePath),
420
+ version: result.version,
421
+ message: result.message
422
+ },
423
+ null,
424
+ 2
425
+ )
426
+ }
427
+ ]
428
+ };
429
+ } catch (err) {
430
+ return {
431
+ isError: true,
432
+ content: [{ type: "text", text: err.message }]
433
+ };
434
+ }
435
+ }
436
+ case "agent_dom_test_action": {
437
+ const { componentId, action, payload } = args;
438
+ try {
439
+ const testResult = await testAction(componentId, action, payload);
440
+ return {
441
+ content: [{ type: "text", text: JSON.stringify(testResult, null, 2) }]
442
+ };
443
+ } catch (err) {
444
+ return {
445
+ isError: true,
446
+ content: [{ type: "text", text: `Action Test Failed: ${err.message}` }]
447
+ };
448
+ }
449
+ }
450
+ case "agent_dom_apply_patch": {
451
+ const { filePath, patch } = args;
452
+ let resolved;
453
+ try {
454
+ resolved = validateWorkspacePath(filePath, projectRoot);
455
+ } catch (err) {
456
+ return { isError: true, content: [{ type: "text", text: err.message }] };
457
+ }
458
+ if (!fs3.existsSync(resolved)) {
459
+ return { isError: true, content: [{ type: "text", text: `File not found: ${resolved}` }] };
460
+ }
461
+ const source = fs3.readFileSync(resolved, "utf-8");
462
+ const patchResult = applyPatch(source, patch);
463
+ if (!patchResult.success) {
464
+ return { isError: true, content: [{ type: "text", text: `Patch Error: ${patchResult.error}` }] };
465
+ }
466
+ const leakCheck = checkSecretLeak(patchResult.code);
467
+ if (leakCheck.hasLeak) {
468
+ return {
469
+ isError: true,
470
+ content: [{ type: "text", text: `Security Guard: Commit blocked. ${leakCheck.reason}` }]
471
+ };
472
+ }
473
+ fs3.writeFileSync(resolved, patchResult.code, "utf-8");
474
+ return {
475
+ content: [
476
+ {
477
+ type: "text",
478
+ text: `Successfully applied patch (${patch.op}) to ${path3.basename(resolved)}.`
479
+ }
480
+ ]
481
+ };
482
+ }
483
+ case "agent_dom_get_errors": {
484
+ return {
485
+ content: [{ type: "text", text: JSON.stringify({ errors: [] }) }]
486
+ };
487
+ }
488
+ default: {
489
+ return { isError: true, content: [{ type: "text", text: `Unknown tool: ${name}` }] };
490
+ }
491
+ }
492
+ });
493
+ return server;
494
+ }
495
+ function inspectComponentContract(sourceCode, componentId) {
496
+ const ast = parser2.parse(sourceCode, {
497
+ sourceType: "module",
498
+ plugins: ["jsx", "typescript"]
499
+ });
500
+ const stateFields = [];
501
+ const actionNames = [];
502
+ const agentIds = [];
503
+ traverse(ast, {
504
+ CallExpression(path4) {
505
+ const callee = path4.node.callee;
506
+ const isDefine = t.isIdentifier(callee) && callee.name === "defineComponent" || t.isMemberExpression(callee) && t.isIdentifier(callee.property) && callee.property.name === "defineComponent";
507
+ if (!isDefine || path4.node.arguments.length === 0) return;
508
+ const configArg = path4.node.arguments[0];
509
+ if (!t.isObjectExpression(configArg)) return;
510
+ const idProp = configArg.properties.find(
511
+ (p) => t.isObjectProperty(p) && t.isIdentifier(p.key) && p.key.name === "id" && t.isStringLiteral(p.value) && p.value.value === componentId
512
+ );
513
+ if (!idProp) return;
514
+ const stateProp = configArg.properties.find(
515
+ (p) => t.isObjectProperty(p) && t.isIdentifier(p.key) && p.key.name === "state"
516
+ );
517
+ if (stateProp && t.isObjectExpression(stateProp.value)) {
518
+ for (const p of stateProp.value.properties) {
519
+ if (t.isObjectProperty(p) && t.isIdentifier(p.key)) {
520
+ stateFields.push(p.key.name);
521
+ }
522
+ }
523
+ }
524
+ const actionsProp = configArg.properties.find(
525
+ (p) => t.isObjectProperty(p) && t.isIdentifier(p.key) && p.key.name === "actions"
526
+ );
527
+ if (actionsProp && t.isObjectExpression(actionsProp.value)) {
528
+ for (const p of actionsProp.value.properties) {
529
+ if (t.isObjectProperty(p) && t.isIdentifier(p.key)) {
530
+ actionNames.push(p.key.name);
531
+ }
532
+ }
533
+ }
534
+ },
535
+ JSXAttribute(path4) {
536
+ if (path4.node.name.name === "data-agent-id" && t.isStringLiteral(path4.node.value)) {
537
+ agentIds.push(path4.node.value.value);
538
+ }
539
+ }
540
+ });
541
+ return {
542
+ componentId,
543
+ stateFields,
544
+ actionNames,
545
+ elementAgentIds: agentIds
546
+ };
547
+ }
548
+ if (typeof process !== "undefined" && process.argv && process.argv[1]?.endsWith("agent-dom-mcp")) {
549
+ const server = createAgentDomMcpServer();
550
+ const transport = new StdioServerTransport();
551
+ server.connect(transport).catch((err) => {
552
+ console.error("Failed to start agent-dom MCP server:", err);
553
+ process.exit(1);
554
+ });
555
+ }
556
+ var MCP_SERVER_VERSION = "0.2.0";
557
+
558
+ export {
559
+ validateWorkspacePath,
560
+ checkSecretLeak,
561
+ validateSourceSyntaxAndTypes,
562
+ atomicApplySourceEdit,
563
+ createAgentDomMcpServer,
564
+ inspectComponentContract,
565
+ MCP_SERVER_VERSION
566
+ };