perf(server): cut idle CPU use and stop provider event leaks (#8187)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-09-01 02:12:35 -07:00
1 parent a9ffb82796
commit 0bfb6df34b
19 files changed
+913 -98

No files matched your search

@@ -973,6 +973,29 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("ignores provider content deltas that cannot change thread state", async () => {
const harness = await createHarness();
const initial = await harness.readModel();
for (const streamKind of ["reasoning_text", "command_output", "file_change_output"] as const) {
harness.emit({
type: "content.delta",
eventId: asEventId(`evt-ignored-${streamKind}`),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-ignored"),
payload: {
streamKind,
delta: "ignored output",
},
});
}
await harness.drain();
expect(await harness.readModel()).toEqual(initial);
});
it("maps canonical content delta/item completed into finalized assistant messages", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -1499,6 +1499,10 @@ const make = Effect.gen(function* () {
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
if (event.type === "content.delta" && event.payload.streamKind !== "assistant_text") {
return;
}
const thread = yield* resolveThreadShell(event.threadId);
if (!thread) return;
@@ -1515,9 +1519,17 @@ const make = Effect.gen(function* () {
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
});
const pendingTurnStart =
event.type === "session.started" ||
event.type === "session.state.changed" ||
event.type === "session.exited" ||
event.type === "thread.started" ||
event.type === "turn.started" ||
event.type === "turn.completed"
? yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
})
: Option.none();
const hasPendingTurnStart =
Option.isSome(pendingTurnStart) && thread.session?.status === "starting";
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { TestClock } from "effect/testing";
import * as ProcessRunner from "../processRunner.ts";
@@ -35,6 +36,89 @@ const makeRepositoryIdentityResolverTestLayer = (options: {
).pipe(Layer.provide(ProcessRunner.layer));
it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
it.effect("reuses the cached Git root for repeated workspace lookups", () => {
const calls: Array<ReadonlyArray<string>> = [];
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
run: (input) =>
Effect.sync(() => {
calls.push(input.args);
return {
stdout: input.args.includes("rev-parse")
? "/repo\n"
: "origin\[email protected]:T3Tools/t3code.git (fetch)\n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
});
const resolverLayer = Layer.effect(
RepositoryIdentityResolver.RepositoryIdentityResolver,
RepositoryIdentityResolver.make(),
).pipe(Layer.provide(processRunner));
return Effect.gen(function* () {
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
const first = yield* resolver.resolve("/repo/packages/web");
const second = yield* resolver.resolve("/repo/packages/web");
expect(first?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(second).toEqual(first);
expect(calls).toEqual([
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
["-C", "/repo", "remote", "-v"],
]);
}).pipe(Effect.provide(resolverLayer));
});
it.effect("retries Git root discovery after a failed lookup", () => {
const calls: Array<ReadonlyArray<string>> = [];
let rootAttempts = 0;
const processRunner = Layer.succeed(ProcessRunner.ProcessRunner, {
run: (input) =>
Effect.sync(() => {
calls.push(input.args);
const rootLookup = input.args.includes("rev-parse");
const failed = rootLookup && rootAttempts++ === 0;
return {
stdout: rootLookup
? failed
? ""
: "/repo\n"
: "origin\[email protected]:T3Tools/t3code.git (fetch)\n",
stderr: failed ? "temporary Git failure" : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
});
const resolverLayer = Layer.effect(
RepositoryIdentityResolver.RepositoryIdentityResolver,
RepositoryIdentityResolver.make(),
).pipe(Layer.provide(processRunner));
return Effect.gen(function* () {
const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
expect(yield* resolver.resolve("/repo/packages/web")).toBeNull();
const recovered = yield* resolver.resolve("/repo/packages/web");
expect(recovered?.rootPath).toBe("/repo");
expect(calls).toEqual([
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"],
["-C", "/repo", "remote", "-v"],
]);
}).pipe(Effect.provide(resolverLayer));
});
it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -90,7 +90,6 @@ function buildRepositoryIdentity(input: {
const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
function* (cwd: string) {
const processRunner = yield* ProcessRunner.ProcessRunner;
let cacheKey = cwd;
// git is a real executable on every platform — no cmd.exe shell mode, which
// would split paths containing spaces during cmd's re-tokenization.
@@ -102,15 +101,11 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.
})
.pipe(Effect.option);
if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
return cacheKey;
return null;
}
const candidate = topLevelResult.value.stdout.trim();
if (candidate.length > 0) {
cacheKey = candidate;
}
return cacheKey;
return candidate.length > 0 ? candidate : null;
},
);
@@ -139,6 +134,22 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
options: RepositoryIdentityResolverOptions = {},
) {
const processRunner = yield* ProcessRunner.ProcessRunner;
const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
const repositoryRootCache = yield* Cache.makeWith<string, string | null>(
(cwd) =>
resolveRepositoryIdentityCacheKey(cwd).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
),
{
capacity: cacheCapacity,
timeToLive: Exit.match({
onSuccess: (value) =>
value === null ? Duration.zero : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
onFailure: () => Duration.zero,
}),
},
);
const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
(cacheKey) =>
@@ -146,7 +157,7 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
),
{
capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
capacity: cacheCapacity,
timeToLive: Exit.match({
onSuccess: (value) =>
value === null
@@ -160,9 +171,8 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fn(
"RepositoryIdentityResolver.resolve",
)(function* (cwd) {
const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
);
const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
if (cacheKey === null) return null;
return yield* Cache.get(repositoryIdentityCache, cacheKey);
});
@@ -286,7 +286,7 @@ describe("EventNdjsonLogger", () => {
}),
);
it.effect("drops transient canonical events before serialization", () =>
it.effect("drops transient provider events before serialization", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
@@ -302,6 +302,46 @@ describe("EventNdjsonLogger", () => {
yield* canonical.write(circularDelta, threadId);
yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
yield* native.write(
{ method: "item/agentMessage/delta", payload: circularDelta },
threadId,
);
yield* native.write(
{ method: "thread/realtime/outputAudio/delta", payload: circularDelta },
threadId,
);
yield* native.write(
{ method: "thread/realtime/transcript/delta", payload: circularDelta },
threadId,
);
yield* native.write(
{
event: {
method: "claude/stream_event/content_block_delta/text_delta",
payload: circularDelta,
},
},
threadId,
);
yield* native.write(
{
event: {
method: "session/update",
payload: { update: { sessionUpdate: "agent_message_chunk" } },
},
},
threadId,
);
yield* native.write(
{
event: {
type: "message.part.updated",
payload: { properties: { part: { type: "text" } } },
},
},
threadId,
);
yield* native.write({ type: "turn.completed", id: "native-final" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-filtered"), "utf8")
@@ -313,7 +353,7 @@ describe("EventNdjsonLogger", () => {
lines.map(({ stream, payload }) => ({ stream, payload })),
[
{ stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
{ stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
{ stream: "NTIVE", payload: '{"type":"turn.completed","id":"native-final"}' },
],
);
} finally {
@@ -45,6 +45,17 @@ const transientCanonicalEventTypes = new Set([
"tool.progress",
"turn.proposed.delta",
]);
const transientNativeMethods = new Set([
"item/agentMessage/delta",
"item/commandExecution/outputDelta",
"item/fileChange/outputDelta",
"item/plan/delta",
"item/reasoning/summaryTextDelta",
"item/reasoning/textDelta",
"thread/realtime/outputAudio/delta",
"thread/realtime/transcript/delta",
]);
const transientAcpUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
@@ -126,7 +137,7 @@ export interface PendingRecord {
}
interface StoreState {
readonly pending: ReadonlyArray<PendingRecord>;
readonly pending: Array<PendingRecord>;
readonly pendingBytes: number;
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
readonly flushScheduled: boolean;
@@ -178,12 +189,50 @@ function providerLogPath(directory: string, prefix: string, threadSegment: strin
}
function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
if (stream !== "canonical" || typeof event !== "object" || event === null) {
if (stream === "orchestration" || typeof event !== "object" || event === null) {
return true;
}
try {
const type = Reflect.get(event, "type");
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
if (typeof type === "string" && transientCanonicalEventTypes.has(type)) {
return false;
}
if (stream !== "native") return true;
const nested = Reflect.get(event, "event");
const nativeEvent = typeof nested === "object" && nested !== null ? nested : event;
const method = Reflect.get(nativeEvent, "method");
if (
typeof method === "string" &&
(transientNativeMethods.has(method) ||
method.startsWith("claude/stream_event/content_block_delta/"))
) {
return false;
}
const nativeType = Reflect.get(nativeEvent, "type");
if (nativeType === "message.part.delta") return false;
const payload = Reflect.get(nativeEvent, "payload");
if (typeof payload !== "object" || payload === null) return true;
if (method === "session/update") {
const update = Reflect.get(payload, "update");
if (typeof update !== "object" || update === null) return true;
const updateType = Reflect.get(update, "sessionUpdate");
return typeof updateType !== "string" || !transientAcpUpdates.has(updateType);
}
if (nativeType === "message.part.updated") {
const properties = Reflect.get(payload, "properties");
if (typeof properties !== "object" || properties === null) return true;
const part = Reflect.get(properties, "part");
if (typeof part !== "object" || part === null) return true;
const partType = Reflect.get(part, "type");
return partType !== "text" && partType !== "reasoning";
}
return true;
} catch {
return true;
}
@@ -566,10 +615,8 @@ export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
if (state.closed) {
return Effect.succeed([{ flush: false }, state] as const);
}
const pending = [
...state.pending,
{ stream, threadSegment: resolveThreadSegment(threadId), line, bytes },
];
const pending = state.pending;
pending.push({ stream, threadSegment: resolveThreadSegment(threadId), line, bytes });
const pendingBytes = state.pendingBytes + bytes;
const flush =
resolved.batchWindowMs === 0 ||
@@ -4607,12 +4607,27 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hellolo world");
const appendedUpdate = mergeOpenCodeAssistantText("Hello", "Hello world");
const changedUpdate = mergeOpenCodeAssistantText("Hello world", "Hello there");
const staleUpdate = mergeOpenCodeAssistantText("Hello world", "Hello");
NodeAssert.deepEqual(
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
["Hello", "lo world", ""],
);
NodeAssert.equal(secondUpdate.latestText, "Hellolo world");
NodeAssert.deepEqual(appendedUpdate, {
latestText: "Hello world",
deltaToEmit: " world",
});
NodeAssert.deepEqual(changedUpdate, {
latestText: "Hello there",
deltaToEmit: "there",
});
NodeAssert.deepEqual(staleUpdate, {
latestText: "Hello world",
deltaToEmit: "",
});
}),
);
@@ -565,9 +565,13 @@ export function mergeOpenCodeAssistantText(
readonly deltaToEmit: string;
} {
const latestText = resolveLatestAssistantText(previousText, nextText);
const previous = previousText ?? "";
const prefixLength = latestText.startsWith(previous)
? previous.length
: commonPrefixLength(previous, latestText);
return {
latestText,
deltaToEmit: latestText.slice(commonPrefixLength(previousText ?? "", latestText)),
deltaToEmit: latestText.slice(prefixLength),
};
}
@@ -28,6 +28,7 @@ nodeServicesIt("ACP native logging", (it) => {
nativeEventLogger,
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
verboseProtocolLogging: true,
});
const secret = "secret-token-value";
const requestLogger = logger.requestLogger;
@@ -67,6 +68,174 @@ nodeServicesIt("ACP native logging", (it) => {
}),
);
it.effect("keeps request diagnostics without enabling full protocol logging", () =>
Effect.gen(function* () {
const records: Array<unknown> = [];
const makeLogger = yield* makeAcpNativeLoggerFactory();
const logger = makeLogger({
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: (event) => Effect.sync(() => void records.push(event)),
close: () => Effect.void,
},
provider: ProviderDriverKind.make("grok"),
threadId: ThreadId.make("thread-1"),
});
assert.isUndefined(logger.protocolLogging);
const requestLogger = logger.requestLogger;
assert.exists(requestLogger);
if (!requestLogger) return;
yield* requestLogger({
method: "session/prompt",
payload: {},
status: "started",
});
assert.lengthOf(records, 1);
}),
);
it.effect("drops transient ACP chunks before formatting verbose protocol logs", () =>
Effect.gen(function* () {
const records: Array<unknown> = [];
const makeLogger = yield* makeAcpNativeLoggerFactory();
const logger = makeLogger({
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: (event) => Effect.sync(() => void records.push(event)),
close: () => Effect.void,
},
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
verboseProtocolLogging: true,
});
const protocolLogger = logger.protocolLogging?.logger;
assert.exists(protocolLogger);
if (!protocolLogger) return;
for (const updateType of ["agent_message_chunk", "agent_thought_chunk"] as const) {
yield* protocolLogger({
direction: "incoming",
stage: "raw",
payload: `${encodeUnknownJson({
method: "session/update",
params: { update: { sessionUpdate: updateType } },
})}\n`,
});
yield* protocolLogger({
direction: "incoming",
stage: "decoded",
payload: [
{
_tag: "Request",
tag: "session/update",
payload: { update: { sessionUpdate: updateType } },
},
],
});
}
assert.lengthOf(records, 0);
yield* protocolLogger({
direction: "incoming",
stage: "decoded",
payload: [
{
_tag: "Request",
tag: "session/update",
payload: { update: { sessionUpdate: "tool_call" } },
},
],
});
assert.lengthOf(records, 1);
}),
);
it.effect("keeps mixed and incomplete raw diagnostics", () =>
Effect.gen(function* () {
const records: Array<unknown> = [];
const makeLogger = yield* makeAcpNativeLoggerFactory();
const logger = makeLogger({
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: (event) => Effect.sync(() => void records.push(event)),
close: () => Effect.void,
},
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
verboseProtocolLogging: true,
});
const protocolLogger = logger.protocolLogging?.logger;
assert.exists(protocolLogger);
if (!protocolLogger) return;
const transient = encodeUnknownJson({
method: "session/update",
params: { update: { sessionUpdate: "agent_message_chunk" } },
});
const lifecycle = encodeUnknownJson({ method: "session/new", params: {} });
yield* protocolLogger({
direction: "incoming",
stage: "raw",
payload: `${transient}\n${lifecycle}\n`,
});
yield* protocolLogger({
direction: "incoming",
stage: "raw",
payload: transient,
});
yield* protocolLogger({
direction: "incoming",
stage: "raw",
payload: `${transient}\n{malformed}\n`,
});
assert.lengthOf(records, 3);
}),
);
it.effect("filters transient entries from mixed decoded batches", () =>
Effect.gen(function* () {
const records: Array<unknown> = [];
const makeLogger = yield* makeAcpNativeLoggerFactory();
const logger = makeLogger({
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: (event) => Effect.sync(() => void records.push(event)),
close: () => Effect.void,
},
provider: ProviderDriverKind.make("grok"),
threadId: ThreadId.make("thread-1"),
verboseProtocolLogging: true,
});
const protocolLogger = logger.protocolLogging?.logger;
assert.exists(protocolLogger);
if (!protocolLogger) return;
yield* protocolLogger({
direction: "incoming",
stage: "decoded",
payload: [
{
_tag: "Request",
tag: "session/update",
payload: { update: { sessionUpdate: "agent_thought_chunk" } },
},
{
_tag: "Request",
tag: "session/new",
payload: {},
},
],
});
assert.lengthOf(records, 1);
assert.include(encodeUnknownJson(records), '"itemCount":1');
}),
);
it.effect("logs a structural tag when the native writer defects", () => {
const messages: Array<unknown> = [];
const logCapture = Logger.make<unknown, void>(({ message }) => {
@@ -9,6 +9,8 @@ import type * as EffectAcpProtocol from "effect-acp/protocol";
import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const transientProtocolUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
function structuralMethod(value: string): string {
return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
}
@@ -64,12 +66,61 @@ function formatProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent)
};
}
function isTransientProtocolMessage(message: unknown): boolean {
if (typeof message !== "object" || message === null) return false;
const method = Reflect.get(message, "tag") ?? Reflect.get(message, "method");
if (method !== "session/update") return false;
const payload = Reflect.get(message, "payload") ?? Reflect.get(message, "params");
if (typeof payload !== "object" || payload === null) return false;
const update = Reflect.get(payload, "update");
if (typeof update !== "object" || update === null) return false;
const updateType = Reflect.get(update, "sessionUpdate");
return typeof updateType === "string" && transientProtocolUpdates.has(updateType);
}
function rawChunkContainsOnlyTransientMessages(payload: string): boolean {
const lines = payload.split("\n");
const remainder = lines.pop() ?? "";
if (remainder.trim().length > 0) return false;
const messages: Array<unknown> = [];
for (const line of lines) {
if (line.trim().length === 0) continue;
try {
messages.push(JSON.parse(line));
} catch {
return false;
}
}
return messages.length > 0 && messages.every(isTransientProtocolMessage);
}
function filterTransientProtocolLog(
event: EffectAcpProtocol.AcpProtocolLogEvent,
): EffectAcpProtocol.AcpProtocolLogEvent | undefined {
if (event.direction !== "incoming") return event;
if (event.stage === "raw" && typeof event.payload === "string") {
return rawChunkContainsOnlyTransientMessages(event.payload) ? undefined : event;
}
if (event.stage !== "decoded") return event;
if (!Array.isArray(event.payload)) {
return isTransientProtocolMessage(event.payload) ? undefined : event;
}
const payload = event.payload.filter((message) => !isTransientProtocolMessage(message));
return payload.length === 0 ? undefined : { ...event, payload };
}
export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory")(function* () {
const crypto = yield* Crypto.Crypto;
return (input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly provider: ProviderDriverKind;
readonly threadId: ThreadId;
readonly verboseProtocolLogging?: boolean;
}): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
const writeNativeAcpLog = (logInput: {
readonly kind: "request" | "protocol";
@@ -111,16 +162,20 @@ export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory"
kind: "request",
payload: formatRequestLogPayload(event),
}),
...(input.nativeEventLogger
...(input.nativeEventLogger && input.verboseProtocolLogging
? {
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
writeNativeAcpLog({
kind: "protocol",
payload: formatProtocolLogPayload(event),
}),
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) => {
const filtered = filterTransientProtocolLog(event);
return filtered
? writeNativeAcpLog({
kind: "protocol",
payload: formatProtocolLogPayload(filtered),
})
: Effect.void;
},
} satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]>,
}
: {}),
@@ -44,7 +44,7 @@ describe("resolveNativeSampleIntervalMs", () => {
expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 1)).toBe(5_000);
});
it("keeps unknown background telemetry cheap but serves live diagnostics at 1Hz", () => {
it("slows background telemetry and serves live diagnostics at 1Hz", () => {
const unknown: HostPowerSnapshot = {
...basePower,
source: "unknown",
@@ -58,7 +58,8 @@ describe("resolveNativeSampleIntervalMs", () => {
0,
),
).toBe(5_000);
expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(1_000);
expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(5_000);
expect(resolveNativeSampleIntervalMs(basePower, 1)).toBe(1_000);
});
});
@@ -268,7 +268,7 @@ export function resolveNativeSampleIntervalMs(
return CONSTRAINED_SAMPLE_INTERVAL_MS;
}
if (snapshot.onBattery === "true") return BATTERY_SAMPLE_INTERVAL_MS;
return SAMPLE_INTERVAL_MS;
return liveSubscriberCount > 0 ? SAMPLE_INTERVAL_MS : UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS;
}
export function commitCollectionControlUpdate<E, R>(
@@ -462,13 +462,16 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
return Effect.gen(function* () {
const nativeSnapshot = { generation, snapshot: event } satisfies NativeTelemetrySnapshot;
const sampledAt = DateTime.makeUnsafe(event.sampledAtUnixMs);
yield* Ref.update(state, (current) => ({
...current,
status: "healthy" as const,
lastSampleAt: Option.some(sampledAt),
lastError: Option.none(),
}));
yield* publishHealth;
const healthChanged = yield* Ref.modify(state, (current) => [
current.status !== "healthy" || Option.isSome(current.lastError),
{
...current,
status: "healthy" as const,
lastSampleAt: Option.some(sampledAt),
lastError: Option.none(),
},
]);
if (healthChanged) yield* publishHealth;
yield* PubSub.publish(snapshots, nativeSnapshot);
if (event.requestId) {
const deferred = yield* Ref.modify(pendingSamples, (pending) => {
@@ -485,15 +488,18 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
case "historyChunk":
return Effect.gen(function* () {
const latestSnapshot = event.snapshots.at(-1);
yield* Ref.update(state, (current) => ({
...current,
status: "healthy" as const,
lastSampleAt: latestSnapshot
? Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs))
: current.lastSampleAt,
lastError: Option.none(),
}));
yield* publishHealth;
const healthChanged = yield* Ref.modify(state, (current) => [
current.status !== "healthy" || Option.isSome(current.lastError),
{
...current,
status: "healthy" as const,
lastSampleAt: latestSnapshot
? Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs))
: current.lastSampleAt,
lastError: Option.none(),
},
]);
if (healthChanged) yield* publishHealth;
const completed = yield* Ref.modify(pendingHistories, (pending) => {
const request = pending.get(event.requestId);
if (!request) return [Option.none(), pending] as const;
+2 -1
View File
@@ -475,6 +475,7 @@ function trace2ChildKey(record: Record<string, unknown>): string | null {
}
const Trace2Record = Schema.Record(Schema.String, Schema.Unknown);
const decodeTrace2Record = decodeJsonResult(Trace2Record);
const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
@@ -509,7 +510,7 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
return;
}
const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine);
const traceRecord = decodeTrace2Record(trimmedLine);
if (Result.isFailure(traceRecord)) {
yield* Effect.logDebug(
`GitVcsDriver.trace2: failed to parse trace line for ${input.operation} in ${input.cwd} (${input.args.length} arguments)`,
+5 -4
View File
@@ -103,9 +103,9 @@ power-adaptive interval selected by the server. It collects:
- resident and virtual memory;
- cumulative process I/O counters.
On Linux, task/thread enumeration is disabled. Command lines are loaded only
when first needed. This avoids the expensive default behavior of walking every
`/proc/<pid>/task/<tid>` directory on each refresh.
On Linux, task/thread enumeration is disabled. Command lines are refreshed with
each sample so process replacements remain visible. Disabling task enumeration
avoids walking every `/proc/<pid>/task/<tid>` directory on each refresh.
### Process-tree selection
@@ -142,7 +142,8 @@ The server adjusts native sampling without restarting the sidecar:
- suspended, locked, low-power, or serious/critical thermal state: 15 seconds;
- battery: 5 seconds;
- normal AC: 1 second;
- normal AC: 5 seconds in the background and 1 second while live diagnostics is
open;
- unknown or stale power: 5 seconds in the background and 1 second while live
diagnostics is open.
+22 -13
View File
@@ -250,6 +250,10 @@ impl HistoryRecorder {
max_retained_entries: usize,
max_retained_bytes: usize,
) {
let clock_moved_backward = self
.snapshots
.back()
.is_some_and(|previous| previous.sampled_at_unix_ms > snapshot.sampled_at_unix_ms);
let mut retained = snapshot.clone();
retained.request_id = None;
self.retained_entry_count = self
@@ -264,6 +268,7 @@ impl HistoryRecorder {
max_snapshots,
max_retained_entries,
max_retained_bytes,
clock_moved_backward,
);
}
@@ -273,20 +278,24 @@ impl HistoryRecorder {
max_snapshots: usize,
max_retained_entries: usize,
max_retained_bytes: usize,
clock_moved_backward: bool,
) {
let mut future_entry_count = 0usize;
let mut future_bytes = 0usize;
self.snapshots.retain(|snapshot| {
let keep = snapshot.sampled_at_unix_ms <= now_ms;
if !keep {
future_entry_count =
future_entry_count.saturating_add(snapshot.retained_entry_count());
future_bytes = future_bytes.saturating_add(snapshot.estimated_history_bytes());
}
keep
});
self.retained_entry_count = self.retained_entry_count.saturating_sub(future_entry_count);
self.retained_bytes = self.retained_bytes.saturating_sub(future_bytes);
if clock_moved_backward {
let mut future_entry_count = 0usize;
let mut future_bytes = 0usize;
self.snapshots.retain(|snapshot| {
let keep = snapshot.sampled_at_unix_ms <= now_ms;
if !keep {
future_entry_count =
future_entry_count.saturating_add(snapshot.retained_entry_count());
future_bytes = future_bytes.saturating_add(snapshot.estimated_history_bytes());
}
keep
});
self.retained_entry_count =
self.retained_entry_count.saturating_sub(future_entry_count);
self.retained_bytes = self.retained_bytes.saturating_sub(future_bytes);
}
while self.snapshots.front().is_some_and(|snapshot| {
snapshot.sampled_at_unix_ms < now_ms.saturating_sub(HISTORY_RETENTION_MS)
+35
View File
@@ -135,6 +135,41 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
}),
);
it.effect("keeps only recent raw notifications after their callbacks run", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
const handled = yield* Deferred.make<void>();
let handledCount = 0;
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
onNotification: () =>
Effect.sync(() => ++handledCount).pipe(
Effect.flatMap((count) =>
count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
),
),
});
const messages = Array.from({ length: 64 }, (_, index) =>
encodeUnknownJsonString({
jsonrpc: "2.0",
method: "x/performance",
params: { index },
}),
);
yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
yield* Deferred.await(handled);
const retained = yield* transport.incoming.pipe(Stream.take(32), Stream.runCollect);
assert.equal(handledCount, 64);
assert.equal(retained.length, 32);
assert.deepEqual(retained[0]?.params, { index: 32 });
assert.deepEqual(retained[31]?.params, { index: 63 });
}),
);
it.effect("keeps invalid core notification values only in the schema cause", () =>
Effect.gen(function* () {
const secret = "acp-core-notification-secret-sentinel";
+12 -6
View File
@@ -76,6 +76,7 @@ const decodeElicitationComplete = Schema.decodeUnknownEffect(
AcpSchema.ElicitationCompleteNotification,
);
const parserFactory = RpcSerialization.ndJsonRpc();
const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
options: AcpPatchedProtocolOptions,
@@ -83,7 +84,9 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
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* Queue.sliding<AcpIncomingNotification>(
MAX_BUFFERED_RAW_NOTIFICATIONS,
);
const disconnects = yield* Queue.unbounded<number>();
const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
const nextRequestId = yield* Ref.make(1);
@@ -408,11 +411,14 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
yield* options.stdio.stdin.pipe(
Stream.runForEach((data) =>
logProtocol({
direction: "incoming",
stage: "raw",
payload: typeof data === "string" ? data : new TextDecoder().decode(data),
}).pipe(
(options.logIncoming
? logProtocol({
direction: "incoming",
stage: "raw",
payload: typeof data === "string" ? data : new TextDecoder().decode(data),
})
: Effect.void
).pipe(
Effect.flatMap(() =>
Effect.try({
try: () =>
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -398,6 +399,257 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
}),
);
it.effect("keeps only recent raw notifications after their callbacks run", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
const handled = yield* Deferred.make<void>();
let handledCount = 0;
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onNotification: () =>
Effect.sync(() => ++handledCount).pipe(
Effect.flatMap((count) =>
count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
),
),
});
const messages = Array.from({ length: 64 }, (_, index) =>
encodeUnknownJsonString({
method: "item/agentMessage/delta",
params: { index },
}),
);
yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
yield* Deferred.await(handled);
const retained = yield* transport.incomingNotifications.pipe(
Stream.take(32),
Stream.runCollect,
);
assert.equal(handledCount, 64);
assert.equal(retained.length, 32);
assert.deepEqual(retained[0]?.params, { index: 32 });
assert.deepEqual(retained[31]?.params, { index: 63 });
}),
);
it.effect("keeps processing protocol messages while an approval is pending", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const approvalStarted = yield* Deferred.make<void>();
const approvalDecision = yield* Deferred.make<{ readonly decision: string }>();
const notificationReceived = yield* Deferred.make<void>();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onRequest: () =>
Deferred.succeed(approvalStarted, undefined).pipe(
Effect.andThen(Deferred.await(approvalDecision)),
),
onNotification: () => Deferred.succeed(notificationReceived, undefined).pipe(Effect.asVoid),
});
const pendingRequest = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
yield* Queue.take(output);
yield* Queue.offer(
input,
encoder.encode(
`${[
encodeUnknownJsonString({ id: 7, method: "item/tool/requestUserInput", params: {} }),
encodeUnknownJsonString({ method: "item/agentMessage/delta", params: { delta: "ok" } }),
encodeUnknownJsonString({ id: 1, result: { threadId: "thread-1" } }),
].join("\n")}\n`,
),
);
yield* Deferred.await(approvalStarted);
yield* Deferred.await(notificationReceived);
assert.deepEqual(yield* Fiber.join(pendingRequest), { threadId: "thread-1" });
yield* Deferred.succeed(approvalDecision, { decision: "accept" });
assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
id: 7,
result: { decision: "accept" },
});
}),
);
it.effect("rejects incoming requests after the active handler limit is reached", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const handlersStarted = yield* Deferred.make<void>();
const releaseHandlers = yield* Deferred.make<void>();
let activeHandlers = 0;
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onRequest: () =>
Effect.sync(() => ++activeHandlers).pipe(
Effect.flatMap((count) =>
count === 32
? Deferred.succeed(handlersStarted, undefined).pipe(Effect.asVoid)
: Effect.void,
),
Effect.andThen(Deferred.await(releaseHandlers)),
Effect.as({ decision: "accept" }),
),
});
const requests = Array.from({ length: 33 }, (_, index) =>
encodeUnknownJsonString({
id: index + 1,
method: "item/tool/requestUserInput",
params: {},
}),
);
yield* Queue.offer(input, encoder.encode(`${requests.join("\n")}\n`));
yield* Deferred.await(handlersStarted);
assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
id: 33,
error: {
code: -32001,
message: "Too many Codex requests are already active.",
},
});
assert.equal(activeHandlers, 32);
yield* Deferred.succeed(releaseHandlers, undefined);
yield* Effect.forEach(Array.from({ length: 32 }), () => Queue.take(output), {
discard: true,
});
}),
);
it.effect("interrupts pending request handlers when the protocol terminates", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
const approvalStarted = yield* Deferred.make<void>();
const approvalInterrupted = yield* Deferred.make<void>();
const terminated = yield* Deferred.make<void>();
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onRequest: () =>
Deferred.succeed(approvalStarted, undefined).pipe(
Effect.andThen(Effect.never),
Effect.onInterrupt(() =>
Deferred.succeed(approvalInterrupted, undefined).pipe(Effect.asVoid),
),
),
onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),
});
yield* Queue.offer(
input,
encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
);
yield* Deferred.await(approvalStarted);
yield* Queue.end(input);
yield* Deferred.await(approvalInterrupted);
yield* Deferred.await(terminated);
}),
);
it.effect("rejects outgoing messages after an approval response cannot be encoded", () =>
Effect.gen(function* () {
const { stdio: baseStdio, input } = yield* makeInMemoryStdio();
const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
const readerStopped = yield* Deferred.make<void>();
let notificationCount = 0;
let requestCount = 0;
const stdio = Stdio.make({
args: baseStdio.args,
stdin: baseStdio.stdin.pipe(
Stream.ensuring(Deferred.succeed(readerStopped, undefined).pipe(Effect.asVoid)),
),
stdout: baseStdio.stdout,
stderr: baseStdio.stderr,
});
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onRequest: () =>
Effect.sync(() => ++requestCount).pipe(
Effect.map((count) => (count === 1 ? { invalid: 1n } : { ok: true })),
),
onNotification: () => Effect.sync(() => notificationCount++).pipe(Effect.asVoid),
onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
});
yield* Queue.offer(
input,
encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
);
const failure = yield* Deferred.await(terminated);
assert.instanceOf(failure, CodexError.CodexAppServerProtocolParseError);
const requestFailure = yield* transport.request("thread/read", {}).pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: () => assert.fail("Expected a terminated protocol request to fail"),
}),
);
const notificationFailure = yield* transport.notify("initialized").pipe(Effect.flip);
assert.strictEqual(requestFailure, failure);
assert.strictEqual(notificationFailure, failure);
yield* Deferred.await(readerStopped);
yield* Queue.offer(
input,
encoder.encode(
`${[
encodeUnknownJsonString({ method: "x/late-notification" }),
encodeUnknownJsonString({ id: 8, method: "x/late-request" }),
].join("\n")}\n`,
),
);
assert.equal(notificationCount, 0);
assert.equal(requestCount, 1);
assert.equal(yield* Queue.size(input), 1);
}),
);
it.effect("fails pending requests before interrupted handler cleanup completes", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const handlerStarted = yield* Deferred.make<void>();
const finalizerStarted = yield* Deferred.make<void>();
const releaseFinalizer = yield* Deferred.make<void>();
const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onRequest: () =>
Deferred.succeed(handlerStarted, undefined).pipe(
Effect.andThen(Effect.never),
Effect.onInterrupt(() =>
Deferred.succeed(finalizerStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseFinalizer)),
),
),
),
onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
});
const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
yield* Queue.take(output);
yield* Queue.offer(input, encodeJsonl({ id: 7, method: "x/approval" }));
yield* Deferred.await(handlerStarted);
yield* Queue.end(input);
const failure = yield* Deferred.await(terminated);
yield* Deferred.await(finalizerStarted);
const pendingFailure = yield* Fiber.join(pending).pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: () => assert.fail("Expected the pending request to fail"),
}),
);
assert.strictEqual(pendingFailure, failure);
yield* Deferred.succeed(releaseFinalizer, undefined);
}),
);
it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
Effect.gen(function* () {
const { stdio } = yield* makeInMemoryStdio();
@@ -1,6 +1,8 @@
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
@@ -13,6 +15,7 @@ import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
const isJsonRpcId = Schema.is(JsonRpcId);
const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
const MAX_BUFFERED_RAW_MESSAGES = 32;
export interface CodexAppServerProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
@@ -152,13 +155,20 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
function* (
options: CodexAppServerPatchedProtocolOptions,
): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
const protocolScope = yield* Scope.Scope;
const requestHandlerScope = yield* Scope.fork(protocolScope, "parallel");
const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();
const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();
const incomingNotifications =
yield* Queue.sliding<CodexAppServerIncomingNotification>(MAX_BUFFERED_RAW_MESSAGES);
const incomingRequests =
yield* Queue.sliding<CodexAppServerIncomingRequest>(MAX_BUFFERED_RAW_MESSAGES);
const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());
const nextRequestId = yield* Ref.make(1);
const remainder: Array<string> = [];
const terminationHandled = yield* Ref.make(false);
const terminationFailure = yield* Ref.make(Option.none<CodexError.CodexAppServerError>());
const terminationSignal = yield* Deferred.make<void>();
const activeRequestHandlers = yield* Ref.make(0);
const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
if (event.direction === "incoming" && !options.logIncoming) {
@@ -191,8 +201,14 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
return [
Effect.gen(function* () {
const error = yield* classify();
yield* Ref.set(terminationFailure, Option.some(error));
yield* failAllPending(error);
yield* Queue.end(outgoing);
yield* Deferred.succeed(terminationSignal, undefined);
yield* Scope.close(requestHandlerScope, Exit.void).pipe(
Effect.forkIn(protocolScope, { startImmediately: true }),
Effect.asVoid,
);
if (options.onTermination) {
yield* options.onTermination(error);
}
@@ -203,6 +219,9 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
const offerOutgoing = (message: Record<string, unknown>) =>
Effect.gen(function* () {
const failure = yield* Ref.get(terminationFailure);
if (Option.isSome(failure)) return yield* failure.value;
yield* logProtocol({
direction: "outgoing",
stage: "decoded",
@@ -214,7 +233,14 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
stage: "raw",
payload: encoded,
});
yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
const accepted = yield* Queue.offer(outgoing, encoded);
if (!accepted) {
const closed = yield* Ref.get(terminationFailure);
return yield* Option.getOrElse(
closed,
() => new CodexError.CodexAppServerInputStreamEndedError({}),
);
}
});
const removePending = (requestId: string) =>
@@ -271,9 +297,24 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
const handleRequest = (request: CodexAppServerIncomingRequest) =>
Queue.offer(incomingRequests, request).pipe(
Effect.andThen(
options.onRequest
? options.onRequest(request).pipe(
Effect.flatMap(() => {
const handler = options.onRequest;
if (!handler) return Effect.void;
return Ref.modify(activeRequestHandlers, (count) =>
count >= MAX_BUFFERED_RAW_MESSAGES ? [false, count] : [true, count + 1],
).pipe(
Effect.flatMap((accepted) => {
if (!accepted) {
return respondError(
request.id,
CodexError.CodexAppServerRequestError.overloaded(
"Too many Codex requests are already active.",
),
);
}
return handler(request).pipe(
Effect.matchEffect({
onFailure: (error) =>
respondError(
@@ -285,9 +326,21 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
),
onSuccess: (result) => respond(request.id, result),
}),
)
: Effect.void,
),
Effect.ensuring(
Ref.update(activeRequestHandlers, (count) => Math.max(0, count - 1)),
),
Effect.catch((error) =>
handleTermination(() => Effect.succeed(error)).pipe(
Effect.forkIn(protocolScope),
Effect.asVoid,
),
),
Effect.forkIn(requestHandlerScope, { startImmediately: true }),
Effect.asVoid,
);
}),
);
}),
Effect.asVoid,
);
@@ -297,22 +350,13 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
Effect.asVoid,
);
const routeMessage = (
message: unknown,
): Effect.Effect<void, CodexError.CodexAppServerError> => {
if (isIncomingRequest(message)) {
return handleRequest(message);
}
if (isIncomingNotification(message)) {
return handleNotification(message);
}
if (isIncomingResponse(message)) {
return handleResponse(message);
}
return Effect.fail(
CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message),
);
};
const routeMessage = Effect.fnUntraced(function* (message: unknown) {
if (Option.isSome(yield* Ref.get(terminationFailure))) return;
if (isIncomingRequest(message)) return yield* handleRequest(message);
if (isIncomingNotification(message)) return yield* handleNotification(message);
if (isIncomingResponse(message)) return yield* handleResponse(message);
return yield* CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message);
});
const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
if (line.trim().length === 0) {
@@ -352,6 +396,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
};
yield* options.stdio.stdin.pipe(
Stream.interruptWhen(Deferred.await(terminationSignal)),
Stream.decodeText(),
Stream.runForEach((chunk) =>
Effect.sync(() => {