kizunajs 2.0.0-beta.0 → 2.0.0-beta.10

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 (55) hide show
  1. package/README.md +2 -2
  2. package/dist/{adapter-BGfMqEkM.d.cts → adapter-BTZYI-zK.d.mts} +4 -4
  3. package/dist/{adapter-CZW-unqX.mjs → adapter-CA3eQ5mU.mjs} +354 -17
  4. package/dist/{adapter-Ci3cfcoT.d.mts → adapter-CpTYJ-HG.d.cts} +4 -4
  5. package/dist/{adapter-DDR_yo9L.cjs → adapter-DKQpBP4R.cjs} +389 -16
  6. package/dist/adapter.cjs +9 -3
  7. package/dist/adapter.d.cts +5 -5
  8. package/dist/adapter.d.mts +5 -5
  9. package/dist/adapter.mjs +4 -4
  10. package/dist/{api-definition-BHnh15zD.d.mts → api-definition-D8wA48BA.d.mts} +2 -2
  11. package/dist/{api-definition-DQj-ewHy.d.cts → api-definition-mKT2sX4P.d.cts} +2 -2
  12. package/dist/{cache-BgohRj0i.cjs → cache-C2NzZFQO.cjs} +54 -1
  13. package/dist/{cache-CLN5y0Xp.mjs → cache-OFJ8xsXC.mjs} +43 -2
  14. package/dist/{error-response-C8Ragjcd.cjs → error-response-Dn5Ci5UP.cjs} +12 -5
  15. package/dist/{error-response-C839d8By.mjs → error-response-rsiMhmJP.mjs} +12 -5
  16. package/dist/generator.cjs +4 -45
  17. package/dist/generator.d.cts +7 -5
  18. package/dist/generator.d.mts +7 -5
  19. package/dist/generator.mjs +2 -43
  20. package/dist/index.cjs +8 -5
  21. package/dist/index.d.cts +50 -8
  22. package/dist/index.d.mts +50 -8
  23. package/dist/index.mjs +8 -5
  24. package/dist/jobs-entry.cjs +2 -2
  25. package/dist/jobs-entry.d.cts +1 -1
  26. package/dist/jobs-entry.d.mts +1 -1
  27. package/dist/jobs-entry.mjs +2 -2
  28. package/dist/{plugin-Cz0kn6Lk.d.mts → plugin-DaiXr_zT.d.mts} +175 -14
  29. package/dist/{plugin-DhKvx_T0.d.cts → plugin-u5qE0OXd.d.cts} +175 -14
  30. package/dist/plugin.d.cts +2 -2
  31. package/dist/plugin.d.mts +2 -2
  32. package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-BOAI1bqI.d.cts} +1 -1
  33. package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-DWMR91fl.d.mts} +1 -1
  34. package/dist/{schemas-C56no6bv.cjs → schemas-BG1zYJdk.cjs} +28 -1
  35. package/dist/{schemas-CJQcc97N.mjs → schemas-BL5VlNt2.mjs} +23 -2
  36. package/dist/schemas.cjs +3 -2
  37. package/dist/schemas.d.cts +23 -2
  38. package/dist/schemas.d.mts +23 -2
  39. package/dist/schemas.mjs +3 -3
  40. package/dist/{security-scheme-BrszwGD5.d.cts → security-scheme-DofJ3GcE.d.cts} +9 -7
  41. package/dist/{security-scheme-D3nb4XKj.d.mts → security-scheme-GJa2h7Tg.d.mts} +9 -7
  42. package/package.json +1 -1
  43. package/src/adapter.ts +137 -8
  44. package/src/config.ts +34 -0
  45. package/src/define-config.ts +12 -1
  46. package/src/handler-pipeline.ts +15 -1
  47. package/src/index.ts +3 -1
  48. package/src/schemas.ts +1 -0
  49. package/src/tool-answer.ts +21 -0
  50. package/src/tool-definitions.ts +162 -0
  51. package/src/tool-events.ts +90 -18
  52. package/src/tool-records.ts +11 -3
  53. package/src/tool-runner.ts +298 -0
  54. package/src/types.ts +9 -7
  55. package/src/zod-internals.ts +12 -5
package/README.md CHANGED
@@ -4,13 +4,13 @@
4
4
 
5
5
  A spec-driven framework for building fully typed REST APIs in TypeScript, where your route declarations produce the validation, the documentation, the clients, and the AI tools.
6
6
 
