Open History to see the last commit
1import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
2import { causeErrorTag, errorTag } from "@t3tools/shared/observability";
3import * as Cause from "effect/Cause";
4import * as Crypto from "effect/Crypto";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import type * as EffectAcpProtocol from "effect-acp/protocol";
8
9import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
10import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
11
12const transientProtocolUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
13
14function structuralMethod(value: string): string {
15 return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
16}
17
18function summarizePayload(payload: unknown): Readonly<Record<string, unknown>> {
19 if (payload === null) return { valueType: "null" };
20 if (typeof payload === "string") {
21 return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };
22 }
23 if (payload instanceof Uint8Array) {
24 return { valueType: "bytes", byteLength: payload.byteLength };
25 }
26 if (Array.isArray(payload)) {
27 return { valueType: "array", itemCount: payload.length };
28 }
29 if (typeof payload !== "object") {
30 return { valueType: typeof payload };
31 }
32
33 try {
34 const record = payload as Record<string, unknown>;
35 return {
36 valueType: "object",
37 fieldCount: Object.keys(record).length,
38 ...(typeof record._tag === "string" ? { messageTag: errorTag(record) } : {}),
39 ...(typeof record.tag === "string" ? { method: structuralMethod(record.tag) } : {}),
40 };
41 } catch {
42 return { valueType: "object" };
43 }
44}
45
46function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) {
47 return {
48 method: structuralMethod(event.method),
49 status: event.status,
50 request: summarizePayload(event.payload),
51 ...(event.result !== undefined ? { result: summarizePayload(event.result) } : {}),
52 ...(event.cause !== undefined
53 ? {
54 errorTag: causeErrorTag(event.cause),
55 reasonCount: event.cause.reasons.length,
56 }
57 : {}),
58 };
59}
60
61function formatProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) {
62 return {
63 direction: event.direction,
64 stage: event.stage,
65 payload: summarizePayload(event.payload),
66 };
67}
68
69function isTransientProtocolMessage(message: unknown): boolean {
70 if (typeof message !== "object" || message === null) return false;
71 const method = Reflect.get(message, "tag") ?? Reflect.get(message, "method");
72 if (method !== "session/update") return false;
73
74 const payload = Reflect.get(message, "payload") ?? Reflect.get(message, "params");
75 if (typeof payload !== "object" || payload === null) return false;
76 const update = Reflect.get(payload, "update");
77 if (typeof update !== "object" || update === null) return false;
78 const updateType = Reflect.get(update, "sessionUpdate");
79 return typeof updateType === "string" && transientProtocolUpdates.has(updateType);
80}
81
82function rawChunkContainsOnlyTransientMessages(payload: string): boolean {
83 const lines = payload.split("\n");
84 const remainder = lines.pop() ?? "";
85 if (remainder.trim().length > 0) return false;
86
87 const messages: Array<unknown> = [];
88 for (const line of lines) {
89 if (line.trim().length === 0) continue;
90 try {
91 messages.push(JSON.parse(line));
92 } catch {
93 return false;
94 }
95 }
96 return messages.length > 0 && messages.every(isTransientProtocolMessage);
97}
98
99function filterTransientProtocolLog(
100 event: EffectAcpProtocol.AcpProtocolLogEvent,
101): EffectAcpProtocol.AcpProtocolLogEvent | undefined {
102 if (event.direction !== "incoming") return event;
103
104 if (event.stage === "raw" && typeof event.payload === "string") {
105 return rawChunkContainsOnlyTransientMessages(event.payload) ? undefined : event;
106 }
107
108 if (event.stage !== "decoded") return event;
109 if (!Array.isArray(event.payload)) {
110 return isTransientProtocolMessage(event.payload) ? undefined : event;
111 }
112
113 const payload = event.payload.filter((message) => !isTransientProtocolMessage(message));
114 return payload.length === 0 ? undefined : { ...event, payload };
115}
116
117export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory")(function* () {
118 const crypto = yield* Crypto.Crypto;
119 return (input: {
120 readonly nativeEventLogger: EventNdjsonLogger | undefined;
121 readonly provider: ProviderDriverKind;
122 readonly threadId: ThreadId;
123 readonly verboseProtocolLogging?: boolean;
124 }): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
125 const writeNativeAcpLog = (logInput: {
126 readonly kind: "request" | "protocol";
127 readonly payload: unknown;
128 }) =>
129 Effect.gen(function* () {
130 if (!input.nativeEventLogger) return;
131 const observedAt = DateTime.formatIso(yield* DateTime.now);
132 yield* input.nativeEventLogger.write(
133 {
134 observedAt,
135 event: {
136 id: yield* crypto.randomUUIDv4,
137 kind: logInput.kind,
138 provider: input.provider,
139 createdAt: observedAt,
140 threadId: input.threadId,
141 payload: logInput.payload,
142 },
143 },
144 input.threadId,
145 );
146 }).pipe(
147 Effect.catchCause((cause) =>
148 Cause.hasInterrupts(cause)
149 ? Effect.interrupt
150 : Effect.logWarning("Failed to write native ACP event log.", {
151 errorTag: causeErrorTag(cause),
152 reasonCount: cause.reasons.length,
153 provider: input.provider,
154 threadId: input.threadId,
155 }),
156 ),
157 );
158
159 return {
160 requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>
161 writeNativeAcpLog({
162 kind: "request",
163 payload: formatRequestLogPayload(event),
164 }),
165 ...(input.nativeEventLogger && input.verboseProtocolLogging
166 ? {
167 protocolLogging: {
168 logIncoming: true,
169 logOutgoing: true,
170 logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) => {
171 const filtered = filterTransientProtocolLog(event);
172 return filtered
173 ? writeNativeAcpLog({
174 kind: "protocol",
175 payload: formatProtocolLogPayload(filtered),
176 })
177 : Effect.void;
178 },
179 } satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]>,
180 }
181 : {}),
182 };
183 };
184});