@arbol-ai/maximus 7.3.1 → 8.0.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 (138) 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-CfVZBt7D.js +336 -0
  14. package/dist/chunks/errors-WfyKhiyk.js +131 -0
  15. package/dist/chunks/execution-CfZEx_JP.js +84 -0
  16. package/dist/chunks/generate-C-9FKW0o.js +197 -0
  17. package/dist/chunks/handler-DWTGoduQ.js +140 -0
  18. package/dist/chunks/http-layout-_h7xwgPC.js +128 -0
  19. package/dist/chunks/http-paths-DMBxwpp6.js +218 -0
  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-CV0KmJpS.js +1588 -0
  23. package/dist/chunks/openapi-file-OjSs9mRv.js +83 -0
  24. package/dist/chunks/pages-DyC0m8Zb.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-BPnaa-NK.js → runtime-CVVf5hmp.js} +50 -25
  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-CCc7fil4.js +410 -0
  36. package/dist/chunks/src--HZrH1U9.js +568 -0
  37. package/dist/chunks/standard-failures-CLjxS2ea.js +74 -0
  38. package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
  39. package/dist/chunks/{types-BWxDd3tY.d.ts → types-BQYB4Ads.d.ts} +998 -337
  40. package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
  41. package/dist/chunks/workers-types-iONp32T4.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 -125
  47. package/dist/http-paths.d.ts +1 -1
  48. package/dist/http-paths.js +1 -197
  49. package/dist/index.d.ts +2 -2
  50. package/dist/index.js +12 -10
  51. package/dist/internals.d.ts +1 -1
  52. package/dist/internals.js +5 -3
  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 +139 -0
  58. package/dist/project/config.js +196 -0
  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 -72
  67. package/dist/tooling/cli.js +151 -107
  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 +30 -22
  77. package/skills/maximus/SKILL.md +165 -69
  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 -22
  91. package/templates/project/README.md.template +54 -47
  92. package/templates/project/middleware/10-response.ts.template +16 -0
  93. package/templates/project/package.json.template +16 -8
  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 -5
  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/execution-B-yy4C7N.js +0 -691
  108. package/dist/chunks/prepare-project-zi106pWF.js +0 -146
  109. package/dist/chunks/record-DY-lX9w1.js +0 -34
  110. package/dist/chunks/src-DPSpGNnT.js +0 -1164
  111. package/dist/client/client.d.ts +0 -129
  112. package/dist/client/client.js +0 -321
  113. package/dist/tooling/vite.d.ts +0 -3
  114. package/dist/tooling/vite.js +0 -44
  115. package/skills/maximus/references/adding-an-operation.md +0 -179
  116. package/skills/maximus/references/building-a-service.md +0 -167
  117. package/skills/maximus/references/migration-from-v2.md +0 -62
  118. package/skills/maximus/references/migration-to-v5.md +0 -37
  119. package/skills/maximus/references/publishing-and-verification.md +0 -39
  120. package/templates/project/cloudflare.config.ts.template +0 -24
  121. package/templates/project/routes/v1/greeting.ts.template +0 -22
  122. package/templates/project/src/app.ts.template +0 -2
  123. package/templates/project/src/application.ts.template +0 -26
  124. package/templates/project/src/index.ts.template +0 -3
  125. package/templates/project/src/worker.ts.template +0 -6
  126. package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
  127. package/templates/service/.github/workflows/ci.yml.template +0 -21
  128. package/templates/service/.gitignore.template +0 -9
  129. package/templates/service/CLAUDE.md.template +0 -5
  130. package/templates/service/README.md.template +0 -45
  131. package/templates/service/cloudflare.config.ts.template +0 -30
  132. package/templates/service/package.json.template +0 -36
  133. package/templates/service/src/app.ts.template +0 -30
  134. package/templates/service/src/index.ts.template +0 -13
  135. package/templates/service/tests/contract.test.ts.template +0 -12
  136. package/templates/service/tsconfig.json.template +0 -16
  137. package/templates/service/vite.config.ts.template +0 -13
  138. package/templates/service/vitest.config.ts.template +0 -10
@@ -1,119 +1,132 @@
1
1
  # Transports
2
2
 
