Repository navigation
Expand file tree
/
Copy pathcodex.test.ts
More file actions
3505 lines (3213 loc) · 199 KB
/
Copy pathcodex.test.ts
File metadata and controls
3505 lines (3213 loc) · 199 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 { createHash } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { once } from "node:events";
import { spawn } from "node:child_process";
import { createInterface } from "node:readline";
import { tmpdir } from "node:os";
import { dirname, join, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ProviderInstance, RuntimeEvent } from "../contracts.ts";
import { DATA_DIR, NATIVE_DIR } from "../config.ts";
import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { CodexDriver, codexNativeIncomingLogMessage, codexUpdateCommand } from "./codex.ts";
import { codexCliOverrides } from "./codex-process.ts";
import { CODEX_SIGN_IN_EXPIRED, codexNotSignedIn, codexSignInRefused, codexUserError } from "./codex-errors.ts";
import { CODEX_USAGE_LIMIT_REACHED } from "../../shared/codex-usage-limit.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { TEAM_TOOLS_FAILED } from "./team-tools.ts";
import { rebuiltSessionNotice } from "../resume-recovery.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
import * as procs from "../procs.ts";
import { autoVerdict } from "../auto-approve.ts";
import { formatQuestionAnswers } from "../../shared/ask-question.ts";
vi.mock("./codex-release.ts", async (importOriginal) => ({
...await importOriginal<typeof import("./codex-release.ts")>(),
readLatestCodexRelease: async () => "0.156.1",
}));
const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-codex-app-server.ts");
function processIsAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
const CONTROL_PLANE_FIXTURE = {
OMB_CLOUD_READY_TOKEN: "ready-should-not-leak", OMB_CLOUD_BOOTSTRAP: "bootstrap-should-not-leak",
OMB_LICENSE_KEY: "license-should-not-leak", OMB_INSTALLATION_CREDENTIAL: "fleet-should-not-leak",
};
describe("CodexDriver.decodeConfig", () => {
it("makes plan/provider failures actionable without changing billing", () => {
expect(codexUserError("provider_not_configured", "own")).toContain("Continue with ChatGPT");
expect(codexUserError("provider_not_configured", "plan")).toContain("API billing will not be used");
expect(codexUserError("x".repeat(500) + "subscription_sharing_usage_limit_exceeded", "plan")).toMatch(/^subscription_sharing_usage_limit_exceeded:/);
expect(() => CodexDriver.decodeConfig({ authMode: "chatgpt-plan", managed: {} })).toThrow("cannot be combined");
});
it("defaults to the codex binary with fullAuto off", () => {
expect(CodexDriver.decodeConfig({})).toEqual({ cli: "codex", fullAuto: false });
expect(CodexDriver.decodeConfig(undefined)).toEqual({ cli: "codex", fullAuto: false });
expect(CodexDriver.decodeConfig({ fullAuto: true }).fullAuto).toBe(true);
expect(CodexDriver.decodeConfig({ fullAuto: "yes" }).fullAuto).toBe(false);
});
it("allows Company endpoints over HTTPS, and over HTTP only on loopback", () => {
expect(CodexDriver.decodeConfig({ managed: { url: "https://company.example/v1", models: ["m"] } }))
.toMatchObject({ managed: { url: "https://company.example/v1", models: ["m"] } });
expect(CodexDriver.decodeConfig({ managed: { url: "http://127.0.0.1:1/v1", models: ["m"] } }))
.toMatchObject({ managed: { url: "http://127.0.0.1:1/v1" } });
expect(CodexDriver.decodeConfig({ managed: { url: "http://localhost:1/v1", models: ["m"] } }))
.toMatchObject({ managed: { url: "http://localhost:1/v1" } });
expect(() => CodexDriver.decodeConfig({ managed: { url: "http://company.example/v1", models: ["m"] } }))
.toThrow("Invalid Company Codex endpoint.");
});
});
describe("Codex native diagnostic sanitization", () => {
it("omits a late config/read response even after its pending promise timed out", () => {
const late = {
jsonrpc: "2.0",
id: 17,
result: { config: { mcp_servers: { example: { env: { LABEL: "late-innocuous-secret" } } } } },
};
const logged = codexNativeIncomingLogMessage(late, new Set([17]));
expect(logged).toEqual({ jsonrpc: "2.0", id: 17, result: "[effective config omitted]" });
expect(JSON.stringify(logged)).not.toContain("late-innocuous-secret");
expect(codexNativeIncomingLogMessage({
jsonrpc: "2.0",
id: 17,
error: { code: -1, message: "secret-bearing provider error" },
}, new Set([17]))).toEqual({
jsonrpc: "2.0",
id: 17,
error: "[config/read error omitted]",
});
});
});
// The fake must report what codex-cli 0.160.1's config/read does, or a test pins a policy the driver never meets.
describe("fake app-server shell policy", () => {
const readPolicy = async (args: string[], policy: unknown) => {
const child = spawn(process.execPath, [FAKE_CLI, "app-server", ...args], {
env: { ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("FAKE_CODEX_"))), FAKE_CODEX_SHELL_ENVIRONMENT_POLICY: JSON.stringify(policy) },
stdio: ["pipe", "pipe", "pipe"],
});
try {
const lines = createInterface({ input: child.stdout });
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "config/read", params: { includeLayers: false } })}\n`);
for await (const line of lines) {
const frame = JSON.parse(line);
if (frame.id === 1) return frame.result.config.shell_environment_policy;
}
} finally {
child.kill();
}
};
it("lets a `-c exclude` override drop the lower layers' filters but keep their include_only", async () => {
const policy = await readPolicy(["-c", 'shell_environment_policy.exclude=["OPENMAUSBOT_CHATGPT_TOKEN"]'],
{ filters: { "USER_SECRET_*": "exclude" }, include_only: ["PATH", "HOME"] });
expect(policy).toMatchObject({ exclude: ["OPENMAUSBOT_CHATGPT_TOKEN"], filters: null, include_only: ["PATH", "HOME"] });
expect(await readPolicy([], { filters: { "USER_SECRET_*": "exclude" } })).toMatchObject({ exclude: null, filters: { "USER_SECRET_*": "exclude" } });
});
});
describe("CodexDriver turns (fake app-server)", () => {
let instance: ProviderInstance;
let recorder: EventRecorder;
let scratch: string;
const create = async (
opts: { mode?: string; fullAuto?: boolean; environment?: Record<string, string>; managed?: boolean; authMode?: "chatgpt-plan"; cli?: string } = {},
) => {
if (opts.mode) process.env.FAKE_CODEX_MODE = opts.mode;
instance = await CodexDriver.create({
instanceId: "codex-test",
displayName: "Codex Test",
environment: {
...(opts.managed ? { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: join(scratch, ".codex"), OPENMAUSBOT_COMPANY_API_KEY: "synthetic-company-fixture" } : {}),
...opts.environment,
},
enabled: true,
config: {
cli: opts.cli ?? FAKE_CLI,
fullAuto: opts.fullAuto ?? false,
...(opts.authMode ? { authMode: opts.authMode } : {}),
...(opts.managed ? { managed: { url: "http://127.0.0.1:1/v1", models: ["company-codex-model"] } } : {}),
},
});
recorder = recordEvents(instance.adapter);
};
const record = (mount: string) => `OMB_REMOTE_MCP_CONFIG_${createHash("sha256").update(mount).digest("hex")}`;
beforeEach(() => {
chmodSync(FAKE_CLI, 0o755);
scratch = mkdtempSync(join(tmpdir(), "omb-codex-test-"));
});
it("says once when its team tools did not start", async () => {
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_FAILED: "agents" } });
await instance.adapter.sendTurn({ threadId: "team-tools", text: "Fixture" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.filter((e) => e.type === "runtime.notice").map((e) => (e as { message: string }).message)).toEqual([TEAM_TOOLS_FAILED]);
});
it("refuses native selection before a Codex prompt, including resumed Full-access turns", async () => {
const dump = join(scratch, "scope-refused.json"); process.env.FAKE_CODEX_DUMP = dump;
await create({ fullAuto: true, environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex") } });
await expect(instance.adapter.sendTurn({ threadId: "scope-refused", text: "Must not run", resumeCursor: "old-session", approvalMode: "full", toolScope: { allow: [] } })).rejects.toThrow(/native tool selection.*not supported/i);
expect(existsSync(dump)).toBe(false);
});
it("gates raw custom identities before mount renaming and disables ambient MCP servers", async () => {
const dump = join(scratch, "scope-mcp.json"); process.env.FAKE_CODEX_DUMP = dump;
mkdirSync(join(scratch, ".codex")); writeFileSync(join(scratch, ".codex/config.toml"), '[mcp_servers.notes]\nurl="https://example.test/ambient"\n');
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_OVERRIDES: "1" } });
await instance.adapter.sendTurn({ threadId: "scope-mcp", text: "Fixture", toolScope: { allow: ["native:*", "mcp:notes:read"] }, integrations: { custom: { notes: { type: "sse", url: "https://example.test/notes", headers: {} } } } });
await recorder.until((event) => event.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv).toContain("mcp_servers.notes.enabled=false");
expect(JSON.stringify(seen.argv)).toContain("OMB_GATE_CONFIG_");
expect(JSON.stringify(seen.argv)).not.toContain("https://example.test/notes");
const before = seen.calls.filter((call: { method: string }) => call.method === "turn/start").length;
expect(before).toBe(1);
expect(Object.keys(seen.calls.find((call: { method: string }) => call.method === "thread/start").params.config.mcp_servers)).toEqual(["notes_openmausbot"]);
expect(seen.calls.find((call: { method: string }) => call.method === "thread/start").params.config.mcp_servers.notes_openmausbot.default_tools_approval_mode).toBe("prompt");
recorder.events.length = 0;
await instance.adapter.sendTurn({ threadId: "scope-mcp", text: "Continue", resumeCursor: "old-session", toolScope: { allow: ["native:*", "mcp:notes:read"] }, integrations: { custom: { notes: { type: "sse", url: "https://example.test/notes", headers: {} } } } });
await recorder.until((event) => event.type === "turn.completed");
const restored = JSON.parse(readFileSync(dump, "utf8"));
expect(Object.keys(restored.calls.find((call: { method: string }) => call.method === "thread/resume").params.config.mcp_servers)).toEqual(["notes_openmausbot"]);
expect(restored.calls.find((call: { method: string }) => call.method === "thread/resume").params.config.mcp_servers.notes_openmausbot.default_tools_approval_mode).toBe("prompt");
});
it("still mounts its own copy of a config.toml server when a tool selection switches config.toml's off", async () => {
const dump = join(scratch, "scope-same.json"); process.env.FAKE_CODEX_DUMP = dump;
mkdirSync(join(scratch, ".codex"), { recursive: true }); writeFileSync(join(scratch, ".codex/config.toml"), '[mcp_servers.notes]\nurl="https://example.test/notes"\n');
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_OVERRIDES: "1" } });
await instance.adapter.sendTurn({ threadId: "scope-same", text: "Fixture", toolScope: { allow: ["native:*", "mcp:notes:read"] }, integrations: { custom: { notes: { type: "http", url: "https://example.test/notes", headers: {} } } } });
await recorder.until((event) => event.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv).toContain("mcp_servers.notes.enabled=false");
expect(Object.keys(seen.calls.find((call: { method: string }) => call.method === "thread/start").params.config.mcp_servers)).toEqual(["notes_openmausbot"]);
});
it("refuses a scoped prompt when effective Codex configuration still has an ambient MCP server", async () => {
const dump = join(scratch, "scope-ambient.json"); process.env.FAKE_CODEX_DUMP = dump;
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex") } });
await instance.adapter.sendTurn({ threadId: "scope-ambient", text: "Must not run", toolScope: { allow: ["native:*"] } });
await recorder.until((event) => event.type === "turn.completed");
const seen = existsSync(dump) ? JSON.parse(readFileSync(dump, "utf8")) : { calls: [] };
expect(seen.calls.some((call: { method: string }) => call.method === "turn/start")).toBe(false);
expect(recorder.events.some((event) => event.type === "runtime.error" && /outside the selected configuration/.test(event.message))).toBe(true);
});
it.each(["ask", "custom", "full"] as const)("preserves shell exclusions for scoped %s turns on new and resumed threads", async (approvalMode) => {
const dump = join(scratch, "shell-policy.json"); process.env.FAKE_CODEX_DUMP = dump;
const policy = { inherit: "all", ignore_default_excludes: true, exclude: ["USER_SECRET_*"],
include_only: ["*"], set: { SAFE_FIXTURE_LABEL: "retained" } };
await create({ mode: "resume", environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"),
FAKE_CODEX_MCP_OVERRIDES: "1", FAKE_CODEX_SHELL_ENVIRONMENT_POLICY: JSON.stringify(policy) } });
for (const resumeCursor of [undefined, "old-session"]) {
const { turnId } = await instance.adapter.sendTurn({ threadId: "scoped-shell", text: "Fixture", approvalMode, resumeCursor,
toolScope: { allow: ["native:*", "mcp:notes:read"] },
integrations: { custom: { notes: { type: "http", url: "https://example.test/notes", headers: { authorization: "synthetic-fixture-credential" } } } },
});
const completed = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId);
expect(completed).toMatchObject({ ok: true });
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv).toContain("features.shell_snapshot=false");
const thread = seen.calls.find((call: { method: string }) => call.method === (resumeCursor ? "thread/resume" : "thread/start"));
expect(thread.params.config["shell_environment_policy.exclude"]).toEqual([...policy.exclude, "OMB_GATE_CONFIG_*", "ELECTRON_RUN_AS_NODE"]);
expect(thread.params.config).not.toHaveProperty("shell_environment_policy");
expect(Object.keys(seen.env).some(name => name.startsWith("OMB_GATE_CONFIG_"))).toBe(true);
expect(JSON.stringify({ argv: seen.argv, calls: seen.calls })).not.toContain("synthetic-fixture-credential");
}
});
it("runs scoped turns when Codex reports every shell policy field as null", async () => {
const dump = join(scratch, "null-shell-policy.json"); process.env.FAKE_CODEX_DUMP = dump;
await create({ mode: "resume", environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_OVERRIDES: "1" } });
for (const resumeCursor of [undefined, "old-session"]) {
const { turnId } = await instance.adapter.sendTurn({ threadId: "null-shell-policy", text: "Fixture", resumeCursor,
toolScope: { allow: ["native:*", "mcp:notes:read"] },
integrations: { custom: { notes: { type: "http", url: "https://example.test/notes", headers: {} } } },
});
const completed = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId);
expect(recorder.events.filter(event => event.type === "runtime.error")).toEqual([]);
expect(completed).toMatchObject({ ok: true });
const seen = JSON.parse(readFileSync(dump, "utf8"));
const config = seen.calls.find((call: { method: string }) => call.method === (resumeCursor ? "thread/resume" : "thread/start")).params.config;
expect(config["shell_environment_policy.exclude"]).toEqual(["OMB_GATE_CONFIG_*", "ELECTRON_RUN_AS_NODE"]);
expect(Object.keys(config).filter(key => key.startsWith("shell_environment_policy"))).toEqual(["shell_environment_policy.exclude"]);
}
});
it("keeps a person's shell filters and adds the gate pattern as an exclude filter", async () => {
const dump = join(scratch, "shell-filters.json"); process.env.FAKE_CODEX_DUMP = dump;
const policy = { inherit: "all", filters: { "USER_SECRET_*": "exclude", "KEEP_*": "include", "omb_gate_config_*": "include" } };
await create({ mode: "resume", environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"),
FAKE_CODEX_MCP_OVERRIDES: "1", FAKE_CODEX_SHELL_ENVIRONMENT_POLICY: JSON.stringify(policy) } });
for (const resumeCursor of [undefined, "old-session"]) {
const { turnId } = await instance.adapter.sendTurn({ threadId: "shell-filters", text: "Fixture", resumeCursor,
toolScope: { allow: ["native:*", "mcp:notes:read"] },
integrations: { custom: { notes: { type: "http", url: "https://example.test/notes", headers: {} } } },
});
const completed = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId);
expect(completed).toMatchObject({ ok: true });
const seen = JSON.parse(readFileSync(dump, "utf8"));
const config = seen.calls.find((call: { method: string }) => call.method === (resumeCursor ? "thread/resume" : "thread/start")).params.config;
expect(config["shell_environment_policy.filters"]).toEqual({ "USER_SECRET_*": "exclude", "KEEP_*": "include", "OMB_GATE_CONFIG_*": "exclude", ELECTRON_RUN_AS_NODE: "exclude" });
expect(Object.keys(config).filter(key => key.startsWith("shell_environment_policy"))).toEqual(["shell_environment_policy.filters"]);
}
});
it("refuses a scoped prompt when inherited shell snapshots cannot be disabled", async () => {
const dump = join(scratch, "unsafe-shell-snapshot.json"); process.env.FAKE_CODEX_DUMP = dump;
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"),
FAKE_CODEX_MCP_OVERRIDES: "1", FAKE_CODEX_IGNORE_FEATURES: "1" } });
const { turnId } = await instance.adapter.sendTurn({ threadId: "unsafe-shell-snapshot", text: "Must not run.",
toolScope: { allow: ["native:*", "mcp:notes:read"] },
integrations: { custom: { notes: { type: "http", url: "https://example.test/notes", headers: {} } } },
});
const completed = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId);
expect(completed).toMatchObject({ ok: false });
expect(recorder.events.some(event => event.type === "runtime.error" && /shell snapshots/.test(event.message))).toBe(true);
const seen = existsSync(dump) ? JSON.parse(readFileSync(dump, "utf8")) : { calls: [] };
expect(seen.calls.some((call: { method: string }) => call.method === "turn/start")).toBe(false);
});
it.each([null, false, [], { exclude: "SAFE_*" }, { exclude: ["SAFE_*", 42] }, { filters: [] }, { filters: "SAFE_*" },
{ filters: { "SAFE_*": "keep" } }, { filters: { "SAFE_*": null } },
// Codex refuses a layer that mixes the two representations.
{ exclude: ["SAFE_*"], filters: { "OTHER_*": "exclude" } }, { include_only: ["PATH"], filters: { "OTHER_*": "exclude" } },
])("refuses a scoped prompt with a malformed shell policy %j", async (policy) => {
const dump = join(scratch, "invalid-shell-policy.json"); process.env.FAKE_CODEX_DUMP = dump;
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"),
FAKE_CODEX_MCP_OVERRIDES: "1", FAKE_CODEX_SHELL_ENVIRONMENT_POLICY: JSON.stringify(policy) } });
const { turnId } = await instance.adapter.sendTurn({ threadId: "invalid-shell-policy", text: "Must not run.",
toolScope: { allow: ["native:*", "mcp:notes:read"] },
integrations: { custom: { notes: { type: "http", url: "https://example.test/notes", headers: {} } } },
});
const completed = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId);
expect(completed).toMatchObject({ ok: false });
expect(recorder.events.some(event => event.type === "runtime.error" && /shell environment/.test(event.message))).toBe(true);
const seen = existsSync(dump) ? JSON.parse(readFileSync(dump, "utf8")) : { calls: [] };
expect(seen.calls.some((call: { method: string }) => call.method === "turn/start")).toBe(false);
});
it("keeps multiple scoped Codex servers independent on new and resumed threads, including custom approvals", async () => {
const dump = join(scratch, "multi-scope.json"); process.env.FAKE_CODEX_DUMP = dump;
const upstream = join(scratch, "upstream.cjs"), receipt = join(scratch, "receipt.txt");
writeFileSync(upstream, `const {createInterface}=require('node:readline');const {appendFileSync}=require('node:fs');
createInterface({input:process.stdin}).on('line',line=>{const m=JSON.parse(line);if(m.id===undefined)return;let result={};
if(m.method==='initialize')result={protocolVersion:m.params.protocolVersion,capabilities:{tools:{}},serverInfo:{name:process.env.IDENTITY,version:'1'}};
if(m.method==='tools/list')result={tools:[process.env.TOOL,'forbidden'].map(name=>({name,inputSchema:{type:'object'}}))};
if(m.method==='tools/call'){appendFileSync(process.env.RECEIPT,process.env.IDENTITY+':'+m.params.name+'\\n');result={content:[{type:'text',text:Object.keys(process.env).some(key=>key.startsWith('OMB_GATE_'))?'private-config-leak':process.env.IDENTITY}]};}
process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`);
await create({ mode: "resume", environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_MCP_OVERRIDES: "1" } });
const turn = { threadId: "multi-scope", text: "Fixture", toolScope: { allow: ["native:*", "mcp:agents:list_bots", "mcp:notes:read_notes"] }, integrations: {
agents: { command: process.execPath, args: [upstream], env: { IDENTITY: "agents", TOOL: "list_bots", RECEIPT: receipt } },
custom: { notes: { command: process.execPath, args: [upstream], env: { IDENTITY: "notes", TOOL: "read_notes", RECEIPT: receipt } } },
} };
for (const resumeCursor of [undefined, "old-session"]) {
recorder.events.length = 0;
await instance.adapter.sendTurn({ ...turn, resumeCursor });
await recorder.until(event => event.type === "turn.completed");
expect(recorder.events.filter(event => event.type === "runtime.error")).toEqual([]);
const seen = JSON.parse(readFileSync(dump, "utf8"));
const config = seen.calls.find((call: { method: string }) => call.method === (resumeCursor ? "thread/resume" : "thread/start")).params.config.mcp_servers;
expect(config.agents.default_tools_approval_mode).toBe("approve");
expect(config.notes.default_tools_approval_mode).toBe("prompt");
for (const [name, tool] of [["agents", "list_bots"], ["notes", "read_notes"]]) {
const spec = config[name!];
const gate = spawn(spec.command, spec.args, { env: { ...seen.env, ...spec.env, ...Object.fromEntries(spec.env_vars.map((key: string) => [key, seen.env[key]])) }, stdio: ["pipe", "pipe", "pipe"] });
let nextId = 1;
const pending = new Map<number, (message: any) => void>();
const lines = createInterface({ input: gate.stdout });
lines.on("line", line => { const message = JSON.parse(line); pending.get(message.id)?.(message); pending.delete(message.id); });
const request = (method: string, params: unknown = {}) => new Promise<any>((resolve, reject) => {
const id = nextId++, timer = setTimeout(() => reject(new Error("Gate did not reply")), 10_000);
pending.set(id, message => { clearTimeout(timer); resolve(message); });
gate.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
});
try {
await request("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "fixture", version: "1" } });
expect((await request("tools/list")).result.tools.map((entry: { name: string }) => entry.name)).toEqual([tool]);
expect((await request("tools/call", { name: tool, arguments: {} })).result.content[0].text).toBe(name);
expect((await request("tools/call", { name: "forbidden", arguments: {} })).error).toBeDefined();
} finally { lines.close(); const closed = once(gate, "close"); gate.kill(); await closed; }
}
}
expect(readFileSync(receipt, "utf8")).toBe("agents:list_bots\nnotes:read_notes\nagents:list_bots\nnotes:read_notes\n");
});
afterEach(async () => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
delete process.env.FAKE_CODEX_MODE;
delete process.env.FAKE_CODEX_REVIEW_EVENTS;
delete process.env.FAKE_CODEX_REVIEW_AFTER_COMPLETION;
delete process.env.FAKE_CODEX_APPROVAL_REQUEST;
delete process.env.FAKE_CODEX_DUMP;
delete process.env.FAKE_CODEX_ASK_HOLD;
delete process.env.FAKE_CODEX_TRANSIENTS;
delete process.env.FAKE_CODEX_PARTIAL_FAILS;
delete process.env.FAKE_CODEX_STATE;
delete process.env.FAKE_CODEX_RETRY_SCALE;
delete process.env.FAKE_CODEX_LAUNCH_CRASHES;
delete process.env.FAKE_CODEX_LAUNCH_KILLS;
delete process.env.FAKE_CODEX_LAUNCH_SILENT;
delete process.env.FAKE_CODEX_ACK_CRASH;
delete process.env.FAKE_CODEX_EXIT_MID_TURN;
delete process.env.FAKE_CODEX_EXIT_MID_TURN_KILL;
delete process.env.FAKE_CODEX_VERSION;
delete process.env.FAKE_CODEX_ASTRA;
delete process.env.FAKE_CODEX_INSTRUCTIONS;
delete process.env.FAKE_CODEX_RESUME_ERROR;
delete process.env.FAKE_CODEX_START_ERROR;
delete process.env.FAKE_CODEX_RESOLVED_SANDBOX;
delete process.env.FAKE_CODEX_MCP_START;
delete process.env.FAKE_CODEX_MCP_HANDSHAKE;
delete process.env.FAKE_CODEX_STEER_ERROR;
delete process.env.FAKE_CODEX_STEER_ERROR_FILE;
delete process.env.FAKE_CODEX_STEER_HANG;
delete process.env.FAKE_CODEX_STEER_TIMEOUT_MS;
delete process.env.FAKE_CODEX_INTERRUPT_SILENT;
delete process.env.FAKE_CODEX_INTERRUPT_GRACE_MS;
delete process.env.OPENAI_API_KEY;
delete process.env.BOX_TOKEN;
delete process.env.OMB_TTS_KEY;
for (const name of Object.keys(CONTROL_PLANE_FIXTURE)) delete process.env[name];
recorder?.stop();
await instance?.dispose();
await removeTempDir(scratch);
});
it("surfaces one attributed Auto-review timeout without failing a completed reply", async () => {
const scope = { threadId: "codex-thread-1", turnId: "turn-1" };
process.env.FAKE_CODEX_REVIEW_EVENTS = JSON.stringify([
{ method: "guardianWarning", params: { threadId: scope.threadId, message: "Automatic approval review timed out." } },
{ method: "item/autoApprovalReview/completed", params: {
...scope, reviewId: "review-1", targetItemId: "tool-1", review: { status: "timedOut" },
action: { type: "command", source: "unifiedExec", command: "git status --short" },
} },
]);
await create({ mode: "review-events" });
await instance.adapter.sendTurn({ threadId: "app-thread", text: "check", approvalMode: "auto" });
await recorder.until((event) => event.type === "turn.completed");
const notices = recorder.events.filter((event) => event.type === "runtime.error" && event.message.includes("automatic review"));
expect(notices).toHaveLength(1);
expect(notices[0]).toMatchObject({ threadId: "app-thread", message: expect.stringContaining("git status --short") });
expect(notices[0]?.type === "runtime.error" && notices[0].message).toMatch(/Ask.*Auto|Auto.*Ask/);
expect(recorder.events.find((event) => event.type === "turn.completed")).toMatchObject({ ok: true });
});
it("names Custom rather than Auto when Custom uses native automatic review", async () => {
process.env.FAKE_CODEX_REVIEW_EVENTS = JSON.stringify([{
method: "item/autoApprovalReview/completed",
params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "custom-1", review: { status: "timedOut" } },
}]);
await create({ mode: "review-events", fullAuto: true });
await instance.adapter.sendTurn({ threadId: "app-thread", text: "check", approvalMode: "custom" });
await recorder.until((event) => event.type === "turn.completed");
const notices = recorder.events.filter((event) => event.type === "runtime.error" && event.message.includes("automatic review"));
expect(notices).toHaveLength(1);
expect(notices[0]).toMatchObject({ message: expect.stringContaining("Retry stays Custom") });
});
it.each([
{ name: "thread warning only", events: [
{ method: "guardianWarning", params: { threadId: "codex-thread-1", message: "Automatic approval review timed out." } },
], expected: "reported a timeout" },
{ name: "explicit denial", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "denied-1", review: { status: "denied" } } },
], expected: "denied" },
{ name: "approved review", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "approved-1", review: { status: "approved" } } },
], expected: null },
{ name: "approved review after another timeout warning", events: [
{ method: "guardianWarning", params: { threadId: "codex-thread-1", message: "Automatic approval review timed out." } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "approved-1", review: { status: "approved" } } },
], expected: "reported a timeout" },
{ name: "unknown review status", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", review: { status: "futureStatus" } } },
], expected: null },
{ name: "missing review status", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1" } },
], expected: null },
{ name: "duplicate result", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "same", review: { status: "timedOut" } } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "same", review: { status: "timedOut" } } },
], expected: "timed out" },
{ name: "ID-less result cannot be safely deduplicated", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", review: { status: "timedOut" } } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", review: { status: "timedOut" } } },
], expected: null },
{ name: "helper and stale turns", events: [
{ method: "guardianWarning", params: { threadId: "helper-thread", message: "Automatic approval review timed out." } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "helper-thread", turnId: "turn-1", review: { status: "timedOut" } } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "old-turn", review: { status: "timedOut" } } },
{ method: "guardianWarning", params: { threadId: "codex-thread-1", turnId: "old-turn", message: "Automatic approval review timed out." } },
{ method: "guardianWarning", params: { threadId: "codex-thread-1", turnId: null, message: "Automatic approval review timed out." } },
], expected: null },
])("handles $name without contaminating another turn", async ({ events, expected }) => {
process.env.FAKE_CODEX_REVIEW_EVENTS = JSON.stringify(events);
await create({ mode: "review-events" });
await instance.adapter.sendTurn({ threadId: "app-thread", text: "check", approvalMode: "auto" });
await recorder.until((event) => event.type === "turn.completed");
const notices = recorder.events.filter((event) => event.type === "runtime.error" && event.message.includes("automatic review"));
expect(notices).toHaveLength(expected ? 1 : 0);
if (expected) expect(notices[0]).toMatchObject({ message: expect.stringContaining(expected) });
});
it.each([
{ name: "warning plus unrelated denial", events: [
{ method: "guardianWarning", params: { threadId: "codex-thread-1", message: "Automatic approval review timed out." } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "denied-1", review: { status: "denied" } } },
], outcomes: ["denied", "reported a timeout"] },
{ name: "distinct actionless failures", events: [
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "first", review: { status: "timedOut" } } },
{ method: "item/autoApprovalReview/completed", params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "second", review: { status: "timedOut" } } },
], outcomes: ["timed out", "timed out"] },
])("keeps $name separate", async ({ events, outcomes }) => {
process.env.FAKE_CODEX_REVIEW_EVENTS = JSON.stringify(events);
await create({ mode: "review-events" });
await instance.adapter.sendTurn({ threadId: "app-thread", text: "check", approvalMode: "auto" });
await recorder.until((event) => event.type === "turn.completed");
const notices = recorder.events.filter((event) => event.type === "runtime.error" && event.message.includes("automatic review"));
expect(notices.map((event) => event.type === "runtime.error" && event.message)).toEqual(outcomes.map((outcome) => expect.stringContaining(outcome)));
});
it("ignores a review result delayed past turn completion", async () => {
process.env.FAKE_CODEX_REVIEW_AFTER_COMPLETION = JSON.stringify({
method: "item/autoApprovalReview/completed",
params: { threadId: "codex-thread-1", turnId: "turn-1", reviewId: "late", review: { status: "timedOut" } },
});
await create({ mode: "review-events" });
await instance.adapter.sendTurn({ threadId: "app-thread", text: "check", approvalMode: "auto" });
await recorder.until((event) => event.type === "turn.completed");
await new Promise((resolve) => setTimeout(resolve, 50));
expect(recorder.events.some((event) => event.type === "runtime.error" && event.message.includes("automatic review"))).toBe(false);
});
it("names the signed-in ChatGPT account from Codex's protocol and offers sign-out", async () => {
const codexHome = join(scratch, ".codex");
mkdirSync(codexHome, { recursive: true });
const claims = Buffer.from(JSON.stringify({ email: "stale-file@example.test" })).toString("base64url");
writeFileSync(join(codexHome, "auth.json"), JSON.stringify({
tokens: { id_token: `header.${claims}.signature-fixture`, access_token: "access-fixture", refresh_token: "refresh-fixture" },
}));
await create({ environment: { HOME: scratch, CODEX_HOME: codexHome } });
const connected = await instance.snapshot();
expect(connected).toMatchObject({ state: "available", authenticated: true, account: { email: "ada@example.test" } });
expect(JSON.stringify(connected)).not.toContain("fixture");
expect(instance.signOut).toBeTypeOf("function");
process.env.FAKE_CODEX_MODE = "logged-out";
const signedOut = await instance.snapshot();
expect(signedOut).toMatchObject({ state: "available", authenticated: false });
expect(signedOut).not.toHaveProperty("account");
});
it.each(["api-key", "none", "unsupported", "error"])("omits ChatGPT identity when Codex account/read reports %s", async (mode) => {
await create({ environment: { HOME: scratch, CODEX_HOME: join(scratch, ".codex"), FAKE_CODEX_ACCOUNT_MODE: mode } });
expect(await instance.snapshot()).not.toHaveProperty("account");
});
it("runs a guest's turn with no environment and the shell off, proven before the turn starts", async () => {
await create();
expect(instance.adapter.capabilities.guestTurns).toBe("confined");
const dump = join(scratch, "dump.json");
process.env.FAKE_CODEX_DUMP = dump;
await instance.adapter.sendTurn({ threadId: "t-guest", text: "cat /proc/1/environ", system: "You are Testy.", model: "gpt-5.6-sol", approvalMode: "ask", guestConfined: true });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8")) as { argv: string[]; calls: Array<{ method: string; params: any }> };
for (const override of ["features.shell_tool=false", "features.unified_exec=false", "features.view_image=false"]) {
expect(seen.argv[seen.argv.indexOf(override) - 1], override).toBe("-c");
}
expect(seen.calls.find((call) => call.method === "thread/start")?.params.environments).toEqual([]);
expect(seen.calls.find((call) => call.method === "turn/start")?.params.environments).toEqual([]);
await instance.adapter.sendTurn({ threadId: "t-owner", text: "ls", system: "You are Testy.", model: "gpt-5.6-sol", approvalMode: "ask" });
await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-owner");
const owner = JSON.parse(readFileSync(dump, "utf8")) as { argv: string[]; calls: Array<{ method: string; params: any }> };
expect(owner.argv).not.toContain("features.shell_tool=false");
expect(owner.calls.find((call) => call.method === "turn/start")?.params).not.toHaveProperty("environments");
});
it("refuses a guest's turn when Codex did not take the shell-off overrides", async () => {
await create({ environment: { FAKE_CODEX_IGNORE_FEATURES: "1" } });
const dump = join(scratch, "dump.json");
process.env.FAKE_CODEX_DUMP = dump;
await instance.adapter.sendTurn({ threadId: "t-guest", text: "cat /proc/1/environ", system: "You are Testy.", model: "gpt-5.6-sol", approvalMode: "ask", guestConfined: true })
.then(() => recorder.until((e) => e.type === "turn.completed"), (error: unknown) => error);
const failed = recorder.events.find((e) => e.type === "turn.completed") as { state?: string; errorMessage?: string } | undefined;
const seen = existsSync(dump) ? JSON.parse(readFileSync(dump, "utf8")) as { calls: Array<{ method: string }> } : { calls: [] };
expect(seen.calls.some((call) => call.method === "turn/start")).toBe(false);
expect(JSON.stringify(recorder.events)).toContain("could not turn its shell off");
expect(failed).toMatchObject({ ok: false });
});
it("runs the handshake and normalizes a full turn", async () => {
await create();
const dump = join(scratch, "dump.json");
process.env.FAKE_CODEX_DUMP = dump;
process.env.OPENAI_API_KEY = "sk-should-not-leak";
process.env.BOX_TOKEN = "box-should-not-leak";
process.env.OMB_TTS_KEY = "tts-should-not-leak";
Object.assign(process.env, CONTROL_PLANE_FIXTURE);
const { turnId } = await instance.adapter.sendTurn({
threadId: "t-happy",
text: "list files",
system: "You are Testy.",
model: "gpt-5.6-sol",
});
await recorder.until((e) => e.type === "turn.completed");
const types = recorder.events.map((e) => e.type);
expect(types).toEqual([
"turn.started",
"session.started",
"item.started",
"item.started",
"item.completed",
"item.completed",
"content.delta",
"item.completed",
"thread.token-usage.updated",
"turn.completed",
]);
expect(recorder.events.every((e) => e.turnId === turnId && e.provider === "codex")).toBe(true);
expect(recorder.events.find((e) => e.type === "session.started")).toMatchObject({
sessionId: "codex-thread-1",
model: "fake-codex-model",
});
expect(recorder.events.find((e) => e.type === "thread.token-usage.updated")).toMatchObject({
input: 7,
output: 3,
cachedInput: 4,
contextTokens: 7,
contextWindow: 272000,
});
expect(recorder.events.filter((event) => event.itemId === "w1")).toMatchObject([
{ type: "item.started", itemType: "tool", title: "web_search" },
{ type: "item.completed", itemType: "tool", ok: true },
]);
expect(recorder.events.filter((event) => event.itemId === "i1")).toMatchObject([
{ type: "item.started", input: expect.stringContaining("ls -la") },
{ type: "item.completed", output: expect.stringContaining("README.md") },
]);
const commandResult = recorder.events.find((event) => event.itemId === "i1" && event.type === "item.completed");
expect(JSON.stringify(commandResult)).toContain("exitCode");
expect(JSON.stringify(commandResult)).not.toContain("codex-output-secret");
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(processIsAlive(seen.pid)).toBe(false);
expect(seen.env.OPENAI_API_KEY).toBeUndefined();
expect(seen.env.BOX_TOKEN).toBeUndefined();
expect(seen.env.OMB_TTS_KEY).toBeUndefined();
for (const name of Object.keys(CONTROL_PLANE_FIXTURE)) expect(seen.env[name]).toBeUndefined();
const methods = seen.calls.map((c: { method: string }) => c.method);
expect(methods).toEqual(["initialize", "initialized", "config/read", "thread/start", "turn/start"]);
const turnStart = seen.calls.at(-1);
expect(turnStart.params.input[0].text).toBe("list files");
const threadStart = seen.calls.find((c: { method: string }) => c.method === "thread/start");
expect(threadStart.params).toMatchObject({ model: "gpt-5.6-sol", modelProvider: "openai", developerInstructions: "You are Testy." });
});
it("keeps the developer slot stable and delivers volatile context in-turn", async () => {
await create({ mode: "resume" });
// Each turn spawns a fresh app-server whose dump overwrites the file, so every turn writes its own.
const send = async (dumpName: string, text: string, volatile: string, cursor?: string, mentionTurn?: boolean) => {
process.env.FAKE_CODEX_DUMP = join(scratch, dumpName);
const { turnId } = await instance.adapter.sendTurn({
threadId: "t-prompt-split",
text,
system: "Stable rules.",
systemStable: "Stable rules.",
systemVolatile: volatile,
...(cursor ? { resumeCursor: cursor } : {}),
...(mentionTurn ? { mentionTurn: true } : {}),
});
await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
return JSON.parse(readFileSync(join(scratch, dumpName), "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
};
const first = await send("split-1.json", "first", "Memory: likes quiet hours.");
const second = await send("split-2.json", "second", "Memory: likes quiet hours.", "codex-thread-1");
const third = await send("split-3.json", "third", "Memory: moved to Toronto.", "codex-thread-1");
const threadStarts = first.filter((c) => c.method === "thread/start");
expect(threadStarts).toHaveLength(1);
expect(threadStarts[0].params.developerInstructions).toBe("Stable rules.");
for (const calls of [first, second, third]) {
expect(calls.some((c) => c.method === "thread/inject_items")).toBe(false);
}
const turnText = (calls: typeof first) => {
const input = calls.find((c) => c.method === "turn/start")?.params?.input as Array<{ text?: string }> | undefined;
return input?.[0]?.text;
};
expect(turnText(first)).toBe("Context from OpenMausBot updated since this conversation started; it replaces any earlier copy:\n\nMemory: likes quiet hours.\n\nfirst");
expect(turnText(second)).toBe("second");
expect(turnText(third)).toContain("Memory: moved to Toronto.");
expect(turnText(third)).toContain("third");
const fourth = await send("split-4.json", "fourth", "Memory: moved to Toronto.", "codex-thread-1", true);
expect(turnText(fourth)).toContain("Memory: moved to Toronto.");
expect(turnText(fourth)).toContain("fourth");
});
it("ignores requests received after turn completion", async () => {
await create({ mode: "late-request" });
await instance.adapter.sendTurn({ threadId: "t-late-request", text: "finish" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.some((event) => event.type === "request.opened")).toBe(false);
});
it("keeps the parent working after helper completion and ignores foreign output and usage", async () => {
await create({ mode: "helper-events" });
await instance.adapter.sendTurn({ threadId: "t-helper-events", text: "use a helper then continue" });
const permission = await recorder.until((event) => event.type === "request.opened");
expect(permission).toMatchObject({ summary: "echo parent continues" });
expect(recorder.events.some((event) => event.type === "turn.completed")).toBe(false);
expect(JSON.stringify(recorder.events)).not.toContain("FOREIGN");
expect(recorder.events.some((event) => event.type === "thread.token-usage.updated")).toBe(false);
await instance.adapter.respondToRequest("t-helper-events", permission.requestId!, { behavior: "allow" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.filter((event) => event.type === "turn.completed")).toHaveLength(1);
expect(recorder.events.at(-1)).toMatchObject({ ok: true, usage: { input: 7, output: 3 } });
expect(recorder.events.find((event) => event.type === "item.completed" && event.itemType === "assistant_text")).toMatchObject({ text: "done from fake codex" });
expect(JSON.stringify(recorder.events)).not.toContain("FOREIGN");
const repeat = await instance.adapter.sendTurn({
threadId: "t-helper-events", resumeCursor: "codex-thread-1", text: "continue and deny the next request",
});
const denied = await recorder.until((event) => event.turnId === repeat.turnId && event.type === "request.opened");
await instance.adapter.respondToRequest("t-helper-events", denied.requestId!, { behavior: "deny" });
await recorder.until((event) => event.turnId === repeat.turnId && event.type === "turn.completed");
expect(recorder.events.filter((event) => event.type === "turn.completed")).toHaveLength(2);
expect(recorder.events.at(-1)).toMatchObject({ ok: true });
expect(recorder.events.find((event) => event.turnId === repeat.turnId && event.type === "request.resolved")).toMatchObject({ behavior: "deny" });
expect(JSON.stringify(recorder.events)).not.toContain("FOREIGN");
});
it("retains parent notifications delivered before the turn/start response", async () => {
await create({ mode: "early-turn-events" });
await instance.adapter.sendTurn({ threadId: "t-early-events", text: "finish quickly" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.at(-1)).toMatchObject({ ok: true });
expect(recorder.events.filter((event) => event.type === "turn.completed")).toHaveLength(1);
expect(recorder.events.find((event) => event.type === "item.completed" && event.itemType === "assistant_text")).toMatchObject({ text: "done from fake codex" });
});
it.each([
["ask", "on-request", "workspace-write", "workspaceWrite"],
["auto", "on-request", "workspace-write", "workspaceWrite"],
["full", "never", "danger-full-access", "dangerFullAccess"],
] as const)(
"reasserts the %s approval mode on thread start and turn start",
async (approvalMode, approvalPolicy, sandbox, turnSandbox) => {
await create();
const dump = join(scratch, `${approvalMode}.json`);
process.env.FAKE_CODEX_DUMP = dump;
await instance.adapter.sendTurn({
threadId: `t-${approvalMode}`,
text: "continue",
approvalMode,
});
await recorder.until((event) => event.type === "turn.completed");
const calls = JSON.parse(readFileSync(dump, "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
expect(calls.find((call) => call.method === "thread/start")?.params).toMatchObject({
approvalPolicy,
approvalsReviewer: approvalMode === "auto" ? "auto_review" : "user",
sandbox,
});
expect(calls.find((call) => call.method === "turn/start")?.params).toMatchObject({
approvalPolicy,
approvalsReviewer: approvalMode === "auto" ? "auto_review" : "user",
sandboxPolicy: { type: turnSandbox },
});
},
);
it.each([false, true])("preserves the complete resolved sandbox (resumed=%s)", async (resumed) => {
await create({ mode: "resume" });
const dump = join(scratch, "resolved-sandbox.json");
process.env.FAKE_CODEX_DUMP = dump;
const sandbox = {
type: "workspaceWrite", networkAccess: true,
writableRoots: [join(scratch, "extra-root")],
excludeTmpdirEnvVar: true, excludeSlashTmp: true,
};
process.env.FAKE_CODEX_RESOLVED_SANDBOX = JSON.stringify(sandbox);
await instance.adapter.sendTurn({ threadId: "t-resolved", text: "continue", approvalMode: "ask",
...(resumed ? { resumeCursor: "codex-thread-1" } : {}) });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.at(-1)).toMatchObject({ ok: true });
const calls = JSON.parse(readFileSync(dump, "utf8")).calls;
expect(calls.find((call: { method: string }) => call.method === "turn/start").params.sandboxPolicy).toEqual(sandbox);
});
it.each([false, true].flatMap(resumed => [null, {}, { type: "dangerFullAccess" }].map(sandbox => ({ resumed, sandbox }))))("refuses an absent or mismatched resolved sandbox: %j", async ({ resumed, sandbox }) => {
await create({ mode: "resume" });
const dump = join(scratch, "invalid-sandbox.json");
process.env.FAKE_CODEX_DUMP = dump;
process.env.FAKE_CODEX_RESOLVED_SANDBOX = JSON.stringify(sandbox);
await instance.adapter.sendTurn({ threadId: "t-invalid-sandbox", text: "continue", approvalMode: "ask",
...(resumed ? { resumeCursor: "codex-thread-1" } : {}) });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.at(-1)).toMatchObject({ ok: false });
if (!sandbox || !("type" in sandbox)) {
expect(recorder.events.some(event => event.type === "runtime.error" && event.message.includes("Update Codex"))).toBe(true);
}
const calls = JSON.parse(readFileSync(dump, "utf8")).calls;
expect(calls.some((call: { method: string }) => call.method === "turn/start")).toBe(false);
});
it.each(["gpt-5.6-sol", "gpt-5.4"])(
"reapplies Full, Auto, and Ask across thread start and resume for %s",
async (model) => {
await create({ mode: "resume", fullAuto: true });
const dump = join(scratch, "approval-transitions.json");
process.env.FAKE_CODEX_DUMP = dump;
for (const [approvalMode, approvalPolicy, sandbox, turnSandbox] of [
["full", "never", "danger-full-access", "dangerFullAccess"],
["auto", "on-request", "workspace-write", "workspaceWrite"],
["ask", "on-request", "workspace-write", "workspaceWrite"],
] as const) {
const resumed = approvalMode !== "full";
const { turnId } = await instance.adapter.sendTurn({
threadId: "t-mode-transitions",
text: "continue",
model,
approvalMode,
...(resumed ? { resumeCursor: "codex-thread-1" } : {}),
});
await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
const calls = JSON.parse(readFileSync(dump, "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
expect(calls.find((call) => call.method === (resumed ? "thread/resume" : "thread/start"))?.params).toMatchObject({
...(resumed ? { threadId: "codex-thread-1" } : { model }),
approvalPolicy,
approvalsReviewer: approvalMode === "auto" ? "auto_review" : "user",
sandbox,
});
expect(calls.find((call) => call.method === "turn/start")?.params).toMatchObject({
approvalPolicy,
approvalsReviewer: approvalMode === "auto" ? "auto_review" : "user",
sandboxPolicy: { type: turnSandbox },
});
}
},
);
it("reasserts the effective config.toml settings for Custom", async () => {
await create({ mode: "resume", fullAuto: true });
const dump = join(scratch, "custom.json");
process.env.FAKE_CODEX_DUMP = dump;
mkdirSync(NATIVE_DIR, { recursive: true });
await instance.adapter.sendTurn({
threadId: "t-custom",
text: "continue",
approvalMode: "custom",
resumeCursor: "codex-thread-custom",
});
await recorder.until((event) => event.type === "turn.completed");
const calls = JSON.parse(readFileSync(dump, "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
expect(calls.find((call) => call.method === "config/read")?.params).toMatchObject({
cwd: expect.any(String),
includeLayers: false,
});
expect(calls.find((call) => call.method === "thread/resume")?.params).toMatchObject({
threadId: "codex-thread-custom",
approvalPolicy: "never",
approvalsReviewer: "auto_review",
sandbox: "read-only",
});
expect(calls.find((call) => call.method === "turn/start")?.params).toMatchObject({
approvalPolicy: "never",
approvalsReviewer: "auto_review",
sandboxPolicy: { type: "readOnly" },
});
const nativeLog = readFileSync(join(NATIVE_DIR, "t-custom.ndjson"), "utf8");
expect(nativeLog).toContain("[effective config omitted]");
expect(nativeLog).not.toContain("innocuous-config-secret-7a9c");
});
it.each([
["thread/start", undefined],
["thread/resume", "codex-thread-profile"],
] as const)("reasserts a named Custom permission profile through %s and turn/start", async (
threadMethod,
resumeCursor,
) => {
await create({ mode: "config-profile" });
const threadId = `t-custom-profile-${threadMethod.replace("/", "-")}`;
const dump = join(scratch, `${threadId}.json`);
process.env.FAKE_CODEX_DUMP = dump;
mkdirSync(NATIVE_DIR, { recursive: true });
await instance.adapter.sendTurn({
threadId,
text: "continue with my profile",
approvalMode: "custom",
...(resumeCursor ? { resumeCursor } : {}),
});
await recorder.until((event) => event.type === "turn.completed");
const calls = JSON.parse(readFileSync(dump, "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
expect(calls.find((call) => call.method === "initialize")?.params).toMatchObject({
capabilities: { experimentalApi: true },
});
const threadParams = calls.find((call) => call.method === threadMethod)?.params;
expect(threadParams).toMatchObject({
permissions: "private-operator-profile",
approvalPolicy: "on-request",
approvalsReviewer: "user",
});
expect(threadParams).not.toHaveProperty("sandbox");
const turnParams = calls.find((call) => call.method === "turn/start")?.params;
expect(turnParams).toMatchObject({
permissions: "private-operator-profile",
approvalPolicy: "on-request",
approvalsReviewer: "user",
});
expect(turnParams).not.toHaveProperty("sandboxPolicy");
});
it("falls back to the safe legacy Custom settings when profiles are unsupported", async () => {
await create({ mode: "config-profile-unsupported" });
const dump = join(scratch, "custom-profile-fallback.json");
process.env.FAKE_CODEX_DUMP = dump;
await instance.adapter.sendTurn({
threadId: "t-custom-profile-fallback",
text: "continue safely",
approvalMode: "custom",
resumeCursor: "codex-thread-profile-fallback",
});
await recorder.until((event) => event.type === "turn.completed");
const calls = JSON.parse(readFileSync(dump, "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
const resumes = calls.filter((call) => call.method === "thread/resume");
expect(resumes).toHaveLength(2);
expect(resumes[0]?.params).toMatchObject({ permissions: "private-operator-profile" });
expect(resumes[1]?.params).toMatchObject({
approvalPolicy: "on-request",
approvalsReviewer: "user",
sandbox: "read-only",
});
expect(calls.find((call) => call.method === "turn/start")?.params).toMatchObject({
approvalPolicy: "on-request",
approvalsReviewer: "user",
sandboxPolicy: { type: "readOnly" },
});
});
it.each(["ask", "auto", "full", "custom"] as const)("stops before replacing unknown native instructions in %s mode", async (approvalMode) => {
await create({ mode: "config-read-error" });
const dump = join(scratch, "custom-config-error.json");
process.env.FAKE_CODEX_DUMP = dump;
await instance.adapter.sendTurn({
threadId: "t-custom-config-error",
text: "continue safely",
approvalMode,
});
await expect(recorder.until((event) => event.type === "turn.completed")).resolves.toMatchObject({ ok: false });
const calls = JSON.parse(readFileSync(dump, "utf8")).calls as Array<{
method: string;
params: Record<string, unknown>;
}>;
expect(calls.map((call) => call.method)).toEqual(["initialize", "initialized", "config/read"]);
expect(recorder.events.some((event) => event.type === "runtime.error" && event.message.includes("cannot safely update bot instructions"))).toBe(true);
});
it("sends current-turn images as native localImage inputs without logging their private paths", async () => {
await create();
const dump = join(scratch, "images.json");
const imagePath = join(scratch, "private image.png");
process.env.FAKE_CODEX_DUMP = dump;
mkdirSync(NATIVE_DIR, { recursive: true });
writeFileSync(imagePath, "png");
await instance.adapter.sendTurn({
threadId: "t-native-input-image",
text: "describe this",
system: "You are Testy.",
images: [{ path: imagePath, mime: "image/png", bytes: 3 }],
});
await recorder.until((event) => event.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
const turnStart = seen.calls.find((call: { method: string }) => call.method === "turn/start");
expect(turnStart.params.input).toEqual([
{ type: "text", text: "describe this" },
{ type: "localImage", path: imagePath },
]);
const nativeLog = readFileSync(join(NATIVE_DIR, "t-native-input-image.ndjson"), "utf8");
expect(nativeLog).toContain('"type":"localImage"');
expect(nativeLog).toContain("[private attachment path omitted]");
expect(nativeLog).not.toContain(imagePath);
});
it("normalizes native image generation bytes without exposing the provider path", async () => {
process.env.FAKE_CODEX_MODE = "image";
await create();
await instance.adapter.sendTurn({
threadId: "t-image",
text: "make an image",
model: "gpt-5.6-sol",
});
await recorder.until((event) => event.type === "turn.completed");
const image = recorder.events.find(
(event) => event.type === "item.completed" && event.itemType === "assistant_image",
);
expect(image).toMatchObject({
itemType: "assistant_image",