cvm-server 0.2.7 → 0.3.1

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.
Files changed (2) hide show
  1. package/package.json +5 -5
  2. package/main.js +0 -725
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cvm-server",
3
- "version": "0.2.7",
3
+ "version": "0.3.1",
4
4
  "description": "Cognitive Virtual Machine (CVM) - A deterministic bytecode VM with AI cognitive operations",
5
5
  "keywords": [
6
6
  "mcp",
@@ -39,10 +39,10 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "@modelcontextprotocol/sdk": "^1.12.2",
42
- "dotenv": "^16.0.0",
42
+ "zod": "^3.25.64",
43
43
  "mongodb": "^6.17.0",
44
- "typescript": "^5.7.3",
45
- "zod": "^3.25.64"
44
+ "dotenv": "^16.0.0",
45
+ "typescript": "^5.7.3"
46
46
  },
47
47
  "type": "commonjs",
48
48
  "nx": {
@@ -111,4 +111,4 @@
111
111
  }
112
112
  }
113
113
  }
114
- }
114
+ }
package/main.js DELETED
@@ -1,725 +0,0 @@
1
- "use strict";
2
- const mcp_js = require("@modelcontextprotocol/sdk/server/mcp.js");
3
- const stdio_js = require("@modelcontextprotocol/sdk/server/stdio.js");
4
- const zod = require("zod");
5
- const t = require("typescript");
6
- const fs = require("fs");
7
- const s = require("path");
8
- const mongodb = require("mongodb");
9
- const h = require("os");
10
- const dotenv = require("dotenv");
11
- function _interopNamespaceDefault(e) {
12
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
13
- if (e) {
14
- for (const k in e) {
15
- if (k !== "default") {
16
- const d2 = Object.getOwnPropertyDescriptor(e, k);
17
- Object.defineProperty(n, k, d2.get ? d2 : {
18
- enumerable: true,
19
- get: () => e[k]
20
- });
21
- }
22
- }
23
- }
24
- n.default = e;
25
- return Object.freeze(n);
26
- }
27
- const t__namespace = /* @__PURE__ */ _interopNamespaceDefault(t);
28
- const s__namespace = /* @__PURE__ */ _interopNamespaceDefault(s);
29
- const h__namespace = /* @__PURE__ */ _interopNamespaceDefault(h);
30
- const dotenv__namespace = /* @__PURE__ */ _interopNamespaceDefault(dotenv);
31
- var a = /* @__PURE__ */ ((i2) => (i2.PUSH = "PUSH", i2.POP = "POP", i2.LOAD = "LOAD", i2.STORE = "STORE", i2.CONCAT = "CONCAT", i2.JUMP = "JUMP", i2.JUMP_IF = "JUMP_IF", i2.CALL = "CALL", i2.RETURN = "RETURN", i2.CC = "CC", i2.PRINT = "PRINT", i2.HALT = "HALT", i2))(a || {});
32
- function l$1(i2) {
33
- const p3 = [], r2 = [];
34
- let u2 = false, c2 = false;
35
- const o = t__namespace.createSourceFile(
36
- "program.ts",
37
- i2,
38
- t__namespace.ScriptTarget.Latest,
39
- true
40
- );
41
- function s2(e) {
42
- if (t__namespace.isFunctionDeclaration(e) && e.name && e.name.text === "main" && (u2 = true, e.parameters.length > 0 && p3.push("main() must not have parameters")), t__namespace.isExpressionStatement(e) && e.parent === o) {
43
- const n = e.expression;
44
- t__namespace.isCallExpression(n) && t__namespace.isIdentifier(n.expression) && n.expression.text === "main" && (c2 = true);
45
- }
46
- if (t__namespace.isCallExpression(e) && t__namespace.isIdentifier(e.expression)) {
47
- const n = e.expression.text;
48
- ["setTimeout", "fetch", "require", "import"].includes(n) && p3.push(`Unsupported function: ${n}`);
49
- }
50
- t__namespace.forEachChild(e, s2);
51
- }
52
- return s2(o), u2 || p3.push("Program must have a main() function"), u2 && !c2 && p3.push("main() must be called at the top level"), p3.length === 0 && r2.push({ op: a.HALT }), {
53
- bytecode: r2,
54
- errors: p3,
55
- hasMain: u2
56
- };
57
- }
58
- function m$1(i2) {
59
- const p3 = l$1(i2);
60
- if (p3.errors.length > 0)
61
- return {
62
- success: false,
63
- bytecode: [],
64
- errors: p3.errors
65
- };
66
- const r2 = [], u2 = t__namespace.createSourceFile("program.ts", i2, t__namespace.ScriptTarget.Latest, true);
67
- function c2(s2) {
68
- if (t__namespace.isExpressionStatement(s2)) {
69
- const e = s2.expression;
70
- t__namespace.isCallExpression(e) && t__namespace.isPropertyAccessExpression(e.expression) && e.expression.expression.getText() === "console" && e.expression.name.getText() === "log" ? (e.arguments.forEach((n) => {
71
- o(n);
72
- }), r2.push({ op: a.PRINT })) : t__namespace.isCallExpression(e) && t__namespace.isIdentifier(e.expression) && e.expression.text === "CC" && (e.arguments.length > 0 && o(e.arguments[0]), r2.push({ op: a.CC }), r2.push({ op: a.POP }));
73
- } else if (t__namespace.isVariableStatement(s2)) {
74
- const e = s2.declarationList.declarations[0];
75
- e.initializer && (o(e.initializer), r2.push({ op: a.STORE, arg: e.name.getText() }));
76
- }
77
- }
78
- function o(s2) {
79
- t__namespace.isStringLiteral(s2) ? r2.push({ op: a.PUSH, arg: s2.text }) : t__namespace.isIdentifier(s2) ? r2.push({ op: a.LOAD, arg: s2.text }) : t__namespace.isCallExpression(s2) && t__namespace.isIdentifier(s2.expression) && s2.expression.text === "CC" ? (s2.arguments.length > 0 && o(s2.arguments[0]), r2.push({ op: a.CC })) : t__namespace.isBinaryExpression(s2) && s2.operatorToken.kind === t__namespace.SyntaxKind.PlusToken && (o(s2.left), o(s2.right), r2.push({ op: a.CONCAT }));
80
- }
81
- return u2.forEachChild((s2) => {
82
- var e;
83
- t__namespace.isFunctionDeclaration(s2) && ((e = s2.name) == null ? void 0 : e.text) === "main" && s2.body && s2.body.statements.forEach((n) => {
84
- c2(n);
85
- });
86
- }), r2.push({ op: a.HALT }), {
87
- success: true,
88
- bytecode: r2,
89
- errors: []
90
- };
91
- }
92
- var l = Object.defineProperty;
93
- var d = (i2, t2, e) => t2 in i2 ? l(i2, t2, { enumerable: true, configurable: true, writable: true, value: e }) : i2[t2] = e;
94
- var r = (i2, t2, e) => d(i2, typeof t2 != "symbol" ? t2 + "" : t2, e);
95
- let p$1 = class p {
96
- constructor(t2) {
97
- r(this, "connected", false);
98
- r(this, "programsDir");
99
- r(this, "executionsDir");
100
- this.dataDir = t2, this.programsDir = s__namespace.join(t2, "programs"), this.executionsDir = s__namespace.join(t2, "executions");
101
- }
102
- async connect() {
103
- await fs.promises.mkdir(this.dataDir, { recursive: true }), await fs.promises.mkdir(this.programsDir, { recursive: true }), await fs.promises.mkdir(this.executionsDir, { recursive: true }), this.connected = true;
104
- }
105
- async disconnect() {
106
- this.connected = false;
107
- }
108
- isConnected() {
109
- return this.connected;
110
- }
111
- async saveProgram(t2) {
112
- if (!this.connected) throw new Error("Not connected");
113
- const e = s__namespace.join(this.programsDir, `${t2.id}.json`), o = JSON.stringify(t2, null, 2);
114
- await fs.promises.writeFile(e, o, "utf-8");
115
- }
116
- async getProgram(t2) {
117
- if (!this.connected) throw new Error("Not connected");
118
- const e = s__namespace.join(this.programsDir, `${t2}.json`);
119
- try {
120
- const o = await fs.promises.readFile(e, "utf-8"), n = JSON.parse(o);
121
- return n.created = new Date(n.created), n.updated && (n.updated = new Date(n.updated)), n;
122
- } catch (o) {
123
- if (o.code === "ENOENT")
124
- return null;
125
- throw o;
126
- }
127
- }
128
- async saveExecution(t2) {
129
- if (!this.connected) throw new Error("Not connected");
130
- const e = s__namespace.join(this.executionsDir, `${t2.id}.json`), o = JSON.stringify(t2, null, 2);
131
- await fs.promises.writeFile(e, o, "utf-8");
132
- }
133
- async getExecution(t2) {
134
- if (!this.connected) throw new Error("Not connected");
135
- const e = s__namespace.join(this.executionsDir, `${t2}.json`);
136
- try {
137
- const o = await fs.promises.readFile(e, "utf-8"), n = JSON.parse(o);
138
- return n.created = new Date(n.created), n.updated && (n.updated = new Date(n.updated)), n;
139
- } catch (o) {
140
- if (o.code === "ENOENT")
141
- return null;
142
- throw o;
143
- }
144
- }
145
- };
146
- let w$1 = class w {
147
- constructor(t2) {
148
- r(this, "client");
149
- r(this, "db", null);
150
- r(this, "connected", false);
151
- this.connectionString = t2, this.client = new mongodb.MongoClient(t2);
152
- }
153
- async connect() {
154
- var n;
155
- await this.client.connect();
156
- const t2 = ((n = this.connectionString.split("/").pop()) == null ? void 0 : n.split("?")[0]) || "cvm";
157
- this.db = this.client.db(t2), this.connected = true;
158
- const o = (await this.db.listCollections().toArray()).map((a2) => a2.name);
159
- o.includes("programs") || await this.db.createCollection("programs"), o.includes("executions") || await this.db.createCollection("executions");
160
- }
161
- async disconnect() {
162
- await this.client.close(), this.connected = false, this.db = null;
163
- }
164
- isConnected() {
165
- return this.connected;
166
- }
167
- async getCollections() {
168
- if (!this.db) throw new Error("Not connected to database");
169
- return (await this.db.listCollections().toArray()).map((e) => e.name);
170
- }
171
- getCollection(t2) {
172
- if (!this.db) throw new Error("Not connected to database");
173
- return this.db.collection(t2);
174
- }
175
- async saveProgram(t2) {
176
- await this.getCollection("programs").replaceOne(
177
- { id: t2.id },
178
- t2,
179
- { upsert: true }
180
- );
181
- }
182
- async getProgram(t2) {
183
- return await this.getCollection("programs").findOne({ id: t2 });
184
- }
185
- async saveExecution(t2) {
186
- await this.getCollection("executions").replaceOne(
187
- { id: t2.id },
188
- t2,
189
- { upsert: true }
190
- );
191
- }
192
- async getExecution(t2) {
193
- return await this.getCollection("executions").findOne({ id: t2 });
194
- }
195
- };
196
- class g {
197
- static create(t2) {
198
- const e = (t2 == null ? void 0 : t2.type) || process.env.CVM_STORAGE_TYPE || "file";
199
- switch (e) {
200
- case "file": {
201
- const o = (t2 == null ? void 0 : t2.dataDir) || process.env.CVM_DATA_DIR || s__namespace.join(h__namespace.homedir(), ".cvm");
202
- return new p$1(o);
203
- }
204
- case "mongodb": {
205
- const o = (t2 == null ? void 0 : t2.mongoUri) || process.env.MONGODB_URI || "mongodb://localhost:27017/cvm";
206
- return new w$1(o);
207
- }
208
- default:
209
- throw new Error(`Unsupported storage type: ${e}`);
210
- }
211
- }
212
- }
213
- var m = Object.defineProperty;
214
- var w2 = (p3, r2, t2) => r2 in p3 ? m(p3, r2, { enumerable: true, configurable: true, writable: true, value: t2 }) : p3[r2] = t2;
215
- var u = (p3, r2, t2) => w2(p3, typeof r2 != "symbol" ? r2 + "" : r2, t2);
216
- class i {
217
- execute(r2, t2) {
218
- const e = {
219
- pc: (t2 == null ? void 0 : t2.pc) ?? 0,
220
- stack: (t2 == null ? void 0 : t2.stack) ?? [],
221
- variables: (t2 == null ? void 0 : t2.variables) ?? /* @__PURE__ */ new Map(),
222
- status: "running",
223
- output: (t2 == null ? void 0 : t2.output) ?? [],
224
- ...t2
225
- };
226
- for (; e.status === "running" && e.pc < r2.length; ) {
227
- const s2 = r2[e.pc];
228
- switch (s2.op) {
229
- case a.HALT:
230
- e.status = "complete";
231
- break;
232
- case a.PUSH:
233
- e.stack.push(s2.arg), e.pc++;
234
- break;
235
- case a.POP:
236
- e.stack.pop(), e.pc++;
237
- break;
238
- case a.LOAD:
239
- e.stack.push(e.variables.get(s2.arg) ?? ""), e.pc++;
240
- break;
241
- case a.STORE:
242
- const c2 = e.stack.pop();
243
- e.variables.set(s2.arg, c2), e.pc++;
244
- break;
245
- case a.CONCAT:
246
- const o = e.stack.pop(), a$1 = e.stack.pop();
247
- e.stack.push(a$1 + o), e.pc++;
248
- break;
249
- case a.PRINT:
250
- const g2 = e.stack.pop();
251
- e.output.push(g2), e.pc++;
252
- break;
253
- case a.CC:
254
- e.ccPrompt = e.stack.pop(), e.status = "waiting_cc";
255
- break;
256
- default:
257
- e.status = "error", e.error = `Unknown opcode: ${s2.op}`;
258
- }
259
- }
260
- return e;
261
- }
262
- resume(r2, t2, e) {
263
- if (r2.status !== "waiting_cc")
264
- throw new Error("Cannot resume: VM not waiting for CC");
265
- const s2 = {
266
- ...r2,
267
- stack: [...r2.stack, t2],
268
- status: "running",
269
- ccPrompt: void 0,
270
- pc: r2.pc + 1
271
- };
272
- return this.execute(e, s2);
273
- }
274
- }
275
- class b {
276
- constructor(r2) {
277
- u(this, "vms", /* @__PURE__ */ new Map());
278
- u(this, "storage");
279
- r2 ? this.storage = r2 : this.storage = g.create();
280
- }
281
- /**
282
- * Initialize the VMManager (connect to database)
283
- */
284
- async initialize() {
285
- await this.storage.connect();
286
- }
287
- /**
288
- * Cleanup resources
289
- */
290
- async dispose() {
291
- await this.storage.disconnect(), this.vms.clear();
292
- }
293
- /**
294
- * Load and compile a program from source code
295
- */
296
- async loadProgram(r2, t2) {
297
- const e = m$1(t2);
298
- if (!e.success)
299
- throw new Error(`Compilation failed: ${e.errors.join(", ")}`);
300
- const s2 = {
301
- id: r2,
302
- name: r2,
303
- source: t2,
304
- bytecode: e.bytecode,
305
- // VM decides internal format
306
- created: /* @__PURE__ */ new Date()
307
- };
308
- await this.storage.saveProgram(s2);
309
- }
310
- /**
311
- * Start execution of a loaded program
312
- */
313
- async startExecution(r2, t2) {
314
- if (!await this.storage.getProgram(r2))
315
- throw new Error(`Program not found: ${r2}`);
316
- const s2 = {
317
- id: t2,
318
- programId: r2,
319
- state: "ready",
320
- pc: 0,
321
- stack: [],
322
- variables: {},
323
- output: [],
324
- created: /* @__PURE__ */ new Date()
325
- };
326
- await this.storage.saveExecution(s2);
327
- const c2 = new i();
328
- this.vms.set(t2, c2);
329
- }
330
- /**
331
- * Get next action from execution (Claude polls this)
332
- * This is READ-ONLY - just returns current state
333
- */
334
- async getNext(r2) {
335
- const t2 = await this.storage.getExecution(r2);
336
- if (!t2)
337
- throw new Error(`Execution not found: ${r2}`);
338
- if (t2.state === "ready") {
339
- const e = await this.storage.getProgram(t2.programId);
340
- if (!e)
341
- throw new Error(`Program not found: ${t2.programId}`);
342
- let s2 = this.vms.get(r2);
343
- s2 || (s2 = new i(), this.vms.set(r2, s2));
344
- const c2 = {
345
- pc: 0,
346
- stack: [],
347
- variables: /* @__PURE__ */ new Map(),
348
- output: []
349
- }, o = s2.execute(e.bytecode, c2);
350
- if (t2.pc = o.pc, t2.stack = o.stack, t2.variables = Object.fromEntries(o.variables), t2.output = o.output, o.status === "complete")
351
- return t2.state = "completed", await this.storage.saveExecution(t2), this.vms.delete(r2), {
352
- type: "completed",
353
- message: "Execution completed"
354
- };
355
- if (o.status === "waiting_cc")
356
- return t2.state = "waiting_cc", t2.ccPrompt = o.ccPrompt, await this.storage.saveExecution(t2), {
357
- type: "waiting",
358
- message: o.ccPrompt || "Waiting for input"
359
- };
360
- if (o.status === "error")
361
- return t2.state = "error", t2.error = o.error, await this.storage.saveExecution(t2), this.vms.delete(r2), {
362
- type: "error",
363
- error: o.error
364
- };
365
- }
366
- if (t2.state === "completed")
367
- return {
368
- type: "completed",
369
- message: "Execution completed"
370
- };
371
- if (t2.state === "error")
372
- return {
373
- type: "error",
374
- error: t2.error || "Unknown error"
375
- };
376
- if (t2.state === "waiting_cc")
377
- return {
378
- type: "waiting",
379
- message: t2.ccPrompt || "Waiting for input"
380
- };
381
- throw new Error(`Unexpected execution state: ${t2.state}`);
382
- }
383
- /**
384
- * Report result from cognitive operation and continue execution
385
- */
386
- async reportCCResult(r2, t2) {
387
- const e = await this.storage.getExecution(r2);
388
- if (!e)
389
- throw new Error(`Execution not found: ${r2}`);
390
- const s2 = await this.storage.getProgram(e.programId);
391
- if (!s2)
392
- throw new Error(`Program not found: ${e.programId}`);
393
- let c2 = this.vms.get(r2);
394
- c2 || (c2 = new i(), this.vms.set(r2, c2));
395
- const o = {
396
- pc: e.pc,
397
- stack: e.stack,
398
- variables: new Map(Object.entries(e.variables)),
399
- status: "waiting_cc",
400
- output: e.output,
401
- ccPrompt: void 0
402
- }, a2 = c2.resume(o, t2, s2.bytecode);
403
- e.pc = a2.pc, e.stack = a2.stack, e.variables = Object.fromEntries(a2.variables), e.output = a2.output, a2.status === "complete" ? (e.state = "completed", this.vms.delete(r2)) : a2.status === "error" ? (e.state = "error", e.error = a2.error, this.vms.delete(r2)) : a2.status === "waiting_cc" ? (e.state = "waiting_cc", e.ccPrompt = a2.ccPrompt) : e.state = "running", await this.storage.saveExecution(e);
404
- }
405
- /**
406
- * Get current execution status
407
- */
408
- async getExecutionStatus(r2) {
409
- const t2 = await this.storage.getExecution(r2);
410
- if (!t2)
411
- throw new Error(`Execution not found: ${r2}`);
412
- return {
413
- id: t2.id,
414
- state: t2.state,
415
- pc: t2.pc,
416
- stack: t2.stack,
417
- variables: t2.variables,
418
- output: t2.output
419
- };
420
- }
421
- }
422
- var x = Object.defineProperty;
423
- var p2 = (i2, r2, t2) => r2 in i2 ? x(i2, r2, { enumerable: true, configurable: true, writable: true, value: t2 }) : i2[r2] = t2;
424
- var c = (i2, r2, t2) => p2(i2, typeof r2 != "symbol" ? r2 + "" : r2, t2);
425
- class f {
426
- constructor() {
427
- c(this, "server");
428
- c(this, "transport", null);
429
- c(this, "vmManager");
430
- this.vmManager = new b(), this.server = new mcp_js.McpServer({
431
- name: "cvm-server",
432
- version: "1.0.0"
433
- }), this.setupTools();
434
- }
435
- getName() {
436
- return "cvm-server";
437
- }
438
- getVersion() {
439
- return "1.0.0";
440
- }
441
- setupTools() {
442
- this.server.tool(
443
- "loadProgram",
444
- {
445
- programId: zod.z.string(),
446
- source: zod.z.string()
447
- },
448
- async ({ programId: r2, source: t2 }) => {
449
- try {
450
- return await this.vmManager.loadProgram(r2, t2), {
451
- content: [{ type: "text", text: `Program loaded successfully: ${r2}` }]
452
- };
453
- } catch (o) {
454
- return {
455
- content: [{ type: "text", text: `Error: ${o instanceof Error ? o.message : "Unknown error"}` }],
456
- isError: true
457
- };
458
- }
459
- }
460
- ), this.server.tool(
461
- "startExecution",
462
- {
463
- programId: zod.z.string(),
464
- executionId: zod.z.string()
465
- },
466
- async ({ programId: r2, executionId: t2 }) => {
467
- try {
468
- return await this.vmManager.startExecution(r2, t2), {
469
- content: [{ type: "text", text: `Execution started: ${t2}` }]
470
- };
471
- } catch (o) {
472
- return {
473
- content: [{ type: "text", text: `Error: ${o instanceof Error ? o.message : "Unknown error"}` }],
474
- isError: true
475
- };
476
- }
477
- }
478
- ), this.server.tool(
479
- "getNext",
480
- {
481
- executionId: zod.z.string()
482
- },
483
- async ({ executionId: r2 }) => {
484
- try {
485
- const t2 = await this.vmManager.getNext(r2);
486
- return t2.type === "completed" ? {
487
- content: [{ type: "text", text: "Execution completed" }]
488
- } : t2.type === "waiting" ? {
489
- content: [{ type: "text", text: t2.message || "Waiting for input" }]
490
- } : t2.type === "error" ? {
491
- content: [{ type: "text", text: `Error: ${t2.error}` }],
492
- isError: true
493
- } : {
494
- content: [{ type: "text", text: "Unexpected state" }],
495
- isError: true
496
- };
497
- } catch (t2) {
498
- return {
499
- content: [{ type: "text", text: `Error: ${t2 instanceof Error ? t2.message : "Unknown error"}` }],
500
- isError: true
501
- };
502
- }
503
- }
504
- ), this.server.tool(
505
- "reportCCResult",
506
- {
507
- executionId: zod.z.string(),
508
- result: zod.z.string()
509
- },
510
- async ({ executionId: r2, result: t2 }) => {
511
- try {
512
- return await this.vmManager.reportCCResult(r2, t2), {
513
- content: [{ type: "text", text: "Execution resumed" }]
514
- };
515
- } catch (o) {
516
- return {
517
- content: [{ type: "text", text: `Error: ${o instanceof Error ? o.message : "Unknown error"}` }],
518
- isError: true
519
- };
520
- }
521
- }
522
- ), this.server.tool(
523
- "getExecutionState",
524
- {
525
- executionId: zod.z.string()
526
- },
527
- async ({ executionId: r2 }) => {
528
- try {
529
- const t2 = await this.vmManager.getExecutionStatus(r2);
530
- return {
531
- content: [{ type: "text", text: JSON.stringify(t2, null, 2) }]
532
- };
533
- } catch (t2) {
534
- return {
535
- content: [{ type: "text", text: `Error: ${t2 instanceof Error ? t2.message : "Unknown error"}` }],
536
- isError: true
537
- };
538
- }
539
- }
540
- );
541
- }
542
- async start() {
543
- await this.vmManager.initialize(), this.transport = new stdio_js.StdioServerTransport(), await this.server.connect(this.transport);
544
- }
545
- async stop() {
546
- this.transport && (await this.transport.close(), this.transport = null), await this.vmManager.dispose();
547
- }
548
- // For testing - direct tool invocation
549
- async handleTool(r2, t2) {
550
- const u2 = {
551
- loadProgram: async ({ programId: n, source: e }) => {
552
- try {
553
- return await this.vmManager.loadProgram(n, e), { content: [{ type: "text", text: `Program loaded successfully: ${n}` }] };
554
- } catch (s2) {
555
- return { content: [{ type: "text", text: s2 instanceof Error ? s2.message : "Unknown error" }], isError: true };
556
- }
557
- },
558
- startExecution: async ({ programId: n, executionId: e }) => {
559
- try {
560
- return await this.vmManager.startExecution(n, e), { content: [{ type: "text", text: `Execution started: ${e}` }] };
561
- } catch (s2) {
562
- return { content: [{ type: "text", text: s2 instanceof Error ? s2.message : "Unknown error" }], isError: true };
563
- }
564
- },
565
- getNext: async ({ executionId: n }) => {
566
- try {
567
- const e = await this.vmManager.getNext(n);
568
- return e.type === "completed" ? { content: [{ type: "text", text: "Execution completed" }] } : e.type === "waiting" ? { content: [{ type: "text", text: e.message || "Waiting for input" }] } : { content: [{ type: "text", text: `Error: ${e.error}` }], isError: true };
569
- } catch (e) {
570
- return { content: [{ type: "text", text: e instanceof Error ? e.message : "Unknown error" }], isError: true };
571
- }
572
- },
573
- reportCCResult: async ({ executionId: n, result: e }) => {
574
- try {
575
- return await this.vmManager.reportCCResult(n, e), { content: [{ type: "text", text: "Execution resumed" }] };
576
- } catch (s2) {
577
- return { content: [{ type: "text", text: s2 instanceof Error ? s2.message : "Unknown error" }], isError: true };
578
- }
579
- },
580
- getExecutionState: async ({ executionId: n }) => {
581
- try {
582
- const e = await this.vmManager.getExecutionStatus(n);
583
- return { content: [{ type: "text", text: JSON.stringify(e, null, 2) }] };
584
- } catch (e) {
585
- return { content: [{ type: "text", text: e instanceof Error ? e.message : "Unknown error" }], isError: true };
586
- }
587
- }
588
- }[r2];
589
- if (!u2)
590
- throw new Error(`Tool not found: ${r2}`);
591
- return await u2(t2);
592
- }
593
- }
594
- dotenv__namespace.config({ path: s.resolve(__dirname, "../../../.env") });
595
- function loadConfig() {
596
- const env = process.env.NODE_ENV || "development";
597
- const storageType = process.env.CVM_STORAGE_TYPE || "file";
598
- const mongoUri = process.env.MONGODB_URI;
599
- const dataDir = process.env.CVM_DATA_DIR;
600
- if (storageType === "mongodb" && !mongoUri) {
601
- throw new Error("MONGODB_URI environment variable is required when CVM_STORAGE_TYPE is mongodb");
602
- }
603
- const logLevel = process.env.CVM_LOG_LEVEL || "info";
604
- const validLogLevels = ["debug", "info", "warn", "error"];
605
- if (!validLogLevels.includes(logLevel)) {
606
- throw new Error(`Invalid CVM_LOG_LEVEL: ${logLevel}. Must be one of: ${validLogLevels.join(", ")}`);
607
- }
608
- const maxExecutionTime = parseInt(process.env.CVM_MAX_EXECUTION_TIME || "300000", 10);
609
- const maxStackSize = parseInt(process.env.CVM_MAX_STACK_SIZE || "1000", 10);
610
- const maxOutputSize = parseInt(process.env.CVM_MAX_OUTPUT_SIZE || "1048576", 10);
611
- return {
612
- storage: {
613
- type: storageType,
614
- mongoUri,
615
- dataDir
616
- },
617
- logging: {
618
- level: logLevel
619
- },
620
- execution: {
621
- maxExecutionTime,
622
- maxStackSize,
623
- maxOutputSize
624
- },
625
- env
626
- };
627
- }
628
- const LOG_LEVELS = {
629
- debug: 0,
630
- info: 1,
631
- warn: 2,
632
- error: 3
633
- };
634
- class Logger {
635
- levelValue;
636
- constructor(level) {
637
- this.levelValue = LOG_LEVELS[level];
638
- }
639
- log(level, message, ...args) {
640
- if (LOG_LEVELS[level] >= this.levelValue) {
641
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
642
- const prefix = `[${timestamp}] [${level.toUpperCase()}]`;
643
- if (args.length > 0) {
644
- console.error(prefix, message, ...args);
645
- } else {
646
- console.error(prefix, message);
647
- }
648
- }
649
- }
650
- debug(message, ...args) {
651
- this.log("debug", message, ...args);
652
- }
653
- info(message, ...args) {
654
- this.log("info", message, ...args);
655
- }
656
- warn(message, ...args) {
657
- this.log("warn", message, ...args);
658
- }
659
- error(message, ...args) {
660
- this.log("error", message, ...args);
661
- }
662
- }
663
- let logger;
664
- function initLogger(level) {
665
- logger = new Logger(level);
666
- return logger;
667
- }
668
- function getLogger() {
669
- if (!logger) {
670
- throw new Error("Logger not initialized. Call initLogger() first.");
671
- }
672
- return logger;
673
- }
674
- async function main() {
675
- let cvmServer;
676
- try {
677
- const config = loadConfig();
678
- initLogger(config.logging.level);
679
- const logger2 = getLogger();
680
- logger2.info("Starting CVM Server...", {
681
- env: config.env,
682
- logLevel: config.logging.level
683
- });
684
- if (config.storage.type === "file") {
685
- const dataDir = config.storage.dataDir || ".cvm";
686
- const fullPath = s.resolve(process.cwd(), dataDir);
687
- logger2.info(`[CVM] Initializing file storage in: ${fullPath}`);
688
- logger2.warn(`[CVM] ⚠️ Remember to add '${dataDir}/' to your .gitignore file!`);
689
- } else {
690
- logger2.info("[CVM] Using MongoDB storage");
691
- }
692
- cvmServer = new f();
693
- await cvmServer.start();
694
- logger2.info("CVM Server is running and ready to accept MCP connections");
695
- process.on("SIGINT", async () => {
696
- logger2.info("Received SIGINT, shutting down gracefully...");
697
- await shutdown();
698
- });
699
- process.on("SIGTERM", async () => {
700
- logger2.info("Received SIGTERM, shutting down gracefully...");
701
- await shutdown();
702
- });
703
- } catch (error) {
704
- console.error("Fatal error starting CVM Server:", error);
705
- process.exit(1);
706
- }
707
- async function shutdown() {
708
- const logger2 = getLogger();
709
- try {
710
- logger2.info("Closing connections...");
711
- if (cvmServer) {
712
- await cvmServer.stop();
713
- }
714
- logger2.info("Shutdown complete");
715
- process.exit(0);
716
- } catch (error) {
717
- logger2.error("Error during shutdown:", error);
718
- process.exit(1);
719
- }
720
- }
721
- }
722
- main().catch((error) => {
723
- console.error("Unhandled error:", error);
724
- process.exit(1);
725
- });