@guren/server 2.13.0 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  2. package/dist/agent/derive.d.ts +155 -0
  3. package/dist/agent/dispatch.d.ts +123 -0
  4. package/dist/agent/events.d.ts +80 -0
  5. package/dist/agent/redact.d.ts +55 -0
  6. package/dist/agent/scopes.d.ts +115 -0
  7. package/dist/auth/AuthManager.d.ts +64 -0
  8. package/dist/auth/RequestAuthContext.d.ts +3 -5
  9. package/dist/auth/TokenGuard.d.ts +61 -0
  10. package/dist/auth/api-token.d.ts +25 -5
  11. package/dist/auth/context.d.ts +24 -0
  12. package/dist/auth/index.d.ts +5 -2
  13. package/dist/auth/index.js +2 -2
  14. package/dist/auth/providers/UserProvider.d.ts +7 -0
  15. package/dist/auth/types.d.ts +6 -0
  16. package/dist/{auth-C7sVmYgc.js → auth-BSUc14CD.js} +313 -122
  17. package/dist/authorization/index.js +1 -1
  18. package/dist/authorization/middleware.d.ts +28 -1
  19. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  20. package/dist/broadcasting/index.js +1 -1
  21. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BxU-LIfF.js} +2 -45
  22. package/dist/context-DoD0c7J_.js +26 -0
  23. package/dist/http/middleware/auth.d.ts +2 -2
  24. package/dist/http/middleware/capabilities.d.ts +57 -0
  25. package/dist/http/middleware/csrf.d.ts +3 -0
  26. package/dist/http/request.d.ts +51 -2
  27. package/dist/index.d.ts +12 -3
  28. package/dist/index.js +1015 -84
  29. package/dist/internal/agent-preflight.d.ts +28 -0
  30. package/dist/internal/request.d.ts +19 -0
  31. package/dist/internal/request.js +2 -0
  32. package/dist/internal/route-path.d.ts +28 -0
  33. package/dist/internal/route-path.js +33 -0
  34. package/dist/internal/zod-compat.d.ts +201 -0
  35. package/dist/internal/zod-compat.js +193 -0
  36. package/dist/internal/zod-json-schema.d.ts +102 -0
  37. package/dist/internal/zod-json-schema.js +461 -0
  38. package/dist/mcp/create-mcp-server.d.ts +29 -0
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Controller.d.ts +46 -0
  41. package/dist/mvc/Router.d.ts +53 -0
  42. package/dist/request-CRVuIiQr.js +78 -0
  43. package/dist/runtime/index.js +5 -2
  44. package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-BGfWbPYp.js} +1 -1
  45. package/package.json +17 -1
