@arbol-ai/maximus 7.2.1 → 7.2.3

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 (35) 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 +40 -0
  5. package/dist/capture/index.js +182 -0
  6. package/dist/chunks/delay-B9YcAv-2.js +25 -0
  7. package/dist/chunks/{record-D2H3cg8S.js → exact-length-CNFWdMzi.js} +1 -11
  8. package/dist/chunks/{execution-C-ZHm0Ya.js → execution-DxGsKvjA.js} +201 -21
  9. package/dist/chunks/{schemas-q-51wBMQ.js → schemas-CldDAUy1.js} +1 -1
  10. package/dist/chunks/{src-D-JmAzlF.js → src-Ct4fEN4z.js} +58 -13
  11. package/dist/chunks/{telemetry-DvZgrzZn.js → telemetry-Bcq3GquK.js} +4 -4
  12. package/dist/chunks/{types-B1C3Ogo5.d.ts → types-D_QnYxPM.d.ts} +247 -30
  13. package/dist/chunks/{validation-DWxKk1Js.js → validation-B8XH1b_o.js} +276 -14
  14. package/dist/client/client.d.ts +1 -1
  15. package/dist/client/client.js +2 -1
  16. package/dist/diagnostics.d.ts +1 -1
  17. package/dist/diagnostics.js +1 -1
  18. package/dist/errors.d.ts +1 -1
  19. package/dist/errors.js +1 -1
  20. package/dist/http-paths.d.ts +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +5 -5
  23. package/dist/internals.d.ts +2 -2
  24. package/dist/internals.js +3 -3
  25. package/dist/mcp/index.d.ts +1 -1
  26. package/dist/mcp/index.js +22 -12
  27. package/dist/schemas.d.ts +2 -2
  28. package/dist/schemas.js +3 -3
  29. package/dist/webhooks.d.ts +1 -1
  30. package/dist/workers/runtime.d.ts +1 -1
  31. package/dist/workers/runtime.js +36 -7
  32. package/package.json +5 -1
  33. package/skills/maximus/SKILL.md +5 -0
  34. package/skills/maximus/references/adding-an-operation.md +2 -0
  35. package/skills/maximus/references/building-a-service.md +1 -1
@@ -1,4 +1,4 @@
1
- import { bn as Result, kn as Failure, qt as Observer } from "../chunks/types-B1C3Ogo5.js";
1
+ import { Mn as Result, Vn as Failure, in as Observer } from "../chunks/types-D_QnYxPM.js";
2
2
  import { Static } from "@sinclair/typebox";
3
3
  //#region src/analytics/analytics.d.ts
4
4
  /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
@@ -1,5 +1,5 @@
1
- import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-q-51wBMQ.js";
2
- import { a as telemetryEnabled } from "../chunks/telemetry-DvZgrzZn.js";
1
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-CldDAUy1.js";
2
+ import { s as telemetryEnabled } from "../chunks/telemetry-Bcq3GquK.js";
3
3
  import { Type } from "@sinclair/typebox";
4
4
 
5
5
  //#region src/analytics/analytics.ts
package/dist/body.d.ts CHANGED
@@ -1,2 +1,2 @@
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-B1C3Ogo5.js";
1
+ import { c as readJsonBody, d as BodyReadOptions, f as HttpBodyFailure, h as readBodyText, l as readJsonResponse, m as readBodyBytes, p as HttpBodyFailureReason, s as isJsonMediaType, u as retryAfterSeconds } from "./chunks/types-D_QnYxPM.js";
2
2
  export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -0,0 +1,40 @@
