@better-fs-tools/ai-sdk 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gareth Andrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # @better-fs-tools/ai-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Better Read tool, the `edit`, `write`, and `apply_patch` tools, and the `bash` tool for [AI SDK 7](https://ai-sdk.dev). Each factory gives a tool object that you put in a `ToolSet`. `createAiSdkFsTools()` builds them in one call.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @better-fs-tools/ai-sdk @better-fs-tools/read @better-fs-tools/write ai
9
+ ```
10
+
11
+ `ai` is a required peer (`^7.0.77`). Add a filesystem package too, for example `@better-fs-tools/node` or `@better-fs-tools/cloudflare-shell`.
12
+
13
+ ## Example
14
+
15
+ ```ts
16
+ import { generateText, isStepCount } from "ai";
17
+ import type { LanguageModel } from "ai";
18
+ import { createAiSdkReadTool } from "@better-fs-tools/ai-sdk";
19
+ import { nodeDigest, nodeFileSystem } from "@better-fs-tools/node";
20
+ import { lineRangeSignature } from "@better-fs-tools/read/signature";
21
+
22
+ const cwd = process.cwd();
23
+ const read = createAiSdkReadTool({
24
+ fs: nodeFileSystem({ cwd, allowedRoots: [cwd] }),
25
+ digest: nodeDigest(),
26
+ signature: lineRangeSignature({
27
+ name: "read_file",
28
+ names: { path: "file_path", start: "start_line", end: "end_line" },
29
+ }),
30
+ });
31
+
32
+ export async function ask(model: LanguageModel, prompt: string): Promise<string> {
33
+ const result = await generateText({
34
+ model,
35
+ prompt,
36
+ tools: { [read.name]: read },
37
+ stopWhen: isStepCount(5),
38
+ });
39
+ return result.text;
40
+ }
41
+ ```
42
+
43
+ ## What the tool does
44
+
45
+ - `createAiSdkReadTool(options)` takes every `createReadTool()` option, plus `signature`. `fs` is required. `digest` defaults to `null`, as in the core.
46
+ - The model sees the signature's name, description, and JSON Schema. The tool is `strict: true`, and the provider schema stays inside the JSON Schema subset that [OpenAI strict mode](https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas) documents. See [Strict provider schema](#strict-provider-schema). The default signature is `defaultReadSignature()`: `read` with `path`, `offset`, and `limit`.
47
+ - The schema's `validate` hook runs `signature.toInput` and then the core input check. A refusal names the host's parameters, and `generateText` reports it as a tool error.
48
+ - `execute` passes AI SDK's `ToolExecutionOptions` object to the core as `ctx.call.host`, with `abortSignal` as the signal and `toolCallId` as `callId`. Host functions can read `ctx.call.host.context`. `execute` returns the whole `ReadResult`. If `toInput` refuses an input that reached `execute`, `execute` rejects with that `TypeError`.
49
+ - Retry text in notes uses the signature's names. `result.continuation.next` stays canonical.
50
+ - `toModelOutput` maps text parts to text parts, and media parts to base64 `file` parts. `toAiSdkOutput(result)` does the same mapping for your own tool.
51
+
52
+ For a Cloudflare Agents host, pass `fs: cloudflareShellFileSystem(workspace, { allowedRoots: [root] })` from `@better-fs-tools/cloudflare-shell`. No other wrapper is needed.
53
+
54
+ ## Write tools
55
+
56
+ `createAiSdkFsTools({ fs })` builds the read tool and the write tools from [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write) in one call. They share one `state`, one `digest` (default `sha256Digest()`), one lock manager, and one clock, so `edit` and `write` know what the model has read. `tools` has every tool keyed by its name, for `generateText`:
57
+
58
+ ```ts
59
+ import { generateText, isStepCount } from "ai";
60
+ import type { LanguageModel } from "ai";
61
+ import { createAiSdkFsTools } from "@better-fs-tools/ai-sdk";
62
+ import { nodeFileSystem } from "@better-fs-tools/node";
63
+
64
+ const cwd = process.cwd();
65
+ // read, edit, write, and apply_patch over one filesystem, with one store,
66
+ // one digest, and one lock manager. No bash: this bundle starts no process.
67
+ const { tools } = createAiSdkFsTools({ fs: nodeFileSystem({ cwd, allowedRoots: [cwd] }) });
68
+
69
+ export async function change(model: LanguageModel, prompt: string): Promise<string> {
70
+ const result = await generateText({ model, prompt, tools, stopWhen: isStepCount(10) });
71
+ return result.text;
72
+ }
73
+ ```
74
+
75
+ - `createAiSdkFsTools(options)` wraps `createFsTools()`. `fs` is required. `state` (default `memoryStore({ clock })`, `null` turns read-before-write off), `digest`, `locks`, and `clock` are set once. Each tool's other options, and its `signature`, go under `read`, `edit`, `write`, and `applyPatch`. `bash: { runner, env, ... }` adds a bash tool with the same digest and clock. The result has `read`, `edit`, `write`, `applyPatch`, `bash` (`null` when off), `tools`, `state`, `digest`, `locks`, `clock`, and `invalidate(path, call?)`. An unknown option key, a shared key inside a tool's options, or two tools with one name throws `TypeError`.
76
+ - The single factories, `createAiSdkEditTool()`, `createAiSdkWriteTool()`, and `createAiSdkApplyPatchTool()`, take every option of their core factory, plus `signature`. `fs` is required. `state` and `digest` default to `null`, so without them every update carries a `read-before-write-off` note. A `state` needs a `digest`: the options type refuses one without the other, and the factory throws `TypeError`.
77
+ - The default signatures are `defaultEditSignature()` (`edit` with `path`, `old_string`, `new_string`, and `replace_all`), `defaultWriteSignature()` (`write` with `path` and `content`), and `defaultPatchSignature()` (`apply_patch` with `patch`). Error texts use the signature's names.
78
+ - The tools are `strict: true`. The schema's `validate` hook runs `signature.toInput` and the core input check.
79
+ - `execute` passes the `ToolExecutionOptions` object as `ctx.call.host`, and returns the whole `MutationResult`. `toModelOutput` gives the model the formatter's text.
80
+ - AI SDK tools take JSON only. A signature with a grammar, such as `freeformPatchSignature()`, still works, but the grammar is not sent.
81
+
82
+ ## Strict provider schema
83
+
84
+ Every tool is `strict: true`. The adapter turns the signature's JSON Schema into a provider schema that OpenAI strict mode accepts:
85
+
86
+ - Every object lists every property in `required` and has `additionalProperties: false`. An optional property becomes required and nullable: `null` joins its `type` and its `enum`, or the schema is wrapped in `anyOf` with `{ type: "null" }`. The tool maps a `null` back to an absent parameter before the signature reads the input.
87
+ - `oneOf` becomes `anyOf`. `allOf` is merged into its schema. `const` becomes a one-value `enum`. A root `definitions` becomes `$defs`. A local `$ref` stays as it is.
88
+ - The schema keeps only `type`, `description`, `properties`, `required`, `additionalProperties`, `items`, `anyOf`, `$ref`, `$defs`, `enum`, `pattern`, `format`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `minItems`, and `maxItems`. Other keywords, such as `minLength`, `maxLength`, `title`, and `default`, and a `format` that strict mode does not list, are dropped. The schema's `validate` hook runs the signature's parse, so a dropped check still applies to the input.
89
+ - The same rules apply inside `anyOf`, `oneOf`, `allOf`, array items, and `$defs`.
90
+
91
+ A custom schema that strict mode cannot express throws a `TypeError` with the tool name and the schema path when you create the tool: a root that is not an object, an object that allows other properties, a schema with no type, `not`, `if`, `patternProperties`, `dependentRequired`, tuple items, both `anyOf` and `oneOf`, an `allOf` over two object schemas, with a `$ref`, or with a keyword that differs from its schema, or a `$ref` outside the schema.
92
+
93
+ ## Bash tool
94
+
95
+ `createAiSdkBashTool({ runner, env })` adapts the `bash` tool from [`@better-fs-tools/shell`](https://www.npmjs.com/package/@better-fs-tools/shell). This package starts no process and reads no `process.env`, so `runner` and `env` are required. The default signature takes the timeout in milliseconds and names the runner in the description.
96
+
97
+ ```ts
98
+ import { generateText, isStepCount } from "ai";
99
+ import type { LanguageModel } from "ai";
100
+ import { createAiSdkBashTool } from "@better-fs-tools/ai-sdk";
101
+ import { nodeCommandRunner } from "@better-fs-tools/node";
102
+ import { shellEnv } from "@better-fs-tools/shell";
103
+
104
+ // The AI SDK package starts no process. Give it a runner.
105
+ const bash = createAiSdkBashTool({
106
+ runner: nodeCommandRunner(),
107
+ env: shellEnv(() => process.env),
108
+ });
109
+
110
+ export async function run(model: LanguageModel, prompt: string): Promise<string> {
111
+ const result = await generateText({
112
+ model,
113
+ prompt,
114
+ tools: { [bash.name]: bash },
115
+ stopWhen: isStepCount(5),
116
+ });
117
+ return result.text;
118
+ }
119
+ ```
120
+
121
+ ## End-to-end tests
122
+
123
+ `packages/ai-sdk/test/e2e/openai.e2e.ts` calls OpenAI for real with the strict `read`, `write`, `apply_patch`, and `bash` tools, over a memory filesystem and a just-bash shell. Each test forces one tool call and checks that the provider took the schema, the input parsed, and the result is right. `bun test` and `bun run check` do not run them. From the repository root:
124
+
125
+ ```sh
126
+ OPENAI_API_KEY=sk-... bun run test:e2e
127
+ ```
128
+
129
+ `BFT_E2E_OPENAI_MODEL` picks the model (default `gpt-5.4-mini`). Without `OPENAI_API_KEY` the run fails and names the variable.
130
+
131
+ ## Links
132
+
133
+ - `docs/hosts.md` in [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write): the defaults of every host and bundle, and what each backend can do
134
+ - [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): every read option, and the signature builders
135
+ - [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write): every write option, and the write signatures
136
+ - [`@better-fs-tools/cloudflare-shell`](https://www.npmjs.com/package/@better-fs-tools/cloudflare-shell): a filesystem for Cloudflare Agents
@@ -0,0 +1 @@
1
+ export declare function toBase64(bytes: Uint8Array): string;
package/dist/base64.js ADDED
@@ -0,0 +1,9 @@
1
+ // Keeps each String.fromCharCode spread under engine argument-count limits.
2
+ const CHUNK = 0x8000;
3
+ export function toBase64(bytes) {
4
+ let binary = "";
5
+ for (let offset = 0; offset < bytes.byteLength; offset += CHUNK) {
6
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK));
7
+ }
8
+ return btoa(binary);
9
+ }
@@ -0,0 +1,35 @@
1
+ import type { Schema, ToolExecutionOptions } from "ai";
2
+ import type { JsonObject } from "@better-fs-tools/read";
3
+ import type { BashTool, ShellLimits, ShellResult, ShellToolDeps } from "@better-fs-tools/shell";
4
+ import type { BashSignature } from "@better-fs-tools/shell/signature";
5
+ import type { AiSdkToolOutput } from "./output.ts";
6
+ export type CreateAiSdkBashToolOptions<C = unknown> = ShellToolDeps<ToolExecutionOptions<C>> & {
7
+ /** Defaults to defaultBashSignature() for the runner's id and the limits. */
8
+ readonly signature?: BashSignature;
9
+ };
10
+ /** An AI SDK bash tool, assignable to `Tool<JsonObject, ShellResult, C>` from ai 7.0.77. */
11
+ export interface AiSdkBashTool<C = unknown> {
12
+ readonly name: string;
13
+ readonly description: string;
14
+ readonly strict: true;
15
+ /** The strict input schema. A `null` for an optional parameter means absent. */
16
+ readonly inputSchema: Schema<JsonObject>;
17
+ /** Runs the command. The AI SDK execution options are the call's host. */
18
+ execute(input: JsonObject, options: ToolExecutionOptions<C>): Promise<ShellResult>;
19
+ toModelOutput(options: {
20
+ output: ShellResult;
21
+ }): AiSdkToolOutput;
22
+ }
23
+ /**
24
+ * Creates an AI SDK bash tool. `options.messages` override the signature's
25
+ * messages. The runner and env are required: this package starts no process
26
+ * and does not read process.env. Use nodeCommandRunner() from
27
+ * @better-fs-tools/node or justBashCommandRunner() from
28
+ * @better-fs-tools/just-bash, and shellEnv() from @better-fs-tools/shell.
29
+ */
30
+ export declare function createAiSdkBashTool<C = unknown>(options: CreateAiSdkBashToolOptions<C>): AiSdkBashTool<C>;
31
+ export declare function defaultAiSdkBashSignature(deps: {
32
+ readonly runner?: ShellToolDeps<never>["runner"];
33
+ readonly limits?: Partial<ShellLimits>;
34
+ }): BashSignature;
35
+ export declare function adaptBashTool<C>(signature: BashSignature, bash: BashTool<ToolExecutionOptions<C>>, limitOverrides: Partial<ShellLimits> | undefined): AiSdkBashTool<C>;
@@ -0,0 +1,64 @@
1
+ import { jsonSchema } from "ai";
2
+ import { createBashTool, parseBashInput, resolveShellLimits } from "@better-fs-tools/shell";
3
+ import { bashSignatureMessages, defaultBashSignature } from "@better-fs-tools/shell/signature";
4
+ import { toAiSdkOutput } from "./output.js";
5
+ import { fromStrictInput, toStrictSchema } from "./strict.js";
6
+ /**
7
+ * Creates an AI SDK bash tool. `options.messages` override the signature's
8
+ * messages. The runner and env are required: this package starts no process
9
+ * and does not read process.env. Use nodeCommandRunner() from
10
+ * @better-fs-tools/node or justBashCommandRunner() from
11
+ * @better-fs-tools/just-bash, and shellEnv() from @better-fs-tools/shell.
12
+ */
13
+ export function createAiSdkBashTool(options) {
14
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
15
+ throw new TypeError("AI SDK bash tool options must be an object");
16
+ }
17
+ const { signature: given, ...deps } = options;
18
+ const signature = given ?? defaultAiSdkBashSignature(deps);
19
+ const bash = createBashTool({
20
+ ...deps,
21
+ messages: { ...bashSignatureMessages(signature), ...deps.messages },
22
+ });
23
+ return adaptBashTool(signature, bash, deps.limits);
24
+ }
25
+ export function defaultAiSdkBashSignature(deps) {
26
+ const runnerId = typeof deps.runner === "function" ? undefined : deps.runner?.id;
27
+ return defaultBashSignature({
28
+ ...(runnerId === undefined ? {} : { runner: runnerId }),
29
+ ...(deps.limits === undefined ? {} : { limits: deps.limits }),
30
+ });
31
+ }
32
+ export function adaptBashTool(signature, bash, limitOverrides) {
33
+ const limits = resolveShellLimits(limitOverrides);
34
+ const strict = toStrictSchema(signature.schema, signature.name);
35
+ return Object.freeze({
36
+ name: signature.name,
37
+ description: signature.description,
38
+ strict: true,
39
+ inputSchema: jsonSchema(strict, {
40
+ validate(model) {
41
+ try {
42
+ const value = fromStrictInput(signature.schema, model);
43
+ parseBashInput(signature.toInput(value), limits);
44
+ return { success: true, value: value };
45
+ }
46
+ catch (error) {
47
+ return {
48
+ success: false,
49
+ error: error instanceof Error ? error : new Error(String(error)),
50
+ };
51
+ }
52
+ },
53
+ }),
54
+ async execute(input, execution) {
55
+ const call = {
56
+ ...(execution.abortSignal === undefined ? {} : { signal: execution.abortSignal }),
57
+ callId: execution.toolCallId,
58
+ host: execution,
59
+ };
60
+ return bash(signature.toInput(fromStrictInput(signature.schema, input)), call);
61
+ },
62
+ toModelOutput: ({ output }) => toAiSdkOutput(output),
63
+ });
64
+ }
@@ -0,0 +1,84 @@
1
+ import type { ToolExecutionOptions } from "ai";
2
+ import type { Clock, Digest, ReadStateStore, ReadToolDeps, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { ReadSignature } from "@better-fs-tools/read/signature";
4
+ import type { BashSignature } from "@better-fs-tools/shell/signature";
5
+ import type { ApplyPatchToolDeps, CreateFsToolsOptions, EditToolDeps, FsToolsBashOptions, FsToolsSharedKey, InvalidateOutcome, LockManager, WriteToolDeps } from "@better-fs-tools/write";
6
+ import type { EditSignature, PatchSignature, WriteSignature } from "@better-fs-tools/write/signature";
7
+ import type { AiSdkBashTool } from "./bash-tool.ts";
8
+ import type { AiSdkMutationTool } from "./mutation-tools.ts";
9
+ import type { AiSdkReadTool } from "./tool.ts";
10
+ type Host<C> = ToolExecutionOptions<C>;
11
+ /** Read tool options for createAiSdkFsTools. Shared keys are set once at the top level. */
12
+ export type AiSdkFsToolsReadOptions<C = unknown> = Omit<Partial<ReadToolDeps<Host<C>>>, FsToolsSharedKey> & {
13
+ /** Defaults to defaultReadSignature(). */
14
+ readonly signature?: ReadSignature;
15
+ };
16
+ export type AiSdkFsToolsEditOptions<C = unknown> = Omit<Partial<EditToolDeps<Host<C>>>, FsToolsSharedKey> & {
17
+ /** Defaults to defaultEditSignature() for `matchers`. */
18
+ readonly signature?: EditSignature;
19
+ };
20
+ export type AiSdkFsToolsWriteOptions<C = unknown> = Omit<Partial<WriteToolDeps<Host<C>>>, FsToolsSharedKey> & {
21
+ /** Defaults to defaultWriteSignature(). */
22
+ readonly signature?: WriteSignature;
23
+ };
24
+ export type AiSdkFsToolsApplyPatchOptions<C = unknown> = Omit<Partial<ApplyPatchToolDeps<Host<C>>>, FsToolsSharedKey> & {
25
+ /** Defaults to defaultPatchSignature(). */
26
+ readonly signature?: PatchSignature;
27
+ };
28
+ /** Bash tool options for createAiSdkFsTools. `runner` and `env` are required. */
29
+ export type AiSdkFsToolsBashOptions<C = unknown> = FsToolsBashOptions<Host<C>> & {
30
+ /** Defaults to defaultBashSignature() for the runner's id and the limits. */
31
+ readonly signature?: BashSignature;
32
+ };
33
+ export interface CreateAiSdkFsToolsOptions<C = unknown> {
34
+ /** Required. A backend, or a factory called once for each tool call with the AI SDK options as host. */
35
+ readonly fs: CreateFsToolsOptions<Host<C>>["fs"];
36
+ /** Defaults to memoryStore({ clock }). null turns read-before-write off. */
37
+ readonly state?: ReadStateStore | null;
38
+ /** Defaults to sha256Digest() from @better-fs-tools/read, which runs in a Worker. */
39
+ readonly digest?: Digest;
40
+ /** Defaults to memoryLocks(). */
41
+ readonly locks?: LockManager;
42
+ /** Defaults to () => new Date(). */
43
+ readonly clock?: Clock;
44
+ readonly read?: AiSdkFsToolsReadOptions<C>;
45
+ readonly edit?: AiSdkFsToolsEditOptions<C>;
46
+ readonly write?: AiSdkFsToolsWriteOptions<C>;
47
+ readonly applyPatch?: AiSdkFsToolsApplyPatchOptions<C>;
48
+ /** Off by default. This package starts no process: give a runner and an env to turn bash on. */
49
+ readonly bash?: false | AiSdkFsToolsBashOptions<C>;
50
+ }
51
+ export interface AiSdkFsTools<C = unknown> {
52
+ readonly read: AiSdkReadTool<C>;
53
+ readonly edit: AiSdkMutationTool<C>;
54
+ readonly write: AiSdkMutationTool<C>;
55
+ readonly applyPatch: AiSdkMutationTool<C>;
56
+ /** null unless options.bash is set. */
57
+ readonly bash: AiSdkBashTool<C> | null;
58
+ /** Every tool of the bundle keyed by its name, ready for generateText({ tools }). */
59
+ readonly tools: Readonly<Record<string, AiSdkReadTool<C> | AiSdkMutationTool<C> | AiSdkBashTool<C>>>;
60
+ readonly state: ReadStateStore | null;
61
+ readonly digest: Digest;
62
+ readonly locks: LockManager;
63
+ readonly clock: Clock;
64
+ /** Same as createFsTools().invalidate. When fs is a factory, pass the call context. */
65
+ invalidate(path: string, call?: ToolCallContext<Host<C>>): Promise<InvalidateOutcome>;
66
+ }
67
+ /** The createAiSdkFsTools result when `bash` is set: `bash` is never null. */
68
+ export interface AiSdkFsToolsWithBash<C = unknown> extends AiSdkFsTools<C> {
69
+ readonly bash: AiSdkBashTool<C>;
70
+ }
71
+ /**
72
+ * Creates AI SDK read, edit, write, and apply_patch tools over one backend,
73
+ * sharing one read state store, digest, lock manager, and clock. Needs no
74
+ * Node module, so it runs in a Worker. With `bash`, also creates a bash tool
75
+ * with the same digest and clock.
76
+ *
77
+ * Throws TypeError on an unknown option key, and on a shared key (fs, state,
78
+ * digest, locks, clock) inside a tool's options.
79
+ */
80
+ export declare function createAiSdkFsTools<C = unknown>(options: CreateAiSdkFsToolsOptions<C> & {
81
+ readonly bash: AiSdkFsToolsBashOptions<C>;
82
+ }): AiSdkFsToolsWithBash<C>;
83
+ export declare function createAiSdkFsTools<C = unknown>(options: CreateAiSdkFsToolsOptions<C>): AiSdkFsTools<C>;
84
+ export {};
@@ -0,0 +1,127 @@
1
+ import { readSignatureMessages, defaultReadSignature } from "@better-fs-tools/read/signature";
2
+ import { bashSignatureMessages } from "@better-fs-tools/shell/signature";
3
+ import { createFsTools, parseApplyPatchInput, parseEditInput, parseWriteInput, } from "@better-fs-tools/write";
4
+ import { defaultEditSignature, defaultPatchSignature, defaultWriteSignature, writeSignatureMessages, } from "@better-fs-tools/write/signature";
5
+ import { adaptBashTool, defaultAiSdkBashSignature } from "./bash-tool.js";
6
+ import { adaptMutationTool, matchersOf } from "./mutation-tools.js";
7
+ import { adaptReadTool } from "./tool.js";
8
+ const KNOWN = new Set([
9
+ "fs",
10
+ "state",
11
+ "digest",
12
+ "locks",
13
+ "clock",
14
+ "read",
15
+ "edit",
16
+ "write",
17
+ "applyPatch",
18
+ "bash",
19
+ ]);
20
+ const SHARED_KEYS = {
21
+ read: ["fs", "state", "digest", "clock"],
22
+ edit: ["fs", "state", "digest", "locks", "clock"],
23
+ write: ["fs", "state", "digest", "locks", "clock"],
24
+ applyPatch: ["fs", "state", "digest", "locks", "clock"],
25
+ bash: ["digest", "clock"],
26
+ };
27
+ export function createAiSdkFsTools(options) {
28
+ checkOptions(options);
29
+ const { signature: readSignature = defaultReadSignature(), ...read } = options.read ?? {};
30
+ const { signature: editGiven, ...edit } = options.edit ?? {};
31
+ const editSignature = editGiven ?? defaultEditSignature(matchersOf(edit.matchers));
32
+ const { signature: writeSignature = defaultWriteSignature(), ...write } = options.write ?? {};
33
+ const { signature: patchSignature = defaultPatchSignature(), ...applyPatch } = options.applyPatch ?? {};
34
+ const bashOptions = options.bash === undefined || options.bash === false ? null : options.bash;
35
+ let bash = null;
36
+ if (bashOptions !== null) {
37
+ const { signature, ...deps } = bashOptions;
38
+ bash = { deps, signature: signature ?? defaultAiSdkBashSignature(deps) };
39
+ }
40
+ const core = createFsTools({
41
+ fs: options.fs,
42
+ ...(options.state === undefined ? {} : { state: options.state }),
43
+ ...(options.digest === undefined ? {} : { digest: options.digest }),
44
+ ...(options.locks === undefined ? {} : { locks: options.locks }),
45
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
46
+ read: { ...read, messages: { ...readSignatureMessages(readSignature), ...read.messages } },
47
+ edit: { ...edit, messages: { ...writeSignatureMessages(editSignature), ...edit.messages } },
48
+ write: {
49
+ ...write,
50
+ messages: { ...writeSignatureMessages(writeSignature), ...write.messages },
51
+ },
52
+ applyPatch: {
53
+ ...applyPatch,
54
+ messages: { ...writeSignatureMessages(patchSignature), ...applyPatch.messages },
55
+ },
56
+ ...(bash === null
57
+ ? {}
58
+ : {
59
+ bash: {
60
+ ...bash.deps,
61
+ messages: { ...bashSignatureMessages(bash.signature), ...bash.deps.messages },
62
+ },
63
+ }),
64
+ });
65
+ const adapted = {
66
+ read: adaptReadTool(readSignature, core.read, read.limits),
67
+ edit: adaptMutationTool(editSignature, core.edit, parseEditInput, edit.limits),
68
+ write: adaptMutationTool(writeSignature, core.write, parseWriteInput, write.limits),
69
+ applyPatch: adaptMutationTool(patchSignature, core.applyPatch, parseApplyPatchInput, applyPatch.limits),
70
+ bash: bash === null || core.bash === null
71
+ ? null
72
+ : adaptBashTool(bash.signature, core.bash, bash.deps.limits),
73
+ };
74
+ const tools = {};
75
+ for (const tool of Object.values(adapted)) {
76
+ if (tool === null)
77
+ continue;
78
+ if (Object.hasOwn(tools, tool.name)) {
79
+ throw new TypeError(`createAiSdkFsTools has two tools named ${tool.name}`);
80
+ }
81
+ tools[tool.name] = tool;
82
+ }
83
+ return Object.freeze({
84
+ ...adapted,
85
+ tools: Object.freeze(tools),
86
+ state: core.state,
87
+ digest: core.digest,
88
+ locks: core.locks,
89
+ clock: core.clock,
90
+ invalidate: core.invalidate,
91
+ });
92
+ }
93
+ function checkOptions(options) {
94
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
95
+ throw new TypeError("createAiSdkFsTools options must be an object");
96
+ }
97
+ for (const key of Object.keys(options)) {
98
+ if (!KNOWN.has(key))
99
+ throw new TypeError(`Unknown createAiSdkFsTools option: ${key}`);
100
+ }
101
+ const state = options.state;
102
+ if (state !== undefined && state !== null && !isStore(state)) {
103
+ throw new TypeError(`createAiSdkFsTools state must be a read state store or null: a bundle takes one store, not a per-call factory`);
104
+ }
105
+ for (const [tool, keys] of Object.entries(SHARED_KEYS)) {
106
+ const part = options[tool];
107
+ if (part === undefined || (tool === "bash" && part === false))
108
+ continue;
109
+ if (tool === "bash" && part === true) {
110
+ throw new TypeError("createAiSdkFsTools bash must be an object with a runner and an env: the portable bundle has no default runner");
111
+ }
112
+ if (part === null || typeof part !== "object" || Array.isArray(part)) {
113
+ throw new TypeError(`createAiSdkFsTools ${tool} options must be an object`);
114
+ }
115
+ for (const key of keys) {
116
+ if (Object.hasOwn(part, key)) {
117
+ throw new TypeError(`createAiSdkFsTools ${tool} options cannot set ${key}: set it once at the top level`);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ function isStore(value) {
123
+ if (value === null || typeof value !== "object")
124
+ return false;
125
+ const store = value;
126
+ return ["get", "put", "delete"].every((key) => typeof store[key] === "function");
127
+ }
@@ -0,0 +1,10 @@
1
+ export { createAiSdkBashTool } from "./bash-tool.ts";
2
+ export type { AiSdkBashTool, CreateAiSdkBashToolOptions } from "./bash-tool.ts";
3
+ export { createAiSdkFsTools } from "./fs-tools.ts";
4
+ export type { AiSdkFsTools, AiSdkFsToolsApplyPatchOptions, AiSdkFsToolsBashOptions, AiSdkFsToolsEditOptions, AiSdkFsToolsReadOptions, AiSdkFsToolsWithBash, AiSdkFsToolsWriteOptions, CreateAiSdkFsToolsOptions, } from "./fs-tools.ts";
5
+ export { createAiSdkApplyPatchTool, createAiSdkEditTool, createAiSdkWriteTool, } from "./mutation-tools.ts";
6
+ export type { AiSdkMutationTool, CreateAiSdkApplyPatchToolOptions, CreateAiSdkEditToolOptions, CreateAiSdkWriteToolOptions, } from "./mutation-tools.ts";
7
+ export { toAiSdkOutput } from "./output.ts";
8
+ export type { AiSdkContentPart, AiSdkToolOutput } from "./output.ts";
9
+ export { createAiSdkReadTool } from "./tool.ts";
10
+ export type { AiSdkReadTool, CreateAiSdkReadToolOptions } from "./tool.ts";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createAiSdkBashTool } from "./bash-tool.js";
2
+ export { createAiSdkFsTools } from "./fs-tools.js";
3
+ export { createAiSdkApplyPatchTool, createAiSdkEditTool, createAiSdkWriteTool, } from "./mutation-tools.js";
4
+ export { toAiSdkOutput } from "./output.js";
5
+ export { createAiSdkReadTool } from "./tool.js";
@@ -0,0 +1,50 @@
1
+ import type { Schema, ToolExecutionOptions } from "ai";
2
+ import type { JsonObject, StateNeedsDigest, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { ApplyPatchToolDeps, EditToolDeps, MutationResult, WriteLimits, WriteToolDeps } from "@better-fs-tools/write";
4
+ import type { EditSignature, MutationSignature, PatchSignature, WriteSignature } from "@better-fs-tools/write/signature";
5
+ import type { AiSdkToolOutput } from "./output.ts";
6
+ /** Options for createAiSdkEditTool. A state store requires a digest. */
7
+ export type CreateAiSdkEditToolOptions<C = unknown> = EditToolDeps<ToolExecutionOptions<C>> & StateNeedsDigest & {
8
+ /** Defaults to defaultEditSignature() for `options.matchers`. */
9
+ readonly signature?: EditSignature;
10
+ };
11
+ /** Options for createAiSdkWriteTool. A state store requires a digest. */
12
+ export type CreateAiSdkWriteToolOptions<C = unknown> = WriteToolDeps<ToolExecutionOptions<C>> & StateNeedsDigest & {
13
+ /** Defaults to defaultWriteSignature(). */
14
+ readonly signature?: WriteSignature;
15
+ };
16
+ /** Options for createAiSdkApplyPatchTool. A state store requires a digest. */
17
+ export type CreateAiSdkApplyPatchToolOptions<C = unknown> = ApplyPatchToolDeps<ToolExecutionOptions<C>> & StateNeedsDigest & {
18
+ /** Defaults to defaultPatchSignature(). A grammar on the signature is ignored: AI SDK tools take JSON only. */
19
+ readonly signature?: PatchSignature;
20
+ };
21
+ /** An AI SDK edit, write, or apply_patch tool, assignable to `Tool<JsonObject, MutationResult, C>` from ai 7.0.77. */
22
+ export interface AiSdkMutationTool<C = unknown> {
23
+ readonly name: string;
24
+ readonly description: string;
25
+ readonly strict: true;
26
+ /** The strict input schema. A `null` for an optional parameter means absent. */
27
+ readonly inputSchema: Schema<JsonObject>;
28
+ /** Runs the change. The AI SDK execution options are the call's host. */
29
+ execute(input: JsonObject, options: ToolExecutionOptions<C>): Promise<MutationResult>;
30
+ toModelOutput(options: {
31
+ output: MutationResult;
32
+ }): AiSdkToolOutput;
33
+ }
34
+ export type BuiltMutationTool<C> = (input: never, ctx: ToolCallContext<ToolExecutionOptions<C>>) => Promise<MutationResult>;
35
+ /** Creates an AI SDK edit tool. `options.messages` override the signature's messages. */
36
+ export declare function createAiSdkEditTool<C = unknown>(options: CreateAiSdkEditToolOptions<C>): AiSdkMutationTool<C>;
37
+ /** Creates an AI SDK write tool. `options.messages` override the signature's messages. */
38
+ export declare function createAiSdkWriteTool<C = unknown>(options: CreateAiSdkWriteToolOptions<C>): AiSdkMutationTool<C>;
39
+ /**
40
+ * Creates an AI SDK apply_patch tool. `options.messages` override the
41
+ * signature's messages. The model sends JSON even when the signature has a
42
+ * grammar, because the AI SDK has no freeform tool input.
43
+ */
44
+ export declare function createAiSdkApplyPatchTool<C = unknown>(options: CreateAiSdkApplyPatchToolOptions<C>): AiSdkMutationTool<C>;
45
+ export declare function matchersOf(matchers: EditToolDeps["matchers"]): {
46
+ matchers?: undefined;
47
+ } | {
48
+ matchers: readonly import("@better-fs-tools/write").Matcher[];
49
+ };
50
+ export declare function adaptMutationTool<TInput, C>(signature: MutationSignature<TInput>, tool: BuiltMutationTool<C>, parse: (input: TInput, limits: Readonly<WriteLimits>) => unknown, limitOverrides: Partial<WriteLimits> | undefined): AiSdkMutationTool<C>;
@@ -0,0 +1,81 @@
1
+ import { jsonSchema } from "ai";
2
+ import { createApplyPatchTool, createEditTool, createWriteTool, parseApplyPatchInput, parseEditInput, parseWriteInput, resolveWriteLimits, } from "@better-fs-tools/write";
3
+ import { defaultEditSignature, defaultPatchSignature, defaultWriteSignature, writeSignatureMessages, } from "@better-fs-tools/write/signature";
4
+ import { toAiSdkOutput } from "./output.js";
5
+ import { fromStrictInput, toStrictSchema } from "./strict.js";
6
+ /** Creates an AI SDK edit tool. `options.messages` override the signature's messages. */
7
+ export function createAiSdkEditTool(options) {
8
+ checkOptions(options, "edit");
9
+ const { signature: given, ...deps } = options;
10
+ const signature = given ?? defaultEditSignature(matchersOf(deps.matchers));
11
+ const edit = createEditTool({
12
+ ...deps,
13
+ messages: { ...writeSignatureMessages(signature), ...deps.messages },
14
+ });
15
+ return adaptMutationTool(signature, edit, parseEditInput, deps.limits);
16
+ }
17
+ /** Creates an AI SDK write tool. `options.messages` override the signature's messages. */
18
+ export function createAiSdkWriteTool(options) {
19
+ checkOptions(options, "write");
20
+ const { signature = defaultWriteSignature(), ...deps } = options;
21
+ const write = createWriteTool({
22
+ ...deps,
23
+ messages: { ...writeSignatureMessages(signature), ...deps.messages },
24
+ });
25
+ return adaptMutationTool(signature, write, parseWriteInput, deps.limits);
26
+ }
27
+ /**
28
+ * Creates an AI SDK apply_patch tool. `options.messages` override the
29
+ * signature's messages. The model sends JSON even when the signature has a
30
+ * grammar, because the AI SDK has no freeform tool input.
31
+ */
32
+ export function createAiSdkApplyPatchTool(options) {
33
+ checkOptions(options, "apply_patch");
34
+ const { signature = defaultPatchSignature(), ...deps } = options;
35
+ const applyPatch = createApplyPatchTool({
36
+ ...deps,
37
+ messages: { ...writeSignatureMessages(signature), ...deps.messages },
38
+ });
39
+ return adaptMutationTool(signature, applyPatch, parseApplyPatchInput, deps.limits);
40
+ }
41
+ function checkOptions(options, tool) {
42
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
43
+ throw new TypeError(`AI SDK ${tool} tool options must be an object`);
44
+ }
45
+ }
46
+ export function matchersOf(matchers) {
47
+ return matchers === undefined ? {} : { matchers };
48
+ }
49
+ export function adaptMutationTool(signature, tool, parse, limitOverrides) {
50
+ const limits = resolveWriteLimits(limitOverrides);
51
+ const strict = toStrictSchema(signature.schema, signature.name);
52
+ return Object.freeze({
53
+ name: signature.name,
54
+ description: signature.description,
55
+ strict: true,
56
+ inputSchema: jsonSchema(strict, {
57
+ validate(model) {
58
+ try {
59
+ const value = fromStrictInput(signature.schema, model);
60
+ parse(signature.toInput(value), limits);
61
+ return { success: true, value: value };
62
+ }
63
+ catch (error) {
64
+ return {
65
+ success: false,
66
+ error: error instanceof Error ? error : new Error(String(error)),
67
+ };
68
+ }
69
+ },
70
+ }),
71
+ async execute(input, execution) {
72
+ const call = {
73
+ ...(execution.abortSignal === undefined ? {} : { signal: execution.abortSignal }),
74
+ callId: execution.toolCallId,
75
+ host: execution,
76
+ };
77
+ return tool(signature.toInput(fromStrictInput(signature.schema, input)), call);
78
+ },
79
+ toModelOutput: ({ output }) => toAiSdkOutput(output),
80
+ });
81
+ }
@@ -0,0 +1,21 @@
1
+ import type { ContentPart } from "@better-fs-tools/read";
2
+ export type AiSdkContentPart = {
3
+ type: "text";
4
+ text: string;
5
+ } | {
6
+ type: "file";
7
+ mediaType: string;
8
+ data: {
9
+ type: "data";
10
+ data: string;
11
+ };
12
+ };
13
+ /** The model output of every AI SDK tool: read, edit, write, apply_patch, and bash. */
14
+ export interface AiSdkToolOutput {
15
+ type: "content";
16
+ value: AiSdkContentPart[];
17
+ }
18
+ /** Converts a read, mutation, or bash result to AI SDK tool output. Media parts become base64 file parts. */
19
+ export declare function toAiSdkOutput(result: {
20
+ readonly content: readonly ContentPart[];
21
+ }): AiSdkToolOutput;
package/dist/output.js ADDED
@@ -0,0 +1,17 @@
1
+ import { toBase64 } from "./base64.js";
2
+ /** Converts a read, mutation, or bash result to AI SDK tool output. Media parts become base64 file parts. */
3
+ export function toAiSdkOutput(result) {
4
+ return { type: "content", value: result.content.map(toAiSdkPart) };
5
+ }
6
+ function toAiSdkPart(part) {
7
+ switch (part.type) {
8
+ case "text":
9
+ return { type: "text", text: part.text };
10
+ case "media":
11
+ return {
12
+ type: "file",
13
+ mediaType: part.mediaType,
14
+ data: { type: "data", data: toBase64(part.data) },
15
+ };
16
+ }
17
+ }
@@ -0,0 +1,9 @@
1
+ import type { JsonObject } from "@better-fs-tools/read";
2
+ /**
3
+ * Converts a signature schema to the JSON Schema subset OpenAI strict mode
4
+ * accepts. Optional properties become required and nullable. Throws TypeError
5
+ * naming the tool and schema path for a form strict mode cannot express.
6
+ */
7
+ export declare function toStrictSchema(schema: JsonObject, tool: string): JsonObject;
8
+ /** Turns each `null` that toStrictSchema allows for an optional property back into an absent key. */
9
+ export declare function fromStrictInput(schema: JsonObject, input: unknown): unknown;
package/dist/strict.js ADDED
@@ -0,0 +1,312 @@
1
+ const UNSUPPORTED_KEYWORDS = [
2
+ "not",
3
+ "if",
4
+ "then",
5
+ "else",
6
+ "patternProperties",
7
+ "propertyNames",
8
+ "unevaluatedProperties",
9
+ "unevaluatedItems",
10
+ "dependentSchemas",
11
+ "dependentRequired",
12
+ "dependencies",
13
+ "prefixItems",
14
+ "additionalItems",
15
+ "contains",
16
+ ];
17
+ /** Keywords OpenAI strict mode supports. Others are dropped; the signature's parse still checks them. */
18
+ const STRICT_KEYWORDS = new Set([
19
+ "type",
20
+ "description",
21
+ "properties",
22
+ "required",
23
+ "additionalProperties",
24
+ "items",
25
+ "anyOf",
26
+ "$ref",
27
+ "$defs",
28
+ "enum",
29
+ "pattern",
30
+ "format",
31
+ "minimum",
32
+ "maximum",
33
+ "exclusiveMinimum",
34
+ "exclusiveMaximum",
35
+ "multipleOf",
36
+ "minItems",
37
+ "maxItems",
38
+ ]);
39
+ /** String formats OpenAI strict mode supports. */
40
+ const STRICT_FORMATS = new Set([
41
+ "date-time",
42
+ "time",
43
+ "date",
44
+ "duration",
45
+ "email",
46
+ "hostname",
47
+ "ipv4",
48
+ "ipv6",
49
+ "uuid",
50
+ ]);
51
+ /**
52
+ * Converts a signature schema to the JSON Schema subset OpenAI strict mode
53
+ * accepts. Optional properties become required and nullable. Throws TypeError
54
+ * naming the tool and schema path for a form strict mode cannot express.
55
+ */
56
+ export function toStrictSchema(schema, tool) {
57
+ const root = structuredClone(schema);
58
+ const walk = { tool, root, renamesDefinitions: "definitions" in root };
59
+ if (walk.renamesDefinitions && "$defs" in root)
60
+ refuse(walk, "#/definitions", "both $defs and definitions");
61
+ const strict = strictNode(root, walk, "#");
62
+ if (strict.type !== "object" || "anyOf" in strict) {
63
+ refuse(walk, "#", "a root schema that is not an object");
64
+ }
65
+ return deepFreeze(strict);
66
+ }
67
+ /** Turns each `null` that toStrictSchema allows for an optional property back into an absent key. */
68
+ export function fromStrictInput(schema, input) {
69
+ return restore(schema, input, schema);
70
+ }
71
+ function strictNode(input, walk, at) {
72
+ const schema = mergeAllOf(input, (form, where) => refuse(walk, `${at}${where}`, form));
73
+ for (const key of UNSUPPORTED_KEYWORDS) {
74
+ if (key in schema)
75
+ refuse(walk, `${at}/${key}`, `the "${key}" keyword`);
76
+ }
77
+ if ("anyOf" in schema && "oneOf" in schema)
78
+ refuse(walk, `${at}/oneOf`, "both anyOf and oneOf");
79
+ if ("definitions" in schema && at !== "#") {
80
+ refuse(walk, `${at}/definitions`, "definitions below the root");
81
+ }
82
+ const next = {};
83
+ for (const [key, value] of Object.entries(schema)) {
84
+ if (STRICT_KEYWORDS.has(key))
85
+ next[key] = value;
86
+ }
87
+ if (typeof schema.format === "string" && !STRICT_FORMATS.has(schema.format))
88
+ delete next.format;
89
+ if ("const" in schema)
90
+ next.enum = [schema.const];
91
+ const ref = schema.$ref;
92
+ if (ref !== undefined) {
93
+ if (typeof ref !== "string" || resolvePointer(ref, walk.root) === undefined) {
94
+ refuse(walk, `${at}/$ref`, "a $ref that is not a local pointer into the schema");
95
+ }
96
+ if (walk.renamesDefinitions && ref.startsWith("#/definitions/")) {
97
+ next.$ref = `#/$defs/${ref.slice("#/definitions/".length)}`;
98
+ }
99
+ }
100
+ const definitions = schema.$defs ?? schema.definitions;
101
+ if (definitions !== undefined) {
102
+ const key = "$defs" in schema ? "$defs" : "definitions";
103
+ if (!isObject(definitions))
104
+ refuse(walk, `${at}/${key}`, `a ${key} that is not an object`);
105
+ const strict = {};
106
+ for (const [name, child] of Object.entries(definitions)) {
107
+ strict[name] = strictChild(child, walk, `${at}/${key}/${name}`);
108
+ }
109
+ next.$defs = strict;
110
+ }
111
+ const union = schema.anyOf ?? schema.oneOf;
112
+ if (union !== undefined) {
113
+ const key = "anyOf" in schema ? "anyOf" : "oneOf";
114
+ if (!Array.isArray(union))
115
+ refuse(walk, `${at}/${key}`, `a ${key} that is not a list`);
116
+ next.anyOf = union.map((child, index) => strictChild(child, walk, `${at}/${key}/${index}`));
117
+ }
118
+ if (!["type", "enum", "const", "anyOf", "oneOf", "$ref"].some((key) => key in schema)) {
119
+ refuse(walk, at, "a schema with no type");
120
+ }
121
+ const items = schema.items;
122
+ if (items !== undefined) {
123
+ if (!isObject(items))
124
+ refuse(walk, `${at}/items`, "tuple items");
125
+ next.items = strictNode(items, walk, `${at}/items`);
126
+ }
127
+ const properties = schema.properties;
128
+ const open = schema.additionalProperties;
129
+ if (properties !== undefined) {
130
+ if (!isObject(properties))
131
+ refuse(walk, `${at}/properties`, "properties that are not an object");
132
+ if (open !== undefined && open !== false) {
133
+ refuse(walk, `${at}/additionalProperties`, "an object that allows other properties");
134
+ }
135
+ const required = requiredOf(schema);
136
+ const strict = {};
137
+ for (const [key, child] of Object.entries(properties)) {
138
+ const node = strictChild(child, walk, `${at}/properties/${key}`);
139
+ strict[key] = required.includes(key) ? node : nullable(node);
140
+ }
141
+ next.properties = strict;
142
+ next.required = Object.keys(properties);
143
+ next.additionalProperties = false;
144
+ }
145
+ else if (typeIncludes(schema, "object") && open !== false) {
146
+ refuse(walk, at, "an object with no properties that allows other properties");
147
+ }
148
+ return next;
149
+ }
150
+ function strictChild(child, walk, at) {
151
+ if (!isObject(child))
152
+ refuse(walk, at, "a schema that is not an object");
153
+ return strictNode(child, walk, at);
154
+ }
155
+ function mergeAllOf(schema, conflict) {
156
+ const allOf = schema.allOf;
157
+ if (allOf === undefined)
158
+ return schema;
159
+ if (!Array.isArray(allOf))
160
+ conflict("an allOf that is not a list", "/allOf");
161
+ const { allOf: _, ...merged } = schema;
162
+ let objects = "properties" in merged ? 1 : 0;
163
+ for (const [index, child] of allOf.entries()) {
164
+ const at = `/allOf/${index}`;
165
+ if (!isObject(child))
166
+ conflict("a schema that is not an object", at);
167
+ if ("$ref" in child)
168
+ conflict("a $ref inside allOf", `${at}/$ref`);
169
+ const branch = mergeAllOf(child, (form, where) => conflict(form, `${at}${where}`));
170
+ if ("properties" in branch && ++objects > 1) {
171
+ conflict("an allOf over more than one object schema", "/allOf");
172
+ }
173
+ for (const [key, value] of Object.entries(branch)) {
174
+ const current = merged[key];
175
+ if (current === undefined)
176
+ merged[key] = value;
177
+ else if (key === "description")
178
+ continue;
179
+ else if (key === "required" && Array.isArray(current) && Array.isArray(value)) {
180
+ merged[key] = [...new Set([...current, ...value])];
181
+ }
182
+ else if (JSON.stringify(current) !== JSON.stringify(value)) {
183
+ conflict(`an allOf whose "${key}" differs from its schema`, `${at}/${key}`);
184
+ }
185
+ }
186
+ }
187
+ return merged;
188
+ }
189
+ function nullable(schema) {
190
+ const type = schema.type;
191
+ const composed = "anyOf" in schema || "$ref" in schema;
192
+ if (!composed && (typeof type === "string" || Array.isArray(type))) {
193
+ const next = { ...schema };
194
+ if (typeof type === "string") {
195
+ if (type !== "null")
196
+ next.type = [type, "null"];
197
+ }
198
+ else if (!type.includes("null")) {
199
+ next.type = [...type, "null"];
200
+ }
201
+ const values = schema.enum;
202
+ if (Array.isArray(values))
203
+ next.enum = values.includes(null) ? values : [...values, null];
204
+ return next;
205
+ }
206
+ const { description, ...rest } = schema;
207
+ return {
208
+ ...(description === undefined ? {} : { description }),
209
+ anyOf: [rest, { type: "null" }],
210
+ };
211
+ }
212
+ function restore(schema, input, root) {
213
+ const node = mergedOrAsIs(resolveRef(schema, root));
214
+ let value = input;
215
+ for (const key of ["anyOf", "oneOf"]) {
216
+ const branches = node[key];
217
+ if (!Array.isArray(branches))
218
+ continue;
219
+ const branch = findBranchFitting(branches, value, root);
220
+ if (branch !== undefined)
221
+ value = restore(branch, value, root);
222
+ }
223
+ if (Array.isArray(value)) {
224
+ const items = node.items;
225
+ return isObject(items) ? value.map((item) => restore(items, item, root)) : value;
226
+ }
227
+ if (!isObject(value))
228
+ return value;
229
+ const properties = node.properties;
230
+ if (!isObject(properties))
231
+ return value;
232
+ const required = requiredOf(node);
233
+ const output = {};
234
+ for (const [key, child] of Object.entries(value)) {
235
+ const property = properties[key];
236
+ if (child === null && isObject(property) && !required.includes(key))
237
+ continue;
238
+ output[key] = isObject(property) ? restore(property, child, root) : child;
239
+ }
240
+ return output;
241
+ }
242
+ function mergedOrAsIs(schema) {
243
+ try {
244
+ return mergeAllOf(schema, (form) => {
245
+ throw new TypeError(form);
246
+ });
247
+ }
248
+ catch {
249
+ return schema;
250
+ }
251
+ }
252
+ function findBranchFitting(branches, value, root) {
253
+ const nodes = branches.filter(isObject).map((branch) => mergedOrAsIs(resolveRef(branch, root)));
254
+ if (Array.isArray(value))
255
+ return nodes.find((node) => isObject(node.items));
256
+ if (!isObject(value))
257
+ return undefined;
258
+ const keys = Object.keys(value);
259
+ return nodes.find((node) => {
260
+ const properties = node.properties;
261
+ return isObject(properties) && keys.every((key) => key in properties);
262
+ });
263
+ }
264
+ const MAX_REF_HOPS = 32;
265
+ function resolveRef(schema, root) {
266
+ let node = schema;
267
+ for (let hops = 0; hops < MAX_REF_HOPS && typeof node.$ref === "string"; hops++) {
268
+ const target = resolvePointer(node.$ref, root);
269
+ if (target === undefined)
270
+ break;
271
+ node = target;
272
+ }
273
+ return node;
274
+ }
275
+ function resolvePointer(ref, root) {
276
+ if (ref === "#")
277
+ return root;
278
+ if (!ref.startsWith("#/"))
279
+ return undefined;
280
+ let node = root;
281
+ for (const part of ref.slice(2).split("/")) {
282
+ const key = decodeURIComponent(part).replaceAll("~1", "/").replaceAll("~0", "~");
283
+ if (!isObject(node) || !(key in node))
284
+ return undefined;
285
+ node = node[key];
286
+ }
287
+ return isObject(node) ? node : undefined;
288
+ }
289
+ function refuse(walk, at, form) {
290
+ throw new TypeError(`${walk.tool}: strict mode cannot express ${form} at ${at}`);
291
+ }
292
+ function typeIncludes(schema, name) {
293
+ const type = schema.type;
294
+ return type === name || (Array.isArray(type) && type.includes(name));
295
+ }
296
+ function requiredOf(schema) {
297
+ const required = schema.required;
298
+ return Array.isArray(required)
299
+ ? required.filter((key) => typeof key === "string")
300
+ : [];
301
+ }
302
+ function isObject(value) {
303
+ return value !== null && typeof value === "object" && !Array.isArray(value);
304
+ }
305
+ function deepFreeze(value) {
306
+ if (value !== null && typeof value === "object") {
307
+ for (const child of Object.values(value))
308
+ deepFreeze(child);
309
+ Object.freeze(value);
310
+ }
311
+ return value;
312
+ }
package/dist/tool.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Schema, ToolExecutionOptions } from "ai";
2
+ import type { JsonObject, ReadLimits, ReadResult, ReadTool, ReadToolDeps, StateNeedsDigest } from "@better-fs-tools/read";
3
+ import type { ReadSignature } from "@better-fs-tools/read/signature";
4
+ import type { AiSdkToolOutput } from "./output.ts";
5
+ /** Options for createAiSdkReadTool. A state store requires a digest. */
6
+ export type CreateAiSdkReadToolOptions<C = unknown> = ReadToolDeps<ToolExecutionOptions<C>> & StateNeedsDigest & {
7
+ /** Defaults to defaultReadSignature(). */
8
+ readonly signature?: ReadSignature;
9
+ };
10
+ /** An AI SDK read tool, assignable to `Tool<JsonObject, ReadResult, C>` from ai 7.0.77. */
11
+ export interface AiSdkReadTool<C = unknown> {
12
+ readonly name: string;
13
+ readonly description: string;
14
+ readonly strict: true;
15
+ /** The strict input schema. A `null` for an optional parameter means absent. */
16
+ readonly inputSchema: Schema<JsonObject>;
17
+ /** Runs the read. The AI SDK execution options are the call's host. */
18
+ execute(input: JsonObject, options: ToolExecutionOptions<C>): Promise<ReadResult>;
19
+ toModelOutput(options: {
20
+ output: ReadResult;
21
+ }): AiSdkToolOutput;
22
+ }
23
+ /** Creates an AI SDK read tool. `options.messages` override the signature's messages. */
24
+ export declare function createAiSdkReadTool<C = unknown>(options: CreateAiSdkReadToolOptions<C>): AiSdkReadTool<C>;
25
+ export declare function adaptReadTool<C>(signature: ReadSignature, read: ReadTool<ToolExecutionOptions<C>>, limitOverrides: Partial<ReadLimits> | undefined): AiSdkReadTool<C>;
package/dist/tool.js ADDED
@@ -0,0 +1,50 @@
1
+ import { jsonSchema } from "ai";
2
+ import { createReadTool, parseReadInput, resolveReadLimits } from "@better-fs-tools/read";
3
+ import { defaultReadSignature, readSignatureMessages } from "@better-fs-tools/read/signature";
4
+ import { toAiSdkOutput } from "./output.js";
5
+ import { fromStrictInput, toStrictSchema } from "./strict.js";
6
+ /** Creates an AI SDK read tool. `options.messages` override the signature's messages. */
7
+ export function createAiSdkReadTool(options) {
8
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
9
+ throw new TypeError("AI SDK read tool options must be an object");
10
+ }
11
+ const { signature = defaultReadSignature(), ...deps } = options;
12
+ const read = createReadTool({
13
+ ...deps,
14
+ messages: { ...readSignatureMessages(signature), ...deps.messages },
15
+ });
16
+ return adaptReadTool(signature, read, deps.limits);
17
+ }
18
+ export function adaptReadTool(signature, read, limitOverrides) {
19
+ const limits = resolveReadLimits(limitOverrides);
20
+ const strict = toStrictSchema(signature.schema, signature.name);
21
+ return Object.freeze({
22
+ name: signature.name,
23
+ description: signature.description,
24
+ strict: true,
25
+ inputSchema: jsonSchema(strict, {
26
+ validate(model) {
27
+ try {
28
+ const value = fromStrictInput(signature.schema, model);
29
+ parseReadInput(signature.toInput(value), limits);
30
+ return { success: true, value: value };
31
+ }
32
+ catch (error) {
33
+ return {
34
+ success: false,
35
+ error: error instanceof Error ? error : new Error(String(error)),
36
+ };
37
+ }
38
+ },
39
+ }),
40
+ async execute(input, execution) {
41
+ const call = {
42
+ ...(execution.abortSignal === undefined ? {} : { signal: execution.abortSignal }),
43
+ callId: execution.toolCallId,
44
+ host: execution,
45
+ };
46
+ return read(signature.toInput(fromStrictInput(signature.schema, input)), call);
47
+ },
48
+ toModelOutput: ({ output }) => toAiSdkOutput(output),
49
+ });
50
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@better-fs-tools/ai-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Better FS Tools read, edit, write, apply_patch, and bash tools for AI SDK 7.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/gingerhendrix/better-fs-tools.git",
9
+ "directory": "packages/ai-sdk"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "publishConfig": {
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js"
27
+ }
28
+ },
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@better-fs-tools/read": "^0.1.0",
33
+ "@better-fs-tools/shell": "^0.1.0",
34
+ "@better-fs-tools/write": "^0.1.0"
35
+ },
36
+ "devDependencies": {
37
+ "@ai-sdk/openai": "4.0.78",
38
+ "@better-fs-tools/fs": "^0.1.0",
39
+ "@better-fs-tools/just-bash": "^0.1.0",
40
+ "ai": "^7.0.77",
41
+ "just-bash": "3.4.2"
42
+ },
43
+ "peerDependencies": {
44
+ "ai": "^7.0.77"
45
+ }
46
+ }