';
+ box.appendChild(wrap);
+ scrollBottom();
+ } else {
+ await req('POST', '/api/sessions/' + state.sessionId + '/stop');
+ toast('已发送终止指令');
+ }
+ } catch (e) { toast('操作失败:' + e.message); }
+ },
+ toggleFiles() {
+ state.filePanelOpen = !state.filePanelOpen;
+ $('files-panel').classList.toggle('hidden', !state.filePanelOpen);
+ if (state.filePanelOpen) loadFiles();
+ },
+ async uploadFiles(ev) {
+ const input = ev.target;
+ const files = input.files;
+ if (!files || !files.length || !state.sessionId) return;
+ const fd = new FormData();
+ for (const f of files) fd.append('files', f);
+ input.value = '';
+ try {
+ const r = await req('POST', '/api/sessions/' + state.sessionId + '/files', fd, true);
+ toast('已上传 ' + r.uploaded.length + ' 个文件');
+ loadFiles();
+ } catch (e) { toast('上传失败:' + e.message); }
+ },
+ async deleteFile(name) {
+ if (!confirm('删除文件 ' + name + '?')) return;
+ try {
+ await req('DELETE', '/api/sessions/' + state.sessionId + '/files?path=' + encodeURIComponent(name));
+ loadFiles();
+ } catch (e) { toast('删除失败:' + e.message); }
+ },
+};
+
+// ---------- 输入框行为 ----------
+document.addEventListener('input', e => {
+ if (e.target.id === 'msg-input') {
+ e.target.style.height = 'auto';
+ e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px';
+ }
+});
+document.addEventListener('keydown', e => {
+ if (e.target.id === 'msg-input' && e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ ui.send();
+ }
+});
+
+// ---------- 启动 ----------
+showList();
+loadSessions();
+loadModels();
+setInterval(loadSessions, 8000);
diff --git a/app/server/routes/files.js b/app/server/routes/files.js
new file mode 100644
index 0000000..66e181f
--- /dev/null
+++ b/app/server/routes/files.js
@@ -0,0 +1,138 @@
+// 文件管理 API(README 10.3):上传 / 列表 / 下载 / 删除
+const express = require('express');
+const fs = require('fs');
+const path = require('path');
+const multer = require('multer');
+const engine = require('../engine');
+const { listTaskFiles } = require('./sessions');
+const { resolveInTask } = require('../tools/executor');
+
+const router = express.Router();
+
+function taskDir(req) {
+ const dir = engine.taskDirOf(req.params.id);
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+function sanitizeName(original) {
+ let name = Buffer.from(original || 'file', 'latin1').toString('utf8');
+ name = path.basename(name).replace(/[\/\x00-\x1f]/g, '_');
+ while (name.startsWith('.')) name = name.slice(1);
+ return name || 'file';
+}
+
+const upload = multer({
+ storage: multer.diskStorage({
+ destination: function (req, file, cb) {
+ try { cb(null, taskDir(req)); } catch (err) { cb(err); }
+ },
+ filename: function (req, file, cb) {
+ try {
+ const dir = taskDir(req);
+ const name = sanitizeName(file.originalname);
+ const ext = path.extname(name);
+ const stem = name.slice(0, name.length - ext.length);
+ let target = name;
+ let i = 0;
+ while (fs.existsSync(path.join(dir, target))) {
+ i++;
+ target = stem + '-' + i + ext;
+ }
+ cb(null, target);
+ } catch (err) { cb(err); }
+ },
+ }),
+ limits: { filesize: 50 * 1024 * 1024 },
+});
+
+router.post('/:id/files', upload.array('files', 10), function (req, res) {
+ try {
+ const uploaded = (req.files || []).map(f => ({ filename: f.filename, size: f.size }));
+ const db = engine.getDb();
+ for (const f of uploaded) {
+ db.prepare('INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)')
+ .run(req.params.id, f.filename, f.size, Date.now());
+ }
+ res.json({ uploaded });
+ } catch (err) {
+ res.status(500).json({ error: String(err && err.message || err) });
+ }
+});
+
+router.get('/:id/files', function (req, res) {
+ try {
+ const session = engine.getSession(req.params.id);
+ if (!session) return res.status(404).json({ error: '会话不存在' });
+ res.json(listTaskFiles(engine.taskDirOf(session.id)));
+ } catch (err) {
+ res.status(500).json({ error: String(err && err.message || err) });
+ }
+});
+
+// 下载(支持子目录路径,前端用 ?path=xxx 传入相对路径)
+router.get('/:id/files/download', function (req, res) {
+ try {
+ const rel = String(req.query.path || '');
+ if (!rel) return res.status(400).json({ error: '缺少 path 参数' });
+ const abs = resolveInTask(engine.taskDirOf(req.params.id), rel);
+ const st = fs.statSync(abs);
+ if (!st.isFile()) return res.status(400).json({ error: '不是文件' });
+ res.download(abs, path.basename(abs));
+ } catch (err) {
+ res.status(404).json({ error: '文件不存在' });
+ }
+});
+
+router.delete('/:id/files', function (req, res) {
+ try {
+ const rel = String(req.query.path || '');
+ if (!rel) return res.status(400).json({ error: '缺少 path 参数' });
+ const dir = engine.taskDirOf(req.params.id);
+ const abs = resolveInTask(dir, rel);
+ if (path.resolve(abs) === path.resolve(dir)) {
+ return res.status(400).json({ error: '禁止删除任务目录' });
+ }
+ fs.rmSync(abs, { recursive: true, force: true });
+ engine.getDb().prepare('DELETE FROM files WHERE session_id = ? AND filename = ?')
+ .run(req.params.id, rel);
+ res.json({ ok: true });
+ } catch (err) {
+ res.status(404).json({ error: '文件不存在' });
+ }
+});
+
+// 兼容 README 形式:GET /:id/files/{filename}(支持子目录)
+router.get('/:id/files/*', function (req, res) {
+ try {
+ const rel = req.params[req.params.length - 1] || '';
+ if (!rel) return res.status(400).json({ error: '缺少文件名' });
+ const abs = resolveInTask(engine.taskDirOf(req.params.id), rel);
+ const st = fs.statSync(abs);
+ if (!st.isFile()) return res.status(400).json({ error: '不是文件' });
+ res.download(abs, path.basename(abs));
+ } catch (err) {
+ res.status(404).json({ error: '文件不存在' });
+ }
+});
+
+// 兼容 README 形式:DELETE /:id/files/{filename}
+router.delete('/:id/files/*', function (req, res) {
+ req.query.path = req.params[req.params.length - 1] || '';
+ if (!req.query.path) return res.status(400).json({ error: '缺少文件名' });
+ try {
+ const dir = engine.taskDirOf(req.params.id);
+ const abs = resolveInTask(dir, req.query.path);
+ if (path.resolve(abs) === path.resolve(dir)) {
+ return res.status(400).json({ error: '禁止删除任务目录' });
+ }
+ fs.rmSync(abs, { recursive: true, force: true });
+ engine.getDb().prepare('DELETE FROM files WHERE session_id = ? AND filename = ?')
+ .run(req.params.id, req.query.path);
+ res.json({ ok: true });
+ } catch (err) {
+ res.status(404).json({ error: '文件不存在' });
+ }
+});
+
+module.exports = router;
diff --git a/app/server/routes/messages.js b/app/server/routes/messages.js
new file mode 100644
index 0000000..91bf032
--- /dev/null
+++ b/app/server/routes/messages.js
@@ -0,0 +1,62 @@
+// 消息与交互 API(README 10.2):发消息 / SSE 流 / 开始执行 / 终止
+const express = require('express');
+const engine = require('../engine');
+
+const router = express.Router();
+
+function wrap(fn) {
+ return function (req, res) {
+ try {
+ fn(req, res);
+ } catch (err) {
+ res.status(err && err.status_code || 500).json({ error: String(err && err.message || err) });
+ }
+ };
+}
+
+router.post('/:id/messages', wrap((req, res) => {
+ const content = String((req.body && req.body.content) || '').trim();
+ if (!content) return res.status(400).json({ error: 'content 不能为空' });
+ const r = engine.postUserMessage(req.params.id, content);
+ res.json(r);
+}));
+
+router.post('/:id/start', wrap((req, res) => {
+ res.json(engine.startExecution(req.params.id));
+}));
+
+router.post('/:id/stop', wrap((req, res) => {
+ res.json(engine.stop(req.params.id));
+}));
+
+// SSE 事件流
+router.get('/:id/stream', (req, res) => {
+ const session = engine.getSession(req.params.id);
+ if (!session) return res.status(404).json({ error: '会话不存在' });
+ const bus = engine.getBus();
+ res.set({
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders && res.flushHeaders();
+ res.write('retry: 3000\n\n');
+ bus.addClient(session.id, res);
+ const heartbeat = setInterval(() => {
+ try { res.write(': ping\n\n'); } catch (_) {}
+ }, 15000);
+ req.on('close', () => {
+ clearInterval(heartbeat);
+ bus.removeClient(session.id, res);
+ });
+ bus.emit(session.id, 'status', {
+ session_id: session.id,
+ status: session.status,
+ phase: session.phase,
+ model_id: session.model_id,
+ queue_pos: session.status === 'queued' ? engine.queuePosition(session.id) : null,
+ });
+});
+
+module.exports = router;
diff --git a/app/server/routes/sessions.js b/app/server/routes/sessions.js
new file mode 100644
index 0000000..44d851e
--- /dev/null
+++ b/app/server/routes/sessions.js
@@ -0,0 +1,89 @@
+// 会话管理 API(README 10.1)
+const express = require('express');
+const fs = require('fs');
+const path = require('path');
+const engine = require('../engine');
+
+const router = express.Router();
+
+function wrap(fn) {
+ return function (req, res) {
+ try {
+ const r = fn(req, res);
+ if (r && typeof r.catch === 'function') {
+ r.catch(err => sendErr(res, err));
+ }
+ } catch (err) {
+ sendErr(res, err);
+ }
+ };
+}
+
+function sendErr(res, err) {
+ const code = err && err.status_code || 500;
+ res.status(code).json({ error: String(err && err.message || err) });
+}
+
+// 递归列出任务目录文件
+function listTaskFiles(dir) {
+ const out = [];
+ (function rec(d, rel) {
+ let entries;
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; }
+ for (const e of entries) {
+ const abs = path.join(d, e.name);
+ const relPath = rel ? rel + '/' + e.name : e.name;
+ if (e.isDirectory()) rec(abs, relPath);
+ else if (e.isFile()) {
+ let size = null, mtime = null;
+ try { const st = fs.statSync(abs); size = st.size; mtime = st.mtimeMs; } catch (_) {}
+ out.push({ filename: relPath, size, mtime });
+ }
+ }
+ })(dir, '');
+ out.sort(function (a, b) { return a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0; });
+ return out;
+}
+
+router.post('/', wrap((req, res) => {
+ const title = (req.body && req.body.title || '').trim();
+ const session = engine.createSession(title);
+ res.json(session);
+}));
+
+router.get('/', wrap((req, res) => {
+ const db = engine.getDb();
+ const rows = db.prepare('SELECT * FROM sessions ORDER BY updated_at DESC LIMIT 50').all();
+ const qpos = db.prepare(
+ 'SELECT session_id, ROW_NUMBER() OVER (ORDER BY queued_at, id) AS pos FROM wait_queue'
+ ).all();
+ const posMap = {};
+ for (const r of qpos) posMap[r.session_id] = r.pos;
+ for (const row of rows) {
+ row.queue_pos = row.status === 'queued' ? (posMap[row.id] || null) : null;
+ }
+ res.json(rows);
+}));
+
+router.get('/:id', wrap((req, res) => {
+ const session = engine.getSession(req.params.id);
+ if (!session) return sendErr(res, Object.assign(new Error('会话不存在'), { status_code: 404 }));
+ const db = engine.getDb();
+ const messages = db.prepare('SELECT id, role, content, tool_calls, tool_call_id, name, created_at FROM messages WHERE session_id = ? ORDER BY id').all(session.id);
+ const taskDir = engine.taskDirOf(session.id);
+ res.json({
+ session,
+ messages,
+ files: listTaskFiles(taskDir),
+ queue_pos: session.status === 'queued' ? engine.queuePosition(session.id) : null,
+ running: !!(engine.getRun(session.id) || {}).looping,
+ });
+}));
+
+router.delete('/:id', wrap((req, res) => {
+ const delDir = req.query.delete_dir === 'true' || req.query.delete_dir === '';
+ res.json(engine.deleteSession(req.params.id, delDir));
+}));
+
+module.exports = router;
+module.exports.listTaskFiles = listTaskFiles;
diff --git a/app/server/server.js b/app/server/server.js
new file mode 100644
index 0000000..bde54b9
--- /dev/null
+++ b/app/server/server.js
@@ -0,0 +1,52 @@
+// 入口:装配配置、数据库、SSE 总线、路由与静态资源。
+const express = require('express');
+const http = require('http');
+const path = require('path');
+const fs = require('fs');
+
+const { loadConfig } = require('./config');
+const { initDb } = require('./db');
+const { createBus } = require('./sse');
+const engine = require('./engine');
+
+const cfg = loadConfig(process.env.AGENT_CONFIG);
+const db = initDb(cfg.db_path);
+const bus = createBus();
+
+engine.setModelPool(cfg, db, bus);
+engine.init();
+
+const app = express();
+const server = http.createServer(app);
+
+app.use(express.json({ limit: '2mb' }));
+
+// 可选 basic auth(若前置 nginx 已做,可不启用)
+if (cfg.auth && cfg.auth.user) {
+ const expected = 'Basic ' + Buffer.From(cfg.auth.user + ':' + cfg.auth.password).toString('base64');
+ app.use((req, res, next) => {
+ if (req.headers.authorization === expected) return next();
+ res.set('WWW-Authenticate', 'Basic realm="agent"');
+ res.status(401).end('需要认证');
+ });
+}
+
+app.use(express.static(path.join(__dirname, 'public')));
+
+app.use('/api/sessions', require('./routes/sessions'));
+app.use('/api/sessions', require('./routes/messages'));
+app.use('/api/sessions', require('./routes/files'));
+
+// 模型池状态(前端可展示空闲/占用)
+app.get('/api/models', (req, res) => {
+ res.json(db.prepare('SELECT id, display_name, is_busy, current_session_id FROM model_pool ORDER BY id').all());
+});
+
+app.get('/api/health', (req, res) => res.json({ ok: true, time: Date.now() }));
+
+const PORT = process.env.PORT || cfg.port;
+server.listen(PORT, () => {
+ console.log('Agent server listening on ' + PORT);
+ console.log(' workspace_root=' + cfg.workspace_root);
+ console.log(' models=' + cfg.models.map(m => m.id).join(',') + ' upstream=' + cfg.upstream_url);
+});
diff --git a/app/server/sse.js b/app/server/sse.js
new file mode 100644
index 0000000..d3b5671
--- /dev/null
+++ b/app/server/sse.js
@@ -0,0 +1,39 @@
+// 按会话分组的 SSE 事件总线;前端通过 GET /api/sessions/:id/stream 订阅。
+function createBus() {
+ const clients = new Map(); // session_id -> Set
+
+ function addClient(sessionId, res) {
+ if (!clients.has(sessionId)) clients.set(sessionId, new Set());
+ clients.get(sessionId).add(res);
+ }
+
+ function removeClient(sessionId, res) {
+ const set = clients.get(sessionId);
+ if (!set) return;
+ set.delete(res);
+ if (set.size === 0) clients.delete(sessionId);
+ }
+
+ // event 名称 + 任意 JSON data。无客户端时静默丢弃(消息本身已持久化,重连可回放)。
+ function emit(sessionId, event, data) {
+ const set = clients.get(sessionId);
+ if (!set || set.size === 0) return;
+ const payload = 'event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n';
+ for (const res of Array.from(set)) {
+ try { res.write(payload); } catch (_) { removeClient(sessionId, res); }
+ }
+ }
+
+ function closeAll(sessionId) {
+ const set = clients.get(sessionId);
+ if (!set) return;
+ for (const res of Array.from(set)) {
+ try { res.end(); } catch (_) {}
+ }
+ clients.delete(sessionId);
+ }
+
+ return { addClient, removeClient, emit, closeAll };
+}
+
+module.exports = { createBus };
diff --git a/app/server/templates/system-prompt.txt b/app/server/templates/system-prompt.txt
new file mode 100644
index 0000000..f86f6e4
--- /dev/null
+++ b/app/server/templates/system-prompt.txt
@@ -0,0 +1,155 @@
+You are the Zed coding agent running inside the Zed editor. You help users complete software engineering tasks by understanding their codebase, making careful changes, and explaining your work clearly. Use your broad knowledge of programming languages, frameworks, design patterns, and engineering best practices to solve problems pragmatically.
+
+## Communication
+
+- Default to a tone that is concise, direct, and friendly. Communicate efficiently and prioritize actionable guidance over verbose narration of your work.
+- Match the level of detail to the task: be brief for straightforward work, and provide context when it helps the user make a decision. Reach for structured headers, tables, or long explanations only when they genuinely help the user scan the result.
+- Be accurate and truthful. Ground claims in the user's codebase, tool results, or reliable external resources. Do not fabricate details or pretend to know something you have not verified.
+- Prioritize technical correctness over affirming the user's assumptions. If something seems wrong or risky, say so respectfully and explain the reasoning.
+- Be transparent about uncertainty. If you infer something, label it as an inference; if you cannot verify something, say what you would check next.
+- Do not over-apologize when results are unexpected. Briefly explain what happened, then continue with the best available next step.
+
+## Formatting Responses
+
+Format responses in markdown. Use backticks for file paths, directories, commands, functions, classes, and other code identifiers.
+
+To display an image to the user, use standard markdown image syntax: ``. Remote URLs (http/https), absolute file paths, and paths relative to a workspace root directory are supported.
+
+To include a mermaid diagram that will be rendered visually, use `mermaid` as the language:
+
+```mermaid
+graph TD
+ A[Start] --> B[End]
+```
+
+The renderer supports the following diagram types: flowchart, sequence, class, state, ER, gantt, pie, gitgraph, mindmap, timeline, quadrant chart, xy chart, and journey. Other diagram types will only show as code.
+
+Mermaid diagrams are automatically themed to match the user's editor theme. Do not include `%%{init}%%` directives or define your own `classDef` styles.
+
+Do *NOT* include inline HTML elements in mermaid diagrams, as they cannot be rendered. It is better to simply skip formatting (e.g. bold/italic/etc.).
+
+Mermaid diagrams are automatically color-coded using the user's theme accent palette. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
+
+## Tool Use
+
+- Follow the available tool schemas exactly and provide every required argument.
+- Use only the tools that are currently available. Do not call a tool just because it appeared earlier in the conversation; the user may have disabled it.
+- Prefer the most direct tool for the job. Use file tools for reading and editing files, search tools for code discovery, and terminal commands for build, test, and project-specific workflows.
+- Before acting, gather enough context to avoid guessing. Do not use placeholders, invented paths, or assumed command arguments in tool calls.
+- You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead.
+- When running commands that may run indefinitely or for a long time, such as builds, tests, servers, or file watchers, specify `timeout_ms` to bound runtime. If a command times out, report that clearly and let the user decide whether to rerun it with a longer timeout.
+- Avoid HTML entity escaping; use plain characters instead.
+- Do not waste tokens by re-reading files after calling `write_file`, `edit_file`, or similar. The tool call will fail if it didn't work. The same goes for creating folders, deleting folders, etc.
+- Before a group of related tool calls, send a brief one- to two-sentence preamble explaining what you're about to do, so the user can follow along. Skip the preamble for trivial single reads or when continuing a clearly described step.
+
+## Task Execution
+
+- Keep going until the user's task is completely resolved before ending your turn and yielding back to the user. Only terminate your turn when you are sure the problem is solved.
+- Autonomously resolve the task to the best of your ability with the tools available rather than coming back to the user prematurely. Ask the user only when the information you need is genuinely unavailable from the project, or when proceeding without clarification would be risky.
+- Do not guess or make up an answer.
+
+## Searching and Reading
+
+If you are unsure how to fulfill the user's request, gather more information with tool calls and/or clarifying questions.
+
+- When providing paths to tools, the path should always start with the name of a project root directory listed above.
+- Before you read or edit a file, you must first know its full project-relative path. Do not guess file paths.
+- Read only the portions of large files that are relevant to the task when targeted reads are available.
+- When looking for symbols in the project, prefer the `grep` tool.
+- As you learn about the structure of the project, scope searches to targeted subtrees instead of repeatedly searching the whole repository.
+- If the user specifies a partial file path and you do not know the full path, use `find_path` rather than `grep` before reading or editing the file.
+
+## Making Code Changes
+
+- Fix the problem at the root cause rather than applying surface-level patches, when possible.
+- Avoid unneeded complexity in your solution.
+- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
+- Prefer existing dependencies and patterns already used in the project. Add new dependencies only when they are justified by the task.
+- Keep user work safe. Do not overwrite, remove, or revert changes you did not make unless the user explicitly asks.
+- Update related tests, documentation, configuration, or call sites when they are part of the requested change.
+- Do not fix unrelated bugs or broken tests. It is not your responsibility to fix them, but you may mention them in your final message.
+- Do not commit changes or create new git branches unless the user explicitly requests it.
+- Do not add comments that merely restate the code. Add comments only when they explain non-obvious intent, constraints, or tradeoffs.
+- If a change may affect behavior, call out the impact and any migration or follow-up work the user should know about.
+
+## Ambition vs. Precision
+
+- For tasks with no prior context (the user is starting something brand new), feel free to be ambitious and demonstrate creativity with your implementation.
+- For tasks in an existing codebase, do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (e.g. changing filenames or variables unnecessarily). Balance this with being sufficiently ambitious and proactive when completing tasks of this nature.
+- Use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. Show good judgment about doing the right extras without gold-plating: high-value, creative touches when scope is vague, and surgical, targeted work when scope is tightly specified.
+
+## Validation
+
+- If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete.
+- Start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence.
+- Do not claim validation passed unless you actually ran it and saw it pass.
+- If validation fails, report the failing command and the relevant error. Fix issues you caused when you can identify the root cause.
+- If you cannot run validation, state that clearly and explain why.
+
+## Fixing Diagnostics
+
+1. Make 1-2 focused attempts at fixing diagnostics you are likely able to resolve, then defer to the user with a clear explanation of what remains.
+2. Never simplify or discard meaningful code just to silence diagnostics. Complete, mostly correct code is more valuable than superficially clean code that does not solve the problem.
+
+## Debugging
+
+When debugging, only make code changes if you are confident they address the root cause. Otherwise, first gather evidence and isolate the problem.
+
+1. Prefer reproducing the issue or inspecting the failing path before changing code.
+2. Address the root cause instead of the symptoms.
+3. Add descriptive logging or error messages when they help reveal state or make future failures actionable.
+4. Add or adjust tests when they help isolate the problem or prevent regressions.
+
+## Calling External APIs
+
+- Use external APIs, packages, or services when they are appropriate for the task and consistent with the project's dependency and security expectations. You do not need to ask permission unless the user requested a specific constraint.
+- When choosing a package or API version, prefer one compatible with the user's dependency management files. If the project provides no guidance, use a stable, current version you know to be appropriate.
+- If an external API requires an API key or secret, tell the user. Never hardcode secrets or place them where they may be exposed.
+- Be explicit about network, cost, rate-limit, privacy, or data-sharing implications when they matter to the task.
+
+## Multi-agent delegation
+
+Sub-agents can help you move faster on large tasks when you use them thoughtfully. This is most useful for:
+
+- Very large tasks with multiple well-defined scopes.
+- Plans with independent steps that can be executed in parallel.
+- Independent information-gathering tasks that can be done in parallel.
+- Requesting a review or fresh perspective on your work, another agent's work, or a difficult design/debugging question.
+- Running tests or config commands that can produce large logs when you only need a concise summary. Because you only receive the sub-agent's final message, ask it to include relevant failing lines or diagnostics.
+
+When delegating, create concrete, self-contained subtasks and include all context the sub-agent needs. Coordinate the work instead of duplicating it yourself. If multiple agents may edit files, assign disjoint write scopes.
+
+Use this feature wisely. For simple or straightforward tasks, prefer doing the work directly.
+
+## Final Message
+
+- When you finish a coding task, briefly summarize what changed, reference the relevant files, and state what validation you ran (or why you did not run any).
+- Reference files by their project-relative path so the user can click through; do not ask the user to "save the file" or "copy this code".
+- If there is an obvious follow-up the user may want (running a broader test suite, committing, scaffolding the next component), offer it as a question rather than doing it unprompted.
+
+## System Information
+
+Operating System: linux
+Default Shell: bash
+Today's Date: {动态日期}
+
+The current project contains the following root directories:
+
+- {任务目录路径}
+
+## Model Information
+
+You are powered by the model named {模型显示名}.
+
+## Agent Skills
+
+You have access to the following Skills - modular capabilities that provide specialized instructions for specific tasks. When a user's request matches a Skill's description, use the `skill` tool to retrieve the full instructions.
+
+
+
+
+To use a Skill:
+1. Identify when a user's request matches a Skill's description
+2. Use the `skill` tool with the skill's name to get detailed instructions
+3. Follow the instructions in the Skill
+4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`).
\ No newline at end of file
diff --git a/app/server/tools/definitions.json b/app/server/tools/definitions.json
new file mode 100644
index 0000000..74f8470
--- /dev/null
+++ b/app/server/tools/definitions.json
@@ -0,0 +1,360 @@
+[
+ {
+ "type": "function",
+ "function": {
+ "name": "copy_path",
+ "description": "Copies a file or directory in the project, and returns confirmation that the copy succeeded.\nDirectory contents will be copied recursively.\n\nThis tool should be used when it's desirable to create a copy of a file or directory without modifying the original.\nIt's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
+ "parameters": {
+ "required": [
+ "source_path",
+ "destination_path"
+ ],
+ "properties": {
+ "source_path": {
+ "description": "The source path of the file or directory to copy.\nIf a directory is specified, its contents will be copied recursively.\n\n\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can copy the first file by providing a source_path of \"directory1/a/something.txt\"\n",
+ "type": "string"
+ },
+ "destination_path": {
+ "description": "The destination path where the file or directory should be copied to.\n\n\nTo copy \"directory1/a/something.txt\" to \"directory2/b/copy.txt\", provide a destination_path of \"directory2/b/copy.txt\"\n",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "create_directory",
+ "description": "Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.\n\nThis tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
+ "parameters": {
+ "required": [
+ "path"
+ ],
+ "properties": {
+ "path": {
+ "description": "The path of the new directory.\n\n\nIf the project has the following structure:\n\n- directory1/\n- directory2/\n\nYou can create a new directory by providing a path of \"directory1/new_directory\"\n\n\n\nTo create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "delete_path",
+ "description": "Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.\n\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
+ "parameters": {
+ "required": [
+ "path"
+ ],
+ "properties": {
+ "path": {
+ "description": "The path of the file or directory to delete.\n\n\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can delete the first file by providing a path of \"directory1/a/something.txt\"\n",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "edit_file",
+ "description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.\n\n`read_file` prefixes each line of its output with a line number right-aligned in a\n6-character field followed by a single tab, then the line's actual content. When you\nderive `old_text` or `new_text` from that output, strip this prefix and keep only what\ncomes after the tab, preserving the original indentation (tabs and spaces) exactly.\nNever include any part of the line number prefix in `old_text` or `new_text`.",
+ "parameters": {
+ "required": [
+ "path",
+ "edits"
+ ],
+ "properties": {
+ "path": {
+ "description": "The full path of the file to edit in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n\n\n\n`frontend/db.js`\n\n\n\nTo edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n",
+ "type": "string"
+ },
+ "edits": {
+ "description": "List of edit operations to apply sequentially.\nEach edit finds `old_text` in the file and replaces it with `new_text`.",
+ "type": "array",
+ "items": {
+ "description": "A single edit operation that replaces old text with new text\nProperly escape all text fields as valid JSON strings.\nRemember to escape special characters like newlines (`\\n`) and quotes (`\"`) in JSON strings.",
+ "type": "object",
+ "properties": {
+ "old_text": {
+ "description": "The exact text to find in the file. This will be matched using fuzzy matching\nto handle minor differences in whitespace or formatting.\n\nBe minimal with replacements:\n- For unique lines, include only those lines\n- For non-unique lines, include enough context to identify them",
+ "type": "string"
+ },
+ "new_text": {
+ "description": "The text to replace it with",
+ "type": "string"
+ }
+ },
+ "required": [
+ "old_text",
+ "new_text"
+ ]
+ }
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "fetch",
+ "description": "Fetches a URL and returns the content as Markdown.\n\nThis tool is not run inside the terminal OS sandbox, but it still refuses to\nreach any host that hasn't been granted network access. It shares the same\nper-host grants as the `terminal` tool: approving a host for one authorizes\nit for the other, whether the grant is for this thread or saved permanently.\nWhen unsandboxed access has been granted, these restrictions are lifted\nentirely, matching the terminal, which is also how loopback and IP-literal\nhosts (which can't be granted individually) become reachable.",
+ "parameters": {
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "url": {
+ "description": "The URL to fetch.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "find_path",
+ "description": "Find file paths that match a given pattern.\n\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted alphabetically\n- Prefer the `grep` tool to this tool when searching for symbols unless you have specific information about paths.\n- Use this tool when you need to find files by name patterns\n- Results are paginated with 50 matches per page. Use the optional 'offset' parameter to request subsequent pages.",
+ "parameters": {
+ "required": [
+ "glob"
+ ],
+ "properties": {
+ "glob": {
+ "description": "The glob to match against every path in the project.\n\n\nIf the project has the following root directories:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can get back the first two paths by providing a glob of \"*thing*.txt\"\n",
+ "type": "string"
+ },
+ "offset": {
+ "description": "Optional starting position for paginated results (0-based).\nWhen not provided, starts from the beginning.",
+ "type": "integer",
+ "default": 0,
+ "minimum": 0
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "grep",
+ "description": "Searches the contents of files in the project with a regular expression\n\n- Prefer this tool to path search when searching for symbols in the project, because you won't need to guess what path it's in.\n- Supports full regex syntax (eg. \"log.*Error\", \"function\\\\s+\\\\w+\", etc.)\n- Pass an `include_pattern` if you know how to narrow your search on the files system\n- Never use this tool to search for paths. Only search file contents with this tool.\n- Use this tool when you need to find files containing specific patterns\n- Results are paginated with 20 matches per page. Use the optional 'offset' parameter to request subsequent pages.\n- DO NOT use HTML entities solely to escape characters in the tool parameters.",
+ "parameters": {
+ "required": [
+ "regex"
+ ],
+ "properties": {
+ "regex": {
+ "description": "A regex pattern to search for in the entire project. Note that the regex will be parsed by the Rust `regex` crate.\n\nDo NOT specify a path here! This will only be matched against the code **content**.",
+ "type": "string"
+ },
+ "include_pattern": {
+ "description": "A glob pattern for the paths of files to include in the search.\nSupports standard glob patterns like \"**/*.rs\" or \"frontend/src/**/*.ts\".\nIf omitted, all files in the project will be searched.\n\nThe glob pattern is matched against the full path including the project root directory.\n\n\nIf the project has the following root directories:\n\n- /a/b/backend\n- /c/d/frontend\n\nUse \"backend/**/*.rs\" to search only Rust files in the backend root directory.\nUse \"frontend/src/**/*.ts\" to search TypeScript files only in the frontend root directory (sub-directory \"src\").\nUse \"**/*.rs\" to search Rust files across all root directories.\n",
+ "type": "string",
+ "nullable": true
+ },
+ "offset": {
+ "description": "Optional starting position for paginated results (0-based).\nWhen not provided, starts from the beginning.",
+ "type": "integer",
+ "default": 0,
+ "minimum": 0
+ },
+ "case_sensitive": {
+ "description": "Whether the regex is case-sensitive. Defaults to false (case-insensitive).",
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "list_directory",
+ "description": "Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
+ "parameters": {
+ "required": [
+ "path"
+ ],
+ "properties": {
+ "path": {
+ "description": "The fully-qualified path of the directory to list in the project.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.\n\n\nIf the project has the following root directories:\n\n- directory1\n- directory2\n\nYou can list the contents of `directory1` by using the path `directory1`.\n\n\n\nIf the project has the following root directories:\n\n- foo\n- bar\n\nIf you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.\n\n\n\nTo list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "move_path",
+ "description": "Moves or rename a file or directory in the project, and returns confirmation that the move succeeded.\n\nIf the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.\n\nThis tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
+ "parameters": {
+ "required": [
+ "source_path",
+ "destination_path"
+ ],
+ "properties": {
+ "source_path": {
+ "description": "The source path of the file or directory to move/rename.\n\n\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can move the first file by providing a source_path of \"directory1/a/something.txt\"\n",
+ "type": "string"
+ },
+ "destination_path": {
+ "description": "The destination path where the file or directory should be moved/renamed to.\nIf the paths are the same except for the filename, then this will be a rename.\n\n\nTo move \"directory1/a/something.txt\" to \"directory2/b/renamed.txt\",\nprovide a destination_path of \"directory2/b/renamed.txt\"\n",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "read_file",
+ "description": "Reads the content of the given file in the project.\n\n- Never attempt to read a path that hasn't been previously mentioned.\n- For large files, this tool returns a file outline with symbol names and line numbers instead of the full content.\n This outline IS a successful response - use the line numbers to read specific sections with start_line/end_line.\n Do NOT retry reading the same file without line numbers if you receive an outline.\n- This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.\n Image files are returned as visual content that you can analyze directly.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
+ "parameters": {
+ "required": [
+ "path"
+ ],
+ "properties": {
+ "path": {
+ "description": "The relative path of the file to read.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.\n\n\nIf the project has the following root directories:\n\n- /a/b/directory1\n- /c/d/directory2\n\nIf you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.\nIf you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.\n\n\n\nTo read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n",
+ "type": "string"
+ },
+ "start_line": {
+ "description": "Optional line number to start reading on (1-based index)",
+ "type": "integer",
+ "nullable": true,
+ "minimum": 0,
+ "default": null
+ },
+ "end_line": {
+ "description": "Optional line number to end reading on (1-based index, inclusive)",
+ "type": "integer",
+ "nullable": true,
+ "minimum": 0,
+ "default": null
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "terminal",
+ "description": "Executes a shell one-liner and returns the combined output.\n\nThis tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result.\n\nThe output results will be shown to the user already, only list it again if necessary, avoid being redundant.\n\nMake sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error.\n\nDo not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values yourself before calling this tool, or ask the user for the literal value to use.\n\nDo not pipe output to `head`, `tail`, or similar output-filtering commands just to reduce what you receive. Instead, use `head_lines` and/or `tail_lines`; this keeps the terminal output visible to the user in real time while limiting only the final output sent back to you. When both are specified, the first `head_lines` lines are returned, then a blank line, then the last `tail_lines` lines. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.\n\nDo not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own.\n\nFor potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs.\n\nRemember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations.\n\nThe terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this:\n\n- Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).\n- Prefer Git flags that avoid optional metadata writes when possible, such as `git --no-optional-locks status` instead of `git status`.\n- Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).\n- For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.",
+ "parameters": {
+ "required": [
+ "command",
+ "cd"
+ ],
+ "properties": {
+ "command": {
+ "description": "The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user for the literal value to use.\n\nREMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Prefer `git --no-optional-locks status` over `git status` to avoid optional metadata writes. Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang.",
+ "type": "string"
+ },
+ "cd": {
+ "description": "Working directory for the command. This must be one of the root directories of the project.",
+ "type": "string"
+ },
+ "timeout_ms": {
+ "description": "Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.",
+ "type": "integer",
+ "nullable": true,
+ "minimum": 0
+ },
+ "head_lines": {
+ "description": "Return only the first N lines of terminal output to the model after the command finishes. Do not pipe output to `head`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.",
+ "type": "integer",
+ "nullable": true,
+ "minimum": 0,
+ "default": null
+ },
+ "tail_lines": {
+ "description": "Return only the last N lines of terminal output to the model after the command finishes. Do not pipe output to `tail`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.",
+ "type": "integer",
+ "nullable": true,
+ "minimum": 0,
+ "default": null
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "description": "免费网页搜索:Parallel(默认,匿名免 key)或 Exa(备用)。返回结构化结果数组(title / url / snippet / publishedAt)。",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "搜索查询词"
+ },
+ "provider": {
+ "type": "string",
+ "enum": [
+ "parallel",
+ "exa"
+ ],
+ "description": "免费后端:parallel(默认)/ exa(备用)"
+ },
+ "numResults": {
+ "type": "number",
+ "description": "返回结果条数上限(默认 8)"
+ }
+ },
+ "required": [
+ "query"
+ ]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "write_file",
+ "description": "This is a tool for creating a new file or overwriting an existing file with completely new contents.\n\nTo make granular edits to an existing file, prefer the `edit_file` tool instead.\n\nBefore using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
+ "parameters": {
+ "required": [
+ "path",
+ "content"
+ ],
+ "properties": {
+ "path": {
+ "description": "The full path of the file to create or overwrite in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n\n\n\n`frontend/db.js`\n\n\n\nTo create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n",
+ "type": "string"
+ },
+ "content": {
+ "description": "The entire content for the file.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ }
+]
diff --git a/app/server/tools/executor.js b/app/server/tools/executor.js
new file mode 100644
index 0000000..f4e907d
--- /dev/null
+++ b/app/server/tools/executor.js
@@ -0,0 +1,438 @@
+// 工具执行器。所有文件路径强制解析到任务目录内(防路径穿越)。
+// 工具名与参数 schema 来自 README 7.2(生成到 definitions.json)。
+const fs = require('fs');
+const path = require('path');
+const fsp = require('fs').promises;
+const { spawn } = require('child_process');
+const { Minimatch } = require('minimatch');
+
+function makeMatcher(pattern, opts) {
+ const mm = new Minimatch(pattern, opts || {});
+ return function (p) { return mm.match(p); };
+}
+
+const IGNORED_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build', '.next', '.cache']);
+
+// ---------- 路径沙箱 ----------
+function resolveInTask(taskDir, p) {
+ if (typeof p !== 'string' || !p.trim()) throw new Error('路径不能为空');
+ let abs;
+ if (path.isAbsolute(p)) {
+ abs = path.normalize(p);
+ } else {
+ abs = path.resolve(taskDir, p);
+ }
+ const root = path.resolve(taskDir);
+ if (abs !== root && !abs.startsWith(root + path.sep)) {
+ throw new Error('路径越界(只允许任务目录内操作):' + p);
+ }
+ return abs;
+}
+
+function relOf(taskDir, abs) {
+ return path.relative(path.resolve(taskDir), abs) || '.';
+}
+
+// ---------- 文件系统遍历 ----------
+function walk(taskDir, opts) {
+ const out = [];
+ const maxFiles = (opts && opts.maxFiles) || 20000;
+ function rec(dir) {
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
+ for (const ent of entries) {
+ if (out.length >= maxFiles) return;
+ if (ent.name.startsWith('.') && IGNORED_DIRS.has(ent.name)) continue;
+ if (IGNORED_DIRS.has(ent.name)) continue;
+ const abs = path.join(dir, ent.name);
+ if (ent.isDirectory()) {
+ rec(abs);
+ } else if (ent.isFile()) {
+ out.push(abs);
+ }
+ }
+ }
+ rec(taskDir);
+ return out;
+}
+
+function isProbablyBinary(abs) {
+ let fd;
+ try {
+ fd = fs.openSync(abs, 'r');
+ const buf = Buffer.alloc(8192);
+ const bytes = fs.readSync(fd, buf, 0, buf.length, null);
+ if (bytes === 0) return false;
+ const slice = buf.slice(0, bytes);
+ return slice.includes(0);
+ } catch (_) {
+ return true;
+ } finally {
+ if (fd !== undefined) try { fs.closeSync(fd); } catch (_) {}
+ }
+}
+
+function truncate(text, max) {
+ if (text.length <= max) return text;
+ return text.slice(0, max) + '\n...(输出已截断,共 ' + text.length + ' 字符)';
+}
+
+// ---------- 各工具实现 ----------
+async function toolReadFile(ctx, args) {
+ const abs = resolveInTask(ctx.taskDir, args.path);
+ const st = await fsp.stat(abs);
+ if (st.isDirectory()) throw new Error("目录不是文件: " + args.path);
+ if (isProbablyBinary(abs)) return '[二进制文件,跳过文本读取] ' + relOf(ctx.taskDir, abs);
+ let text = await fsp.readFile(abs, 'utf8');
+ let lines = text.split('\n');
+ const total = lines.length;
+ const startLine = args.start_line || 1;
+ let endLine = args.end_line || total;
+ if (startLine > total) return '(文件共 ' + total + ' 行,start_line 超出范围)';
+ // 未指定范围且文件很大时,只回前 200 行,避免灌满上下文
+ let note = '';
+ if (!args.start_line && !args.end_line && total > 200) {
+ endLine = 200;
+ note = '\n(文件过大,已截断显示前 200 行,共 ' + total + ' 行;可用 start_line/end_line 继续读)';
+ }
+ lines = lines.slice(startLine - 1, Math.min(endLine, total));
+ return lines.map((l, i) => String(startLine + i).padStart(6, ' ') + '\t' + l).join('\n') + note;
+}
+
+async function toolWriteFile(ctx, args) {
+ const abs = resolveInTask(ctx.taskDir, args.path);
+ await fsp.mkdir(path.dirname(abs), { recursive: true });
+ await fsp.writeFile(abs, args.content ?? '', 'utf8');
+ recordFile(ctx, abs);
+ return '已成功写入文件 ' + relOf(ctx.taskDir, abs) + '(' + Buffer.byteLength(args.content || '') + ' 字节)';
+}
+
+function applyEditsOnce(text, edits) {
+ let cur = text;
+ for (let i = 0; i < edits.length; i++) {
+ const { old_text, new_text } = edits[i];
+ if (!old_text) throw new Error('edit #' + (i + 1) + ': old_text 不能为空');
+ let idx = cur.indexOf(old_text);
+ if (~idx) {
+ cur = cur.slice(0, idx) + new_text + cur.slice(idx + old_text.length);
+ continue;
+ }
+ // 模糊回退:按“每行去掉首尾空白”后逐行匹配
+ const oldLines = old_text.replace(/\r\n?/g, '\n').split('\n');
+ if (oldLines.length > 1 && oldLines[0].trim() === '' && oldLines[oldLines.length - 1].trim() === '') { oldLines.pop(); oldLines.shift(); }
+ const normalizedOld = oldLines.map(l => l.trim());
+ const curLines = cur.split('\n');
+ let found = -1;
+ for (let s = 0; s + oldLines.length <= curLines.length; s++) {
+ let ok = true;
+ for (let j = 0; j < oldLines.length; j++) {
+ if (curLines[s + j].trim() !== normalizedOld[j]) { ok = false; break; }
+ }
+ if (ok) { found = s; break; }
+ }
+ if (found < 0) throw new Error('edit #' + (i + 1) + ': 在文件中找不到 old_text(可能已被之前的 edit 修改)');
+ const replaceLen = oldLines.length;
+ curLines.splice(found, replaceLen, ...new_text.replace(/\r\n?/g, '\n').split('\n'));
+ cur = curLines.join('\n');
+ }
+ return cur;
+}
+
+async function toolEditFile(ctx, args) {
+ const abs = resolveInTask(ctx.taskDir, args.path);
+ let text = await fsp.readFile(abs, 'utf8');
+ text = applyEditsOnce(text, args.edits || []);
+ await fsp.writeFile(abs, text, 'utf8');
+ recordFile(ctx, abs);
+ return '已成功应用 ' + ((args.edits || []).length) + ' 处编辑到 ' + relOf(ctx.taskDir, abs);
+}
+
+async function toolListDirectory(ctx, args) {
+ const abs = resolveInTask(ctx.taskDir, args.path);
+ const entries = await fsp.readdir(abs, { withFileTypes: true });
+ const dirs = []; const files = [];
+ for (const e of entries) {
+ if (e.isDirectory()) dirs.push(e.name + '/');
+ else files.push(e.name);
+ }
+ dirs.sort(); files.sort();
+ const all = dirs.concat(files);
+ const shown = all.slice(0, 500);
+ let out = '目录 ' + relOf(ctx.taskDir, abs) + ' 下的文件与子目录:\n' + shown.join('\n');
+ if (all.length > shown.length) out += '\n...(共 ' + all.length + ' 项,已截断)';
+ if (all.length === 0) out = '(目录为空)';
+ return out;
+}
+
+async function toolCreateDirectory(ctx, args) {
+ const abs = resolveInTask(ctx.taskDir, args.path);
+ await fsp.mkdir(abs, { recursive: true });
+ return '已创建目录 ' + relOf(ctx.taskDir, abs);
+}
+
+async function toolDeletePath(ctx, args) {
+ const abs = resolveInTask(ctx.taskDir, args.path);
+ if (path.resolve(abs) === path.resolve(ctx.taskDir)) throw new Error('禁止删除任务目录本身');
+ await fsp.rm(abs, { recursive: true, force: true });
+ return '已删除 ' + relOf(ctx.taskDir, abs);
+}
+
+async function toolMovePath(ctx, args) {
+ const src = resolveInTask(ctx.taskDir, args.source_path);
+ const dst = resolveInTask(ctx.taskDir, args.destination_path);
+ await fsp.mkdir(path.dirname(dst), { recursive: true });
+ await fsp.rename(src, dst);
+ recordFile(ctx, dst);
+ return '已移动/重命名 ' + relOf(ctx.taskDir, src) + ' → ' + relOf(ctx.taskDir, dst);
+}
+
+async function toolCopyPath(ctx, args) {
+ const src = resolveInTask(ctx.taskDir, args.source_path);
+ const dst = resolveInTask(ctx.taskDir, args.destination_path);
+ await fsp.mkdir(path.dirname(dst), { recursive: true });
+ await fsp.cp(src, dst, { recursive: true });
+ recordFile(ctx, dst);
+ return '已复制 ' + relOf(ctx.taskDir, src) + ' → ' + relOf(ctx.taskDir, dst);
+}
+
+async function toolFindPath(ctx, args) {
+ const files = walk(ctx.taskDir).map(f => relOf(ctx.taskDir, f)).sort();
+ const matcher = makeMatcher(args.glob, { dot: true });
+ const matched = files.filter(matcher);
+ const offset = args.offset || 0;
+ const page = matched.slice(offset, offset + 50);
+ if (page.length === 0) return '没有匹配 ' + args.glob + ' 的路径';
+ return page.join('\n') + '\n(共 ' + matched.length + ' 个匹配' + (offset + 50 < matched.length ? ',用 offset=' + (offset + 50) + ' 看下一页' : '') + ')';
+}
+
+async function toolGrep(ctx, args) {
+ let re;
+ try { re = new RegExp(args.regex, args.case_sensitive ? '' : 'i'); } catch (e) {
+ return '正则解析失败:' + e.message;
+ }
+ const pattern = args.include_pattern ? makeMatcher(args.include_pattern, { dot: false }) : null;
+ const files = walk(ctx.taskDir);
+ const matches = [];
+ for (const abs of files) {
+ const rel = relOf(ctx.taskDir, abs);
+ if (pattern && !pattern(rel)) continue;
+ if (isProbablyBinary(abs)) continue;
+ let text;
+ try { text = await fsp.readFile(abs, 'utf8'); } catch (_) { continue; }
+ if (text.length > 2 * 1024 * 1024) continue;
+ const lines = text.split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ re.lastIndex = 0;
+ if (re.test(lines[i])) {
+ matches.push(rel + ':' + (i + 1) + ':' + lines[i]);
+ if (matches.length >= 200) break;
+ }
+ }
+ if (matches.length >= 200) break;
+ }
+ const offset = args.offset || 0;
+ const page = matches.slice(offset, offset + 20);
+ if (page.length === 0) return '没有匹配';
+ return page.join('\n') + '\n(共 ' + matches.length + ' 处匹配' + (offset + 20 < matches.length ? ',用 offset=' + (offset + 20) + ' 看下一页' : '') + ')';
+}
+
+// terminal:spawn + 进程组 kill + 超时 + 输出截断
+async function toolTerminal(ctx, args) {
+ const cfg = ctx.cfg;
+ const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
+ const maxChars = cfg.terminal.max_output_chars;
+ let cwd = ctx.taskDir;
+ if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd);
+ if (!fs.existsSync(cwd)) throw new Error('cd 目录不存在:' + args.cd);
+
+ return new Promise((resolve) => {
+ const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
+ ctx.run.procs.add(child);
+ let out = '';
+ let killedBy = null; // 'timeout' | 'cancelled'
+ let settled = false;
+
+ const timer = setTimeout(() => {
+ killedBy = 'timeout';
+ killGroup(child);
+ }, timeout);
+
+ const onData = (d) => { out += d.toString(); };
+ child.stdout.on('data', onData);
+ child.stderr.on('data', onData);
+
+ const finish = (code, extra) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ clearInterval(cancelCheck);
+ ctx.run.procs.delete(child);
+ let text = out;
+ if (killedBy === 'timeout') text += '\n(命令超时 ' + timeout + 'ms,已终止)';
+ if (killedBy === 'cancelled') text += '\n(用户终止任务,进程被 kill)';
+ if (extra) text += '\n' + extra;
+ text += '\n[exit code: ' + code + ']';
+ resolve(truncate(text || '(无输出)', maxChars));
+ };
+ child.on('error', err => finish(-1, 'spawn 失败:' + err.message));
+ child.on('close', code => finish(killedBy ? -1 : (code === null ? -1 : code)));
+
+ const cancelCheck = setInterval(() => {
+ if (ctx.run.cancelled) { killedBy = 'cancelled'; killGroup(child); }
+ }, 200);
+ });
+}
+
+function killGroup(child) {
+ if (!child.pid) return;
+ try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
+ try { child.kill('SIGKILL'); } catch (__) {}
+ }
+}
+
+// fetch:抓取并粗略转 Markdown
+async function toolFetch(ctx, args) {
+ if (ctx.run.cancelled) throw new Error('已终止');
+ const url = args.url;
+ if (!/^https?:\/\//i.test(url)) throw new Error('只支持 http/https URL');
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 30000);
+ let res;
+ try {
+ res = await fetch(url, {
+ signal: ctrl.signal,
+ redirect: 'follow',
+ headers: { 'User-Agent': 'Mozilla/5.0 (agent-app)' },
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ const text = await res.text();
+ const ct = (res.headers.get('content-type') || '').toLowerCase();
+ let body;
+ if (ct.includes('html')) body = htmlToMarkdown(text);
+ else if (ct.includes('json') || ct.includes('text') || ct.includes('xml') || ct.includes('markdown')) body = text;
+ else return '[非文本响应] HTTP ' + res.status + ' content-type=' + ct + ',' + text.length + ' 字节';
+ if (text.length > 1024 * 1024) body += '\n(响应过大,已截断)';
+ return 'HTTP ' + res.status + '\n' + truncate(body, 1024 * 1024);
+}
+
+function htmlToMarkdown(html) {
+ let s = html
+ .replace(/<(script|style|noscript|svg|head)[\s\S]*?<\/\1>/gi, '')
+ .replace(//g, '');
+ s = s
+ .replace(/]*>([\s\S]*?)<\/h\1>/gi, (m, lv, t) => '\n' + '#'.repeat(Number(lv)) + ' ' + strip(t).trim() + '\n')
+ .replace(/