1
+ import { Gt as AnyContext, Jt as CaptureInvocation, Kt as CaptureConfig, On as CaptureRecord, Yt as CaptureSink, kn as CaptureRecordSchema, qt as CaptureDimensions, tt as withoutSecrets } from "../chunks/types-D_QnYxPM.js";
2
+ //#region src/capture/pipeline.d.ts
3
+ /** What `pipeline()` takes. */
4
+ interface PipelineOptions<E> {
5
+ /**
6
+ * The name of the Pipelines binding. While the env has no such binding, capture records nothing and logs
7
+ * nothing, so a preview or a local run without the stream costs nothing.
8
+ */
9
+ binding: string;
10
+ /**
11
+ * Turns a record into the row the stream's schema expects: the stream gets the record itself without it. A
12
+ * structured stream drops a row its schema refuses, so a stream of another shape needs this. An answer of
13
+ * `null` or `undefined` sends nothing.
14
+ */
15
+ map?: (record: CaptureRecord, env: E) => unknown;
16
+ /**
17
+ * The name of an R2 binding for what the stream cannot take. A payload over 900 KB is written to
18
+ * `payloads/<organizationId>/<id>.json`, and the record carries `payloadRef` instead; a row the stream
19
+ * refused twice is written to `dlq/<service>/<yyyy-mm-dd>/<id>.json`, for a job to send again. Without it,
20
+ * both count as failed deliveries.
21
+ */
22
+ blobs?: string;
23
+ }
24
+ /**
25
+ * Sends each record to a Pipelines stream, the binding `env[binding]`. A send that fails is retried once after
26
+ * 200 ms, with the same record id, then written to the dead letter when `blobs` is set; the delivery still
27
+ * counts as failed, so the failure is logged. A stream is a durable buffer that accepts a repeated row, and a
28
+ * consumer deduplicates on the record's id. A sink for an append whose outcome may be lost should never retry.
29
+ */
30
+ export declare function pipeline<E>(options: PipelineOptions<E>): CaptureSink<E>;
31
+ //#endregion
32
+ //#region src/capture/index.d.ts
33
+ /**
34
+ * Declares what `maximus<Env>({ …, capture })` takes: whether calls are captured (`enabled`), where the records
35
+ * go (`sink`), whether they carry each input and output (`payloads`) and what each call is about (`dimensions`).
36
+ * `E` names the bindings and `C` the context `dimensions` reads. Any other field throws a TypeError.
37
+ */
38
+ export declare function defineCapture<E = unknown, C = AnyContext>(capture: CaptureConfig<E, C>): CaptureConfig<E, C>;
39
+ //#endregion
40
+ export { type CaptureConfig, type CaptureDimensions, type CaptureInvocation, type CaptureRecord, CaptureRecordSchema, type CaptureSink, type PipelineOptions, withoutSecrets };
@@ -0,0 +1,182 @@
1
+ import { T as isRecord, w as withoutSecrets } from "../chunks/validation-B8XH1b_o.js";
2
+ import { n as sha256Hex, t as delay } from "../chunks/delay-B9YcAv-2.js";
3
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-CldDAUy1.js";
4
+ import { Type } from "@sinclair/typebox";
5
+
6
+ //#region src/capture-record.ts
7
+ /**
8
+ * The capture record: what one operation call, or one refusal, becomes for the sink that keeps it. The fields
9
+ * an analytics event has keep its names, so live counters and a store of records agree.
10
+ */
11
+ /** A field a record leaves null when the call never reached what fills it. */
12
+ const nullable = (schema, description) => Type.Union([schema, Type.Null()], { description });
13
+ /**
14
+ * One complete record of a call: who called which operation over which transport, when and for how long, what
15
+ * it answered, and, under `payloads: 'all'`, its input and output without what their schemas mark
16
+ * `secret: true`. A refusal before the operation ran has `stage: 'admission'` and null wherever admission had
17
+ * not learned the value: a token is never read before it is verified.
18
+ */
19
+ const CaptureRecordSchema = Type.Object({
20
+ id: UuidSchema,
21
+ service: Type.String({ description: "The application's name." }),
22
+ operation: nullable(Type.String(), "The operation, or null when the refusal names none."),
23
+ organizationId: nullable(OrganizationIdSchema, "The verified caller's organization, never one a request names; null before verification."),
24
+ actorId: nullable(Type.String(), "The verified caller; null before verification."),
25
+ actorKind: nullable(Type.Union([Type.Literal("user"), Type.Literal("service")]), "The verified caller's kind; null before verification."),
26
+ requestId: UuidSchema,
27
+ traceId: nullable(Type.String({ pattern: "^[0-9a-f]{32}$" }), "The active trace id `telemetry.traceId` returns; never generated, never read from a header."),
28
+ surface: Type.Union([
29
+ Type.Literal("http"),
30
+ Type.Literal("mcp"),
31
+ Type.Literal("rpc")
32
+ ], { description: "The transport that admitted the call." }),
33
+ occurredAt: Type.Integer({
34
+ minimum: 0,
35
+ description: "When the call finished, in Unix milliseconds."
36
+ }),
37
+ durationMicros: Type.Integer({
38
+ minimum: 0,
39
+ description: "How long execution took, or admission for a refusal, in whole microseconds."
40
+ }),
41
+ outcome: Type.Union([Type.Literal("success"), Type.Literal("failure")], { description: "`success` when the caller received the output, `failure` when it received a failure." }),
42
+ errorCode: nullable(Type.String(), "The code of the failure the caller received; null on success."),
43
+ stage: Type.Union([Type.Literal("execution"), Type.Literal("admission")], { description: "`admission` for a refusal before the shared execution path, `execution` from there on." }),
44
+ version: Type.String({ description: "The application's version." }),
45
+ effect: nullable(Type.Union([
46
+ Type.Literal("read"),
47
+ Type.Literal("write"),
48
+ Type.Literal("delete")
49
+ ]), "The operation's declared effect."),
50
+ scopes: Type.Array(Type.String(), { description: "The scopes the operation declares." }),
51
+ visibility: nullable(Type.Union([Type.Literal("public"), Type.Literal("internal")]), "The operation's visibility."),
52
+ httpMethod: nullable(Type.String(), "The route's method, on HTTP."),
53
+ httpPath: nullable(Type.String(), "The route's path template, never the requested path, on HTTP."),
54
+ mcpTool: nullable(Type.String(), "The operation's tool name, on MCP."),
55
+ 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."),
56
+ clientId: nullable(Type.String(), "The OAuth client the verified token was issued to."),
57
+ clientClass: nullable(Type.Union([
58
+ Type.Literal("human"),
59
+ Type.Literal("machine"),
60
+ Type.Literal("dcr")
61
+ ]), "That client's class."),
62
+ grantedScopes: nullable(Type.Array(Type.String()), "The scopes the verified token grants."),
63
+ userAgent: nullable(Type.String({ maxLength: 200 }), "On HTTP and MCP, the request's `user-agent`, cut to 200 characters. What the caller claims."),
64
+ 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."),
65
+ dimensions: Type.Record(Type.String(), Type.String(), { description: "What the `dimensions` callback named for this call." }),
66
+ startedAt: Type.Integer({
67
+ minimum: 0,
68
+ description: "When the transport began admitting the call, in Unix milliseconds."
69
+ }),
70
+ admissionMicros: Type.Integer({
71
+ minimum: 0,
72
+ description: "How long admission took, in whole microseconds."
73
+ }),
74
+ 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." }),
75
+ 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." }),
76
+ failureData: Type.Unknown({ description: "Under `payloads: all`, the failure's data without its secrets: `issues` for `INVALID_INPUT`, never the refused values. Null otherwise." }),
77
+ payloadRef: nullable(Type.Object({
78
+ $ref: Type.String({ description: "The key the payload was written to." }),
79
+ bytes: Type.Integer({
80
+ minimum: 0,
81
+ description: "The size of the payload written, in bytes."
82
+ }),
83
+ sha256: Type.String({
84
+ pattern: "^[0-9a-f]{64}$",
85
+ description: "The payload's hex SHA-256."
86
+ })
87
+ }, { additionalProperties: false }), "Where a sink wrote `input`, `output` and `failureData` when they were too large to send, as JSON; they are then null.")
88
+ }, { additionalProperties: false });
89
+
90
+ //#endregion
91
+ //#region src/capture/pipeline.ts
92
+ /** The largest `input`, `output` and `failureData` one record carries together, in bytes. */
93
+ const MAX_PAYLOAD_BYTES = 9e5;
94
+ /** How long the one retry waits. A stream that refuses a send usually recovers within a moment. */
95
+ const RETRY_DELAY_MILLISECONDS = 200;
96
+ /** A binding of the env, by name. */
97
+ function bindingOf(env, name) {
98
+ return isRecord(env) ? env[name] : void 0;
99
+ }
100
+ /** The record, with a payload over the limit written to the bucket: it fails when there is no bucket. */
101
+ async function withinLimit(record, bucket) {
102
+ const { input, output, failureData } = record;
103
+ const payload = new TextEncoder().encode(JSON.stringify({
104
+ input,
105
+ output,
106
+ failureData
107
+ }));
108
+ if (payload.byteLength <= MAX_PAYLOAD_BYTES) return record;
109
+ if (!bucket) throw new RangeError("A capture payload over the limit needs a blobs binding.");
110
+ const key = `payloads/${record.organizationId ?? "platform"}/${record.id}.json`;
111
+ await bucket.put(key, payload, { httpMetadata: { contentType: "application/json" } });
112
+ return {
113
+ ...record,
114
+ input: null,
115
+ output: null,
116
+ failureData: null,
117
+ payloadRef: {
118
+ $ref: key,
119
+ bytes: payload.byteLength,
120
+ sha256: await sha256Hex(payload)
121
+ }
122
+ };
123
+ }
124
+ /** Keeps a row the stream refused twice, for a job to send again. The record's id names it, so a replay finds one. */
125
+ async function deadLetter(record, row, bucket) {
126
+ const day = new Date(record.occurredAt).toISOString().slice(0, 10);
127
+ await bucket.put(`dlq/${record.service}/${day}/${record.id}.json`, JSON.stringify(row), { httpMetadata: { contentType: "application/json" } });
128
+ }
129
+ /**
130
+ * Sends each record to a Pipelines stream, the binding `env[binding]`. A send that fails is retried once after
131
+ * 200 ms, with the same record id, then written to the dead letter when `blobs` is set; the delivery still
132
+ * counts as failed, so the failure is logged. A stream is a durable buffer that accepts a repeated row, and a
133
+ * consumer deduplicates on the record's id. A sink for an append whose outcome may be lost should never retry.
134
+ */
135
+ function pipeline(options) {
136
+ const { binding, blobs, map } = options;
137
+ if (typeof binding !== "string" || !binding) throw new TypeError("pipeline() takes the name of a Pipelines binding.");
138
+ return {
139
+ available: (env) => typeof bindingOf(env, binding)?.send === "function",
140
+ async send(record, env) {
141
+ const stream = bindingOf(env, binding);
142
+ const bucket = blobs === void 0 ? void 0 : bindingOf(env, blobs);
143
+ const carried = await withinLimit(record, bucket);
144
+ const row = map ? await map(carried, env) : carried;
145
+ if (row === null || row === void 0) return;
146
+ try {
147
+ await stream.send([row]);
148
+ } catch {
149
+ await delay(RETRY_DELAY_MILLISECONDS);
150
+ try {
151
+ await stream.send([row]);
152
+ } catch (error) {
153
+ if (bucket) await deadLetter(carried, row, bucket);
154
+ throw error;
155
+ }
156
+ }
157
+ }
158
+ };
159
+ }
160
+
161
+ //#endregion
162
+ //#region src/capture/index.ts
163
+ /** The fields a capture declaration states. */
164
+ const CAPTURE_FIELDS = /* @__PURE__ */ new Set([
165
+ "enabled",
166
+ "sink",
167
+ "payloads",
168
+ "dimensions"
169
+ ]);
170
+ /**
171
+ * Declares what `maximus<Env>({ …, capture })` takes: whether calls are captured (`enabled`), where the records
172
+ * go (`sink`), whether they carry each input and output (`payloads`) and what each call is about (`dimensions`).
173
+ * `E` names the bindings and `C` the context `dimensions` reads. Any other field throws a TypeError.
174
+ */
175
+ function defineCapture(capture) {
176
+ const unknown = Object.keys(capture).filter((field) => !CAPTURE_FIELDS.has(field));
177
+ if (unknown.length) throw new TypeError(`A capture declaration states only enabled, sink, payloads and dimensions: remove ${unknown.join(", ")}.`);
178
+ return Object.freeze(capture);
179
+ }
180
+
181
+ //#endregion
182
+ export { CaptureRecordSchema, defineCapture, pipeline, withoutSecrets };
@@ -0,0 +1,25 @@
1
+ //#region src/internal/digest.ts
2
+ /**
3
+ * SHA-256 digests in hexadecimal, for rate limit keys and skill manifests.
4
+ */
5
+ /** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
6
+ async function sha256Hex(value) {
7
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
8
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
9
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
10
+ }
11
+
12
+ //#endregion
13
+ //#region src/internal/delay.ts
14
+ /**
15
+ * A wait on the runtime's global timer, for code the core reaches: it may load where `node:timers` does not.
16
+ */
17
+ /** Resolves after `milliseconds`. */
18
+ function delay(milliseconds) {
19
+ return new Promise((resolve) => {
20
+ setTimeout(resolve, milliseconds);
21
+ });
22
+ }
23
+
24
+ //#endregion
25
+ export { sha256Hex as n, delay as t };
@@ -23,14 +23,4 @@ function exactLength(stream, length) {
23
23
  }
