Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nativeProtocolLogging.ts

39 lines1.3 KB

1import { errorTag } from "@t3tools/shared/observability";
2​
3export function structuralProtocolMethod(value: string): string {
4 return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
5}
6​
7/**
8 * Provider payload values may contain prompts, credentials, or arbitrarily
9 * large tool output and must never be copied into the observability stream.
10 */
11export function summarizeNativeProtocolPayload(
12 payload: unknown,
13): Readonly<Record<string, unknown>> {
14 if (payload === null) return { valueType: "null" };
15 if (typeof payload === "string") {
16 return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };
17 }
18 if (payload instanceof Uint8Array) {
19 return { valueType: "bytes", byteLength: payload.byteLength };
20 }
21 if (Array.isArray(payload)) {
22 return { valueType: "array", itemCount: payload.length };
23 }
24 if (typeof payload !== "object") {
25 return { valueType: typeof payload };
26 }
27​
28 try {
29 const record = payload as Record<string, unknown>;
30 return {
31 valueType: "object",
32 fieldCount: Object.keys(record).length,
33 ...(typeof record._tag === "string" ? { messageTag: errorTag(record) } : {}),
34 ...(typeof record.tag === "string" ? { method: structuralProtocolMethod(record.tag) } : {}),
35 };
36 } catch {
37 return { valueType: "object" };
38 }