omp-opencode-bridge 0.0.0-stage → 2.6.0
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/AGENTS.md +253 -0
- package/LICENSE +21 -0
- package/README.md +892 -3
- package/THIRD_PARTY_NOTICES.md +33 -0
- package/anthropic.ts +698 -0
- package/egress-proxy.ts +245 -0
- package/gate-drill.ts +1096 -0
- package/identity.ts +2841 -0
- package/install.sh +708 -0
- package/package.json +79 -4
- package/panel.ts +537 -0
- package/proxy.ts +1508 -0
- package/server.ts +3766 -0
- package/src/index.ts +364 -0
- package/token-budget.ts +116 -0
- package/transport-baseline.json +39 -0
- package/transport-fingerprint.ts +182 -0
- package/tunnel-doctor.sh +171 -0
- package/verify.ts +374 -0
package/tunnel-doctor.sh
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
#
|
|
3
|
+
# tunnel-doctor.sh — reap stale SSH port forwards, and check the keepalive that
|
|
4
|
+
# prevents them.
|
|
5
|
+
#
|
|
6
|
+
# The problem this exists for
|
|
7
|
+
# ---------------------------
|
|
8
|
+
# A reverse tunnel (`ssh -R 127.0.0.1:20132:127.0.0.1:20129 …`) is held open by
|
|
9
|
+
# an sshd child process on the *receiving* host. When the sending host reboots,
|
|
10
|
+
# loses power, or is suspended, the TCP connection dies without a FIN. The
|
|
11
|
+
# receiving sshd keeps the listening socket until it notices, and until then a
|
|
12
|
+
# replacement tunnel fails with:
|
|
13
|
+
#
|
|
14
|
+
# Error: remote port forwarding failed for listen port 20132
|
|
15
|
+
#
|
|
16
|
+
# With the default `ClientAliveInterval 300` / `ClientAliveCountMax 2`, "until it
|
|
17
|
+
# notices" can be ten minutes — long enough for a supervisor to give up, and long
|
|
18
|
+
# enough that an operator concludes the tunnel unit itself is broken. This script
|
|
19
|
+
# is the manual remedy for that window, and `--check` reports whether the
|
|
20
|
+
# keepalive is tight enough to keep the window short.
|
|
21
|
+
#
|
|
22
|
+
# What counts as stale
|
|
23
|
+
# --------------------
|
|
24
|
+
# Not "a listening socket exists" — a healthy tunnel listens too. A forwarded
|
|
25
|
+
# port is stale when its owning sshd session has **no established TCP connection
|
|
26
|
+
# to the peer**. The listener is the port forward; the ESTAB socket is the SSH
|
|
27
|
+
# transport that makes it work. No transport, no tunnel, regardless of what the
|
|
28
|
+
# listener still claims.
|
|
29
|
+
#
|
|
30
|
+
# Usage
|
|
31
|
+
# -----
|
|
32
|
+
# ./tunnel-doctor.sh # report only (default)
|
|
33
|
+
# ./tunnel-doctor.sh --reap # kill sessions whose transport is gone
|
|
34
|
+
# ./tunnel-doctor.sh --reap 20131 20132
|
|
35
|
+
# ./tunnel-doctor.sh --check # keepalive audit, exits 1 if too loose
|
|
36
|
+
#
|
|
37
|
+
# Exit codes: 0 healthy / reaped nothing needed, 1 problems found (report mode)
|
|
38
|
+
# or keepalive too loose (--check), 2 usage error.
|
|
39
|
+
#
|
|
40
|
+
# By default it scans the whole 20120-20149 block (set TUNNEL_PORTS="20129 20136"
|
|
41
|
+
# to narrow it). A hardcoded list silently skipped newly added nodes.
|
|
42
|
+
#
|
|
43
|
+
# Requires: ss, ps (iproute2 + procps). Must run as root on the receiving host.
|
|
44
|
+
|
|
45
|
+
set -euo pipefail
|
|
46
|
+
|
|
47
|
+
PORTS=()
|
|
48
|
+
REAP=0
|
|
49
|
+
CHECK=0
|
|
50
|
+
|
|
51
|
+
while [ $# -gt 0 ]; do
|
|
52
|
+
case "$1" in
|
|
53
|
+
--reap) REAP=1; shift ;;
|
|
54
|
+
--check) CHECK=1; shift ;;
|
|
55
|
+
-h|--help) sed -n '2,45p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
|
|
56
|
+
--*) echo "unknown flag: $1" >&2; exit 2 ;;
|
|
57
|
+
*) PORTS+=("$1"); shift ;;
|
|
58
|
+
esac
|
|
59
|
+
done
|
|
60
|
+
|
|
61
|
+
if [ "${#PORTS[@]}" -eq 0 ]; then
|
|
62
|
+
# Scan the whole 201xx block rather than a hardcoded 20129..20135 list: a new
|
|
63
|
+
# node's tunnel (20136 in this fleet) silently escaped the report, which is
|
|
64
|
+
# the one thing this script exists to catch. Override with TUNNEL_PORTS.
|
|
65
|
+
if [ -n "${TUNNEL_PORTS:-}" ]; then
|
|
66
|
+
# shellcheck disable=SC2206
|
|
67
|
+
PORTS=(${TUNNEL_PORTS})
|
|
68
|
+
else
|
|
69
|
+
PORTS=()
|
|
70
|
+
for p in $(seq 20120 20149); do
|
|
71
|
+
PORTS+=("$p")
|
|
72
|
+
done
|
|
73
|
+
fi
|
|
74
|
+
fi
|
|
75
|
+
|
|
76
|
+
# --- keepalive audit --------------------------------------------------------
|
|
77
|
+
# A session is declared dead after ClientAliveInterval × ClientAliveCountMax
|
|
78
|
+
# seconds. Anything above ~2 minutes leaves a rebooted peer's port held long
|
|
79
|
+
# enough to collide with an automatic restart.
|
|
80
|
+
if [ "$CHECK" -eq 1 ]; then
|
|
81
|
+
if ! command -v sshd >/dev/null 2>&1; then
|
|
82
|
+
echo "sshd not found; cannot audit keepalive" >&2
|
|
83
|
+
exit 1
|
|
84
|
+
fi
|
|
85
|
+
# `sshd -T` needs root to read its own config. Capture the failure rather than
|
|
86
|
+
# letting `set -e` + `pipefail` abort the script with no explanation.
|
|
87
|
+
if ! sshd_config=$(sshd -T 2>&1); then
|
|
88
|
+
echo "cannot read the effective sshd config (run as root):" >&2
|
|
89
|
+
echo " $(echo "$sshd_config" | head -1)" >&2
|
|
90
|
+
exit 1
|
|
91
|
+
fi
|
|
92
|
+
interval=$(printf '%s\n' "$sshd_config" | awk '$1=="clientaliveinterval"{print $2; exit}')
|
|
93
|
+
count=$(printf '%s\n' "$sshd_config" | awk '$1=="clientalivecountmax"{print $2; exit}')
|
|
94
|
+
interval=${interval:-0}
|
|
95
|
+
count=${count:-0}
|
|
96
|
+
window=$((interval * count))
|
|
97
|
+
echo "sshd keepalive: ClientAliveInterval=${interval}s ClientAliveCountMax=${count} -> dead peer detected after ${window}s"
|
|
98
|
+
if [ "$interval" -eq 0 ]; then
|
|
99
|
+
echo "FAIL: keepalive is disabled; a rebooted peer's forwards are held until the kernel gives up" >&2
|
|
100
|
+
exit 1
|
|
101
|
+
fi
|
|
102
|
+
if [ "$window" -gt 120 ]; then
|
|
103
|
+
echo "FAIL: ${window}s is too long; an automatic tunnel restart will collide with the stale listener" >&2
|
|
104
|
+
echo " Set ClientAliveInterval 30 + ClientAliveCountMax 4 (120s), or 15 + 4 (60s)." >&2
|
|
105
|
+
echo " Note OpenSSH uses the FIRST value it reads: a drop-in must sort BEFORE any" >&2
|
|
106
|
+
echo " existing one (e.g. /etc/ssh/sshd_config.d/00-keepalive.conf), or it is ignored." >&2
|
|
107
|
+
exit 1
|
|
108
|
+
fi
|
|
109
|
+
echo "OK: a dead peer is detected within ${window}s"
|
|
110
|
+
fi
|
|
111
|
+
|
|
112
|
+
if [ "$CHECK" -eq 1 ] && [ "$REAP" -eq 0 ] && [ "$#" -eq 0 ]; then
|
|
113
|
+
exit 0
|
|
114
|
+
fi
|
|
115
|
+
|
|
116
|
+
# --- stale forward reaping --------------------------------------------------
|
|
117
|
+
# For each port: find the sshd-session holding the listener, then ask whether
|
|
118
|
+
# that same process still has an ESTAB socket. `ss -tanp` lists the transport
|
|
119
|
+
# under both the privileged parent and the session child, so match the pid set
|
|
120
|
+
# of the whole session rather than one pid.
|
|
121
|
+
problems=0
|
|
122
|
+
reaped=0
|
|
123
|
+
|
|
124
|
+
for port in "${PORTS[@]}"; do
|
|
125
|
+
holder=$(ss -ltnp 2>/dev/null | awk -v p=":$port" '$4 ~ p"$" {print}' | grep -oE 'pid=[0-9]+' | head -1 | cut -d= -f2 || true)
|
|
126
|
+
if [ -z "${holder:-}" ]; then
|
|
127
|
+
printf '%-6s no listener (nothing to reap)\n' "$port"
|
|
128
|
+
continue
|
|
129
|
+
fi
|
|
130
|
+
|
|
131
|
+
cmd=$(ps -o cmd= -p "$holder" 2>/dev/null || true)
|
|
132
|
+
case "$cmd" in
|
|
133
|
+
*sshd-session*) : ;;
|
|
134
|
+
*)
|
|
135
|
+
printf '%-6s held by pid %s (%s) — not sshd, leaving alone\n' "$port" "$holder" "$(echo "$cmd" | cut -c1-40)"
|
|
136
|
+
continue
|
|
137
|
+
;;
|
|
138
|
+
esac
|
|
139
|
+
|
|
140
|
+
estab=$(ss -tanp 2>/dev/null | awk -v pid="pid=$holder," '$0 ~ pid && $1=="ESTAB"' | wc -l)
|
|
141
|
+
if [ "$estab" -gt 0 ]; then
|
|
142
|
+
printf '%-6s pid %-8s OK (%s established)\n' "$port" "$holder" "$estab"
|
|
143
|
+
continue
|
|
144
|
+
fi
|
|
145
|
+
|
|
146
|
+
problems=$((problems + 1))
|
|
147
|
+
printf '%-6s pid %-8s STALE (listener held, no established transport)\n' "$port" "$holder"
|
|
148
|
+
if [ "$REAP" -eq 1 ]; then
|
|
149
|
+
if kill "$holder" 2>/dev/null; then
|
|
150
|
+
printf '%-6s killed %s\n' "$port" "$holder"
|
|
151
|
+
reaped=$((reaped + 1))
|
|
152
|
+
else
|
|
153
|
+
printf '%-6s could not kill %s\n' "$port" "$holder" >&2
|
|
154
|
+
fi
|
|
155
|
+
fi
|
|
156
|
+
done
|
|
157
|
+
|
|
158
|
+
if [ "$REAP" -eq 1 ]; then
|
|
159
|
+
echo
|
|
160
|
+
echo "reaped ${reaped} stale session(s); restart the tunnel unit(s) to re-establish the forwards"
|
|
161
|
+
exit 0
|
|
162
|
+
fi
|
|
163
|
+
|
|
164
|
+
if [ "$problems" -gt 0 ]; then
|
|
165
|
+
echo
|
|
166
|
+
echo "${problems} stale forward(s). Re-run with --reap to clear them." >&2
|
|
167
|
+
exit 1
|
|
168
|
+
fi
|
|
169
|
+
|
|
170
|
+
echo
|
|
171
|
+
echo "all forwarded ports have a live transport"
|
package/verify.ts
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* verify.ts — self-check for opencode-free-bridge.
|
|
4
|
+
*
|
|
5
|
+
* Answers the only question a new user has: "does this actually work?"
|
|
6
|
+
*
|
|
7
|
+
* bun verify.ts full check: every discovered model, real prompt
|
|
8
|
+
* bun verify.ts --quick one probe per model, faster
|
|
9
|
+
*
|
|
10
|
+
* Exit code is 0 when at least one model answers, 1 otherwise, so it can be
|
|
11
|
+
* wired into CI or a post-install step.
|
|
12
|
+
*
|
|
13
|
+
* Upstream rate-limits individual models (HTTP 429, "Endpoint is
|
|
14
|
+
* unavailable"), so a single failure is not fatal — the summary separates
|
|
15
|
+
* "rate-limited" from "broken" and the exit code only depends on whether
|
|
16
|
+
* anything worked.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const http = require("http");
|
|
20
|
+
|
|
21
|
+
const PORT = parseInt(process.env.PORT || "20129", 10);
|
|
22
|
+
const RAW_HOST = process.env.HOST || "127.0.0.1";
|
|
23
|
+
const HOST = RAW_HOST === "0.0.0.0" || RAW_HOST === "::" ? "127.0.0.1" : RAW_HOST;
|
|
24
|
+
const BASE = `http://${HOST}:${PORT}`;
|
|
25
|
+
const QUICK = process.argv.includes("--quick");
|
|
26
|
+
|
|
27
|
+
const C = {
|
|
28
|
+
reset: "\x1b[0m", dim: "\x1b[2m", bold: "\x1b[1m",
|
|
29
|
+
green: "\x1b[32m", yellow: "\x1b[33m", red: "\x1b[31m", cyan: "\x1b[36m",
|
|
30
|
+
};
|
|
31
|
+
const ok = (s) => `${C.green}${s}${C.reset}`;
|
|
32
|
+
const warn = (s) => `${C.yellow}${s}${C.reset}`;
|
|
33
|
+
const bad = (s) => `${C.red}${s}${C.reset}`;
|
|
34
|
+
|
|
35
|
+
/** One probe's verdict for a model. */
|
|
36
|
+
interface ProbeResult {
|
|
37
|
+
state: "ok" | "ratelimited" | "gate-closed" | "upgrade-required" | "thinking-only" | "empty" | "failed";
|
|
38
|
+
ms: number;
|
|
39
|
+
detail?: string;
|
|
40
|
+
chars?: number;
|
|
41
|
+
outTokens?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Where the bridge dials upstream, as /health reports it. */
|
|
45
|
+
interface EgressInfo {
|
|
46
|
+
mode?: string;
|
|
47
|
+
proxy?: { proxy?: string };
|
|
48
|
+
relay?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The /health fields this check reads. */
|
|
52
|
+
interface HealthResult {
|
|
53
|
+
ok: boolean;
|
|
54
|
+
detail?: string;
|
|
55
|
+
version?: string;
|
|
56
|
+
runtime?: string | null;
|
|
57
|
+
models?: number;
|
|
58
|
+
egress?: EgressInfo | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Token usage as the bridge reports it. */
|
|
62
|
+
interface Usage {
|
|
63
|
+
completion_tokens?: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One completion, SSE chunk, or error envelope — only the fields read here. */
|
|
67
|
+
interface CompletionBody {
|
|
68
|
+
choices?: Array<{
|
|
69
|
+
message?: { role?: string; content?: string; reasoning_content?: string };
|
|
70
|
+
delta?: { content?: string; reasoning_content?: string };
|
|
71
|
+
finish_reason?: string | null;
|
|
72
|
+
}>;
|
|
73
|
+
usage?: Usage | null;
|
|
74
|
+
error?: { message?: string };
|
|
75
|
+
data?: Array<{ id?: string }>;
|
|
76
|
+
version?: string;
|
|
77
|
+
runtime?: string;
|
|
78
|
+
discoveredModels?: number;
|
|
79
|
+
egress?: EgressInfo;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The TLS fingerprint fields the drift check compares and prints. */
|
|
83
|
+
interface Fingerprint {
|
|
84
|
+
runtime?: string;
|
|
85
|
+
ciphers?: unknown;
|
|
86
|
+
extensions?: unknown;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Raw HTTP result; `error` is set only when the request never completed. */
|
|
90
|
+
interface ProbeHttpResponse {
|
|
91
|
+
status: number;
|
|
92
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
93
|
+
body?: CompletionBody | null;
|
|
94
|
+
raw?: string;
|
|
95
|
+
error?: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Fold an SSE stream from the bridge into one Chat Completions object.
|
|
100
|
+
*
|
|
101
|
+
* Only the fields the verdict logic reads are rebuilt: `choices[0].message`
|
|
102
|
+
* (content plus reasoning_content) and `usage`. Tool-call deltas are not needed
|
|
103
|
+
* by a readiness probe, so they are ignored rather than reconstructed.
|
|
104
|
+
*/
|
|
105
|
+
function assembleSse(raw: string): CompletionBody {
|
|
106
|
+
let content = "";
|
|
107
|
+
let reasoning = "";
|
|
108
|
+
let finish: string | null = null;
|
|
109
|
+
let usage: Usage | null = null;
|
|
110
|
+
for (const line of raw.split("\n")) {
|
|
111
|
+
if (!line.startsWith("data:")) continue;
|
|
112
|
+
const chunk = line.slice(5).trim();
|
|
113
|
+
if (!chunk || chunk === "[DONE]") continue;
|
|
114
|
+
let ev: CompletionBody | null = null;
|
|
115
|
+
try { ev = JSON.parse(chunk); } catch { continue; }
|
|
116
|
+
// The bridge forwards an in-stream failure as an SSE error event.
|
|
117
|
+
if (ev?.error) return { error: ev.error };
|
|
118
|
+
const choice = ev?.choices?.[0];
|
|
119
|
+
if (choice?.delta?.content) content += choice.delta.content;
|
|
120
|
+
if (choice?.delta?.reasoning_content) reasoning += choice.delta.reasoning_content;
|
|
121
|
+
if (choice?.finish_reason) finish = choice.finish_reason;
|
|
122
|
+
if (ev?.usage) usage = ev.usage;
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
choices: [{ message: { role: "assistant", content, reasoning_content: reasoning }, finish_reason: finish }],
|
|
126
|
+
usage,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function request(method: string, path: string, body: unknown, timeoutMs: number = QUICK ? 25000 : 120000): Promise<ProbeHttpResponse> {
|
|
131
|
+
return new Promise((resolve) => {
|
|
132
|
+
const payload = body ? JSON.stringify(body) : null;
|
|
133
|
+
const req = http.request(
|
|
134
|
+
{
|
|
135
|
+
host: HOST,
|
|
136
|
+
port: PORT,
|
|
137
|
+
path,
|
|
138
|
+
method,
|
|
139
|
+
headers: payload
|
|
140
|
+
? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) }
|
|
141
|
+
: {},
|
|
142
|
+
},
|
|
143
|
+
(res) => {
|
|
144
|
+
let data = "";
|
|
145
|
+
res.on("data", (c) => (data += c));
|
|
146
|
+
res.on("end", () => {
|
|
147
|
+
let parsed: CompletionBody | null = null;
|
|
148
|
+
try { parsed = JSON.parse(data); } catch { /* non-JSON body */ }
|
|
149
|
+
// The bridge always streams upstream, so a `stream: true` probe comes
|
|
150
|
+
// back as SSE. Fold it into the same shape a non-streaming call would
|
|
151
|
+
// return, so the verdict logic below reads one form only.
|
|
152
|
+
if (!parsed && /^\s*data:/.test(data)) parsed = assembleSse(data);
|
|
153
|
+
resolve({ status: res.statusCode, headers: res.headers, body: parsed, raw: data });
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
);
|
|
157
|
+
req.on("error", (err) => resolve({ status: 0, error: err.code || err.message }));
|
|
158
|
+
req.setTimeout(timeoutMs, () => { req.destroy(); resolve({ status: 0, error: "timeout" }); });
|
|
159
|
+
if (payload) req.write(payload);
|
|
160
|
+
req.end();
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// A reasoning model needs room to think before it answers. This mirrors the
|
|
165
|
+
// floor token-budget.ts enforces, so the check exercises the real path.
|
|
166
|
+
const PROBE_MAX_TOKENS = QUICK ? 50 : 2000;
|
|
167
|
+
|
|
168
|
+
async function checkHealth(): Promise<HealthResult> {
|
|
169
|
+
const res = await request("GET", "/health", null, 10000);
|
|
170
|
+
if (res.status !== 200 || !res.body) {
|
|
171
|
+
return { ok: false, detail: res.error || `HTTP ${res.status}` };
|
|
172
|
+
}
|
|
173
|
+
return {
|
|
174
|
+
ok: true,
|
|
175
|
+
version: res.body.version,
|
|
176
|
+
runtime: res.body.runtime || null,
|
|
177
|
+
models: res.body.discoveredModels,
|
|
178
|
+
egress: res.body.egress || null,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function listModels(): Promise<string[]> {
|
|
183
|
+
const res = await request("GET", "/v1/models", null, 15000);
|
|
184
|
+
if (res.status !== 200 || !res.body?.data) return [];
|
|
185
|
+
return res.body.data.map((m) => m.id);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function probe(model: string): Promise<ProbeResult> {
|
|
189
|
+
const started = Date.now();
|
|
190
|
+
// `stream: true` is not cosmetic. Measured from one IP, one process, one
|
|
191
|
+
// header set: an upstream request without `stream` is refused with 403
|
|
192
|
+
// FreeTierError while the identical request with `stream: true` succeeds
|
|
193
|
+
// (6/6 vs 0/6, interleaved). Upstream treats a non-streaming call as
|
|
194
|
+
// "not the real client". A probe that omits it therefore measures nothing
|
|
195
|
+
// and reports the IP as blocked. The bridge always streams upstream and
|
|
196
|
+
// normalises the SSE back to JSON for non-streaming clients, so this
|
|
197
|
+
// matches what the bridge actually sends.
|
|
198
|
+
const res = await request("POST", "/v1/chat/completions", {
|
|
199
|
+
model,
|
|
200
|
+
messages: [{ role: "user", content: QUICK ? "Say OK" : "Write a Python function `add(a,b)` that returns their sum. Output only code." }],
|
|
201
|
+
max_tokens: PROBE_MAX_TOKENS,
|
|
202
|
+
stream: true,
|
|
203
|
+
});
|
|
204
|
+
const ms = Date.now() - started;
|
|
205
|
+
|
|
206
|
+
if (res.status === 429) return { state: "ratelimited", ms };
|
|
207
|
+
if (res.status === 403) {
|
|
208
|
+
const msg = String(res.body?.error?.message || res.error || "");
|
|
209
|
+
// The bridge labels the refusal, so the verdict does not depend on wording
|
|
210
|
+
// that upstream can rephrase:
|
|
211
|
+
// ip-throttled per-IP free-tier allowance spent
|
|
212
|
+
// ip-abuse gateway flagged this network (abusive traffic)
|
|
213
|
+
// shape-rejected the bridge built a request the gate refuses (real fault)
|
|
214
|
+
// Both IP states are upstream refusals, not a broken install, so they share
|
|
215
|
+
// the GATE state and exit code 2.
|
|
216
|
+
const gate = String(res.headers?.["x-opencode-gate"] || "");
|
|
217
|
+
if (gate === "shape-rejected") {
|
|
218
|
+
return { state: "failed", ms, detail: `gate rejected the bridge's request shape: ${msg.slice(0, 70)}` };
|
|
219
|
+
}
|
|
220
|
+
if (
|
|
221
|
+
gate === "ip-throttled" ||
|
|
222
|
+
gate === "ip-abuse" ||
|
|
223
|
+
/free tier can only be used|free models aren[’']t available|abusive traffic|abuse traffic|abuse of traffic|FreeTierError/i.test(msg)
|
|
224
|
+
) {
|
|
225
|
+
return { state: "gate-closed", ms, detail: String(msg).slice(0, 90) };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (res.status === 426) {
|
|
229
|
+
const msg = res.body?.error?.message || res.error || "HTTP 426";
|
|
230
|
+
return { state: "upgrade-required", ms, detail: String(msg).slice(0, 90) };
|
|
231
|
+
}
|
|
232
|
+
if (res.status !== 200) {
|
|
233
|
+
const msg = res.body?.error?.message || res.error || `HTTP ${res.status}`;
|
|
234
|
+
return { state: "failed", ms, detail: String(msg).slice(0, 70) };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const message = res.body?.choices?.[0]?.message;
|
|
238
|
+
const content = (message?.content || "").trim();
|
|
239
|
+
const reasoning = (message?.reasoning_content || "").trim();
|
|
240
|
+
|
|
241
|
+
if (!content && reasoning) {
|
|
242
|
+
return { state: "thinking-only", ms, detail: `${reasoning.length} chars of reasoning, no answer` };
|
|
243
|
+
}
|
|
244
|
+
if (!content) return { state: "empty", ms };
|
|
245
|
+
return { state: "ok", ms, chars: content.length, outTokens: res.body?.usage?.completion_tokens };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
(async (): Promise<void> => {
|
|
249
|
+
console.log(`\n${C.bold}opencode-free-bridge — self check${C.reset}`);
|
|
250
|
+
console.log(`${C.dim}${BASE}${C.reset}\n`);
|
|
251
|
+
|
|
252
|
+
const health = await checkHealth();
|
|
253
|
+
if (!health.ok) {
|
|
254
|
+
console.log(` ${bad("FAIL")} bridge not reachable: ${health.detail}`);
|
|
255
|
+
console.log(`\n Start it first: ${C.cyan}bun server.ts${C.reset}`);
|
|
256
|
+
console.log(` Or install it: ${C.cyan}bash install.sh${C.reset}\n`);
|
|
257
|
+
process.exit(1);
|
|
258
|
+
}
|
|
259
|
+
console.log(` ${ok("OK")} bridge v${health.version}, ${health.models} free models discovered\n`);
|
|
260
|
+
// Which IP upstream will see. A refused allowance is often a proxy problem,
|
|
261
|
+
// so say where the traffic leaves before blaming upstream.
|
|
262
|
+
const egress = health.egress;
|
|
263
|
+
if (egress) {
|
|
264
|
+
const label =
|
|
265
|
+
egress.mode === "proxy"
|
|
266
|
+
? `proxy ${egress.proxy?.proxy || "(configured)"}`
|
|
267
|
+
: egress.mode === "relay"
|
|
268
|
+
? `relay ${egress.relay || "(configured)"}`
|
|
269
|
+
: "direct (this machine's IP)";
|
|
270
|
+
console.log(` ${C.dim}egress: ${label}${C.reset}\n`);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const models = await listModels();
|
|
274
|
+
if (models.length === 0) {
|
|
275
|
+
console.log(` ${warn("WARN")} no models listed at /v1/models — upstream may be unreachable`);
|
|
276
|
+
console.log(` ${C.dim}wait for discovery to complete, then try again${C.reset}\n`);
|
|
277
|
+
process.exit(1);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// --quick answers one question: does this bridge work right now? The first
|
|
281
|
+
// model that answers settles it. Probing all nine costs up to 120s each when
|
|
282
|
+
// upstream is throttling, which made `install.sh` look hung for minutes.
|
|
283
|
+
const toProbe = QUICK ? models.slice(0, 3) : models;
|
|
284
|
+
console.log(
|
|
285
|
+
` Probing ${toProbe.length}${QUICK && models.length > toProbe.length ? " of " + models.length : ""} models${
|
|
286
|
+
QUICK ? " (quick — stops at the first success)" : ""
|
|
287
|
+
}...\n`
|
|
288
|
+
);
|
|
289
|
+
const results: Array<ProbeResult & { model: string }> = [];
|
|
290
|
+
for (const model of toProbe) {
|
|
291
|
+
const r = await probe(model);
|
|
292
|
+
results.push({ model, ...r });
|
|
293
|
+
const time = `${(r.ms / 1000).toFixed(1)}s`.padStart(6);
|
|
294
|
+
if (r.state === "ok") {
|
|
295
|
+
console.log(` ${ok("OK")} ${model.padEnd(36)} ${time} ${C.dim}${r.chars} chars, ${r.outTokens} tokens${C.reset}`);
|
|
296
|
+
} else if (r.state === "ratelimited") {
|
|
297
|
+
console.log(` ${warn("BUSY")} ${model.padEnd(36)} ${time} ${C.dim}upstream rate limit, retry later${C.reset}`);
|
|
298
|
+
} else if (r.state === "gate-closed") {
|
|
299
|
+
console.log(` ${warn("GATE")} ${model.padEnd(36)} ${time} ${C.dim}upstream refuses this IP (allowance or abuse block)${C.reset}`);
|
|
300
|
+
} else if (r.state === "upgrade-required") {
|
|
301
|
+
console.log(` ${bad("UPGR")} ${model.padEnd(36)} ${time} ${C.dim}${r.detail}${C.reset}`);
|
|
302
|
+
} else if (r.state === "thinking-only") {
|
|
303
|
+
console.log(` ${bad("THINK")} ${model.padEnd(36)} ${time} ${C.dim}${r.detail}${C.reset}`);
|
|
304
|
+
} else if (r.state === "empty") {
|
|
305
|
+
console.log(` ${bad("EMPTY")} ${model.padEnd(36)} ${time}`);
|
|
306
|
+
} else {
|
|
307
|
+
console.log(` ${bad("FAIL")} ${model.padEnd(36)} ${time} ${C.dim}${r.detail}${C.reset}`);
|
|
308
|
+
}
|
|
309
|
+
if (QUICK && r.state === "ok") break;
|
|
310
|
+
// A 429 allowance is per-IP: firing the remaining models at a throttled
|
|
311
|
+
// peer only prolongs the penalty window — same trade-off as gate-closed.
|
|
312
|
+
if (r.state === "gate-closed") break;
|
|
313
|
+
if (r.state === "ratelimited") break;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const counts: Record<string, number> = results.reduce((acc: Record<string, number>, r) => ((acc[r.state] = (acc[r.state] || 0) + 1), acc), {});
|
|
317
|
+
const usable = counts.ok || 0;
|
|
318
|
+
const blocked = (counts["gate-closed"] || 0) + (counts.ratelimited || 0);
|
|
319
|
+
const broken = (counts["thinking-only"] || 0) + (counts.empty || 0) + (counts.failed || 0) + (counts["upgrade-required"] || 0);
|
|
320
|
+
|
|
321
|
+
console.log(`\n${C.bold}Summary${C.reset}`);
|
|
322
|
+
console.log(` ${ok(String(usable))} usable, ${blocked} blocked by upstream (${counts["gate-closed"] || 0} gate-closed, ${counts.ratelimited || 0} rate-limited), ${broken} broken`);
|
|
323
|
+
|
|
324
|
+
if (usable > 0) {
|
|
325
|
+
console.log(`\n ${ok("Bridge is working.")} Point any OpenAI-compatible client at ${C.cyan}${BASE}/v1${C.reset}\n`);
|
|
326
|
+
process.exit(0);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (blocked > 0 && broken === 0) {
|
|
330
|
+
if (counts["gate-closed"] > 0) {
|
|
331
|
+
if (typeof health.runtime === "string" && health.runtime.startsWith("node/")) {
|
|
332
|
+
console.log(`\n ${bad("Server is running on Node.js, not Bun.")}`);
|
|
333
|
+
console.log(` ${C.dim}The bridge reported runtime ${health.runtime}. Upstream rejects Node's TLS ClientHello with 403 FreeTierError.${C.reset}`);
|
|
334
|
+
console.log(` ${C.dim}Restart the bridge with Bun: ${C.reset}${C.cyan}bun server.ts${C.reset}\n`);
|
|
335
|
+
process.exit(1);
|
|
336
|
+
}
|
|
337
|
+
if (process.versions.bun) {
|
|
338
|
+
let tlsDrift: { now: Fingerprint; base: Fingerprint } | null = null;
|
|
339
|
+
try {
|
|
340
|
+
const fs = require("fs");
|
|
341
|
+
const path = require("path");
|
|
342
|
+
const basePath = path.join(__dirname, "transport-baseline.json");
|
|
343
|
+
if (fs.existsSync(basePath)) {
|
|
344
|
+
const { capture, describe } = require("./transport-fingerprint");
|
|
345
|
+
const base = JSON.parse(fs.readFileSync(basePath, "utf8"));
|
|
346
|
+
const now = describe(await capture());
|
|
347
|
+
const sameCiphers = JSON.stringify(base.ciphers) === JSON.stringify(now.ciphers);
|
|
348
|
+
const sameExts = JSON.stringify(base.extensions) === JSON.stringify(now.extensions);
|
|
349
|
+
if (!sameCiphers || !sameExts) tlsDrift = { now, base };
|
|
350
|
+
}
|
|
351
|
+
} catch {}
|
|
352
|
+
if (tlsDrift) {
|
|
353
|
+
console.log(`\n ${bad("TLS fingerprint drift detected.")}`);
|
|
354
|
+
console.log(` ${C.dim}This Bun runtime (${tlsDrift.now.runtime}) does not match the recorded OpenCode CLI baseline (${tlsDrift.base.runtime}).${C.reset}`);
|
|
355
|
+
console.log(` ${C.dim}Inspect: ${C.reset}${C.cyan}bun transport-fingerprint.ts --check${C.reset}\n`);
|
|
356
|
+
process.exit(1);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
// Exit 2 is deliberately distinct from 1: the install is correct, the IP
|
|
361
|
+
// is not currently allowed. The installer and CI can tell these apart.
|
|
362
|
+
console.log(`\n ${warn("Bridge is healthy, but upstream refused this IP.")}`);
|
|
363
|
+
console.log(` ${C.dim}The gateway answered every probe with its own free-tier refusal, not a bridge error.${C.reset}`);
|
|
364
|
+
console.log(` ${C.dim}The official OpenCode CLI gets the same answer from this network right now.${C.reset}`);
|
|
365
|
+
console.log(` ${C.dim}If the message names abusive traffic, the network is flagged: email help@anoma.ly; only upstream can clear it.${C.reset}`);
|
|
366
|
+
console.log(` ${C.dim}Otherwise wait for the allowance window to reset, or run the bridge on another host.${C.reset}`);
|
|
367
|
+
console.log(` ${C.dim}Re-check later: ${C.reset}${C.cyan}bun verify.ts --quick${C.reset}\n`);
|
|
368
|
+
process.exit(2);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
console.log(`\n ${bad("No model answered.")}`);
|
|
372
|
+
console.log(` ${C.dim}Check the bridge log for the upstream error, then retry.${C.reset}\n`);
|
|
373
|
+
process.exit(1);
|
|
374
|
+
})();
|