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.
- package/README.md +3 -2
- package/dist/{adapter-CZW-unqX.mjs → adapter-BSqNrxhq.mjs} +522 -104
- package/dist/adapter-C3WYdSfx.d.cts +2754 -0
- package/dist/{adapter-DDR_yo9L.cjs → adapter-ClaFZoab.cjs} +638 -196
- package/dist/adapter-D4bTPElA.d.mts +2754 -0
- package/dist/adapter.cjs +37 -29
- package/dist/adapter.d.cts +3 -5
- package/dist/adapter.d.mts +3 -5
- package/dist/adapter.mjs +5 -5
- package/dist/{error-response-C8Ragjcd.cjs → error-response-C9ymqSU4.cjs} +25 -5
- package/dist/{error-response-C839d8By.mjs → error-response-CNQaKVYd.mjs} +20 -6
- package/dist/{security-scheme-BrszwGD5.d.cts → error-response-NoOGdh8H.d.mts} +151 -24
- package/dist/{security-scheme-D3nb4XKj.d.mts → error-response-YbkRMKno.d.cts} +151 -24
- package/dist/generator.cjs +190 -95
- package/dist/generator.d.cts +189 -28
- package/dist/generator.d.mts +189 -28
- package/dist/generator.mjs +151 -60
- package/dist/index.cjs +159 -84
- package/dist/index.d.cts +193 -253
- package/dist/index.d.mts +193 -253
- package/dist/index.mjs +112 -38
- package/dist/jobs-entry.cjs +12 -11
- package/dist/jobs-entry.d.cts +1 -1
- package/dist/jobs-entry.d.mts +1 -1
- package/dist/jobs-entry.mjs +3 -2
- package/dist/plugin-Dw-yCjTY.cjs +233 -0
- package/dist/{cache-CLN5y0Xp.mjs → plugin-server-BztlE1fz.mjs} +188 -49
- package/dist/{cache-BgohRj0i.cjs → plugin-server-kUsK7thV.cjs} +238 -93
- package/dist/plugin-xxCxibmu.mjs +138 -0
- package/dist/plugin.cjs +8 -72
- package/dist/plugin.d.cts +3 -3
- package/dist/plugin.d.mts +3 -3
- package/dist/plugin.mjs +2 -68
- package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-B9hMFQ9N.d.cts} +1 -1
- package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-CfBVsqIk.d.mts} +1 -1
- package/dist/{schemas-C56no6bv.cjs → schemas-DNPVDvkd.cjs} +28 -1
- package/dist/{schemas-CJQcc97N.mjs → schemas-HW2FDsvz.mjs} +23 -2
- package/dist/schemas.cjs +3 -2
- package/dist/schemas.d.cts +24 -3
- package/dist/schemas.d.mts +24 -3
- package/dist/schemas.mjs +3 -3
- package/package.json +1 -1
- package/src/adapter.ts +245 -29
- package/src/api-definition.ts +12 -16
- package/src/api.ts +7 -3
- package/src/brand.ts +29 -0
- package/src/config.ts +51 -10
- package/src/configured.ts +13 -6
- package/src/define-config.ts +118 -39
- package/src/generator.ts +363 -46
- package/src/group-routes.ts +106 -0
- package/src/groups.ts +140 -0
- package/src/handler-pipeline.ts +78 -19
- package/src/index.ts +15 -6
- package/src/job-runner.ts +5 -0
- package/src/job-transport.ts +3 -3
- package/src/job.ts +8 -6
- package/src/jobs-dev-runner.ts +6 -0
- package/src/jobs.ts +61 -8
- package/src/kizuna.ts +56 -33
- package/src/plugin-server.ts +129 -19
- package/src/plugin.ts +269 -127
- package/src/routes.ts +80 -32
- package/src/schemas.ts +1 -0
- package/src/tool-answer.ts +21 -0
- package/src/tool-definitions.ts +166 -0
- package/src/tool-events.ts +90 -18
- package/src/tool-records.ts +11 -3
- package/src/tool-runner.ts +298 -0
- package/src/types.ts +90 -24
- package/src/zod-internals.ts +22 -5
- package/src/zod-meta.ts +7 -2
- package/dist/adapter-BGfMqEkM.d.cts +0 -563
- package/dist/adapter-Ci3cfcoT.d.mts +0 -563
- package/dist/api-definition-BHnh15zD.d.mts +0 -803
- package/dist/api-definition-DQj-ewHy.d.cts +0 -803
- package/dist/error-response-BBGSdgYw.d.mts +0 -67
- package/dist/error-response-Do38sr-9.d.cts +0 -67
- package/dist/plugin-Cz0kn6Lk.d.mts +0 -830
- package/dist/plugin-DhKvx_T0.d.cts +0 -830
- package/src/tags.ts +0 -67
package/src/routes.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { z } from 'zod';
|
|
2
|
-
import {
|
|
2
|
+
import { ROUTES_GROUP, type Routes, type RouteDefinition, type ResponseDefinition } from './types.js';
|
|
3
3
|
import { isRouteDefinition } from './handler-pipeline.js';
|
|
4
|
-
import { type TagSet, type TagKeysOf, isTagSet } from './tags.js';
|
|
5
4
|
import { findCoercedSchemaPath, readObjectShape, resolveBaseType } from './zod-internals.js';
|
|
6
5
|
import { resolveCoercionPlans } from './coercion.js';
|
|
7
6
|
import { parsePath, type PathParamsCheck } from './path-params.js';
|
|
@@ -125,38 +124,87 @@ const validateRoutes = (routes: Routes, prefix?: string): void => {
|
|
|
125
124
|
}
|
|
126
125
|
};
|
|
127
126
|
|
|
127
|
+
const isDeclared = (value: unknown): boolean => typeof value === 'object' && value !== null && ROUTES_GROUP in value;
|
|
128
|
+
|
|
129
|
+
const groupOf = (value: unknown): string | undefined =>
|
|
130
|
+
isDeclared(value) ? (value as Record<typeof ROUTES_GROUP, string>)[ROUTES_GROUP] : undefined;
|
|
131
|
+
|
|
128
132
|
/**
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
* tag is stamped onto every route in the group.
|
|
133
|
+
* Throw on a grouped tree nested inside another. It belongs in `defineConfig`'s
|
|
134
|
+
* list.
|
|
132
135
|
*/
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
if (isTagSet(first)) {
|
|
143
|
-
if (third !== undefined) {
|
|
144
|
-
const result = third;
|
|
145
|
-
(result as Record<typeof ROUTES_TAG, string>)[ROUTES_TAG] = second as string;
|
|
146
|
-
validateRoutes(result);
|
|
147
|
-
return result;
|
|
136
|
+
const assertNoGroupInside = (routes: Routes, prefix?: string): void => {
|
|
137
|
+
for (const [key, value] of Object.entries(routes)) {
|
|
138
|
+
if (isRouteDefinition(value) || !value || typeof value !== 'object') continue;
|
|
139
|
+
const fullKey = prefix ? `${prefix}.${key}` : key;
|
|
140
|
+
const group = groupOf(value);
|
|
141
|
+
if (group !== undefined && group !== '') {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`"${fullKey}" was declared into the group ${group}, so its key comes from there. List it in defineConfig's \`routes\` instead of nesting it.`
|
|
144
|
+
);
|
|
148
145
|
}
|
|
149
|
-
|
|
150
|
-
validateRoutes(result);
|
|
151
|
-
return result;
|
|
152
|
-
}
|
|
153
|
-
if (typeof first === 'string') {
|
|
154
|
-
const result = second as Routes;
|
|
155
|
-
(result as Record<typeof ROUTES_TAG, string>)[ROUTES_TAG] = first;
|
|
156
|
-
validateRoutes(result);
|
|
157
|
-
return result;
|
|
146
|
+
assertNoGroupInside(value as Routes, fullKey);
|
|
158
147
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Validate a tree of routes and stamp its group's path, `''` for none.
|
|
152
|
+
*/
|
|
153
|
+
export function groupRoutes<const T extends Routes>(routes: T & PathParamsCheck<T>): T;
|
|
154
|
+
export function groupRoutes<const T extends Routes>(group: string, routes: T & PathParamsCheck<T>): T;
|
|
155
|
+
export function groupRoutes(first: string | Routes, second?: Routes): Routes {
|
|
156
|
+
const routes = typeof first === 'string' ? second! : first;
|
|
157
|
+
assertNoGroupInside(routes);
|
|
158
|
+
(routes as Record<typeof ROUTES_GROUP, string>)[ROUTES_GROUP] = typeof first === 'string' ? first : '';
|
|
159
|
+
validateRoutes(routes);
|
|
160
|
+
return routes;
|
|
162
161
|
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Merge `source` into `target`, throwing when both hold the same key.
|
|
165
|
+
*/
|
|
166
|
+
const mergeRoutes = (target: Routes, source: Routes, path: string): void => {
|
|
167
|
+
for (const [key, value] of Object.entries(source)) {
|
|
168
|
+
const fullKey = path === '' ? key : `${path}.${key}`;
|
|
169
|
+
const existing = target[key];
|
|
170
|
+
if (existing === undefined) {
|
|
171
|
+
target[key] = value;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (isRouteDefinition(existing) || isRouteDefinition(value)) {
|
|
175
|
+
throw new Error(`Two routes claim the key "${fullKey}". Rename one, or declare it into another group.`);
|
|
176
|
+
}
|
|
177
|
+
// A spread keeps the group symbol.
|
|
178
|
+
const merged: Routes = {
|
|
179
|
+
...existing,
|
|
180
|
+
};
|
|
181
|
+
mergeRoutes(merged, value as Routes, fullKey);
|
|
182
|
+
target[key] = merged;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The route tree a list of declared trees makes, each at its group's path.
|
|
188
|
+
*/
|
|
189
|
+
export const assembleRoutes = (declared: readonly Routes[]): Routes => {
|
|
190
|
+
const root: Routes = {};
|
|
191
|
+
for (const entry of declared) {
|
|
192
|
+
// A plain object is routes in no group.
|
|
193
|
+
const routes = isDeclared(entry) ? entry : groupRoutes(entry);
|
|
194
|
+
const group = (routes as Record<typeof ROUTES_GROUP, string>)[ROUTES_GROUP];
|
|
195
|
+
let node = root;
|
|
196
|
+
let path = '';
|
|
197
|
+
for (const segment of group === '' ? [] : group.split('.')) {
|
|
198
|
+
path = path === '' ? segment : `${path}.${segment}`;
|
|
199
|
+
const existing = node[segment];
|
|
200
|
+
if (isRouteDefinition(existing)) {
|
|
201
|
+
throw new Error(`The route "${path}" sits where the group ${group} needs its key. Rename the route, or the group.`);
|
|
202
|
+
}
|
|
203
|
+
if (existing === undefined) node[segment] = {};
|
|
204
|
+
node = node[segment] as Routes;
|
|
205
|
+
}
|
|
206
|
+
if (group !== '') (node as Record<typeof ROUTES_GROUP, string>)[ROUTES_GROUP] = group;
|
|
207
|
+
mergeRoutes(node, routes, path);
|
|
208
|
+
}
|
|
209
|
+
return root;
|
|
210
|
+
};
|
package/src/schemas.ts
CHANGED
|
@@ -2,3 +2,4 @@ export { ProblemDetailsSchema } from './error-response.js';
|
|
|
2
2
|
export { ProtectedResourceMetadataSchema } from './protected-resource-metadata.js';
|
|
3
3
|
export { ValidationErrorSchema, type ValidationError, type ValidationErrorFor, type ValidationIssueCode } from './validation-error.js';
|
|
4
4
|
export { BinarySchema, FileSchema } from './binary.js';
|
|
5
|
+
export { ToolAnswerSchema } from './tool-answer.js';
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The person's answer to a call that needs approval, for a route's body.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* body: z.object({
|
|
9
|
+
* prompt: z.string(),
|
|
10
|
+
* answer: ToolAnswerSchema.optional(),
|
|
11
|
+
* }),
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export const ToolAnswerSchema = z.object({
|
|
15
|
+
call: z.object({
|
|
16
|
+
id: z.string(),
|
|
17
|
+
name: z.string(),
|
|
18
|
+
input: z.unknown().optional(),
|
|
19
|
+
}),
|
|
20
|
+
approved: z.boolean(),
|
|
21
|
+
});
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { RouteDefinition, RouteToolOptions, Routes } from './types.js';
|
|
3
|
+
import { flattenRoutes, type FlattenedRoute } from './handler-pipeline.js';
|
|
4
|
+
import { parsePath } from './path-params.js';
|
|
5
|
+
import { resolveSecurityRequirements } from './security-scheme.js';
|
|
6
|
+
import { routeStreams } from './stream.js';
|
|
7
|
+
import { deriveToolNames } from './tool-name.js';
|
|
8
|
+
import { isVoidSchema, readObjectShape } from './zod-internals.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* What a route says about publishing itself, or `undefined` when it says
|
|
12
|
+
* nothing.
|
|
13
|
+
*/
|
|
14
|
+
export const toolOptionsOf = (route: RouteDefinition): RouteToolOptions | undefined => {
|
|
15
|
+
if (route.tool === undefined || route.tool === false) return undefined;
|
|
16
|
+
return route.tool === true ? {} : route.tool;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Why a route cannot run as a tool, or `undefined` when it can.
|
|
21
|
+
*/
|
|
22
|
+
export const toolRefusal = (route: RouteDefinition): string | undefined => {
|
|
23
|
+
if (route.hidden === true) return 'it is hidden, and a hidden route never publishes';
|
|
24
|
+
if (route.contentType !== undefined && route.contentType !== 'application/json') {
|
|
25
|
+
return `it takes a ${route.contentType} body, and tool input is JSON`;
|
|
26
|
+
}
|
|
27
|
+
if (routeStreams(route)) return 'it streams, and a tool result is one value';
|
|
28
|
+
return undefined;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The routes a model may call: the ones that declared `tool`, less the ones
|
|
33
|
+
* whose shape a tool call cannot carry.
|
|
34
|
+
*/
|
|
35
|
+
export const selectToolRoutes = (routes: FlattenedRoute[]): FlattenedRoute[] =>
|
|
36
|
+
routes.filter(({ route }) => toolOptionsOf(route) !== undefined && toolRefusal(route) === undefined);
|
|
37
|
+
|
|
38
|
+
const describeRoles = (route: RouteDefinition): string | undefined =>
|
|
39
|
+
route.roles !== undefined && route.roles.length > 0 ? `Roles: ${route.roles.join(', ')}` : undefined;
|
|
40
|
+
|
|
41
|
+
const describeRequires = (route: RouteDefinition): string | undefined => {
|
|
42
|
+
const requires = route.requires;
|
|
43
|
+
if (requires === undefined) return undefined;
|
|
44
|
+
const names = Object.entries(requires).flatMap(([resource, verbs]) => verbs.map((verb) => `${resource}:${verb}`));
|
|
45
|
+
return names.length > 0 ? `Permissions: ${names.join(', ')}` : undefined;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What a model reads before it calls the route.
|
|
50
|
+
*/
|
|
51
|
+
export const describeTool = (route: RouteDefinition): string => {
|
|
52
|
+
const parts: string[] = [];
|
|
53
|
+
const declared = toolOptionsOf(route)?.description;
|
|
54
|
+
if (declared) parts.push(declared);
|
|
55
|
+
else if (route.summary) parts.push(route.summary);
|
|
56
|
+
if (route.description) parts.push(route.description);
|
|
57
|
+
if (parts.length === 0) parts.push(`${route.method} ${route.path}`);
|
|
58
|
+
parts.push(`\nHTTP: ${route.method} ${route.path}`);
|
|
59
|
+
|
|
60
|
+
const requirements = resolveSecurityRequirements(route);
|
|
61
|
+
if (requirements.length > 0) {
|
|
62
|
+
parts.push(`Requires: ${requirements.map(({ scheme }) => scheme).join(', ')}`);
|
|
63
|
+
}
|
|
64
|
+
const roles = describeRoles(route);
|
|
65
|
+
if (roles !== undefined) parts.push(roles);
|
|
66
|
+
const permissions = describeRequires(route);
|
|
67
|
+
if (permissions !== undefined) parts.push(permissions);
|
|
68
|
+
|
|
69
|
+
return parts.join('\n');
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export interface ToolInputSchema {
|
|
73
|
+
shape: Record<string, z.ZodType> | undefined;
|
|
74
|
+
hasParams: boolean;
|
|
75
|
+
hasQuery: boolean;
|
|
76
|
+
hasBody: boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The `{ params, query, body }` a model sends to call the route.
|
|
81
|
+
*/
|
|
82
|
+
export const buildToolInputSchema = (route: RouteDefinition): ToolInputSchema => {
|
|
83
|
+
const shape: Record<string, z.ZodType> = {};
|
|
84
|
+
let hasParams = false;
|
|
85
|
+
let hasQuery = false;
|
|
86
|
+
let hasBody = false;
|
|
87
|
+
|
|
88
|
+
const paramNames = parsePath(route.path).paramNames;
|
|
89
|
+
if (paramNames.length > 0) {
|
|
90
|
+
hasParams = true;
|
|
91
|
+
const paramShape: Record<string, z.ZodType> = {};
|
|
92
|
+
const explicitShape = (route.pathParams ? readObjectShape(route.pathParams) : undefined) as Record<string, z.ZodType> | undefined;
|
|
93
|
+
for (const name of paramNames) {
|
|
94
|
+
paramShape[name] = explicitShape?.[name] ?? z.string();
|
|
95
|
+
}
|
|
96
|
+
shape['params'] = z.object(paramShape);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (route.query) {
|
|
100
|
+
hasQuery = true;
|
|
101
|
+
shape['query'] = route.query.safeParse({}).success ? route.query.optional() : route.query;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (route.body && !isVoidSchema(route.body)) {
|
|
105
|
+
hasBody = true;
|
|
106
|
+
shape['body'] = route.body.safeParse(undefined).success ? route.body.optional() : route.body;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
shape: Object.keys(shape).length === 0 ? undefined : shape,
|
|
111
|
+
hasParams,
|
|
112
|
+
hasQuery,
|
|
113
|
+
hasBody,
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* One route as a model sees it.
|
|
119
|
+
*/
|
|
120
|
+
export interface ToolDefinition {
|
|
121
|
+
/**
|
|
122
|
+
* What the model calls it, e.g. `users_list_users`.
|
|
123
|
+
*/
|
|
124
|
+
name: string;
|
|
125
|
+
/**
|
|
126
|
+
* What the stream events call it, e.g. `users.listUsers`.
|
|
127
|
+
*/
|
|
128
|
+
key: string;
|
|
129
|
+
description: string;
|
|
130
|
+
/**
|
|
131
|
+
* The `{ params, query, body }` it takes, as JSON Schema.
|
|
132
|
+
*/
|
|
133
|
+
inputSchema: Record<string, unknown>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const toJsonSchema = (route: RouteDefinition): Record<string, unknown> => {
|
|
137
|
+
const { shape } = buildToolInputSchema(route);
|
|
138
|
+
const { $schema: _, ...schema } = z.toJSONSchema(z.object(shape ?? {}), {
|
|
139
|
+
io: 'input',
|
|
140
|
+
unrepresentable: 'any',
|
|
141
|
+
override: ({ jsonSchema }) => {
|
|
142
|
+
delete jsonSchema.brand;
|
|
143
|
+
},
|
|
144
|
+
}) as Record<string, unknown>;
|
|
145
|
+
return schema;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* One {@link ToolDefinition} per route.
|
|
150
|
+
*/
|
|
151
|
+
export const buildToolDefinitions = (routes: Routes): ToolDefinition[] => {
|
|
152
|
+
const entries = flattenRoutes(routes);
|
|
153
|
+
const names = deriveToolNames(
|
|
154
|
+
entries.map(({ routeKey }) => ({
|
|
155
|
+
key: routeKey,
|
|
156
|
+
origin: 'route',
|
|
157
|
+
}))
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
return entries.map(({ routeKey, route }) => ({
|
|
161
|
+
name: names.get(routeKey)!,
|
|
162
|
+
key: routeKey,
|
|
163
|
+
description: describeTool(route),
|
|
164
|
+
inputSchema: toJsonSchema(route),
|
|
165
|
+
}));
|
|
166
|
+
};
|
package/src/tool-events.ts
CHANGED
|
@@ -1,9 +1,26 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import type { RouteDefinition, Routes, StreamDefinition, StreamResponseDefinition } from './types.js';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
isJsonMediaType,
|
|
5
|
+
isStreamResponse,
|
|
6
|
+
isSuccessStatus,
|
|
7
|
+
isZodSchema,
|
|
8
|
+
resolveResponseBody,
|
|
9
|
+
resolveResponseContentType,
|
|
10
|
+
} from './generator-utils.js';
|
|
4
11
|
import { flattenRoutes } from './handler-pipeline.js';
|
|
5
12
|
import { parsePath } from './path-params.js';
|
|
6
|
-
import { readObjectShape } from './zod-internals.js';
|
|
13
|
+
import { isVoidSchema, readObjectShape } from './zod-internals.js';
|
|
14
|
+
import { toolOptionsOf, toolRefusal } from './tool-definitions.js';
|
|
15
|
+
import { deriveToolNames } from './tool-name.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Where a streamed response keeps the routes it named under `tools`.
|
|
19
|
+
*/
|
|
20
|
+
export const STREAM_TOOLS: unique symbol = Symbol.for('kizuna.stream.tools') as symbol as typeof STREAM_TOOLS;
|
|
21
|
+
|
|
22
|
+
export const streamToolsOf = (response: unknown): Routes | undefined =>
|
|
23
|
+
response !== null && typeof response === 'object' ? (response as { [STREAM_TOOLS]?: Routes })[STREAM_TOOLS] : undefined;
|
|
7
24
|
|
|
8
25
|
/**
|
|
9
26
|
* Every route in a tree as its dotted key, e.g. `'weather.getForecast'`. A tool
|
|
@@ -48,15 +65,21 @@ type ToolInput<Route, Io extends 'input' | 'output'> = Flatten<
|
|
|
48
65
|
(Route extends { body: infer Body extends z.ZodType } ? { body: SchemaSide<Body, Io> } : {})
|
|
49
66
|
>;
|
|
50
67
|
|
|
68
|
+
type SuccessBody<Response, Io extends 'input' | 'output'> = Response extends z.ZodType
|
|
69
|
+
? SchemaSide<Response, Io>
|
|
70
|
+
: Response extends { stream: unknown }
|
|
71
|
+
? void
|
|
72
|
+
: Response extends { body: infer Body extends z.ZodType }
|
|
73
|
+
? SchemaSide<Body, Io>
|
|
74
|
+
: never;
|
|
75
|
+
|
|
51
76
|
/**
|
|
52
|
-
* What the route answers with,
|
|
77
|
+
* What the route answers with, from each `2xx` it declares.
|
|
53
78
|
*/
|
|
54
|
-
type ToolOutput<Route, Io extends 'input' | 'output'> = Route extends { responses:
|
|
55
|
-
?
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
? SchemaSide<Body, Io>
|
|
59
|
-
: never
|
|
79
|
+
type ToolOutput<Route, Io extends 'input' | 'output'> = Route extends { responses: infer Responses }
|
|
80
|
+
? {
|
|
81
|
+
[Status in keyof Responses]: `${Status & number}` extends `2${string}` ? SuccessBody<Responses[Status], Io> : never;
|
|
82
|
+
}[keyof Responses]
|
|
60
83
|
: never;
|
|
61
84
|
|
|
62
85
|
/**
|
|
@@ -64,10 +87,11 @@ type ToolOutput<Route, Io extends 'input' | 'output'> = Route extends { response
|
|
|
64
87
|
*/
|
|
65
88
|
type InputField<Route, Io extends 'input' | 'output'> = [keyof ToolInput<Route, Io>] extends [never] ? {} : { input: ToolInput<Route, Io> };
|
|
66
89
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
90
|
+
type OutputField<Route, Io extends 'input' | 'output'> = [Exclude<ToolOutput<Route, Io>, void>] extends [never]
|
|
91
|
+
? {}
|
|
92
|
+
: void extends ToolOutput<Route, Io>
|
|
93
|
+
? { output?: Exclude<ToolOutput<Route, Io>, void> }
|
|
94
|
+
: { output: ToolOutput<Route, Io> };
|
|
71
95
|
|
|
72
96
|
/**
|
|
73
97
|
* One tool call, discriminated on `name` so `input` narrows to the route's own
|
|
@@ -78,6 +102,10 @@ export type ToolCall<R extends Routes, Io extends 'input' | 'output' = 'output'>
|
|
|
78
102
|
{
|
|
79
103
|
id: string;
|
|
80
104
|
name: Key;
|
|
105
|
+
/**
|
|
106
|
+
* The call waits for the person to approve it.
|
|
107
|
+
*/
|
|
108
|
+
needsApproval?: true;
|
|
81
109
|
} & InputField<ToolAt<R, Key>, Io>
|
|
82
110
|
>;
|
|
83
111
|
}[ToolKeys<R>];
|
|
@@ -133,13 +161,34 @@ export const toolInputShape = (route: RouteDefinition): Record<string, z.ZodType
|
|
|
133
161
|
};
|
|
134
162
|
|
|
135
163
|
/**
|
|
136
|
-
*
|
|
164
|
+
* The body of each `2xx` the route declares.
|
|
137
165
|
*/
|
|
138
166
|
const toolOutputSchema = (route: RouteDefinition): z.ZodType | undefined => {
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
167
|
+
const bodies: z.ZodType[] = [];
|
|
168
|
+
let someSuccessHasNoBody = false;
|
|
169
|
+
|
|
170
|
+
for (const status of Object.keys(route.responses)
|
|
171
|
+
.map(Number)
|
|
172
|
+
.sort((left, right) => left - right)) {
|
|
173
|
+
if (!isSuccessStatus(status)) continue;
|
|
174
|
+
const response = route.responses[status];
|
|
175
|
+
if (response === undefined) continue;
|
|
176
|
+
const contentType = resolveResponseContentType(response);
|
|
177
|
+
if (isStreamResponse(response) || (contentType !== undefined && !isJsonMediaType(contentType))) {
|
|
178
|
+
someSuccessHasNoBody = true;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const body = resolveResponseBody(response);
|
|
182
|
+
if (body === undefined || isVoidSchema(body)) {
|
|
183
|
+
someSuccessHasNoBody = true;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
bodies.push(body);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (bodies.length === 0) return undefined;
|
|
190
|
+
const output = bodies.length === 1 ? bodies[0]! : z.union(bodies);
|
|
191
|
+
return someSuccessHasNoBody ? output.optional() : output;
|
|
143
192
|
};
|
|
144
193
|
|
|
145
194
|
/**
|
|
@@ -173,6 +222,7 @@ export const toolEvents = <const R extends Routes>(tools: R): ToolEvents<R> => {
|
|
|
173
222
|
return z.object({
|
|
174
223
|
...identifier,
|
|
175
224
|
name: z.literal(routeKey),
|
|
225
|
+
needsApproval: z.literal(true).optional(),
|
|
176
226
|
...(Object.keys(input).length > 0 ? { input: z.object(input) } : {}),
|
|
177
227
|
});
|
|
178
228
|
});
|
|
@@ -216,16 +266,36 @@ export type StreamWithTools<Def extends StreamResponseDefinition> = Def extends
|
|
|
216
266
|
* `k.routes` before a route is validated.
|
|
217
267
|
*/
|
|
218
268
|
export const expandStreamTools = (route: RouteDefinition, routeKey: string): void => {
|
|
269
|
+
let namedAt: string | undefined;
|
|
219
270
|
for (const [status, response] of Object.entries(route.responses)) {
|
|
220
271
|
if (!isStreamResponse(response)) continue;
|
|
221
272
|
const { tools } = response;
|
|
222
273
|
if (tools === undefined) continue;
|
|
223
274
|
|
|
224
275
|
const where = `Route "${routeKey}" declares tools on status ${status}`;
|
|
276
|
+
if (namedAt !== undefined) {
|
|
277
|
+
throw new Error(`${where} and on status ${namedAt}. A handler runs one set of tools, so name them on one response.`);
|
|
278
|
+
}
|
|
279
|
+
namedAt = status;
|
|
225
280
|
if (isZodSchema(response.stream)) {
|
|
226
281
|
throw new Error(`${where} beside a single stream schema. Tool events are named, so name the other events too.`);
|
|
227
282
|
}
|
|
228
283
|
|
|
284
|
+
const toolEntries = flattenRoutes(tools);
|
|
285
|
+
deriveToolNames(
|
|
286
|
+
toolEntries.map(({ routeKey: toolKey }) => ({
|
|
287
|
+
key: toolKey,
|
|
288
|
+
origin: 'route',
|
|
289
|
+
}))
|
|
290
|
+
);
|
|
291
|
+
for (const { routeKey: toolKey, route: toolRoute } of toolEntries) {
|
|
292
|
+
if (toolOptionsOf(toolRoute) === undefined) {
|
|
293
|
+
throw new Error(`${where}, naming "${toolKey}", which does not declare \`tool\`. Declare it on that route.`);
|
|
294
|
+
}
|
|
295
|
+
const refusal = toolRefusal(toolRoute);
|
|
296
|
+
if (refusal !== undefined) throw new Error(`${where}, naming "${toolKey}", which cannot run as a tool: ${refusal}.`);
|
|
297
|
+
}
|
|
298
|
+
|
|
229
299
|
const events = toolEvents(tools);
|
|
230
300
|
const named = response.stream as Record<string, z.ZodType>;
|
|
231
301
|
for (const name of Object.keys(events)) {
|
|
@@ -237,11 +307,13 @@ export const expandStreamTools = (route: RouteDefinition, routeKey: string): voi
|
|
|
237
307
|
const mutable = response as {
|
|
238
308
|
stream: StreamDefinition;
|
|
239
309
|
tools?: Routes;
|
|
310
|
+
[STREAM_TOOLS]?: Routes;
|
|
240
311
|
};
|
|
241
312
|
mutable.stream = {
|
|
242
313
|
...named,
|
|
243
314
|
...(events as unknown as Record<string, z.ZodType>),
|
|
244
315
|
};
|
|
316
|
+
mutable[STREAM_TOOLS] = tools;
|
|
245
317
|
delete mutable.tools;
|
|
246
318
|
}
|
|
247
319
|
};
|
package/src/tool-records.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* How far along one tool call is.
|
|
2
|
+
* How far along one tool call is. `needs-approval` waits for the person.
|
|
3
3
|
*/
|
|
4
|
-
export type ToolCallState = 'running' | 'done' | 'failed';
|
|
4
|
+
export type ToolCallState = 'running' | 'needs-approval' | 'done' | 'failed';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* The shape {@link readToolCalls} reads: whatever a stream hands back, as long
|
|
@@ -87,13 +87,21 @@ export const readToolCalls = <Message extends ToolCallMessage>(messages: Iterabl
|
|
|
87
87
|
};
|
|
88
88
|
|
|
89
89
|
for (const message of messages) {
|
|
90
|
-
const data = message.data as {
|
|
90
|
+
const data = message.data as {
|
|
91
|
+
id?: unknown;
|
|
92
|
+
name?: unknown;
|
|
93
|
+
input?: unknown;
|
|
94
|
+
output?: unknown;
|
|
95
|
+
message?: unknown;
|
|
96
|
+
needsApproval?: unknown;
|
|
97
|
+
};
|
|
91
98
|
if (typeof data?.id !== 'string' || typeof data.name !== 'string') continue;
|
|
92
99
|
|
|
93
100
|
switch (message.event) {
|
|
94
101
|
case 'tool_call': {
|
|
95
102
|
const call = at(data.id, data.name);
|
|
96
103
|
call.input = data.input;
|
|
104
|
+
if (data.needsApproval === true && call.state === 'running') call.state = 'needs-approval';
|
|
97
105
|
break;
|
|
98
106
|
}
|
|
99
107
|
case 'tool_result': {
|