@@ -0,0 +1,461 @@
1
+ import { SINGLE_CHILD_WRAPPERS, ZOD3_UNSUPPORTED_MESSAGE, arrayElement, enumValues, getTypeName, innerSchema, isZod3Schema, literalValues, objectShape, pipeSides, recordValueType, schemaChecks, schemaFormat, typeOf, unwrapSingleChild } from "./zod-compat.js";
2
+ //#region src/internal/zod-json-schema.ts
3
+ /**
4
+ * The one Zod → JSON Schema rule, shared by every surface that has to describe
5
+ * an application's contracts to something outside the process: `@guren/openapi`
6
+ * renders it as OpenAPI 3.1 schema objects (which *are* JSON Schema 2020-12),
7
+ * and RFC 0016's agent tools advertise it as MCP input/output schemas.
8
+ *
9
+ * Internal by the rules in `contributing/api-stability.md`: reachable only
10
+ * through a deep import under `internal/`, never re-exported from
11
+ * `@guren/server`'s or `@guren/core`'s index. No stability guarantee — it
12
+ * exists so two derivations of the same schema cannot disagree, not as a
13
+ * public extension point. That is the whole reason it was promoted out of
14
+ * `@guren/openapi`: a second walker is how an agent tool comes to advertise a
15
+ * schema the documented API contradicts.
16
+ *
17
+ * It lives in `@guren/server` rather than `@guren/core` (where RFC 0016 §2
18
+ * first placed it) for a build-order reason, not a layering one. Core's index
19
+ * is `export * from '@guren/server'`, so core builds *after* server and a
20
+ * server module cannot import a core one — the edge would close a cycle, and
21
+ * server's declaration build (`tsc -p tsconfig.build.json`, `paths: {}`)
22
+ * would look for a core `dist/` that does not exist yet. `deriveAgentTools`
23
+ * lives in `@guren/server`, so the walker had to move down to the package
24
+ * both it and the OpenAPI generator can see. `@guren/core/internal/*`
25
+ * re-exports this module, which keeps that the specifier every consumer
26
+ * outside this package writes.
27
+ *
28
+ * Every `_def` read goes through `zod-compat.ts`, including the check reads
29
+ * this module added. Reaching into `_def` here would put zod-layout knowledge
30
+ * in two places, which is exactly the split `zod-compat` exists to prevent.
31
+ *
32
+ * Zod 4 only, and a v3 node is *refused* rather than walked — on v3 `_def.type`
33
+ * holds a nested schema where v4 keeps the type name, so every read below would
34
+ * misfire and produce a confidently wrong document. The refusal is re-checked
35
+ * at each recursion, because a v3 node can hide inside a v4 wrapper.
36
+ *
37
+ * What this module does not decide: what a caller does with the warnings, and
38
+ * how the result is embedded (a `requestBody` content map, an MCP `inputSchema`).
39
+ * Warnings are appended to a caller-owned array so a document generator can
40
+ * surface them per request and a codegen step can fail on them.
41
+ */
42
+ /**
43
+ * Zod's string formats mapped to the JSON Schema `format` names that mean the
44
+ * same thing, matched against zod's own `z.toJSONSchema()` output so the two
45
+ * cannot disagree about, say, whether `z.url()` is `"url"` or `"uri"`.
46
+ *
47
+ * The line is "registered by JSON Schema 2020-12", not "short". Zod carries
48
+ * plenty of formats the spec has never registered (`cuid`, `nanoid`, `emoji`,
49
+ * `ulid`, `jwt`, `base64`…), and emitting those verbatim advertises a
50
+ * constraint no consumer can interpret — an agent reading `format: "cuid"`
51
+ * learns nothing it can act on, while the `type: "string"` it already had stays
52
+ * true. Unmapped formats are dropped, not warned about: the schema is still
53
+ * correct, just less specific.
54
+ *
55
+ * `time` is the one registered format deliberately left out, and zod omits it
56
+ * from its own output for the same reason: JSON Schema's `time` is an RFC 3339
57
+ * `full-time`, which requires an offset, while `z.iso.time()` accepts a local
58
+ * wall-clock time. Claiming the format would assert an offset the schema does
59
+ * not require.
60
+ */
61
+ const JSON_SCHEMA_STRING_FORMATS = {
62
+ email: "email",
63
+ url: "uri",
64
+ uuid: "uuid",
65
+ datetime: "date-time",
66
+ date: "date",
67
+ duration: "duration",
68
+ hostname: "hostname",
69
+ ipv4: "ipv4",
70
+ ipv6: "ipv6"
71
+ };
72
+ /**
73
+ * The `number_format` values that describe an integer. JSON Schema says this
74
+ * with a *type*, not a format, so these change `type: "number"` to
75
+ * `type: "integer"` — a `z.int()` that documents as `number` advertises a
76
+ * contract admitting `3.14`, which the route then rejects.
77
+ *
78
+ * `float32` / `float64` are the other half of the same zod vocabulary and stay
79
+ * plain numbers. The bounds each of these formats implies (zod's own emitter
80
+ * adds `minimum: -2147483648` for `int32`, and the safe-integer range for
81
+ * `safeint`) are deliberately not emitted: they are the representation's
82
+ * limits rather than the application's contract, and they bury the constraints
83
+ * an author actually wrote. `int64` / `uint64` need no entry — they sit on
84
+ * `bigint` nodes, which this walker already renders as `integer`.
85
+ */
86
+ const INTEGER_NUMBER_FORMATS = /* @__PURE__ */ new Set([
87
+ "safeint",
88
+ "int32",
89
+ "uint32"
90
+ ]);
91
+ /**
92
+ * The string formats whose zod-supplied regex is worth carrying as `pattern` —
93
+ * the ones a user *wrote as a pattern* (`.regex()`) or as a prefix/suffix/
94
+ * substring test, which zod stores only as a compiled regex.
95
+ *
96
+ * The registered formats above are excluded on purpose even though zod exposes
97
+ * a pattern for them too: their regexes run to hundreds of characters (the
98
+ * `datetime` one alone is ~300), they are zod's parsing implementation rather
99
+ * than the contract, and `format` already says the same thing in a word.
100
+ */
101
+ const PATTERN_BEARING_FORMATS = /* @__PURE__ */ new Set([
102
+ "regex",
103
+ "starts_with",
104
+ "ends_with",
105
+ "includes"
106
+ ]);
107
+ /**
108
+ * Turn a Zod schema into a JSON Schema object, appending a line to `warnings`
109
+ * for anything it cannot express. `label` names the schema in those warnings
110
+ * (`"POST /posts body.title"`); `io` picks the side of coercing and piped
111
+ * schemas to describe — `input` is what a caller sends, `output` what a parse
112
+ * produces.
113
+ *
114
+ * Returns `undefined` when the node contributes nothing (a bare `z.undefined()`)
115
+ * or could not be read; a caller treats that as "omit this property".
116
+ */
117
+ function toJsonSchema(schema, warnings, label, io) {
118
+ if (warnIfZod3(schema, warnings, label)) return;
119
+ if (!isZodSchema(schema)) {
120
+ warnings.push(`${label}: skipped because schema is not a supported Zod schema.`);
121
+ return;
122
+ }
123
+ const typeName = typeOf(schema);
124
+ const def = schema._def ?? {};
125
+ if (typeName !== "nullable" && SINGLE_CHILD_WRAPPERS.has(typeName)) {
126
+ const nested = unwrapSingleChild(schema, io);
127
+ if (!nested) {
128
+ warnings.push(`${label}: the contents of a "${typeName}" schema could not be read, so it is omitted.`);
129
+ return;
130
+ }
131
+ return toJsonSchema(nested, warnings, label, io);
132
+ }
133
+ switch (typeName) {
134
+ case "string": return {
135
+ type: "string",
136
+ ...stringConstraints(schema)
137
+ };
138
+ case "number": return numberSchema(schema);
139
+ case "boolean": return { type: "boolean" };
140
+ case "bigint": return { type: "integer" };
141
+ case "date": return {
142
+ type: "string",
143
+ format: "date-time"
144
+ };
145
+ case "undefined": return;
146
+ case "null": return { type: "null" };
147
+ case "literal": return literalSchema(def);
148
+ case "array": return {
149
+ type: "array",
150
+ items: toJsonSchema(arrayElement(def), warnings, `${label}[]`, io) ?? {},
151
+ ...lengthConstraints(schemaChecks(schema), "minItems", "maxItems")
152
+ };
153
+ case "object": {
154
+ const details = readObjectSchemaDetails(schema, warnings, label, io);
155
+ if (!details) return { type: "object" };
156
+ return {
157
+ type: "object",
158
+ properties: details.properties,
159
+ required: details.required.size > 0 ? Array.from(details.required) : void 0
160
+ };
161
+ }
162
+ case "nullable": {
163
+ const nested = unwrapSingleChild(schema, io);
164
+ const nestedSchema = nested ? toJsonSchema(nested, warnings, label, io) : void 0;
165
+ return nestedSchema ? { anyOf: [nestedSchema, { type: "null" }] } : { type: ["null"] };
166
+ }
167
+ case "transform":
168
+ warnings.push(`${label}: transform schemas are documented as generic objects.`);
169
+ return { type: "object" };
170
+ case "union": {
171
+ const oneOf = (def.options ?? []).map((option, index) => toJsonSchema(option, warnings, `${label}.option${index}`, io)).filter((option) => Boolean(option));
172
+ return oneOf.length > 0 ? { oneOf } : void 0;
173
+ }
174
+ case "intersection": {
175
+ const allOf = [toJsonSchema(def.left, warnings, `${label}.left`, io), toJsonSchema(def.right, warnings, `${label}.right`, io)].filter((value) => Boolean(value));
176
+ return allOf.length > 0 ? { allOf } : void 0;
177
+ }
178
+ case "record": return {
179
+ type: "object",
180
+ additionalProperties: toJsonSchema(recordValueType(def), warnings, `${label}.value`, io) ?? true
181
+ };
182
+ case "enum": {
183
+ const values = enumValues(schema);
184
+ if (values.length === 0) return { type: "string" };
185
+ const hasNumber = values.some((value) => typeof value === "number");
186
+ const hasString = values.some((value) => typeof value === "string");
187
+ if (hasNumber && hasString) return {
188
+ type: ["string", "number"],
189
+ enum: values
190
+ };
191
+ return {
192
+ type: hasNumber ? "number" : "string",
193
+ enum: values
194
+ };
195
+ }
196
+ case "tuple": {
197
+ const items = (def.items ?? []).map((item, index) => toJsonSchema(item, warnings, `${label}[${index}]`, io)).filter((item) => Boolean(item));
198
+ return {
199
+ type: "array",
200
+ prefixItems: items,
201
+ minItems: items.length,
202
+ maxItems: items.length
203
+ };
204
+ }
205
+ case "promise": {
206
+ const nested = innerSchema(def);
207
+ return nested ? toJsonSchema(nested, warnings, label, io) : void 0;
208
+ }
209
+ default:
210
+ warnings.push(`${label}: unsupported Zod type "${typeName}".`);
211
+ return;
212
+ }
213
+ }
214
+ /**
215
+ * Take an object schema apart into its properties and the set of keys a caller
216
+ * must supply, looking through any wrappers around it. Warns and returns
217
+ * `undefined` when the schema is absent, not Zod, or not an object once
218
+ * unwrapped — a caller that expands properties into something else (query
219
+ * parameters, merged tool input) has nothing to expand otherwise.
220
+ */
221
+ function readObjectSchema(schema, warnings, label, io) {
222
+ if (!schema) return;
223
+ if (warnIfZod3(schema, warnings, label)) return;
224
+ if (!isZodSchema(schema)) {
225
+ warnings.push(`${label}: skipped because schema is not a supported Zod schema.`);
226
+ return;
227
+ }
228
+ const details = readObjectSchemaDetails(schema, warnings, label, io);
229
+ if (!details) warnings.push(`${label}: expected an object schema for parameter expansion.`);
230
+ return details;
231
+ }
232
+ /** Whether this value looks like a Zod schema at all — the gate every walk opens with. */
233
+ function isZodSchema(schema) {
234
+ if (!schema || typeof schema !== "object") return false;
235
+ return Boolean(getTypeName(schema));
236
+ }
237
+ /**
238
+ * Push the v3 refusal warning and report whether it fired. One helper so the
239
+ * composed message cannot drift between the entry points, and so the recursive
240
+ * walks re-check nested nodes — a v3 schema can sit inside a v4 object, and an
241
+ * ungated recursion would document it wrong instead of refusing it.
242
+ */
243
+ function warnIfZod3(schema, warnings, label) {
244
+ if (schema && typeof schema === "object" && isZod3Schema(schema)) {
245
+ warnings.push(`${label}: skipped — ${ZOD3_UNSUPPORTED_MESSAGE}`);
246
+ return true;
247
+ }
248
+ return false;
249
+ }
250
+ function readObjectSchemaDetails(schema, warnings, label, io) {
251
+ if (warnIfZod3(schema, warnings, label)) return;
252
+ if (typeOf(schema) !== "object") {
253
+ const nested = unwrapSingleChild(schema, io);
254
+ return nested ? readObjectSchemaDetails(nested, warnings, label, io) : void 0;
255
+ }
256
+ const shape = objectShape(schema);
257
+ if (!shape) {
258
+ warnings.push(`${label}: object schema shape could not be read.`);
259
+ return;
260
+ }
261
+ const properties = {};
262
+ const required = /* @__PURE__ */ new Set();
263
+ for (const [key, value] of Object.entries(shape)) {
264
+ const propertySchema = toJsonSchema(value, warnings, `${label}.${key}`, io);
265
+ if (!propertySchema) continue;
266
+ properties[key] = propertySchema;
267
+ if (!isOptional(value, io)) required.add(key);
268
+ }
269
+ return {
270
+ properties,
271
+ required
272
+ };
273
+ }
274
+ /**
275
+ * Whether a caller may leave this property out — the `required` half of an
276
+ * object schema.
277
+ *
278
+ * Stays here rather than joining `unwrapSingleChild` in `zod-compat`: applying
279
+ * the wrapper vocabulary is schema-reading, but what to *conclude* from a
280
+ * wrapper is a policy each caller sets — see the `pipe` case.
281
+ */
282
+ function isOptional(schema, io) {
283
+ switch (typeOf(schema)) {
284
+ case "optional": return true;
285
+ case "default":
286
+ case "prefault": return io === "input";
287
+ case "catch": return io === "input";
288
+ case "nonoptional": return false;
289
+ case "pipe": {
290
+ const { from, to } = pipeSides(schema._def ?? {});
291
+ if (!from) return false;
292
+ return to ? isOptional(from, io) && isOptional(to, io) : isOptional(from, io);
293
+ }
294
+ default: {
295
+ const nested = unwrapSingleChild(schema, io);
296
+ return nested ? isOptional(nested, io) : false;
297
+ }
298
+ }
299
+ }
300
+ function literalSchema(def) {
301
+ const value = literalValues(def)[0];
302
+ if (typeof value === "string") return {
303
+ type: "string",
304
+ const: value
305
+ };
306
+ if (typeof value === "number") return {
307
+ type: "number",
308
+ const: value
309
+ };
310
+ if (typeof value === "boolean") return {
311
+ type: "boolean",
312
+ const: value
313
+ };
314
+ if (value === null) return {
315
+ type: "null",
316
+ const: null
317
+ };
318
+ return {};
319
+ }
320
+ /**
321
+ * A check value that JSON Schema can carry. The guard is not ceremonial: the
322
+ * same `greater_than` / `min_length` check kinds are attached to `z.date()` and
323
+ * `z.bigint()`, where the bound is a `Date` or a `bigint` — emitting either
324
+ * would produce a keyword whose value is not a JSON number (and, for bigint,
325
+ * one that `JSON.stringify` throws on).
326
+ */
327
+ function numeric(value) {
328
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
329
+ }
330
+ /** The tighter of two lower bounds — a schema may carry `.min(2).min(5)`. */
331
+ function tightenLower(current, candidate) {
332
+ return current === void 0 ? candidate : Math.max(current, candidate);
333
+ }
334
+ /** The tighter of two upper bounds. */
335
+ function tightenUpper(current, candidate) {
336
+ return current === void 0 ? candidate : Math.min(current, candidate);
337
+ }
338
+ /**
339
+ * `min_length` / `max_length` / `length_equals` under whichever pair of
340
+ * keywords the type spells them: strings count characters (`minLength`), arrays
341
+ * count elements (`minItems`). Zod uses the same three check kinds for both.
342
+ */
343
+ function lengthConstraints(checks, minKey, maxKey) {
344
+ const constraints = {};
345
+ for (const check of checks) switch (check.check) {
346
+ case "min_length": {
347
+ const minimum = numeric(check.minimum);
348
+ if (minimum !== void 0) constraints[minKey] = tightenLower(constraints[minKey], minimum);
349
+ break;
350
+ }
351
+ case "max_length": {
352
+ const maximum = numeric(check.maximum);
353
+ if (maximum !== void 0) constraints[maxKey] = tightenUpper(constraints[maxKey], maximum);
354
+ break;
355
+ }
356
+ case "length_equals": {
357
+ const length = numeric(check.length);
358
+ if (length !== void 0) {
359
+ constraints[minKey] = tightenLower(constraints[minKey], length);
360
+ constraints[maxKey] = tightenUpper(constraints[maxKey], length);
361
+ }
362
+ break;
363
+ }
364
+ }
365
+ return constraints;
366
+ }
367
+ /**
368
+ * Every format this node declares, in the order a reader should prefer them.
369
+ *
370
+ * Two sources, because zod has two spellings: the top-level constructors
371
+ * (`z.email()`, `z.int()`) record the format on the node, while the equivalent
372
+ * methods (`z.string().email()`, `z.number().int()`) attach it as a check and
373
+ * leave the node's own field empty. Reading one source loses half the formats
374
+ * an app writes, so both are collected here once rather than in each caller.
375
+ *
376
+ * Takes the node's checks rather than re-reading them: every caller has already
377
+ * walked `_def.checks` for something else, and this walker is on RFC 0016's
378
+ * tool-derivation path as well as the document one.
379
+ */
380
+ function declaredFormats(schema, checks) {
381
+ const onNode = schemaFormat(schema);
382
+ const onChecks = checks.flatMap((check) => typeof check.format === "string" ? [check.format] : []);
383
+ return onNode ? [onNode, ...onChecks] : onChecks;
384
+ }
385
+ /**
386
+ * The whole rendering of a `number` node, because its *type* and its
387
+ * constraints are read from the same check list — `z.int()` is a format, and
388
+ * splitting the two would walk `_def.checks` twice per node.
389
+ */
390
+ function numberSchema(schema) {
391
+ const checks = schemaChecks(schema);
392
+ return {
393
+ type: declaredFormats(schema, checks).some((format) => INTEGER_NUMBER_FORMATS.has(format)) ? "integer" : "number",
394
+ ...numericConstraints(checks)
395
+ };
396
+ }
397
+ function stringConstraints(schema) {
398
+ const checks = schemaChecks(schema);
399
+ const constraints = lengthConstraints(checks, "minLength", "maxLength");
400
+ const format = declaredFormats(schema, checks).map((declared) => JSON_SCHEMA_STRING_FORMATS[declared]).find(Boolean);
401
+ if (format) constraints.format = format;
402
+ assignWithSurplus(constraints, "pattern", checks.flatMap((check) => {
403
+ if (check.check !== "string_format") return [];
404
+ if (typeof check.format !== "string" || !PATTERN_BEARING_FORMATS.has(check.format)) return [];
405
+ const pattern = patternSource(check);
406
+ return pattern ? [pattern] : [];
407
+ }));
408
+ return constraints;
409
+ }
410
+ /**
411
+ * Put the first value under `keyword` and fold any remainder into `allOf`.
412
+ *
413
+ * JSON Schema allows one `pattern` and one `multipleOf` per schema object, so a
414
+ * node carrying two of either (`z.string().regex(/^a/).startsWith('b')`,
415
+ * `z.number().multipleOf(2).multipleOf(3)`) cannot state both in place. Keeping
416
+ * only the first is not a lesser answer, it is a wrong one: the emitted schema
417
+ * then *accepts values the route rejects*, which is the one direction a derived
418
+ * contract must never be wrong in — an agent handed it will send input that
419
+ * fails validation. `allOf` conjoins, so the surplus stays enforceable.
420
+ *
421
+ * The first value stays on the node rather than going into `allOf` with the
422
+ * rest, so the overwhelmingly common single-constraint case emits flat.
423
+ * (zod's own emitter drops the surplus `multipleOf` outright here.)
424
+ */
425
+ function assignWithSurplus(constraints, keyword, values) {
426
+ const [first, ...surplus] = values;
427
+ if (first === void 0) return;
428
+ constraints[keyword] = first;
429
+ if (surplus.length > 0) constraints.allOf = surplus.map((value) => ({ [keyword]: value }));
430
+ }
431
+ /** A check's regex as a JSON Schema `pattern` — the source, never the `/…/` literal form. */
432
+ function patternSource(check) {
433
+ return check.pattern instanceof RegExp ? check.pattern.source : void 0;
434
+ }
435
+ function numericConstraints(checks) {
436
+ const constraints = {};
437
+ for (const check of checks) switch (check.check) {
438
+ case "greater_than": {
439
+ const value = numeric(check.value);
440
+ if (value === void 0) break;
441
+ if (check.inclusive === true) constraints.minimum = tightenLower(constraints.minimum, value);
442
+ else constraints.exclusiveMinimum = tightenLower(constraints.exclusiveMinimum, value);
443
+ break;
444
+ }
445
+ case "less_than": {
446
+ const value = numeric(check.value);
447
+ if (value === void 0) break;
448
+ if (check.inclusive === true) constraints.maximum = tightenUpper(constraints.maximum, value);
449
+ else constraints.exclusiveMaximum = tightenUpper(constraints.exclusiveMaximum, value);
450
+ break;
451
+ }
452
+ }
453
+ assignWithSurplus(constraints, "multipleOf", checks.flatMap((check) => {
454
+ if (check.check !== "multiple_of") return [];
455
+ const value = numeric(check.value);
456
+ return value === void 0 ? [] : [value];
457
+ }));
458
+ return constraints;
459
+ }
460
+ //#endregion
461
+ export { isZodSchema, readObjectSchema, toJsonSchema };
@@ -64,6 +64,8 @@ export interface GurenCliApi {
64
64
  className: string;
65
65
  }>;
