lemma-agent 0.0.0-stage → 1.0.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.
- package/README.md +140 -2
- package/bin/lemma.mjs +60 -0
- package/dist/acceptance.js +63 -0
- package/dist/admin.js +1482 -0
- package/dist/agents.js +245 -0
- package/dist/api-member.js +537 -0
- package/dist/app.js +161 -0
- package/dist/board.js +185 -0
- package/dist/business-tools.js +153 -0
- package/dist/change-ops.js +91 -0
- package/dist/changes.js +46 -0
- package/dist/cli-runner.js +106 -0
- package/dist/code-tools.js +396 -0
- package/dist/coding-benchmark-fixtures.js +1049 -0
- package/dist/coding-benchmark-suite.js +1252 -0
- package/dist/collaboration-benchmark.js +349 -0
- package/dist/config.js +392 -0
- package/dist/context-benchmark.js +91 -0
- package/dist/conventions.js +282 -0
- package/dist/conversation.js +39 -0
- package/dist/credentials.js +44 -0
- package/dist/deliverables.js +43 -0
- package/dist/digest.js +129 -0
- package/dist/dispatch.js +801 -0
- package/dist/execution-settings.js +24 -0
- package/dist/git-workbench.js +800 -0
- package/dist/git.js +149 -0
- package/dist/integration-git.js +108 -0
- package/dist/integrations.js +557 -0
- package/dist/jobs.js +100 -0
- package/dist/lead.js +263 -0
- package/dist/learning.js +36 -0
- package/dist/main.js +1459 -0
- package/dist/mcp-settings.js +45 -0
- package/dist/mcp-tools.js +102 -0
- package/dist/member-settings.js +245 -0
- package/dist/model-selection.js +48 -0
- package/dist/models.js +145 -0
- package/dist/native-selectors.js +45 -0
- package/dist/native-terminal-components.js +100 -0
- package/dist/ood-benchmark.js +660 -0
- package/dist/operations.js +21 -0
- package/dist/printer.js +113 -0
- package/dist/projects.js +282 -0
- package/dist/repair.js +102 -0
- package/dist/resources.js +31 -0
- package/dist/result-summary.js +8 -0
- package/dist/results.js +41 -0
- package/dist/scope.js +114 -0
- package/dist/sessions.js +95 -0
- package/dist/settings.js +32 -0
- package/dist/task-commands.js +37 -0
- package/dist/task-lifecycle.js +49 -0
- package/dist/task-readiness.js +22 -0
- package/dist/task-recovery.js +116 -0
- package/dist/task-review.js +70 -0
- package/dist/task-workflow.js +424 -0
- package/dist/terminal-layout.js +27 -0
- package/dist/terminal-state.js +145 -0
- package/dist/terminal.js +800 -0
- package/dist/tool-settings.js +111 -0
- package/dist/tools.js +1043 -0
- package/dist/ux-telemetry.js +127 -0
- package/dist/view.js +114 -0
- package/package.json +80 -6
- package/web/index.html +136 -0
- package/web/js/conversations.js +312 -0
- package/web/js/dag.js +495 -0
- package/web/js/drawer.js +139 -0
- package/web/js/editors.js +424 -0
- package/web/js/gitlens.js +844 -0
- package/web/js/main.js +152 -0
- package/web/js/sankey.js +476 -0
- package/web/js/store.js +291 -0
- package/web/js/ticket.js +151 -0
- package/web/js/timeline.js +183 -0
- package/web/js/topology.js +454 -0
- package/web/js/util.js +232 -0
- package/web/js/views.js +1496 -0
- package/web/style.css +5299 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// 启动本机 AI CLI 子进程:提示词走 stdin(避免 Windows 命令行转义问题),
|
|
2
|
+
// 支持超时、中止(杀整个进程树)和逐行输出回调。
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
/** Windows 上 kill() 只杀外层进程,需要 taskkill /T 杀掉整棵进程树 */
|
|
5
|
+
function killTree(pid) {
|
|
6
|
+
if (pid === undefined)
|
|
7
|
+
return;
|
|
8
|
+
if (process.platform === "win32") {
|
|
9
|
+
spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
try {
|
|
13
|
+
process.kill(-pid, "SIGKILL");
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
try {
|
|
17
|
+
process.kill(pid, "SIGKILL");
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
/* 已退出 */
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export function runCli(options) {
|
|
26
|
+
const started = Date.now();
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
if (options.signal?.aborted) {
|
|
29
|
+
resolve({ exitCode: null, stdout: "", stderr: "", timedOut: false, aborted: true, durationMs: 0 });
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const child = spawn(options.command, options.args, {
|
|
33
|
+
cwd: options.cwd,
|
|
34
|
+
env: options.env ?? process.env,
|
|
35
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
36
|
+
windowsHide: true,
|
|
37
|
+
detached: process.platform !== "win32", // 非 Windows 下建进程组,方便整组杀掉
|
|
38
|
+
});
|
|
39
|
+
let stdout = "";
|
|
40
|
+
let stderr = "";
|
|
41
|
+
let timedOut = false;
|
|
42
|
+
let aborted = false;
|
|
43
|
+
const partial = { stdout: "", stderr: "" };
|
|
44
|
+
const feed = (stream, chunk) => {
|
|
45
|
+
const text = chunk.toString("utf8");
|
|
46
|
+
if (stream === "stdout")
|
|
47
|
+
stdout += text;
|
|
48
|
+
else
|
|
49
|
+
stderr += text;
|
|
50
|
+
if (!options.onLine)
|
|
51
|
+
return;
|
|
52
|
+
const lines = (partial[stream] + text).split(/\r?\n/);
|
|
53
|
+
partial[stream] = lines.pop() ?? "";
|
|
54
|
+
for (const line of lines)
|
|
55
|
+
if (line.length > 0)
|
|
56
|
+
options.onLine(line, stream);
|
|
57
|
+
};
|
|
58
|
+
child.stdout.on("data", (c) => feed("stdout", c));
|
|
59
|
+
child.stderr.on("data", (c) => feed("stderr", c));
|
|
60
|
+
const timer = options.timeoutMs !== undefined && options.timeoutMs > 0
|
|
61
|
+
? setTimeout(() => {
|
|
62
|
+
timedOut = true;
|
|
63
|
+
killTree(child.pid);
|
|
64
|
+
}, options.timeoutMs)
|
|
65
|
+
: undefined;
|
|
66
|
+
const onAbort = () => {
|
|
67
|
+
aborted = true;
|
|
68
|
+
killTree(child.pid);
|
|
69
|
+
};
|
|
70
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
71
|
+
child.on("error", (error) => {
|
|
72
|
+
if (timer)
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
75
|
+
reject(error);
|
|
76
|
+
});
|
|
77
|
+
child.on("close", (code) => {
|
|
78
|
+
if (timer)
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
81
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
82
|
+
if (partial[stream].length > 0)
|
|
83
|
+
options.onLine?.(partial[stream], stream);
|
|
84
|
+
}
|
|
85
|
+
resolve({ exitCode: code, stdout, stderr, timedOut, aborted, durationMs: Date.now() - started });
|
|
86
|
+
});
|
|
87
|
+
child.stdin.on("error", () => {
|
|
88
|
+
/* 子进程可能不读 stdin 就退出了 */
|
|
89
|
+
});
|
|
90
|
+
child.stdin.end(options.stdin ?? "");
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 给子 CLI 用的环境变量:去掉当前宿主(例如 Claude 桌面会话)注入的变量,
|
|
95
|
+
* 让 claude / codex / gemini 使用它们自己的登录和配置。
|
|
96
|
+
*/
|
|
97
|
+
export function cleanEnv(stripPatterns, extra) {
|
|
98
|
+
const regexes = stripPatterns.map((p) => new RegExp(p));
|
|
99
|
+
const env = {};
|
|
100
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
101
|
+
if (regexes.some((r) => r.test(key)))
|
|
102
|
+
continue;
|
|
103
|
+
env[key] = value;
|
|
104
|
+
}
|
|
105
|
+
return { ...env, ...extra };
|
|
106
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// 工作区只读代码感知工具:目录浏览(list_files)、代码检索(search_code)、改动差异(git_diff)。
|
|
2
|
+
// 仅对编码工作区(workspace !== "none")且具备 read 权限的 API 成员开放;严格限制在子对话 cwd 内,不修改任何文件或 Git 状态。
|
|
3
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { stripTypeScriptTypes } from "node:module";
|
|
5
|
+
import { extname, join, posix, relative, resolve, sep } from "node:path";
|
|
6
|
+
import vm from "node:vm";
|
|
7
|
+
import { AgentDoc, defineTool } from "@earendil-works/pi-durable";
|
|
8
|
+
import { bool, int, obj, oneOf, opt, str } from "@earendil-works/pi-schema";
|
|
9
|
+
import { git } from "./git.js";
|
|
10
|
+
const IGNORED_DIRS = new Set([".git", "node_modules", ".venv", "venv", ".pi-agent", "worktrees"]);
|
|
11
|
+
const MAX_FILE_BYTES = 1_048_576; // 1 MB
|
|
12
|
+
function normalizeRel(cwd, target) {
|
|
13
|
+
const rel = relative(cwd, target);
|
|
14
|
+
return rel ? rel.split(sep).join(posix.sep) : ".";
|
|
15
|
+
}
|
|
16
|
+
function resolveInside(cwd, rawPath, checkPath) {
|
|
17
|
+
const requested = rawPath?.trim() ? rawPath.trim() : ".";
|
|
18
|
+
const refusal = checkPath(requested, cwd);
|
|
19
|
+
if (refusal)
|
|
20
|
+
return { refusal };
|
|
21
|
+
const target = resolve(cwd, requested);
|
|
22
|
+
return { target, rel: normalizeRel(cwd, target) };
|
|
23
|
+
}
|
|
24
|
+
function walkFiles(root, start, maxDepth, maxEntries, includeDirs) {
|
|
25
|
+
const items = [];
|
|
26
|
+
let truncated = false;
|
|
27
|
+
function visit(dir, depth) {
|
|
28
|
+
if (truncated || depth > maxDepth)
|
|
29
|
+
return;
|
|
30
|
+
let entries;
|
|
31
|
+
try {
|
|
32
|
+
entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
for (const entry of entries) {
|
|
38
|
+
if (IGNORED_DIRS.has(entry.name) || entry.isSymbolicLink())
|
|
39
|
+
continue;
|
|
40
|
+
const full = join(dir, entry.name);
|
|
41
|
+
const rel = normalizeRel(root, full);
|
|
42
|
+
if (entry.isDirectory()) {
|
|
43
|
+
if (includeDirs) {
|
|
44
|
+
if (items.length >= maxEntries) {
|
|
45
|
+
truncated = true;
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
items.push(`${rel}/`);
|
|
49
|
+
}
|
|
50
|
+
if (depth < maxDepth)
|
|
51
|
+
visit(full, depth + 1);
|
|
52
|
+
}
|
|
53
|
+
else if (entry.isFile()) {
|
|
54
|
+
if (items.length >= maxEntries) {
|
|
55
|
+
truncated = true;
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
items.push(rel);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
let st;
|
|
63
|
+
try {
|
|
64
|
+
st = statSync(start);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return { items: [], truncated: false };
|
|
68
|
+
}
|
|
69
|
+
if (st.isFile())
|
|
70
|
+
return { items: [normalizeRel(root, start)], truncated: false };
|
|
71
|
+
if (st.isDirectory())
|
|
72
|
+
visit(start, 1);
|
|
73
|
+
return { items, truncated };
|
|
74
|
+
}
|
|
75
|
+
export function createCodeReadTools(checkPath, changes) {
|
|
76
|
+
const listFiles = defineTool({
|
|
77
|
+
name: "list_files",
|
|
78
|
+
description: "只读列出当前工作目录(或指定子目录)下的文件与目录结构,自动跳过 .git 和 node_modules。",
|
|
79
|
+
parameters: obj({
|
|
80
|
+
path: opt(str({ description: "相对工作目录的子路径,默认 ." })),
|
|
81
|
+
max_depth: opt(int({ minimum: 1, maximum: 6, description: "最大目录深度(1–6,默认 3)" })),
|
|
82
|
+
limit: opt(int({ minimum: 1, maximum: 500, description: "最多返回条数(默认 200)" })),
|
|
83
|
+
}),
|
|
84
|
+
replay: "safe",
|
|
85
|
+
execute: async (args, api, context) => {
|
|
86
|
+
const agent = (await api.snapshot(AgentDoc, api.conversationId, context));
|
|
87
|
+
if (!agent?.cwd)
|
|
88
|
+
return { output: [{ type: "text", text: "没有确定的工作目录,不能列出文件。" }], isError: true };
|
|
89
|
+
const resolved = resolveInside(agent.cwd, args.path, checkPath);
|
|
90
|
+
if (resolved.refusal)
|
|
91
|
+
return { output: [{ type: "text", text: resolved.refusal }], isError: true };
|
|
92
|
+
try {
|
|
93
|
+
statSync(resolved.target);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return { output: [{ type: "text", text: `路径不存在:${args.path ?? "."}` }], isError: true };
|
|
97
|
+
}
|
|
98
|
+
const { items, truncated } = walkFiles(agent.cwd, resolved.target, args.max_depth ?? 3, args.limit ?? 200, true);
|
|
99
|
+
const body = items.length ? items.join("\n") : "(空目录或无可显示文件)";
|
|
100
|
+
const note = truncated ? `\n…(已达 ${args.limit ?? 200} 条上限,请指定子目录 path 继续查看)` : "";
|
|
101
|
+
return { output: [{ type: "text", text: `${body}${note}` }] };
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
const searchCode = defineTool({
|
|
105
|
+
name: "search_code",
|
|
106
|
+
description: "只读在当前工作目录的代码文件中搜索关键字或正则表达式,返回匹配的文件路径、行号与内容。",
|
|
107
|
+
parameters: obj({
|
|
108
|
+
query: str({ description: "要搜索的关键字或正则表达式" }),
|
|
109
|
+
path: opt(str({ description: "限定搜索的相对子目录或文件路径,默认 ." })),
|
|
110
|
+
regex: opt(bool({ description: "是否按正则表达式匹配,默认 false(字面量匹配)" })),
|
|
111
|
+
case_sensitive: opt(bool({ description: "是否区分大小写,默认 true" })),
|
|
112
|
+
limit: opt(int({ minimum: 1, maximum: 200, description: "最多返回匹配行数(默认 80)" })),
|
|
113
|
+
}),
|
|
114
|
+
replay: "safe",
|
|
115
|
+
execute: async (args, api, context) => {
|
|
116
|
+
const agent = (await api.snapshot(AgentDoc, api.conversationId, context));
|
|
117
|
+
if (!agent?.cwd)
|
|
118
|
+
return { output: [{ type: "text", text: "没有确定的工作目录,不能搜索代码。" }], isError: true };
|
|
119
|
+
if (!args.query.trim())
|
|
120
|
+
return { output: [{ type: "text", text: "query 不能为空。" }], isError: true };
|
|
121
|
+
if (args.query.length > 240)
|
|
122
|
+
return { output: [{ type: "text", text: "query 长度不能超过 240 个字符。" }], isError: true };
|
|
123
|
+
const resolved = resolveInside(agent.cwd, args.path, checkPath);
|
|
124
|
+
if (resolved.refusal)
|
|
125
|
+
return { output: [{ type: "text", text: resolved.refusal }], isError: true };
|
|
126
|
+
let matcher;
|
|
127
|
+
const sensitive = args.case_sensitive !== false;
|
|
128
|
+
if (args.regex) {
|
|
129
|
+
try {
|
|
130
|
+
const re = new RegExp(args.query, sensitive ? "" : "i");
|
|
131
|
+
matcher = (line) => re.test(line);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
return { output: [{ type: "text", text: `无效的正则表达式:${error instanceof Error ? error.message : String(error)}` }], isError: true };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
const needle = sensitive ? args.query : args.query.toLowerCase();
|
|
139
|
+
matcher = (line) => (sensitive ? line : line.toLowerCase()).includes(needle);
|
|
140
|
+
}
|
|
141
|
+
const { items: files } = walkFiles(agent.cwd, resolved.target, 8, 2000, false);
|
|
142
|
+
const maxMatches = args.limit ?? 80;
|
|
143
|
+
const matches = [];
|
|
144
|
+
let hitLimit = false;
|
|
145
|
+
for (const rel of files) {
|
|
146
|
+
if (hitLimit)
|
|
147
|
+
break;
|
|
148
|
+
const full = join(agent.cwd, rel);
|
|
149
|
+
let stat;
|
|
150
|
+
try {
|
|
151
|
+
stat = statSync(full);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES)
|
|
157
|
+
continue;
|
|
158
|
+
let buf;
|
|
159
|
+
try {
|
|
160
|
+
buf = readFileSync(full);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (buf.includes(0))
|
|
166
|
+
continue; // 跳过二进制文件
|
|
167
|
+
const lines = buf.toString("utf8").split(/\r?\n/);
|
|
168
|
+
for (let index = 0; index < lines.length; index++) {
|
|
169
|
+
const line = lines[index];
|
|
170
|
+
if (!matcher(line))
|
|
171
|
+
continue;
|
|
172
|
+
const snippet = line.length > 240 ? `${line.slice(0, 240)}…` : line;
|
|
173
|
+
matches.push(`${rel}:${index + 1}: ${snippet}`);
|
|
174
|
+
if (matches.length >= maxMatches) {
|
|
175
|
+
hitLimit = true;
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (!matches.length)
|
|
181
|
+
return { output: [{ type: "text", text: `未找到匹配项:${args.query}` }] };
|
|
182
|
+
const suffix = hitLimit ? `\n…(已达 ${maxMatches} 条上限,请缩小 path 或细化 query)` : "";
|
|
183
|
+
return { output: [{ type: "text", text: `${matches.join("\n")}${suffix}` }] };
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
const gitDiff = defineTool({
|
|
187
|
+
name: "git_diff",
|
|
188
|
+
description: "只读查看当前工作副本相对于起始基线(base)的代码改动统计或补丁差异,不会修改任何 Git 状态。",
|
|
189
|
+
parameters: obj({
|
|
190
|
+
path: opt(str({ description: "可选相对文件或目录路径,仅查看该路径下的改动" })),
|
|
191
|
+
stat_only: opt(bool({ description: "为 true 时仅输出变更文件与增删行数统计" })),
|
|
192
|
+
}),
|
|
193
|
+
replay: "safe",
|
|
194
|
+
execute: async (args, api, context) => {
|
|
195
|
+
const agent = (await api.snapshot(AgentDoc, api.conversationId, context));
|
|
196
|
+
if (!agent?.cwd)
|
|
197
|
+
return { output: [{ type: "text", text: "没有确定的工作目录,不能读取差异。" }], isError: true };
|
|
198
|
+
const resolved = resolveInside(agent.cwd, args.path, checkPath);
|
|
199
|
+
if (resolved.refusal)
|
|
200
|
+
return { output: [{ type: "text", text: resolved.refusal }], isError: true };
|
|
201
|
+
const change = changes?.byPath(agent.cwd);
|
|
202
|
+
let baseRef = change ? changes.range(change)[0] : "HEAD";
|
|
203
|
+
let upstreamNote = "";
|
|
204
|
+
const pathArgs = args.path?.trim() && resolved.rel && resolved.rel !== "." ? [resolved.rel] : [];
|
|
205
|
+
let out = await git(agent.cwd, ["diff", "--no-color", ...(args.stat_only ? ["--stat"] : ["--unified=3"]), baseRef, "--", ...pathArgs]);
|
|
206
|
+
if (out.code === 0 && !out.stdout.trim() && change?.basedOn && change.head === change.base) {
|
|
207
|
+
const upstream = changes?.get(change.basedOn);
|
|
208
|
+
if (upstream) {
|
|
209
|
+
baseRef = changes.range(upstream)[0];
|
|
210
|
+
upstreamNote = `[上游改动 #${upstream.id}(${baseRef.slice(0, 12)}..${upstream.head.slice(0, 12)})]\n`;
|
|
211
|
+
out = await git(agent.cwd, ["diff", "--no-color", ...(args.stat_only ? ["--stat"] : ["--unified=3"]), baseRef, "--", ...pathArgs]);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (out.code !== 0)
|
|
215
|
+
return { output: [{ type: "text", text: `无法读取 Git 差异:${(out.stderr || out.stdout).trim()}` }], isError: true };
|
|
216
|
+
const text = out.stdout.trim();
|
|
217
|
+
if (!text)
|
|
218
|
+
return { output: [{ type: "text", text: `相对于基线 ${baseRef.slice(0, 12)} 暂无已跟踪文件差异。` }] };
|
|
219
|
+
const full = `${upstreamNote}${text}`;
|
|
220
|
+
const limit = 16000;
|
|
221
|
+
const clipped = full.length > limit ? `${full.slice(0, limit)}\n…(差异共 ${full.length} 字符,可传 path 查看单个文件或 stat_only:true 查看概览)` : full;
|
|
222
|
+
return { output: [{ type: "text", text: clipped }] };
|
|
223
|
+
},
|
|
224
|
+
});
|
|
225
|
+
const OUTLINE_RE = /^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?(?:function\*?\s+[A-Za-z0-9_$]+|class\s+[A-Za-z0-9_$]+|interface\s+[A-Za-z0-9_$]+|type\s+[A-Za-z0-9_$]+|enum\s+[A-Za-z0-9_$]+|(?:const|let|var)\s+[A-Za-z0-9_$]+|def\s+[A-Za-z0-9_]+|func\s+(?:\([^)]+\)\s*)?[A-Za-z0-9_]+|struct\s+[A-Za-z0-9_]+|#{1,6}\s+.+)/;
|
|
226
|
+
const METHOD_RE = /^(?:\t| {2,8})(?:(?:public|private|protected|static|readonly|override|async|get|set)\s+)*(?!if\b|for\b|while\b|switch\b|catch\b|return\b)[A-Za-z_$][A-Za-z0-9_$]*\s*\([^;]*\)\s*(?::\s*[^{=]+)?\{/;
|
|
227
|
+
const outlineFile = defineTool({
|
|
228
|
+
name: "outline_file",
|
|
229
|
+
description: "只读提取代码或文档文件的结构大纲(导出的函数、类、接口、类型、常量及行号),便于先定位行号区间再用 read 分段读取。",
|
|
230
|
+
parameters: obj({
|
|
231
|
+
path: str({ description: "相对当前工作目录的文件路径" }),
|
|
232
|
+
}),
|
|
233
|
+
replay: "safe",
|
|
234
|
+
execute: async (args, api, context) => {
|
|
235
|
+
const agent = (await api.snapshot(AgentDoc, api.conversationId, context));
|
|
236
|
+
if (!agent?.cwd)
|
|
237
|
+
return { output: [{ type: "text", text: "没有确定的工作目录,不能读取文件大纲。" }], isError: true };
|
|
238
|
+
const resolved = resolveInside(agent.cwd, args.path, checkPath);
|
|
239
|
+
if (resolved.refusal)
|
|
240
|
+
return { output: [{ type: "text", text: resolved.refusal }], isError: true };
|
|
241
|
+
let st;
|
|
242
|
+
try {
|
|
243
|
+
st = statSync(resolved.target);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return { output: [{ type: "text", text: `文件不存在:${args.path}` }], isError: true };
|
|
247
|
+
}
|
|
248
|
+
if (!st.isFile())
|
|
249
|
+
return { output: [{ type: "text", text: `路径不是文件:${args.path}` }], isError: true };
|
|
250
|
+
if (st.size > MAX_FILE_BYTES)
|
|
251
|
+
return { output: [{ type: "text", text: `文件过大(>${MAX_FILE_BYTES} 字节),请使用 search_code 搜索。` }], isError: true };
|
|
252
|
+
const buf = readFileSync(resolved.target);
|
|
253
|
+
if (buf.includes(0))
|
|
254
|
+
return { output: [{ type: "text", text: `二进制文件无法提取代码大纲:${args.path}` }], isError: true };
|
|
255
|
+
const lines = buf.toString("utf8").split(/\r?\n/);
|
|
256
|
+
const items = [];
|
|
257
|
+
for (let i = 0; i < lines.length; i++) {
|
|
258
|
+
const line = lines[i];
|
|
259
|
+
if (OUTLINE_RE.test(line) || METHOD_RE.test(line)) {
|
|
260
|
+
const cleaned = line.replace(/\s+$/, "").slice(0, 160);
|
|
261
|
+
items.push(`L${i + 1}: ${cleaned}`);
|
|
262
|
+
if (items.length >= 200)
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const header = `${resolved.rel}(共 ${lines.length} 行)`;
|
|
267
|
+
if (!items.length)
|
|
268
|
+
return { output: [{ type: "text", text: `${header}\n(未识别到顶层符号声明,可直接用 read 读取)` }] };
|
|
269
|
+
return { output: [{ type: "text", text: `${header}\n${items.join("\n")}` }] };
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
const findSymbol = defineTool({
|
|
273
|
+
name: "find_symbol",
|
|
274
|
+
description: "只读在工作区中按符号名称定位其【定义处 (Definitions)】与【引用处 (References)】(精确匹配标识符边界)。",
|
|
275
|
+
parameters: obj({
|
|
276
|
+
symbol: str({ description: "要定位的函数、类、接口、类型或变量标识符名称" }),
|
|
277
|
+
path: opt(str({ description: "可选限定的相对子目录或文件路径,默认 ." })),
|
|
278
|
+
kind: opt(oneOf(["all", "definition", "reference"], { description: "筛选范围:all(默认,定义+引用)、definition(仅定义)、reference(仅引用)" })),
|
|
279
|
+
limit: opt(int({ minimum: 1, maximum: 200, description: "最多返回条数(默认 80)" })),
|
|
280
|
+
}),
|
|
281
|
+
replay: "safe",
|
|
282
|
+
execute: async (args, api, context) => {
|
|
283
|
+
const agent = (await api.snapshot(AgentDoc, api.conversationId, context));
|
|
284
|
+
if (!agent?.cwd)
|
|
285
|
+
return { output: [{ type: "text", text: "没有确定的工作目录,不能定位符号。" }], isError: true };
|
|
286
|
+
const sym = args.symbol.trim();
|
|
287
|
+
if (!sym || sym.length > 120)
|
|
288
|
+
return { output: [{ type: "text", text: "symbol 需要 1–120 个字符的有效名称。" }], isError: true };
|
|
289
|
+
const resolved = resolveInside(agent.cwd, args.path, checkPath);
|
|
290
|
+
if (resolved.refusal)
|
|
291
|
+
return { output: [{ type: "text", text: resolved.refusal }], isError: true };
|
|
292
|
+
const escaped = sym.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
293
|
+
const tokenRe = new RegExp(`(?<![A-Za-z0-9_$])${escaped}(?![A-Za-z0-9_$])`);
|
|
294
|
+
const defRe = new RegExp(`(?:\\b(?:export|function\\*?|class|interface|type|enum|const|let|var|def|func|struct)\\s+(?:async\\s+)?${escaped}(?![A-Za-z0-9_$])|^\\s*(?:(?:public|private|protected|static|readonly|override|async|get|set)\\s+)*${escaped}\\s*\\([^;]*\\)\\s*(?::\\s*[^{=]+)?\\{)`);
|
|
295
|
+
const mode = args.kind ?? "all";
|
|
296
|
+
const maxItems = args.limit ?? 80;
|
|
297
|
+
const { items: files } = walkFiles(agent.cwd, resolved.target, 8, 2000, false);
|
|
298
|
+
const defs = [];
|
|
299
|
+
const refs = [];
|
|
300
|
+
for (const rel of files) {
|
|
301
|
+
if (defs.length + refs.length >= maxItems)
|
|
302
|
+
break;
|
|
303
|
+
const full = join(agent.cwd, rel);
|
|
304
|
+
let st;
|
|
305
|
+
try {
|
|
306
|
+
st = statSync(full);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (!st.isFile() || st.size > MAX_FILE_BYTES)
|
|
312
|
+
continue;
|
|
313
|
+
let buf;
|
|
314
|
+
try {
|
|
315
|
+
buf = readFileSync(full);
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (buf.includes(0))
|
|
321
|
+
continue;
|
|
322
|
+
const lines = buf.toString("utf8").split(/\r?\n/);
|
|
323
|
+
for (let i = 0; i < lines.length; i++) {
|
|
324
|
+
const line = lines[i];
|
|
325
|
+
if (!tokenRe.test(line))
|
|
326
|
+
continue;
|
|
327
|
+
const isDef = defRe.test(line);
|
|
328
|
+
if (isDef && mode === "reference")
|
|
329
|
+
continue;
|
|
330
|
+
if (!isDef && mode === "definition")
|
|
331
|
+
continue;
|
|
332
|
+
const entry = `${rel}:${i + 1}: ${line.trim().slice(0, 220)}`;
|
|
333
|
+
if (isDef)
|
|
334
|
+
defs.push(entry);
|
|
335
|
+
else
|
|
336
|
+
refs.push(entry);
|
|
337
|
+
if (defs.length + refs.length >= maxItems)
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (!defs.length && !refs.length)
|
|
342
|
+
return { output: [{ type: "text", text: `未找到符号:${sym}` }] };
|
|
343
|
+
const sections = [];
|
|
344
|
+
if (defs.length)
|
|
345
|
+
sections.push(`【定义处 (${defs.length})】\n${defs.join("\n")}`);
|
|
346
|
+
if (refs.length)
|
|
347
|
+
sections.push(`【引用处 (${refs.length})】\n${refs.join("\n")}`);
|
|
348
|
+
return { output: [{ type: "text", text: sections.join("\n\n") }] };
|
|
349
|
+
},
|
|
350
|
+
});
|
|
351
|
+
return [listFiles, searchCode, gitDiff, outlineFile, findSymbol];
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* 编辑后即时零成本语法/JSON 诊断:在 write/edit 刚落盘时立即捕获语法错误,
|
|
355
|
+
* 避免 API 成员直到派工结束跑 autonomy.checks 才发现低级语法问题而浪费整轮返工。
|
|
356
|
+
*/
|
|
357
|
+
export function checkFileSyntax(cwd, rawPath) {
|
|
358
|
+
const full = resolve(cwd, rawPath.trim());
|
|
359
|
+
const ext = extname(full).toLowerCase();
|
|
360
|
+
if (![".ts", ".mts", ".cts", ".tsx", ".js", ".mjs", ".cjs", ".json"].includes(ext))
|
|
361
|
+
return undefined;
|
|
362
|
+
let content;
|
|
363
|
+
try {
|
|
364
|
+
const st = statSync(full);
|
|
365
|
+
if (!st.isFile() || st.size > MAX_FILE_BYTES)
|
|
366
|
+
return undefined;
|
|
367
|
+
content = readFileSync(full, "utf8");
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
return undefined;
|
|
371
|
+
}
|
|
372
|
+
if (ext === ".json") {
|
|
373
|
+
try {
|
|
374
|
+
JSON.parse(content);
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
catch (error) {
|
|
378
|
+
return `JSON 语法错误:${error instanceof Error ? error.message : String(error)}`;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
if (ext === ".tsx") {
|
|
383
|
+
// stripTypeScriptTypes 支持 ts/mts/cts;tsx 跳过 JSX 误报仅做基础校验
|
|
384
|
+
return undefined;
|
|
385
|
+
}
|
|
386
|
+
const js = [".ts", ".mts", ".cts"].includes(ext) ? stripTypeScriptTypes(content, { mode: "strip" }) : content;
|
|
387
|
+
// 用 vm.Script 校验普通 JS 语法;若含 import/export(ESM)则跳过 vm.Script(stripTypeScriptTypes 已校验 TS 语法)
|
|
388
|
+
if (!/^\s*(?:import|export)\b/m.test(js)) {
|
|
389
|
+
new vm.Script(js, { filename: rawPath });
|
|
390
|
+
}
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
return `语法检查未通过:${error instanceof Error ? error.message : String(error)}`;
|
|
395
|
+
}
|
|
396
|
+
}
|