mirror of
https://github.com/dtzp555-max/ocp.git
synced 2026-07-22 05:25:08 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a731fc36e | ||
|
|
49baffe2da | ||
|
|
4b01d4e768 | ||
|
|
36fa81d1e6 | ||
|
|
cce0110253 | ||
|
|
40391791a1 | ||
|
|
342a0a44f5 |
@@ -0,0 +1,9 @@
|
|||||||
|
# GitHub recognizes this file and shows a "Sponsor" button on the repo page.
|
||||||
|
# Add other platforms here as they get set up. Empty / commented-out entries
|
||||||
|
# are skipped silently.
|
||||||
|
|
||||||
|
buy_me_a_coffee: dtzp555
|
||||||
|
|
||||||
|
# github: [dtzp555-max] # uncomment after GitHub Sponsors enrollment is approved
|
||||||
|
# ko_fi: dtzp555
|
||||||
|
# custom: ["https://example.com/donate"]
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
# OCP — Open Claude Proxy
|
# OCP — Open Claude Proxy
|
||||||
|
|
||||||
|
[](LICENSE) [](https://github.com/dtzp555-max/ocp/releases) [](https://buymeacoffee.com/dtzp555)
|
||||||
|
|
||||||
> **Already paying for Claude Pro/Max? Use your subscription as an OpenAI-compatible API — $0 extra cost.**
|
> **Already paying for Claude Pro/Max? Use your subscription as an OpenAI-compatible API — $0 extra cost.**
|
||||||
|
|
||||||
|
*Open source from day one, used daily by my family, maintained on nights and weekends. If OCP saves you money too, you can [☕ buy me a coffee](https://buymeacoffee.com/dtzp555) — [full story below](#support-ocp).*
|
||||||
|
|
||||||
OCP turns your Claude Pro/Max subscription into a standard OpenAI-compatible API on localhost. Any tool that speaks the OpenAI protocol can use it — no separate API key, no extra billing.
|
OCP turns your Claude Pro/Max subscription into a standard OpenAI-compatible API on localhost. Any tool that speaks the OpenAI protocol can use it — no separate API key, no extra billing.
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -16,14 +20,15 @@ One proxy. Multiple IDEs. All models. **$0 API cost.**
|
|||||||
|
|
||||||
## Why OCP?
|
## Why OCP?
|
||||||
|
|
||||||
There are several Claude proxy projects. OCP picks a specific lane: **align tightly with what `cli.js` actually does, observe + multiplex what's already there, don't extend the protocol.** Concretely:
|
There are several Claude proxy projects. OCP picks a specific lane: **align tightly with what `cli.js` actually does, observe + multiplex what's already there, don't extend the protocol.** What you get:
|
||||||
|
|
||||||
- **SSE heartbeat on streaming** ([v3.12.0](https://github.com/dtzp555-max/ocp/releases/tag/v3.12.0), opt-in via `CLAUDE_HEARTBEAT_INTERVAL`). Long Claude reasoning or tool-use pauses can sit silent for minutes; downstream load balancers and reverse proxies often kill the connection at 60s idle. OCP emits an SSE comment frame during silent windows so the connection stays alive without polluting the response. ([PR #49](https://github.com/dtzp555-max/ocp/pull/49))
|
- **LAN multi-user keys** (v3.7.0) — share one Claude Pro/Max subscription with family, friends, or your own devices. Each user gets a per-key API token (no OAuth session leak), with independent usage tracking and one-line revocation.
|
||||||
- **Alignment constitution + CI guardrail.** [`ALIGNMENT.md`](./ALIGNMENT.md) is the binding spec: every endpoint OCP exposes must correspond to something `cli.js` actually does, with a line-number citation. The [`alignment.yml`](./.github/workflows/alignment.yml) workflow auto-blocks PRs that introduce known-hallucinated tokens (`api/oauth/usage`, `api/usage`, etc). Hard to drift, even with LLM-assisted contributions.
|
- **`ocp-connect` one-shot IDE setup** — one command on the client machine detects and configures Claude Code, Cursor, Cline, Continue.dev, OpenCode, and OpenClaw. No pasting `OPENAI_BASE_URL` six times.
|
||||||
- **`models.json` single source of truth** (v3.11.0). Adding a model is one file edit; both `/v1/models` and the OpenClaw bootstrap derive from it. No more drift between server and installer. ([PR #30](https://github.com/dtzp555-max/ocp/pull/30))
|
- **Response cache with per-key isolation + singleflight** (v3.13.0). Optional SHA-256 prompt cache, isolated per API key (cross-user pollution is impossible by hash construction, not by application logic), with stampede protection on concurrent identical prompts. Off by default. ([PR #65](https://github.com/dtzp555-max/ocp/pull/65), [PR #66](https://github.com/dtzp555-max/ocp/pull/66))
|
||||||
- **Multi anonymous-key distribution** (v3.7.0). Share one OCP instance with friends/family/devices without exposing your OAuth session — each gets a per-user key, with usage tracking and revocation.
|
- **Per-key request quotas** (v3.8.0). Daily / weekly / monthly limits per key — set a kid's iPad to 20/day, a partner's laptop to 100/week. ([PR #18](https://github.com/dtzp555-max/ocp/pull/18))
|
||||||
- **Per-key quota + response cache** (v3.8.0). Daily/weekly/monthly request limits per key. Optional SHA-256 prompt cache for development loops. ([PR #18](https://github.com/dtzp555-max/ocp/pull/18))
|
- **SSE heartbeat for long reasoning** ([v3.12.0](https://github.com/dtzp555-max/ocp/releases/tag/v3.12.0), opt-in). If you've ever watched your IDE die at the 60s idle mark during a long Claude tool-use pause — that's nginx/Cloudflare default behavior. OCP emits an SSE comment frame to keep the connection alive without polluting the response. ([PR #49](https://github.com/dtzp555-max/ocp/pull/49))
|
||||||
- **`ocp-connect` IDE auto-config.** Detects Claude Code, Cursor, Cline, Continue.dev, opencode, and OpenClaw on the client machine and configures them in one command.
|
- **`cli.js` alignment + CI guardrail.** LLM-assisted code drifts easily — it's tempting to invent plausible-looking endpoints that `cli.js` doesn't actually use. [`ALIGNMENT.md`](./ALIGNMENT.md) is binding: every endpoint OCP exposes must cite a `cli.js` line. The [`alignment.yml`](./.github/workflows/alignment.yml) CI workflow blocks PRs that introduce known-hallucinated tokens. The payoff is boring: your setup keeps working when `cli.js` ships its next minor.
|
||||||
|
- **`models.json` single source of truth** (v3.11.0). Adding a model is one file edit; both `/v1/models` and the OpenClaw bootstrap derive from it. ([PR #30](https://github.com/dtzp555-max/ocp/pull/30))
|
||||||
|
|
||||||
### Comparison
|
### Comparison
|
||||||
|
|
||||||
@@ -78,13 +83,96 @@ OCP has two roles: **Server** (runs the proxy, needs Claude CLI) and **Client**
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Quick install with AI assistance
|
||||||
|
|
||||||
|
If you've got Claude Code, Cursor, or any other AI coding assistant on this machine, you can copy-paste one of these prompts and let the AI walk through the install for you. Each prompt pins the AI to the right README section, names the verification step, and forbids silent retries — so you stay in the loop.
|
||||||
|
|
||||||
|
**Single-machine use** — install OCP for IDEs on this same machine only:
|
||||||
|
|
||||||
|
```text
|
||||||
|
I want to install OCP on this machine to use my Claude Pro/Max subscription
|
||||||
|
as an OpenAI-compatible API for local IDEs.
|
||||||
|
|
||||||
|
Please follow https://github.com/dtzp555-max/ocp/blob/main/README.md
|
||||||
|
"Server Setup" → "Single-machine use" path:
|
||||||
|
|
||||||
|
1. Verify prerequisites: macOS or Linux, Node.js 22.5+, git, Claude CLI
|
||||||
|
installed and logged in (`claude auth status`). Install missing pieces
|
||||||
|
using my system's package manager.
|
||||||
|
2. git clone the repo, cd in, and run `node setup.mjs`.
|
||||||
|
3. Verify with `curl http://127.0.0.1:3456/v1/models` (should list 4 models).
|
||||||
|
4. Add `export OPENAI_BASE_URL=http://127.0.0.1:3456/v1` to my shell rc.
|
||||||
|
5. Tell me to reload my shell and try a tool like Cline / Continue / Cursor.
|
||||||
|
|
||||||
|
Before each step, tell me what you'll run and wait for confirmation.
|
||||||
|
On any error, diagnose first — don't auto-retry.
|
||||||
|
```
|
||||||
|
|
||||||
|
**LAN mode (server)** — install OCP as a server so your family or multiple devices can share it:
|
||||||
|
|
||||||
|
```text
|
||||||
|
I want to install OCP on this device as a LAN server so my family and other
|
||||||
|
devices on the network can share my Claude Pro/Max subscription.
|
||||||
|
|
||||||
|
Please follow https://github.com/dtzp555-max/ocp/blob/main/README.md
|
||||||
|
"Server Setup" → "LAN mode" path:
|
||||||
|
|
||||||
|
1. Verify prerequisites: macOS or Linux (Windows not supported), Node.js
|
||||||
|
22.5+, git, Claude CLI installed and authenticated.
|
||||||
|
2. Generate a strong admin key with `openssl rand -base64 32`. Save it —
|
||||||
|
I'll need it to manage per-user keys later.
|
||||||
|
3. git clone https://github.com/dtzp555-max/ocp.git && cd ocp
|
||||||
|
4. Run `node setup.mjs --bind 0.0.0.0 --auth-mode multi`.
|
||||||
|
5. Add OCP_ADMIN_KEY to my shell rc (~/.zshrc or ~/.bashrc).
|
||||||
|
6. Run `ocp lan` to show me the LAN IP and connect command.
|
||||||
|
7. Optionally create example keys: `ocp keys add laptop`, `ocp keys add tablet`.
|
||||||
|
8. Verify: `curl http://127.0.0.1:3456/v1/models` returns 4 models.
|
||||||
|
|
||||||
|
Tell me each step before running it. On error, diagnose before retrying.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Client connect** — configure this device to use an existing OCP server on your LAN:
|
||||||
|
|
||||||
|
```text
|
||||||
|
There's an OCP server at <SERVER_IP> on my LAN. Configure this machine to
|
||||||
|
use it for any local IDEs (Cursor, Cline, Continue.dev, OpenCode, Claude
|
||||||
|
Code, OpenClaw).
|
||||||
|
|
||||||
|
Server IP: <SERVER_IP>
|
||||||
|
API key (leave blank if the server has anonymous mode enabled): <OPTIONAL_KEY>
|
||||||
|
|
||||||
|
Please follow https://github.com/dtzp555-max/ocp/blob/main/README.md
|
||||||
|
"Client Setup" path:
|
||||||
|
|
||||||
|
1. Download ocp-connect:
|
||||||
|
curl -fsSL https://raw.githubusercontent.com/dtzp555-max/ocp/main/ocp-connect -o ocp-connect
|
||||||
|
chmod +x ocp-connect
|
||||||
|
2. Run `./ocp-connect <SERVER_IP>` (add `--key <KEY>` if you have one).
|
||||||
|
3. Follow any IDE-specific manual hints it prints.
|
||||||
|
4. Verify: `curl http://<SERVER_IP>:3456/v1/models` returns 4 models.
|
||||||
|
5. Tell me to reload my shell + restart any IDE that was already running.
|
||||||
|
|
||||||
|
Don't auto-retry on error. Tell me the failure mode first.
|
||||||
|
```
|
||||||
|
|
||||||
|
> If you'd rather do everything manually, the **Server Setup** and **Client Setup** sections below have the same steps in handbook form.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Server Setup
|
### Server Setup
|
||||||
|
|
||||||
> **Recommended:** Install OCP on a device that stays powered on — Mac mini, NAS, Raspberry Pi, or a desktop that doesn't sleep. This ensures all clients always have access.
|
> **Recommended:** Install OCP on a device that stays powered on — Mac mini, NAS, Raspberry Pi, or a desktop that doesn't sleep. This ensures all clients always have access.
|
||||||
|
|
||||||
**Prerequisites:**
|
**Prerequisites:**
|
||||||
|
- macOS or Linux (Windows is not supported — `setup.mjs` installs launchd / systemd auto-start)
|
||||||
- Node.js 22.5+ (Node 23+ recommended — `node:sqlite` is fully stable without flags from 23.0; on 22.5–22.x it works behind `--experimental-sqlite`)
|
- Node.js 22.5+ (Node 23+ recommended — `node:sqlite` is fully stable without flags from 23.0; on 22.5–22.x it works behind `--experimental-sqlite`)
|
||||||
- [Claude CLI](https://docs.anthropic.com/en/docs/claude-cli) installed and authenticated (`claude auth login`)
|
- `git`
|
||||||
|
- [Claude CLI](https://docs.anthropic.com/en/docs/claude-cli) — install and authenticate:
|
||||||
|
```bash
|
||||||
|
npm install -g @anthropic-ai/claude-code
|
||||||
|
claude auth login # prints a URL + code — open URL on any browser, sign in, paste code back
|
||||||
|
```
|
||||||
|
Headless servers (Pi / NAS / VPS without a desktop browser): see [Headless install notes](#headless-install-notes) below.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Clone and run setup
|
# 1. Clone and run setup
|
||||||
@@ -112,7 +200,9 @@ node setup.mjs --bind 0.0.0.0 --auth-mode multi
|
|||||||
|
|
||||||
Then create API keys for each person/device:
|
Then create API keys for each person/device:
|
||||||
```bash
|
```bash
|
||||||
export OCP_ADMIN_KEY=your-secret-admin-key
|
# Generate a strong admin key (one-time — save it for later key management):
|
||||||
|
export OCP_ADMIN_KEY=$(openssl rand -base64 32)
|
||||||
|
# Add the same export line to ~/.zshrc or ~/.bashrc so it persists.
|
||||||
|
|
||||||
ocp keys add wife-laptop
|
ocp keys add wife-laptop
|
||||||
# ✓ Key created for "wife-laptop"
|
# ✓ Key created for "wife-laptop"
|
||||||
@@ -131,6 +221,22 @@ curl http://127.0.0.1:3456/v1/models
|
|||||||
# Returns: claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5-20251001
|
# Returns: claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5-20251001
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Headless install notes
|
||||||
|
|
||||||
|
OCP is designed for always-on devices that often don't have a desktop browser — Mac mini, NAS, Raspberry Pi, cloud VPS. The Claude CLI auth flow still works headless:
|
||||||
|
|
||||||
|
**Option 1 — interactive OAuth over SSH (one-shot).** `claude auth login` prints a URL + 8-digit code. Open the URL on **any** device with a browser (your laptop, phone), sign in to your Anthropic account, and paste the code back into the SSH session. No browser needed on the server itself.
|
||||||
|
|
||||||
|
**Option 2 — long-lived token (auth once, no re-prompts).**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
claude setup-token # subscription-backed long-lived token
|
||||||
|
```
|
||||||
|
|
||||||
|
Same Claude subscription as Option 1; the token is stored in Claude CLI's normal config location. Useful when you'd rather not redo the OAuth flow when sessions expire.
|
||||||
|
|
||||||
|
If `claude auth login` errors out with something like `cannot open browser`, you've hit the same case — fall back to either option above.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Uninstall
|
### Uninstall
|
||||||
@@ -147,6 +253,8 @@ Removes the launchd (macOS) or systemd (Linux) auto-start entry. Handles both le
|
|||||||
### Client Setup
|
### Client Setup
|
||||||
|
|
||||||
> Clients do **not** need to install Node.js, Claude CLI, or the OCP repo. Only `curl` and `python3` are required (pre-installed on most Linux/Mac systems).
|
> Clients do **not** need to install Node.js, Claude CLI, or the OCP repo. Only `curl` and `python3` are required (pre-installed on most Linux/Mac systems).
|
||||||
|
>
|
||||||
|
> **Find the server's LAN IP** by running `ocp lan` on the server machine — it prints both the IP and a ready-to-share connect command.
|
||||||
|
|
||||||
**One-command setup** — download the lightweight `ocp-connect` script:
|
**One-command setup** — download the lightweight `ocp-connect` script:
|
||||||
|
|
||||||
@@ -592,6 +700,37 @@ After installing the gateway plugin, use `/ocp` slash commands in your chat:
|
|||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Setup fails with "claude: command not found"
|
||||||
|
|
||||||
|
`setup.mjs` requires the Claude CLI to be on `PATH`. Install it via the [official guide](https://docs.anthropic.com/en/docs/claude-cli), confirm with `which claude`, then run `claude auth login` before re-running `node setup.mjs`.
|
||||||
|
|
||||||
|
### Setup fails with "EADDRINUSE: port 3456 already in use"
|
||||||
|
|
||||||
|
Something else is already bound to port 3456 — usually an old OCP instance. Check what:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
lsof -nP -iTCP:3456 -sTCP:LISTEN
|
||||||
|
```
|
||||||
|
|
||||||
|
If it's an old OCP process, stop it before re-running setup:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ocp stop # if the CLI is on PATH
|
||||||
|
launchctl bootout gui/$(id -u)/dev.ocp.proxy # macOS launchd fallback
|
||||||
|
sudo systemctl stop ocp-proxy # Linux systemd fallback
|
||||||
|
```
|
||||||
|
|
||||||
|
### Setup fails with "node: command not found" or version error
|
||||||
|
|
||||||
|
OCP requires Node.js 22.5+. Install:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
brew install node # macOS
|
||||||
|
# Linux: see https://nodejs.org/en/download for current install commands
|
||||||
|
```
|
||||||
|
|
||||||
|
Confirm with `node --version` (should be ≥ v22.5).
|
||||||
|
|
||||||
### Requests fail or agents stuck
|
### Requests fail or agents stuck
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -706,6 +845,24 @@ OCP runs under a small set of binding documents so contributions stay aligned wi
|
|||||||
|
|
||||||
If you want to contribute: read `ALIGNMENT.md` first, search `cli.js` for the operation you're proposing, and cite the line number in your PR.
|
If you want to contribute: read `ALIGNMENT.md` first, search `cli.js` for the operation you're proposing, and cite the line number in your PR.
|
||||||
|
|
||||||
|
## Support OCP
|
||||||
|
|
||||||
|
OCP has been **open source from day one** — not a freemium tool, not a commercial product turned open, just open. It will stay that way forever. No paid tiers, no premium features, no "Pro" version locked behind a paywall.
|
||||||
|
|
||||||
|
I built it because my family and I needed it. We use OCP every day across our own machines and IDEs — keeping one Claude Pro/Max subscription powering everything, saving the per-token API cost we'd otherwise pay. It's been quietly heartwarming to hear from users online who say OCP has saved them money the same way it saves ours. That's the whole point.
|
||||||
|
|
||||||
|
Behind every version are hundreds of hours that don't show up in commits: building it from scratch, adding new features as the Claude Code ecosystem evolves, debugging across Mac / Windows / Linux machines, validating against half a dozen IDEs (Claude Code, Cursor, Cline, OpenCode, Aider, Continue.dev, OpenClaw), tracking down `cli.js` drift, OAuth refresh edge cases, SSE streaming quirks, concurrency leaks, and the occasional incident that turns into a multi-day investigation (the [2026-04-11 alignment drift](./docs/adr/0002-alignment-constitution.md), the [v3.11.1 concurrency leak](./CHANGELOG.md), the v3.12 SSE replay regression).
|
||||||
|
|
||||||
|
**The commitment**: this project will keep being updated, keep getting new features, and will stay open source as long as I'm able to maintain it.
|
||||||
|
|
||||||
|
**Please try it.** If something breaks or could be better, [open an issue](https://github.com/dtzp555-max/ocp/issues) — feedback is genuinely what keeps the project moving.
|
||||||
|
|
||||||
|
And if OCP saves you (or your team, or your family) real money and you'd like to chip in toward the next debugging session:
|
||||||
|
|
||||||
|
- ☕ **[Buy me a coffee](https://buymeacoffee.com/dtzp555)**
|
||||||
|
|
||||||
|
Donations directly fund the time it takes to keep OCP saving the community money.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT — see [`LICENSE`](LICENSE).
|
MIT — see [`LICENSE`](LICENSE).
|
||||||
|
|||||||
@@ -8,21 +8,18 @@ set -euo pipefail
|
|||||||
|
|
||||||
PROXY="http://127.0.0.1:3456"
|
PROXY="http://127.0.0.1:3456"
|
||||||
|
|
||||||
# Auth header for multi-key mode: reads from OCP_ADMIN_KEY env or ~/.ocp/admin-key file
|
# Auth args for multi-key mode: reads from OCP_ADMIN_KEY env or ~/.ocp/admin-key file
|
||||||
_AUTH_HEADER=""
|
# Using a bash array preserves word boundaries — no eval needed.
|
||||||
|
_AUTH_ARGS=()
|
||||||
if [[ -n "${OCP_ADMIN_KEY:-}" ]]; then
|
if [[ -n "${OCP_ADMIN_KEY:-}" ]]; then
|
||||||
_AUTH_HEADER="-H \"Authorization: Bearer $OCP_ADMIN_KEY\""
|
_AUTH_ARGS=(-H "Authorization: Bearer $OCP_ADMIN_KEY")
|
||||||
elif [[ -f "$HOME/.ocp/admin-key" ]]; then
|
elif [[ -f "$HOME/.ocp/admin-key" ]]; then
|
||||||
_AUTH_HEADER="-H \"Authorization: Bearer $(cat "$HOME/.ocp/admin-key")\""
|
_AUTH_ARGS=(-H "Authorization: Bearer $(cat "$HOME/.ocp/admin-key")")
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Wrapper: curl with optional auth
|
# Wrapper: curl with optional auth
|
||||||
_curl() {
|
_curl() {
|
||||||
if [[ -n "$_AUTH_HEADER" ]]; then
|
curl "${_AUTH_ARGS[@]}" "$@"
|
||||||
eval curl "$_AUTH_HEADER" "$@"
|
|
||||||
else
|
|
||||||
curl "$@"
|
|
||||||
fi
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_json() { python3 -m json.tool 2>/dev/null || cat; }
|
_json() { python3 -m json.tool 2>/dev/null || cat; }
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
* 4. Creates start.sh for easy launch
|
* 4. Creates start.sh for easy launch
|
||||||
* 5. Optionally starts the proxy
|
* 5. Optionally starts the proxy
|
||||||
*/
|
*/
|
||||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
|
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync } from "node:fs";
|
||||||
import { execSync } from "node:child_process";
|
import { execSync } from "node:child_process";
|
||||||
import { join, dirname } from "node:path";
|
import { join, dirname } from "node:path";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
@@ -107,77 +107,82 @@ try {
|
|||||||
warn("Make sure you're logged in: claude login");
|
warn("Make sure you're logged in: claude login");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check openclaw config
|
// Check openclaw config (optional — OCP runs standalone without OpenClaw)
|
||||||
if (!existsSync(CONFIG_PATH)) fail(`OpenClaw config not found at ${CONFIG_PATH}`);
|
const OPENCLAW_PRESENT = existsSync(CONFIG_PATH);
|
||||||
log(`OpenClaw config: ${CONFIG_PATH}`);
|
if (OPENCLAW_PRESENT) {
|
||||||
|
log(`OpenClaw config: ${CONFIG_PATH}`);
|
||||||
|
} else {
|
||||||
|
warn(`OpenClaw not detected at ${CONFIG_PATH} — skipping OpenClaw integration.`);
|
||||||
|
warn(`To register OCP with OpenClaw later, install OpenClaw and re-run \`node setup.mjs\`,`);
|
||||||
|
warn(`or run \`ocp update\` if OpenClaw is installed afterward.`);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Step 2: Patch openclaw.json ─────────────────────────────────────────
|
// ── Step 2: Patch openclaw.json ─────────────────────────────────────────
|
||||||
console.log("\n📝 Configuring OpenClaw...\n");
|
if (OPENCLAW_PRESENT) {
|
||||||
|
console.log("\n📝 Configuring OpenClaw...\n");
|
||||||
|
|
||||||
const config = readJSON(CONFIG_PATH);
|
const config = readJSON(CONFIG_PATH);
|
||||||
|
|
||||||
// Ensure models.providers exists
|
// Ensure models.providers exists
|
||||||
if (!config.models) config.models = {};
|
if (!config.models) config.models = {};
|
||||||
if (!config.models.providers) config.models.providers = {};
|
if (!config.models.providers) config.models.providers = {};
|
||||||
|
|
||||||
// Add/update claude-local provider
|
// Add/update claude-local provider
|
||||||
config.models.providers[PROVIDER_NAME] = {
|
config.models.providers[PROVIDER_NAME] = {
|
||||||
baseUrl: `http://127.0.0.1:${PORT}/v1`,
|
baseUrl: `http://127.0.0.1:${PORT}/v1`,
|
||||||
api: "openai-completions",
|
api: "openai-completions",
|
||||||
authHeader: false,
|
authHeader: false,
|
||||||
models: MODELS,
|
models: MODELS,
|
||||||
};
|
};
|
||||||
log(`Provider "${PROVIDER_NAME}" → http://127.0.0.1:${PORT}/v1`);
|
log(`Provider "${PROVIDER_NAME}" → http://127.0.0.1:${PORT}/v1`);
|
||||||
|
|
||||||
// Ensure auth profile in config
|
// Ensure auth profile in config
|
||||||
if (!config.auth) config.auth = {};
|
if (!config.auth) config.auth = {};
|
||||||
if (!config.auth.profiles) config.auth.profiles = {};
|
if (!config.auth.profiles) config.auth.profiles = {};
|
||||||
config.auth.profiles[`${PROVIDER_NAME}:default`] = {
|
config.auth.profiles[`${PROVIDER_NAME}:default`] = {
|
||||||
provider: PROVIDER_NAME,
|
provider: PROVIDER_NAME,
|
||||||
mode: "api_key",
|
mode: "api_key",
|
||||||
};
|
};
|
||||||
log(`Auth profile "${PROVIDER_NAME}:default" registered`);
|
log(`Auth profile "${PROVIDER_NAME}:default" registered`);
|
||||||
|
|
||||||
// Add models to agents.defaults.models
|
// Add models to agents.defaults.models
|
||||||
if (!config.agents) config.agents = {};
|
if (!config.agents) config.agents = {};
|
||||||
if (!config.agents.defaults) config.agents.defaults = {};
|
if (!config.agents.defaults) config.agents.defaults = {};
|
||||||
if (!config.agents.defaults.models) config.agents.defaults.models = {};
|
if (!config.agents.defaults.models) config.agents.defaults.models = {};
|
||||||
for (const [key, val] of Object.entries(MODEL_ALIASES)) {
|
for (const [key, val] of Object.entries(MODEL_ALIASES)) {
|
||||||
config.agents.defaults.models[key] = val;
|
config.agents.defaults.models[key] = val;
|
||||||
}
|
}
|
||||||
log(`Model aliases added to agents.defaults.models`);
|
log(`Model aliases added to agents.defaults.models`);
|
||||||
|
|
||||||
// Set idleTimeoutSeconds to 0 — critical for Claude tool-use.
|
// Set idleTimeoutSeconds to 0 — critical for Claude tool-use.
|
||||||
// When Claude calls tools (Bash, Read, etc.), the token stream pauses for 30-120s.
|
// When Claude calls tools (Bash, Read, etc.), the token stream pauses for 30-120s.
|
||||||
// OpenClaw's default idleTimeoutSeconds (60s) kills the connection mid-tool-call,
|
// OpenClaw's default idleTimeoutSeconds (60s) kills the connection mid-tool-call,
|
||||||
// causing exit 143 (SIGTERM) and stuck sessions. Setting to 0 disables the idle timer.
|
// causing exit 143 (SIGTERM) and stuck sessions. Setting to 0 disables the idle timer.
|
||||||
if (!config.agents.defaults.llm) config.agents.defaults.llm = {};
|
if (!config.agents.defaults.llm) config.agents.defaults.llm = {};
|
||||||
if (config.agents.defaults.llm.idleTimeoutSeconds === undefined ||
|
if (config.agents.defaults.llm.idleTimeoutSeconds === undefined ||
|
||||||
config.agents.defaults.llm.idleTimeoutSeconds > 0) {
|
config.agents.defaults.llm.idleTimeoutSeconds > 0) {
|
||||||
config.agents.defaults.llm.idleTimeoutSeconds = 0;
|
config.agents.defaults.llm.idleTimeoutSeconds = 0;
|
||||||
log(`Set agents.defaults.llm.idleTimeoutSeconds = 0 (prevents tool-call timeouts)`);
|
log(`Set agents.defaults.llm.idleTimeoutSeconds = 0 (prevents tool-call timeouts)`);
|
||||||
} else {
|
} else {
|
||||||
log(`idleTimeoutSeconds already configured: ${config.agents.defaults.llm.idleTimeoutSeconds}`);
|
log(`idleTimeoutSeconds already configured: ${config.agents.defaults.llm.idleTimeoutSeconds}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
writeJSON(CONFIG_PATH, config);
|
writeJSON(CONFIG_PATH, config);
|
||||||
log(`Config saved`);
|
log(`Config saved`);
|
||||||
|
|
||||||
// ── Step 3: Patch auth-profiles.json ────────────────────────────────────
|
// ── Step 3: Patch auth-profiles.json ────────────────────────────────────
|
||||||
console.log("\n🔑 Configuring auth profiles...\n");
|
console.log("\n🔑 Configuring auth profiles...\n");
|
||||||
|
|
||||||
// Find all agent auth-profiles.json files
|
// Find all agent auth-profiles.json files
|
||||||
const agentsDir = join(OPENCLAW_DIR, "agents");
|
const agentsDir = join(OPENCLAW_DIR, "agents");
|
||||||
const agentDirs = existsSync(agentsDir)
|
const agentDirs = existsSync(agentsDir)
|
||||||
? readdirSync(agentsDir).filter((d) => {
|
? readdirSync(agentsDir).filter((d) => {
|
||||||
const ap = join(agentsDir, d, "agent", "auth-profiles.json");
|
const ap = join(agentsDir, d, "agent", "auth-profiles.json");
|
||||||
return existsSync(ap);
|
return existsSync(ap);
|
||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
import { readdirSync } from "node:fs";
|
for (const agentId of agentDirs) {
|
||||||
|
|
||||||
for (const agentId of agentDirs) {
|
|
||||||
const apPath = join(agentsDir, agentId, "agent", "auth-profiles.json");
|
const apPath = join(agentsDir, agentId, "agent", "auth-profiles.json");
|
||||||
try {
|
try {
|
||||||
const ap = readJSON(apPath);
|
const ap = readJSON(apPath);
|
||||||
@@ -203,10 +208,11 @@ for (const agentId of agentDirs) {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
warn(`Skipped agent "${agentId}": ${e.message}`);
|
warn(`Skipped agent "${agentId}": ${e.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (agentDirs.length === 0) {
|
if (agentDirs.length === 0) {
|
||||||
warn("No agent auth-profiles.json found — you may need to restart the gateway first");
|
warn("No agent auth-profiles.json found — you may need to restart the gateway first");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Step 4: Create start.sh ─────────────────────────────────────────────
|
// ── Step 4: Create start.sh ─────────────────────────────────────────────
|
||||||
@@ -238,38 +244,46 @@ if (!DRY_RUN) {
|
|||||||
log(`Launcher: ${startPath}`);
|
log(`Launcher: ${startPath}`);
|
||||||
|
|
||||||
// ── Step 5: Summary ─────────────────────────────────────────────────────
|
// ── Step 5: Summary ─────────────────────────────────────────────────────
|
||||||
console.log(`
|
const banner = [
|
||||||
╔══════════════════════════════════════════════════════════════╗
|
`╔══════════════════════════════════════════════════════════════╗`,
|
||||||
║ Setup complete! ║
|
`║ Setup complete! ║`,
|
||||||
╠══════════════════════════════════════════════════════════════╣
|
`╠══════════════════════════════════════════════════════════════╣`,
|
||||||
║ ║
|
`║ ║`,
|
||||||
║ Provider: ${PROVIDER_NAME.padEnd(44)}║
|
`║ Provider: ${PROVIDER_NAME.padEnd(44)}║`,
|
||||||
║ Port: ${String(PORT).padEnd(44)}║
|
`║ Port: ${String(PORT).padEnd(44)}║`,
|
||||||
║ Models: ${`see models.json (${MODELS.length} available)`.padEnd(44)}║
|
`║ Models: ${`see models.json (${MODELS.length} available)`.padEnd(44)}║`,
|
||||||
║ Default: ${DEFAULT_MODEL_ID.padEnd(44)}║
|
`║ Default: ${DEFAULT_MODEL_ID.padEnd(44)}║`,
|
||||||
║ ║
|
`║ ║`,
|
||||||
║ Start proxy: ║
|
`║ Start proxy: ║`,
|
||||||
║ bash ${startPath.replace(HOME, "~").padEnd(50)}║
|
`║ bash ${startPath.replace(HOME, "~").padEnd(50)}║`,
|
||||||
║ ║
|
`║ ║`,
|
||||||
║ Or directly: ║
|
`║ Or directly: ║`,
|
||||||
║ node ${serverPath.replace(HOME, "~").padEnd(49)}║
|
`║ node ${serverPath.replace(HOME, "~").padEnd(49)}║`,
|
||||||
║ ║
|
`║ ║`,
|
||||||
║ Set as default model in openclaw.json: ║
|
];
|
||||||
║ agents.defaults.model.primary = ║
|
if (OPENCLAW_PRESENT) {
|
||||||
║ "${PROVIDER_NAME}/${DEFAULT_MODEL_ID}"${" ".repeat(Math.max(0, 30 - PROVIDER_NAME.length - DEFAULT_MODEL_ID.length))}║
|
banner.push(
|
||||||
║ ║
|
`║ Set as default model in openclaw.json: ║`,
|
||||||
║ Then restart gateway: ║
|
`║ agents.defaults.model.primary = ║`,
|
||||||
║ openclaw gateway restart ║
|
`║ "${PROVIDER_NAME}/${DEFAULT_MODEL_ID}"${" ".repeat(Math.max(0, 30 - PROVIDER_NAME.length - DEFAULT_MODEL_ID.length))}║`,
|
||||||
║ ║
|
`║ ║`,
|
||||||
╚══════════════════════════════════════════════════════════════╝
|
`║ Then restart gateway: ║`,
|
||||||
`);
|
`║ openclaw gateway restart ║`,
|
||||||
|
`║ ║`,
|
||||||
// ── Step 6: Optionally start ────────────────────────────────────────────
|
);
|
||||||
if (!SKIP_START && !DRY_RUN) {
|
} else {
|
||||||
try {
|
banner.push(
|
||||||
execSync(`bash "${startPath}"`, { stdio: "inherit" });
|
`║ OpenClaw not detected — running in standalone mode. ║`,
|
||||||
} catch { /* ignore */ }
|
`║ Point your IDE (Cline / Cursor / Continue / OpenCode / ║`,
|
||||||
|
`║ Aider / OpenClaw) at: ║`,
|
||||||
|
`║ http://${BIND_ADDRESS}:${String(PORT)}/v1${" ".repeat(Math.max(0, 47 - BIND_ADDRESS.length - String(PORT).length))}║`,
|
||||||
|
`║ ║`,
|
||||||
|
`║ See README § "Client Setup" for per-IDE instructions. ║`,
|
||||||
|
`║ ║`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
banner.push(`╚══════════════════════════════════════════════════════════════╝`);
|
||||||
|
console.log("\n" + banner.join("\n") + "\n");
|
||||||
|
|
||||||
// ── Step 7: Install auto-start on boot ──────────────────────────────────
|
// ── Step 7: Install auto-start on boot ──────────────────────────────────
|
||||||
if (!DRY_RUN) {
|
if (!DRY_RUN) {
|
||||||
@@ -405,4 +419,52 @@ WantedBy=default.target
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log("\n✅ Auto-start installed — proxy will start automatically on login\n");
|
console.log("\n✅ Auto-start installed — proxy will start automatically on login\n");
|
||||||
|
|
||||||
|
// ── Step 8: Post-install health verification ───────────────────────────
|
||||||
|
if (!SKIP_START) {
|
||||||
|
console.log("⏳ Waiting for server to bind...\n");
|
||||||
|
await new Promise(r => setTimeout(r, 3000));
|
||||||
|
|
||||||
|
const healthUrl = `http://127.0.0.1:${PORT}/health`;
|
||||||
|
let verified = false;
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(), 5000);
|
||||||
|
const res = await fetch(healthUrl, { signal: controller.signal });
|
||||||
|
clearTimeout(timer);
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
console.log(` ✓ Health check passed (${healthUrl})`);
|
||||||
|
console.log(` version: ${body.version ?? "unknown"}`);
|
||||||
|
console.log(` authMode: ${body.authMode ?? "unknown"}`);
|
||||||
|
|
||||||
|
// Verify bind socket
|
||||||
|
try {
|
||||||
|
const bindCheck = process.platform === "linux"
|
||||||
|
? execSync(`ss -tlnp 2>/dev/null | grep ':${PORT}'`, { encoding: "utf-8" }).trim()
|
||||||
|
: execSync(`lsof -nP -iTCP:${PORT} -sTCP:LISTEN 2>/dev/null`, { encoding: "utf-8" }).trim();
|
||||||
|
if (bindCheck) {
|
||||||
|
console.log(` bind: ${bindCheck.split("\n")[0]}`);
|
||||||
|
}
|
||||||
|
} catch { /* bind check is best-effort */ }
|
||||||
|
|
||||||
|
verified = true;
|
||||||
|
} else {
|
||||||
|
warn(`Health check returned HTTP ${res.status} — service may not have started cleanly`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
const isTimeout = e.name === "AbortError" || (e.cause && e.cause.code === "UND_ERR_CONNECT_TIMEOUT");
|
||||||
|
warn(`Health check failed: ${isTimeout ? "timeout (5s)" : e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!verified) {
|
||||||
|
const logHint = process.platform === "linux"
|
||||||
|
? "journalctl --user -u ocp-proxy -n 50"
|
||||||
|
: `tail -n 100 ~/.ocp/logs/proxy.log`;
|
||||||
|
console.error(`\n ✗ Server did not respond on port ${PORT} within 5 seconds.`);
|
||||||
|
console.error(` Check service logs:\n ${logHint}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user