Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
1051 lines (966 loc) · 42.8 KB
/
Copy pathindex.ts
File metadata and controls
1051 lines (966 loc) · 42.8 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
/**
* Entry point — load config, create auth manager, start proxy server.
*/
import net from "node:net";
// Process-wide Happy Eyeballs (2026-10-30): z.ai/alicdn CDN IPv6 answers
// are intermittently blackholed and Node's fetch (undici) does not race
// address families — a v6-first DNS answer wedged outbound requests
// (captcha config/solves → persistent 503 on IPv6-preferring networks;
// see NOTEPAD「3.17.1 增补」八轮). Node-only API; Bun's node:net shim
// ignores it and carries its own connect behavior.
try {
if (typeof net.setDefaultAutoSelectFamily === "function") {
net.setDefaultAutoSelectFamily(true);
if (typeof net.setDefaultAutoSelectFamilyAttemptTimeout === "function") {
net.setDefaultAutoSelectFamilyAttemptTimeout(250);
}
}
} catch { /* never fatal */ }
import { loadConfig } from "./config/loader.js";
import { AuthManager } from "./auth/manager.js";
import { startServer, type ProxyServer } from "./server/server.js";
import {
startControlListener,
createControlDispatcher,
LogBuffer,
type ControlState,
} from "./android/control.js";
import { collectQuotaSnapshot } from "./server/routes-quota.js";
import { loadCredential, saveCredential, clearCredential, getStorePath } from "./auth/store.js";
import { createPollLoginClient, type OAuthResult } from "./auth/oauth.js";
import { KeyResolver } from "./auth/resolver.js";
import type { Credential } from "./auth/types.js";
import type { LoginProviderId, ProviderId } from "./provider/types.js";
import type { ProxyConfig } from "./config/types.js";
import { updateConfigYaml, ensureConfigFile } from "./config/edit.js";
import { openBrowser } from "./runtime/open-browser.js";
import { buildServerOptions } from "./server/server-options.js";
import { createPollLoginHost, type LoginFlowHost } from "./server/login-handler.js";
import { credentialFamily } from "./provider/providers.js";
import {
resolvePanelSettings,
startPanelServer,
type ControlDispatcher,
type PanelServer,
type PanelSettings,
} from "./server/panel.js";
import { checkForUpdate } from "./update/check.js";
import { shutdownAllHighspeed } from "./highspeed/manager.js";
import { readFileSync, existsSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { randomUUID } from "node:crypto";
import { ensureNodeFetchNoTimeouts } from "./runtime/node-fetch-compat.js";
export const VERSION = "4.9.0";
if (require.main === module) main();
export interface ServeArgs {
configPath?: string;
debug: boolean;
}
/**
* Parse `serve` subcommand arguments. The token `debug` toggles debug mode;
* any other token is treated as the config path. Order-independent:
* [] → { debug: false }
* ["debug"] → { debug: true }
* ["my.yaml"] → { configPath: "my.yaml", debug: false }
* ["debug","x.yaml"] → { configPath: "x.yaml", debug: true }
* ["x.yaml","debug"] → { configPath: "x.yaml", debug: true }
*/
export function parseServeArgs(args: string[]): ServeArgs {
const debug = args.includes("debug");
const configPath = args.find((a) => a !== "debug");
return { configPath, debug };
}
function main(): void {
// Fire-and-forget is race-safe: the dynamic import resolves in a microtask,
// before the listener's event-loop callback can admit a request.
void ensureNodeFetchNoTimeouts();
try {
runCli();
} catch (err) {
process.stderr.write(`zcode-proxy: uncaught error: ${(err as Error).stack ?? String(err)}\n`);
process.exit(1);
}
}
function runCli(): void {
const args = process.argv.slice(2);
// `--cli` opts out of the default TUI and restores the classic CLI dispatch
// (bare `--cli` = the old no-arg default: serve).
if (args[0] === "--cli") {
dispatchCli(args.slice(1));
return;
}
// Default surface is the TUI. Bare invocation, the retired `tui` token
// (kept as a silent alias), and tui-style args (`debug`, `*.yaml`) all land
// here — the former `tui <args>` subcommand simply dropped its prefix.
if (
args.length === 0 ||
args[0] === "tui" ||
args[0] === "debug" ||
args[0].endsWith(".yaml") ||
args[0].endsWith(".yml")
) {
launchTui(parseServeArgs(args[0] === "tui" ? args.slice(1) : args));
return;
}
dispatchCli(args);
}
/** Classic CLI dispatch — subcommand routing where bare = serve. */
function dispatchCli(args: string[]): void {
const cmd = args[0] ?? "serve";
if (cmd === "auth") {
authCommand(args.slice(1));
} else if (cmd === "claim") {
void claimCommand(args.slice(1));
} else if (cmd === "quota") {
void quotaCommand();
} else if (cmd === "android") {
// Explicit catch: an async startup failure (e.g. control port already
// bound by an orphaned process) must exit non-zero deterministically, not
// surface as an unhandled rejection.
runAndroid().catch((err: unknown) => {
process.stderr.write(`zcode-proxy: android entry failed: ${(err as Error).stack ?? String(err)}\n`);
process.exit(1);
});
} else if (cmd === "tui") {
// Kept for muscle memory under `--cli`: the default dispatch already
// routes `tui` to the TUI, but `--cli tui` should not regress to an error.
launchTui(parseServeArgs(args.slice(1)));
} else if (cmd === "serve" || cmd.endsWith(".yaml") || cmd.endsWith(".yml")) {
const serveArgs = cmd === "serve"
? parseServeArgs(args.slice(1))
: parseServeArgs(args);
serve(serveArgs.configPath, serveArgs.debug);
} else if (cmd === "version" || cmd === "--version" || cmd === "-v") {
console.log(`zcode-proxy ${VERSION}`);
} else if (cmd === "help" || cmd === "--help" || cmd === "-h") {
printHelp();
} else {
console.error(`Unknown command: ${cmd}\n`);
printHelp();
process.exit(1);
}
}
function launchTui(args: ServeArgs): void {
// Dynamic import: the TUI module imports helpers back from this file, so a
// static edge would create a load-time cycle (same pattern as claimCommand).
import("./tui/app.js")
.then((m) => m.runTui(args))
.catch((err: unknown) => {
process.stderr.write(`zcode-proxy: tui failed: ${(err as Error).stack ?? String(err)}\n`);
process.exit(1);
});
}
function printHelp(): void {
console.log(`zcode-proxy ${VERSION}
Usage:
zcode-proxy Interactive terminal UI (default):
login, start/stop, live logs
zcode-proxy [debug] [config.yaml] Same, with debug diagnostics / custom config
zcode-proxy serve [config.yaml] Start the proxy server (classic CLI mode)
zcode-proxy serve debug [config.yaml]
Start with verbose per-request diagnostics
zcode-proxy --cli Classic CLI mode (bare --cli = serve)
zcode-proxy android Android entry: proxy + localhost control listener
zcode-proxy auth login <provider> Login via OAuth (provider: zai | bigmodel)
zcode-proxy auth login <provider> --import
Import API key from ~/.zcode/v2/config.json
zcode-proxy auth logout Clear stored credentials
zcode-proxy auth status Show current authentication state
zcode-proxy claim [list|now] List / claim weekend-plan trial packages
zcode-proxy quota Show plan quota (per-model remaining/total)
zcode-proxy version Show version
zcode-proxy help Show this help
Examples:
zcode-proxy Terminal UI: login, start/stop, live logs
zcode-proxy debug Terminal UI with per-request diagnostics
zcode-proxy serve debug CLI: start with extra debug logging
zcode-proxy auth login bigmodel OAuth login for Bigmodel
zcode-proxy auth login bigmodel --import
Import existing key from ZCode config
zcode-proxy auth status Check if logged in
`);
}
/**
* Mirror console output into a ring buffer so the panel's Logs card has data.
* Same tee the Android entry installs — the buffer is also what `getLogs` reads.
*/
function installLogTee(): LogBuffer {
const buffer = new LogBuffer();
const origLog = console.log;
const origErr = console.error;
const origWarn = console.warn;
console.log = (...args: unknown[]) => { buffer.push(args.join(" ")); origLog(...args); };
console.error = (...args: unknown[]) => { buffer.push("[error] " + args.join(" ")); origErr(...args); };
console.warn = (...args: unknown[]) => { buffer.push("[warn] " + args.join(" ")); origWarn(...args); };
return buffer;
}
/**
* Loopback spellings that keep the panel unexposed (same set the config loader
* accepts for http:// origins). Anything else was an explicit `ZCODE_PANEL_HOST`
* and gets the startup warning below.
*/
function isLoopbackPanelHost(host: string): boolean {
return host === "127.0.0.1" || host === "localhost" || host === "::1";
}
/**
* Start the optional web panel for `serve`. `serve` has no TUI, so this is the
* only way to see quota, read live logs or switch provider/plan on a headless
* box without `docker exec`.
*
* Commands are dispatched in-process through `createControlDispatcher()` — the
* same protocol the Android shell drives over `POST /control`, without opening a
* second, unauthenticated loopback port. The panel token is therefore the only
* way in.
*
* The proxy lifecycle hooks mirror `runAndroid` on purpose: `serve` starts the
* proxy eagerly, so `serverRef` is pre-filled and the start/stop commands only
* matter for restarts (including the `stop_proxy_first` rule before setConfig).
*
* Two behaviours are panel-only and stay out of the shared control layer: the
* `shutdown` command unwinds the whole process (through the same path as the
* signals, so it works after the proxy was stopped from the page), and a
* logout/login re-syncs the live credential — see `handleControl` below.
*/
async function startServePanel(
settings: PanelSettings,
ctx: {
config: ProxyConfig;
path: string;
auth: AuthManager;
serverRef: { current: ProxyServer | null };
logBuffer: LogBuffer;
/** Unwind the process; independent of whether the proxy is still running. */
shutdown: () => void;
/** `/login` page backend carried across panel-driven proxy restarts. */
loginHost?: LoginFlowHost;
/**
* Shared store-fingerprint holder (serve() owns it): the /login completion
* path pre-bumps it after applying its own swap, so the two hot-swap
* writers agree and syncAuthWithDisk stays a no-op for already-applied
* changes.
*/
authFingerprint: { current: string };
},
): Promise<PanelServer> {
const { config, path, auth, serverRef, logBuffer, shutdown, loginHost, authFingerprint } = ctx;
// The panel can log out (or log in another account) while `serve` keeps
// running, but AuthManager caches the credential in memory and auto-claim
// prefers it over the store — so a disk-only change would leave `/v1` and
// auto-claim serving the account that was just replaced (issue #58 review,
// P2). Fingerprint the store and re-sync after every panel command: the
// page polls `getLogs` every 2s, so a background login lands within one poll.
// The fingerprint holder itself lives in serve() (initialized from the boot
// credential) so the /login completion path can pre-bump it.
async function syncAuthWithDisk(): Promise<void> {
const onDisk = await loadCredential().catch(() => null);
const fingerprint = JSON.stringify(onDisk ?? null);
if (fingerprint === authFingerprint.current) return;
authFingerprint.current = fingerprint;
if (onDisk) {
auth.setOAuthCredential(onDisk);
console.log("auth: switched to the account now on disk");
} else {
auth.clearOAuthCredential();
console.log("auth: credential cleared (logged out)");
}
}
const controlState: ControlState = {
provider: config.provider,
plan: config.plan,
proxyPort: serverRef.current?.port ?? 0,
};
async function startProxy(): Promise<{ ok: true; port: number } | { ok: false; error: string }> {
if (serverRef.current) return { ok: false, error: "already_running" };
const cred = await loadCredential().catch(() => null);
if (!cred) return { ok: false, error: "not_logged_in" };
auth.setOAuthCredential(cred);
authFingerprint.current = JSON.stringify(cred);
try {
const s = await startServer(buildServerOptions(config, auth, false, loginHost));
serverRef.current = s;
console.log(`zcode-proxy listening on http://${s.hostname}:${s.port}`);
return { ok: true, port: s.port };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
}
async function stopProxy(): Promise<{ ok: true } | { ok: false; error: string }> {
const s = serverRef.current;
if (!s) return { ok: false, error: "not_running" };
try {
s.stop(false);
serverRef.current = null;
console.log("zcode-proxy stopped");
return { ok: true };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
}
async function setConfig(changes: {
provider?: ProviderId;
plan?: "coding-plan" | "start-plan";
}): Promise<{ ok: true; provider: ProviderId; plan: "coding-plan" | "start-plan" } | { ok: false; error: string }> {
if (serverRef.current) return { ok: false, error: "stop_proxy_first" };
// Config surface stays zai|bigmodel — zai_cn is a login flavor, never a
// config provider (official folding). Runtime check: the control JSON
// path bypasses the type system.
if (changes.provider && changes.provider !== "zai" && changes.provider !== "bigmodel") {
return { ok: false, error: "invalid_provider" };
}
if (changes.provider) config.provider = changes.provider;
if (changes.plan) config.plan = changes.plan;
updateConfigYaml(path, { provider: config.provider, plan: config.plan });
console.log(`config updated: provider=${config.provider} plan=${config.plan}`);
return { ok: true, provider: config.provider, plan: config.plan };
}
// Dispatched in-process: the panel already guards its own transport with a
// token, so a second loopback listener would only add an unauthenticated way
// to reach stopProxy / logout / shutdown (issue #58 review, P1) and a second
// thing to clean up when the panel fails to start (P2, now structurally gone).
const dispatchControl = createControlDispatcher(controlState, {
logBuffer,
onStartProxy: startProxy,
onStopProxy: stopProxy,
onSetConfig: setConfig,
onQuota: () => collectQuotaSnapshot(config),
});
/** Grace period for the `shutdown` reply before `process.exit()` runs. */
const SHUTDOWN_REPLY_GRACE_MS = 50;
/**
* The panel's transport wrapper. Two panel-only responsibilities live here
* rather than in the shared control layer, so the Android protocol keeps its
* existing semantics:
*
* - `shutdown` answers first and unwinds afterwards. Exiting inside the
* command would truncate the reply the page is waiting for, and it unwinds
* through the same path as SIGTERM/SIGINT, so it works whether or not the
* proxy is still running (issue #58 review, P2).
* - Every other successful command re-syncs the live credential with the
* store, and a logout while the proxy runs stops it. Otherwise `/v1` and
* auto-claim keep spending the account that was just logged out (issue #58
* review, P2).
*/
const handleControl: ControlDispatcher = async (cmd) => {
if (cmd.cmd === "shutdown") {
setTimeout(shutdown, SHUTDOWN_REPLY_GRACE_MS);
return { ok: true, event: "shuttingDown" };
}
const res = await dispatchControl(cmd);
if (!res.ok) return res;
await syncAuthWithDisk();
if (cmd.cmd === "logout" && serverRef.current) {
await stopProxy();
controlState.proxyPort = 0;
console.log("panel: logout cleared the live credential — proxy stopped");
}
return res;
};
const panel = await startPanelServer({
port: settings.port,
hostname: settings.host,
token: settings.token,
handleControl,
});
console.log(`panel: http://${panel.hostname}:${panel.port} (token required)`);
// A non-loopback bind (the Docker bridge escape hatch, `ZCODE_PANEL_HOST`)
// is safe only as long as the token is strong and the port stays firewalled
// past the host that needs it — say so at startup, not only in the docs.
if (!isLoopbackPanelHost(panel.hostname)) {
console.warn(
`panel: bound to ${panel.hostname} — anyone who reaches this port with the token can stop the proxy, log out, or shut down`,
);
}
return panel;
}
async function serve(configPath: string | undefined, debug: boolean): Promise<void> {
const path = configPath ?? process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
if (ensureConfigFile(path)) {
ensureDeviceMidInConfig(path);
console.log(`Created ${path} from bundled template.`);
console.log(`Run: zcode-proxy auth login <zai|bigmodel>\n`);
}
const config = loadConfig(path);
// Optional web panel (issue #58). Resolved early so console output from the
// startup path below is already captured for the panel's Logs card.
const panelSettings = resolvePanelSettings();
const panelLogBuffer = panelSettings ? installLogTee() : null;
const auth = new AuthManager();
const cred = await loadCredential();
if (!cred) {
console.error("Not logged in. Run: zcode-proxy auth login " + config.provider);
process.exit(1);
}
auth.setOAuthCredential(cred);
// Shared store-fingerprint holder: the panel's syncAuthWithDisk and the
// /login completion path must agree on what's already applied, or every
// /login login is followed ~2s later by a spurious "auth: switched to the
// account now on disk" line (review 2026-11-14 P2).
const authFingerprint = { current: JSON.stringify(cred) };
if (debug) printDebugBanner(config, path, cred);
// Serve-mode `/login` backend (login-handler.ts): the same selection page
// the TUI hosts on a temporary listener, served by the proxy itself. A
// completed login saves the credential and hot-swaps the live one — serve
// mode runs the proxy continuously, and panel-driven re-login already
// hot-swaps the same way (syncAuthWithDisk).
const serveLoginHost: LoginFlowHost = createPollLoginHost({
onTokens: async (flavor, tokens) => {
const resolver = new KeyResolver();
const cred = await resolver.resolveCodingPlanCredential(tokens.accessToken, flavor, tokens.userId, tokens.linkedBigModel);
if (tokens.jwt) cred.jwt = tokens.jwt;
await saveCredential(cred);
auth.setOAuthCredential(cred);
// The swap is already applied — pre-bump the fingerprint so the next
// panel poll's syncAuthWithDisk is a no-op instead of re-setting the
// identical credential and logging a phantom switch.
authFingerprint.current = JSON.stringify(cred);
// Family sync (zai_cn→zai folding): keep config.yaml's provider on the
// credential's family so upstream endpoint selection stays coherent.
const family = credentialFamily(flavor);
if (config.provider !== family) {
config.provider = family;
try {
updateConfigYaml(path, { provider: family, plan: config.plan });
console.log(`config synced: provider=${family} (matches credential family)`);
} catch (err) {
console.error(`config sync failed: ${(err as Error).message}`);
}
}
console.log(`OAuth completed for ${flavor}`);
},
});
const server = await startServer(buildServerOptions(config, auth, debug, serveLoginHost));
// The optional panel can stop and restart the proxy, so the signal handlers
// and the lifecycle hooks go through this ref rather than the initial handle.
const serverRef: { current: ProxyServer | null } = { current: server };
const url = `http://${server.hostname}:${server.port}`;
console.log(`zcode-proxy listening on ${url}`);
// Handles for the background timers started below, so `shutdown` can clear
// them without the proxy handle being involved (issue #58 review, P2).
let claimScheduler: { stop: () => void } | null = null;
let captchaModule: { shutdownCaptcha: () => void } | null = null;
if (config.plan === "start-plan") {
// Pre-solve the captcha token pool in the background so first requests
// don't pay the full solve latency (in-process happy-dom backend).
import("./proxy/captcha.js")
.then(async (m) => {
captchaModule = m;
await m.startCaptchaPool(config.identity.appVersion);
})
.catch((err) => console.error(`[captcha] pool warmup failed: ${(err as Error).message}`));
}
if (config.claim.enabled && config.claim.auto) {
import("./claim/runtime.js")
.then((m) => {
claimScheduler = m.startAutoClaim(config, auth);
console.log(` claim: auto ON (poll ${Math.round(config.claim.pollIntervalMs / 1000)}s)`);
})
.catch((err) => console.error(`[claim] scheduler failed to start: ${(err as Error).message}`));
}
console.log(` provider: ${config.provider}`);
console.log(` plan: ${config.plan}`);
console.log(` models: ${config.models.length} available`);
if (config.responses.enabled) console.log(` /v1/responses: ON`);
if (config.async.enabled) {
console.log(config.plan === "coding-plan" ? ` /async/v1/*: ON` : ` /async/v1/*: OFF (requires plan "coding-plan")`);
}
if (debug) console.log(` debug: ON`);
// Update notice (issue #60): fire-and-forget — a slow or blocked GitHub must
// never delay startup, and every failure mode is silent (see update/check.ts).
// In a container the hint is the compose command: the image cannot self-update.
void checkForUpdate(VERSION).then((result) => {
if (result.kind === "update") console.log(` update: ${result.notice.text}`);
});
let panelRuntime: PanelServer | null = null;
const closePanel = (): void => {
if (!panelRuntime) return;
void panelRuntime.close().catch(() => {});
};
// Single shutdown path, shared by the signals and the panel's `shutdown`
// command. It must not depend on `serverRef`: the page can stop the proxy,
// and the timers below keep the event loop alive, so "the proxy is already
// stopped" is not the same as "there is nothing left to do" — without this,
// SIGTERM/SIGINT and `docker stop` hung until the kill timeout after a
// panel-side Stop proxy (issue #58 review, P2).
let shuttingDown = false;
const shutdown = (): void => {
if (shuttingDown) return;
shuttingDown = true;
closePanel();
const cleared: string[] = [];
if (claimScheduler) {
try {
claimScheduler.stop();
cleared.push("auto-claim");
} catch {
/* already stopped */
}
claimScheduler = null;
}
if (captchaModule) {
try {
captchaModule.shutdownCaptcha();
cleared.push("captcha pool");
} catch {
/* pool never started */
}
captchaModule = null;
}
try {
shutdownAllHighspeed(); // heartbeats are unref'd but stopped explicitly on shutdown
cleared.push("highspeed");
} catch {
/* loop never ignited */
}
if (cleared.length > 0) console.log(`shutdown: cleared ${cleared.join(" + ")} timers`);
if (serverRef.current) {
// Closes the listener and exits the process (`stop(true)`).
serverRef.current.stop(true);
return;
}
console.log("shutdown: proxy already stopped — exiting");
process.exit(0);
};
if (panelSettings && panelLogBuffer) {
try {
panelRuntime = await startServePanel(panelSettings, {
config,
path,
auth,
serverRef,
logBuffer: panelLogBuffer,
shutdown,
loginHost: serveLoginHost,
authFingerprint,
});
} catch (err) {
// The panel is a convenience layer; it must never take the proxy down.
console.error(`[panel] failed to start: ${(err as Error).message}`);
}
}
process.on("SIGINT", () => {
console.log("\nShutting down...");
shutdown();
});
process.on("SIGTERM", () => {
shutdown();
});
}
/**
* Desktop-Linux identity defaults for the Android entry (anti-pattern #34).
* Without these, the Node process on Android reports its true host values:
* `X-Platform: linux-arm64` and `X-Os-Version: 6.1.xx-android14-…` — a kernel
* string no real ZCode desktop emits. `identity.ts` reads these env vars per
* request, so setting them once here retargets every upstream call. Values are
* deliberately CONSTANT (Ubuntu 24.04 x64 profile — the largest desktop-Linux
* population): kernel strings are shared by millions of real machines, and
* stability is required by anti-pattern #13 (never randomize fingerprints).
* Explicit env values (adb shell setprop / NodeRunner) still win — each is set
* with `??`, not unconditionally.
*/
export function applyAndroidIdentityDefaults(): void {
process.env.ZCODE_IDENTITY_PLATFORM = process.env.ZCODE_IDENTITY_PLATFORM ?? "linux";
process.env.ZCODE_IDENTITY_ARCH = process.env.ZCODE_IDENTITY_ARCH ?? "x64";
process.env.ZCODE_IDENTITY_RELEASE = process.env.ZCODE_IDENTITY_RELEASE ?? "6.8.0-49-generic";
}
/**
* Android entry — starts the proxy plus a localhost control listener.
* Caller (Kotlin shell) must set env: ZCODE_CONTROL_PORT (control listener).
*/
async function runAndroid(): Promise<void> {
applyAndroidIdentityDefaults();
const path = process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
ensureConfigFile(path);
const config = loadConfig(path);
const logBuffer = new LogBuffer();
const origLog = console.log;
const origErr = console.error;
const origWarn = console.warn;
console.log = (...args: unknown[]) => { logBuffer.push(args.join(" ")); origLog(...args); };
console.error = (...args: unknown[]) => { logBuffer.push("[error] " + args.join(" ")); origErr(...args); };
console.warn = (...args: unknown[]) => { logBuffer.push("[warn] " + args.join(" ")); origWarn(...args); };
const auth = new AuthManager();
// Captcha module handle for the start-plan pool warmup (started in
// startProxy, stopped whenever the proxy stops) — mirrors serve()'s
// warmup. On Android this also brings up the persistent captcha workers
// (ZCODE_CAPTCHA_WARM_WORKERS, injected by NodeRunner).
let captchaModule: { shutdownCaptcha: () => void } | null = null;
const stopCaptchaPoolRuntime = (): void => {
try { captchaModule?.shutdownCaptcha(); } catch {}
captchaModule = null;
};
const serverRef: { current: ProxyServer | null } = { current: null };
async function startProxy(): Promise<{ ok: true; port: number } | { ok: false; error: string }> {
if (serverRef.current) return { ok: false, error: "already_running" };
const cred = await loadCredential().catch(() => null);
if (!cred) return { ok: false, error: "not_logged_in" };
auth.setOAuthCredential(cred);
try {
const s = await startServer(buildServerOptions(config, auth, false));
serverRef.current = s;
console.log(`zcode-proxy listening on http://${s.hostname}:${s.port}`);
if (config.plan === "start-plan") {
// Mirror serve(): size the pool, start background refill and prefill
// — previously Android never initialized the pool at all (every take
// hit an empty-pool race + one urgent refill). The prefill also warms
// the persistent captcha workers on this platform.
import("./proxy/captcha.js")
.then(async (m) => {
captchaModule = m;
await m.startCaptchaPool(config.identity.appVersion);
})
.catch((err) => console.error(`[captcha] pool warmup failed: ${(err as Error).message}`));
}
return { ok: true, port: s.port };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
}
async function stopProxy(): Promise<{ ok: true } | { ok: false; error: string }> {
const s = serverRef.current;
if (!s) return { ok: false, error: "not_running" };
try {
s.stop(false);
serverRef.current = null;
stopCaptchaPoolRuntime();
console.log("zcode-proxy stopped");
return { ok: true };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
}
async function setConfig(changes: {
provider?: ProviderId;
plan?: "coding-plan" | "start-plan";
}): Promise<{ ok: true; provider: ProviderId; plan: "coding-plan" | "start-plan" } | { ok: false; error: string }> {
if (serverRef.current) return { ok: false, error: "stop_proxy_first" };
// Config surface stays zai|bigmodel — zai_cn is a login flavor, never a
// config provider (official folding). Runtime check: the control JSON
// path bypasses the type system.
if (changes.provider && changes.provider !== "zai" && changes.provider !== "bigmodel") {
return { ok: false, error: "invalid_provider" };
}
if (changes.provider) config.provider = changes.provider;
if (changes.plan) config.plan = changes.plan;
updateConfigYaml(path, { provider: config.provider, plan: config.plan });
console.log(`config updated: provider=${config.provider} plan=${config.plan}`);
return { ok: true, provider: config.provider, plan: config.plan };
}
console.log("control listener ready; proxy stopped — use startProxy command to start");
if (config.claim.enabled && config.claim.auto) {
import("./claim/runtime.js")
.then((m) => {
m.startAutoClaim(config, auth);
console.log(`[claim] auto ON (poll ${Math.round(config.claim.pollIntervalMs / 1000)}s; waits for login)`);
})
.catch((err) => console.error(`[claim] scheduler failed to start: ${(err as Error).message}`));
}
const controlPort = Number(process.env.ZCODE_CONTROL_PORT ?? 0) || 0;
const controlState: ControlState = {
provider: config.provider,
plan: config.plan,
proxyPort: serverRef.current?.port ?? 0,
};
const controlListener = await startControlListener({
port: controlPort,
state: controlState,
logBuffer,
onStartProxy: startProxy,
onStopProxy: stopProxy,
onSetConfig: setConfig,
onQuota: () => collectQuotaSnapshot(config),
onShutdown: async () => {
serverRef.current?.stop(true);
stopCaptchaPoolRuntime();
},
});
console.log(`control listener: 127.0.0.1:${controlPort}`);
console.log(`provider: ${config.provider}`);
console.log(`plan: ${config.plan}`);
process.on("SIGINT", () => {
stopCaptchaPoolRuntime();
void controlListener.close().then(() => serverRef.current?.stop(true));
});
process.on("SIGTERM", () => {
stopCaptchaPoolRuntime();
void controlListener.close().then(() => serverRef.current?.stop(true));
});
}
function printDebugBanner(config: ProxyConfig, path: string, cred: Credential | null): void {
const credShape = cred
? `${cred.apiKey.slice(0, 6)}...${cred.apiKey.slice(-4)} (${cred.apiKey.length} chars)`
: "(none)";
const active = config.providers[config.provider];
console.log("=== zcode-proxy DEBUG MODE ===");
console.log(` config file: ${path}`);
console.log(` server: ${config.server.host}:${config.server.port}`);
console.log(` proxy api key: ${config.auth.proxyApiKey ? "required" : "open (no client auth)"}`);
console.log(` provider: ${config.provider}`);
console.log(` plan: ${config.plan}`);
console.log(` identity: appVersion=${config.identity.appVersion} sourceTitle=${config.identity.sourceTitle} referer=${config.identity.refererOrigin}`);
console.log(` client identity: mode=${config.clientIdentity.mode} ttl=${config.clientIdentity.ttlSeconds}s max=${config.clientIdentity.maxSessions}`);
console.log(` anthropic base: ${active.anthropicBase}`);
console.log(` openai base: ${active.openaiBase}`);
console.log(` credential: ${credShape}`);
console.log(` models (${config.models.length}): ${config.models.join(", ")}`);
console.log(` log level: ${config.logging.level}`);
console.log("===============================");
}
function authCommand(args: string[]): void {
const sub = args[0];
if (sub === "login") {
authLogin(args.slice(1));
} else if (sub === "logout") {
authLogout();
} else if (sub === "status") {
authStatus();
} else {
console.error("Usage: zcode-proxy auth <login|logout|status>");
process.exit(1);
}
}
async function claimCommand(args: string[]): Promise<void> {
const sub = args[0] ?? "now";
if (sub !== "list" && sub !== "now") {
console.error("Usage: zcode-proxy claim [list|now]");
process.exit(1);
}
const path = process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
if (!existsSync(path)) {
console.error(`Config file not found: ${path} (run serve once or create it).`);
process.exit(1);
}
// The billing gateway requires a stable X-Device-Mid — self-heal configs
// created before the deviceMid feature (idempotent: reuses existing value).
ensureDeviceMidInConfig(path);
const config = loadConfig(path);
try {
const { runClaimCli } = await import("./claim/runtime.js");
await runClaimCli(config, sub);
} catch (err) {
console.error(`claim failed: ${(err as Error).message}`);
process.exit(1);
}
}
/**
* `quota` subcommand — print the live quota snapshot: per-model credit buckets
* (billing plane) and coding-plan usage windows (monitor plane). Reuses
* collectQuotaSnapshot (same path GET /quota serves).
*/
async function quotaCommand(): Promise<void> {
const path = process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
if (!existsSync(path)) {
console.error(`Config file not found: ${path} (run serve once or create it).`);
process.exit(1);
}
ensureDeviceMidInConfig(path);
const config = loadConfig(path);
try {
const { collectQuotaSnapshot } = await import("./server/routes-quota.js");
const snap = await collectQuotaSnapshot(config);
if (snap.balances.length === 0) {
console.log("No balance windows reported by the billing endpoint.");
}
for (const b of snap.balances) {
const exp = b.expiresAt ? ` · expires ${fmtQuotaExpiry(b.expiresAt)}` : "";
console.log(` ${b.showName || "(unnamed)"}: ${b.remainingUnits.toLocaleString("en-US")} / ${b.totalUnits.toLocaleString("en-US")} units${exp}`);
}
if (snap.codingPlan) {
const { level, limits } = snap.codingPlan;
if (limits.length === 0) {
console.log("No coding-plan usage windows reported by the monitor endpoint.");
}
for (const l of limits) {
const tier = level ? ` (${level})` : "";
// Mirror of the official panel: remaining only — upstream `number` is
// not a comparable total (live TIME_LIMIT row: remaining=3894, number=1).
const amount =
l.remaining !== undefined
? `${l.remaining.toLocaleString("en-US")}${l.unit ? ` ${l.unit}` : ""} remaining`
: "no usage numbers reported";
const reset = l.nextResetTime !== undefined ? ` · resets ${fmtQuotaExpiry(l.nextResetTime)}` : "";
console.log(` coding-plan${tier}: [${l.type}] ${amount}${reset}`);
}
}
for (const plan of snap.claimablePlans) {
const grants = plan.entitlements
.map((e) => `${e.showName || plan.name}: ${(e.grantUnits ?? 0).toLocaleString("en-US")} ${e.unitType}`)
.join("; ");
console.log(` claimable: ${plan.name}${grants ? ` (${grants})` : ""}`);
}
for (const err of snap.errors) console.error(` ⚠ ${err}`);
if (snap.errors.length > 0) process.exitCode = 1;
} catch (err) {
console.error(`quota query failed: ${(err as Error).message}`);
process.exit(1);
}
}
/** `YYYY-MM-DD HH:mm` local time; `expiresAt` may be seconds or milliseconds. */
function fmtQuotaExpiry(expiresAt: number): string {
const d = new Date(expiresAt > 1e12 ? expiresAt : expiresAt * 1000);
if (Number.isNaN(d.getTime())) return String(expiresAt);
const pad = (n: number): string => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
async function authLogin(args: string[]): Promise<void> {
const provider = args[0] as ProviderId | undefined;
const importMode = args.includes("--import");
if (!provider || (provider !== "zai" && provider !== "zai_cn" && provider !== "bigmodel")) {
console.error("Usage: zcode-proxy auth login <zai|zai_cn|bigmodel> [--import]");
process.exit(1);
}
// The bigmodel OAuth login (bigmodel.cn auth-code/poll) is deprecated —
// superseded by the zai_cn "Z.ai (CN)" zchat login (decision 2026-11-14).
// --import of an existing bigmodel key stays supported.
if (!importMode && provider === "bigmodel") {
console.error("bigmodel OAuth login is deprecated — use 'zai_cn' (Z.ai 中国版; linked BigModel login) instead,");
console.error("or pass --import to register an existing bigmodel API key.");
process.exit(1);
}
ensureConfigWithDeviceMid();
const configPath = process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
const mode = importMode ? "(import)" : "(OAuth)";
console.log(`Logging in: ${provider} ${mode}\n`);
let cred: Credential;
if (importMode) {
cred = importFromZCodeConfig(provider);
} else {
// The guard above exits on bigmodel+!importMode — only zai|zai_cn reach OAuth.
const { accessToken, userId, jwt, linkedBigModel } = await runOAuth(provider as LoginProviderId);
console.log("\nResolving API key...");
const resolver = new KeyResolver();
cred = await resolver.resolveCodingPlanCredential(accessToken, provider, userId, linkedBigModel);
if (jwt) cred.jwt = jwt;
}
await saveCredential(cred);
// Family sync — same discipline as the TUI finalizeLogin / serve onTokens
// paths: serving a zai-family credential through bigmodel endpoints (or vice
// versa, e.g. a zai_cn login while config says bigmodel) 401s every request
// with nothing pointing at the mismatch.
try {
const config = loadConfig(configPath);
const family = credentialFamily(provider);
if (config.provider !== family) {
updateConfigYaml(configPath, { provider: family, plan: config.plan });
console.log(`config synced: provider=${family} (matches credential family)`);
}
} catch (err) {
console.error(`config sync failed: ${(err as Error).message}`);
}
console.log(`\nLogged in as ${provider}.`);
console.log(` API Key: ${cred.apiKey.substring(0, 12)}...`);
if (cred.userId) console.log(` User ID: ${cred.userId}`);
console.log(` Stored: ${getStorePath()}`);
}
/**
* Ensure config.yaml exists and carries a stable `identity.deviceMid`.
* Creates the file from the bundled template when missing (desktop flow;
* Android's mid comes from NodeRunner env injection instead and is never
* written here). Returns the mid (existing or freshly generated).
*/
function ensureConfigWithDeviceMid(): string {
const path = process.env.ZCODE_PROXY_CONFIG ?? "config.yaml";
if (ensureConfigFile(path)) {
console.log(`Created ${path} from bundled template.`);
}
return ensureDeviceMidInConfig(path);
}
/**
* Generate-or-reuse `identity.deviceMid` in a YAML config via targeted line
* edit (comments preserved): fills an empty `deviceMid:` value, inserts one
* under a block-style `identity:` key, or appends a new `identity:` block when
* the key is absent entirely. Idempotent — an existing non-empty value is
* returned untouched. The regexes are function-local on purpose: `main()` runs
* synchronously at module top (before later top-level statements initialize),
* so any module-level const this function touches would still be undefined on
* the boot-time `serve` path.
*/
export function ensureDeviceMidInConfig(path: string): string {
const deviceMidLine = /^(\s*)deviceMid:\s*(.*)$/m;
const identityBlockLine = /^identity:\s*$/m;
const raw = readFileSync(path, "utf-8");
const existing = deviceMidLine.exec(raw);
if (existing) {
const value = existing[2].trim().replace(/^"|"$/g, "");
if (value.length > 0) return value;
}
const mid = randomUUID();
let updated: string;
if (existing) {
updated = raw.replace(deviceMidLine, `${existing[1]}deviceMid: "${mid}"`);
} else if (identityBlockLine.test(raw)) {
updated = raw.replace(identityBlockLine, `identity:\n deviceMid: "${mid}"`);
} else {
const block = `identity:\n deviceMid: "${mid}"\n`;
updated = raw.endsWith("\n") || raw.length === 0 ? raw + block : raw + "\n" + block;
}
writeFileSync(path, updated, "utf-8");
console.log(`Device identity generated: ${mid.slice(0, 8)}… (stored in ${path})`);
return mid;
}
function authLogout(): void {
if (!existsSync(getStorePath())) {
console.log("Not logged in.");
return;
}
clearCredential();
console.log("Logged out. Credentials removed.");
}
async function authStatus(): Promise<void> {
const cred = await loadCredential();
if (!cred) {
console.log("Not logged in.");
console.log("Run: zcode-proxy auth login <zai|bigmodel>");
return;
}
console.log(`Logged in: ${cred.provider}`);
console.log(` API Key: ${cred.apiKey.substring(0, 12)}...`);
console.log(` Store: ${getStorePath()}`);
}
async function runOAuth(provider: LoginProviderId): Promise<OAuthResult> {
// Both login flavors use the server-mediated poll login (ZCode 3.12.3