Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Add edit_file tool (in-place old_string -> new_string replacement)

claw234be05a4651c
diff --git a/CLAUDE.md b/CLAUDE.md
index ffbc531e..5d376235 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -182,9 +182,9 @@ Stored at `<uid>/cloud/chat_attachments/<cid>/<file>`, **zero pre-processing**;
### Local execution tools
-`bash / write_file / markdown_to_pdf / html_to_pdf / generate_image` share the `localExec.granted` permission gate (grant/revoke from the settings page, re-read on every `execute()` so it takes effect mid-conversation); unauthorized → `isError=true`. `web_search` goes through `searchProfiles[0]` → paid API → fallback built-in. Outputs are collected via `ChatOptions.onFileWritten`; the renderer shows green chips → IPC `workspace.revealPath` (strictly validated to stay inside the workspace). See `model/core-agent/{local-tools, image-gen-tool, search-tools}.ts`.
+`bash / write_file / edit_file / markdown_to_pdf / html_to_pdf / generate_image` share the `localExec.granted` permission gate (grant/revoke from the settings page, re-read on every `execute()` so it takes effect mid-conversation); unauthorized → `isError=true`. `web_search` goes through `searchProfiles[0]` → paid API → fallback built-in. Outputs are collected via `ChatOptions.onFileWritten` (also fires for `edit_file` so in-place modifications surface as green chips); the renderer shows green chips → IPC `workspace.revealPath` (strictly validated to stay inside the workspace). See `model/core-agent/{local-tools, image-gen-tool, search-tools}.ts`.
-**Write-file conflict avoidance** (`util/uniquify-path.ts`): `write_file / markdown_to_pdf / html_to_pdf / generate_image` write to the path the model gives by default; **on conflict, uniquify** (insert `-N` before the basename suffix) and pass it back explicitly via the `<file-renamed>` block in the tool result. "Mine vs not mine" is decided by the caller-injected `ChatOptions.hasProducedPath` (group_chat uses producedSet at turn granularity) — paths this turn already wrote are treated as refinement (overwrite); other pre-existing files are external conflicts. **`bash` is not in the protected scope** (shell redirection is a black box). When `read_file` hits ENOENT, it scans sibling `<name>-N<ext>` files in the same directory; on a hit it appends a `<file-renamed-earlier>` hint as a second layer of defense.
+**Write-file conflict avoidance** (`util/uniquify-path.ts`): `write_file / markdown_to_pdf / html_to_pdf / generate_image` write to the path the model gives by default; **on conflict, uniquify** (insert `-N` before the basename suffix) and pass it back explicitly via the `<file-renamed>` block in the tool result. "Mine vs not mine" is decided by the caller-injected `ChatOptions.hasProducedPath` (group_chat uses producedSet at turn granularity) — paths this turn already wrote are treated as refinement (overwrite); other pre-existing files are external conflicts. **`bash` is not in the protected scope** (shell redirection is a black box). **`edit_file` is also not in this scope** by design — its semantics is "modify an existing file in place" (not "create a new artefact"), so uniquify would be wrong; it instead enforces sandbox-membership (workspace + current attachment dir + extraRoots, same set as the file-tools read side) and rejects pdf/docx/image kinds, so the LLM can only mutate text files the conversation can already see. When `read_file` hits ENOENT, it scans sibling `<name>-N<ext>` files in the same directory; on a hit it appends a `<file-renamed-earlier>` hint as a second layer of defense.
---
diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.ts
index 8f15bba5..0a592ae1 100644
--- a/src/main/model/core-agent/local-tools.ts
+++ b/src/main/model/core-agent/local-tools.ts
@@ -2,7 +2,7 @@
* Local-machine tool wrappers injected into every AgentRunner built by
* this app.
*
- * Four tools:
+ * Five tools:
* - `bash` — overrides core-agent's builtin (last-write-wins in
* AgentRunner's tool map). Same schema; tighter
* English description; permission-gated.
@@ -15,6 +15,14 @@
* does not claim it (i.e. it's not our own prior
* write being refined). The rename is surfaced via a
* `<file-renamed>` block in the tool result.
+ * - `edit_file` — in-place `old_string → new_string` replacement on
+ * an existing text file. Sandbox-checked
+ * (workspace + current attachment dir + extraRoots);
+ * does NOT uniquify (semantics are "modify
+ * existing"); pdf/docx/image kinds rejected; on
+ * success fires `onFileWritten` so the UI can show
+ * the green chip. Companion to `write_file` for
+ * cheap targeted edits without a full overwrite.
* - `markdown_to_pdf` — built-in PDF channel (no pandoc/wkhtmltopdf
* dependency). Renders via util/md-to-pdf +
* Electron's webContents.printToPDF.
@@ -32,6 +40,7 @@
* wrapper's perspective. Prompts shouldn't claim otherwise.
*/
+import * as fs from 'node:fs';
import * as path from 'node:path';
import type { AgentTool, ToolContext, ToolResult } from '#core-agent';
@@ -39,25 +48,41 @@ import { bashTool as coreBashTool, writeFileTool as coreWriteFileTool } from '..
import { getLocalExecGranted } from '../../features/permissions';
import { markdownToPdf, htmlToPdf } from '../../util/md-to-pdf';
import { uniquifyPath, renderRenameSignal } from '../../util/uniquify-path';
+import { isPathAllowed } from '../../util/path-sandbox';
+import { kindOf } from '../../features/file_indexer';
+import { getWorkspacePath } from '../../features/user_workspace';
+import { chatAttachmentDir } from '../../paths';
import { createLogger } from '../../logger';
const log = createLogger('local-tools');
export interface LocalToolsOpts {
- /** Active uid. Reserved for tools that need user-scoped resolution
- * (none currently — kept on the signature for forward compatibility
- * and so existing callers don't have to change). */
+ /** Active uid. Used by `edit_file` to resolve workspace + attachment
+ * sandbox roots; also reserved for future tools that need user-scoped
+ * resolution. Optional so the catalog drift test can call
+ * `createLocalTools({})` without runtime user state. */
userId?: string;
+ /** Current conversation id. Used by `edit_file` to add the current
+ * conv's attachment dir to the sandbox. Without it, only the workspace
+ * (+ extraRoots) is editable. */
+ cid?: string;
+ /** Extra absolute directory roots `edit_file` should treat as in-scope
+ * on top of workspace + attachment. Used by skill-edit / agent-edit
+ * chats so the LLM can edit files inside the skill / agent dir. */
+ extraRoots?: readonly string[];
/** Fires with absolute path after every successful write (write_file,
- * markdown_to_pdf, html_to_pdf). Lets chats.ts surface produced files
- * to the UI. */
+ * edit_file, markdown_to_pdf, html_to_pdf). Lets chats.ts surface
+ * produced files to the UI. */
onFileWritten?: (absPath: string) => void;
/** Predicate: returns true when the given absolute path was already
* written by this caller in the current scope (typically: a Set
* populated by `onFileWritten` this turn). When true, the wrapped
* tool overwrites in place — the refinement pattern. When false /
* absent, an existing file at the target is treated as a foreign
- * collision and uniquify (`-2 / -3 / ...`) kicks in. */
+ * collision and uniquify (`-2 / -3 / ...`) kicks in. Consumed by
+ * `write_file` / `markdown_to_pdf` / `html_to_pdf`; `edit_file`
+ * ignores it (its semantics is "modify existing", uniquify would be
+ * wrong). */
hasProducedPath?: (absPath: string) => boolean;
}
@@ -78,6 +103,57 @@ function isMineFor(opts: LocalToolsOpts): (p: string) => boolean {
return fn ? (p) => fn(p) : () => false;
}
+function errText(code: string, msg: string): string {
+ return `${code}: ${msg}`;
+}
+
+/** Assemble the edit-time sandbox roots for the current (uid, cid). Mirrors
+ * `file-tools.ts::allowedRoots` so the read-side and edit-side share the
+ * same visible scope. Returns [] when uid is missing — guardPath then
+ * rejects with E_NO_SCOPE rather than silently allowing an unscoped edit. */
+function allowedRootsFor(opts: LocalToolsOpts): string[] {
+ const roots: string[] = [];
+ if (opts.userId) {
+ try {
+ const ws = getWorkspacePath(opts.userId);
+ if (ws) roots.push(ws);
+ } catch (err) { log.warn(`edit_file resolve workspace: ${(err as Error).message}`); }
+ if (opts.cid) {
+ try { roots.push(chatAttachmentDir(opts.userId, opts.cid)); }
+ catch (err) { log.warn(`edit_file resolve attachment dir: ${(err as Error).message}`); }
+ }
+ }
+ if (opts.extraRoots?.length) {
+ for (const r of opts.extraRoots) if (r) roots.push(r);
+ }
+ return roots;
+}
+
+function guardEditPath(opts: LocalToolsOpts, abs: string): string | null {
+ const roots = allowedRootsFor(opts);
+ if (!roots.length) {
+ return errText('E_NO_SCOPE', 'no visible roots for this conversation');
+ }
+ if (!isPathAllowed(abs, roots)) {
+ return errText(
+ 'E_PATH_OUT_OF_SCOPE',
+ `path is outside the current conversation's visible scope (workspace + attachments): ${abs}`,
+ );
+ }
+ return null;
+}
+
+function countOccurrences(haystack: string, needle: string): number {
+ if (!needle) return 0;
+ let count = 0;
+ let idx = 0;
+ while ((idx = haystack.indexOf(needle, idx)) !== -1) {
+ count++;
+ idx += needle.length;
+ }
+ return count;
+}
+
/** Wrapped `bash` tool — identical schema, permission-gated, host-shell wording. */
function createBashTool(): AgentTool {
return {
@@ -135,6 +211,135 @@ function createWriteFileTool(opts: LocalToolsOpts): AgentTool {
};
}
+/** Wrapped `edit_file` tool — in-place string replacement on existing text files.
+ * Sandbox-checked, permission-gated, no uniquify (semantics is "modify in place").
+ * pdf/docx/image kinds rejected — those are extracted-only. */
+function createEditFileTool(opts: LocalToolsOpts): AgentTool {
+ return {
+ name: 'edit_file',
+ description:
+ 'Replace `old_string` with `new_string` inside an existing text file. ' +
+ 'Cheaper and safer than rewriting the whole file via `write_file`; the rest of the file is preserved verbatim.\n' +
+ '\n' +
+ 'Parameters:\n' +
+ ' path — required. Absolute or workspace-relative path. The file MUST already exist.\n' +
+ ' old_string — required. Exact text to find. Must be unique in the file unless `replace_all=true`.\n' +
+ ' new_string — required. Replacement text. May be empty (deletes `old_string`).\n' +
+ ' replace_all — optional, default false. When true, every occurrence of `old_string` is replaced.\n' +
+ '\n' +
+ 'How to use:\n' +
+ ' - Prefer this over `write_file` for targeted edits to existing files.\n' +
+ ' - To CREATE a new file, use `write_file` instead — `edit_file` does not create files.\n' +
+ ' - Make `old_string` long enough to be unique. On `E_MULTIPLE_MATCHES`, expand `old_string` with surrounding context, or set `replace_all=true` if every occurrence should change.\n' +
+ ' - Cannot edit pdf / docx / image files (text from those is extracted, not the source). Use `write_file` if you really need to overwrite the binary.\n' +
+ '\n' +
+ 'Permission: requires local execution permission (same gate as `write_file` / `bash`).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Absolute or workspace-relative path to an existing file.' },
+ old_string: { type: 'string', description: 'Exact text to find. Must be unique unless replace_all=true.' },
+ new_string: { type: 'string', description: 'Replacement text. May be empty.' },
+ replace_all: { type: 'boolean', description: 'Default false. When true, every occurrence of old_string is replaced.' },
+ },
+ required: ['path', 'old_string', 'new_string'],
+ },
+ async execute(input, ctx) {
+ if (!getLocalExecGranted()) return deniedResult();
+
+ const rawPath = String(input.path ?? '');
+ if (!rawPath) return { content: errText('E_BAD_INPUT', '`path` is required'), isError: true };
+ const oldStr = typeof input.old_string === 'string' ? input.old_string : null;
+ const newStr = typeof input.new_string === 'string' ? input.new_string : null;
+ if (oldStr === null || newStr === null) {
+ return { content: errText('E_BAD_INPUT', '`old_string` and `new_string` are both required strings'), isError: true };
+ }
+ if (oldStr.length === 0) {
+ return { content: errText('E_BAD_INPUT', '`old_string` must be non-empty'), isError: true };
+ }
+ if (oldStr === newStr) {
+ return { content: errText('E_BAD_INPUT', '`old_string` and `new_string` are identical — no-op rejected'), isError: true };
+ }
+ const replaceAll = input.replace_all === true;
+
+ const abs = resolveAbs(ctx, rawPath);
+ const scopeErr = guardEditPath(opts, abs);
+ if (scopeErr) {
+ log.warn(`edit_file scope reject user=${opts.userId ?? '?'} path=${abs}`);
+ return { content: scopeErr, isError: true };
+ }
+
+ let st: fs.Stats;
+ try { st = fs.statSync(abs); }
+ catch (err) {
+ log.warn(`edit_file not-found user=${opts.userId ?? '?'} path=${abs}: ${(err as Error).message}`);
+ return {
+ content: errText('E_NOT_FOUND', `${abs}: file does not exist (use write_file to create new files)`),
+ isError: true,
+ };
+ }
+ if (!st.isFile()) {
+ return { content: errText('E_NOT_FOUND', `${abs}: not a regular file`), isError: true };
+ }
+
+ const kind = kindOf(abs);
+ if (kind === 'pdf' || kind === 'docx' || kind === 'image') {
+ return {
+ content: errText(
+ 'E_NOT_EDITABLE',
+ `${abs}: kind=${kind} is not editable in place (extracted format). Use write_file to overwrite the file if you really need to.`,
+ ),
+ isError: true,
+ };
+ }
+
+ let body: string;
+ try { body = fs.readFileSync(abs, 'utf8'); }
+ catch (err) {
+ const msg = (err as Error).message;
+ log.warn(`edit_file read failed user=${opts.userId ?? '?'} path=${abs}: ${msg}`);
+ return { content: errText('E_EDIT_FAILED', `${abs}: read failed: ${msg}`), isError: true };
+ }
+
+ const count = countOccurrences(body, oldStr);
+ if (count === 0) {
+ return { content: errText('E_NO_MATCH', `${abs}: \`old_string\` not found in file`), isError: true };
+ }
+ if (count > 1 && !replaceAll) {
+ return {
+ content: errText(
+ 'E_MULTIPLE_MATCHES',
+ `${abs}: \`old_string\` matches ${count} occurrences. Provide more surrounding context to make it unique, or set replace_all=true.`,
+ ),
+ isError: true,
+ };
+ }
+
+ const next = replaceAll ? body.split(oldStr).join(newStr) : body.replace(oldStr, newStr);
+
+ try {
+ fs.writeFileSync(abs, next, 'utf8');
+ } catch (err) {
+ const msg = (err as Error).message;
+ log.warn(`edit_file write failed user=${opts.userId ?? '?'} path=${abs}: ${msg}`);
+ return { content: errText('E_EDIT_FAILED', `${abs}: write failed: ${msg}`), isError: true };
+ }
+
+ const replaced = replaceAll ? count : 1;
+ log.info(`edit_file user=${opts.userId ?? '?'} replaced=${replaced} path=${abs}`);
+
+ if (opts.onFileWritten) {
+ try { opts.onFileWritten(abs); }
+ catch (err) { log.warn(`onFileWritten callback failed: ${(err as Error).message}`); }
+ }
+
+ return {
+ content: `<file path="${abs}" edited="${replaced}" kind="${kind}"/>`,
+ };
+ },
+ };
+}
+
/** `markdown_to_pdf` — zero-dependency built-in channel. */
function createMarkdownToPdfTool(opts: LocalToolsOpts): AgentTool {
return {
@@ -228,6 +433,7 @@ export function createLocalTools(opts: LocalToolsOpts = {}): AgentTool[] {
return [
createBashTool(),
createWriteFileTool(opts),
+ createEditFileTool(opts),
createMarkdownToPdfTool(opts),
createHtmlToPdfTool(opts),
];
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index d418a373..fe539c76 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -189,6 +189,8 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// overrides `bash` and `write_file` with the permission-gated versions.
const localTools = createLocalTools({
...(uid ? { userId: uid } : {}),
+ ...(params.cid ? { cid: params.cid } : {}),
+ ...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),
...(params.onFileWritten ? { onFileWritten: params.onFileWritten } : {}),
...(params.hasProducedPath ? { hasProducedPath: params.hasProducedPath } : {}),
});
diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.ts
index 5bf7bf54..7c9617e9 100644
--- a/src/main/model/core-agent/tool-catalog.ts
+++ b/src/main/model/core-agent/tool-catalog.ts
@@ -1,17 +1,20 @@
/**
- * ToolCatalog — 注入式内建工具清单。
+ * ToolCatalog — registry of injected built-in tools.
*
- * 角色与 `skill-registry.ts` 对称:把"当前会话可用的内建工具"以 markdown 块
- * 形式注入到 system prompt,让 prompt 模板(chat_agent_setup.md 等)不必
- * 硬编码工具名字。
+ * Symmetric to `skill-registry.ts`: emits an "available tools" markdown
+ * block injected into setup-LLM prompts, so that prompt templates
+ * (`chat_agent_setup.md` etc.) don't have to hard-code tool names.
*
- * 数据来源:**手写中央常量表** `TOOL_CATALOG`。不从 `AgentTool` 实例派生——
- * 工具自身的 `description` 是写给 runtime-LLM 的英文长文档,而 catalog 的
- * `summary` 是写给 setup-LLM 看的中文短句,受众不同;`group` / `permission`
- * 是人脑判断的元数据,没法从代码自动推。
+ * Source of truth: a hand-written central constant table `TOOL_CATALOG`.
+ * NOT derived from `AgentTool` instances — the runtime `description` on
+ * each tool is a long English doc aimed at the runtime LLM, while the
+ * catalog `summary` is a short blurb aimed at the setup LLM; the two
+ * audiences are different. `group` / `permission` are human-judged
+ * metadata and cannot be inferred from code.
*
- * 反漂移:测试 `tool-catalog.test.ts` 断言"runner.ts 实际注入的工具 name
- * 集合 ⊆ `TOOL_CATALOG` name 集合"。漏写一条 catalog entry → 测试红。
+ * Anti-drift: `tool-catalog.test.ts` asserts that the set of tool names
+ * runner.ts actually injects is a subset of `TOOL_CATALOG`. Forgetting
+ * a catalog entry → test red.
*/
import { createLogger } from '../../logger';
@@ -19,77 +22,81 @@ import { createLogger } from '../../logger';
const log = createLogger('tool-catalog');
export type ToolGroup =
- | 'fs' // 文件 / 工作区
- | 'shell' // 命令行
- | 'pdf' // PDF 渲染
- | 'kb' // 知识库
- | 'image' // 图像生成
- | 'web' // 联网
- | 'meta' // 跨会话状态
- | 'group'; // 群聊调度(commander only)
+ | 'fs' // files / workspace
+ | 'shell' // command line
+ | 'pdf' // PDF rendering
+ | 'kb' // knowledge base
+ | 'image' // image generation
+ | 'web' // web access
+ | 'meta' // cross-session state
+ | 'group'; // group-chat dispatch (commander only)
export interface ToolCatalogEntry {
- /** 工具名,必须与 `AgentTool.name` 严格一致。 */
+ /** Tool name. Must match `AgentTool.name` exactly. */
name: string;
- /** 一句话描述,写给 setup-LLM 看的中文。 */
+ /** One-line English description aimed at the setup LLM. */
summary: string;
- /** 用途分组,决定渲染时落入哪个小节。 */
+ /** Render group; decides which section the entry lands in. */
group: ToolGroup;
- /** 受运行时权限门控制时填入。当前唯一值是 `localExec`。 */
+ /** Filled when the tool is gated by a runtime permission. Currently
+ * the only value is `localExec`. */
permission?: 'localExec';
}
/**
- * 中央常量表。新增工具时**必须**在此追加一条;漏加由测试兜底。
+ * The central constant table. **Always** append a row when adding a new
+ * tool; the anti-drift test catches omissions.
*
- * 顺序在每个 group 内部按"使用频率从高到低"手动排列,以稳定 KV cache 前缀。
+ * Within each group the order is "most frequently used first", kept stable
+ * to keep the rendered KV-cache prefix stable.
*/
export const TOOL_CATALOG: ToolCatalogEntry[] = [
- // 文件 / 工作区
- { name: 'read_file', group: 'fs', summary: '读工作区或附件里的文本/PDF/DOCX 切片,或图片(多模态)' },
- { name: 'write_file', group: 'fs', permission: 'localExec', summary: '向工作区写文本/代码/markdown 等,自动落到 $working_dir' },
- { name: 'list_files', group: 'fs', summary: '列工作区目录树' },
- { name: 'stat_file', group: 'fs', summary: '触发 PDF/DOCX 抽取并返回 total_chars,read_file 之前用' },
- { name: 'search_files', group: 'fs', summary: '按名字 / glob 在工作区+附件域里找文件' },
- { name: 'grep_files', group: 'fs', summary: '在工作区+附件域里 grep 文本(PDF/DOCX 自动抽取后搜)' },
-
- // 命令行
- { name: 'bash', group: 'shell', permission: 'localExec', summary: '在用户机器上执行 shell 命令(cwd = $working_dir)' },
+ // Files / workspace
+ { name: 'read_file', group: 'fs', summary: 'Read a slice of text from a workspace or attachment file (PDF/DOCX text or image as multimodal).' },
+ { name: 'write_file', group: 'fs', permission: 'localExec', summary: 'Write text/code/markdown into the workspace; resolves under $working_dir.' },
+ { name: 'edit_file', group: 'fs', permission: 'localExec', summary: 'In-place `old_string → new_string` replacement on an existing text file (instead of rewriting the whole file).' },
+ { name: 'list_files', group: 'fs', summary: 'List the workspace directory tree.' },
+ { name: 'stat_file', group: 'fs', summary: 'Trigger PDF/DOCX extraction and return total_chars; call before read_file.' },
+ { name: 'search_files', group: 'fs', summary: 'Find files by name / glob across the workspace + attachment scope.' },
+ { name: 'grep_files', group: 'fs', summary: 'Grep text across the workspace + attachment scope (PDF/DOCX auto-extracted, then searched).' },
+
+ // Shell
+ { name: 'bash', group: 'shell', permission: 'localExec', summary: 'Execute a shell command on the user\'s machine (cwd = $working_dir).' },
// PDF
- { name: 'markdown_to_pdf', group: 'pdf', permission: 'localExec', summary: 'markdown → PDF(CJK 友好,零外部依赖)' },
- { name: 'html_to_pdf', group: 'pdf', permission: 'localExec', summary: 'HTML → PDF(同上)' },
+ { name: 'markdown_to_pdf', group: 'pdf', permission: 'localExec', summary: 'Markdown → PDF (CJK-friendly, zero external dependency).' },
+ { name: 'html_to_pdf', group: 'pdf', permission: 'localExec', summary: 'HTML → PDF (same renderer).' },
- // 知识库
- { name: 'kb_search', group: 'kb', summary: '用户知识库语义检索' },
- { name: 'kb_read', group: 'kb', summary: '读 kb_search 命中过的 KB 文件分块原文' },
+ // Knowledge base
+ { name: 'kb_search', group: 'kb', summary: 'Semantic search over the user\'s knowledge base.' },
+ { name: 'kb_read', group: 'kb', summary: 'Read source-text chunks from a KB file that kb_search has hit.' },
- // 图像
- { name: 'generate_image', group: 'image', permission: 'localExec', summary: '调厂商图像 API 生成图片,落到工作区' },
+ // Image
+ { name: 'generate_image', group: 'image', permission: 'localExec', summary: 'Call the configured image-generation API and save the result into the workspace.' },
- // 联网(厂商原生搜索可用时框架自动优先用原生,下面两个是兜底)
- { name: 'web_search', group: 'web', summary: '内置兜底联网搜索(厂商原生搜索可用时框架自动优先用原生)' },
- { name: 'web_fetch', group: 'web', summary: '抓取 URL 正文,配合 web_search 使用' },
+ // Web (when a vendor-native search is available the framework picks it automatically; the two below are the fallback channel)
+ { name: 'web_search', group: 'web', summary: 'Built-in fallback web search (vendor-native search is preferred automatically when available).' },
+ { name: 'web_fetch', group: 'web', summary: 'Fetch the body of a URL; pairs with web_search.' },
- // 跨会话状态
- { name: 'cross_session_memory', group: 'meta', summary: '跨会话 user / agent memory 读写' },
- { name: 'metacognition', group: 'meta', summary: '元认知(COMPETENCE / LEARNING_STRATEGIES)读写,env 开关控制' },
+ // Cross-session state
+ { name: 'cross_session_memory', group: 'meta', summary: 'Read/write user / agent memory that persists across sessions.' },
+ { name: 'metacognition', group: 'meta', summary: 'Read/write metacognition (COMPETENCE / LEARNING_STRATEGIES); env-flag gated.' },
- // 群聊调度(commander 专用,普通 agent 不会注入)
- { name: 'plan_set', group: 'group', summary: '落档整体执行计划;首次同步在群里发公告,后续覆盖只更文件' },
- { name: 'plan_update', group: 'group', summary: '更新某一步的状态(in_progress / done / failed)' },
+ // Group-chat dispatch (commander only — never injected for ordinary agents)
+ { name: 'plan_set', group: 'group', summary: 'Persist the overall execution plan; the first call announces in the group, subsequent overwrites only update the file.' },
+ { name: 'plan_update', group: 'group', summary: 'Update the status of one step (in_progress / done / failed).' },
];
-/** 渲染时各 group 的固定输出顺序与 section 标题。 */
+/** Fixed render order + section heading per group. */
const GROUP_ORDER: ReadonlyArray<{ group: ToolGroup; title: string }> = [
- { group: 'fs', title: '文件 / 工作区' },
- { group: 'shell', title: '命令行' },
+ { group: 'fs', title: 'Files / workspace' },
+ { group: 'shell', title: 'Shell' },
{ group: 'pdf', title: 'PDF' },
- { group: 'kb', title: '知识库' },
- { group: 'image', title: '图像' },
- { group: 'web', title: '联网' },
- { group: 'meta', title: '跨会话状态' },
- { group: 'group', title: '群聊调度' },
+ { group: 'kb', title: 'Knowledge base' },
+ { group: 'image', title: 'Image' },
+ { group: 'web', title: 'Web' },
+ { group: 'meta', title: 'Cross-session state' },
+ { group: 'group', title: 'Group-chat dispatch' },
];
const CATALOG_BY_NAME: ReadonlyMap<string, ToolCatalogEntry> = new Map(
@@ -97,23 +104,28 @@ const CATALOG_BY_NAME: ReadonlyMap<string, ToolCatalogEntry> = new Map(
);
const PREAMBLE =
- '按用途分组列出当前会话可用的内建工具。**调用工具不需要任何 skill 包装**——' +
- '能直接做完的事情就直接调,别为单步任务设计 skill。skill 的真正用武之地是' +
- '多步逻辑封装、第三方 API 凭证管理、重复性高的复合流程。';
+ 'Built-in tools available in the current session, grouped by purpose. ' +
+ '**Calling a tool does NOT require a skill wrapper** — if a tool can do the job in one call, just call it; ' +
+ 'do not design a skill for a single-step task. The real value of a skill is encapsulating multi-step logic, ' +
+ 'managing third-party API credentials, or reusing a high-frequency composite flow.';
/**
- * 渲染 `## 可用工具 (tools)` 块。
+ * Render the `## Available tools` block.
*
- * `names` 应当来自 runner.ts 实际组装出的 `allTools.map(t => t.name)`——这样
- * 受运行态条件控制的工具(memory / metacognition / plan_* / 按 uid 启用
- * 的 fileTools 等)会自动跟随实际注入情况,不会出现"清单写了但实际没注入"
- * 的漂移。
+ * `names` should be sourced from runner.ts's actual assembled
+ * `allTools.map(t => t.name)` — that way runtime-conditional tools
+ * (memory / metacognition / plan_* / uid-gated fileTools, ...) follow
+ * the actual injection state automatically; no "listed but not
+ * actually injected" drift.
*
- * 行为:
- * - `names` 为空 → 返回 `""`(core-agent 把空字符串视为"跳过该段")
- * - `names` 中存在但 `TOOL_CATALOG` 里查不到 → warn 日志 + 跳过该 name,不抛
- * - 输出按 `GROUP_ORDER` 固定顺序拼装,每个 group 内按 catalog 数组里出现的
- * 原始顺序——保证同样输入产生同样输出,KV cache 友好
+ * Behaviour:
+ * - empty `names` → return `""` (core-agent treats empty string as "skip
+ * this section")
+ * - a name in `names` that is missing from `TOOL_CATALOG` → warn log +
+ * skip that name; never throws
+ * - output is assembled in fixed `GROUP_ORDER`; within each group the
+ * order matches the catalog array — same input → same output, KV
+ * cache friendly
*/
export function getToolsSystemPromptBlock(names: string[]): string {
if (!names.length) return '';
@@ -134,7 +146,7 @@ export function getToolsSystemPromptBlock(names: string[]): string {
if (!present.length) return '';
const presentSet = new Set(present.map((e) => e.name));
- const lines: string[] = ['## 可用工具 (tools)', '', PREAMBLE, ''];
+ const lines: string[] = ['## Available tools', '', PREAMBLE, ''];
for (const { group, title } of GROUP_ORDER) {
const groupEntries = TOOL_CATALOG.filter(
@@ -143,7 +155,7 @@ export function getToolsSystemPromptBlock(names: string[]): string {
if (!groupEntries.length) continue;
lines.push(`### ${title}`);
for (const e of groupEntries) {
- const perm = e.permission === 'localExec' ? '(受本机执行权限控制)' : '';
+ const perm = e.permission === 'localExec' ? ' (gated by local-execution permission)' : '';
lines.push(`- **${e.name}** — ${e.summary}${perm}`);
}
lines.push('');
diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.ts
index 52db6089..a7554206 100644
--- a/src/main/util/tool-result-cap.ts
+++ b/src/main/util/tool-result-cap.ts
@@ -46,6 +46,7 @@ export const MAX_RESULT_CHARS_BY_TOOL: Record<string, number> = {
markdown_to_pdf: 4_000,
html_to_pdf: 4_000,
write_file: 4_000,
+ edit_file: 4_000,
generate_image: 4_000,
};
diff --git a/test/main/model/core-agent/local-tools.test.ts b/test/main/model/core-agent/local-tools.test.ts
new file mode 100644
index 00000000..5b352da3
--- /dev/null
+++ b/test/main/model/core-agent/local-tools.test.ts
@@ -0,0 +1,224 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+import { makeMinimalPdf } from '../../../fixtures/make-minimal-pdf';
+
+const UID = 'u-localtools-001';
+const CID = 'conv-edit';
+
+let tmpDir: string;
+let prevWs: string | undefined;
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-localtools-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ const users = await import('../../../../src/main/features/users');
+ users.activateUser(UID);
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function buildEditTool(opts: { onFileWritten?: (p: string) => void; extraRoots?: string[] } = {}) {
+ const localTools = await import('../../../../src/main/model/core-agent/local-tools');
+ const ws = await import('../../../../src/main/features/user_workspace');
+ const wsDir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(wsDir, { recursive: true });
+ const r = ws.setWorkspacePath(UID, wsDir);
+ if (!r.ok) throw new Error(`setWorkspacePath failed: ${r.error}`);
+ const tools = localTools.createLocalTools({
+ userId: UID,
+ cid: CID,
+ ...(opts.onFileWritten ? { onFileWritten: opts.onFileWritten } : {}),
+ ...(opts.extraRoots ? { extraRoots: opts.extraRoots } : {}),
+ });
+ const edit = tools.find((t) => t.name === 'edit_file');
+ if (!edit) throw new Error('edit_file tool missing');
+ return { edit, wsDir };
+}
+
+async function grant() {
+ const perm = await import('../../../../src/main/features/permissions');
+ perm.grantLocalExec();
+}
+
+async function run(tool: any, input: Record<string, any>) {
+ const ctx = { workingDir: '.', signal: undefined } as any;
+ return await tool.execute(input, ctx);
+}
+
+describe('local-tools › edit_file › permission gate', () => {
+ it('rejects when localExec not granted', async () => {
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.txt');
+ fs.writeFileSync(p, 'hello world');
+ const r = await run(edit, { path: p, old_string: 'hello', new_string: 'hi' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toMatch(/Local execution is not authorised/i);
+ // file untouched
+ expect(fs.readFileSync(p, 'utf8')).toBe('hello world');
+ });
+});
+
+describe('local-tools › edit_file › sandbox', () => {
+ it('rejects path outside workspace + attachment + extraRoots', async () => {
+ await grant();
+ const { edit } = await buildEditTool();
+ const outside = path.join(tmpDir, 'outside.txt');
+ fs.writeFileSync(outside, 'hello');
+ const r = await run(edit, { path: outside, old_string: 'hello', new_string: 'hi' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_PATH_OUT_OF_SCOPE');
+ // file untouched
+ expect(fs.readFileSync(outside, 'utf8')).toBe('hello');
+ });
+
+ it('accepts a path inside extraRoots', async () => {
+ await grant();
+ const skillDir = path.join(tmpDir, 'skill-x');
+ fs.mkdirSync(skillDir, { recursive: true });
+ const p = path.join(skillDir, 'SKILL.md');
+ fs.writeFileSync(p, 'foo bar');
+ const { edit } = await buildEditTool({ extraRoots: [skillDir] });
+ const r = await run(edit, { path: p, old_string: 'foo', new_string: 'baz' });
+ expect(r.isError).toBeFalsy();
+ expect(fs.readFileSync(p, 'utf8')).toBe('baz bar');
+ });
+});
+
+describe('local-tools › edit_file › input validation', () => {
+ it('rejects missing path / old / new', async () => {
+ await grant();
+ const { edit } = await buildEditTool();
+ expect((await run(edit, { old_string: 'a', new_string: 'b' })).isError).toBe(true);
+ expect((await run(edit, { path: 'x', new_string: 'b' })).isError).toBe(true);
+ expect((await run(edit, { path: 'x', old_string: 'a' })).isError).toBe(true);
+ });
+
+ it('rejects empty old_string', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.txt');
+ fs.writeFileSync(p, 'x');
+ const r = await run(edit, { path: p, old_string: '', new_string: 'b' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_BAD_INPUT');
+ });
+
+ it('rejects no-op when old === new', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.txt');
+ fs.writeFileSync(p, 'foo');
+ const r = await run(edit, { path: p, old_string: 'foo', new_string: 'foo' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_BAD_INPUT');
+ });
+});
+
+describe('local-tools › edit_file › file kind / existence', () => {
+ it('rejects when file does not exist (no auto-create)', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'missing.txt');
+ const r = await run(edit, { path: p, old_string: 'a', new_string: 'b' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_NOT_FOUND');
+ expect(fs.existsSync(p)).toBe(false);
+ });
+
+ it('rejects PDF kind with E_NOT_EDITABLE', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'doc.pdf');
+ fs.writeFileSync(p, makeMinimalPdf(['some pdf text']));
+ const r = await run(edit, { path: p, old_string: 'a', new_string: 'b' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_NOT_EDITABLE');
+ });
+});
+
+describe('local-tools › edit_file › matching semantics', () => {
+ it('replaces a unique occurrence and returns char-counted result tag', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, '# Title\n\nhello world\n');
+ const r = await run(edit, { path: p, old_string: 'hello world', new_string: 'goodbye world' });
+ expect(r.isError).toBeFalsy();
+ expect(r.content).toContain('edited="1"');
+ expect(fs.readFileSync(p, 'utf8')).toBe('# Title\n\ngoodbye world\n');
+ });
+
+ it('rejects when old_string not found', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, 'abc');
+ const r = await run(edit, { path: p, old_string: 'xyz', new_string: '?' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_NO_MATCH');
+ });
+
+ it('rejects multiple matches when replace_all=false', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, 'foo bar foo');
+ const r = await run(edit, { path: p, old_string: 'foo', new_string: 'baz' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_MULTIPLE_MATCHES');
+ // file untouched
+ expect(fs.readFileSync(p, 'utf8')).toBe('foo bar foo');
+ });
+
+ it('replaces all when replace_all=true', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, 'foo bar foo');
+ const r = await run(edit, { path: p, old_string: 'foo', new_string: 'baz', replace_all: true });
+ expect(r.isError).toBeFalsy();
+ expect(r.content).toContain('edited="2"');
+ expect(fs.readFileSync(p, 'utf8')).toBe('baz bar baz');
+ });
+
+ it('preserves CRLF line endings (no normalization)', async () => {
+ await grant();
+ const { edit, wsDir } = await buildEditTool();
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, 'line1\r\nALPHA\r\nline3\r\n');
+ const r = await run(edit, { path: p, old_string: 'ALPHA', new_string: 'BETA' });
+ expect(r.isError).toBeFalsy();
+ expect(fs.readFileSync(p, 'utf8')).toBe('line1\r\nBETA\r\nline3\r\n');
+ });
+});
+
+describe('local-tools › edit_file › onFileWritten', () => {
+ it('fires onFileWritten with the absolute path on success', async () => {
+ await grant();
+ const written: string[] = [];
+ const { edit, wsDir } = await buildEditTool({ onFileWritten: (p) => written.push(p) });
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, 'hello');
+ const r = await run(edit, { path: p, old_string: 'hello', new_string: 'hi' });
+ expect(r.isError).toBeFalsy();
+ expect(written).toEqual([p]);
+ });
+
+ it('does NOT fire onFileWritten on error', async () => {
+ await grant();
+ const written: string[] = [];
+ const { edit, wsDir } = await buildEditTool({ onFileWritten: (p) => written.push(p) });
+ const p = path.join(wsDir, 'a.md');
+ fs.writeFileSync(p, 'hello');
+ await run(edit, { path: p, old_string: 'NOT-PRESENT', new_string: 'x' });
+ expect(written).toEqual([]);
+ });
+});
diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.ts
index d5ce2552..3c52cad8 100644
--- a/test/main/model/core-agent/tool-catalog.test.ts
+++ b/test/main/model/core-agent/tool-catalog.test.ts
@@ -86,23 +86,23 @@ describe('tool-catalog', () => {
it('输出按 group 顺序分节,且只含命中分组', () => {
// read_file (fs) + bash (shell) + kb_search (kb) → 三个分节按 fs/shell/kb 序
const out = getToolsSystemPromptBlock(['kb_search', 'bash', 'read_file']);
- const fsIdx = out.indexOf('### 文件 / 工作区');
- const shellIdx = out.indexOf('### 命令行');
- const kbIdx = out.indexOf('### 知识库');
+ const fsIdx = out.indexOf('### Files / workspace');
+ const shellIdx = out.indexOf('### Shell');
+ const kbIdx = out.indexOf('### Knowledge base');
expect(fsIdx).toBeGreaterThan(-1);
expect(shellIdx).toBeGreaterThan(fsIdx);
expect(kbIdx).toBeGreaterThan(shellIdx);
// 没命中的分组不出现
expect(out).not.toContain('### PDF');
- expect(out).not.toContain('### 图像');
+ expect(out).not.toContain('### Image');
});
- it('权限门工具有 (受本机执行权限控制) 后缀', () => {
+ it('权限门工具有 local-execution permission 后缀', () => {
const out = getToolsSystemPromptBlock(['bash', 'read_file']);
// bash 有 permission='localExec',read_file 没有
const bashLine = out.split('\n').find((l) => l.includes('**bash**'));
const readLine = out.split('\n').find((l) => l.includes('**read_file**'));
- expect(bashLine).toContain('受本机执行权限控制');
- expect(readLine).not.toContain('受本机执行权限控制');
+ expect(bashLine).toContain('local-execution permission');
+ expect(readLine).not.toContain('local-execution permission');
});
});
diff --git a/test/main/model/local-tools.test.ts b/test/main/model/local-tools.test.ts
index d353162b..c02301f9 100644
--- a/test/main/model/local-tools.test.ts
+++ b/test/main/model/local-tools.test.ts
@@ -58,11 +58,11 @@ function makeCtx(): any {
// ── Tool identity ─────────────────────────────────────────────────────────
describe('local-tools › identity', () => {
- it('exposes exactly four tools, named bash / write_file / markdown_to_pdf / html_to_pdf', async () => {
+ it('exposes exactly five tools, named bash / write_file / edit_file / markdown_to_pdf / html_to_pdf', async () => {
const { lt } = await loadModules();
const tools = lt.createLocalTools({});
expect(tools.map((t) => t.name).sort()).toEqual(
- ['bash', 'html_to_pdf', 'markdown_to_pdf', 'write_file'],
+ ['bash', 'edit_file', 'html_to_pdf', 'markdown_to_pdf', 'write_file'],
);
});