@arbol-ai/maximus 0.0.0-stage → 7.1.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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/config/oxfmt.d.mts +8 -0
  4. package/config/oxfmt.mjs +30 -0
  5. package/config/oxlint-plugin.mjs +41 -0
  6. package/config/oxlint.d.mts +8 -0
  7. package/config/oxlint.mjs +118 -0
  8. package/dist/analytics/analytics.d.ts +34 -0
  9. package/dist/analytics/analytics.js +62 -0
  10. package/dist/body.d.ts +2 -0
  11. package/dist/body.js +4 -0
  12. package/dist/chunks/body-BcMbreNd.js +106 -0
  13. package/dist/chunks/correlation-gaiEoMBr.js +45 -0
  14. package/dist/chunks/execution-qfZuMSIu.js +700 -0
  15. package/dist/chunks/json-Dwni3u4c.js +63 -0
  16. package/dist/chunks/record-D2H3cg8S.js +36 -0
  17. package/dist/chunks/schemas-q-51wBMQ.js +216 -0
  18. package/dist/chunks/src-Ph5KHCRP.js +1160 -0
  19. package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
  20. package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
  21. package/dist/chunks/validation-DWxKk1Js.js +382 -0
  22. package/dist/client/client.d.ts +131 -0
  23. package/dist/client/client.js +325 -0
  24. package/dist/diagnostics.d.ts +41 -0
  25. package/dist/diagnostics.js +4 -0
  26. package/dist/errors.d.ts +2 -0
  27. package/dist/errors.js +128 -0
  28. package/dist/http-paths.d.ts +2 -0
  29. package/dist/http-paths.js +200 -0
  30. package/dist/index.d.ts +2 -0
  31. package/dist/index.js +11 -0
  32. package/dist/internals.d.ts +2 -0
  33. package/dist/internals.js +5 -0
  34. package/dist/mcp/index.d.ts +12 -0
  35. package/dist/mcp/index.js +406 -0
  36. package/dist/postgres/index.d.ts +81 -0
  37. package/dist/postgres/index.js +140 -0
  38. package/dist/projection.d.ts +36 -0
  39. package/dist/projection.js +60 -0
  40. package/dist/schemas.d.ts +2 -0
  41. package/dist/schemas.js +4 -0
  42. package/dist/standard-failures.d.ts +91 -0
  43. package/dist/standard-failures.js +75 -0
  44. package/dist/tooling/cli.js +110 -0
  45. package/dist/tooling/testing.d.ts +7 -0
  46. package/dist/tooling/testing.js +21 -0
  47. package/dist/webhooks.d.ts +69 -0
  48. package/dist/webhooks.js +162 -0
  49. package/dist/workers/runtime.d.ts +112 -0
  50. package/dist/workers/runtime.js +228 -0
  51. package/package.json +157 -4
  52. package/skills/maximus/SKILL.md +89 -0
  53. package/skills/maximus/references/adding-an-operation.md +179 -0
  54. package/skills/maximus/references/building-a-service.md +158 -0
  55. package/skills/maximus/references/errors-and-results.md +77 -0
  56. package/skills/maximus/references/migration-from-v2.md +62 -0
  57. package/skills/maximus/references/migration-to-v5.md +37 -0
  58. package/skills/maximus/references/publishing-and-verification.md +39 -0
  59. package/skills/maximus/references/testing.md +73 -0
  60. package/skills/maximus/references/transports.md +119 -0
  61. package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
  62. package/templates/service/.github/workflows/ci.yml.template +21 -0
  63. package/templates/service/.gitignore.template +8 -0
  64. package/templates/service/CLAUDE.md.template +3 -0
  65. package/templates/service/README.md.template +45 -0
  66. package/templates/service/cloudflare.config.ts.template +30 -0
  67. package/templates/service/oxfmt.config.ts.template +1 -0
  68. package/templates/service/oxlint.config.ts.template +1 -0
  69. package/templates/service/package.json.template +31 -0
  70. package/templates/service/src/app.ts.template +30 -0
  71. package/templates/service/src/index.ts.template +13 -0
  72. package/templates/service/tests/contract.test.ts.template +12 -0
  73. package/templates/service/tsconfig.json.template +16 -0
  74. package/templates/service/vite.config.ts.template +7 -0
  75. package/templates/service/vitest.config.ts.template +10 -0
