diff --git a/app/server/config.js b/app/server/config.js index a4df752..0401853 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -92,13 +92,16 @@ const DEFAULTS = { // 模型平台池(无默认值,结构见 config.example.yml)。 platforms: [], // 全局工具黑名单:profile 未配 tools_deny 时继承它;allow 先、deny 后叠加(deny 赢,与 mcp_servers 同构)。 - // 默认屏蔽元工具 lab:它只该出现在显式清空 deny 的 profile 里,不进任何常规请求的 tools 数组。 - tools_deny: ['lab'], + // 默认屏蔽元工具 lab 与阶段出口 handoff:它们只该出现在显式清空 deny 的 profile 里, + // 不进任何常规请求的 tools 数组(lab → lab 组合;handoff → advising 组合)。 + tools_deny: ['lab', 'handoff'], // 模型 profile(prompt + tools 名单组合):platforms 里的模型用 profile: <名> 引用。 model_profiles: { // advising:顾问阶段(sessions.phase)专用组合——不由模型配置引用,而是 resolveProfileName 在 - // advising 时强制命中:只留问答/调研/写任务书所需工具(terminal 不进名单),配专用顾问提示词模板。 - advising: { tools_allow: ['read_file', 'fetch', 'write_file'], system_prompt_file: 'advising-system.txt' }, + // advising 时强制命中:顾问只聊和读、不写(write_file 已移除,批内幻觉调用另由引擎挡下), + // 唯一出口是 handoff;tools_deny 必须显式清空:不配 = 继承全局 ['lab','handoff'], + // allow 滤完再叠 deny 会把 handoff 自己禁掉(同 lab 组合的教训)。 + advising: { tools_allow: ['read_file', 'fetch', 'handoff'], tools_deny: [], system_prompt_file: 'advising-system.txt' }, // lab:统一入口元工具自测组合——tools 收缩到 1 个,其余能力经 lab(help) 现场发现。 // tools_deny 必须显式清空:不配 = 继承全局 ['lab'],deny 后叠加会把 lab 自己禁掉 → 零工具。 lab: { tools_allow: ['lab'], tools_deny: [], system_prompt_file: 'lab-system.txt' }, diff --git a/app/server/engine.js b/app/server/engine.js index 31260e6..7b2052c 100644 --- a/app/server/engine.js +++ b/app/server/engine.js @@ -275,20 +275,10 @@ function effectiveTools(profileName) { // ---------- 阶段(sessions.phase:advising 顾问 / executing 执行) ---------- // advising:新建会话与「清空」的落点。profile 被 resolveProfileName 强制为 'advising', -// 只问答/判意图/引导澄清;唯一出口是 write_file/edit_file 把任务书 task.md 落在任务目录根(正门判定)。 +// 只聊和读不写(write_file/edit_file 不在其 schema,批内幻觉调用也在 runLoopInner 挡下); +// 唯一出口 = handoff 工具成功返回(brief 由 handler 落盘任务目录根 task.md,见 tools/executor.js)。 // executing:一路走到底,只有清空才回 advising;压缩不碰 phase(压完仍回原模式)。 -// 写类工具(write_file/edit_file)的参数是否恰好落在任务目录根的 task.md——阶段切换的正门判定。 -// resolveInTask 统一解相对/绝对路径并拦越界;子目录 task.md 不算。 -// 不扫文件存在性:用户随时上传同名素材不算承诺,只有 AI 亲自写一次才算(上传也永远覆盖不了 -// task.md:files.js 同名自动加后缀)。 -function argsHitTaskBrief(taskDir, args) { - try { - const abs = path.resolve(resolveInTask(taskDir, String((args && args.path) || ''))); - return abs === path.resolve(taskDir, 'task.md'); - } catch (_) { return false; } -} - // advising → executing:任务书落地,当场重建上下文—— // 全部历史标 archived(UI 照常展示、不再发模型,与压缩/定时投递同机制), // 插一条 type='task_brief' 的 user 行(内容 = 此刻 task.md 磁盘快照,非引用:后续文件怎么改都不动锚点) @@ -313,9 +303,9 @@ function enterExecuting(sessionId) { ).run(sessionId).changes; saveMessage(sessionId, { role: 'user', type: 'task_brief', - content: '【任务书】需求澄清完毕,会话已进入执行模式。以下任务书快照(task.md)是唯一目标依据;' - + '之前的顾问对话已存档、不再发送。执行中可修订 task.md(以文件现状为准);' - + '上一轮任务书归档在 .task-history/,仅限用户明确要求时查阅。\n\n' + snapshot, + content: '【任务书】顾问阶段结束,会话已进入执行模式。以下任务书快照(task.md)是唯一目标依据;' + + '之前的顾问对话已存档、不再发送。若正文列有 Missing/未澄清事项,先向用户提问确认再动手;' + + '执行中可修订 task.md(以文件现状为准);上一轮任务书归档在 .task-history/,仅限用户明确要求时查阅。\n\n' + snapshot, }); db.prepare("UPDATE sessions SET phase='executing', updated_at=? WHERE id=?").run(now(), sessionId); bus.emit(sessionId, 'phase', { phase: 'executing' }); @@ -763,7 +753,7 @@ async function runLoopInner(sessionId, run) { // 执行工具 const vision = modelVision(session); - let taskBriefWritten = false; // 本批工具里是否有「正门落 task.md」(批量跑完统一切换,见循环尾注释) + let handoffDone = false; // 本批工具里是否有 handoff 成功返回(批量跑完统一切换,见循环尾注释) for (const tc of msgRow.tool_calls) { if (run.cancelled) break; const id = tc.id; @@ -777,6 +767,12 @@ async function runLoopInner(sessionId, run) { // 把正确形状告诉模型,替它纠正包装习惯 output = chk.error; isError = true; + } else if (session.phase === 'advising' + && (tc.function.name === 'write_file' || tc.function.name === 'edit_file')) { + // 顾问单入口硬约束:写类工具不在其 schema,但「名单外照跑」是全局策略(executeTool 全表), + // 幻觉调用会真写文件、绕过出口制造假承诺——阶段契约优先,挡下并指向 handoff。 + output = 'Error: 顾问阶段不能写文件。任务书请通过 handoff 工具的 brief 参数提交。'; + isError = true; } else { try { output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db, vision }, @@ -816,15 +812,14 @@ async function runLoopInner(sessionId, run) { image_url: imageRel ? '/api/sessions/' + encodeURIComponent(sessionId) + '/files/download?path=' + encodeURIComponent(imageRel) : undefined, msg_id: toolMsgId, }); - // 阶段切换正门:advising 回合里 write_file/edit_file 成功且路径恰为根 task.md → 标记待切换。 + // 阶段切换入口:advising 回合里 handoff 成功返回(brief 已由 handler 落盘 task.md)→ 标记待切换。 // 不在这里就地切:同批可能还有其它 tool_calls,其父 assistant 行若先被存档、 // 后落库的回执就成了无主孤儿行(上游拒收)——整批跑完再统一重建上下文。 - if (!isError && (tc.function.name === 'write_file' || tc.function.name === 'edit_file') - && argsHitTaskBrief(taskDirOf(sessionId), chk.args)) { - taskBriefWritten = true; + if (!isError && tc.function.name === 'handoff') { + handoffDone = true; } } - if (taskBriefWritten) enterExecuting(sessionId); + if (handoffDone) enterExecuting(sessionId); iter++; } if (iter >= maxIter && !run.cancelled) { diff --git a/app/server/templates/advising-system.txt b/app/server/templates/advising-system.txt index 403e47b..21b2b57 100644 --- a/app/server/templates/advising-system.txt +++ b/app/server/templates/advising-system.txt @@ -19,23 +19,30 @@ unless stated otherwise. three clarification rounds, or as soon as the picture is clear enough, stop asking and produce the task brief. -## Producing the task brief (task.md) +## Producing the task brief (handoff) -When the requirement is clear, write the task brief to `task.md` — that exact -filename, at the root of the working directory — with the `write_file` tool. -This is the ONLY way work starts here: as soon as the file lands, the system -automatically switches this session into execution mode and a full-capability -agent continues from the file alone. Therefore: +When work should start — the requirement is clear, or the user explicitly asks +to skip planning, or clarification has visibly stalled — call the `handoff` +tool with a `reason` and the full `brief`. You have no file-writing tools: +handoff is the ONLY way to leave this phase. The system writes your `brief` +verbatim to `task.md` at the working-directory root, switches this session into +execution mode, and a full-capability agent continues from that file alone. +Therefore: -- The file must be self-contained: someone who has never seen this chat must be - able to do the job from it. For very small requests a three-line brief is - fine; never inflate it. -- Always use `write_file` (one shot). Never create it via other means, and - never treat an uploaded file named task.md as the brief — writing it - yourself is the commitment. +- The brief must be self-contained: someone who has never seen this chat must be + able to do the job from it alone. For very small requests a three-line brief + is fine; never inflate it. - Suggested structure (trim or extend as fits): short title / Goal / Scope & constraints / What the deliverable must contain / Acceptance criteria / Assumptions picked. +- If planning was skipped or key facts are still missing, keep the brief + minimal: state the goal in the user's own words and list every unknown under a + "Missing" section instead of guessing or writing generic advice. The executor + will ask the user for these directly. Do not turn a skipped-planning brief + into a methodology document. +- Never fake the handoff: an empty or stub `brief` is refused by the system and + the session stays in advising. An uploaded file named task.md is never the + brief — only your handoff call commits. ## What you must not do diff --git a/app/server/tools/definitions.json b/app/server/tools/definitions.json index ffcb5e8..b636df0 100644 --- a/app/server/tools/definitions.json +++ b/app/server/tools/definitions.json @@ -6,11 +6,19 @@ "description": "Execute operations on the session's SQLite database (data.db in the session working directory). The database file is isolated per session and auto-created on first use. For inserting rows (especially batches), prefer op=insert which avoids writing SQL by hand; use exec/query for DDL, updates, deletes and complex SQL.", "parameters": { "type": "object", - "required": ["op"], + "required": [ + "op" + ], "properties": { "op": { "type": "string", - "enum": ["exec", "query", "insert", "tables", "schema"], + "enum": [ + "exec", + "query", + "insert", + "tables", + "schema" + ], "description": "Operation type:\n- exec: run a write statement (CREATE / UPDATE / DELETE / ALTER / DROP), in a transaction\n- query: run a read statement (SELECT), returns an array of rows\n- insert: insert one or more rows from row objects (structured, no SQL needed, one transaction)\n- tables: list all tables with row counts\n- schema: show column definitions for a table" }, "sql": { @@ -29,7 +37,9 @@ "rows": { "type": "array", "description": "Array of row objects for op=insert. Each object maps column names to values; all objects must have the same keys.", - "items": { "type": "object" } + "items": { + "type": "object" + } } } } @@ -42,7 +52,10 @@ "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\nWhen copying text from `read_file` output into `old_text` or `new_text`, strip the line-number prefix and the tab after it, and keep the original indentation exactly.\n\nMatching rules:\n- `old_text` is first matched exactly. If there is no exact match, a fuzzy match tolerating minor whitespace and formatting differences is attempted.\n- If `old_text` matches more than one location (overlapping matches count as separate locations), the edit fails. Include enough surrounding context to make it unique; avoid very short or repetitive `old_text`.\n- If no match is found at all, the edit fails. For very large files the fuzzy stage degrades to per-line whitespace-insensitive exact matching; the error message says so — do not retry the same text, locate with `read_file` by line numbers or use `terminal` with sed.\n\nTo delete whole lines, put the exact line(s) in `old_text` and set `new_text` to an empty string — matched whole lines are removed cleanly together with their line endings (a trailing newline in `old_text` makes no difference).\n\nEdits are applied in order. If one edit fails, the edits before it are already written to disk and the file has changed: the error message tells you how many were applied. You must call `read_file` again before retrying; do not reuse the previous `old_text` values.", "parameters": { "type": "object", - "required": ["path", "edits"], + "required": [ + "path", + "edits" + ], "properties": { "path": { "type": "string", @@ -53,7 +66,10 @@ "description": "List of edit operations to apply sequentially. Each edit finds `old_text` in the file and replaces it with `new_text`. If any edit fails, the edits before it remain applied.", "items": { "type": "object", - "required": ["old_text", "new_text"], + "required": [ + "old_text", + "new_text" + ], "properties": { "old_text": { "type": "string", @@ -77,7 +93,9 @@ "description": "Fetches a URL and returns its content as Markdown. Only http and https are supported; if the scheme is omitted, https is assumed.\n\nHTML pages are converted to Markdown. JSON, XML, plain text, and Markdown responses are returned as-is. Binary responses are not returned — only their HTTP status, content-type, and size.\n\nThe response always starts with a line `HTTP `, followed by the body. Check the status line: a non-2xx status means the fetch did not succeed, even if body content is present.\n\nRequests are subject to a timeout, and oversized responses are truncated. Redirects are followed automatically.", "parameters": { "type": "object", - "required": ["url"], + "required": [ + "url" + ], "properties": { "url": { "type": "string", @@ -87,6 +105,58 @@ } } }, + { + "type": "function", + "function": { + "name": "handoff", + "description": "Hand off from the advising phase to the execution phase. Call this when the task brief is ready. The system will write your `brief` to task.md and switch to execution. There are three cases:\n\n- ready: The requirement is clear enough to execute.\n- user_skip: The user explicitly asks to skip planning (\"just do it\", \"别问了\", \"换个 agent\", \"直接开始\", or similar). Do not call this on tone or mood alone — only on explicit signals.\n- user_stuck: You have asked 2-3 rounds and the user is still not providing key information, and they seem to want to move on.\n\nWhen reason is not \"ready\", pass the user's own words as `brief` and leave it at that. Do not invent a methodology or generic plan. The executor will ask the user for missing information directly.", + "parameters": { + "type": "object", + "required": [ + "reason", + "brief" + ], + "properties": { + "reason": { + "type": "string", + "enum": [ + "ready", + "user_skip", + "user_stuck" + ], + "description": "Why the handoff is happening." + }, + "brief": { + "type": "string", + "description": "The task brief content, in Markdown. This is written to task.md verbatim. Follow the structure described in your system prompt." + } + } + } + } + }, + { + "type": "function", + "function": { + "name": "lab", + "description": "Unified entry point for calling any available tool by name.\n\nCall a tool:\n lab(tool: \"\", args: {})\n\nThe target tool's arguments go inside `args` as a JSON object. Omit `args` for tools that take no arguments.\n\nDiscovering tools:\n lab(tool: \"help\") → list all tools with a one-line description each\n lab(tool: \"help\", args: {tool: \"\"}) → full description and parameter schema of \n\nAn unknown tool name also returns the list of available tools.\nNested lab calls are rejected; inner tool errors surface unchanged.\n\nCalling a tool directly and calling it through lab are equivalent. When the tool you need is already in your tool list, call it directly. Use lab to discover or reach tools that are not in the current list.", + "parameters": { + "type": "object", + "required": [ + "tool" + ], + "properties": { + "tool": { + "type": "string", + "description": "Name of the tool to call, or \"help\"." + }, + "args": { + "type": "object", + "description": "Arguments for the target tool, matching its own schema (look it up with lab(tool: \"help\", args: {tool: \"\"}) if unsure). Omit for tools that take no arguments." + } + } + } + } + }, { "type": "function", "function": { @@ -94,7 +164,9 @@ "description": "Create a short-lived, publicly reachable URL for a local file, so an external service that cannot authenticate can download it.\nUse this when another tool or API needs to fetch a local file by URL. Returns the URL as plain text on a single line.", "parameters": { "type": "object", - "required": ["path"], + "required": [ + "path" + ], "properties": { "path": { "type": "string", @@ -111,7 +183,9 @@ "description": "Reads the content of a file.\n\nText files: each returned line is prefixed with a line number right-aligned in a 6-character field, followed by a tab, then the line content.\n\nLarge text files (roughly over 16 KB) are not returned in full: you get an outline listing top-level symbols (or Markdown headings) with line numbers instead. The outline IS a successful response — do NOT retry the same call without a line range; use the outline line numbers with `start_line` / `end_line` to read specific sections. If no outline can be extracted, a first-1KB excerpt is returned instead. Supplying `start_line` or `end_line` disables outline mode.\n\nImage files (PNG, JPEG, WebP, GIF, BMP, TIFF) are returned as visual content you can analyze directly, but only if the current model supports vision; otherwise a text placeholder is returned — that placeholder is not an error. Very large images (roughly over 50 MB) are skipped, and images may be downscaled (long edge ~2000 px, re-encoded as JPEG) before being returned.\n\nBinary files are not returned as text; a short notice is returned instead. Text files over 32 MB cannot be read by this tool — use `terminal` (grep -n / head / sed -n).", "parameters": { "type": "object", - "required": ["path"], + "required": [ + "path" + ], "properties": { "path": { "type": "string", @@ -142,11 +216,18 @@ "description": "Manage the recurring scheduled task bound to the CURRENT session. At most one task per session; it is deleted together with the session. At each trigger, the prompt is sent to this session as a new user message. Schedule times are interpreted in Asia/Shanghai (UTC+8). Call this ONLY when the user explicitly asks for something to run periodically or at a specific time.\n\nop=get No arguments.\nop=create Requires cron_expr and prompt.\nop=update Requires at least one of cron_expr, prompt; only the given fields change.\nop=delete No arguments.", "parameters": { "type": "object", - "required": ["op"], + "required": [ + "op" + ], "properties": { "op": { "type": "string", - "enum": ["get", "create", "update", "delete"], + "enum": [ + "get", + "create", + "update", + "delete" + ], "description": "Operation to perform on the current session's scheduled task." }, "cron_expr": { @@ -161,6 +242,38 @@ } } }, + { + "type": "function", + "function": { + "name": "skill", + "description": "Use the skills installed on this server. A skill is a directory under the skill root whose SKILL.md defines its purpose and input_schema.\n\nop=list No arguments.\nop=get Requires name.\nop=run Requires name; input_args optional (default {}).\n\nop=list: lists all installed skills with a one-line description each, read live from the skill root; use it to choose among skills or to confirm what is installed. An empty skill set returns an empty list — that is not an error.\nop=get: returns the full raw SKILL.md (front matter included): purpose, input_schema, and usage notes. Call it before op=run with a skill you have not used in this conversation. A nonexistent skill returns an error.\nop=run: executes the skill with input_args validated against its input_schema (a validation error names the missing fields). The entry script receives a JSON string as its only CLI argument, so input_args must be a JSON object.\n- Returns the skill's combined stdout+stderr as plain text after it exits; exit 0 with no output yields '(无输出)'. A non-zero exit raises an error containing the output and [exit code: N].\n- Direct output files via arguments: relative paths in arguments are resolved against the session working directory; do not rely on the skill's cwd.\n- Default timeout 120 seconds: the process group is killed and the error includes partial output collected so far (a timeout is not a skill failure).", + "parameters": { + "type": "object", + "required": [ + "op" + ], + "properties": { + "op": { + "type": "string", + "enum": [ + "list", + "get", + "run" + ], + "description": "Operation to perform on skills." + }, + "name": { + "type": "string", + "description": "Name of the skill (subdirectory name under the skill root directory). Required with op=get and op=run." + }, + "input_args": { + "type": "object", + "description": "Dictionary of input arguments for the skill. Keys and values should match the skill's input_schema (call op=get first if unsure). Example: {\"input\": \"file.md\", \"output\": \"out.pdf\"}. Used only with op=run; omit it for skills that take no arguments." + } + } + } + } + }, { "type": "function", "function": { @@ -168,7 +281,9 @@ "description": "Executes a shell one-liner and returns combined stdout/stderr output.\n\n- Run commands relative to the session working directory. Use the `cd` parameter to specify a different directory if needed.\n- Do not use shell substitutions or interpolations (e.g., `$VAR`, `${VAR}`, `$(...)`, backticks). Resolve values yourself first.\n- Do not pipe output to `head` or `tail`; use the `head_lines` and `tail_lines` parameters to limit what is returned while keeping full output visible to the user.\n- Avoid commands that run indefinitely (servers, watchers). For long-running commands, set `timeout_ms`.\n- Each invocation starts a new shell; do not rely on state from previous calls.\n- If a command may open a pager or editor, disable it using environment variables (e.g., `GIT_PAGER=cat`, `EDITOR=true`).", "parameters": { "type": "object", - "required": ["command"], + "required": [ + "command" + ], "properties": { "command": { "type": "string", @@ -210,7 +325,10 @@ "description": "Creates a new file or overwrites an existing file with the given content.\n\nParent directories are created automatically, so the path does not need to exist beforehand.\n\nOverwriting replaces the file's entire content irreversibly. If the file already exists, read it first, or use `edit_file` for targeted changes instead.\n\nText is written as UTF-8. To produce binary files, use `terminal` instead.", "parameters": { "type": "object", - "required": ["path", "content"], + "required": [ + "path", + "content" + ], "properties": { "path": { "type": "string", @@ -223,51 +341,5 @@ } } } - }, - { - "type": "function", - "function": { - "name": "skill", - "description": "Use the skills installed on this server. A skill is a directory under the skill root whose SKILL.md defines its purpose and input_schema.\n\nop=list No arguments.\nop=get Requires name.\nop=run Requires name; input_args optional (default {}).\n\nop=list: lists all installed skills with a one-line description each, read live from the skill root; use it to choose among skills or to confirm what is installed. An empty skill set returns an empty list — that is not an error.\nop=get: returns the full raw SKILL.md (front matter included): purpose, input_schema, and usage notes. Call it before op=run with a skill you have not used in this conversation. A nonexistent skill returns an error.\nop=run: executes the skill with input_args validated against its input_schema (a validation error names the missing fields). The entry script receives a JSON string as its only CLI argument, so input_args must be a JSON object.\n- Returns the skill's combined stdout+stderr as plain text after it exits; exit 0 with no output yields '(无输出)'. A non-zero exit raises an error containing the output and [exit code: N].\n- Direct output files via arguments: relative paths in arguments are resolved against the session working directory; do not rely on the skill's cwd.\n- Default timeout 120 seconds: the process group is killed and the error includes partial output collected so far (a timeout is not a skill failure).", - "parameters": { - "type": "object", - "required": ["op"], - "properties": { - "op": { - "type": "string", - "enum": ["list", "get", "run"], - "description": "Operation to perform on skills." - }, - "name": { - "type": "string", - "description": "Name of the skill (subdirectory name under the skill root directory). Required with op=get and op=run." - }, - "input_args": { - "type": "object", - "description": "Dictionary of input arguments for the skill. Keys and values should match the skill's input_schema (call op=get first if unsure). Example: {\"input\": \"file.md\", \"output\": \"out.pdf\"}. Used only with op=run; omit it for skills that take no arguments." - } - } - } - } - }, - { - "type": "function", - "function": { - "name": "lab", - "description": "Unified entry point for calling any available tool by name.\n\nCall a tool:\n lab(tool: \"\", args: {})\n\nThe target tool's arguments go inside `args` as a JSON object. Omit `args` for tools that take no arguments.\n\nDiscovering tools:\n lab(tool: \"help\") → list all tools with a one-line description each\n lab(tool: \"help\", args: {tool: \"\"}) → full description and parameter schema of \n\nAn unknown tool name also returns the list of available tools.\nNested lab calls are rejected; inner tool errors surface unchanged.\n\nCalling a tool directly and calling it through lab are equivalent. When the tool you need is already in your tool list, call it directly. Use lab to discover or reach tools that are not in the current list.", "parameters": { - "type": "object", - "required": ["tool"], - "properties": { - "tool": { - "type": "string", - "description": "Name of the tool to call, or \"help\"." - }, - "args": { - "type": "object", - "description": "Arguments for the target tool, matching its own schema (look it up with lab(tool: \"help\", args: {tool: \"\"}) if unsure). Omit for tools that take no arguments." - } - } - } - } } ] diff --git a/app/server/tools/executor.js b/app/server/tools/executor.js index da1905d..e4d5b5e 100644 --- a/app/server/tools/executor.js +++ b/app/server/tools/executor.js @@ -1118,8 +1118,29 @@ function runLabHelp(args) { return JSON.stringify(def.function, null, 2); } +// handoff:顾问阶段唯一出口(advising 组合见 config.js)。brief 原样落盘任务目录根 task.md; +// 切换不在此发生——executeTool 只落盘与回执,runLoopInner 在工具批尾接成功回执触发 enterExecuting +//(其读盘取快照作锚点,幂等防重切)。phase 守卫不可省:「名单外工具照跑」是全局策略, +// 执行期幻觉调用不得覆写修订中的 task.md;reason 枚举与 brief 非空也在此兑底(checkToolArgs 只查必填键)。 +async function toolHandoff(ctx, args) { + const sess = ctx.db.prepare('SELECT phase FROM sessions WHERE id = ?').get(ctx.sessionId); + if (!sess || sess.phase !== 'advising') return 'Error: 当前不在顾问阶段,handoff 仅在 advising 可用'; + const reason = String((args && args.reason) || ''); + if (['ready', 'user_skip', 'user_stuck'].indexOf(reason) < 0) { + return 'Error: reason 需为 ready / user_skip / user_stuck 之一'; + } + const brief = typeof args.brief === 'string' ? args.brief : ''; + if (!brief.trim()) return 'Error: brief 不能为空,任务书需完整带上(user_skip/user_stuck 至少含用户原话与 Missing 清单)'; + const abs = path.join(ctx.taskDir, 'task.md'); + await fsp.writeFile(abs, brief, 'utf8'); + recordFile(ctx, abs); // 同步 files 元数据表(与 write_file 同轨,任务目录列表/清理逻辑一致) + // 同批多次 handoff:后写覆盖(last-wins),批尾的切换只发生一次(enterExecuting 幂等)。 + return '任务书已写入 task.md(reason: ' + reason + '),本批工具跑完后系统将切换到执行模式。请在给用户的回复里带一句「已切换到执行阶段」。'; +} + const HANDLERS = { read_file: toolReadFile, + handoff: toolHandoff, write_file: toolWriteFile, edit_file: toolEditFile, mint_public_link: toolMintPublicLink, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 34e424a..92cfbc6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -220,12 +220,14 @@ stateDiagram-v2 ```mermaid stateDiagram-v2 [*] --> advising: createSession - advising --> executing: write_file/edit_file 落根目录 task.md(enterExecuting,同回合继续开工) + advising --> executing: handoff 工具(handler 落盘 task.md → enterExecuting,同回合继续开工) executing --> advising: clearSessionMessages(旧 task.md mv 进 .task-history/) ``` - advising(顾问):profile 被 `resolveProfileName` 强制为内置 `advising` 组合(问答/判意图/引导澄清需求), - 唯一出口是 AI 用 `write_file` 把任务书写到任务目录根的 `task.md`(正门判定,上传/terminal 间接创建不算)。 + 只聊和读不写(`write_file`/`edit_file` 不在其白名单,批内幻觉调用也被 runLoopInner 挡下); + 唯一出口是 `handoff` 工具:handler 把 `brief` 原样落盘根 `task.md`(reason ∈ ready/user_skip/user_stuck, + 空 brief 拒回不切);`handoff` 与 `lab` 同入全局 `tools_deny`,advising 组合显式 `tools_deny: []` 独享可见。 - executing(执行):回到常规 profile 链路(模型配置 > 默认全量);单会话只解决一个问题,一路走到底,回头路只有「清空」。 - 上下文压缩对 phase 中性(原来什么模式、压完仍什么模式);定时任务投递前强制 `executing`(无人值守不能被顾问话术卡住)。 - 切换瞬间全史标 `archived`、插一条 `type='task_brief'` user 行(task.md 磁盘快照)作执行阶段唯一上下文起点; @@ -234,7 +236,7 @@ stateDiagram-v2 ### 4.2 文件布局 -**任务目录**(`cfg.workspace_root//`):每个会话一个目录;Core 与 Executor 都可读写;sh 命令默认 cwd 即此目录。`task.md` = 当前轮任务书(phase 切换触发,仅 `write_file` 正门);`.task-history/` = 清空会话时旧任务书归档(点目录,文件列表默认隐藏,同 `.imgcache` 约定)。 +**任务目录**(`cfg.workspace_root//`):每个会话一个目录;Core 与 Executor 都可读写;sh 命令默认 cwd 即此目录。`task.md` = 当前轮任务书(由 `handoff` handler 落盘,phase 切换唯一入口);`.task-history/` = 清空会话时旧任务书归档(点目录,文件列表默认隐藏,同 `.imgcache` 约定)。 **技能目录**(`cfg.skills_root//`):所有会话共享;`deps/` 子目录是 pip `--target` 共享的 Python 依赖(只放镜像缺失的包,镜像已带的不重复装),**与技能目录同级**(不是技能子目录)。`RESERVED_DIRS = {deps}` 在 `routes/skills.js` 里被排除以免被当成技能。 @@ -257,7 +259,7 @@ stateDiagram-v2 | `createSession` | 生成 id(`task-YYYYMMDD-NNN`,序号从历史 + `meta.task_seq` 取大)→ mkdir 任务目录 → phase 默认 advising → 决定立即绑/入队 | | `postUserMessage` | 用户消息入口;识别 active/held/queued 路径并决定是 `delivered:'live'` 还是 `'queued'` | | `summarizeContext` / `clearSessionMessages` / `deleteMessage` | 收尾 + 上下文压缩(清空同时把 phase 打回 advising 并归档旧 task.md) | -| `enterExecuting` / `argsHitTaskBrief` / `archiveTaskBrief` | 阶段切换:正门判定(根 task.md)→ 全史存档 + 插 task_brief 快照 + phase='executing' + SSE 广播;清空时旧 task.md mv 进 `.task-history/` | +| `enterExecuting` / `archiveTaskBrief` | 阶段切换:批尾接 `handoff` 成功标记(brief 已由 handler 落盘)→ 全史存档 + 插 task_brief 快照 + phase='executing' + SSE 广播;清空时旧 task.md mv 进 `.task-history/` | | `checkToolArgs` / `unwrapToolArgs` | 工具参数校验 + 部分弱模型参数包裹外层自动解包 | | `ensureSessionContext` | 注入/刷新"会话上下文"首条 user 消息(日期/任务目录/模型名/vision 能力) | @@ -269,8 +271,8 @@ stateDiagram-v2 - **archived/summary 机制**(上下文压缩):`type='archived'` 的消息 UI 照常展示但不再发模型;`type='summary'` 是压缩后的"上下文起点"。压缩回合**不插入任何指令消息**:由 `engine.summarizeContext` 在内存 run 上标 `summarizing`,`runLoopInner` 据此走 `llm.compressMessages`:沿用默认 system prompt + 正常历史 messages,末尾追加一条 user(`server/templates/compress-prompt.txt` 原文,参考标题回合的拼法),且不传 tools;回合内首条无 tool_calls 的收尾回复即摘要。(`llm.buildMessages` 仍保留旧库 `summarize_request` 行的处理,仅为历史数据兼容。) - **图片(多模态)**:`messages.content` 列是 TEXT,含图时存 `{"__blocks__":[content...]}` 哨兵 JSON。新版 `read_file` 读图:sharp 压缩产物落任务目录 `.imgcache/`(前端文件列表隐带点的项),库里只存 `image_ref` 轻量块;`buildMessages` 发送前经调用方传入的 `mintUrl` 回调现签成公网外链(同 `mint_public_link` 那套 `GET /p/`)填入 `image_url` 块,base64 不进 DB 也不进请求体;签不到降级为文字占位。旧库/用户粘贴附件的 `data:` URL 块原样透传。图块**只保留最后一条 assistant 之后的**(`lastAssistant` 判定),之前的换成"已省略"文字描述;UI 渲染走带 cookie 的会话内下载路由,历史永不裂图。 - **保持租约**(`holdSweeper`):sweeper_ms 巡检(默认 10s);held 会话无观看者 idle_release_ms 释放(默认 3 分钟),有观看者 active_max_ms 强制释放(默认 30 分钟)。active 闲置(绑了模型但无 run 在跑、无未回应消息)按相同租约处理。 -- **task_brief(任务书锚点,advising→executing 切换)**:runLoopInner 工具批跑完后,若 advising 回合内有 `write_file`/`edit_file` 成功落在任务目录根 `task.md`(`argsHitTaskBrief` 正门判定;批量末尾统一切,防父 assistant 先存档、后落库回执成孤儿行被上游拒收),`enterExecuting` 当场重建上下文:全史标 `archived` → 插一条 `type='task_brief'` user 行(内容 = task.md 磁盘快照,非引用)→ phase='executing' + SSE `phase`/`status` 事件;下一迭代重读历史 + 重解 profile,天然切默认组合、同回合开工。压缩不碰 phase(task_brief 与其它历史一样会被后续压缩存档,漂移可控:压缩本就由用户主导)。 -- **profile(prompt+tools 组合)**:顶层 `model_profiles` 定义多套组合,`platforms[].models[].profile` 引用(见 §5.8)——这是唯一的引用来源:运行期手动切换已全部移除(消息级 profile 参数、`sessions.profile` 会话绑定均废弃,列保留不读写);`advising` 例外,不走引用、由 phase 强制命中。名单外工具被调用不拦(`checkToolArgs` 查不到 def 不报错,`executeTool` 全表照跑);tools schema 只活在请求体不进历史,所以切换不脏化旧消息。压缩回合同样跟随(小模型会话点压缩不会回退到默认大模板)。 +- **task_brief(任务书锚点,advising→executing 切换)**:runLoopInner 工具批跑完后,若 advising 回合内有 `handoff` 成功返回(brief 已由 handler 原样落盘根 task.md 并记 files 表;批量末尾统一切,防父 assistant 先存档、后落库回执成孤儿行被上游拒收;同批多次 handoff 后写覆盖 last-wins),`enterExecuting` 当场重建上下文:全史标 `archived` → 插一条 `type='task_brief'` user 行(内容 = task.md 磁盘快照,非引用)→ phase='executing' + SSE `phase`/`status` 事件;下一迭代重读历史 + 重解 profile,天然切默认组合、同回合开工。压缩不碰 phase(task_brief 与其它历史一样会被后续压缩存档,漂移可控:压缩本就由用户主导)。 +- **profile(prompt+tools 组合)**:顶层 `model_profiles` 定义多套组合,`platforms[].models[].profile` 引用(见 §5.8)——这是唯一的引用来源:运行期手动切换已全部移除(消息级 profile 参数、`sessions.profile` 会话绑定均废弃,列保留不读写);`advising` 例外,不走引用、由 phase 强制命中。名单外工具被调用不拦(`checkToolArgs` 查不到 def 不报错,`executeTool` 全表照跑),但阶段契约类例外:advising 内 `write_file`/`edit_file` 在批内挡下、`handoff` 在 handler 里带 phase 守卫;tools schema 只活在请求体不进历史,所以切换不脏化旧消息。压缩回合同样跟随(小模型会话点压缩不会回退到默认大模板)。 ### 5.2 `llm.js` —— 上游调用