[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78CTHKZ028JGD12MJ3WDJ22":3,"skill-same:01M78CTHKZ028JGD12MJ3WDJ22":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M78CTHKZ028JGD12MJ3WDJ22","adding-an-agent-tool",null,"Step-by-step reference for adding a new agent tool to KlennyCode — where the schema, dispatch case, approval preview, tool-name registries, ledger paths, barrel export and tests must all be touched, plus the prompt-caching rule that forbids state-driven tool gating. Read this before adding, removing or re-gating any tool.","DanTahir\u002FKlennyCode","DanTahir","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99351513?v=4","01M78CTFRJGAC45M96HFH32B1N","Dan Tahir","01M78CTFSYX1B4YMCTYFKFGQ8N",2,"MIT","https:\u002F\u002Fgithub.com\u002FDanTahir\u002FKlennyCode\u002Fblob\u002Fmain\u002F.klenny\u002Fskills\u002Fadding-an-agent-tool\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: adding-an-agent-tool\ndescription: >-\n  Step-by-step reference for adding a new agent tool to KlennyCode — where the\n  schema, dispatch case, approval preview, tool-name registries, ledger paths,\n  barrel export and tests must all be touched, plus the prompt-caching rule that\n  forbids state-driven tool gating. Read this before adding, removing or\n  re-gating any tool.\n---\n\n> Anchors here are **symbol names and grep patterns, never line numbers** — an earlier version of\n> this reference lived as a root-level markdown file full of line numbers and every one of them had\n> rotted (`executeTool` had moved ~500 lines, `resolveWorkspacePath` ~120). Grep for the symbol.\n\n## The files a new tool touches\n\n| Step | File | What goes there |\n|------|------|-----------------|\n| 1 | `agent\u002Fshared\u002Ftypes.ts` | add the name to the `ToolName` union, plus any family arrays that apply |\n| 2 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002F\u003Cmodule>.ts` | the implementation, returning `ToolResultPayload` |\n| 3 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002Findex.ts` | re-export from the barrel |\n| 4 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002Fdefinitions.ts` | the JSON schema in `getToolDefinitions()`'s `all[]` |\n| 5 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Forchestrator\u002Floop.ts` | a `case` in `dispatchTool()`, and an approval entry in `executeTool()` if it mutates |\n| 6 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Forchestrator\u002Fapproval-previews.ts` | a branch in `previewMutatingTool()` if it mutates |\n| 7 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Forchestrator\u002Fledger.ts` | `WRITE_TOOLS` + `collectPathsFromArgs` if it creates files |\n| 8 | `agent\u002Fshared\u002Fipc.ts`, `agent\u002Fsrc\u002Fmain\u002Fipc.ts`, `agent\u002Fsrc\u002Fpreload\u002Findex.ts` | only if the renderer needs to call it |\n| 9 | `agent\u002Ftests\u002F` | a test file; barrel tests already exist and will need updating |\n| 10 | `README.md` \u002F `KLENNY.md` | if user-visible behavior or architecture changed |\n\n---\n\n## 1. Register the name\n\n`ToolName` in `agent\u002Fshared\u002Ftypes.ts` is the single source of truth. Below it sit the family\narrays that drive gating and behavior — decide membership deliberately for each:\n\n- `CODING_ONLY_TOOLS` — needs a real project workspace; excluded from Assistant tabs. Currently\n  `run_command`, `read_terminal`, `codebase_search`, `parallel_write`.\n- `ASSISTANT_TOOLS` — the *entire* allow-set for Assistant tabs (file tools included, scoped to\n  `documentsDirectory`). If a tool should work there, it must be listed here explicitly.\n- `MUTATING_TOOLS` — used by reasoning-effort scoring, not by the approval gate.\n- `ALWAYS_BLOCKED_TOOLS` — hard-blocked pending human approval regardless of approval mode, and\n  refused outright inside subagents (the Pawprint tools).\n- `BROWSER_TOOLS`, `DOCX_TOOLS`, `GMAIL_READ_TOOLS`, `GMAIL_SEND_TOOLS`, `DISCORD_TOOLS` — the\n  option-dependent families.\n\n`ASSISTANT_TOOLS`' doc comment notes the Assistant system prompt **spells the same names out in\nprose**, not generated from the array — keep both in sync by hand.\n\n## 2. Implement it\n\nPut it in the module that fits (`file-ops.ts`, `search.ts`, `web.ts`, `shell.ts`, `browser.ts`,\n`image.ts`, …) or a new one. Always return `ToolResultPayload`:\n\n```typescript\n| { ok: true;  summary: string; data?: Record\u003Cstring, unknown> }\n| { ok: false; summary: string; error: string; data?: Record\u003Cstring, unknown> }\n```\n\n`summary` is user-visible; `error` is a machine-readable code; `data` is what the model reads.\n\n### Paths and the mutation sandbox\n\n```typescript\nconst abs = resolveWorkspacePath(args.path, root)          \u002F\u002F tools\u002Ffile-ops.ts\nif (!assertMutationAllowed(abs, root)) {                    \u002F\u002F main\u002Fworkspace.ts\n  return { ok: false, summary: 'Path outside workspace', error: 'sandbox' }\n}\n```\n\n**`assertMutationAllowed` RETURNS false — it does not throw.** A bare call inside a `try` block is\na silent sandbox escape (this actually shipped in `parallel_write`'s Phase 1). Only\n`resolveWorkspacePath` throws, and only for a structurally invalid path; it does no `..` stripping,\nso the boolean branch is the only thing between a relative path and an escape.\n\nAllowed mutation roots: the open workspace, the Assistant `documentsDirectory`, and always\n`~\u002F.klenny` plus Electron's `userData` (`alwaysAllowedMutationRoots()`).\n\n### Other implementation invariants\n\n- Respect EOL: `detectEol`\u002F`toLf`\u002F`fromLf` (`tools\u002Feol.ts`) — CRLF is the primary dev platform.\n- For edits, honor `fileReadCache` staleness (`mtimeMs` mismatch → `error: 'stale'`).\n- **A diff is a bounded preview, never raw content.** Use `makeDiff`\u002F`joinDiffs` (`tools\u002Fdiff.ts`)\n  and `readTextForDiff()` rather than `readFile` + diff — an unbounded diff once wrote a 61 MB\n  session file and froze the app.\n- If the model must *see* an image, the key is exactly `data.dataUrl` (lifted out by `loop.ts`);\n  any other key silently becomes truncated base64 garbage.\n- Wrap anything that can hang (Playwright, network) in a deadline race, as `browser.ts` does.\n\n## 3. Barrel export\n\nAdd it to `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002Findex.ts`. `agent\u002Ftests\u002Ftools-index-barrel.test.ts` asserts\nthe barrel re-exports every implementation function — extend it.\n\n## 4. Schema in `definitions.ts`\n\nAppend to the `all[]` array inside `getToolDefinitions(mode, restrictTo, codebaseSearchAvailable,\nhasWorkspace, isAssistant, gating)`:\n\n```typescript\n{\n  type: 'function',\n  function: {\n    name: 'write_file',\n    description: 'Write or overwrite a file.',\n    parameters: {\n      type: 'object',\n      properties: { path: { type: 'string' }, content: { type: 'string' } },\n      required: ['path', 'content']\n    }\n  }\n}\n```\n\nSchemas are **documentation only** — there is no ajv\u002Fzod validation at dispatch. Real enforcement\nis in the implementation, and models do send JSON-string-encoded arrays where a native array was\ndeclared, so coerce defensively (see `normalizeFilesArg` in `file-ops.ts` and\n`coerce-array-arg.test.ts`).\n\nThe description is the model's only instruction manual for the tool; spend words on routing rules\nand failure modes, not just a label.\n\n### ⛔ The gating rule you must not break\n\n`getToolDefinitions()`'s return value **is** the request's `tools` array, and providers serialize\nit *ahead* of the system prompt. A cached block is keyed on its entire preceding prefix, so a\n`tools` array that changes mid-conversation invalidates **every** cache breakpoint, including the\nfixed system one.\n\n**Never add a gate driven by per-turn conversation state.** This was a real, measured bug:\n`update_checklist` used to be hidden until `TabSession.activeChecklist` existed, so the first\n`create_checklist` call grew the array and re-wrote the whole prefix at full price\n(`cachedTokens=0`, `cacheWriteTokens=53456`) while the system message's own fingerprint was\nbyte-identical. Every legitimate gate derives from settings, tab kind or subagent type — all fixed\nfor a conversation's life. Prefer always offering the tool and returning a clean error\n(`no_active_checklist`) over hiding it.\n\nGates at the end of the function, all filter-style, all legitimate: `hasWorkspace`,\n`codebaseSearchAvailable`, `gating.imageGenerationAvailable`, docx\u002FGmail\u002FDiscord connection +\n`automationPermissions` + `*AvailableInCoding`, and `gating.browserAutomationAvailable`. Add new\noptional fields to `ToolGatingOptions`, which defaults every field **closed** so a caller that\nforgets one never over-shares.\n\n`agent\u002Ftests\u002Ftools-cache-stability.test.ts` pins this; it has positive controls, so don't \"fix\" a\nfailure by blinding it.\n\n## 5. Dispatch and approval in `loop.ts`\n\n`dispatchTool()` is a plain `switch (name)` ending in `default: { ok: false, error: 'unknown_tool' }`:\n\n```typescript\ncase 'edit_file':\n  return editFileTool(args as { path: string; old_string: string; new_string: string; replace_all?: boolean }, fileRoot)\n```\n\n`fileRoot` is the sandbox root (Assistant `documentsDirectory`, else `undefined` = open workspace).\nExtra capabilities arrive as injected dispatch objects (`imageGen`, `parallelWrite`, `toolCallId`)\nrather than globals — follow that pattern instead of reaching for module state.\n\n`executeTool()` runs the gates in order before dispatch:\n\n1. **Assistant-tab guard** — `tab.kind === 'assistant' && CODING_ONLY_TOOLS.includes(name)` is\n   refused server-side, because `getWorkspace()` is a process-global singleton and a hallucinated\n   or stale call would otherwise execute against whatever project another window has open. The\n   client-side allow-list is not sufficient on its own.\n2. **`ALWAYS_BLOCKED_TOOLS`** — always prompts; refused with `unsupported_in_subagent` in a subagent.\n3. **The standard mutating list** — `['write_file', 'edit_file', 'multi_edit', 'multi_write',\n   'delete_file', 'write_docx', 'edit_docx', 'generate_image', 'run_command']`:\n\n```typescript\nconst needsApproval = approvalMode === 'manual' || (approvalMode === 'command' && name === 'run_command')\nif (needsApproval) {\n  const preview = await previewMutatingTool(name, args, fileRoot)\n  const action = approvalManager.buildPendingFromTool(tab.id, tc.id, name as PendingActionKind, preview.title, preview.extra)\n  emit({ type: 'pending_action', tabId: tab.id, action })\n  const decision = await approvalManager.waitForDecision(action.id)\n  emit({ type: 'pending_action_resolved', tabId: tab.id, actionId: action.id })\n  if (decision === 'reject') return { payload: { ok: false, summary: 'User rejected action', error: 'rejected' }, status: 'rejected' }\n} else {\n  const ws = getWorkspace()\n  if (ws) await approvalManager.createCheckpoint(ws)\n}\n```\n\nAdding a name here also means adding it to `PendingActionKind` (grep it in `agent\u002Fshared\u002Ftypes.ts`)\nand handling the card in `ApprovalCard.tsx`. Note the `else` branch: skipping approval still takes\na checkpoint — don't drop it.\n\n**A tool whose content doesn't exist yet must not be listed here.** `parallel_write` is\ndeliberately absent and instead requests approval from *inside* the tool, once per job, via an\ninjected `approve()` callback; listing it would queue a second, contentless card. `browser` has its\nown independent policy gate (`'off' | 'ask' | 'auto'`) keyed on whether the action is mutating.\n\n**Subagent exclusion is a runtime check, not an allow-list one.** A subagent type may declare\n`tools: 'all'`, so allow-lists alone leak; `parallel_write` checks `unattended` inside its dispatch\ncase. Subagent runs also force `approvalMode: 'auto'`, so anything needing a human must refuse\noutright there.\n\n## 6. Approval preview\n\n`previewMutatingTool(name, args, root)` returns `{ title, extra }`:\n\n```typescript\nif (name === 'write_file') {\n  const { content: oldContent } = await readTextForDiff(resolveWorkspacePath(path, root))\n  return { title: `Write ${path}`, extra: { filePath: path, diff: makeDiff(oldContent, String(args.content), path) } }\n}\n```\n\nThis path ships over IPC to the renderer, so it needs the same bounded-diff discipline as the tool\nitself — it once had the identical unbounded-diff bug. Never let a preview throw; degrade to\n`{ title, extra: { filePath } }` with no diff.\n\n## 7. Ledger (only if the tool creates files)\n\nThe fabrication guard's C3 check flags a claimed-created file that no write targeted. Add the name\nto `WRITE_TOOLS` in `orchestrator\u002Fledger.ts` and teach `collectPathsFromArgs` your argument shape\n(including alias keys and map forms, as `multi_write` needs) — otherwise a file genuinely written\nby your tool gets hard-flagged as fabricated.\n\n## 8. IPC (only if the renderer calls it)\n\nFour coordinated edits, all in `agent\u002Fshared\u002Fipc.ts` + `agent\u002Fsrc\u002Fmain\u002Fipc.ts` +\n`agent\u002Fsrc\u002Fpreload\u002Findex.ts`:\n\n1. A channel constant in `IPC`, named `namespace:action` (`'memory:write'`, `'chat:sendMessage'`).\n2. A method on the `KlennyApi` interface.\n3. `ipcMain.handle(IPC.x, …)` in main.\n4. `ipcRenderer.invoke(IPC.x, …)` in the preload bridge (or an `on`-listener returning an\n   unsubscribe function, for streaming events).\n\n## 9. Tests\n\n`bun test` (Bun, not npm\u002Fyarn). Existing suites you will likely need to update: `tools.test.ts`,\n`tools-index-barrel.test.ts`, `tools-cache-stability.test.ts`, `global-mutation-sandbox.test.ts`,\n`ledger.test.ts`, and `diff-safety.test.ts` if the tool produces diffs. Cover at minimum: the happy\npath, an out-of-sandbox path (asserting nothing was written), and a malformed-arguments shape.\n\n## Checklist\n\n1. `ToolName` + family arrays in `agent\u002Fshared\u002Ftypes.ts`\n2. Implementation returning `ToolResultPayload`, with the `assertMutationAllowed` **return-value**\n   branch if it mutates\n3. Barrel export in `tools\u002Findex.ts`\n4. Schema in `getToolDefinitions()`'s `all[]` — no per-turn-state gate\n5. `dispatchTool()` case; approval entry + `PendingActionKind` if mutating; runtime `unattended`\n   refusal if it needs a human\n6. `previewMutatingTool()` branch with a bounded diff\n7. `WRITE_TOOLS` + `collectPathsFromArgs` if it creates files\n8. IPC channel \u002F handler \u002F preload \u002F `KlennyApi` if the UI needs it\n9. Tests in `agent\u002Ftests\u002F`\n10. `README.md` and `KLENNY.md` if documented behavior changed\n","> Anchors here are **symbol names and grep patterns, never line numbers** — an earlier version of\n> this reference lived as a root-level markdown file full of line numbers and every one of them had\n> rotted (`executeTool` had moved ~500 lines, `resolveWorkspacePath` ~120). Grep for the symbol.\n\n## The files a new tool touches\n\n| Step | File | What goes there |\n|------|------|-----------------|\n| 1 | `agent\u002Fshared\u002Ftypes.ts` | add the name to the `ToolName` union, plus any family arrays that apply |\n| 2 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002F\u003Cmodule>.ts` | the implementation, returning `ToolResultPayload` |\n| 3 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002Findex.ts` | re-export from the barrel |\n| 4 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002Fdefinitions.ts` | the JSON schema in `getToolDefinitions()`'s `all[]` |\n| 5 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Forchestrator\u002Floop.ts` | a `case` in `dispatchTool()`, and an approval entry in `executeTool()` if it mutates |\n| 6 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Forchestrator\u002Fapproval-previews.ts` | a branch in `previewMutatingTool()` if it mutates |\n| 7 | `agent\u002Fsrc\u002Fmain\u002Fagent\u002Forchestrator\u002Fledger.ts` | `WRITE_TOOLS` + `collectPathsFromArgs` if it creates files |\n| 8 | `agent\u002Fshared\u002Fipc.ts`, `agent\u002Fsrc\u002Fmain\u002Fipc.ts`, `agent\u002Fsrc\u002Fpreload\u002Findex.ts` | only if the renderer needs to call it |\n| 9 | `agent\u002Ftests\u002F` | a test file; barrel tests already exist and will need updating |\n| 10 | `README.md` \u002F `KLENNY.md` | if user-visible behavior or architecture changed |\n\n---\n\n## 1. Register the name\n\n`ToolName` in `agent\u002Fshared\u002Ftypes.ts` is the single source of truth. Below it sit the family\narrays that drive gating and behavior — decide membership deliberately for each:\n\n- `CODING_ONLY_TOOLS` — needs a real project workspace; excluded from Assistant tabs. Currently\n  `run_command`, `read_terminal`, `codebase_search`, `parallel_write`.\n- `ASSISTANT_TOOLS` — the *entire* allow-set for Assistant tabs (file tools included, scoped to\n  `documentsDirectory`). If a tool should work there, it must be listed here explicitly.\n- `MUTATING_TOOLS` — used by reasoning-effort scoring, not by the approval gate.\n- `ALWAYS_BLOCKED_TOOLS` — hard-blocked pending human approval regardless of approval mode, and\n  refused outright inside subagents (the Pawprint tools).\n- `BROWSER_TOOLS`, `DOCX_TOOLS`, `GMAIL_READ_TOOLS`, `GMAIL_SEND_TOOLS`, `DISCORD_TOOLS` — the\n  option-dependent families.\n\n`ASSISTANT_TOOLS`' doc comment notes the Assistant system prompt **spells the same names out in\nprose**, not generated from the array — keep both in sync by hand.\n\n## 2. Implement it\n\nPut it in the module that fits (`file-ops.ts`, `search.ts`, `web.ts`, `shell.ts`, `browser.ts`,\n`image.ts`, …) or a new one. Always return `ToolResultPayload`:\n\n```typescript\n| { ok: true;  summary: string; data?: Record\u003Cstring, unknown> }\n| { ok: false; summary: string; error: string; data?: Record\u003Cstring, unknown> }\n```\n\n`summary` is user-visible; `error` is a machine-readable code; `data` is what the model reads.\n\n### Paths and the mutation sandbox\n\n```typescript\nconst abs = resolveWorkspacePath(args.path, root)          \u002F\u002F tools\u002Ffile-ops.ts\nif (!assertMutationAllowed(abs, root)) {                    \u002F\u002F main\u002Fworkspace.ts\n  return { ok: false, summary: 'Path outside workspace', error: 'sandbox' }\n}\n```\n\n**`assertMutationAllowed` RETURNS false — it does not throw.** A bare call inside a `try` block is\na silent sandbox escape (this actually shipped in `parallel_write`'s Phase 1). Only\n`resolveWorkspacePath` throws, and only for a structurally invalid path; it does no `..` stripping,\nso the boolean branch is the only thing between a relative path and an escape.\n\nAllowed mutation roots: the open workspace, the Assistant `documentsDirectory`, and always\n`~\u002F.klenny` plus Electron's `userData` (`alwaysAllowedMutationRoots()`).\n\n### Other implementation invariants\n\n- Respect EOL: `detectEol`\u002F`toLf`\u002F`fromLf` (`tools\u002Feol.ts`) — CRLF is the primary dev platform.\n- For edits, honor `fileReadCache` staleness (`mtimeMs` mismatch → `error: 'stale'`).\n- **A diff is a bounded preview, never raw content.** Use `makeDiff`\u002F`joinDiffs` (`tools\u002Fdiff.ts`)\n  and `readTextForDiff()` rather than `readFile` + diff — an unbounded diff once wrote a 61 MB\n  session file and froze the app.\n- If the model must *see* an image, the key is exactly `data.dataUrl` (lifted out by `loop.ts`);\n  any other key silently becomes truncated base64 garbage.\n- Wrap anything that can hang (Playwright, network) in a deadline race, as `browser.ts` does.\n\n## 3. Barrel export\n\nAdd it to `agent\u002Fsrc\u002Fmain\u002Fagent\u002Ftools\u002Findex.ts`. `agent\u002Ftests\u002Ftools-index-barrel.test.ts` asserts\nthe barrel re-exports every implementation function — extend it.\n\n## 4. Schema in `definitions.ts`\n\nAppend to the `all[]` array inside `getToolDefinitions(mode, restrictTo, codebaseSearchAvailable,\nhasWorkspace, isAssistant, gating)`:\n\n```typescript\n{\n  type: 'function',\n  function: {\n    name: 'write_file',\n    description: 'Write or overwrite a file.',\n    parameters: {\n      type: 'object',\n      properties: { path: { type: 'string' }, content: { type: 'string' } },\n      required: ['path', 'content']\n    }\n  }\n}\n```\n\nSchemas are **documentation only** — there is no ajv\u002Fzod validation at dispatch. Real enforcement\nis in the implementation, and models do send JSON-string-encoded arrays where a native array was\ndeclared, so coerce defensively (see `normalizeFilesArg` in `file-ops.ts` and\n`coerce-array-arg.test.ts`).\n\nThe description is the model's only instruction manual for the tool; spend words on routing rules\nand failure modes, not just a label.\n\n### ⛔ The gating rule you must not break\n\n`getToolDefinitions()`'s return value **is** the request's `tools` array, and providers serialize\nit *ahead* of the system prompt. A cached block is keyed on its entire preceding prefix, so a\n`tools` array that changes mid-conversation invalidates **every** cache breakpoint, including the\nfixed system one.\n\n**Never add a gate driven by per-turn conversation state.** This was a real, measured bug:\n`update_checklist` used to be hidden until `TabSession.activeChecklist` existed, so the first\n`create_checklist` call grew the array and re-wrote the whole prefix at full price\n(`cachedTokens=0`, `cacheWriteTokens=53456`) while the system message's own fingerprint was\nbyte-identical. Every legitimate gate derives from settings, tab kind or subagent type — all fixed\nfor a conversation's life. Prefer always offering the tool and returning a clean error\n(`no_active_checklist`) over hiding it.\n\nGates at the end of the function, all filter-style, all legitimate: `hasWorkspace`,\n`codebaseSearchAvailable`, `gating.imageGenerationAvailable`, docx\u002FGmail\u002FDiscord connection +\n`automationPermissions` + `*AvailableInCoding`, and `gating.browserAutomationAvailable`. Add new\noptional fields to `ToolGatingOptions`, which defaults every field **closed** so a caller that\nforgets one never over-shares.\n\n`agent\u002Ftests\u002Ftools-cache-stability.test.ts` pins this; it has positive controls, so don't \"fix\" a\nfailure by blinding it.\n\n## 5. Dispatch and approval in `loop.ts`\n\n`dispatchTool()` is a plain `switch (name)` ending in `default: { ok: false, error: 'unknown_tool' }`:\n\n```typescript\ncase 'edit_file':\n  return editFileTool(args as { path: string; old_string: string; new_string: string; replace_all?: boolean }, fileRoot)\n```\n\n`fileRoot` is the sandbox root (Assistant `documentsDirectory`, else `undefined` = open workspace).\nExtra capabilities arrive as injected dispatch objects (`imageGen`, `parallelWrite`, `toolCallId`)\nrather than globals — follow that pattern instead of reaching for module state.\n\n`executeTool()` runs the gates in order before dispatch:\n\n1. **Assistant-tab guard** — `tab.kind === 'assistant' && CODING_ONLY_TOOLS.includes(name)` is\n   refused server-side, because `getWorkspace()` is a process-global singleton and a hallucinated\n   or stale call would otherwise execute against whatever project another window has open. The\n   client-side allow-list is not sufficient on its own.\n2. **`ALWAYS_BLOCKED_TOOLS`** — always prompts; refused with `unsupported_in_subagent` in a subagent.\n3. **The standard mutating list** — `['write_file', 'edit_file', 'multi_edit', 'multi_write',\n   'delete_file', 'write_docx', 'edit_docx', 'generate_image', 'run_command']`:\n\n```typescript\nconst needsApproval = approvalMode === 'manual' || (approvalMode === 'command' && name === 'run_command')\nif (needsApproval) {\n  const preview = await previewMutatingTool(name, args, fileRoot)\n  const action = approvalManager.buildPendingFromTool(tab.id, tc.id, name as PendingActionKind, preview.title, preview.extra)\n  emit({ type: 'pending_action', tabId: tab.id, action })\n  const decision = await approvalManager.waitForDecision(action.id)\n  emit({ type: 'pending_action_resolved', tabId: tab.id, actionId: action.id })\n  if (decision === 'reject') return { payload: { ok: false, summary: 'User rejected action', error: 'rejected' }, status: 'rejected' }\n} else {\n  const ws = getWorkspace()\n  if (ws) await approvalManager.createCheckpoint(ws)\n}\n```\n\nAdding a name here also means adding it to `PendingActionKind` (grep it in `agent\u002Fshared\u002Ftypes.ts`)\nand handling the card in `ApprovalCard.tsx`. Note the `else` branch: skipping approval still takes\na checkpoint — don't drop it.\n\n**A tool whose content doesn't exist yet must not be listed here.** `parallel_write` is\ndeliberately absent and instead requests approval from *inside* the tool, once per job, via an\ninjected `approve()` callback; listing it would queue a second, contentless card. `browser` has its\nown independent policy gate (`'off' | 'ask' | 'auto'`) keyed on whether the action is mutating.\n\n**Subagent exclusion is a runtime check, not an allow-list one.** A subagent type may declare\n`tools: 'all'`, so allow-lists alone leak; `parallel_write` checks `unattended` inside its dispatch\ncase. Subagent runs also force `approvalMode: 'auto'`, so anything needing a human must refuse\noutright there.\n\n## 6. Approval preview\n\n`previewMutatingTool(name, args, root)` returns `{ title, extra }`:\n\n```typescript\nif (name === 'write_file') {\n  const { content: oldContent } = await readTextForDiff(resolveWorkspacePath(path, root))\n  return { title: `Write ${path}`, extra: { filePath: path, diff: makeDiff(oldContent, String(args.content), path) } }\n}\n```\n\nThis path ships over IPC to the renderer, so it needs the same bounded-diff discipline as the tool\nitself — it once had the identical unbounded-diff bug. Never let a preview throw; degrade to\n`{ title, extra: { filePath } }` with no diff.\n\n## 7. Ledger (only if the tool creates files)\n\nThe fabrication guard's C3 check flags a claimed-created file that no write targeted. Add the name\nto `WRITE_TOOLS` in `orchestrator\u002Fledger.ts` and teach `collectPathsFromArgs` your argument shape\n(including alias keys and map forms, as `multi_write` needs) — otherwise a file genuinely written\nby your tool gets hard-flagged as fabricated.\n\n## 8. IPC (only if the renderer calls it)\n\nFour coordinated edits, all in `agent\u002Fshared\u002Fipc.ts` + `agent\u002Fsrc\u002Fmain\u002Fipc.ts` +\n`agent\u002Fsrc\u002Fpreload\u002Findex.ts`:\n\n1. A channel constant in `IPC`, named `namespace:action` (`'memory:write'`, `'chat:sendMessage'`).\n2. A method on the `KlennyApi` interface.\n3. `ipcMain.handle(IPC.x, …)` in main.\n4. `ipcRenderer.invoke(IPC.x, …)` in the preload bridge (or an `on`-listener returning an\n   unsubscribe function, for streaming events).\n\n## 9. Tests\n\n`bun test` (Bun, not npm\u002Fyarn). Existing suites you will likely need to update: `tools.test.ts`,\n`tools-index-barrel.test.ts`, `tools-cache-stability.test.ts`, `global-mutation-sandbox.test.ts`,\n`ledger.test.ts`, and `diff-safety.test.ts` if the tool produces diffs. Cover at minimum: the happy\npath, an out-of-sandbox path (asserting nothing was written), and a malformed-arguments shape.\n\n## Checklist\n\n1. `ToolName` + family arrays in `agent\u002Fshared\u002Ftypes.ts`\n2. Implementation returning `ToolResultPayload`, with the `assertMutationAllowed` **return-value**\n   branch if it mutates\n3. Barrel export in `tools\u002Findex.ts`\n4. Schema in `getToolDefinitions()`'s `all[]` — no per-turn-state gate\n5. `dispatchTool()` case; approval entry + `PendingActionKind` if mutating; runtime `unattended`\n   refusal if it needs a human\n6. `previewMutatingTool()` branch with a bounded diff\n7. `WRITE_TOOLS` + `collectPathsFromArgs` if it creates files\n8. IPC channel \u002F handler \u002F preload \u002F `KlennyApi` if the UI needs it\n9. Tests in `agent\u002Ftests\u002F`\n10. `README.md` and `KLENNY.md` if documented behavior changed\n",{"name":5,"description":7},"main","d533783dd9e5dcaca8da61ed02b5e06f92d000de",".klenny\u002Fskills\u002Fadding-an-agent-tool",1,"https:\u002F\u002Fgithub.com\u002FDanTahir\u002FKlennyCode","https:\u002F\u002Fgithub.com\u002FDanTahir","2026-10-24 08:59:49",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add DanTahir\u002FKlennyCode --skill adding-an-agent-tool",{"tool":37,"command":38},"bunx","bunx skills add DanTahir\u002FKlennyCode --skill adding-an-agent-tool",{"tool":40,"command":41},"pnpm","pnpm dlx skills add DanTahir\u002FKlennyCode --skill adding-an-agent-tool","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDanTahir\u002FKlennyCode\u002Fblob\u002Fmain\u002F.klenny\u002Fskills\u002Fadding-an-agent-tool\u002FSKILL.md",true,[],[46,53,60],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M78CTY177RRDNBJ8J2SZREX9","prompt-caching-safety","Before adding anything to the system prompt or the start of the message array in this codebase, check whether it breaks Anthropic\u002FQwen-style explicit prompt caching — a real regression that shipped once (see project memory \"System prompt caching regression...\"). Use this whenever touching buildSystemPrompt, toORMessages, applyCacheControl, or anything that runs on every agent turn.","https:\u002F\u002Fgithub.com\u002FDanTahir\u002FKlennyCode\u002Fblob\u002Fmain\u002Fagent\u002F.klenny\u002Fskills\u002Fprompt-caching-safety\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M78CTVV1TYM3PBB5AHTJR10H","placeholder-unused","placeholder","https:\u002F\u002Fgithub.com\u002FDanTahir\u002FKlennyCode\u002Fblob\u002Fmain\u002F.klenny\u002Fskills\u002Fplaceholder-unused\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M78CTPJ1MQ482X7J384KY6D6","caching-live-verification","MANDATORY for any change touching prompt caching (openrouter\u002Fcaching.ts, cacheDiag.ts, client.ts request building, the tools array, toORMessages, the trailing time note, compaction): write a throwaway script that runs a REAL live OpenRouter request ladder, run it, confirm read-back, then delete the script. Unit tests cannot observe upstream cache behavior.","https:\u002F\u002Fgithub.com\u002FDanTahir\u002FKlennyCode\u002Fblob\u002Fmain\u002F.klenny\u002Fskills\u002Fcaching-live-verification\u002FSKILL.md",[],[]]