@arbol-ai/maximus 8.0.0 → 8.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 (57) hide show
  1. package/dist/analytics/analytics.d.ts +1 -1
  2. package/dist/analytics/analytics.js +2 -2
  3. package/dist/body.d.ts +1 -1
  4. package/dist/capture/index.d.ts +37 -0
  5. package/dist/capture/index.js +182 -0
  6. package/dist/chunks/{define-app-CfVZBt7D.js → define-app-BxGZdNmS.js} +20 -4
  7. package/dist/chunks/delay-BsKQP_lF.js +12 -0
  8. package/dist/chunks/digest-C7UGt760.js +13 -0
  9. package/dist/chunks/{errors-WfyKhiyk.js → errors-CWgE9uvM.js} +2 -2
  10. package/dist/chunks/execution-BTiAWA4n.js +264 -0
  11. package/dist/chunks/{handler-DWTGoduQ.js → handler-iebR-urt.js} +1 -0
  12. package/dist/chunks/{http-layout-_h7xwgPC.js → http-layout-BvlbD__1.js} +1 -1
  13. package/dist/chunks/{openapi-CV0KmJpS.js → openapi-BF3eCpux.js} +12 -21
  14. package/dist/chunks/{openapi-file-OjSs9mRv.js → openapi-file-RcXoq0AF.js} +1 -1
  15. package/dist/chunks/{pages-DyC0m8Zb.js → pages-BCksUeRf.js} +1 -1
  16. package/dist/chunks/{runtime-CVVf5hmp.js → runtime-D5eR9-Es.js} +38 -9
  17. package/dist/chunks/{schemas-p_aRcMC1.js → schemas-BOFxZP1c.js} +1 -1
  18. package/dist/chunks/{server-CCc7fil4.js → server-B9C8KPwa.js} +5 -4
  19. package/dist/chunks/{src--HZrH1U9.js → src-C-4z443M.js} +67 -16
  20. package/dist/chunks/{standard-failures-CLjxS2ea.js → standard-failures-Lh4mSfwG.js} +1 -1
  21. package/dist/chunks/{telemetry-C3LfZcOB.js → telemetry-BtxJh69Q.js} +4 -4
  22. package/dist/chunks/{types-BQYB4Ads.d.ts → types-Dqo3oGig.d.ts} +245 -34
  23. package/dist/chunks/{validation-fTohBT6R.js → validation-DMu0rkMQ.js} +266 -16
  24. package/dist/chunks/{workers-types-iONp32T4.d.ts → workers-types-BgjyDtGd.d.ts} +1 -1
  25. package/dist/diagnostics.d.ts +1 -1
  26. package/dist/diagnostics.js +1 -1
  27. package/dist/errors.d.ts +1 -1
  28. package/dist/errors.js +1 -1
  29. package/dist/http-paths.d.ts +1 -1
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.js +7 -7
  32. package/dist/internals.d.ts +2 -2
  33. package/dist/internals.js +5 -5
  34. package/dist/mcp/index.d.ts +1 -1
  35. package/dist/mcp/index.js +1 -1
  36. package/dist/project/config.d.ts +1 -1
  37. package/dist/project/config.js +1 -1
  38. package/dist/project/index.d.ts +2 -2
  39. package/dist/project/index.js +3 -3
  40. package/dist/schemas.d.ts +2 -2
  41. package/dist/schemas.js +3 -3
  42. package/dist/standard-failures.d.ts +1 -1
  43. package/dist/standard-failures.js +1 -1
  44. package/dist/tooling/cli.js +1 -1
  45. package/dist/vite/index.d.ts +3 -3
  46. package/dist/vite/index.js +12 -7
  47. package/dist/webhooks.d.ts +1 -1
  48. package/dist/workers/runtime.d.ts +1 -1
  49. package/dist/workers/runtime.js +1 -1
  50. package/package.json +5 -1
  51. package/skills/maximus/SKILL.md +7 -0
  52. package/skills/maximus/references/project.md +4 -0
  53. package/skills/maximus/references/routes-and-tools.md +2 -0
  54. package/templates/project/CLAUDE.md.template +3 -3
  55. package/templates/project/README.md.template +1 -0
  56. package/templates/project/tsconfig.json.template +1 -0
  57. package/dist/chunks/execution-CfZEx_JP.js +0 -84
@@ -1,4 +1,4 @@
1
- import { Sn as Observer } from "../chunks/types-BQYB4Ads.js";
1
+ import { Pn as Observer } from "../chunks/types-Dqo3oGig.js";
2
2
  import { Static } from "@sinclair/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: import("@sinclair/typebox").TObject<{
@@ -1,5 +1,5 @@
1
- import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-p_aRcMC1.js";
2
- import { a as telemetryEnabled } from "../chunks/telemetry-C3LfZcOB.js";
1
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-BOFxZP1c.js";
2
+ import { s as telemetryEnabled } from "../chunks/telemetry-BtxJh69Q.js";
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { Value } from "@sinclair/typebox/value";
5
5
 