24
24
 
25
25
  //#endregion
26
- //#region src/internal/record.ts
27
- /**
28
- * The plain-record guard the readers of untrusted values share.
29
- */
30
- /** Whether an untrusted value is an object with fields: neither null nor an array. */
31
- function isRecord(value) {
32
- return typeof value === "object" && value !== null && !Array.isArray(value);
33
- }
34
-
35
- //#endregion
36
- export { exactLength as n, isRecord as t };
26
+ export { exactLength as t };
@@ -1,11 +1,12 @@
1
1
  import { STANDARD_FAILURES } from "../standard-failures.js";
2
- import { l as hasUncompiledCodecs, r as parseInput, t as decodeInput } from "./validation-DWxKk1Js.js";
2
+ import { S as holdsSecrets, T as isRecord, i as parseInput, t as admitInput, u as hasUncompiledCodecs, w as withoutSecrets } from "./validation-B8XH1b_o.js";
3
3
  import { standardErrors } from "../errors.js";
4
4
  import { n as readBodyBytes } from "./body-BcMbreNd.js";
5
- import { n as exactLength, t as isRecord } from "./record-D2H3cg8S.js";
5
+ import { t as exactLength } from "./exact-length-CNFWdMzi.js";
6
6
  import { createHttpRouteResolver, isInputHeaderName, operationPathParameters } from "../http-paths.js";
