@arbol-ai/maximus 7.4.0 → 8.0.1

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 (137) hide show
  1. package/README.md +36 -38
  2. package/bin/maximus.js +4 -0
  3. package/config/oxfmt.mjs +1 -0
  4. package/config/oxlint.mjs +10 -0
  5. package/dist/analytics/analytics.d.ts +21 -9
  6. package/dist/analytics/analytics.js +19 -5
  7. package/dist/body.d.ts +1 -1
  8. package/dist/body.js +2 -2
  9. package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
  10. package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
  11. package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
  12. package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
  13. package/dist/chunks/define-app-x7uY70_1.js +341 -0
  14. package/dist/chunks/{errors-D7zG9kx9.js → errors-C5w9WY1l.js} +10 -5
  15. package/dist/chunks/{execution-kVUJPy1A.js → execution-rOiLo8VG.js} +28 -15
  16. package/dist/chunks/generate-C-9FKW0o.js +197 -0
  17. package/dist/chunks/handler-iebR-urt.js +141 -0
  18. package/dist/chunks/http-layout-DS8DnPyu.js +128 -0
  19. package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
  20. package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
  21. package/dist/chunks/names-ncD7A3DV.js +280 -0
  22. package/dist/chunks/openapi-CeolxIqa.js +1588 -0
  23. package/dist/chunks/openapi-file-Bz9FRaE6.js +83 -0
  24. package/dist/chunks/pages-iZTvFs5a.js +14 -0
  25. package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
  26. package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
  27. package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
  28. package/dist/chunks/query-kind-CWKAXEME.js +40 -0
  29. package/dist/chunks/record-DQUDTpEA.js +10 -0
  30. package/dist/chunks/result-CKgZHrnj.js +56 -0
  31. package/dist/chunks/{runtime-DlqA7J38.js → runtime-D94vx21X.js} +50 -26
  32. package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
  33. package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
  34. package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
  35. package/dist/chunks/server-Bzf1Q1_4.js +410 -0
  36. package/dist/chunks/src-CPrJpbOM.js +573 -0
  37. package/dist/chunks/{standard-failures-CLjxS2ea.js → standard-failures-Lh4mSfwG.js} +1 -1
  38. package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
  39. package/dist/chunks/{types-DQdfRF3f.d.ts → types-DTIuIEJ-.d.ts} +1000 -342
  40. package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
  41. package/dist/chunks/workers-types-BRk_Xa_5.d.ts +143 -0
  42. package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
  43. package/dist/diagnostics.d.ts +6 -4
  44. package/dist/diagnostics.js +2 -2
  45. package/dist/errors.d.ts +2 -2
  46. package/dist/errors.js +2 -2
  47. package/dist/http-paths.d.ts +1 -1
  48. package/dist/http-paths.js +1 -1
  49. package/dist/index.d.ts +2 -2
  50. package/dist/index.js +12 -11
  51. package/dist/internals.d.ts +1 -1
  52. package/dist/internals.js +5 -4
  53. package/dist/mcp/index.d.ts +3 -2
  54. package/dist/mcp/index.js +5 -387
  55. package/dist/postgres/index.d.ts +25 -8
  56. package/dist/postgres/index.js +17 -8
  57. package/dist/project/config.d.ts +110 -72
  58. package/dist/project/config.js +161 -45
  59. package/dist/project/index.d.ts +17 -4
  60. package/dist/project/index.js +44 -9
  61. package/dist/projection.d.ts +14 -13
  62. package/dist/projection.js +8 -32
  63. package/dist/schemas.d.ts +1 -1
  64. package/dist/schemas.js +2 -2
  65. package/dist/standard-failures.d.ts +2 -89
  66. package/dist/standard-failures.js +1 -1
  67. package/dist/tooling/cli.js +149 -105
  68. package/dist/tooling/testing.js +2 -2
  69. package/dist/vite/cloudflare-workers.js +25 -0
  70. package/dist/vite/index.d.ts +157 -0
  71. package/dist/vite/index.js +1477 -0
  72. package/dist/webhooks.d.ts +12 -10
  73. package/dist/webhooks.js +26 -12
  74. package/dist/workers/runtime.d.ts +1 -1
  75. package/dist/workers/runtime.js +1 -1
  76. package/package.json +26 -22
  77. package/skills/maximus/SKILL.md +165 -68
  78. package/skills/maximus/references/deploying.md +73 -0
  79. package/skills/maximus/references/errors-and-results.md +114 -55
  80. package/skills/maximus/references/project.md +202 -0
  81. package/skills/maximus/references/routes-and-tools.md +256 -0
  82. package/skills/maximus/references/testing.md +137 -50
  83. package/skills/maximus/references/transports.md +113 -100
  84. package/skills/maximus/references/writing-code.md +84 -0
  85. package/templates/mcp/mcp/instructions.md.template +2 -0
  86. package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
  87. package/templates/mcp/tests/mcp.test.ts.template +36 -0
  88. package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
  89. package/templates/project/.github/workflows/ci.yml.template +4 -1
  90. package/templates/project/CLAUDE.md.template +41 -25
  91. package/templates/project/README.md.template +54 -48
  92. package/templates/project/middleware/10-response.ts.template +5 -2
  93. package/templates/project/package.json.template +13 -9
  94. package/templates/project/pages/index.ts.template +2 -4
  95. package/templates/project/routes/v1/greeting.get.ts.template +10 -0
  96. package/templates/project/routes/v1/greeting.post.ts.template +12 -0
  97. package/templates/project/tests/greeting.test.ts.template +45 -0
  98. package/templates/project/tsconfig.json.template +8 -6
  99. package/templates/project/vite.config.ts.template +15 -7
  100. package/templates/web/app/main.tsx.template +16 -0
  101. package/templates/web/app/root.tsx.template +17 -0
  102. package/templates/web/app/routes/index.tsx.template +9 -0
  103. package/templates/web/index.html.template +12 -0
  104. package/templates/web/package.json.template +12 -0
  105. package/templates/web/tsconfig.json.template +7 -0
  106. package/templates/web/vite.config.ts.template +22 -0
  107. package/dist/chunks/builder-BiXv7d2v.js +0 -100
  108. package/dist/chunks/define-app-DvD_1jUE.js +0 -625
  109. package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
  110. package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
  111. package/dist/chunks/record-DY-lX9w1.js +0 -34
  112. package/dist/chunks/src-N3oyx5QF.js +0 -1091
  113. package/dist/client/client.d.ts +0 -129
  114. package/dist/client/client.js +0 -321
  115. package/dist/tooling/vite.d.ts +0 -3
  116. package/dist/tooling/vite.js +0 -57
  117. package/skills/maximus/references/adding-an-operation.md +0 -179
  118. package/skills/maximus/references/building-a-service.md +0 -167
  119. package/skills/maximus/references/migration-from-v2.md +0 -62
  120. package/skills/maximus/references/migration-to-v5.md +0 -37
  121. package/skills/maximus/references/publishing-and-verification.md +0 -42
  122. package/templates/project/cloudflare.config.ts.template +0 -24
  123. package/templates/project/maximus.config.ts.template +0 -20
  124. package/templates/project/routes/v1/greeting.ts.template +0 -38
  125. package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
  126. package/templates/service/.github/workflows/ci.yml.template +0 -21
  127. package/templates/service/.gitignore.template +0 -9
  128. package/templates/service/CLAUDE.md.template +0 -5
  129. package/templates/service/README.md.template +0 -45
  130. package/templates/service/cloudflare.config.ts.template +0 -30
  131. package/templates/service/package.json.template +0 -36
  132. package/templates/service/src/app.ts.template +0 -30
  133. package/templates/service/src/index.ts.template +0 -13
  134. package/templates/service/tests/contract.test.ts.template +0 -12
  135. package/templates/service/tsconfig.json.template +0 -16
  136. package/templates/service/vite.config.ts.template +0 -13
  137. package/templates/service/vitest.config.ts.template +0 -10
