Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
perf(protocol): make raw event retention opt-in (#198)
Leob6b09944c676
diff --git a/docs/internals/providers.md b/docs/internals/providers.mdindex 48c3b4592..26251e326 100644--- a/docs/internals/providers.md+++ b/docs/internals/providers.md@@ -60,6 +60,29 @@ the active runtime and starts the selected provider without reusing an incompatibridge is not the Codex turn path, and AgentController never falls back to the legacy Codex loop whena Mastra session is absent.+## Raw protocol observation++The [ACP protocol](../../packages/effect-acp/src/protocol.ts) and+[Codex app-server protocol](../../packages/effect-codex-app-server/src/protocol.ts) retain raw+observations only when configured before connection. `AcpClientOptions` and `AcpAgentOptions` expose+`rawNotificationBufferSize` for `raw.notifications`. `CodexAppServerClientOptions` exposes that option+and `rawRequestBufferSize` for `raw.requests`. Pass them to the package's `make` or layer constructor.++- `0`, the default, retains nothing and completes the raw stream immediately.+- A positive safe integer `N` keeps the newest `N` unread events in a sliding queue. Overflow drops+ the oldest observation, including when a reader starts late or falls behind.+- `"unbounded"` explicitly restores the legacy lossless FIFO within the connection scope. An absent+ or slow reader can then retain the whole session.++These are work-sharing streams, not broadcasts. Enabled streams drain when input ends; closing the+connection scope discards the buffer and interrupts readers. Observation never blocks callback+dispatch. Notification callbacks, request handlers, and replies keep their existing behavior even+when raw observation is disabled or drops events. Reading `raw.requests` does not send a reply.+Use handlers for required protocol work, not a lossy observation stream.++This bounds optional transport observations, not provider transcripts or the Mastra Codex/Kimi turn+path described above.+## Composio runtimeComposio is an integration provider. Its toolkits appear as named plugins such as Gmail, but Akerudiff --git a/packages/effect-acp/src/agent.test.ts b/packages/effect-acp/src/agent.test.tsindex fac52398c..06ea759f9 100644--- a/packages/effect-acp/src/agent.test.ts+++ b/packages/effect-acp/src/agent.test.ts@@ -7,6 +7,7 @@ import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";+import * as Stream from "effect/Stream";import { assert, it } from "@effect/vitest";@@ -179,6 +180,42 @@ it.effect("effect-acp agent handles core agent requests and outbound client requ}),);+it.effect(+ "effect-acp agent opts into bounded late raw observation without changing cancel callbacks",+ () =>+ Effect.gen(function* () {+ const { stdio, input } = yield* makeInMemoryStdio();+ const agent = yield* AcpAgent.make(stdio, { rawNotificationBufferSize: 2 });+ const received = yield* Deferred.make<void>();+ let handled = 0;+ yield* agent.handleCancel(() =>+ Effect.suspend(() => {+ handled++;+ return handled === 3+ ? Deferred.succeed(received, undefined).pipe(Effect.asVoid)+ : Effect.void;+ }),+ );+ for (const index of [0, 1, 2]) {+ yield* Queue.offer(+ input,+ yield* encodeJsonl(SessionCancelNotification, {+ jsonrpc: "2.0",+ method: "session/cancel",+ params: { sessionId: `session-${index}` },+ }),+ );+ }+ yield* Deferred.await(received);+ const replay = yield* agent.raw.notifications.pipe(Stream.take(2), Stream.runCollect);+ assert.equal(handled, 3);+ assert.deepEqual(+ replay.map((notification) => notification.params),+ [{ sessionId: "session-1" }, { sessionId: "session-2" }],+ );+ }),+);+it.effect("effect-acp agent uses distinct ids for RPC calls and extension requests", () =>Effect.gen(function* () {const { stdio, input, output } = yield* makeInMemoryStdio();diff --git a/packages/effect-acp/src/agent.ts b/packages/effect-acp/src/agent.tsindex bff3491c3..a85350304 100644--- a/packages/effect-acp/src/agent.ts+++ b/packages/effect-acp/src/agent.ts@@ -22,7 +22,10 @@ import {} from "./_internal/shared.ts";import * as AcpTerminal from "./terminal.ts";-export interface AcpAgentOptions {+export interface AcpAgentOptions extends Pick<+ AcpProtocol.AcpPatchedProtocolOptions,+ "rawNotificationBufferSize"+> {readonly logIncoming?: boolean;readonly logOutgoing?: boolean;readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;@@ -33,7 +36,9 @@ export class AcpAgent extends Context.Service<{readonly raw: {/**- * Stream of inbound ACP notifications observed on the connection.+ * Opt-in, work-sharing stream of inbound ACP notifications, not a broadcast.+ * Configure rawNotificationBufferSize before connecting; disabled streams end immediately.+ * Enabled streams drain on input termination and are interrupted when the connection scope closes.*/readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;/**@@ -280,6 +285,7 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (const transport = yield* AcpProtocol.makeAcpPatchedProtocol({stdio,serverRequestMethods: new Set(AcpRpcs.AgentRpcs.requests.keys()),+ rawNotificationBufferSize: options.rawNotificationBufferSize ?? 0,...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),...(options.logger ? { logger: options.logger } : {}),diff --git a/packages/effect-acp/src/client.test.ts b/packages/effect-acp/src/client.test.tsindex 779a6499e..00ed5a378 100644--- a/packages/effect-acp/src/client.test.ts+++ b/packages/effect-acp/src/client.test.ts@@ -1,6 +1,7 @@import * as Path from "effect/Path";import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";+import * as Deferred from "effect/Deferred";import * as Exit from "effect/Exit";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";@@ -31,6 +32,10 @@ const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.Stringconst ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);+const SessionUpdateNotification = jsonRpcNotification(+ "session/update",+ AcpSchema.SessionNotification,+);const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));const XAiPromptCompleteNotification = jsonRpcNotification("_x.ai/session/prompt_complete",@@ -71,6 +76,43 @@ function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {}it.layer(NodeServices.layer)("effect-acp client", (it) => {+ it.effect("handles callback-only session traffic without retaining raw notifications", () =>+ Effect.gen(function* () {+ const { stdio, input } = yield* makeInMemoryStdio();+ const acp = yield* AcpClient.make(stdio);+ const handled = yield* Deferred.make<void>();+ const count = 10_000;+ let updates = 0;+ yield* acp.handleSessionUpdate(() =>+ Effect.suspend(() => {+ updates++;+ return updates === count+ ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid)+ : Effect.void;+ }),+ );+ for (let index = 0; index < count; index++) {+ yield* Queue.offer(+ input,+ yield* encodeJsonl(SessionUpdateNotification, {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: "stress-session",+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: `${index}:${"x".repeat(1024)}` },+ },+ },+ }),+ );+ }+ yield* Deferred.await(handled);+ assert.equal(updates, count);+ assert.deepEqual(yield* Stream.runCollect(acp.raw.notifications), []);+ }),+ );+const makeHandle = (env?: Record<string, string>) =>Effect.gen(function* () {const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;@@ -90,7 +132,9 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {const typedNotifications = yield* Ref.make<Array<unknown>>([]);const handle = yield* makeHandle();const scope = yield* Scope.make();- const acpLayer = AcpClient.layerChildProcess(handle);+ const acpLayer = AcpClient.layerChildProcess(handle, {+ rawNotificationBufferSize: "unbounded",+ });const context = yield* Layer.buildWithScope(acpLayer, scope);const ext = yield* Effect.gen(function* () {diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.tsindex 165d834bb..80ddf7be6 100644--- a/packages/effect-acp/src/client.ts+++ b/packages/effect-acp/src/client.ts@@ -23,13 +23,20 @@ import {} from "./_internal/shared.ts";import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";-export interface AcpClientOptions {+export interface AcpClientOptions extends Pick<+ AcpProtocol.AcpPatchedProtocolOptions,+ "rawNotificationBufferSize"+> {readonly logIncoming?: boolean;readonly logOutgoing?: boolean;readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;}type AcpClientRaw = {+ /**+ * Opt-in, work-sharing stream, not a broadcast. Configure rawNotificationBufferSize before connecting.+ * Disabled streams end immediately; enabled streams drain on input termination and are interrupted on scope close.+ */readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;@@ -401,6 +408,7 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (stdio: stdio,...(terminationError ? { terminationError } : {}),serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),+ rawNotificationBufferSize: options.rawNotificationBufferSize ?? 0,...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),...(options.logger ? { logger: options.logger } : {}),diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.tsindex a66cc7522..68ca73a07 100644--- a/packages/effect-acp/src/protocol.test.ts+++ b/packages/effect-acp/src/protocol.test.ts@@ -3,6 +3,8 @@ import * as AcpError from "./errors.ts";import * as Effect from "effect/Effect";import * as Deferred from "effect/Deferred";import * as Fiber from "effect/Fiber";+import * as Exit from "effect/Exit";+import * as Scope from "effect/Scope";import * as Queue from "effect/Queue";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -68,6 +70,149 @@ const makeHandle = (env?: Record<string, string>) =>});it.layer(NodeServices.layer)("effect-acp protocol", (it) => {+ for (const bufferSize of [undefined, 0, 8] as const) {+ it.effect(+ `bounds callback-only raw retention with buffer size ${bufferSize ?? "default"}`,+ () =>+ Effect.gen(function* () {+ const { stdio, input, output } = yield* makeInMemoryStdio();+ const terminated = yield* Deferred.make<void>();+ const count = 10_000;+ const text = "x".repeat(1024);+ let handled = 0;+ const transport = yield* AcpProtocol.makeAcpPatchedProtocol({+ stdio,+ serverRequestMethods: new Set(),+ ...(bufferSize === undefined ? {} : { rawNotificationBufferSize: bufferSize }),+ onNotification: () =>+ Effect.suspend(() => {+ handled++;+ return handled === 1+ ? Effect.fail(AcpError.AcpRequestError.internalError("handler failed"))+ : Effect.void;+ }),+ onExtRequest: () => Effect.succeed({ ok: true }),+ onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),+ });++ for (let index = 0; index < count; index++) {+ yield* Queue.offer(+ input,+ encoder.encode(+ `${encodeUnknownJsonString({+ jsonrpc: "2.0",+ method: "x/stress",+ params: { index, text },+ })}\n`,+ ),+ );+ }+ yield* Queue.offer(+ input,+ yield* encodeJsonl(ExtRequest, {+ jsonrpc: "2.0",+ id: 7,+ method: "x/test",+ params: { hello: "world" },+ headers: [],+ }),+ );+ assert.deepEqual(yield* decodeExtResponse(yield* Queue.take(output)), {+ jsonrpc: "2.0",+ id: 7,+ result: { ok: true },+ });+ yield* Queue.end(input);+ yield* Deferred.await(terminated);++ assert.equal(handled, count);+ const retained = yield* Stream.runCollect(transport.incoming);+ assert.deepEqual(+ retained.map((notification) => notification.params),+ Array.from({ length: bufferSize ?? 0 }, (_, offset) => ({+ index: count - (bufferSize ?? 0) + offset,+ text,+ })),+ );+ assert.deepEqual(yield* Stream.runCollect(transport.incoming), []);+ }),+ );+ }++ it.effect("preserves opt-in late replay after a reader is interrupted", () =>+ Effect.gen(function* () {+ const { stdio, input } = yield* makeInMemoryStdio();+ const observed = yield* Deferred.make<void>();+ const terminated = yield* Deferred.make<void>();+ const transport = yield* AcpProtocol.makeAcpPatchedProtocol({+ stdio,+ serverRequestMethods: new Set(),+ rawNotificationBufferSize: "unbounded",+ onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),+ });+ const reader = yield* transport.incoming.pipe(+ Stream.runForEach(() =>+ Deferred.succeed(observed, undefined).pipe(Effect.andThen(Effect.never)),+ ),+ Effect.forkScoped,+ );+ yield* Queue.offer(input, encoder.encode('{"jsonrpc":"2.0","method":"x/first"}\n'));+ yield* Deferred.await(observed);+ yield* Fiber.interrupt(reader);++ yield* Queue.offer(+ input,+ encoder.encode(+ '{"jsonrpc":"2.0","method":"x/second"}\n{"jsonrpc":"2.0","method":"x/third"}\n',+ ),+ );+ yield* Queue.end(input);+ yield* Deferred.await(terminated);+ const replay = yield* Stream.runCollect(transport.incoming);+ assert.deepEqual(+ replay.map((notification) => notification.method),+ ["x/second", "x/third"],+ );+ assert.deepEqual(yield* Stream.runCollect(transport.incoming), []);+ }),+ );++ it.effect("drains raw observations and completes waiting readers on decode failure", () =>+ Effect.gen(function* () {+ const { stdio, input } = yield* makeInMemoryStdio();+ const transport = yield* AcpProtocol.makeAcpPatchedProtocol({+ stdio,+ serverRequestMethods: new Set(),+ rawNotificationBufferSize: 8,+ });+ const reader = yield* transport.incoming.pipe(Stream.runCollect, Effect.forkScoped);+ yield* Queue.offer(input, encoder.encode('{"jsonrpc":"2.0","method":"x/first"}\n'));+ yield* Queue.offer(input, encoder.encode("{malformed}\n"));+ assert.deepEqual(+ (yield* Fiber.join(reader)).map((notification) => notification.method),+ ["x/first"],+ );+ }),+ );++ it.effect("interrupts raw readers outside the connection scope when it closes", () =>+ Effect.gen(function* () {+ const { stdio } = yield* makeInMemoryStdio();+ const scope = yield* Scope.make();+ const transport = yield* AcpProtocol.makeAcpPatchedProtocol({+ stdio,+ serverRequestMethods: new Set(),+ rawNotificationBufferSize: 8,+ }).pipe(Effect.provideService(Scope.Scope, scope));+ const reader = yield* transport.incoming.pipe(+ Stream.runCollect,+ Effect.forkScoped({ startImmediately: true }),+ );+ yield* Scope.close(scope, Exit.void);+ assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(reader)));+ }),+ );+it.effect("emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",() =>@@ -76,6 +221,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {const transport = yield* AcpProtocol.makeAcpPatchedProtocol({stdio,serverRequestMethods: new Set(),+ rawNotificationBufferSize: "unbounded",});const notifications =diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.tsindex d61641fbb..71a6e1238 100644--- a/packages/effect-acp/src/protocol.ts+++ b/packages/effect-acp/src/protocol.ts@@ -45,6 +45,13 @@ export interface AcpPatchedProtocolOptions {readonly stdio: Stdio.Stdio;readonly terminationError?: Effect.Effect<AcpError.AcpError>;readonly serverRequestMethods: ReadonlySet<string>;+ /**+ * Enables raw notification observation. Zero (the default) returns an empty stream.+ * A positive integer retains the newest N unread events, dropping the oldest on overflow.+ * "unbounded" preserves the legacy lossless FIFO, including all events before a late reader.+ * Buffers never block callback dispatch; finite buffers can also drop events for slow readers.+ */+ readonly rawNotificationBufferSize?: number | "unbounded";readonly logIncoming?: boolean;readonly logOutgoing?: boolean;readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;@@ -61,6 +68,10 @@ export interface AcpPatchedProtocolOptions {export interface AcpPatchedProtocol {readonly clientProtocol: RpcClient.Protocol["Service"];readonly serverProtocol: RpcServer.Protocol["Service"];+ /**+ * Opt-in FIFO shared by readers, not a broadcast. Disabled streams end immediately.+ * Enabled streams drain on input termination; scope closure discards the buffer and interrupts readers.+ */readonly incoming: Stream.Stream<AcpIncomingNotification>;readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;@@ -77,13 +88,32 @@ const decodeElicitationComplete = Schema.decodeUnknownEffect();const parserFactory = RpcSerialization.ndJsonRpc();+const makeRawQueue = Effect.fn("makeRawQueue")(function* <A>(bufferSize: number | "unbounded" = 0) {+ if (bufferSize === 0) {+ return undefined;+ }+ if (bufferSize !== "unbounded" && (!Number.isSafeInteger(bufferSize) || bufferSize < 0)) {+ return yield* Effect.die(+ new RangeError("Raw buffer size must be a non-negative safe integer or 'unbounded'."),+ );+ }+ return yield* Effect.acquireRelease(+ Queue.sliding<A, Cause.Done<void>>(+ bufferSize === "unbounded" ? Number.POSITIVE_INFINITY : bufferSize,+ ),+ Queue.shutdown,+ );+});+export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (options: AcpPatchedProtocolOptions,): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {const parser = parserFactory.makeUnsafe();const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();- const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();+ const notificationQueue = yield* makeRawQueue<AcpIncomingNotification>(+ options.rawNotificationBufferSize,+ );const disconnects = yield* Queue.unbounded<number>();const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();const nextRequestId = yield* Ref.make(1);@@ -178,7 +208,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi);const dispatchNotification = (notification: AcpIncomingNotification) =>- Queue.offer(notificationQueue, notification).pipe(+ (notificationQueue ? Queue.offer(notificationQueue, notification) : Effect.void).pipe(Effect.andThen(options.onNotification? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))@@ -206,6 +236,9 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functireturn [Effect.gen(function* () {yield* Queue.offer(disconnects, 0);+ if (notificationQueue) {+ yield* Queue.end(notificationQueue);+ }const error = yield* classify();if (!error) {return;@@ -552,9 +585,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functireturn {clientProtocol,serverProtocol,- get incoming() {- return Stream.fromQueue(notificationQueue);- },+ incoming: notificationQueue ? Stream.fromQueue(notificationQueue) : Stream.empty,request: sendRequest,notify: sendNotification,} satisfies AcpPatchedProtocol;diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.tsindex 3830c5fc5..e24ca166f 100644--- a/packages/effect-codex-app-server/src/client.test.ts+++ b/packages/effect-codex-app-server/src/client.test.ts@@ -4,12 +4,20 @@ import * as Path from "effect/Path";import * as Effect from "effect/Effect";import * as Ref from "effect/Ref";import * as Scope from "effect/Scope";+import * as Queue from "effect/Queue";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";import * as CodexClient from "./client.ts";+import { makeInMemoryStdio } from "./_internal/stdio.ts";++const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));+const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));+const encoder = new TextEncoder();const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),@@ -17,6 +25,72 @@ const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>const mockPeerArgs = (path: string) => [path];it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {+ for (const [rawNotificationBufferSize, rawRequestBufferSize] of [+ [2, 0],+ [0, 2],+ ["unbounded", "unbounded"],+ ] as const) {+ it.effect(+ `opts into raw buffers independently (${rawNotificationBufferSize}, ${rawRequestBufferSize})`,+ () =>+ Effect.gen(function* () {+ const { stdio, input, output } = yield* makeInMemoryStdio();+ const client = yield* CodexClient.make(stdio, {+ rawNotificationBufferSize,+ rawRequestBufferSize,+ });+ let notifications = 0;+ let requests = 0;+ yield* client.handleUnknownServerNotification(() =>+ Effect.sync(() => {+ notifications++;+ }),+ );+ yield* client.handleUnknownServerRequest(() =>+ Effect.sync(() => {+ requests++;+ return { ok: true };+ }),+ );+ for (const index of [0, 1, 2]) {+ yield* Queue.offer(+ input,+ encoder.encode(`${encodeJson({ method: "x/notify", params: index })}\n`),+ );+ yield* Queue.offer(+ input,+ encoder.encode(`${encodeJson({ id: index, method: "x/request" })}\n`),+ );+ assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {+ id: index,+ result: { ok: true },+ });+ }+ const notificationCount =+ rawNotificationBufferSize === "unbounded" ? 3 : rawNotificationBufferSize;+ const requestCount = rawRequestBufferSize === "unbounded" ? 3 : rawRequestBufferSize;+ const rawNotifications = yield* client.raw.notifications.pipe(+ Stream.take(notificationCount),+ Stream.runCollect,+ );+ const rawRequests = yield* client.raw.requests.pipe(+ Stream.take(requestCount),+ Stream.runCollect,+ );+ assert.deepEqual(+ rawNotifications.map((notification) => notification.params),+ [0, 1, 2].slice(3 - notificationCount),+ );+ assert.deepEqual(+ rawRequests.map((request) => request.id),+ [0, 1, 2].slice(3 - requestCount),+ );+ assert.equal(notifications, 3);+ assert.equal(requests, 3);+ }),+ );+ }+const makeHandle = (env?: Record<string, string>) =>Effect.gen(function* () {const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;@@ -85,6 +159,8 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {const skills = yield* client.request("skills/list", { cwds: [peerCwd] });assert.equal(skills.data.length, 1);assert.equal(skills.data[0]?.cwd, peerCwd);+ assert.deepEqual(yield* Stream.runCollect(client.raw.notifications), []);+ assert.deepEqual(yield* Stream.runCollect(client.raw.requests), []);return {account,diff --git a/packages/effect-codex-app-server/src/client.ts b/packages/effect-codex-app-server/src/client.tsindex c0cb5b1dc..65dfbe34a 100644--- a/packages/effect-codex-app-server/src/client.ts+++ b/packages/effect-codex-app-server/src/client.ts@@ -18,7 +18,10 @@ import {} from "./_internal/shared.ts";import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";-export interface CodexAppServerClientOptions {+export interface CodexAppServerClientOptions extends Pick<+ CodexProtocol.CodexAppServerPatchedProtocolOptions,+ "rawNotificationBufferSize" | "rawRequestBufferSize"+> {readonly logIncoming?: boolean;readonly logOutgoing?: boolean;readonly logger?: (@@ -27,7 +30,15 @@ export interface CodexAppServerClientOptions {}interface CodexAppServerClientRaw {+ /**+ * Opt-in, work-sharing stream, not a broadcast. Configure rawNotificationBufferSize before connecting.+ * Disabled streams end immediately; enabled streams drain on input termination and are interrupted on scope close.+ */readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];+ /**+ * Opt-in request observation with the same stream lifecycle as notifications.+ * Configure rawRequestBufferSize before connecting. Registered handlers still send replies.+ */readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];@@ -187,6 +198,8 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.makeconst transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({stdio,...(terminationError ? { terminationError } : {}),+ rawNotificationBufferSize: options.rawNotificationBufferSize ?? 0,+ rawRequestBufferSize: options.rawRequestBufferSize ?? 0,...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),...(options.logger ? { logger: options.logger } : {}),diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.tsindex a7e0397b4..fd3cfb1f7 100644--- a/packages/effect-codex-app-server/src/protocol.test.ts+++ b/packages/effect-codex-app-server/src/protocol.test.ts@@ -1,6 +1,8 @@import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";+import * as Exit from "effect/Exit";+import * as Scope from "effect/Scope";import * as Queue from "effect/Queue";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -34,6 +36,181 @@ const decodeConsumeRateLimitResetCreditResponse = Schema.decodeUnknownEffect();it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {+ for (const bufferSize of [undefined, 0, 8] as const) {+ it.effect(+ `bounds callback-only raw retention with buffer size ${bufferSize ?? "default"}`,+ () =>+ Effect.gen(function* () {+ const { stdio, input, output } = yield* makeInMemoryStdio();+ const terminated = yield* Deferred.make<void>();+ const count = 10_000;+ const text = "x".repeat(1024);+ let notificationCount = 0;+ let requestCount = 0;+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({+ stdio,+ ...(bufferSize === undefined+ ? {}+ : {+ rawNotificationBufferSize: bufferSize,+ rawRequestBufferSize: bufferSize,+ }),+ onNotification: () =>+ Effect.sync(() => {+ notificationCount++;+ }),+ onRequest: (request) =>+ Effect.suspend(() => {+ requestCount++;+ return request.id === 0+ ? Effect.fail(+ CodexError.CodexAppServerRequestError.methodNotFound(request.method),+ )+ : Effect.succeed({ ok: true });+ }),+ onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),+ });++ for (let index = 0; index < count; index++) {+ yield* Queue.offer(input, encodeJsonl({ method: "x/stress", params: { index, text } }));+ yield* Queue.offer(+ input,+ encodeJsonl({ id: index, method: "x/request", params: { text } }),+ );+ }+ for (let index = 0; index < count; index++) {+ assert.deepEqual(+ yield* decodeJson(yield* Queue.take(output)),+ index === 0+ ? {+ id: 0,+ error: { code: -32601, message: "Method not found: x/request" },+ }+ : { id: index, result: { ok: true } },+ );+ }+ yield* Queue.end(input);+ yield* Deferred.await(terminated);++ assert.equal(notificationCount, count);+ assert.equal(requestCount, count);+ const notifications = yield* Stream.runCollect(transport.incomingNotifications);+ const requests = yield* Stream.runCollect(transport.incomingRequests);+ const retainedIndexes = Array.from(+ { length: bufferSize ?? 0 },+ (_, offset) => count - (bufferSize ?? 0) + offset,+ );+ assert.deepEqual(+ notifications.map((notification) => notification.params),+ retainedIndexes.map((index) => ({ index, text })),+ );+ assert.deepEqual(+ requests.map((request) => request.id),+ retainedIndexes,+ );+ assert.deepEqual(yield* Queue.clear(output), []);+ assert.deepEqual(yield* Stream.runCollect(transport.incomingNotifications), []);+ assert.deepEqual(yield* Stream.runCollect(transport.incomingRequests), []);+ }),+ );+ }++ it.effect("preserves opt-in late replay after raw readers are interrupted", () =>+ Effect.gen(function* () {+ const { stdio, input } = yield* makeInMemoryStdio();+ const notificationObserved = yield* Deferred.make<void>();+ const requestObserved = yield* Deferred.make<void>();+ const terminated = yield* Deferred.make<void>();+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({+ stdio,+ rawNotificationBufferSize: "unbounded",+ rawRequestBufferSize: "unbounded",+ onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),+ });+ const notificationReader = yield* transport.incomingNotifications.pipe(+ Stream.runForEach(() =>+ Deferred.succeed(notificationObserved, undefined).pipe(Effect.andThen(Effect.never)),+ ),+ Effect.forkScoped,+ );+ const requestReader = yield* transport.incomingRequests.pipe(+ Stream.runForEach(() =>+ Deferred.succeed(requestObserved, undefined).pipe(Effect.andThen(Effect.never)),+ ),+ Effect.forkScoped,+ );+ yield* Queue.offer(input, encodeJsonl({ method: "x/first" }));+ yield* Queue.offer(input, encodeJsonl({ id: 1, method: "x/first" }));+ yield* Deferred.await(notificationObserved);+ yield* Deferred.await(requestObserved);+ yield* Fiber.interrupt(notificationReader);+ yield* Fiber.interrupt(requestReader);++ for (const id of [2, 3]) {+ yield* Queue.offer(input, encodeJsonl({ method: "x/next", params: id }));+ yield* Queue.offer(input, encodeJsonl({ id, method: "x/next" }));+ }+ yield* Queue.end(input);+ yield* Deferred.await(terminated);+ assert.deepEqual(+ (yield* Stream.runCollect(transport.incomingNotifications)).map(+ (notification) => notification.params,+ ),+ [2, 3],+ );+ assert.deepEqual(+ (yield* Stream.runCollect(transport.incomingRequests)).map((request) => request.id),+ [2, 3],+ );+ assert.deepEqual(yield* Stream.runCollect(transport.incomingNotifications), []);+ assert.deepEqual(yield* Stream.runCollect(transport.incomingRequests), []);+ }),+ );++ it.effect("drains raw observations and completes waiting readers on decode failure", () =>+ Effect.gen(function* () {+ const { stdio, input } = yield* makeInMemoryStdio();+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({+ stdio,+ rawNotificationBufferSize: 8,+ rawRequestBufferSize: 8,+ });+ const notifications = yield* transport.incomingNotifications.pipe(+ Stream.runCollect,+ Effect.forkScoped,+ );+ const requests = yield* transport.incomingRequests.pipe(Stream.runCollect, Effect.forkScoped);+ yield* Queue.offer(input, encodeJsonl({ method: "x/first" }));+ yield* Queue.offer(input, encodeJsonl({ id: 1, method: "x/first" }));+ yield* Queue.offer(input, encoder.encode("{malformed}\n"));+ assert.deepEqual(yield* Fiber.join(notifications), [{ method: "x/first" }]);+ assert.deepEqual(yield* Fiber.join(requests), [{ id: 1, method: "x/first" }]);+ }),+ );++ it.effect("interrupts raw readers outside the connection scope when it closes", () =>+ Effect.gen(function* () {+ const { stdio } = yield* makeInMemoryStdio();+ const scope = yield* Scope.make();+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({+ stdio,+ rawNotificationBufferSize: 8,+ rawRequestBufferSize: 8,+ }).pipe(Effect.provideService(Scope.Scope, scope));+ const notifications = yield* transport.incomingNotifications.pipe(+ Stream.runCollect,+ Effect.forkScoped({ startImmediately: true }),+ );+ const requests = yield* transport.incomingRequests.pipe(+ Stream.runCollect,+ Effect.forkScoped({ startImmediately: true }),+ );+ yield* Scope.close(scope, Exit.void);+ assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(notifications)));+ assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(requests)));+ }),+ );+it.effect("maps account usage responses to the upstream token usage schema", () =>Effect.gen(function* () {assert.strictEqual(@@ -133,7 +310,11 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {() =>Effect.gen(function* () {const { stdio, input, output } = yield* makeInMemoryStdio();- const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({+ stdio,+ rawNotificationBufferSize: "unbounded",+ rawRequestBufferSize: "unbounded",+ });const notificationDeferred =yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.tsindex 17bfaed2b..c420a73db 100644--- a/packages/effect-codex-app-server/src/protocol.ts+++ b/packages/effect-codex-app-server/src/protocol.ts@@ -34,6 +34,18 @@ export interface CodexAppServerIncomingRequest {export interface CodexAppServerPatchedProtocolOptions {readonly stdio: Stdio.Stdio;readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;+ /**+ * Enables raw notification observation. Zero (the default) returns an empty stream.+ * A positive integer retains the newest N unread events, dropping the oldest on overflow.+ * "unbounded" preserves the legacy lossless FIFO, including all events before a late reader.+ * Buffers never block callback dispatch; finite buffers can also drop events for slow readers.+ */+ readonly rawNotificationBufferSize?: number | "unbounded";+ /**+ * Enables raw request observation with the same buffering rules as rawNotificationBufferSize.+ * Observation does not replace onRequest or send replies; finite buffers can drop requests.+ */+ readonly rawRequestBufferSize?: number | "unbounded";readonly logIncoming?: boolean;readonly logOutgoing?: boolean;readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;@@ -47,7 +59,15 @@ export interface CodexAppServerPatchedProtocolOptions {}export interface CodexAppServerPatchedProtocol {+ /**+ * Opt-in FIFO shared by readers, not a broadcast. Disabled streams end immediately.+ * Enabled streams drain on input termination; scope closure discards the buffer and interrupts readers.+ */readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;+ /**+ * Opt-in request observation with the same stream lifecycle as incomingNotifications.+ * Reading does not send a reply or disable onRequest.+ */readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;readonly request: (method: string,@@ -148,13 +168,34 @@ const toProtocolMessage = (...(fields.error !== undefined ? { error: fields.error } : {}),});+const makeRawQueue = Effect.fn("makeRawQueue")(function* <A>(bufferSize: number | "unbounded" = 0) {+ if (bufferSize === 0) {+ return undefined;+ }+ if (bufferSize !== "unbounded" && (!Number.isSafeInteger(bufferSize) || bufferSize < 0)) {+ return yield* Effect.die(+ new RangeError("Raw buffer size must be a non-negative safe integer or 'unbounded'."),+ );+ }+ return yield* Effect.acquireRelease(+ Queue.sliding<A, Cause.Done<void>>(+ bufferSize === "unbounded" ? Number.POSITIVE_INFINITY : bufferSize,+ ),+ Queue.shutdown,+ );+});+export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(function* (options: CodexAppServerPatchedProtocolOptions,): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();- const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();- const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();+ const incomingNotifications = yield* makeRawQueue<CodexAppServerIncomingNotification>(+ options.rawNotificationBufferSize,+ );+ const incomingRequests = yield* makeRawQueue<CodexAppServerIncomingRequest>(+ options.rawRequestBufferSize,+ );const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());const nextRequestId = yield* Ref.make(1);const remainder = yield* Ref.make("");@@ -190,6 +231,12 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa}return [Effect.gen(function* () {+ if (incomingNotifications) {+ yield* Queue.end(incomingNotifications);+ }+ if (incomingRequests) {+ yield* Queue.end(incomingRequests);+ }const error = yield* classify();yield* failAllPending(error);yield* Queue.end(outgoing);@@ -270,7 +317,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa};const handleRequest = (request: CodexAppServerIncomingRequest) =>- Queue.offer(incomingRequests, request).pipe(+ (incomingRequests ? Queue.offer(incomingRequests, request) : Effect.void).pipe(Effect.andThen(options.onRequest? options.onRequest(request).pipe(@@ -292,7 +339,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa);const handleNotification = (notification: CodexAppServerIncomingNotification) =>- Queue.offer(incomingNotifications, notification).pipe(+ (incomingNotifications ? Queue.offer(incomingNotifications, notification) : Effect.void).pipe(Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),Effect.asVoid,);@@ -412,8 +459,10 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa});return {- incomingNotifications: Stream.fromQueue(incomingNotifications),- incomingRequests: Stream.fromQueue(incomingRequests),+ incomingNotifications: incomingNotifications+ ? Stream.fromQueue(incomingNotifications)+ : Stream.empty,+ incomingRequests: incomingRequests ? Stream.fromQueue(incomingRequests) : Stream.empty,request,notify,respond,