kizunajs 2.0.0-beta.2 → 2.0.0-beta.21

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 (81) hide show
  1. package/README.md +3 -2
  2. package/dist/{adapter-CZW-unqX.mjs → adapter-BSqNrxhq.mjs} +522 -104
  3. package/dist/adapter-C3WYdSfx.d.cts +2754 -0
  4. package/dist/{adapter-DDR_yo9L.cjs → adapter-ClaFZoab.cjs} +638 -196
  5. package/dist/adapter-D4bTPElA.d.mts +2754 -0
  6. package/dist/adapter.cjs +37 -29
  7. package/dist/adapter.d.cts +3 -5
  8. package/dist/adapter.d.mts +3 -5
  9. package/dist/adapter.mjs +5 -5
  10. package/dist/{error-response-C8Ragjcd.cjs → error-response-C9ymqSU4.cjs} +25 -5
  11. package/dist/{error-response-C839d8By.mjs → error-response-CNQaKVYd.mjs} +20 -6
  12. package/dist/{security-scheme-BrszwGD5.d.cts → error-response-NoOGdh8H.d.mts} +151 -24
  13. package/dist/{security-scheme-D3nb4XKj.d.mts → error-response-YbkRMKno.d.cts} +151 -24
  14. package/dist/generator.cjs +190 -95
  15. package/dist/generator.d.cts +189 -28
  16. package/dist/generator.d.mts +189 -28
  17. package/dist/generator.mjs +151 -60
  18. package/dist/index.cjs +159 -84
  19. package/dist/index.d.cts +193 -253
  20. package/dist/index.d.mts +193 -253
  21. package/dist/index.mjs +112 -38
  22. package/dist/jobs-entry.cjs +12 -11
  23. package/dist/jobs-entry.d.cts +1 -1
  24. package/dist/jobs-entry.d.mts +1 -1
  25. package/dist/jobs-entry.mjs +3 -2
  26. package/dist/plugin-Dw-yCjTY.cjs +233 -0
  27. package/dist/{cache-CLN5y0Xp.mjs → plugin-server-BztlE1fz.mjs} +188 -49
  28. package/dist/{cache-BgohRj0i.cjs → plugin-server-kUsK7thV.cjs} +238 -93
  29. package/dist/plugin-xxCxibmu.mjs +138 -0
  30. package/dist/plugin.cjs +8 -72
  31. package/dist/plugin.d.cts +3 -3
  32. package/dist/plugin.d.mts +3 -3
  33. package/dist/plugin.mjs +2 -68
  34. package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-B9hMFQ9N.d.cts} +1 -1
  35. package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-CfBVsqIk.d.mts} +1 -1
  36. package/dist/{schemas-C56no6bv.cjs → schemas-DNPVDvkd.cjs} +28 -1
  37. package/dist/{schemas-CJQcc97N.mjs → schemas-HW2FDsvz.mjs} +23 -2
  38. package/dist/schemas.cjs +3 -2
  39. package/dist/schemas.d.cts +24 -3
  40. package/dist/schemas.d.mts +24 -3
  41. package/dist/schemas.mjs +3 -3
  42. package/package.json +1 -1
  43. package/src/adapter.ts +245 -29
  44. package/src/api-definition.ts +12 -16
  45. package/src/api.ts +7 -3
  46. package/src/brand.ts +29 -0
  47. package/src/config.ts +51 -10
  48. package/src/configured.ts +13 -6
  49. package/src/define-config.ts +118 -39
  50. package/src/generator.ts +363 -46
  51. package/src/group-routes.ts +106 -0
  52. package/src/groups.ts +140 -0
  53. package/src/handler-pipeline.ts +78 -19
  54. package/src/index.ts +15 -6
  55. package/src/job-runner.ts +5 -0
  56. package/src/job-transport.ts +3 -3
  57. package/src/job.ts +8 -6
  58. package/src/jobs-dev-runner.ts +6 -0
  59. package/src/jobs.ts +61 -8
  60. package/src/kizuna.ts +56 -33
  61. package/src/plugin-server.ts +129 -19
  62. package/src/plugin.ts +269 -127
  63. package/src/routes.ts +80 -32
  64. package/src/schemas.ts +1 -0
  65. package/src/tool-answer.ts +21 -0
  66. package/src/tool-definitions.ts +166 -0
  67. package/src/tool-events.ts +90 -18
  68. package/src/tool-records.ts +11 -3
  69. package/src/tool-runner.ts +298 -0
  70. package/src/types.ts +90 -24
  71. package/src/zod-internals.ts +22 -5
  72. package/src/zod-meta.ts +7 -2
  73. package/dist/adapter-BGfMqEkM.d.cts +0 -563
  74. package/dist/adapter-Ci3cfcoT.d.mts +0 -563
  75. package/dist/api-definition-BHnh15zD.d.mts +0 -803
  76. package/dist/api-definition-DQj-ewHy.d.cts +0 -803
  77. package/dist/error-response-BBGSdgYw.d.mts +0 -67
  78. package/dist/error-response-Do38sr-9.d.cts +0 -67
  79. package/dist/plugin-Cz0kn6Lk.d.mts +0 -830
  80. package/dist/plugin-DhKvx_T0.d.cts +0 -830
  81. package/src/tags.ts +0 -67
