@providerkit/core 0.33.0 → 0.34.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.
Files changed (70) hide show
  1. package/README.md +64 -4
  2. package/dist/fallback.d.ts +5 -2
  3. package/dist/fallback.d.ts.map +1 -1
  4. package/dist/fallback.js +8 -4
  5. package/dist/fallback.js.map +1 -1
  6. package/dist/image.d.ts +16 -1
  7. package/dist/image.d.ts.map +1 -1
  8. package/dist/image.js +16 -4
  9. package/dist/image.js.map +1 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/presets.d.ts +5 -3
  15. package/dist/presets.d.ts.map +1 -1
  16. package/dist/presets.js +22 -3
  17. package/dist/presets.js.map +1 -1
  18. package/dist/providers/anthropic.d.ts +2 -0
  19. package/dist/providers/anthropic.d.ts.map +1 -1
  20. package/dist/providers/anthropic.js +2 -2
  21. package/dist/providers/anthropic.js.map +1 -1
  22. package/dist/providers/factory.d.ts +10 -0
  23. package/dist/providers/factory.d.ts.map +1 -1
  24. package/dist/providers/factory.js.map +1 -1
  25. package/dist/providers/gemini.d.ts +2 -0
  26. package/dist/providers/gemini.d.ts.map +1 -1
  27. package/dist/providers/gemini.js +2 -2
  28. package/dist/providers/gemini.js.map +1 -1
  29. package/dist/providers/openai.d.ts +2 -0
  30. package/dist/providers/openai.d.ts.map +1 -1
  31. package/dist/providers/openai.js +2 -2
  32. package/dist/providers/openai.js.map +1 -1
  33. package/dist/providers/responses.d.ts +2 -0
  34. package/dist/providers/responses.d.ts.map +1 -1
  35. package/dist/providers/responses.js +47 -8
  36. package/dist/providers/responses.js.map +1 -1
  37. package/dist/tool-args.d.ts.map +1 -1
  38. package/dist/tool-args.js +6 -8
  39. package/dist/tool-args.js.map +1 -1
  40. package/dist/tool-markup.d.ts +38 -0
  41. package/dist/tool-markup.d.ts.map +1 -0
  42. package/dist/tool-markup.js +177 -0
  43. package/dist/tool-markup.js.map +1 -0
  44. package/dist/tools.d.ts +10 -2
  45. package/dist/tools.d.ts.map +1 -1
  46. package/dist/tools.js +15 -1
  47. package/dist/tools.js.map +1 -1
  48. package/dist/transport.d.ts +22 -0
  49. package/dist/transport.d.ts.map +1 -1
  50. package/dist/transport.js +65 -1
  51. package/dist/transport.js.map +1 -1
  52. package/dist/zod.d.ts +18 -2
  53. package/dist/zod.d.ts.map +1 -1
  54. package/dist/zod.js +150 -14
  55. package/dist/zod.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/fallback.ts +16 -4
  58. package/src/image.ts +35 -4
  59. package/src/index.ts +1 -0
  60. package/src/presets.ts +22 -3
  61. package/src/providers/anthropic.ts +8 -2
  62. package/src/providers/factory.ts +10 -0
  63. package/src/providers/gemini.ts +8 -2
  64. package/src/providers/openai.ts +8 -2
  65. package/src/providers/responses.ts +55 -8
  66. package/src/tool-args.ts +6 -7
  67. package/src/tool-markup.ts +205 -0
  68. package/src/tools.ts +26 -3
  69. package/src/transport.ts +86 -1
  70. package/src/zod.ts +181 -17
package/src/zod.ts CHANGED
@@ -6,8 +6,20 @@
6
6
  import { z } from "zod";
7
7
  import { defineTool, type Tool, type ToolContext } from "./tools.ts";
8
8
  import { clampToSchema } from "./schema.ts";
9
+ import { messageOf } from "./errors.ts";
9
10
  import type { JsonObjectSchema } from "./types.ts";
10
11
 
