@useavalon/caelence-agent 0.2.2-canary.1 → 0.2.2-canary.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useavalon/caelence-agent",
3
- "version": "0.2.2-canary.1",
3
+ "version": "0.2.2-canary.3",
4
4
  "description": "Caelence agent: Strands turn loop, local tools, skills, evals, and a themable terminal UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -57,7 +57,6 @@
57
57
  "dependencies": {
58
58
  "@strands-agents/sdk": "^1.10.0",
59
59
  "ink": "^5.2.1",
60
- "ink-text-input": "^6.0.0",
61
60
  "openai": "^6.45.0",
62
61
  "react": "^18.3.1"
63
62
  },
@@ -0,0 +1,23 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { applyTextInputKey } from "./tui-text-input.ts";
3
+
4
+ describe("tui text input", () => {
5
+ test("inserts, moves, deletes, and submits", () => {
6
+ expect(applyTextInputKey("ab", 2, "c", {})).toEqual({ value: "abc", cursor: 3 });
7
+ expect(applyTextInputKey("abc", 3, "", { backspace: true })).toEqual({
8
+ value: "ab",
9
+ cursor: 2,
10
+ });
11
+ expect(applyTextInputKey("abc", 1, "", { delete: true })).toEqual({ value: "ac", cursor: 1 });
12
+ expect(applyTextInputKey("abc", 3, "", { leftArrow: true })).toEqual({
13
+ value: "abc",
14
+ cursor: 2,
15
+ });
16
+ expect(applyTextInputKey("hi", 2, "", { return: true })).toEqual({
17
+ value: "hi",
18
+ cursor: 2,
19
+ submit: true,
20
+ });
21
+ expect(applyTextInputKey("hi", 2, "", { upArrow: true })).toBeUndefined();
22
+ });
23
+ });
@@ -0,0 +1,40 @@
1
+ export interface TextInputKey {
2
+ return?: boolean;
3
+ escape?: boolean;
4
+ tab?: boolean;
5
+ upArrow?: boolean;
6
+ downArrow?: boolean;
7
+ leftArrow?: boolean;
8
+ rightArrow?: boolean;
9
+ backspace?: boolean;
10
+ delete?: boolean;
11
+ ctrl?: boolean;
12
+ meta?: boolean;
13
+ }
14
+
15
+ export function applyTextInputKey(
16
+ value: string,
17
+ cursor: number,
18
+ input: string,
19
+ key: TextInputKey,
20
+ ): { value: string; cursor: number; submit?: boolean } | undefined {
21
+ if (key.return) return { value, cursor, submit: true };
22
+ if (key.escape || key.tab || key.upArrow || key.downArrow || key.ctrl || key.meta) {
23
+ return undefined;
24
+ }
25
+ if (key.leftArrow) return { value, cursor: Math.max(0, cursor - 1) };
26
+ if (key.rightArrow) return { value, cursor: Math.min(value.length, cursor + 1) };
27
+ if (key.backspace) {
28
+ if (cursor === 0) return { value, cursor };
29
+ return { value: value.slice(0, cursor - 1) + value.slice(cursor), cursor: cursor - 1 };
30
+ }
31
+ if (key.delete) {
32
+ if (cursor >= value.length) return { value, cursor };
33
+ return { value: value.slice(0, cursor) + value.slice(cursor + 1), cursor };
34
+ }
35
+ if (!input) return undefined;
36
+ return {
37
+ value: value.slice(0, cursor) + input + value.slice(cursor),
38
+ cursor: cursor + input.length,
39
+ };
40
+ }
@@ -0,0 +1,38 @@
1
+ import { Text, useInput } from "ink";
2
+ import type React from "react";
3
+ import { useEffect, useState } from "react";
4
+ import { applyTextInputKey } from "./tui-text-input.ts";
5
+
6
+ export function TuiTextInput(
7
+ props: Readonly<{
8
+ value: string;
9
+ onChange: (value: string) => void;
10
+ onSubmit: (value: string) => void;
11
+ }>,
12
+ ): React.ReactElement {
13
+ const [cursor, setCursor] = useState(props.value.length);
14
+
15
+ useEffect(() => {
16
+ setCursor((current) => Math.min(Math.max(current, 0), props.value.length));
17
+ }, [props.value]);
18
+
19
+ useInput((input, key) => {
20
+ const next = applyTextInputKey(props.value, cursor, input, key);
21
+ if (!next) return;
22
+ if (next.submit) {
23
+ props.onSubmit(next.value);
24
+ return;
25
+ }
26
+ if (next.value !== props.value) props.onChange(next.value);
27
+ setCursor(next.cursor);
28
+ });
29
+
30
+ const atEnd = cursor >= props.value.length;
31
+ return (
32
+ <Text>
33
+ {props.value.slice(0, cursor)}
34
+ <Text inverse>{atEnd ? " " : props.value.slice(cursor, cursor + 1)}</Text>
35
+ {atEnd ? null : props.value.slice(cursor + 1)}
36
+ </Text>
37
+ );
38
+ }
package/src/cli/tui.tsx CHANGED
@@ -1,5 +1,4 @@
1
1
  import { Box, render, Text, useApp, useInput, useStdout } from "ink";