package/package.json CHANGED
@@ -1,6 +1,159 @@
1
1
  {
2
2
  "name": "@arbol-ai/maximus",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "7.1.0",
4
+ "description": "Maximus: define a service once and serve it over HTTP, MCP and Worker RPC on Cloudflare Workers, with its OpenAPI, typed client and CLI.",
5
+ "keywords": [
6
+ "api",
7
+ "cloudflare",
8
+ "cloudflare-workers",
9
+ "framework",
10
+ "mcp",
11
+ "model-context-protocol",
12
+ "multi-tenant",
13
+ "openapi",
14
+ "rpc",
15
+ "typebox"
16
+ ],
17
+ "homepage": "https://github.com/getarbol/maximus#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/getarbol/maximus/issues"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Arbol",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/getarbol/maximus.git",
26
+ "directory": "packages/maximus"
27
+ },
28
+ "bin": {
29
+ "maximus": "dist/tooling/cli.js"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "config",
34
+ "templates",
35
+ "skills",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "type": "module",
40
+ "sideEffects": false,
41
+ "exports": {
42
+ ".": {
43
+ "types": "./dist/index.d.ts",
44
+ "import": "./dist/index.js"
45
+ },
46
+ "./schemas": {
47
+ "types": "./dist/schemas.d.ts",
48
+ "import": "./dist/schemas.js"
49
+ },
50
+ "./errors": {
51
+ "types": "./dist/errors.d.ts",
52
+ "import": "./dist/errors.js"
53
+ },
54
+ "./failures": {
55
+ "types": "./dist/standard-failures.d.ts",
56
+ "import": "./dist/standard-failures.js"
57
+ },
58
+ "./body": {
59
+ "types": "./dist/body.d.ts",
60
+ "import": "./dist/body.js"
61
+ },
62
+ "./webhooks": {
63
+ "types": "./dist/webhooks.d.ts",
64
+ "import": "./dist/webhooks.js"
65
+ },
66
+ "./http-paths": {
67
+ "types": "./dist/http-paths.d.ts",
68
+ "import": "./dist/http-paths.js"
69
+ },
70
+ "./projection": {
71
+ "types": "./dist/projection.d.ts",
72
+ "import": "./dist/projection.js"
73
+ },
74
+ "./diagnostics": {
75
+ "types": "./dist/diagnostics.d.ts",
76
+ "import": "./dist/diagnostics.js"
77
+ },
78
+ "./internals": {
79
+ "types": "./dist/internals.d.ts",
80
+ "import": "./dist/internals.js"
81
+ },
82
+ "./workers": {
83
+ "types": "./dist/workers/runtime.d.ts",
84
+ "import": "./dist/workers/runtime.js"
85
+ },
86
+ "./mcp": {
87
+ "types": "./dist/mcp/index.d.ts",
88
+ "import": "./dist/mcp/index.js"
89
+ },
90
+ "./client": {
91
+ "types": "./dist/client/client.d.ts",
92
+ "import": "./dist/client/client.js"
93
+ },
94
+ "./analytics": {
95
+ "types": "./dist/analytics/analytics.d.ts",
96
+ "import": "./dist/analytics/analytics.js"
97
+ },
98
+ "./postgres": {
99
+ "types": "./dist/postgres/index.d.ts",
100
+ "import": "./dist/postgres/index.js"
101
+ },
102
+ "./testing": {
103
+ "types": "./dist/tooling/testing.d.ts",
104
+ "import": "./dist/tooling/testing.js"
105
+ },
106
+ "./oxfmt": {
107
+ "types": "./config/oxfmt.d.mts",
108
+ "import": "./config/oxfmt.mjs"
109
+ },
110
+ "./oxlint": {
111
+ "types": "./config/oxlint.d.mts",
112
+ "import": "./config/oxlint.mjs"
113
+ }
114
+ },
115
+ "publishConfig": {
116
+ "access": "public",
117
+ "registry": "https://registry.npmjs.org/"
118
+ },
119
+ "scripts": {
120
+ "typecheck": "tsc --noEmit",
121
+ "build": "tsdown",
122
+ "test": "vitest run --exclude '**/*.integration.test.ts'",
123
+ "test:integration": "vitest run --config vitest.integration.config.ts"
124
+ },
125
+ "dependencies": {
126
+ "@modelcontextprotocol/server": "2.3.1",
127
+ "@sinclair/typebox": "0.34.52",
128
+ "ajv-formats": "3.0.1",
129
+ "jose": "6.2.12",
130
+ "yaml": "2.9.1"
131
+ },
132
+ "devDependencies": {
133
+ "@types/pg": "8.23.1",
134
+ "ajv": "8.20.0",
135
+ "miniflare": "5.20261012.1-beta",
136
+ "pg": "8.23.1",
137
+ "tsdown": "0.23.1"
138
+ },
139
+ "peerDependencies": {
140
+ "oxfmt": ">=0.71.0 <1",
141
+ "oxlint": "^1.86.0",
142
+ "pg": "^8.23.1",
143
+ "ultracite": "^8.0.0"
144
+ },
145
+ "peerDependenciesMeta": {
146
+ "oxfmt": {
147
+ "optional": true
148
+ },
149
+ "oxlint": {
150
+ "optional": true
151
+ },
152
+ "pg": {
153
+ "optional": true
154
+ },
155
+ "ultracite": {
156
+ "optional": true
157
+ }
158
+ }
159
+ }
@@ -0,0 +1,89 @@
1
+ ---
2
+ name: maximus
3
+ description: Build, extend, test, migrate and release services with the Maximus framework (@arbol-ai/maximus*), which declares schema-first, organization-scoped operations once and serves them over HTTP/OpenAPI, MCP and Cloudflare Worker RPC. Use when code imports @arbol-ai/maximus or a task involves Maximus operations, scopes, error catalogs, derive/use middleware, MCP tools, RPC entrypoints, OpenAPI documents or the maximus CLI.
4
+ ---
5
+
6
+ # Maximus
7
+
8
+ Maximus services declare each operation once (schemas, scope, effect, exposure, handler) on one
9
+ fluent application. Each transport admits the caller its own way, then every call runs the same
10
+ pipeline: input decoding, preparation, middleware, handler, output validation. Work with that
11
+ pipeline, never around it.
12
+
13
+ ## Workflow
14
+
15
+ 1. **Read the service first.** Find `maximus<Env>(…)` (usually `src/application.ts`), the resource
16
+ modules (`src/api/<resource>/operations.ts`), the composition (`src/app.ts`) and the Worker
17
+ (`src/index.ts`). Keep the project's existing folders and named domain functions.
18
+ 2. **Declare, don't wire.** Add an operation to its resource module with strict schemas, a namespaced
19
+ scope, a truthful effect and only the transports it needs (`http`, `mcp`, `rpc`). Mount new
20
+ modules in `app.ts`. See `references/adding-an-operation.md`.
21
+ 3. **Return Results.** Expected failures are `err(catalog.x.create())` from the application's own
22
+ catalog; throw only for the unexpected. See `references/errors-and-results.md`.
23
+ 4. **Prepare context with `.derive()`** in the group that needs it, and wrap with `.use()` only for
24
+ cross-cutting behavior after authorization.
25
+ 5. **Verify** with the project's typecheck, lint and tests, then `cf build` and a dry-run deploy
26
+ (`cf deploy --prebuilt --mode production --dry-run`). See `references/testing.md` and
27
+ `references/publishing-and-verification.md`.
28
+
29
+ ## Decisions
30
+
31
+ | Question | Choose |
32
+ | --- | --- |
33
+ | Who calls it? People or external services over the network | `http` (and `mcp` for agents) with OAuth tokens |
34
+ | Another Worker in the same account, trusted deployment | `rpc` with `rpc.callers`; see `references/transports.md` |
35
+ | Documents that list only the failures it can answer | `failures` (its domain codes); any other becomes `INTERNAL_ERROR`; see `references/adding-an-operation.md` |
36
+ | A gateway in front of the service, forwarding each caller's own token | Nothing special: list its audience in `tokens.audience` after the service's own; it calls the origin's own routes |
37
+ | Staff operations hidden from documents and clients | `visibility: 'internal'`: still routed and decided by scope on the origin |
38
+ | Verifying a provider webhook | `@arbol-ai/maximus/webhooks` on the raw body, in a plain route |
39
+ | Callers without bearer tokens (webhooks, signed links) | A plain route that verifies its own signature |
40
+ | Tokens that are not organization-bound OAuth access tokens | `tokens.resolve`, verifying cryptographically |
41
+ | SDKs or a catalog generated from the contract | The origin's `/openapi.json`, or `createOpenApi(app)` at build time; see `references/transports.md` |
42
+ | A new service from scratch | `references/building-a-service.md` |
43
+ | Upgrading from 4.x | `references/migration-to-v5.md` |
44
+ | Upgrading from 2.x | `references/migration-from-v2.md` |
45
+
46
+ ## Rules that are never broken
47
+
48
+ - **Tenancy:** every tenant query uses `context.principal.organizationId`. Never take an
49
+ organization from input, a header or a path.
50
+ - **Strict schemas:** inputs and outputs are `t.Object({...}, { additionalProperties: false })` or
51
+ unions of such objects; a GET input is one object, each field read from the query string as its
52
+ kind (integer, number, boolean, comma-separated string list, otherwise string).
53
+ - **Validation ownership:** the framework validates operation input and output once. Do not re-parse
54
+ inputs in handlers or helpers; do validate provider responses, stored records and model output with
55
+ `checkSchema`/`readSchema`. No casts, trust flags or no-op validators.
56
+ - **Codecs need `inputSchema()`:** an input using `normalizeSchema`, `refineSchema`,
57
+ `transformSchema`, `inspectSchema`, `pipeSchema` or `stripObject` must be wrapped in
58
+ `inputSchema(...)`; `.build()` refuses it otherwise, because a plain decode would skip the codecs.
59
+ - **Authorization is scopes plus your checks:** effects, `visibility: 'internal'`, descriptions and
60
+ MCP annotations never authorize. Ordinary RPC checks no scopes.
61
+ - **Failures are honest:** an outage is a failure, never an empty success. A write whose outcome is
62
+ lost answers `OUTCOME_UNKNOWN` and is reconciled, never retried blindly.
63
+ - **Outbound calls:** in a Worker, `fetch(..., { redirect: 'error' })` throws before any request
64
+ (only `follow` and `manual` exist). Send credentials with `redirect: 'manual'` and refuse a `3xx`.
65
+ - **Privacy:** never log or return request bodies, credentials or submitted values in failure
66
+ `data`, refinement messages, MCP skills or examples. Skills and guides hold no tenant data.
67
+ - **Collections are pages:** an operation that returns many items answers `Page(Item, { $id })` with
68
+ `PageQueryFields`; one that reads, creates or updates an item answers the named entity (the list's
69
+ item); a delete answers `DeletedObjectSchema`. Use the shared schemas (`UuidSchema`,
70
+ `EmailAddressSchema`, …) instead of local copies.
71
+ - **Construction errors are guidance:** `.build()` throws a `TypeError` stating the rule (usually with
72
+ the operation's name); fix the definition rather than loosening checks.
73
+
74
+ ## References
75
+
76
+ Load the one that matches the task:
77
+
78
+ - `references/building-a-service.md`: project layout, configuration, tokens, Worker, local run.
79
+ - `references/adding-an-operation.md`: every definition field, routes, schemas, codecs, middleware.
80
+ - `references/transports.md`: HTTP and OpenAPI, MCP, native RPC, plain routes and Worker composition.
81
+ - `references/errors-and-results.md`: catalogs, standard failures, presentation, uncertain outcomes.
82
+ - `references/testing.md`: handler tests, the `verify` seam, MCP, `executeOperation`, RPC types.
83
+ - `references/migration-to-v5.md`: what 5.0 removed and what to change.
84
+ - `references/migration-from-v2.md`: 3.0.0 breaking changes and classifying older services.
85
+ - `references/publishing-and-verification.md`: `maximus init`, deploying, verifying a deployment and
86
+ releasing Maximus itself.
87
+
88
+ The full documentation is in the Maximus repository under `docs/`; this skill ships in
89
+ `@arbol-ai/maximus` at `skills/maximus/`.
@@ -0,0 +1,179 @@
1
+ # Adding an operation
2
+
3
+ ## Template
4
+
5
+ ```ts
6
+ import { err, ok, t, UuidSchema } from '@arbol-ai/maximus';
7
+
8
+ import { base, errors } from '../../application';
9
+
10
+ export const notes = base.operation(
11
+ 'getNote', // camelCase, unique; also the OpenAPI operationId and RPC method name
12
+ {
13
+ scope: ['notes:notes:read', 'notes:notes:write'], // any one admits; scopeMatch: 'all' for every one
14
+ effect: 'read', // 'read' | 'write' | 'delete' — truthful; only reads may use GET
15
+ group: 'Notes', // OpenAPI tag
16
+ title: 'Get a note',
17
+ description: 'Read one note by its identifier.', // written for people and models
18
+ input: t.Object({ noteId: UuidSchema }, { additionalProperties: false }),
19
+ output: NoteSchema,
20
+ http: { method: 'GET', path: '/v1/notes/{noteId}' },
21
+ mcp: { name: 'get_note', idempotent: true },
22
+ // rpc: true,
23
+ },
24
+ async ({ env, principal }, input) => {
25
+ const note = await readNote(env.NOTES, principal.organizationId, input.noteId);
26
+ return note ? ok(note) : err(errors.noteNotFound.create());
27
+ }
28
+ );
29
+ ```
30
+
31
+ ### Declared failures
32
+
33
+ Declare `failures` (the domain codes it may answer) so its documents list only those and any other
34
+ domain failure it returns becomes `INTERNAL_ERROR`, reported. Omitted, every failure of the catalog is
35
+ listed and allowed; standard failures are always allowed.
36
+
37
+ ```ts
38
+ base.operation(
39
+ 'archiveNote',
40
+ {
41
+ scope: 'notes:notes:write',
42
+ effect: 'write',
43
+ actorKinds: ['user'],
44
+ title: 'Archive a note',
45
+ description: 'Moves a note out of the active list; it stays readable.',
46
+ input: t.Object({ noteId: UuidSchema }, { additionalProperties: false }),
47
+ output: NoteSchema,
48
+ http: { method: 'POST', path: '/v1/notes/{noteId}/archive' },
49
+ mcp: { name: 'archive_note', idempotent: true },
50
+ failures: ['NOTE_NOT_FOUND'], // the only domain failure it may answer
51
+ },
52
+ async ({ env, principal }, input) => archiveNote(env.NOTES, principal.organizationId, input.noteId)
53
+ );
54
+ ```
55
+
56
+ Reserved names: `fetch`, `connect`, `constructor`, `then`, `scheduled`, `queue`, `alarm`,
57
+ `__proto__`, `prototype`.
58
+
59
+ ## Fields
60
+
61
+ An inline definition with a field no operation has (a misspelling, a retired `api` name) does not
62
+ compile.
63
+
64
+ | Field | Rule |
65
+ | --- | --- |
66
+ | `scope` | `<namespace>:<resource>:<action>` with the app's namespace; a list is any-of unless `scopeMatch: 'all'`. |
67
+ | `conditionalScopes` | Extra namespaced scopes the handler checks via `context.authority?.scopes`; calls without authority (ordinary RPC) are refused. |
68
+ | `actorKinds` | `['user']`, `['service']` or both; omitted, either is admitted. Required on every documented operation under the `oauth+bearer` token scheme. |
69
+ | `visibility` | `'internal'`: routed and scope-checked, hidden from OpenAPI, `scopes_supported` and the client. Give it a staff-only scope. |
70
+ | `maxBodyBytes` | Per-operation body limit, up to 16 MiB, never on GET. App default 32 KiB. |
71
+ | `maxOutputBytes` | Up to 16 MiB. Default 256 KiB. Over the limit → `INTERNAL_ERROR`. |
72
+ | `http.method`, `http.path` | `/v<n>/…`, static segments `[A-Za-z0-9_-]+`, whole-segment `{param}`; unique `METHOD path`. |
73
+ | `http.successStatus` | `200`, `201` or `202`. |
74
+ | `mcp.name` | `^[a-z][A-Za-z0-9_]{0,63}$`, unique; `idempotent` required; `openWorld` defaults to `true`. Served once the Worker mounts `transports: [mcp()]`. |
75
+ | `rpc` | `true` (all app callers) or `{ callers }` (a subset). |
76
+
77
+ ## HTTP input rules
78
+
79
+ - GET input comes from the query string: each declared field is read as its kind (integer, number,
80
+ boolean, comma-separated string list, otherwise string); repeated keys are refused. The typed
81
+ client writes those values the same way.
82
+ - POST, PUT, PATCH and DELETE read a JSON body with `content-type: application/json` (415
83
+ otherwise); a DELETE with no body and no `content-type` is the empty input.
84
+ - A `{param}` must be a required `string` field of the input (of each union member). The query or
85
+ body may not repeat it.
86
+ - Unknown routes and methods are 404 before authentication; no trailing-slash normalization.
87
+
88
+ ## Schemas
89
+
90
+ - Strict objects or unions of strict objects (discriminated by a field). A GET input is one object.
91
+ - Shared, each a named component: `OrganizationIdSchema`, `UuidSchema`, `EmailAddressSchema`,
92
+ `PhoneNumberSchema` (E.164), `HttpsUrlSchema`, `HexColorSchema`, `DeletedObjectSchema`,
93
+ `SignedUrlSchema`, `NamedReferenceSchema`, `PostalAddressSchema`; `EmptyInputSchema` (unnamed). Ids
94
+ are strings; use `organizationId` and `requestId`, never aliases. Name your own entities with a
95
+ PascalCase `$id`, one shape per name: it becomes a public SDK type.
96
+ - Lists: `input: inputSchema(t.Object({ ...PageQueryFields, ...filters }, { additionalProperties: false }))`
97
+ (`cursor`, `direction`, `limit`; `limit: pageLimit({ maximum })` to lower it) and
98
+ `output: Page(Item, { $id: 'ItemPage' })`, answering `{ object: 'list', data, pageInfo }`.
99
+ - Formats: `date`, `time`, `date-time` (time zone required), `email`, `uuid`, `uri`.
100
+ - Use `t.Union([X, t.Null()])` for absent values in outputs; present every field.
101
+
102
+ ## Codecs (from `@arbol-ai/maximus/schemas`)
103
+
104
+ ```ts
105
+ import { defaultSchema, inputSchema, normalizeSchema, refineSchema, t } from '@arbol-ai/maximus/schemas';
106
+
107
+ input: inputSchema(
108
+ refineSchema(
109
+ t.Object(
110
+ {
111
+ query: normalizeSchema(t.String({ minLength: 1, maxLength: 100 }), (value) => value.trim()),
112
+ limit: defaultSchema(t.Integer({ minimum: 1, maximum: 50 }), 20),
113
+ from: t.String({ format: 'date' }),
114
+ to: t.String({ format: 'date' }),
115
+ },
116
+ { additionalProperties: false }
117
+ ),
118
+ (value) => value.from <= value.to,
119
+ { message: 'The range must not end before it starts.', path: ['to'] }
120
+ )
121
+ ),
122
+ ```
123
+
124
+ - Without `inputSchema(...)` around the input, normalizers, transforms, refinements and stripping do
125
+ not run.
126
+ - Handlers receive `StaticDecode<typeof input>`; clients and OpenAPI see `Static<typeof input>`.
127
+ - Refinement messages travel to callers in `INVALID_INPUT` issues: never include input values.
128
+ - Other helpers: `transformSchema`, `inspectSchema` (several issues via `addIssue`), `pipeSchema`,
129
+ `stripObject` / `strictObject` / `looseObject` / `extendObject`, `literalUnion`, `urlSchema`.
130
+
131
+ Numbers in a GET query need a wire schema:
132
+
133
+ ```ts
134
+ const Query = t.Object(
135
+ {
136
+ limit: t.Optional(
137
+ t.Transform(t.String({ pattern: '^[1-9][0-9]{0,2}$' })).Decode((v) => Number(v)).Encode((v) => String(v))
138
+ ),
139
+ },
140
+ { additionalProperties: false }
141
+ );
142
+ const Canonical = t.Object({ limit: t.Optional(t.Integer({ minimum: 1, maximum: 100 })) }, { additionalProperties: false });
143
+ // input: inputSchema(Canonical, Query)
144
+ ```
145
+
146
+ ## Context, derive and use
147
+
148
+ Handler context: `env`, `principal` (`actorId`, `actorKind`, `organizationId`, `requestId`),
149
+ `authority` (`{ surface, scopes, client, token? }`, frozen; absent over ordinary RPC), `input`,
150
+ `operation`, `background` (`waitUntil`, best effort), and `body` for byte uploads.
151
+
152
+ ```ts
153
+ const connected = base.derive(async ({ env, principal }) => {
154
+ const account = await loadAccount(env, principal.organizationId);
155
+ return account ? ok({ account }) : err(errors.accountNotConnected.create());
156
+ });
157
+ export const reports = connected.operation('listReports', definition, async ({ account }, input) => …);
158
+ ```
159
+
160
+ - `.derive()` must precede `.operation()` on its chain (it throws otherwise); it runs after
161
+ admission and input validation; its failure ends the call.
162
+ - `.use(async (context, proceed) => …)`: call `proceed()` at most once and return its `Result`, or
163
+ return your own. Results are validated. Applies to operations declared after it.
164
+ - Operations that set something up (a connection) must not sit in the group that requires it.
165
+ - `mount` only builders from the same `maximus()` base.
166
+
167
+ ## Files
168
+
169
+ Upload: `http: { method: 'PUT', path: '/v1/notes/{noteId}/attachment', body: 'bytes', headers: { contentType: 'content-type' } }`,
170
+ a `maxBodyBytes`, and `const bytes = await context.body.read()` (a `Result`, read once) after checking
171
+ the target resource. Download: `output: AttachmentOutputSchema`, `http: { …, response: 'attachment' }`,
172
+ return `ok({ body, contentType, filename, byteLength })`. Both are HTTP-only.
173
+
174
+ ## Before you finish
175
+
176
+ - Scopes namespaced; effect truthful; strict schemas; every failure from the app's catalog.
177
+ - No organization in the input; tenant keys built from `principal.organizationId`.
178
+ - Provider and storage reads go through `checkSchema`/`readSchema`.
179
+ - Typecheck, tests and lint pass; `.build()` raises no `TypeError`.
@@ -0,0 +1,158 @@
1
+ # Building a service
2
+
3
+ ## Packages
4
+
5
+ ```sh
6
+ bun add @arbol-ai/maximus # everything: /workers, /mcp, /client, the maximus CLI, …
7
+ bun add -d cf vite @cloudflare/vite-plugin@beta typescript @cloudflare/workers-types
8
+ ```
9
+
10
+ ## Layout
11
+
12
+ ```text
13
+ src/
14
+ application.ts export const base = maximus<Env>({ ... })
15
+ tokens.ts the TokenPolicy (issuer, audience, optional resolve)
16
+ env.ts Env: the bindings, typed by the narrow interfaces the code uses
17
+ api/<resource>/
18
+ schemas.ts TypeBox schemas
19
+ <resource>.ts named domain functions
20
+ operations.ts export const <resource> = base.operation(...)...
21
+ app.ts export const app = base.mount(a).mount(b).build() (no cloudflare:workers import)
22
+ index.ts createWorker(app, ...) and the exports
23
+ cloudflare.config.ts the Worker for cf: name, runtime, entrypoint, bindings, triggers, exports
24
+ vite.config.ts cloudflare() from @cloudflare/vite-plugin, which cf builds and runs with
25
+ ```
26
+
27
+ `app.ts` must stay importable outside workerd so tests and scripts can load it.
28
+
29
+ ## Configuration
30
+
31
+ ```ts
32
+ import { defineErrors, maximus } from '@arbol-ai/maximus';
33
+
34
+ export const errors = defineErrors({
35
+ noteNotFound: { code: 'NOTE_NOT_FOUND', status: 404, message: 'The note does not exist.' },
36
+ });
37
+
38
+ export const base = maximus<Env>({
39
+ name: 'notes', // lowercase; health, MCP server name, telemetry
40
+ namespace: 'notes', // ^[a-z][a-z0-9-]{1,63}$, prefixes every scope
41
+ title: 'Notes',
42
+ version: '1.0.0',
43
+ origin: 'https://notes.example.com', // must be https:, the public URL
44
+ tokens: { issuer: 'https://auth.example.com/', audience: 'https://notes.example.com' },
45
+ errors,
46
+ rpc: { callers: [] }, // deployments allowed over native RPC
47
+ // optional: mcp, telemetry, rateLimit, maxBodyBytes, maxOutputBytes
48
+ });
49
+ ```
50
+
51
+ - `tokens.issuer` has no default. Without it the app builds, but OAuth tokens are refused and
52
+ `/openapi.json` answers 500.
53
+ - `mcp` configuration requires `transports: [mcp()]` in `createWorker`, or the Worker fails to start.
54
+
55
+ ## Tokens
56
+
57
+ Default: OAuth access tokens from any provider, RS256 (or `tokens.algorithms`) from
58
+ `<issuer>.well-known/jwks.json` (or `tokens.jwksUri`), exact issuer and audience (`tokens.audience`
59
+ may list several, any one accepted; the first is the discovery `resource`). Standard claims: `sub`
60
+ (actor; `<client>@clients` is a machine), `org_id` (required; 1-128 letters, digits, `_`, `-`),
61
+ `azp`/`client_id` (optional), `scope`; a person holds only the scopes their `permissions` claim also
62
+ lists, none without it (Auth0 with RBAC and permissions in the token). `tokens.claims` maps providers
63
+ that name them differently: `{ scopes: 'scp', client: 'cid', permissions: false, machineSubject:
64
+ '{client}' }` (Okta), `{ scopes: 'permissions' }` (WorkOS session tokens). Set `permissions: false`
65
+ only when the authorization server grants each person no more than they may hold, and
66
+ `machineSubject: '{client}'` only when it assigns every client id. OpenAPI's OAuth flows use
67
+ `tokens.authorizationEndpoint` and `tokens.tokenEndpoint` (Auth0's `authorize` and `oauth/token` by
68
+ default); for other providers copy them and `jwksUri` from the server's
69
+ `/.well-known/oauth-authorization-server` metadata.
70
+
71
+ Other credentials: `tokens.resolve(token, context)` verifies cryptographically and returns a
72
+ `TokenPrincipal` (`{ actorId, actorKind, organizationId, scopes, client? }`) or a `Result`
73
+ (`FORBIDDEN` → 403, any other failure or a throw → 401). `context` has `env`, `request`, `surface`,
74
+ `applicationScopes`, `background`. Return a `client` so calls carry `authority`.
75
+
76
+ `tokens.scheme`: `{ type: 'bearer', description }` for application-issued tokens (needs `resolve`, no
77
+ OAuth discovery, cannot mount MCP); `{ type: 'oauth+bearer', description }` for OAuth people plus
78
+ resolver-verified workload keys (every operation in the OpenAPI document declares `actorKinds`).
79
+
80
+ Local development (`examples/minimal-http/src/tokens.ts`): `tokens.development: { binding:
81
+ 'DEVELOPMENT_TOKEN' }` accepts that token, at least 32 characters, from `.dev.vars` only from
82
+ `localhost`/`127.0.0.1`/`[::1]`, as `local-developer` holding every declared scope; every other token is
83
+ verified as usual. Never write that resolver by hand.
84
+
85
+ ## Env
86
+
87
+ Type bindings by what the code uses, so tests can fake them without casts:
88
+
89
+ ```ts
90
+ export interface NoteStore {
91
+ get: (key: string) => Promise<string | null>;
92
+ put: (key: string, value: string) => Promise<void>;
93
+ }
94
+ export interface Env {
95
+ NOTES: NoteStore; // a KVNamespace satisfies it
96
+ PRICING: Service<typeof PricingService>; // RPC binding typed from the owner's entrypoint
97
+ }
98
+ ```
99
+
100
+ ## The Worker
101
+
102
+ ```ts
103
+ import { mcp } from '@arbol-ai/maximus/mcp';
104
+ import { createWorker } from '@arbol-ai/maximus/workers';
105
+
106
+ import { app } from './app';
107
+
108
+ const worker = createWorker(app, {
109
+ transports: [mcp()], // serves the MCP tools; required by app mcp configuration
110
+ // routes, http: { basePath, origins, mounts, before, aroundOperation, fallback, healthPath },
111
+ // assets, handlers: { scheduled, queue }
112
+ });
113
+
114
+ export default worker.handler;
115
+ export const NotesService = worker.entrypoint; // if any operation declares rpc
116
+ ```
117
+
118
+ ## cloudflare.config.ts
119
+
120
+ ```ts
121
+ import { bindings, defineConfig } from 'cf/config';
122
+
123
+ import * as entrypoint from './src/index.ts' with { type: 'cf-worker' };
124
+
125
+ export default defineConfig(({ mode }) => ({
126
+ worker: {
127
+ name: 'notes',
128
+ compatibilityDate: '2026-10-12',
129
+ compatibilityFlags: ['nodejs_compat'], // required: node:async_hooks
130
+ entrypoint,
131
+ observability: { enabled: true },
132
+ env: {
133
+ NOTES: bindings.kv(), // no id: cf deploy provisions it
134
+ DEVELOPMENT_TOKEN: mode === 'development' && bindings.secret(), // cf dev only, from .dev.vars
135
+ },
136
+ },
137
+ }));
138
+ ```
139
+
140
+ `cf` is in beta and needs Node 22+. Wrangler files are not read: convert one with `cf migrate`.
141
+
142
+ ## Run locally
143
+
144
+ ```sh
145
+ echo "DEVELOPMENT_TOKEN=$(openssl rand -hex 32)" > .dev.vars
146
+ bunx cf dev # Vite on http://localhost:5173
147
+ curl -s http://localhost:5173/health
148
+ curl -s http://localhost:5173/openapi.json
149
+ curl -s http://localhost:5173/v1/notes -H "authorization: Bearer $(sed 's/^DEVELOPMENT_TOKEN=//' .dev.vars)"
150
+ ```
151
+
152
+ Several Workers together: the caller's `vite.config.ts` runs the others as auxiliary Workers,
153
+ `cloudflare({ auxiliaryWorkers: [{ config: otherWorker, devOnly: true }] })`.
154
+
155
+ ## Native endpoints (served automatically)
156
+
157
+ `/` (name, OpenAPI path, MCP path), `/health`, `/openapi.json`, `/openapi.yaml`, `/openapi.yml`,
158
+ `/.well-known/oauth-protected-resource` and `…/mcp`. They are reserved paths.
@@ -0,0 +1,77 @@
1
+ # Errors and results
2
+
3
+ ## Results
4
+
5
+ ```ts
6
+ import { err, ok } from '@arbol-ai/maximus';
7
+
8
+ return note ? ok(note) : err(errors.noteNotFound.create());
9
+ ```
10
+
11
+ A handler returns exactly `{ ok: true, value }` or `{ ok: false, error }`. Anything else, a throw, an
12
+ output that fails its schema or exceeds its byte limit, or a failure outside the catalog becomes
13
+ `INTERNAL_ERROR`, reported to diagnostics without its message.
14
+
15
+ ## Catalog
16
+
17
+ ```ts
18
+ export const errors = defineErrors({
19
+ noteNotFound: { code: 'NOTE_NOT_FOUND', status: 404, message: 'The note does not exist.' },
20
+ quotaExceeded: {
21
+ code: 'QUOTA_EXCEEDED',
22
+ status: 429,
23
+ message: 'The organization has reached its note quota.',
24
+ retryable: true,
25
+ retryAfter: 3600,
26
+ dataSchema: t.Object({ limit: t.Integer() }, { additionalProperties: false }),
27
+ },
28
+ });
29
+
30
+ errors.quotaExceeded.create({ limit: 100 }); // data required when dataSchema has required fields
31
+ errors.noteNotFound.is(value);
32
+ errors.status('NOTE_NOT_FOUND'); // 404
33
+ ```
34
+
35
+ - Codes `UPPER_SNAKE_CASE`, unique including standard codes; status 400–599; messages fixed and
36
+ value-free; `dataSchema` strict.
37
+ - Standard names are reserved keys: `invalidInput`, `unauthorized`, `forbidden`, `notFound`,
38
+ `methodNotAllowed`, `tooLarge`, `unsupportedMedia`, `rateLimited`, `internal`,
39
+ `upstreamUnavailable`, `upstreamTimeout`, `outcomeUnknown`. Every catalog contains them, so use
40
+ `errors.forbidden.create()` etc. `standardErrors` is the catalog with nothing added.
41
+ - The catalog's members are reserved keys too: `schema`, `definitions`, `status`, `retryAfter`,
42
+ `validate`.
43
+ - Return only failures from this application's catalog. A dependency's failure must be translated.
44
+
45
+ ## Standard codes
46
+
47
+ | Code | Status | Retryable | Typical cause |
48
+ | --- | --- | --- | --- |
49
+ | `INVALID_INPUT` | 400 | No | Schema refusal with `data.issues` (≤ 10 `{ path, message }`, JSON Pointers); repeated query key; bad JSON |
50
+ | `UNAUTHORIZED` | 401 | No | Missing/invalid token, bad RPC props or principal, invalid proof |
51
+ | `FORBIDDEN` | 403 | No | Missing scope, ineligible actor, absent authority for conditional scopes, proof not admitting the call |
52
+ | `NOT_FOUND` | 404 | No | No route (before authentication), unpinned origin |
53
+ | `HTTP_METHOD_NOT_ALLOWED` | 405 | No | Non-GET on health or a `tokens.resources` path, non-GET/HEAD on assets |
54
+ | `REQUEST_TOO_LARGE` | 413 | No | Body over its limit |
55
+ | `UNSUPPORTED_MEDIA_TYPE` | 415 | No | Non-JSON body; content-encoded byte upload |
56
+ | `RATE_LIMITED` | 429 | Yes (60 s) | The configured rate limit |
57
+ | `INTERNAL_ERROR` | 500 | No | Unexpected error or invalid result |
58
+ | `OUTCOME_UNKNOWN` | 502 | No | Returned by handlers: a write may have happened |
59
+ | `UPSTREAM_UNAVAILABLE` | 503 | Yes | Returned by handlers |
60
+ | `UPSTREAM_TIMEOUT` | 504 | Yes | Returned by handlers |
61
+
62
+ ## Presentation
63
+
64
+ HTTP: the catalog status, the envelope, `Retry-After` for `retryAfter`. MCP: a tool result with
65
+ `isError: true` and the failure JSON. RPC: the `Result` itself. The typed client returns the envelope,
66
+ or with `response: 'data'` throws an `Error` whose `cause` is `{ status, failure, requestId }`.
67
+
68
+ ## Uncertain outcomes and retries
69
+
70
+ - `retryable: true` only when the same call may succeed later (rate limit, outage, timeout).
71
+ - When a write may have been applied and its answer was lost, return
72
+ `errors.outcomeUnknown.create()`. Callers reconcile (read the resource, poll an operation) before
73
+ repeating anything. Record intent before provider writes and use idempotency keys where possible.
74
+ - Never retry uncertain writes or paid provider calls blindly; never turn an outage into an empty
75
+ success.
76
+ - `data` holds finite codes, counts, positions and field paths. Never submitted values, credentials
77
+ or provider bodies.