7
- import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-q-51wBMQ.js";
8
- import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-DvZgrzZn.js";
7
+ import { n as sha256Hex, t as delay } from "./delay-B9YcAv-2.js";
8
+ import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-CldDAUy1.js";
9
+ import { o as reportUnexpected, r as elapsedMicros, s as telemetryEnabled, t as activeTraceId } from "./telemetry-Bcq3GquK.js";
9
10
  import { Kind, Type } from "@sinclair/typebox";
10
11
  import { Value } from "@sinclair/typebox/value";
11
12
  import { createRemoteJWKSet, jwtVerify } from "jose";
@@ -172,18 +173,6 @@ function mcpOpenWorld(tool) {
172
173
  return tool.openWorld ?? true;
173
174
  }
174
175
 
175
- //#endregion
176
- //#region src/internal/digest.ts
177
- /**
178
- * SHA-256 digests in hexadecimal, for rate limit keys and skill manifests.
179
- */
180
- /** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
181
- async function sha256Hex(value) {
182
- const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
183
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
184
- return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
185
- }
186
-
187
176
  //#endregion
188
177
  //#region src/result.ts
189
178
  /** A success carrying `value`. */
@@ -550,10 +539,21 @@ function checkApplication(manifest) {
550
539
  if (!validBodyLimit(manifest.maxBodyBytes)) throw new TypeError("The application body limit is a positive integer up to 16 MiB.");
551
540
  if (!validBodyLimit(manifest.maxOutputBytes)) throw new TypeError("The application output limit is a positive integer up to 16 MiB.");
552
541
  if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
542
+ checkCapture(manifest.capture);
553
543
  checkTokenAuthority(manifest.tokens);
554
544
  tokenAudiences(manifest.tokens);
555
545
  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.");
556
546
  }