package/dist/body.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as readBodyText, d as readJsonResponse, f as retryAfterSeconds, g as readBodyBytes, h as HttpBodyFailureReason, l as isJsonMediaType, m as HttpBodyFailure, p as BodyReadOptions, u as readJsonBody } from "./chunks/types-BQYB4Ads.js";
1
+ import { c as isJsonMediaType, d as retryAfterSeconds, f as BodyReadOptions, g as readBodyText, h as readBodyBytes, l as readJsonBody, m as HttpBodyFailureReason, p as HttpBodyFailure, u as readJsonResponse } from "./chunks/types-Dqo3oGig.js";
2
2
  export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -0,0 +1,37 @@
1
+ import { Cn as CaptureDimensions, Ht as RegisteredEnv, Sn as CaptureConfig, Tn as CaptureSink, it as withoutSecrets, or as CaptureRecord, sr as CaptureRecordSchema, wn as CaptureInvocation, xn as AnyContext } from "../chunks/types-Dqo3oGig.js";
2
+ /** What `pipeline()` takes. */
3
+ interface PipelineOptions<E> {
4
+ /**
5
+ * The name of the Pipelines binding. While the env has no such binding, capture records nothing and logs
6
+ * nothing, so a preview or a local run without the stream costs nothing.
7
+ */
8
+ binding: string;
9
+ /**
10
+ * Turns a record into the row the stream's schema expects: the stream gets the record itself without it. A
11
+ * structured stream drops a row its schema refuses, so a stream of another shape needs this. An answer of
12
+ * `null` or `undefined` sends nothing.
13
+ */
14
+ map?: (record: CaptureRecord, env: E) => unknown;
15
+ /**
16
+ * The name of an R2 binding for what the stream cannot take. A payload over 900 KB is written to
17
+ * `payloads/<organizationId>/<id>.json`, and the record carries `payloadRef` instead; a row the stream
18
+ * refused twice is written to `dlq/<service>/<yyyy-mm-dd>/<id>.json`, for a job to send again. Without it,
19
+ * both count as failed deliveries.
20
+ */
21
+ blobs?: string;
22
+ }
23
+ /**
24
+ * Sends each record to a Pipelines stream, the binding `env[binding]`. A send that fails is retried once after
25
+ * 200 ms, with the same record id, then written to the dead letter when `blobs` is set; the delivery still
26
+ * counts as failed, so the failure is logged. A stream is a durable buffer that accepts a repeated row, and a
27
+ * consumer deduplicates on the record's id. A sink for an append whose outcome may be lost should never retry.
28
+ */
29
+ export declare function pipeline<E>(options: PipelineOptions<E>): CaptureSink<E>;
30
+ /**
31
+ * Declares, as `capture.ts`'s default export, whether calls are captured (`enabled`), where the records go
32
+ * (`sink`), whether they carry each input and output (`payloads`) and what each call is about (`dimensions`).
33
+ * `C` names the context `dimensions` reads, `PreparedContext<typeof context>`, importing the type alone. Any other
34
+ * field throws a TypeError.
35
+ */
36
+ export declare function defineCapture<C = AnyContext>(capture: CaptureConfig<RegisteredEnv, C>): CaptureConfig<RegisteredEnv, C>;
37
+ export { type CaptureConfig, type CaptureDimensions, type CaptureInvocation, type CaptureRecord, CaptureRecordSchema, type CaptureSink, type PipelineOptions, withoutSecrets };
@@ -0,0 +1,182 @@
1
+ import { E as withoutSecrets } from "../chunks/validation-DMu0rkMQ.js";
2
+ import { t as isRecord } from "../chunks/record-DQUDTpEA.js";
3
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-BOFxZP1c.js";
4
+ import { t as sha256Hex } from "../chunks/digest-C7UGt760.js";
5
+ import { t as delay } from "../chunks/delay-BsKQP_lF.js";
6
+ import { Type } from "@sinclair/typebox";
7
+
8
+ // src/capture-record.ts
9
+ /**
10
+ * The capture record: what one operation call, or one refusal, becomes for the sink that keeps it. The fields
11
+ * an analytics event has keep its names, so live counters and a store of records agree.
12
+ */
13
+ /** A field a record leaves null when the call never reached what fills it. */
14
+ const nullable = (schema, description) => Type.Union([schema, Type.Null()], { description });
15
+ /**
16
+ * One complete record of a call: who called which operation over which transport, when and for how long, what
17
+ * it answered, and, under `payloads: 'all'`, its input and output without what their schemas mark
18
+ * `secret: true`. A refusal before the operation ran has `stage: 'admission'` and null wherever admission had
19
+ * not learned the value: a token is never read before it is verified.
20
+ */
21
+ const CaptureRecordSchema = Type.Object({
22
+ id: UuidSchema,
23
+ service: Type.String({ description: "The application's name." }),
24
+ operation: nullable(Type.String(), "The operation, or null when the refusal names none."),
25
+ organizationId: nullable(OrganizationIdSchema, "The verified caller's organization, never one a request names; null before verification."),
26
+ actorId: nullable(Type.String(), "The verified caller; null before verification."),
27
+ actorKind: nullable(Type.Union([Type.Literal("user"), Type.Literal("service")]), "The verified caller's kind; null before verification."),
28
+ requestId: UuidSchema,
29
+ traceId: nullable(Type.String({ pattern: "^[0-9a-f]{32}$" }), "The active trace id `telemetry.traceId` returns; never generated, never read from a header."),
30
+ surface: Type.Union([
31
+ Type.Literal("http"),
32
+ Type.Literal("mcp"),
33
+ Type.Literal("rpc")
34
+ ], { description: "The transport that admitted the call." }),
35
+ occurredAt: Type.Integer({
36
+ minimum: 0,
37
+ description: "When the call finished, in Unix milliseconds."
38
+ }),
39
+ durationMicros: Type.Integer({
40
+ minimum: 0,
41
+ description: "How long execution took, or admission for a refusal, in whole microseconds."
42
+ }),
43
+ outcome: Type.Union([Type.Literal("success"), Type.Literal("failure")], { description: "`success` when the caller received the output, `failure` when it received a failure." }),
44
+ errorCode: nullable(Type.String(), "The code of the failure the caller received; null on success."),
45
+ stage: Type.Union([Type.Literal("execution"), Type.Literal("admission")], { description: "`admission` for a refusal before the shared execution path, `execution` from there on." }),
46
+ version: Type.String({ description: "The application's version." }),
47
+ effect: nullable(Type.Union([
48
+ Type.Literal("read"),
49
+ Type.Literal("write"),
50
+ Type.Literal("delete")
51
+ ]), "The operation's declared effect."),
52
+ scopes: Type.Array(Type.String(), { description: "The scopes the operation declares." }),
53
+ visibility: nullable(Type.Union([Type.Literal("public"), Type.Literal("internal")]), "The operation's visibility."),
54
+ httpMethod: nullable(Type.String(), "The route's method, on HTTP."),
55
+ httpPath: nullable(Type.String(), "The route's path template, never the requested path, on HTTP."),
56
+ mcpTool: nullable(Type.String(), "The operation's tool name, on MCP."),
57
+ rpcCaller: nullable(Type.String(), "Over RPC, the `caller` of the Service Binding, as admission checked it or, when it refused the binding, as it claimed."),
58
+ clientId: nullable(Type.String(), "The OAuth client the verified token was issued to."),
59
+ clientClass: nullable(Type.Union([
60
+ Type.Literal("human"),
61
+ Type.Literal("machine"),
62
+ Type.Literal("dcr")
63
+ ]), "That client's class."),
64
+ grantedScopes: nullable(Type.Array(Type.String()), "The scopes the verified token grants."),
65
+ userAgent: nullable(Type.String({ maxLength: 200 }), "On HTTP and MCP, the request's `user-agent`, cut to 200 characters. What the caller claims."),
66
+ tokenSha256: nullable(Type.String({ pattern: "^[0-9a-f]{64}$" }), "The hex SHA-256 of the verified token: it joins the calls of one session, and the token never travels."),
67
+ dimensions: Type.Record(Type.String(), Type.String(), { description: "What the `dimensions` callback named for this call." }),
68
+ startedAt: Type.Integer({
69
+ minimum: 0,
70
+ description: "When the transport began admitting the call, in Unix milliseconds."
71
+ }),
72
+ admissionMicros: Type.Integer({
73
+ minimum: 0,
74
+ description: "How long admission took, in whole microseconds."
75
+ }),
76
+ input: Type.Unknown({ description: "Under `payloads: all`, the decoded input without its secrets; null for a refused input or `payloads: none`. An input whose schema has both codecs and secrets is the value its schema checked, before the codecs ran." }),
77
+ output: Type.Unknown({ description: "Under `payloads: all`, the checked output without its secrets, as the caller received it; for an attachment, its `contentType`, `filename` and `byteLength`, never its bytes. Null otherwise." }),
78
+ failureData: Type.Unknown({ description: "Under `payloads: all`, the failure's data without its secrets: `issues` for `INVALID_INPUT`, never the refused values. Null otherwise." }),
79
+ payloadRef: nullable(Type.Object({
80
+ $ref: Type.String({ description: "The key the payload was written to." }),
81
+ bytes: Type.Integer({
82
+ minimum: 0,
83
+ description: "The size of the payload written, in bytes."
84
+ }),
85
+ sha256: Type.String({
86
+ pattern: "^[0-9a-f]{64}$",
87
+ description: "The payload's hex SHA-256."
88
+ })
89
+ }, { additionalProperties: false }), "Where a sink wrote `input`, `output` and `failureData` when they were too large to send, as JSON; they are then null.")
90
+ }, { additionalProperties: false });
91
+
92
+ // src/capture/pipeline.ts
93
+ /** The largest `input`, `output` and `failureData` one record carries together, in bytes. */
94
+ const MAX_PAYLOAD_BYTES = 9e5;
95
+ /** How long the one retry waits. A stream that refuses a send usually recovers within a moment. */
96
+ const RETRY_DELAY_MILLISECONDS = 200;
97
+ /** A binding of the env, by name. */
98
+ function bindingOf(env, name) {
99
+ return isRecord(env) ? env[name] : void 0;
100
+ }
101
+ /** The record, with a payload over the limit written to the bucket: it fails when there is no bucket. */
102
+ async function withinLimit(record, bucket) {
103
+ const { input, output, failureData } = record;
104
+ const payload = new TextEncoder().encode(JSON.stringify({
105
+ input,
106
+ output,
107
+ failureData
108
+ }));
109
+ if (payload.byteLength <= MAX_PAYLOAD_BYTES) return record;
110
+ if (!bucket) throw new RangeError("A capture payload over the limit needs a blobs binding.");
111
+ const key = `payloads/${record.organizationId ?? "platform"}/${record.id}.json`;
112
+ await bucket.put(key, payload, { httpMetadata: { contentType: "application/json" } });
113
+ return {
114
+ ...record,
115
+ input: null,
116
+ output: null,
117
+ failureData: null,
118
+ payloadRef: {
119
+ $ref: key,
120
+ bytes: payload.byteLength,
121
+ sha256: await sha256Hex(payload)
122
+ }
123
+ };
124
+ }
125
+ /** Keeps a row the stream refused twice, for a job to send again. The record's id names it, so a replay finds one. */
126
+ async function deadLetter(record, row, bucket) {
127
+ const day = new Date(record.occurredAt).toISOString().slice(0, 10);
128
+ await bucket.put(`dlq/${record.service}/${day}/${record.id}.json`, JSON.stringify(row), { httpMetadata: { contentType: "application/json" } });
129
+ }
130
+ /**
131
+ * Sends each record to a Pipelines stream, the binding `env[binding]`. A send that fails is retried once after
132
+ * 200 ms, with the same record id, then written to the dead letter when `blobs` is set; the delivery still
133
+ * counts as failed, so the failure is logged. A stream is a durable buffer that accepts a repeated row, and a
134
+ * consumer deduplicates on the record's id. A sink for an append whose outcome may be lost should never retry.
135
+ */
136
+ function pipeline(options) {
137
+ const { binding, blobs, map } = options;
138
+ if (typeof binding !== "string" || !binding) throw new TypeError("pipeline() takes the name of a Pipelines binding.");
139
+ return {
140
+ available: (env) => typeof bindingOf(env, binding)?.send === "function",
141
+ async send(record, env) {
142
+ const stream = bindingOf(env, binding);
143
+ const bucket = blobs === void 0 ? void 0 : bindingOf(env, blobs);
144
+ const carried = await withinLimit(record, bucket);
145
+ const row = map ? await map(carried, env) : carried;
146
+ if (row === null || row === void 0) return;
147
+ try {
148
+ await stream.send([row]);
149
+ } catch {
150
+ await delay(RETRY_DELAY_MILLISECONDS);
151
+ try {
152
+ await stream.send([row]);
153
+ } catch (error) {
154
+ if (bucket) await deadLetter(carried, row, bucket);
155
+ throw error;
156
+ }
157
+ }
158
+ }
159
+ };
160
+ }
161
+
162
+ // src/capture/index.ts
163
+ /** The fields `capture.ts` states. */
164
+ const CAPTURE_FIELDS = /* @__PURE__ */ new Set([
165
+ "enabled",
166
+ "sink",
167
+ "payloads",
168
+ "dimensions"
169
+ ]);
170
+ /**
171
+ * Declares, as `capture.ts`'s default export, whether calls are captured (`enabled`), where the records go
172
+ * (`sink`), whether they carry each input and output (`payloads`) and what each call is about (`dimensions`).
173
+ * `C` names the context `dimensions` reads, `PreparedContext<typeof context>`, importing the type alone. Any other
174
+ * field throws a TypeError.
175
+ */
176
+ function defineCapture(capture) {
177
+ const unknown = Object.keys(capture).filter((field) => !CAPTURE_FIELDS.has(field));
178
+ if (unknown.length) throw new TypeError(`capture.ts states only enabled, sink, payloads and dimensions: remove ${unknown.join(", ")}.`);
179
+ return Object.freeze(capture);
180
+ }
181
+
182
+ export { CaptureRecordSchema, defineCapture, pipeline, withoutSecrets };
@@ -1,9 +1,9 @@
1
- import { u as hasUncompiledCodecs } from "./validation-fTohBT6R.js";
2
- import { i as standardErrors } from "./errors-WfyKhiyk.js";
1
+ import { d as hasUncompiledCodecs } from "./validation-DMu0rkMQ.js";
2
+ import { i as standardErrors } from "./errors-CWgE9uvM.js";
3
3
  import { n as readBodyBytes } from "./body-DOIHwIIl.js";
