-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcodex-app-server-agent.test.ts
More file actions
3148 lines (2873 loc) · 107 KB
/
Copy pathcodex-app-server-agent.test.ts
File metadata and controls
3148 lines (2873 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
AgentSideConnection,
InitializeRequest,
NewSessionRequest,
PromptRequest,
} from "@agentclientprotocol/sdk";
import { describe, expect, it } from "vitest";
import type {
AppServerClientHandlers,
AppServerRpc,
} from "./app-server-client";
import { CodexAppServerAgent } from "./codex-app-server-agent";
import { sandboxPolicyFor } from "./session-config";
// Required-field invariants the native codex app-server enforces on each request.
const REQUIRED_FIELDS: Record<string, string[]> = {
"thread/goal/clear": ["threadId"],
"thread/goal/get": ["threadId"],
"thread/goal/set": ["threadId"],
"turn/interrupt": ["threadId", "turnId"],
"turn/steer": ["threadId", "input", "expectedTurnId"],
};
function requiredFieldMissing(
method: string,
params: unknown,
): string | undefined {
const p = (params ?? {}) as Record<string, unknown>;
return REQUIRED_FIELDS[method]?.find(
(f) => p[f] === undefined || p[f] === null || p[f] === "",
);
}
function makeStubRpc(responses: Record<string, unknown>) {
let handlers: AppServerClientHandlers | undefined;
const requests: Array<{ method: string; params?: unknown }> = [];
const rpc: AppServerRpc = {
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
requests.push({ method, params });
// Enforce the schema contract so a dropped required field fails loudly, not as a CI false-green.
const missing = requiredFieldMissing(method, params);
if (missing) {
throw {
code: -32600,
message: `Invalid request: missing field \`${missing}\``,
};
}
const response = responses[method];
return (
typeof response === "function"
? await response(params)
: (response ?? {})
) as T;
},
notify() {},
async close() {},
};
return {
requests,
factory(captured: AppServerClientHandlers): AppServerRpc {
handlers = captured;
return rpc;
},
emit(method: string, params: unknown) {
handlers?.onNotification?.(method, params);
},
invokeRequest(method: string, params: unknown): Promise<unknown> {
if (!handlers?.onRequest) throw new Error("no onRequest handler");
return handlers.onRequest(method, params);
},
triggerClose() {
handlers?.onClose?.();
},
};
}
function makeFakeClient(
outcome: unknown = { outcome: "selected", optionId: "allow" },
) {
const sessionUpdates: unknown[] = [];
const extNotifications: Array<{ method: string; params: unknown }> = [];
const client = {
sessionUpdate: async (notification: unknown) => {
sessionUpdates.push(notification);
},
requestPermission: async () => ({ outcome }),
extNotification: async (method: string, params: unknown) => {
extNotifications.push({ method, params });
},
} as unknown as AgentSideConnection;
return { client, sessionUpdates, extNotifications };
}
const init = { protocolVersion: 1 } as unknown as InitializeRequest;
describe("CodexAppServerAgent", () => {
it("runs initialize -> thread/start -> turn/start and streams agent text", async () => {
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
"turn/start": { turn: { id: "turn_1", status: "inProgress" } },
});
const { client, sessionUpdates } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
});
await agent.initialize(init);
const session = await agent.newSession({
cwd: "/repo",
} as unknown as NewSessionRequest);
expect(session.sessionId).toBe("thr_1");
const promptDone = agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: "hello" }],
} as unknown as PromptRequest);
stub.emit("item/agentMessage/delta", { itemId: "i1", delta: "Hi there" });
stub.emit("turn/completed", {
turn: { id: "turn_1", status: "completed" },
});
const result = await promptDone;
expect(result.stopReason).toBe("end_turn");
expect(sessionUpdates).toContainEqual({
sessionId: "thr_1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Hi there" },
},
});
const turnStart = stub.requests.find((r) => r.method === "turn/start");
expect(turnStart?.params).toMatchObject({
threadId: "thr_1",
input: [{ type: "text", text: "hello" }],
});
});
it("isolates subagent output, usage, compaction, and completion", async () => {
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
"turn/start": { turn: { id: "turn_1", status: "inProgress" } },
});
const { client, sessionUpdates, extNotifications } = makeFakeClient();
const structuredOutputs: Array<Record<string, unknown>> = [];
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
onStructuredOutput: async (output) => {
structuredOutputs.push(output);
},
});
const schema = {
type: "object",
properties: { source: { type: "string" } },
required: ["source"],
};
await agent.initialize(init);
await agent.newSession({
cwd: "/repo",
_meta: {
environment: "cloud",
jsonSchema: schema,
taskRunId: "run_1",
},
} as unknown as NewSessionRequest);
const promptDone = agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: "delegate this" }],
} as unknown as PromptRequest);
stub.emit("item/started", {
threadId: "thr_1",
turnId: "turn_1",
item: {
type: "collabAgentToolCall",
id: "spawn_1",
tool: "spawnAgent",
status: "inProgress",
senderThreadId: "thr_1",
receiverThreadIds: ["subagent_1"],
prompt: "Review the implementation",
},
});
const sessionUpdateCount = sessionUpdates.length;
const extNotificationCount = extNotifications.length;
stub.emit("item/agentMessage/delta", {
threadId: "subagent_1",
turnId: "subagent_turn_1",
itemId: "subagent_message_1",
delta: "subagent prose",
});
stub.emit("item/reasoning/textDelta", {
threadId: "subagent_1",
turnId: "subagent_turn_1",
itemId: "subagent_reasoning_1",
delta: "subagent reasoning",
});
stub.emit("item/completed", {
threadId: "subagent_1",
turnId: "subagent_turn_1",
item: {
type: "agentMessage",
id: "subagent_message_1",
text: '{"source":"child"}',
},
});
stub.emit("item/commandExecution/outputDelta", {
threadId: "subagent_1",
turnId: "subagent_turn_1",
itemId: "shared_command_id",
delta: "child command output",
});
stub.emit("thread/tokenUsage/updated", {
threadId: "subagent_1",
tokenUsage: {
total: { totalTokens: 9000 },
modelContextWindow: 10000,
},
});
stub.emit("item/started", {
threadId: "subagent_1",
turnId: "subagent_turn_1",
item: { type: "contextCompaction", id: "subagent_compaction_1" },
});
stub.emit("item/completed", {
threadId: "subagent_1",
turnId: "subagent_turn_1",
item: { type: "contextCompaction", id: "subagent_compaction_1" },
});
stub.emit("turn/completed", {
threadId: "subagent_1",
turn: { id: "subagent_turn_1", status: "completed" },
});
let promptSettled = false;
void promptDone.then(() => {
promptSettled = true;
});
await Promise.resolve();
expect({
extNotifications: extNotifications.length,
promptSettled,
sessionUpdates: sessionUpdates.length,
}).toEqual({
extNotifications: extNotificationCount,
promptSettled: false,
sessionUpdates: sessionUpdateCount,
});
stub.emit("item/agentMessage/delta", {
threadId: "thr_1",
turnId: "turn_1",
itemId: "message_1",
delta: "parent response",
});
stub.emit("item/completed", {
threadId: "thr_1",
turnId: "turn_1",
item: {
type: "commandExecution",
id: "shared_command_id",
command: "echo parent",
status: "completed",
aggregatedOutput: null,
},
});
stub.emit("item/completed", {
threadId: "thr_1",
turnId: "turn_1",
item: {
type: "agentMessage",
id: "message_1",
text: '{"source":"parent"}',
},
});
stub.emit("turn/completed", {
threadId: "thr_1",
turn: { id: "turn_1", status: "completed" },
});
await expect(promptDone).resolves.toMatchObject({ stopReason: "end_turn" });
const serializedUpdates = JSON.stringify(sessionUpdates);
expect(serializedUpdates).toContain("spawn_agent");
expect(serializedUpdates).toContain("parent response");
expect(serializedUpdates).not.toContain("subagent prose");
expect(serializedUpdates).not.toContain("subagent reasoning");
expect(serializedUpdates).not.toContain("child command output");
expect(structuredOutputs).toEqual([{ source: "parent" }]);
expect(
extNotifications.filter(
(notification) => notification.method === "_posthog/turn_complete",
),
).toHaveLength(1);
});
it.each([
{
label: "reads an empty goal",
prompt: "/goal",
method: "thread/goal/get",
response: { goal: null },
expectedParams: { threadId: "thr_1" },
expectedText: "No goal set. Usage: `/goal <objective>`",
expectedGoal: undefined,
},
{
label: "reads an active goal",
prompt: "/goal",
method: "thread/goal/get",
response: { goal: { objective: "Ship the fix", status: "active" } },
expectedParams: { threadId: "thr_1" },
expectedText: "Goal active: Ship the fix",
expectedGoal: undefined,
},
{
label: "sets a goal",
prompt: "/goal Ship the fix",
method: "thread/goal/set",
response: { goal: { objective: "Ship the fix", status: "active" } },
expectedParams: { threadId: "thr_1", objective: "Ship the fix" },
expectedText: "Goal set: Ship the fix",
expectedGoal: { objective: "Ship the fix", status: "active" },
},
{
label: "clears a goal",
prompt: "/goal clear",
method: "thread/goal/clear",
response: { cleared: true },
expectedParams: { threadId: "thr_1" },
expectedText: "Goal cleared.",
expectedGoal: null,
},
{
label: "pauses a goal",
prompt: "/goal pause",
method: "thread/goal/set",
response: { goal: { objective: "Ship the fix", status: "paused" } },
expectedParams: { threadId: "thr_1", status: "paused" },
expectedText: "Goal paused: Ship the fix",
expectedGoal: { objective: "Ship the fix", status: "paused" },
},
{
label: "resumes a goal",
prompt: "/goal resume",
method: "thread/goal/set",
response: { goal: { objective: "Ship the fix", status: "active" } },
expectedParams: { threadId: "thr_1", status: "active" },
expectedText: "Goal resumed: Ship the fix",
expectedGoal: { objective: "Ship the fix", status: "active" },
},
])("$label without starting a model turn", async (testCase) => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
[testCase.method]: testCase.response,
});
const { client, sessionUpdates, extNotifications } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
rpcFactory: stub.factory,
});
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
const result = await agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: testCase.prompt }],
} as unknown as PromptRequest);
expect(result.stopReason).toBe("end_turn");
expect(stub.requests).toContainEqual({
method: testCase.method,
params: testCase.expectedParams,
});
expect(
stub.requests.some((request) => request.method === "turn/start"),
).toBe(false);
expect(sessionUpdates).toContainEqual({
sessionId: "thr_1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: testCase.expectedText },
},
});
if (testCase.expectedGoal !== undefined) {
expect(extNotifications).toContainEqual({
method: "_posthog/codex_goal",
params: { goal: testCase.expectedGoal },
});
}
});
it("handles a goal command wrapped in hidden cold-resume context", async () => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
"thread/goal/get": {
goal: { objective: "Ship the fix", status: "paused" },
},
});
const { client, sessionUpdates } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
rpcFactory: stub.factory,
});
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
await agent.prompt({
sessionId: "thr_1",
prompt: [
{
type: "text",
text: "Previous conversation context",
_meta: { ui: { hidden: true } },
},
{ type: "text", text: "/goal" },
{
type: "text",
text: "Respond to the user above",
_meta: { ui: { hidden: true } },
},
],
} as unknown as PromptRequest);
expect(stub.requests).toContainEqual({
method: "thread/goal/get",
params: { threadId: "thr_1" },
});
expect(
stub.requests.some((request) => request.method === "turn/start"),
).toBe(false);
expect(sessionUpdates).toContainEqual({
sessionId: "thr_1",
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "/goal" },
},
});
});
it("restores a persisted goal when starting a replacement thread", async () => {
const restoredGoal = { objective: "Ship the fix", status: "paused" };
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
"thread/goal/set": { goal: restoredGoal },
});
const { client, extNotifications } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
rpcFactory: stub.factory,
});
await agent.newSession({
cwd: "/repo",
_meta: { nativeGoal: restoredGoal },
} as unknown as NewSessionRequest);
expect(stub.requests).toContainEqual({
method: "thread/goal/set",
params: { threadId: "thr_1", ...restoredGoal },
});
expect(extNotifications).toContainEqual({
method: "_posthog/codex_goal",
params: { goal: restoredGoal },
});
});
it("interrupts a native goal turn that was already queued when paused", async () => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
"thread/goal/set": {
goal: { objective: "Ship the fix", status: "paused" },
},
});
const { client } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
rpcFactory: stub.factory,
});
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
await agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: "/goal pause" }],
} as unknown as PromptRequest);
stub.emit("turn/started", { turn: { id: "goal_tick_1" } });
await Promise.resolve();
expect(stub.requests).toContainEqual({
method: "turn/interrupt",
params: { threadId: "thr_1", turnId: "goal_tick_1" },
});
});
it("interrupts a native goal turn that started before it was paused", async () => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
"thread/goal/set": {
goal: { objective: "Ship the fix", status: "paused" },
},
});
const { client } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
rpcFactory: stub.factory,
});
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
stub.emit("turn/started", { turn: { id: "goal_tick_1" } });
await agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: "/goal pause" }],
} as unknown as PromptRequest);
expect(stub.requests).toContainEqual({
method: "turn/interrupt",
params: { threadId: "thr_1", turnId: "goal_tick_1" },
});
});
it("retries queued goal cancellation after an interrupt failure", async () => {
let interruptAttempts = 0;
const stub = makeStubRpc({
"thread/start": { thread: { id: "thr_1" } },
"thread/goal/set": {
goal: { objective: "Ship the fix", status: "paused" },
},
"turn/interrupt": () => {
interruptAttempts++;
if (interruptAttempts === 1) {
throw new Error("interrupt failed");
}
return {};
},
});
const { client } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
rpcFactory: stub.factory,
});
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
await agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: "/goal pause" }],
} as unknown as PromptRequest);
stub.emit("turn/started", { turn: { id: "goal_tick_1" } });
await Promise.resolve();
await Promise.resolve();
stub.emit("turn/started", { turn: { id: "goal_tick_2" } });
await Promise.resolve();
expect(
stub.requests.filter((request) => request.method === "turn/interrupt"),
).toEqual([
{
method: "turn/interrupt",
params: { threadId: "thr_1", turnId: "goal_tick_1" },
},
{
method: "turn/interrupt",
params: { threadId: "thr_1", turnId: "goal_tick_2" },
},
]);
});
it("includes buffered command output when completion omits aggregatedOutput", async () => {
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
});
const { client, sessionUpdates } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
});
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
stub.emit("item/commandExecution/outputDelta", {
itemId: "cmd_1",
delta: "https://github.com/PostHog/posthog/p",
});
stub.emit("item/commandExecution/outputDelta", {
itemId: "cmd_1",
delta: "ull/12345\n",
});
stub.emit("item/completed", {
item: {
type: "commandExecution",
id: "cmd_1",
command: "gh pr create --draft",
status: "completed",
aggregatedOutput: null,
},
});
expect(sessionUpdates).toContainEqual({
sessionId: "thr_1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "cmd_1",
status: "completed",
content: [
{
type: "content",
content: {
type: "text",
text: "https://github.com/PostHog/posthog/pull/12345\n",
},
},
],
},
});
});
it("enriches an MCP tool-call approval with the structured posthog channel", async () => {
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
});
const permissionToolCalls: unknown[] = [];
const client = {
sessionUpdate: async () => {},
requestPermission: async (params: { toolCall: unknown }) => {
permissionToolCalls.push(params.toolCall);
return { outcome: { outcome: "selected", optionId: "allow" } };
},
extNotification: async () => {},
} as unknown as AgentSideConnection;
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
});
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
// The MCP tool call item arrives first, then codex approves it via a command-execution request.
stub.emit("item/started", {
item: {
type: "mcpToolCall",
id: "m1",
server: "posthog",
tool: "exec",
arguments: { command: "call execute-sql {}" },
},
});
const decision = await stub.invokeRequest(
"item/commandExecution/requestApproval",
{
itemId: "m1",
command: 'Allow the posthog MCP server to run tool "exec"?',
},
);
expect(decision).toEqual({ decision: "accept" });
expect(permissionToolCalls).toHaveLength(1);
expect(permissionToolCalls[0]).toMatchObject({
toolCallId: "m1",
kind: "other",
rawInput: { command: "call execute-sql {}" },
_meta: {
posthog: {
toolName: "mcp__posthog__exec",
mcp: { server: "posthog", tool: "exec" },
},
},
});
});
it("enriches the MCP elicitation approval (posthog exec) from the in-flight tool call", async () => {
// codex gates PostHog `exec` behind a generic elicitation (serverName only, no tool/args);
// the adapter correlates it to the in-flight mcpToolCall so the real tool + command render.
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
});
const permissionToolCalls: Array<Record<string, unknown>> = [];
const client = {
sessionUpdate: async () => {},
requestPermission: async (params: {
toolCall: Record<string, unknown>;
}) => {
permissionToolCalls.push(params.toolCall);
return { outcome: { outcome: "selected", optionId: "accept" } };
},
extNotification: async () => {},
} as unknown as AgentSideConnection;
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
});
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
stub.emit("item/started", {
item: {
type: "mcpToolCall",
id: "m1",
server: "posthog",
tool: "exec",
arguments: { command: "call execute-sql {}" },
},
});
const decision = await stub.invokeRequest("mcpServer/elicitation/request", {
threadId: "thr_1",
turnId: "turn_1",
serverName: "posthog",
mode: "form",
message: 'Allow the posthog MCP server to run tool "exec"?',
});
expect(decision).toMatchObject({ action: "accept" });
expect(permissionToolCalls[0]).toMatchObject({
toolCallId: "posthog:elicitation",
rawInput: { command: "call execute-sql {}" },
_meta: {
posthog: {
toolName: "mcp__posthog__exec",
mcp: { server: "posthog", tool: "exec" },
},
},
});
});
function makeApprovalAgent(chooseOptionId = "allow") {
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
});
const permissionToolCalls: Array<Record<string, unknown>> = [];
const permissionOptions: Array<
Array<{ optionId?: string; kind?: string }>
> = [];
const client = {
sessionUpdate: async () => {},
requestPermission: async (params: {
toolCall: Record<string, unknown>;
options: Array<{ optionId?: string; kind?: string }>;
}) => {
permissionToolCalls.push(params.toolCall);
permissionOptions.push(params.options);
return { outcome: { outcome: "selected", optionId: chooseOptionId } };
},
extNotification: async () => {},
} as unknown as AgentSideConnection;
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/bundle/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
});
return { agent, stub, permissionToolCalls, permissionOptions };
}
it("routes a non-MCP command approval to an execute permission (kind + command body)", async () => {
// kind:"execute" + command text content makes the host render ExecutePermission (not the fallback).
const { agent, stub, permissionToolCalls } = makeApprovalAgent();
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
await stub.invokeRequest("item/commandExecution/requestApproval", {
itemId: "c1",
command: "rm -rf build",
});
expect(permissionToolCalls).toHaveLength(1);
expect(permissionToolCalls[0]).toEqual({
toolCallId: "c1",
title: "rm -rf build",
kind: "execute",
content: [
{ type: "content", content: { type: "text", text: "rm -rf build" } },
],
});
});
it("surfaces Allow-always and echoes codex's execpolicy amendment decision verbatim", async () => {
const { agent, stub, permissionOptions } =
makeApprovalAgent("allow_always");
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
// codex offers the command-prefix allowlist decision for this approval. Exact
// 0.140 wire shape: serde renames only the VARIANT to camelCase, the field
// stays snake_case, and ExecPolicyAmendment is transparent over a string array.
const amendment = {
acceptWithExecpolicyAmendment: {
execpolicy_amendment: ["pnpm", "test"],
},
};
const decision = await stub.invokeRequest(
"item/commandExecution/requestApproval",
{
itemId: "c1",
command: "pnpm test",
availableDecisions: ["accept", amendment, "decline"],
},
);
expect(permissionOptions[0].map((o) => o.kind)).toContain("allow_always");
// Picking it echoes codex's own decision entry verbatim (same reference, no remapping).
expect((decision as { decision: unknown }).decision).toBe(amendment);
});
it("surfaces Allow-always for the session-scoped command decision", async () => {
const { agent, stub, permissionOptions } =
makeApprovalAgent("allow_always");
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
const decision = await stub.invokeRequest(
"item/commandExecution/requestApproval",
{
itemId: "c1",
command: "pnpm test",
availableDecisions: ["accept", "acceptForSession", "decline"],
},
);
expect(permissionOptions[0].map((o) => o.kind)).toContain("allow_always");
expect(decision).toEqual({ decision: "acceptForSession" });
});
it("omits Allow-always when codex offers no remember decision for a command", async () => {
const { agent, stub, permissionOptions } = makeApprovalAgent("allow");
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
const decision = await stub.invokeRequest(
"item/commandExecution/requestApproval",
{ itemId: "c1", command: "ls" },
);
expect(permissionOptions[0].map((o) => o.kind)).not.toContain(
"allow_always",
);
expect(permissionOptions[0].map((o) => o.optionId)).toEqual([
"allow",
"reject",
"reject_with_feedback",
]);
expect(decision).toEqual({ decision: "accept" });
});
it("always offers Allow-always on file changes and answers acceptForSession", async () => {
const { agent, stub, permissionOptions } =
makeApprovalAgent("allow_always");
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
// File-change approvals carry no availableDecisions, but codex always
// accepts the session-scoped decision for them.
const decision = await stub.invokeRequest(
"item/fileChange/requestApproval",
{
itemId: "f1",
changes: [{ path: "src/a.ts", diff: "@@ -1 +1 @@\n-old\n+new\n" }],
},
);
expect(permissionOptions[0].map((o) => o.kind)).toContain("allow_always");
expect(decision).toEqual({ decision: "acceptForSession" });
});
it("honors an explicit file-change decision list without a remember option", async () => {
const { agent, stub, permissionOptions } = makeApprovalAgent("allow");
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
const decision = await stub.invokeRequest(
"item/fileChange/requestApproval",
{
itemId: "f1",
changes: [{ path: "src/a.ts", diff: "@@ -1 +1 @@\n-old\n+new\n" }],
availableDecisions: ["accept", "decline"],
},
);
expect(permissionOptions[0].map((o) => o.kind)).not.toContain(
"allow_always",
);
expect(decision).toEqual({ decision: "accept" });
});
it("reject-with-feedback declines and steers the user's guidance into the running turn", async () => {
const stub = makeStubRpc({
initialize: {},
"thread/start": { thread: { id: "thr_1" } },
"turn/start": { turn: { id: "turn_1" } },
// codex rotates the turn id on steer.
"turn/steer": { turnId: "turn_2" },
});
const offeredOptions: Array<Array<{ optionId?: string; kind?: string }>> =
[];
const client = {
sessionUpdate: async () => {},
requestPermission: async (params: {
options: Array<{ optionId?: string; kind?: string }>;
}) => {
offeredOptions.push(params.options);
return {
outcome: { outcome: "selected", optionId: "reject_with_feedback" },
_meta: { customInput: "use the SDK instead of shelling out" },
};
},
extNotification: async () => {},
} as unknown as AgentSideConnection;
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/x/codex" },
model: "gpt-5.5",
rpcFactory: stub.factory,
});
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
// Start a turn so there's a live turnId for the steer to target.
const done = agent.prompt({
sessionId: "thr_1",
prompt: [{ type: "text", text: "go" }],
} as unknown as PromptRequest);
stub.emit("turn/started", { turn: { id: "turn_1" } });
// codex asks to run a command mid-turn; user rejects with guidance.
const decision = await stub.invokeRequest(
"item/commandExecution/requestApproval",
{ itemId: "c1", command: "rm -rf build" },
);
expect(decision).toEqual({ decision: "decline" });
const feedbackOpt = offeredOptions[0].find(
(o) => o.optionId === "reject_with_feedback",
);
expect(feedbackOpt).toBeTruthy();
// The guidance was steered into the running turn as a follow-up message.
const steer = stub.requests.find((r) => r.method === "turn/steer");
expect((steer?.params as { expectedTurnId?: string })?.expectedTurnId).toBe(
"turn_1",
);
// The rotated turn id from the steer response was adopted: a second
// rejection targets turn_2, not the dead turn_1.
await new Promise((r) => setImmediate(r));
await stub.invokeRequest("item/commandExecution/requestApproval", {
itemId: "c2",
command: "rm -rf dist",
});
const steers = stub.requests.filter((r) => r.method === "turn/steer");
expect(
(steers[1]?.params as { expectedTurnId?: string })?.expectedTurnId,
).toBe("turn_2");
stub.emit("turn/completed", { turn: { status: "completed" } });
await done;
});
it("routes a non-MCP file-change approval to an edit permission (kind + diff + locations)", async () => {
const { agent, stub, permissionToolCalls } = makeApprovalAgent();
await agent.initialize(init);
await agent.newSession({ cwd: "/repo" } as unknown as NewSessionRequest);
await stub.invokeRequest("item/fileChange/requestApproval", {
itemId: "f1",
changes: [{ path: "src/a.ts", diff: "@@ -1 +1 @@\n-old\n+new\n" }],
});
expect(permissionToolCalls).toHaveLength(1);
const tc = permissionToolCalls[0];
expect(tc.kind).toBe("edit");
expect(tc.locations).toEqual([{ path: "src/a.ts" }]);
// A diff content block so the host's EditPermission renders the change.
expect(Array.isArray(tc.content)).toBe(true);
expect((tc.content as Array<{ type?: string }>)[0]?.type).toBe("diff");
});
it("passes outputSchema to turn/start and fires onStructuredOutput", async () => {
const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
const { client } = makeFakeClient();
const outputs: Array<Record<string, unknown>> = [];
const schema = {
type: "object",
properties: { repo: { type: "string" } },
required: ["repo"],
};
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/x/codex" },
rpcFactory: stub.factory,
onStructuredOutput: async (o) => {
outputs.push(o);
},