3
- | | HTTP | MCP | Native RPC |
4
- | --- | --- | --- | --- |
5
- | Opt in | `http: { method, path }` | `mcp: { name, idempotent }` + `transports: [mcp()]` | `rpc: true` or `{ callers }` + app `rpc.callers` |
6
- | Caller proves | Bearer token | Bearer token with `<namespace>:mcp:use` | Service Binding props `{ caller }` |
7
- | Scopes checked | Yes | Yes, also to list tools | No |
8
- | Success | Envelope `{ success: true, data, error: null, metadata: { requestId } }` | `structuredContent` + JSON text | `{ ok: true, value }` |
9
- | Failure | Catalog status + `{ success: false, data: null, error, metadata }` | `isError: true`, failure JSON text | `{ ok: false, error }` |
3
+ | | HTTP | MCP | Worker RPC |
4
+ | -------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
5
+ | Opt in | Every route | `mcp: { name }` in a route's contract, or a file of `mcp/tools/` | `rpc: true` or `{ callers }` in the contract, and the caller in `maximus()`'s `rpc.callers` |
6
+ | Caller proves | An access token that holds the operation's scope | The same, and `<namespace>:mcp:use` | Its Service Binding's props, `{ caller }` |
7
+ | Scopes checked | Yes | Yes, to list tools and to call them | No: the calling deployment is trusted |
8
+ | Success | `{ success: true, data, error: null, metadata: { requestId } }` | The output as `structuredContent`, and as JSON text | `{ ok: true, value }` |
9
+ | Failure | The code's status, `{ success: false, data: null, error, metadata }` | A result with `isError: true`, the failure as text | `{ ok: false, error }` |
10
10
 
11
- All three share input validation, `derive`, middleware, the handler and output validation.
11
+ All three share the input check, `context.ts`, operation middleware, the handler and the output check.
12
12
 
13
13
  ## HTTP and OpenAPI
14
14
 
15
- - Responses always carry `x-request-id`, `cache-control: private, no-store`, `nosniff` and
16
- `server-timing`. A `401` carries `WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource"`.
17
- - `/openapi.json`, `/openapi.yaml`, `/openapi.yml`: OpenAPI 3.1 of the public HTTP operations (never
18
- an internal one): scopes as OAuth security requirements (`<issuer>authorize`, `<issuer>oauth/token`
19
- by default), one response per failure status naming the codes that answer with it
20
- (`FailureResponse` narrowed to them), and the operation extensions `x-required-scopes`,
21
- `x-scope-match` (with more than one scope), `x-conditional-scopes`, `x-effect`, `x-mcp-tool` (with
22
- `x-mcp-idempotent`, `x-mcp-open-world`), `x-native-rpc`, `x-max-body-bytes` and
23
- `x-max-output-bytes` (the limits in force), `x-body`, `x-input-headers` and `x-response`. The root
24
- holds only `openapi`, `info`, `servers`, `paths` and `components`; the tag defaults to the
25
- operation's name. Every `$ref` is local: a schema's `$id` (shared schemas, `PageInfo`, each `Page`,
26
- recursive schemas) becomes `#/components/schemas/<id>`; every envelope's `metadata` refers to
27
- `ResponseMetadata` and every failure narrows `Failure`. MCP tool schemas stay self-contained: named
28
- schemas written in place, without `$id`.
29
- - `createOpenApi(app)` builds that same document at build time.
30
- - Rate limiting: `rateLimit: { binding, retryAfter }` (a Workers rate limit binding), keyed by
31
- organization and actor after authentication; 429 `RATE_LIMITED`.
32
- - Typed callers: `createClient<typeof app>(baseUrl, token, { response: 'data' })` from
33
- `@arbol-ai/maximus/client`, importing `app` as a type only. HTTPS (plain `http://` only on
34
- loopback), no redirects, no write retries, `fetch` option for tests.
15
+ - The API answers below `/api`: routes, `/api/openapi.json`, `/api/openapi.yaml` and OAuth discovery at
16
+ `/api/.well-known/oauth-protected-resource`. `/health` answers
17
+ `{ "status": "ok", "service": "<name>", "version": "<version>" }`. None of these needs a token.
18
+ - Every answer carries `x-request-id`, `x-content-type-options: nosniff`, `server-timing` and
19
+ `cache-control: private, no-store` (a page may set its own). A `401` carries
20
+ `www-authenticate: Bearer resource_metadata="<origin>/api/.well-known/oauth-protected-resource"`.
21
+ - The OpenAPI 3.1 document holds every public route, never an internal one or a tool only MCP serves, with
22
+ its scopes as OpenAPI `security` requirements, one response per failure status, every named schema as a
23
+ component, and the extensions `x-required-scopes`, `x-effect`, `x-mcp-tool`, `x-native-rpc`, `x-max-body-bytes` and
24
+ the others the wire formats reference lists.
25
+ - A caller in TypeScript sends `fetch` with the caller's token and reads the envelope, typing each call with
26
+ `Static` of schemas it imports from a module that imports no route.
35
27
 
36
28
  ## MCP
37
29
 
