@kitn.ai/ui 0.22.2 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mcp.es.js +365 -117
- package/package.json +5 -2
- package/src/agent-tooling/integrations/vercel-ai-sdk.ts +255 -14
- package/src/agent-tooling/mcp/tools/scaffold.ts +19 -187
- package/src/agent-tooling/route-emit.ts +281 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a second emitter needs in order to write a chat route to a real file.
|
|
3
|
+
*
|
|
4
|
+
* Three facts live here, and they are the three a consumer that writes handlers
|
|
5
|
+
* to disk cannot do without: `chatRoutePreamble` (what goes above a bare
|
|
6
|
+
* `Integration.webRoute` so it compiles), and `CLIENT_MODEL_IDS` +
|
|
7
|
+
* `defaultModelFor` (whether the front end sends a model, and which id is valid
|
|
8
|
+
* for the host its route POSTs to). The `kai` MCP's own emitter in
|
|
9
|
+
* `mcp/tools/scaffold.ts` imports them from here, so there is one code path and
|
|
10
|
+
* the two emitters cannot disagree.
|
|
11
|
+
*
|
|
12
|
+
* WHY THIS IS ITS OWN MODULE, AND WHY IT MUST STAY A LEAF. These three were
|
|
13
|
+
* exported from `mcp/tools/scaffold.ts`, which is ~5,300 lines and builds a zod
|
|
14
|
+
* schema at MODULE SCOPE (`scaffold.inputSchema = z.object({…})`). A side effect
|
|
15
|
+
* at module scope is not tree-shakeable, so a bundler asked for
|
|
16
|
+
* `chatRoutePreamble` alone had to keep the whole file and all of zod with it.
|
|
17
|
+
* Measured on `create-kai`, whose CLI is one bundled zero-dependency file:
|
|
18
|
+
* **203 kB -> 904 kB**, of which 505 kB was zod the CLI never executes, on every
|
|
19
|
+
* `npx create-kai`. It also pulled 5,300 lines of kit source into `create-kai`'s
|
|
20
|
+
* `tsc` program under `--noUnusedLocals`, a flag the kit's own typecheck does not
|
|
21
|
+
* run, which forced an unrelated deletion in the kit to keep the CLI green.
|
|
22
|
+
*
|
|
23
|
+
* So the rule for this file is a rule about its IMPORTS, not its size: nothing
|
|
24
|
+
* here may import a module that reaches zod, the registry, or the integration
|
|
25
|
+
* catalog. `import type` is fine — it erases. Today that means exactly one
|
|
26
|
+
* import, and it is type-only. `create-kai`'s build guard
|
|
27
|
+
* (`bundleGraphProblem` in its `src/build-guards.ts`) fails the CLI build if zod
|
|
28
|
+
* ever reappears in the bundle, which is the check that turns this paragraph
|
|
29
|
+
* into something that can go red.
|
|
30
|
+
*
|
|
31
|
+
* NOT RE-EXPORTED from `mcp/tools/scaffold.ts`, deliberately. A second import
|
|
32
|
+
* path for the same symbol is how the fat one gets picked again.
|
|
33
|
+
*/
|
|
34
|
+
import type { Integration } from './types';
|
|
35
|
+
|
|
36
|
+
// ── SCAF-8: per-integration default model ids ─────────────────────────────────
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Default model id per integration whose route forwards one.
|
|
40
|
+
*
|
|
41
|
+
* THE ID IS HOST-SPECIFIC, and there is no such thing as a safe generic one.
|
|
42
|
+
* This used to fall through to `'openai/gpt-4o-mini'` for anything unlisted, on
|
|
43
|
+
* the reasoning that "a route that forwards the client's model is by definition
|
|
44
|
+
* pointed at an OpenAI-compatible endpoint". That was false twice over the
|
|
45
|
+
* moment a first-party provider landed: `openai/gpt-4o-mini` is an OPENROUTER
|
|
46
|
+
* slug — api.openai.com 404s the prefixed form, and api.anthropic.com rejects it
|
|
47
|
+
* outright — so a scaffold generated for the provider it names could not run
|
|
48
|
+
* against it.
|
|
49
|
+
*
|
|
50
|
+
* tsc cannot see any of this; every one of those strings compiles. The guard is
|
|
51
|
+
* `scaffold.test.ts` → "the emitted model id is valid for the host its route
|
|
52
|
+
* POSTs to", which reads the id out of the EMITTED scaffold and the host out of
|
|
53
|
+
* the route source, so a new integration cannot reintroduce a wrong one.
|
|
54
|
+
*
|
|
55
|
+
* EXPORTED because a route is only half of the fact. `openrouter`'s handler puts
|
|
56
|
+
* the client's `model` straight into its upstream payload, so a front end that
|
|
57
|
+
* posts `{ messages }` alone sends no model, OpenRouter answers 400, and nothing
|
|
58
|
+
* in a build or a typecheck can see it. Any second emitter of these routes needs
|
|
59
|
+
* the same table; `defaultModelFor` below is the accessor, and the raw table is
|
|
60
|
+
* exported alongside it so a consumer can also check it for drift at ITS build
|
|
61
|
+
* time rather than discovering a missing row when a user types.
|
|
62
|
+
*/
|
|
63
|
+
export const CLIENT_MODEL_IDS: Record<string, string> = {
|
|
64
|
+
// Vendor-prefixed `vendor/model`: OpenRouter's own id space, and the ONLY one
|
|
65
|
+
// of the three where the prefix belongs.
|
|
66
|
+
openrouter: 'openai/gpt-4o-mini',
|
|
67
|
+
// No vendor prefix. This is what the route already pinned, so moving the knob
|
|
68
|
+
// to the client changes the wire not at all.
|
|
69
|
+
openai: 'gpt-4o-mini',
|
|
70
|
+
// Anthropic's id space. Matches what the route pinned; 'claude-sonnet-5' and
|
|
71
|
+
// 'claude-haiku-4-5' are the cheaper swaps (see this integration's runNote).
|
|
72
|
+
anthropic: 'claude-opus-5',
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The default model id for an integration whose ROUTE reads the client's `model`
|
|
77
|
+
* field, and undefined for every other one.
|
|
78
|
+
*
|
|
79
|
+
* This used to be a substring test (`routeSrc.includes('model')`), which is true
|
|
80
|
+
* of any template that so much as writes `model: 'llama3.2'`. That emitted an
|
|
81
|
+
* editable `const model` into ollama, langgraph, vercel-ai-sdk and cloudflare
|
|
82
|
+
* scaffolds whose routes pin their own model and never read the field, so
|
|
83
|
+
* changing it did nothing, and cloudflare's default was not even a valid Workers
|
|
84
|
+
* AI id. `forwardsFromClient` states the fact instead of guessing at it.
|
|
85
|
+
*
|
|
86
|
+
* Exported for the same reason as `CLIENT_MODEL_IDS`: a second emitter of these
|
|
87
|
+
* routes has to answer "does this front end send a model, and which" the same
|
|
88
|
+
* way, and both halves of that answer live here.
|
|
89
|
+
*/
|
|
90
|
+
export function defaultModelFor(integration: Integration): string | undefined {
|
|
91
|
+
if (!integration.forwardsFromClient.includes('model')) return undefined;
|
|
92
|
+
const id = CLIENT_MODEL_IDS[integration.id];
|
|
93
|
+
// No fallback, deliberately — the old `?? 'openai/gpt-4o-mini'` is what let a
|
|
94
|
+
// first-party provider inherit an OpenRouter slug and emit a scaffold that
|
|
95
|
+
// 404s on its own host. A model id is a per-host fact; an integration that
|
|
96
|
+
// forwards one has to say which.
|
|
97
|
+
if (id === undefined) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
`Integration '${integration.id}' forwards the client's 'model' but has no CLIENT_MODEL_IDS entry, so the ` +
|
|
100
|
+
`scaffold would emit a model id that is not valid for the host its route POSTs to. Add one in ` +
|
|
101
|
+
`agent-tooling/route-emit.ts.`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return id;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The request body, declared once per route file.
|
|
109
|
+
*
|
|
110
|
+
* `await request.json()` is `unknown` — it is whatever the client sent — so
|
|
111
|
+
* destructuring it directly is TS2339 on EVERY field. That is not pedantry: it
|
|
112
|
+
* is a hard `npm run build` failure the moment a Node-typed project compiles the
|
|
113
|
+
* route, where `Request` comes from undici (`json(): Promise<unknown>`) rather
|
|
114
|
+
* than from the DOM lib (`json(): Promise<any>`). A stock Vite app does exactly
|
|
115
|
+
* that — `tsc -b` walks vite.config.ts → vite-chat-api.ts → src/server/chat.ts
|
|
116
|
+
* with `lib` and no DOM — so the route ran fine and the build did not.
|
|
117
|
+
*
|
|
118
|
+
* `messages` is typed as the kit's OWN encoder output rather than restated
|
|
119
|
+
* structurally, which keeps the two halves of the scaffold pinned to one type:
|
|
120
|
+
* the front end sends `toOpenAIMessages(thread)`, and this is what that returns.
|
|
121
|
+
* The import is type-only and erases at build time, so the route ships no
|
|
122
|
+
* runtime dependency on the kit.
|
|
123
|
+
*/
|
|
124
|
+
const CHAT_REQUEST_BODY_IMPORT = `import type { OpenAIWireMessage } from '@kitn.ai/ui/wire';`;
|
|
125
|
+
const CHAT_REQUEST_BODY_DECL = [
|
|
126
|
+
`/**`,
|
|
127
|
+
` * What the front end POSTs. \`request.json()\` is \`unknown\` (it is whatever the`,
|
|
128
|
+
` * client sent), so the body is narrowed once here instead of at every use —`,
|
|
129
|
+
` * without it this route does not compile under a server tsconfig. Widen it as`,
|
|
130
|
+
` * you add fields of your own.`,
|
|
131
|
+
` */`,
|
|
132
|
+
`type ChatRequestBody = {`,
|
|
133
|
+
` messages: OpenAIWireMessage[];`,
|
|
134
|
+
` model?: string;`,
|
|
135
|
+
` tools?: unknown[];`,
|
|
136
|
+
`};`,
|
|
137
|
+
``,
|
|
138
|
+
`/** Narrow the JSON body once, at the edge. */`,
|
|
139
|
+
`async function readChatRequest(request: Request): Promise<ChatRequestBody> {`,
|
|
140
|
+
` return (await request.json()) as ChatRequestBody;`,
|
|
141
|
+
`}`,
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Attachments, on the way IN.
|
|
146
|
+
*
|
|
147
|
+
* A user turn's `content` is a plain string until it carries a file, at which
|
|
148
|
+
* point `toOpenAIMessages` emits the ARRAY form. Every route that re-maps
|
|
149
|
+
* messages into some other SDK's shape has to handle both, and the three that do
|
|
150
|
+
* (anthropic, mastra, vercel-ai-sdk) were each written when only the string form
|
|
151
|
+
* existed — so each one would have quietly dropped the attachment while still
|
|
152
|
+
* compiling, which is the same defect the encoder was just fixed for.
|
|
153
|
+
*
|
|
154
|
+
* These two helpers are the shared half of that: flattening the wire shape is
|
|
155
|
+
* identical everywhere, while the target shape is not, so each route maps
|
|
156
|
+
* `WirePart[]` into its own SDK itself rather than inheriting a lowest common
|
|
157
|
+
* denominator.
|
|
158
|
+
*
|
|
159
|
+
* Only injected into routes that actually call them — the eight pass-through
|
|
160
|
+
* integrations forward `messages` untouched and need none of this, and an unused
|
|
161
|
+
* declaration is a hard error under the gate's `--noUnusedLocals`.
|
|
162
|
+
*/
|
|
163
|
+
const CONTENT_PARTS_DECL = [
|
|
164
|
+
`/** Where an attachment's bytes are: inline base64, or an address the PROVIDER`,
|
|
165
|
+
` * fetches. Never both. */`,
|
|
166
|
+
`type WireFileSource = { type: 'data'; data: string } | { type: 'url'; url: string };`,
|
|
167
|
+
``,
|
|
168
|
+
`/** One piece of a turn, with the string and array content forms flattened into`,
|
|
169
|
+
` * a single shape. */`,
|
|
170
|
+
`type WirePart =`,
|
|
171
|
+
` | { kind: 'text'; text: string }`,
|
|
172
|
+
` | { kind: 'file'; mediaType: string; filename?: string; source: WireFileSource };`,
|
|
173
|
+
``,
|
|
174
|
+
`const DATA_URI = /^data:([^;,]+);base64,([\\s\\S]*)$/;`,
|
|
175
|
+
``,
|
|
176
|
+
`/**`,
|
|
177
|
+
` * Flatten a wire message's content into parts.`,
|
|
178
|
+
` *`,
|
|
179
|
+
` * An image sent by URL has no media type here — \`image_url\` carries only the`,
|
|
180
|
+
` * address — so it reports the top-level segment \`'image'\`, which is all a URL`,
|
|
181
|
+
` * source needs. Only images can reach that branch: the kit refuses to encode a`,
|
|
182
|
+
` * remote PDF rather than guess at one.`,
|
|
183
|
+
` */`,
|
|
184
|
+
`function wireParts(content: OpenAIWireMessage['content']): WirePart[] {`,
|
|
185
|
+
` if (content == null) return [];`,
|
|
186
|
+
` if (typeof content === 'string') return content === '' ? [] : [{ kind: 'text', text: content }];`,
|
|
187
|
+
` return content.map((part): WirePart => {`,
|
|
188
|
+
` if (part.type === 'text') return { kind: 'text', text: part.text };`,
|
|
189
|
+
` if (part.type === 'image_url') {`,
|
|
190
|
+
` const asData = DATA_URI.exec(part.image_url.url);`,
|
|
191
|
+
` return asData`,
|
|
192
|
+
` ? { kind: 'file', mediaType: asData[1], source: { type: 'data', data: asData[2] } }`,
|
|
193
|
+
` : { kind: 'file', mediaType: 'image', source: { type: 'url', url: part.image_url.url } };`,
|
|
194
|
+
` }`,
|
|
195
|
+
` const asData = DATA_URI.exec(part.file.file_data);`,
|
|
196
|
+
` if (!asData) {`,
|
|
197
|
+
` // LOUD on purpose. \`file_data\` is a data URI on this wire; anything else`,
|
|
198
|
+
` // cannot be turned into bytes without fetching it, and forwarding a turn`,
|
|
199
|
+
` // with the attachment quietly missing is the bug this whole path exists`,
|
|
200
|
+
` // to prevent.`,
|
|
201
|
+
` throw new Error(`,
|
|
202
|
+
` 'Unsupported file content part: file_data must be a data: URI of the form data:<media type>;base64,<data>.',`,
|
|
203
|
+
` );`,
|
|
204
|
+
` }`,
|
|
205
|
+
` return {`,
|
|
206
|
+
` kind: 'file',`,
|
|
207
|
+
` mediaType: asData[1],`,
|
|
208
|
+
` filename: part.file.filename,`,
|
|
209
|
+
` source: { type: 'data', data: asData[2] },`,
|
|
210
|
+
` };`,
|
|
211
|
+
` });`,
|
|
212
|
+
`}`,
|
|
213
|
+
``,
|
|
214
|
+
`/** Just the text of a turn. System, assistant and tool messages are text-only`,
|
|
215
|
+
` * on this wire, so this collapses the array form for them. */`,
|
|
216
|
+
`function wireText(content: OpenAIWireMessage['content']): string {`,
|
|
217
|
+
` return wireParts(content)`,
|
|
218
|
+
` .map((p) => (p.kind === 'text' ? p.text : ''))`,
|
|
219
|
+
` .join('');`,
|
|
220
|
+
`}`,
|
|
221
|
+
];
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* What a bare `Integration.webRoute` needs above it before it will compile.
|
|
225
|
+
*
|
|
226
|
+
* WHY THIS IS A FUNCTION AND NOT TWO EXPORTED CONSTANTS. `webRoute` reads like a
|
|
227
|
+
* self-contained handler and is not one: every fragment in the catalog calls
|
|
228
|
+
* `readChatRequest`, and three of them (anthropic, mastra, vercel-ai-sdk) also
|
|
229
|
+
* call `wireParts` / `wireText` and annotate with `WirePart`. Measured over the
|
|
230
|
+
* catalog, a bare fragment under `tsc --strict` is TS2304 on five distinct names.
|
|
231
|
+
* A consumer handed `CHAT_REQUEST_BODY_DECL` alone would therefore emit five
|
|
232
|
+
* routes that compile and three that do not, and would find out only for the
|
|
233
|
+
* ones it happened to wire first. Asking the question the caller actually has —
|
|
234
|
+
* "what goes above THIS fragment" — is the shape that cannot be answered
|
|
235
|
+
* half-right, so that is what is exported.
|
|
236
|
+
*
|
|
237
|
+
* `symbols` is DERIVED from `decl` rather than listed beside it, so a rename
|
|
238
|
+
* inside either declaration block moves it and a consumer's drift guard grades
|
|
239
|
+
* the real text.
|
|
240
|
+
*/
|
|
241
|
+
export interface ChatRoutePreamble {
|
|
242
|
+
/** import lines the declarations need, emitted at the top of the route file */
|
|
243
|
+
readonly imports: readonly string[];
|
|
244
|
+
/** the declaration lines, emitted immediately above the handler */
|
|
245
|
+
readonly decl: readonly string[];
|
|
246
|
+
/** every symbol `decl` declares, read back out of `decl` */
|
|
247
|
+
readonly symbols: readonly string[];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A top-level declaration in a preamble block. Indented lines are bodies. */
|
|
251
|
+
const PREAMBLE_DECLARATION = /^(?:export\s+)?(?:async\s+)?(?:function|type|interface|const|class)\s+([A-Za-z_$][\w$]*)/;
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The preamble a given handler fragment needs.
|
|
255
|
+
*
|
|
256
|
+
* Used by the MCP below to build its own route blocks, and exported for
|
|
257
|
+
* `create-kai`, which writes the same handler to a real file that has to
|
|
258
|
+
* compile. One code path, so the two cannot disagree about what a route needs.
|
|
259
|
+
*/
|
|
260
|
+
export function chatRoutePreamble(fragment: string): ChatRoutePreamble {
|
|
261
|
+
// The content helpers ride along only where the route calls them; see
|
|
262
|
+
// CONTENT_PARTS_DECL for why an unconditional injection would not compile.
|
|
263
|
+
//
|
|
264
|
+
// KNOWN GAP, live but not yet reachable: this tests for a CALL, so a fragment
|
|
265
|
+
// that only annotates with `WirePart` / `WireFileSource` and never calls
|
|
266
|
+
// either helper would be told it needs nothing and would not compile. No
|
|
267
|
+
// catalog route is shaped that way today — vercel-ai-sdk is the only one that
|
|
268
|
+
// names the type, and it calls `wireParts` two lines later — so widening the
|
|
269
|
+
// test would change no emitted byte, and that is exactly why it is left alone
|
|
270
|
+
// here rather than fixed blind. `scaffold.test.ts` → "webRoute has no symbol
|
|
271
|
+
// its own preamble fails to declare" is the check that turns this from a
|
|
272
|
+
// comment into a failing build the day an integration lands in that shape.
|
|
273
|
+
const decl = /\bwire(?:Parts|Text)\s*\(/.test(fragment)
|
|
274
|
+
? [...CHAT_REQUEST_BODY_DECL, ``, ...CONTENT_PARTS_DECL]
|
|
275
|
+
: [...CHAT_REQUEST_BODY_DECL];
|
|
276
|
+
return {
|
|
277
|
+
imports: [CHAT_REQUEST_BODY_IMPORT],
|
|
278
|
+
decl,
|
|
279
|
+
symbols: decl.flatMap((line) => PREAMBLE_DECLARATION.exec(line)?.[1] ?? []),
|
|
280
|
+
};
|
|
281
|
+
}
|