2
- import TextInput from "ink-text-input";
3
2
  import type React from "react";
4
3
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
4
  import { resolveOpenRouter } from "../config.ts";
@@ -41,6 +40,7 @@ import {
41
40
  visibleTranscriptCount,
42
41
  } from "./tui-layout.ts";
43
42
  import { enterAltScreen } from "./tui-screen.ts";
43
+ import { TuiTextInput } from "./tui-text-input.tsx";
44
44
 
45
45
  type ToolStatus = "running" | "ok" | "fail";
46
46
 
@@ -521,7 +521,7 @@ function ComposerFooter(
521
521
  <Box flexDirection="column">
522
522
  <Box>
523
523
  <Text color={props.theme.brand}>› </Text>
524
- <TextInput value={props.value} onChange={props.onChange} onSubmit={props.onSubmit} />
524
+ <TuiTextInput value={props.value} onChange={props.onChange} onSubmit={props.onSubmit} />
525
525
  </Box>
526
526
  {props.slashOpen ? (
527
527
  <SlashMenu
@@ -57,4 +57,46 @@ describe("exec approval", () => {
57
57
  await gate.request({ callId: "1", toolName: "exec", input: { command: "sudo ls" } }),
58
58
  ).toBe(false);
59
59
  });
60
+
61
+ test("prompt policy asks before ordinary file writes", async () => {
62
+ const asked: string[] = [];
63
+ const alwaysAllow = new Set<string>();
64
+ const gate = createExecApprovalGate({
65
+ policy: "prompt",
66
+ alwaysAllow,
67
+ ask: async (req) => {
68
+ asked.push(`${req.toolName}:${String(req.input.path)}`);
69
+ return true;
70
+ },
71
+ });
72
+ expect(
73
+ await gate.request({
74
+ callId: "1",
75
+ toolName: "write_file",
76
+ input: { path: "README.md", content: "x" },
77
+ }),
78
+ ).toBe(true);
79
+ expect(asked).toEqual(["write_file:README.md"]);
80
+ alwaysAllow.add("write_file");
81
+ alwaysAllow.add("edit_file");
82
+ expect(
83
+ await gate.request({
84
+ callId: "2",
85
+ toolName: "edit_file",
86
+ input: { path: "README.md", old: "x", new: "y" },
87
+ }),
88
+ ).toBe(true);
89
+ expect(asked).toEqual(["write_file:README.md"]);
90
+ });
91
+
92
+ test("deny and auto still allow file writes", async () => {
93
+ const deny = createExecApprovalGate({ policy: "deny" });
94
+ const auto = createExecApprovalGate({ policy: "auto" });
95
+ expect(
96
+ await deny.request({ callId: "1", toolName: "write_file", input: { path: "a.ts" } }),
97
+ ).toBe(true);
98
+ expect(
99
+ await auto.request({ callId: "2", toolName: "edit_file", input: { path: "a.ts" } }),
100
+ ).toBe(true);
101
+ });
60
102
  });
@@ -16,6 +16,10 @@ export function isRiskyToolCall(toolName: string): boolean {
16
16
  return toolName === "exec" || toolName === "git_commit";
17
17
  }
18
18
 
19
+ export function isFileWriteTool(toolName: string): boolean {
20
+ return toolName === "edit_file" || toolName === "write_file";
21
+ }
22
+
19
23
  /** Host-side denylist — local exec is the machine, not a sandbox. */