@@ -1,35 +1,122 @@
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";
3
- 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";
1
+ import { g as ROUTES_GROUP, n as PLUGIN_SERVERS_META_KEY, o as pluginRouteTree, p as HANDLER, t as PLUGIN_ROUTES_META_KEY } from "./plugin-xxCxibmu.mjs";
2
+ import { E as resolveBaseType, T as readObjectShape, c as isBinarySchema, o as findCoercedSchemaPath, p as isVoidSchema, t as ProblemDetailsSchema } from "./error-response-CNQaKVYd.mjs";
3
+ import { F as routeStreams, G as isZodSchema, H as isJsonMediaType, J as resolveResponseBody, L as streamContentType, M as assertValidStreams, N as encodeStreamBody, S as dueSchedules, U as isStreamResponse, W as isSuccessStatus, X as resolveResponseContentType, Y as resolveResponseCache, Z as resolveResponseEtag, _ as jobAt, c as cacheHeaders, ct as allowedMethodsForPath, dt as isRouteDefinition, ft as validateRequest, h as isCompiledJob, j as EVENT_STREAM_MEDIA_TYPE, k as deriveToolNames, lt as flattenRoutes, m as flattenJobs, pt as resolveCoercionPlans, st as parsePath, u as deprecationHeaders, ut as formatValidationError, y as toJobResponse, z as streamSchemas } from "./plugin-server-BztlE1fz.mjs";
4
+ import { l as authenticationChallenge, p as resolveSecurityRequirements } from "./schemas-HW2FDsvz.mjs";
5
5
  import { z } from "zod";
6
- //#region src/tags.ts
7
- const isTagSet = (value) => typeof value === "object" && value !== null && "__brand" in value && value.__brand === "TagSet";
6
+ //#region src/tool-definitions.ts
8
7
  /**
9
- * Define a set of tags. A tag value may be a full {@link TagOptions} object or a
10
- * string, which is shorthand for `{ title }`. Pass the result to `defineConfig`
11
- * under `tags`.
12
- *
13
- * @example
14
- * const tags = k.tags({
15
- * orders: {
16
- * title: 'Orders',
17
- * description: 'Create and manage orders',
18
- * },
19
- * health: 'Health',
20
- * });
8
+ * What a route says about publishing itself, or `undefined` when it says
9
+ * nothing.
21
10
  */
22
- const createTags = (tags) => {
23
- const normalized = {};
24
- for (const [key, value] of Object.entries(tags)) normalized[key] = typeof value === "string" ? { title: value } : value;
11
+ const toolOptionsOf = (route) => {
12
+ if (route.tool === void 0 || route.tool === false) return void 0;
13
+ return route.tool === true ? {} : route.tool;
14
+ };
15
+ /**
16
+ * Why a route cannot run as a tool, or `undefined` when it can.
17
+ */
18
+ const toolRefusal = (route) => {
19
+ if (route.hidden === true) return "it is hidden, and a hidden route never publishes";
20
+ if (route.contentType !== void 0 && route.contentType !== "application/json") return `it takes a ${route.contentType} body, and tool input is JSON`;
21
+ if (routeStreams(route)) return "it streams, and a tool result is one value";
22
+ };
23
+ /**
24
+ * The routes a model may call: the ones that declared `tool`, less the ones
25
+ * whose shape a tool call cannot carry.
26
+ */
27
+ const selectToolRoutes = (routes) => routes.filter(({ route }) => toolOptionsOf(route) !== void 0 && toolRefusal(route) === void 0);
28
+ const describeRoles = (route) => route.roles !== void 0 && route.roles.length > 0 ? `Roles: ${route.roles.join(", ")}` : void 0;
29
+ const describeRequires = (route) => {
30
+ const requires = route.requires;
31
+ if (requires === void 0) return void 0;
32
+ const names = Object.entries(requires).flatMap(([resource, verbs]) => verbs.map((verb) => `${resource}:${verb}`));
33
+ return names.length > 0 ? `Permissions: ${names.join(", ")}` : void 0;
34
+ };
35
+ /**
36
+ * What a model reads before it calls the route.
37
+ */
38
+ const describeTool = (route) => {
39
+ const parts = [];
40
+ const declared = toolOptionsOf(route)?.description;
41
+ if (declared) parts.push(declared);
42
+ else if (route.summary) parts.push(route.summary);
43
+ if (route.description) parts.push(route.description);
44
+ if (parts.length === 0) parts.push(`${route.method} ${route.path}`);
45
+ parts.push(`\nHTTP: ${route.method} ${route.path}`);
46
+ const requirements = resolveSecurityRequirements(route);
47
+ if (requirements.length > 0) parts.push(`Requires: ${requirements.map(({ scheme }) => scheme).join(", ")}`);
48
+ const roles = describeRoles(route);
49
+ if (roles !== void 0) parts.push(roles);
50
+ const permissions = describeRequires(route);
51
+ if (permissions !== void 0) parts.push(permissions);
52
+ return parts.join("\n");
53
+ };
54
+ /**
55
+ * The `{ params, query, body }` a model sends to call the route.
56
+ */
57
+ const buildToolInputSchema = (route) => {
58
+ const shape = {};
59
+ let hasParams = false;
60
+ let hasQuery = false;
61
+ let hasBody = false;
62
+ const paramNames = parsePath(route.path).paramNames;
63
+ if (paramNames.length > 0) {
64
+ hasParams = true;
65
+ const paramShape = {};
66
+ const explicitShape = route.pathParams ? readObjectShape(route.pathParams) : void 0;
67
+ for (const name of paramNames) paramShape[name] = explicitShape?.[name] ?? z.string();
68
+ shape["params"] = z.object(paramShape);
69
+ }
70
+ if (route.query) {
71
+ hasQuery = true;
72
+ shape["query"] = route.query.safeParse({}).success ? route.query.optional() : route.query;
73
+ }
74
+ if (route.body && !isVoidSchema(route.body)) {
75
+ hasBody = true;
76
+ shape["body"] = route.body.safeParse(void 0).success ? route.body.optional() : route.body;
77
+ }
25
78
  return {
26
- __brand: "TagSet",
27
- tags: normalized
79
+ shape: Object.keys(shape).length === 0 ? void 0 : shape,
80
+ hasParams,
81
+ hasQuery,
82
+ hasBody
28
83
  };
29
84
  };
85
+ const toJsonSchema = (route) => {
86
+ const { shape } = buildToolInputSchema(route);
87
+ const { $schema: _, ...schema } = z.toJSONSchema(z.object(shape ?? {}), {
88
+ io: "input",
89
+ unrepresentable: "any",
90
+ override: ({ jsonSchema }) => {
91
+ delete jsonSchema.brand;
92
+ }
93
+ });
94
+ return schema;
95
+ };
96
+ /**
97
+ * One {@link ToolDefinition} per route.
98
+ */
99
+ const buildToolDefinitions = (routes) => {
100
+ const entries = flattenRoutes(routes);
101
+ const names = deriveToolNames(entries.map(({ routeKey }) => ({
102
+ key: routeKey,
103
+ origin: "route"
104
+ })));
105
+ return entries.map(({ routeKey, route }) => ({
106
+ name: names.get(routeKey),
107
+ key: routeKey,
108
+ description: describeTool(route),
109
+ inputSchema: toJsonSchema(route)
110
+ }));
111
+ };
30
112
  //#endregion
31
113
  //#region src/tool-events.ts
32
114
  /**
115
+ * Where a streamed response keeps the routes it named under `tools`.
116
+ */
117
+ const STREAM_TOOLS = Symbol.for("kizuna.stream.tools");
118
+ const streamToolsOf = (response) => response !== null && typeof response === "object" ? response[STREAM_TOOLS] : void 0;
119
+ /**
33
120
  * The `{ params, query, body }` a route takes as a tool, as schemas, so the
34
121
  * stream events and the MCP endpoint agree on one shape.
35
122
  */
@@ -45,13 +132,30 @@ const toolInputShape = (route) => {
45
132
  return shape;
46
133
  };
47
134
  /**
48
- * What a route answers a tool call with, read from its `200`.
135
+ * The body of each `2xx` the route declares.
49
136
  */
50
137
  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;
138
+ const bodies = [];
139
+ let someSuccessHasNoBody = false;
140
+ for (const status of Object.keys(route.responses).map(Number).sort((left, right) => left - right)) {
141
+ if (!isSuccessStatus(status)) continue;
142
+ const response = route.responses[status];
143
+ if (response === void 0) continue;
144
+ const contentType = resolveResponseContentType(response);
145
+ if (isStreamResponse(response) || contentType !== void 0 && !isJsonMediaType(contentType)) {
146
+ someSuccessHasNoBody = true;
147
+ continue;
148
+ }
149
+ const body = resolveResponseBody(response);
150
+ if (body === void 0 || isVoidSchema(body)) {
151
+ someSuccessHasNoBody = true;
152
+ continue;
153
+ }
154
+ bodies.push(body);
155
+ }
156
+ if (bodies.length === 0) return void 0;
157
+ const output = bodies.length === 1 ? bodies[0] : z.union(bodies);
158
+ return someSuccessHasNoBody ? output.optional() : output;
55
159
  };
