@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
@@ -0,0 +1,81 @@
1
+ import { Pool, PoolClient } from "pg";
2
+ //#region src/postgres/failures.d.ts
3
+ /** Where a transaction was when it failed. */
4
+ type TransactionStage = 'connect' | 'begin' | 'configure' | 'work' | 'commit';
5
+ /**
6
+ * A classified transaction failure: retryable only when the database says so, and never for a commit whose
7
+ * outcome is unknown.
8
+ */
9
+ interface TransactionFailure {
10
+ /**
11
+ * The stable code callers branch on, such as `DATABASE_RETRY` for a serialization or deadlock abort, or
12
+ * `COMMIT_UNCERTAIN` when the commit's outcome is unknown.
13
+ */
14
+ code: 'DATABASE_CONFLICT' | 'DATABASE_RETRY' | 'DATABASE_UNAVAILABLE' | 'COMMIT_UNCERTAIN' | 'DATABASE_FAILURE';
15
+ /** A fixed description of the failure, never the server's own message or the query text. */
16
+ message: string;
17
+ /** A database retry never authorizes replaying an external effect. */
18
+ retryable: boolean;
19
+ /** Where the transaction was when it failed, such as `work` while the callback ran, or `commit`. */
20
+ stage: TransactionStage;
21
+ /**
22
+ * The five-character SQLSTATE the server reported, such as `40001`; absent when the server reported none
23
+ * and for an uncertain commit.
24
+ */
25
+ sqlState?: string;
26
+ }
27
+ /** Only server ErrorResponse instances establish a SQLSTATE; arbitrary error messages are never classified. */
28
+ export declare function classifyTransactionFailure(error: unknown, stage: TransactionStage): TransactionFailure;
29
+ //#endregion
30
+ //#region src/postgres/transaction.d.ts
31
+ /** The organization a transaction works for, taken from the verified principal. */
32
+ interface TenantContext {
33
+ /**
34
+ * The trusted organization id (1 to 128 letters, digits, `_` and `-`, starting with a letter or digit) that
35
+ * every query in the callback must filter by; any other form is refused.
36
+ */
37
+ readonly organizationId: string;
38
+ }
39
+ /** The time budgets, isolation level and opt-in database-only retries of a transaction. */
40
+ interface TransactionOptions {
41
+ /**
42
+ * How long one statement may run before Postgres aborts it (`statement_timeout`), in milliseconds from 1 to
43
+ * 60000.
44
+ */
45
+ statementTimeoutMs: number;
46
+ /**
47
+ * How long a statement may wait for a lock before Postgres aborts it (`lock_timeout`), in milliseconds from
48
+ * 1 to 60000.
49
+ */
50
+ lockTimeoutMs: number;
51
+ /**
52
+ * How long the transaction may wait idle for its next statement before Postgres ends the session
53
+ * (`idle_in_transaction_session_timeout`), in milliseconds from 1 to 60000.
54
+ */
55
+ idleTimeoutMs: number;
56
+ /** The transaction's isolation level; `read committed` when absent. */
57
+ isolation?: 'read committed' | 'repeatable read' | 'serializable';
58
+ /** Opt in only when the callback performs database work exclusively. Defaults to one attempt. */
59
+ databaseOnlyRetry?: {
60
+ maxAttempts: number;
61
+ baseDelayMs: number;
62
+ };
63
+ }
64
+ /** The work's value, or a classified failure. */
65
+ type TransactionResult<T> = {
66
+ ok: true;
67
+ value: T;
68
+ } | {
69
+ ok: false;
70
+ error: TransactionFailure;
71
+ };
72
+ /**
73
+ * Run short owner SQL on one checked-out client, passing trusted tenant context explicitly.
74
+ * Owners enforce organization predicates and composite keys; this helper does not install RLS
75
+ * or pretend a session setting enforces isolation. The pool must use a restricted runtime role.
76
+ * Never perform provider/model/stream I/O in the callback. Unexpected callback errors retain their
77
+ * identity after rollback. Uncertain COMMIT never retries; reconcile by the owner's logical key.
78
+ */
79
+ export declare function withTenantTransaction<T>(pool: Pick<Pool, 'connect'>, tenant: TenantContext, options: TransactionOptions, work: (client: PoolClient, tenant: TenantContext) => Promise<T>): Promise<TransactionResult<T>>;
80
+ //#endregion
81
+ export type { TenantContext, TransactionFailure, TransactionOptions, TransactionResult, TransactionStage };
@@ -0,0 +1,140 @@
1
+ import { setTimeout } from "node:timers/promises";
2
+ import { DatabaseError } from "pg";
3
+
4
+ //#region src/postgres/failures.ts
5
+ /**
6
+ * Classifies a Postgres transaction failure by the server's SQLSTATE and the stage it happened in, never
7
+ * by its message.
8
+ */
9
+ /** Only server ErrorResponse instances establish a SQLSTATE; arbitrary error messages are never classified. */
10
+ function classifyTransactionFailure(error, stage) {
11
+ const sqlState = error instanceof DatabaseError && /^[0-9A-Z]{5}$/.test(error.code ?? "") ? error.code : void 0;
12
+ if (stage === "commit" && (!sqlState || sqlState.startsWith("08") || sqlState === "40003" || sqlState.startsWith("57"))) return {
13
+ code: "COMMIT_UNCERTAIN",
14
+ message: "Commit outcome must be reconciled before replay.",
15
+ retryable: false,
16
+ stage
17
+ };
18
+ if (sqlState === "40001" || sqlState === "40P01") return {
19
+ code: "DATABASE_RETRY",
20
+ message: "The database transaction was aborted.",
21
+ retryable: true,
22
+ stage,
23
+ sqlState
24
+ };
25
+ if (sqlState === "23505" || sqlState === "23503" || sqlState === "23514" || sqlState === "23P01") return {
26
+ code: "DATABASE_CONFLICT",
27
+ message: "The database constraint rejected the change.",
28
+ retryable: false,
29
+ stage,
30
+ sqlState
31
+ };
32
+ if (stage === "connect" || sqlState?.startsWith("08") || sqlState === "53300" || sqlState === "57P03") return {
33
+ code: "DATABASE_UNAVAILABLE",
34
+ message: "The database is unavailable.",
35
+ retryable: true,
36
+ stage,
37
+ ...sqlState ? { sqlState } : {}
38
+ };
39
+ return {
40
+ code: "DATABASE_FAILURE",
41
+ message: "The database transaction failed.",
42
+ retryable: false,
43
+ stage,
44
+ ...sqlState ? { sqlState } : {}
45
+ };
46
+ }
47
+
48
+ //#endregion
49
+ //#region src/postgres/transaction.ts
50
+ /**
51
+ * Short tenant-scoped Postgres transactions on one checked-out client, with time budgets and opt-in
52
+ * database-only retries.
53
+ */
54
+ /** A verified organization id; the same rule as the core's `OrganizationIdSchema`, which this entry does not import. */
55
+ const ORGANIZATION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
56
+ /**
57
+ * Refuses an organization id that is not one, time budgets outside 1 to 60000 ms, an unknown isolation level
58
+ * and unbounded retries.
59
+ */
60
+ function validateOptions(tenant, options) {
61
+ if (!ORGANIZATION_ID.test(tenant.organizationId)) throw new TypeError("A trusted organization identifier is required.");
62
+ for (const value of [
63
+ options.statementTimeoutMs,
64
+ options.lockTimeoutMs,
65
+ options.idleTimeoutMs
66
+ ]) if (!Number.isSafeInteger(value) || value < 1 || value > 6e4) throw new TypeError("Transaction time budgets must be between 1 and 60000 milliseconds.");
67
+ if (options.isolation && ![
68
+ "read committed",
69
+ "repeatable read",
70
+ "serializable"
71
+ ].includes(options.isolation)) throw new TypeError("Unsupported isolation level.");
72
+ const retry = options.databaseOnlyRetry;
73
+ if (retry && (!Number.isSafeInteger(retry.maxAttempts) || retry.maxAttempts < 1 || retry.maxAttempts > 5 || !Number.isSafeInteger(retry.baseDelayMs) || retry.baseDelayMs < 1 || retry.baseDelayMs > 1e3)) throw new TypeError("Database retries require bounded attempts and delay.");
74
+ }
75
+ /**
76
+ * Run short owner SQL on one checked-out client, passing trusted tenant context explicitly.
77
+ * Owners enforce organization predicates and composite keys; this helper does not install RLS
78
+ * or pretend a session setting enforces isolation. The pool must use a restricted runtime role.
79
+ * Never perform provider/model/stream I/O in the callback. Unexpected callback errors retain their
80
+ * identity after rollback. Uncertain COMMIT never retries; reconcile by the owner's logical key.
81
+ */
82
+ async function withTenantTransaction(pool, tenant, options, work) {
83
+ validateOptions(tenant, options);
84
+ const attempts = options.databaseOnlyRetry?.maxAttempts ?? 1;
85
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
86
+ let client;
87
+ let stage = "connect";
88
+ let discard = false;
89
+ let failure;
90
+ try {
91
+ client = await pool.connect();
92
+ stage = "begin";
93
+ await client.query(`BEGIN ISOLATION LEVEL ${options.isolation ?? "read committed"}`);
94
+ stage = "configure";
95
+ await client.query("SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true), set_config('idle_in_transaction_session_timeout', $3, true)", [
96
+ `${options.statementTimeoutMs}ms`,
97
+ `${options.lockTimeoutMs}ms`,
98
+ `${options.idleTimeoutMs}ms`
99
+ ]);
100
+ stage = "work";
101
+ const value = await work(client, Object.freeze({ organizationId: tenant.organizationId }));
102
+ stage = "commit";
103
+ if ((await client.query("COMMIT")).command !== "COMMIT") return {
104
+ ok: false,
105
+ error: {
106
+ code: "DATABASE_FAILURE",
107
+ message: "The database rolled back the transaction.",
108
+ retryable: false,
109
+ stage
110
+ }
111
+ };
112
+ return {
113
+ ok: true,
114
+ value
115
+ };
116
+ } catch (error) {
117
+ failure = classifyTransactionFailure(error, stage);
118
+ discard = failure.code === "COMMIT_UNCERTAIN" || failure.code === "DATABASE_UNAVAILABLE";
119
+ if (client && !discard) try {
120
+ await client.query("ROLLBACK");
121
+ } catch {
122
+ discard = true;
123
+ }
124
+ if (stage === "work" && failure.code === "DATABASE_FAILURE" && !failure.sqlState) throw error;
125
+ } finally {
126
+ client?.release(discard);
127
+ }
128
+ if (!failure) throw new Error("Missing transaction outcome.");
129
+ if (failure.code !== "DATABASE_RETRY" || discard || attempt === attempts) return {
130
+ ok: false,
131
+ error: failure
132
+ };
133
+ const base = options.databaseOnlyRetry?.baseDelayMs ?? 1;
134
+ await setTimeout(base * attempt + Math.floor(Math.random() * base));
135
+ }
136
+ throw new Error("Unreachable transaction attempt.");
137
+ }
138
+
139
+ //#endregion
140
+ export { classifyTransactionFailure, withTenantTransaction };
@@ -0,0 +1,36 @@
1
+ //#region src/projection.d.ts
2
+ /**
3
+ * How a service's names and input schemas project onto the surfaces a gateway builds from its OpenAPI
4
+ * document, so the service, the gateway and the gateway's generated clients agree without coordinating:
5
+ * the MCP tool, the CLI's kebab-case words, a permission's description and the typed query codec.
6
+ * Browser-safe: no runtime, no schema library.
7
+ */
8
+ /** How one input field travels in a query string. */
9
+ export type QueryKind = 'string' | 'integer' | 'number' | 'boolean' | 'list';
10
+ /** Resolves a local `$ref` (`#/components/schemas/<name>`) of a bundled document. */
11
+ export type SchemaResolver = (reference: string) => unknown;
12
+ /** A resource and the verb that acts on it, such as `appointments` and `findNearest`. */
13
+ export interface ProjectedName {
14
+ /** The resource, in camelCase. */
15
+ readonly resource: string;
16
+ /** The verb, in camelCase. */
17
+ readonly verb: string;
18
+ }
19
+ /** A camelCase name in kebab-case: `findNearest` is `find-nearest`. */
20
+ export declare function kebab(value: string): string;
21
+ /** A camelCase or kebab-case name in snake_case: `findNearest` and `find-nearest` are `find_nearest`. */
22
+ export declare function snake(value: string): string;
23
+ /**
24
+ * What a permission lets a person do, read from its scope: `integrations:service-accounts:write` is
25
+ * "Write service accounts". A description the service declares wins over it; one operation's title
26
+ * never stands in, since a permission covers several operations.
27
+ */
28
+ export declare function permissionDescription(scope: string): string;
29
+ /** Portable across MCP clients and model providers (`^[a-z][a-z0-9_]{0,63}$`). */
30
+ export declare function mcpToolName(namespace: string, name: ProjectedName): string;
31
+ /**
32
+ * How one input field travels in a query string, or null when it cannot: objects and nested lists
33
+ * do not. Lists are comma separated; a `null` alternative is not expressible and is ignored.
34
+ */
35
+ export declare function queryKind(schema: unknown, resolve?: SchemaResolver): QueryKind | null;
36
+ //#endregion
@@ -0,0 +1,60 @@
1
+ //#region src/projection.ts
2
+ function record(value) {
3
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4
+ }
5
+ /** A camelCase name in kebab-case: `findNearest` is `find-nearest`. */
6
+ function kebab(value) {
7
+ return value.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
8
+ }
9
+ /** A camelCase or kebab-case name in snake_case: `findNearest` and `find-nearest` are `find_nearest`. */
10
+ function snake(value) {
11
+ return value.replaceAll("-", "_").replaceAll(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
12
+ }
13
+ /**
14
+ * What a permission lets a person do, read from its scope: `integrations:service-accounts:write` is
15
+ * "Write service accounts". A description the service declares wins over it; one operation's title
16
+ * never stands in, since a permission covers several operations.
17
+ */
18
+ function permissionDescription(scope) {
19
+ const [, ...segments] = scope.split(":");
20
+ const action = segments.at(-1) ?? scope;
21
+ const subject = segments.slice(0, -1).join(" ").replaceAll("-", " ");
22
+ return `${action.charAt(0).toUpperCase()}${action.slice(1)} ${subject}`;
23
+ }
24
+ /** Portable across MCP clients and model providers (`^[a-z][a-z0-9_]{0,63}$`). */
25
+ function mcpToolName(namespace, name) {
26
+ const tool = `${snake(namespace)}_${snake(name.resource)}_${snake(name.verb)}`;
27
+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(tool)) throw new TypeError(`MCP tool name ${tool} is not portable.`);
28
+ return tool;
29
+ }
30
+ function resolved(schema, resolve) {
31
+ let value = schema;
32
+ for (let depth = 0; record(value) && typeof value.$ref === "string"; depth += 1) {
33
+ if (!resolve || depth > 16) return;
34
+ value = resolve(value.$ref);
35
+ }
36
+ return value;
37
+ }
38
+ /**
39
+ * How one input field travels in a query string, or null when it cannot: objects and nested lists
40
+ * do not. Lists are comma separated; a `null` alternative is not expressible and is ignored.
41
+ */
42
+ function queryKind(schema, resolve) {
43
+ const value = resolved(schema, resolve);
44
+ if (!record(value)) return null;
45
+ let branches = null;
46
+ if (Array.isArray(value.anyOf)) branches = value.anyOf;
47
+ else if (Array.isArray(value.oneOf)) branches = value.oneOf;
48
+ if (branches) {
49
+ const kinds = branches.filter((branch) => !(record(branch) && branch.type === "null")).map((branch) => queryKind(branch, resolve));
50
+ if (!kinds.length || kinds.includes(null)) return null;
51
+ if (kinds.includes("list")) return kinds.every((kind) => kind === "list" || kind === "string") ? "list" : null;
52
+ return kinds.every((kind) => kind === kinds[0]) ? kinds[0] ?? null : null;
53
+ }
54
+ if (value.type === "array") return queryKind(value.items, resolve) === "string" ? "list" : null;
55
+ if (value.type === "string" || typeof value.const === "string" || Array.isArray(value.enum) && value.enum.every((entry) => typeof entry === "string")) return "string";
56
+ return value.type === "integer" || value.type === "number" || value.type === "boolean" ? value.type : null;
57
+ }
58
+
59
+ //#endregion
60
+ export { kebab, mcpToolName, permissionDescription, queryKind, snake };
@@ -0,0 +1,2 @@
1
+ import { $ as PageQuery, A as EmptyInputSchema, B as EmailAddressSchema, Ct as decodeInput, Et as parseSchema, F as Type, G as PhoneNumberSchema, H as HttpsUrlSchema, Hn as AttachmentOutputSchema, I as UuidSchema, J as SignedUrl, K as PostalAddress, L as t, M as Static, N as StaticDecode, P as TSchema, Q as PageInfoSchema, R as DeletedObject, St as InputIssue, Tt as parseInput, U as NamedReference, V as HexColorSchema, Vn as Attachment, W as NamedReferenceSchema, X as Page, Y as SignedUrlSchema, Z as PageInfo, _t as refineSchema, at as readSchema, bt as transformSchema, ct as SchemaValidationError, dt as inputSchema, et as PageQueryFields, ft as inspectSchema, gt as pipeSchema, ht as normalizeSchema, it as checkSchema, j as OrganizationIdSchema, lt as defaultSchema, mt as looseObject, nt as pageLimit, ot as SchemaInput, pt as literalUnion, q as PostalAddressSchema, rt as Checked, st as SchemaIssue, tt as TPage, ut as extendObject, vt as strictObject, wt as decodeSchema, xt as urlSchema, yt as stripObject, z as DeletedObjectSchema } from "./chunks/types-CGwAhnTE.js";
2
+ export { type Attachment, AttachmentOutputSchema, type Checked, type DeletedObject, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, HexColorSchema, HttpsUrlSchema, type InputIssue, type NamedReference, NamedReferenceSchema, OrganizationIdSchema, Page, type PageInfo, PageInfoSchema, type PageQuery, PageQueryFields, PhoneNumberSchema, type PostalAddress, PostalAddressSchema, type SchemaInput, type SchemaIssue, SchemaValidationError, type SignedUrl, SignedUrlSchema, type Static, type StaticDecode, type TPage, type TSchema, Type, UuidSchema, checkSchema, decodeInput, decodeSchema, defaultSchema, extendObject, inputSchema, inspectSchema, literalUnion, looseObject, normalizeSchema, pageLimit, parseInput, parseSchema, pipeSchema, readSchema, refineSchema, strictObject, stripObject, t, transformSchema, urlSchema };
@@ -0,0 +1,4 @@
1
+ import { _ as strictObject, b as urlSchema, c as extendObject, d as inspectSchema, f as literalUnion, g as refineSchema, h as pipeSchema, i as parseSchema, m as normalizeSchema, n as decodeSchema, o as SchemaValidationError, p as looseObject, r as parseInput, s as defaultSchema, t as decodeInput, u as inputSchema, v as stripObject, y as transformSchema } from "./chunks/validation-DWxKk1Js.js";
2
+ import { _ as pageLimit, a as t, b as readSchema, c as HexColorSchema, d as PhoneNumberSchema, f as PostalAddressSchema, g as PageQueryFields, h as PageInfoSchema, i as UuidSchema, l as HttpsUrlSchema, m as Page, n as OrganizationIdSchema, o as DeletedObjectSchema, p as SignedUrlSchema, r as Type, s as EmailAddressSchema, t as EmptyInputSchema, u as NamedReferenceSchema, v as AttachmentOutputSchema, y as checkSchema } from "./chunks/schemas-q-51wBMQ.js";
3
+
4
+ export { AttachmentOutputSchema, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, HexColorSchema, HttpsUrlSchema, NamedReferenceSchema, OrganizationIdSchema, Page, PageInfoSchema, PageQueryFields, PhoneNumberSchema, PostalAddressSchema, SchemaValidationError, SignedUrlSchema, Type, UuidSchema, checkSchema, decodeInput, decodeSchema, defaultSchema, extendObject, inputSchema, inspectSchema, literalUnion, looseObject, normalizeSchema, pageLimit, parseInput, parseSchema, pipeSchema, readSchema, refineSchema, strictObject, stripObject, t, transformSchema, urlSchema };
@@ -0,0 +1,91 @@
1
+ //#region src/standard-failures.d.ts
2
+ /**
3
+ * `@arbol-ai/maximus/failures`: the framework's own failures as plain data: code, HTTP status,
4
+ * message, retryability and Retry-After. No runtime and no schema library, for a dispatcher that presents
5
+ * them, such as an API gateway. `defineErrors` builds their schemas from this same table.
6
+ */
7
+ /** One of the framework's own failures. */
8
+ export interface StandardFailure {
9
+ /** The stable code clients branch on, such as `RATE_LIMITED`. */
10
+ readonly code: string;
11
+ /** The HTTP status that answers it. */
12
+ readonly status: number;
13
+ /** A fixed message for people; it never carries request data. */
14
+ readonly message: string;
15
+ /** Whether the same request may succeed later; false when absent. */
16
+ readonly retryable?: boolean;
17
+ /** The seconds a client waits before retrying, sent as `Retry-After`. */
18
+ readonly retryAfter?: number;
19
+ }
20
+ /** The framework's own failures, by the name `standardErrors` gives each. */
21
+ export declare const STANDARD_FAILURES: {
22
+ readonly invalidInput: {
23
+ readonly code: 'INVALID_INPUT';
24
+ readonly status: 400;
25
+ readonly message: 'The request does not match the published schema.';
26
+ };
27
+ readonly unauthorized: {
28
+ readonly code: 'UNAUTHORIZED';
29
+ readonly status: 401;
30
+ readonly message: 'A valid access token is required.';
31
+ };
32
+ readonly forbidden: {
33
+ readonly code: 'FORBIDDEN';
34
+ readonly status: 403;
35
+ readonly message: 'The token does not authorize this operation.';
36
+ };
37
+ readonly notFound: {
38
+ readonly code: 'NOT_FOUND';
39
+ readonly status: 404;
40
+ readonly message: 'The requested operation does not exist.';
41
+ };
42
+ readonly methodNotAllowed: {
43
+ readonly code: 'HTTP_METHOD_NOT_ALLOWED';
44
+ readonly status: 405;
45
+ readonly message: 'The HTTP method is not supported for this resource.';
46
+ };
47
+ readonly tooLarge: {
48
+ readonly code: 'REQUEST_TOO_LARGE';
49
+ readonly status: 413;
50
+ readonly message: 'The request exceeds the allowed size.';
51
+ };
52
+ readonly unsupportedMedia: {
53
+ readonly code: 'UNSUPPORTED_MEDIA_TYPE';
54
+ readonly status: 415;
55
+ readonly message: 'The request content type is not supported.';
56
+ };
57
+ readonly rateLimited: {
58
+ readonly code: 'RATE_LIMITED';
59
+ readonly status: 429;
60
+ readonly message: 'The request rate limit was exceeded. Try again later.';
61
+ readonly retryable: true;
62
+ readonly retryAfter: 60;
63
+ };
64
+ readonly internal: {
65
+ readonly code: 'INTERNAL_ERROR';
66
+ readonly status: 500;
67
+ readonly message: 'The service could not complete the operation.';
68
+ };
69
+ readonly upstreamUnavailable: {
70
+ readonly code: 'UPSTREAM_UNAVAILABLE';
71
+ readonly status: 503;
72
+ readonly message: 'The upstream service could not complete the request.';
73
+ readonly retryable: true;
74
+ };
75
+ readonly upstreamTimeout: {
76
+ readonly code: 'UPSTREAM_TIMEOUT';
77
+ readonly status: 504;
78
+ readonly message: 'The upstream service did not respond before its deadline.';
79
+ readonly retryable: true;
80
+ };
81
+ /**
82
+ * A write may have been applied and its answer was lost. Never retried: the caller reconciles (reads
83
+ * the resource or polls the operation) before deciding to repeat anything.
84
+ */
85
+ readonly outcomeUnknown: {
86
+ readonly code: 'OUTCOME_UNKNOWN';
87
+ readonly status: 502;
88
+ readonly message: 'The operation may have been applied; check its result before repeating it.';
89
+ };
90
+ };
91
+ //#endregion
@@ -0,0 +1,75 @@
1
+ //#region src/standard-failures.ts
2
+ /** The framework's own failures, by the name `standardErrors` gives each. */
3
+ const STANDARD_FAILURES = {
4
+ invalidInput: {
5
+ code: "INVALID_INPUT",
6
+ status: 400,
7
+ message: "The request does not match the published schema."
8
+ },
9
+ unauthorized: {
10
+ code: "UNAUTHORIZED",
11
+ status: 401,
12
+ message: "A valid access token is required."
13
+ },
14
+ forbidden: {
15
+ code: "FORBIDDEN",
16
+ status: 403,
17
+ message: "The token does not authorize this operation."
18
+ },
19
+ notFound: {
20
+ code: "NOT_FOUND",
21
+ status: 404,
22
+ message: "The requested operation does not exist."
23
+ },
24
+ methodNotAllowed: {
25
+ code: "HTTP_METHOD_NOT_ALLOWED",
26
+ status: 405,
27
+ message: "The HTTP method is not supported for this resource."
28
+ },
29
+ tooLarge: {
30
+ code: "REQUEST_TOO_LARGE",
31
+ status: 413,
32
+ message: "The request exceeds the allowed size."
33
+ },
34
+ unsupportedMedia: {
35
+ code: "UNSUPPORTED_MEDIA_TYPE",
36
+ status: 415,
37
+ message: "The request content type is not supported."
38
+ },
39
+ rateLimited: {
40
+ code: "RATE_LIMITED",
41
+ status: 429,
42
+ message: "The request rate limit was exceeded. Try again later.",
43
+ retryable: true,
44
+ retryAfter: 60
45
+ },
46
+ internal: {
47
+ code: "INTERNAL_ERROR",
48
+ status: 500,
49
+ message: "The service could not complete the operation."
50
+ },
51
+ upstreamUnavailable: {
52
+ code: "UPSTREAM_UNAVAILABLE",
53
+ status: 503,
54
+ message: "The upstream service could not complete the request.",
55
+ retryable: true
56
+ },
57
+ upstreamTimeout: {
58
+ code: "UPSTREAM_TIMEOUT",
59
+ status: 504,
60
+ message: "The upstream service did not respond before its deadline.",
61
+ retryable: true
62
+ },
63
+ /**
64
+ * A write may have been applied and its answer was lost. Never retried: the caller reconciles (reads
65
+ * the resource or polls the operation) before deciding to repeat anything.
66
+ */
67
+ outcomeUnknown: {
68
+ code: "OUTCOME_UNKNOWN",
69
+ status: 502,
70
+ message: "The operation may have been applied; check its result before repeating it."
71
+ }
72
+ };
73
+
74
+ //#endregion
75
+ export { STANDARD_FAILURES };
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { randomBytes } from "node:crypto";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, relative, resolve } from "node:path";
6
+
7
+ //#region src/tooling/internal/scaffold.ts
8
+ /**
9
+ * `maximus init`: a new service from the starter template.
10
+ */
11
+ /**
12
+ * The Maximus package's own directory: the nearest one above this module with a package.json. The
13
+ * build bundles this module into the CLI, so its depth below the package differs from the source's.
14
+ */
15
+ function packageDirectory() {
16
+ let directory = import.meta.dirname;
17
+ while (!existsSync(join(directory, "package.json"))) {
18
+ const parent = dirname(directory);
19
+ if (parent === directory) throw new Error("Found no package.json above the Maximus CLI.");
20
+ directory = parent;
21
+ }
22
+ return directory;
23
+ }
24
+ /**
25
+ * `maximus init`: writes a new service from the starter template into a directory that does not exist yet.
26
+ */
27
+ function scaffold(directory, name) {
28
+ if (!/^(?=.{2,41}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name)) throw new TypeError("Use a lowercase kebab-case project name of 2 to 41 characters.");
29
+ const root = resolve(directory);
30
+ if (existsSync(root)) throw new Error("Choose a new directory; existing projects are never overwritten.");
31
+ const own = packageDirectory();
32
+ const template = join(own, "templates", "service");
33
+ const { version } = JSON.parse(readFileSync(join(own, "package.json"), "utf-8"));
34
+ const values = {
35
+ __PROJECT_NAME__: name,
36
+ __ENTRYPOINT__: `${name.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("")}Service`,
37
+ __MAXIMUS_VERSION__: version
38
+ };
39
+ for (const file of readdirSync(template, {
40
+ recursive: true,
41
+ withFileTypes: true
42
+ })) {
43
+ if (!file.isFile() || !file.name.endsWith(".template")) continue;
44
+ const source = resolve(file.parentPath, file.name);
45
+ const target = resolve(root, relative(template, source).replace(/\.template$/, ""));
46
+ mkdirSync(dirname(target), { recursive: true });
47
+ let text = readFileSync(source, "utf-8");
48
+ for (const [placeholder, value] of Object.entries(values)) text = text.replaceAll(placeholder, value);
49
+ writeFileSync(target, text, { flag: "wx" });
50
+ }
51
+ writeFileSync(resolve(root, ".dev.vars"), `DEVELOPMENT_TOKEN=${randomBytes(32).toString("hex")}\n`, {
52
+ flag: "wx",
53
+ mode: 384
54
+ });
55
+ symlinkSync("CLAUDE.md", resolve(root, "AGENTS.md"));
56
+ for (const harness of [".claude", ".codex"]) {
57
+ mkdirSync(resolve(root, harness, "skills"), { recursive: true });
58
+ symlinkSync("../../.agents/skills/project", resolve(root, harness, "skills/project"));
59
+ }
60
+ return {
61
+ directory: root,
62
+ next: "Run bun install and bun run dev, and call it with the DEVELOPMENT_TOKEN in .dev.vars. Before the first deployment, set origin, audience and issuer in src/app.ts, run bun run verify, sign in with cf auth login and run bun run deploy."
63
+ };
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/tooling/cli.ts
68
+ /**
69
+ * The `maximus` command: `init` creates a new service. Developing, building and deploying it are `cf`'s own
70
+ * commands, which Maximus does not wrap.
71
+ */
72
+ const { values, positionals } = parseArgs({
73
+ allowPositionals: true,
74
+ options: {
75
+ name: { type: "string" },
76
+ help: {
77
+ type: "boolean",
78
+ default: false
79
+ }
80
+ }
81
+ });
82
+ const [command, target] = positionals;
83
+ /** The help the command prints for `--help` or a usage mistake. */
84
+ const USAGE = [
85
+ "Usage: maximus init <new-directory> --name <name>",
86
+ "Creates a new service. Develop, build and deploy it with cf: cf dev, cf build, cf workers types and",
87
+ "cf deploy."
88
+ ].join("\n");
89
+ if (values.help) {
90
+ console.info(USAGE);
91
+ process.exit(0);
92
+ }
93
+ /** Runs the command the arguments name. */
94
+ function run() {
95
+ if (command !== "init") {
96
+ console.error(USAGE);
97
+ process.exitCode = 1;
98
+ return;
99
+ }
100
+ if (!target || !values.name) throw new TypeError("Use maximus init <new-directory> --name <name>.");
101
+ console.info(JSON.stringify(scaffold(target, values.name)));
102
+ }
103
+ try {
104
+ run();
105
+ } catch (error) {
106
+ console.error(error instanceof Error && !process.env.MAXIMUS_DEBUG ? `maximus: ${error.message}` : error);
107
+ process.exitCode = 1;
108
+ }
109
+
110
+ //#endregion
@@ -0,0 +1,7 @@
1
+ //#region src/tooling/testing.d.ts
2
+ /** One deployed contract smoke; security and protocol matrices remain framework tests. */
3
+ export declare function verifyContract(fetch: (request: Request) => Promise<Response>, origin: string): Promise<{
4
+ paths: string[];
5
+ operations: string[];
6
+ }>;
7
+ //#endregion
@@ -0,0 +1,21 @@
1
+ import { parse } from "yaml";
2
+
3
+ //#region src/tooling/testing.ts
4
+ /**
5
+ * `@arbol-ai/maximus/testing`: a contract smoke test for a local or deployed service.
6
+ */
7
+ /** One deployed contract smoke; security and protocol matrices remain framework tests. */
8
+ async function verifyContract(fetch, origin) {
9
+ const json = await fetch(new Request(`${origin}/openapi.json`));
10
+ const yaml = await fetch(new Request(`${origin}/openapi.yaml`));
11
+ if (!json.ok || !yaml.ok) throw new Error("OpenAPI is unavailable.");
12
+ const schema = await json.json();
13
+ if (JSON.stringify(schema) !== JSON.stringify(parse(await yaml.text()))) throw new Error("OpenAPI JSON/YAML differ.");
14
+ return {
15
+ paths: Object.keys(schema.paths),
16
+ operations: Object.values(schema.paths).flatMap((path) => Object.values(path).map((op) => op.operationId))
17
+ };
18
+ }
19
+
20
+ //#endregion
21
+ export { verifyContract };