-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathlocal.mjs
More file actions
10547 lines (9456 loc) · 470 KB
/
Copy pathlocal.mjs
File metadata and controls
10547 lines (9456 loc) · 470 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
/**
* Deterministic local tests (no live model dependency).
* These should run fast and reliably in CI/local environments.
*/
// Harness components that issue their own LLM calls (prefetch, grounding
// evaluator, LLM router) must be disabled for tests that spin up mock HTTP
// servers and count request iterations. Their presence would double-count
// requests and break mock-server-based assertions. Unit tests for those
// modules call them directly with stub classifiers and don't depend on
// these env toggles.
process.env.FRANKLIN_NO_PREFETCH = '1';
process.env.FRANKLIN_NO_EVAL = '1';
process.env.FRANKLIN_NO_ANALYZER = '1';
// 3.15.17 renamed several in-process test fixtures from `local/test-model`
// to `zai/glm-5.1` so persistence tests could verify the write path. That
// rename sidestepped 3.15.16's model-name fixture gate, and audit/stats
// writes started leaking into the user's real ~/.blockrun on every npm
// test run — verified 310 of 370 recent zai/glm-5.1 audit entries were
// mock responses (output_tokens < 10). FRANKLIN_NO_AUDIT short-circuits
// audit + stats persistence at file scope; session persistence is
// controlled separately via setSessionPersistenceDisabled and stays on
// for the resume tests at 489/609.
process.env.FRANKLIN_NO_AUDIT = '1';
// Many tests fetch from a local 127.0.0.1 server; the new SSRF guard blocks
// loopback by default, so opt in here. (The guard's own logic is covered by the
// pure-helper test `isBlockedSsrfHost ...`, which is independent of this env.)
process.env.FRANKLIN_ALLOW_PRIVATE_FETCH = '1';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { execFileSync, spawn } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unwatchFile, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { homedir, tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
const DIST = fileURLToPath(new URL('../dist/index.js', import.meta.url));
const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));
function runCli(prompt = '', { cwd, timeoutMs = 15_000, args, env } = {}) {
return new Promise((resolve, reject) => {
const proc = spawn('node', args ?? [DIST, '--model', 'zai/glm-5.1', '--trust'], {
cwd: cwd ?? tmpdir(),
// FRANKLIN_NO_PERSIST=1 blocks the spawned child from writing
// session jsonl/meta into the real ~/.blockrun/sessions/. Verified
// 2026-05-04: a single `npm test` left 3 ghost metas behind because
// runCli uses `zai/glm-5.1` (real model name → not caught by
// isTestFixtureModel) and inherits HOME from the test process. A
// caller can still override by passing `env: { FRANKLIN_NO_PERSIST: '' }`.
env: { FRANKLIN_NO_PERSIST: '1', ...process.env, ...env },
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
proc.stdout.on('data', (d) => { stdout += d.toString(); });
proc.stderr.on('data', (d) => { stderr += d.toString(); });
proc.stdin.write(prompt + '\n');
proc.stdin.end();
const timer = setTimeout(() => {
proc.kill('SIGTERM');
reject(new Error(`Timeout after ${timeoutMs}ms\nstdout:\n${stdout}\nstderr:\n${stderr}`));
}, timeoutMs);
proc.on('close', (code) => {
clearTimeout(timer);
resolve({ stdout, stderr, code: code ?? 0 });
});
proc.on('error', (err) => {
clearTimeout(timer);
reject(err);
});
});
}
async function listenOnRandomPort(server) {
await new Promise((resolve, reject) => {
server.listen(0, '127.0.0.1', (err) => {
if (err) reject(err);
else resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error(`Unexpected server address: ${String(address)}`);
}
return address.port;
}
async function withPermissionConfigSnapshot(contents, fn) {
const configFile = join(homedir(), '.blockrun', 'franklin-permissions.json');
const preExistedSnapshot = existsSync(configFile) ? readFileSync(configFile, 'utf-8') : null;
try {
if (contents === null) {
rmSync(configFile, { force: true });
} else {
mkdirSync(dirname(configFile), { recursive: true });
writeFileSync(configFile, contents);
}
return await fn();
} finally {
if (preExistedSnapshot === null) {
try { rmSync(configFile, { force: true }); } catch { /* ignore */ }
} else {
try {
mkdirSync(dirname(configFile), { recursive: true });
writeFileSync(configFile, preExistedSnapshot);
} catch { /* ignore */ }
}
}
}
test('cli startup prints the full portrait banner by default', { timeout: 20_000 }, async () => {
const result = await runCli('/exit');
assert.equal(result.code, 0, `CLI exited non-zero.\nstderr:\n${result.stderr}`);
assert.ok(result.stdout.includes('██████╗'), `Default banner should be the full FRANKLIN block-art + portrait.\nstdout:\n${result.stdout}`);
assert.ok(result.stdout.includes('blockrun.ai'), `Banner tagline should include blockrun.ai.\nstdout:\n${result.stdout}`);
assert.ok(result.stdout.includes('The AI agent with a wallet'), `Banner tagline should include the slogan.\nstdout:\n${result.stdout}`);
assert.ok(result.stdout.includes('Wallet:'), `Missing wallet line.\nstdout:\n${result.stdout}`);
assert.ok(result.stderr.includes('Model:'), `Missing model line.\nstderr:\n${result.stderr}`);
});
test('FRANKLIN_BANNER=compact opts into the 2-line banner', { timeout: 20_000 }, async () => {
const result = await runCli('/exit', {
env: { FRANKLIN_BANNER: 'compact' },
});
assert.equal(result.code, 0, `CLI exited non-zero.\nstderr:\n${result.stderr}`);
assert.ok(!result.stdout.includes('██████╗'), `Compact opt-in should drop the block art.\nstdout:\n${result.stdout}`);
assert.ok(result.stdout.includes('blockrun.ai'), `Expected compact tagline.\nstdout:\n${result.stdout}`);
});
test('flags-only start options still honor --help without launching the agent', async () => {
const result = await runCli('', {
args: [DIST, '--model', 'zai/glm-5.1', '--help'],
});
assert.equal(result.code, 0, `CLI exited non-zero.\nstderr:\n${result.stderr}`);
assert.ok(result.stdout.includes('Usage: franklin start [options]'), `Expected start help.\nstdout:\n${result.stdout}`);
assert.ok(!result.stdout.includes('blockrun.ai'), `Help path should not print startup banner.\nstdout:\n${result.stdout}`);
});
test('flags-only start options still honor --version without launching the agent', async () => {
const result = await runCli('', {
args: [DIST, '--model', 'zai/glm-5.1', '--version'],
});
assert.equal(result.code, 0, `CLI exited non-zero.\nstderr:\n${result.stderr}`);
assert.match(result.stdout.trim(), /^\d+\.\d+\.\d+$/, `Expected plain version output.\nstdout:\n${result.stdout}`);
assert.ok(!result.stdout.includes('blockrun.ai'), `Version path should not print startup banner.\nstdout:\n${result.stdout}`);
});
test('--prompt one-shot mode skips interactive startup chatter', async () => {
const result = await runCli('', {
args: [DIST, '--model', 'nvidia/llama-4-maverick', '--prompt', '/exit'],
});
assert.equal(result.code, 0, `CLI exited non-zero.\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`);
assert.ok(!result.stdout.includes('blockrun.ai'), `One-shot mode should not print startup banner.\nstdout:\n${result.stdout}`);
assert.ok(!result.stdout.includes('Wallet:'), `One-shot mode should not print wallet info.\nstdout:\n${result.stdout}`);
assert.ok(!result.stdout.includes('Dashboard:'), `One-shot mode should not print dashboard info.\nstdout:\n${result.stdout}`);
assert.ok(!result.stderr.includes('Model:'), `One-shot mode should not print interactive model warnings.\nstderr:\n${result.stderr}`);
});
test('--prompt preserves non-zero exit code through the CLI entrypoint', async () => {
const result = await runCli('', {
args: [DIST, '--model', 'nvidia/llama-4-maverick', '--prompt', 'hello', '--resume'],
});
assert.equal(result.code, 1, `Expected exit 1 when --prompt is paired with picker-style --resume.\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`);
assert.ok(
result.stderr.includes('`--prompt` requires `--resume` to include an explicit session id.'),
`Expected explicit batch-mode resume error.\nstderr:\n${result.stderr}`,
);
});
test('oneShotExitCodeForTurnReason treats only completed turns as success', async () => {
const { oneShotExitCodeForTurnReason } = await import('../dist/commands/start.js');
assert.equal(oneShotExitCodeForTurnReason('completed'), 0);
assert.equal(oneShotExitCodeForTurnReason('error'), 1);
assert.equal(oneShotExitCodeForTurnReason('budget'), 1);
assert.equal(oneShotExitCodeForTurnReason('no_progress'), 1);
assert.equal(oneShotExitCodeForTurnReason('max_turns'), 1);
assert.equal(oneShotExitCodeForTurnReason('aborted'), 1);
});
test('chain shortcut --help does not mutate saved chain or launch the agent', async () => {
const fakeHome = mkdtempSync(join(tmpdir(), 'rc-chain-help-'));
const chainFile = join(fakeHome, '.blockrun', 'payment-chain');
try {
const result = await runCli('', {
args: [DIST, 'base', '--help'],
env: { HOME: fakeHome },
});
assert.equal(result.code, 0, `CLI exited non-zero.\nstderr:\n${result.stderr}`);
assert.ok(result.stdout.includes('Usage: franklin start [options]'), `Expected start help.\nstdout:\n${result.stdout}`);
assert.ok(!existsSync(chainFile), `Help path should not persist chain config at ${chainFile}`);
assert.ok(!result.stdout.includes('blockrun.ai'), `Help path should not print startup banner.\nstdout:\n${result.stdout}`);
} finally {
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('chain shortcut --version does not mutate saved chain or launch the agent', async () => {
const fakeHome = mkdtempSync(join(tmpdir(), 'rc-chain-version-'));
const chainFile = join(fakeHome, '.blockrun', 'payment-chain');
try {
const result = await runCli('', {
args: [DIST, 'solana', '--version'],
env: { HOME: fakeHome },
});
assert.equal(result.code, 0, `CLI exited non-zero.\nstderr:\n${result.stderr}`);
assert.match(result.stdout.trim(), /^\d+\.\d+\.\d+$/, `Expected plain version output.\nstdout:\n${result.stdout}`);
assert.ok(!existsSync(chainFile), `Version path should not persist chain config at ${chainFile}`);
assert.ok(!result.stdout.includes('blockrun.ai'), `Version path should not print startup banner.\nstdout:\n${result.stdout}`);
} finally {
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('panel HTML wires the Tasks tab (list + detail + /api/tasks polling)', async () => {
// Tasks UI shipped in v3.10.1: sidebar nav, content section, and JS module
// that polls /api/tasks every 10s. html.ts is one giant template literal —
// no JSDOM here, just assert the load-bearing markers are present so the
// backend endpoints stay paired with a UI that calls them.
const htmlUrl = new URL('../dist/panel/html.js', import.meta.url);
const { getHTML } = await import(`${htmlUrl.href}?t=${Date.now()}`);
const html = getHTML();
assert.ok(html.includes('data-tab="tasks"'), 'Missing Tasks tab nav (data-tab="tasks")');
assert.ok(html.includes('id="tab-tasks"'), 'Missing Tasks tab content section (id="tab-tasks")');
assert.ok(html.includes('/api/tasks'), 'Tasks JS module not wired (no /api/tasks fetch)');
});
test('panel HTML wires Calls tab safely (deep link + recording URL escaping)', async () => {
const htmlUrl = new URL('../dist/panel/html.js', import.meta.url);
const { getHTML } = await import(`${htmlUrl.href}?t=${Date.now()}`);
const html = getHTML();
assert.ok(html.includes('data-tab="calls"'), 'Missing Calls tab nav (data-tab="calls")');
assert.ok(html.includes('id="tab-calls"'), 'Missing Calls tab content section (id="tab-calls")');
assert.ok(html.includes('/api/calls?limit=50'), 'Calls JS module not wired (no /api/calls fetch)');
assert.ok(html.includes("if (initialHash === 'calls') loadCalls();"), 'Calls deep link must load journal data');
assert.ok(html.includes('function safeHttpUrl'), 'Calls recording links must be protocol-filtered');
assert.ok(html.includes('escapeHtml(recordingUrl)'), 'Calls recording href must be attribute-escaped');
assert.ok(!html.includes('href="\' + c.recording_url + \'"'), 'Calls recording href must not directly interpolate raw journal data');
});
test('panel server serves dashboard HTML and stats JSON', async () => {
const panelUrl = new URL('../dist/panel/server.js', import.meta.url);
const { createPanelServer } = await import(`${panelUrl.href}?t=${Date.now()}`);
const server = createPanelServer(0);
const port = await listenOnRandomPort(server);
try {
const htmlRes = await fetch(`http://127.0.0.1:${port}/`);
assert.equal(htmlRes.status, 200, `Expected dashboard HTML, got ${htmlRes.status}`);
const html = await htmlRes.text();
assert.ok(html.includes('<title>Franklin Agent Panel</title>'), 'Missing panel title in HTML');
assert.ok(html.includes('Overview'), 'Missing Overview section in HTML');
const statsRes = await fetch(`http://127.0.0.1:${port}/api/stats`);
assert.equal(statsRes.status, 200, `Expected stats JSON, got ${statsRes.status}`);
const stats = await statsRes.json();
assert.equal(typeof stats.totalRequests, 'number');
assert.equal(typeof stats.totalCostUsd, 'number');
assert.equal(typeof stats.byModel, 'object');
} finally {
await new Promise((resolve) => server.close(() => resolve()));
unwatchFile(join(homedir(), '.blockrun', 'franklin-stats.json'));
}
});
test('panel server rejects cross-origin browser requests to spendful phone routes', async () => {
const panelUrl = new URL('../dist/panel/server.js', import.meta.url);
const { createPanelServer } = await import(`${panelUrl.href}?t=${Date.now()}`);
const server = createPanelServer(0);
const port = await listenOnRandomPort(server);
try {
const listRes = await fetch(`http://127.0.0.1:${port}/api/phone/numbers`, {
headers: { Origin: 'https://evil.example' },
});
assert.equal(listRes.status, 403, `Expected cross-origin phone list to be forbidden, got ${listRes.status}`);
const listBody = await listRes.json();
assert.deepEqual(listBody, { error: 'forbidden', numbers: [] });
const buyRes = await fetch(`http://127.0.0.1:${port}/api/phone/numbers/buy`, {
method: 'POST',
headers: {
Origin: 'https://evil.example',
'Content-Type': 'text/plain',
},
body: JSON.stringify({ country: 'US' }),
});
assert.equal(buyRes.status, 403, `Expected cross-origin phone buy to be forbidden, got ${buyRes.status}`);
} finally {
await new Promise((resolve) => server.close(() => resolve()));
unwatchFile(join(homedir(), '.blockrun', 'franklin-stats.json'));
}
});
test('panel server allows same-origin browser requests to guarded routes', async () => {
const panelUrl = new URL('../dist/panel/server.js', import.meta.url);
const { createPanelServer } = await import(`${panelUrl.href}?t=${Date.now()}`);
const server = createPanelServer(0);
const port = await listenOnRandomPort(server);
try {
const res = await fetch(`http://127.0.0.1:${port}/api/phone/numbers/renew`, {
method: 'POST',
headers: {
Origin: `http://127.0.0.1:${port}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
assert.equal(res.status, 400, `Same-origin request should reach handler validation, got ${res.status}`);
const body = await res.json();
assert.equal(body.error, 'phoneNumber required');
} finally {
await new Promise((resolve) => server.close(() => resolve()));
unwatchFile(join(homedir(), '.blockrun', 'franklin-stats.json'));
}
});
test('proxy server handles OPTIONS and local model switching without backend calls', async () => {
const originalHome = process.env.HOME;
const fakeHome = mkdtempSync(join(tmpdir(), 'rc-proxy-home-'));
const proxyUrl = new URL('../dist/proxy/server.js', import.meta.url);
let server;
try {
process.env.HOME = fakeHome;
const { createProxy } = await import(`${proxyUrl.href}?t=${Date.now()}`);
server = createProxy({
port: 0,
apiUrl: 'http://127.0.0.1:9',
chain: 'base',
modelOverride: 'zai/glm-5.1',
fallbackEnabled: false,
});
const port = await listenOnRandomPort(server);
const optionsRes = await fetch(`http://127.0.0.1:${port}/api/messages`, { method: 'OPTIONS' });
assert.equal(optionsRes.status, 200, `Expected OPTIONS 200, got ${optionsRes.status}`);
const switchRes = await fetch(`http://127.0.0.1:${port}/api/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [{ role: 'user', content: 'use sonnet' }],
}),
});
assert.equal(switchRes.status, 200, `Expected switch response 200, got ${switchRes.status}`);
const payload = await switchRes.json();
assert.equal(payload.model, 'anthropic/claude-sonnet-4.6');
assert.ok(
payload.content?.[0]?.text?.includes('Switched to **anthropic/claude-sonnet-4.6**'),
`Unexpected switch payload: ${JSON.stringify(payload)}`
);
const suffixSwitchRes = await fetch(`http://127.0.0.1:${port}/api/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [{ role: 'user', content: 'use k2.6' }],
}),
});
assert.equal(suffixSwitchRes.status, 200, `Expected suffix switch response 200, got ${suffixSwitchRes.status}`);
const suffixPayload = await suffixSwitchRes.json();
assert.equal(suffixPayload.model, 'moonshot/kimi-k2.6');
assert.ok(
suffixPayload.content?.[0]?.text?.includes('Switched to **moonshot/kimi-k2.6**'),
`Unexpected suffix switch payload: ${JSON.stringify(suffixPayload)}`
);
const freeSwitches = {
free: 'nvidia/llama-4-maverick',
glm4: 'nvidia/llama-4-maverick',
'qwen-think': 'nvidia/llama-4-maverick',
'qwen-coder': 'nvidia/llama-4-maverick',
maverick: 'nvidia/llama-4-maverick',
'deepseek-free': 'nvidia/llama-4-maverick',
'gpt-oss': 'nvidia/llama-4-maverick',
'gpt-oss-small': 'nvidia/llama-4-maverick',
'mistral-small': 'nvidia/llama-4-maverick',
nemotron: 'nvidia/llama-4-maverick',
devstral: 'nvidia/llama-4-maverick',
};
for (const [shortcut, expectedModel] of Object.entries(freeSwitches)) {
const freeSwitchRes = await fetch(`http://127.0.0.1:${port}/api/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [{ role: 'user', content: `use ${shortcut}` }],
}),
});
assert.equal(freeSwitchRes.status, 200, `Expected free switch ${shortcut} response 200, got ${freeSwitchRes.status}`);
const freePayload = await freeSwitchRes.json();
assert.equal(freePayload.model, expectedModel, `Proxy shortcut ${shortcut} drifted`);
assert.ok(
freePayload.content?.[0]?.text?.includes(`Switched to **${expectedModel}**`),
`Unexpected free switch payload for ${shortcut}: ${JSON.stringify(freePayload)}`
);
}
} finally {
if (server) {
await new Promise((resolve) => server.close(() => resolve()));
}
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('proxy server falls back when the paid BlockRun request times out', async () => {
const originalHome = process.env.HOME;
const fakeHome = mkdtempSync(join(tmpdir(), 'rc-proxy-timeout-home-'));
const proxyUrl = new URL('../dist/proxy/server.js', import.meta.url);
const attempts = [];
const paymentRequired = Buffer.from(JSON.stringify({
x402Version: 2,
accepts: [{
scheme: 'exact',
network: 'eip155:8453',
asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
amount: '1',
payTo: '0x0000000000000000000000000000000000000001',
maxTimeoutSeconds: 300,
}],
resource: { url: 'http://127.0.0.1/test', description: 'test' },
})).toString('base64');
const backend = createServer(async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk.toString();
const payload = raw ? JSON.parse(raw) : {};
const model = payload.model || 'unknown';
const paid = Boolean(req.headers['payment-signature']);
attempts.push({ model, paid });
if (!paid) {
res.writeHead(402, {
'content-type': 'application/json',
'payment-required': paymentRequired,
});
res.end(JSON.stringify({ error: 'payment required' }));
return;
}
if (model === 'slow/model') {
await new Promise((resolve) => setTimeout(resolve, 120));
if (!res.destroyed) {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ model, content: [] }));
}
return;
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({
id: 'msg_fallback',
type: 'message',
role: 'assistant',
model,
content: [{ type: 'text', text: 'fallback ok' }],
stop_reason: 'end_turn',
usage: { input_tokens: 1, output_tokens: 2 },
}));
});
let proxy;
try {
process.env.HOME = fakeHome;
const backendPort = await listenOnRandomPort(backend);
const { createProxy } = await import(`${proxyUrl.href}?t=${Date.now()}`);
proxy = createProxy({
port: 0,
apiUrl: `http://127.0.0.1:${backendPort}`,
chain: 'base',
modelOverride: 'slow/model',
fallbackEnabled: true,
requestTimeoutMs: 40, // forces slow/model to time out, exercising fallback
});
const proxyPort = await listenOnRandomPort(proxy);
const response = await fetch(`http://127.0.0.1:${proxyPort}/api/v1/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'slow/model',
messages: [{ role: 'user', content: 'hello' }],
max_tokens: 128,
}),
});
assert.equal(response.status, 200, `Expected fallback success, got ${response.status}`);
const payload = await response.json();
assert.equal(payload.content?.[0]?.text, 'fallback ok');
assert.ok(
attempts.some((a) => a.model === 'slow/model' && a.paid),
`Expected a paid slow/model attempt.\n${JSON.stringify(attempts, null, 2)}`
);
assert.ok(
attempts.some((a) => a.model !== 'slow/model' && a.paid),
`Expected a paid fallback attempt.\n${JSON.stringify(attempts, null, 2)}`
);
} finally {
if (proxy) await new Promise((resolve) => proxy.close(() => resolve()));
await new Promise((resolve) => backend.close(() => resolve()));
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('write capability allows files under system temp directory', async () => {
const { writeCapability } = await import('../dist/tools/write.js');
const target = join(tmpdir(), `rc-local-write-${Date.now()}.txt`);
try {
const result = await writeCapability.execute(
{ file_path: target, content: 'LOCAL_WRITE_OK' },
{ workingDir: process.cwd(), abortSignal: new AbortController().signal }
);
assert.equal(result.isError, undefined, `Write returned error: ${result.output}`);
assert.ok(existsSync(target), `Expected file to exist: ${target}`);
assert.equal(readFileSync(target, 'utf8'), 'LOCAL_WRITE_OK');
} finally {
rmSync(target, { force: true });
}
});
test('session storage falls back to temp dir when HOME is not writable', async () => {
const originalHome = process.env.HOME;
const fakeHome = mkdtempSync(join(tmpdir(), 'rc-home-ro-'));
const fallbackDir = join(tmpdir(), 'franklin', 'sessions');
try {
mkdirSync(fakeHome, { recursive: true });
chmodSync(fakeHome, 0o500); // read+execute, no write
const storageHref = new URL('../dist/session/storage.js', import.meta.url).href;
const script = `
const storage = await import(${JSON.stringify(storageHref)} + '?t=' + Date.now());
const sessionId = storage.createSessionId();
storage.appendToSession(sessionId, { role: 'user', content: 'fallback-check' });
storage.updateSessionMeta(sessionId, {
model: 'local/test',
workDir: process.cwd(),
turnCount: 1,
messageCount: 1,
});
console.log(JSON.stringify({ sessionId }));
`;
const result = await new Promise((resolve, reject) => {
const proc = spawn('node', ['-e', script], {
cwd: process.cwd(),
env: { ...process.env, HOME: fakeHome },
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
proc.stdout.on('data', (d) => { stdout += d.toString(); });
proc.stderr.on('data', (d) => { stderr += d.toString(); });
proc.on('close', (code) => {
if (code === 0) resolve({ stdout, stderr });
else reject(new Error(`session storage subprocess failed (${code})\nstdout:\n${stdout}\nstderr:\n${stderr}`));
});
proc.on('error', reject);
});
const { sessionId } = JSON.parse(result.stdout.trim());
const jsonl = join(fallbackDir, `${sessionId}.jsonl`);
const meta = join(fallbackDir, `${sessionId}.meta.json`);
assert.ok(existsSync(jsonl), `Expected fallback session file at ${jsonl}`);
assert.ok(existsSync(meta), `Expected fallback session meta at ${meta}`);
rmSync(jsonl, { force: true });
rmSync(meta, { force: true });
} finally {
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
chmodSync(fakeHome, 0o700);
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('interactive session persists tool exchanges for resume', { timeout: 20_000 }, async () => {
const beforeIds = new Set((await import('../dist/session/storage.js')).listSessions().map((s) => s.id));
let requestCount = 0;
const previousDynamicTools = process.env.FRANKLIN_DYNAMIC_TOOLS;
const server = createServer(async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk.toString();
requestCount++;
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
connection: 'keep-alive',
});
const send = (event, data) => {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
if (requestCount === 1) {
send('message_start', { message: { usage: { input_tokens: 12, output_tokens: 0 } } });
send('content_block_start', { content_block: { type: 'tool_use', id: 'tool_echo_1', name: 'Echo' } });
send('content_block_delta', { delta: { type: 'input_json_delta', partial_json: '{"text":"persist me"}' } });
send('content_block_stop', {});
send('message_delta', { delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 9 } });
send('message_stop', {});
} else {
const payload = JSON.parse(raw);
const messages = payload.messages || [];
const toolResultSeen = messages.some((msg) =>
msg.role === 'user' &&
Array.isArray(msg.content) &&
msg.content.some((part) => part.type === 'tool_result' && String(part.content).includes('echo:persist me'))
);
assert.ok(toolResultSeen, 'Expected follow-up request to include tool_result history');
send('message_start', { message: { usage: { input_tokens: 24, output_tokens: 0 } } });
send('content_block_start', { content_block: { type: 'text', text: '' } });
send('content_block_delta', { delta: { type: 'text_delta', text: 'final answer' } });
send('content_block_stop', {});
send('message_delta', { delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 7 } });
send('message_stop', {});
}
res.end('data: [DONE]\n\n');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
assert.ok(address && typeof address === 'object', 'Expected HTTP server address');
const apiUrl = `http://127.0.0.1:${address.port}`;
try {
process.env.FRANKLIN_DYNAMIC_TOOLS = '0';
const { interactiveSession } = await import('../dist/agent/loop.js');
const { listSessions, loadSessionHistory, getSessionFilePath } = await import('../dist/session/storage.js');
const capability = {
spec: {
name: 'Echo',
description: 'Echo back the provided text',
input_schema: {
type: 'object',
properties: {
text: { type: 'string' },
},
required: ['text'],
},
},
async execute(input) {
return { output: `echo:${input.text}` };
},
concurrent: false,
};
let calls = 0;
await interactiveSession(
{
model: 'zai/glm-5.1',
apiUrl,
chain: 'base',
systemInstructions: ['You are a test harness.'],
capabilities: [capability],
workingDir: process.cwd(),
permissionMode: 'trust',
},
async () => {
calls++;
return calls === 1 ? 'use the echo tool' : null;
},
() => {}
);
const created = listSessions().find((session) => !beforeIds.has(session.id));
assert.ok(created, 'Expected a new persisted session');
const restored = loadSessionHistory(created.id);
assert.equal(restored.length, 4, `Expected full transcript with tool exchange.\n${JSON.stringify(restored, null, 2)}`);
assert.equal(restored[0].role, 'user');
assert.equal(restored[1].role, 'assistant');
assert.equal(restored[2].role, 'user');
assert.equal(restored[3].role, 'assistant');
assert.ok(
Array.isArray(restored[2].content) &&
restored[2].content.some((part) => part.type === 'tool_result' && String(part.content).includes('echo:persist me')),
'Expected persisted tool_result in session transcript'
);
const sessionFile = getSessionFilePath(created.id);
rmSync(sessionFile, { force: true });
rmSync(join(dirname(sessionFile), `${created.id}.meta.json`), { force: true });
} finally {
if (previousDynamicTools === undefined) delete process.env.FRANKLIN_DYNAMIC_TOOLS;
else process.env.FRANKLIN_DYNAMIC_TOOLS = previousDynamicTools;
await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())));
}
});
test('resume: second interactiveSession with resumeSessionId continues prior transcript', { timeout: 20_000 }, async () => {
const { listSessions, loadSessionHistory, getSessionFilePath } = await import('../dist/session/storage.js');
const beforeIds = new Set(listSessions().map((s) => s.id));
let requestCount = 0;
const server = createServer(async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk.toString();
requestCount++;
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
connection: 'keep-alive',
});
const send = (event, data) => {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
if (requestCount === 1) {
// First session's only turn: answer directly and end.
send('message_start', { message: { usage: { input_tokens: 10, output_tokens: 0 } } });
send('content_block_start', { content_block: { type: 'text', text: '' } });
send('content_block_delta', { delta: { type: 'text_delta', text: 'first answer' } });
send('content_block_stop', {});
send('message_delta', { delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 5 } });
send('message_stop', {});
} else {
// Second session (resumed): verify the prior user+assistant turn is in the history.
const payload = JSON.parse(raw);
const messages = payload.messages || [];
const userMsgs = messages.filter((m) => m.role === 'user');
const assistantMsgs = messages.filter((m) => m.role === 'assistant');
assert.ok(userMsgs.length >= 2, `Expected resumed request to include both user turns, got ${userMsgs.length}`);
assert.ok(assistantMsgs.length >= 1, `Expected resumed request to include prior assistant turn, got ${assistantMsgs.length}`);
const firstUserText = JSON.stringify(userMsgs[0].content ?? '');
assert.ok(firstUserText.includes('first prompt'), `Expected first user prompt in resumed history.\n${firstUserText}`);
const assistantText = JSON.stringify(assistantMsgs[0].content ?? '');
assert.ok(assistantText.includes('first answer'), `Expected prior assistant answer in resumed history.\n${assistantText}`);
send('message_start', { message: { usage: { input_tokens: 20, output_tokens: 0 } } });
send('content_block_start', { content_block: { type: 'text', text: '' } });
send('content_block_delta', { delta: { type: 'text_delta', text: 'second answer' } });
send('content_block_stop', {});
send('message_delta', { delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 5 } });
send('message_stop', {});
}
res.end('data: [DONE]\n\n');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
const apiUrl = `http://127.0.0.1:${address.port}`;
try {
const { interactiveSession } = await import('../dist/agent/loop.js');
const baseConfig = {
model: 'zai/glm-5.1',
apiUrl,
chain: 'base',
systemInstructions: ['You are a test harness.'],
capabilities: [],
workingDir: process.cwd(),
permissionMode: 'trust',
};
// First session
let calls = 0;
await interactiveSession(
baseConfig,
async () => (++calls === 1 ? 'first prompt' : null),
() => {}
);
const created = listSessions().find((s) => !beforeIds.has(s.id));
assert.ok(created, 'Expected a new persisted session from first turn');
const beforeResumeLen = loadSessionHistory(created.id).length;
assert.equal(beforeResumeLen, 2, `Expected 2 messages after first turn, got ${beforeResumeLen}`);
// Second session — resume by id
let calls2 = 0;
await interactiveSession(
{ ...baseConfig, resumeSessionId: created.id },
async () => (++calls2 === 1 ? 'second prompt' : null),
() => {}
);
// Transcript must have grown in the same session file (no new session created)
const afterIds = listSessions().map((s) => s.id);
const newSessionsAfterResume = afterIds.filter((id) => !beforeIds.has(id) && id !== created.id);
assert.equal(newSessionsAfterResume.length, 0, `Resume must not create a new session.\nNew: ${newSessionsAfterResume}`);
const finalHistory = loadSessionHistory(created.id);
assert.equal(finalHistory.length, 4, `Expected 4 messages after resume turn, got ${finalHistory.length}\n${JSON.stringify(finalHistory, null, 2)}`);
assert.equal(finalHistory[0].role, 'user');
assert.equal(finalHistory[1].role, 'assistant');
assert.equal(finalHistory[2].role, 'user');
assert.equal(finalHistory[3].role, 'assistant');
const lastAssistant = JSON.stringify(finalHistory[3].content ?? '');
assert.ok(lastAssistant.includes('second answer'), `Expected second-turn answer in transcript.\n${lastAssistant}`);
// Cleanup
const sessionFile = getSessionFilePath(created.id);
rmSync(sessionFile, { force: true });
rmSync(join(dirname(sessionFile), `${created.id}.meta.json`), { force: true });
} finally {
await new Promise((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())));
}
});
test('pruneOldSessions removes stale ghost sessions even when visible session count is below the cap', async () => {
const fakeHome = mkdtempSync(join(tmpdir(), 'franklin-ghost-prune-'));
const storagePath = fileURLToPath(new URL('../dist/session/storage.js', import.meta.url));
try {
const sessionsDir = join(fakeHome, '.blockrun', 'sessions');
mkdirSync(sessionsDir, { recursive: true });
const staleGhostId = 'session-stale-ghost';
const staleGhostMeta = join(sessionsDir, `${staleGhostId}.meta.json`);
const staleGhostJsonl = join(sessionsDir, `${staleGhostId}.jsonl`);
const oldTs = Date.now() - (10 * 60 * 1000);
writeFileSync(staleGhostMeta, JSON.stringify({
id: staleGhostId,
model: 'zai/glm-5.1',
workDir: fakeHome,
createdAt: oldTs,
updatedAt: oldTs,
turnCount: 0,
messageCount: 0,
}, null, 2));
writeFileSync(staleGhostJsonl, '');
const visibleSessionId = 'session-visible';
const visibleSessionMeta = join(sessionsDir, `${visibleSessionId}.meta.json`);
const visibleSessionJsonl = join(sessionsDir, `${visibleSessionId}.jsonl`);
const freshTs = Date.now();
writeFileSync(visibleSessionMeta, JSON.stringify({
id: visibleSessionId,
model: 'zai/glm-5.1',
workDir: fakeHome,
createdAt: freshTs,
updatedAt: freshTs,
turnCount: 1,
messageCount: 2,
}, null, 2));
writeFileSync(visibleSessionJsonl, '{"role":"user","content":"hello"}\n{"role":"assistant","content":"world"}\n');
const result = await new Promise((resolve, reject) => {
const proc = spawn('node', [
'--input-type=module',
'-e',
`
const { listSessions, pruneOldSessions } = await import(${JSON.stringify(`file://${storagePath}`)});
const beforeVisible = listSessions().map((session) => session.id);
pruneOldSessions();
const afterVisible = listSessions().map((session) => session.id);
process.stdout.write(JSON.stringify({ beforeVisible, afterVisible }));
`,
], {
env: { ...process.env, HOME: fakeHome, BLOCKRUN_DIR: join(fakeHome, '.blockrun') },
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
proc.on('close', (code) => {
if (code === 0) resolve({ stdout, stderr });
else reject(new Error(`ghost prune subprocess failed (${code})\nstdout:\n${stdout}\nstderr:\n${stderr}`));
});
proc.on('error', reject);
});
const parsed = JSON.parse(result.stdout.trim());
assert.deepEqual(parsed.beforeVisible, [visibleSessionId], 'Ghost sessions should stay hidden from the visible session list');
assert.deepEqual(parsed.afterVisible, [visibleSessionId], 'Visible session list should stay stable after pruning');
assert.ok(!existsSync(staleGhostMeta), 'Expected stale ghost session meta to be removed');
assert.ok(!existsSync(staleGhostJsonl), 'Expected stale ghost session transcript to be removed');
assert.ok(existsSync(visibleSessionMeta), 'Visible session meta should remain');
assert.ok(existsSync(visibleSessionJsonl), 'Visible session transcript should remain');
} finally {
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('session meta imported flag can be set and survives later updates', async () => {
const fakeHome = mkdtempSync(join(tmpdir(), 'franklin-imported-meta-'));
const storagePath = fileURLToPath(new URL('../dist/session/storage.js', import.meta.url));
try {
const result = await new Promise((resolve, reject) => {
const proc = spawn('node', [
'--input-type=module',
'-e',
`
const { updateSessionMeta, loadSessionMeta } = await import(${JSON.stringify(`file://${storagePath}`)});
const id = 'session-imported-sticky';
updateSessionMeta(id, {
model: 'imported',
workDir: process.cwd(),
turnCount: 1,
messageCount: 2,
imported: true,
});
const first = loadSessionMeta(id)?.imported;
updateSessionMeta(id, {
model: 'zai/glm-5.1',
workDir: process.cwd(),
turnCount: 2,
messageCount: 4,
});
const second = loadSessionMeta(id)?.imported;
process.stdout.write(JSON.stringify({ first, second }));
`,
], {
env: { ...process.env, HOME: fakeHome, BLOCKRUN_DIR: join(fakeHome, '.blockrun') },
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
proc.on('close', (code) => {
if (code === 0) resolve({ stdout, stderr });
else reject(new Error(`imported meta subprocess failed (${code})\nstdout:\n${stdout}\nstderr:\n${stderr}`));
});
proc.on('error', reject);
});
const parsed = JSON.parse(result.stdout.trim());
assert.equal(parsed.first, true);
assert.equal(parsed.second, true);
} finally {
rmSync(fakeHome, { recursive: true, force: true });
}
});
test('resume: --resume with unknown id fails fast with non-zero exit (no wallet/banner)', { timeout: 10_000 }, async () => {
const home = mkdtempSync(join(tmpdir(), 'franklin-e2e-fastfail-'));
try {
const result = await runCli('', {
args: [DIST, '--resume', 'session-nonexistent-xyz'],
env: { HOME: home, BLOCKRUN_DIR: join(home, '.blockrun') },
timeoutMs: 8_000,
});
assert.equal(result.code, 1, `Expected exit 1 for unknown resume id, got ${result.code}\nstderr: ${result.stderr}`);
const combined = result.stdout + result.stderr;
assert.ok(combined.includes('No session found with id'), `Expected 'No session found' error.\n${combined}`);
// Must fail before wallet/banner work runs — banner string would reveal it
assert.ok(!combined.includes('Wallet created automatically'), `Validation should happen before wallet creation.\n${combined}`);
assert.ok(!combined.includes('FRANKLIN') && !combined.includes('blockrun.ai ·'), `Validation should happen before banner.\n${combined}`);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
test('resume: findLatestSessionForDir canonicalizes symlinked paths', async () => {
const { findLatestSessionForDir } = await import('../dist/ui/session-picker.js');
const { updateSessionMeta, appendToSession, getSessionFilePath } = await import('../dist/session/storage.js');
const fs = await import('node:fs');
// Create a real dir and a symlink pointing at it
const real = mkdtempSync(join(tmpdir(), 'franklin-real-'));
const link = join(tmpdir(), `franklin-link-${Date.now()}-${Math.floor(Math.random() * 1e6)}`);
fs.symlinkSync(real, link);
const id = `session-symlink-test-${Date.now()}`;
try {
// Session stored under the symlinked path
appendToSession(id, { role: 'user', content: 'symlink test' });
updateSessionMeta(id, { model: 'local/test', workDir: link, turnCount: 1, messageCount: 1 });
// Querying with the real path should still find it