66
66
  routes: Array<unknown>;
67
+ /** Why `routes` is empty, when it is empty because the load failed. */
68
+ routesError?: string;
67
69
  pages: string[];
68
70
  controllers: string[];
69
71
  resources: string[];
@@ -139,12 +141,39 @@ export interface GurenCliApi {
139
141
  generateApiClientTypes(definitions: unknown[], opts: CodegenOptions & {
140
142
  resources?: unknown[];
141
143
  }): Promise<CodegenResult | void>;
144
+ /**
145
+ * Agent tools derived from the route manifest (RFC 0016), so it runs after
146
+ * `generateRouteTypes` and — because a `resource` hint's payload type is
147
+ * embedded in a tool description — after `generateDataTypes` too. Optional
148
+ * because `@guren/cli` is resolved from the app at runtime and may predate
149
+ * it; an older CLI simply generates no agent manifest.
150
+ */
151
+ generateAgentTypes?(definitions: unknown[], opts: CodegenOptions & {
152
+ resources?: unknown[];
153
+ }): Promise<CodegenResult | void>;
142
154
  /**
143
155
  * Route-dependent context generation that re-runs the CLI in a fresh
144
156
  * process. Optional because `@guren/cli` is resolved from the app at
145
157
  * runtime and may predate it — see `McpServiceProvider`.
146
158
  */
147
159
  createFreshContextApi?: () => Pick<GurenCliApi, 'generateContext' | 'generateEntityContext'>;
160
+ /**
161
+ * Optional fields the CLI's context routes populate. Spelled exactly as
162
+ * `@guren/cli` exports it — this interface describes that module namespace,
163
+ * so a prettier camelCase name here would read `undefined` off every real
164
+ * CLI and silently answer "unsupported" forever.
165
+ *
166
+ * Optional for the same runtime-resolution reason as the members above, and
167
+ * read for exactly that reason: an older CLI emits routes with no `agent`
168
+ * field at all, which reads identically to an app exposing no agent tools.
169
+ */
170
+ CONTEXT_ROUTE_FEATURES?: readonly string[];
171
+ /**
172
+ * Every route as a context route, without building the rest of the project
173
+ * context. Optional like the above; `guren_agent_surface` falls back to
174
+ * `generateContext` when an older CLI does not provide it.
175
+ */
176
+ loadContextRoutes?(cwd: string, routesFile?: string, loadErrors?: string[]): Promise<unknown[]>;
148
177
  /**
149
178
  * The OKF docs relation graph (RFC 0005). Optional for the same
150
179
  * runtime-resolution reason as above.
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { r as createMcpServer, t as McpServiceProvider } from "../McpServiceProvider-D6D9nhgn.js";
1
+ import { r as createMcpServer, t as McpServiceProvider } from "../McpServiceProvider-BawsYjgN.js";
2
2
  export { McpServiceProvider, createMcpServer };
@@ -169,6 +169,32 @@ export declare class Controller {
169
169
  * Returns an empty array when none were uploaded.
170
170
  */
171
171
  protected files(name: string): Promise<File[]>;
172
+ /**
173
+ * The one multipart read behind {@link file} and {@link files}, guarded so a
174
+ * body the parser cannot decode carries no files rather than crashing the
175
+ * request: it reads as `{}`, which is the same answer both helpers already
176
+ * give for a field that is simply absent — `null` and `[]`. Left to throw,
177
+ * the parser's `TypeError` escaped as a 500 reporting the exception and a
178
+ * stack, the defect {@link parseRequestBody} fixes for the validation paths.
179
+ *
180
+ * Deliberately *not* routed through `parseRequestBody()`, which looks like
181
+ * the same rule and is not: it parses without `{ all: true }` and flattens a
182
+ * repeated field to its first value, so sharing it would silently reduce
183
+ * `files()` to one file per field. `{ all: true }` is the contract here, and
184
+ * a malformed-body test cannot see its loss — hence the separate helper.
185
+ *
186
+ * try/catch rather than `.catch()`, for the reason given on the shared
187
+ * fallback: `parseBody` may throw synchronously as well as reject, and only
188
+ * one of those two shapes reaches a `.catch()`.
189
+ *
190
+ * It fails open in one direction, deliberately and for the same reason
191
+ * {@link parseRequestBody} does: a body already consumed upstream reads as
192
+ * "no upload" rather than throwing, so a middleware-ordering bug loses the
193
+ * 500 that used to announce it. Telling that apart from a client's malformed
194
+ * body means matching runtime-specific error codes, which answer differently
195
+ * on Bun, Node and Workers.
196
+ */
197
+ private parseUploads;
172
198
  protected get auth(): AuthContext;
173
199
  protected make<K extends keyof ServiceBindings>(key: K): ServiceBindings[K];
174
200
  protected make<T>(key: string): T;
@@ -364,6 +390,26 @@ export declare class Controller {
364
390
  protected validateParamsSafe<T>(schema: ZodLikeSchema<T>): SafeValidationResult<T>;
365
391
  private runValidation;
366
392
  private runValidationSafe;
393
+ /**
394
+ * The parsed body as sent: an array stays an array, a string stays a string.
395
+ * Only validation reads it — a schema is what decides whether the shape is
396
+ * acceptable, so narrowing first would make a non-object contract
397
+ * unreachable.
398
+ *
399
+ * Memoized in a box rather than by truthiness: a body of `null`, `''`, `0`
400
+ * or `false` is a parsed body, and re-reading the request would find the
401
+ * stream consumed.
402
+ *
403
+ * No fallback of its own: an unparseable body already arrives here as `{}`
404
+ * from {@link parseRequestBody}, which is what gives every dispatch path the
405
+ * same answer. A second fallback here could only diverge from that one.
406
+ */
407
+ private getRawBody;
408
+ /**
409
+ * The record view of {@link getRawBody}, for the field-by-field helpers
410
+ * (`input`, `only`, `except`, `has`). A non-object body has no field to
411
+ * read, so it reads as `{}`.
412
+ */
367
413
  private getBody;
368
414
  }
369
415
  export {};
@@ -109,6 +109,8 @@ export interface RouteContractOptions<TParamsSchema extends SchemaLike<unknown>
109
109
  * and expose the record to the controller via `this.model(Post)`.
110
110
  */
111
111
  bind?: Record<string, RouteModelBinding>;
112
+ /** Agent exposure metadata (RFC 0016). See {@link AgentRouteMetadata}. */
113
+ agent?: AgentRouteMetadata;
112
114
  }