12
+ type Issues = readonly z.core.$ZodIssue[];
13
+
14
+ /** zod's JSON Schema without the dialect URI it puts at the root. */
15
+ function jsonSchemaOf(
16
+ schema: z.ZodType,
17
+ params: z.core.ToJSONSchemaParams,
18
+ ): Record<string, unknown> {
19
+ const { $schema: _dialect, ...json } = z.toJSONSchema(schema, params) as Record<string, unknown>;
20
+ return json;
21
+ }
22
+
11
23
  /**
12
24
  * A zod schema as the JSON Schema every provider's tool contract wants.
13
25
  *
@@ -17,10 +29,7 @@ import type { JsonObjectSchema } from "./types.ts";
17
29
  * tool over that one key, with a message that names neither zod nor the field.
18
30
  */
19
31
  export function toJsonObjectSchema(schema: z.ZodType, label = "schema"): JsonObjectSchema {
20
- const { $schema: _dialect, ...json } = z.toJSONSchema(schema, { io: "input" }) as Record<
21
- string,
22
- unknown
23
- >;
32
+ const json = jsonSchemaOf(schema, { io: "input" });
24
33
  if (json.type !== "object") {
25
34
  // Every provider requires an object at the top level of a tool's
26
35
  // parameters; a bare string or array is rejected at the wire, far from
@@ -30,11 +39,20 @@ export function toJsonObjectSchema(schema: z.ZodType, label = "schema"): JsonObj
30
39
  return json as JsonObjectSchema;
31
40
  }
32
41
 
33
- export interface ZodToolSpec<I, O> {
42
+ /** `R` is what `run` returns. It is `O` unless `output` parses it into something else. */
43
+ export interface ZodToolSpec<I, O, R = O> {
34
44
  name: string;
35
45
  description: string;
36
46
  input: z.ZodType<I>;
37
- run: (input: I, ctx: ToolContext) => Promise<O>;
47
+ /**
48
+ * Checks every result before the model or your code reads it, and fills `outputSchema` for
49
+ * generated result types. `run` returns what the schema takes, `unknown` included, and the
50
+ * tool returns what the schema parses that into, after any transform. A result that fails is
51
+ * a `failed` outcome the model reads, and its value is dropped. A result that passes is the
52
+ * parsed value, so unknown keys are dropped and defaults are filled in before the model sees it.
53
+ */
54
+ output?: z.ZodType<O, R>;
55
+ run: (input: I, ctx: ToolContext) => Promise<R>;
38
56
  summarize?: (output: O) => string;
39
57
  timeoutMs?: number;
40
58
  isReadOnly?: boolean;
@@ -51,34 +69,180 @@ export interface ZodToolSpec<I, O> {
51
69
  clampOverflow?: boolean;
52
70
  }
53
71
 
72
+ /** How many problems the model reads back: a 1,000-row sheet can fail on every cell. */
73
+ const MAX_ISSUES = 5;
74
+
75
+ /**
76
+ * Where each problem is and what to change, in zod's words. The message names the fix
77
+ * ("expected array, received string"); the bare code sent a model back to resend the same
78
+ * call. The rest are counted, so a model that fixes five does not take them for all of it.
79
+ * `root` names a problem with the whole value: the model's arguments, or the tool's result.
80
+ */
81
+ function describeIssues(issues: Issues, root: "input" | "result"): string {
82
+ const lines = issues
83
+ .slice(0, MAX_ISSUES)
84
+ .map((issue) => `${issue.path.map(String).join(".") || root}: ${issue.message}`);
85
+ if (issues.length > MAX_ISSUES) lines.push(`and ${issues.length - MAX_ISSUES} more`);
86
+ return lines.join("; ");
87
+ }
88
+
89
+ function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
90
+ return typeof value === "object" && value !== null;
91
+ }
92
+
93
+ /** Whether each zod type a JSON string can stand in for is a JSON list (true) or object (false). */
94
+ const JSON_CONTAINERS = new Map([
95
+ ["array", true],
96
+ ["tuple", true],
97
+ ["object", false],
98
+ ["record", false],
99
+ ]);
100
+
101
+ /**
102
+ * `text` decoded, only when it is the JSON container the schema `expected`. Anything else fails
103
+ * the second parse too, and that parse's error would tell the model about a value it never
104
+ * sent: `"[3]"` for a number would come back as "received array". `"42"`, `"null"` and prose
105
+ * stay strings.
106
+ */
107
+ function jsonContainer(text: string, expected: string): object | undefined {
108
+ const isList = JSON_CONTAINERS.get(expected);
109
+ if (isList === undefined) return undefined;
110
+ try {
111
+ const value: unknown = JSON.parse(text);
112
+ const fits = typeof value === "object" && value !== null && Array.isArray(value) === isList;
113
+ return fits ? value : undefined;
114
+ } catch {
115
+ return undefined;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * The fix for a value the schema rejected for its type, or undefined when there is none.
121
+ * Both slips cost production runs:
122
+ *
123
+ * - An array or object sent as a JSON string, `{"sheets":"[{...}]"}`. 13 of 16 spreadsheet
124
+ * calls in one day failed this way, each resent unchanged.
125
+ * - A string sent as `{ text }`, copying a sibling field whose items are objects. A research
126
+ * run lost its brief this way on its last step. Only an object holding exactly one string
127
+ * `text`: an extra key or a non-string `text` stays the model's error to fix.
128
+ */
129
+ function slipFix(value: unknown, expected: string): unknown {
130
+ if (typeof value === "string") return jsonContainer(value, expected);
131
+ const wrapped =
132
+ expected === "string" &&
133
+ isRecord(value) &&
134
+ Object.keys(value).length === 1 &&
135
+ typeof value.text === "string";
136
+ return wrapped ? value.text : undefined;
137
+ }
138
+
139
+ /**
140
+ * `raw` with each slip fixed, only where zod rejected a value for its type: a string the
141
+ * schema took is never decoded, however much it looks like JSON. Returns `raw` itself when
142
+ * nothing applies, and never changes the caller's arguments.
143
+ */
144
+ function repairSlips(raw: unknown, issues: Issues): unknown {
145
+ const copy = structuredClone(raw);
146
+ let changed = false;
147
+ for (const issue of issues) {
148
+ if (issue.code !== "invalid_type") continue;
149
+ const key = issue.path.at(-1);
150
+ let parent: unknown = copy;
151
+ for (const step of issue.path.slice(0, -1)) parent = isRecord(parent) ? parent[step] : null;
152
+ if (key === undefined || !isRecord(parent)) continue;
153
+ const fixed = slipFix(parent[key], issue.expected);
154
+ if (fixed === undefined) continue;
155
+ parent[key] = fixed;
156
+ changed = true;
157
+ }
158
+ return changed ? copy : raw;
159
+ }
160
+
161
+ /**
162
+ * `spec.run` with each result checked against `output` before the model or your code reads it.
163
+ * The result is read as unknown: `output` decides its type, whatever `run` declared.
164
+ */
165
+ function checkedRun<I, O>(
166
+ spec: ZodToolSpec<I, O, unknown>,
167
+ output: z.ZodType<O>,
168
+ ): (input: I, ctx: ToolContext) => Promise<O> {
169
+ return async (input, ctx) => {
170
+ const result = await spec.run(input, ctx);
171
+ let problems: string;
172
+ try {
173
+ // Async, because the sync parse throws on an async refine or transform.
174
+ const parsed = await output.safeParseAsync(result);
175
+ if (parsed.success) return parsed.data;
176
+ problems = describeIssues(parsed.error.issues, "result");
177
+ } catch (err) {
178
+ // zod does not catch a refine or transform that throws (`new URL` on a bad link). The
179
+ // call ran all the same, and that is what the model must read.
180
+ problems = messageOf(err);
181
+ }
182
+ // The call ran, so a write may already have happened. The model decides whether to
183
+ // call again from this, as it does from `repairHistory`'s interrupted-call note.
184
+ const effect = spec.isReadOnly ? "" : " Check its effect before calling it again.";
185
+ throw new Error(
186
+ `${spec.name} ran, but its result does not match its output schema.${effect} Problems: ${problems}`,
187
+ );
188
+ };
189
+ }
190
+
191
+ /**
192
+ * A zod tool that checks its results too. It returns what `output` makes of `run`'s result, so
193
+ * `run` can return `unknown`, or the string a transform turns into a `Date`.
194
+ */
195
+ export function zodTool<I, O, R>(
196
+ spec: ZodToolSpec<I, O, R> & { output: z.ZodType<O, R> },
197
+ ): Tool<I, O>;
54
198
  /**
55
199
  * A tool whose arguments are validated by zod, with the failure reported to
56
200
  * the model in words it can act on. `topic: expected string, received number`
57
201
  * beats a stack trace it cannot read.
58
202
  */
203
+ export function zodTool<I, O>(spec: ZodToolSpec<I, O>): Tool<I, O>;
204
+ // Two signatures, so only a tool with `output` can return a type `run` does not. `output` comes
205
+ // first: the second signature takes an optional one too, for a wrapper that passes it through,
206
+ // and would type a `run` that returns `unknown` as a tool that returns `unknown`. The body is
207
+ // typed as the second. With `output`, `checkedRun` reads the result as unknown, so that holds
208
+ // for any `R`.
59
209
  export function zodTool<I, O>(spec: ZodToolSpec<I, O>): Tool<I, O> {
60
210
  const inputSchema = toJsonObjectSchema(spec.input, `Tool "${spec.name}" input`);
211
+ const { output } = spec;
212
+
213
+ function clamp(value: unknown): unknown {
214
+ return spec.clampOverflow ? clampToSchema(value, inputSchema) : value;
215
+ }
216
+
217
+ // One repair, one more parse, and the error is the second parse's: a real mistake inside
218
+ // a decoded string, or beside a fixed wrapper, still reaches the model. The repaired
219
+ // value is clamped too, since a string unwrapped from `{ text }` can be the one too long.
220
+ function parseInput(raw: unknown): I {
221
+ const candidate = clamp(raw);
222
+ const first = spec.input.safeParse(candidate);
223
+ if (first.success) return first.data;
224
+ const repaired = repairSlips(candidate, first.error.issues);
225
+ const parsed = repaired === candidate ? first : spec.input.safeParse(clamp(repaired));
226
+ if (parsed.success) return parsed.data;
227
+ throw new Error(describeIssues(parsed.error.issues, "input"));
228
+ }
61
229
 
62
230
  return defineTool<I, O>({
63
231
  name: spec.name,
64
232
  description: spec.description,
65
233
  inputSchema,
234
+ // Metadata only, never sent to a provider. A type JSON Schema cannot express (a Date, a
235
+ // transform) reads as any value here rather than refusing the tool; the check runs on zod.
236
+ ...(output
237
+ ? { outputSchema: jsonSchemaOf(output, { io: "output", unrepresentable: "any" }) }
238
+ : {}),
66
239
  ...(spec.summarize ? { summarize: spec.summarize } : {}),
67
240
  ...(spec.timeoutMs !== undefined ? { timeoutMs: spec.timeoutMs } : {}),
68
241
  ...(spec.isReadOnly !== undefined ? { isReadOnly: spec.isReadOnly } : {}),
69
242
  ...(spec.needsApproval !== undefined ? { needsApproval: spec.needsApproval } : {}),
70
243
  ...(spec.isConcurrencySafe !== undefined ? { isConcurrencySafe: spec.isConcurrencySafe } : {}),
71
244
  ...(spec.isTerminal !== undefined ? { isTerminal: spec.isTerminal } : {}),
72
- validate: (raw) => {
73
- const candidate = spec.clampOverflow ? clampToSchema(raw, inputSchema) : raw;
74
- const parsed = spec.input.safeParse(candidate);
75
- if (parsed.success) return parsed.data;
76
- throw new Error(
77
- parsed.error.issues
78
- .map((issue) => `${issue.path.join(".") || "input"}: ${issue.message}`)
79
- .join("; "),
80
- );
81
- },
82
- run: spec.run,
245
+ validate: parseInput,
246
+ run: output ? checkedRun(spec, output) : spec.run,
83
247
  });
84
248
  }