Repository navigation
Expand file tree
/
Copy pathclaude.test.ts
More file actions
4227 lines (3833 loc) · 219 KB
/
Copy pathclaude.test.ts
File metadata and controls
4227 lines (3833 loc) · 219 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 { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { createServer as createHttpServer, type IncomingHttpHeaders } from "node:http";
import { connect, createServer as createNetServer, type AddressInfo, type Socket } from "node:net";
import { homedir, tmpdir } from "node:os";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR, ensureDirs, instanceConfigs, NATIVE_DIR, type AppConfig } from "../config.ts";
import { TurnAuthenticationRefusedError, type ProviderInstance } from "../contracts.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { BACKGROUND_CALL_TIMEOUT_MS, BACKGROUND_SETTINGS, backgroundCallArgs } from "./claude-background.ts";
import {
autoCompactWindow,
brokerSocketCandidates,
claudeCliSupports,
claudeCliUpdate,
claudeHookSettings,
ClaudeDriver,
createPermissionBroker,
hookTokenFile,
parseClaudeCliVersion,
permissionSocketPath,
readClaudeAuthSettings,
claudeCostSnapshot,
restoredCostBase,
STEERED_CONTINUATION_GRACE_MS,
sumNativeTurnResults,
turnCostFromRunningTotal,
type ClaudeConfig,
} from "./claude.ts";
import { TEAM_TOOLS_FAILED } from "./team-tools.ts";
import { claudeLimitMessage } from "./claude-limits.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { rebuiltSessionNotice } from "../resume-recovery.ts";
import { BASH_MAX_TIMEOUT_MS } from "../system-prompt.ts";
import { ephemeralWorkspaceTokenPath } from "../workspace-backup-policy.ts";
import * as procs from "../procs.ts";
import * as localInject from "./local-inject.ts";
const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");
const dumpedPid = (dump: string): number => JSON.parse(readFileSync(dump, "utf8")).pid;
/** Each must truncate to a unique 8-char tag so no two tests share a broker socket. */
const COLLISION_THREAD_IDS = ["t-dup-1", "t-dup-2", "t-dup-3", "t-dup-4"];
function connectSocket(path: string): Promise<Socket> {
return new Promise((resolve, reject) => {
let retriesLeft = 20;
const tryConnect = () => {
const conn = connect(path);
const onConnect = () => {
conn.removeListener("error", onError);
resolve(conn);
};
const onError = (error: NodeJS.ErrnoException) => {
conn.removeListener("connect", onConnect);
conn.destroy();
// A Windows named pipe can briefly disappear while the server creates its next instance.
if (process.platform === "win32" && error.code === "ENOENT" && retriesLeft-- > 0) {
setTimeout(tryConnect, 25);
return;
}
reject(error);
};
conn.once("connect", onConnect);
conn.once("error", onError);
};
tryConnect();
});
}
function answerQueue(conn: ReturnType<typeof connect>) {
const waiters: Array<(msg: any) => void> = [];
let buf = "";
conn.on("data", (chunk) => {
buf += chunk;
let nl;
while ((nl = buf.indexOf("\n")) !== -1) {
const line = buf.slice(0, nl);
buf = buf.slice(nl + 1);
waiters.shift()?.(JSON.parse(line));
}
});
return () => new Promise<any>((resolve) => waiters.push(resolve));
}
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("ClaudeDriver.decodeConfig", () => {
it("quotes hook paths as shell data rather than JSON strings", () => {
const settings = claudeHookSettings("/tmp/it's $OMB_HOOK_TEST `literal`/helper.ts") as { PostToolUse: Array<{ hooks: Array<{ command: string }> }> };
const command = settings.PostToolUse[0]!.hooks[0]!.command;
if (process.platform === "win32") {
expect(command).toBe('"%OMB_HOOK_NODE%" "%OMB_HOOK_HELPER%"');
} else {
expect(command).toContain("'/tmp/it'\\''s $OMB_HOOK_TEST `literal`/helper.ts'");
}
});
it("hooks failed tool calls too, so a timed-out command can be given a hint", () => {
expect(Object.keys(claudeHookSettings("/tmp/helper.ts"))).toContain("PostToolUseFailure");
});
it("keeps the per-turn hook token where workspace backups never look", () => {
const path = relative(DATA_DIR, hookTokenFile("thread", "bot")).replaceAll("\\", "/");
expect(ephemeralWorkspaceTokenPath(path)).toBe(true);
expect(ephemeralWorkspaceTokenPath(path.split("/")[0]!)).toBe(true);
});
it("defaults to the claude binary with acceptEdits", () => {
expect(ClaudeDriver.decodeConfig({})).toEqual({ cli: "claude", permissionMode: "acceptEdits" });
expect(ClaudeDriver.decodeConfig(undefined)).toEqual({ cli: "claude", permissionMode: "acceptEdits" });
});
it("bills a steered continuation's native results as one turn", () => {
const first = { ok: true, stopReason: "end_turn", cost: 0.01, usage: { input: 12, output: 5, cachedInput: 2 } };
expect(sumNativeTurnResults(null, first)).toEqual(first);
expect(sumNativeTurnResults(first, { ok: true, stopReason: "end_turn", cost: 0.03, usage: { input: 3, output: 4 } }))
.toEqual({ ok: true, stopReason: "end_turn", cost: 0.03, usage: { input: 15, output: 9, cachedInput: 2 } });
expect(sumNativeTurnResults(first, { ok: false, stopReason: null, cost: null }))
.toEqual({ ok: false, stopReason: "end_turn", cost: 0.01, usage: first.usage });
expect(sumNativeTurnResults({ ok: true, stopReason: null, cost: null }, { ok: true, stopReason: null, cost: null }))
.toEqual({ ok: true, stopReason: null, cost: null });
});
it("accepts the three known permission modes", () => {
for (const permissionMode of ["acceptEdits", "auto", "bypassPermissions"] as const) {
expect(ClaudeDriver.decodeConfig({ permissionMode }).permissionMode).toBe(permissionMode);
}
});
it("books a turn's share of the CLI's running cost total", () => {
expect(turnCostFromRunningTotal(1.5822674, null)).toBe(1.5822674);
expect(turnCostFromRunningTotal(1.7255570000000002, 1.5822674)).toBe(0.1432896);
expect(turnCostFromRunningTotal(0.03, 0.02)).toBe(0.01);
expect(turnCostFromRunningTotal(0.02, 0.02)).toBe(0);
expect(turnCostFromRunningTotal(null, 0.02)).toBeNull();
expect(turnCostFromRunningTotal(0.004, 0.02)).toBe(0.004);
});
it("finds the running cost the CLI restored for a resumed session", () => {
// Real 2.1.282 frames: modelUsage is [input, cache read, cache write, output] per model for the session.
const opus = (total: number, tokens: [number, number, number, number]) => claudeCostSnapshot(total, {
"claude-opus-5-5": { inputTokens: tokens[0], cacheReadInputTokens: tokens[1], cacheCreationInputTokens: tokens[2], outputTokens: tokens[3], costUSD: total },
})!;
const earlier = [
opus(1.5822674, [18, 776097, 103347, 30010]),
opus(1.7255570000000002, [24, 1167845, 107739, 31499]),
opus(3.2557024000000006, [34, 1682172, 227804, 54835]),
opus(4.3538464, [36, 1682172, 353781, 59351]),
];
const resumed = opus(4.212299000000001, [60, 3542515, 254587, 73343]);
expect(restoredCostBase(earlier, resumed, { input: 26, cacheRead: 1860343, cacheWrite: 26783, output: 18508 })).toBe(3.2557024000000006);
const fresh = claudeCostSnapshot(0.20990999999999999, {
"claude-haiku-4-5-20251001": { inputTokens: 978, cacheReadInputTokens: 0, cacheCreationInputTokens: 0, outputTokens: 10, costUSD: 0.001028 },
"claude-sonnet-5": { inputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 52057, outputTokens: 65, costUSD: 0.208882 },
})!;
expect(restoredCostBase([], fresh, { input: 2, cacheRead: 0, cacheWrite: 52057, output: 65 })).toBe(0);
const beforeInterrupt = opus(0.8265352, [20, 559016, 79339, 3997]);
const afterInterrupt = opus(3.0735268, [86, 4211334, 254837, 9611]);
expect(restoredCostBase([beforeInterrupt], afterInterrupt, { input: 48, cacheRead: 2873716, cacheWrite: 142479, output: 3805 })).toBe(0.8265352);
expect(restoredCostBase([], resumed, { input: 26, cacheRead: 1860343, cacheWrite: 26783, output: 18508 })).toBe(0);
expect(claudeCostSnapshot(null, {})).toBeNull();
});
it("matches a resumed turn split over two models by the sum of its growth", () => {
const state = (total: number, models: Record<string, number>) => claudeCostSnapshot(total, Object.fromEntries(
Object.entries(models).map(([model, input]) => [model, { inputTokens: input, cacheReadInputTokens: 0, cacheCreationInputTokens: 0, outputTokens: 0, costUSD: 0 }]),
))!;
const earlier = [state(0.01, { A: 2 }), state(0.02, { A: 3 })];
expect(restoredCostBase(earlier, state(0.03, { A: 3, B: 1 }), { input: 2, cacheRead: 0, cacheWrite: 0, output: 0 })).toBe(0.01);
});
it("measures from the latest known state, not the highest total", () => {
const state = (total: number, input: number) => claudeCostSnapshot(total, {
A: { inputTokens: input, cacheReadInputTokens: 0, cacheCreationInputTokens: 0, outputTokens: 0, costUSD: total },
})!;
const earlier = [state(0.05, 5), state(0.03, 4)];
expect(restoredCostBase(earlier, state(0.06, 8), { input: 1, cacheRead: 0, cacheWrite: 0, output: 0 })).toBe(0.03);
});
it("throws on an invalid permissionMode (registry downgrades this to a shadow)", () => {
expect(() => ClaudeDriver.decodeConfig({ permissionMode: "yolo" })).toThrow(/permissionMode/);
});
it("normalizes and deduplicates built-in tool lists", () => {
expect(
ClaudeDriver.decodeConfig({
tools: [" Read ", "WebFetch", "Read"],
disallowedTools: [" Bash(git *) ", "Bash(git *)"],
}),
).toMatchObject({
tools: ["Read", "WebFetch"],
disallowedTools: ["Bash(git *)"],
});
expect(ClaudeDriver.decodeConfig({ tools: [] }).tools).toEqual([]);
});
it.each([
["tools", "Read"],
["tools", ["Read", " "]],
["disallowedTools", [42]],
])("rejects invalid %s configuration", (field, value) => {
expect(() => ClaudeDriver.decodeConfig({ [field]: value })).toThrow(new RegExp(field));
});
it.skipIf(process.platform !== "win32")("names permission pipes per harness process", () => {
expect(permissionSocketPath("thread-abc")).toMatch(
new RegExp(`^\\\\\\\\\\.\\\\pipe\\\\openmausbot-perm-${process.pid}-thre[0-9a-f]{4}$`),
);
});
it("keeps threads whose ids share a prefix on distinct sockets", () => {
// Only the digest separates them; Windows pipes would otherwise collide.
expect(permissionSocketPath("t-perm-dup-1")).not.toBe(permissionSocketPath("t-perm-dup-2"));
});
it("advertises per-bot local CUA but rejects legacy bypass turns without a mode", async () => {
const bypass = await ClaudeDriver.create({
instanceId: "claude-bypass",
displayName: "Claude Bypass",
environment: {},
enabled: true,
config: { cli: FAKE_CLI, permissionMode: "bypassPermissions" },
});
expect(bypass.adapter.capabilities.localComputerMcp).toBe(true);
await expect(
bypass.adapter.sendTurn({
threadId: "t-bypass-local",
text: "click",
integrations: {
localComputer: {
command: "/cua-driver",
args: ["mcp"],
env: {},
platform: "linux",
scope: "local-computer",
},
},
}),
).rejects.toThrow(/interactive approval broker/);
expect(bypass.startAuthentication).toBeTypeOf("function");
expect(bypass.signOut).toBeTypeOf("function");
await bypass.dispose();
});
it("gives each collision test a distinct broker pipe path", () => {
const paths = COLLISION_THREAD_IDS.map((threadId) => permissionSocketPath(threadId));
expect(new Set(paths).size).toBe(COLLISION_THREAD_IDS.length);
});
it("gives two bots distinct broker pipes even if they ever share a threadId (#1017)", () => {
const sharedThreadId = "t-shared-by-parent-and-child";
const parentPath = permissionSocketPath(sharedThreadId, "bot-chief");
const childPath = permissionSocketPath(sharedThreadId, "bot-cliff");
expect(parentPath).not.toBe(childPath);
});
it("disposes its account controller while a logout is running", async () => {
const home = mkdtempSync(join(tmpdir(), "omb-claude-logout-dispose-"));
const cli = join(home, "fake-logout.mjs");
const pidPath = join(home, "logout-pid");
writeFileSync(cli, [
"#!/usr/bin/env node",
'import { writeFileSync } from "node:fs";',
'import { join } from "node:path";',
'if (process.argv.slice(2).join(" ") !== "auth logout") process.exit(2);',
'writeFileSync(join(process.env.HOME, "logout-pid"), String(process.pid));',
'setInterval(() => {}, 1000);',
].join("\n"), { mode: 0o700 });
const instance = await ClaudeDriver.create({
instanceId: "claude-logout-dispose", displayName: "Fixture", enabled: true,
config: { cli, permissionMode: "acceptEdits" },
environment: { HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, ".claude") },
});
const pending = instance.signOut!().catch(() => {});
let pid: number | undefined;
const alive = (value: number) => { try { process.kill(value, 0); return true; } catch { return false; } };
try {
await expect.poll(() => existsSync(pidPath), { timeout: 2500 }).toBe(true);
pid = Number(readFileSync(pidPath, "utf8"));
await instance.dispose();
expect(alive(pid)).toBe(false);
await expect(instance.signOut!()).rejects.toThrow("provider was removed");
} finally {
if (pid !== undefined && alive(pid)) {
if (process.platform === "win32") process.kill(pid, "SIGKILL");
else process.kill(-pid, "SIGKILL");
}
await pending;
await instance.dispose();
await removeTempDir(home);
}
}, 60_000);
it("keeps the deterministic path as the first broker candidate", () => {
const candidates = brokerSocketCandidates("t-candidates");
expect(candidates[0]).toBe(permissionSocketPath("t-candidates"));
if (process.platform === "win32") {
expect(candidates.length).toBeGreaterThan(1);
expect(new Set(candidates).size).toBe(candidates.length);
} else {
expect(candidates).toHaveLength(2);
expect(candidates[1]).toMatch(/omb-perm-[0-9a-f]{16}\.sock$/);
expect(candidates[1]).not.toBe(candidates[0]);
}
});
// Windows cannot listen on filesystem socket paths (EACCES); the fake-CLI e2e covers its pipe fallback.
it.skipIf(process.platform === "win32")(
"binds the next candidate when the first is unbindable, and asks round-trip on it",
async () => {
const dir = mkdtempSync(join(tmpdir(), "omb-broker-fallback-"));
const held = join(dir, "held.sock");
// A directory squats the path the way a hung child holds a pipe.
mkdirSync(held);
const free = join(dir, "free.sock");
const asks: Array<{ id: string }> = [];
const broker = await createPermissionBroker({
socketPaths: [held, free],
onAsk: (ask) => asks.push(ask),
onResolve: () => {},
});
try {
expect(broker.socketPath).toBe(free);
const conn = connect(free);
await new Promise<void>((resolve, reject) => {
conn.on("connect", resolve);
conn.on("error", reject);
});
const answered = new Promise<{ behavior: string }>((resolve) => {
let buf = "";
conn.on("data", (c) => {
buf += c;
const nl = buf.indexOf("\n");
if (nl !== -1) resolve(JSON.parse(buf.slice(0, nl)));
});
});
conn.write(JSON.stringify({ t: "ask", id: "ask-fb", tool: "Bash", input: { command: "echo hi" } }) + "\n");
await expect.poll(() => asks.length).toBe(1);
expect(broker.answer("ask-fb", "allow")).toBe(true);
expect(await answered).toMatchObject({ behavior: "allow" });
conn.end();
} finally {
broker.close();
rmSync(dir, { recursive: true, force: true });
}
},
);
it.skipIf(process.platform === "win32")(
"keeps a large non-ASCII ask whole across socket reads",
async () => {
const dir = mkdtempSync(join(tmpdir(), "omb-broker-utf8-"));
const socketPath = join(dir, "broker.sock");
const asks: Array<{ input: unknown }> = [];
const broker = await createPermissionBroker({
socketPaths: [socketPath],
onAsk: (ask) => asks.push(ask),
onResolve: () => {},
});
try {
// One line spans many reads, and most read boundaries fall inside a three-byte character.
const content = "中文ok€".repeat(150_000);
const conn = connect(socketPath);
await new Promise<void>((resolve, reject) => {
conn.on("connect", resolve);
conn.on("error", reject);
});
conn.write(JSON.stringify({ t: "ask", id: "ask-utf8", tool: "Write", input: { file_path: "notes.md", content } }) + "\n");
await expect.poll(() => asks.length, { timeout: 20_000 }).toBe(1);
const received = (asks[0]!.input as { content: string }).content;
expect(received.includes("\uFFFD")).toBe(false);
expect(received === content).toBe(true);
conn.destroy();
} finally {
broker.close();
rmSync(dir, { recursive: true, force: true });
}
},
30_000,
);
it.skipIf(process.platform === "win32")(
"rejects instead of returning an occupied path when every candidate is unavailable",
async () => {
const dir = mkdtempSync(join(tmpdir(), "omb-broker-unavailable-"));
const heldOne = join(dir, "held-one.sock");
const heldTwo = join(dir, "held-two.sock");
mkdirSync(heldOne);
mkdirSync(heldTwo);
try {
await expect(
createPermissionBroker({
socketPaths: [heldOne, heldTwo],
onAsk: () => {},
onResolve: () => {},
}),
).rejects.toThrow(/could not bind a local socket/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
},
);
});
describe("ClaudeDriver turns (fake CLI)", () => {
let instance: ProviderInstance;
let recorder: EventRecorder;
let scratch: string;
const create = async (
mode?: string,
environment: Record<string, string> = {},
config: Partial<ClaudeConfig> = {},
) => {
if (mode) process.env.FAKE_CLAUDE_MODE = mode;
instance = await ClaudeDriver.create({
instanceId: "claude-test",
displayName: "Claude Test",
environment,
enabled: true,
config: {
...config,
cli: config.cli ?? FAKE_CLI,
permissionMode: config.permissionMode ?? "acceptEdits",
},
});
recorder = recordEvents(instance.adapter);
};
beforeEach(() => {
ensureDirs();
chmodSync(FAKE_CLI, 0o755);
scratch = mkdtempSync(join(tmpdir(), "omb-claude-test-"));
});
it("refuses an unsupported native selection before launching, even with instance tools and Full access", async () => {
const dump = join(scratch, "scope-refused.json"); process.env.FAKE_CLAUDE_DUMP = dump;
await create("echo", {}, { tools: ["Read"], disallowedTools: ["Write"] });
await expect(instance.adapter.sendTurn({ threadId: "scope-refused", text: "Must not run", toolScope: { allow: ["native:Read", "native:Write"] }, approvalMode: "full", guestConfined: true })).rejects.toThrow(/native tool selection.*not supported/i);
expect(existsSync(dump)).toBe(false);
});
it("gates every eligible MCP mount while preserving guest and instance restrictions", async () => {
const dump = join(scratch, "scope-mcp.json"); process.env.FAKE_CLAUDE_DUMP = dump;
await create("echo", { FAKE_CLAUDE_VERSION: "2.1.284" }, { tools: ["Read"], disallowedTools: ["Write"] });
await instance.adapter.sendTurn({ threadId: "scope-mcp", text: "Fixture", approvalMode: "ask", guestConfined: true, toolScope: { allow: ["native:*", "mcp:agents:list_bots"] }, integrations: {
agents: { command: "node", args: ["agents"], env: {} }, browser: { command: "node", args: ["browser"], env: {} },
} });
await recorder.until((event) => event.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv).toContain("--restricted");
expect(seen.argv[seen.argv.indexOf("--disallowedTools") + 1]).toBe("Write");
expect(seen.mcpConfig.mcpServers).not.toHaveProperty("browser");
expect(JSON.parse(seen.mcpConfig.mcpServers.agents.env.OMB_GATE_TOOL_SCOPE)).toEqual({ allow: ["native:*", "mcp:agents:list_bots"] });
});
it("keeps a bot's tool selection working with the person's own skills", async () => {
const dump = join(scratch, "scope-user-skills.json"); process.env.FAKE_CLAUDE_DUMP = dump;
await create();
await instance.adapter.sendTurn({ threadId: "scope-user-skills", text: "Fixture", userSkillsDir: join(scratch, "claude-user-skills"), toolScope: { allow: ["native:*"] } });
await recorder.until((event) => event.type === "turn.completed");
expect(JSON.parse(readFileSync(dump, "utf8")).argv).toContain("--add-dir");
});
it("refuses native MCP inheritance when a bot has an explicit selection", async () => {
const dump = join(scratch, "scope-inherited-mcp.json"); process.env.FAKE_CLAUDE_DUMP = dump;
await create();
await expect(instance.adapter.sendTurn({ threadId: "scope-inherited-mcp", text: "Must not run", mcpFromUserConfig: true, toolScope: { allow: ["native:*"] } })).rejects.toThrow(/restricted MCP configuration/);
expect(existsSync(dump)).toBe(false);
});
afterEach(async () => {
delete process.env.FAKE_CLAUDE_MODE;
delete process.env.FAKE_CLAUDE_AUTO_UNAVAILABLE_MODELS;
delete process.env.FAKE_CLAUDE_DUMP;
delete process.env.FAKE_CLAUDE_PROMPTS;
delete process.env.FAKE_CLAUDE_TRANSIENTS;
delete process.env.FAKE_CLAUDE_PARTIAL_FAILS;
delete process.env.FAKE_CLAUDE_STATE;
delete process.env.FAKE_CLAUDE_RETRY_SCALE;
delete process.env.FAKE_CLAUDE_TEXT_HANG;
delete process.env.FAKE_CLAUDE_STEER_GRACE_SCALE;
delete process.env.FAKE_CLAUDE_STEER_SILENCE_SCALE;
delete process.env.ANTHROPIC_API_KEY;
delete process.env.XAI_API_KEY;
delete process.env.COMPOSIO_API_KEY;
delete process.env.BOX_TOKEN;
delete process.env.OPENCODE_API_KEY;
delete process.env.OMB_TTS_KEY;
for (const name of Object.keys(CONTROL_PLANE_FIXTURE)) delete process.env[name];
delete process.env.OMB_CLAUDE_SESSION_IDLE_MS;
delete process.env.OMB_CLAUDE_SESSION_IDLE_MIN_MS;
recorder?.stop();
await instance?.dispose();
await removeTempDir(scratch);
});
it.each([
["without a workspace URL", { key: "sk-ant-workspace-secret" }],
["with a workspace URL", { key: "sk-ant-workspace-secret", url: "http://127.0.0.1:9" }],
])("sends a router instance's turn to its own host with only its own token (%s)", async (_label, anthropic) => {
const seen: IncomingHttpHeaders[] = [];
const router = createHttpServer((request, response) => {
seen.push(request.headers);
request.resume();
response.end("{}");
});
await new Promise<void>((resolve) => router.listen(0, "127.0.0.1", resolve));
try {
const base = `http://127.0.0.1:${(router.address() as AddressInfo).port}`;
const map = instanceConfigs({
anthropic,
instances: {
claude: { driver: "claudeAgent" },
router: { driver: "claudeAgent", environment: { ANTHROPIC_BASE_URL: base, ANTHROPIC_AUTH_TOKEN: "router-token" } },
},
});
expect(map.claude!.environment).toMatchObject({ ANTHROPIC_API_KEY: "sk-ant-workspace-secret" });
process.env.FAKE_CLAUDE_ROUTER_PING = "1";
await create(undefined, map.router!.environment as Record<string, string>);
await instance.adapter.sendTurn({ threadId: "t-router", text: "hi", model: "claude-sonnet-5" });
await recorder.until((e) => e.type === "turn.completed");
expect(seen).toHaveLength(1);
expect(seen[0]!.authorization).toBe("Bearer router-token");
expect(seen[0]!["x-api-key"]).toBeUndefined();
expect(JSON.stringify(seen)).not.toContain("sk-ant-workspace-secret");
} finally {
delete process.env.FAKE_CLAUDE_ROUTER_PING;
await new Promise((resolve) => router.close(resolve));
}
});
it("normalizes a full turn into the canonical event sequence", async () => {
await create();
const { turnId } = await instance.adapter.sendTurn({ threadId: "t-happy", text: "hi", model: "claude-sonnet-5" });
await recorder.until((e) => e.type === "turn.completed");
const types = recorder.events.map((e) => e.type);
expect(types).toEqual([
"turn.started",
"session.started",
"content.delta",
"item.completed",
"item.started",
"thread.token-usage.updated",
"item.completed",
"turn.completed",
]);
expect(recorder.events.every((e) => e.turnId === turnId && e.provider === "claudeAgent")).toBe(true);
expect(recorder.events.find((e) => e.type === "item.started")).toMatchObject({ title: "Bash", summary: "echo hi" });
expect(recorder.events.find((e) => e.type === "item.started")).toMatchObject({ input: expect.stringContaining("echo hi") });
expect(recorder.events.find((e) => e.type === "item.completed" && e.itemType === "tool")).toMatchObject({ output: expect.stringContaining('"text": "hi"') });
const usage = recorder.events.find((e) => e.type === "thread.token-usage.updated")!;
expect(usage).toMatchObject({ input: 12, output: 5, cachedInput: 2 });
const done = recorder.events.at(-1)!;
expect(done).toMatchObject({ type: "turn.completed", ok: true, cost: 0.01, usage: { input: 12, output: 5, cachedInput: 2 } });
expect(instance.adapter.hasSession("t-happy")).toBe(false);
});
it("streams partial-message text deltas without re-emitting the whole message", async () => {
await create("stream");
await instance.adapter.sendTurn({ threadId: "t-stream", text: "hi" });
await recorder.until((e) => e.type === "turn.completed");
const deltas = recorder.events.filter((e) => e.type === "content.delta");
const text = deltas.filter((d: any) => d.streamKind === "assistant_text");
expect(text.map((d: any) => d.delta)).toEqual(["hello from ", "fake claude"]);
expect(text.some((d: any) => d.delta.includes("SUBAGENT"))).toBe(false);
expect(deltas.some((d: any) => d.streamKind === "reasoning_text" && d.delta === "hmm")).toBe(true);
const settled = recorder.events.filter((e: any) => e.type === "item.completed" && e.itemType === "assistant_text");
expect(settled).toHaveLength(1);
expect((settled[0] as any).text).toBe("hello from fake claude");
});
it("passes on a running tool's heartbeat as tool activity, so a long tool is not taken for a stall", async () => {
await create("tool-heartbeat");
await instance.adapter.sendTurn({ threadId: "t-heartbeat", text: "hi" });
await recorder.until((e) => e.type === "turn.completed");
const types = recorder.events.map((e) => e.type);
const beat = types.indexOf("item.updated");
expect(recorder.events[beat]).toMatchObject({ itemType: "tool" });
expect(beat).toBeGreaterThan(types.indexOf("item.started"));
expect(beat).toBeLessThan(types.lastIndexOf("item.completed"));
});
it("names the CLI process while a long tool runs, and no process once the turn is over", async () => {
const release = join(scratch, "release");
await create(undefined, {
FAKE_CLAUDE_TOOL_CALLS: JSON.stringify([{ name: "Bash", input: { command: "python3 scrape.py" }, hold: "idle" }]), FAKE_CLAUDE_RELEASE: release,
});
await instance.adapter.sendTurn({ threadId: "t-engine-pid", text: "scrape" });
await recorder.until((e) => e.type === "item.started" && e.itemType === "tool");
const pid = instance.adapter.enginePid?.("t-engine-pid");
expect(pid).toEqual(expect.any(Number));
expect(() => process.kill(pid!, 0), "the CLI running this turn").not.toThrow();
writeFileSync(release, "go");
await recorder.until((e) => e.type === "turn.completed");
expect(instance.adapter.enginePid?.("t-engine-pid")).toBeUndefined();
});
it("reports a long Write's input as it streams, after the bot's words and before its tool call", async () => {
await create("slow-write", { FAKE_CLAUDE_WRITE_BYTES: "6144", FAKE_CLAUDE_WRITE_STEP_MS: "5" });
await instance.adapter.sendTurn({ threadId: "t-slow-write", text: "build a dashboard" });
await recorder.until((e) => e.type === "turn.completed", 20_000);
const types = recorder.events.map((e) => e.type);
const started = recorder.events.find((e) => e.type === "item.started") as any;
const progress = recorder.events.filter((e) => e.type === "turn.progress") as any[];
expect(progress.length, "one report per streamed chunk, before the bus coalesces them").toBeGreaterThan(10);
expect(progress.every((e) => e.activity === "write" && e.itemId === started.itemId && e.turnId === started.turnId)).toBe(true);
expect(progress.at(-1)).toMatchObject({ file: "index.html" });
expect(progress.at(-1).bytes).toBeGreaterThanOrEqual(6144);
const intro = recorder.events.findIndex((e: any) => e.type === "item.completed" && e.itemType === "assistant_text");
expect(types.indexOf("turn.progress")).toBeGreaterThan(intro);
expect(types.lastIndexOf("turn.progress")).toBeLessThan(types.indexOf("item.started"));
});
it("turns a signed-out CLI into a setup error, not a bot reply", async () => {
const dump = join(scratch, "signed-out-session.json");
process.env.FAKE_CLAUDE_DUMP = dump;
await create("not-logged-in");
await instance.adapter.sendTurn({ threadId: "t-auth", text: "hi" });
await recorder.until((e) => e.type === "turn.completed");
const failure = recorder.events.find((e: any) => e.type === "runtime.error") as any;
expect(failure).toMatchObject({ message: "Not logged in \u00b7 Please run /login", setup: true });
expect(recorder.events.some((e: any) => e.type === "item.completed" && e.itemType === "assistant_text")).toBe(false);
expect(recorder.events.some((e: any) => e.type === "content.delta")).toBe(false);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "auth_required" });
const pid = dumpedPid(dump);
await expect.poll(() => {
try { process.kill(pid, 0); return false; } catch { return true; }
}, { timeout: 7_000 }).toBe(true);
});
it("reports a synthetic sign-out refusal for recovery only after its process has stopped", async () => {
const dump = join(scratch, "recover-signed-out-session.json");
process.env.FAKE_CLAUDE_DUMP = dump;
await create("not-logged-in");
await expect(instance.adapter.sendTurn({ threadId: "t-auth-recovery", text: "hi", startupRecovery: true }))
.rejects.toBeInstanceOf(TurnAuthenticationRefusedError);
expect(() => process.kill(dumpedPid(dump), 0)).toThrow();
expect(recorder.events.some(event => event.type === "runtime.error" || event.type === "turn.completed")).toBe(false);
});
it("keeps a sign-out after model activity as an ordinary failed turn", async () => {
await create("not-logged-in", { FAKE_CLAUDE_AUTH_AFTER_WORK: "1" });
await expect(instance.adapter.sendTurn({ threadId: "t-auth-work", text: "hi", startupRecovery: true })).resolves.toHaveProperty("turnId");
expect(await recorder.until(event => event.type === "turn.completed"))
.toMatchObject({ ok: false, stopReason: "auth_required" });
expect(recorder.events.find(event => event.type === "runtime.error"))
.toMatchObject({ message: "Not logged in · Please run /login", setup: true });
});
it("recovers a later sign-out in a retained process without counting earlier turns as new work", async () => {
const dump = join(scratch, "retained-sign-out.json");
process.env.FAKE_CLAUDE_DUMP = dump;
await create("happy", { FAKE_CLAUDE_AUTH_AFTER_TURN: "1" });
const turn = { threadId: "t-auth-retained", text: "hi", startupRecovery: true };
const first = await instance.adapter.sendTurn(turn);
await recorder.until(event => event.type === "turn.completed" && event.turnId === first.turnId);
const pid = dumpedPid(dump);
await expect(instance.adapter.sendTurn({ ...turn, text: "again" })).rejects.toBeInstanceOf(TurnAuthenticationRefusedError);
expect(dumpedPid(dump)).toBe(pid);
expect(() => process.kill(pid, 0)).toThrow();
});
it("settles an outdated CLI as update_required without emitting an assistant reply", async () => {
const message = "API Error: 400 Claude Code 2.1.268 does not support this model; version 2.1.280 or newer is required. Run 'claude update'.";
await create("api-error", { FAKE_CLAUDE_API_ERROR: message });
await instance.adapter.sendTurn({ threadId: "t-update", text: "hi" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events).toContainEqual(expect.objectContaining({
type: "runtime.error", message, setup: true, claudeUpdate: true,
}));
expect(recorder.events.some((event) => event.type === "item.completed" && event.itemType === "assistant_text")).toBe(false);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "update_required" });
});
it("settles a turn its account's weekly limit refused as quota, saying when it resets, with no reply", async () => {
const resetsAt = Math.floor(Date.now() / 1000) + 3 * 86_400;
const weekly = { status: "rejected", resetsAt, rateLimitType: "seven_day", overageStatus: "rejected", isUsingOverage: false };
await create("usage-limit", { FAKE_CLAUDE_RATE_LIMIT: JSON.stringify(weekly) });
await instance.adapter.sendTurn({ threadId: "t-weekly", text: "Hey talk to @Tango" });
await recorder.until((event) => event.type === "turn.completed");
const errors = recorder.events.filter((event) => event.type === "runtime.error");
expect(errors).toEqual([expect.objectContaining({ message: claudeLimitMessage({ window: "seven_day", resetsAt }), limitResetsAt: resetsAt * 1000, limit: "engine" })]);
expect((errors[0] as any).message).toMatch(/^This Claude account has reached its weekly limit, which resets .+\. Until then, /);
expect(errors[0]).not.toHaveProperty("setup");
expect(errors[0]).not.toHaveProperty("claudeUpdate");
expect(recorder.events.some((event) => event.type === "item.completed" && event.itemType === "assistant_text")).toBe(false);
expect(recorder.events.some((event) => event.type === "content.delta")).toBe(false);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });
});
it("settles a turn whose model's extra-usage credits ran out as quota, without holding the engine", async () => {
const resetsAt = Math.floor(Date.now() / 1000) + 11 * 86_400;
const credits = { status: "rejected", resetsAt, overageDisabledReason: "out_of_credits", isUsingOverage: false, errorCode: "credits_required" };
await create("usage-limit", { FAKE_CLAUDE_RATE_LIMIT: JSON.stringify(credits) });
await instance.adapter.sendTurn({ threadId: "t-credits", text: "continue" });
await recorder.until((event) => event.type === "turn.completed");
const errors = recorder.events.filter((event) => event.type === "runtime.error");
expect(errors).toEqual([expect.objectContaining({ message: claudeLimitMessage({ window: null, resetsAt, credits: true }), limit: "credits" })]);
expect((errors[0] as any).message).toContain("those credits are used up");
expect(errors[0]).not.toHaveProperty("limitResetsAt");
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });
});
it("settles a turn its model's own weekly window refused as that model's limit, with that window's reset", async () => {
const resetsAt = Math.floor(Date.now() / 1000) + 2 * 86_400;
const opus = { status: "rejected", resetsAt, rateLimitType: "seven_day_opus", overageStatus: "rejected", isUsingOverage: false };
await create("usage-limit", { FAKE_CLAUDE_RATE_LIMIT: JSON.stringify(opus) });
await instance.adapter.sendTurn({ threadId: "t-opus-window", text: "continue" });
await recorder.until((event) => event.type === "turn.completed");
const errors = recorder.events.filter((event) => event.type === "runtime.error");
expect(errors).toEqual([expect.objectContaining({ limit: "model", limitResetsAt: resetsAt * 1000 })]);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });
});
it("names the weekly limit behind an older CLI's update request, and offers no update", async () => {
const resetsAt = Math.floor(Date.now() / 1000) + 86_400;
await create("api-error", {
FAKE_CLAUDE_API_ERROR: "API Error: 400 Claude Code 2.1.272 does not support this model; version 2.1.280 or newer is required. Run 'claude update'.",
FAKE_CLAUDE_RATE_LIMIT: JSON.stringify({ status: "rejected", resetsAt, rateLimitType: "seven_day", isUsingOverage: false }),
});
await instance.adapter.sendTurn({ threadId: "t-weekly-old-cli", text: "hi" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.filter((event) => event.type === "runtime.error")).toEqual([
expect.objectContaining({ message: claudeLimitMessage({ window: "seven_day", resetsAt }) }),
]);
expect(recorder.events.some((event) => event.type === "runtime.error" && (event.claudeUpdate || event.setup))).toBe(false);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });
});
it("still offers the update to an account near, not past, its limit", async () => {
const message = "API Error: 400 Claude Code 2.1.268 does not support this model; version 2.1.280 or newer is required. Run 'claude update'.";
await create("api-error", {
FAKE_CLAUDE_API_ERROR: message,
FAKE_CLAUDE_RATE_LIMIT: JSON.stringify({ status: "allowed_warning", resetsAt: Math.floor(Date.now() / 1000) + 86_400, rateLimitType: "seven_day", utilization: 0.97 }),
});
await instance.adapter.sendTurn({ threadId: "t-near-limit", text: "hi" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.filter((event) => event.type === "runtime.error")).toEqual([
expect.objectContaining({ message, setup: true, claudeUpdate: true }),
]);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "update_required" });
});
it.each([
// 2.1.295 on Cloud: no terminal_reason, so the result's only stop token is its synthetic message's "stop_sequence"
[{ FAKE_CLAUDE_API_ERROR: "Credit balance is too low", FAKE_CLAUDE_API_ERROR_KIND: "billing_error", FAKE_CLAUDE_API_ERROR_STATUS: "402", FAKE_CLAUDE_NO_TERMINAL_REASON: "1" },
'Your Claude account is out of credits (Claude says: "Credit balance is too low"). Add credits with Claude, then run it again.', "stop_sequence"],
[{ FAKE_CLAUDE_API_ERROR: "API Error: Repeated 529 Overloaded errors. The API is at capacity — this is usually temporary. Try again in a moment.", FAKE_CLAUDE_API_ERROR_KIND: "overloaded" },
'Claude is overloaded right now (Claude says: "Repeated 529 Overloaded errors"). This is usually temporary, so try again in a few minutes.', "api_error"],
[{ FAKE_CLAUDE_API_ERROR: "There's an issue with the selected model (claude-fixture). It may not exist or you may not have access to it.", FAKE_CLAUDE_API_ERROR_KIND: "model_not_found", FAKE_CLAUDE_NO_TERMINAL_REASON: "1" },
"There's an issue with the selected model (claude-fixture). It may not exist or you may not have access to it.", "stop_sequence"],
])("shows an api-error frame as one plain error row in Claude's real cause, never a reply or a bare stop token (%#)", async (environment, message, stopReason) => {
await create("api-error", environment);
await instance.adapter.sendTurn({ threadId: "t-api-error-words", text: "hi" });
await recorder.until((event) => event.type === "turn.completed");
expect(recorder.events.filter((event) => event.type === "runtime.error")).toEqual([expect.objectContaining({ message })]);
expect(recorder.events.filter((event) => event.type === "runtime.error")[0]).not.toHaveProperty("setup");
expect(recorder.events.some((event) => event.type === "item.completed" && event.itemType === "assistant_text")).toBe(false);
expect(recorder.events.some((event) => event.type === "content.delta")).toBe(false);
expect(recorder.events.some((event) => event.type === "thread.token-usage.updated" && event.contextTokens === 0)).toBe(false);
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason });
});
it("retires an outdated child before retry while preserving a healthy pooled session", async () => {
await create(undefined, {
FAKE_CLAUDE_API_ERROR: "Claude Code 2.1.268 does not support this model; version 2.1.280 or newer is required.",
});
const healthyDump = join(scratch, "healthy-session.json");
process.env.FAKE_CLAUDE_DUMP = healthyDump;
const healthy = await instance.adapter.sendTurn({ threadId: "t-update-healthy", text: "keep this session" });
await recorder.until((event) => event.type === "turn.completed" && event.turnId === healthy.turnId);
const healthyPid = dumpedPid(healthyDump);
process.env.FAKE_CLAUDE_MODE = "api-error";
const outdatedDump = join(scratch, "outdated-session.json");
process.env.FAKE_CLAUDE_DUMP = outdatedDump;
const resumeCursor = "fixture-update-session";
const outdated = await instance.adapter.sendTurn({ threadId: "t-update-retry", text: "try the model", resumeCursor });
await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === outdated.turnId))
.resolves.toMatchObject({ ok: false, stopReason: "update_required" });
const outdatedPid = JSON.parse(readFileSync(outdatedDump, "utf8")).pid;
// Only a new child sees this replacement runtime; a pooled child keeps its loaded code.
process.env.FAKE_CLAUDE_MODE = "happy";
const retryDump = join(scratch, "updated-session.json");
process.env.FAKE_CLAUDE_DUMP = retryDump;
const retry = await instance.adapter.sendTurn({ threadId: "t-update-retry", text: "retry explicitly", resumeCursor });
await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === retry.turnId))
.resolves.toMatchObject({ ok: true });
const replacement = JSON.parse(readFileSync(retryDump, "utf8"));
expect(replacement.pid).not.toBe(outdatedPid);
expect(replacement.argv).toContain("--resume");
expect(replacement.argv).toContain(resumeCursor);
const continued = await instance.adapter.sendTurn({ threadId: "t-update-healthy", text: "continue normally" });
await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === continued.turnId))
.resolves.toMatchObject({ ok: true });
expect(dumpedPid(healthyDump)).toBe(healthyPid);
expect(JSON.parse(readFileSync(retryDump, "utf8")).pid).toBe(replacement.pid);
expect(recorder.events.some((event) => event.type === "turn.retrying")).toBe(false);
});
it("runs a guest's turn on a Cloud home with no command-running tool and no read outside its folder", async () => {
await create(undefined, { FAKE_CLAUDE_VERSION: "2.1.284" });
expect(instance.adapter.capabilities.guestTurns).toBe("confined");
// Inside the scratch folder: its removal waits for the CLI to let go of it (Windows).
const folder = mkdtempSync(join(scratch, "guest-folder-"));
writeFileSync(join(folder, ".mcp.json"), JSON.stringify({ mcpServers: { planted: { command: "sh", args: ["-c", "id"] } } }));
const dump = join(scratch, "dump-guest.json");
process.env.FAKE_CLAUDE_DUMP = dump;
await instance.adapter.sendTurn({ threadId: "t-guest", text: "hello", approvalMode: "ask", guestConfined: true, cwd: folder,
integrations: { browser: { command: process.execPath, args: ["fixture-browser"], env: {} } } });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8")) as { argv: string[]; settings: any; mcpConfig: any };
const after = (flag: string) => seen.argv[seen.argv.indexOf(flag) + 1];
expect(seen.argv).toContain("--restricted");
expect(after("--tools")).toBe("Read,Grep,Glob,Edit,Write,WebSearch");
expect(after("--permission-mode")).toBe("default");
expect(seen.settings.permissions).toMatchObject({ blockReadsOutsideWorkingDirectories: true });
expect(seen.settings.permissions.deny).toEqual(expect.arrayContaining(["Bash", "PowerShell", "WebFetch"]));
expect(Object.keys(seen.mcpConfig.mcpServers)).not.toContain("planted");
expect(after("--allowedTools").split(",")).not.toContain("mcp__browser");
expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
});
it("stops a guest's turn when the CLI kept a shell, and refuses one too old to confine it", async () => {
await create(undefined, { FAKE_CLAUDE_VERSION: "2.1.284", FAKE_CLAUDE_KEEP_BASH: "1" });
await instance.adapter.sendTurn({ threadId: "t-kept", text: "hello", approvalMode: "ask", guestConfined: true, confinedWhy: "This routine was made before this update." });
await recorder.until((e) => e.type === "turn.completed");
expect(JSON.stringify(recorder.events)).toContain("kept its shell, so it can't run this turn. Update Claude Code. This routine was made before this update.");
expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: false });
await create(undefined, { FAKE_CLAUDE_VERSION: "2.1.250" });
const refused = await instance.adapter.sendTurn({ threadId: "t-old", text: "hello", approvalMode: "ask", guestConfined: true })
.then(() => recorder.until((e) => e.type === "turn.completed").then((event) => JSON.stringify(event) + JSON.stringify(recorder.events)), (error: unknown) => String(error));
expect(refused).toContain("too old to run this turn without a shell");
});
it("keeps a workspace Anthropic key set on purpose while still dropping one from the parent env", async () => {
await create(undefined, { ANTHROPIC_API_KEY: "sk-ant-workspace-fixture" });
const dump = join(scratch, "dump-workspace-key.json");
process.env.FAKE_CLAUDE_DUMP = dump;
process.env.ANTHROPIC_API_KEY = "sk-should-not-leak";
await instance.adapter.sendTurn({ threadId: "t-workspace-key", text: "hello" });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.env.ANTHROPIC_API_KEY).toBe("sk-ant-workspace-fixture");
});
it("hands a hosted tenant's CLI the hosted model token but none of the operator's control-plane secrets", async () => {
await create(undefined, { ANTHROPIC_API_KEY: "omb_workspace_fixture", ANTHROPIC_AUTH_TOKEN: "omb_workspace_fixture" });
const dump = join(scratch, "dump-hosted.json");
process.env.FAKE_CLAUDE_DUMP = dump;
Object.assign(process.env, CONTROL_PLANE_FIXTURE);
await instance.adapter.sendTurn({ threadId: "t-hosted-env", text: "hello" });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.env.ANTHROPIC_API_KEY).toBe("omb_workspace_fixture");
expect(seen.env.ANTHROPIC_AUTH_TOKEN).toBe("omb_workspace_fixture");
for (const name of Object.keys(CONTROL_PLANE_FIXTURE)) expect(seen.env[name]).toBeUndefined();
});
it("keeps user and system prompts off argv and strips identity env vars", async () => {
await create();
const dump = join(scratch, "dump.json");
process.env.FAKE_CLAUDE_DUMP = dump;
process.env.ANTHROPIC_API_KEY = "sk-should-not-leak";
process.env.XAI_API_KEY = "xai-should-not-leak";
process.env.BOX_TOKEN = "box-should-not-leak";
process.env.OMB_TTS_KEY = "tts-should-not-leak";
await instance.adapter.sendTurn({ threadId: "t-hygiene", text: "the secret prompt", system: "You are Testy." });
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(JSON.stringify(seen.argv)).not.toContain("the secret prompt");
expect(JSON.stringify(seen.argv)).not.toContain("You are Testy.");
expect(seen.prompt).toMatchObject({ type: "user", message: { role: "user", content: "the secret prompt" } });
expect(seen.argv).toContain("--append-system-prompt-file");
expect(seen.systemPrompt).toBe("You are Testy.");
expect(existsSync(seen.argv[seen.argv.indexOf("--append-system-prompt-file") + 1])).toBe(false);
expect(seen.argv).toContain("--session-id");
expect(seen.env.ANTHROPIC_API_KEY).toBeUndefined();
expect(seen.env.CLAUDECODE).toBeUndefined();
expect(seen.env.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();
expect(seen.env.XAI_API_KEY).toBeUndefined();
expect(seen.env.BOX_TOKEN).toBeUndefined();
expect(seen.env.OMB_TTS_KEY).toBeUndefined();
});
it("per-bot Ask restores the broker on a legacy bypass instance", async () => {
await create(undefined, {}, { permissionMode: "bypassPermissions" });
const dump = join(scratch, "ask-overrides-bypass.json");
process.env.FAKE_CLAUDE_DUMP = dump;
await instance.adapter.sendTurn({
threadId: "t-ask-overrides-bypass",
text: "go",
approvalMode: "ask",
});
await recorder.until((e) => e.type === "turn.completed");
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv).toContain("--permission-mode");
expect(seen.argv[seen.argv.indexOf("--permission-mode") + 1]).toBe("default");
expect(seen.argv).toContain("--permission-prompt-tool");
});
it.each(["claude-sonnet-5", "claude-fable-5"])("reapplies Full, Auto, and Ask on the same resumed %s conversation", async (model) => {
await create(undefined, {}, { permissionMode: "bypassPermissions" });
const dump = join(scratch, "approval-transitions.json");
process.env.FAKE_CLAUDE_DUMP = dump;
for (const [approvalMode, nativeMode] of [["full", "bypassPermissions"], ["auto", "auto"], ["edits", "acceptEdits"], ["ask", "default"]] as const) {
const { turnId } = await instance.adapter.sendTurn({
threadId: "t-mode-transitions",
text: "hello",
model,
approvalMode,
resumeCursor: "11111111-1111-4111-8111-111111111111",
});
await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId);
const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv[seen.argv.indexOf("--model") + 1]).toBe(model);
expect(seen.argv[seen.argv.indexOf("--permission-mode") + 1]).toBe(nativeMode);
expect(seen.argv.includes("--permission-prompt-tool")).toBe(approvalMode !== "full");
expect(seen.argv).toContain("--resume");
}
});
it("keeps questions answerable in per-bot Full access", async () => {
await create("hang");
await instance.adapter.sendTurn({ threadId: "t-full-question", text: "go", approvalMode: "full" });
const conn = await connectSocket(permissionSocketPath("t-full-question"));
try {
conn.write(JSON.stringify({ t: "ask", kind: "question", id: "full-question", tool: "ask_user", input: { question: "Which account?" } }) + "\n");
const opened = await recorder.until((e) => e.type === "request.opened");
expect(opened).toMatchObject({ requestType: "question" });
expect(await instance.adapter.respondToRequest("t-full-question", (opened as { requestId: string }).requestId, { behavior: "answer", message: "Work" })).toBe("answered");
} finally {
conn.destroy();
}
});
it("flattens ask_user choices a model sends as {label, description} rows", async () => {
// MiniMax M3 (through the Anthropic-compatible endpoint) answers ask_user with AskUserQuestion-shaped rows.
await create("hang");
await instance.adapter.sendTurn({ threadId: "t-object-choices", text: "go" });
const conn = await connectSocket(permissionSocketPath("t-object-choices"));
try {
conn.write(JSON.stringify({
t: "ask",
kind: "question",
id: "object-choices",
tool: "ask_user",
input: {
question: "Email the Persun COGS breakdown with PDF template now?",
choices: [
{ label: "Yes, email it now", description: "Generate the PDF and send it." },
{ label: "No, skip the email", description: "Leave it as file-only." },
],
},
}) + "\n");
const opened = await recorder.until((e) => e.type === "request.opened") as { requestId: string; choices?: unknown };
expect(opened.choices).toEqual(["Yes, email it now", "No, skip the email"]);
expect(await instance.adapter.respondToRequest("t-object-choices", opened.requestId, { behavior: "answer", message: "No, skip the email" })).toBe("answered");
} finally {
conn.destroy();
}
});
it("draws a multiSelect ask_user as a checkbox question card", async () => {
// In Full access the CLI has no permission prompt tool, so ask_user is the only way to ask.
await create("hang");
await instance.adapter.sendTurn({ threadId: "t-multi-ask", text: "go", approvalMode: "full" });
const conn = await connectSocket(permissionSocketPath("t-multi-ask"));
try {
const questions = [{ question: "Which fruits?", multiSelect: true, options: [{ label: "Apple" }, { label: "Cherry" }] }];
conn.write(JSON.stringify({
t: "ask", kind: "question", id: "multi-ask", tool: "ask_user",
input: { question: "Which fruits?", choices: ["Apple", "Cherry"], questions },
}) + "\n");
const opened = await recorder.until((e) => e.type === "request.opened") as { requestId: string; questions?: unknown; choices?: unknown };
expect(opened.questions).toEqual(questions);
expect(opened.choices).toBeUndefined();
expect(await instance.adapter.respondToRequest("t-multi-ask", opened.requestId, { behavior: "answer", message: "Apple, Cherry" })).toBe("answered");
} finally {
conn.destroy();
}