progmune-runtime 2.0.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.
@@ -0,0 +1,119 @@
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
+ const extract_ir_python_1 = require("./extract-ir-python");
37
+ const planner_1 = require("./planner");
38
+ const search_planner_1 = require("./search-planner");
39
+ const validator_1 = require("./validator");
40
+ const python_emitter_1 = require("./python-emitter");
41
+ const feedback_1 = require("./feedback");
42
+ const llm_1 = require("./llm");
43
+ const fs = __importStar(require("fs"));
44
+ const path = __importStar(require("path"));
45
+ const child_process_1 = require("child_process");
46
+ async function main() {
47
+ const results = [];
48
+ const intents = [
49
+ "实现 login 函数,验证密码,成功则生成JWT,否则返回错误信息",
50
+ "实现批量处理支付 transactions,对每笔交易校验卡片并记录日志",
51
+ "实现数据报表函数,分页获取活跃用户,按类别分组并排序"
52
+ ];
53
+ const planners = ["llm", "search"];
54
+ const lang = "python";
55
+ const projectPath = "./test-xlarge";
56
+ const fns = (0, extract_ir_python_1.extractIRPython)(projectPath);
57
+ fs.writeFileSync("ir.json", JSON.stringify(fns, null, 2));
58
+ console.log(`✅ 项目规模: ${fns.length} 函数\n`);
59
+ for (const intent of intents) {
60
+ for (const planner of planners) {
61
+ const start = Date.now();
62
+ let actions = [];
63
+ try {
64
+ if (planner === "llm") {
65
+ actions = await (0, planner_1.plan)(intent);
66
+ }
67
+ else {
68
+ actions = await (0, search_planner_1.searchPlan)(intent, 2, 4);
69
+ }
70
+ }
71
+ catch (e) {
72
+ results.push({ intent, planner, duration_ms: Date.now() - start, llm_calls: llm_1.callCount, success: false, error: String(e) });
73
+ continue;
74
+ }
75
+ const duration = Date.now() - start;
76
+ const validationResults = actions.map((a) => (0, validator_1.validateAction)(a));
77
+ const valid = validationResults.every((r) => r.valid);
78
+ if (!valid || actions.length === 0) {
79
+ results.push({ intent, planner, duration_ms: duration, llm_calls: llm_1.callCount, success: false, error: "校验失败" });
80
+ continue;
81
+ }
82
+ const code = (0, python_emitter_1.emitPython)(actions);
83
+ const tmpFile = path.join(path.resolve(projectPath), "__test.py");
84
+ fs.writeFileSync(tmpFile, code);
85
+ let success = false;
86
+ let error;
87
+ try {
88
+ (0, child_process_1.execSync)(`python3 ${tmpFile}`, { timeout: 5000, encoding: "utf-8", cwd: path.resolve(projectPath) });
89
+ success = true;
90
+ }
91
+ catch (e) {
92
+ error = e.stderr?.toString() || e.toString();
93
+ }
94
+ finally {
95
+ if (fs.existsSync(tmpFile))
96
+ fs.unlinkSync(tmpFile);
97
+ }
98
+ (0, feedback_1.recordRun)(intent, actions, success, error);
99
+ results.push({ intent, planner, duration_ms: duration, llm_calls: llm_1.callCount, success, error });
100
+ console.log(`${planner} | ${intent.substring(0, 20)}... | ${duration}ms | 调用:${llm_1.callCount} | ${success ? '✅' : '❌'}`);
101
+ }
102
+ }
103
+ console.log("\n📊 200函数压力测试报告:");
104
+ console.table(results.map(r => ({
105
+ Intent: r.intent.substring(0, 30),
106
+ Planner: r.planner,
107
+ Time: r.duration_ms + 'ms',
108
+ LLM: r.llm_calls,
109
+ Success: r.success ? '✅' : '❌'
110
+ })));
111
+ fs.writeFileSync("stress_200_test.json", JSON.stringify(results, null, 2));
112
+ console.log("报告已保存到 stress_200_test.json");
113
+ // 计算统计指标
114
+ const totalLLM = results.reduce((s, r) => s + r.llm_calls, 0);
115
+ const avgTime = results.reduce((s, r) => s + r.duration_ms, 0) / results.length;
116
+ const successRate = results.filter(r => r.success).length / results.length * 100;
117
+ console.log(`\n📈 汇总: 总LLM调用=${totalLLM}, 平均耗时=${avgTime.toFixed(0)}ms, 成功率=${successRate.toFixed(0)}%`);
118
+ }
119
+ main().catch(console.error);
@@ -0,0 +1,112 @@
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
+ const extract_ir_python_1 = require("./extract-ir-python");
37
+ const planner_1 = require("./planner");
38
+ const search_planner_1 = require("./search-planner");
39
+ const validator_1 = require("./validator");
40
+ const python_emitter_1 = require("./python-emitter");
41
+ const feedback_1 = require("./feedback");
42
+ const llm_1 = require("./llm");
43
+ const fs = __importStar(require("fs"));
44
+ const path = __importStar(require("path"));
45
+ const child_process_1 = require("child_process");
46
+ async function main() {
47
+ const results = [];
48
+ const intents = [
49
+ "实现 login 函数,验证密码,成功则生成JWT,否则返回错误信息",
50
+ "实现批量处理支付 transactions,对每笔交易校验卡片并记录日志",
51
+ "实现数据报表函数,分页获取活跃用户,按类别分组并排序"
52
+ ];
53
+ const planners = ["llm", "search"];
54
+ const projectPath = "./test-500";
55
+ const fns = (0, extract_ir_python_1.extractIRPython)(projectPath);
56
+ fs.writeFileSync("ir.json", JSON.stringify(fns, null, 2));
57
+ console.log(`✅ 项目规模: ${fns.length} 函数\n`);
58
+ for (const intent of intents) {
59
+ for (const planner of planners) {
60
+ const start = Date.now();
61
+ let actions = [];
62
+ try {
63
+ if (planner === "llm")
64
+ actions = await (0, planner_1.plan)(intent);
65
+ else
66
+ actions = await (0, search_planner_1.searchPlan)(intent, 2, 4);
67
+ }
68
+ catch (e) {
69
+ results.push({ intent, planner, duration_ms: Date.now() - start, llm_calls: llm_1.callCount, success: false, error: String(e) });
70
+ continue;
71
+ }
72
+ const duration = Date.now() - start;
73
+ const valid = actions.length > 0 && actions.map((a) => (0, validator_1.validateAction)(a)).every((r) => r.valid);
74
+ if (!valid) {
75
+ results.push({ intent, planner, duration_ms: duration, llm_calls: llm_1.callCount, success: false, error: "校验失败或无动作" });
76
+ continue;
77
+ }
78
+ const code = (0, python_emitter_1.emitPython)(actions);
79
+ const tmpFile = path.join(path.resolve(projectPath), "__test.py");
80
+ fs.writeFileSync(tmpFile, code);
81
+ let success = false, error;
82
+ try {
83
+ (0, child_process_1.execSync)(`python3 ${tmpFile}`, { timeout: 5000, encoding: "utf-8", cwd: path.resolve(projectPath) });
84
+ success = true;
85
+ }
86
+ catch (e) {
87
+ error = e.stderr?.toString() || e.toString();
88
+ }
89
+ finally {
90
+ if (fs.existsSync(tmpFile))
91
+ fs.unlinkSync(tmpFile);
92
+ }
93
+ (0, feedback_1.recordRun)(intent, actions, success, error);
94
+ results.push({ intent, planner, duration_ms: duration, llm_calls: llm_1.callCount, success, error });
95
+ console.log(`${planner} | ${intent.substring(0, 20)}... | ${duration}ms | 调用:${llm_1.callCount} | ${success ? '✅' : '❌'}`);
96
+ }
97
+ }
98
+ console.log("\n📊 500函数压力测试报告:");
99
+ console.table(results.map(r => ({
100
+ Intent: r.intent.substring(0, 30),
101
+ Planner: r.planner,
102
+ Time: r.duration_ms + 'ms',
103
+ LLM: r.llm_calls,
104
+ Success: r.success ? '✅' : '❌'
105
+ })));
106
+ fs.writeFileSync("stress_500_report.json", JSON.stringify(results, null, 2));
107
+ const totalCalls = results.reduce((s, r) => s + r.llm_calls, 0);
108
+ const avgTime = results.reduce((s, r) => s + r.duration_ms, 0) / results.length;
109
+ const successRate = results.filter(r => r.success).length / results.length * 100;
110
+ console.log(`\n📈 汇总: LLM总调用=${totalCalls}, 平均耗时=${avgTime.toFixed(0)}ms, 成功率=${successRate.toFixed(0)}%`);
111
+ }
112
+ main().catch(console.error);
package/dist/llm.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.callCount = void 0;
7
+ exports.resetCallCount = resetCallCount;
8
+ exports.generate = generate;
9
+ const openai_1 = __importDefault(require("openai"));
10
+ const apiKey = process.env.LLM_API_KEY || "sk-xxxx";
11
+ const baseURL = process.env.LLM_BASE_URL || "https://api.deepseek.com/v1";
12
+ const model = process.env.LLM_MODEL || "deepseek-chat";
13
+ const client = new openai_1.default({ apiKey, baseURL });
14
+ exports.callCount = 0;
15
+ function resetCallCount() { exports.callCount = 0; }
16
+ async function generate(prompt) {
17
+ exports.callCount++;
18
+ const resp = await client.chat.completions.create({
19
+ model,
20
+ messages: [{ role: "user", content: prompt }],
21
+ temperature: 0.0,
22
+ });
23
+ return resp.choices[0]?.message?.content || "";
24
+ }
package/dist/main.js ADDED
@@ -0,0 +1,142 @@
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
+ const extract_ir_1 = require("./extract-ir");
37
+ const planner_1 = require("./planner");
38
+ const validator_1 = require("./validator");
39
+ const emitter_1 = require("./emitter");
40
+ const runtime_1 = require("./runtime");
41
+ const fs = __importStar(require("fs"));
42
+ async function runTest(name, actions) {
43
+ console.log(`\n🧪 测试: ${name}`);
44
+ // 校验
45
+ const results = actions.map((a) => (0, validator_1.validateAction)(a));
46
+ const valid = results.every((r) => r.valid);
47
+ if (!valid) {
48
+ console.log(" ❌ 校验器拦截:");
49
+ results.forEach((r, i) => { if (!r.valid)
50
+ console.log(` 动作${i}: ${r.errors}`); });
51
+ return;
52
+ }
53
+ // 发射代码
54
+ const code = (0, emitter_1.emitCode)(actions);
55
+ console.log(" 生成的代码:\n" + code.split("\n").map(l => " " + l).join("\n"));
56
+ // 编译运行
57
+ const execResult = (0, runtime_1.runAndCheck)(code);
58
+ if (!execResult.success) {
59
+ console.log(" ❌ 编译/运行失败 (类型系统生效)");
60
+ console.log(" 错误摘要:", execResult.error?.split("\n")[0]);
61
+ }
62
+ else {
63
+ console.log(" ✅ 运行通过 (需人工复核是否真正安全)");
64
+ }
65
+ }
66
+ async function main() {
67
+ console.log("═══════════════════════════════════════");
68
+ console.log(" BrainyCode v2.0 – 扩展语义拦截测试");
69
+ console.log("═══════════════════════════════════════");
70
+ // 1. 提取 IR
71
+ console.log("\n📊 提取 IR...");
72
+ const fns = (0, extract_ir_1.extractIR)("./test-login");
73
+ fs.writeFileSync("ir.json", JSON.stringify(fns, null, 2));
74
+ console.log(`✅ 函数数量: ${fns.length}`);
75
+ // 2. 获取正常动作序列
76
+ const intent = "实现登录接口,验证密码后返回 JWT,并记录日志";
77
+ console.log("\n🧠 正常规划...");
78
+ const normalActions = await (0, planner_1.plan)(intent);
79
+ console.log("🎯 正常动作:");
80
+ console.log(JSON.stringify(normalActions, null, 2));
81
+ // 3. 正常流程
82
+ await runTest("正常流程", normalActions);
83
+ // 4. 错误注入测试集
84
+ const maliciousTests = [
85
+ {
86
+ name: "篡改参数类型 (PasswordHash -> Token)",
87
+ modify: (actions) => {
88
+ const copy = JSON.parse(JSON.stringify(actions));
89
+ for (const a of copy) {
90
+ if (a.kind === "call" && a.function === "verifyPassword") {
91
+ const hashArg = a.args.find((x) => x.name === "hash");
92
+ if (hashArg)
93
+ hashArg.type = "Token";
94
+ }
95
+ }
96
+ return copy;
97
+ }
98
+ },
99
+ {
100
+ name: "调用不存在的函数",
101
+ modify: (actions) => {
102
+ const copy = JSON.parse(JSON.stringify(actions));
103
+ copy.push({ kind: "call", function: "hackSystem", args: [] });
104
+ return copy;
105
+ }
106
+ },
107
+ {
108
+ name: "参数数量错误 (verifyPassword 只给一个参数)",
109
+ modify: (actions) => {
110
+ const copy = JSON.parse(JSON.stringify(actions));
111
+ for (const a of copy) {
112
+ if (a.kind === "call" && a.function === "verifyPassword") {
113
+ a.args = [a.args[0]]; // 只保留第一个参数
114
+ }
115
+ }
116
+ return copy;
117
+ }
118
+ },
119
+ {
120
+ name: "将 string 参数类型改为 number",
121
+ modify: (actions) => {
122
+ const copy = JSON.parse(JSON.stringify(actions));
123
+ for (const a of copy) {
124
+ if (a.kind === "call" && a.function === "verifyPassword") {
125
+ const plainArg = a.args.find((x) => x.name === "plain");
126
+ if (plainArg)
127
+ plainArg.type = "number";
128
+ }
129
+ }
130
+ return copy;
131
+ }
132
+ }
133
+ ];
134
+ for (const test of maliciousTests) {
135
+ const maliciousActions = test.modify(normalActions);
136
+ await runTest(test.name, maliciousActions);
137
+ }
138
+ console.log("\n═══════════════════════════════════════");
139
+ console.log(" ✅ 扩展测试完成");
140
+ console.log("═══════════════════════════════════════");
141
+ }
142
+ main().catch(console.error);
@@ -0,0 +1,55 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
+ import { createRequire } from 'module';
5
+
6
+ const require = createRequire(import.meta.url);
7
+ const fs = require('fs');
8
+
9
+ const { plan } = require('./planner.js');
10
+ const { extractIRPython } = require('./extract-ir-python.js');
11
+ const { emitPython } = require('./python-emitter.js');
12
+ const { recordRun } = require('./feedback.js');
13
+
14
+ async function main() {
15
+ const server = new Server({
16
+ name: "progmune",
17
+ version: "2.0.0"
18
+ }, { capabilities: { tools: {} } });
19
+
20
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
21
+ tools: [{
22
+ name: "generate_verified_code",
23
+ description: "生成类型安全的Python代码,仅使用项目中真实存在的函数。",
24
+ inputSchema: {
25
+ type: "object",
26
+ properties: {
27
+ intent: { type: "string", description: "编程意图" },
28
+ projectPath: { type: "string", description: "项目根目录绝对路径" }
29
+ },
30
+ required: ["intent", "projectPath"]
31
+ }
32
+ }]
33
+ }));
34
+
35
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
36
+ if (request.params.name === "generate_verified_code") {
37
+ const { intent, projectPath } = request.params.arguments;
38
+ const fns = extractIRPython(projectPath);
39
+ fs.writeFileSync("ir.json", JSON.stringify(fns, null, 2));
40
+ const actions = await plan(intent);
41
+ if (!actions || actions.length === 0) {
42
+ return { content: [{ type: "text", text: "无法生成满足约束的代码。" }] };
43
+ }
44
+ const code = emitPython(actions);
45
+ recordRun(intent, actions, true);
46
+ return { content: [{ type: "text", text: code }] };
47
+ }
48
+ throw new Error("未知工具");
49
+ });
50
+
51
+ const transport = new StdioServerTransport();
52
+ await server.connect(transport);
53
+ }
54
+
55
+ main().catch(console.error);
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
+ import { createRequire } from 'module';
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const fs = require('fs');
9
+
10
+ // 加载编译后的 CommonJS 模块
11
+ const { plan } = require('./planner.js');
12
+ const { validateActionSequence } = require('./validator.js');
13
+ const { extractIRPython } = require('./extract-ir-python.js');
14
+ const { emitPython } = require('./python-emitter.js');
15
+ const { recordRun } = require('./feedback.js');
16
+
17
+ async function main() {
18
+ const server = new Server({
19
+ name: "progmune",
20
+ version: "2.0.0"
21
+ }, { capabilities: { tools: {} } });
22
+
23
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
24
+ tools: [{
25
+ name: "generate_verified_code",
26
+ description: "生成类型安全的Python代码,仅使用项目中真实存在的函数。",
27
+ inputSchema: {
28
+ type: "object",
29
+ properties: {
30
+ intent: { type: "string", description: "编程意图" },
31
+ projectPath: { type: "string", description: "项目根目录绝对路径" }
32
+ },
33
+ required: ["intent", "projectPath"]
34
+ }
35
+ }]
36
+ }));
37
+
38
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
39
+ if (request.params.name === "generate_verified_code") {
40
+ const { intent, projectPath } = request.params.arguments;
41
+
42
+ // 1. 提取 IR
43
+ const fns = extractIRPython(projectPath);
44
+ fs.writeFileSync("ir.json", JSON.stringify(fns, null, 2));
45
+
46
+ // 2. 规划动作
47
+ let actions;
48
+ try {
49
+ actions = await plan(intent);
50
+ } catch (e) {
51
+ return { content: [{ type: "text", text: `规划失败: ${e.message}` }] };
52
+ }
53
+
54
+ if (!actions || actions.length === 0) {
55
+ return { content: [{ type: "text", text: "Planner 返回空序列,可能是 LLM 输出异常或项目函数不足。" }] };
56
+ }
57
+
58
+ // 3. 校验动作序列
59
+ const seqResult = validateActionSequence(actions);
60
+ if (!seqResult.valid) {
61
+ return { content: [{ type: "text", text: `校验失败: ${seqResult.errors.join("; ")}` }] };
62
+ }
63
+
64
+ // 4. 发射代码
65
+ const code = emitPython(actions);
66
+ recordRun(intent, actions, true);
67
+ return { content: [{ type: "text", text: code }] };
68
+ }
69
+ throw new Error("未知工具");
70
+ });
71
+
72
+ const transport = new StdioServerTransport();
73
+ await server.connect(transport);
74
+ }
75
+
76
+ main().catch(console.error);
@@ -0,0 +1,150 @@
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.WorkMemory = void 0;
37
+ exports.recordEpisode = recordEpisode;
38
+ exports.getRecentEpisodes = getRecentEpisodes;
39
+ exports.getSuccessfulEpisodes = getSuccessfulEpisodes;
40
+ exports.consolidateSemantic = consolidateSemantic;
41
+ exports.findSemanticTemplate = findSemanticTemplate;
42
+ const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
44
+ const MEMORY_DIR = path.resolve(__dirname, "../.progmune_memory");
45
+ class WorkMemory {
46
+ constructor() {
47
+ this.bindings = new Map();
48
+ this.intent = "";
49
+ }
50
+ setIntent(intent) { this.intent = intent; }
51
+ getIntent() { return this.intent; }
52
+ bind(name, type) { this.bindings.set(name, type); }
53
+ get(name) { return this.bindings.get(name); }
54
+ clear() { this.bindings.clear(); this.intent = ""; }
55
+ }
56
+ exports.WorkMemory = WorkMemory;
57
+ const EPISODIC_FILE = path.join(MEMORY_DIR, "episodic.json");
58
+ const MAX_EPISODES = 50;
59
+ function ensureDir(dir) {
60
+ if (!fs.existsSync(dir))
61
+ fs.mkdirSync(dir, { recursive: true });
62
+ }
63
+ function loadEpisodes() {
64
+ ensureDir(MEMORY_DIR);
65
+ if (!fs.existsSync(EPISODIC_FILE))
66
+ return [];
67
+ return JSON.parse(fs.readFileSync(EPISODIC_FILE, "utf-8"));
68
+ }
69
+ function saveEpisodes(episodes) {
70
+ ensureDir(MEMORY_DIR);
71
+ fs.writeFileSync(EPISODIC_FILE, JSON.stringify(episodes.slice(0, MAX_EPISODES), null, 2));
72
+ }
73
+ function recordEpisode(episode) {
74
+ const episodes = loadEpisodes();
75
+ const newEpisode = {
76
+ ...episode,
77
+ id: `ep_${Date.now()}`,
78
+ timestamp: new Date().toISOString(),
79
+ };
80
+ episodes.unshift(newEpisode);
81
+ if (episodes.length > MAX_EPISODES)
82
+ episodes.length = MAX_EPISODES;
83
+ saveEpisodes(episodes);
84
+ }
85
+ function getRecentEpisodes(limit = 10) {
86
+ return loadEpisodes().slice(0, limit);
87
+ }
88
+ function getSuccessfulEpisodes(limit = 10) {
89
+ return loadEpisodes().filter(e => e.success).slice(0, limit);
90
+ }
91
+ const SEMANTIC_FILE = path.join(MEMORY_DIR, "semantic.json");
92
+ function loadSemantic() {
93
+ ensureDir(MEMORY_DIR);
94
+ if (!fs.existsSync(SEMANTIC_FILE))
95
+ return [];
96
+ return JSON.parse(fs.readFileSync(SEMANTIC_FILE, "utf-8"));
97
+ }
98
+ function saveSemantic(templates) {
99
+ ensureDir(MEMORY_DIR);
100
+ fs.writeFileSync(SEMANTIC_FILE, JSON.stringify(templates, null, 2));
101
+ }
102
+ function consolidateSemantic(minOccurrences = 3) {
103
+ const episodes = getSuccessfulEpisodes(MAX_EPISODES);
104
+ const grouped = new Map();
105
+ for (const ep of episodes) {
106
+ const pattern = ep.intent.substring(0, 20);
107
+ if (!grouped.has(pattern))
108
+ grouped.set(pattern, []);
109
+ grouped.get(pattern).push(ep);
110
+ }
111
+ const templates = loadSemantic();
112
+ for (const [pattern, eps] of grouped) {
113
+ if (eps.length >= minOccurrences) {
114
+ const existing = templates.find(t => t.intentPattern === pattern);
115
+ if (existing) {
116
+ existing.successRate = (existing.successRate * existing.useCount + eps.length) / (existing.useCount + eps.length);
117
+ existing.useCount += eps.length;
118
+ existing.lastUsedAt = new Date().toISOString();
119
+ existing.actionSequence = eps[0].actions;
120
+ }
121
+ else {
122
+ templates.push({
123
+ id: `tmpl_${Date.now()}`,
124
+ intentPattern: pattern,
125
+ actionSequence: eps[0].actions,
126
+ successRate: 1.0,
127
+ useCount: eps.length,
128
+ createdAt: new Date().toISOString(),
129
+ lastUsedAt: new Date().toISOString(),
130
+ });
131
+ }
132
+ }
133
+ }
134
+ saveSemantic(templates);
135
+ console.log(`[语义记忆] 巩固完成,模板数量: ${templates.length}`);
136
+ }
137
+ function findSemanticTemplate(intent) {
138
+ const templates = loadSemantic();
139
+ if (templates.length === 0)
140
+ return undefined;
141
+ const prefix = intent.substring(0, 20).toLowerCase();
142
+ const exactMatch = templates.find(t => t.intentPattern.toLowerCase() === prefix);
143
+ if (exactMatch && exactMatch.successRate >= 0.7)
144
+ return exactMatch;
145
+ const fuzzyMatch = templates.find(t => {
146
+ const pattern = t.intentPattern.toLowerCase();
147
+ return (prefix.includes(pattern) || pattern.includes(prefix)) && t.successRate >= 0.8;
148
+ });
149
+ return fuzzyMatch;
150
+ }