56
160
  /**
57
161
  * Server-sent events for the routes a model may call, to spread into a route's
@@ -78,6 +182,7 @@ const toolEvents = (tools) => {
78
182
  return z.object({
79
183
  ...identifier,
80
184
  name: z.literal(routeKey),
185
+ needsApproval: z.literal(true).optional(),
81
186
  ...Object.keys(input).length > 0 ? { input: z.object(input) } : {}
82
187
  });
83
188
  });
@@ -106,12 +211,25 @@ const toolEvents = (tools) => {
106
211
  * `k.routes` before a route is validated.
107
212
  */
108
213
  const expandStreamTools = (route, routeKey) => {
214
+ let namedAt;
109
215
  for (const [status, response] of Object.entries(route.responses)) {
110
216
  if (!isStreamResponse(response)) continue;
111
217
  const { tools } = response;
112
218
  if (tools === void 0) continue;
113
219
  const where = `Route "${routeKey}" declares tools on status ${status}`;
220
+ 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.`);
221
+ namedAt = status;
114
222
  if (isZodSchema(response.stream)) throw new Error(`${where} beside a single stream schema. Tool events are named, so name the other events too.`);
223
+ const toolEntries = flattenRoutes(tools);
224
+ deriveToolNames(toolEntries.map(({ routeKey: toolKey }) => ({
225
+ key: toolKey,
226
+ origin: "route"
227
+ })));
228
+ for (const { routeKey: toolKey, route: toolRoute } of toolEntries) {
229
+ if (toolOptionsOf(toolRoute) === void 0) throw new Error(`${where}, naming "${toolKey}", which does not declare \`tool\`. Declare it on that route.`);
230
+ const refusal = toolRefusal(toolRoute);
231
+ if (refusal !== void 0) throw new Error(`${where}, naming "${toolKey}", which cannot run as a tool: ${refusal}.`);
232
+ }
115
233
  const events = toolEvents(tools);
116
234
  const named = response.stream;
117
235
  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 +238,7 @@ const expandStreamTools = (route, routeKey) => {
120
238
  ...named,
121
239
  ...events
122
240
  };
241
+ mutable[STREAM_TOOLS] = tools;
123
242
  delete mutable.tools;
124
243
  }
125
244
  };
@@ -216,28 +335,124 @@ const validateRoutes = (routes, prefix) => {
216
335
  } else if (value && typeof value === "object") validateRoutes(value, fullKey);
217
336
  }
218
337
  };