@@ -0,0 +1,341 @@
1
+ import { u as hasUncompiledCodecs } from "./validation-fTohBT6R.js";
2
+ import { i as standardErrors } from "./errors-C5w9WY1l.js";
3
+ import { n as readBodyBytes } from "./body-DOIHwIIl.js";
4
+ import { a as operationPathParameters, r as isInputHeaderName, t as createHttpRouteResolver } from "./http-paths-DMBxwpp6.js";
5
+ import { i as pathParameterSchemas } from "./result-CKgZHrnj.js";
6
+ import { C as MAX_BODY_BYTES_CEILING, M as isNamespacedScope, f as hasSchemaReferences, j as operationScopes, r as checkTokenAuthority, s as tokenAudiences, t as createOpenApi, w as STANDARD_CODES } from "./openapi-CeolxIqa.js";
7
+ import { Kind } from "@sinclair/typebox";
8
+
9
+ // src/internal/exact-length.ts
10
+ /**
11
+ * Byte streams held to the length their headers declare.
12
+ */
13
+ /**
14
+ * Passes a byte stream through only while it keeps its declared length: a chunk that is not bytes,
15
+ * a byte beyond `length` or an end before it errors the stream, so a body never carries more or
16
+ * fewer bytes than its headers say.
17
+ */
18
+ function exactLength(stream, length) {
19
+ let received = 0;
20
+ return stream.pipeThrough(new TransformStream({
21
+ transform(chunk, controller) {
22
+ if (!(chunk instanceof Uint8Array)) throw new TypeError("A byte stream carried a chunk that is not bytes.");
23
+ received += chunk.byteLength;
24
+ if (received > length) throw new TypeError("A byte stream exceeds its declared length.");
25
+ controller.enqueue(chunk);
26
+ },
27
+ flush() {
28
+ if (received !== length) throw new TypeError("A byte stream ended before its declared length.");
29
+ }
30
+ }));
31
+ }
32
+
33
+ // src/binary.ts
34
+ /**
35
+ * Byte bodies and file attachments over HTTP: the on-demand reader of a declared byte body, the checks an
36
+ * attachment output passes before anything is sent, and the exact-length response that serves it.
37
+ */
38
+ /**
39
+ * The on-demand reader of a request's byte body, held to `maxBytes`. Creating it reads nothing and records
40
+ * nothing of the request.
41
+ */
42
+ function binaryBody(request, maxBytes) {
43
+ let reading;
44
+ return { read() {
45
+ reading ??= (async () => {
46
+ const encoding = request.headers.get("content-encoding");
47
+ if (encoding && encoding.toLowerCase() !== "identity") return {
48
+ ok: false,
49
+ error: standardErrors.unsupportedMedia.create()
50
+ };
51
+ const result = await readBodyBytes(request, {
52
+ maxBytes,
53
+ signal: request.signal
54
+ });
55
+ return result.ok ? result : {
56
+ ok: false,
57
+ error: result.error.data.reason === "too_large" ? standardErrors.tooLarge.create() : standardErrors.invalidInput.create()
58
+ };
59
+ })();
60
+ return reading;
61
+ } };
62
+ }
63
+ /** Whether an output schema is `AttachmentOutputSchema`. */
64
+ function isAttachmentSchema(schema) {
65
+ return schema[Kind] === "HttpAttachment";
66
+ }
67
+ /**
68
+ * Whether an output is a well-formed `Attachment` within `maxBytes`: exactly its four fields, bytes of
69
+ * exactly `byteLength` or an unlocked stream, a `type/subtype` media type of at most 255 characters, and a
70
+ * filename of 1 to 512 characters without control characters, slashes or backslashes. Execution checks it
71
+ * before anything is sent.
72
+ */
73
+ function validAttachment(value, maxBytes) {
74
+ if (!value || typeof value !== "object") return false;
75
+ const keys = Object.keys(value);
76
+ if (keys.length !== 4 || keys.some((key) => ![
77
+ "body",
78
+ "contentType",
79
+ "filename",
80
+ "byteLength"
81
+ ].includes(key))) return false;
82
+ const file = value;
83
+ if (!(file.body instanceof Uint8Array || file.body instanceof ReadableStream)) return false;
84
+ if (file.body instanceof ReadableStream && file.body.locked) return false;
85
+ if (!Number.isSafeInteger(file.byteLength) || file.byteLength < 0 || file.byteLength > maxBytes) return false;
86
+ if (file.body instanceof Uint8Array && file.body.byteLength !== file.byteLength) return false;
87
+ if (typeof file.contentType !== "string" || file.contentType.length > 255 || !/^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/u.test(file.contentType)) return false;
88
+ if (typeof file.filename !== "string" || !file.filename.length || file.filename.length > 512 || /[\p{Cc}/\\]/u.test(file.filename)) return false;
89
+ try {
90
+ encodeURIComponent(file.filename);
91
+ return true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+ /**
97
+ * The response that serves an attachment: its bytes with `content-type`, `content-length`, an RFC 8187
98
+ * `content-disposition`, `cache-control: private, no-store`, a sandboxing `content-security-policy` and
99
+ * `x-content-type-options: nosniff`. A stream is held to exactly `byteLength` bytes, so a handler can send
100
+ * neither more nor fewer than it declared.
101
+ */
102
+ function attachmentResponse(file, status = 200) {
103
+ const encodedFilename = encodeURIComponent(file.filename).replaceAll(/[!'()*]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
104
+ const body = file.body instanceof Uint8Array ? file.body : attachmentStream(file.body, file.byteLength);
105
+ return new Response(body, {
106
+ status,
107
+ headers: {
108
+ "cache-control": "private, no-store",
109
+ "content-type": file.contentType,
110
+ "content-length": String(file.byteLength),
111
+ "content-disposition": `attachment; filename="${file.filename.replaceAll(/[^\u0020-\u007E]|["\\]/gu, "_")}"; filename*=UTF-8''${encodedFilename}`,
112
+ "content-security-policy": "default-src 'none'; sandbox",
113
+ "x-content-type-options": "nosniff"
114
+ }
115
+ });
116
+ }
117
+ /** Workers determines Content-Length from the body, ignoring a header on an ordinary stream. */
118
+ function attachmentStream(body, byteLength) {
119
+ const bounded = exactLength(body, byteLength);
120
+ return typeof FixedLengthStream === "function" ? bounded.pipeThrough(new FixedLengthStream(byteLength)) : bounded;
121
+ }
122
+
123
+ // src/define-app.ts
124
+ /** Names a Worker entrypoint already uses, or that would break a class or a promise. */
125
+ const RESERVED_NAMES = /* @__PURE__ */ new Set([
126
+ "fetch",
127
+ "connect",
128
+ "constructor",
129
+ "then",
130
+ "scheduled",
131
+ "queue",
132
+ "alarm",
133
+ "__proto__",
134
+ "prototype"
135
+ ]);
136
+ /** An MCP tool name: a lowercase letter, then up to 63 letters, digits and underscores. */
137
+ const TOOL_NAME = /^[a-z][A-Za-z0-9_]{0,63}$/;
138
+ /** Every field an operation has: any other, such as a misspelled one, would do nothing. */
139
+ const OPERATION_FIELDS = new Set(Object.keys({
140
+ actorKinds: true,
141
+ http: true,
142
+ visibility: true,
143
+ mcp: true,
144
+ rpc: true,
145
+ scope: true,
146
+ scopeMatch: true,
147
+ conditionalScopes: true,
148
+ failures: true,
149
+ title: true,
150
+ description: true,
151
+ group: true,
152
+ effect: true,
153
+ input: true,
154
+ output: true,
155
+ maxBodyBytes: true,
156
+ maxOutputBytes: true,
157
+ execute: true,
158
+ pipeline: true
159
+ }));
160
+ /**
161
+ * Checks an application against every rule `.build()` enforces, then hands it back unchanged; a refusal is a
162
+ * TypeError. Curried, so `Env` and `C` can be given explicitly while the operations' types are inferred from
163
+ * the argument.
164
+ */
165
+ function defineApp() {
166
+ return (manifest) => {
167
+ checkApplication(manifest);
168
+ return manifest;
169
+ };
170
+ }
171
+ /**
172
+ * Every rule, in a fixed order, so an application that breaks several always meets the same refusal first.
173
+ */
174
+ function checkApplication(manifest) {
175
+ if (!/^[a-z][a-z0-9-]{1,63}$/.test(manifest.namespace)) throw new TypeError("A scope namespace is required.");
176
+ if (!/^[a-z][a-z0-9-]{1,63}$/.test(manifest.name)) throw new TypeError("An application name is a lowercase kebab-case word of 2 to 64 characters.");
177
+ checkDeclaredFailures(manifest.operations, manifest.errors);
178
+ const claimed = {
179
+ routes: /* @__PURE__ */ new Set(),
180
+ tools: /* @__PURE__ */ new Set()
181
+ };
182
+ for (const [name, op] of Object.entries(manifest.operations)) checkOperation(name, op, manifest, claimed);
183
+ createHttpRouteResolver(Object.values(manifest.operations));
184
+ checkSchemaReferences(manifest);
185
+ checkGuides(manifest.mcp?.guides ?? []);
186
+ checkSkills(manifest.mcp?.skills ?? []);
187
+ checkMcpResourceNames(manifest.mcp);
188
+ checkSkillTool(manifest.mcp, claimed.tools);
189
+ if (!validBodyLimit(manifest.maxBodyBytes)) throw new TypeError("The application body limit is a positive integer up to 16 MiB.");
190
+ if (!validBodyLimit(manifest.maxOutputBytes)) throw new TypeError("The application output limit is a positive integer up to 16 MiB.");
191
+ if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
192
+ checkTelemetry(manifest.telemetry);
193
+ checkTokenAuthority(manifest.tokens, manifest.namespace);
194
+ tokenAudiences(manifest.tokens);
195
+ if (Object.keys(manifest.tokens.resources ?? {}).length > 0 && manifest.tokens.resourceMetadataUrl === void 0) throw new TypeError("tokens.resources requires tokens.resourceMetadataUrl: name the metadata a 401 challenge points at.");
196
+ }
197
+ /** The callbacks an observer may have, each a function when present. */
198
+ const OBSERVER_CALLBACKS = [
199
+ "execution",
200
+ "admission",
201
+ "error"
202
+ ];
203
+ /** Whether a value is an observer: an object whose callbacks, when present, are functions. */
204
+ function isObserver(value) {
205
+ return typeof value === "object" && value !== null && OBSERVER_CALLBACKS.every((name) => {
206
+ const callback = Reflect.get(value, name);
207
+ return callback === void 0 || typeof callback === "function";
208
+ });
209
+ }
210
+ /**
211
+ * The telemetry option, as code untyped by TypeScript may give it: a switch that is a boolean or a function,
212
+ * observers that are objects whose callbacks are functions, and a trace id accessor that is a function. A
213
+ * malformed observer would fail every call it observes, and a switch such as `'false'` would leave telemetry
214
+ * on.
215
+ */
216
+ function checkTelemetry(telemetry) {
217
+ if (telemetry === void 0) return;
218
+ if (typeof telemetry !== "object" || telemetry === null || telemetry.enabled !== void 0 && typeof telemetry.enabled !== "boolean" && typeof telemetry.enabled !== "function" || telemetry.observers !== void 0 && (!Array.isArray(telemetry.observers) || !telemetry.observers.every(isObserver)) || telemetry.traceId !== void 0 && typeof telemetry.traceId !== "function") throw new TypeError("Telemetry takes enabled as true, false or a function of env, observers as a list of objects whose execution, admission and error are functions, and traceId as a function.");
219
+ }
220
+ /** An operation's `failures` name domain codes of the catalog, each once. */
221
+ function checkDeclaredFailures(operations, errors) {
222
+ const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
223
+ for (const [name, op] of Object.entries(operations)) if (op.failures && (new Set(op.failures).size !== op.failures.length || op.failures.some((code) => !domainCodes.has(code)))) throw new TypeError(`Operation "${name}": failures lists each domain failure code of the error catalog once; standard failures are always allowed.`);
224
+ }
225
+ /** Every rule one operation keeps, in the order a definition is usually written. */
226
+ function checkOperation(name, op, application, claimed) {
227
+ checkOperationContract(name, op, application.namespace);
228
+ if (application.tokens.scheme?.type === "oauth+bearer" && !op.actorKinds) throw new TypeError(`Operation "${name}": dual authentication requires explicit actor eligibility.`);
229
+ checkHttpExposure(name, op, claimed.routes);
230
+ if (op.conditionalScopes && (!op.conditionalScopes.length || new Set(op.conditionalScopes).size !== op.conditionalScopes.length || op.conditionalScopes.some((scope) => operationScopes(op).includes(scope) || !isNamespacedScope(scope, application.namespace)))) throw new TypeError(`Operation "${name}": conditional scopes require unique namespaced declarations distinct from the admission scope.`);
231
+ if (op.mcp) {
232
+ if (!TOOL_NAME.test(op.mcp.name) || claimed.tools.has(op.mcp.name)) throw new TypeError(`Operation "${name}": MCP tools require unique safe names.`);
233
+ claimed.tools.add(op.mcp.name);
234
+ }
235
+ if (op.rpc && op.rpc !== true && op.rpc.callers.some((caller) => !application.rpc.callers.includes(caller))) throw new TypeError(`Operation "${name}": RPC callers must be allowed by the application.`);
236
+ }
237
+ /** The operation's fields, name, scopes, eligible actors and schemas. */
238
+ function checkOperationContract(name, op, namespace) {
239
+ const unknown = Object.keys(op).find((field) => !OPERATION_FIELDS.has(field));
240
+ if (unknown !== void 0) throw new TypeError(`Operation "${name}": "${unknown}" is not an operation field.`);
241
+ if (op.scopeMatch !== void 0 && op.scopeMatch !== "any" && op.scopeMatch !== "all") throw new TypeError(`Operation "${name}": scopeMatch must be any or all.`);
242
+ if (hasUncompiledCodecs(op.input)) throw new TypeError(`Operation "${name}": its input uses codecs (normalize, transform, inspect, refine, pipe or stripObject) that run only inside inputSchema(); wrap the input in inputSchema().`);
243
+ if (op.actorKinds && (!op.actorKinds.length || new Set(op.actorKinds).size !== op.actorKinds.length || op.actorKinds.some((kind) => kind !== "user" && kind !== "service"))) throw new TypeError(`Operation "${name}": actorKinds must explicitly name eligible users or services.`);
244
+ if (!/^[a-z][a-zA-Z0-9]{0,99}$/.test(name) || RESERVED_NAMES.has(name)) throw new TypeError(`Operation "${name}": use a camelCase name of up to 100 characters that is not a reserved Worker method. Use safe operation names, namespaced scopes and strict object schemas.`);
245
+ const scopes = operationScopes(op);
246
+ if (!scopes.length || new Set(scopes).size !== scopes.length || scopes.some((scope) => !isNamespacedScope(scope, namespace))) throw new TypeError(`Operation "${name}": every scope is "${namespace}:<resource>:<action>", listed once. Use safe operation names, namespaced scopes and strict object schemas.`);
247
+ if (!(strictObject(op.input, op.http?.method !== "GET") && (isAttachmentSchema(op.output) || strictObject(op.output, true)))) throw new TypeError(`Operation "${name}": input and output are strict objects or unions of strict objects; a GET input is one strict object (its query). Use safe operation names, namespaced scopes and strict object schemas.`);
248
+ if (looseRecord(op.input) || looseRecord(op.output)) throw new TypeError(`Operation "${name}": a record whose keys follow a pattern takes additionalProperties: false, t.Record(key, value, { additionalProperties: false }), or a key outside the pattern passes unchecked.`);
249
+ }
250
+ /** Byte bodies, attachments, limits, header-sourced fields and the route itself. */
251
+ function checkHttpExposure(name, op, routes) {
252
+ if (op.http?.body !== void 0 && op.http.body !== "bytes" || op.http?.response !== void 0 && op.http.response !== "attachment") throw new TypeError(`Operation "${name}": unsupported HTTP binary contract.`);
253
+ const binary = op.http?.body === "bytes";
254
+ const attachment = isAttachmentSchema(op.output);
255
+ if ((binary || attachment) && (!op.http || op.mcp || op.rpc)) throw new TypeError(`Operation "${name}": byte bodies and attachments are HTTP-only.`);
256
+ if (op.http?.response === "attachment" !== attachment || binary && op.http?.method === "GET") throw new TypeError(`Operation "${name}": declare matching attachment output and non-GET byte bodies.`);
257
+ if (!validBodyLimit(op.maxOutputBytes)) throw new TypeError(`Operation "${name}": invalid output byte limit.`);
258
+ if (op.http?.successStatus !== void 0 && ![
259
+ 200,
260
+ 201,
261
+ 202
262
+ ].includes(op.http.successStatus)) throw new TypeError(`Operation "${name}": invalid success status; use 200, 201 or 202.`);
263
+ if (op.http?.headers) {
264
+ const pathFields = new Set(operationPathParameters(op.http.path));
265
+ const headers = Object.entries(op.http.headers);
266
+ if (!binary || op.input.type !== "object" || new Set(headers.map(([, wire]) => wire.toLowerCase())).size !== headers.length || headers.some(([field, wire]) => !Object.hasOwn(op.input.properties, field) || pathFields.has(field) || !isInputHeaderName(wire))) throw new TypeError(`Operation "${name}": byte operation headers must name unique, non-authority metadata fields.`);
267
+ }
268
+ if (!validBodyLimit(op.maxBodyBytes) || op.maxBodyBytes !== void 0 && op.http?.method === "GET") throw new TypeError(`Operation "${name}": an operation body limit is a positive integer up to 16 MiB, on a non-GET route.`);
269
+ if (op.http) {
270
+ for (const parameter of operationPathParameters(op.http.path)) pathParameterSchemas(op.input, parameter);
271
+ const route = `${op.http.method} ${op.http.path}`;
272
+ if (routes.has(route) || op.effect !== "read" && op.http.method === "GET") throw new TypeError(`Operation "${name}": use unique versioned routes; mutations cannot use GET.`);
273
+ routes.add(route);
274
+ }
275
+ }
276
+ /**
277
+ * A schema reference (TypeBox `Ref` or `Recursive`) resolves when the OpenAPI document bundles the schemas,
278
+ * to the one definition its name has. An application whose schemas refer to a name is bundled at
279
+ * construction, so a reference that names no single definition is refused before the service starts rather
280
+ * than when the document is first requested; schemas without references have nothing to resolve.
281
+ */
282
+ function checkSchemaReferences(manifest) {
283
+ if ([...Object.values(manifest.operations).flatMap((op) => [op.input, op.output]), ...Object.values(manifest.errors.definitions).map((definition) => definition.dataSchema)].some(hasSchemaReferences)) createOpenApi(manifest);
284
+ }
285
+ /** Guides are named resources and prompts: each name safe and unique. */
286
+ function checkGuides(guides) {
287
+ if (new Set(guides.map((guide) => guide.name)).size !== guides.length || guides.some((guide) => !/^[a-z][a-z0-9-]{0,63}$/.test(guide.name))) throw new TypeError("Guides require unique safe names.");
288
+ }
289
+ /** The names of the MCP resources the server always lists: the OpenAPI document as JSON and as YAML. */
290
+ const OPENAPI_RESOURCES = ["openapi-json", "openapi-yaml"];
291
+ /**
292
+ * Guides and skills name MCP resources beside the OpenAPI document's, so each name stands for one resource: a
293
+ * guide and a skill never share one, and neither takes `openapi-json` or `openapi-yaml`. `maximus prepare`
294
+ * applies this to `mcp/guides/` and `mcp/skills/` too.
295
+ */
296
+ function checkMcpResourceNames(mcp) {
297
+ const taken = new Set(OPENAPI_RESOURCES);
298
+ for (const { name } of [...mcp?.guides ?? [], ...mcp?.skills ?? []]) {
299
+ if (taken.has(name)) throw new TypeError(`MCP resource name ${name} is taken: guides and skills need names of their own, and openapi-json and openapi-yaml name the OpenAPI document.`);
300
+ taken.add(name);
301
+ }
302
+ }
303
+ /** The MCP skills: unique Agent Skills names, one-line descriptions and instructions. */
304
+ function checkSkills(skills) {
305
+ if (new Set(skills.map((skill) => skill.name)).size !== skills.length || skills.some((skill) => skill.name.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skill.name) || !skill.description.trim() || skill.description.length > 1024 || /[\r\n]/.test(skill.description) || !skill.text.trim())) throw new TypeError("Skills require unique Agent Skills names, a one-line description and instructions.");
306
+ }
307
+ /** The skill tool serves the MCP skills under a name no operation's tool takes. */
308
+ function checkSkillTool(mcp, tools) {
309
+ const skillTool = mcp?.skillTool;
310
+ if (skillTool !== void 0 && (!(mcp?.skills ?? []).length || !TOOL_NAME.test(skillTool) || tools.has(skillTool))) throw new TypeError("A skill tool requires skills and a safe name no operation uses.");
311
+ }
312
+ /** Whether a body or output limit is absent, or a positive integer up to 16 MiB. */
313
+ function validBodyLimit(value) {
314
+ return value === void 0 || Number.isInteger(value) && value > 0 && value <= 16777216;
315
+ }
316
+ /** The key pattern of `t.Record(t.String(), value)`, which every key matches, so every value is checked. */
317
+ const ANY_KEY = "^(.*)$";
318
+ /**
319
+ * Whether a schema holds, at any depth, a record whose keys follow a pattern but that admits other keys:
320
+ * without `additionalProperties: false`, a key outside the pattern passes with any value at all.
321
+ */
322
+ function looseRecord(schema) {
323
+ if (Array.isArray(schema)) return schema.some(looseRecord);
324
+ if (!schema || typeof schema !== "object") return false;
325
+ const node = schema;
326
+ const patterns = node.patternProperties;
327
+ if (patterns && typeof patterns === "object" && node.additionalProperties !== false && Object.keys(patterns).some((pattern) => pattern !== ANY_KEY)) return true;
328
+ return Object.values(node).some(looseRecord);
329
+ }
330
+ /**
331
+ * A strict object (`additionalProperties: false`), or — when `unions` is true —
332
+ * a union whose every member is a strict object, so a request body or a result
333
+ * can be discriminated by a field (`{ channel: 'email', … } | { channel: 'sms', … }`).
334
+ */
335
+ function strictObject(schema, unions) {
336
+ if (schema.type === "object") return schema.additionalProperties === false;
337
+ const members = schema.anyOf;
338
+ return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
339
+ }
340
+
341
+ export { isAttachmentSchema as a, binaryBody as i, defineApp as n, validAttachment as o, attachmentResponse as r, checkMcpResourceNames as t };
@@ -1,5 +1,5 @@
1
- import { t as STANDARD_FAILURES } from "./standard-failures-CLjxS2ea.js";
2
- import { i as parseSchema } from "./validation-r-sgmsqb.js";
1
+ import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
2
+ import { i as parseSchema } from "./validation-fTohBT6R.js";
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { Value } from "@sinclair/typebox/value";
5
5
 
@@ -10,8 +10,8 @@ import { Value } from "@sinclair/typebox/value";
10
10
  * failure an operation returns.
11
11
  */
12
12
  /**
13
- * Every failure, whatever its code: the base each catalog's failures narrow. The OpenAPI document
14
- * names it `Failure`, so every service's errors share one type.
13
+ * Every failure, whatever its code: the shape each catalog's failures narrow, which every service's errors
14
+ * share. The OpenAPI document names each code's own failure, `NoteNotFoundFailure`, which fixes its code.
15
15
  */
16
16
  const FailureSchema = Type.Object({
17
17
  code: Type.String({ description: "The failure code, stable across releases." }),
@@ -33,6 +33,8 @@ const InputIssuesSchema = Type.Object({ issues: Type.Optional(Type.Array(Type.Ob
33
33
  $id: "ValidationIssue",
34
34
  additionalProperties: false
35
35
  }), { maxItems: 10 })) }, { additionalProperties: false });
36
+ /** A failure code: uppercase words joined by underscores, as clients branch on it and observations carry it. */
37
+ const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,80}$/;
36
38
  /** The standard failures as a catalog defines them; INVALID_INPUT carries its field issues. */
37
39
  const STANDARD = {
38
40
  ...STANDARD_FAILURES,
@@ -77,7 +79,9 @@ const CATALOG_MEMBERS = {
77
79
  /**
78
80
  * An error catalog: the standard failures and the application's own, each with a fixed code, status, message
79
81
  * and retry semantics. `catalog.name.create(data?)` builds a failure; the application validates every failure
80
- * an operation returns against the catalog.
82
+ * an operation returns against the catalog. It throws a TypeError for a name the standard failures or the
83
+ * catalog's members use, a code that is not uppercase words joined by underscores, a repeated code, a status
84
+ * outside 400 to 599, or a `dataSchema` that is not a strict object.
81
85
  */
82
86
  function defineErrors(domain) {
83
87
  const own = domain;
@@ -88,6 +92,7 @@ function defineErrors(domain) {
88
92
  };
89
93
  const byCode = /* @__PURE__ */ new Map();
90
94
  for (const definition of Object.values(definitions)) {
95
+ if (!ERROR_CODE.test(definition.code)) throw new TypeError(`An error code is uppercase words joined by underscores, such as RECORD_NOT_FOUND: ${definition.code}`);
91
96
  if (byCode.has(definition.code) || definition.status < 400 || definition.status > 599) throw new TypeError("Error definitions require unique codes and failure statuses.");
92
97
  if ("dataSchema" in definition && definition.dataSchema && (definition.dataSchema.type !== "object" || definition.dataSchema.additionalProperties !== false)) throw new TypeError("Domain error data must be a strict object schema.");
93
98
  byCode.set(definition.code, definition);
@@ -1,7 +1,9 @@
1
- import { t as decodeInput } from "./validation-r-sgmsqb.js";
2
- import { i as standardErrors } from "./errors-D7zG9kx9.js";
3
- import { A as validAttachment, C as operationOutputLimit, S as operationMatchesScopes, g as STANDARD_CODES, k as isAttachmentSchema, u as err } from "./define-app-DvD_1jUE.js";
4
- import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-BTwB68m5.js";
1
+ import { t as decodeInput } from "./validation-fTohBT6R.js";
2
+ import { i as standardErrors } from "./errors-C5w9WY1l.js";
3
+ import { a as isAttachmentSchema, o as validAttachment } from "./define-app-x7uY70_1.js";
4
+ import { t as err } from "./result-CKgZHrnj.js";
5
+ import { A as operationOutputLimit, b as ADMISSION_CODES, k as operationMatchesScopes, w as STANDARD_CODES, x as BODY_CODES } from "./openapi-CeolxIqa.js";
6
+ import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-C3LfZcOB.js";
5
7
  import { Value } from "@sinclair/typebox/value";
6
8
 
7
9
  // src/execution.ts
@@ -10,15 +12,18 @@ import { Value } from "@sinclair/typebox/value";
10
12
  * preparation, middleware, the handler, and the checks on what it returns.
11
13
  */
12
14
  /**
13
- * The execution path every transport shares: checks that the caller may run the operation, decodes the input,
14
- * prepares the context, runs the middleware and the handler, then checks the result against the declared
15
- * output and failures. An unexpected error becomes `INTERNAL_ERROR` and is reported, never thrown.
15
+ * The execution path every transport shares: checks that the caller may run the operation (its scopes when
16
+ * `authority` is given, its actor kind, and `authority` itself when the operation has conditional scopes),
17
+ * decodes the input, prepares the context, runs the middleware and the handler, then checks the result
18
+ * against the catalog, the declared failures, the output schema and the output limit. A refused caller
19
+ * answers `FORBIDDEN` and a refused input `INVALID_INPUT`. An unexpected error becomes `INTERNAL_ERROR`,
20
+ * reported while telemetry is on, and is never thrown.
16
21
  */
17
22
  async function executeOperation(manifest, operation, env, principal, input, authority, background, body) {
18
23
  if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
19
- const admitted = decodeInput(operation.input, input);
20
- if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
21
24
  try {
25
+ const admitted = decodeInput(operation.input, input);
26
+ if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
22
27
  const trustedAuthority = authority ? Object.freeze({
23
28
  surface: authority.surface,
24
29
  scopes: Object.freeze([...authority.scopes]),
@@ -33,8 +38,20 @@ async function executeOperation(manifest, operation, env, principal, input, auth
33
38
  ...background ? { background } : {},
34
39
  ...trustedAuthority ? { authority: trustedAuthority } : {}
35
40
  };
41
+ /**
42
+ * A failure the call answers, from its context, middleware or handler: one of the catalog and, when the
43
+ * operation declares its failures, a declared or standard one. A failure only admission answers, or a
44
+ * body's for an operation that reads no byte body, is never the operation's. Any other is the server's
45
+ * error.
46
+ */
47
+ const declared = (answered) => {
48
+ const failure = manifest.errors.validate(answered);
49
+ if (ADMISSION_CODES.has(failure.code) || BODY_CODES.has(failure.code) && operation.http?.body !== "bytes") throw new TypeError(`Failure ${failure.code} is answered before an operation runs, never by it`);
50
+ if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
51
+ return failure;
52
+ };
36
53
  const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
37
- if (!context.ok) return err(manifest.errors.validate(context.error));
54
+ if (!context.ok) return err(declared(context.error));
38
55
  const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
39
56
  let latest = -1;
40
57
  /**
@@ -49,11 +66,7 @@ async function executeOperation(manifest, operation, env, principal, input, auth
49
66
  };
50
67
  const result = await dispatch(0);
51
68
  if (!result || typeof result.ok !== "boolean" || !Object.hasOwn(result, "ok") || Object.keys(result).length !== 2 || !Object.hasOwn(result, result.ok ? "value" : "error")) throw new TypeError("Invalid operation result");
52
- if (!result.ok) {
53
- const failure = manifest.errors.validate(result.error);
54
- if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
55
- return err(failure);
56
- }
69
+ if (!result.ok) return err(declared(result.error));
57
70
  const maxOutputBytes = operationOutputLimit(manifest, operation);
58
71
  if (isAttachmentSchema(operation.output)) {
59
72
  if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
@@ -0,0 +1,197 @@
1
+ import { a as operationPathParameters } from "./http-paths-DMBxwpp6.js";
2
+ import { a as projectPath, i as projectFiles, n as checkProjectFolder, s as routeShape } from "./project-files-C0OX7MQQ.js";
3
+ import { existsSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+
6
+ // src/tooling/internal/generate.ts
7
+ /**
8
+ * `maximus gen`: a new route or MCP tool file, named and placed by the conventions prepare reads, with a
9
+ * handler and a contract to fill in. An existing module is never overwritten, and neither is a route a file
10
+ * already answers.
11
+ */
12
+ /** The methods a route file may answer, by the suffix its name takes. */
13
+ const METHODS = [
14
+ "get",
15
+ "post",
16
+ "put",
17
+ "patch",
18
+ "delete"
19
+ ];
20
+ /** A tool's file name, which names it: lowercase words joined by single hyphens. */
21
+ const TOOL = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
22
+ /** An MCP tool name a route declares: lowercase words joined by single underscores. */
23
+ const TOOL_NAME = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
24
+ /** The widest line the project's formatter writes, in characters. */
25
+ const PRINT_WIDTH = 110;
26
+ /** The base path a project serves its API below unless its configuration moves it. */
27
+ const API_BASE_PATH = "/api";
28
+ /** A one-sentence JSDoc comment: on one line when it fits, otherwise wrapped at the formatter's width. */
29
+ function jsDoc(sentence) {
30
+ const line = `/** ${sentence} */`;
31
+ if (line.length <= PRINT_WIDTH) return [line];
32
+ const lines = [];
33
+ let current = " *";
34
+ for (const word of sentence.split(" ")) {
35
+ const fitsAlone = ` * ${word}`.length <= PRINT_WIDTH;
36
+ if (current !== " *" && fitsAlone && `${current} ${word}`.length > PRINT_WIDTH) {
37
+ lines.push(current);
38
+ current = " *";
39
+ }
40
+ current = `${current} ${word}`;
41
+ }
42
+ return [
43
+ "/**",
44
+ ...lines,
45
+ current,
46
+ " */"
47
+ ];
48
+ }
49
+ /** `head{ a, b }tail`, as the formatter writes it: on one line when it fits, otherwise one entry per line. */
50
+ function braces(indent, head, entries, tail) {
51
+ const line = `${indent}${head}{ ${entries.join(", ")} }${tail}`;
52
+ if (line.length <= PRINT_WIDTH) return [line];
53
+ return [
54
+ `${indent}${head}{`,
55
+ ...entries.map((entry) => `${indent} ${entry},`),
56
+ `${indent}}${tail}`
57
+ ];
58
+ }
59
+ /** `const { a, b } = input;` as the formatter writes it: it breaks after `=` before it breaks the braces. */
60
+ function destructureInput(indent, names) {
61
+ const pattern = `${indent}const { ${names.join(", ")} } =`;
62
+ if (`${pattern} input;`.length <= PRINT_WIDTH) return [`${pattern} input;`];
63
+ if (pattern.length <= PRINT_WIDTH) return [pattern, `${indent} input;`];
64
+ return braces(indent, "const ", names, " = input;");
65
+ }
66
+ /** A contract field whose value is text, as the formatter writes it: a long text on a line of its own. */
67
+ function textField(indent, name, text) {
68
+ const line = `${indent}${name}: '${text}',`;
69
+ if (line.length <= PRINT_WIDTH) return [line];
70
+ return [`${indent}${name}:`, `${indent} '${text}',`];
71
+ }
72
+ /**
73
+ * A placeholder handler that answers its input fields back, written as statements: it names the fields it
74
+ * takes, then answers them.
75
+ */
76
+ function echoHandler(names) {
77
+ return [
78
+ " ({ input }) => {",
79
+ ...destructureInput(" ", names),
80
+ ...braces(" ", "return ", names, ";"),
81
+ " },"
82
+ ];
83
+ }
84
+ /**
85
+ * A route's path as file segments: `/v1/tasks/{taskId}`, `/v1/tasks/:taskId` and `v1/tasks/[taskId]` are
86
+ * `v1`, `tasks` and `[taskId]`. A leading `/api` is the base path, not the route's.
87
+ */
88
+ function routeSegments(path) {
89
+ const segments = path.replace(/^\/?api(?=\/v[1-9])/, "").split("/").filter(Boolean).map((segment) => {
90
+ const parameter = /^(?:\{([a-zA-Z][a-zA-Z0-9_]*)\}|:([a-zA-Z][a-zA-Z0-9_]*)|\[([a-zA-Z][a-zA-Z0-9_]*)\])$/.exec(segment);
91
+ if (parameter) return `[${parameter[1] ?? parameter[2] ?? parameter[3]}]`;
92
+ if (!/^[a-zA-Z0-9_-]+$/.test(segment)) throw new TypeError(`Use letters, digits, _ and - in a fixed segment, and {name} for a parameter: ${segment}`);
93
+ return segment;
94
+ });
95
+ if (!/^v[1-9][0-9]*$/.test(segments[0] ?? "") || segments.length < 2) throw new TypeError(`A route lives below its API version, such as /v1/tasks: ${path}`);
96
+ return segments;
97
+ }
98
+ /**
99
+ * Writes a new file of the project, refusing an existing one, a path that leads outside the project and a
100
+ * folder on the way that is a symlink.
101
+ */
102
+ function writeModule(root, path, text) {
103
+ const target = resolve(root, path);
104
+ if (relative(root, target).startsWith("..")) throw new TypeError(`${path} is outside the project.`);
105
+ checkProjectFolder(root, dirname(target));
106
+ if (existsSync(target) || lstatSync(target, { throwIfNoEntry: false })) throw new TypeError(`${path} exists; edit it instead.`);
107
+ mkdirSync(dirname(target), { recursive: true });
108
+ writeFileSync(target, text, { flag: "wx" });
109
+ return target;
110
+ }
111
+ /**
112
+ * Writes `routes/<path>.<method>.ts`, or `routes/<path>/index.<method>.ts` when `<path>` is already a folder,
113
+ * declaring a route that takes its path parameters and answers them back, an MCP tool too when `tool` names
114
+ * it. Refuses a method and path a route file already answers.
115
+ */
116
+ function generateRoute(directory, method, path, tool) {
117
+ const root = resolve(directory);
118
+ const verb = method.toLowerCase();
119
+ if (!METHODS.some((known) => known === verb)) throw new TypeError(`Choose a route method: ${METHODS.join(", ")}.`);
120
+ if (tool !== void 0 && !TOOL_NAME.test(tool)) throw new TypeError(`Name an MCP tool in snake_case, such as get_task: ${tool}`);
121
+ const segments = routeSegments(path);
122
+ const routePath = projectPath(segments.join("/"), "routes");
123
+ operationPathParameters(routePath);
124
+ for (const { name, file } of projectFiles(root, "routes", "development")) {
125
+ const suffix = /\.(get|post|put|patch|delete)$/.exec(name);
126
+ if (suffix?.[1] === verb && routeShape(projectPath(name.slice(0, -suffix[0].length), "routes")) === routeShape(routePath)) throw new TypeError(`${relative(root, file)} already answers ${verb.toUpperCase()} ${routePath}.`);
127
+ }
128
+ const folder = join("routes", ...segments);
129
+ const file = existsSync(join(root, folder)) ? join(folder, `index.${verb}.ts`) : `${folder}.${verb}.ts`;
130
+ const parameters = segments.flatMap((segment) => segment.startsWith("[") ? [segment.slice(1, -1)] : []);
131
+ const call = `${verb.toUpperCase()} ${API_BASE_PATH}${routePath}`;
132
+ const exposure = tool ? `${call}, also the MCP tool ${tool}` : call;
133
+ return {
134
+ file: writeModule(root, file, [
135
+ `import { defineHandler${parameters.length ? ", t" : ""} } from '@arbol-ai/maximus';`,
136
+ "",
137
+ ...jsDoc(`${exposure}: what it answers, in a few words.`),
138
+ ...routeDeclaration(call, parameters, tool),
139
+ ""
140
+ ].join("\n")),
141
+ method: verb.toUpperCase(),
142
+ path: routePath
143
+ };
144
+ }
145
+ /**
146
+ * A route's `defineHandler` call: a placeholder handler that answers its path parameters back, and a
147
+ * contract whose description says what to write there. A route without parameters takes and answers nothing.
148
+ */
149
+ function routeDeclaration(call, parameters, tool) {
150
+ const indent = parameters.length ? " " : " ";
151
+ const fields = parameters.map((parameter) => `${parameter}: t.String()`);
152
+ const contract = [
153
+ ...textField(indent, "description", `Write one sentence that tells callers what ${call} does.`),
154
+ ...fields.length ? braces(indent, "input: ", fields, ",") : [],
155
+ ...fields.length ? braces(indent, "output: ", fields, ",") : [],
156
+ ...tool ? [`${indent}mcp: { name: '${tool}' },`] : []
157
+ ];
158
+ if (!parameters.length) return [
159
+ "export default defineHandler(() => {}, {",
160
+ ...contract,
161
+ "});"
162
+ ];
163
+ return [
164
+ "export default defineHandler(",
165
+ ...echoHandler(parameters),
166
+ " {",
167
+ ...contract,
168
+ " }",
169
+ ");"
170
+ ];
171
+ }
172
+ /** Writes `mcp/tools/<name>.ts`, an MCP tool only agents call, named `<name>` in snake_case. */
173
+ function generateTool(directory, name) {
174
+ if (!TOOL.test(name)) throw new TypeError(`Name a tool file in kebab-case, such as summarize-tasks: ${name}`);
175
+ const tool = name.replaceAll("-", "_");
176
+ const text = [
177
+ "import { defineTool, t } from '@arbol-ai/maximus';",
178
+ "",
179
+ ...jsDoc(`The MCP tool ${tool}, which no HTTP route serves: what it answers, in a few words.`),
180
+ "export default defineTool(",
181
+ ...echoHandler(["text"]),
182
+ " {",
183
+ ...textField(" ", "description", `Write one sentence that tells agents what ${tool} does.`),
184
+ " effect: 'read',",
185
+ " input: { text: t.String({ maxLength: 1000 }) },",
186
+ " output: { text: t.String() },",
187
+ " }",
188
+ ");",
189
+ ""
190
+ ].join("\n");
191
+ return {
192
+ file: writeModule(resolve(directory), join("mcp", "tools", `${name}.ts`), text),
193
+ tool
194
+ };
195
+ }
196
+
197
+ export { generateRoute, generateTool };