7
- [![npm](https://img.shields.io/npm/v/kizunajs?color=blue&label=npm)](https://www.npmjs.com/package/kizunajs)
7
+ [![npm](https://img.shields.io/npm/v/kizunajs/beta?color=blue&label=npm)](https://www.npmjs.com/package/kizunajs/v/2.0.0-beta.10)
8
8
  ![license](https://img.shields.io/badge/license-MIT-blue)
9
9
 
10
10
  [Documentation](https://kizunajs.com)
11
11
 
12
12
  > [!NOTE]
13
- > v2 is in beta while the way you declare routes and call them settles, so a minor version can carry a breaking change. Every release names them under **⚠ BREAKING CHANGES**, so pin your version and upgrade when it suits you.
13
+ > v2 is in beta, so a minor version can carry a breaking change. Every release names them under **⚠ BREAKING CHANGES**, so pin your version and upgrade when it suits you.
14
14
  >
15
15
  > [See the release notes](https://github.com/kizunajs/kizuna/releases)
16
16
 
@@ -1,6 +1,6 @@
1
- import { H as ResponseHeaders, J as Routes, L as Method, W as RouteDefinition, a as SecurityScheme, nt as ProblemDetails, z as RequiredPermissions } from "./security-scheme-BrszwGD5.cjs";
2
- import { $ as PathParamsCheck, B as Router, F as HandlersFromRoutes, Kt as NoCredential, L as RequestContextValues, P as HandlerReturn, Rt as Credential, W as ValidationStage, a as PluginArgs, at as EncodeStreamOptions, n as ApiPlugins, z as RouteHandler } from "./plugin-DhKvx_T0.cjs";
3
- import { Q as JobsConfig, X as Jobs, Z as JobsArg, a as RequestContextOf, dt as JobRunner, ft as JobRunnerOptions, h as TagSet, i as JobsOf, it as JobErrorHandler, n as ApiPluginsOf, o as RoutesOf, p as TagKeysOf, s as SchemesOf, t as ApiDefinition, vt as JobTransport } from "./api-definition-DQj-ewHy.cjs";
1
+ import { H as ResponseHeaders, J as Routes, L as Method, W as RouteDefinition, a as SecurityScheme, nt as ProblemDetails, z as RequiredPermissions } from "./security-scheme-GJa2h7Tg.mjs";
2
+ import { $t as Credential, B as Router, F as HandlersFromRoutes, L as RequestContextValues, P as HandlerReturn, W as ValidationStage, a as PluginArgs, bt as EncodeStreamOptions, mt as PathParamsCheck, n as ApiPlugins, sn as NoCredential, z as RouteHandler } from "./plugin-DaiXr_zT.mjs";
3
+ import { Q as JobsConfig, X as Jobs, Z as JobsArg, a as RequestContextOf, dt as JobRunner, ft as JobRunnerOptions, h as TagSet, i as JobsOf, it as JobErrorHandler, n as ApiPluginsOf, o as RoutesOf, p as TagKeysOf, s as SchemesOf, t as ApiDefinition, vt as JobTransport } from "./api-definition-D8wA48BA.mjs";
4
4
  import { z } from "zod";
5
5
 
6
6
  //#region src/access-check.d.ts
@@ -210,7 +210,7 @@ declare const contractOf: <C = unknown>(api: unknown) => C;
210
210
  /**
211
211
  * What kizuna puts in handler args. Must agree with the spread in `runPipeline`.
212
212
  */
213
- declare const HANDLER_ARG_KEYS: readonly ["params", "query", "body", "headers", "throwError", "auth", "requestContext", "plugins"];
213
+ declare const HANDLER_ARG_KEYS: readonly ["params", "query", "body", "headers", "throwError", "auth", "requestContext", "plugins", "tools"];
214
214
  /**
215
215
  * The adapter's own context, with kizuna's arguments removed.
216
216
  */
@@ -1,7 +1,7 @@
1
- import { $ as allowedMethodsForPath, A as streamSchemas, B as resolveResponseCache, C as assertValidStreams, F as isSuccessStatus, H as resolveResponseEtag, I as isZodSchema, N as isJsonMediaType, O as streamContentType, P as isStreamResponse, Q as parsePath, S as EVENT_STREAM_MEDIA_TYPE, V as resolveResponseContentType, c as isCompiledJob, et as flattenRoutes, f as toJobResponse, ft as ROUTES_TAG, h as dueSchedules, i as deprecationHeaders, it as resolveCoercionPlans, lt as HANDLER, n as cacheHeaders, nt as isRouteDefinition, rt as validateRequest, s as flattenJobs, tt as formatValidationError, u as jobAt, w as encodeStreamBody, z as resolveResponseBody } from "./cache-CLN5y0Xp.mjs";
2
- import { T as resolveBaseType, c as isBinarySchema, o as findCoercedSchemaPath, p as isVoidSchema, t as ProblemDetailsSchema, w as readObjectShape } from "./error-response-C839d8By.mjs";
1
+ import { A as streamContentType, E as encodeStreamBody, F as isJsonMediaType, H as resolveResponseCache, I as isStreamResponse, L as isSuccessStatus, M as streamSchemas, O as routeStreams, R as isZodSchema, S as deriveToolNames, T as assertValidStreams, U as resolveResponseContentType, V as resolveResponseBody, W as resolveResponseEtag, at as validateRequest, c as isCompiledJob, dt as HANDLER, et as parsePath, f as toJobResponse, h as dueSchedules, i as deprecationHeaders, it as isRouteDefinition, mt as ROUTES_TAG, n as cacheHeaders, nt as flattenRoutes, ot as resolveCoercionPlans, rt as formatValidationError, s as flattenJobs, tt as allowedMethodsForPath, u as jobAt, w as EVENT_STREAM_MEDIA_TYPE } from "./cache-OFJ8xsXC.mjs";
2
+ import { T as resolveBaseType, c as isBinarySchema, o as findCoercedSchemaPath, p as isVoidSchema, t as ProblemDetailsSchema, w as readObjectShape } from "./error-response-rsiMhmJP.mjs";
3
+ import { l as authenticationChallenge, p as resolveSecurityRequirements } from "./schemas-BL5VlNt2.mjs";
3
4
  import { PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, pluginRouteTree } from "./plugin.mjs";
4
- import { c as authenticationChallenge, f as resolveSecurityRequirements } from "./schemas-CJQcc97N.mjs";
5
5
  import { z } from "zod";
6
6
  //#region src/tags.ts
7
7
  const isTagSet = (value) => typeof value === "object" && value !== null && "__brand" in value && value.__brand === "TagSet";
@@ -28,8 +28,116 @@ const createTags = (tags) => {
28
28
  };
29
29
  };
30
30
  //#endregion
31
+ //#region src/tool-definitions.ts
32
+ /**
33
+ * What a route says about publishing itself, or `undefined` when it says
34
+ * nothing.
35
+ */
36
+ const toolOptionsOf = (route) => {
37
+ if (route.tool === void 0 || route.tool === false) return void 0;
38
+ return route.tool === true ? {} : route.tool;
39
+ };
40
+ /**
41
+ * Why a route cannot run as a tool, or `undefined` when it can.
42
+ */
43
+ const toolRefusal = (route) => {
44
+ if (route.contentType !== void 0 && route.contentType !== "application/json") return `it takes a ${route.contentType} body, and tool input is JSON`;
45
+ if (routeStreams(route)) return "it streams, and a tool result is one value";
46
+ };
47
+ /**
48
+ * The routes a model may call: the ones that declared `tool`, less the ones
49
+ * whose shape a tool call cannot carry.
50
+ */
51
+ const selectToolRoutes = (routes) => routes.filter(({ route }) => toolOptionsOf(route) !== void 0 && toolRefusal(route) === void 0);
52
+ const describeRoles = (route) => route.roles !== void 0 && route.roles.length > 0 ? `Roles: ${route.roles.join(", ")}` : void 0;
53
+ const describeRequires = (route) => {
54
+ const requires = route.requires;
55
+ if (requires === void 0) return void 0;
56
+ const names = Object.entries(requires).flatMap(([resource, verbs]) => verbs.map((verb) => `${resource}:${verb}`));
57
+ return names.length > 0 ? `Permissions: ${names.join(", ")}` : void 0;
58
+ };
59
+ /**
60
+ * What a model reads before it calls the route.
61
+ */
62
+ const describeTool = (route) => {
63
+ const parts = [];
64
+ const declared = toolOptionsOf(route)?.description;
65
+ if (declared) parts.push(declared);
66
+ else if (route.summary) parts.push(route.summary);
67
+ if (route.description) parts.push(route.description);
68
+ if (parts.length === 0) parts.push(`${route.method} ${route.path}`);
69
+ parts.push(`\nHTTP: ${route.method} ${route.path}`);
70
+ const requirements = resolveSecurityRequirements(route);
71
+ if (requirements.length > 0) parts.push(`Requires: ${requirements.map(({ scheme }) => scheme).join(", ")}`);
72
+ const roles = describeRoles(route);
73
+ if (roles !== void 0) parts.push(roles);
74
+ const permissions = describeRequires(route);
75
+ if (permissions !== void 0) parts.push(permissions);
76
+ return parts.join("\n");
77
+ };
78
+ /**
79
+ * The `{ params, query, body }` a model sends to call the route.
80
+ */
81
+ const buildToolInputSchema = (route) => {
82
+ const shape = {};
83
+ let hasParams = false;
84
+ let hasQuery = false;
85
+ let hasBody = false;
86
+ const paramNames = parsePath(route.path).paramNames;
87
+ if (paramNames.length > 0) {
88
+ hasParams = true;
89
+ const paramShape = {};
90
+ const explicitShape = route.pathParams ? readObjectShape(route.pathParams) : void 0;
91
+ for (const name of paramNames) paramShape[name] = explicitShape?.[name] ?? z.string();
92
+ shape["params"] = z.object(paramShape);
93
+ }
94
+ if (route.query) {
95
+ hasQuery = true;
96
+ shape["query"] = route.query.safeParse({}).success ? route.query.optional() : route.query;
97
+ }
98
+ if (route.body && !isVoidSchema(route.body)) {
99
+ hasBody = true;
100
+ shape["body"] = route.body.safeParse(void 0).success ? route.body.optional() : route.body;
101
+ }
102
+ return {
103
+ shape: Object.keys(shape).length === 0 ? void 0 : shape,
104
+ hasParams,
105
+ hasQuery,
106
+ hasBody
107
+ };
108
+ };
109
+ const toJsonSchema = (route) => {
110
+ const { shape } = buildToolInputSchema(route);
111
+ const { $schema: _, ...schema } = z.toJSONSchema(z.object(shape ?? {}), {
112
+ io: "input",
113
+ unrepresentable: "any"
114
+ });
115
+ return schema;
116
+ };
117
+ /**
118
+ * One {@link ToolDefinition} per route.
119
+ */
120
+ const buildToolDefinitions = (routes) => {
121
+ const entries = flattenRoutes(routes);
122
+ const names = deriveToolNames(entries.map(({ routeKey }) => ({
123
+ key: routeKey,
124
+ origin: "route"
125
+ })));
126
+ return entries.map(({ routeKey, route }) => ({
127
+ name: names.get(routeKey),
128
+ key: routeKey,
129
+ description: describeTool(route),
130
+ inputSchema: toJsonSchema(route)
131
+ }));
132
+ };
133
+ //#endregion
31
134
  //#region src/tool-events.ts
32
135
  /**
136
+ * Where a streamed response keeps the routes it named under `tools`.
137
+ */
138
+ const STREAM_TOOLS = Symbol.for("kizuna.stream.tools");
139
+ const streamToolsOf = (response) => response !== null && typeof response === "object" ? response[STREAM_TOOLS] : void 0;
140
+ /**
33
141
  * The `{ params, query, body }` a route takes as a tool, as schemas, so the
34
142
  * stream events and the MCP endpoint agree on one shape.
35
143
  */
@@ -45,13 +153,30 @@ const toolInputShape = (route) => {
45
153
  return shape;
46
154
  };
47
155
  /**
48
- * What a route answers a tool call with, read from its `200`.
156
+ * The body of each `2xx` the route declares.
49
157
  */
50
158
  const toolOutputSchema = (route) => {
51
- const response = route.responses[200];
52
- if (response === void 0) return void 0;
53
- if (isZodSchema(response)) return response;
54
- return "body" in response && isZodSchema(response.body) ? response.body : void 0;
159
+ const bodies = [];
160
+ let someSuccessHasNoBody = false;
161
+ for (const status of Object.keys(route.responses).map(Number).sort((left, right) => left - right)) {
162
+ if (!isSuccessStatus(status)) continue;
163
+ const response = route.responses[status];
164
+ if (response === void 0) continue;
165
+ const contentType = resolveResponseContentType(response);
166
+ if (isStreamResponse(response) || contentType !== void 0 && !isJsonMediaType(contentType)) {
167
+ someSuccessHasNoBody = true;
168
+ continue;
169
+ }
170
+ const body = resolveResponseBody(response);
171
+ if (body === void 0 || isVoidSchema(body)) {
172
+ someSuccessHasNoBody = true;
173
+ continue;
174
+ }
175
+ bodies.push(body);
176
+ }
177
+ if (bodies.length === 0) return void 0;
178
+ const output = bodies.length === 1 ? bodies[0] : z.union(bodies);
179
+ return someSuccessHasNoBody ? output.optional() : output;
55
180
  };
56
181
  /**
57
182
  * Server-sent events for the routes a model may call, to spread into a route's
@@ -78,6 +203,7 @@ const toolEvents = (tools) => {
78
203
  return z.object({
79
204
  ...identifier,
80
205
  name: z.literal(routeKey),
206
+ needsApproval: z.literal(true).optional(),
81
207
  ...Object.keys(input).length > 0 ? { input: z.object(input) } : {}
82
208
  });
83
209
  });
@@ -106,12 +232,25 @@ const toolEvents = (tools) => {
106
232
  * `k.routes` before a route is validated.
107
233
  */
108
234
  const expandStreamTools = (route, routeKey) => {
235
+ let namedAt;
109
236
  for (const [status, response] of Object.entries(route.responses)) {
110
237
  if (!isStreamResponse(response)) continue;
111
238
  const { tools } = response;
112
239
  if (tools === void 0) continue;
113
240
  const where = `Route "${routeKey}" declares tools on status ${status}`;
241
+ if (namedAt !== void 0) throw new Error(`${where} and on status ${namedAt}. A handler runs one set of tools, so name them on one response.`);
242
+ namedAt = status;
114
243
  if (isZodSchema(response.stream)) throw new Error(`${where} beside a single stream schema. Tool events are named, so name the other events too.`);
244
+ const toolEntries = flattenRoutes(tools);
245
+ deriveToolNames(toolEntries.map(({ routeKey: toolKey }) => ({
246
+ key: toolKey,
247
+ origin: "route"
248
+ })));
249
+ for (const { routeKey: toolKey, route: toolRoute } of toolEntries) {
250
+ if (toolOptionsOf(toolRoute) === void 0) throw new Error(`${where}, naming "${toolKey}", which does not declare \`tool\`. Declare it on that route.`);
251
+ const refusal = toolRefusal(toolRoute);
252
+ if (refusal !== void 0) throw new Error(`${where}, naming "${toolKey}", which cannot run as a tool: ${refusal}.`);
253
+ }
115
254
  const events = toolEvents(tools);
116
255
  const named = response.stream;
117
256
  for (const name of Object.keys(events)) if (name in named) throw new Error(`${where}, but its stream already names an event "${name}". Rename that event.`);
@@ -120,6 +259,7 @@ const expandStreamTools = (route, routeKey) => {
120
259
  ...named,
121
260
  ...events
122
261
  };
262
+ mutable[STREAM_TOOLS] = tools;
123
263
  delete mutable.tools;
124
264
  }
125
265
  };
@@ -992,6 +1132,134 @@ const resolvePluginServers = (plugins, api) => {
992
1132
  return resolved;
993
1133
  };
994
1134
  //#endregion
1135
+ //#region src/tool-runner.ts
1136
+ const DECLINED = "Declined, so nothing ran.";
1137
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1138
+ const detailOf = (status, body) => isRecord(body) && typeof body["detail"] === "string" ? body["detail"] : `The route answered ${status}.`;
1139
+ const callInput = (route, parsed) => {
1140
+ const input = {};
1141
+ if (parsePath(route.path).paramNames.length > 0) input["params"] = parsed.params;
1142
+ if (route.query) input["query"] = parsed.query;
1143
+ if (route.body && !isVoidSchema(route.body)) input["body"] = parsed.body;
1144
+ return Object.keys(input).length > 0 ? input : void 0;
1145
+ };
1146
+ const definitionsCache = /* @__PURE__ */ new WeakMap();
1147
+ const definitionsFor = (tools) => {
1148
+ const cached = definitionsCache.get(tools);
1149
+ if (cached) return cached;
1150
+ const built = buildToolDefinitions(tools);
1151
+ definitionsCache.set(tools, built);
1152
+ return built;
1153
+ };
1154
+ /**
1155
+ * Bind a response's tools to the request streaming it.
1156
+ */
1157
+ const createStreamTools = (tools, pipeline) => {
1158
+ const definitions = definitionsFor(tools);
1159
+ const entries = new Map(flattenRoutes(tools).map((entry) => [entry.routeKey, entry]));
1160
+ const keysByName = new Map(definitions.map((definition) => [definition.name, definition.key]));
1161
+ const namesByKey = new Map(definitions.map((definition) => [definition.key, definition.name]));
1162
+ const answered = (call, status, body) => {
1163
+ const content = JSON.stringify({
1164
+ status,
1165
+ body
1166
+ });
1167
+ return status < 400 ? {
1168
+ call,
1169
+ state: "done",
1170
+ status,
1171
+ body,
1172
+ content,
1173
+ isError: false
1174
+ } : {
1175
+ call,
1176
+ state: "failed",
1177
+ status,
1178
+ body,
1179
+ content,
1180
+ isError: true
1181
+ };
1182
+ };
1183
+ async function* run(call, options = {}) {
1184
+ const key = keysByName.get(call.name) ?? call.name;
1185
+ const entry = entries.get(key);
1186
+ const modelCall = {
1187
+ id: call.id,
1188
+ name: namesByKey.get(key) ?? call.name,
1189
+ input: call.input ?? {}
1190
+ };
1191
+ if (entry === void 0) return answered(modelCall, 404, problemDetails(404, `No tool named "${call.name}". Call one of: ${[...keysByName.keys()].join(", ")}.`));
1192
+ const failed = (status, body) => ({
1193
+ event: "tool_error",
1194
+ data: {
1195
+ id: call.id,
1196
+ name: key,
1197
+ message: detailOf(status, body)
1198
+ }
1199
+ });
1200
+ const input = isRecord(call.input) ? call.input : {};
1201
+ const params = Object.fromEntries(Object.entries(isRecord(input["params"]) ? input["params"] : {}).map(([name, value]) => [name, String(value)]));
1202
+ const validation = validateRequest(entry.route, {
1203
+ params,
1204
+ query: input["query"] ?? {},
1205
+ body: input["body"],
1206
+ headers: pipeline.headers
1207
+ });
1208
+ if (!validation.ok) {
1209
+ const rendered = pipeline.render(validation.error);
1210
+ yield failed(rendered.status, rendered.body);
1211
+ return answered(modelCall, rendered.status, rendered.body);
1212
+ }
1213
+ const validated = callInput(entry.route, validation.parsed);
1214
+ const needsApproval = toolOptionsOf(entry.route)?.needsApproval === true;
1215
+ const waiting = needsApproval && options.approved === void 0;
1216
+ yield {
1217
+ event: "tool_call",
1218
+ data: {
1219
+ id: call.id,
1220
+ name: key,
1221
+ ...waiting ? { needsApproval: true } : {},
1222
+ ...validated === void 0 ? {} : { input: validated }
1223
+ }
1224
+ };
1225
+ if (waiting) return {
1226
+ call: modelCall,
1227
+ state: "needs-approval"
1228
+ };
1229
+ if (needsApproval && options.approved === false) {
1230
+ yield {
1231
+ event: "tool_error",
1232
+ data: {
1233
+ id: call.id,
1234
+ name: key,
1235
+ message: DECLINED
1236
+ }
1237
+ };
1238
+ return {
1239
+ call: modelCall,
1240
+ state: "declined",
1241
+ content: DECLINED,
1242
+ isError: true
1243
+ };
1244
+ }
1245
+ const { status, body } = await pipeline.invoke(entry, validation.parsed, params);
1246
+ if (status >= 400) yield failed(status, body);
1247
+ else yield {
1248
+ event: "tool_result",
1249
+ data: {
1250
+ id: call.id,
1251
+ name: key,
1252
+ ...body === void 0 ? {} : { output: body }
1253
+ }
1254
+ };
1255
+ return answered(modelCall, status, body);
1256
+ }
1257
+ return {
1258
+ definitions,
1259
+ run
1260
+ };
1261
+ };
1262
+ //#endregion
995
1263
  //#region src/adapter.ts
996
1264
  var ResponseValidationError = class extends Error {
997
1265
  routeKey;
@@ -1067,7 +1335,8 @@ const HANDLER_ARG_KEYS = [
1067
1335
  "throwError",
1068
1336
  "auth",
1069
1337
  "requestContext",
1070
- "plugins"
1338
+ "plugins",
1339
+ "tools"
1071
1340
  ];
1072
1341
  /**
1073
1342
  * The adapter's own context, with kizuna's arguments removed.
@@ -1573,18 +1842,84 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1573
1842
  issues: formatted.issues
1574
1843
  };
1575
1844
  }
1576
- const handler = resolveHandler(router, routeKey);
1845
+ return invokeRoute({
1846
+ resolved,
1847
+ parsed: validation.parsed,
1848
+ handler: resolveHandler(router, routeKey),
1849
+ request,
1850
+ routes,
1851
+ definition,
1852
+ handlerContext: () => definition.buildHandlerContext(request, responseContext),
1853
+ guards,
1854
+ schemes,
1855
+ contextResolvers,
1856
+ pluginExports,
1857
+ jobRunner,
1858
+ responseValidation
1859
+ });
1860
+ };
1861
+ const streamToolsOfRoute = (route) => {
1862
+ for (const response of Object.values(route.responses)) {
1863
+ const tools = streamToolsOf(response);
1864
+ if (tools !== void 0) return tools;
1865
+ }
1866
+ };
1867
+ /**
1868
+ * What a tool call reports: the status and body HTTP would have sent.
1869
+ */
1870
+ const toolAnswer = (result) => {
1871
+ if (result.kind === "raw-response") return {
1872
+ status: 500,
1873
+ body: problemDetails(500, "This route answers with a raw response, and a tool answers with a JSON body.")
1874
+ };
1875
+ if (result.kind === "handler-error") console.error(`[kizuna] tool "${result.routeKey}" threw:`, result.error);
1876
+ const rendered = renderJsonResult(result);
1877
+ return {
1878
+ status: rendered.status,
1879
+ body: rendered.body
1880
+ };
1881
+ };
1882
+ /**
1883
+ * Each call runs its route as a request of its own, from the same caller.
1884
+ */
1885
+ const streamToolsFor = (tools, invocation, handlerContext) => createStreamTools(tools, {
1886
+ headers: invocation.request.headers,
1887
+ invoke: async (entry, parsed, params) => toolAnswer(await invokeRoute({
1888
+ ...invocation,
1889
+ resolved: {
1890
+ routeKey: entry.routeKey,
1891
+ route: entry.route,
1892
+ params
1893
+ },
1894
+ parsed,
1895
+ handler: entry.route[HANDLER],
1896
+ handlerContext: () => handlerContext
1897
+ })),
1898
+ render: (failure) => {
1899
+ const formatted = formatValidationError(failure);
1900
+ return toolAnswer({
1901
+ kind: "validation-failed",
1902
+ stage: failure.stage,
1903
+ detail: formatted.detail,
1904
+ issues: formatted.issues
1905
+ });
1906
+ }
1907
+ });
1908
+ const invokeRoute = async (invocation) => {
1909
+ const { resolved, parsed, request, routes, definition, guards, schemes, contextResolvers, pluginExports, jobRunner, responseValidation } = invocation;
1910
+ const { routeKey, route, params } = resolved;
1911
+ const handler = invocation.handler;
1577
1912
  if (typeof handler !== "function") return {
1578
1913
  kind: "no-handler",
1579
1914
  routeKey
1580
1915
  };
1581
1916
  try {
1582
- const handlerContext = await definition.buildHandlerContext(request, responseContext);
1917
+ const handlerContext = await invocation.handlerContext();
1583
1918
  const requestContext = {};
1584
1919
  if (contextResolvers) for (const [name, resolver] of Object.entries(contextResolvers)) requestContext[name] = await resolver({
1585
1920
  ...handlerContext,
1586
1921
  params,
1587
- headers: raw.headers
1922
+ headers: request.headers
1588
1923
  });
1589
1924
  const hasRequestContext = Object.keys(requestContext).length > 0;
1590
1925
  const securityContext = {};
@@ -1636,13 +1971,15 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1636
1971
  const throwError = (response) => {
1637
1972
  throw new ResponseError(response);
1638
1973
  };
1974
+ const tools = streamToolsOfRoute(route);
1639
1975
  const handlerResult = await handler({
1640
- params: validation.parsed.params,
1641
- query: validation.parsed.query,
1642
- body: validation.parsed.body,
1643
- headers: validation.parsed.headers,
1976
+ params: parsed.params,
1977
+ query: parsed.query,
1978
+ body: parsed.body,
1979
+ headers: parsed.headers,
1644
1980
  throwError,
1645
1981
  ...handlerContext,
1982
+ ...tools ? { tools: streamToolsFor(tools, invocation, handlerContext) } : {},
1646
1983
  ...jobRunner ? { jobs: jobRunner } : {},
1647
1984
  ...hasRequestContext ? { requestContext } : {},
1648
1985
  ...Object.keys(securityContext).length > 0 ? { auth: securityContext } : {},
@@ -1850,4 +2187,4 @@ const headersToObject = (headers) => {
1850
2187
  return result;
1851
2188
  };
1852
2189
  //#endregion
1853
- export { DispatchFailedSchema as $, routerFromRoutes as A, assertNoPathCollisions as B, headersToObject as C, jobRunnerFrom as D, jobRoutes as E, pluginRouterOf as F, requiresDenial as G, matchRoute as H, pluginRoutesOf as I, createJobTransport as J, withPermissions as K, resolvePluginServers as L, runRoute as M, warnUnsupportedJobOptions as N, parseFetchBody as O, pluginExportsOf as P, ResponseError as Q, isRawResponse as R, guardDenyFor as S, jobRouter as T, sortFlattenedRoutes as U, routeClaims as V, insufficientScope as W, createJobRunner as X, JobInputError as Y, jobFnAt as Z, createAdapter as _, createTags as _t, HANDLER_ARG_KEYS as a, problemDetails as at, extractCredential as b, ROUTER_META as c, getStatusText as ct, SCHEMES_META as d, isPermissions as dt, DispatchResultSchema as et, adapterContextOf as f, isRoles as ft, contractOf as g, toolEvents as gt, boundJobKeys as h, expandStreamTools as ht, GUARD_SCHEMA_META as i, failedJobs as it, runHandler as j, renderJsonResult as k, RUN_ROUTE_KEY as l, createPermissions as lt, bearerChallenge as m, tagRoutes as mt, DISPATCH_ROUTE_KEY as n, dispatchSucceeded as nt, JOBS_META as o, problemFromBody as ot, assembleApi as p, permissionNames as pt, JobDispatchError as q, GUARDS_META as r, dueJobs as rt, REQUEST_CONTEXT_META as s, STATUS_TITLES as st, API_META as t, dispatchDueJobs as tt, ResponseValidationError as u, createRoles as ut, dispatchHandler as v, isTagSet as vt, isGuardDenial as w, getHeaderValue as x, dispatchRoute as y, rawResponse as z };
2190
+ export { DispatchFailedSchema as $, routerFromRoutes as A, assertNoPathCollisions as B, headersToObject as C, createTags as Ct, jobRunnerFrom as D, jobRoutes as E, pluginRouterOf as F, requiresDenial as G, matchRoute as H, pluginRoutesOf as I, createJobTransport as J, withPermissions as K, resolvePluginServers as L, runRoute as M, warnUnsupportedJobOptions as N, parseFetchBody as O, pluginExportsOf as P, ResponseError as Q, isRawResponse as R, guardDenyFor as S, toolRefusal as St, jobRouter as T, sortFlattenedRoutes as U, routeClaims as V, insufficientScope as W, createJobRunner as X, JobInputError as Y, jobFnAt as Z, createAdapter as _, buildToolDefinitions as _t, HANDLER_ARG_KEYS as a, problemDetails as at, extractCredential as b, selectToolRoutes as bt, ROUTER_META as c, getStatusText as ct, SCHEMES_META as d, isPermissions as dt, DispatchResultSchema as et, adapterContextOf as f, isRoles as ft, contractOf as g, toolEvents as gt, boundJobKeys as h, expandStreamTools as ht, GUARD_SCHEMA_META as i, failedJobs as it, runHandler as j, renderJsonResult as k, RUN_ROUTE_KEY as l, createPermissions as lt, bearerChallenge as m, tagRoutes as mt, DISPATCH_ROUTE_KEY as n, dispatchSucceeded as nt, JOBS_META as o, problemFromBody as ot, assembleApi as p, permissionNames as pt, JobDispatchError as q, GUARDS_META as r, dueJobs as rt, REQUEST_CONTEXT_META as s, STATUS_TITLES as st, API_META as t, dispatchDueJobs as tt, ResponseValidationError as u, createRoles as ut, dispatchHandler as v, buildToolInputSchema as vt, isGuardDenial as w, isTagSet as wt, getHeaderValue as x, toolOptionsOf as xt, dispatchRoute as y, describeTool as yt, rawResponse as z };
@@ -1,6 +1,6 @@
1
- import { H as ResponseHeaders, J as Routes, L as Method, W as RouteDefinition, a as SecurityScheme, nt as ProblemDetails, z as RequiredPermissions } from "./security-scheme-D3nb4XKj.mjs";
2
- import { $ as PathParamsCheck, B as Router, F as HandlersFromRoutes, Kt as NoCredential, L as RequestContextValues, P as HandlerReturn, Rt as Credential, W as ValidationStage, a as PluginArgs, at as EncodeStreamOptions, n as ApiPlugins, z as RouteHandler } from "./plugin-Cz0kn6Lk.mjs";
3
- import { Q as JobsConfig, X as Jobs, Z as JobsArg, a as RequestContextOf, dt as JobRunner, ft as JobRunnerOptions, h as TagSet, i as JobsOf, it as JobErrorHandler, n as ApiPluginsOf, o as RoutesOf, p as TagKeysOf, s as SchemesOf, t as ApiDefinition, vt as JobTransport } from "./api-definition-BHnh15zD.mjs";
1
+ import { H as ResponseHeaders, J as Routes, L as Method, W as RouteDefinition, a as SecurityScheme, nt as ProblemDetails, z as RequiredPermissions } from "./security-scheme-DofJ3GcE.cjs";
2
+ import { $t as Credential, B as Router, F as HandlersFromRoutes, L as RequestContextValues, P as HandlerReturn, W as ValidationStage, a as PluginArgs, bt as EncodeStreamOptions, mt as PathParamsCheck, n as ApiPlugins, sn as NoCredential, z as RouteHandler } from "./plugin-u5qE0OXd.cjs";
3
+ import { Q as JobsConfig, X as Jobs, Z as JobsArg, a as RequestContextOf, dt as JobRunner, ft as JobRunnerOptions, h as TagSet, i as JobsOf, it as JobErrorHandler, n as ApiPluginsOf, o as RoutesOf, p as TagKeysOf, s as SchemesOf, t as ApiDefinition, vt as JobTransport } from "./api-definition-mKT2sX4P.cjs";
4
4
  import { z } from "zod";
5
5
 
6
6
  //#region src/access-check.d.ts
@@ -210,7 +210,7 @@ declare const contractOf: <C = unknown>(api: unknown) => C;
210
210
  /**
211
211
  * What kizuna puts in handler args. Must agree with the spread in `runPipeline`.
212
212
  */
213
- declare const HANDLER_ARG_KEYS: readonly ["params", "query", "body", "headers", "throwError", "auth", "requestContext", "plugins"];
213
+ declare const HANDLER_ARG_KEYS: readonly ["params", "query", "body", "headers", "throwError", "auth", "requestContext", "plugins", "tools"];
214
214
  /**
215
215
  * The adapter's own context, with kizuna's arguments removed.
216
216
  */