@orpc/ai-sdk 2.0.0-beta.49 → 2.0.0-beta.51

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
@@ -78,13 +78,14 @@ Read the full documentation at [orpc.dev](https://orpc.dev), starting with the [
78
78
 
79
79
  **Built-in features**
80
80
 
81
- | Package | Purpose | Docs |
82
- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
83
- | [@orpc/publisher](https://www.npmjs.com/package/@orpc/publisher) | Pub/Sub with memory, Redis, and Upstash adapters. | [Publisher](https://orpc.dev/docs/helpers/publisher) |
84
- | [@orpc/ratelimit](https://www.npmjs.com/package/@orpc/ratelimit) | Rate limiting with memory, Redis, and Upstash adapters. | [Rate Limit](https://orpc.dev/docs/helpers/ratelimit) |
85
- | [@orpc/experimental-lock](https://www.npmjs.com/package/@orpc/experimental-lock) | Locking with memory, Redis, and Upstash adapters. | [Lock](https://orpc.dev/docs/helpers/lock) |
86
- | [@orpc/hibernation](https://www.npmjs.com/package/@orpc/hibernation) | Leverage Hibernation APIs like [Cloudflare's Hibernation WebSocket](https://developers.cloudflare.com/durable-objects/best-practices/websockets/#durable-objects-hibernation-websocket-api). | [Hibernation](https://orpc.dev/docs/integrations/hibernation) |
87
- | [@orpc/json-schema](https://www.npmjs.com/package/@orpc/json-schema) | Smart coercion for OpenAPI requests. | [Smart Coercion](https://orpc.dev/docs/plugins/smart-coercion) |
81
+ | Package | Purpose | Docs |
82
+ | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
83
+ | [@orpc/publisher](https://www.npmjs.com/package/@orpc/publisher) | Pub/Sub with memory, Redis, and Upstash adapters. | [Publisher](https://orpc.dev/docs/helpers/publisher) |
84
+ | [@orpc/ratelimit](https://www.npmjs.com/package/@orpc/ratelimit) | Rate limiting with memory, Redis, and Upstash adapters. | [Rate Limit](https://orpc.dev/docs/helpers/ratelimit) |
85
+ | [@orpc/experimental-lock](https://www.npmjs.com/package/@orpc/experimental-lock) | Locking with memory, Redis, and Upstash adapters. | [Lock](https://orpc.dev/docs/helpers/lock) |
86
+ | [@orpc/experimental-openapi-inference](https://www.npmjs.com/package/@orpc/experimental-openapi-inference) | Generate OpenAPI specs from TypeScript types, no output schemas required. | [Type Inference](https://orpc.dev/docs/openapi/specification#type-inference) |
87
+ | [@orpc/hibernation](https://www.npmjs.com/package/@orpc/hibernation) | Leverage Hibernation APIs like [Cloudflare's Hibernation WebSocket](https://developers.cloudflare.com/durable-objects/best-practices/websockets/#durable-objects-hibernation-websocket-api). | [Hibernation](https://orpc.dev/docs/integrations/hibernation) |
88
+ | [@orpc/json-schema](https://www.npmjs.com/package/@orpc/json-schema) | Smart coercion for OpenAPI requests. | [Smart Coercion](https://orpc.dev/docs/plugins/smart-coercion) |
88
89
 
89
90
  **Framework & ecosystem integrations**
90
91
 
@@ -192,9 +193,10 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
192
193
  <td align="center"><a href="https://kellychan.im/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&amp;v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
193
194
  <td align="center"><a href="https://guyariely.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&amp;v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
194
195
  <td align="center"><a href="https://paulsenon.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&amp;v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
195
- <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
196
+ <td align="center"><a href="https://usagerail.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="UsageRail"><img src="https://avatars.githubusercontent.com/u/347653714?v=4" width="139" alt="UsageRail"/><br />UsageRail</a></td>
196
197
  </tr>
197
198
  <tr>
199
+ <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
198
200
  <td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&amp;v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
199
201
  </tr>
200
202
  </table>
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export * from './tool.ts';
2
- export * from './tool-meta.ts';
1
+ import { CreateToolFactoryOptions, ImplementToolFactoryOptions, ToolFactory, ToolImplementer, ToolOutput, createToolFactory, implementToolFactory } from "./tool.js";
2
+ import { AiSdkToolFunction, AiSdkToolMeta, AiSdkToolMetaPlugin, FunctionTool, aiSdkTool, getAiSdkToolMeta } from "./tool-meta.js";
3
+ export { AiSdkToolFunction, AiSdkToolMeta, AiSdkToolMetaPlugin, CreateToolFactoryOptions, FunctionTool, ImplementToolFactoryOptions, ToolFactory, ToolImplementer, ToolOutput, aiSdkTool, createToolFactory, getAiSdkToolMeta, implementToolFactory };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export * from './tool.js';
2
- export * from './tool-meta.js';
1
+ export { createToolFactory, implementToolFactory } from "./tool.js";
2
+ export { aiSdkTool, getAiSdkToolMeta } from "./tool-meta.js";
@@ -1,13 +1,13 @@
1
- import type { AnyProcedureContract, AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, MetaPlugin } from '@orpc/contract';
2
- import type { Lazy } from '@orpc/server';
3
- import type { JSONValue, Tool } from 'ai';
4
- import type { ToolOutput } from './tool.ts';
1
+ import { ToolOutput } from "./tool.js";
2
+ import { AnyProcedureContract, AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, MetaPlugin } from "@orpc/contract";
3
+ import { Lazy } from "@orpc/server";
4
+ import { JSONValue, Tool } from "ai";
5
5
  /**
6
6
  * The [function tool](https://ai-sdk.dev/docs/foundations/tools) member of the AI SDK `Tool` union,
7
7
  * which is the kind of tool this package produces.
8
8
  */
9
9
  export type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = Extract<Tool<INPUT, OUTPUT>, {
10
- type?: 'function' | undefined;
10
+ type?: "function" | undefined;
11
11
  }>;
12
12
  /**
13
13
  * Base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options attached to a procedure/contract,
@@ -18,12 +18,12 @@ export type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT
18
18
  *
19
19
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
20
20
  */
21
- export type AiSdkToolMeta<TInputSchema extends AnySchema = AnySchema, TOutputSchema extends AnySchema = AnySchema> = Partial<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema' | 'execute'>>;
21
+ export type AiSdkToolMeta<TInputSchema extends AnySchema = AnySchema, TOutputSchema extends AnySchema = AnySchema> = Partial<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, "inputSchema" | "outputSchema" | "execute">>;
22
22
  export interface AiSdkToolMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
23
- name: '~ai-sdk/tool';
23
+ name: "~ai-sdk/tool";
24
24
  }
25
25
  export interface AiSdkToolFunction {
26
- <TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(meta: AiSdkToolMeta<TInputSchema, TOutputSchema>): AiSdkToolMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
26
+ <TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(meta: AiSdkToolMeta<TInputSchema, TOutputSchema>): AiSdkToolMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
27
27
  }
28
28
  /**
29
29
  * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
@@ -51,4 +51,4 @@ export declare const aiSdkTool: AiSdkToolFunction;
51
51
  *
52
52
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
53
53
  */
54
- export declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): AiSdkToolMeta | undefined;
54
+ export declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): AiSdkToolMeta | undefined;
package/dist/tool-meta.js CHANGED
@@ -1,38 +1,43 @@
1
+ // src/tool-meta.ts
1
2
  /**
2
- * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
3
- * used as defaults when creating tools from it.
4
- *
5
- * @remarks
6
- * **Note**: When defined multiple times, options are overridden by the most recent call.
7
- *
8
- * @example
9
- * ```ts
10
- * const getWeatherContract = oc
11
- * .meta(aiSdkTool({
12
- * description: 'Get the weather in a location',
13
- * metadata: { source: 'weather-service' },
14
- * }))
15
- * .input(z.object({ location: z.string() }))
16
- * ```
17
- *
18
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
19
- */
20
- export const aiSdkTool = (incoming) => ({
21
- name: '~ai-sdk/tool',
22
- init(meta) {
23
- const existing = meta['~ai-sdk/tool'];
24
- return {
25
- ...meta,
26
- '~ai-sdk/tool': { ...existing, ...incoming },
27
- };
28
- },
3
+ * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
4
+ * used as defaults when creating tools from it.
5
+ *
6
+ * @remarks
7
+ * **Note**: When defined multiple times, options are overridden by the most recent call.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const getWeatherContract = oc
12
+ * .meta(aiSdkTool({
13
+ * description: 'Get the weather in a location',
14
+ * metadata: { source: 'weather-service' },
15
+ * }))
16
+ * .input(z.object({ location: z.string() }))
17
+ * ```
18
+ *
19
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
20
+ */
21
+ const aiSdkTool = (incoming) => ({
22
+ name: "~ai-sdk/tool",
23
+ init(meta) {
24
+ const existing = meta["~ai-sdk/tool"];
25
+ return {
26
+ ...meta,
27
+ "~ai-sdk/tool": {
28
+ ...existing,
29
+ ...incoming
30
+ }
31
+ };
32
+ }
29
33
  });
30
34
  /**
31
- * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
32
- * attached to a procedure/contract by {@link aiSdkTool}.
33
- *
34
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
35
- */
36
- export function getAiSdkToolMeta(procedureOrLazy) {
37
- return procedureOrLazy['~orpc'].meta['~ai-sdk/tool'];
35
+ * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
36
+ * attached to a procedure/contract by {@link aiSdkTool}.
37
+ *
38
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
39
+ */
40
+ function getAiSdkToolMeta(procedureOrLazy) {
41
+ return procedureOrLazy["~orpc"].meta["~ai-sdk/tool"];
38
42
  }
43
+ export { aiSdkTool, getAiSdkToolMeta };
package/dist/tool.d.ts CHANGED
@@ -1,11 +1,10 @@
1
- import type { ClientOptions } from '@orpc/client';
2
- import type { AnySchema, InferSchemaInput, InferSchemaOutput, ProcedureContract, Schema } from '@orpc/contract';
3
- import { OpenAPIJsonSerializer } from '@orpc/openapi';
4
- import type { Context, ProcedureClientOptions } from '@orpc/server';
5
- import { Procedure } from '@orpc/server';
6
- import type { MaybeOptionalOptions, Public } from '@orpc/shared';
7
- import type { Tool } from 'ai';
8
- import type { FunctionTool } from './tool-meta.ts';
1
+ import { FunctionTool } from "./tool-meta.js";
2
+ import { AnySchema, InferSchemaInput, InferSchemaOutput, ProcedureContract, Schema } from "@orpc/contract";
3
+ import { OpenAPIJsonSerializer } from "@orpc/openapi";
4
+ import { Context, Procedure, ProcedureClientOptions } from "@orpc/server";
5
+ import { MaybeOptionalOptions, Public } from "@orpc/shared";
6
+ import { Tool } from "ai";
7
+ import { ClientOptions } from "@orpc/client";
9
8
  /**
10
9
  * Infers the value an AI SDK tool outputs for a given oRPC output type.
11
10
  *
@@ -17,17 +16,17 @@ import type { FunctionTool } from './tool-meta.ts';
17
16
  */
18
17
  export type ToolOutput<T> = T extends AsyncIteratorObject<infer TYield, any, any> ? TYield : T;
19
18
  export interface ImplementToolFactoryOptions {
20
- /**
21
- * Serializes outputs for the default `toModelOutput`, converting types such as `Date`, `BigInt`, and `Set`
22
- * the same way OpenAPI responses do.
23
- *
24
- * @default new OpenAPIJsonSerializer()
25
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-outputs | AI SDK Integration - Tool Outputs}
26
- */
27
- serializer?: Public<OpenAPIJsonSerializer> | undefined;
19
+ /**
20
+ * Serializes outputs for the default `toModelOutput`, converting types such as `Date`, `BigInt`, and `Set`
21
+ * the same way OpenAPI responses do.
22
+ *
23
+ * @default new OpenAPIJsonSerializer()
24
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-outputs | AI SDK Integration - Tool Outputs}
25
+ */
26
+ serializer?: Public<OpenAPIJsonSerializer> | undefined;
28
27
  }
29
28
  export interface ToolImplementer {
30
- <TInputSchema extends AnySchema, TOutputSchema extends AnySchema>(contract: ProcedureContract<TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema'>>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
29
+ <TInputSchema extends AnySchema, TOutputSchema extends AnySchema>(contract: ProcedureContract<TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, "inputSchema" | "outputSchema">>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
31
30
  }
32
31
  /**
33
32
  * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
@@ -73,9 +72,9 @@ export interface ToolImplementer {
73
72
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
74
73
  */
75
74
  export declare function implementToolFactory(options?: ImplementToolFactoryOptions): ToolImplementer;
76
- export type CreateToolFactoryOptions<TInitialContext extends Context> = ImplementToolFactoryOptions & ProcedureClientOptions<TInitialContext, Schema<unknown>, object, object> & Omit<ClientOptions<object>, 'context' | 'signal'>;
75
+ export type CreateToolFactoryOptions<TInitialContext extends Context> = ImplementToolFactoryOptions & ProcedureClientOptions<TInitialContext, Schema<unknown>, object, object> & Omit<ClientOptions<object>, "context" | "signal">;
77
76
  export interface ToolFactory<TInitialContext extends Context> {
78
- <TInputSchema extends AnySchema, TOutputSchema extends AnySchema>(procedure: Procedure<TInitialContext, any, TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema' | 'execute'>>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
77
+ <TInputSchema extends AnySchema, TOutputSchema extends AnySchema>(procedure: Procedure<TInitialContext, any, TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, "inputSchema" | "outputSchema" | "execute">>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
79
78
  }
80
79
  /**
81
80
  * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
@@ -116,4 +115,4 @@ export interface ToolFactory<TInitialContext extends Context> {
116
115
  *
117
116
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
118
117
  */
119
- export declare function createToolFactory<TInitialContext extends Context = object>(...rest: MaybeOptionalOptions<CreateToolFactoryOptions<TInitialContext>>): ToolFactory<TInitialContext>;
118
+ export declare function createToolFactory<TInitialContext extends Context = object>(...rest: MaybeOptionalOptions<CreateToolFactoryOptions<TInitialContext>>): ToolFactory<TInitialContext>;
package/dist/tool.js CHANGED
@@ -1,244 +1,238 @@
1
- import { getAsyncIteratorObjectSchemasDetails } from '@orpc/contract';
2
- import { combineJsonSchemasWithComposition } from '@orpc/json-schema';
3
- import { OpenAPIJsonSerializer } from '@orpc/openapi';
4
- import { call, Procedure } from '@orpc/server';
5
- import { encodeBase64, isAsyncGeneratorFunction, loadBytes, mergeTwoLevels, ORPC_NAME, resolveMaybeOptionalOptions, stringifyJSON, toArray, } from '@orpc/shared';
6
- import { tool } from 'ai';
7
- import { getAiSdkToolMeta } from './tool-meta.js';
8
- const ANY_SCHEMA = {
9
- '~standard': {
10
- vendor: ORPC_NAME,
11
- version: 1,
12
- validate: (value) => ({ value }),
13
- jsonSchema: {
14
- input: () => ({}),
15
- output: () => ({}),
16
- },
17
- },
18
- };
1
+ import { getAiSdkToolMeta } from "./tool-meta.js";
2
+ import { getAsyncIteratorObjectSchemasDetails } from "@orpc/contract";
3
+ import { combineJsonSchemasWithComposition } from "@orpc/json-schema";
4
+ import { OpenAPIJsonSerializer } from "@orpc/openapi";
5
+ import { Procedure, call } from "@orpc/server";
6
+ import { ORPC_NAME, encodeBase64, isAsyncGeneratorFunction, loadBytes, mergeTwoLevels, resolveMaybeOptionalOptions, stringifyJSON, toArray } from "@orpc/shared";
7
+ import { tool } from "ai";
8
+ // src/tool.ts
9
+ const ANY_SCHEMA = { "~standard": {
10
+ vendor: ORPC_NAME,
11
+ version: 1,
12
+ validate: (value) => ({ value }),
13
+ jsonSchema: {
14
+ input: () => ({}),
15
+ output: () => ({})
16
+ }
17
+ } };
19
18
  function combineJsonSchemas(jsonSchemas) {
20
- let $schema;
21
- const branches = jsonSchemas.map((jsonSchema) => {
22
- if ('$schema' in jsonSchema) {
23
- const { $schema: branch$schema, ...rest } = jsonSchema;
24
- $schema ??= branch$schema;
25
- return rest;
26
- }
27
- return jsonSchema;
28
- });
29
- const combined = combineJsonSchemasWithComposition('allOf', branches);
30
- return { $schema, ...combined };
19
+ let $schema;
20
+ const branches = jsonSchemas.map((jsonSchema) => {
21
+ if ("$schema" in jsonSchema) {
22
+ const { $schema: branch$schema, ...rest } = jsonSchema;
23
+ $schema ??= branch$schema;
24
+ return rest;
25
+ }
26
+ return jsonSchema;
27
+ });
28
+ const combined = combineJsonSchemasWithComposition("allOf", branches);
29
+ return {
30
+ $schema,
31
+ ...combined
32
+ };
31
33
  }
32
34
  function combineSchemas(schemas, merge) {
33
- if (schemas.length === 0) {
34
- return undefined;
35
- }
36
- if (schemas.length === 1) {
37
- return schemas[0];
38
- }
39
- const standardJsonSchemas = schemas.filter((schema) => schema['~standard'].jsonSchema);
40
- const jsonSchema = standardJsonSchemas.length
41
- ? {
42
- input: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema['~standard'].jsonSchema.input(options))),
43
- output: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema['~standard'].jsonSchema.output(options))),
44
- }
45
- : undefined;
46
- return {
47
- '~standard': {
48
- vendor: ORPC_NAME,
49
- version: 1,
50
- async validate(value) {
51
- let current = value;
52
- // Mirrors the server's stacked input validation, output schemas stay piped.
53
- for (const [index, schema] of schemas.entries()) {
54
- const merging = merge && index !== 0;
55
- const result = await schema['~standard'].validate(merging ? mergeTwoLevels(value, current) : current);
56
- if (result.issues) {
57
- return result;
58
- }
59
- current = merging ? mergeTwoLevels(current, result.value) : result.value;
60
- }
61
- return { value: current };
62
- },
63
- jsonSchema,
64
- },
65
- };
35
+ if (schemas.length === 0) return;
36
+ if (schemas.length === 1) return schemas[0];
37
+ const standardJsonSchemas = schemas.filter((schema) => schema["~standard"].jsonSchema);
38
+ const jsonSchema = standardJsonSchemas.length ? {
39
+ input: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema["~standard"].jsonSchema.input(options))),
40
+ output: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema["~standard"].jsonSchema.output(options)))
41
+ } : void 0;
42
+ return { "~standard": {
43
+ vendor: ORPC_NAME,
44
+ version: 1,
45
+ async validate(value) {
46
+ let current = value;
47
+ for (const [index, schema] of schemas.entries()) {
48
+ const merging = merge && index !== 0;
49
+ const result = await schema["~standard"].validate(merging ? mergeTwoLevels(value, current) : current);
50
+ if (result.issues) return result;
51
+ current = merging ? mergeTwoLevels(current, result.value) : result.value;
52
+ }
53
+ return { value: current };
54
+ },
55
+ jsonSchema
56
+ } };
66
57
  }
67
58
  function combineOutputSchemas(outputSchemas) {
68
- const yieldSchemas = getAsyncIteratorObjectSchemasDetails(outputSchemas)?.yieldSchemas;
69
- // oxlint-disable-next-line unicorn/no-array-reverse
70
- return combineSchemas([...(yieldSchemas ?? outputSchemas)].reverse(), false);
59
+ const yieldSchemas = getAsyncIteratorObjectSchemasDetails(outputSchemas)?.yieldSchemas;
60
+ return combineSchemas([...yieldSchemas ?? outputSchemas].reverse(), false);
71
61
  }
72
62
  /**
73
- * Serializes an output like an OpenAPI response body. JSON shows a `Blob` as an empty object,
74
- * so blobs, nested or not, are sent as file parts named by their path, such as `report/q3.pdf`.
75
- */
63
+ * Serializes an output like an OpenAPI response body. JSON shows a `Blob` as an empty object,
64
+ * so blobs, nested or not, are sent as file parts named by their path, such as `report/q3.pdf`.
65
+ */
76
66
  async function toModelOutput(serializer, output) {
77
- const { json, maps, blobs } = serializer.serializeJson(output);
78
- if (typeof json === 'string') {
79
- return { type: 'text', value: json };
80
- }
81
- if (!blobs?.length) {
82
- return { type: 'json', value: (json ?? null) };
83
- }
84
- const files = await Promise.all(blobs.map(async (blob, i) => {
85
- const path = maps[i];
86
- const names = blob instanceof File && blob.name !== '' ? [...path, blob.name] : path;
87
- return {
88
- type: 'file',
89
- mediaType: blob.type || 'application/octet-stream',
90
- // base64 is encoded once, providers would otherwise re-encode the bytes on every step
91
- data: { type: 'data', data: encodeBase64(await loadBytes(blob)) },
92
- ...(names.length === 0 ? {} : { filename: names.join('/') }),
93
- };
94
- }));
95
- return {
96
- type: 'content',
97
- value: json instanceof Blob ? files : [{ type: 'text', text: stringifyJSON(json) }, ...files],
98
- };
67
+ const { json, maps, blobs } = serializer.serializeJson(output);
68
+ if (typeof json === "string") return {
69
+ type: "text",
70
+ value: json
71
+ };
72
+ if (!blobs?.length) return {
73
+ type: "json",
74
+ value: json ?? null
75
+ };
76
+ const files = await Promise.all(blobs.map(async (blob, i) => {
77
+ const path = maps[i];
78
+ const names = blob instanceof File && blob.name !== "" ? [...path, blob.name] : path;
79
+ return {
80
+ type: "file",
81
+ mediaType: blob.type || "application/octet-stream",
82
+ data: {
83
+ type: "data",
84
+ data: encodeBase64(await loadBytes(blob))
85
+ },
86
+ ...names.length === 0 ? {} : { filename: names.join("/") }
87
+ };
88
+ }));
89
+ return {
90
+ type: "content",
91
+ value: json instanceof Blob ? files : [{
92
+ type: "text",
93
+ text: stringifyJSON(json)
94
+ }, ...files]
95
+ };
99
96
  }
100
97
  /**
101
- * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
102
- * as [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing contract definitions.
103
- *
104
- * The factory accepts oRPC related options, and the resulting builder
105
- * accepts a contract alongside AI SDK tool options.
106
- *
107
- * @remarks
108
- * **Note**: [Procedures](https://orpc.dev/docs/procedure) are also compatible with [procedure contracts](https://orpc.dev/docs/contract/procedure).
109
- *
110
- * @example
111
- * ```ts
112
- * import { aiSdkTool, implementToolFactory } from '@orpc/ai-sdk'
113
- * import { oc } from '@orpc/contract'
114
- *
115
- * const getWeatherContract = oc
116
- * .meta(
117
- * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
118
- * )
119
- * .input(
120
- * z.object({
121
- * location: z.string().describe('The location to get the weather for'),
122
- * }),
123
- * )
124
- * .output(
125
- * z.object({
126
- * location: z.string().describe('The location the weather is for'),
127
- * temperature: z.number().describe('The temperature in Celsius'),
128
- * }),
129
- * )
130
- *
131
- * const implementTool = implementToolFactory()
132
- *
133
- * const getWeatherTool = implementTool(getWeatherContract, {
134
- * execute: async ({ location }) => ({
135
- * location,
136
- * temperature: 72 + Math.floor(Math.random() * 21) - 10,
137
- * }),
138
- * })
139
- * ```
140
- *
141
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
142
- */
143
- export function implementToolFactory(options = {}) {
144
- const serializer = options.serializer ?? new OpenAPIJsonSerializer();
145
- const defaultToModelOutput = ({ output }) => toModelOutput(serializer, output);
146
- const factory = (contract, ...rest) => {
147
- const toolOptions = resolveMaybeOptionalOptions(rest);
148
- const inputSchemas = toArray(contract['~orpc'].inputSchemas);
149
- const outputSchemas = toArray(contract['~orpc'].outputSchemas);
150
- const defaults = getAiSdkToolMeta(contract);
151
- return tool({
152
- ...defaults,
153
- ...toolOptions,
154
- toModelOutput: toolOptions.toModelOutput ?? defaults?.toModelOutput ?? defaultToModelOutput,
155
- inputSchema: combineSchemas(inputSchemas, true) ?? ANY_SCHEMA,
156
- outputSchema: combineOutputSchemas(outputSchemas),
157
- });
158
- };
159
- return factory;
98
+ * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
99
+ * as [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing contract definitions.
100
+ *
101
+ * The factory accepts oRPC related options, and the resulting builder
102
+ * accepts a contract alongside AI SDK tool options.
103
+ *
104
+ * @remarks
105
+ * **Note**: [Procedures](https://orpc.dev/docs/procedure) are also compatible with [procedure contracts](https://orpc.dev/docs/contract/procedure).
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * import { aiSdkTool, implementToolFactory } from '@orpc/ai-sdk'
110
+ * import { oc } from '@orpc/contract'
111
+ *
112
+ * const getWeatherContract = oc
113
+ * .meta(
114
+ * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
115
+ * )
116
+ * .input(
117
+ * z.object({
118
+ * location: z.string().describe('The location to get the weather for'),
119
+ * }),
120
+ * )
121
+ * .output(
122
+ * z.object({
123
+ * location: z.string().describe('The location the weather is for'),
124
+ * temperature: z.number().describe('The temperature in Celsius'),
125
+ * }),
126
+ * )
127
+ *
128
+ * const implementTool = implementToolFactory()
129
+ *
130
+ * const getWeatherTool = implementTool(getWeatherContract, {
131
+ * execute: async ({ location }) => ({
132
+ * location,
133
+ * temperature: 72 + Math.floor(Math.random() * 21) - 10,
134
+ * }),
135
+ * })
136
+ * ```
137
+ *
138
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
139
+ */
140
+ function implementToolFactory(options = {}) {
141
+ const serializer = options.serializer ?? new OpenAPIJsonSerializer();
142
+ const defaultToModelOutput = ({ output }) => toModelOutput(serializer, output);
143
+ const factory = (contract, ...rest) => {
144
+ const toolOptions = resolveMaybeOptionalOptions(rest);
145
+ const inputSchemas = toArray(contract["~orpc"].inputSchemas);
146
+ const outputSchemas = toArray(contract["~orpc"].outputSchemas);
147
+ const defaults = getAiSdkToolMeta(contract);
148
+ return tool({
149
+ ...defaults,
150
+ ...toolOptions,
151
+ toModelOutput: toolOptions.toModelOutput ?? defaults?.toModelOutput ?? defaultToModelOutput,
152
+ inputSchema: combineSchemas(inputSchemas, true) ?? ANY_SCHEMA,
153
+ outputSchema: combineOutputSchemas(outputSchemas)
154
+ });
155
+ };
156
+ return factory;
160
157
  }
161
158
  /**
162
- * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
163
- * into [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing procedure definitions.
164
- *
165
- * The factory accepts oRPC related options, and the resulting builder
166
- * accepts a procedure alongside AI SDK tool options.
167
- *
168
- * @example
169
- * ```ts
170
- * import { aiSdkTool, createToolFactory } from '@orpc/ai-sdk'
171
- * import { os } from '@orpc/server'
172
- *
173
- * const getWeatherProcedure = os
174
- * .meta(
175
- * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
176
- * )
177
- * .input(z.object({
178
- * location: z.string().describe('The location to get the weather for'),
179
- * }))
180
- * .output(z.object({
181
- * location: z.string().describe('The location the weather is for'),
182
- * temperature: z.number().describe('The temperature in Celsius'),
183
- * }))
184
- * .handler(async ({ input }) => ({
185
- * location: input.location,
186
- * temperature: 72 + Math.floor(Math.random() * 21) - 10,
187
- * }))
188
- *
189
- * const createTool = createToolFactory({
190
- * context: {}, // provide initial context if needed
191
- * })
192
- *
193
- * const getWeatherTool = createTool(getWeatherProcedure, {
194
- * // ...AI SDK tool options/overrides here if needed
195
- * })
196
- * ```
197
- *
198
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
199
- */
200
- export function createToolFactory(...rest) {
201
- const options = resolveMaybeOptionalOptions(rest);
202
- const implementTool = implementToolFactory(options);
203
- const factory = (procedure, ...rest) => {
204
- const toolOptions = resolveMaybeOptionalOptions(rest);
205
- /**
206
- * The AI SDK already validates input against the tool's `inputSchema`,
207
- * so input validation is disabled at the oRPC level to avoid validating twice.
208
- * Output validation stays enabled because the AI SDK does not validate
209
- * the value returned from `execute` against the tool's `outputSchema`.
210
- */
211
- const disabledValidation = new Procedure({
212
- ...procedure['~orpc'],
213
- disableInputValidation: true,
214
- });
215
- /**
216
- * Output schemas are the source of truth, but an `async function*` handler always
217
- * returns an async iterator, so it streams even without an `asyncIteratorObject` schema.
218
- */
219
- const isIteratorOutput = getAsyncIteratorObjectSchemasDetails(procedure['~orpc'].outputSchemas) !== undefined ||
220
- isAsyncGeneratorFunction(procedure['~orpc'].handler);
221
- return implementTool(procedure, {
222
- ...toolOptions,
223
- /**
224
- * For async iterator outputs, the tool streams each event as a
225
- * [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results),
226
- * and the last event becomes the final result.
227
- */
228
- execute: isIteratorOutput
229
- ? async function* (input, callingOptions) {
230
- yield* (await call(disabledValidation, input, {
231
- ...options,
232
- signal: callingOptions.abortSignal,
233
- }));
234
- }
235
- : (input, callingOptions) => {
236
- return call(disabledValidation, input, {
237
- ...options,
238
- signal: callingOptions.abortSignal,
239
- });
240
- },
241
- });
242
- };
243
- return factory;
159
+ * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
160
+ * into [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing procedure definitions.
161
+ *
162
+ * The factory accepts oRPC related options, and the resulting builder
163
+ * accepts a procedure alongside AI SDK tool options.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { aiSdkTool, createToolFactory } from '@orpc/ai-sdk'
168
+ * import { os } from '@orpc/server'
169
+ *
170
+ * const getWeatherProcedure = os
171
+ * .meta(
172
+ * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
173
+ * )
174
+ * .input(z.object({
175
+ * location: z.string().describe('The location to get the weather for'),
176
+ * }))
177
+ * .output(z.object({
178
+ * location: z.string().describe('The location the weather is for'),
179
+ * temperature: z.number().describe('The temperature in Celsius'),
180
+ * }))
181
+ * .handler(async ({ input }) => ({
182
+ * location: input.location,
183
+ * temperature: 72 + Math.floor(Math.random() * 21) - 10,
184
+ * }))
185
+ *
186
+ * const createTool = createToolFactory({
187
+ * context: {}, // provide initial context if needed
188
+ * })
189
+ *
190
+ * const getWeatherTool = createTool(getWeatherProcedure, {
191
+ * // ...AI SDK tool options/overrides here if needed
192
+ * })
193
+ * ```
194
+ *
195
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
196
+ */
197
+ function createToolFactory(...rest) {
198
+ const options = resolveMaybeOptionalOptions(rest);
199
+ const implementTool = implementToolFactory(options);
200
+ const factory = (procedure, ...rest) => {
201
+ const toolOptions = resolveMaybeOptionalOptions(rest);
202
+ /**
203
+ * The AI SDK validates input itself, and treats outputs as the output schema's
204
+ * input side (e.g. in `validateUIMessages`), so oRPC validates neither.
205
+ */
206
+ const disabledValidation = new Procedure({
207
+ ...procedure["~orpc"],
208
+ disableInputValidation: true,
209
+ disableOutputValidation: true
210
+ });
211
+ /**
212
+ * Output schemas are the source of truth, but an `async function*` handler always
213
+ * returns an async iterator, so it streams even without an `asyncIteratorObject` schema.
214
+ */
215
+ const isIteratorOutput = getAsyncIteratorObjectSchemasDetails(procedure["~orpc"].outputSchemas) !== void 0 || isAsyncGeneratorFunction(procedure["~orpc"].handler);
216
+ return implementTool(procedure, {
217
+ ...toolOptions,
218
+ /**
219
+ * For async iterator outputs, the tool streams each event as a
220
+ * [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results),
221
+ * and the last event becomes the final result.
222
+ */
223
+ execute: isIteratorOutput ? async function* (input, callingOptions) {
224
+ yield* await call(disabledValidation, input, {
225
+ ...options,
226
+ signal: callingOptions.abortSignal
227
+ });
228
+ } : (input, callingOptions) => {
229
+ return call(disabledValidation, input, {
230
+ ...options,
231
+ signal: callingOptions.abortSignal
232
+ });
233
+ }
234
+ });
235
+ };
236
+ return factory;
244
237
  }
238
+ export { createToolFactory, implementToolFactory };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orpc/ai-sdk",
3
- "version": "2.0.0-beta.49",
3
+ "version": "2.0.0-beta.51",
4
4
  "description": "AI SDK integration for oRPC: turn contracts and procedures into typesafe AI SDK tools",
5
5
  "keywords": [
6
6
  "agents",
@@ -37,12 +37,12 @@
37
37
  }
38
38
  },
39
39
  "dependencies": {
40
- "@orpc/client": "2.0.0-beta.49",
41
- "@orpc/contract": "2.0.0-beta.49",
42
- "@orpc/json-schema": "2.0.0-beta.49",
43
- "@orpc/openapi": "2.0.0-beta.49",
44
- "@orpc/server": "2.0.0-beta.49",
45
- "@orpc/shared": "2.0.0-beta.49"
40
+ "@orpc/client": "2.0.0-beta.51",
41
+ "@orpc/contract": "2.0.0-beta.51",
42
+ "@orpc/json-schema": "2.0.0-beta.51",
43
+ "@orpc/openapi": "2.0.0-beta.51",
44
+ "@orpc/server": "2.0.0-beta.51",
45
+ "@orpc/shared": "2.0.0-beta.51"
46
46
  },
47
47
  "devDependencies": {
48
48
  "ai": "^7.0.162",