113
115
  export interface RouteOpenApiMetadata {
114
116
  summary?: string;
@@ -117,6 +119,39 @@ export interface RouteOpenApiMetadata {
117
119
  operationId?: string;
118
120
  deprecated?: boolean;
119
121
  }
122
+ /**
123
+ * Agent exposure metadata for a route (RFC 0016). Declaring it marks the
124
+ * route as an agent tool; everything else about the tool — its input schema,
125
+ * output schema, authorization — is derived from the contracts the route
126
+ * already carries, never restated here.
127
+ *
128
+ * Storage only: no defaults are applied at registration, and the router does
129
+ * not require a route name here — `.agent()` may legally be chained before
130
+ * `.name()`, so name-requirement enforcement is deliberately left to static
131
+ * checks over `definitions()` (a route without a name cannot become a tool;
132
+ * the name is the tool's identity).
133
+ */
134
+ export interface AgentRouteMetadata {
135
+ /** Tool description. Absent, the route's OpenAPI `description` ?? `summary` stands in. */
136
+ description?: string;
137
+ /** Tool name override. Defaults to the route name, used verbatim. */
138
+ toolName?: string;
139
+ /** Protocol surfaces this tool appears on. Unset surfaces count as exposed. */
140
+ expose?: {
141
+ mcp?: boolean;
142
+ webMcp?: boolean;
143
+ };
144
+ /** MCP ToolAnnotations override: the tool does not modify its environment. Unset: GET/QUERY routes read-only. */
145
+ readOnlyHint?: boolean;
146
+ /** MCP ToolAnnotations override. `false` is the strong claim "additive updates only"; unset keeps the spec default (true for non-read-only tools). */
147
+ destructiveHint?: boolean;
148
+ /** MCP ToolAnnotations override: repeat calls with the same arguments have no additional effect. Unset: PUT/DELETE routes idempotent. */
149
+ idempotentHint?: boolean;
150
+ /** Route invocations through an agent surface require server-side approval. */
151
+ approval?: 'required';
152
+ /** Argument fields masked in agent audit logs. */
153
+ redact?: string[];
154
+ }
120
155
  /**
121
156
  * Represents a registered route definition for introspection.
122
157
  */
@@ -161,6 +196,11 @@ export interface RouteDefinition {
161
196
  };
162
197
  /** Route model bindings: param name → bound model class name (from `bind`) */
163
198
  bindings?: Record<string, string>;
199
+ /**
200
+ * Agent exposure metadata as declared (RFC 0016) — raw, no defaults
201
+ * applied. Absence means the route is not an agent tool.
202
+ */
203
+ agent?: AgentRouteMetadata;
164
204
  summary?: string;
165
205
  description?: string;
166
206
  tags?: string[];
@@ -176,6 +216,8 @@ export interface RouteBuilder<M extends string = never> {
176
216
  name(routeName: string): RouteBuilder<M>;
177
217
  /** Attach middleware to this specific route. See {@link RouteMiddlewareInput}. */
178
218
  middleware(...items: RouteMiddlewareInput<M>[]): RouteBuilder<M>;
219
+ /** Expose this route as an agent tool (RFC 0016). See {@link AgentRouteMetadata}. */
220
+ agent(metadata: AgentRouteMetadata): RouteBuilder<M>;
179
221
  }
180
222
  /**
181
223
  * Accepted by `.middleware()`: a registered alias name or a handler function.
@@ -208,6 +250,14 @@ export interface ResourceRouteOptions {
208
250
  param?: string;
209
251
  only?: ResourceAction[];
210
252
  except?: ResourceAction[];
253
+ /**
254
+ * Per-action agent exposure (RFC 0016). An action not listed here is not
255
+ * exposed as a tool — deny by default, no `destroy: false` spelling needed.
256
+ * Listing an action this call does not register (excluded via `only`/
257
+ * `except`, or missing from the controller) throws: metadata for a tool
258
+ * that cannot exist is a wiring mistake, not a no-op.
259
+ */
260
+ agent?: Partial<Record<ResourceAction, AgentRouteMetadata>>;
211
261
  }
212
262
  /**
213
263
  * Instance-based router for app-local route registration and mounting.
@@ -288,6 +338,9 @@ export declare class Router<M extends string = never> {
288
338
  * thrown: `definitions()` must stay side-effect-free for introspection of
289
339
  * routers that never mount (audit, codegen), and an unresolvable alias
290
340
  * simply contributes no capabilities.
341
+ *
342
+ * This walks the chain; the rules for combining what it finds live with the
343
+ * capability type, in `mergeCapabilities`.
291
344
  */
292
345
  private aggregateCapabilities;
293
346
  private resolveMiddlewareNames;