@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,217 @@
1
+ import type { Buffer } from "node:buffer";
2
+ import { rmSync } from "node:fs";
3
+ import { z } from "zod";
4
+ import { AgentError } from "../../errors";
5
+ import { analyzeCommand } from "../../permissions/command";
6
+ import { runProcess } from "../bin";
7
+ import { defineTool } from "../define";
8
+ import { findBash } from "./find-bash";
9
+ import { pathOrRoot, resolveInWorkspace } from "../../paths";
10
+ import { formatBytes, openSpill, type SpilledFile } from "../spill";
11
+
12
+ /**
13
+ * A bash command: stdin is closed, so a prompting command fails instead of
14
+ * hanging, and output is capped, with a timeout that kills the child. The
15
+ * policy decides what it may run and matches `resources().command`.
16
+ *
17
+ * Always bash, on every platform. A missing one is an error with an install
18
+ * hint, never a quiet fall back to the shell the OS prefers: the permission
19
+ * rules match POSIX grammar, so another shell would judge one language and run
20
+ * another.
21
+ */
22
+
23
+ const DEFAULT_TIMEOUT_MS = 120_000;
24
+ const MAX_TIMEOUT_MS = 600_000;
25
+ const OUTPUT_LIMIT_BYTES = 64 * 1024;
26
+
27
+ /**
28
+ * Names `tools.bashPath`, so a user with an installation nobody predicted knows
29
+ * where to write the path.
30
+ */
31
+ const INSTALL_HINT =
32
+ "On Windows it ships with Git for Windows (https://git-scm.com/download/win); " +
33
+ "elsewhere install it with your package manager. If it is installed somewhere " +
34
+ 'unusual, set "tools.bashPath" in the configuration.';
35
+
36
+ export interface BashToolOptions {
37
+ /**
38
+ * Where bash is, when neither `PATH` nor git can say. Supplied by the host
39
+ * from configuration.
40
+ */
41
+ bashPath?: string;
42
+ /** Where the Windows job helper is compiled to, in `bin/`; absent: temp. */
43
+ cacheDir?: string;
44
+ /** The name `PATH` resolves. Injected only so the lookup order can be tested. */
45
+ shell?: string;
46
+ /** The git lookup. Injected for the same reason. */
47
+ find?: () => Promise<string | null>;
48
+ /** Decides whether git is asked at all. Injected for the same reason. */
49
+ platform?: NodeJS.Platform;
50
+ }
51
+
52
+ interface BashOutput {
53
+ command: string;
54
+ exitCode: number | null;
55
+ stdout: string;
56
+ stderr: string;
57
+ truncated: boolean;
58
+ durationMs: number;
59
+ /** The whole output, both streams, when it was cut and there was somewhere to keep it. */
60
+ outputPath?: string;
61
+ /** Present when the output was cut: where the rest is, or that it is gone. */
62
+ notice?: string;
63
+ }
64
+
65
+ /** How a command that ended in the background answers: its output is in the task's log. */
66
+ interface BackgroundOutput {
67
+ command: string;
68
+ exitCode: number | null;
69
+ durationMs: number;
70
+ }
71
+
72
+ /** True in both worlds: a host with nowhere to keep a task offers no such parameter. */
73
+ const NO_AMPERSAND =
74
+ "A command must not put anything in the background with '&': it could not be stopped " +
75
+ "or watched from here. Where run_in_background is offered, use that instead.";
76
+
77
+ const CAP = formatBytes(OUTPUT_LIMIT_BYTES);
78
+
79
+ /** Says where the rest went, because a model told nothing reasons about half an output. */
80
+ function cutNotice(saved: SpilledFile | undefined): string {
81
+ if (saved === undefined) {
82
+ return (
83
+ `Only the last ${CAP} of each stream is shown; what came before was not kept. ` +
84
+ "Narrow the command, or redirect its output to a file and read that."
85
+ );
86
+ }
87
+ const capped = saved.capped ? " The file stops at that size; the command wrote more." : "";
88
+ // read_file cuts a line at 2000 characters, so a one-line output needs the shell.
89
+ return (
90
+ `Only the last ${CAP} of each stream is shown. The full output (stdout and stderr, ` +
91
+ `${formatBytes(saved.bytes)}) is saved at ${saved.path} — read it with read_file ` +
92
+ "(offset, limit) or search it with grep; for very long lines use bash on it " +
93
+ `(head -c, tail -c, cut, jq).${capped}`
94
+ );
95
+ }
96
+
97
+ export function createBashTool(options: BashToolOptions = {}) {
98
+ return defineTool({
99
+ name: "bash",
100
+ description:
101
+ "Run a command with bash in the workspace and return its output. It is " +
102
+ "bash on every platform, including Windows, so write POSIX syntax: " +
103
+ "`/dev/null` not `NUL`, `$VAR` not `%VAR%`, forward slashes. " +
104
+ "There is no stdin: a command that expects input " +
105
+ "will fail rather than wait. Output is capped — past the cap you get its " +
106
+ "end, and `notice` says where the rest is — and a command that runs past " +
107
+ "its wait is stopped, or moved to the background where that is available. " +
108
+ "Prefer the file tools over shell equivalents — they are safer " +
109
+ "and their output is structured.",
110
+ danger: "exec",
111
+ inputSchema: z.object({
112
+ command: z
113
+ .string()
114
+ .min(1)
115
+ // Refused before anybody is asked: the orphan cannot be killed on Windows.
116
+ .refine((command) => !analyzeCommand(command).detaches, NO_AMPERSAND)
117
+ .describe("Command line to run through the platform shell."),
118
+ cwd: z.string().optional().describe("Directory to run in, relative to the workspace root."),
119
+ timeout_ms: z
120
+ .number()
121
+ .int()
122
+ .min(1)
123
+ .max(MAX_TIMEOUT_MS)
124
+ .optional()
125
+ .describe("How long to wait for the command."),
126
+ }),
127
+ background: {
128
+ log: true,
129
+ moveAfterMs: (input) => input.timeout_ms ?? DEFAULT_TIMEOUT_MS,
130
+ },
131
+ resources: (input) => ({
132
+ command: input.command,
133
+ // An empty `cwd` is the workspace root, so it claims nothing rather than
134
+ // the empty string.
135
+ paths: input.cwd === undefined || input.cwd.trim() === "" ? [] : [input.cwd],
136
+ }),
137
+ describe: (input) => input.command,
138
+ execute: async (input, context): Promise<BashOutput | BackgroundOutput> => {
139
+ const cwd = resolveInWorkspace(context, pathOrRoot(input.cwd));
140
+ const spill = openSpill(context, "bash");
141
+ const task = context.task;
142
+
143
+ const run = (command: string) =>
144
+ runProcess({
145
+ // Explicitly bash: `shell: true` means cmd.exe on Windows, and then the
146
+ // tool's name, description and POSIX grammar describe another shell.
147
+ command,
148
+ args: ["-c", input.command],
149
+ cwd,
150
+ signal: context.signal,
151
+ // With a task the registry moves the call to the background at this
152
+ // point instead; without one the command is killed.
153
+ ...(task === undefined ? { timeoutMs: input.timeout_ms ?? DEFAULT_TIMEOUT_MS } : {}),
154
+ ...(task === undefined ? {} : { onOutput: (chunk: Buffer) => task.write(chunk) }),
155
+ maxOutputBytes: OUTPUT_LIMIT_BYTES,
156
+ // The end, not the start: a failing build says why on its last lines.
157
+ keep: "tail",
158
+ install: INSTALL_HINT,
159
+ ...(spill === undefined ? {} : { overflow: spill }),
160
+ // A stop has to take what `npm run dev` started, not only the shell.
161
+ contain: options.cacheDir === undefined ? {} : { dir: options.cacheDir },
162
+ });
163
+
164
+ // Git before PATH on Windows: wherever WSL is enabled, `bash` on PATH is its
165
+ // launcher, which would run the command in Linux instead.
166
+ const fromGit =
167
+ options.bashPath === undefined && (options.platform ?? process.platform) === "win32"
168
+ ? await (options.find ?? findBash)()
169
+ : null;
170
+ let saved: SpilledFile | undefined;
171
+ let result;
172
+ try {
173
+ result = await run(options.bashPath ?? fromGit ?? options.shell ?? "bash");
174
+ } finally {
175
+ // Closed on every road out: a cancelled run would otherwise keep the file open.
176
+ saved = spill?.close();
177
+ }
178
+
179
+ if (task?.background === true) {
180
+ // The task's log is the whole output, so the overflow file would be a second copy.
181
+ if (saved !== undefined) rmSync(saved.path, { force: true });
182
+ return { command: input.command, exitCode: result.code, durationMs: result.durationMs };
183
+ }
184
+
185
+ if (result.timedOut) {
186
+ const kept = saved === undefined ? "" : ` What it wrote until then is saved at ${saved.path}.`;
187
+ throw new AgentError(
188
+ "tool/timeout",
189
+ `The command was killed after ${String(input.timeout_ms ?? DEFAULT_TIMEOUT_MS)} ms.${kept}`,
190
+ { details: { command: input.command } },
191
+ );
192
+ }
193
+
194
+ const output: BashOutput = {
195
+ command: input.command,
196
+ exitCode: result.code,
197
+ stdout: result.stdout,
198
+ stderr: result.stderr,
199
+ truncated: result.truncated,
200
+ durationMs: result.durationMs,
201
+ };
202
+ if (saved !== undefined) output.outputPath = saved.path;
203
+ if (result.truncated) output.notice = cutNotice(saved);
204
+ return output;
205
+ },
206
+ describeResult: (output) => {
207
+ const status = output.exitCode === 0 ? "ok" : `exit ${String(output.exitCode)}`;
208
+ if (!("stdout" in output)) return status;
209
+ const lines = output.stdout === "" ? 0 : output.stdout.split("\n").length;
210
+ const cut = output.truncated ? ", truncated" : "";
211
+ return `${status}, ${String(lines)} lines${cut}${output.outputPath === undefined ? "" : ", saved to a file"}`;
212
+ },
213
+ });
214
+ }
215
+
216
+ /** The default instance, for hosts with nothing to configure. */
217
+ export const bashTool = createBashTool();
@@ -0,0 +1,162 @@
1
+ import { access } from "node:fs/promises";
2
+ import { win32 } from "node:path";
3
+ import { runProcess } from "../bin";
4
+
5
+ /**
6
+ * Where Git Bash is on Windows, asked before `PATH`.
7
+ *
8
+ * Git for Windows installs `bash.exe` but leaves it off `PATH` unless the user
9
+ * ticks an option, and where WSL is enabled `PATH` answers with WSL's launcher
10
+ * instead. The location comes from `git --exec-path`, not from a list of
11
+ * directories or environment variables.
12
+ */
13
+
14
+ export interface FindBashDeps {
15
+ /** Runs `git --exec-path` and returns stdout, or null when git is absent. */
16
+ execPath: () => Promise<string | null>;
17
+ exists: (path: string) => Promise<boolean>;
18
+ }
19
+
20
+ /**
21
+ * `…/mingw64/libexec/git-core` → `…/bin/bash.exe`.
22
+ *
23
+ * Three levels up from the exec path is the installation root on every Git for
24
+ * Windows build.
25
+ */
26
+ export function bashPathFromExecPath(execPath: string): string {
27
+ // Git for Windows prints a Windows path; the host's own rules would take `C:/` for relative.
28
+ const root = win32.resolve(execPath.trim(), "..", "..", "..");
29
+ return win32.join(root, "bin", "bash.exe");
30
+ }
31
+
32
+ export const defaultFindBashDeps: FindBashDeps = {
33
+ execPath: async () => {
34
+ try {
35
+ const result = await runProcess({
36
+ command: "git",
37
+ args: ["--exec-path"],
38
+ // Git is asked about itself, so the directory is irrelevant; the port
39
+ // requires one, and the process's own is used.
40
+ cwd: ".",
41
+ timeoutMs: 5_000,
42
+ maxOutputBytes: 4_096,
43
+ });
44
+ return result.code === 0 && result.stdout.trim() !== "" ? result.stdout : null;
45
+ } catch {
46
+ // No git either. Nothing more to try; the caller reports the original.
47
+ return null;
48
+ }
49
+ },
50
+ exists: async (path) => {
51
+ try {
52
+ await access(path);
53
+ return true;
54
+ } catch {
55
+ return false;
56
+ }
57
+ },
58
+ };
59
+
60
+ /**
61
+ * Resolved once per process.
62
+ *
63
+ * The promise itself is cached rather than its value: two tool calls running at
64
+ * the same time would otherwise both shell out to git.
65
+ */
66
+ let pending: Promise<string | null> | undefined;
67
+
68
+ export function findBash(deps: FindBashDeps = defaultFindBashDeps): Promise<string | null> {
69
+ pending ??= (async () => {
70
+ const execPath = await deps.execPath();
71
+ if (execPath === null) return null;
72
+
73
+ const candidate = bashPathFromExecPath(execPath);
74
+ return (await deps.exists(candidate)) ? candidate : null;
75
+ })();
76
+
77
+ return pending;
78
+ }
79
+
80
+ /** Test seam. Nothing in the product calls this. */
81
+ export function resetFoundBash(): void {
82
+ pending = undefined;
83
+ }
84
+
85
+ /**
86
+ * Which bash this environment has, checked by running it.
87
+ *
88
+ * The tool discovers this lazily and only when something fails; `doctor` asks
89
+ * up front instead. The order is the tool's: configuration, then git on Windows
90
+ * only, then PATH. Two orders that drift apart would make `doctor` describe a
91
+ * lookup nobody performs.
92
+ */
93
+ export type BashStatus =
94
+ | { mode: "configured"; path: string }
95
+ | { mode: "path"; path: string }
96
+ | { mode: "git"; path: string }
97
+ | { mode: "missing"; tried: string[] };
98
+
99
+ export interface CheckBashDeps {
100
+ /** Runs `<path> --version`; false when it cannot be executed at all. */
101
+ probe: (path: string) => Promise<boolean>;
102
+ find: () => Promise<string | null>;
103
+ platform: NodeJS.Platform;
104
+ }
105
+
106
+ export const defaultCheckBashDeps: CheckBashDeps = {
107
+ probe: async (path) => {
108
+ try {
109
+ const result = await runProcess({
110
+ command: path,
111
+ args: ["--version"],
112
+ cwd: ".",
113
+ timeoutMs: 5_000,
114
+ maxOutputBytes: 4_096,
115
+ });
116
+ return result.code === 0;
117
+ } catch {
118
+ return false;
119
+ }
120
+ },
121
+ find: () => findBash(),
122
+ platform: process.platform,
123
+ };
124
+
125
+ export async function checkBash(
126
+ configured?: string,
127
+ deps: CheckBashDeps = defaultCheckBashDeps,
128
+ ): Promise<BashStatus> {
129
+ const tried: string[] = [];
130
+
131
+ // Configuration wins and is not silently replaced: a wrong path the user
132
+ // wrote is something they need told, not something to route around.
133
+ if (configured !== undefined) {
134
+ return (await deps.probe(configured))
135
+ ? { mode: "configured", path: configured }
136
+ : { mode: "missing", tried: [configured] };
137
+ }
138
+
139
+ if (deps.platform === "win32") {
140
+ const found = await deps.find();
141
+ if (found !== null && (await deps.probe(found))) return { mode: "git", path: found };
142
+ tried.push("git --exec-path");
143
+ }
144
+
145
+ if (await deps.probe("bash")) return { mode: "path", path: "bash" };
146
+ tried.push("bash (PATH)");
147
+
148
+ return { mode: "missing", tried };
149
+ }
150
+
151
+ export function describeBash(status: BashStatus): string {
152
+ switch (status.mode) {
153
+ case "configured":
154
+ return `${status.path} (tools.bashPath)`;
155
+ case "path":
156
+ return `${status.path} (from PATH)`;
157
+ case "git":
158
+ return `${status.path} (git --exec-path)`;
159
+ default:
160
+ return `not found — tried ${status.tried.join(", ")}`;
161
+ }
162
+ }
@@ -0,0 +1,35 @@
1
+ import type { AgentTool } from "./define";
2
+
3
+ /**
4
+ * Where tools come from. Built-ins are one source; any other source, such as
5
+ * an MCP server, needs no change above this file.
6
+ *
7
+ * Listing is asynchronous because a remote source has to be asked.
8
+ */
9
+ export interface ToolSource {
10
+ /** "builtin", "mcp:filesystem", … — identifies the source in errors and listings. */
11
+ readonly id: string;
12
+ /**
13
+ * When set, tools are exposed as `<namespace>__<name>`, so a remote
14
+ * `write_file` does not inherit the permission rules written for the
15
+ * built-in one. Unset, names stay plain, so an accidental clash is caught
16
+ * as a duplicate, not renamed.
17
+ */
18
+ readonly namespace?: string;
19
+ /**
20
+ * Kept off the model's tool list: the model finds these with `search_tools`
21
+ * and calls them through `call_tool`, so the list, which opens every request,
22
+ * never changes. `list()` is then asked whenever the catalog is needed, and
23
+ * has to be cheap.
24
+ */
25
+ readonly onDemand?: true;
26
+ list(): Promise<AgentTool[]>;
27
+ close?(): Promise<void>;
28
+ }
29
+
30
+ export const BUILTIN_SOURCE_ID = "builtin";
31
+
32
+ export function exposedName(namespace: string | undefined, toolName: string): string {
33
+ if (namespace === undefined) return toolName;
34
+ return `${namespace.replace(/[^a-zA-Z0-9_]+/g, "__")}__${toolName}`;
35
+ }
@@ -0,0 +1,127 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { closeSync, mkdirSync, openSync, rmSync, writeSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { toPosix } from "../paths";
5
+ import { formatBytes } from "../units";
6
+ import type { ToolContext } from "./define";
7
+
8
+ /**
9
+ * A file for the part of a result that is too big to return.
10
+ *
11
+ * The tool calls this, not the registry: a result is an object here, and only
12
+ * the tool knows which field outgrew it.
13
+ */
14
+
15
+ /** `yes` for two minutes is gigabytes; past this the file stops growing. */
16
+ export const SPILL_LIMIT_BYTES = 32 * 1024 * 1024;
17
+
18
+ export interface SpilledFile {
19
+ /** Absolute, forward slashes: the same string works in `read_file` and in bash. */
20
+ path: string;
21
+ bytes: number;
22
+ /** The file itself was cut, at the limit. */
23
+ capped: boolean;
24
+ }
25
+
26
+ export interface Spill {
27
+ write(chunk: Uint8Array | string): void;
28
+ /** What was kept. Nothing when nothing was written, or when the disk refused. */
29
+ close(): SpilledFile | undefined;
30
+ }
31
+
32
+ export interface SpillOptions {
33
+ limitBytes?: number;
34
+ /** The unique part of the file name. Injected so a test can predict it. */
35
+ newName?: () => string;
36
+ /** Without the dot. Absent: `txt`. */
37
+ extension?: string;
38
+ }
39
+
40
+ /** Absent when the host gave nowhere to keep results — the caller cuts in place. */
41
+ export function openSpill(
42
+ context: Pick<ToolContext, "resultsDir">,
43
+ tool: string,
44
+ options: SpillOptions = {},
45
+ ): Spill | undefined {
46
+ const dir = context.resultsDir;
47
+ if (dir === undefined) return undefined;
48
+
49
+ const limit = options.limitBytes ?? SPILL_LIMIT_BYTES;
50
+ // Our own name, never the call id: that one comes from the model's provider.
51
+ const extension = (options.extension ?? "txt").replace(/[^a-zA-Z0-9]+/g, "");
52
+ const name = `${tool.replace(/[^a-zA-Z0-9_-]+/g, "_")}-${(options.newName ?? uniqueName)()}.${extension}`;
53
+ const file = join(dir, name);
54
+
55
+ let descriptor: number | undefined;
56
+ let opened = false;
57
+ let bytes = 0;
58
+ let capped = false;
59
+ let failed = false;
60
+
61
+ return {
62
+ write(chunk) {
63
+ if (failed) return;
64
+ const data = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
65
+ if (data.length === 0) return;
66
+
67
+ const room = limit - bytes;
68
+ if (room <= 0) {
69
+ capped = true;
70
+ return;
71
+ }
72
+ const part = data.length > room ? data.subarray(0, room) : data;
73
+ if (part.length < data.length) capped = true;
74
+
75
+ try {
76
+ // Opened by the first byte, so a result that fit leaves no empty file.
77
+ if (descriptor === undefined) {
78
+ mkdirSync(dir, { recursive: true });
79
+ descriptor = openSync(file, "w");
80
+ opened = true;
81
+ }
82
+ writeSync(descriptor, part);
83
+ bytes += part.length;
84
+ } catch {
85
+ // A full disk costs the saved copy, never the call.
86
+ failed = true;
87
+ }
88
+ },
89
+
90
+ close() {
91
+ if (descriptor !== undefined) {
92
+ try {
93
+ closeSync(descriptor);
94
+ } catch {
95
+ failed = true;
96
+ }
97
+ descriptor = undefined;
98
+ }
99
+
100
+ if (failed) {
101
+ // Only a file that was made: removing one behind a blocked directory throws on Linux.
102
+ if (opened) rmSync(file, { force: true });
103
+ return undefined;
104
+ }
105
+ return bytes === 0 ? undefined : { path: toPosix(file), bytes, capped };
106
+ },
107
+ };
108
+ }
109
+
110
+ /**
111
+ * The start of a text, for a result whose beginning matters more than its end:
112
+ * a page, a report. Cut on a line, so the saved file's line numbers carry on.
113
+ */
114
+ export function headOf(text: string, limitBytes: number): { head: string; lines: number | undefined } {
115
+ const cut = new TextDecoder().decode(Buffer.from(text, "utf8").subarray(0, limitBytes));
116
+ const newline = cut.lastIndexOf("\n");
117
+ // One endless line: there is no line to cut on, only a character.
118
+ if (newline <= 0) return { head: cut.replace(/�+$/, ""), lines: undefined };
119
+ const head = cut.slice(0, newline);
120
+ return { head, lines: head.split("\n").length };
121
+ }
122
+
123
+ function uniqueName(): string {
124
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
125
+ }
126
+
127
+ export { formatBytes };