4
4
  import { a as operationPathParameters, r as isInputHeaderName, t as createHttpRouteResolver } from "./http-paths-DMBxwpp6.js";
5
5
  import { i as pathParameterSchemas } from "./result-CKgZHrnj.js";
6
- import { C as MAX_BODY_BYTES_CEILING, M as isNamespacedScope, f as hasSchemaReferences, j as operationScopes, r as checkTokenAuthority, s as tokenAudiences, t as createOpenApi, w as STANDARD_CODES } from "./openapi-CV0KmJpS.js";
6
+ import { C as MAX_BODY_BYTES_CEILING, M as isNamespacedScope, c as tokenAudiences, f as hasSchemaReferences, j as operationScopes, r as checkTokenAuthority, t as createOpenApi, w as STANDARD_CODES } from "./openapi-BF3eCpux.js";
7
7
  import { Kind } from "@sinclair/typebox";
8
8
 
9
9
  // src/internal/exact-length.ts
@@ -101,7 +101,7 @@ function validAttachment(value, maxBytes) {
101
101
  */
102
102
  function attachmentResponse(file, status = 200) {
103
103
  const encodedFilename = encodeURIComponent(file.filename).replaceAll(/[!'()*]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
104
- const body = file.body instanceof Uint8Array ? file.body : exactLength(file.body, file.byteLength);
104
+ const body = file.body instanceof Uint8Array ? file.body : attachmentStream(file.body, file.byteLength);
105
105
  return new Response(body, {
106
106
  status,
107
107
  headers: {
@@ -114,6 +114,11 @@ function attachmentResponse(file, status = 200) {
114
114
  }
115
115
  });
116
116
  }
117
+ /** Workers determines Content-Length from the body, ignoring a header on an ordinary stream. */
118
+ function attachmentStream(body, byteLength) {
119
+ const bounded = exactLength(body, byteLength);
120
+ return typeof FixedLengthStream === "function" ? bounded.pipeThrough(new FixedLengthStream(byteLength)) : bounded;
121
+ }
117
122
 
118
123
  // src/define-app.ts
119
124
  /** Names a Worker entrypoint already uses, or that would break a class or a promise. */
@@ -185,6 +190,7 @@ function checkApplication(manifest) {
185
190
  if (!validBodyLimit(manifest.maxOutputBytes)) throw new TypeError("The application output limit is a positive integer up to 16 MiB.");
186
191
  if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
187
192
  checkTelemetry(manifest.telemetry);
193
+ checkCapture(manifest.capture);
188
194
  checkTokenAuthority(manifest.tokens, manifest.namespace);
189
195
  tokenAudiences(manifest.tokens);
190
196
  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.");
@@ -212,6 +218,16 @@ function checkTelemetry(telemetry) {
212
218
  if (telemetry === void 0) return;
213
219
  if (typeof telemetry !== "object" || telemetry === null || telemetry.enabled !== void 0 && typeof telemetry.enabled !== "boolean" && typeof telemetry.enabled !== "function" || telemetry.observers !== void 0 && (!Array.isArray(telemetry.observers) || !telemetry.observers.every(isObserver)) || telemetry.traceId !== void 0 && typeof telemetry.traceId !== "function") throw new TypeError("Telemetry takes enabled as true, false or a function of env, observers as a list of objects whose execution, admission and error are functions, and traceId as a function.");
214
220
  }
221
+ /**
222
+ * The capture option, as code untyped by TypeScript may give it: a switch that is a boolean or a function, a
223
+ * sink that can send, `payloads` of `all` or `none`, and a `dimensions` callback that is a function. A sink
224
+ * that cannot send would lose every record it is handed, and a `payloads` such as `'al'` would silently send
225
+ * metadata alone.
226
+ */
227
+ function checkCapture(capture) {
228
+ if (capture === void 0) return;
229
+ 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.");
230
+ }
215
231
  /** An operation's `failures` name domain codes of the catalog, each once. */
216
232
  function checkDeclaredFailures(operations, errors) {
217
233
  const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
@@ -0,0 +1,12 @@
1
+ // src/internal/delay.ts
2
+ /**
3
+ * A wait on the runtime's global timer, for code the core reaches: it may load where `node:timers` does not.
4
+ */
5
+ /** Resolves after `milliseconds`. */
6
+ function delay(milliseconds) {
7
+ return new Promise((resolve) => {
8
+ setTimeout(resolve, milliseconds);
9
+ });
10
+ }
11
+
12
+ export { delay as t };
@@ -0,0 +1,13 @@
1
+ // src/internal/digest.ts
2
+ /**
3
+ * SHA-256 digests in hexadecimal, for rate limit keys, the development token's comparison and skill
4
+ * manifests.
5
+ */
6
+ /** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
7
+ async function sha256Hex(value) {
8
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
9
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
10
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
11
+ }
12
+
13
+ export { sha256Hex as t };
@@ -1,5 +1,5 @@
1
- import { t as STANDARD_FAILURES } from "./standard-failures-CLjxS2ea.js";
2
- import { i as parseSchema } from "./validation-fTohBT6R.js";
1
+ import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
2
+ import { a as parseSchema } from "./validation-DMu0rkMQ.js";
3
3
  import { Type } from "@sinclair/typebox";
4
4
  import { Value } from "@sinclair/typebox/value";
5
5
 
@@ -0,0 +1,264 @@
1
+ import { E as withoutSecrets, t as admitInput, w as holdsSecrets } from "./validation-DMu0rkMQ.js";
2
+ import { i as standardErrors } from "./errors-CWgE9uvM.js";
3
+ import { a as isAttachmentSchema, o as validAttachment } from "./define-app-BxGZdNmS.js";
4
+ import { t as err } from "./result-CKgZHrnj.js";
5
+ import { A as operationOutputLimit, b as ADMISSION_CODES, j as operationScopes, k as operationMatchesScopes, w as STANDARD_CODES, x as BODY_CODES } from "./openapi-BF3eCpux.js";
6
+ import { t as sha256Hex } from "./digest-C7UGt760.js";
7
+ import { t as delay } from "./delay-BsKQP_lF.js";
8
+ import { o as reportUnexpected, r as elapsedMicros, s as telemetryEnabled, t as activeTraceId } from "./telemetry-BtxJh69Q.js";
9
+ import { Value } from "@sinclair/typebox/value";
10
+
11
+ // src/capture.ts
12
+ /** The most entries a `dimensions` callback's answer keeps. */
13
+ const MAX_DIMENSIONS = 32;
14
+ /** The longest value of one entry a `dimensions` callback's answer keeps. */
15
+ const MAX_DIMENSION_LENGTH = 256;
16
+ /** Writes one line of capture's own diagnostics; they are best effort. */
17
+ function logCapture(line) {
18
+ try {
19
+ console.error(JSON.stringify(line));
20
+ } catch {}
21
+ }
22
+ /** Whether capture is on for this env: a switch that throws turns it off and says so. */
23
+ function captureEnabled(capture, env) {
24
+ if (typeof capture.enabled !== "function") return capture.enabled !== false;
25
+ try {
26
+ return capture.enabled(env);
27
+ } catch {
28
+ logCapture({ event: "maximus.capture.switch_failed" });
29
+ return false;
30
+ }
31
+ }
32
+ /** A UUIDv7 at this instant: its leading bits are the time, so ids sort by when their records happened. */
33
+ function timeOrderedId(instant) {
34
+ const time = instant.toString(16).padStart(12, "0");
35
+ const random = crypto.randomUUID().replaceAll("-", "");
36
+ return `${time.slice(0, 8)}-${time.slice(8)}-7${random.slice(13, 16)}-${random.slice(16, 20)}-${random.slice(20)}`;
37
+ }
38
+ /**
39
+ * The input a record carries. An input whose schema marks nothing is the decoded one, as plain JSON. One whose
40
+ * schema marks a field is what the schema checked, without that field: a codec may move a value to where no
41
+ * mark reaches, so only the checked value is known to have the shape the marks describe. Decoded values a
42
+ * record cannot carry, such as a `BigInt`, fall back to the checked one, which is plain JSON by admission. Read
43
+ * after the call: a handler that changes its input in place changes the record, and in a strict object nothing
44
+ * it adds to a marked schema's input can reach it.
45
+ */
46
+ function recordedInput(schema, admitted) {
47
+ if (!admitted) return null;
48
+ if (holdsSecrets(schema)) return withoutSecrets(schema, admitted.checked) ?? null;
49
+ if (admitted.decoded === admitted.checked) return admitted.checked;
50
+ try {
51
+ return JSON.parse(JSON.stringify(admitted.decoded));
52
+ } catch {
53
+ return admitted.checked;
54
+ }
55
+ }
56
+ /** The output a record carries: never an attachment's bytes, and never what its schema marks. */
57
+ function recordedOutput(schema, value) {
58
+ if (isAttachmentSchema(schema)) {
59
+ const { contentType, filename, byteLength } = value;
60
+ return {
61
+ contentType,
62
+ filename,
63
+ byteLength
64
+ };
65
+ }
66
+ return holdsSecrets(schema) ? withoutSecrets(schema, value) ?? null : value;
67
+ }
68
+ /** The failure's data a record carries, without what its code's schema marks. */
69
+ function recordedFailureData(errors, failure) {
70
+ const schema = Object.values(errors.definitions).find(({ code }) => code === failure.code)?.dataSchema;
71
+ return schema && holdsSecrets(schema) ? withoutSecrets(schema, failure.data) ?? null : failure.data ?? null;
72
+ }
73
+ /** What the `dimensions` callback names for this call: bounded identifiers, or nothing when it throws. */
74
+ function recordedDimensions(application, env, captured) {
75
+ const dimensions = application.capture?.dimensions;
76
+ if (!dimensions) return {};
77
+ try {
78
+ const { operation, surface, principal, verified, call } = captured;
79
+ const named = dimensions({
80
+ env,
81
+ operation,
82
+ surface,
83
+ principal,
84
+ ...verified?.client ? { authority: {
85
+ surface,
86
+ scopes: verified.scopes,
87
+ client: verified.client
88
+ } } : {},
89
+ ...call?.rpcCaller ? { rpcCaller: call.rpcCaller } : {},
90
+ ...call?.userAgent ? { userAgent: call.userAgent } : {},
91
+ context: call?.context ?? {},
92
+ ...call?.admitted ? { input: call.admitted.decoded } : {}
93
+ });
94
+ return Object.fromEntries(Object.entries(named).filter((entry) => typeof entry[1] === "string" && entry[1] !== "").slice(0, MAX_DIMENSIONS).map(([name, value]) => [name, value.slice(0, MAX_DIMENSION_LENGTH)]));
95
+ } catch {
96
+ logCapture({
97
+ event: "maximus.capture.dimensions_failed",
98
+ requestId: captured.requestId
99
+ });
100
+ return {};
101
+ }
102
+ }
103
+ /** The record of one call, as background work. */
104
+ async function buildRecord(application, capture, env, captured, moment) {
105
+ const { operation, surface, principal, verified, result, call } = captured;
106
+ const declared = operation !== null && Object.hasOwn(application.operations, operation) ? application.operations[operation] : void 0;
107
+ const http = surface === "http" ? declared?.http : void 0;
108
+ const payloads = capture.payloads === "all";
109
+ return {
110
+ id: timeOrderedId(moment.occurredAt),
111
+ service: application.name,
112
+ operation,
113
+ organizationId: principal?.organizationId ?? null,
114
+ actorId: principal?.actorId ?? null,
115
+ actorKind: principal?.actorKind ?? null,
116
+ requestId: captured.requestId,
117
+ traceId: moment.traceId,
118
+ surface,
119
+ occurredAt: moment.occurredAt,
120
+ durationMicros: moment.durationMicros,
121
+ outcome: result.ok ? "success" : "failure",
122
+ errorCode: result.ok ? null : result.error.code,
123
+ stage: captured.executionStarted === void 0 ? "admission" : "execution",
124
+ version: application.version,
125
+ effect: declared?.effect ?? null,
126
+ scopes: declared ? [...operationScopes(declared)] : [],
127
+ visibility: declared ? declared.visibility ?? "public" : null,
128
+ httpMethod: http?.method ?? null,
129
+ httpPath: http?.path ?? null,
130
+ mcpTool: surface === "mcp" ? declared?.mcp?.name ?? null : null,
131
+ rpcCaller: call?.rpcCaller ?? null,
132
+ clientId: verified?.client?.id ?? null,
133
+ clientClass: verified?.client?.class ?? null,
134
+ grantedScopes: verified ? [...verified.scopes] : null,
135
+ userAgent: call?.userAgent ?? null,
136
+ tokenSha256: verified?.token ? await sha256Hex(verified.token) : null,
137
+ dimensions: recordedDimensions(application, env, captured),
138
+ startedAt: moment.startedAt,
139
+ admissionMicros: moment.admissionMicros,
140
+ input: payloads && declared ? recordedInput(declared.input, call?.admitted) : null,
141
+ output: payloads && declared && result.ok ? recordedOutput(declared.output, result.value) : null,
142
+ failureData: payloads && !result.ok ? recordedFailureData(application.errors, result.error) : null,
143
+ payloadRef: null
144
+ };
145
+ }
146
+ /**
147
+ * Captures one call beside `recordExecution` or `recordAdmission`, as background work: it never throws, never
148
+ * delays or changes the response and never affects an observer. A failed delivery logs
149
+ * `maximus.capture.delivery_failed` with the request id alone. Nothing is recorded without a background context,
150
+ * or while capture is off, whether telemetry is on or not.
151
+ */
152
+ function recordCapture(application, env, background, captured) {
153
+ const { capture } = application;
154
+ if (!(capture && background)) return;
155
+ try {
156
+ if (!captureEnabled(capture, env) || capture.sink.available?.(env) === false) return;
157
+ const occurredAt = Date.now();
158
+ const admissionMicros = elapsedMicros(captured.requestStarted, captured.executionStarted);
159
+ const executionMicros = captured.executionStarted === void 0 ? 0 : elapsedMicros(captured.executionStarted);
160
+ const moment = {
161
+ occurredAt,
162
+ startedAt: Math.max(0, Math.round(occurredAt - (admissionMicros + executionMicros) / 1e3)),
163
+ durationMicros: captured.executionStarted === void 0 ? admissionMicros : executionMicros,
164
+ admissionMicros,
165
+ traceId: activeTraceId(application.telemetry)
166
+ };
167
+ background.waitUntil(delay(0).then(() => buildRecord(application, capture, env, captured, moment)).then((record) => capture.sink.send(record, env)).catch(() => {
168
+ logCapture({
169
+ event: "maximus.capture.delivery_failed",
170
+ requestId: captured.requestId
171
+ });
172
+ }));
173
+ } catch {
174
+ logCapture({
175
+ event: "maximus.capture.delivery_failed",
176
+ requestId: captured.requestId
177
+ });
178
+ }
179
+ }
180
+
181
+ // src/execution.ts
182
+ /**
183
+ * The one execution path every transport calls: the caller's eligibility, input decoding, context
184
+ * preparation, middleware, the handler, and the checks on what it returns.
185
+ */
186
+ /**
187
+ * The execution path every transport shares: checks that the caller may run the operation (its scopes when
188
+ * `authority` is given, its actor kind, and `authority` itself when the operation has conditional scopes),
189
+ * decodes the input, prepares the context, runs the middleware and the handler, then checks the result
190
+ * against the catalog, the declared failures, the output schema and the output limit. A refused caller
191
+ * answers `FORBIDDEN` and a refused input `INVALID_INPUT`. An unexpected error becomes `INTERNAL_ERROR`,
192
+ * reported while telemetry is on, and is never thrown. `call` hands the admitted input and the prepared context
193
+ * to the recording points, which only the Result would otherwise reach.
194
+ */
195
+ async function executeOperation(manifest, operation, env, principal, input, authority, background, body, call) {
196
+ if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
197
+ try {
198
+ const admitted = admitInput(operation.input, input);
199
+ if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
200
+ if (call) call.admitted = {
201
+ checked: admitted.checked,
202
+ decoded: admitted.value
203
+ };
204
+ const trustedAuthority = authority ? Object.freeze({
205
+ surface: authority.surface,
206
+ scopes: Object.freeze([...authority.scopes]),
207
+ client: Object.freeze({ ...authority.client }),
208
+ ...authority.token ? { token: authority.token } : {}
209
+ }) : void 0;
210
+ const invocation = {
211
+ env,
212
+ principal,
213
+ input: admitted.value,
214
+ ...body ? { body } : {},
215
+ ...background ? { background } : {},
216
+ ...trustedAuthority ? { authority: trustedAuthority } : {},
217
+ ...call?.rpcCaller ? { rpcCaller: call.rpcCaller } : {},
218
+ ...call?.userAgent ? { userAgent: call.userAgent } : {}
219
+ };
220
+ /**
221
+ * A failure the call answers, from its context, middleware or handler: one of the catalog and, when the
222
+ * operation declares its failures, a declared or standard one. A failure only admission answers, or a
223
+ * body's for an operation that reads no byte body, is never the operation's. Any other is the server's
224
+ * error.
225
+ */
226
+ const declared = (answered) => {
227
+ const failure = manifest.errors.validate(answered);
228
+ if (ADMISSION_CODES.has(failure.code) || BODY_CODES.has(failure.code) && operation.http?.body !== "bytes") throw new TypeError(`Failure ${failure.code} is answered before an operation runs, never by it`);
229
+ if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
230
+ return failure;
231
+ };
232
+ const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
233
+ if (!context.ok) return err(declared(context.error));
234
+ if (call) call.context = context.value;
235
+ const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
236
+ let latest = -1;
237
+ /**
238
+ * Runs the middleware at `index`, whose `next` runs the following one, until the handler; each `next`
239
+ * runs once.
240
+ */
241
+ const dispatch = async (index) => {
242
+ if (index <= latest) throw new Error("Middleware next() may be called only once.");
243
+ latest = index;
244
+ const middleware = chain[index];
245
+ return await (middleware ? middleware(context.value, () => dispatch(index + 1)) : operation.execute(context.value, admitted.value));
246
+ };
247
+ const result = await dispatch(0);
248
+ if (!result || typeof result.ok !== "boolean" || !Object.hasOwn(result, "ok") || Object.keys(result).length !== 2 || !Object.hasOwn(result, result.ok ? "value" : "error")) throw new TypeError("Invalid operation result");
249
+ if (!result.ok) return err(declared(result.error));
250
+ const maxOutputBytes = operationOutputLimit(manifest, operation);
251
+ if (isAttachmentSchema(operation.output)) {
252
+ if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
253
+ return result;
254
+ }
255
+ if (!Value.Check(operation.output, result.value)) throw new TypeError("Invalid operation output");
256
+ if (new TextEncoder().encode(JSON.stringify(result.value)).byteLength > maxOutputBytes) throw new TypeError("Operation output exceeds its limit");
257
+ return result;
258
+ } catch (error) {
259
+ if (telemetryEnabled(manifest.telemetry, env)) reportUnexpected(error, "operation", principal.requestId);
260
+ return err(standardErrors.internal.create());
261
+ }
262
+ }
263
+
264
+ export { recordCapture as n, executeOperation as t };
@@ -103,6 +103,7 @@ function isContextDeclaration(value) {
103
103
  /** The fields `auth.ts` states: code. The issuer, audience, scheme and every other field are configuration. */
104
104
  const AUTH_FIELDS = /* @__PURE__ */ new Set([
105
105
  "resolve",
106
+ "challenge",
106
107
  "resourceMetadataUrl",
107
108
  "resources"
108
109
  ]);
@@ -1,4 +1,4 @@
1
- import { l as usesOwnBearer, v as usesCloudflareAccess } from "./openapi-CV0KmJpS.js";
1
+ import { u as usesOwnBearer, v as usesCloudflareAccess } from "./openapi-BF3eCpux.js";
2
2
 
3
3
  // src/internal/http-layout.ts
4
4
  /**