20
24
  export const DESTRUCTIVE_COMMAND_PATTERNS: readonly RegExp[] = [
21
25
  /\bsudo\b/,
@@ -55,10 +59,28 @@ export interface ExecApprovalGateDeps {
55
59
  alwaysAllow?: Set<string>;
56
60
  }
57
61
 
62
+ async function promptAsk(deps: ExecApprovalGateDeps, req: ApprovalRequest): Promise<boolean> {
63
+ deps.emit?.({
64
+ kind: "approval_request",
65
+ callId: req.callId,
66
+ toolName: req.toolName,
67
+ input: req.input,
68
+ });
69
+ if (!deps.ask) return false;
70
+ return deps.ask(req);
71
+ }
72
+
58
73
  export function createExecApprovalGate(deps: ExecApprovalGateDeps): ApprovalGate {
59
74
  const always = deps.alwaysAllow ?? new Set<string>();
60
75
  return {
61
76
  async request(req) {
77
+ if (isFileWriteTool(req.toolName)) {
78
+ if (always.has("write_file") || always.has("edit_file") || always.has(req.toolName)) {
79
+ return true;
80
+ }
81
+ if (deps.policy === "prompt" && deps.ask) return promptAsk(deps, req);
82
+ return true;
83
+ }
62
84
  if (!isRiskyToolCall(req.toolName)) return true;
63
85
  if (always.has(req.toolName)) return true;
64
86
  if (deps.policy === "deny") return false;
@@ -66,14 +88,7 @@ export function createExecApprovalGate(deps: ExecApprovalGateDeps): ApprovalGate
66
88
  if (deps.policy === "auto") {
67
89
  return !isLikelyDestructive(command);
68
90
  }
69
- deps.emit?.({
70
- kind: "approval_request",
71
- callId: req.callId,
72
- toolName: req.toolName,
73
- input: req.input,
74
- });
75
- if (!deps.ask) return false;
76
- return deps.ask(req);
91
+ return promptAsk(deps, req);
77
92
  },
78
93
  };
79
94
  }
@@ -0,0 +1,46 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ createMcpServer,
4
+ mcpToolListItem,
5
+ READ_ONLY_ANNOTATIONS,
6
+ resolveToolAnnotations,
7
+ UNKNOWN_TOOL_ANNOTATIONS,
8
+ } from "./mcp.ts";
9
+
10
+ describe("tool annotations", () => {
11
+ test("requires all four hints or falls back", () => {
12
+ expect(resolveToolAnnotations(undefined)).toEqual(UNKNOWN_TOOL_ANNOTATIONS);
13
+ expect(resolveToolAnnotations({ readOnlyHint: true })).toEqual(UNKNOWN_TOOL_ANNOTATIONS);
14
+ expect(resolveToolAnnotations(READ_ONLY_ANNOTATIONS)).toEqual(READ_ONLY_ANNOTATIONS);
15
+ });
16
+
17
+ test("tools/list payload includes explicit boolean hints", () => {
18
+ const listed = mcpToolListItem({
19
+ name: "git_status",
20
+ description: "status",
21
+ inputSchema: { type: "object", properties: {} },
22
+ annotations: READ_ONLY_ANNOTATIONS,
23
+ async handler() {
24
+ return { content: [{ type: "text", text: "ok" }] };
25
+ },
26
+ });
27
+ expect(listed.annotations).toEqual({
28
+ readOnlyHint: true,
29
+ destructiveHint: false,
30
+ idempotentHint: true,
31
+ openWorldHint: false,
32
+ });
33
+ const server = createMcpServer([
34
+ {
35
+ name: "git_status",
36
+ description: "status",
37
+ inputSchema: { type: "object", properties: {} },
38
+ annotations: READ_ONLY_ANNOTATIONS,
39
+ async handler() {
40
+ return { content: [{ type: "text", text: "ok" }] };
41
+ },
42
+ },
43
+ ]);
44
+ expect(server.listTools()[0]?.annotations.readOnlyHint).toBe(true);
45
+ });
46
+ });
package/src/core/mcp.ts CHANGED
@@ -8,10 +8,65 @@ export interface ToolResult {
8
8
  structuredContent?: Record<string, unknown>;
9
9
  }
10
10
 
11
+ export interface McpToolAnnotations {
12
+ readOnlyHint: boolean;
13
+ destructiveHint: boolean;
14
+ idempotentHint: boolean;
15
+ openWorldHint: boolean;
16
+ }
17
+
18
+ export const READ_ONLY_ANNOTATIONS: McpToolAnnotations = {
19
+ readOnlyHint: true,
20
+ destructiveHint: false,
21
+ idempotentHint: true,
22
+ openWorldHint: false,
23
+ };
24
+
25
+ export const UNKNOWN_TOOL_ANNOTATIONS: McpToolAnnotations = {
26
+ readOnlyHint: false,
27
+ destructiveHint: true,
28
+ idempotentHint: false,
29
+ openWorldHint: true,
30
+ };
31
+
32
+ export function resolveToolAnnotations(raw: unknown): McpToolAnnotations {
33
+ if (!raw || typeof raw !== "object") return UNKNOWN_TOOL_ANNOTATIONS;
34
+ const rec = raw as Record<string, unknown>;
35
+ if (
36
+ typeof rec.readOnlyHint !== "boolean" ||
37
+ typeof rec.destructiveHint !== "boolean" ||
38
+ typeof rec.idempotentHint !== "boolean" ||
39
+ typeof rec.openWorldHint !== "boolean"
40
+ ) {
41
+ return UNKNOWN_TOOL_ANNOTATIONS;
42
+ }
43
+ return {
44
+ readOnlyHint: rec.readOnlyHint,
45
+ destructiveHint: rec.destructiveHint,
46
+ idempotentHint: rec.idempotentHint,
47
+ openWorldHint: rec.openWorldHint,
48
+ };
49
+ }
50
+
51
+ export function mcpToolListItem(tool: McpToolDefinition): {
52
+ name: string;
53
+ description: string;
54
+ inputSchema: Record<string, unknown>;
55
+ annotations: McpToolAnnotations;
56
+ } {
57
+ return {
58
+ name: tool.name,
59
+ description: tool.description,
60
+ inputSchema: tool.inputSchema,
61
+ annotations: tool.annotations,
62
+ };
63
+ }
64
+
11
65
  export interface McpToolDefinition {
12
66
  name: string;
13
67
  description: string;
14
68
  inputSchema: Record<string, unknown>;
69
+ annotations: McpToolAnnotations;
15
70
  handler(input: Record<string, unknown>): Promise<ToolResult>;
16
71
  }
