@arbol-ai/maximus 8.5.2 → 8.7.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 (56) hide show
  1. package/dist/analytics/analytics.d.ts +1 -1
  2. package/dist/analytics/analytics.js +1 -1
  3. package/dist/body.d.ts +1 -1
  4. package/dist/body.js +1 -1
  5. package/dist/capture/index.d.ts +1 -1
  6. package/dist/capture/index.js +2 -2
  7. package/dist/chunks/{define-app-CvTei9a8.js → define-app-CRKaiTzi.js} +46 -5
  8. package/dist/chunks/{http-layout-pnmGxDOY.js → http-layout-CB6MdZOO.js} +4 -5
  9. package/dist/chunks/{execution-BJGx5Kxb.js → meter-Mddtgv9_.js} +64 -3
  10. package/dist/chunks/{openapi-file-Crm9fT4U.js → openapi-file-D1Fz9-oO.js} +2 -2
  11. package/dist/chunks/{openapi-CoKhMm1C.js → openapi-tJeJfq1G.js} +7 -5
  12. package/dist/chunks/{pages-D0zdaO0w.js → pages-DzAPVx2p.js} +1 -1
  13. package/dist/chunks/{runtime-CUhyce4d.js → runtime-D-yNrgEP.js} +18 -6
  14. package/dist/chunks/{scaffold-DZD6dfoZ.js → scaffold-BfrJN0Yk.js} +1 -1
  15. package/dist/chunks/{scaffold-DGrcjR3h.js → scaffold-C16tbL7M.js} +1 -1
  16. package/dist/chunks/{server-tygU8dw_.js → server-D49V-Sd4.js} +5 -5
  17. package/dist/chunks/{src-DfMzoKE_.js → src-DPB9t4u0.js} +17 -10
  18. package/dist/chunks/{tasks-DYdY-dBI.js → tasks-CD-B6_nv.js} +2 -2
  19. package/dist/chunks/{tasks-C873C3le.js → tasks-DELqUSq8.js} +1 -1
  20. package/dist/chunks/{tokens-D4gRyyPu.js → tokens-CS3E9OGg.js} +83 -2
  21. package/dist/chunks/{types-BfGa2aJT.d.ts → types-hP7p4Rsp.d.ts} +233 -9
  22. package/dist/chunks/{workers-types-Cxf-5cH7.d.ts → workers-types-qWuu8LZ0.d.ts} +1 -1
  23. package/dist/client.d.ts +1 -1
  24. package/dist/diagnostics.d.ts +1 -1
  25. package/dist/diagnostics.js +1 -1
  26. package/dist/errors.d.ts +1 -1
  27. package/dist/http-paths.d.ts +1 -1
  28. package/dist/index.d.ts +2 -2
  29. package/dist/index.js +5 -5
  30. package/dist/internals.d.ts +2 -2
  31. package/dist/internals.js +5 -5
  32. package/dist/mcp/index.d.ts +1 -1
  33. package/dist/mcp/index.js +1 -1
  34. package/dist/mcp/tasks.d.ts +1 -1
  35. package/dist/mcp/tasks.js +1 -1
  36. package/dist/project/config.d.ts +5 -3
  37. package/dist/project/config.js +1 -1
  38. package/dist/project/index.d.ts +2 -2
  39. package/dist/project/index.js +2 -2
  40. package/dist/schemas.d.ts +1 -1
  41. package/dist/standard-failures.d.ts +1 -1
  42. package/dist/tooling/cli.js +2 -2
  43. package/dist/vite/index.d.ts +17 -2
  44. package/dist/vite/index.js +22 -10
  45. package/dist/webhooks.d.ts +1 -1
  46. package/dist/workers/runtime.d.ts +1 -1
  47. package/dist/workers/runtime.js +1 -1
  48. package/package.json +10 -10
  49. package/skills/maximus/SKILL.md +9 -7
  50. package/skills/maximus/references/project.md +6 -4
  51. package/skills/maximus/references/routes-and-tools.md +22 -0
  52. package/skills/maximus/references/testing.md +1 -1
  53. package/templates/project/.github/workflows/ci.yml.template +23 -2
  54. package/templates/project/CLAUDE.md.template +1 -1
  55. package/templates/project/README.md.template +3 -3
  56. package/templates/project/package.json.template +13 -13
@@ -1,4 +1,4 @@
1
- import { Hn as Observer } from "../chunks/types-BfGa2aJT.js";
1
+ import { rr as Observer } from "../chunks/types-hP7p4Rsp.js";
2
2
  import { Static, Type } from "typebox";
3
3
  /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
4
4
  export declare const ExecutionEventSchema: Type.TObject<{
@@ -1,5 +1,5 @@
1
- import { f as Value } from "../chunks/validation-CpzAxj2_.js";
2
1
  import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-_UJcx_uY.js";
2
+ import { f as Value } from "../chunks/validation-CpzAxj2_.js";
3
3
  import { s as telemetryEnabled } from "../chunks/telemetry-BtxJh69Q.js";
4
4
  import { Type } from "typebox";
5
5
 
package/dist/body.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as readBodyText, c as isJsonMediaType, d as retryAfterSeconds, f as publicDestination, g as readBodyBytes, h as HttpBodyFailureReason, l as readJsonBody, m as HttpBodyFailure, p as BodyReadOptions, u as readJsonResponse } from "./chunks/types-BfGa2aJT.js";
1
+ import { _ as readBodyText, c as isJsonMediaType, d as retryAfterSeconds, f as publicDestination, g as readBodyBytes, h as HttpBodyFailureReason, l as readJsonBody, m as HttpBodyFailure, p as BodyReadOptions, u as readJsonResponse } from "./chunks/types-hP7p4Rsp.js";
2
2
  export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, publicDestination, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
