maxpool 1.24.36 → 1.24.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/account-manager.js +11 -0
- package/src/index.js +78 -5
- package/src/screen.html +138 -0
- package/src/secret-resolver.js +3 -1
- package/src/server.js +85 -15
- package/src/tui.js +5 -2
package/package.json
CHANGED
package/src/account-manager.js
CHANGED
|
@@ -465,6 +465,9 @@ export class AccountManager {
|
|
|
465
465
|
else this.scheduler.routingMode = 'sticky';
|
|
466
466
|
}
|
|
467
467
|
this._refreshAccessToken = dependencies.refreshAccessToken || refreshAccessToken;
|
|
468
|
+
// Named-caller request attribution (team pools): callerName → requests served.
|
|
469
|
+
// Server-side (not TUI-side) so headless pools feed the web screen too.
|
|
470
|
+
this.callerCounts = new Map();
|
|
468
471
|
this.poolUpSince = Date.now();
|
|
469
472
|
this.accounts = accounts.map((acct, index) => ({
|
|
470
473
|
index,
|
|
@@ -840,6 +843,13 @@ export class AccountManager {
|
|
|
840
843
|
this.sessionBindings.set(sessionKey, binding);
|
|
841
844
|
}
|
|
842
845
|
|
|
846
|
+
// Named-caller attribution: one bump per CLIENT request (server calls this
|
|
847
|
+
// right after auth, so retries/reroutes never double-count).
|
|
848
|
+
countRequest(callerName) {
|
|
849
|
+
if (!callerName) return;
|
|
850
|
+
this.callerCounts.set(callerName, (this.callerCounts.get(callerName) || 0) + 1);
|
|
851
|
+
}
|
|
852
|
+
|
|
843
853
|
releaseAccount(lease, outcome = {}) {
|
|
844
854
|
if (!lease?.account) return;
|
|
845
855
|
const account = lease.account;
|
|
@@ -4677,6 +4687,7 @@ export class AccountManager {
|
|
|
4677
4687
|
? Math.max(0, now - this.queueState.waiting[0].queuedAt)
|
|
4678
4688
|
: 0,
|
|
4679
4689
|
},
|
|
4690
|
+
callers: Object.fromEntries([...this.callerCounts.entries()].map(([n, c]) => [n, { requests: c }])),
|
|
4680
4691
|
sessions: {
|
|
4681
4692
|
stickyBindings: this.sessionBindings.size,
|
|
4682
4693
|
thinkingProtected: [...this.sessionPolicies.values()].filter(p => p.requiresAnthropicThinkingIntegrity).length,
|
package/src/index.js
CHANGED
|
@@ -15,7 +15,7 @@ import { stat } from 'node:fs/promises';
|
|
|
15
15
|
import { spawn, spawnSync } from 'node:child_process';
|
|
16
16
|
import { createInterface } from 'node:readline';
|
|
17
17
|
import { loadOrCreateConfig, loadConfig, saveConfig, atomicConfigUpdate, getConfigPath, loadState, saveState, getStatePath, getLogPath, readGeneration, flushConfigWrites, flushStateWrites, saveStateUnbumped } from './config.js';
|
|
18
|
-
import { setEventLogPath, installConsoleMirror, setConsoleStdoutSuppressed } from './event-log.js';
|
|
18
|
+
import { setEventLogPath, installConsoleMirror, setConsoleStdoutSuppressed, appendEventLog } from './event-log.js';
|
|
19
19
|
import { SleepGuard } from './sleep-guard.js';
|
|
20
20
|
import { AccountManager } from './account-manager.js';
|
|
21
21
|
import { createProxyServer, REQUEST_IDLE_MAX_MS } from './server.js';
|
|
@@ -133,6 +133,10 @@ switch (command) {
|
|
|
133
133
|
await envCommand();
|
|
134
134
|
process.exit(0);
|
|
135
135
|
break;
|
|
136
|
+
case 'pool':
|
|
137
|
+
await poolCommand();
|
|
138
|
+
process.exit(0);
|
|
139
|
+
break;
|
|
136
140
|
case 'status':
|
|
137
141
|
await statusCommand();
|
|
138
142
|
process.exit(0);
|
|
@@ -947,7 +951,14 @@ async function serverWorkerCommand() {
|
|
|
947
951
|
},
|
|
948
952
|
onRequestEnd: (id, info) => {
|
|
949
953
|
restartController.requestEnded(id);
|
|
950
|
-
tui
|
|
954
|
+
if (tui) {
|
|
955
|
+
tui.onRequestEnd(id, info);
|
|
956
|
+
} else if (info.caller) {
|
|
957
|
+
// Headless (service / shared VM) pools have no TUI log buffer, so named-caller
|
|
958
|
+
// attribution would otherwise reach no log at all. Only named callers are
|
|
959
|
+
// logged here — a solo headless pool stays as quiet as before.
|
|
960
|
+
appendEventLog(`[Maxpool] ${info.caller} · ${info.method} ${info.path} → ${info.account || '?'} (${info.status})`);
|
|
961
|
+
}
|
|
951
962
|
},
|
|
952
963
|
};
|
|
953
964
|
|
|
@@ -1695,9 +1706,60 @@ async function loginOAuthCommand() {
|
|
|
1695
1706
|
|
|
1696
1707
|
async function envCommand() {
|
|
1697
1708
|
const config = await loadOrCreateConfig();
|
|
1698
|
-
|
|
1709
|
+
// A `pool shared` switch redirects this machine's client traffic at the team
|
|
1710
|
+
// pool; `env`/`run` must follow it or they'd keep hitting the local pool.
|
|
1711
|
+
const client = config.client?.mode === 'shared' && config.client?.sharedHost
|
|
1712
|
+
? { host: config.client.sharedHost, key: config.client.sharedKey || '' }
|
|
1713
|
+
: { host: `${config.proxy.host || '127.0.0.1'}:${config.proxy.port}`, key: '' };
|
|
1714
|
+
console.log(`export ANTHROPIC_BASE_URL=http://${client.host}`);
|
|
1699
1715
|
if (args.includes('--with-key')) {
|
|
1700
|
-
console.log(`export ANTHROPIC_API_KEY=${config.proxy.apiKey}`);
|
|
1716
|
+
console.log(`export ANTHROPIC_API_KEY=${client.key || config.proxy.apiKey}`);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
// ── pool (client-side switch between local and shared pool) ─
|
|
1721
|
+
|
|
1722
|
+
async function poolCommand() {
|
|
1723
|
+
const sub = args[1];
|
|
1724
|
+
const config = await loadOrCreateConfig();
|
|
1725
|
+
config.client = config.client || {};
|
|
1726
|
+
|
|
1727
|
+
if (sub === 'shared') {
|
|
1728
|
+
const host = args[2];
|
|
1729
|
+
const key = args[3];
|
|
1730
|
+
if (!host || !key || key.startsWith('-')) {
|
|
1731
|
+
console.error('Usage: maxpool pool shared <host:port> <your-pool-key>');
|
|
1732
|
+
console.error(' e.g. maxpool pool shared maxpool.tail-scale.ts.net:3456 mp-personal-key');
|
|
1733
|
+
process.exit(1);
|
|
1734
|
+
}
|
|
1735
|
+
// atomicConfigUpdate, not load→save: a running local pool may rotate an OAuth
|
|
1736
|
+
// token in the same instant, and a whole-file save would undo that refresh.
|
|
1737
|
+
await atomicConfigUpdate(c => {
|
|
1738
|
+
c.client = { ...(c.client || {}), mode: 'shared', sharedHost: host, sharedKey: key };
|
|
1739
|
+
});
|
|
1740
|
+
console.log(`This machine now points at the SHARED pool: http://${host}`);
|
|
1741
|
+
console.log('Apply it in your shells (or restart terminals):');
|
|
1742
|
+
console.log(` export ANTHROPIC_BASE_URL=http://${host}`);
|
|
1743
|
+
console.log(` export ANTHROPIC_API_KEY=${key}`);
|
|
1744
|
+
console.log('rc-gate users: also set RC_GATE_MAXPOOL_HOST/PORT/KEY in the LaunchAgent and restart it.');
|
|
1745
|
+
} else if (sub === 'local') {
|
|
1746
|
+
await atomicConfigUpdate(c => {
|
|
1747
|
+
c.client = { ...(c.client || {}), mode: 'local' };
|
|
1748
|
+
delete c.client.sharedHost;
|
|
1749
|
+
delete c.client.sharedKey;
|
|
1750
|
+
});
|
|
1751
|
+
console.log(`This machine points at its OWN local pool: http://${config.proxy.host || '127.0.0.1'}:${config.proxy.port}`);
|
|
1752
|
+
console.log('Unset ANTHROPIC_BASE_URL/ANTHROPIC_API_KEY (or re-export the local ones) and restart terminals.');
|
|
1753
|
+
} else if (sub === 'status') {
|
|
1754
|
+
const mode = config.client?.mode || 'local';
|
|
1755
|
+
if (mode === 'shared') {
|
|
1756
|
+
console.log(`mode: shared → http://${config.client.sharedHost}`);
|
|
1757
|
+
} else {
|
|
1758
|
+
console.log(`mode: local → http://${config.proxy.host || '127.0.0.1'}:${config.proxy.port}`);
|
|
1759
|
+
}
|
|
1760
|
+
} else {
|
|
1761
|
+
console.error('Usage: maxpool pool <shared <host:port> <key> | local | status>');
|
|
1762
|
+
process.exit(1);
|
|
1701
1763
|
}
|
|
1702
1764
|
}
|
|
1703
1765
|
|
|
@@ -1714,11 +1776,19 @@ async function runCommand() {
|
|
|
1714
1776
|
// which the proxy accepts from localhost. Not setting ANTHROPIC_API_KEY
|
|
1715
1777
|
// lets Claude Code stay in subscription mode (full model access).
|
|
1716
1778
|
// Use spawnSync so the Node process blocks entirely — behaves like execvp.
|
|
1779
|
+
const shared = config.client?.mode === 'shared' && !!config.client?.sharedHost;
|
|
1717
1780
|
const result = spawnSync('claude', claudeArgs, {
|
|
1718
1781
|
stdio: 'inherit',
|
|
1719
1782
|
env: {
|
|
1720
1783
|
...process.env,
|
|
1721
|
-
|
|
1784
|
+
// Follows the `pool shared` switch like envCommand (client.mode 'shared'
|
|
1785
|
+
// redirects run-subcommand traffic at the team pool).
|
|
1786
|
+
ANTHROPIC_BASE_URL: shared
|
|
1787
|
+
? `http://${config.client.sharedHost}`
|
|
1788
|
+
: `http://${config.proxy.host || '127.0.0.1'}:${config.proxy.port}`,
|
|
1789
|
+
// A shared pool trusts no address, so it needs the person's key; the local
|
|
1790
|
+
// pool keeps today's keyless subscription-mode behavior.
|
|
1791
|
+
...(shared && config.client.sharedKey ? { ANTHROPIC_API_KEY: config.client.sharedKey } : {}),
|
|
1722
1792
|
},
|
|
1723
1793
|
});
|
|
1724
1794
|
|
|
@@ -2021,6 +2091,9 @@ Commands:
|
|
|
2021
2091
|
login OAuth login via browser (adds the account you're signed into at claude.ai)
|
|
2022
2092
|
login --api Add an API key account
|
|
2023
2093
|
env [--with-key] Print env vars to use with Claude
|
|
2094
|
+
pool shared <host> <key> Point this machine at a shared team pool
|
|
2095
|
+
pool local Point this machine back at its own local pool
|
|
2096
|
+
pool status Show which pool this machine points at
|
|
2024
2097
|
run [-- args...] Run Claude Code through the proxy
|
|
2025
2098
|
status Show proxy & account status (live)
|
|
2026
2099
|
accounts List configured accounts
|
package/src/screen.html
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
+
<title>Maxpool Accounts</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root{
|
|
9
|
+
--bg:#f7f6f3; --fg:#1b1a17; --muted:#6c665c; --line:#e3ded5; --card:#fff;
|
|
10
|
+
--ok:#1f7a5c; --warn:#a86500; --bad:#b3261e; --bar:#e9e5dd; --chip:#efece6;
|
|
11
|
+
color-scheme:light;
|
|
12
|
+
}
|
|
13
|
+
@media (prefers-color-scheme: dark){
|
|
14
|
+
:root{ --bg:#131210; --fg:#ebe6dc; --muted:#a29a8c; --line:#2b2823; --card:#1b1a16;
|
|
15
|
+
--ok:#56c3a0; --warn:#e2a650; --bad:#f07b72; --bar:#2a2722; --chip:#24221d; color-scheme:dark; }
|
|
16
|
+
}
|
|
17
|
+
*{box-sizing:border-box}
|
|
18
|
+
body{margin:0;background:var(--bg);color:var(--fg);
|
|
19
|
+
font:14px/1.5 ui-sans-serif,-apple-system,"Segoe UI",Roboto,sans-serif;
|
|
20
|
+
padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px))}
|
|
21
|
+
.wrap{max-width:980px;margin:0 auto;padding-block:24px 48px}
|
|
22
|
+
header{display:flex;flex-wrap:wrap;align-items:baseline;gap:8px 16px;margin-bottom:16px}
|
|
23
|
+
h1{font-size:22px;margin:0;letter-spacing:-.3px}
|
|
24
|
+
.meta{color:var(--muted);font-size:13px}
|
|
25
|
+
.people{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 18px}
|
|
26
|
+
.chip{background:var(--chip);border:1px solid var(--line);border-radius:999px;padding:3px 11px;font-size:12.5px}
|
|
27
|
+
.grid{display:grid;gap:10px}
|
|
28
|
+
.acct{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:12px 14px;display:grid;
|
|
29
|
+
grid-template-columns:minmax(0,1.2fr) minmax(0,2fr) auto;gap:6px 16px;align-items:center}
|
|
30
|
+
@media (max-width:640px){.acct{grid-template-columns:minmax(0,1fr) auto}.bars{grid-column:1/-1}}
|
|
31
|
+
.name{font-weight:600;overflow-wrap:anywhere}
|
|
32
|
+
.sub{color:var(--muted);font-size:12px}
|
|
33
|
+
.bars{display:grid;gap:5px}
|
|
34
|
+
.bar{display:grid;grid-template-columns:28px minmax(0,1fr) 42px;gap:8px;align-items:center;font-size:12px;color:var(--muted)}
|
|
35
|
+
.track{height:8px;background:var(--bar);border-radius:99px;overflow:hidden}
|
|
36
|
+
.fill{height:100%;background:var(--ok);border-radius:99px}
|
|
37
|
+
.fill.warn{background:var(--warn)}.fill.bad{background:var(--bad)}
|
|
38
|
+
.state{justify-self:start;font-size:12.5px;font-weight:600;padding:3px 10px;border-radius:999px;white-space:nowrap;background:var(--chip)}
|
|
39
|
+
.state.ok{color:var(--ok)}.state.warn{color:var(--warn)}.state.bad{color:#fff;background:var(--bad)}
|
|
40
|
+
.acct.dead{border-color:var(--bad)}
|
|
41
|
+
.gate{max-width:420px;margin:12vh auto;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px}
|
|
42
|
+
.gate input{width:100%;font:inherit;padding:9px 11px;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--fg);margin:10px 0}
|
|
43
|
+
.gate button,.link{font:inherit;padding:8px 14px;border-radius:8px;border:1px solid var(--line);background:var(--chip);color:var(--fg);cursor:pointer}
|
|
44
|
+
.err{color:var(--bad);font-size:13px;min-height:18px}
|
|
45
|
+
.link{padding:3px 9px;font-size:12px}
|
|
46
|
+
</style>
|
|
47
|
+
</head>
|
|
48
|
+
<body>
|
|
49
|
+
<div class="wrap" id="app"></div>
|
|
50
|
+
<script>
|
|
51
|
+
(function () {
|
|
52
|
+
var KEY_STORE = 'maxpool.screen.key';
|
|
53
|
+
var app = document.getElementById('app');
|
|
54
|
+
function getKey() { try { return localStorage.getItem(KEY_STORE) || ''; } catch (e) { return ''; } }
|
|
55
|
+
function setKey(k) { try { if (k) localStorage.setItem(KEY_STORE, k); else localStorage.removeItem(KEY_STORE); } catch (e) {} }
|
|
56
|
+
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]; }); }
|
|
57
|
+
function pct(v) { if (v == null || !isFinite(v)) return null; return Math.max(0, Math.min(100, v > 1 ? v : v * 100)); }
|
|
58
|
+
|
|
59
|
+
function gate(msg) {
|
|
60
|
+
app.innerHTML = '<div class="gate"><h1>Maxpool accounts</h1>' +
|
|
61
|
+
'<p class="sub">Enter your personal pool key. It stays in this browser only.</p>' +
|
|
62
|
+
'<input id="k" type="password" autocomplete="off" placeholder="Pool key">' +
|
|
63
|
+
'<div class="err">' + esc(msg || '') + '</div><button id="go">Open</button></div>';
|
|
64
|
+
document.getElementById('go').onclick = function () { setKey(document.getElementById('k').value.trim()); load(); };
|
|
65
|
+
document.getElementById('k').onkeydown = function (e) { if (e.key === 'Enter') document.getElementById('go').click(); };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function bar(label, v) {
|
|
69
|
+
var p = pct(v);
|
|
70
|
+
if (p == null) return '';
|
|
71
|
+
var cls = p >= 90 ? 'bad' : p >= 75 ? 'warn' : '';
|
|
72
|
+
return '<div class="bar"><span>' + label + '</span><div class="track"><div class="fill ' + cls + '" style="width:' + p.toFixed(0) + '%"></div></div><span>' + p.toFixed(0) + '%</span></div>';
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// status enum from account-manager: 'active' | 'throttled' | 'error'.
|
|
76
|
+
function stateOf(a) {
|
|
77
|
+
var q = a.quota || {};
|
|
78
|
+
var week = q.unified7d != null ? q.unified7d : q.providerWk;
|
|
79
|
+
if (a.enabled === false) return ['', 'Off'];
|
|
80
|
+
if (a.refreshDead) return ['bad', 'Needs login'];
|
|
81
|
+
if (a.status === 'error') return ['bad', 'Error'];
|
|
82
|
+
if (week != null && week >= 0.999) return ['warn', 'Used up this week'];
|
|
83
|
+
if (a.status === 'throttled' || a.rateLimitedUntil) return ['warn', 'Resting'];
|
|
84
|
+
return ['ok', 'Ready'];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function render(s) {
|
|
88
|
+
// Live needs-login accounts first; switched-off accounts last.
|
|
89
|
+
function rank(a) { return a.enabled === false ? 2 : (a.refreshDead ? 0 : 1); }
|
|
90
|
+
var accts = (s.accounts || []).slice().sort(function (x, y) {
|
|
91
|
+
return rank(x) - rank(y) || String(x.name).localeCompare(String(y.name));
|
|
92
|
+
});
|
|
93
|
+
var dead = accts.filter(function (a) { return a.refreshDead && a.enabled !== false; }).length;
|
|
94
|
+
var callers = s.callers || {};
|
|
95
|
+
var people = Object.keys(callers).sort().map(function (n) {
|
|
96
|
+
var c = callers[n].requests;
|
|
97
|
+
return '<span class="chip">' + esc(n) + ' · ' + c + (c === 1 ? ' request' : ' requests') + '</span>';
|
|
98
|
+
}).join('');
|
|
99
|
+
var rows = accts.map(function (a) {
|
|
100
|
+
var st = stateOf(a), q = a.quota || {};
|
|
101
|
+
// Field names from getStatus().accounts[].quota: Claude = unified5h/unified7d,
|
|
102
|
+
// providers (z.ai/kimi) = providerSes/providerWk. All 0..1 fractions.
|
|
103
|
+
var five = q.unified5h != null ? q.unified5h : q.providerSes;
|
|
104
|
+
var week = q.unified7d != null ? q.unified7d : q.providerWk;
|
|
105
|
+
return '<div class="acct' + (a.refreshDead ? ' dead' : '') + '">' +
|
|
106
|
+
'<div><div class="name">' + esc(a.name) + '</div><div class="sub">' + esc(a.provider || (a.type === 'oauth' ? 'Claude' : a.type)) +
|
|
107
|
+
(a.inFlight ? ' · ' + a.inFlight + ' running' : '') + '</div></div>' +
|
|
108
|
+
'<div class="bars">' + bar('5h', five) + bar('7d', week) + '</div>' +
|
|
109
|
+
'<span class="state ' + st[0] + '">' + st[1] + '</span></div>';
|
|
110
|
+
}).join('');
|
|
111
|
+
var ver = (s.runningVersion || (s.version && s.version.current) || '');
|
|
112
|
+
app.innerHTML = '<header><h1>Maxpool accounts</h1><span class="meta">' + accts.length + ' accounts' +
|
|
113
|
+
(dead ? ' · <b style="color:var(--bad)">' + dead + (dead === 1 ? ' needs login' : ' need login') + '</b>' : '') +
|
|
114
|
+
(ver ? ' · v' + esc(ver) : '') + ' · updated ' + new Date().toLocaleTimeString() + '</span>' +
|
|
115
|
+
'<button class="link" id="out">Forget key</button></header>' +
|
|
116
|
+
(people ? '<div class="people">' + people + '</div>' : '') +
|
|
117
|
+
'<div class="grid">' + rows + '</div>';
|
|
118
|
+
document.getElementById('out').onclick = function () { setKey(''); gate(); };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
var timer = null;
|
|
122
|
+
function load() {
|
|
123
|
+
var k = getKey();
|
|
124
|
+
if (!k) { gate(); return; }
|
|
125
|
+
fetch('/maxpool/status', { headers: { 'x-api-key': k }, cache: 'no-store' })
|
|
126
|
+
.then(function (r) {
|
|
127
|
+
if (r.status === 401) { setKey(''); gate('That key was not accepted.'); throw null; }
|
|
128
|
+
if (!r.ok) throw new Error('Pool returned ' + r.status);
|
|
129
|
+
return r.json();
|
|
130
|
+
})
|
|
131
|
+
.then(function (s) { render(s); clearTimeout(timer); timer = setTimeout(load, 5000); })
|
|
132
|
+
.catch(function (e) { if (e) { clearTimeout(timer); timer = setTimeout(load, 5000); } });
|
|
133
|
+
}
|
|
134
|
+
load();
|
|
135
|
+
})();
|
|
136
|
+
</script>
|
|
137
|
+
</body>
|
|
138
|
+
</html>
|
package/src/secret-resolver.js
CHANGED
|
@@ -17,7 +17,9 @@ import { join } from 'node:path';
|
|
|
17
17
|
|
|
18
18
|
const execFileAsync = promisify(execFile);
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
// Configurable so public-npm users point at their own GCP project (set
|
|
21
|
+
// MAXPOOL_GCP_PROJECT); our team default stays ours.
|
|
22
|
+
const DEFAULT_PROJECT = process.env.MAXPOOL_GCP_PROJECT || 'mokka-business-automations';
|
|
21
23
|
|
|
22
24
|
// A single `gcloud secrets versions access` costs ~17-33s on this machine (python
|
|
23
25
|
// interpreter start + an ADC round-trip), and running them CONCURRENTLY makes it
|
package/src/server.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
+
import { appendEventLog } from './event-log.js';
|
|
2
3
|
import { ThreadOwners, readThreadIntent, threadRefusalBody, isThreadlessAccount } from './thread-gate.js';
|
|
3
4
|
import { writeFile, mkdir } from 'node:fs/promises';
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
4
6
|
import { join } from 'node:path';
|
|
5
7
|
import { modelFamily } from './oauth.js';
|
|
6
8
|
|
|
@@ -39,6 +41,15 @@ const isNetworkCode = c => Boolean(c) && NETWORK_ERROR_CODES.has(c);
|
|
|
39
41
|
const NETWORK_SOAK_NONSTREAM_MS = Math.max(5_000,
|
|
40
42
|
Number(process.env.MAXPOOL_NETWORK_SOAK_NONSTREAM_MS) || 45_000);
|
|
41
43
|
const QUEUE_KEEPALIVE = 'event: ping\ndata: {}\n\n';
|
|
44
|
+
// Account screen shell (served keyless at /maxpool/screen; the page itself prompts
|
|
45
|
+
// for a pool key and reads the key-gated /maxpool/status). Read once at boot.
|
|
46
|
+
const SCREEN_HTML = (() => {
|
|
47
|
+
try {
|
|
48
|
+
return readFileSync(new URL('./screen.html', import.meta.url), 'utf8');
|
|
49
|
+
} catch {
|
|
50
|
+
return '<!doctype html><title>Maxpool</title><p>screen.html missing</p>';
|
|
51
|
+
}
|
|
52
|
+
})();
|
|
42
53
|
// Claude Code's absolute per-stream ceiling (binary-verified 2026-10-07: idle timeout =
|
|
43
54
|
// min(env-or-300s-floor, 1800000)). Nothing resets it; the stream dies at 30 min.
|
|
44
55
|
const CLI_STREAM_CEILING_MS = 25 * 60_000; // bound network holds strictly below it
|
|
@@ -146,6 +157,42 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
146
157
|
const logDir = config.logDir || null;
|
|
147
158
|
let requestCounter = 0;
|
|
148
159
|
|
|
160
|
+
// ── team clients (per-person keys + caller identity) ──
|
|
161
|
+
// `clients: [{name, key}]` opts into strict auth: EVERY request (proxy traffic,
|
|
162
|
+
// /maxpool/status, /maxpool/screen) must carry a listed key, the loopback bypass
|
|
163
|
+
// is removed, and each request is attributed to the named person in logs/status.
|
|
164
|
+
// A non-loopback listen host also forces strict even without clients (a shared
|
|
165
|
+
// pool must never trust by address). Default local config (loopback host, no
|
|
166
|
+
// clients) keeps today's behavior exactly.
|
|
167
|
+
const clientList = Array.isArray(config.proxy?.clients)
|
|
168
|
+
? config.proxy.clients.filter(c => c && typeof c.key === 'string' && c.key)
|
|
169
|
+
: [];
|
|
170
|
+
const clientByKey = new Map(clientList.map(c => [c.key, c.name]));
|
|
171
|
+
// '0.0.0.0' stays in the trusted set for backward compatibility (a solo user who
|
|
172
|
+
// binds every interface keeps keyless local use); it is warned about at startup
|
|
173
|
+
// because it also exposes the pool to the network. Shared pools set `clients`.
|
|
174
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '0.0.0.0']);
|
|
175
|
+
const hostIsLoopback = (config.proxy?.host == null) || LOOPBACK_HOSTS.has(String(config.proxy.host).toLowerCase());
|
|
176
|
+
const strictClients = clientByKey.size > 0 || !hostIsLoopback;
|
|
177
|
+
const resolveCaller = (key, isLocal) => {
|
|
178
|
+
if (key != null && clientByKey.has(key)) return { name: clientByKey.get(key), ok: true };
|
|
179
|
+
// Legacy single key still works — including strict mode, so a solo user can
|
|
180
|
+
// point clients at a shared host without defining named clients.
|
|
181
|
+
if (proxyApiKey && key === proxyApiKey) return { name: null, ok: true };
|
|
182
|
+
if (!strictClients) {
|
|
183
|
+
// Legacy trust model: loopback callers are trusted; when NO key is
|
|
184
|
+
// configured at all the pool is open (today's no-apiKey behavior).
|
|
185
|
+
if (isLocal || !proxyApiKey) return { name: null, ok: true };
|
|
186
|
+
}
|
|
187
|
+
return { name: null, ok: false };
|
|
188
|
+
};
|
|
189
|
+
if (strictClients) {
|
|
190
|
+
const who = clientByKey.size > 0 ? `${clientByKey.size} named client${clientByKey.size > 1 ? 's' : ''}` : 'non-loopback listen host';
|
|
191
|
+
appendEventLog(`[Maxpool] Strict client auth ON (${who}; loopback bypass removed)`);
|
|
192
|
+
} else if (String(config.proxy?.host) === '0.0.0.0') {
|
|
193
|
+
appendEventLog('[Maxpool] WARNING: listening on every interface (0.0.0.0) with local callers trusted keyless — set proxy.clients to require a key from everyone');
|
|
194
|
+
}
|
|
195
|
+
|
|
149
196
|
if (logDir) {
|
|
150
197
|
mkdir(logDir, { recursive: true }).catch(() => {});
|
|
151
198
|
}
|
|
@@ -181,20 +228,41 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
181
228
|
if (draining) {
|
|
182
229
|
try { res.setHeader('Connection', 'close'); } catch { /* headers may be sent */ }
|
|
183
230
|
}
|
|
184
|
-
// Auth check —
|
|
231
|
+
// Auth check — per-person clients when configured, legacy single key otherwise.
|
|
232
|
+
// strictClients (clients list present, or a non-loopback listen host) removes
|
|
233
|
+
// the loopback bypass entirely: every caller must present a known key.
|
|
185
234
|
const clientKey = req.headers['x-api-key'];
|
|
186
235
|
const remoteAddr = req.socket.remoteAddress;
|
|
187
236
|
const isLocal = remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1';
|
|
237
|
+
const caller = resolveCaller(clientKey, isLocal);
|
|
238
|
+
|
|
239
|
+
const rejectUnauthorized = () => {
|
|
240
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
241
|
+
res.end(JSON.stringify({
|
|
242
|
+
type: 'error',
|
|
243
|
+
error: { type: 'authentication_error', message: strictClients ? 'Invalid or missing pool key' : 'Invalid proxy API key' },
|
|
244
|
+
}));
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
// Account screen: a static page with NO data in it — it asks the viewer for
|
|
248
|
+
// their pool key and reads /maxpool/status with it (which stays key-gated
|
|
249
|
+
// below), so serving the shell itself keyless leaks nothing.
|
|
250
|
+
if (req.method === 'GET' && (req.url === '/maxpool/screen' || req.url === '/maxpool/screen/')) {
|
|
251
|
+
res.writeHead(200, {
|
|
252
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
253
|
+
'Cache-Control': 'no-store',
|
|
254
|
+
'X-Frame-Options': 'DENY',
|
|
255
|
+
'Referrer-Policy': 'no-referrer',
|
|
256
|
+
});
|
|
257
|
+
res.end(SCREEN_HTML);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
188
260
|
|
|
189
261
|
// Status exposes account names and quota state, so require the local
|
|
190
262
|
// proxy key even for loopback callers.
|
|
191
263
|
if (req.method === 'GET' && req.url === '/maxpool/status') {
|
|
192
|
-
if (proxyApiKey && clientKey !== proxyApiKey) {
|
|
193
|
-
|
|
194
|
-
res.end(JSON.stringify({
|
|
195
|
-
type: 'error',
|
|
196
|
-
error: { type: 'authentication_error', message: 'Invalid proxy API key' },
|
|
197
|
-
}));
|
|
264
|
+
if (strictClients ? !caller.ok : (proxyApiKey && clientKey !== proxyApiKey)) {
|
|
265
|
+
rejectUnauthorized();
|
|
198
266
|
return;
|
|
199
267
|
}
|
|
200
268
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
@@ -202,14 +270,14 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
202
270
|
return;
|
|
203
271
|
}
|
|
204
272
|
|
|
205
|
-
if (
|
|
206
|
-
|
|
207
|
-
res.end(JSON.stringify({
|
|
208
|
-
type: 'error',
|
|
209
|
-
error: { type: 'authentication_error', message: 'Invalid proxy API key' },
|
|
210
|
-
}));
|
|
273
|
+
if (!caller.ok) {
|
|
274
|
+
rejectUnauthorized();
|
|
211
275
|
return;
|
|
212
276
|
}
|
|
277
|
+
// In strict mode the legacy single key is still accepted; label it so its
|
|
278
|
+
// traffic is attributed and logged rather than anonymous.
|
|
279
|
+
req.callerName = caller.name || (strictClients ? 'legacy-key' : null);
|
|
280
|
+
accountManager.countRequest?.(req.callerName);
|
|
213
281
|
|
|
214
282
|
// Let client token refresh requests pass through to upstream untouched.
|
|
215
283
|
// The proxy manages its own tokens via ensureTokenFresh(); intercepting
|
|
@@ -217,7 +285,7 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
217
285
|
if (req.method === 'POST' && req.url === '/v1/oauth/token') {
|
|
218
286
|
const reqId = ++requestCounter;
|
|
219
287
|
const ctx = { account: '(oauth relay)', status: null };
|
|
220
|
-
const accepted = hooks.onRequestStart?.(reqId, { method: req.method, path: req.url, sessionKey: headerValue(req.headers, 'x-maxpool-session') });
|
|
288
|
+
const accepted = hooks.onRequestStart?.(reqId, { method: req.method, path: req.url, sessionKey: headerValue(req.headers, 'x-maxpool-session'), caller: req.callerName || null });
|
|
221
289
|
if (accepted === false) {
|
|
222
290
|
res.writeHead(503, {
|
|
223
291
|
'Content-Type': 'application/json',
|
|
@@ -243,6 +311,7 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
243
311
|
path: req.url,
|
|
244
312
|
account: ctx.account,
|
|
245
313
|
status: ctx.status,
|
|
314
|
+
caller: req.callerName || null,
|
|
246
315
|
});
|
|
247
316
|
}
|
|
248
317
|
return;
|
|
@@ -253,7 +322,7 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
253
322
|
// sessionKey (from the per-terminal x-maxpool-session header) lets the TUI show
|
|
254
323
|
// how many distinct client sessions the in-flight requests span — so "N in-flight"
|
|
255
324
|
// isn't misread as "N sessions" (subagents of one terminal share one session key).
|
|
256
|
-
const accepted = hooks.onRequestStart?.(reqId, { method: req.method, path: req.url, sessionKey: headerValue(req.headers, 'x-maxpool-session') });
|
|
325
|
+
const accepted = hooks.onRequestStart?.(reqId, { method: req.method, path: req.url, sessionKey: headerValue(req.headers, 'x-maxpool-session'), caller: req.callerName || null });
|
|
257
326
|
if (accepted === false) {
|
|
258
327
|
res.writeHead(503, {
|
|
259
328
|
'Content-Type': 'application/json',
|
|
@@ -338,6 +407,7 @@ export function createProxyServer(accountManager, config, hooks = {}) {
|
|
|
338
407
|
hooks.onRequestEnd?.(reqId, {
|
|
339
408
|
method: req.method, path: req.url,
|
|
340
409
|
account: ctx.account, status: ctx.status,
|
|
410
|
+
caller: req.callerName || null,
|
|
341
411
|
});
|
|
342
412
|
}
|
|
343
413
|
} catch (err) {
|
package/src/tui.js
CHANGED
|
@@ -522,7 +522,7 @@ export class TUI {
|
|
|
522
522
|
// ── server hooks ───────────────────────────────────
|
|
523
523
|
|
|
524
524
|
onRequestStart(id, info) {
|
|
525
|
-
this.active.set(id, { ...info, t: timestamp(), started: Date.now(), account: null });
|
|
525
|
+
this.active.set(id, { ...info, t: timestamp(), started: Date.now(), account: null, caller: info.caller || null });
|
|
526
526
|
this.render();
|
|
527
527
|
}
|
|
528
528
|
|
|
@@ -536,6 +536,9 @@ export class TUI {
|
|
|
536
536
|
this.active.delete(id);
|
|
537
537
|
const dur = r ? ((Date.now() - r.started) / 1000).toFixed(1) : '?';
|
|
538
538
|
const acct = info.account || r?.account || '?';
|
|
539
|
+
// Named-caller attribution (team pools): prefix the log line with the person
|
|
540
|
+
// whose pool key authenticated the request. Null on legacy/local setups.
|
|
541
|
+
const who = info.caller || r?.caller ? `${info.caller || r?.caller} · ` : '';
|
|
539
542
|
// Tag PROVIDER-routed requests with the maxpool session id so provider traffic
|
|
540
543
|
// (when-exhausted overflow, or an incompatible-session pin) is traceable back to
|
|
541
544
|
// the session that caused it: grep the event log for `→ glm-fallback … [sess X]`,
|
|
@@ -543,7 +546,7 @@ export class TUI {
|
|
|
543
546
|
// guard — a header-less request has sessionKey '' (server.js headerValue) → no tag.
|
|
544
547
|
const isProvider = this.am.accounts.find(a => a.name === acct)?.type === 'provider';
|
|
545
548
|
const tag = (isProvider && r?.sessionKey) ? ` [sess ${String(r.sessionKey).slice(0, 8)}]` : '';
|
|
546
|
-
this._addLog(`${info.method} ${info.path} → ${acct} (${info.status}, ${dur}s)${tag}`);
|
|
549
|
+
this._addLog(`${who}${info.method} ${info.path} → ${acct} (${info.status}, ${dur}s)${tag}`);
|
|
547
550
|
}
|
|
548
551
|
|
|
549
552
|
_addLog(msg) {
|