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

protocol.test.ts

223 lines7.2 KB

1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Queue from "effect/Queue";
5import * as Schema from "effect/Schema";
6import * as Stream from "effect/Stream";
7​
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10​
11import * as CodexError from "./errors.ts";
12import * as CodexProtocol from "./protocol.ts";
13import * as CodexRpc from "./rpc.ts";
14import * as CodexSchema from "./schema.ts";
15import { makeInMemoryStdio } from "./_internal/stdio.ts";
16const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
17​
18const encoder = new TextEncoder();
19​
20const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
21​
22const decodeJson = Schema.decodeEffect(Schema.UnknownFromJsonString);
23const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
24 CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
25);
26​
27it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
28 it.effect("maps account usage responses to the upstream token usage schema", () =>
29 Effect.gen(function* () {
30 assert.strictEqual(
31 CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
32 CodexSchema.V2GetAccountTokenUsageResponse,
33 );
34 const decoded = yield* decodeAccountTokenUsageResponse({
35 dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
36 summary: { lifetimeTokens: 42 },
37 });
38 assert.deepEqual(decoded, {
39 dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
40 summary: { lifetimeTokens: 42 },
41 });
42 }),
43 );
44​
45 it.effect(
46 "encodes requests without a jsonrpc field and routes inbound requests and notifications",
47 () =>
48 Effect.gen(function* () {
49 const { stdio, input, output } = yield* makeInMemoryStdio();
50 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
51​
52 const notificationDeferred =
53 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
54 const requestDeferred =
55 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
56​
57 yield* transport.incomingNotifications.pipe(
58 Stream.take(1),
59 Stream.runCollect,
60 Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
61 Effect.forkScoped,
62 );
63​
64 yield* transport.incomingRequests.pipe(
65 Stream.take(1),
66 Stream.runCollect,
67 Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
68 Effect.forkScoped,
69 );
70​
71 yield* transport.notify("initialized");
72 assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
73​
74 const initializeParams = {
75 clientInfo: {
76 name: "effect-codex-app-server-test",
77 title: "Effect Codex App Server Test",
78 version: "0.0.0",
79 },
80 capabilities: {
81 experimentalApi: true,
82 optOutNotificationMethods: null,
83 },
84 };
85​
86 const pendingInitialize = yield* transport
87 .request("initialize", initializeParams)
88 .pipe(Effect.forkScoped);
89 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
90 id: 1,
91 method: "initialize",
92 params: initializeParams,
93 });
94​
95 yield* Queue.offer(
96 input,
97 encodeJsonl({
98 method: "item/agentMessage/delta",
99 params: {
100 delta: "Hello from the mock peer.",
101 itemId: "item-1",
102 threadId: "thread-1",
103 turnId: "turn-1",
104 },
105 }),
106 );
107 yield* Queue.offer(
108 input,
109 encodeJsonl({
110 id: 77,
111 method: "item/tool/requestUserInput",
112 params: {
113 itemId: "item-approval-1",
114 threadId: "thread-1",
115 turnId: "turn-1",
116 questions: [
117 {
118 id: "approved",
119 header: "Approve",
120 question: "Continue?",
121 },
122 ],
123 },
124 }),
125 );
126 yield* Queue.offer(
127 input,
128 encodeJsonl({
129 id: 1,
130 result: {
131 userAgent: "mock-codex-app-server",
132 codexHome: "/tmp/codex-home",
133 platformFamily: "unix",
134 platformOs: "macos",
135 },
136 }),
137 );
138​
139 assert.deepEqual(yield* Fiber.join(pendingInitialize), {
140 userAgent: "mock-codex-app-server",
141 codexHome: "/tmp/codex-home",
142 platformFamily: "unix",
143 platformOs: "macos",
144 });
145 assert.deepEqual(yield* Deferred.await(notificationDeferred), [
146 {
147 method: "item/agentMessage/delta",
148 params: {
149 delta: "Hello from the mock peer.",
150 itemId: "item-1",
151 threadId: "thread-1",
152 turnId: "turn-1",
153 },
154 },
155 ]);
156 assert.deepEqual(yield* Deferred.await(requestDeferred), [
157 {
158 id: 77,
159 method: "item/tool/requestUserInput",
160 params: {
161 itemId: "item-approval-1",
162 threadId: "thread-1",
163 turnId: "turn-1",
164 questions: [
165 {
166 id: "approved",
167 header: "Approve",
168 question: "Continue?",
169 },
170 ],
171 },
172 },
173 ]);
174​
175 yield* transport.respond(77, {
176 answers: {
177 approved: {
178 answers: ["yes"],
179 },
180 },
181 });
182 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
183 id: 77,
184 result: {
185 answers: {
186 approved: {
187 answers: ["yes"],
188 },
189 },
190 },
191 });
192​
193 yield* transport.respondError(
194 78,
195 CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
196 );
197 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
198 id: 78,
199 error: {
200 code: -32601,
201 message: "Method not found: x/test",
202 },
203 });
204 }),
205 );
206​
207 it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
208 Effect.gen(function* () {
209 const { stdio } = yield* makeInMemoryStdio();
210 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
211​
212 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
213 assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
214 assert.equal(bigintError.detail, "Failed to encode Codex App Server message");
215​
216 const circular: Record<string, unknown> = {};
217 circular.self = circular;
218 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
219 assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
220 assert.equal(circularError.detail, "Failed to encode Codex App Server message");
221 }),
222 );
223});