38
- - Endpoint `/mcp` (or `mcp({ path })`, `/` for a dedicated host), Streamable HTTP, stateless.
39
- Clients send `accept: application/json, text/event-stream`; answers are SSE `data:` lines.
40
- - Tools visible to a token: its scopes match the operation and `actorKinds` allows its actor. 50 per
41
- `tools/list` page. Calls of unseen tools are JSON-RPC errors.
42
- - Annotations: `readOnlyHint` = effect read, `destructiveHint` = effect delete, `idempotentHint` =
43
- `mcp.idempotent`, `openWorldHint` = `mcp.openWorld ?? true`. Hints are not authorization.
44
- - App `mcp`: `instructions`; `guides: [{ name, title, text }]` (resources and prompts);
45
- `skills: [{ name, description, text }]` (MCP Skills extension, `skill://<name>/SKILL.md`);
46
- `skillTool: 'read_skill'` (skills as one read-only tool, first in the catalog).
47
- - A union input lists as one object (every member's fields, the discriminator as an `enum`), since
48
- hosts refuse a root `anyOf`; each call is still checked against the exact union.
49
- - An unexpected failure of the server answers the JSON-RPC `Internal error`, never its own text, and
50
- is reported as `maximus.unexpected`.
51
- - Resources `openapi-json` and `openapi-yaml` expose the public contract, named by the URLs that
52
- serve it (below `http.basePath`); reading grants nothing.
53
- - The endpoint admits the largest `maxBodyBytes` among the tools the caller may call and holds each
54
- call to its own.
55
- - A `bearer` token scheme cannot mount MCP. Keep credential and permission management out of tools.
56
-
57
- ## Native RPC
58
-
59
- Owner:
30
+ - The Worker serves `/mcp` when a route or tool declares MCP, or when `mcp/` holds Markdown: the MCP SDK over
31
+ Streamable HTTP, one stateless server per request. A client sends
32
+ `accept: application/json, text/event-stream`; the answer is a server-sent event whose `data:` line holds
33
+ the JSON-RPC message.
34
+ - `tools/list` lists the tools the caller's scopes and actor kind admit, 50 per page. A call to a tool the
35
+ caller cannot see is a JSON-RPC error, `Tool not found`.
36
+ - Hints follow the declaration: `readOnlyHint` for a read, `destructiveHint` for a delete, `idempotentHint`
37
+ from `idempotent`, `openWorldHint` from `openWorld`, `true` unless declared. Hints never authorize.
38
+ - `mcp/instructions.md` is sent to every client that connects. `mcp/guides/<name>.md`, starting with its
39
+ `# title`, is a resource at `<origin>/guides/<name>` and a prompt. `mcp/skills/<name>.md`, with a
40
+ frontmatter `description:`, is an Agent Skill, `skill://<name>/SKILL.md`. All of it is static text for
41
+ every caller: never tenant data.
42
+ - The OpenAPI document is served as the resources `openapi-json` and `openapi-yaml`; reading them grants
43
+ nothing.
44
+ - A union input lists as one object with every member's fields; each call is still checked against the exact
45
+ union.
46
+ - Every message of a JSON-RPC batch passes the rate limit before any of them runs.
47
+ - An unexpected failure answers the JSON-RPC error `Internal error`, never its text, and is reported as
48
+ `maximus.unexpected` with the surface `mcp`.
49
+
50
+ See [MCP](https://github.com/getarbol/maximus/blob/main/docs/guides/mcp.md).
51
+
52
+ ## Worker RPC
53
+
54
+ The owner names the services allowed to call it, by their names, and each route it serves over RPC says so:
60
55
 
61
56
  ```ts
62
- maximus<Env>({ /* ... */ rpc: { callers: ['orders'] } })
63
- .operation('quoteItems', { /* ... */ rpc: true }, handler);
64
- export const PricingService = createWorker(app).entrypoint;
65
- ```
66
-
67
- Owner `cloudflare.config.ts` declares `exports: { PricingService: exports.worker() }` and exports its
68
- `defineWorker` definition; caller `cloudflare.config.ts`:
69
-
70
- ```ts
71
- PRICING: bindings.worker({ worker: pricingWorker, exportName: 'PricingService', props: { caller: 'orders' } }),
72
- ```
73
-
74
- Locally, the caller's `vite.config.ts` runs the owner beside it:
75
- `cloudflare({ auxiliaryWorkers: [{ config: pricingWorker, devOnly: true }] })`.
76
-
77
- ```ts
78
- // Env: PRICING: Service<typeof PricingService>
79
- const quote = await env.PRICING.quoteItems(principal, { items }); // forward the verified principal
57
+ // pricing/vite.config.ts: maximus({ name: 'example-pricing', …, rpc: { callers: ['example-orders'] } })
58
+ // pricing/routes/v1/quotes.post.ts, also the RPC method quoteItems
59
+ export default defineHandler(
60
+ ({ input, fail }) => {
61
+ const priced = priceItems(input.items);
62
+ if (!priced.ok) {
63
+ return fail('UNKNOWN_SKU', { index: priced.unknownIndex });
64
+ }
65
+ return priced.quote;
66
+ },
67
+ {
68
+ description: 'Price a list of catalog items for the calling organization.',
69
+ effect: 'read',
70
+ operationId: 'quoteItems',
71
+ input: { items: ItemsSchema },
72
+ output: QuoteSchema,
73
+ failures: ['UNKNOWN_SKU'],
74
+ rpc: true,
75
+ visibility: 'internal',
76
+ }
77
+ );
80
78
  ```
81
79
 
82
- - The owner requires props exactly `{ caller }` with an admitted caller, and a principal that matches
83
- `{ actorId, actorKind, organizationId, requestId }` exactly; otherwise `UNAUTHORIZED`.
84
- - No scopes are checked and `authority` is absent: the calling deployment is trusted. When the owner
85
- must verify the original authority, call its HTTP route with the caller's token
86
- (`authority.token`).
87
- - Owner failures belong to the owner's catalog: translate them before returning them, or the
88
- caller's output check turns them into `INTERNAL_ERROR`. Catch thrown calls (owner unreachable).
89
- - `worker.service(Class)` and `worker.durableObject(Class)` wrap your own entrypoints and Durable
90
- Objects with diagnostics and adapters. Never rename Durable Object classes or migration tags.
80
+ The generated Worker exports the methods as its `Service` entrypoint, one per route or tool that declares
81
+ `rpc`, named by the operation. `bunx maximus openapi` writes the owner's RPC document, `openapi.rpc.json`,
82
+ beside `openapi.json`: each method as `POST /rpc/<method>` whose body is its whole input, its answer and
83
+ failures as named components, and `x-rpc-callers`. Commit both; `maximus openapi --check` fails when the
84
+ routes changed and the files did not.
91
85
 
92
- ## Plain routes and Worker composition
86
+ The caller binds the owner by its Worker's name and that document, and imports nothing of the owner's
87
+ project:
93
88
 
94
89
  ```ts
95
- createWorker(app, {
96
- routes: { '/webhooks/payments': paymentWebhook }, // exact paths, no principal, not in OpenAPI
97
- http: {
98
- basePath: '/api', // operations + discovery below /api; transports stay absolute
99
- mounts: { '/files': serveFiles }, // prefix + slash-delimited descendants
100
- before: async (request) => null, // first; a Response answers
101
- aroundOperation: async (request, env, op, run) => run(env), // matched HTTP operations; run once
102
- origins: ['https://notes.example.com'], // exact HTTPS origins, others 404
103
- healthPath: '/healthz',
104
- },
105
- assets: { binding: 'ASSETS', pages: { paths: ['/'] }, immutablePrefixes: ['/assets/'] },
106
- handlers: { scheduled: runJobs },
90
+ // orders/vite.config.ts
91
+ maximus({
92
+ name: 'example-orders',
93
+ // …
94
+ services: { PRICING: { worker: 'example-pricing', openapi: '../pricing/openapi.rpc.json' } },
107
95
  });
108
96
  ```
109
97
 
110
- - A plain route (`HttpRoute<Env>`: `(request, env, { requestId, fail, waitUntil })`) verifies its
111
- own signature on the exact bytes (`readBodyBytes(request, { maxBytes, signal })`) before treating
112
- them as data, answers failures with `context.fail(failure, headers?)`, and may set its own
113
- `cache-control`.
114
- - Reserved: `/v<n>/…`, native paths, transport paths, `tokens.resources` keys. Collisions fail at
115
- construction. A route may sit beneath a transport's path.
116
- - `fallback` (or `assets`, not both) answers only paths outside API, versioned, native,
117
- `/.well-known` and transport namespaces.
118
- - Assets: configure the binding with `html_handling: "none"`, `not_found_handling: "none"` and
119
- `run_worker_first: true`.
98
+ `maximus()` binds `PRICING` to the owner's `Service` entrypoint with the props `{ caller: 'example-orders' }`,
99
+ this service's name. `maximus prepare` writes `.maximus/services/pricing.ts` from the document:
100
+ `PricingService`, and each method's input, output and failure union, so `env.PRICING` is
101
+ `Service<PricingService>`. A handler imports those types from `#maximus/services/pricing`, forwards its
102
+ verified principal, catches a call that throws and translates the owner's failures, narrowed by their code,
103
+ into its own catalog: see [errors-and-results.md](errors-and-results.md#failures-of-other-services).
104
+
105
+ - The owner admits a call only when the binding's props are exactly `{ caller }` with an allowed caller and
106
+ the principal is exactly `{ actorId, actorKind, organizationId, requestId }`; otherwise `UNAUTHORIZED`.
107
+ - No scope is checked and `authority` is absent: the calling deployment is trusted. When the owner must
108
+ verify the original caller's token, call its HTTP route with that token (`authority.token`) instead.
109
+ - Several services of one repository: one `services` entry per binding, each to the document the other
110
+ publishes, each typed in its own `.maximus/services/<binding>.ts`. A service can be both an owner
111
+ (`rpc.callers`) and a caller (`services`). From another repository, the document is a copy the owner's CI
112
+ publishes and the caller's updates.
113
+ - The caller's type check fails the moment the owner's document changes in a way its calls do not follow.
114
+ - Under `vp dev`, start the owner first, then the caller, which finds it by name. Deploy the owner first,
115
+ too: the caller's binding names it.
116
+
117
+ See [Worker RPC](https://github.com/getarbol/maximus/blob/main/docs/guides/worker-rpc.md) and
118
+ `examples/worker-rpc` in the Maximus repository.
119
+
120
+ ## A Worker composed by hand
121
+
122
+ A project's conventions cover routes, tools, pages (webhooks included), middleware, telemetry and event
123
+ handlers. A plain route below a transport's path, a mounted protocol, hooks around requests and operations,
124
+ pinned origins, or entrypoints of your own need a Worker composed by hand: the builder, `maximus()` from
125
+ `@arbol-ai/maximus`, with `.derive()`, `.use()`, `.operation()`, `.mount()` and `.build()`, served by
126
+ `createWorker(app, { transports, routes, http, assets, handlers })` from `@arbol-ai/maximus/workers`. A
127
+ plain route, like a page, verifies its own signature on the exact bytes (`readBodyBytes(request,
128
+ { maxBytes })`, then `@arbol-ai/maximus/webhooks`) before it treats them as data.
129
+ That Worker is built as any other, with its own module as its entry and `nodejs_compat`, not through
130
+ `maximus()` from `@arbol-ai/maximus/vite`.
131
+
132
+ See [Worker composition](https://github.com/getarbol/maximus/blob/main/docs/guides/worker-composition.md).
@@ -0,0 +1,84 @@
1
+ # Writing code people and agents read easily
2
+
3
+ The house style of a Maximus project. Follow it in every file you write or change, and keep the code you
4
+ touch in it. The full guide, with its reasons, is
5
+ [Write code people and agents read easily](https://github.com/getarbol/maximus/blob/main/docs/guides/writing-code.md).
6
+
7
+ ## A route file
8
+
9
+ Imports, then the handler, then the contract. The handler says what the route does; the contract what it
10
+ accepts, answers and may fail with; the domain lives in `src/`.
11
+
12
+ ```ts
13
+ // routes/v1/notes/[noteId].get.ts
14
+ import { defineHandler, UuidSchema } from '@arbol-ai/maximus';
15
+
16
+ import { NoteSchema } from '#src/notes.ts';
17
+
18
+ /** GET /api/v1/notes/{noteId}: one note of the caller's organization. */
19
+ export default defineHandler(
20
+ async ({ input, notes, fail }) => {
21
+ const note = await notes.find(input.noteId);
22
+ if (!note) {
23
+ return fail('NOTE_NOT_FOUND');
24
+ }
25
+ return note;
26
+ },
27
+ {
28
+ description: 'Read one note of the organization by its id.',
29
+ input: { noteId: UuidSchema },
30
+ output: NoteSchema,
31
+ failures: ['NOTE_NOT_FOUND'],
32
+ mcp: { name: 'get_note' },
33
+ }
34
+ );
35
+ ```
36
+
37
+ ## Handlers are statements
38
+
39
+ | Never | Write |
40
+ | --------------------------------------------------------- | -------------------------------------------------------------------------------- |
41
+ | `(await notes.find(id)) ?? fail('NOTE_NOT_FOUND')` | `const note = await notes.find(id);` then `if (!note) { return fail(…); }` |
42
+ | `'quote' in priced ? priced.quote : fail('UNKNOWN_SKU')` | `if (!priced.ok) { return fail('UNKNOWN_SKU', …); }` then `return priced.quote;` |
43
+ | Nested ternaries | One `if` per case, or a function whose name says what it decides |
44
+ | Destructuring several levels deep in the parameter list | `({ input, notes })`, then `const { noteId, ...fields } = input;` |
45
+ | A loop, a calculation or a second service call in a route | A named function in `src/` that the handler calls |
46
+
47
+ ## Modules and imports
48
+
49
+ - `src/` holds the domain, one module per subject: `src/notes.ts`, `src/reminders.ts`. Never
50
+ `src/utils.ts`, `src/helpers.ts` or `src/types.ts`.
51
+ - Import a module of `src/` by its name, `#src/notes.ts`, never `../../../src/notes.ts`; the project's
52
+ `package.json` maps `#src/*` to `./src/*`. Inside `src/`, a module imports its neighbor as `./x.ts`.
53
+ - `import type` for types. Keep the `.ts` extension.
54
+ - `context.ts` builds what every handler needs, bound to `principal.organizationId`, so no handler repeats
55
+ the tenant. A store answers the value it found or `undefined`; the route owns the failure code.
56
+
57
+ ## Names
58
+
59
+ - Whole English words: `reminder`, `request`, `configuration`; never `rem`, `req`, `cfg`.
60
+ - Data is a noun (`note`, `notes`, `dueAt`); a collection is plural and its element singular.
61
+ - A function starts with a verb (`findNote`, `scheduleReminder`, `noteFromRow`); one that answers a boolean
62
+ reads as a question (`isOverdue`, `hasScope`).
63
+ - A quantity carries its unit: `timeoutMs`, `maxBytes`, `durationMicros`.
64
+ - Never `data`, `info`, `item`, `value`, `result`, `obj`, `temp`, `helper`, `utils`, `manager`, `handle`.
65
+ - A route needs no name: `GET /v1/notes/{noteId}` is `getNote` and `POST /v1/notes/{noteId}/archive` is
66
+ `archiveNote`. Declare `operationId` only where the derived name reads wrong. Shape paths so it reads
67
+ right: plural collections (`/v1/notes`), parameters for items (`/{noteId}`), verbs for POST actions
68
+ (`/archive`, `/mark-read`, `/search`).
69
+
70
+ ## Functions and comments
71
+
72
+ - One thing per function, at most three arguments (then one options object), no boolean that switches
73
+ behavior, early returns, `async` only when it awaits.
74
+ - Every exported declaration has a one-sentence JSDoc saying what it is or answers. A comment inside a
75
+ function says why, never what the next line does. Update or delete a comment with its code.
76
+
77
+ ## Failures, types and tests
78
+
79
+ - An outcome the caller handles is a declared failure: list its code in `failures` and return `fail(code)`.
80
+ Throw only for what no caller can fix. Never turn an error into empty data.
81
+ - Take types from schemas (`Static<typeof NoteSchema>`). No `as` casts or `any` in place of a check: read
82
+ untrusted data with `readSchema` or `checkSchema`.
83
+ - A test's name is the behavior it proves, as a sentence: `it('refuses a note of another organization')`.
84
+ Arrange, act and assert once; synthetic data only; never a live service.
@@ -0,0 +1,2 @@
1
+ __PROJECT_NAME__ greets the people of the organization your token belongs to. Call get_greeting to greet the
2
+ caller. Every call acts for that organization alone.
@@ -0,0 +1,12 @@
1
+ import { defineHandler, t } from '@arbol-ai/maximus';
2
+
3
+ /**
4
+ * GET /api/v1/greeting, also the MCP tool get_greeting: a greeting for the signed-in caller. The file's name
5
+ * gives the path and the method, and from them the operation, getGreeting, and its scope,
6
+ * __PROJECT_NAME__:greeting:read.
7
+ */
8
+ export default defineHandler(() => ({ message: 'Hello World' }), {
9
+ description: 'Greet the authenticated caller.',
10
+ output: { message: t.String() },
11
+ mcp: { name: 'get_greeting' },
12
+ });
@@ -0,0 +1,36 @@
1
+ import { expect, it } from 'vite-plus/test';
2
+
3
+ import { handler } from '#maximus/http';
4
+
5
+ /** The development token `vp test` accepts from localhost, as in greeting.test.ts. */
6
+ const token = 'test-development-token-for-local-tests';
7
+ const env = { DEVELOPMENT_TOKEN: token } as Env;
8
+
9
+ /** Sends one JSON-RPC request to the MCP server and answers its reply, which arrives as a server-sent event. */
10
+ async function callMcp(method: string, params: object = {}) {
11
+ const response = await handler(
12
+ new Request('http://localhost/mcp', {
13
+ method: 'POST',
14
+ headers: {
15
+ authorization: `Bearer ${token}`,
16
+ 'content-type': 'application/json',
17
+ accept: 'application/json, text/event-stream',
18
+ 'mcp-protocol-version': '2025-11-25',
19
+ },
20
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
21
+ }),
22
+ env
23
+ );
24
+ const text = await response.text();
25
+ return JSON.parse(/data: (\{[^\n]*)/u.exec(text)?.[1] ?? text) as { result: Record<string, unknown> };
26
+ }
27
+
28
+ it('lists the greeting route as the MCP tool get_greeting', async () => {
29
+ const { result } = await callMcp('tools/list');
30
+ expect(result.tools).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'get_greeting' })]));
31
+ });
32
+
33
+ it('runs get_greeting as the route runs', async () => {
34
+ const { result } = await callMcp('tools/call', { name: 'get_greeting', arguments: {} });
35
+ expect(result).toMatchObject({ structuredContent: { message: 'Hello World' } });
36
+ });
@@ -1,17 +1,26 @@
1
1
  ---
2
2
  name: __PROJECT_NAME__-development
3
- description: Extend the __PROJECT_NAME__ Maximus backend using its optional file conventions.
3
+ description: Extend the __PROJECT_NAME__ Maximus project with routes, MCP tools, bindings and tests that follow its conventions.
4
4
  ---
5
5
 
6
- Read CLAUDE.md and the installed Maximus skill. Add authenticated route factories in routes/v1/;
7
- their default export receives the path and returns operations derived from src/application.ts's base.
8
- Declare strict input/output schemas, scope and effect. Use src/ for named domain functions.
9
- Pages return native Responses. Middleware modules default-export an OperationMiddleware<Invocation<Env>>.
10
- Crons export a cron expression and a default scheduled handler; queues and email export native handlers.
11
- Durable Object files default-export their class. Infrastructure declarations remain explicit in
12
- cloudflare.config.ts. Read the Maximus project-structure guide before adding another module kind.
13
- Run bun run verify for non-test validation. Tests require a human request.
6
+ Read CLAUDE.md and the Maximus skill (.agents/skills/maximus/SKILL.md) before changing the project.
14
7
 
15
- Vite+ owns the root toolchain: `vite.config.ts` configures lint/format, `vp check` checks them,
16
- `vp build` bundles the Worker and `vp dev` runs it locally. TypeScript and Cloudflare type generation
17
- remain part of `bun run verify`. Tests are never part of automatic deployment.
8
+ - Add a route with `bunx maximus gen route <method> <path>`, then write its handler, its description and its
9
+ strict input and output schemas. Its operation name, effect and scope derive from the method and path
10
+ (`GET /v1/tasks/{taskId}` is `getTask`): declare one only where the derived one is wrong, and `mcp` or
11
+ `rpc` only to expose the route there.
12
+ - Add a tool only agents use with `bunx maximus gen tool <name>`, in mcp/tools/.
13
+ - Write a handler as statements: name each result, test one condition at a time and return early. Move a
14
+ loop, a calculation or a call to another service into a named function of src/.
15
+ - Put domain logic in modules of src/ named after their domain, imported as `#src/<module>.ts` from any
16
+ folder, and what every handler needs in context.ts, scoped to `principal.organizationId`. A store answers
17
+ what it found or `undefined`, and the route answers the failure.
18
+ - Name things in whole English words: functions start with a verb, booleans read as questions, quantities
19
+ carry their unit. Give every exported declaration a one-sentence JSDoc.
20
+ - Answer expected failures with `fail(code)` from the catalog in errors.ts, declared in `failures`.
21
+ - Declare each binding in maximus()'s `env` with `bindings` from cf/config, and check what you read back
22
+ from storage with `readSchema`.
23
+ - Cover each route in tests/ through `handler` from #maximus/http, its refusals included, with stand-ins
24
+ for the bindings it uses.
25
+ - Run `bun run verify` before you finish. Never edit .maximus/; Cloudflare resources and migrations stay
26
+ explicit.
@@ -18,14 +18,17 @@ jobs:
18
18
  steps:
19
19
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
20
20
  with:
21
+ # Later steps, dependency install scripts among them, never see the job token.
21
22
  persist-credentials: false
22
23
  - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
23
24
  with:
24
- bun-version: 1.4.3
25
+ bun-version: 1.4.4
26
+ # Bun runs every command; Vite+ and Cloudflare's local runtime run on Node.js underneath.
25
27
  - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
26
28
  with:
27
29
  node-version: '24'
28
30
  - run: bun install --frozen-lockfile --ignore-scripts
31
+ # Types, lint and format, the tests and the build.
29
32
  - run: bun run verify
30
33
  - run: bunx cf deploy --prebuilt --mode production --dry-run
31
34
  - name: Deploy main
@@ -1,34 +1,53 @@
1
1
  # __PROJECT_NAME__ agent guide
2
2
 
3
3
  AGENTS.md is a symlink to this file. Keep code, documentation, comments and agent instructions in English.
4
- Read .agents/skills/project/SKILL.md and node_modules/@arbol-ai/maximus/skills/maximus/SKILL.md.
4
+ Read .agents/skills/project/SKILL.md, and the Maximus skill in .agents/skills/maximus/SKILL.md, a link into
5
+ node_modules/@arbol-ai/maximus that `bun install` fills.
5
6
 
6
7
  ## Structure
7
8
 
8
- This is a Maximus project layout. The Vite plugin and `maximus prepare` generate `.maximus/` from
9
- optional directories. Never edit generated files. Routes are factories that receive their inferred
10
- versioned path and return a builder derived from `base` in src/application.ts. Pages return native
11
- Responses; public pages never contain tenant data. Middleware runs after authentication and scopes.
12
- Configure platform bindings, triggers and Durable Object migrations in cloudflare.config.ts.
13
- Keep domain logic in src/, schemas and migrations in db/, and uploaded files in public/ only after
14
- configuring an assets binding and explicit file admission. Never apply migrations implicitly.
9
+ This is a Maximus project on Cloudflare Workers. vite.config.ts is its only configuration: maximus() states
10
+ the application, its bindings and its Worker, and errors.ts, context.ts, auth.ts and telemetry.ts complete
11
+ it in code when present.
12
+
13
+ - routes/: one defineHandler(handler, contract) per file, named by its path and method:
14
+ routes/v1/tasks/[taskId].delete.ts answers DELETE /api/v1/tasks/{taskId}. Its operation name, effect and
15
+ scope derive from the method and path unless declared. Declare strict input and output schemas, and MCP
16
+ or RPC exposure explicitly.
17
+ - mcp/tools/: tools only MCP serves, one defineTool per kebab-case file. mcp/instructions.md, mcp/guides/
18
+ and mcp/skills/ describe the MCP server to every client, so they hold no tenant data.
19
+ - middleware/: defineMiddleware wraps requests before token admission and sees no principal;
20
+ defineOperationMiddleware runs after admission on HTTP, MCP and RPC. Modules run in filename order.
21
+ - pages/: public responses at fixed paths outside the API, for GET unless the file names its method:
22
+ pages/webhooks/payments.post.ts receives a provider's webhook and verifies its signature itself. They hold
23
+ no tenant data.
24
+ - index.html, app/ and public/: a web app, when index.html exists. app/routes/ holds its React Router
25
+ pages, named as routes are, and the app calls the API with fetch and the person's token.
26
+ - crons/: scheduled handlers, each exporting its schedule as `export const cron = '…'`. queues/: one
27
+ consumer per queue, named after it. email/: one handler per recipient address, and _default.
28
+ durable-objects/: Durable Object classes, day-schedule.ts exported as DaySchedule.
29
+ - src/: the domain, in modules named after it, which any folder imports as #src/<module>.ts. tests/:
30
+ tests that call `handler` from #maximus/http in Node.
31
+ - .maximus/: generated by `maximus prepare`, vp dev, vp build and vp test. Never edit it, and never import
32
+ it at runtime from errors.ts, context.ts, auth.ts or telemetry.ts.
33
+
34
+ The project-structure guide maps every file:
35
+ https://github.com/getarbol/maximus/blob/main/docs/guides/project-structure.md. Bindings and triggers
36
+ belong in maximus(); Env is generated from them. Creating Cloudflare resources and applying migrations stay
37
+ explicit: adding a file never provisions anything.
15
38
 
16
39
  ## Boundaries
17
40
 
18
- Tenant authority is context.principal.organizationId, never caller input. Declare strict schemas,
19
- scopes, effects and the required transports once. Use the shared Result pipeline. Never put provider
20
- credentials, customer data or request bodies in logs, examples, errors or agent instructions.
21
- Secrets belong in bindings; .dev.vars is local and ignored. Production tokens are refused until the
22
- application configures a real identity provider or cryptographically verified resolver.
41
+ Tenant authority is the verified principal's organizationId, never caller input. Answer expected failures
42
+ with `fail(code)` from errors.ts, declared in the route's `failures`. Never put credentials, personal or
43
+ clinical data or request bodies in logs, examples, errors or agent instructions. Secrets are
44
+ bindings.secret(); .dev.vars is local and ignored by Git. A deployed Worker accepts only the access tokens
45
+ of tokens.issuer, so set it to the real authorization server before deploying.
23
46
 
24
47
  ## Workflows
25
48
 
26
- Use `bun run verify` for type generation, TypeScript, lint, format and build. Tests require an explicit
27
- human request, including tests in scripts, hooks or CI. Never start them implicitly.
28
- Use `cf` for Cloudflare; discover account/resource commands with anonymous `cf cli search` queries
29
- and inspect their schema before execution. Deploy with the project's script or its GitHub workflow.
30
- Preserve unrelated work and Git identity configuration. Do not add assistant attribution to commits.
31
-
32
- Vite+ owns the root toolchain: `vite.config.ts` configures lint/format, `vp check` checks them,
33
- `vp build` bundles the Worker and `vp dev` runs it locally. TypeScript and Cloudflare type generation
34
- remain part of `bun run verify`. Tests are never part of automatic deployment.
49
+ `bun run dev` runs the Worker locally and `bun run test` runs the tests. `bun run verify` runs type
50
+ generation, TypeScript, lint and format, the tests and the build; CI runs it on every pull request. Use
51
+ `cf` for Cloudflare: discover commands with `cf cli search` and inspect a command's API request with
52
+ `cf schema` before running it. Deploy with `bun run deploy` or the GitHub workflow. Preserve unrelated work
53
+ and Git identity configuration, and add no assistant attribution to commits.