219
- function tagRoutes(first, second, third) {
220
- if (isTagSet(first)) {
221
- if (third !== void 0) {
222
- const result = third;
223
- result[ROUTES_TAG] = second;
224
- validateRoutes(result);
225
- return result;
338
+ const isDeclared = (value) => typeof value === "object" && value !== null && ROUTES_GROUP in value;
339
+ const groupOf = (value) => isDeclared(value) ? value[ROUTES_GROUP] : void 0;
340
+ /**
341
+ * Throw on a grouped tree nested inside another. It belongs in `defineConfig`'s
342
+ * list.
343
+ */
344
+ const assertNoGroupInside = (routes, prefix) => {
345
+ for (const [key, value] of Object.entries(routes)) {
346
+ if (isRouteDefinition(value) || !value || typeof value !== "object") continue;
347
+ const fullKey = prefix ? `${prefix}.${key}` : key;
348
+ const group = groupOf(value);
349
+ if (group !== void 0 && group !== "") throw new Error(`"${fullKey}" was declared into the group ${group}, so its key comes from there. List it in defineConfig's \`routes\` instead of nesting it.`);
350
+ assertNoGroupInside(value, fullKey);
351
+ }
352
+ };
353
+ function groupRoutes(first, second) {
354
+ const routes = typeof first === "string" ? second : first;
355
+ assertNoGroupInside(routes);
356
+ routes[ROUTES_GROUP] = typeof first === "string" ? first : "";
357
+ validateRoutes(routes);
358
+ return routes;
359
+ }
360
+ /**
361
+ * Merge `source` into `target`, throwing when both hold the same key.
362
+ */
363
+ const mergeRoutes = (target, source, path) => {
364
+ for (const [key, value] of Object.entries(source)) {
365
+ const fullKey = path === "" ? key : `${path}.${key}`;
366
+ const existing = target[key];
367
+ if (existing === void 0) {
368
+ target[key] = value;
369
+ continue;
226
370
  }
227
- const result = second;
228
- validateRoutes(result);
229
- return result;
371
+ if (isRouteDefinition(existing) || isRouteDefinition(value)) throw new Error(`Two routes claim the key "${fullKey}". Rename one, or declare it into another group.`);
372
+ const merged = { ...existing };
373
+ mergeRoutes(merged, value, fullKey);
374
+ target[key] = merged;
230
375
  }
231
- if (typeof first === "string") {
232
- const result = second;
233
- result[ROUTES_TAG] = first;
234
- validateRoutes(result);
235
- return result;
376
+ };
377
+ /**
378
+ * The route tree a list of declared trees makes, each at its group's path.
379
+ */
380
+ const assembleRoutes = (declared) => {
381
+ const root = {};
382
+ for (const entry of declared) {
383
+ const routes = isDeclared(entry) ? entry : groupRoutes(entry);
384
+ const group = routes[ROUTES_GROUP];
385
+ let node = root;
386
+ let path = "";
387
+ for (const segment of group === "" ? [] : group.split(".")) {
388
+ path = path === "" ? segment : `${path}.${segment}`;
389
+ const existing = node[segment];
390
+ if (isRouteDefinition(existing)) throw new Error(`The route "${path}" sits where the group ${group} needs its key. Rename the route, or the group.`);
391
+ if (existing === void 0) node[segment] = {};
392
+ node = node[segment];
393
+ }
394
+ if (group !== "") node[ROUTES_GROUP] = group;
395
+ mergeRoutes(node, routes, path);
236
396
  }
237
- const result = first;
238
- validateRoutes(result);
239
- return result;
240
- }
397
+ return root;
398
+ };
399
+ //#endregion
400
+ //#region src/groups.ts
401
+ const isGroupSet = (value) => typeof value === "object" && value !== null && "__brand" in value && value.__brand === "GroupSet";
402
+ const collect = (declared, ancestors, into) => {
403
+ for (const [key, value] of Object.entries(declared)) {
404
+ if (key.includes(".")) throw new Error(`The group "${key}" has a dot in its key. Nest it under \`groups\` instead.`);
405
+ const options = typeof value === "string" ? { title: value } : value;
406
+ const parent = ancestors[ancestors.length - 1];
407
+ const path = parent === void 0 ? key : `${parent}.${key}`;
408
+ const lineage = [...ancestors, path];
409
+ into.set(path, {
410
+ path,
411
+ title: options.title,
412
+ ...options.description === void 0 ? {} : { description: options.description },
413
+ ...options.externalDocs === void 0 ? {} : { externalDocs: options.externalDocs },
414
+ lineage
415
+ });
416
+ if (options.groups) collect(options.groups, lineage, into);
417
+ }
418
+ };
419
+ /**
420
+ * Throw on two siblings with one title.
421
+ */
422
+ const assertUniqueTitles = (groups) => {
423
+ const owners = /* @__PURE__ */ new Map();
424
+ for (const group of groups.values()) {
425
+ const sibling = `${group.lineage[group.lineage.length - 2] ?? ""}\u0000${group.title}`;
426
+ const owner = owners.get(sibling);
427
+ if (owner !== void 0) throw new Error(`The groups "${owner}" and "${group.path}" share the title "${group.title}". Give each group its own title.`);
428
+ owners.set(sibling, group.path);
429
+ }
430
+ };
431
+ /**
432
+ * Declare the groups routes are filed under. A string is shorthand for
433
+ * `{ title }`.
434
+ *
435
+ * @example
436
+ * const groups = k.groups({
437
+ * workspace: {
438
+ * title: 'Workspace',
439
+ * groups: {
440
+ * members: 'Members',
441
+ * },
442
+ * },
443
+ * health: 'Health',
444
+ * });
445
+ */
446
+ const createGroups = (declared) => {
447
+ const groups = /* @__PURE__ */ new Map();
448
+ collect(declared, [], groups);
449
+ assertUniqueTitles(groups);
450
+ return {
451
+ __brand: "GroupSet",
452
+ declared,
453
+ groups
454
+ };
455
+ };
241
456
  //#endregion
242
457
  //#region src/permissions.ts
243
458
  const isPermissions = (value) => typeof value === "object" && value !== null && "__brand" in value && value.__brand === "Permissions";
@@ -577,7 +792,8 @@ const createJobRunner = (source, handlers, options) => {
577
792
  throwError: (response) => {
578
793
  throw new ResponseError(response);
579
794
  },
580
- jobs: tree
795
+ jobs: tree,
796
+ plugins: options?.plugins ?? {}
581
797
  }));
582
798
  };