package/dist/body.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as readBodyBytes, r as readBodyText } from "./chunks/body-DOIHwIIl.js";
2
- import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-B14evE6-.js";
3
2
  import { t as publicDestination } from "./chunks/destination-5xTX0b7E.js";
3
+ import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-B14evE6-.js";
4
4
 
5
5
  export { isJsonMediaType, publicDestination, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -1,4 +1,4 @@
1
- import { An as CaptureConfig, Kt as RegisteredEnv, Mn as CaptureInvocation, Nn as CaptureSink, ct as withoutSecrets, hr as CaptureRecordSchema, jn as CaptureDimensions, kn as AnyContext, mr as CaptureRecord } from "../chunks/types-BfGa2aJT.js";
1
+ import { Ar as CaptureRecordSchema, Gn as CaptureConfig, Jn as CaptureSink, Kn as CaptureDimensions, Kt as RegisteredEnv, Wn as AnyContext, ct as withoutSecrets, kr as CaptureRecord, qn as CaptureInvocation } from "../chunks/types-hP7p4Rsp.js";
2
2
  /** What `pipeline()` takes. */
3
3
  interface PipelineOptions<E> {
4
4
  /**
@@ -1,7 +1,7 @@
1
1
  import { B as withoutSecrets, i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-_UJcx_uY.js";
2
- import { t as isRecord } from "../chunks/record-DQUDTpEA.js";
3
- import { t as sha256Hex } from "../chunks/digest-C51F1bhA.js";
4
2
  import { t as delay } from "../chunks/delay-BsKQP_lF.js";
3
+ import { t as sha256Hex } from "../chunks/digest-C51F1bhA.js";
4
+ import { t as isRecord } from "../chunks/record-DQUDTpEA.js";
5
5
  import { Type } from "typebox";
6
6
 
7
7
  // src/capture-record.ts
@@ -1,10 +1,10 @@
1
- import { R as holdsSecrets, T as hasUncompiledCodecs } from "./schemas-_UJcx_uY.js";
2
1
  import { i as standardErrors } from "./errors-BoutSmiy.js";
3
2
  import { n as readBodyBytes } from "./body-DOIHwIIl.js";
4
3
  import { a as operationPathParameters, r as isInputHeaderName, t as createHttpRouteResolver } from "./http-paths-D043DkJv.js";
4
+ import { R as holdsSecrets, T as hasUncompiledCodecs } from "./schemas-_UJcx_uY.js";
5
5
  import { t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
6
- import { b as operationScopes, d as MAX_BODY_BYTES_CEILING, f as STANDARD_CODES, t as MAX_TASK_TTL_MS, x as isNamespacedScope } from "./tasks-DYdY-dBI.js";
7
- import { g as hasSchemaReferences, m as bundleSchemas, o as tokenAudiences, t as checkTokenAuthority } from "./tokens-D4gRyyPu.js";
6
+ import { b as operationScopes, d as MAX_BODY_BYTES_CEILING, f as STANDARD_CODES, t as MAX_TASK_TTL_MS, x as isNamespacedScope } from "./tasks-CD-B6_nv.js";
7
+ import { b as checkRoles, g as hasSchemaReferences, m as bundleSchemas, o as tokenAudiences, t as checkTokenAuthority } from "./tokens-CS3E9OGg.js";
8
8
  import { IsKind } from "typebox";
9
9
 
10
10
  // src/internal/exact-length.ts
@@ -161,9 +161,18 @@ const OPERATION_FIELDS = new Set(Object.keys({
161
161
  output: true,
162
162
  maxBodyBytes: true,
163
163
  maxOutputBytes: true,
164
+ meter: true,
164
165
  execute: true,
165
166
  pipeline: true
166
167
  }));
168
+ /** The functions an operation's `meter` may hold beside its fact, each of the answer's output and input. */
169
+ const METER_FUNCTIONS = [
170
+ "when",
171
+ "value",
172
+ "properties"
173
+ ];
174
+ /** Every field an operation's `meter` has: its fact and those functions. */
175
+ const METER_FIELDS = /* @__PURE__ */ new Set(["feature", ...METER_FUNCTIONS]);
167
176
  /**
168
177
  * Checks an application against every rule `.build()` enforces, then hands it back unchanged; a refusal is a
169
178
  * TypeError. Curried, so `Env` and `C` can be given explicitly while the operations' types are inferred from
@@ -198,6 +207,8 @@ function checkApplication(manifest) {
198
207
  if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
199
208
  checkTelemetry(manifest.telemetry);
200
209
  checkCapture(manifest.capture);
210
+ checkMeter(manifest.meter);
211
+ checkRoles(manifest);
201
212
  checkTokenAuthority(manifest.tokens, manifest.namespace);
202
213
  tokenAudiences(manifest.tokens);
203
214
  if (Object.keys(manifest.tokens.resources ?? {}).length > 0 && manifest.tokens.resourceMetadataUrl === void 0) throw new TypeError("tokens.resources requires tokens.resourceMetadataUrl: name the metadata a 401 challenge points at.");
@@ -235,6 +246,27 @@ function checkCapture(capture) {
235
246
  if (capture === void 0) return;
236
247
  if (typeof capture !== "object" || capture === null || capture.enabled !== void 0 && typeof capture.enabled !== "boolean" && typeof capture.enabled !== "function" || typeof capture.sink?.send !== "function" || capture.sink.available !== void 0 && typeof capture.sink.available !== "function" || capture.payloads !== void 0 && capture.payloads !== "all" && capture.payloads !== "none" || capture.dimensions !== void 0 && typeof capture.dimensions !== "function") throw new TypeError("Capture takes enabled as true, false or a function of env, sink as an object whose send and available are functions, payloads as all or none, and dimensions as a function.");
237
248
  }
249
+ /**
250
+ * The application's `meter`, as code untyped by TypeScript may give it: the name of the env binding its billing
251
+ * service answers on, and nothing else. A meter without one would report every billable call nowhere.
252
+ */
253
+ function checkMeter(meter) {
254
+ if (meter === void 0) return;
255
+ if (typeof meter !== "object" || meter === null || Object.keys(meter).some((field) => field !== "binding") || typeof meter.binding !== "string" || meter.binding === "") throw new TypeError("Meter takes binding, the name of the env binding of the billing service it reports to.");
256
+ }
257
+ /**
258
+ * An operation's `meter`: a fact named by a non-empty string, `when`, `value` and `properties` as functions
259
+ * when present, and nothing else; and the application's billing service, without which every billable call
260
+ * would go unreported.
261
+ */
262
+ function checkOperationMeter(name, meter, application) {
263
+ if (meter === void 0) return;
264
+ if (typeof meter !== "object" || meter === null || Object.keys(meter).some((field) => !METER_FIELDS.has(field)) || typeof Reflect.get(meter, "feature") !== "string" || Reflect.get(meter, "feature") === "" || METER_FUNCTIONS.some((field) => {
265
+ const declared = Reflect.get(meter, field);
266
+ return declared !== void 0 && typeof declared !== "function";
267
+ })) throw new TypeError(`Operation "${name}": meter is { feature, when?, value?, properties? }: the fact a billable call is, and functions of its output and input.`);
268
+ if (application.meter === void 0) throw new TypeError(`Operation "${name}": meter reports to the application's billing service; name its binding with meter: { binding }.`);
269
+ }
238
270
  /** An operation's `failures` name domain codes of the catalog, each once. */
239
271
  function checkDeclaredFailures(operations, errors) {
240
272
  const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
@@ -242,7 +274,7 @@ function checkDeclaredFailures(operations, errors) {
242
274
  }
243
275
  /** Every rule one operation keeps, in the order a definition is usually written. */
244
276
  function checkOperation(name, op, application, claimed) {
245
- checkOperationContract(name, op, application.namespace);
277
+ checkOperationContract(name, op, application.namespace, application.errors);
246
278
  if (application.tokens.scheme?.type === "oauth+bearer" && !op.actorKinds) throw new TypeError(`Operation "${name}": dual authentication requires explicit actor eligibility.`);
247
279
  checkHttpExposure(name, op, claimed.routes);
248
280
  if (op.conditionalScopes && (!op.conditionalScopes.length || new Set(op.conditionalScopes).size !== op.conditionalScopes.length || op.conditionalScopes.some((scope) => operationScopes(op).includes(scope) || !isNamespacedScope(scope, application.namespace)))) throw new TypeError(`Operation "${name}": conditional scopes require unique namespaced declarations distinct from the admission scope.`);
@@ -251,9 +283,10 @@ function checkOperation(name, op, application, claimed) {
251
283
  claimed.tools.add(op.mcp.name);
252
284
  }
253
285
  if (op.rpc && op.rpc !== true && op.rpc.callers.some((caller) => !application.rpc.callers.includes(caller))) throw new TypeError(`Operation "${name}": RPC callers must be allowed by the application.`);
286
+ checkOperationMeter(name, op.meter, application);
254
287
  }
255
288
  /** The operation's fields, name, scopes, eligible actors and schemas. */
256
- function checkOperationContract(name, op, namespace) {
289
+ function checkOperationContract(name, op, namespace, errors) {
257
290
  const unknown = Object.keys(op).find((field) => !OPERATION_FIELDS.has(field));
258
291
  if (unknown !== void 0) throw new TypeError(`Operation "${name}": "${unknown}" is not an operation field.`);
259
292
  if (op.scopeMatch !== void 0 && op.scopeMatch !== "any" && op.scopeMatch !== "all") throw new TypeError(`Operation "${name}": scopeMatch must be any or all.`);
@@ -266,6 +299,14 @@ function checkOperationContract(name, op, namespace) {
266
299
  if (looseRecord(op.input) || looseRecord(op.output)) throw new TypeError(`Operation "${name}": a record whose keys follow a pattern takes additionalProperties: false, t.Record(key, value, { additionalProperties: false }), or a key outside the pattern passes unchecked.`);
267
300
  if (!validTask(op.task)) throw new TypeError(`Operation "${name}": task is true or { ttlMs }, a positive integer of milliseconds up to a day.`);
268
301
  if (op.task && holdsSecrets(op.output)) throw new TypeError(`Operation "${name}": a task keeps its result until it expires, so its output marks nothing secret: true.`);
302
+ if (op.task && failureDataHoldsSecrets(op, errors)) throw new TypeError(`Operation "${name}": a task keeps its failure until it expires, so the data of every failure it may answer marks nothing secret: true.`);
303
+ }
304
+ /**
305
+ * Whether the data of a failure the operation may answer marks anything `secret: true`. Execution admits the
306
+ * standard failures and those it declares, or the whole catalog when it declares none.
307
+ */
308
+ function failureDataHoldsSecrets(op, errors) {
309
+ return Object.values(errors.definitions).filter(({ code }) => op.failures === void 0 || STANDARD_CODES.has(code) || op.failures.includes(code)).some(({ dataSchema }) => dataSchema !== void 0 && holdsSecrets(dataSchema));
269
310
  }
270
311
  /** Whether `task` is absent, `true` or `{ ttlMs }`: a positive integer of milliseconds up to a day. */
271
312
  function validTask(task) {
@@ -1,4 +1,4 @@
1
- import { f as usesCloudflareAccess, l as usesOwnBearer } from "./tokens-D4gRyyPu.js";
1
+ import { f as usesCloudflareAccess, l as usesOwnBearer } from "./tokens-CS3E9OGg.js";
2
2
 
3
3
  // src/internal/http-layout.ts
4
4
  /**
@@ -88,13 +88,12 @@ function servesOwnBearer(tokens, mcp) {
88
88
  return ownBearer;
89
89
  }
90
90
  /**
91
- * Whether the application admits Cloudflare Access application tokens, refusing the MCP transport beside
92
- * them: MCP clients find their authorization server through OAuth discovery and present its bearer tokens,
93
- * neither of which Access serves.
91
+ * Whether the application admits Cloudflare Access application tokens. MCP clients need OAuth discovery;
92
+ * Access can serve it at the edge and pass its verified application token to the Worker.
94
93
  */
95
94
  function servesCloudflareAccess(tokens, mcp) {
96
95
  const access = usesCloudflareAccess(tokens);
97
- if (access && mcp) throw new TypeError("The MCP transport needs OAuth discovery and bearer tokens; it cannot serve Cloudflare Access application tokens.");
96
+ if (access && mcp && tokens.access?.managedOAuth !== true) throw new TypeError("The MCP transport needs OAuth discovery and bearer tokens; it cannot serve Cloudflare Access application tokens.");
98
97
  return access;
99
98
  }
100
99
  /**
@@ -1,8 +1,8 @@
1
1
  import { f as Value, t as admitInput } from "./validation-CpzAxj2_.js";
2
2
  import { B as withoutSecrets, R as holdsSecrets } from "./schemas-_UJcx_uY.js";
3
3
  import { i as standardErrors } from "./errors-BoutSmiy.js";
4
- import { a as isAttachmentSchema, o as validAttachment } from "./define-app-CvTei9a8.js";
5
- import { b as operationScopes, c as ADMISSION_CODES, f as STANDARD_CODES, l as BODY_CODES, v as operationMatchesScopes, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
4
+ import { a as isAttachmentSchema, o as validAttachment } from "./define-app-CRKaiTzi.js";
5
+ import { b as operationScopes, c as ADMISSION_CODES, f as STANDARD_CODES, l as BODY_CODES, v as operationMatchesScopes, y as operationOutputLimit } from "./tasks-CD-B6_nv.js";
6
6
  import { t as err } from "./result-CF4OzG9O.js";
7
7
  import { t as sha256Hex } from "./digest-C51F1bhA.js";
8
8
  import { t as delay } from "./delay-BsKQP_lF.js";
@@ -262,4 +262,65 @@ async function executeOperation(manifest, operation, env, principal, input, auth
262
262
  }
263
263
  }
264
264
 
265
- export { recordCapture as n, executeOperation as t };
265
+ // src/meter.ts
266
+ /** Writes one line of the meter's own diagnostics: the operation and the request id, never what it reports. */
267
+ function logMeter(event, metered) {
268
+ try {
269
+ console.error(JSON.stringify({
270
+ event,
271
+ operation: metered.operation,
272
+ requestId: metered.principal.requestId
273
+ }));
274
+ } catch {}
275
+ }
276
+ /** The fact an answer reports, or undefined when its operation's `when` says it is not billable. */
277
+ function billableFact(meter, output, input) {
278
+ if (meter.when && meter.when(output, input) !== true) return;
279
+ const value = meter.value?.(output, input);
280
+ const properties = meter.properties?.(output, input);
281
+ return {
282
+ feature: meter.feature,
283
+ ...value === void 0 ? {} : { value },
284
+ ...properties === void 0 ? {} : { properties }
285
+ };
286
+ }
287
+ /**
288
+ * Reports the fact an answer is, once and never again: a declaration that throws logs
289
+ * `maximus.meter.evaluation_failed`, and a billing service that refuses it or cannot be reached logs
290
+ * `maximus.meter.delivery_failed`.
291
+ */
292
+ async function report(meter, service, metered, output) {
293
+ await delay(0);
294
+ let fact;
295
+ try {
296
+ fact = billableFact(meter, output, metered.call?.admitted?.decoded);
297
+ } catch {
298
+ logMeter("maximus.meter.evaluation_failed", metered);
299
+ return;
300
+ }
301
+ if (!fact) return;
302
+ try {
303
+ await service.reportUsage(metered.principal.organizationId, fact);
304
+ } catch {
305
+ logMeter("maximus.meter.delivery_failed", metered);
306
+ }
307
+ }
308
+ /**
309
+ * Reports the fact a successful call is, beside `recordCapture`, when its operation declares `meter`: to the
310
+ * billing service the application names, for the verified organization, as background work after the answer,
311
+ * once and never retried. It never throws, and never delays or changes the answer. Nothing is reported for a
312
+ * failure, without a background context, or while the env has no such binding, as in a preview.
313
+ */
314
+ function recordMeter(application, env, background, metered) {
315
+ const binding = application.meter?.binding;
316
+ const meter = Object.hasOwn(application.operations, metered.operation) ? application.operations[metered.operation]?.meter : void 0;
317
+ if (binding === void 0 || meter === void 0 || !background || !metered.result.ok) return;
318
+ try {
319
+ const service = env?.[binding];
320
+ if (service) background.waitUntil(report(meter, service, metered, metered.result.value));
321
+ } catch {
322
+ logMeter("maximus.meter.delivery_failed", metered);
323
+ }
324
+ }
325
+
326
+ export { executeOperation as n, recordCapture as r, recordMeter as t };
@@ -1,6 +1,6 @@
1
- import { n as createRpcOpenApi } from "./openapi-CoKhMm1C.js";
1
+ import { n as createRpcOpenApi } from "./openapi-tJeJfq1G.js";
2
2
  import { t as prepareConfiguredProject } from "./prepare-configured-Cithjf80.js";
3
- import { t as packageDirectory } from "./scaffold-DZD6dfoZ.js";
3
+ import { t as packageDirectory } from "./scaffold-BfrJN0Yk.js";
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join, relative, resolve } from "node:path";
6
6
 
@@ -1,9 +1,9 @@
1
- import { L as wireInput } from "./schemas-_UJcx_uY.js";
1
+ import { S as resolveRoles, _ as schemaIds, f as usesCloudflareAccess, h as canonical, m as bundleSchemas, s as tokenEndpoints } from "./tokens-CS3E9OGg.js";
2
2
  import { a as operationPathParameters } from "./http-paths-D043DkJv.js";
3
- import { n as routeGroup, t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
4
- import { _ as operationBodyLimit, b as operationScopes, f as STANDARD_CODES, h as mcpOpenWorld, l as BODY_CODES, m as isPublicOperation, n as TASK_GROUP, r as TASK_GROUP_DESCRIPTION, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
5
- import { _ as schemaIds, f as usesCloudflareAccess, h as canonical, m as bundleSchemas, s as tokenEndpoints } from "./tokens-D4gRyyPu.js";
3
+ import { L as wireInput } from "./schemas-_UJcx_uY.js";
6
4
  import { t as queryKind } from "./query-kind-CWKAXEME.js";
5
+ import { n as routeGroup, t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
6
+ import { _ as operationBodyLimit, b as operationScopes, f as STANDARD_CODES, h as mcpOpenWorld, l as BODY_CODES, m as isPublicOperation, n as TASK_GROUP, r as TASK_GROUP_DESCRIPTION, y as operationOutputLimit } from "./tasks-CD-B6_nv.js";
7
7
  import { Type } from "typebox";
8
8
 
9
9
  // src/internal/http-query.ts
@@ -323,7 +323,8 @@ function bodyWithoutPathParameters(input, names) {
323
323
  * The document the origin serves at `/openapi.json`: every public operation that declares an HTTP route,
324
324
  * never an internal one, under one tag per group. Each request body, success envelope and failure is a named
325
325
  * component, which a generated client names its types after; each operation also carries its scopes,
326
- * effect, limits in force, MCP tool hints and native RPC as `x-*` extensions.
326
+ * effect, limits in force, MCP tool hints and native RPC as `x-*` extensions. An application that declares
327
+ * roles publishes each with the scopes it holds, as `x-maximus-roles`.
327
328
  *
328
329
  * Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
329
330
  * schemas of its paths and components (TypeBox Cyclic/Ref) become components, as `bundleSchemas`
@@ -478,6 +479,7 @@ function openApiDocument(manifest, kind) {
478
479
  } : { name: group };
479
480
  }),
480
481
  paths,
482
+ ...rpc || !manifest.roles ? {} : { "x-maximus-roles": resolveRoles(manifest) },
481
483
  components: {
482
484
  schemas: components.schemas,
483
485
  ...headers.size ? { headers: Object.fromEntries([...headers].map((name) => [name, HEADERS[name]])) } : {},
@@ -1,4 +1,4 @@
1
- import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-pnmGxDOY.js";
1
+ import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-CB6MdZOO.js";
2
2
 
3
3
  // src/project/pages.ts
4
4
  /**
@@ -1,12 +1,12 @@
1
- import { i as parseInput } from "./validation-CpzAxj2_.js";
2
- import { r as isRequestId } from "./correlation-4b23a-a4.js";
1
+ import { n as executeOperation, r as recordCapture, t as recordMeter } from "./meter-Mddtgv9_.js";
3
2
  import { i as standardErrors } from "./errors-BoutSmiy.js";
4
- import { p as PrincipalSchema } from "./tokens-D4gRyyPu.js";
3
+ import { r as createHttpHandler } from "./src-DPB9t4u0.js";
5
4
  import { r as ok, t as err } from "./result-CF4OzG9O.js";
6
- import { r as createHttpHandler } from "./src-DfMzoKE_.js";
7
- import { t as delay } from "./delay-BsKQP_lF.js";
5
+ import { p as PrincipalSchema } from "./tokens-CS3E9OGg.js";
6
+ import { i as parseInput } from "./validation-CpzAxj2_.js";
8
7
  import { a as recordExecution, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
9
- import { n as recordCapture, t as executeOperation } from "./execution-BJGx5Kxb.js";
8
+ import { r as isRequestId } from "./correlation-4b23a-a4.js";
9
+ import { t as delay } from "./delay-BsKQP_lF.js";
10
10
  import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
11
11
 
12
12
  // src/workers/assets.ts
@@ -252,6 +252,12 @@ function tasksObject(manifest) {
252
252
  result,
253
253
  call
254
254
  });
255
+ recordMeter(manifest, this.env, background, {
256
+ operation: task.operation,
257
+ principal: task.principal,
258
+ result,
259
+ call
260
+ });
255
261
  await this.#settle(task, result);
256
262
  } finally {
257
263
  this.#running = false;
@@ -367,6 +373,12 @@ function createWorker(application, options = {}) {
367
373
  result,
368
374
  call
369
375
  });
376
+ recordMeter(manifest, this.env, this.ctx, {
377
+ operation: name,
378
+ principal: parsed.value,
379
+ result,
380
+ call
381
+ });
370
382
  return result;
371
383
  }
372
384
  });
@@ -131,7 +131,7 @@ function scaffold(directory, name, options = {}) {
131
131
  mcp: options.mcp !== false,
132
132
  web: options.web === true,
133
133
  skills,
134
- next: "Run bun install and bun run dev. Set origin and tokens.issuer in vite.config.ts before the first deployment; bun run verify runs the types, lint, tests and build, and bun run deploy deploys."
134
+ next: "Run bun install and bun run dev. Before the first deployment, set origin and tokens.issuer in vite.config.ts. Run bun run verify for static checks and a build, or bun run deploy to deploy."
135
135
  };
136
136
  }
137
137
 
@@ -1,3 +1,3 @@
1
- import { n as scaffold, t as packageDirectory } from "./scaffold-DZD6dfoZ.js";
1
+ import { n as scaffold, t as packageDirectory } from "./scaffold-BfrJN0Yk.js";
2
2
 
3
3
  export { scaffold };
@@ -1,10 +1,10 @@
1
- import { L as wireInput } from "./schemas-_UJcx_uY.js";
2
- import { i as standardErrors } from "./errors-BoutSmiy.js";
3
- import { d as MAX_BODY_BYTES_CEILING, h as mcpOpenWorld, v as operationMatchesScopes } from "./tasks-DYdY-dBI.js";
4
- import { h as canonical, v as standaloneSchema } from "./tokens-D4gRyyPu.js";
1
+ import { d as MAX_BODY_BYTES_CEILING, h as mcpOpenWorld, v as operationMatchesScopes } from "./tasks-CD-B6_nv.js";
5
2
  import { o as reportUnexpected } from "./telemetry-BtxJh69Q.js";
3
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
4
+ import { L as wireInput } from "./schemas-_UJcx_uY.js";
5
+ import { h as canonical, v as standaloneSchema } from "./tokens-CS3E9OGg.js";
6
6
  import { t as toYaml } from "./yaml-Dk2L24yQ.js";
7
- import { a as mcpTask, n as attachTasks, o as toolResult, r as declaresTasks } from "./tasks-C873C3le.js";
7
+ import { a as mcpTask, n as attachTasks, o as toolResult, r as declaresTasks } from "./tasks-DELqUSq8.js";
8
8
  import { McpServer, ProtocolError, ProtocolErrorCode, createMcpHandler } from "@modelcontextprotocol/server";
9
9
  import { SkillCatalog, memorySkillFiles } from "@modelcontextprotocol/server/ext/skills";
10
10
 
@@ -1,17 +1,17 @@
1
+ import { i as binaryBody, n as defineApp, r as attachmentResponse } from "./define-app-CRKaiTzi.js";
2
+ import { a as taskAccess, b as operationScopes, m as isPublicOperation, o as taskView, p as composeOperations, s as withTaskOperations, u as DEFAULT_MAX_BODY_BYTES, v as operationMatchesScopes } from "./tasks-CD-B6_nv.js";
3
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
1
4
  import { i as standardErrors } from "./errors-BoutSmiy.js";
2
- import { r as readBodyText } from "./body-DOIHwIIl.js";
3
- import { i as binaryBody, n as defineApp, r as attachmentResponse } from "./define-app-CvTei9a8.js";
5
+ import { c as tokenIssuer, i as presentedToken, n as createTokenAuthorization, o as tokenAudiences, u as isCrossSiteWrite } from "./tokens-CS3E9OGg.js";
6
+ import { n as executeOperation, r as recordCapture, t as recordMeter } from "./meter-Mddtgv9_.js";
4
7
  import { t as createHttpRouteResolver } from "./http-paths-D043DkJv.js";
5
- import { a as taskAccess, b as operationScopes, m as isPublicOperation, o as taskView, p as composeOperations, s as withTaskOperations, u as DEFAULT_MAX_BODY_BYTES, v as operationMatchesScopes } from "./tasks-DYdY-dBI.js";
6
- import { c as tokenIssuer, i as presentedToken, n as createTokenAuthorization, o as tokenAudiences, u as isCrossSiteWrite } from "./tokens-D4gRyyPu.js";
7
- import { r as ok, t as err } from "./result-CF4OzG9O.js";
8
+ import { r as readBodyText } from "./body-DOIHwIIl.js";
8
9
  import { t as sha256Hex } from "./digest-C51F1bhA.js";
9
- import { a as recordExecution, i as recordAdmission, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
10
- import { n as recordCapture, t as executeOperation } from "./execution-BJGx5Kxb.js";
11
- import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-pnmGxDOY.js";
12
- import { i as queryKinds, r as queryInput, t as createOpenApi } from "./openapi-CoKhMm1C.js";
10
+ import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-CB6MdZOO.js";
11
+ import { i as queryKinds, r as queryInput, t as createOpenApi } from "./openapi-tJeJfq1G.js";
13
12
  import { n as mediaType } from "./json-B14evE6-.js";
14
13
  import { t as toYaml } from "./yaml-Dk2L24yQ.js";
14
+ import { a as recordExecution, i as recordAdmission, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
15
15
  import { Type as Type$1, Type as t } from "typebox";
16
16
 
17
17
  // src/builder.ts
@@ -450,7 +450,8 @@ function createHttpHandler(manifest, hooks = {}) {
450
450
  for (let admitted = 0; admitted < requests; admitted += 1) if (!await withinRateLimit(scopedEnv, authenticated)) return reject(standardErrors.rateLimited.create());
451
451
  }
452
452
  /**
453
- * Runs one operation through the shared execution path as the admitted caller, and records the call.
453
+ * Runs one operation through the shared execution path as the admitted caller, records the call and
454
+ * reports the fact a billable call is.
454
455
  */
455
456
  async function invoke(name, op, input) {
456
457
  if (transport && !operations.some(([selectedName, selected]) => selectedName === name && selected === op)) {
@@ -491,6 +492,12 @@ function createHttpHandler(manifest, hooks = {}) {
491
492
  result: output,
492
493
  call
493
494
  });
495
+ recordMeter(manifest, scopedEnv, background, {
496
+ operation: name,
497
+ principal: actor,
498
+ result: output,
499
+ call
500
+ });
494
501
  return output;
495
502
  }
496
503
  if (transport) return transport.handle({
@@ -1,7 +1,7 @@
1
+ import { i as standardErrors, t as FailureSchema } from "./errors-BoutSmiy.js";
2
+ import { O as literalUnion, i as UuidSchema } from "./schemas-_UJcx_uY.js";
1
3
  import { f as Value } from "./validation-CpzAxj2_.js";
2
4
  import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
3
- import { O as literalUnion, i as UuidSchema } from "./schemas-_UJcx_uY.js";
4
- import { i as standardErrors, t as FailureSchema } from "./errors-BoutSmiy.js";
5
5
  import { r as ok, t as err } from "./result-CF4OzG9O.js";
6
6
  import { Type } from "typebox";
7
7
 
@@ -1,4 +1,4 @@
1
- import { i as TASK_POLL_MS } from "./tasks-DYdY-dBI.js";
1
+ import { i as TASK_POLL_MS } from "./tasks-CD-B6_nv.js";
2
2
  import { ProtocolError, ProtocolErrorCode } from "@modelcontextprotocol/server";
3
3
 
4
4
  // src/mcp/tasks.ts
@@ -2,12 +2,92 @@ import { i as parseInput } from "./validation-CpzAxj2_.js";
2
2
  import { i as UuidSchema, n as OrganizationIdSchema, z as withoutSecretKeyword } from "./schemas-_UJcx_uY.js";
3
3
  import { t as isRecord } from "./record-DQUDTpEA.js";
4
4
  import { i as standardErrors } from "./errors-BoutSmiy.js";
5
- import { S as matchesScopes, x as isNamespacedScope } from "./tasks-DYdY-dBI.js";
5
+ import { S as matchesScopes, b as operationScopes, m as isPublicOperation, v as operationMatchesScopes, x as isNamespacedScope } from "./tasks-CD-B6_nv.js";
6
6
  import { r as ok, t as err } from "./result-CF4OzG9O.js";
7
7
  import { t as sha256Hex } from "./digest-C51F1bhA.js";
8
8
  import { Type } from "typebox";
9
9
  import { createRemoteJWKSet, jwtVerify } from "jose";
10
10
 
11
+ // src/roles.ts
12
+ /**
13
+ * A service's roles: what a person, or a key that stands for one, may do there, in the few words an
14
+ * administrator chooses among. A role names resources and what it may do with them; its scopes are derived
15
+ * from that, so nobody lists permissions by hand.
16
+ */
17
+ /** The most roles a service declares: few enough that each is explained in one sentence. */
18
+ const MAX_ROLES = 3;
19
+ /**
20
+ * Declares a service's roles for its application's `roles`. It returns them unchanged: what it adds is the
21
+ * type check that a role extends another declared role and never itself. `.build()` checks the rest
22
+ * against the application's operations.
23
+ */
24
+ function defineRoles(roles) {
25
+ return roles;
26
+ }
27
+ const ROLE_NAME = /^[a-z][a-z0-9-]{1,31}$/;
28
+ const ROLE_FIELDS = /* @__PURE__ */ new Set([
29
+ "description",
30
+ "extends",
31
+ "can",
32
+ "all"
33
+ ]);
34
+ /** Every scope a public operation takes: the ones that admit a call and the ones its handler checks. */
35
+ function publicScopes(operations) {
36
+ return new Set(Object.values(operations).filter(isPublicOperation).flatMap((operation) => [...operationScopes(operation), ...operation.conditionalScopes ?? []]));
37
+ }
38
+ /** The scopes a role names itself, without the ones it extends. */
39
+ function ownScopes(namespace, role) {
40
+ return Object.entries(role.can ?? {}).flatMap(([action, resources]) => resources.map((resource) => `${namespace}:${resource}:${action}`));
41
+ }
42
+ /**
43
+ * Each role of an application with every scope it holds; an application without roles has none. Call it on
44
+ * a built application: `.build()` has then checked the roles, and this only expands them.
45
+ */
46
+ function resolveRoles(application) {
47
+ const roles = application.roles ?? {};
48
+ const everything = publicScopes(application.operations);
49
+ const resolved = /* @__PURE__ */ new Map();
50
+ const scopesOf = (name, path) => {
51
+ const known = resolved.get(name);
52
+ if (known) return known;
53
+ const role = roles[name];
54
+ if (!role || path.includes(name)) throw new TypeError(`Role "${path[0] ?? name}": it extends a role that is not declared, or itself.`);
55
+ const scopes = role.all ? [...everything] : [...ownScopes(application.namespace, role), ...role.extends ? scopesOf(role.extends, [...path, name]) : []];
56
+ const sorted = [...new Set(scopes)].toSorted();
57
+ resolved.set(name, sorted);
58
+ return sorted;
59
+ };
60
+ return Object.fromEntries(Object.entries(roles).map(([name, role]) => [name, {
61
+ description: role.description,
62
+ permissions: scopesOf(name, [])
63
+ }]));
64
+ }
65
+ /**
66
+ * Refuses roles an application cannot have, with a TypeError that names the role: more than `MAX_ROLES`, a
67
+ * name that is not a word, an unknown field, a missing description, `all` beside `can` or `extends`, a role
68
+ * extending an undeclared one or itself, a scope no public operation takes, a role that holds nothing, and
69
+ * a public operation no role may call.
70
+ */
71
+ function checkRoles(application) {
72
+ const { roles } = application;
73
+ if (roles === void 0) return;
74
+ const names = Object.keys(roles);
75
+ if (names.length === 0 || names.length > 3) throw new TypeError(`An application declares between one and ${3} roles, or none at all.`);
76
+ const everything = publicScopes(application.operations);
77
+ for (const [name, role] of Object.entries(roles)) {
78
+ if (!ROLE_NAME.test(name)) throw new TypeError(`Role "${name}": a role's name is a lowercase kebab-case word of 2 to 32 characters.`);
79
+ const unknown = Object.keys(role).find((field) => !ROLE_FIELDS.has(field));
80
+ if (unknown) throw new TypeError(`Role "${name}": "${unknown}" is not a role field.`);
81
+ if (typeof role.description !== "string" || !role.description.trim()) throw new TypeError(`Role "${name}": a description says what the role is for.`);
82
+ if (role.all !== void 0 && (role.all !== true || role.can !== void 0 || role.extends !== void 0)) throw new TypeError(`Role "${name}": "all: true" stands alone, without "can" or "extends".`);
83
+ for (const scope of ownScopes(application.namespace, role)) if (!isNamespacedScope(scope, application.namespace) || !everything.has(scope)) throw new TypeError(`Role "${name}": no public operation takes the scope "${scope}".`);
84
+ }
85
+ const resolved = resolveRoles(application);
86
+ for (const [name, role] of Object.entries(resolved)) if (role.permissions.length === 0) throw new TypeError(`Role "${name}": it holds no scope.`);
87
+ const held = Object.values(resolved).map((role) => role.permissions);
88
+ for (const [operation, declared] of Object.entries(application.operations)) if (isPublicOperation(declared) && !held.some((permissions) => operationMatchesScopes(declared, permissions))) throw new TypeError(`Operation "${operation}": it is public and no role may call it.`);
89
+ }
90
+
11
91
  // src/schema-bundle.ts
12
92
  /**
13
93
  * Schema bundling: named schemas (`$id`) become shared components for an OpenAPI document, or are written
@@ -367,6 +447,7 @@ function checkAccessPolicy(policy, namespace) {
367
447
  if (oauth.length) throw new TypeError(`Cloudflare Access application tokens are not OAuth access tokens: remove ${oauth.map((option) => `tokens.${option}`).join(", ")}.`);
368
448
  if (claims !== void 0 && Object.entries(claims).some(([name, value]) => name !== "organization" && value !== void 0)) throw new TypeError("Under Cloudflare Access, tokens.claims names the organization alone: tokens.access grants the scopes.");
369
449
  if (access === void 0) return;
450
+ if (access.managedOAuth !== void 0 && typeof access.managedOAuth !== "boolean") throw new TypeError("tokens.access.managedOAuth is a boolean.");
370
451
  const { organizationId } = access;
371
452
  const claim = claims?.organization;
372
453
  if (!(claim === void 0 ? parseInput(OrganizationIdSchema, organizationId).ok : organizationId === void 0 && typeof claim === "string" && claim !== "")) throw new TypeError("Under Cloudflare Access, name a valid organization once: tokens.access.organizationId or tokens.claims.organization.");
@@ -701,4 +782,4 @@ function createTokenAuthorization(policy, given) {
701
782
  };
702
783
  }
703
784
 
704
- export { schemaIds as _, projectToken as a, tokenIssuer as c, projectAccessToken as d, usesCloudflareAccess as f, hasSchemaReferences as g, canonical as h, presentedToken as i, usesOwnBearer as l, bundleSchemas as m, createTokenAuthorization as n, tokenAudiences as o, PrincipalSchema as p, createTokenVerifier as r, tokenEndpoints as s, checkTokenAuthority as t, isCrossSiteWrite as u, standaloneSchema as v };
785
+ export { resolveRoles as S, schemaIds as _, projectToken as a, checkRoles as b, tokenIssuer as c, projectAccessToken as d, usesCloudflareAccess as f, hasSchemaReferences as g, canonical as h, presentedToken as i, usesOwnBearer as l, bundleSchemas as m, createTokenAuthorization as n, tokenAudiences as o, PrincipalSchema as p, createTokenVerifier as r, tokenEndpoints as s, checkTokenAuthority as t, isCrossSiteWrite as u, standaloneSchema as v, defineRoles as x, MAX_ROLES as y };