547
+ /**
548
+ * The capture option, as code untyped by TypeScript may give it: a switch that is a boolean or a function, a
549
+ * sink that can send, `payloads` of `all` or `none`, and a `dimensions` callback that is a function. A sink
550
+ * that cannot send would lose every record it is handed, and a `payloads` such as `'al'` would silently send
551
+ * metadata alone.
552
+ */
553
+ function checkCapture(capture) {
554
+ if (capture === void 0) return;
555
+ 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.");
556
+ }
557
557
  /** An operation's `failures` name domain codes of the catalog, each once. */
558
558
  function checkDeclaredFailures(operations, errors) {
559
559
  const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
@@ -636,6 +636,177 @@ function strictObject(schema, unions) {
636
636
  return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
637
637
  }
638
638
 
639
+ //#endregion
640
+ //#region src/capture.ts
641
+ /** The most entries a `dimensions` callback's answer keeps. */
642
+ const MAX_DIMENSIONS = 32;
643
+ /** The longest value of one entry a `dimensions` callback's answer keeps. */
644
+ const MAX_DIMENSION_LENGTH = 256;
645
+ /** Writes one line of capture's own diagnostics; they are best effort. */
646
+ function logCapture(line) {
647
+ try {
648
+ console.error(JSON.stringify(line));
649
+ } catch {}
650
+ }
651
+ /** Whether capture is on for this env: a switch that throws turns it off and says so. */
652
+ function captureEnabled(capture, env) {
653
+ if (typeof capture.enabled !== "function") return capture.enabled !== false;
654
+ try {
655
+ return capture.enabled(env);
656
+ } catch {
657
+ logCapture({ event: "maximus.capture.switch_failed" });
658
+ return false;
659
+ }
660
+ }
661
+ /** A UUIDv7 at this instant: its leading bits are the time, so ids sort by when their records happened. */
662
+ function timeOrderedId(instant) {
663
+ const time = instant.toString(16).padStart(12, "0");
664
+ const random = crypto.randomUUID().replaceAll("-", "");
665
+ return `${time.slice(0, 8)}-${time.slice(8)}-7${random.slice(13, 16)}-${random.slice(16, 20)}-${random.slice(20)}`;
666
+ }
667
+ /**
668
+ * The input a record carries. An input whose schema marks nothing is the decoded one, as plain JSON. One whose
669
+ * schema marks a field is what the schema checked, without that field: a codec may move a value to where no
670
+ * mark reaches, so only the checked value is known to have the shape the marks describe. Decoded values a
671
+ * record cannot carry, such as a `BigInt`, fall back to the checked one, which is plain JSON by admission. Read
672
+ * after the call: a handler that changes its input in place changes the record, and in a strict object nothing
673
+ * it adds to a marked schema's input can reach it.
674
+ */
675
+ function recordedInput(schema, admitted) {
676
+ if (!admitted) return null;
677
+ if (holdsSecrets(schema)) return withoutSecrets(schema, admitted.checked) ?? null;
678
+ if (admitted.decoded === admitted.checked) return admitted.checked;
679
+ try {
680
+ return JSON.parse(JSON.stringify(admitted.decoded));
681
+ } catch {
682
+ return admitted.checked;
683
+ }
684
+ }
685
+ /** The output a record carries: never an attachment's bytes, and never what its schema marks. */
686
+ function recordedOutput(schema, value) {
687
+ if (isAttachmentSchema(schema)) {
688
+ const { contentType, filename, byteLength } = value;
689
+ return {
690
+ contentType,
691
+ filename,
692
+ byteLength
693
+ };
694
+ }
695
+ return holdsSecrets(schema) ? withoutSecrets(schema, value) ?? null : value;
696
+ }
697
+ /** The failure's data a record carries, without what its code's schema marks. */
698
+ function recordedFailureData(errors, failure) {
699
+ const schema = Object.values(errors.definitions).find(({ code }) => code === failure.code)?.dataSchema;
700
+ return schema && holdsSecrets(schema) ? withoutSecrets(schema, failure.data) ?? null : failure.data ?? null;
701
+ }
702
+ /** What the `dimensions` callback names for this call: bounded identifiers, or nothing when it throws. */
703
+ function recordedDimensions(application, env, captured) {
704
+ const dimensions = application.capture?.dimensions;
705
+ if (!dimensions) return {};
706
+ try {
707
+ const { operation, surface, principal, verified, call } = captured;
708
+ const named = dimensions({
709
+ env,
710
+ operation,
711
+ surface,
712
+ principal,
713
+ ...verified?.client ? { authority: {
714
+ surface,
715
+ scopes: verified.scopes,
716
+ client: verified.client
717
+ } } : {},
718
+ ...call?.rpcCaller ? { rpcCaller: call.rpcCaller } : {},
719
+ ...call?.userAgent ? { userAgent: call.userAgent } : {},
720
+ context: call?.context ?? {},
721
+ ...call?.admitted ? { input: call.admitted.decoded } : {}
722
+ });
723
+ 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)]));
724
+ } catch {
725
+ logCapture({
726
+ event: "maximus.capture.dimensions_failed",
727
+ requestId: captured.requestId
728
+ });
729
+ return {};
730
+ }
731
+ }
732
+ /** The record of one call, as background work. */
733
+ async function buildRecord(application, capture, env, captured, moment) {
734
+ const { operation, surface, principal, verified, result, call } = captured;
735
+ const declared = operation !== null && Object.hasOwn(application.operations, operation) ? application.operations[operation] : void 0;
736
+ const http = surface === "http" ? declared?.http : void 0;
737
+ const payloads = capture.payloads === "all";
738
+ return {
739
+ id: timeOrderedId(moment.occurredAt),
740
+ service: application.name,
741
+ operation,
742
+ organizationId: principal?.organizationId ?? null,
743
+ actorId: principal?.actorId ?? null,
744
+ actorKind: principal?.actorKind ?? null,
745
+ requestId: captured.requestId,
746
+ traceId: moment.traceId,
747
+ surface,
748
+ occurredAt: moment.occurredAt,
749
+ durationMicros: moment.durationMicros,
750
+ outcome: result.ok ? "success" : "failure",
751
+ errorCode: result.ok ? null : result.error.code,
752
+ stage: captured.executionStarted === void 0 ? "admission" : "execution",
753
+ version: application.version,
754
+ effect: declared?.effect ?? null,
755
+ scopes: declared ? [...operationScopes(declared)] : [],
756
+ visibility: declared ? declared.visibility ?? "public" : null,
757
+ httpMethod: http?.method ?? null,
758
+ httpPath: http?.path ?? null,
759
+ mcpTool: surface === "mcp" ? declared?.mcp?.name ?? null : null,
760
+ rpcCaller: call?.rpcCaller ?? null,
761
+ clientId: verified?.client?.id ?? null,
762
+ clientClass: verified?.client?.class ?? null,
763
+ grantedScopes: verified ? [...verified.scopes] : null,
764
+ userAgent: call?.userAgent ?? null,
765
+ tokenSha256: verified?.token ? await sha256Hex(verified.token) : null,
766
+ dimensions: recordedDimensions(application, env, captured),
767
+ startedAt: moment.startedAt,
768
+ admissionMicros: moment.admissionMicros,
769
+ input: payloads && declared ? recordedInput(declared.input, call?.admitted) : null,
770
+ output: payloads && declared && result.ok ? recordedOutput(declared.output, result.value) : null,
771
+ failureData: payloads && !result.ok ? recordedFailureData(application.errors, result.error) : null,
772
+ payloadRef: null
773
+ };
774
+ }
775
+ /**
776
+ * Captures one call beside `recordExecution` or `recordAdmission`, as background work: it never throws, never
777
+ * delays or changes the response and never affects an observer. A failed delivery logs
778
+ * `maximus.capture.delivery_failed` with the request id alone. Nothing is recorded without a background context,
779
+ * or while capture is off, whether telemetry is on or not.
780
+ */
781
+ function recordCapture(application, env, background, captured) {
782
+ const { capture } = application;
783
+ if (!(capture && background)) return;
784
+ try {
785
+ if (!captureEnabled(capture, env) || capture.sink.available?.(env) === false) return;
786
+ const occurredAt = Date.now();
787
+ const admissionMicros = elapsedMicros(captured.requestStarted, captured.executionStarted);
788
+ const executionMicros = captured.executionStarted === void 0 ? 0 : elapsedMicros(captured.executionStarted);
789
+ const moment = {
790
+ occurredAt,
791
+ startedAt: Math.max(0, Math.round(occurredAt - (admissionMicros + executionMicros) / 1e3)),
792
+ durationMicros: captured.executionStarted === void 0 ? admissionMicros : executionMicros,
793
+ admissionMicros,
794
+ traceId: activeTraceId(application.telemetry)
795
+ };
796
+ background.waitUntil(delay(0).then(() => buildRecord(application, capture, env, captured, moment)).then((record) => capture.sink.send(record, env)).catch(() => {
797
+ logCapture({
798
+ event: "maximus.capture.delivery_failed",
799
+ requestId: captured.requestId
800
+ });
801
+ }));
802
+ } catch {
803
+ logCapture({
804
+ event: "maximus.capture.delivery_failed",
805
+ requestId: captured.requestId
806
+ });
807
+ }
808
+ }
809
+
639
810
  //#endregion