583
799
  const runDetached = (jobKey, input, runAt) => {
@@ -657,7 +873,7 @@ var JobDispatchError = class extends Error {
657
873
  *
658
874
  * @example
659
875
  * export const pgBoss = (boss: PgBoss) =>
660
- * createJobTransport({
876
+ * defineJobTransport({
661
877
  * name: 'pg-boss',
662
878
  * supports: {
663
879
  * retry: true,
@@ -686,8 +902,8 @@ var JobDispatchError = class extends Error {
686
902
  * },
687
903
  * });
688
904
  */
689
- const createJobTransport = (definition) => {
690
- if (!definition.name) throw new Error("createJobTransport needs a `name`.");
905
+ const defineJobTransport = (definition) => {
906
+ if (!definition.name) throw new Error("defineJobTransport needs a `name`.");
691
907
  return {
692
908
  ...definition,
693
909
  supports: definition.supports ?? {},
@@ -950,46 +1166,132 @@ const rawResponse = (response) => ({
950
1166
  });
951
1167
  const isRawResponse = (value) => typeof value === "object" && value !== null && RAW_RESPONSE in value;
952
1168
  //#endregion
953
- //#region src/plugin-server.ts
954
- /**
955
- * The plugin routes `assembleApi` stashed on the api. Empty without plugins, so
956
- * an adapter can mount it unconditionally.
957
- */
958
- const pluginRoutesOf = (api) => api[PLUGIN_ROUTES_META_KEY] ?? {};
959
- /**
960
- * Their handlers, keyed to match {@link pluginRoutesOf}.
961
- */
962
- const pluginRouterOf = (api) => {
963
- const servers = api[PLUGIN_SERVERS_META_KEY];
964
- const router = {};
965
- for (const [pluginKey, served] of Object.entries(servers ?? {})) router[pluginKey] = served.router;
966
- return router;
967
- };
968
- /**
969
- * What each plugin exports, for the adapter to pass into the pipeline as the
970
- * handler args' `plugins`.
971
- */
972
- const pluginExportsOf = (api) => {
973
- const servers = api[PLUGIN_SERVERS_META_KEY];
974
- const exported = {};
975
- for (const [pluginKey, served] of Object.entries(servers ?? {})) if (served.exports !== void 0) exported[pluginKey] = served.exports;
976
- return exported;
977
- };
978
- /**
979
- * Run every plugin's `serve`. Deferred until the api object exists, because
980
- * `serve` receives it.
981
- */
982
- const resolvePluginServers = (plugins, api) => {
983
- const resolved = {};
984
- for (const [pluginKey, declaration] of Object.entries(plugins ?? {})) {
985
- const served = declaration.serve(declaration.props, api);
986
- for (const routeKey of Object.keys(declaration.routes)) {
987
- if (routeKey in served.router) continue;
988
- throw new Error(`Plugin '${pluginKey}' declares the route '${routeKey}' but its \`serve\` does not handle it.`);
1169
+ //#region src/tool-runner.ts
1170
+ const DECLINED = "Declined, so nothing ran.";
1171
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1172
+ const detailOf = (status, body) => isRecord(body) && typeof body["detail"] === "string" ? body["detail"] : `The route answered ${status}.`;
1173
+ const callInput = (route, parsed) => {
1174
+ const input = {};
1175
+ if (parsePath(route.path).paramNames.length > 0) input["params"] = parsed.params;
1176
+ if (route.query) input["query"] = parsed.query;
1177
+ if (route.body && !isVoidSchema(route.body)) input["body"] = parsed.body;
1178
+ return Object.keys(input).length > 0 ? input : void 0;
1179
+ };
1180
+ const definitionsCache = /* @__PURE__ */ new WeakMap();
1181
+ const definitionsFor = (tools) => {
1182
+ const cached = definitionsCache.get(tools);
1183
+ if (cached) return cached;
1184
+ const built = buildToolDefinitions(tools);
1185
+ definitionsCache.set(tools, built);
1186
+ return built;
1187
+ };
1188
+ /**
1189
+ * Bind a response's tools to the request streaming it.
1190
+ */
1191
+ const createStreamTools = (tools, pipeline) => {
1192
+ const definitions = definitionsFor(tools);
1193
+ const entries = new Map(flattenRoutes(tools).map((entry) => [entry.routeKey, entry]));
1194
+ const keysByName = new Map(definitions.map((definition) => [definition.name, definition.key]));
1195
+ const namesByKey = new Map(definitions.map((definition) => [definition.key, definition.name]));
1196
+ const answered = (call, status, body) => {
1197
+ const content = JSON.stringify({
1198
+ status,
1199
+ body
1200
+ });
1201
+ return status < 400 ? {
1202
+ call,
1203
+ state: "done",
1204
+ status,
1205
+ body,
1206
+ content,
1207
+ isError: false
1208
+ } : {
1209
+ call,
1210
+ state: "failed",
1211
+ status,
1212
+ body,
1213
+ content,
1214
+ isError: true
1215
+ };
1216
+ };
1217
+ async function* run(call, options = {}) {
1218
+ const key = keysByName.get(call.name) ?? call.name;
1219
+ const entry = entries.get(key);
1220
+ const modelCall = {
1221
+ id: call.id,
1222
+ name: namesByKey.get(key) ?? call.name,
1223
+ input: call.input ?? {}
1224
+ };
1225
+ if (entry === void 0) return answered(modelCall, 404, problemDetails(404, `No tool named "${call.name}". Call one of: ${[...keysByName.keys()].join(", ")}.`));
1226
+ const failed = (status, body) => ({
1227
+ event: "tool_error",
1228
+ data: {
1229
+ id: call.id,
1230
+ name: key,
1231
+ message: detailOf(status, body)
1232
+ }
1233
+ });
1234
+ const input = isRecord(call.input) ? call.input : {};
1235
+ const params = Object.fromEntries(Object.entries(isRecord(input["params"]) ? input["params"] : {}).map(([name, value]) => [name, String(value)]));
1236
+ const validation = validateRequest(entry.route, {
1237
+ params,
1238
+ query: input["query"] ?? {},
1239
+ body: input["body"],
1240
+ headers: pipeline.headers
1241
+ });
1242
+ if (!validation.ok) {
1243
+ const rendered = pipeline.render(validation.error);
1244
+ yield failed(rendered.status, rendered.body);
1245
+ return answered(modelCall, rendered.status, rendered.body);
989
1246
  }
990
- resolved[pluginKey] = served;
1247
+ const validated = callInput(entry.route, validation.parsed);
1248
+ const needsApproval = toolOptionsOf(entry.route)?.needsApproval === true;
1249
+ const waiting = needsApproval && options.approved === void 0;
1250
+ yield {
1251
+ event: "tool_call",
1252
+ data: {
1253
+ id: call.id,
1254
+ name: key,
1255
+ ...waiting ? { needsApproval: true } : {},
1256
+ ...validated === void 0 ? {} : { input: validated }
1257
+ }
1258
+ };
1259
+ if (waiting) return {
1260
+ call: modelCall,
1261
+ state: "needs-approval"
1262
+ };
1263
+ if (needsApproval && options.approved === false) {
1264
+ yield {
1265
+ event: "tool_error",
1266
+ data: {
1267
+ id: call.id,
1268
+ name: key,
1269
+ message: DECLINED
1270
+ }
1271
+ };
1272
+ return {
1273
+ call: modelCall,
1274
+ state: "declined",
1275
+ content: DECLINED,
1276
+ isError: true
1277
+ };
1278
+ }
1279
+ const { status, body } = await pipeline.invoke(entry, validation.parsed, params);
1280
+ if (status >= 400) yield failed(status, body);
1281
+ else yield {
1282
+ event: "tool_result",
1283
+ data: {
1284
+ id: call.id,
1285
+ name: key,
1286
+ ...body === void 0 ? {} : { output: body }
1287
+ }
1288
+ };
1289
+ return answered(modelCall, status, body);
991
1290
  }
992
- return resolved;
1291
+ return {
1292
+ definitions,
1293
+ run
1294
+ };
993
1295
  };
994
1296
  //#endregion
995
1297
  //#region src/adapter.ts
@@ -1067,7 +1369,10 @@ const HANDLER_ARG_KEYS = [
1067
1369
  "throwError",
1068
1370
  "auth",
1069
1371
  "requestContext",
1070
- "plugins"
1372
+ "plugins",
1373
+ "tools",
1374
+ "rawBody",
1375
+ "lastEventId"
1071
1376
  ];
1072
1377
  /**
1073
1378
  * The adapter's own context, with kizuna's arguments removed.
@@ -1077,6 +1382,25 @@ const assertNoDuplicateRoutes = (routes, pluginRoutes = {}) => {
1077
1382
  assertNoPathCollisions([...routeClaims(routes), ...routeClaims(pluginRoutes, "Plugin route")]);
1078
1383
  };
1079
1384
  /**
1385
+ * Each plugin's router, built from the handlers its routes carry, and its
1386
+ * exports. A plugin route without a handler throws, since nothing would answer
1387
+ * it.
1388
+ */
1389
+ const pluginServers = (plugins) => {
1390
+ const servers = {};
1391
+ for (const [slug, plugin] of Object.entries(plugins ?? {})) {
1392
+ for (const [routeKey, route] of Object.entries(plugin.routes)) {
1393
+ if (route[HANDLER] !== void 0) continue;
1394
+ throw new Error(`Plugin '${slug}' declares the route '${routeKey}' without a handler. Declare it with \`route(...).handler(...)\`.`);
1395
+ }
1396
+ servers[slug] = {
1397
+ router: routerFromRoutes(plugin.routes),
1398
+ exports: plugin.exports
1399
+ };
1400
+ }
1401
+ return servers;
1402
+ };
1403
+ /**
1080
1404
  * Brand an api's routes with the parts that serve them, for the adapter to read back when mounting.
1081
1405
  */
1082
1406
  const assembleApi = (contract, parts) => {
@@ -1094,17 +1418,17 @@ const assembleApi = (contract, parts) => {
1094
1418
  [PLUGIN_ROUTES_META_KEY]: pluginRoutes,
1095
1419
  [CONTRACT_META]: contract
1096
1420
  };
1097
- api[PLUGIN_SERVERS_META_KEY] = resolvePluginServers(contract.plugins, api);
1421
+ api[PLUGIN_SERVERS_META_KEY] = pluginServers(contract.plugins);
1098
1422
  return api;
1099
1423
  };
1100
1424
  /**
1101
1425
  * The endpoints jobs are served on, in the {@link Routes} shape the request
1102
- * pipeline takes.
1426
+ * pipeline takes. None when the jobs run in process.
1103
1427
  */
1104
- const jobRoutes = (meta) => ({
1428
+ const jobRoutes = (meta) => meta.config?.mode === "in-process" ? {} : {
1105
1429
  [DISPATCH_ROUTE_KEY]: dispatchRoute(meta),
1106
1430
  [RUN_ROUTE_KEY]: runRoute(meta)
1107
- });
1431
+ };
1108
1432
  /**
1109
1433
  * Their handlers, in the {@link Router} shape the request pipeline takes.
1110
1434
  */
@@ -1249,6 +1573,7 @@ const boundJobKeys = (meta) => {
1249
1573
  * header, `undefined` when absent. For guards and request context resolvers on
1250
1574
  * adapters that expose raw header records.
1251
1575
  */
1576
+ const streamsEvents = (route) => Object.values(route.responses).some((response) => isStreamResponse(response) && streamContentType(response) === "text/event-stream");
1252
1577
  const getHeaderValue = (value) => {
1253
1578
  if (typeof value === "string") return value;
1254
1579
  if (Array.isArray(value) && typeof value[0] === "string") return value[0];
@@ -1540,6 +1865,20 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1540
1865
  headers: request.headers,
1541
1866
  body: void 0
1542
1867
  };
1868
+ let rawBody;
1869
+ if (route.rawBody === true) {
1870
+ rawBody = request.readRawBody === void 0 ? void 0 : await request.readRawBody(route);
1871
+ if (rawBody === void 0) {
1872
+ const error = /* @__PURE__ */ new Error(`[kizuna] ${routeKey} needs the raw body, but it was parsed before kizuna saw it. On Express, mount kizuna before express.json(), or pass \`verify: keepRawBody\` to it.`);
1873
+ console.error(error.message);
1874
+ return {
1875
+ kind: "handler-error",
1876
+ routeKey,
1877
+ route,
1878
+ error
1879
+ };
1880
+ }
1881
+ }
1543
1882
  const acceptHeader = raw.headers["accept"];
1544
1883
  if (!isAcceptable(acceptHeader, route)) return { kind: "not-acceptable" };
1545
1884
  if (route.body && !isVoidSchema(route.body)) {
@@ -1554,7 +1893,7 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1554
1893
  received
1555
1894
  };
1556
1895
  try {
1557
- raw.body = await request.readBody(route);
1896
+ raw.body = rawBody !== void 0 ? parseBodyText(rawBody, route) : await request.readBody(route);
1558
1897
  } catch {
1559
1898
  return {
1560
1899
  kind: "invalid-body",
@@ -1573,18 +1912,85 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1573
1912
  issues: formatted.issues
1574
1913
  };
1575
1914
  }
1576
- const handler = resolveHandler(router, routeKey);
1915
+ return invokeRoute({
1916
+ resolved,
1917
+ parsed: validation.parsed,
1918
+ handler: resolveHandler(router, routeKey),
1919
+ request,
1920
+ routes,
1921
+ definition,
1922
+ handlerContext: () => definition.buildHandlerContext(request, responseContext),
1923
+ guards,
1924
+ schemes,
1925
+ contextResolvers,
1926
+ pluginExports,
1927
+ jobRunner,
1928
+ responseValidation,
1929
+ rawBody
1930
+ });
1931
+ };
1932
+ const streamToolsOfRoute = (route) => {
1933
+ for (const response of Object.values(route.responses)) {
1934
+ const tools = streamToolsOf(response);
1935
+ if (tools !== void 0) return tools;
1936
+ }
1937
+ };
1938
+ /**
1939
+ * What a tool call reports: the status and body HTTP would have sent.
1940
+ */
1941
+ const toolAnswer = (result) => {
1942
+ if (result.kind === "raw-response") return {
1943
+ status: 500,
1944
+ body: problemDetails(500, "This route answers with a raw response, and a tool answers with a JSON body.")
1945
+ };
1946
+ if (result.kind === "handler-error") console.error(`[kizuna] tool "${result.routeKey}" threw:`, result.error);
1947
+ const rendered = renderJsonResult(result);
1948
+ return {
1949
+ status: rendered.status,
1950
+ body: rendered.body
1951
+ };
1952
+ };
1953
+ /**
1954
+ * Each call runs its route as a request of its own, from the same caller.
1955
+ */
1956
+ const streamToolsFor = (tools, invocation, handlerContext) => createStreamTools(tools, {
1957
+ headers: invocation.request.headers,
1958
+ invoke: async (entry, parsed, params) => toolAnswer(await invokeRoute({
1959
+ ...invocation,
1960
+ resolved: {
1961
+ routeKey: entry.routeKey,
1962
+ route: entry.route,
1963
+ params
1964
+ },
1965
+ parsed,
1966
+ handler: entry.route[HANDLER],
1967
+ handlerContext: () => handlerContext
1968
+ })),
1969
+ render: (failure) => {
1970
+ const formatted = formatValidationError(failure);
1971
+ return toolAnswer({
1972
+ kind: "validation-failed",
1973
+ stage: failure.stage,
1974
+ detail: formatted.detail,
1975
+ issues: formatted.issues
1976
+ });
1977
+ }
1978
+ });
1979
+ const invokeRoute = async (invocation) => {
1980
+ const { resolved, parsed, request, routes, definition, guards, schemes, contextResolvers, pluginExports, jobRunner, responseValidation } = invocation;
1981
+ const { routeKey, route, params } = resolved;
1982
+ const handler = invocation.handler;
1577
1983
  if (typeof handler !== "function") return {
1578
1984
  kind: "no-handler",
1579
1985
  routeKey
1580
1986
  };
1581
1987
  try {
1582
- const handlerContext = await definition.buildHandlerContext(request, responseContext);
1988
+ const handlerContext = await invocation.handlerContext();
1583
1989
  const requestContext = {};
1584
1990
  if (contextResolvers) for (const [name, resolver] of Object.entries(contextResolvers)) requestContext[name] = await resolver({
1585
1991
  ...handlerContext,
1586
1992
  params,
1587
- headers: raw.headers
1993
+ headers: request.headers
1588
1994
  });
1589
1995
  const hasRequestContext = Object.keys(requestContext).length > 0;
1590
1996
  const securityContext = {};
@@ -1636,13 +2042,17 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1636
2042
  const throwError = (response) => {
1637
2043
  throw new ResponseError(response);
1638
2044
  };
2045
+ const tools = streamToolsOfRoute(route);
1639
2046
  const handlerResult = await handler({
1640
- params: validation.parsed.params,
1641
- query: validation.parsed.query,
1642
- body: validation.parsed.body,
1643
- headers: validation.parsed.headers,
2047
+ params: parsed.params,
2048
+ query: parsed.query,
2049
+ body: parsed.body,
2050
+ headers: parsed.headers,
2051
+ ...route.rawBody === true ? { rawBody: invocation.rawBody } : {},
2052
+ ...streamsEvents(route) ? { lastEventId: getHeaderValue(invocation.request.headers["last-event-id"]) } : {},
1644
2053
  throwError,
1645
2054
  ...handlerContext,
2055
+ ...tools ? { tools: streamToolsFor(tools, invocation, handlerContext) } : {},
1646
2056
  ...jobRunner ? { jobs: jobRunner } : {},
1647
2057
  ...hasRequestContext ? { requestContext } : {},
1648
2058
  ...Object.keys(securityContext).length > 0 ? { auth: securityContext } : {},
@@ -1688,7 +2098,7 @@ const routedPipeline = async (resolved, request, routes, router, definition, res
1688
2098
  };
1689
2099
  }
1690
2100
  };
1691
- const createAdapter = (definition) => ({
2101
+ const defineAdapter = (definition) => ({
1692
2102
  handle: async ({ routes, router, request, responseContext, guards, schemes, requestContext, pluginExports, jobs, basePath, responseValidation }) => {
1693
2103
  const result = await runPipeline(request, routes, router, definition, responseContext, guards, schemes, requestContext, pluginExports, jobs, basePath, responseValidation);
1694
2104
  return definition.respond(result, responseContext);
@@ -1827,6 +2237,14 @@ const formDataToObject = (form) => {
1827
2237
  return result;
1828
2238
  };
1829
2239
  /**
2240
+ * Parse a body from its text, the way {@link parseFetchBody} would, for a route
2241
+ * whose text core already read.
2242
+ */
2243
+ const parseBodyText = (text, route) => {
2244
+ if (route.contentType === "application/x-www-form-urlencoded") return Object.fromEntries(new URLSearchParams(text));
2245
+ return text.length > 0 ? JSON.parse(text) : void 0;
2246
+ };
2247
+ /**
1830
2248
  * Content-type-aware body parser for Web Fetch `Request`.
1831
2249
  *
1832
2250
  * Reusable across any Fetch-based adapter.
@@ -1850,4 +2268,4 @@ const headersToObject = (headers) => {
1850
2268
  return result;
1851
2269
  };
1852
2270
  //#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 };
2271
+ export { dispatchSucceeded as $, renderJsonResult as A, sortFlattenedRoutes as B, headersToObject as C, jobRunnerFrom as D, jobRoutes as E, isRawResponse as F, defineJobTransport as G, requiresDenial as H, rawResponse as I, jobFnAt as J, JobInputError as K, assertNoPathCollisions as L, runHandler as M, runRoute as N, parseBodyText as O, warnUnsupportedJobOptions as P, dispatchDueJobs as Q, routeClaims as R, guardDenyFor as S, toolRefusal as St, jobRouter as T, withPermissions as U, insufficientScope as V, JobDispatchError as W, DispatchFailedSchema as X, ResponseError as Y, DispatchResultSchema as Z, defineAdapter as _, buildToolDefinitions as _t, HANDLER_ARG_KEYS as a, getStatusText as at, extractCredential as b, selectToolRoutes as bt, ROUTER_META as c, isPermissions as ct, SCHEMES_META as d, createGroups as dt, dueJobs as et, adapterContextOf as f, isGroupSet as ft, contractOf as g, toolEvents as gt, boundJobKeys as h, expandStreamTools as ht, GUARD_SCHEMA_META as i, STATUS_TITLES as it, routerFromRoutes as j, parseFetchBody as k, RUN_ROUTE_KEY as l, isRoles as lt, bearerChallenge as m, groupRoutes as mt, DISPATCH_ROUTE_KEY as n, problemDetails as nt, JOBS_META as o, createPermissions as ot, assembleApi as p, assembleRoutes as pt, createJobRunner as q, GUARDS_META as r, problemFromBody as rt, REQUEST_CONTEXT_META as s, createRoles as st, API_META as t, failedJobs as tt, ResponseValidationError as u, permissionNames as ut, dispatchHandler as v, buildToolInputSchema as vt, isGuardDenial as w, getHeaderValue as x, toolOptionsOf as xt, dispatchRoute as y, describeTool as yt, matchRoute as z };