17
72
 
@@ -167,11 +222,7 @@ async function dispatch(
167
222
  return {};
168
223
  case "tools/list":
169
224
  return {
170
- tools: server.listTools().map((t) => ({
171
- name: t.name,
172
- description: t.description,
173
- inputSchema: t.inputSchema,
174
- })),
225
+ tools: server.listTools().map(mcpToolListItem),
175
226
  };
176
227
  case "tools/call": {
177
228
  const params = req.params ?? {};
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import type { McpToolDefinition } from "./mcp.ts";
2
+ import { type McpToolDefinition, UNKNOWN_TOOL_ANNOTATIONS } from "./mcp.ts";
3
3
  import {
4
4
  filterToolsForMode,
5
5
  parseAgentMode,
@@ -12,6 +12,7 @@ function stub(name: string): McpToolDefinition {
12
12
  name,
13
13
  description: name,
14
14
  inputSchema: { type: "object", properties: {} },
15
+ annotations: UNKNOWN_TOOL_ANNOTATIONS,
15
16
  async handler() {
16
17
  return { content: [{ type: "text", text: name }] };
17
18
  },
package/src/core/mode.ts CHANGED
@@ -55,6 +55,7 @@ export function modePrompt(mode: AgentMode): string {
55
55
  return [
56
56
  "## Mode: agent",
57
57
  "You may edit files, run approved exec, and commit when the user asked for the change.",
58
+ "If they asked to change a file, call write_file or edit_file. Do not claim the write until the tool succeeds.",
58
59
  "Use todo_write for multi-step work. Prefer git_status / git_diff / git_log over exec for git.",
59
60
  ].join("\n");
60
61
  }
@@ -2,7 +2,7 @@ import { noopObservability } from "../observability/noop.ts";
2
2
  import { sanitize } from "../observability/sanitize.ts";
3
3
  import type { Observability } from "../observability/types.ts";
4
4
  import type { ApprovalGate } from "./approval.ts";
5
- import { isRiskyToolCall } from "./approval.ts";
5
+ import { isFileWriteTool, isRiskyToolCall } from "./approval.ts";
6
6
  import { errorMessage, isAbortError } from "./errors.ts";
7
7
  import type { AgentEventEmitter, MainModelProvider } from "./events.ts";
8
8
  import type { HookRunner } from "./hooks.ts";
@@ -359,7 +359,7 @@ async function invokeGuardedBody(
359
359
  result = errorResult(errorText);
360
360
  }
361
361
  let approved = true;
362
- if (!result && isRiskyToolCall(def.name)) {
362
+ if (!result && (isRiskyToolCall(def.name) || isFileWriteTool(def.name))) {
363
363
  approved = await approval.request({ callId, toolName: def.name, input });
364
364
  }
365
365
  if (result) {
@@ -439,6 +439,7 @@ export function buildSystemPrompt(input: {
439
439
  "You are a coding agent in this project.",
440
440
  `Project root: ${input.cwd}.`,
441
441
  "Prefer small, targeted edits. Use edit_file for snippets, write_file for new files.",
442
+ "If the user asked to change a file, call write_file or edit_file before you reply. Do not say you wrote, edited, or saved a file unless that tool returned success.",
442
443
  "Use read_file, glob, and grep to inspect the repo. Do not use exec to read or search files.",
443
444
  "Use git_status, git_diff, and git_log for git. git_commit requires approval and does not push.",
444
445
  "Read skills with read_skill when a task matches a skill name. Spawn a subagent with task for a focused job.",
@@ -3,6 +3,7 @@ import {
3
3
  errorResult,
4
4
  jsonResult,
5
5
  type McpToolDefinition,
6
+ resolveToolAnnotations,
6
7
  type ToolResult,
7
8
  textResult,
8
9
  } from "./mcp.ts";
@@ -19,6 +20,7 @@ export interface StdioMcpClientOptions {
19
20
  args?: string[];
20
21
  env?: Record<string, string>;
21
22
  cwd?: string;
23
+ namePrefix?: string;
22
24
  }
23
25
 
24
26
  /**
@@ -47,6 +49,10 @@ export async function loadStdioMcpTools(
47
49
  pending.clear();
48
50
  };
49
51
 
52
+ void Promise.resolve(proc.exited).then(() => {
53
+ if (!closed) failAll(new Error("MCP process closed"));
54
+ });
55
+
50
56
  const onLine = (line: string): void => {
51
57
  const trimmed = line.trim();
52
58
  if (!trimmed) return;
@@ -72,7 +78,10 @@ export async function loadStdioMcpTools(
72
78
  try {
73
79
  while (true) {
74
80
  const { done, value } = await reader.read();
75
- if (done) break;
81
+ if (done) {
82
+ failAll(new Error("MCP process closed"));
83
+ break;
84
+ }
76
85
  buffer += decoder.decode(value, { stream: true });
77
86
  let idx = buffer.indexOf("\n");
78
87
  while (idx >= 0) {
@@ -109,23 +118,56 @@ export async function loadStdioMcpTools(
109
118
  }
110
119
  };
111
120
 
112
- await rpc("initialize", {
113
- protocolVersion: "2024-11-05",
114
- capabilities: {},
115
- clientInfo: { name: "caelence-harness", version: "0.1.0" },
116
- });
117
- await rpc("notifications/initialized").catch(() => undefined);
118
-
119
- const listed = (await rpc("tools/list")) as {
120
- tools?: Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>;
121
+ const initMs = 12_000;
122
+ let listed: {
123
+ tools?: Array<{
124
+ name: string;
125
+ description?: string;
126
+ inputSchema?: Record<string, unknown>;
127
+ annotations?: unknown;
128
+ }>;
121
129
  };
130
+ let timer: ReturnType<typeof setTimeout> | undefined;
131
+ try {
132
+ listed = (await Promise.race([
133
+ (async () => {
134
+ await rpc("initialize", {
135
+ protocolVersion: "2024-11-05",
136
+ capabilities: {},
137
+ clientInfo: { name: "caelence-harness", version: "0.1.0" },
138
+ });
139
+ await rpc("notifications/initialized").catch(() => undefined);
140
+ return rpc("tools/list");
141
+ })(),
142
+ new Promise<never>((_, reject) => {
143
+ timer = setTimeout(() => {
144
+ close();
145
+ reject(new Error("MCP initialize timed out"));
146
+ }, initMs);
147
+ }),
148
+ ])) as {
149
+ tools?: Array<{
150
+ name: string;
151
+ description?: string;
152
+ inputSchema?: Record<string, unknown>;
153
+ annotations?: unknown;
154
+ }>;
155
+ };
156
+ } catch (err) {
157
+ close();
158
+ throw err;
159
+ } finally {
160
+ if (timer) clearTimeout(timer);
161
+ }
122
162
  const remote = listed.tools ?? [];
123
- const prefix = options.command.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "mcp";
163
+ const rawPrefix = options.namePrefix?.trim() || options.command;
164
+ const prefix = rawPrefix.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "mcp";
124
165
 
125
166
  const tools: McpToolDefinition[] = remote.map((t) => ({
126
167
  name: `${prefix}__${t.name}`,
127
168
  description: t.description ?? t.name,
128
169
  inputSchema: t.inputSchema ?? { type: "object", properties: {} },
170
+ annotations: resolveToolAnnotations(t.annotations),
129
171
  async handler(input) {
130
172
  try {
131
173
  const result = (await rpc("tools/call", { name: t.name, arguments: input })) as ToolResult;
package/src/index.ts CHANGED
@@ -35,8 +35,13 @@ export {
35
35
  errorResult,
36
36
  jsonResult,
37
37
  type McpServer,
38
+ type McpToolAnnotations,
38
39
  type McpToolDefinition,
40
+ mcpToolListItem,
41
+ READ_ONLY_ANNOTATIONS,
42
+ resolveToolAnnotations,
39
43
  textResult,
44
+ UNKNOWN_TOOL_ANNOTATIONS,
40
45
  } from "./core/mcp.ts";
41
46
  export {
42
47
  type AgentMode,
@@ -7,6 +7,7 @@ import {
7
7
  errorResult,
8
8
  jsonResult,
9
9
  type McpToolDefinition,
10
+ resolveToolAnnotations,
10
11
  type ToolResult,
11
12
  textResult,
12
13
  } from "../core/mcp.ts";
@@ -17,6 +18,7 @@ export interface RemoteMcpToolMeta {
17
18
  name: string;
18
19
  description: string;
19
20
  inputSchema: Record<string, unknown>;
21
+ annotations?: unknown;
20
22
  }
21
23
 
22
24
  export interface RemoteMcpClient {
@@ -136,7 +138,7 @@ export async function openRemoteMcp(input: {
136
138
  t.inputSchema && typeof t.inputSchema === "object" && !Array.isArray(t.inputSchema)
137
139
  ? (t.inputSchema as Record<string, unknown>)
138
140
  : { type: "object", properties: {} };
139
- out.push({ name, description, inputSchema });
141
+ out.push({ name, description, inputSchema, annotations: t.annotations });
140
142
  }
141
143
  return out;
142
144
  },
@@ -207,6 +209,7 @@ async function loadSourceTools(input: {
207
209
  name,
208
210
  description: `[${input.source.label}] ${tool.description}`,
209
211
  inputSchema: schema,
212
+ annotations: resolveToolAnnotations(tool.annotations),
210
213
  async handler(raw: Record<string, unknown>): Promise<ToolResult> {
211
214
  const { projectId: _projectId, ...args } = raw;
212
215
  return client.callTool(tool.name, args);
package/src/runtime.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  type ApprovalRequest,
7
7
  createExecApprovalGate,
8
8
  type ExecApprovalPolicy,
9
+ isFileWriteTool,
9
10
  } from "./core/approval.ts";
10
11
  import type { AgentEventEmitter, MainModelProvider } from "./core/events.ts";
11
12
  import { createHookRunner } from "./core/hooks.ts";
@@ -295,6 +296,10 @@ export async function createHarness(options: CreateHarnessOptions): Promise<Harn
295
296
  },
296
297
  allowRiskyAlways(toolName) {
297
298
  alwaysAllow.add(toolName);
299
+ if (isFileWriteTool(toolName)) {
300
+ alwaysAllow.add("write_file");
301
+ alwaysAllow.add("edit_file");
302
+ }
298
303
  },
299
304
  async compact() {
300
305
  if (!runtime.activeSessionId) return false;
package/src/tools/git.ts CHANGED
@@ -1,4 +1,10 @@
1
- import { errorResult, jsonResult, type McpToolDefinition, textResult } from "../core/mcp.ts";
1
+ import {
2
+ errorResult,
3
+ jsonResult,
4
+ type McpToolDefinition,
5
+ READ_ONLY_ANNOTATIONS,
6
+ textResult,
7
+ } from "../core/mcp.ts";
2
8
  import { resolveUnderCwd } from "./paths.ts";
3
9
 
4
10
  const GIT_TIMEOUT_MS = 30_000;
@@ -35,6 +41,7 @@ export function createGitTools(cwd: string): McpToolDefinition[] {
35
41
  {
36
42
  name: "git_status",
37
43
  description: "Show branch and porcelain status. Prefer this over exec git status.",
44
+ annotations: READ_ONLY_ANNOTATIONS,
38
45
  inputSchema: { type: "object", properties: {} },
39
46
  async handler() {
40
47
  const result = await git(cwd, ["status", "--porcelain=v1", "-b"]);
@@ -45,6 +52,7 @@ export function createGitTools(cwd: string): McpToolDefinition[] {
45
52
  {
46
53
  name: "git_diff",
47
54
  description: "Show the working tree or staged diff. Optional project-relative path.",
55
+ annotations: READ_ONLY_ANNOTATIONS,
48
56
  inputSchema: {
49
57
  type: "object",
50
58
  properties: {
@@ -71,6 +79,7 @@ export function createGitTools(cwd: string): McpToolDefinition[] {
71
79
  {
72
80
  name: "git_log",
73
81
  description: "Recent commits, oneline. Default 20.",
82
+ annotations: READ_ONLY_ANNOTATIONS,
74
83
  inputSchema: {
75
84
  type: "object",
76
85
  properties: {
@@ -91,6 +100,12 @@ export function createGitTools(cwd: string): McpToolDefinition[] {
91
100
  name: "git_commit",
92
101
  description:
93
102
  "Commit already-staged files, or the listed project-relative paths. Does not push. Requires approval.",
103
+ annotations: {
104
+ readOnlyHint: false,
105
+ destructiveHint: false,
106
+ idempotentHint: false,
107
+ openWorldHint: false,
108
+ },
94
109
  inputSchema: {
95
110
  type: "object",
96
111
  properties: {
@@ -0,0 +1,48 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { McpToolAnnotations } from "../core/mcp.ts";
3
+ import { createGitTools } from "./git.ts";
4
+ import { createLocalTools } from "./local.ts";
5
+ import { createReadSkillTool } from "./read-skill.ts";
6
+ import { createTaskTool } from "./subagent.ts";
7
+ import { createMemoryTodoStore, createTodoTool } from "./todo.ts";
8
+
9
+ function expectHints(hints: McpToolAnnotations): void {
10
+ expect(typeof hints.readOnlyHint).toBe("boolean");
11
+ expect(typeof hints.destructiveHint).toBe("boolean");
12
+ expect(typeof hints.idempotentHint).toBe("boolean");
13
+ expect(typeof hints.openWorldHint).toBe("boolean");
14
+ }
15
+
16
+ describe("built-in tool hints", () => {
17
+ test("every local, git, todo, skill, and task tool declares all four hints", () => {
18
+ const tools = [
19
+ ...createLocalTools({ cwd: process.cwd() }).listTools(),
20
+ ...createGitTools(process.cwd()),
21
+ createTodoTool(createMemoryTodoStore()),
22
+ createReadSkillTool([]),
23
+ createTaskTool({
24
+ skills: [],
25
+ parentEmit: () => () => undefined,
26
+ run: async () => undefined,
27
+ }),
28
+ ];
29
+ expect(tools.map((tool) => tool.name).sort()).toEqual([
30
+ "edit_file",
31
+ "exec",
32
+ "git_commit",
33
+ "git_diff",
34
+ "git_log",
35
+ "git_status",
36
+ "glob",
37
+ "grep",
38
+ "read_file",
39
+ "read_skill",
40
+ "task",
41
+ "todo_write",
42
+ "write_file",
43
+ ]);
44
+ for (const tool of tools) {
45
+ expectHints(tool.annotations);
46
+ }
47
+ });
48
+ });
@@ -1,5 +1,6 @@
1
1
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
2
- import { dirname, join } from "node:path";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
4
  import { Glob } from "bun";
4
5
  import {
5
6
  createMcpServer,
@@ -7,6 +8,7 @@ import {
7
8
  jsonResult,
8
9
  type McpServer,
9
10
  type McpToolDefinition,
11
+ READ_ONLY_ANNOTATIONS,
10
12
  textResult,
11
13
  } from "../core/mcp.ts";
12
14
  import { PathEscapeError, resolveUnderCwd, shouldSkipDir, toProjectRel } from "./paths.ts";
@@ -27,16 +29,36 @@ async function readUtf8(abs: string): Promise<string> {
27
29
 
28
30
  export interface LocalToolsOptions {
29
31
  cwd: string;
32
+ extraWriteAbsolutes?: () => readonly string[];
33
+ }
34
+
35
+ function expandUserPath(path: string): string {
36
+ if (path === "~") return homedir();
37
+ if (path.startsWith("~/")) return resolve(homedir(), path.slice(2));
38
+ return path;
39
+ }
40
+
41
+ function resolveToolPath(cwd: string, rel: string, extra: ReadonlySet<string>): string {
42
+ const trimmed = rel.trim();
43
+ if (trimmed.startsWith("~") || isAbsolute(trimmed)) {
44
+ const abs = resolve(expandUserPath(trimmed));
45
+ if (extra.has(abs)) return abs;
46
+ throw new PathEscapeError(rel);
47
+ }
48
+ return resolveUnderCwd(cwd, rel);
30
49
  }
31
50
 
32
51
  export function createLocalTools(options: LocalToolsOptions): McpServer {
33
52
  const cwd = options.cwd;
53
+ const extras = (): ReadonlySet<string> =>
54
+ new Set((options.extraWriteAbsolutes?.() ?? []).map((path) => resolve(expandUserPath(path))));
34
55
 
35
56
  const tools: McpToolDefinition[] = [
36
57
  {
37
58
  name: "read_file",
38
59
  description:
39
60
  "Read a UTF-8 file under the project root. Prefer this over exec for inspecting source.",
61
+ annotations: READ_ONLY_ANNOTATIONS,
40
62
  inputSchema: {
41
63
  type: "object",
42
64
  properties: {
@@ -46,7 +68,8 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
46
68
  },
47
69
  async handler(raw) {
48
70
  try {
49
- const abs = resolveUnderCwd(cwd, asString(raw.path));
71
+ const extra = extras();
72
+ const abs = resolveToolPath(cwd, asString(raw.path), extra);
50
73
  const content = await readUtf8(abs);
51
74
  return textResult(content);
52
75
  } catch (err) {
@@ -57,7 +80,13 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
57
80
  {
58
81
  name: "write_file",
59
82
  description:
60
- "Create or overwrite a whole file under the project root (up to 10 MB). Prefer edit_file for a small change.",
83
+ "Create or overwrite a whole file under the project root (up to 10 MB). Prefer edit_file for a small change. Call this to apply the write. Do not tell the user the file is saved until this tool succeeds.",
84
+ annotations: {
85
+ readOnlyHint: false,
86
+ destructiveHint: true,
87
+ idempotentHint: true,
88
+ openWorldHint: false,
89
+ },
61
90
  inputSchema: {
62
91
  type: "object",
63
92
  properties: {
@@ -68,7 +97,8 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
68
97
  },
69
98
  async handler(raw) {
70
99
  try {
71
- const abs = resolveUnderCwd(cwd, asString(raw.path));
100
+ const extra = extras();
101
+ const abs = resolveToolPath(cwd, asString(raw.path), extra);
72
102
  const content = asString(raw.content);
73
103
  if (Buffer.byteLength(content, "utf8") > MAX_FILE_BYTES) {
74
104
  return errorResult(`File exceeds ${MAX_FILE_BYTES} bytes`);
@@ -76,7 +106,7 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
76
106
  await mkdir(dirname(abs), { recursive: true });
77
107
  await writeFile(abs, content, "utf8");
78
108
  return jsonResult({
79
- path: toProjectRel(cwd, abs),
109
+ path: extra.has(abs) ? abs : toProjectRel(cwd, abs),
80
110
  bytes: Buffer.byteLength(content, "utf8"),
81
111
  });
82
112
  } catch (err) {
@@ -87,7 +117,13 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
87
117
  {
88
118
  name: "edit_file",
89
119
  description:
90
- "Replace an exact snippet in an existing file. old_str must match uniquely unless replace_all is true.",
120
+ "Replace an exact snippet in an existing file. old_str must match uniquely unless replace_all is true. Call this to apply the edit. Do not tell the user the file is changed until this tool succeeds.",
121
+ annotations: {
122
+ readOnlyHint: false,
123
+ destructiveHint: true,
124
+ idempotentHint: false,
125
+ openWorldHint: false,
126
+ },
91
127
  inputSchema: {
92
128
  type: "object",
93
129
  properties: {
@@ -103,7 +139,8 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
103
139
  },
104
140
  async handler(raw) {
105
141
  try {
106
- const abs = resolveUnderCwd(cwd, asString(raw.path));
142
+ const extra = extras();
143
+ const abs = resolveToolPath(cwd, asString(raw.path), extra);
107
144
  const oldStr = asString(raw.old_str);
108
145
  const newStr = asString(raw.new_str);
109
146
  if (!oldStr) return errorResult("old_str is empty");
@@ -125,7 +162,10 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
125
162
  ? original.split(oldStr).join(newStr)
126
163
  : original.replace(oldStr, newStr);
127
164
  await writeFile(abs, next, "utf8");
128
- return jsonResult({ path: toProjectRel(cwd, abs), replaced: replaceAll ? "all" : "one" });
165
+ return jsonResult({
166
+ path: extra.has(abs) ? abs : toProjectRel(cwd, abs),
167
+ replaced: replaceAll ? "all" : "one",
168
+ });
129
169
  } catch (err) {
130
170
  return errorResult(err instanceof Error ? err.message : String(err));
131
171
  }
@@ -134,6 +174,7 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
134
174
  {
135
175
  name: "glob",
136
176
  description: "List project-relative file paths matching a glob pattern (e.g. **/*.ts).",
177
+ annotations: READ_ONLY_ANNOTATIONS,
137
178
  inputSchema: {
138
179
  type: "object",
139
180
  properties: {
@@ -162,6 +203,7 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
162
203
  {
163
204
  name: "grep",
164
205
  description: "Search file contents under the project root. Prefer this over exec for search.",
206
+ annotations: READ_ONLY_ANNOTATIONS,
165
207
  inputSchema: {
166
208
  type: "object",
167
209
  properties: {
@@ -212,6 +254,12 @@ export function createLocalTools(options: LocalToolsOptions): McpServer {
212
254
  name: "exec",
213
255
  description:
214
256
  "Run a shell command in the project root. Times out after 120 seconds. Do not use exec to read or search files.",
257
+ annotations: {
258
+ readOnlyHint: false,
259
+ destructiveHint: true,
260
+ idempotentHint: false,
261
+ openWorldHint: true,
262
+ },
215
263
  inputSchema: {
216
264
  type: "object",
217
265
  properties: {
@@ -1,6 +1,11 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
- import { errorResult, type McpToolDefinition, textResult } from "../core/mcp.ts";
3
+ import {
4
+ errorResult,
5
+ type McpToolDefinition,
6
+ READ_ONLY_ANNOTATIONS,
7
+ textResult,
8
+ } from "../core/mcp.ts";
4
9
  import type { Skill } from "../skills/loader.ts";
5
10
  import { catalogRefsMatch, skillNameFromCatalogId } from "../skills/registry.ts";
6
11
  import { PathEscapeError, resolveUnderCwd } from "./paths.ts";
@@ -34,6 +39,7 @@ export function createReadSkillTool(skills: Skill[]): McpToolDefinition {
34
39
  name: "read_skill",
35
40
  description:
36
41
  "Read a loaded skill by name or catalog id (user or project). Optional `file` reads a reference next to that skill (e.g. references/anti-slop.md). Prefer this over guessing skill contents.",
42
+ annotations: READ_ONLY_ANNOTATIONS,
37
43
  inputSchema: {
38
44
  type: "object",
39
45
  properties: {
@@ -25,6 +25,12 @@ export function createTaskTool(options: TaskToolOptions): McpToolDefinition {
25
25
  "Spawn a subagent for a focused job (research, an isolated edit, one copy-pipeline step). " +
26
26
  "Pass a complete prompt. Optional `skills` injects those skill bodies into the subagent. " +
27
27
  "Returns the subagent's final reply. Do not use for a one-line question.",
28
+ annotations: {
29
+ readOnlyHint: false,
30
+ destructiveHint: true,
31
+ idempotentHint: false,
32
+ openWorldHint: true,
33
+ },
28
34
  inputSchema: {
29
35
  type: "object",
30
36
  properties: {
package/src/tools/todo.ts CHANGED
@@ -34,6 +34,12 @@ export function createTodoTool(store: TodoStore): McpToolDefinition {
34
34
  name: "todo_write",
35
35
  description:
36
36
  "Replace the session todo list. Use for multi-step work. One in_progress item at a time.",
37
+ annotations: {
38
+ readOnlyHint: false,
39
+ destructiveHint: true,
40
+ idempotentHint: true,
41
+ openWorldHint: false,
42
+ },
37
43
  inputSchema: {
38
44
  type: "object",
39
45
  properties: {