From 0bc9480c1d2afa7624e993ce1dd1c17e2649c74b Mon Sep 17 00:00:00 2001 From: kim Date: Mon, 13 Jul 2026 16:05:00 +0900 Subject: [PATCH] v0.5.0: reduce system prompt token usage by ~35-40% MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Compress systemPrompt.ts guidelines (7 → 5 rules, remove redundancy) - Shorten tool descriptions: read_file, agent, git_status, git_commit, todo_write, edit_file, web_search, web_fetch - Shorten parameter descriptions in readFile, agentTool, git, editFile, todoWrite - Simplify fallbackPrompt.ts (remove example, shorten instructions) - All 123 tests pass --- package.json | 2 +- src/agent/systemPrompt.ts | 12 ++++----- src/toolcalling/fallbackPrompt.ts | 19 +++++--------- src/tools/agentTool.ts | 18 ++++--------- src/tools/editFile.ts | 6 ++--- src/tools/git.ts | 42 +++++++++++++------------------ src/tools/readFile.ts | 13 ++++------ src/tools/todoWrite.ts | 7 +++--- src/tools/webFetch.ts | 2 +- src/tools/webSearch.ts | 2 +- 10 files changed, 48 insertions(+), 75 deletions(-) diff --git a/package.json b/package.json index 482650f..a9e3368 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "locode", - "version": "0.3.1", + "version": "0.5.0", "description": "Agentic coding CLI for local models served via Ollama and LM Studio", "type": "module", "bin": { diff --git a/src/agent/systemPrompt.ts b/src/agent/systemPrompt.ts index 73acefe..a06da36 100644 --- a/src/agent/systemPrompt.ts +++ b/src/agent/systemPrompt.ts @@ -10,13 +10,11 @@ Available tools: ${toolList} Guidelines: -- Use tools to inspect real files before answering questions about code; don't guess at file contents. -- Prefer read_file and grep over asking the user to paste code. -- Call at most one tool at a time and use its result before deciding on the next step. -- write_file, edit_file, and bash require the user's explicit confirmation before they run — expect that some requests may be denied. -- Prefer edit_file for small changes to existing files; use write_file for new files or full rewrites. -- When you have enough information, respond with a normal text answer instead of calling a tool. -- Keep answers concise and focused on the user's question.`; +- Inspect files with tools before answering; don't guess contents. +- Call at most one tool at a time. +- Mutating tools (write_file, edit_file, bash, git_commit) require user confirmation. +- Use edit_file for small edits; write_file for new files or full rewrites. +- Respond in plain text when you have enough information. Keep answers concise.`; const withMode = mode === "fallback" ? `${base}\n\n${FALLBACK_TOOL_INSTRUCTIONS}` : base; return projectInstructions ? `${withMode}\n\n${projectInstructions}` : withMode; diff --git a/src/toolcalling/fallbackPrompt.ts b/src/toolcalling/fallbackPrompt.ts index d932982..41d61e2 100644 --- a/src/toolcalling/fallbackPrompt.ts +++ b/src/toolcalling/fallbackPrompt.ts @@ -1,21 +1,14 @@ -export const FALLBACK_TOOL_INSTRUCTIONS = `This model does not have native function calling. Instead, call a tool by writing a fenced code block in exactly this format: +export const FALLBACK_TOOL_INSTRUCTIONS = `This model does not support native function calling. To call a tool, write a fenced code block: \`\`\`tool_call {"name": "read_file", "arguments": {"path": "src/index.ts"}} \`\`\` Rules: -- Call at most one tool per response. Wait for its result before calling another. -- The block must contain valid JSON with exactly "name" and "arguments" keys. -- If you don't need a tool, just answer normally with no fenced block. +- One tool call per response. Wait for the result before calling another. +- Must contain valid JSON with "name" and "arguments" keys. +- If no tool is needed, answer normally without a fenced block. -Example: -User: What does math.js contain? -Assistant: -\`\`\`tool_call -{"name": "read_file", "arguments": {"path": "math.js"}} -\`\`\` +The result is returned in a \`\`\`tool_result\`\`\` block. Then answer normally or call another tool.`; -The tool's result will be given back to you in a \`\`\`tool_result\`\`\` block. You can then answer normally or call another tool the same way.`; - -export const FALLBACK_RETRY_NUDGE = `Your last message contained a \`\`\`tool_call\`\`\` block that wasn't valid JSON with "name" and "arguments" keys. Please try again using exactly the format shown earlier, or answer without a tool call.`; +export const FALLBACK_RETRY_NUDGE = `Your last \`tool_call\` block wasn't valid JSON with "name" and "arguments" keys. Try again using the correct format, or answer without a tool call.`; diff --git a/src/tools/agentTool.ts b/src/tools/agentTool.ts index 89f3f69..a139166 100644 --- a/src/tools/agentTool.ts +++ b/src/tools/agentTool.ts @@ -2,28 +2,20 @@ import { z } from "zod"; import type { ToolDef } from "./types.js"; const schema = z.object({ - description: z.string().describe("A short (3-6 word) label for what this sub-agent is doing, shown in the UI."), + description: z.string().describe("Short 3-6 word label shown in the UI."), prompt: z .string() .describe( - "The full task for the sub-agent to carry out. Be specific and self-contained — the sub-agent starts with no " + - "memory of this conversation beyond what you put here, and it cannot ask you follow-up questions.", + "Full, self-contained task description. The sub-agent has no conversation memory and cannot ask follow-ups.", ), }); export const agentTool: ToolDef> = { name: "agent", description: - "Delegate a self-contained task to a fresh sub-agent with its own tool loop (read_file, list_files, grep, " + - "web_search, web_fetch, write_file, edit_file, bash — but not another agent). Use for multi-step research or " + - "exploration you want to run in isolation, getting back only the final answer so your own context stays " + - "focused. Only the sub-agent's final text is returned to you, not its intermediate steps. For a task that " + - "needs reading many files (more than a handful), prefer dispatching several sub-agents — each scanning a " + - "subset — over reading them all yourself: every tool call you make yourself counts toward your per-turn step " + - "budget, so a large scan done inline will pause mid-task, while sub-agents run their own loops and report " + - "back in a single step each. A sub-agent also has its own (smaller) step budget and no memory across calls — " + - "if one reports it ran out of steps, don't retry it with the same prompt (it'll hit the same wall); split the " + - "task into narrower sub-agents instead.", + "Delegate a task to a sub-agent with its own tool loop (no nested agents). Only the final answer is returned. " + + "For many files, split into multiple sub-agents. Sub-agents have a smaller step budget; if one runs out, " + + "narrow the task rather than retrying.", schema, mutating: false, handler: async (args, ctx) => { diff --git a/src/tools/editFile.ts b/src/tools/editFile.ts index acb1390..3522366 100644 --- a/src/tools/editFile.ts +++ b/src/tools/editFile.ts @@ -7,8 +7,8 @@ import type { ToolDef } from "./types.js"; const schema = z.object({ path: z.string().describe("File path to edit, relative to the working directory or absolute."), - old_string: z.string().describe("Exact text to replace. Must match the file content exactly, including whitespace."), - new_string: z.string().describe("Text to replace it with."), + old_string: z.string().describe("Exact text to replace. Must match file content exactly."), + new_string: z.string().describe("Replacement text."), replace_all: z.boolean().optional().describe("Replace every occurrence instead of requiring a unique match."), }); @@ -27,7 +27,7 @@ function applyEdit(original: string, oldString: string, newString: string, repla export const editFileTool: ToolDef> = { name: "edit_file", description: - "Replace an exact string in a file with a new string. old_string must match the file content exactly and, unless replace_all is set, must appear exactly once — include enough surrounding context to make it unique.", + "Replace exact text in a file. old_string must match exactly. Unless replace_all is set, it must be unique — include enough context.", schema, mutating: true, preview: async ({ path: filePath, old_string, new_string, replace_all }, ctx) => { diff --git a/src/tools/git.ts b/src/tools/git.ts index 1a24801..08f13c1 100644 --- a/src/tools/git.ts +++ b/src/tools/git.ts @@ -20,18 +20,16 @@ function runGit(args: string[], cwd: string) { const statusSchema = z.object({ operation: z.enum(["status", "diff", "log", "show", "branches"]), - paths: z.array(z.string()).optional().describe("Limit `status`/`diff` to these paths, relative to the working directory."), - staged: z.boolean().optional().describe("For `diff`: show staged changes (--cached) instead of the working tree diff."), - ref: z.string().optional().describe("For `show`: the commit/ref to inspect (default HEAD). For `log`: start from this ref."), - maxCount: z.number().int().min(1).max(200).optional().describe("For `log`: maximum number of commits to return (default 20)."), + paths: z.array(z.string()).optional().describe("Limit status/diff to these paths."), + staged: z.boolean().optional().describe("For diff: show staged changes (--cached)."), + ref: z.string().optional().describe("For show/log: the commit or ref (default HEAD)."), + maxCount: z.number().int().min(1).max(200).optional().describe("For log: max commits (default 20)."), }); export const gitStatusTool: ToolDef> = { name: "git_status", description: - "Inspect the git repository at the working directory: `status` (working tree state), `diff` (unstaged or, with staged:true, " + - "staged changes), `log` (recent commits), `show` (a specific commit/ref, default HEAD), or `branches` (local branches with " + - "upstream tracking info). Read-only — runs automatically without confirmation.", + "Inspect the git repo: `status`, `diff`, `log`, `show`, or `branches`. Read-only — no confirmation needed.", schema: statusSchema, mutating: false, handler: async ({ operation, paths, staged, ref, maxCount }, ctx) => { @@ -87,35 +85,31 @@ const commitSchema = z.object({ "delete_branch", ]), paths: z.array(z.string()).optional() - .describe("For `add`: paths to stage. For `stash push`: paths to stash. Omit to stage all changes.") + .describe("For add: paths to stage. For stash: paths to stash. Omit for all.") .refine((arr) => !arr?.some((p) => p.startsWith("-")), { message: 'paths must not start with "-" (would be parsed as a git flag)', }), message: z .string() .optional() - .describe("For `commit`: commit message. For `stash push`: stash message.") + .describe("For commit: commit message. For stash: stash message.") .refine((v) => !v?.startsWith("-"), { message: 'message must not start with "-" (would be parsed as a git flag)' }), - branchName: refLike("Branch name. Required for create_branch/checkout/merge/rebase/delete_branch."), - createIfMissing: z.boolean().optional().describe("For `checkout`: create the branch if it doesn't exist yet (like `checkout -b`)."), - remote: refLike('For `push`: remote name (default "origin").'), - setUpstream: z.boolean().optional().describe("For `push`: set upstream tracking — needed the first time a new branch is pushed."), - ref: refLike("For `reset`: ref to reset to (default HEAD). For `merge`/`rebase`: alternative ref if branchName omitted."), - mode: z.enum(["soft", "mixed", "hard"]).optional().describe("For `reset`: reset mode (default mixed)."), - strategy: z.enum(["fast-forward", "no-ff", "ff-only"]).optional().describe("For `merge`: merge strategy."), - stashRef: refLike("For `stash pop`: stash reference (default stash@{0})."), - force: z.boolean().optional().describe("For `delete_branch`: force delete an unmerged branch."), + branchName: refLike("Required for create_branch/checkout/merge/rebase/delete_branch."), + createIfMissing: z.boolean().optional().describe("For checkout: create branch if missing (like checkout -b)."), + remote: refLike('For push: remote name (default "origin").'), + setUpstream: z.boolean().optional().describe("For push: set upstream tracking."), + ref: refLike("For reset: ref to reset to (default HEAD). For merge/rebase: alternative ref."), + mode: z.enum(["soft", "mixed", "hard"]).optional().describe("For reset: reset mode (default mixed)."), + strategy: z.enum(["fast-forward", "no-ff", "ff-only"]).optional().describe("For merge: merge strategy."), + stashRef: refLike("For stash pop: stash reference (default stash@{0})."), + force: z.boolean().optional().describe("For delete_branch: force delete unmerged branch."), }); export const gitCommitTool: ToolDef> = { name: "git_commit", description: - "Make changes to the git repository at the working directory: `add` (stage paths, or all changes if omitted), `commit` " + - "(requires `message`; commit staged changes), `create_branch` (requires `branchName`; branch at current HEAD without switching), " + - "`checkout` (requires `branchName`; switch branches, or create-and-switch with createIfMissing), `push` (push current branch), " + - "`reset` (reset current branch; default mixed, default ref HEAD), `stash` (push or pop a stash), `merge` (merge branchName into " + - "current branch), `rebase` (rebase current branch onto branchName), or `delete_branch` (requires `branchName`; delete a local branch). " + - "Each mutating use requires the user's confirmation with a preview of the affected state.", + "Git operations: `add`, `commit`, `create_branch`, `checkout`, `push`, `reset`, `stash`, `merge`, `rebase`, " + + "`delete_branch`. Mutating operations require user confirmation with a preview.", schema: commitSchema, mutating: true, preview: async (args, ctx) => buildPreview(args, ctx.cwd), diff --git a/src/tools/readFile.ts b/src/tools/readFile.ts index ea3a59b..15ee7f6 100644 --- a/src/tools/readFile.ts +++ b/src/tools/readFile.ts @@ -17,19 +17,16 @@ function withinWorkspace(resolved: string, workspace: string): boolean { const MAX_READ_CHARS = 20_000; const schema = z.object({ - path: z.string().describe("File path to read, relative to the working directory or absolute."), - offset: z.number().int().min(1).optional().describe("1-indexed line number to start reading from (text files only)."), - limit: z.number().int().min(1).max(2000).optional().describe("Maximum number of lines to read (text files only)."), + path: z.string().describe("File path, relative to working directory or absolute."), + offset: z.number().int().min(1).optional().describe("1-indexed start line (text only)."), + limit: z.number().int().min(1).max(2000).optional().describe("Max lines to read (text only)."), }); export const readFileTool: ToolDef> = { name: "read_file", description: - "Read a file from the local filesystem. Text files return content with 1-indexed line numbers, optionally a specific " + - "line range. Very large files are paginated: the result is capped and reports `nextOffset` — call read_file again with " + - "that offset to read the next page rather than re-reading the same path. Image files (png, jpg, jpeg, gif, webp, bmp) " + - "are returned as image content for the model to see directly — this requires a vision-capable model/backend; others may " + - "error on the request.", + "Read a local file. Text files return 1-indexed lines; large files are paginated (use nextOffset for next page). " + + "Image files (png, jpg, jpeg, gif, webp, bmp) are returned as image content (requires vision-capable model).", schema, mutating: false, handler: async ({ path: filePath, offset, limit }, ctx) => { diff --git a/src/tools/todoWrite.ts b/src/tools/todoWrite.ts index 4c0b01e..f8a4347 100644 --- a/src/tools/todoWrite.ts +++ b/src/tools/todoWrite.ts @@ -9,15 +9,14 @@ const todoItemSchema = z.object({ const schema = z.object({ todos: z .array(todoItemSchema) - .describe("The full current checklist — this replaces whatever list existed before, so include every item, not just the ones that changed."), + .describe("Full checklist (replaces previous list, not a diff)."), }); export const todoWriteTool: ToolDef> = { name: "todo_write", description: - "Show the user a task checklist for multi-step work (roughly 3+ distinct steps) so progress stays visible. " + - "Mark exactly one item 'in_progress' at a time, mark an item 'completed' as soon as it's actually done (don't " + - "batch completions), and always pass the full list, not a diff. Skip this for single-step or trivial requests.", + "Show a task checklist for multi-step work (3+ steps). One item 'in_progress' at a time, " + + "mark 'completed' when done. Pass the full list each time. Skip for trivial requests.", schema, // Purely informational (like Claude Code's TodoWrite) — never touches the filesystem or asks // the user anything, so it shouldn't interrupt the flow with a confirmation prompt. diff --git a/src/tools/webFetch.ts b/src/tools/webFetch.ts index 455f55a..4957964 100644 --- a/src/tools/webFetch.ts +++ b/src/tools/webFetch.ts @@ -19,7 +19,7 @@ function isBinaryContentType(contentType: string): boolean { export const webFetchTool: ToolDef> = { name: "web_fetch", description: - "Fetch a URL and return its content as readable text (HTML is stripped of tags/scripts/styles). Use to read a specific page, e.g. one found via web_search or linked from documentation.", + "Fetch a URL and return readable text (HTML tags/scripts/styles stripped). Use for specific pages found via web_search.", schema, mutating: false, handler: async ({ url }) => { diff --git a/src/tools/webSearch.ts b/src/tools/webSearch.ts index 09a6060..ad6a90a 100644 --- a/src/tools/webSearch.ts +++ b/src/tools/webSearch.ts @@ -45,7 +45,7 @@ function parseResults(html: string, limit: number): SearchResult[] { export const webSearchTool: ToolDef> = { name: "web_search", description: - "Search the web via DuckDuckGo and return matching results (title, url, snippet). Use for information not available in the local codebase, e.g. current docs, library APIs, or general knowledge.", + "Search the web via DuckDuckGo. Returns title, url, snippet. Use for info not in the local codebase.", schema, mutating: false, handler: async ({ query, max_results }) => {