640
811
  //#region src/execution.ts
641
812
  /**
@@ -645,12 +816,18 @@ function strictObject(schema, unions) {
645
816
  /**
646
817
  * The execution path every transport shares: checks that the caller may run the operation, decodes the input,
647
818
  * prepares the context, runs the middleware and the handler, then checks the result against the declared
648
- * output and failures. An unexpected error becomes `INTERNAL_ERROR` and is reported, never thrown.
819
+ * output and failures. An unexpected error becomes `INTERNAL_ERROR` and is reported, never thrown. `call` hands
820
+ * the admitted input and the prepared context to the recording points, which only the Result would otherwise
821
+ * reach.
649
822
  */
650
- async function executeOperation(manifest, operation, env, principal, input, authority, background, body) {
823
+ async function executeOperation(manifest, operation, env, principal, input, authority, background, body, call) {
651
824
  if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
652
- const admitted = decodeInput(operation.input, input);
825
+ const admitted = admitInput(operation.input, input);
653
826
  if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
827
+ if (call) call.admitted = {
828
+ checked: admitted.checked,
829
+ decoded: admitted.value
830
+ };
654
831
  try {
655
832
  const trustedAuthority = authority ? Object.freeze({
656
833
  surface: authority.surface,
@@ -664,10 +841,13 @@ async function executeOperation(manifest, operation, env, principal, input, auth
664
841
  input: admitted.value,
665
842
  ...body ? { body } : {},
666
843
  ...background ? { background } : {},
667
- ...trustedAuthority ? { authority: trustedAuthority } : {}
844
+ ...trustedAuthority ? { authority: trustedAuthority } : {},
845
+ ...call?.rpcCaller ? { rpcCaller: call.rpcCaller } : {},
846
+ ...call?.userAgent ? { userAgent: call.userAgent } : {}
668
847
  };
669
848
  const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
670
849
  if (!context.ok) return err(manifest.errors.validate(context.error));
850
+ if (call) call.context = context.value;
671
851
  const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
672
852
  let latest = -1;
673
853
  /**
@@ -702,4 +882,4 @@ async function executeOperation(manifest, operation, env, principal, input, auth
702
882
  }
703
883
 
704
884
  //#endregion
705
- export { operationMatchesScopes as C, pathParameterSchemas as D, matchesScopes as E, attachmentResponse as O, operationBodyLimit as S, operationScopes as T, STANDARD_CODES as _, createTokenVerifier as a, mcpOpenWorld as b, tokenEndpoints as c, err as d, isResult as f, MAX_BODY_BYTES_CEILING as g, DEFAULT_MAX_BODY_BYTES as h, createTokenAuthorization as i, binaryBody as k, tokenIssuer as l, sha256Hex as m, defineApp as n, projectToken as o, ok as p, PrincipalSchema as r, tokenAudiences as s, executeOperation as t, usesOwnBearer as u, composeOperations as v, operationOutputLimit as w, operation as x, isPublicOperation as y };
885
+ export { operationMatchesScopes as C, pathParameterSchemas as D, matchesScopes as E, attachmentResponse as O, operationBodyLimit as S, operationScopes as T, STANDARD_CODES as _, createTokenAuthorization as a, mcpOpenWorld as b, tokenAudiences as c, usesOwnBearer as d, err as f, MAX_BODY_BYTES_CEILING as g, DEFAULT_MAX_BODY_BYTES as h, PrincipalSchema as i, binaryBody as k, tokenEndpoints as l, ok as m, recordCapture as n, createTokenVerifier as o, isResult as p, defineApp as r, projectToken as s, executeOperation as t, tokenIssuer as u, composeOperations as v, operationOutputLimit as w, operation as x, isPublicOperation as y };
@@ -1,4 +1,4 @@
1
- import { a as decodeIssues, n as decodeSchema, o as SchemaValidationError, s as defaultSchema, u as inputSchema } from "./validation-DWxKk1Js.js";
1
+ import { c as defaultSchema, d as inputSchema, o as decodeIssues, r as decodeSchema, s as SchemaValidationError } from "./validation-B8XH1b_o.js";
2
2
  import { Kind, Type, Type as Type$1, Type as t } from "@sinclair/typebox";
3
3
 
4
4
  //#region src/schema-reader.ts