@wraith-ai/core 0.1.0 → 0.1.1

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.
Files changed (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,212 @@
1
+ import { z } from "zod";
2
+ import { AgentError, isAgentError } from "../../errors";
3
+ import { runProcess, type ProcessResult } from "../bin";
4
+ import { defineTool } from "../define";
5
+ import { displayPath, pathOrRoot, resolveInWorkspace } from "../../paths";
6
+ import {
7
+ RIPGREP_COMMAND,
8
+ resolveRipgrep,
9
+ withSpawnRetry,
10
+ type RipgrepLocation,
11
+ type RipgrepOptions,
12
+ } from "./ripgrep";
13
+
14
+ /**
15
+ * Search runs ripgrep as a child process. There is no JavaScript fallback: a
16
+ * missing `rg` is reported, not replaced by a different search.
17
+ *
18
+ * Output is read from `--json`, never from the human format, and the result is
19
+ * data. Rendering belongs to ui-kit.
20
+ */
21
+
22
+ const DEFAULT_LIMIT = 100;
23
+ const MAX_LIMIT = 1_000;
24
+ const MAX_LINE_LENGTH = 500;
25
+ const OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
26
+
27
+ /** Names the configuration key, as the bash tool does, so a user knows where to set the path. */
28
+ const INSTALL_HINT =
29
+ "Install ripgrep (https://github.com/BurntSushi/ripgrep) and make sure `rg` is " +
30
+ 'on PATH, or set "tools.ripgrepPath" in the configuration.';
31
+
32
+ export interface RipgrepMatch {
33
+ path: string;
34
+ line: number;
35
+ column: number;
36
+ text: string;
37
+ }
38
+
39
+ export interface GrepToolOptions {
40
+ /**
41
+ * Where ripgrep is: from configuration or a copy compiled in by the host.
42
+ * The core owns the resolution order, but not the asset.
43
+ */
44
+ ripgrep?: RipgrepOptions;
45
+ /** The resolution itself. Injected so tests never unpack anything. */
46
+ resolve?: () => Promise<RipgrepLocation>;
47
+ }
48
+
49
+ function isMissingBinary(error: unknown): boolean {
50
+ return isAgentError(error) && error.code === "tool/missing-binary";
51
+ }
52
+
53
+ export function createGrepTool(options: GrepToolOptions = {}) {
54
+ // Resolved once per process, and the promise rather than its value: two
55
+ // searches starting together would otherwise both unpack the same file.
56
+ let pending: Promise<RipgrepLocation> | undefined;
57
+ const locate = (): Promise<RipgrepLocation> => {
58
+ pending ??= options.resolve?.() ?? resolveRipgrep(options.ripgrep ?? {});
59
+ return pending;
60
+ };
61
+
62
+ return defineTool({
63
+ name: "grep",
64
+ description:
65
+ "Search file contents with a regular expression, using ripgrep. Respects " +
66
+ ".gitignore unless `no_ignore` is set. Returns one entry per matching " +
67
+ "line; when `truncated` is true there were more matches than the limit.",
68
+ danger: "read",
69
+ inputSchema: z.object({
70
+ pattern: z.string().min(1).describe("Regular expression, in ripgrep syntax."),
71
+ path: z.string().optional().describe("File or directory to search. Defaults to the workspace root."),
72
+ glob: z.string().optional().describe("Only search files matching this glob, e.g. `*.ts`."),
73
+ case_insensitive: z.boolean().optional().describe("Ignore case while matching."),
74
+ hidden: z.boolean().optional().describe("Also search dotfiles and dot-directories."),
75
+ no_ignore: z.boolean().optional().describe("Ignore .gitignore rules."),
76
+ limit: z.number().int().min(1).max(MAX_LIMIT).optional().describe("Maximum number of matches."),
77
+ }),
78
+ resources: (input) => ({ paths: [pathOrRoot(input.path)] }),
79
+ // An empty path is the root, so it says as little as no path at all.
80
+ describe: (input) => {
81
+ const where = pathOrRoot(input.path);
82
+ return `${input.pattern}${where === "." ? "" : ` in ${where}`}`;
83
+ },
84
+ execute: async (input, context) => {
85
+ const searchPath = pathOrRoot(input.path);
86
+ resolveInWorkspace(context, searchPath);
87
+ const limit = input.limit ?? DEFAULT_LIMIT;
88
+
89
+ // Without --no-require-git, ripgrep ignores .gitignore outside a git
90
+ // repo, so the same search would answer differently there. --max-count
91
+ // is per file: one more than the limit lets a single file show the cut.
92
+ const args = ["--json", "--no-require-git", `--max-count=${limit + 1}`];
93
+ if (input.case_insensitive === true) args.push("--ignore-case");
94
+ if (input.hidden === true) args.push("--hidden");
95
+ if (input.no_ignore === true) args.push("--no-ignore");
96
+ if (input.glob !== undefined) args.push("--glob", input.glob);
97
+ args.push("-e", input.pattern, "--", searchPath);
98
+
99
+ const run = (command: string): Promise<ProcessResult> =>
100
+ runProcess({
101
+ command,
102
+ args,
103
+ cwd: context.cwd,
104
+ signal: context.signal,
105
+ timeoutMs: 30_000,
106
+ maxOutputBytes: OUTPUT_LIMIT_BYTES,
107
+ install: INSTALL_HINT,
108
+ });
109
+
110
+ const located = await locate();
111
+ let result;
112
+ try {
113
+ result = await withSpawnRetry(() => run(located.path));
114
+ } catch (error) {
115
+ // A bundled copy that will not run is retried with `rg` on PATH. A
116
+ // configured path gets no second try: it is the user's explicit answer
117
+ // and must never be ignored quietly.
118
+ if (located.mode !== "bundled" || !isMissingBinary(error)) throw error;
119
+ result = await withSpawnRetry(() => run(RIPGREP_COMMAND));
120
+ }
121
+
122
+ if (result.timedOut) {
123
+ throw new AgentError("tool/timeout", "The search took too long and was stopped.", {
124
+ details: { pattern: input.pattern },
125
+ });
126
+ }
127
+ // 0 = matches, 1 = no matches, anything else is a real failure.
128
+ if (result.code !== 0 && result.code !== 1) {
129
+ throw new AgentError(
130
+ "tool/failed",
131
+ `ripgrep failed: ${result.stderr.trim() || `exit code ${String(result.code)}`}`,
132
+ { details: { pattern: input.pattern, exitCode: result.code } },
133
+ );
134
+ }
135
+
136
+ const parsed = parseRipgrepJson(result.stdout, limit);
137
+
138
+ return {
139
+ pattern: input.pattern,
140
+ matches: parsed.matches.map((match) => ({
141
+ ...match,
142
+ path: displayPath(context.cwd, match.path),
143
+ })),
144
+ matchCount: parsed.matches.length,
145
+ truncated: parsed.truncated || result.truncated,
146
+ };
147
+ },
148
+ describeResult: (output) =>
149
+ `${String(output.matchCount)} ${output.matchCount === 1 ? "match" : "matches"}${
150
+ output.truncated ? ", truncated" : ""
151
+ }`,
152
+ });
153
+ }
154
+
155
+ /** The default instance, for hosts with nothing configured and nothing bundled. */
156
+ export const grepTool = createGrepTool();
157
+
158
+ interface RipgrepEvent {
159
+ type?: string;
160
+ data?: {
161
+ path?: { text?: string };
162
+ lines?: { text?: string };
163
+ line_number?: number;
164
+ submatches?: { start?: number }[];
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Reads ripgrep's NDJSON. Anything that is not a `match` event is ignored, so
170
+ * a new event type in a future ripgrep cannot break the tool.
171
+ */
172
+ export function parseRipgrepJson(
173
+ stdout: string,
174
+ limit: number,
175
+ ): { matches: RipgrepMatch[]; truncated: boolean } {
176
+ const matches: RipgrepMatch[] = [];
177
+ let truncated = false;
178
+
179
+ for (const line of stdout.split("\n")) {
180
+ if (line.trim() === "") continue;
181
+
182
+ let event: RipgrepEvent;
183
+ try {
184
+ event = JSON.parse(line) as RipgrepEvent;
185
+ } catch {
186
+ continue;
187
+ }
188
+ if (event.type !== "match") continue;
189
+
190
+ const path = event.data?.path?.text;
191
+ const text = event.data?.lines?.text;
192
+ if (path === undefined || text === undefined) continue;
193
+
194
+ if (matches.length >= limit) {
195
+ truncated = true;
196
+ break;
197
+ }
198
+
199
+ matches.push({
200
+ path,
201
+ line: event.data?.line_number ?? 0,
202
+ column: (event.data?.submatches?.[0]?.start ?? 0) + 1,
203
+ text: clamp(text.replace(/\r?\n$/, "")),
204
+ });
205
+ }
206
+
207
+ return { matches, truncated };
208
+ }
209
+
210
+ function clamp(text: string): string {
211
+ return text.length <= MAX_LINE_LENGTH ? text : `${text.slice(0, MAX_LINE_LENGTH)}… [truncated]`;
212
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The model writes `\n` whatever the file holds, and a CRLF file is ordinary:
3
+ * Git for Windows checks out with `core.autocrlf=true`. So text the model
4
+ * writes into a file takes the file's ending, not the other way round.
5
+ */
6
+
7
+ export type LineEnding = "\r\n" | "\n";
8
+
9
+ /** Any CRLF makes the file CRLF. */
10
+ export function lineEndingOf(text: string): LineEnding {
11
+ return text.includes("\r\n") ? "\r\n" : "\n";
12
+ }
13
+
14
+ export function withLineEnding(text: string, ending: LineEnding): string {
15
+ const lf = text.replaceAll("\r\n", "\n");
16
+ return ending === "\n" ? lf : lf.replaceAll("\n", "\r\n");
17
+ }
@@ -0,0 +1,85 @@
1
+ import { readdir, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import { AgentError } from "../../errors";
5
+ import { defineTool } from "../define";
6
+ import { displayPath, pathOrRoot, resolveInWorkspace } from "../../paths";
7
+
8
+ const MAX_ENTRIES = 500;
9
+
10
+ /** Directories that would drown every listing and are never what was meant. */
11
+ export const NOISY_DIRECTORIES = new Set([".git", "node_modules", ".wraith"]);
12
+
13
+ export const listDirTool = defineTool({
14
+ name: "list_dir",
15
+ description:
16
+ "List the contents of a directory. Use `depth` to descend further; " +
17
+ ".git, node_modules and similar directories are listed but not descended " +
18
+ "into. Prefer glob when you already know the shape of the name.",
19
+ danger: "read",
20
+ inputSchema: z.object({
21
+ path: z.string().optional().describe("Directory to list. Defaults to the workspace root."),
22
+ depth: z.number().int().min(1).max(5).optional().describe("How many levels to descend."),
23
+ }),
24
+ resources: (input) => ({ paths: [pathOrRoot(input.path)] }),
25
+ // No `describe`: the default line is built from the path declared above.
26
+ // This is the one built-in that uses that fallback; keep it that way.
27
+ execute: async (input, context) => {
28
+ const path = pathOrRoot(input.path);
29
+ const base = resolveInWorkspace(context, path);
30
+ const depth = input.depth ?? 1;
31
+
32
+ const info = await stat(base).catch((cause: unknown) => {
33
+ throw new AgentError("tool/failed", `Cannot list "${path}": ${reason(cause)}`, {
34
+ cause,
35
+ details: { path },
36
+ });
37
+ });
38
+ if (!info.isDirectory()) {
39
+ throw new AgentError("tool/failed", `"${path}" is not a directory.`, {
40
+ details: { path },
41
+ });
42
+ }
43
+
44
+ const entries: DirectoryEntry[] = [];
45
+ let truncated = false;
46
+
47
+ const visit = async (directory: string, level: number): Promise<void> => {
48
+ if (truncated || level > depth) return;
49
+ const found = await readdir(directory, { withFileTypes: true });
50
+
51
+ for (const entry of found.sort((a, b) => a.name.localeCompare(b.name))) {
52
+ if (entries.length >= MAX_ENTRIES) {
53
+ truncated = true;
54
+ return;
55
+ }
56
+ const full = join(directory, entry.name);
57
+ const isDirectory = entry.isDirectory();
58
+ entries.push({
59
+ path: displayPath(context.cwd,full),
60
+ type: isDirectory ? "directory" : entry.isFile() ? "file" : "other",
61
+ });
62
+ if (isDirectory && !NOISY_DIRECTORIES.has(entry.name)) await visit(full, level + 1);
63
+ }
64
+ };
65
+
66
+ await visit(base, 1);
67
+
68
+ return {
69
+ path: displayPath(context.cwd,base),
70
+ entries,
71
+ truncated,
72
+ };
73
+ },
74
+ describeResult: (output) =>
75
+ `${String(output.entries.length)} entries${output.truncated ? ", truncated" : ""}`,
76
+ });
77
+
78
+ interface DirectoryEntry {
79
+ path: string;
80
+ type: "directory" | "file" | "other";
81
+ }
82
+
83
+ function reason(cause: unknown): string {
84
+ return cause instanceof Error ? cause.message : String(cause);
85
+ }
@@ -0,0 +1,230 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { open, type FileHandle } from "node:fs/promises";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { z } from "zod";
5
+ import {
6
+ checkImageSize,
7
+ describeImage,
8
+ imageFromBytes,
9
+ imageInfo,
10
+ looksLikeImage,
11
+ } from "../../agent/attachments";
12
+ import { AgentError } from "../../errors";
13
+ import { defineTool } from "../define";
14
+ import { displayPath, resolveInWorkspace } from "../../paths";
15
+
16
+ /**
17
+ * Output is capped, and a slice says so: without the `notice` the model
18
+ * reasons about part of a file as if it were all of it. The window follows
19
+ * `offset`, not the start of the file.
20
+ */
21
+
22
+ /** Cap on what one call returns, not on how far into a file it may look. */
23
+ const MAX_BYTES = 50 * 1024;
24
+ /** Up to this size the scan goes on to the end, so `totalLines` is exact. */
25
+ const COUNT_TO_END_BYTES = 512 * 1024;
26
+ const MAX_LINES = 2_000;
27
+ const MAX_LINE_LENGTH = 2_000;
28
+ const BINARY_PROBE_BYTES = 8_192;
29
+ const CHUNK_BYTES = 64 * 1024;
30
+
31
+ export const readFileTool = defineTool({
32
+ name: "read_file",
33
+ description:
34
+ `Read a UTF-8 text file from the workspace. Returns at most ${String(MAX_LINES)} lines ` +
35
+ `or ${String(MAX_BYTES / 1024)} KB, each line prefixed with its number and a tab; ` +
36
+ "the prefix is not part of the file. If you know which part you need (grep gives " +
37
+ "line numbers), read only that part with `offset` (1-based line number) and `limit`. " +
38
+ "When more of the file is left, `notice` says which `offset` continues it. " +
39
+ "A PNG, JPEG, GIF or WebP image comes back as the image itself, for you to look at.",
40
+ danger: "read",
41
+ inputSchema: z.object({
42
+ path: z.string().min(1).describe("Path to the file, relative to the workspace root."),
43
+ offset: z.number().int().min(1).optional().describe("First line to return, 1-based."),
44
+ limit: z.number().int().min(1).max(MAX_LINES).optional().describe("How many lines to return."),
45
+ }),
46
+ resources: (input) => ({ paths: [input.path] }),
47
+ describe: (input) => {
48
+ if (input.limit === undefined) {
49
+ return input.offset === undefined ? input.path : `${input.path}, from line ${String(input.offset)}`;
50
+ }
51
+ const from = input.offset ?? 1;
52
+ return `${input.path}, lines ${String(from)}-${String(from + input.limit - 1)}`;
53
+ },
54
+ execute: async (input, context) => {
55
+ const absolute = resolveInWorkspace(context, input.path);
56
+ const handle = await open(absolute, "r").catch((cause: unknown) => {
57
+ throw new AgentError("tool/failed", `Cannot read "${input.path}": ${reason(cause)}`, {
58
+ cause,
59
+ details: { path: input.path },
60
+ });
61
+ });
62
+
63
+ try {
64
+ const stat = await handle.stat();
65
+ if (stat.isDirectory()) {
66
+ throw new AgentError("tool/failed", `"${input.path}" is a directory, not a file.`, {
67
+ details: { path: input.path },
68
+ });
69
+ }
70
+
71
+ const probe = Buffer.alloc(Math.min(stat.size, BINARY_PROBE_BYTES));
72
+ await handle.read(probe, 0, probe.length, 0);
73
+ if (looksLikeImage(probe)) {
74
+ // Before reading it whole, so a huge file costs nothing.
75
+ checkImageSize(stat.size);
76
+ const image = imageFromBytes(await handle.readFile());
77
+ context.attach(image);
78
+ return { path: displayPath(context.cwd, absolute), image: describeImage(imageInfo(image)) };
79
+ }
80
+ if (probe.includes(0)) {
81
+ // A NUL byte in the probe (the file's first bytes) marks it as binary.
82
+ throw new AgentError("tool/binary-file", `"${input.path}" is a binary file.`, {
83
+ details: { path: input.path, bytes: stat.size },
84
+ });
85
+ }
86
+
87
+ const startLine = input.offset ?? 1;
88
+ const limit = input.limit ?? MAX_LINES;
89
+ const slice = await readSlice(handle, {
90
+ startLine,
91
+ limit,
92
+ // Counting to the end costs a scan, so only files up to
93
+ // COUNT_TO_END_BYTES get one; bigger ones answer `null`.
94
+ countToEnd: stat.size <= COUNT_TO_END_BYTES,
95
+ });
96
+
97
+ // The first line of a window always fits the byte cap, so an empty slice
98
+ // past line 1 means the file ended first; `totalLines` is then exact.
99
+ if (slice.lines.length === 0 && startLine > 1) {
100
+ throw new AgentError(
101
+ "tool/failed",
102
+ `Offset ${String(startLine)} is beyond the end of "${input.path}" (${String(slice.totalLines)} lines).`,
103
+ { details: { path: input.path, totalLines: slice.totalLines } },
104
+ );
105
+ }
106
+
107
+ const end = startLine + slice.lines.length - 1;
108
+ const of = slice.totalLines === null ? "" : ` of ${String(slice.totalLines)}`;
109
+ const notice = slice.truncated
110
+ ? `Showing lines ${String(startLine)}-${String(end)}${of}. Use offset=${String(end + 1)} to continue.`
111
+ : undefined;
112
+
113
+ return {
114
+ path: displayPath(context.cwd, absolute),
115
+ content: slice.lines.map((line, index) => `${String(startLine + index)}\t${line}`).join("\n"),
116
+ startLine,
117
+ lineCount: slice.lines.length,
118
+ totalLines: slice.totalLines,
119
+ truncated: slice.truncated,
120
+ notice,
121
+ };
122
+ } finally {
123
+ await handle.close();
124
+ }
125
+ },
126
+ // Not "truncated": a window the model asked for is not a cut.
127
+ describeResult: (output) =>
128
+ "image" in output
129
+ ? output.image
130
+ : output.totalLines === null || output.totalLines === output.lineCount
131
+ ? `${String(output.lineCount)} ${output.lineCount === 1 ? "line" : "lines"}`
132
+ : `${String(output.lineCount)} of ${String(output.totalLines)} lines`,
133
+ });
134
+
135
+ interface SliceRequest {
136
+ startLine: number;
137
+ limit: number;
138
+ /** Keep counting lines after the slice is full, for an exact `totalLines`. */
139
+ countToEnd: boolean;
140
+ }
141
+
142
+ interface Slice {
143
+ lines: string[];
144
+ /** Known only when the scan reached the end of the file. */
145
+ totalLines: number | null;
146
+ truncated: boolean;
147
+ }
148
+
149
+ /**
150
+ * Walks the file counting newlines, keeps the lines that fall in the window.
151
+ *
152
+ * Chunked so a 40 MB file costs 64 KB of memory, and decoded through
153
+ * `StringDecoder` because a chunk boundary lands in the middle of a multi-byte
154
+ * character often enough to matter.
155
+ */
156
+ async function readSlice(handle: FileHandle, request: SliceRequest): Promise<Slice> {
157
+ const decoder = new StringDecoder("utf8");
158
+ const chunk = Buffer.alloc(CHUNK_BYTES);
159
+ const lines: string[] = [];
160
+
161
+ let position = 0;
162
+ let lineNumber = 0;
163
+ let bytes = 0;
164
+ let current = "";
165
+ let cut = false;
166
+ let full = false;
167
+
168
+ // An over-long line is clamped as it arrives rather than after: holding it
169
+ // whole would undo the chunking.
170
+ const keep = (text: string): void => {
171
+ if (text === "") return;
172
+ const room = MAX_LINE_LENGTH - current.length;
173
+ if (room <= 0) {
174
+ cut = true;
175
+ return;
176
+ }
177
+ current += text.slice(0, room);
178
+ if (text.length > room) cut = true;
179
+ };
180
+
181
+ const endLine = (): void => {
182
+ lineNumber += 1;
183
+ const line = cut ? `${current}… [line truncated]` : current;
184
+ current = "";
185
+ cut = false;
186
+
187
+ if (full || lineNumber < request.startLine) return;
188
+ if (lines.length >= request.limit || bytes + line.length > MAX_BYTES) {
189
+ full = true;
190
+ return;
191
+ }
192
+ lines.push(line);
193
+ bytes += line.length + 1;
194
+ };
195
+
196
+ for (;;) {
197
+ const { bytesRead } = await handle.read(chunk, 0, CHUNK_BYTES, position);
198
+ if (bytesRead === 0) break;
199
+ position += bytesRead;
200
+
201
+ const text = decoder.write(chunk.subarray(0, bytesRead));
202
+ let from = 0;
203
+ for (;;) {
204
+ const newline = text.indexOf("\n", from);
205
+ if (newline === -1) {
206
+ keep(text.slice(from));
207
+ break;
208
+ }
209
+ keep(text.slice(from, newline));
210
+ endLine();
211
+ if (full && !request.countToEnd) return { lines, totalLines: null, truncated: true };
212
+ from = newline + 1;
213
+ }
214
+ }
215
+
216
+ keep(decoder.end());
217
+ // A file that does not end in a newline still has a last line; one that does
218
+ // has a terminator, not an empty line after it.
219
+ if (current !== "" || cut) endLine();
220
+
221
+ return {
222
+ lines,
223
+ totalLines: lineNumber,
224
+ truncated: request.startLine - 1 + lines.length < lineNumber,
225
+ };
226
+ }
227
+
228
+ function reason(cause: unknown): string {
229
+ return cause instanceof Error ? cause.message : String(cause);
230
+ }