@better-fs-tools/ai-sdk 0.2.0 → 0.3.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/README.md CHANGED
@@ -17,15 +17,15 @@ import { generateText, isStepCount } from "ai";
17
17
  import type { LanguageModel } from "ai";
18
18
  import { createAiSdkReadTool } from "@better-fs-tools/ai-sdk";
19
19
  import { nodeDigest, nodeFileSystem } from "@better-fs-tools/node";
20
- import { lineRangeSignature } from "@better-fs-tools/read/signature";
20
+ import { defaultReadSignature } from "@better-fs-tools/read/signature";
21
21
 
22
22
  const cwd = process.cwd();
23
23
  const read = createAiSdkReadTool({
24
24
  fs: nodeFileSystem({ cwd, allowedRoots: [cwd] }),
25
25
  digest: nodeDigest(),
26
- signature: lineRangeSignature({
26
+ signature: defaultReadSignature({
27
27
  name: "read_file",
28
- names: { path: "file_path", start: "start_line", end: "end_line" },
28
+ names: { path: "file_path", offset: "start_line", limit: "max_lines" },
29
29
  }),
30
30
  });
31
31
 
@@ -42,12 +42,12 @@ export async function ask(model: LanguageModel, prompt: string): Promise<string>
42
42
 
43
43
  ## What the tool does
44
44
 
45
- - `createAiSdkReadTool(options)` takes every `createReadTool()` option, plus `signature`. `fs` is required. `digest` defaults to `null`, as in the core.
45
+ - `createAiSdkReadTool(options)` takes every `createReadTool()` option, with the same defaults, plus `signature` and `contextSchema`. `fs` is required. It is an adapter over `readToolDefinition()` from `@better-fs-tools/read/signature`.
46
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
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`.
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`. Set `contextSchema` on a factory or on the bundle to give each tool a context schema. The AI SDK then accepts a `toolsContext` of the factory's context type, and validates it before `execute`. `execute` returns the whole `ReadResult`. If `toInput` refuses an input that reached `execute`, `execute` rejects with that `TypeError`.
49
49
  - Retry text in notes uses the signature's names. `result.continuation.next` stays canonical.
50
- - `converters` defaults to `[imageConverter()]`, so an image read gives a `media` result. The core has no converters by default; this host turns images on. A list you pass replaces the default: `converters: []` turns images off, and a list without `imageConverter()` refuses images.
50
+ - `converters` defaults to `[imageConverter()]`, as in the core, so an image read gives a `media` result. A list you pass replaces the default: `converters: []` turns images off, and a list without `imageConverter()` refuses images.
51
51
  - `toModelOutput` maps text parts to text parts, and media parts to base64 `file` parts. `toAiSdkOutput(result)` does the same mapping for your own tool.
52
52
 
53
53
  For a Cloudflare Agents host, pass `fs: cloudflareShellFileSystem(workspace, { allowedRoots: [root] })` from `@better-fs-tools/cloudflare-shell`. No other wrapper is needed.
@@ -73,9 +73,9 @@ export async function change(model: LanguageModel, prompt: string): Promise<stri
73
73
  }
74
74
  ```
75
75
 
76
- - `createAiSdkFsTools(options)` wraps `createFsTools()`. `fs` is required. `state` (default `null`, so read-before-write is off; `memoryStore()` turns it on), `digest`, `locks`, and `clock` are set once. Each tool's other options, and its `signature`, go under `read`, `edit`, `write`, and `applyPatch`. `read.converters` defaults to `[imageConverter()]`, as for `createAiSdkReadTool()`; `read: { converters: [] }` turns images off. `applyPatch: true`, or an options object, adds `apply_patch`. `bash: { runner, env, ... }` adds a bash tool with the same digest and clock. The result has `read`, `edit`, `write`, `applyPatch` and `bash` (`null` when off), `tools` (only the tools that are on), `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`.
77
- - 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 read-before-write is off. A `state` needs a `digest`: the options type refuses one without the other, and the factory throws `TypeError`.
78
- - 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.
76
+ - `createAiSdkFsTools(options)` takes the options of `createFsTools()`, with the same defaults, plus `contextSchema`. It is an adapter over `fsToolDefinitions()`. `fs` is required. `state` (default `null`, so read-before-write is off; a store or a per-call factory turns it on), `digest`, `locks`, and `clock` are set once. Each tool's other options, and its `signature`, go under `read`, `edit`, `write`, `applyPatch`, and `bash`. `applyPatch: true`, or an options object, adds `apply_patch`. `bash: { runner, env, ... }` adds a bash tool with the same digest and clock. The result has `read`, `edit`, `write`, `applyPatch` and `bash` (`null` when off), `tools` (only the tools that are on), `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`.
77
+ - The single factories, `createAiSdkEditTool()`, `createAiSdkWriteTool()`, `createAiSdkApplyPatchTool()`, and `createAiSdkBashTool()`, take every option of their core factory, with the same defaults, plus `signature` and `contextSchema`. `fs` is required, and bash needs `runner` and `env`. `state` defaults to `null`, so read-before-write is off. `digest` defaults to `sha256Digest()`. A `state` with `digest: null` does not type-check, and the factory throws `TypeError`.
78
+ - The default signatures are the shared defaults of every integration: `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.
79
79
  - The tools are `strict: true`. The schema's `validate` hook runs `signature.toInput` and the core input check.
80
80
  - `execute` passes the `ToolExecutionOptions` object as `ctx.call.host`, and returns the whole `MutationResult`. `toModelOutput` gives the model the formatter's text.
81
81
  - AI SDK tools take JSON only. A signature with a grammar, such as `freeformPatchSignature()`, still works, but the grammar is not sent.
@@ -131,7 +131,7 @@ OPENAI_API_KEY=sk-... bun run test:e2e
131
131
 
132
132
  ## Links
133
133
 
134
- - `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
+ - [Choose a host](https://better-fs-tools.gandrew.com/hosts) and [Backends](https://better-fs-tools.gandrew.com/backends) on the docs site: the defaults of every host and bundle, and what each backend can do. `docs/hosts.md` in [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write) has the same tables
135
135
  - [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): every read option, and the signature builders
136
136
  - [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write): every write option, and the write signatures
137
137
  - [`@better-fs-tools/cloudflare-shell`](https://www.npmjs.com/package/@better-fs-tools/cloudflare-shell): a filesystem for Cloudflare Agents
@@ -0,0 +1,38 @@
1
+ import type { FlexibleSchema, Schema, ToolExecutionOptions } from "ai";
2
+ import type { ContentPart, JsonObject, ToolCallContext } from "@better-fs-tools/read";
3
+ import type { AiSdkToolOutput } from "./output.ts";
4
+ /** An AI SDK tool, assignable to `Tool<JsonObject, TResult, C>` from ai 7.0.77. */
5
+ export interface AiSdkTool<TResult, C = unknown> {
6
+ readonly name: string;
7
+ readonly description: string;
8
+ readonly strict: true;
9
+ /** The strict input schema. A `null` for an optional parameter means absent. */
10
+ readonly inputSchema: Schema<JsonObject>;
11
+ /**
12
+ * The schema of the context that AI SDK passes from `toolsContext`, if set.
13
+ * The field also lets the AI SDK types accept a `toolsContext` entry of type `C`.
14
+ */
15
+ readonly contextSchema?: FlexibleSchema<C>;
16
+ /** Runs the tool. The AI SDK execution options are the call's host. */
17
+ execute(input: JsonObject, options: ToolExecutionOptions<C>): Promise<TResult>;
18
+ toModelOutput(options: {
19
+ output: TResult;
20
+ }): AiSdkToolOutput;
21
+ }
22
+ /** The parts of a tool definition that the adapter uses. Every xxxToolDefinition() result fits. */
23
+ export interface AiSdkDefinitionSource<TResult, C> {
24
+ readonly name: string;
25
+ readonly description: string;
26
+ readonly inputSchema: JsonObject;
27
+ validate(modelInput: unknown): unknown;
28
+ execute(modelInput: unknown, ctx: ToolCallContext<ToolExecutionOptions<C>>): Promise<TResult>;
29
+ }
30
+ /**
31
+ * Wraps a tool definition as a strict AI SDK tool. The schema's `validate`
32
+ * hook runs the definition's validate on the input without the strict nulls.
33
+ * Throws TypeError when strict mode cannot express the schema.
34
+ */
35
+ export declare function adaptAiSdkTool<TResult extends {
36
+ readonly content: readonly ContentPart[];
37
+ }, C>(definition: AiSdkDefinitionSource<TResult, C>, contextSchema: FlexibleSchema<C> | undefined): AiSdkTool<TResult, C>;
38
+ export declare function checkOptions(options: unknown, label: string): void;
package/dist/adapt.js ADDED
@@ -0,0 +1,47 @@
1
+ import { jsonSchema } from "ai";
2
+ import { toAiSdkOutput } from "./output.js";
3
+ import { fromStrictInput, toStrictSchema } from "./strict.js";
4
+ /**
5
+ * Wraps a tool definition as a strict AI SDK tool. The schema's `validate`
6
+ * hook runs the definition's validate on the input without the strict nulls.
7
+ * Throws TypeError when strict mode cannot express the schema.
8
+ */
9
+ export function adaptAiSdkTool(definition, contextSchema) {
10
+ const schema = definition.inputSchema;
11
+ const strict = toStrictSchema(schema, definition.name);
12
+ return Object.freeze({
13
+ name: definition.name,
14
+ description: definition.description,
15
+ strict: true,
16
+ inputSchema: jsonSchema(strict, {
17
+ validate(model) {
18
+ try {
19
+ const value = fromStrictInput(schema, model);
20
+ definition.validate(value);
21
+ return { success: true, value: value };
22
+ }
23
+ catch (error) {
24
+ return {
25
+ success: false,
26
+ error: error instanceof Error ? error : new Error(String(error)),
27
+ };
28
+ }
29
+ },
30
+ }),
31
+ async execute(input, execution) {
32
+ const call = {
33
+ ...(execution.abortSignal === undefined ? {} : { signal: execution.abortSignal }),
34
+ callId: execution.toolCallId,
35
+ host: execution,
36
+ };
37
+ return definition.execute(fromStrictInput(schema, input), call);
38
+ },
39
+ toModelOutput: ({ output }) => toAiSdkOutput(output),
40
+ ...(contextSchema === undefined ? {} : { contextSchema }),
41
+ });
42
+ }
43
+ export function checkOptions(options, label) {
44
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
45
+ throw new TypeError(`${label} options must be an object`);
46
+ }
47
+ }
@@ -1,35 +1,19 @@
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;
1
+ import type { FlexibleSchema, ToolExecutionOptions } from "ai";
2
+ import type { ShellResult } from "@better-fs-tools/shell";
3
+ import type { BashToolDefinitionOptions } from "@better-fs-tools/shell/signature";
4
+ import type { AiSdkTool } from "./adapt.ts";
5
+ /** Options for createAiSdkBashTool: the options of bashToolDefinition(), plus `contextSchema`. */
6
+ export type AiSdkBashToolOptions<C = unknown> = BashToolDefinitionOptions<ToolExecutionOptions<C>> & {
7
+ /** Checks the `toolsContext` entry of this tool. The AI SDK validates the context with it before `execute`. */
8
+ readonly contextSchema?: FlexibleSchema<C>;
9
9
  };
10
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
- }
11
+ export type AiSdkBashTool<C = unknown> = AiSdkTool<ShellResult, C>;
23
12
  /**
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
13
+ * Creates an AI SDK bash tool with the options and defaults of
14
+ * createBashTool(). The runner and env are required: this package starts no
15
+ * process and does not read process.env. Use nodeCommandRunner() from
27
16
  * @better-fs-tools/node or justBashCommandRunner() from
28
17
  * @better-fs-tools/just-bash, and shellEnv() from @better-fs-tools/shell.
29
18
  */
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>;
19
+ export declare function createAiSdkBashTool<C = unknown>(options: AiSdkBashToolOptions<C>): AiSdkBashTool<C>;
package/dist/bash-tool.js CHANGED
@@ -1,64 +1,14 @@
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";
1
+ import { bashToolDefinition } from "@better-fs-tools/shell/signature";
2
+ import { adaptAiSdkTool, checkOptions } from "./adapt.js";
6
3
  /**
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
4
+ * Creates an AI SDK bash tool with the options and defaults of
5
+ * createBashTool(). The runner and env are required: this package starts no
6
+ * process and does not read process.env. Use nodeCommandRunner() from
10
7
  * @better-fs-tools/node or justBashCommandRunner() from
11
8
  * @better-fs-tools/just-bash, and shellEnv() from @better-fs-tools/shell.
12
9
  */
13
10
  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
- });
11
+ checkOptions(options, "AI SDK bash tool");
12
+ const { contextSchema, ...rest } = options;
13
+ return adaptAiSdkTool(bashToolDefinition(rest), contextSchema);
64
14
  }
@@ -1,30 +1,27 @@
1
- import type { ToolExecutionOptions } from "ai";
2
- import type { Clock, Digest, ReadStateStore, ReadToolDeps, ToolCallContext } from "@better-fs-tools/read";
1
+ import type { FlexibleSchema, ToolExecutionOptions } from "ai";
2
+ import type { Clock, Digest, ToolCallContext } from "@better-fs-tools/read";
3
3
  import type { ReadSignature } from "@better-fs-tools/read/signature";
4
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";
5
+ import type { FsToolsApplyPatchOptions, FsToolsBashOptions, FsToolsEditOptions, FsToolsOptions, FsToolsReadOptions, FsToolsState, FsToolsWriteOptions, InvalidateOutcome, LockManager } from "@better-fs-tools/write";
6
6
  import type { EditSignature, PatchSignature, WriteSignature } from "@better-fs-tools/write/signature";
7
7
  import type { AiSdkBashTool } from "./bash-tool.ts";
8
8
  import type { AiSdkMutationTool } from "./mutation-tools.ts";
9
9
  import type { AiSdkReadTool } from "./tool.ts";
10
10
  type Host<C> = ToolExecutionOptions<C>;
11
- /**
12
- * Read tool options for createAiSdkFsTools. Shared keys are set once at the
13
- * top level. converters defaults to [imageConverter()]; [] turns images off.
14
- */
15
- export type AiSdkFsToolsReadOptions<C = unknown> = Omit<Partial<ReadToolDeps<Host<C>>>, FsToolsSharedKey> & {
11
+ /** Read tool options for createAiSdkFsTools. Shared keys are set once at the top level. */
12
+ export type AiSdkFsToolsReadOptions<C = unknown> = FsToolsReadOptions<Host<C>> & {
16
13
  /** Defaults to defaultReadSignature(). */
17
14
  readonly signature?: ReadSignature;
18
15
  };
19
- export type AiSdkFsToolsEditOptions<C = unknown> = Omit<Partial<EditToolDeps<Host<C>>>, FsToolsSharedKey> & {
16
+ export type AiSdkFsToolsEditOptions<C = unknown> = FsToolsEditOptions<Host<C>> & {
20
17
  /** Defaults to defaultEditSignature() for `matchers`. */
21
18
  readonly signature?: EditSignature;
22
19
  };
23
- export type AiSdkFsToolsWriteOptions<C = unknown> = Omit<Partial<WriteToolDeps<Host<C>>>, FsToolsSharedKey> & {
20
+ export type AiSdkFsToolsWriteOptions<C = unknown> = FsToolsWriteOptions<Host<C>> & {
24
21
  /** Defaults to defaultWriteSignature(). */
25
22
  readonly signature?: WriteSignature;
26
23
  };
27
- export type AiSdkFsToolsApplyPatchOptions<C = unknown> = Omit<Partial<ApplyPatchToolDeps<Host<C>>>, FsToolsSharedKey> & {
24
+ export type AiSdkFsToolsApplyPatchOptions<C = unknown> = FsToolsApplyPatchOptions<Host<C>> & {
28
25
  /** Defaults to defaultPatchSignature(). */
29
26
  readonly signature?: PatchSignature;
30
27
  };
@@ -33,17 +30,13 @@ export type AiSdkFsToolsBashOptions<C = unknown> = FsToolsBashOptions<Host<C>> &
33
30
  /** Defaults to defaultBashSignature() for the runner's id and the limits. */
34
31
  readonly signature?: BashSignature;
35
32
  };
36
- export interface CreateAiSdkFsToolsOptions<C = unknown> {
37
- /** Required. A backend, or a factory called once for each tool call with the AI SDK options as host. */
38
- readonly fs: CreateFsToolsOptions<Host<C>>["fs"];
39
- /** Defaults to null: no read-before-write. A store, for example memoryStore(), turns it on. */
40
- readonly state?: ReadStateStore | null;
41
- /** Defaults to sha256Digest() from @better-fs-tools/read, which runs in a Worker. */
42
- readonly digest?: Digest;
43
- /** Defaults to memoryLocks(). */
44
- readonly locks?: LockManager;
45
- /** Defaults to () => new Date(). */
46
- readonly clock?: Clock;
33
+ /** The options of createFsTools(), with a `signature` in each tool's options, plus `contextSchema`. */
34
+ export interface AiSdkFsToolsOptions<C = unknown> extends Omit<FsToolsOptions<Host<C>>, "read" | "edit" | "write" | "applyPatch" | "bash"> {
35
+ /**
36
+ * Checks the `toolsContext` entry of each tool. The AI SDK validates the
37
+ * context with it before `execute`. Every tool of the bundle gets the same schema.
38
+ */
39
+ readonly contextSchema?: FlexibleSchema<C>;
47
40
  readonly read?: AiSdkFsToolsReadOptions<C>;
48
41
  readonly edit?: AiSdkFsToolsEditOptions<C>;
49
42
  readonly write?: AiSdkFsToolsWriteOptions<C>;
@@ -62,11 +55,11 @@ export interface AiSdkFsTools<C = unknown> {
62
55
  readonly bash: AiSdkBashTool<C> | null;
63
56
  /** Every tool of the bundle keyed by its name, ready for generateText({ tools }). */
64
57
  readonly tools: Readonly<Record<string, AiSdkReadTool<C> | AiSdkMutationTool<C> | AiSdkBashTool<C>>>;
65
- readonly state: ReadStateStore | null;
58
+ readonly state: FsToolsState<Host<C>>;
66
59
  readonly digest: Digest;
67
60
  readonly locks: LockManager;
68
61
  readonly clock: Clock;
69
- /** Same as createFsTools().invalidate. When fs is a factory, pass the call context. */
62
+ /** Same as createFsTools().invalidate. When fs or state is a factory, pass the call context. */
70
63
  invalidate(path: string, call?: ToolCallContext<Host<C>>): Promise<InvalidateOutcome>;
71
64
  }
72
65
  /** The createAiSdkFsTools result when `bash` is set: `bash` is never null. */
@@ -88,15 +81,15 @@ export interface AiSdkFsToolsWithApplyPatch<C = unknown> extends AiSdkFsTools<C>
88
81
  * Throws TypeError on an unknown option key, and on a shared key (fs, state,
89
82
  * digest, locks, clock) inside a tool's options.
90
83
  */
91
- export declare function createAiSdkFsTools<C = unknown>(options: CreateAiSdkFsToolsOptions<C> & {
84
+ export declare function createAiSdkFsTools<C = unknown>(options: AiSdkFsToolsOptions<C> & {
92
85
  readonly bash: AiSdkFsToolsBashOptions<C>;
93
86
  readonly applyPatch: true | AiSdkFsToolsApplyPatchOptions<C>;
94
87
  }): AiSdkFsToolsWithBash<C> & AiSdkFsToolsWithApplyPatch<C>;
95
- export declare function createAiSdkFsTools<C = unknown>(options: CreateAiSdkFsToolsOptions<C> & {
88
+ export declare function createAiSdkFsTools<C = unknown>(options: AiSdkFsToolsOptions<C> & {
96
89
  readonly bash: AiSdkFsToolsBashOptions<C>;
97
90
  }): AiSdkFsToolsWithBash<C>;
98
- export declare function createAiSdkFsTools<C = unknown>(options: CreateAiSdkFsToolsOptions<C> & {
91
+ export declare function createAiSdkFsTools<C = unknown>(options: AiSdkFsToolsOptions<C> & {
99
92
  readonly applyPatch: true | AiSdkFsToolsApplyPatchOptions<C>;
100
93
  }): AiSdkFsToolsWithApplyPatch<C>;
101
- export declare function createAiSdkFsTools<C = unknown>(options: CreateAiSdkFsToolsOptions<C>): AiSdkFsTools<C>;
94
+ export declare function createAiSdkFsTools<C = unknown>(options: AiSdkFsToolsOptions<C>): AiSdkFsTools<C>;
102
95
  export {};
package/dist/fs-tools.js CHANGED
@@ -1,144 +1,30 @@
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, aiSdkConverters } 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
- };
1
+ import { fsToolDefinitions } from "@better-fs-tools/write/signature";
2
+ import { adaptAiSdkTool, checkOptions } from "./adapt.js";
27
3
  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 patchOptions = options.applyPatch === true ? {} : options.applyPatch === false ? null : options.applyPatch;
34
- let patch = null;
35
- if (patchOptions !== null && patchOptions !== undefined) {
36
- const { signature = defaultPatchSignature(), ...deps } = patchOptions;
37
- patch = { deps, signature };
38
- }
39
- const bashOptions = options.bash === undefined || options.bash === false ? null : options.bash;
40
- let bash = null;
41
- if (bashOptions !== null) {
42
- const { signature, ...deps } = bashOptions;
43
- bash = { deps, signature: signature ?? defaultAiSdkBashSignature(deps) };
44
- }
45
- const core = createFsTools({
46
- fs: options.fs,
47
- ...(options.state === undefined ? {} : { state: options.state }),
48
- ...(options.digest === undefined ? {} : { digest: options.digest }),
49
- ...(options.locks === undefined ? {} : { locks: options.locks }),
50
- ...(options.clock === undefined ? {} : { clock: options.clock }),
51
- read: {
52
- ...read,
53
- converters: aiSdkConverters(read.converters),
54
- messages: { ...readSignatureMessages(readSignature), ...read.messages },
55
- },
56
- edit: { ...edit, messages: { ...writeSignatureMessages(editSignature), ...edit.messages } },
57
- write: {
58
- ...write,
59
- messages: { ...writeSignatureMessages(writeSignature), ...write.messages },
60
- },
61
- ...(patch === null
62
- ? {}
63
- : {
64
- applyPatch: {
65
- ...patch.deps,
66
- messages: { ...writeSignatureMessages(patch.signature), ...patch.deps.messages },
67
- },
68
- }),
69
- ...(bash === null
70
- ? {}
71
- : {
72
- bash: {
73
- ...bash.deps,
74
- messages: { ...bashSignatureMessages(bash.signature), ...bash.deps.messages },
75
- },
76
- }),
77
- });
4
+ checkOptions(options, "createAiSdkFsTools");
5
+ const { contextSchema, ...rest } = options;
6
+ const defs = fsToolDefinitions(rest, "createAiSdkFsTools");
78
7
  const adapted = {
79
- read: adaptReadTool(readSignature, core.read, read.limits),
80
- edit: adaptMutationTool(editSignature, core.edit, parseEditInput, edit.limits),
81
- write: adaptMutationTool(writeSignature, core.write, parseWriteInput, write.limits),
82
- applyPatch: patch === null || core.applyPatch === null
8
+ read: adaptAiSdkTool(defs.read, contextSchema),
9
+ edit: adaptAiSdkTool(defs.edit, contextSchema),
10
+ write: adaptAiSdkTool(defs.write, contextSchema),
11
+ applyPatch: defs.applyPatch === null
83
12
  ? null
84
- : adaptMutationTool(patch.signature, core.applyPatch, parseApplyPatchInput, patch.deps.limits),
85
- bash: bash === null || core.bash === null
86
- ? null
87
- : adaptBashTool(bash.signature, core.bash, bash.deps.limits),
13
+ : adaptAiSdkTool(defs.applyPatch, contextSchema),
14
+ bash: defs.bash === null ? null : adaptAiSdkTool(defs.bash, contextSchema),
88
15
  };
89
16
  const tools = {};
90
17
  for (const tool of Object.values(adapted)) {
91
- if (tool === null)
92
- continue;
93
- if (Object.hasOwn(tools, tool.name)) {
94
- throw new TypeError(`createAiSdkFsTools has two tools named ${tool.name}`);
95
- }
96
- tools[tool.name] = tool;
18
+ if (tool !== null)
19
+ tools[tool.name] = tool;
97
20
  }
98
21
  return Object.freeze({
99
22
  ...adapted,
100
23
  tools: Object.freeze(tools),
101
- state: core.state,
102
- digest: core.digest,
103
- locks: core.locks,
104
- clock: core.clock,
105
- invalidate: core.invalidate,
24
+ state: defs.state,
25
+ digest: defs.digest,
26
+ locks: defs.locks,
27
+ clock: defs.clock,
28
+ invalidate: defs.invalidate,
106
29
  });
107
30
  }
108
- function checkOptions(options) {
109
- if (options === null || typeof options !== "object" || Array.isArray(options)) {
110
- throw new TypeError("createAiSdkFsTools options must be an object");
111
- }
112
- for (const key of Object.keys(options)) {
113
- if (!KNOWN.has(key))
114
- throw new TypeError(`Unknown createAiSdkFsTools option: ${key}`);
115
- }
116
- const state = options.state;
117
- if (state !== undefined && state !== null && !isStore(state)) {
118
- throw new TypeError(`createAiSdkFsTools state must be a read state store or null: a bundle takes one store, not a per-call factory`);
119
- }
120
- for (const [tool, keys] of Object.entries(SHARED_KEYS)) {
121
- const part = options[tool];
122
- if (part === undefined || (tool === "bash" && part === false))
123
- continue;
124
- if (tool === "applyPatch" && typeof part === "boolean")
125
- continue;
126
- if (tool === "bash" && part === true) {
127
- throw new TypeError("createAiSdkFsTools bash must be an object with a runner and an env: the portable bundle has no default runner");
128
- }
129
- if (part === null || typeof part !== "object" || Array.isArray(part)) {
130
- throw new TypeError(`createAiSdkFsTools ${tool} options must be an object`);
131
- }
132
- for (const key of keys) {
133
- if (Object.hasOwn(part, key)) {
134
- throw new TypeError(`createAiSdkFsTools ${tool} options cannot set ${key}: set it once at the top level`);
135
- }
136
- }
137
- }
138
- }
139
- function isStore(value) {
140
- if (value === null || typeof value !== "object")
141
- return false;
142
- const store = value;
143
- return ["get", "put", "delete"].every((key) => typeof store[key] === "function");
144
- }
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
+ export type { AiSdkTool } from "./adapt.ts";
1
2
  export { createAiSdkBashTool } from "./bash-tool.ts";
2
- export type { AiSdkBashTool, CreateAiSdkBashToolOptions } from "./bash-tool.ts";
3
+ export type { AiSdkBashTool, AiSdkBashToolOptions } from "./bash-tool.ts";
3
4
  export { createAiSdkFsTools } from "./fs-tools.ts";
4
- export type { AiSdkFsTools, AiSdkFsToolsApplyPatchOptions, AiSdkFsToolsBashOptions, AiSdkFsToolsEditOptions, AiSdkFsToolsReadOptions, AiSdkFsToolsWithApplyPatch, AiSdkFsToolsWithBash, AiSdkFsToolsWriteOptions, CreateAiSdkFsToolsOptions, } from "./fs-tools.ts";
5
+ export type { AiSdkFsTools, AiSdkFsToolsApplyPatchOptions, AiSdkFsToolsBashOptions, AiSdkFsToolsEditOptions, AiSdkFsToolsOptions, AiSdkFsToolsReadOptions, AiSdkFsToolsWithApplyPatch, AiSdkFsToolsWithBash, AiSdkFsToolsWriteOptions, } from "./fs-tools.ts";
5
6
  export { createAiSdkApplyPatchTool, createAiSdkEditTool, createAiSdkWriteTool, } from "./mutation-tools.ts";
6
- export type { AiSdkMutationTool, CreateAiSdkApplyPatchToolOptions, CreateAiSdkEditToolOptions, CreateAiSdkWriteToolOptions, } from "./mutation-tools.ts";
7
+ export type { AiSdkApplyPatchToolOptions, AiSdkEditToolOptions, AiSdkMutationTool, AiSdkWriteToolOptions, } from "./mutation-tools.ts";
7
8
  export { toAiSdkOutput } from "./output.ts";
8
9
  export type { AiSdkContentPart, AiSdkToolOutput } from "./output.ts";
9
10
  export { createAiSdkReadTool } from "./tool.ts";
10
- export type { AiSdkReadTool, CreateAiSdkReadToolOptions } from "./tool.ts";
11
+ export type { AiSdkReadTool, AiSdkReadToolOptions } from "./tool.ts";
@@ -1,50 +1,32 @@
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;
1
+ import type { FlexibleSchema, ToolExecutionOptions } from "ai";
2
+ import type { MutationResult } from "@better-fs-tools/write";
3
+ import type { ApplyPatchToolDefinitionOptions, EditToolDefinitionOptions, WriteToolDefinitionOptions } from "@better-fs-tools/write/signature";
4
+ import type { AiSdkTool } from "./adapt.ts";
5
+ type Host<C> = ToolExecutionOptions<C>;
6
+ interface ContextSchemaOption<C> {
7
+ /** Checks the `toolsContext` entry of this tool. The AI SDK validates the context with it before `execute`. */
8
+ readonly contextSchema?: FlexibleSchema<C>;
33
9
  }
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>;
10
+ /** Options for createAiSdkEditTool: the options of editToolDefinition(), plus `contextSchema`. */
11
+ export type AiSdkEditToolOptions<C = unknown> = EditToolDefinitionOptions<Host<C>> & ContextSchemaOption<C>;
12
+ /** Options for createAiSdkWriteTool: the options of writeToolDefinition(), plus `contextSchema`. */
13
+ export type AiSdkWriteToolOptions<C = unknown> = WriteToolDefinitionOptions<Host<C>> & ContextSchemaOption<C>;
14
+ /**
15
+ * Options for createAiSdkApplyPatchTool: the options of
16
+ * applyPatchToolDefinition(), plus `contextSchema`. A grammar on the signature
17
+ * is ignored: AI SDK tools take JSON only.
18
+ */
19
+ export type AiSdkApplyPatchToolOptions<C = unknown> = ApplyPatchToolDefinitionOptions<Host<C>> & ContextSchemaOption<C>;
20
+ /** An AI SDK edit, write, or apply_patch tool, assignable to `Tool<JsonObject, MutationResult, C>` from ai 7.0.77. */
21
+ export type AiSdkMutationTool<C = unknown> = AiSdkTool<MutationResult, C>;
22
+ /** Creates an AI SDK edit tool with the options and defaults of createEditTool(). */
23
+ export declare function createAiSdkEditTool<C = unknown>(options: AiSdkEditToolOptions<C>): AiSdkMutationTool<C>;
24
+ /** Creates an AI SDK write tool with the options and defaults of createWriteTool(). */
25
+ export declare function createAiSdkWriteTool<C = unknown>(options: AiSdkWriteToolOptions<C>): AiSdkMutationTool<C>;
39
26
  /**
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
27
+ * Creates an AI SDK apply_patch tool with the options and defaults of
28
+ * createApplyPatchTool(). The model sends JSON even when the signature has a
42
29
  * grammar, because the AI SDK has no freeform tool input.
43
30
  */
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>;
31
+ export declare function createAiSdkApplyPatchTool<C = unknown>(options: AiSdkApplyPatchToolOptions<C>): AiSdkMutationTool<C>;
32
+ export {};
@@ -1,81 +1,24 @@
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. */
1
+ import { applyPatchToolDefinition, editToolDefinition, writeToolDefinition, } from "@better-fs-tools/write/signature";
2
+ import { adaptAiSdkTool, checkOptions } from "./adapt.js";
3
+ /** Creates an AI SDK edit tool with the options and defaults of createEditTool(). */
7
4
  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);
5
+ checkOptions(options, "AI SDK edit tool");
6
+ const { contextSchema, ...rest } = options;
7
+ return adaptAiSdkTool(editToolDefinition(rest), contextSchema);
16
8
  }
17
- /** Creates an AI SDK write tool. `options.messages` override the signature's messages. */
9
+ /** Creates an AI SDK write tool with the options and defaults of createWriteTool(). */
18
10
  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);
11
+ checkOptions(options, "AI SDK write tool");
12
+ const { contextSchema, ...rest } = options;
13
+ return adaptAiSdkTool(writeToolDefinition(rest), contextSchema);
26
14
  }
27
15
  /**
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
16
+ * Creates an AI SDK apply_patch tool with the options and defaults of
17
+ * createApplyPatchTool(). The model sends JSON even when the signature has a
30
18
  * grammar, because the AI SDK has no freeform tool input.
31
19
  */
32
20
  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
- });
21
+ checkOptions(options, "AI SDK apply_patch tool");
22
+ const { contextSchema, ...rest } = options;
23
+ return adaptAiSdkTool(applyPatchToolDefinition(rest), contextSchema);
81
24
  }
package/dist/tool.d.ts CHANGED
@@ -1,35 +1,19 @@
1
- import type { Schema, ToolExecutionOptions } from "ai";
2
- import type { Converter, 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";
1
+ import type { FlexibleSchema, ToolExecutionOptions } from "ai";
2
+ import type { ReadResult } from "@better-fs-tools/read";
3
+ import type { ReadToolDefinitionOptions } from "@better-fs-tools/read/signature";
4
+ import type { AiSdkTool } from "./adapt.ts";
5
5
  /**
6
- * Options for createAiSdkReadTool. A state store requires a digest.
7
- * converters defaults to [imageConverter()]. A list you pass replaces it:
8
- * [] turns images off.
6
+ * Options for createAiSdkReadTool: the options of readToolDefinition(), with
7
+ * the AI SDK execution options as host, plus `contextSchema`.
9
8
  */
10
- export type CreateAiSdkReadToolOptions<C = unknown> = ReadToolDeps<ToolExecutionOptions<C>> & StateNeedsDigest & {
11
- /** Defaults to defaultReadSignature(). */
12
- readonly signature?: ReadSignature;
9
+ export type AiSdkReadToolOptions<C = unknown> = ReadToolDefinitionOptions<ToolExecutionOptions<C>> & {
10
+ /** Checks the `toolsContext` entry of this tool. The AI SDK validates the context with it before `execute`. */
11
+ readonly contextSchema?: FlexibleSchema<C>;
13
12
  };
14
13
  /** An AI SDK read tool, assignable to `Tool<JsonObject, ReadResult, C>` from ai 7.0.77. */
15
- export interface AiSdkReadTool<C = unknown> {
16
- readonly name: string;
17
- readonly description: string;
18
- readonly strict: true;
19
- /** The strict input schema. A `null` for an optional parameter means absent. */
20
- readonly inputSchema: Schema<JsonObject>;
21
- /** Runs the read. The AI SDK execution options are the call's host. */
22
- execute(input: JsonObject, options: ToolExecutionOptions<C>): Promise<ReadResult>;
23
- toModelOutput(options: {
24
- output: ReadResult;
25
- }): AiSdkToolOutput;
26
- }
14
+ export type AiSdkReadTool<C = unknown> = AiSdkTool<ReadResult, C>;
27
15
  /**
28
- * Creates an AI SDK read tool. `options.messages` override the signature's
29
- * messages. An image becomes a file part unless `options.converters` leaves
30
- * imageConverter() out.
16
+ * Creates an AI SDK read tool. It takes every option of createReadTool() with
17
+ * the same defaults, plus `signature` and `contextSchema`.
31
18
  */
32
- export declare function createAiSdkReadTool<C = unknown>(options: CreateAiSdkReadToolOptions<C>): AiSdkReadTool<C>;
33
- /** The host's converters, or [imageConverter()] when it passes none. */
34
- export declare function aiSdkConverters<THost>(converters: readonly Converter<THost>[] | undefined): readonly Converter<THost>[];
35
- export declare function adaptReadTool<C>(signature: ReadSignature, read: ReadTool<ToolExecutionOptions<C>>, limitOverrides: Partial<ReadLimits> | undefined): AiSdkReadTool<C>;
19
+ export declare function createAiSdkReadTool<C = unknown>(options: AiSdkReadToolOptions<C>): AiSdkReadTool<C>;
package/dist/tool.js CHANGED
@@ -1,59 +1,11 @@
1
- import { jsonSchema } from "ai";
2
- import { createReadTool, imageConverter, 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";
1
+ import { readToolDefinition } from "@better-fs-tools/read/signature";
2
+ import { adaptAiSdkTool, checkOptions } from "./adapt.js";
6
3
  /**
7
- * Creates an AI SDK read tool. `options.messages` override the signature's
8
- * messages. An image becomes a file part unless `options.converters` leaves
9
- * imageConverter() out.
4
+ * Creates an AI SDK read tool. It takes every option of createReadTool() with
5
+ * the same defaults, plus `signature` and `contextSchema`.
10
6
  */
11
7
  export function createAiSdkReadTool(options) {
12
- if (options === null || typeof options !== "object" || Array.isArray(options)) {
13
- throw new TypeError("AI SDK read tool options must be an object");
14
- }
15
- const { signature = defaultReadSignature(), ...deps } = options;
16
- const read = createReadTool({
17
- ...deps,
18
- converters: aiSdkConverters(deps.converters),
19
- messages: { ...readSignatureMessages(signature), ...deps.messages },
20
- });
21
- return adaptReadTool(signature, read, deps.limits);
22
- }
23
- /** The host's converters, or [imageConverter()] when it passes none. */
24
- export function aiSdkConverters(converters) {
25
- return converters ?? [imageConverter()];
26
- }
27
- export function adaptReadTool(signature, read, limitOverrides) {
28
- const limits = resolveReadLimits(limitOverrides);
29
- const strict = toStrictSchema(signature.schema, signature.name);
30
- return Object.freeze({
31
- name: signature.name,
32
- description: signature.description,
33
- strict: true,
34
- inputSchema: jsonSchema(strict, {
35
- validate(model) {
36
- try {
37
- const value = fromStrictInput(signature.schema, model);
38
- parseReadInput(signature.toInput(value), limits);
39
- return { success: true, value: value };
40
- }
41
- catch (error) {
42
- return {
43
- success: false,
44
- error: error instanceof Error ? error : new Error(String(error)),
45
- };
46
- }
47
- },
48
- }),
49
- async execute(input, execution) {
50
- const call = {
51
- ...(execution.abortSignal === undefined ? {} : { signal: execution.abortSignal }),
52
- callId: execution.toolCallId,
53
- host: execution,
54
- };
55
- return read(signature.toInput(fromStrictInput(signature.schema, input)), call);
56
- },
57
- toModelOutput: ({ output }) => toAiSdkOutput(output),
58
- });
8
+ checkOptions(options, "AI SDK read tool");
9
+ const { contextSchema, ...rest } = options;
10
+ return adaptAiSdkTool(readToolDefinition(rest), contextSchema);
59
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-fs-tools/ai-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "The Better FS Tools read, edit, write, apply_patch, and bash tools for AI SDK 7.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,14 +29,14 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@better-fs-tools/read": "^0.2.0",
33
- "@better-fs-tools/shell": "^0.2.0",
34
- "@better-fs-tools/write": "^0.2.0"
32
+ "@better-fs-tools/read": "^0.3.0",
33
+ "@better-fs-tools/shell": "^0.3.0",
34
+ "@better-fs-tools/write": "^0.3.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@ai-sdk/openai": "4.0.78",
38
- "@better-fs-tools/fs": "^0.2.0",
39
- "@better-fs-tools/just-bash": "^0.2.0",
38
+ "@better-fs-tools/fs": "^0.3.0",
39
+ "@better-fs-tools/just-bash": "^0.3.0",
40
40
  "ai": "^7.0.77",
41
41
  "just-bash": "3.4.2"
42
42
  },