mirror of
https://github.com/dtzp555-max/ocp.git
synced 2026-07-21 21:15:09 +00:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d64cd3158 | ||
|
|
70faeff067 | ||
|
|
7a69d72886 | ||
|
|
a8601a6d30 | ||
|
|
cd6ec2a212 | ||
|
|
ab03c13332 | ||
|
|
55c576bbb1 | ||
|
|
750b25ba77 | ||
|
|
fd6e875bd7 | ||
|
|
8c0b97f3ae | ||
|
|
68acf15373 | ||
|
|
a71c939bf8 | ||
|
|
d245c62df7 | ||
|
|
047750e642 | ||
|
|
3bdeb50ed5 | ||
|
|
fbbf3b6c7c | ||
|
|
d760d7fcce | ||
|
|
5e2effd05b | ||
|
|
fb2d1d3feb | ||
|
|
12b09c236e | ||
|
|
c0f2d3ab20 | ||
|
|
0d61da5153 | ||
|
|
49baffe2da | ||
|
|
4b01d4e768 | ||
|
|
36fa81d1e6 | ||
|
|
cce0110253 | ||
|
|
40391791a1 | ||
|
|
342a0a44f5 | ||
|
|
9494fd6c69 | ||
|
|
5ff30ac9b6 | ||
|
|
16eeb66557 | ||
|
|
c998d21a4f | ||
|
|
5be369ed68 | ||
|
|
3d52ffc152 | ||
|
|
68b0838074 | ||
|
|
313cb13a78 | ||
|
|
e4b010af5e | ||
|
|
0752f666fb | ||
|
|
ae4a829904 | ||
|
|
51e908e145 | ||
|
|
d99534dc35 | ||
|
|
39ca20536e | ||
|
|
8b3f50912e | ||
|
|
780462c763 |
@@ -1,8 +0,0 @@
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
node_modules
|
||||
.env
|
||||
.env.*
|
||||
scripts/
|
||||
start.sh
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,32 @@
|
||||
name: gitleaks
|
||||
|
||||
# Secret scanning gate. Runs on every PR (any branch) and every push to main.
|
||||
# Configuration is read from the repo-root `.gitleaks.toml` automatically.
|
||||
# Hard-fails the build on any detected leak — public repo, no tolerance.
|
||||
#
|
||||
# To extend the allowlist (e.g. a new known-safe placeholder), edit
|
||||
# `.gitleaks.toml`. Do not add `continue-on-error` here without an explicit
|
||||
# governance decision.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
scan:
|
||||
name: gitleaks scan (hard fail)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout (full history)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Run gitleaks
|
||||
uses: gitleaks/gitleaks-action@v2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test-features:
|
||||
name: test-features.mjs (smoke)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# `test-features.mjs` is self-contained — it runs assertions against the
|
||||
# `keys.mjs` DB layer using a throwaway test database. It does NOT need a
|
||||
# live claude CLI or a running OCP server. So this job runs as a hard
|
||||
# check on every push / PR.
|
||||
#
|
||||
# If a future expansion of the suite adds tests that DO require a live
|
||||
# claude CLI or a running OCP server, mark those steps `continue-on-error:
|
||||
# true` (or split them into a separate job) — CI must not be flaky on
|
||||
# things outside the contributor's machine.
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
# Node 24 ships `node:sqlite` as stable. The test imports keys.mjs,
|
||||
# which uses `import { DatabaseSync } from "node:sqlite"`.
|
||||
# Node 22 also works with `--experimental-sqlite`, but we run on 24
|
||||
# to keep the CI step simple and to match what released OCP runs on.
|
||||
node-version: '24'
|
||||
|
||||
# OCP has zero runtime npm dependencies (package-lock.json shows only
|
||||
# the project's own package and zero external entries). No install
|
||||
# step needed — `node:*` modules are built into Node 24.
|
||||
|
||||
- name: Run test-features.mjs
|
||||
run: npm test
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Runtime artifacts
|
||||
logs/
|
||||
*.log
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# Editor / OS scratch
|
||||
.DS_Store
|
||||
*.swp
|
||||
*~
|
||||
@@ -22,7 +22,7 @@ Runtime: Node.js (ESM, `.mjs` throughout). No build step. No bundler. `server.mj
|
||||
- `models.json` as the single source of truth for model metadata
|
||||
- GitHub Actions for CI (`alignment.yml`, `release.yml`)
|
||||
- `gh` CLI assumed for PR creation and release automation
|
||||
- No TypeScript. No test framework beyond `test-features.mjs`. Keep dependencies minimal.
|
||||
- No TypeScript. No test framework beyond `test-features.mjs` (run via `npm test`; CI workflow `.github/workflows/test.yml`). Keep dependencies minimal.
|
||||
|
||||
---
|
||||
|
||||
@@ -36,14 +36,16 @@ Runtime: Node.js (ESM, `.mjs` throughout). No build step. No bundler. `server.mj
|
||||
- `ALIGNMENT.md` — the constitution. Binding for any `server.mjs` change. See ADR 0002.
|
||||
- `.github/workflows/alignment.yml` — CI blacklist grep; fails the build on known-hallucinated tokens.
|
||||
- `CLAUDE.md` — Claude-Code-specific session instructions + release_kit overlay (Iron Rule 5.5).
|
||||
- `docs/adr/` — Architecture Decision Records. Read these before proposing governance or SPOT changes.
|
||||
- `docs/adr/` — Architecture Decision Records. Read these before proposing governance or SPOT changes. See `docs/adr/README.md` for the index.
|
||||
- `docs/superpowers/plans/` — active spec-kit plans. `docs/superpowers/plans/shipped/` archives plans that have been delivered (don't propose changes against shipped plans — they're history). `docs/superpowers/specs/` holds long-lived design documents that other code references (e.g., the SSE heartbeat design referenced from `server.mjs`).
|
||||
- `memory/constitution.md` — spec-kit's project constitution (its standard `memory/` location). Distinct from `~/.cc-rules/memory/` (cross-machine personal memory) and from this repo's `ALIGNMENT.md` (the OCP code-level constitution).
|
||||
|
||||
---
|
||||
|
||||
## Project-specific constraints
|
||||
|
||||
- **`ALIGNMENT.md` is binding.** Any PR touching `server.mjs` must cite `cli.js:NNNN` (or `cli.js vE4 <functionName>`) in the commit body and PR description. See `CLAUDE.md` § "Hard requirements for `server.mjs` changes" and ADR 0002.
|
||||
- **Alignment CI is not suppressible.** The `alignment.yml` workflow greps `server.mjs` for known-hallucinated tokens (including `api/oauth/usage`, `api/usage`). Adding to the blacklist is fine; removing entries requires an `ALIGNMENT.md` amendment PR.
|
||||
- **Alignment CI is not suppressible.** The `alignment.yml` workflow greps `server.mjs` for known-hallucinated tokens (currently blocking `api.anthropic.com/api/oauth/usage`). Adding new tokens is done via PR amendment to `alignment.yml`; removing entries requires an `ALIGNMENT.md` amendment PR.
|
||||
- **No self-approval.** Implementation author cannot merge their own PR (Iron Rule 10). A fresh-context reviewer must open `cli.js` at the cited lines and confirm in the review comment.
|
||||
- **`models.json` is the only place to add/edit models.** Do not touch `MODEL_MAP` or `MODELS` arrays directly in `server.mjs` or `setup.mjs`. See ADR 0003.
|
||||
- **OpenClaw boundary.** `scripts/sync-openclaw.mjs` only writes `models.providers["claude-local"].models` and `agents.defaults.models["claude-local/*"]` in `~/.openclaw/openclaw.json`. Do not expand scope. See ADR 0004.
|
||||
@@ -66,7 +68,7 @@ A fresh session picking up OCP work should read, in order:
|
||||
2. `ALIGNMENT.md` — constitution; non-optional.
|
||||
3. `CLAUDE.md` — tool-specific instructions and release_kit overlay.
|
||||
4. `docs/adr/` — most recent ADRs first; they explain why the current structure exists.
|
||||
5. Any active spec under `docs/superpowers/specs/*/tasks.md` (if present).
|
||||
5. Any active plan under `docs/superpowers/plans/` (excluding `shipped/` which is the archive).
|
||||
6. `~/.cc-rules/memory/auto/MEMORY.md` — cross-machine memory index.
|
||||
|
||||
Only after these should the session touch code.
|
||||
|
||||
+143
-1
@@ -1,6 +1,148 @@
|
||||
# Changelog
|
||||
|
||||
## v3.12.0 (2026-04-25)
|
||||
## v3.16.2 — 2026-05-12
|
||||
|
||||
### Fixes — corrects v3.16.1
|
||||
|
||||
The v3.16.1 fix was directionally correct (plugin now reads env first, falls back to a hardcoded default) but **the narrative and the hardcoded default were both wrong**.
|
||||
|
||||
What v3.16.1 said: "OCP server moved to 3478 default in v3.14+; plugin lagged at 3456."
|
||||
What is actually true:
|
||||
- **OCP server source default has been `3456` since `593d0dc` (initial release) and has never changed.** Every line in `server.mjs`, `setup.mjs`, and the `ocp` CLI still uses `3456` as the documented and code-level default.
|
||||
- The single OCP installation observed on `3478` is the maintainer's Mac mini, whose plist was rewritten with `--port 3478` during a PR #71 dogfood smoke-test accident on 2026-05-08 (see `~/.cc-rules/memory/learnings/subagent_setup_mjs_prod_host_collision.md`). The plist drift was never reconciled back to source default, and v3.16.1 incorrectly canonised the post-accident value as if it had been a release decision.
|
||||
|
||||
This release:
|
||||
- Restores the plugin fallback to `http://127.0.0.1:3456` to match server source default.
|
||||
- Updates `openclaw.plugin.json` `configSchema.proxyUrl.default` back to `3456`.
|
||||
- Restores README §"Environment Variables" `CLAUDE_PROXY_PORT` default to `3456`.
|
||||
- Plugin reads `OCP_PROXY_URL` env (full URL) first, then `CLAUDE_PROXY_PORT` env (port only), then falls back to `3456`. Hosts whose OCP plist injects a non-default port must also inject the same `CLAUDE_PROXY_PORT` into the OpenClaw plist for the plugin to follow.
|
||||
- Maintainer's Mac mini plist was reverted from `3478` to `3456` as part of this release deploy (no source change reflects this; it was a one-host correction).
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
|
||||
## v3.16.1 — 2026-05-12 (superseded — narrative incorrect; see v3.16.2 erratum)
|
||||
|
||||
### Fixes (as shipped — note erratum above)
|
||||
|
||||
- **OCP plugin port lag** — `ocp-plugin/index.js` hard-coded `http://127.0.0.1:3456`. ~~While OCP server moved to 3478 in v3.14+,~~ **(corrected v3.16.2: no such move ever happened.)** The Mac mini's plist was on `3478` only as residue from a dogfood accident. Result: `/ocp` slash commands from the home Telegram bot returned "OCP error: fetch failed". v3.16.1 changed the plugin default to `3478` (wrong direction; v3.16.2 reverts to `3456`).
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
|
||||
## v3.16.0 — 2026-05-10
|
||||
|
||||
### Features
|
||||
|
||||
- **`ocp doctor --check oauth`** (PR #93) — fast path that runs only the OAuth check, skipping
|
||||
version detection / from-version / git operations / models endpoint. ~50ms vs. full doctor's
|
||||
~200-500ms. Use cases: AI agent repair loops, post-`claude auth login` verify, quick health
|
||||
gates. Help text in `cmd_doctor_help` now reflects working behaviour.
|
||||
- **`ocp update --rollback --gc`** — manually garbage-collect old upgrade snapshots.
|
||||
Retention policy: keep last 5 snapshots OR snapshots newer than 30 days OR the single most
|
||||
recent (always-keep safety net). `--dry-run` previews. Successful `ocp update` runs auto-GC
|
||||
at the end of the full path; light path does not (no snapshot created there).
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- After a successful cross-minor `ocp update`, the auto-GC emits `[gc] removed N old snapshots`
|
||||
to stderr if any were collected. Safe to ignore; manual gc is `ocp update --rollback --gc`.
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
- PR #93 (--check oauth) merged separately; this release bundles it with the GC feature.
|
||||
|
||||
## v3.15.1 — 2026-05-10
|
||||
|
||||
### Fixes
|
||||
|
||||
- **doctor: dynamic `latest_version` from `origin/main:package.json`** — v3.15.0 doctor used a hard-coded `latest = "v3.14.0"` fallback, which made any v3.15.0+ install report `kind = upgrade` (against a stale value). `ocp update` would then attempt `git checkout v3.14.0` — a downgrade. Doctor now fetches `git -C ~/ocp show origin/main:package.json` to determine the actual latest version; on failure (offline, fresh clone with no remote), falls back to `currentVersion` so `kind = noop` instead of recommending a downgrade.
|
||||
|
||||
## v3.15.0 — 2026-05-10
|
||||
|
||||
### Features
|
||||
|
||||
- **`ocp doctor`** — health & upgrade-readiness check; primary entry for AI-driven debugging.
|
||||
`--json` mode emits a `next_action` with `ai_executable[]` for agents to run verbatim
|
||||
and `human_required[]` for steps requiring the user (typically only OAuth).
|
||||
- **`ocp update` cross-version path** — for cross-minor jumps (e.g. v3.10 → v3.14),
|
||||
`ocp update` now runs doctor → snapshot → `setup.mjs` (with the plist env-merge from
|
||||
PR #90) → service restart → post-flight `/health` + `/v1/models` verification.
|
||||
Same-patch updates retain the existing light path; users see no change for routine
|
||||
patch bumps.
|
||||
- **`ocp update --rollback`** — restore the most recent (or specified) upgrade snapshot.
|
||||
Snapshots are saved to `~/.ocp/upgrade-snapshot-<ISO-ts>/` and never auto-deleted.
|
||||
- **Fresh-install routing** — `ocp update` on installations < v3.4.0 routes to a fresh-install
|
||||
flow (with `--yes` to skip confirmation; AI agents pass this). OAuth survives via Claude
|
||||
Code's credential store; users do not re-OAuth unless their token was independently broken.
|
||||
- **AI prompt blocks in README** — §Installation, §Upgrading, and §Troubleshooting each
|
||||
start with a copy-paste prompt for Claude Code / Cursor / Copilot, so users can drive
|
||||
install / setup / upgrade through their existing AI assistant.
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- `ocp update` may take 10–30s longer when a cross-minor jump triggers the full path
|
||||
(snapshot + post-flight). Patch bumps are unchanged.
|
||||
- Pre-v3.4.0 installs are routed to fresh-install rather than failing silently or
|
||||
half-migrating.
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
- Depends on PR #90 (plist env merge bug fix; merged before this release).
|
||||
|
||||
## v3.14.0 — 2026-05-10
|
||||
|
||||
### Features (security hardening)
|
||||
|
||||
- **Per-key session isolation** (PR #86, S1) — the `sessions` Map in `server.mjs` is now keyed by `${keyName}|${conversationId}` instead of bare `conversationId`. Before this fix, two clients using distinct API keys but the same `session_id` value (e.g. both defaulting to `"default"`) would share the same `cli.js` subprocess and conversation history, creating a cross-tenant leak path. Post-fix each (key, session) pair is isolated end-to-end, extending the per-key cache isolation shipped in v3.13.0 D1 to the session layer.
|
||||
- **On-disk credential file modes 0700/0600** (PR #87, S2) — `setup.mjs` now creates `~/.ocp` at mode 0700 and both `admin-key` and `ocp.db` at mode 0600. An idempotent `reconcileFileModes()` call in `server.mjs` startup tightens any existing installation to these modes automatically on every launch, so existing prod boxes fix themselves without manual `chmod`. Before this fix, all three files were created at the process's default umask (typically world-readable 0644 / 0755), leaving plaintext credentials readable by other local users.
|
||||
- **`/api/usage` default scope = self; admin all-keys requires `?all=true`** (PR #88, S3) — the usage endpoint now applies a least-privilege default: anonymous callers receive only their own rows, non-admin authenticated callers receive only their own rows, and admin callers receive only their own rows unless they explicitly pass `?all=true`. When `?all=true` is used, an audit log line is emitted. Before this fix, any admin-token holder could silently enumerate usage data for every key on the server.
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- **Breaking change for admin tooling**: `/api/usage` no longer returns all-keys data by default. Existing cron jobs, dashboards, or scripts that rely on the admin token seeing all-keys output must add `?all=true` to their request URL after upgrading to v3.14.0.
|
||||
- **File mode reconcile at server startup** logs a one-line notice per path when mode is tightened (e.g. `[security] tightened ~/.ocp/ocp.db → 0600`). No action is required from the operator; the reconcile is idempotent and silent when modes are already correct.
|
||||
- **`sessions` Map key is now `${keyName}|${conversationId}` internally.** No client-visible wire change — the `session_id` field in request/response is unchanged.
|
||||
|
||||
### Verification
|
||||
|
||||
- Stress-test pass: 11/11 phases including S1/S2/S3 security regression checks (Phase E, I, J). 35-minute sustained run, 60 calls, 0 errors, 0 timeouts. RSS dropped 51→47 MB across the window. Per-key cache isolation, singleflight, cache_control bypass, quota enforcement, file-mode reconcile, and scope guard against escalation all verified against running code.
|
||||
|
||||
### Governance
|
||||
|
||||
- All three PRs (#86, #87, #88) include the explicit `cli.js`-citation-not-applicable disclaimer (per PR #75 pattern) since they are OCP-internal access-control, session-state, and file-permission changes with no corresponding `cli.js` operation to cite.
|
||||
|
||||
### No new env vars / no public API surface change beyond the documented breaking change
|
||||
|
||||
This release adds no new env vars or endpoints. The only externally visible change is the `/api/usage` scope guard (breaking for admin all-keys consumers; see Behavior changes above).
|
||||
|
||||
## v3.13.0 — 2026-05-07
|
||||
|
||||
### Features (cache layer hardening)
|
||||
|
||||
- **Per-key cache isolation** (D1) — the cache key now includes the API key id, so distinct keys never share cache entries. Anonymous/unauthenticated callers share one `anon` pool. Hash format upgraded to `v2`; legacy v1-format rows orphan and are reaped by the existing TTL cleanup interval (no migration script).
|
||||
- **`cache_control` bypass** (D2) — when a request carries an Anthropic `cache_control` annotation (top-level or nested in a content array), OCP skips its own cache entirely. The caller is using Anthropic-side prompt caching deliberately, and OCP must not interfere. A `cache_skipped{reason: cache_control_present}` log line is emitted on bypass.
|
||||
- **Chunked stream replay** (D3) — when a streaming request hits the cache, the cached content is now emitted as multiple SSE chunks (80 codepoints/chunk, codepoint-safe via `Array.from()`) instead of a single large delta. Multibyte characters (CJK / emoji) stay intact.
|
||||
- **Singleflight stampede protection** (D4) — concurrent identical cache-miss requests now share one upstream `cli.js` spawn instead of spawning N processes. Followers receive byte-identical responses to what the leader returns. All-or-nothing failure semantics: if the leader errors, all followers receive the same error. Streaming-path singleflight is explicitly out of scope (TODO left for follow-up).
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- `/cache/stats` response now includes additive fields `inflight` and `requesters` (current in-flight singleflight entries and total waiting callers). Existing fields `entries`, `totalHits`, `sizeBytes` are preserved unchanged.
|
||||
|
||||
### Governance
|
||||
|
||||
- New ADR [`docs/adr/0005-no-multi-provider.md`](docs/adr/0005-no-multi-provider.md): OCP stays single-provider (Anthropic via `cli.js` spawn). Multi-provider gateway refactor explicitly out of scope; cache improvements are explicitly in scope.
|
||||
- Design spec for this release: [`docs/superpowers/specs/2026-05-07-cache-upgrade-design.md`](docs/superpowers/specs/2026-05-07-cache-upgrade-design.md).
|
||||
|
||||
### No new env vars / no public API surface change
|
||||
|
||||
This release adds no new env vars or endpoints. All four improvements are internal correctness/concurrency upgrades to the existing `CLAUDE_CACHE_TTL`-gated cache layer. No client-observable wire shape change.
|
||||
|
||||
## v3.12.0 — 2026-04-25
|
||||
|
||||
### Features
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
Every PR that modifies `server.mjs` must satisfy all three of the following. A PR missing any one of them is blocked from merge.
|
||||
|
||||
1. **`cli.js` citation.** The commit message and PR body declare the corresponding `cli.js` function name and line number range, using the format `cli.js:NNNN` or `cli.js vE4 <functionName>`. If `cli.js` does not perform the operation, the PR must state this explicitly and justify scope under `ALIGNMENT.md` Rule 2 (in practice, this almost always means the PR should be closed).
|
||||
2. **CI blacklist pass.** The `alignment.yml` workflow must pass. The workflow greps `server.mjs` for known-hallucinated tokens (including `api/oauth/usage` and `api/usage`) and fails the build on any hit. Do not suppress the workflow. Do not add allowlist entries without an amendment PR to `ALIGNMENT.md`.
|
||||
2. **CI blacklist pass.** The `alignment.yml` workflow must pass. The workflow greps `server.mjs` for known-hallucinated tokens (currently blocking `api.anthropic.com/api/oauth/usage`) and fails the build on any hit. New tokens are added via PR amendment to `alignment.yml`; removing entries requires an `ALIGNMENT.md` amendment PR. Do not suppress the workflow.
|
||||
3. **Independent reviewer (Iron Rule 10).** The implementation author may not self-approve. A separate reviewer — human or a subagent spawned with a fresh context — must read the diff, verify the `cli.js` citation by opening `cli.js` at the cited lines, and explicitly approve. A review comment that does not confirm the `cli.js` citation was checked is not a valid approval.
|
||||
|
||||
---
|
||||
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY server.mjs ./
|
||||
COPY setup.mjs ./
|
||||
COPY package.json ./
|
||||
|
||||
ENV CLAUDE_SESSION_TOKEN="" \
|
||||
CLAUDE_COOKIES=""
|
||||
|
||||
EXPOSE 3456
|
||||
|
||||
CMD ["node", "server.mjs"]
|
||||
@@ -1,7 +1,13 @@
|
||||
# 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.**
|
||||
|
||||
*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).*
|
||||
|
||||
*If OCP saves you a setup, a ⭐ helps other folks discover it. Issue reports are even more useful — that's the highest-quality feedback this project gets.*
|
||||
|
||||
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.
|
||||
|
||||
```
|
||||
@@ -14,6 +20,38 @@ OpenClaw ───┘
|
||||
|
||||
One proxy. Multiple IDEs. All models. **$0 API cost.**
|
||||
|
||||
## 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.** What you get:
|
||||
|
||||
- **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.
|
||||
- **`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.
|
||||
- **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))
|
||||
- **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))
|
||||
- **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))
|
||||
- **`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
|
||||
|
||||
OCP and the alternatives serve adjacent but distinct needs. Pick the one that fits your use case:
|
||||
|
||||
| Feature | OCP | claude-code-router | anthropic-proxy |
|
||||
|---|---|---|---|
|
||||
| Forwards Claude Code subscription as OpenAI API | yes | yes | yes |
|
||||
| Routes to multiple model backends (OpenAI, Gemini, etc.) | no | yes | partial |
|
||||
| SSE heartbeat for long reasoning | yes (opt-in) | no | no |
|
||||
| Per-key quota + LAN multi-user keys | yes | no | no |
|
||||
| Response cache | yes (opt-in) | no | no |
|
||||
| OpenClaw / IDE auto-config | yes | no | no |
|
||||
| Model-routing rules / model-switching | no | yes | no |
|
||||
| GitHub stars / ecosystem size | small | large | mid |
|
||||
| Governance discipline (CI-enforced alignment with cli.js) | yes | n/a | n/a |
|
||||
|
||||
**Plain English**: `claude-code-router` is the routing-and-switching power tool — pick it if you want to mix Anthropic, OpenAI, Gemini, and local models behind one endpoint. `anthropic-proxy` is the minimal forwarder. **OCP focuses on disciplined `cli.js`-aligned forwarding plus subscription multiplexing** — pick it if you want to share one Claude Pro/Max subscription across IDEs, devices, and people, with LAN auth, quotas, and a governance contract that prevents endpoint drift.
|
||||
|
||||
OCP is single-maintainer + LLM-assisted, currently pre-1.0. It runs the maintainer's daily Claude Code workflow. If something breaks, [open an issue](https://github.com/dtzp555-max/ocp/issues).
|
||||
|
||||
## Supported Tools
|
||||
|
||||
Any tool that accepts `OPENAI_BASE_URL` works with OCP:
|
||||
@@ -24,11 +62,27 @@ Any tool that accepts `OPENAI_BASE_URL` works with OCP:
|
||||
| **OpenCode** | `OPENAI_BASE_URL=http://127.0.0.1:3456/v1` |
|
||||
| **Aider** | `aider --openai-api-base http://127.0.0.1:3456/v1` |
|
||||
| **Continue.dev** | config.json → `apiBase: "http://127.0.0.1:3456/v1"` |
|
||||
| **OpenClaw** | `setup.mjs` auto-configures |
|
||||
| **OpenClaw** [^openclaw] | `setup.mjs` auto-configures |
|
||||
| **Any OpenAI client** | Set base URL to `http://127.0.0.1:3456/v1` |
|
||||
|
||||
[^openclaw]: **OpenClaw** is an IDE-agnostic AI coding agent (sibling project to OCP). When OCP runs on the same machine, OpenClaw can use it as a local provider — see `scripts/sync-openclaw.mjs` and ADR 0004.
|
||||
|
||||
## Installation
|
||||
|
||||
The simplest path: ask your AI.
|
||||
|
||||
Paste this prompt to Claude Code / Cursor / Copilot:
|
||||
|
||||
```
|
||||
Install OCP for me. Read README §Manual Installation and follow it.
|
||||
Tell me when I need to run `claude auth login`.
|
||||
```
|
||||
|
||||
The AI will run `git clone`, `npm install`, `node setup.mjs`, and tell you
|
||||
when to OAuth.
|
||||
|
||||
### Manual Installation
|
||||
|
||||
OCP has two roles: **Server** (runs the proxy, needs Claude CLI) and **Client** (connects to a server, zero dependencies).
|
||||
|
||||
```
|
||||
@@ -45,13 +99,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
|
||||
|
||||
> **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:**
|
||||
- Node.js 18+
|
||||
- [Claude CLI](https://docs.anthropic.com/en/docs/claude-cli) installed and authenticated (`claude auth login`)
|
||||
- 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`)
|
||||
- `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
|
||||
# 1. Clone and run setup
|
||||
@@ -64,7 +201,8 @@ The setup script will:
|
||||
1. Verify Claude CLI is installed and authenticated
|
||||
2. Start the proxy on port 3456
|
||||
3. Install auto-start (launchd on macOS, systemd on Linux)
|
||||
4. Symlink `ocp` to `/usr/local/bin` for CLI access
|
||||
|
||||
After install the `ocp` CLI lives at `~/ocp/ocp`. To put it on your PATH, either symlink it manually (`ln -sf ~/ocp/ocp ~/.local/bin/ocp` if `~/.local/bin` is on your PATH, or `sudo ln -sf ~/ocp/ocp /usr/local/bin/ocp` for a system-wide symlink) or add an alias (`alias ocp=~/ocp/ocp`). Otherwise invoke it as `~/ocp/ocp <subcommand>`. The rest of this README assumes `ocp` is on your PATH.
|
||||
|
||||
**Single-machine use** — just set your IDE to use the proxy:
|
||||
```bash
|
||||
@@ -79,7 +217,9 @@ node setup.mjs --bind 0.0.0.0 --auth-mode multi
|
||||
|
||||
Then create API keys for each person/device:
|
||||
```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
|
||||
# ✓ Key created for "wife-laptop"
|
||||
@@ -98,11 +238,40 @@ 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
|
||||
```
|
||||
|
||||
#### 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
|
||||
|
||||
```bash
|
||||
# From the cloned repo
|
||||
node uninstall.mjs
|
||||
```
|
||||
|
||||
Removes the launchd (macOS) or systemd (Linux) auto-start entry. Handles both legacy (`ai.openclaw.proxy` / `openclaw-proxy`) and current (`dev.ocp.proxy` / `ocp-proxy`) service names. Does not delete `~/.openclaw/`, `~/.ocp/`, or the cloned repo — remove those manually if desired.
|
||||
|
||||
---
|
||||
|
||||
### 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).
|
||||
>
|
||||
> **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:
|
||||
|
||||
@@ -237,17 +406,23 @@ ocp keys revoke son-ipad # Revoke a key
|
||||
| `shared` | `CLAUDE_AUTH_MODE=shared` + `PROXY_API_KEY=xxx` | Everyone shares one key |
|
||||
| `multi` | `CLAUDE_AUTH_MODE=multi` + `OCP_ADMIN_KEY=xxx` | Per-person keys with usage tracking (recommended) |
|
||||
|
||||
> **Usage scope (v3.14.0+):** `/api/usage` returns the caller's own rows by default. Admin callers must pass `?all=true` to retrieve data for all keys; doing so emits an audit log line.
|
||||
|
||||
### Anonymous Access (optional)
|
||||
|
||||
In `multi` mode, the admin can designate a single well-known "anonymous" key that bypasses `validateKey()` and grants public read/write access. This is useful for letting LAN users (or clients like OpenClaw multi-agent setups) connect without individual per-user keys.
|
||||
|
||||
**Enable**:
|
||||
|
||||
The anonymous key is wired into the service unit (launchd plist on macOS, systemd unit on Linux) at install time. Export `PROXY_ANONYMOUS_KEY` in your shell before running `setup.mjs`, and `setup.mjs` will write it into the service unit env so the auto-started proxy picks it up:
|
||||
|
||||
```bash
|
||||
export PROXY_ANONYMOUS_KEY=ocp_public_anon # or any string of your choice
|
||||
ocp start # or however you start the server
|
||||
node setup.mjs --bind 0.0.0.0 --auth-mode multi
|
||||
```
|
||||
|
||||
If OCP is already installed without it, re-export the env var and re-run `node setup.mjs` (the installer is idempotent — it refreshes the service unit). Then `ocp restart` so the running proxy picks up the new env. Setting `PROXY_ANONYMOUS_KEY` only in your interactive shell **does not** affect the auto-started proxy — the service unit is the source of truth for its environment.
|
||||
|
||||
**Client side**: the anonymous key value is exposed via `GET /health` as the field `anonymousKey` (null when not set). Clients like `ocp-connect` can auto-discover and use it, so the end user doesn't need to get a personal key from the admin.
|
||||
|
||||
**Security note**: setting this env var is an **opt-in** to public access — anyone who can reach your OCP endpoint can use it, up to any rate limits you configure. Don't enable this on internet-exposed OCP instances without additional protection.
|
||||
@@ -301,6 +476,7 @@ When a key exceeds its quota, OCP returns HTTP 429 with a structured error:
|
||||
- Keys are stored in `~/.ocp/ocp.db` (SQLite, zero external dependencies)
|
||||
- Admin key is required for key management API endpoints
|
||||
- The dashboard (`/dashboard`) and health check (`/health`) are always public
|
||||
- File modes for `~/.ocp` (0700), `admin-key` + `ocp.db` (0600) are auto-tightened at server startup as of v3.14.0
|
||||
|
||||
## Built-in Usage Monitoring
|
||||
|
||||
@@ -339,6 +515,7 @@ ocp keys List all API keys (multi mode)
|
||||
ocp keys add <name> Create a new API key
|
||||
ocp keys revoke <name> Revoke an API key
|
||||
ocp connect <ip> One-command LAN client setup
|
||||
ocp doctor Health & upgrade-readiness check; primary entry for AI-driven debugging. --json produces a next_action for AI agents.
|
||||
ocp lan Show LAN connection info & IP
|
||||
ocp settings View tunable settings
|
||||
ocp settings <k> <v> Update a setting at runtime
|
||||
@@ -365,17 +542,57 @@ ocp --help
|
||||
|
||||
> **Cloud/Linux servers:** If `ocp: command not found`, the binary isn't in PATH. Full path: `~/.openclaw/projects/ocp/ocp`
|
||||
|
||||
### Self-Update
|
||||
## Upgrading
|
||||
|
||||
The simplest path: ask your AI.
|
||||
|
||||
Paste this prompt:
|
||||
|
||||
```
|
||||
Upgrade my OCP. Run `ocp update` and follow whatever it says.
|
||||
If it tells me to run `claude auth login`, I'll do that.
|
||||
```
|
||||
|
||||
What `ocp update` does:
|
||||
|
||||
- **Patch bump** (e.g. `v3.14.0 → v3.14.1`):
|
||||
light path (git pull + npm install + restart).
|
||||
- **Cross-minor** (e.g. `v3.10 → v3.14`):
|
||||
full path: pre-flight check, snapshot, `setup.mjs` (with plist env-merge),
|
||||
service restart, post-flight `/health` and `/v1/models` verification.
|
||||
- **Old version** (< v3.4.0):
|
||||
fresh-install. Pre-v3.4 lacked admin-key/usage-db, so there is nothing to
|
||||
migrate. Your OAuth token (managed by the Claude Code CLI, not OCP) is
|
||||
preserved; you do not need to re-OAuth unless your token expired
|
||||
separately.
|
||||
|
||||
Snapshots are saved to `~/.ocp/upgrade-snapshot-<ISO-ts>/` and never
|
||||
auto-deleted. Clean old ones with `rm -rf ~/.ocp/upgrade-snapshot-*` once
|
||||
you're confident the upgrade is stable.
|
||||
|
||||
### Manual upgrade — same command, no AI
|
||||
|
||||
```bash
|
||||
# Check if a new version is available
|
||||
ocp update --check
|
||||
|
||||
# Pull latest, sync plugin, restart proxy — one command
|
||||
ocp update
|
||||
ocp update # smart-pick path
|
||||
ocp update --check # show available updates, don't apply
|
||||
ocp update --dry-run # preview plan
|
||||
ocp update --target v3.13.0 # pin a specific version
|
||||
ocp update --rollback --yes # restore most recent snapshot (--yes confirms)
|
||||
ocp update --rollback --list # list snapshots, no mutation
|
||||
ocp update --rollback --dry-run # preview rollback plan
|
||||
```
|
||||
|
||||
`ocp update` runs (in order): `git pull` → `npm install` → plugin sync → **OpenClaw model registry sync** (v3.11.0+) → proxy restart → health check.
|
||||
### When upgrade fails
|
||||
|
||||
`ocp update` prints a recovery line on failure. To restore from the snapshot:
|
||||
|
||||
```bash
|
||||
ocp update --rollback --yes # --yes confirms the destructive restore
|
||||
ocp doctor
|
||||
```
|
||||
|
||||
If `ocp doctor` still reports problems after rollback, open a GitHub issue
|
||||
with the snapshot path and the doctor JSON output (`ocp doctor --json`).
|
||||
|
||||
### OpenClaw Auto-Sync (v3.11.0+)
|
||||
|
||||
@@ -428,17 +645,20 @@ ocp settings cacheTTL 300000
|
||||
```
|
||||
|
||||
**How it works:**
|
||||
- Cache key = SHA-256 of `model` + `messages` + `temperature` + `max_tokens` + `top_p`
|
||||
- Cache key = SHA-256 of `v2|<keyId or "anon">|model + messages + temperature + max_tokens + top_p`
|
||||
- **Per-key isolation** — different API keys never share cache entries; anonymous callers share one `anon` pool
|
||||
- Cache hits return instantly — no Claude CLI process spawned
|
||||
- Works for both streaming and non-streaming requests
|
||||
- **Streaming hits** are replayed as multiple SSE chunks (80 codepoints each), not one large delta — incremental render preserved
|
||||
- **`cache_control` bypass** — if a request carries an Anthropic `cache_control` annotation (top-level or nested in `content[]`), OCP skips its own cache entirely so it doesn't interfere with Anthropic-side prompt caching
|
||||
- **Singleflight stampede protection** — concurrent identical cache-miss requests share one upstream `cli.js` spawn; followers receive byte-identical responses to the leader's call. Non-streaming path only (streaming-path singleflight is a known TODO)
|
||||
- Multi-turn conversations (with `session_id`) are never cached
|
||||
- Expired entries are cleaned up automatically every 10 minutes
|
||||
|
||||
**Management:**
|
||||
```bash
|
||||
# View cache stats
|
||||
# View cache stats (now includes singleflight in-flight counts)
|
||||
curl http://127.0.0.1:3456/cache/stats
|
||||
# → { "entries": 42, "totalHits": 156, "sizeBytes": 284000 }
|
||||
# → { "entries": 42, "totalHits": 156, "sizeBytes": 284000, "inflight": 0, "requesters": 0 }
|
||||
|
||||
# Clear all cached responses
|
||||
curl -X DELETE http://127.0.0.1:3456/cache
|
||||
@@ -449,6 +669,8 @@ ocp settings cacheTTL 0
|
||||
|
||||
Cache is **disabled by default** (`CLAUDE_CACHE_TTL=0`). All data is stored locally in `~/.ocp/ocp.db`.
|
||||
|
||||
**Hash format upgrade in v3.13.0:** legacy `v1` cache rows from earlier versions don't match new `v2`-format lookups; they orphan and are reaped by the TTL cleanup interval within one window. No migration script required.
|
||||
|
||||
## How It Works
|
||||
|
||||
```
|
||||
@@ -493,7 +715,7 @@ The canonical list lives in [`models.json`](./models.json) — the single source
|
||||
| `/api/keys` | GET/POST | List or create API keys (admin only) |
|
||||
| `/api/keys/:id` | DELETE | Revoke an API key (admin only) |
|
||||
| `/api/keys/:id/quota` | GET/PATCH | View or set per-key quota (admin only) |
|
||||
| `/api/usage` | GET | Per-key usage stats (`?since=&until=&hours=&limit=`) |
|
||||
| `/api/usage` | GET | Per-key usage stats (`?since=&until=&hours=&limit=`); returns self only by default — pass `?all=true` (admin only) for all-keys data |
|
||||
| `/cache/stats` | GET | Cache statistics (admin only) |
|
||||
| `/cache` | DELETE | Clear response cache (admin only) |
|
||||
|
||||
@@ -543,6 +765,52 @@ After installing the gateway plugin, use `/ocp` slash commands in your chat:
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
The simplest path: ask your AI.
|
||||
|
||||
Paste this prompt:
|
||||
|
||||
```
|
||||
Run `ocp doctor` and follow its `next_action`. Tell me if you hit
|
||||
anything that needs human input.
|
||||
```
|
||||
|
||||
The doctor produces a JSON `next_action` with `ai_executable[]` (commands
|
||||
the agent runs verbatim) and `human_required[]` (steps that need you,
|
||||
typically just OAuth).
|
||||
|
||||
### Manual debugging
|
||||
|
||||
### 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
|
||||
|
||||
```bash
|
||||
@@ -587,7 +855,8 @@ Future `ocp update` invocations sync automatically.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CLAUDE_PROXY_PORT` | `3456` | Listen port |
|
||||
| `CLAUDE_PROXY_PORT` | `3456` | Listen port (server-side). Also consumed by the OpenClaw `ocp-plugin` to dial the local proxy. |
|
||||
| `OCP_PROXY_URL` | *(unset)* | Plugin-side full URL override (e.g. `http://10.0.0.5:3456`). Wins over `CLAUDE_PROXY_PORT` when both are set. Read by `ocp-plugin/index.js` only — server ignores it. |
|
||||
| `CLAUDE_BIND` | `127.0.0.1` | Bind address (`0.0.0.0` for LAN access) |
|
||||
| `CLAUDE_AUTH_MODE` | `none` | Auth mode: `none`, `shared`, or `multi` |
|
||||
| `OCP_ADMIN_KEY` | *(unset)* | Admin key for key management (multi mode) |
|
||||
@@ -614,6 +883,26 @@ Heartbeats are inert SSE comment lines — conforming SSE clients ignore them. I
|
||||
|
||||
OCP also sends `X-Accel-Buffering: no` on SSE responses so nginx-default proxy buffering does not hold heartbeats in an upstream buffer.
|
||||
|
||||
## Repository Layout
|
||||
|
||||
Top-level files a contributor or operator may need to know:
|
||||
|
||||
| Path | Role |
|
||||
|------|------|
|
||||
| `server.mjs` | The proxy itself; every request path lives here. Governed by `ALIGNMENT.md`. |
|
||||
| `setup.mjs` | First-time installer — verifies Claude CLI, patches OpenClaw config, installs auto-start. |
|
||||
| `uninstall.mjs` | Reverses the launchd / systemd auto-start install. |
|
||||
| `keys.mjs` | API-key management module (multi-mode auth: create/list/revoke, quotas, usage tracking). |
|
||||
| `models.json` | Single source of truth for model IDs, aliases, context windows. See ADR 0003. |
|
||||
| `ocp` / `ocp-connect` | User-facing CLI wrappers (server-side / client-side respectively). |
|
||||
| `dashboard.html` | Static dashboard served from `/dashboard`. |
|
||||
| `scripts/sync-openclaw.mjs` | Idempotent OpenClaw registry sync invoked by `ocp update`. See ADR 0004. |
|
||||
| `.claude/skills/` | Project-specific Claude Code skills. |
|
||||
| `ocp-plugin/` | OpenClaw gateway plugin (optional installation). |
|
||||
| `docs/adr/` | Architecture Decision Records. Read these before proposing governance or SPOT changes — see [`docs/adr/README.md`](docs/adr/README.md). |
|
||||
| `ALIGNMENT.md` | The constitution. Binding for any `server.mjs` change. |
|
||||
| `AGENTS.md` / `CLAUDE.md` | Agent and Claude-Code-specific session instructions. |
|
||||
|
||||
## Security
|
||||
|
||||
- **Localhost by default** — binds to `127.0.0.1`; set `CLAUDE_BIND=0.0.0.0` to enable LAN access
|
||||
@@ -625,6 +914,36 @@ OCP also sends `X-Accel-Buffering: no` on SSE responses so nginx-default proxy b
|
||||
- **Keys stored locally** — `~/.ocp/ocp.db` (SQLite), never sent to external services
|
||||
- **Auto-start** — launchd (macOS) / systemd (Linux)
|
||||
|
||||
## Governance
|
||||
|
||||
OCP runs under a small set of binding documents so contributions stay aligned with what `cli.js` actually does, not what an LLM thinks it does:
|
||||
|
||||
- **[`ALIGNMENT.md`](./ALIGNMENT.md)** — the constitution. Every endpoint OCP exposes must correspond to something `cli.js` actually does, with a line-number citation. Background in [ADR 0002](./docs/adr/0002-alignment-constitution.md).
|
||||
- **[`.github/workflows/alignment.yml`](./.github/workflows/alignment.yml)** — CI guardrail. Greps `server.mjs` for known-hallucinated tokens and fails the build on any hit. Not suppressible without an `ALIGNMENT.md` amendment PR.
|
||||
- **[`AGENTS.md`](./AGENTS.md)** — guidelines any AI coding agent (Claude Code / Cursor / Copilot / Codex / Gemini) should read before touching this repo.
|
||||
- **[`models.json`](./models.json)** — single source of truth for the model registry. See [ADR 0003](./docs/adr/0003-models-json-spot.md).
|
||||
- **[`docs/adr/`](./docs/adr/)** — architecture decision records explaining why current structure exists.
|
||||
|
||||
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
|
||||
|
||||
MIT
|
||||
MIT — see [`LICENSE`](LICENSE).
|
||||
|
||||
+21
-2
@@ -55,7 +55,13 @@
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Usage by Key</h2>
|
||||
<div class="flex" style="justify-content: space-between; align-items: center;">
|
||||
<h2 style="margin: 0;">Usage by Key</h2>
|
||||
<label id="usage-scope-toggle" class="flex" style="display:none; gap: 0.4rem; font-size: 0.8rem; color: #94a3b8; cursor: pointer;">
|
||||
<input type="checkbox" id="usage-show-all" style="cursor: pointer;">
|
||||
<span>Show all keys</span>
|
||||
</label>
|
||||
</div>
|
||||
<table id="key-usage-table">
|
||||
<thead><tr><th>Key</th><th>Requests</th><th>OK</th><th>Err</th><th>Avg Time</th><th>Last Request</th></tr></thead>
|
||||
<tbody></tbody>
|
||||
@@ -170,7 +176,8 @@ async function refreshStatus() {
|
||||
|
||||
async function refreshUsage() {
|
||||
try {
|
||||
const data = await api("/api/usage");
|
||||
const showAll = localStorage.getItem("ocp_usage_show_all") === "1";
|
||||
const data = await api(showAll ? "/api/usage?all=true" : "/api/usage");
|
||||
const tbody = document.querySelector("#key-usage-table tbody");
|
||||
tbody.innerHTML = (data.byKey || []).map(k => `
|
||||
<tr>
|
||||
@@ -204,6 +211,8 @@ async function refreshKeys() {
|
||||
try {
|
||||
const data = await api("/api/keys");
|
||||
document.getElementById("key-mgmt-section").style.display = "";
|
||||
// Admin-only "Show all keys" toggle for /api/usage scope.
|
||||
document.getElementById("usage-scope-toggle").style.display = "flex";
|
||||
const tbody = document.querySelector("#keys-table tbody");
|
||||
tbody.innerHTML = (data.keys || []).map(k => `
|
||||
<tr>
|
||||
@@ -240,6 +249,16 @@ async function refreshAll() {
|
||||
document.getElementById("refresh-indicator").textContent = `Updated ${new Date().toLocaleTimeString()}`;
|
||||
}
|
||||
|
||||
// Wire "Show all keys" toggle (visibility gated to admin via refreshKeys()).
|
||||
(function setupUsageScopeToggle() {
|
||||
const cb = document.getElementById("usage-show-all");
|
||||
cb.checked = localStorage.getItem("ocp_usage_show_all") === "1";
|
||||
cb.addEventListener("change", () => {
|
||||
localStorage.setItem("ocp_usage_show_all", cb.checked ? "1" : "0");
|
||||
refreshUsage();
|
||||
});
|
||||
})();
|
||||
|
||||
refreshAll();
|
||||
setInterval(refreshAll, 30000);
|
||||
</script>
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
services:
|
||||
claude-proxy:
|
||||
build: .
|
||||
ports:
|
||||
- "3456:3456"
|
||||
env_file: .env
|
||||
restart: unless-stopped
|
||||
@@ -0,0 +1,79 @@
|
||||
# 0005 — OCP Stays Single-Provider; No Multi-Provider Refactor
|
||||
|
||||
- **Date**: 2026-05-06
|
||||
- **Status**: Accepted
|
||||
- **Authors**: project maintainer (with AI advisory drafting)
|
||||
- **Related**: ADR 0002 (Alignment Constitution), ADR 0003 (`models.json` SPOT)
|
||||
|
||||
## Context
|
||||
|
||||
OCP's `server.mjs` reached 1667 lines and now provides response cache, per-key quota, session tracking, model-level stats, and SSE heartbeat — all targeting a single backend path: `spawn` the locally installed `cli.js` and let it transact with `api.anthropic.com`. This architecture is the source of OCP's only real differentiator: **`cli.js` behavior-level alignment** (session create-vs-resume semantics, tool_use id reuse, SSE quirks, etc.) — none of which a generic LLM gateway has, because none of them speak this protocol.
|
||||
|
||||
The maintainer evaluated extending OCP to support OpenAI / Gemini / OpenRouter / Together / Groq / Ollama — i.e., turning OCP into a multi-provider gateway resembling Helicone, LiteLLM, OpenRouter, or Portkey. The motivation for that extension: reduce dependency on Anthropic, broaden OCP's commercial surface, and stop being grayscale-positioned (the `cli.js` spawn pattern depends on the local Pro/Max subscription, which Anthropic could fingerprint and disable).
|
||||
|
||||
The honest engineering estimate for that extension:
|
||||
|
||||
| Phase | Net New LOC | Calendar Time (part-time) |
|
||||
|---|---|---|
|
||||
| Provider abstraction + OpenAI | ~1230 + schema migration | 2 weeks |
|
||||
| Add Gemini | ~550 | +1.5 weeks |
|
||||
| OpenAI-compatible family (OpenRouter / Together / Groq) | ~300 | +1 week |
|
||||
| Tests, docs, hardening | — | +1.5 weeks |
|
||||
| **Multi-provider v1** | ~2080 | **~7 weeks focused** |
|
||||
|
||||
That number is not the real cost. The real cost is **strategic**:
|
||||
|
||||
1. **Loss of unique value.** `cli.js` behavior alignment is meaningless for OpenAI / Gemini / Ollama traffic. Going multi-provider means OCP's only moat applies to ~30% of its surface; the other 70% is generic gateway code already done better by Helicone / LiteLLM.
|
||||
|
||||
2. **Hybrid architecture awkwardness.** A multi-provider OCP would have two paths: `spawn(cli.js)` for Claude (still grayscale, depends on Pro subscription), and direct API call for everyone else (clean, BYOK). Customers asking "what is OCP?" would hear two different answers depending on which model they pick. This is worse than either pure path.
|
||||
|
||||
3. **Direct competition with funded incumbents.** Helicone (~$5M raised, YC W23), OpenRouter (~$1B valuation), LiteLLM (significant enterprise revenue), Portkey, Langfuse, Cloudflare AI Gateway — all already do multi-provider gateway with mature dashboards, audit logs, SOC2, and team features. OCP would enter that market 2+ years late with one engineer.
|
||||
|
||||
4. **The grayscale problem isn't solved by adding providers.** As long as OCP keeps the `cli.js` spawn path for Anthropic, it remains grayscale for that path; adding OpenAI alongside doesn't make the Anthropic path any less dependent on a Pro/Max subscription that wasn't licensed for proxying.
|
||||
|
||||
The maintainer's separate decision (recorded in personal notes, not this repo) is that **OCP itself will not be commercialized**; it will remain a personal power tool plus open-source contribution. Any commercial gateway work, if pursued, will start from a clean codebase with BYOK from day one — not from OCP.
|
||||
|
||||
Given that, the multi-provider extension would buy OCP nothing: not a moat, not commercial readiness, not even meaningfully better personal utility (the maintainer overwhelmingly uses Claude).
|
||||
|
||||
## Decision
|
||||
|
||||
OCP stays single-provider. Specifically:
|
||||
|
||||
1. **No new providers added to `server.mjs`.** The dispatch path remains `spawn(cli.js) → api.anthropic.com`. Pull requests that introduce a `providers/` directory or a model-to-provider router are declined on the basis of this ADR.
|
||||
|
||||
2. **`models.json` schema stays Anthropic-only.** No `provider` field, no per-model cost/capability metadata that anticipates other providers. If non-Anthropic models ever need to be referenced (e.g., for OpenClaw provider list completeness), they live in a separate file or in OpenClaw's own config — not in OCP's SPOT.
|
||||
|
||||
3. **Cache improvements are in scope.** The existing response cache (in `keys.mjs`: `cacheHash` / `getCachedResponse` / `setCachedResponse` / `clearCache`) is acceptable to upgrade with stream replay, stampede protection (singleflight), per-key isolation, and Anthropic `cache_control` awareness. These reinforce the single-provider position; they do not create provider-extension surface area.
|
||||
|
||||
4. **Anthropic alignment work continues to be encouraged.** Anything that deepens `cli.js` behavior alignment — session lifetime, tool_use id semantics, SSE behavior, multi-account routing, model-tier observability — is the project's actual value and should be prioritized over generic-gateway features.
|
||||
|
||||
5. **Commercial work, if pursued, starts elsewhere.** A separate repository, separate name, BYOK from day one, no `cli.js` spawn. That repo is out of scope for OCP and is not bound by this ADR.
|
||||
|
||||
## Consequences
|
||||
|
||||
**Positive**
|
||||
|
||||
- Project scope stays bounded. The maintainer can keep evolving OCP at part-time pace without the multi-provider maintenance burden (every provider's API breaks at some point and demands attention).
|
||||
- The unique value (`cli.js` alignment) is preserved and continues to compound — every new alignment fix increases OCP's distance from generic gateways.
|
||||
- Future contributors reading the code see one architecture, not a hybrid; debugging stays tractable.
|
||||
- Decisions about commercialization are decoupled from OCP's technical evolution. OCP can stay grayscale-personal-tool indefinitely without that being a blocker for any future commercial product.
|
||||
|
||||
**Negative**
|
||||
|
||||
- OCP cannot serve any user who needs OpenAI / Gemini / local LLM access. Those users must route through a different gateway (Helicone, LiteLLM, OpenRouter) or call providers directly.
|
||||
- If Anthropic substantially changes `cli.js` (e.g., adds client attestation, removes the spawn-and-forward pattern, or migrates `claude` to a non-CLI form factor), OCP's core architecture breaks and there is no second backend to fall back to.
|
||||
- The maintainer must resist a recurring temptation: "while I'm in here, let me just add OpenAI." The whole point of this ADR is to make that temptation cost a documented amendment, not a quiet PR.
|
||||
|
||||
**Neutral**
|
||||
|
||||
- This ADR records a non-decision in code: nothing in `server.mjs` changes today. Its purpose is to make future contributors (including the maintainer) explain themselves before going against it. Per the project's PR template and Iron Rule 11, an amendment to this ADR is the gating step before any provider-extension PR.
|
||||
|
||||
## Trigger conditions for revisiting this ADR
|
||||
|
||||
This ADR should be revisited (and possibly amended or superseded) if any of the following occur:
|
||||
|
||||
1. Anthropic ships a feature that breaks the `cli.js` spawn pattern OCP depends on, and the maintainer wants to keep OCP useful.
|
||||
2. The maintainer makes a deliberate decision to commercialize OCP (rather than start a separate codebase). This requires explicit re-scoping; "let me try" is not enough.
|
||||
3. A genuine user need emerges — e.g., the maintainer themselves starts using OpenAI / Gemini frequently from Claude Code workflows — that single-provider OCP cannot serve.
|
||||
|
||||
In all three cases, the response is **first amend this ADR**, then write code. Order is not optional.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Architecture Decision Records
|
||||
|
||||
This directory holds the OCP Architecture Decision Records (ADRs) — short documents that capture the **why** behind structural choices.
|
||||
|
||||
Read these before proposing governance, SPOT (single-source-of-truth), or process changes.
|
||||
|
||||
## Numbering
|
||||
|
||||
ADRs start at `0002`. The first one (`0001`) was reserved for an early
|
||||
internal proposal that was superseded before publication; `0002` is
|
||||
deliberately the first published record so the archived `0001` slot
|
||||
remains a placeholder rather than being silently renumbered.
|
||||
|
||||
New ADRs increment from the highest existing number. Filenames are
|
||||
`NNNN-<short-slug>.md`.
|
||||
|
||||
## Index
|
||||
|
||||
| ADR | Title | What it covers |
|
||||
|---|---|---|
|
||||
| [0002](0002-alignment-constitution.md) | Alignment Constitution | The `ALIGNMENT.md` constitution: why every `server.mjs` change requires `cli.js` citation + independent reviewer + CI blacklist pass. Background: the 2026-04-11 drift incident. |
|
||||
| [0003](0003-models-json-spot.md) | `models.json` as SPOT | Why model IDs / aliases / context windows live in a single JSON file (not duplicated in `server.mjs` and `setup.mjs` arrays). v3.11.0 refactor. |
|
||||
| [0004](0004-openclaw-auto-sync.md) | OpenClaw Auto-Sync | Why `scripts/sync-openclaw.mjs` runs on `ocp update`, what its scope boundary is (writes only `models.providers["claude-local"].models` and `agents.defaults.models["claude-local/*"]`), and the idempotency contract. |
|
||||
| [0005](0005-no-multi-provider.md) | No Multi-Provider | Why OCP stays single-provider (Anthropic-via-cli.js) and does not extend to OpenAI / Gemini / OpenRouter. Cost estimate: ~7 weeks for a v1 that buys neither moat nor commercial readiness. Separate commercial work starts in a separate repo. |
|
||||
|
||||
## When to write a new ADR
|
||||
|
||||
Open one whenever:
|
||||
|
||||
- A structural rule is being added or changed (e.g., new SPOT, new boundary, new CI guardrail).
|
||||
- A decision encodes a lesson from an incident or drift.
|
||||
- A future contributor reading the code alone could plausibly undo or re-litigate the choice.
|
||||
|
||||
Skip ADRs for routine implementation choices (algorithm pick, naming) — those belong in commit messages.
|
||||
|
||||
## Format
|
||||
|
||||
Keep ADRs short — Context / Decision / Consequences is the standard skeleton. Cite incidents, PRs, or commits where useful.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 222 KiB After Width: | Height: | Size: 366 KiB |
@@ -0,0 +1,147 @@
|
||||
# Design: Response Cache Upgrade (Per-Key Isolation, cache_control Bypass, Chunked Stream Replay, Singleflight)
|
||||
|
||||
**Date:** 2026-05-07
|
||||
**Status:** Draft (awaiting maintainer approval)
|
||||
**Target version:** v3.13.0 (minor — internal correctness/concurrency improvements; no new public env vars or endpoints)
|
||||
**Driving ADR:** [ADR 0005 — No Multi-Provider](../../adr/0005-no-multi-provider.md), decision §3 ("Cache improvements are in scope")
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
OCP already has a response cache (`keys.mjs:296` `cacheHash` / `keys.mjs:311` `getCachedResponse` / `keys.mjs:324` `setCachedResponse`), wired into the proxy core at `server.mjs:1220` (non-streaming path read), `server.mjs:1227` (cache-hit-on-streaming-request replay), and `server.mjs:683` (streaming write-back). Today it has four functional gaps. This PR pair closes all four, in two minimum-reviewable units, **without changing the public API surface**.
|
||||
|
||||
| Gap | Impact today | Fix lands in |
|
||||
|---|---|---|
|
||||
| All keys share one cache pool | Key A's cache hit can leak Key B's prompt response | PR-A |
|
||||
| Anthropic `cache_control` markers not detected | OCP cache may interfere with Anthropic prompt caching that the user explicitly requested | PR-A |
|
||||
| Stream cache hit replays whole content in one SSE chunk | Downstream renders all-at-once; some SDKs misbehave on huge single deltas | PR-A |
|
||||
| Concurrent identical cache misses all spawn `cli.js` independently | Cache stampede: N requests → N spawns → N billable calls | PR-B |
|
||||
|
||||
---
|
||||
|
||||
## Constitutional alignment (ALIGNMENT.md)
|
||||
|
||||
**`cli.js` does not perform response caching at the proxy layer.** The OCP response cache is a value-add operation that exists only inside OCP, between the wire (clients ↔ OCP) and the spawn (OCP ↔ `cli.js`). It does not introduce, rename, or alter any endpoint, header, request field, or response field that `cli.js` emits or expects. Cache hits return content byte-identical to what `cli.js` returned on the original miss, with the same `chat.completion` / `chat.completion.chunk` shape — **no client-observable wire shape change**.
|
||||
|
||||
This PR pair extends the existing cache (introduced in earlier commits) without expanding its surface. No new endpoints. No new headers. No new env vars exposed publicly (we add internal counters readable via the existing `/cache/stats` endpoint, but the response shape only gains numeric fields, not new structural fields).
|
||||
|
||||
Per Rule 1 / Rule 5: every commit body in this PR pair will state the absence of `cli.js` reference explicitly and justify scope under Rule 2's value-add carve-out for non-wire-affecting proxy operations.
|
||||
|
||||
---
|
||||
|
||||
## Key decisions (with rationale)
|
||||
|
||||
### D1. Per-key isolation via hash input, not schema column
|
||||
|
||||
`cacheHash` gains an optional `keyId` input. Distinct `keyId` values produce distinct hashes for the same prompt, so SQLite-level isolation falls out for free without a schema change.
|
||||
|
||||
**Rationale.** Adding a `key_id` column to `response_cache` requires either (a) dropping the existing `hash UNIQUE` index and replacing with a composite `(hash, key_id) UNIQUE`, which SQLite cannot do via plain `ALTER TABLE` and would require a table-rebuild migration, or (b) tolerating duplicate `hash` rows, which contradicts the existing schema comment and breaks `setCachedResponse`'s `ON CONFLICT(hash)` upsert clause.
|
||||
|
||||
The hash-input approach is reversible (we can switch to a schema column later if analytics across keys becomes a real need) and zero-risk on the SQL plane. The trade-off — losing the ability to query "which keys have cached this prompt?" — has no current consumer.
|
||||
|
||||
**Hash input format.** `cacheHash` prepends a version tag and key tag before the existing inputs:
|
||||
|
||||
```
|
||||
v2|k:<keyId or "anon">|<model>|...rest as today
|
||||
```
|
||||
|
||||
The `v2` prefix means existing v1-format rows in the cache table no longer hash-match any new request. They are abandoned, not deleted; the existing TTL-based `clearCache(CACHE_TTL)` cleanup interval at `server.mjs:185` reaps them within one TTL window. **No migration step is needed.** This is acceptable because the cache is by definition ephemeral and best-effort.
|
||||
|
||||
**Anonymous fallback.** When the request has no authenticated key (`req._authKeyId === undefined`), `keyId` is `"anon"`. Anonymous-mode users (PROXY_ANONYMOUS_KEY or no auth) share one anonymous pool, which preserves the only legitimate today-multi-user use case (a household running OCP without per-user keys). If this becomes a problem we can add per-IP scoping later, but anonymous-pool sharing is acceptable for v1 because anonymous mode is fundamentally a trust-everyone-on-LAN posture.
|
||||
|
||||
### D2. `cache_control` bypass: detect anywhere, skip OCP cache entirely
|
||||
|
||||
If any element in `messages` (top-level or nested in `content` arrays) carries a `cache_control` field, OCP sets `req._cacheHash = null` and skips both lookup and write-back.
|
||||
|
||||
**Rationale.** Anthropic's [prompt caching](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching) is opt-in by client-side annotation. A user who annotates `cache_control: { type: "ephemeral" }` is explicitly requesting that *Anthropic's* cache serve the call (and is paying the reduced cache-read pricing). Layering OCP's response cache on top in this case is wrong on two counts:
|
||||
|
||||
1. The user's intent is "cache at provider, not at proxy." OCP overruling that intent silently is the same drift family as the 2026-04-11 incident — proxy invents behavior the upstream surface doesn't request.
|
||||
2. OCP cache hits would make `usage.cache_read_input_tokens` (the client-observable signal that prompt caching worked) appear inconsistent — sometimes present, sometimes absent — depending on whether OCP cached.
|
||||
|
||||
Detection is purely structural: walk `messages`, for each `m` check `m.cache_control` (rare top-level form) and if `m.content` is an array, check each part. No semantic interpretation; if the field is present, we bypass.
|
||||
|
||||
**Implementation site.** A small helper `hasCacheControl(messages)` exported from `keys.mjs`, called in `handleChatCompletions` immediately before the existing `cacheHash` call. If it returns true, we skip the cache-lookup branch entirely.
|
||||
|
||||
### D3. Chunked stream replay (80 chars/chunk, no artificial delay)
|
||||
|
||||
Today's cache-hit-on-streaming-request branch (`server.mjs:1227–1237`) sends the entire cached content in a single `delta.content` chunk. This works for spec-compliant SSE clients but visibly degrades the UX (no incremental render) and has tripped at least one buggy SDK in the wild that assumes deltas are small.
|
||||
|
||||
The fix splits cached content into ~80-character substrings, each sent as a separate `chat.completion.chunk` SSE event. **No artificial delay between chunks** — they ship as fast as `res.write` accepts. This preserves OCP's "ship as fast as possible" disposition; we are simulating *the chunk shape* of streaming, not the *latency*.
|
||||
|
||||
**Why 80 chars?** Compromise: small enough that even a multi-paragraph cached response yields >5 chunks (visible incremental render), large enough that even a 4 KB response only produces 50 chunks (not 4000 single-char events). Tunable later via internal constant; not exposed as env var per scope-creep avoidance.
|
||||
|
||||
**Boundary safety.** UTF-8 multibyte characters: we slice by `Array.from(content)` (so each iteration step is a full code point) and group every 80 code points. This avoids producing invalid UTF-8 mid-character.
|
||||
|
||||
### D4. Singleflight stampede protection: in-process Map, all-or-nothing failure
|
||||
|
||||
`keys.mjs` exports `singleflight(hash, fn)`. An in-memory `Map<hash, Promise>` deduplicates concurrent identical cache-miss flows. The first request executes `fn()`; concurrent requests with the same hash receive the same promise. When the promise settles (resolve or reject), the map entry is deleted.
|
||||
|
||||
**Rationale (single-process scope).** OCP runs as a single Node.js process per host. A `Map` is sufficient. Adding Redis or another shared store would be the start of a multi-instance evolution, which is out of scope per ADR 0005 (OCP is a personal power tool, not a horizontally-scaled SaaS).
|
||||
|
||||
**All-or-nothing failure semantics.** When the leader's `fn()` rejects, all followers receive the same rejection. The alternative — letting followers retry independently after a leader failure — risks N retries of an already-broken upstream, which is exactly what stampede protection was meant to prevent. Followers can retry at the *next* request, with idle backoff handled by the client. This matches Go's `golang.org/x/sync/singleflight` reference behavior.
|
||||
|
||||
**Streaming caveat.** Singleflight wraps the *non-streaming* code path only in PR-B. For streaming, deduplicating concurrent identical streaming requests is materially harder (we'd need to fan out one upstream stream to N downstream connections in real time, with backpressure). It's also a less common case (cache stampedes typically come from non-streaming batch jobs hitting the proxy in parallel). Streaming dedup is **explicitly out of scope** for this PR pair; leave a TODO comment in `callClaudeStreaming` for a future ticket.
|
||||
|
||||
**Map size unboundedness.** In normal operation the map is empty most of the time (entries delete on Promise settlement). Pathological case: an upstream call that hangs forever leaks one Map entry per stuck request. The existing `TIMEOUT` guard on `callClaude` (server.mjs spawn timeout) bounds this — the Promise will reject (timeout) within `TIMEOUT` ms, and the entry clears. No additional sweep needed.
|
||||
|
||||
---
|
||||
|
||||
## PR boundaries
|
||||
|
||||
### PR-A — Foundation (D1 + D2 + D3)
|
||||
|
||||
**Files touched:**
|
||||
- `keys.mjs`: extend `cacheHash` with optional `keyId`/version prefix; add `hasCacheControl(messages)` helper
|
||||
- `server.mjs`: pass `req._authKeyId` to `cacheHash`; check `hasCacheControl` and bypass; chunk cache-hit replay at line 1227–1237
|
||||
- `test-features.mjs`: add cases for keyId isolation, cache_control bypass, chunked replay shape
|
||||
|
||||
**LOC budget:** ~80 production + ~50 test
|
||||
**Risk:** Low — all changes are additive or guard-clause; existing cache behavior preserved when `keyId` defaults to "anon" and no `cache_control` present.
|
||||
**Backward compat:** v1-format hashes naturally orphan; TTL cleanup reaps within one window; no migration script.
|
||||
|
||||
### PR-B — Concurrency (D4)
|
||||
|
||||
**Files touched:**
|
||||
- `keys.mjs`: add `singleflight(hash, fn)` and `getInflightStats()` exports
|
||||
- `server.mjs`: wrap non-streaming cache-miss path through `singleflight`; add inflight count to `/cache/stats` response
|
||||
- `test-features.mjs`: add concurrent-request test that asserts only 1 spawn occurs for N=10 simultaneous identical requests
|
||||
|
||||
**LOC budget:** ~70 production + ~40 test
|
||||
**Risk:** Medium — concurrency code is harder to reason about; mitigation is an explicit test case for the dedup behavior.
|
||||
**Streaming explicitly out of scope:** TODO comment placed in `callClaudeStreaming` for follow-up ticket.
|
||||
|
||||
---
|
||||
|
||||
## Testing strategy
|
||||
|
||||
**Unit-ish (in `test-features.mjs`):**
|
||||
1. `cacheHash` with two different `keyId` values → different hashes
|
||||
2. `cacheHash` v2 prefix present in output (sanity check)
|
||||
3. `hasCacheControl` returns true for top-level `cache_control` and for nested in `content[]`
|
||||
4. `hasCacheControl` returns false for benign messages
|
||||
5. Chunked replay: cached "abcdefgh..." (160 chars) produces 2 deltas
|
||||
|
||||
**Integration (manual smoke before merge):**
|
||||
1. Set `CLAUDE_CACHE_TTL=60000`; create key A and key B; identical prompt from each → both spawn fresh; second-call from same key → cache hit
|
||||
2. Send a message with `cache_control` annotation → OCP logs `cache_skipped: cache_control_present`; no cache write
|
||||
3. Streaming cache hit visibly produces multiple SSE deltas (`curl -N | grep "data: "` shows >1 lines)
|
||||
|
||||
**Concurrent (PR-B only):**
|
||||
1. Spawn 10 simultaneous identical non-streaming requests; assert (via `/cache/stats` inflight peak or via a process spawn counter) only 1 `cli.js` spawn occurred
|
||||
|
||||
---
|
||||
|
||||
## Out of scope (deliberately deferred)
|
||||
|
||||
- **Streaming singleflight** — see D4 streaming caveat. TODO in code.
|
||||
- **Semantic cache** (embedding-based near-match) — needs an embedding provider + vector index. Punt to v3.14+ if there's user demand.
|
||||
- **Cross-process cache** (Redis backend) — violates ADR 0005's "personal power tool" posture.
|
||||
- **Cache versioning by model ID hash** — model upgrades currently invalidate cache organically because model is in the hash; if Anthropic ever silently changes a model's behavior without a model ID bump, that's a separate alignment problem.
|
||||
- **Per-key cache TTL override** — single global TTL (existing `CLAUDE_CACHE_TTL`) is fine; per-key TTL is a knob no one has asked for.
|
||||
|
||||
---
|
||||
|
||||
## Rollback plan
|
||||
|
||||
If either PR introduces a regression, the rollback is a clean git revert. The cache layer is opt-in (default `CLAUDE_CACHE_TTL=0` = disabled), so users who never enabled the cache are unaffected by any cache-layer regression. Users who *had* enabled the cache lose only ephemeral state on revert. No persistent on-disk state is reshaped by this PR pair (we explicitly avoid schema migrations per D1 rationale).
|
||||
@@ -3,11 +3,13 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { randomBytes, createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { mkdirSync, chmodSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
|
||||
const OCP_DIR = join(homedir(), ".ocp");
|
||||
mkdirSync(OCP_DIR, { recursive: true });
|
||||
mkdirSync(OCP_DIR, { recursive: true, mode: 0o700 });
|
||||
// Tighten the directory mode in case it already existed with broader permissions.
|
||||
try { chmodSync(OCP_DIR, 0o700); } catch { /* ignore EPERM on pre-existing dirs */ }
|
||||
const DB_PATH = join(OCP_DIR, "ocp.db");
|
||||
|
||||
let db;
|
||||
@@ -18,6 +20,8 @@ export function getDb() {
|
||||
db.exec("PRAGMA journal_mode = WAL");
|
||||
db.exec("PRAGMA foreign_keys = ON");
|
||||
initSchema();
|
||||
// Tighten mode on the DB file (0600) after creation / first open.
|
||||
try { chmodSync(DB_PATH, 0o600); } catch { /* ignore — same-user access still works */ }
|
||||
}
|
||||
return db;
|
||||
}
|
||||
@@ -292,9 +296,13 @@ export function getKeyQuota(keyId) {
|
||||
|
||||
// ── Response cache ──
|
||||
|
||||
// Generate a cache key from model + messages + request params that affect output
|
||||
// Generate a cache key from model + messages + request params that affect output.
|
||||
// opts.keyId isolates per-API-key cache pools (v2 hash format).
|
||||
// When keyId is absent/null/empty, falls back to "anon" (shared anonymous pool).
|
||||
export function cacheHash(model, messages, opts = {}) {
|
||||
const keyId = opts.keyId || "anon";
|
||||
const h = createHash("sha256");
|
||||
h.update(`v2|k:${keyId}|`);
|
||||
h.update(model);
|
||||
if (opts.temperature != null) h.update(`t:${opts.temperature}`);
|
||||
if (opts.max_tokens != null) h.update(`mt:${opts.max_tokens}`);
|
||||
@@ -306,6 +314,22 @@ export function cacheHash(model, messages, opts = {}) {
|
||||
return h.digest("hex");
|
||||
}
|
||||
|
||||
// Check whether any message (or content part) carries an Anthropic cache_control field.
|
||||
// If true, OCP should skip its own cache to avoid interfering with prompt-caching intent.
|
||||
export function hasCacheControl(messages) {
|
||||
for (const m of messages || []) {
|
||||
if (m && typeof m === "object") {
|
||||
if (m.cache_control) return true;
|
||||
if (Array.isArray(m.content)) {
|
||||
for (const part of m.content) {
|
||||
if (part && typeof part === "object" && part.cache_control) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Look up a cached response. Returns { response, hits } or null.
|
||||
// Also updates last_hit_at and increments hits counter on hit.
|
||||
export function getCachedResponse(hash, ttlMs) {
|
||||
@@ -351,6 +375,36 @@ export function getCacheStats() {
|
||||
return { entries: total, totalHits, sizeBytes };
|
||||
}
|
||||
|
||||
// ── Singleflight stampede protection ──
|
||||
|
||||
// In-memory singleflight Map: hash → { promise, requesters }
|
||||
// Deduplicates concurrent identical cache-miss flows so only one upstream call runs.
|
||||
// Per ADR 0005 / spec D4: in-process scope only (single Node process per host).
|
||||
const inflightMap = new Map();
|
||||
|
||||
export function singleflight(hash, fn) {
|
||||
const existing = inflightMap.get(hash);
|
||||
if (existing) {
|
||||
existing.requesters++;
|
||||
return existing.promise;
|
||||
}
|
||||
// Wrap fn() in Promise.resolve().then() so synchronous throws don't escape.
|
||||
const promise = Promise.resolve().then(fn).finally(() => {
|
||||
inflightMap.delete(hash);
|
||||
});
|
||||
inflightMap.set(hash, { promise, requesters: 1 });
|
||||
return promise;
|
||||
}
|
||||
|
||||
export function getInflightStats() {
|
||||
let totalRequesters = 0;
|
||||
for (const entry of inflightMap.values()) totalRequesters += entry.requesters;
|
||||
return {
|
||||
inflight: inflightMap.size,
|
||||
requesters: totalRequesters,
|
||||
};
|
||||
}
|
||||
|
||||
// Find a key by id or name (returns { id, name } or null)
|
||||
export function findKey(idOrName) {
|
||||
const d = getDb();
|
||||
|
||||
@@ -8,21 +8,18 @@ set -euo pipefail
|
||||
|
||||
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_HEADER=""
|
||||
# Auth args for multi-key mode: reads from OCP_ADMIN_KEY env or ~/.ocp/admin-key file
|
||||
# Using a bash array preserves word boundaries — no eval needed.
|
||||
_AUTH_ARGS=()
|
||||
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
|
||||
_AUTH_HEADER="-H \"Authorization: Bearer $(cat "$HOME/.ocp/admin-key")\""
|
||||
_AUTH_ARGS=(-H "Authorization: Bearer $(cat "$HOME/.ocp/admin-key")")
|
||||
fi
|
||||
|
||||
# Wrapper: curl with optional auth
|
||||
_curl() {
|
||||
if [[ -n "$_AUTH_HEADER" ]]; then
|
||||
eval curl "$_AUTH_HEADER" "$@"
|
||||
else
|
||||
curl "$@"
|
||||
fi
|
||||
curl "${_AUTH_ARGS[@]}" "$@"
|
||||
}
|
||||
|
||||
_json() { python3 -m json.tool 2>/dev/null || cat; }
|
||||
@@ -604,7 +601,7 @@ cmd_restart() {
|
||||
self_r="${BASH_SOURCE[0]}"
|
||||
while [[ -L "$self_r" ]]; do self_r="$(readlink "$self_r")"; done
|
||||
script_dir="$(cd "$(dirname "$self_r")" && pwd)"
|
||||
nohup node "$script_dir/server.mjs" >> "$HOME/.ocp/logs/proxy.log" 2>&1 &
|
||||
DISABLE_AUTOUPDATER=1 nohup node "$script_dir/server.mjs" >> "$HOME/.ocp/logs/proxy.log" 2>&1 &
|
||||
fi
|
||||
sleep 3
|
||||
if curl -sf --max-time 5 "$PROXY/health" > /dev/null 2>&1; then
|
||||
@@ -695,25 +692,35 @@ for e in d.get('errors', []):
|
||||
# ── update ──────────────────────────────────────────────────────────────
|
||||
cmd_update_help() {
|
||||
cat <<'EOF'
|
||||
ocp update — Update OCP to the latest version
|
||||
ocp update — Smart upgrade dispatcher
|
||||
|
||||
Pulls the latest code from GitHub, restarts the proxy service,
|
||||
and optionally syncs the plugin to the OpenClaw extensions directory.
|
||||
Runs `ocp doctor` internally to choose the right path:
|
||||
• Patch bump (same minor): light path (git pull + npm install + restart)
|
||||
• Cross-minor (e.g. v3.10→v3.14): full path with snapshot + post-flight
|
||||
• Old version (< v3.4.0): fresh-install (asks first; AI passes --yes)
|
||||
|
||||
Usage:
|
||||
ocp update Pull latest and restart
|
||||
ocp update --check Check for updates without applying
|
||||
ocp update Smart auto-pick path
|
||||
ocp update --check Show available updates, don't apply
|
||||
ocp update --dry-run Preview the plan, don't mutate
|
||||
ocp update --target v3.13.0 Pin a specific version
|
||||
ocp update --yes Skip y/N prompts (AI agents pass this)
|
||||
ocp update --rollback Restore the most recent upgrade snapshot
|
||||
ocp update --rollback --list List available snapshots
|
||||
ocp update --rollback <path> Restore a specific snapshot
|
||||
ocp update --rollback --dry-run Preview rollback plan
|
||||
ocp update --rollback --gc Delete old snapshots (keep last 5, or <30 days)
|
||||
ocp update --rollback --gc --dry-run Preview what would be deleted
|
||||
EOF
|
||||
}
|
||||
|
||||
cmd_update() {
|
||||
local script_dir self
|
||||
self="${BASH_SOURCE[0]}"
|
||||
# Resolve symlinks (e.g. ~/.local/bin/ocp → real location)
|
||||
while [[ -L "$self" ]]; do self="$(readlink "$self")"; done
|
||||
script_dir="$(cd "$(dirname "$self")" && pwd)"
|
||||
|
||||
# Check-only mode
|
||||
# Pass through --check fast path (existing behaviour)
|
||||
if [[ "${1:-}" == "--check" ]]; then
|
||||
cd "$script_dir"
|
||||
git fetch origin main --quiet 2>/dev/null || true
|
||||
@@ -730,71 +737,104 @@ cmd_update() {
|
||||
echo " Status: ✓ Up to date"
|
||||
else
|
||||
echo " Status: $behind commit(s) behind"
|
||||
echo ""
|
||||
echo " Run 'ocp update' to apply."
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Updating OCP..."
|
||||
echo ""
|
||||
# Rollback path
|
||||
if [[ "${1:-}" == "--rollback" ]]; then
|
||||
shift
|
||||
exec node "$script_dir/scripts/upgrade.mjs" --rollback "$@"
|
||||
fi
|
||||
|
||||
# 1. Pull latest
|
||||
# Doctor-driven path selection
|
||||
local kind
|
||||
kind=$(node "$script_dir/scripts/doctor.mjs" --json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin)['next_action']['kind'])" 2>/dev/null || echo "unknown")
|
||||
|
||||
case "$kind" in
|
||||
noop)
|
||||
echo "Already at latest. Nothing to do."
|
||||
return 0
|
||||
;;
|
||||
update)
|
||||
_cmd_update_light "$script_dir"
|
||||
;;
|
||||
upgrade|fresh_install)
|
||||
exec node "$script_dir/scripts/upgrade.mjs" "$@"
|
||||
;;
|
||||
fix_oauth|fix_service)
|
||||
echo "Pre-upgrade check failed: $kind"
|
||||
echo "Run \`ocp doctor\` for details and ai_executable steps."
|
||||
return 1
|
||||
;;
|
||||
*)
|
||||
echo "Unknown doctor kind: $kind. Run \`ocp doctor --json\` to inspect."
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Existing light-path body extracted into a helper so cmd_update can call it conditionally.
|
||||
_cmd_update_light() {
|
||||
local script_dir="$1"
|
||||
echo "Updating OCP (light path)..."
|
||||
cd "$script_dir"
|
||||
local old_ver
|
||||
local old_ver new_ver
|
||||
old_ver=$(python3 -c "import json; print(json.load(open('package.json'))['version'])" 2>/dev/null || echo "?")
|
||||
|
||||
echo " Pulling latest from GitHub..."
|
||||
if ! git pull origin main --ff-only 2>&1 | sed 's/^/ /'; then
|
||||
echo " ✗ Git pull failed. Resolve conflicts manually in: $script_dir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local new_ver
|
||||
new_ver=$(python3 -c "import json; print(json.load(open('package.json'))['version'])" 2>/dev/null || echo "?")
|
||||
|
||||
if [[ "$old_ver" == "$new_ver" ]]; then
|
||||
echo " ✓ Already at latest (v$new_ver)"
|
||||
else
|
||||
echo " ✓ Updated v$old_ver → v$new_ver"
|
||||
fi
|
||||
|
||||
# 2. Sync plugin to extensions dir
|
||||
# Sync plugin (existing logic preserved)
|
||||
local ext_dir="$HOME/.openclaw/extensions/ocp"
|
||||
if [[ -d "$ext_dir" && -d "$script_dir/ocp-plugin" ]]; then
|
||||
echo ""
|
||||
echo " Syncing OCP plugin..."
|
||||
cp "$script_dir/ocp-plugin/index.js" "$ext_dir/index.js" 2>/dev/null
|
||||
cp "$script_dir/ocp-plugin/package.json" "$ext_dir/package.json" 2>/dev/null
|
||||
cp "$script_dir/ocp-plugin/openclaw.plugin.json" "$ext_dir/openclaw.plugin.json" 2>/dev/null
|
||||
echo " ✓ Plugin synced to $ext_dir"
|
||||
echo " ✓ Plugin synced"
|
||||
fi
|
||||
|
||||
# 3. Sync OpenClaw registry from models.json (non-fatal)
|
||||
if command -v node >/dev/null 2>&1 && [[ -f "$script_dir/scripts/sync-openclaw.mjs" ]]; then
|
||||
echo ""
|
||||
echo " Syncing OpenClaw registry..."
|
||||
if ! node "$script_dir/scripts/sync-openclaw.mjs" 2>&1 | sed 's/^/ /'; then
|
||||
echo " ⚠ OpenClaw sync failed (non-fatal, continuing)"
|
||||
fi
|
||||
node "$script_dir/scripts/sync-openclaw.mjs" 2>&1 | sed 's/^/ /' || echo " ⚠ OpenClaw sync failed (non-fatal)"
|
||||
fi
|
||||
|
||||
# 4. Restart proxy
|
||||
echo ""
|
||||
echo " Restarting proxy..."
|
||||
cmd_restart > /dev/null 2>&1
|
||||
sleep 2
|
||||
}
|
||||
|
||||
if curl -sf --max-time 5 "$PROXY/health" > /dev/null 2>&1; then
|
||||
local running_ver
|
||||
running_ver=$(curl -sf --max-time 5 "$PROXY/health" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['version'])" 2>/dev/null || echo "?")
|
||||
echo " ✓ Proxy running (v$running_ver)"
|
||||
else
|
||||
echo " ⚠ Proxy not responding — check: ocp health"
|
||||
fi
|
||||
cmd_doctor_help() {
|
||||
cat <<'EOF'
|
||||
ocp doctor — Health & upgrade-readiness check
|
||||
|
||||
echo ""
|
||||
echo "Done."
|
||||
Runs a series of checks (Node version, git state, service health,
|
||||
OAuth token, plist customisation, OpenClaw provider) and emits either
|
||||
human-readable PASS/WARN/FAIL output or a JSON next_action that
|
||||
AI agents can execute.
|
||||
|
||||
Usage:
|
||||
ocp doctor Human-readable output
|
||||
ocp doctor --json JSON for AI agents and ocp update internal use
|
||||
ocp doctor --check oauth Fast path: OAuth check only
|
||||
EOF
|
||||
}
|
||||
|
||||
cmd_doctor() {
|
||||
local script_dir self
|
||||
self="${BASH_SOURCE[0]}"
|
||||
while [[ -L "$self" ]]; do self="$(readlink "$self")"; done
|
||||
script_dir="$(cd "$(dirname "$self")" && pwd)"
|
||||
exec node "$script_dir/scripts/doctor.mjs" "$@"
|
||||
}
|
||||
|
||||
# ── help ─────────────────────────────────────────────────────────────────
|
||||
@@ -862,6 +902,7 @@ case "$subcmd" in
|
||||
lan) cmd_lan ;;
|
||||
connect) cmd_connect "$@" ;;
|
||||
restart) cmd_restart "${1:-}" ;;
|
||||
update) cmd_update "${1:-}" ;;
|
||||
doctor) cmd_doctor "$@" ;;
|
||||
update) cmd_update "$@" ;;
|
||||
*) echo "Unknown command: $subcmd"; echo ""; cmd_help; exit 1 ;;
|
||||
esac
|
||||
|
||||
+13
-3
@@ -582,11 +582,19 @@ print(k if k else '')
|
||||
if [[ "${SHELL:-}" == */fish ]]; then
|
||||
echo " Note: fish shell detected. Writing to ~/.bashrc — add to fish config manually."
|
||||
rc_files+=("$HOME/.bashrc")
|
||||
elif $is_mac; then
|
||||
# macOS: default shell since Catalina (2019) is zsh.
|
||||
# Always write ~/.zshrc (create if absent — zsh tolerates an empty file).
|
||||
# Only write ~/.bashrc if it already exists (don't surprise users with new files).
|
||||
[[ -f "$HOME/.bashrc" ]] && rc_files+=("$HOME/.bashrc")
|
||||
# zshrc: always include on macOS; create the file if it doesn't exist yet
|
||||
[[ -f "$HOME/.zshrc" ]] || touch "$HOME/.zshrc"
|
||||
rc_files+=("$HOME/.zshrc")
|
||||
else
|
||||
# Always write both on macOS (default shell is zsh but some tools source bashrc)
|
||||
# Linux / other: write to whichever rc files already exist or match current shell
|
||||
[[ -f "$HOME/.bashrc" || "${SHELL:-}" == */bash ]] && rc_files+=("$HOME/.bashrc")
|
||||
[[ -f "$HOME/.zshrc" || "${SHELL:-}" == */zsh ]] && rc_files+=("$HOME/.zshrc")
|
||||
# If neither exists, create for current shell
|
||||
# If neither exists, fall back to creating one for the current shell
|
||||
[[ ${#rc_files[@]} -eq 0 ]] && rc_files+=("$HOME/.${SHELL##*/}rc")
|
||||
fi
|
||||
|
||||
@@ -705,7 +713,9 @@ PYEOF
|
||||
|
||||
echo ""
|
||||
echo " Done. Reload your shell to apply:"
|
||||
echo " source $rc_file"
|
||||
for rc_file in "${rc_files[@]}"; do
|
||||
echo " source $rc_file"
|
||||
done
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
+13
-3
@@ -1,9 +1,19 @@
|
||||
/**
|
||||
* OCP Plugin — registers /ocp as a native slash command in OpenClaw gateway.
|
||||
* Calls the local claude-proxy at http://127.0.0.1:3456 and formats the response.
|
||||
* Calls the local claude-proxy and formats the response.
|
||||
*
|
||||
* Port resolution (in priority order):
|
||||
* 1. OCP_PROXY_URL env (full URL, e.g. http://10.0.0.5:3456)
|
||||
* 2. CLAUDE_PROXY_PORT env (port only; localhost assumed)
|
||||
* 3. Fallback: http://127.0.0.1:3456 (OCP server source default since v1.0)
|
||||
*
|
||||
* If a particular host's OCP plist injects a non-default CLAUDE_PROXY_PORT,
|
||||
* the OpenClaw launchd plist for that host must also inject the same
|
||||
* CLAUDE_PROXY_PORT into the plugin's env, or the plugin will fall back to
|
||||
* 3456 and miss the server.
|
||||
*/
|
||||
|
||||
const PROXY = "http://127.0.0.1:3456";
|
||||
const PROXY = process.env.OCP_PROXY_URL
|
||||
|| (process.env.CLAUDE_PROXY_PORT ? `http://127.0.0.1:${process.env.CLAUDE_PROXY_PORT}` : "http://127.0.0.1:3456");
|
||||
|
||||
// Wrap output in monospace code block for Telegram/Discord alignment
|
||||
function mono(text) { return "```\n" + text + "\n```"; }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "ocp",
|
||||
"name": "OCP Commands",
|
||||
"description": "Slash commands for the OpenClaw Proxy — /ocp usage, /ocp settings, /ocp health, etc.",
|
||||
"version": "3.12.0",
|
||||
"version": "3.16.2",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
@@ -10,7 +10,7 @@
|
||||
"proxyUrl": {
|
||||
"type": "string",
|
||||
"default": "http://127.0.0.1:3456",
|
||||
"description": "URL of the Claude proxy"
|
||||
"description": "URL of the Claude proxy. Overridable via OCP_PROXY_URL or CLAUDE_PROXY_PORT env."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
# openclaw-claude-proxy v2.3.0
|
||||
|
||||
Use your **Claude Pro / Max** subscription as an **OpenAI-compatible local endpoint**.
|
||||
|
||||
`openclaw-claude-proxy` accepts OpenAI-style chat completion requests, then runs them through the local `claude` CLI. That means tools which only know how to talk to an OpenAI API can still use Claude models through a local base URL.
|
||||
|
||||
## Why v2 matters
|
||||
|
||||
v2 is not just a bugfix release. It changes the runtime model:
|
||||
|
||||
- **On-demand spawning** instead of fragile warm pools
|
||||
- **Session resume** support for multi-turn conversations
|
||||
- **Faster fallback** with first-byte timeout + lower default request timeout
|
||||
- **Full tool access** via configurable allowed tools
|
||||
- **MCP config + system prompt pass-through**
|
||||
- **Health / sessions / diagnostics endpoints**
|
||||
- **Safe coexistence with Claude Code channel / interactive mode**
|
||||
|
||||
## The short pitch
|
||||
|
||||
If Claude's new channel workflow feels useful, OCP v2 now covers the same practical ground for many local agent/tooling setups:
|
||||
|
||||
- multi-turn continuity
|
||||
- tool-enabled Claude runs
|
||||
- local orchestration
|
||||
- stable process isolation
|
||||
- coexistence with your normal Claude Code workflow
|
||||
|
||||
And it adds a few advantages that channel users usually still want:
|
||||
|
||||
- **OpenAI-compatible HTTP API** for existing tools
|
||||
- **Works with OpenClaw, Cursor, Continue, Open WebUI, LangChain, and anything with custom base URL support**
|
||||
- **Explicit health checks and diagnostics**
|
||||
- **Model/provider failover can happen outside Claude itself**
|
||||
- **No lock-in to a single client UX**
|
||||
|
||||
## Coexistence with Claude Code channel
|
||||
|
||||
This is the important part: **OCP v2 does not replace Claude Code channel, and it does not need to. They can coexist on the same machine.**
|
||||
|
||||
### Claude Code channel / interactive mode
|
||||
- persistent interactive workflow
|
||||
- MCP protocol / in-process experience
|
||||
- great when you are directly driving Claude Code
|
||||
|
||||
### OCP v2
|
||||
- local HTTP server on `localhost`
|
||||
- OpenAI-compatible API surface
|
||||
- per-request `claude -p` execution with session resume when you want continuity
|
||||
- ideal for external tools, routers, orchestrators, OpenClaw providers, and local automation
|
||||
|
||||
### Practical takeaway
|
||||
Use both:
|
||||
- use **Claude Code channel** when you want Claude's native interactive workflow
|
||||
- use **OCP v2** when another app expects an OpenAI-style API but you still want to use Claude
|
||||
|
||||
They solve adjacent problems, not identical ones.
|
||||
|
||||
## Unique advantages of OCP v2
|
||||
|
||||
1. **API compatibility**
|
||||
- Drop into tools that already support OpenAI-compatible endpoints.
|
||||
- No need to wait for each tool to add native Claude channel support.
|
||||
|
||||
2. **Routing freedom**
|
||||
- Put OCP behind OpenClaw or another router.
|
||||
- Mix Claude with fallback providers outside the Claude client itself.
|
||||
|
||||
3. **Operational visibility**
|
||||
- `/health`, `/sessions`, recent errors, auth state, resolved binary path, timeout config.
|
||||
- Much easier to debug than a black-box local integration.
|
||||
|
||||
4. **Safer runtime model**
|
||||
- v2 removes the old pre-spawn pool crash loop.
|
||||
- No stale workers, no degraded warm pool states, fewer hidden failure modes.
|
||||
|
||||
5. **Configurable tools and behavior**
|
||||
- allowed tools
|
||||
- skip permissions mode
|
||||
- system prompt append
|
||||
- MCP config passthrough
|
||||
- session TTL
|
||||
- concurrency limits
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
git clone https://github.com/dtzp555-max/openclaw-claude-proxy
|
||||
cd openclaw-claude-proxy
|
||||
npm install
|
||||
node server.mjs
|
||||
```
|
||||
|
||||
Default base URL:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:3456/v1
|
||||
```
|
||||
|
||||
## Quick OpenAI-compatible config
|
||||
|
||||
```json
|
||||
{
|
||||
"baseURL": "http://127.0.0.1:3456/v1",
|
||||
"apiKey": "anything"
|
||||
}
|
||||
```
|
||||
|
||||
If `PROXY_API_KEY` is unset, auth is disabled. If you set it, pass it as a Bearer token.
|
||||
|
||||
## Environment variables
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
|---|---:|---|
|
||||
| `CLAUDE_PROXY_PORT` | `3456` | Listen port |
|
||||
| `CLAUDE_BIN` | auto-detect | Claude CLI binary path |
|
||||
| `CLAUDE_TIMEOUT` | `120000` | Overall per-request timeout |
|
||||
| `CLAUDE_FIRST_BYTE_TIMEOUT` | `30000` | Abort if Claude produces no stdout quickly |
|
||||
| `CLAUDE_ALLOWED_TOOLS` | expanded set | Comma-separated allowed tools |
|
||||
| `CLAUDE_SKIP_PERMISSIONS` | `false` | Bypass permission checks |
|
||||
| `CLAUDE_SYSTEM_PROMPT` | unset | Append a system prompt to every request |
|
||||
| `CLAUDE_MCP_CONFIG` | unset | Path to MCP config JSON |
|
||||
| `CLAUDE_SESSION_TTL` | `3600000` | Session TTL |
|
||||
| `CLAUDE_MAX_CONCURRENT` | `5` | Max concurrent Claude processes |
|
||||
| `PROXY_API_KEY` | unset | Optional Bearer token auth |
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `GET /health`
|
||||
- `GET /v1/models`
|
||||
- `POST /v1/chat/completions`
|
||||
- `GET /sessions`
|
||||
- `DELETE /sessions`
|
||||
|
||||
## Example health response highlights
|
||||
|
||||
`/health` reports useful operational state such as:
|
||||
|
||||
- resolved Claude binary path
|
||||
- whether the binary is executable
|
||||
- auth status
|
||||
- timeouts
|
||||
- current sessions
|
||||
- recent errors
|
||||
- basic request stats
|
||||
|
||||
## Version highlights
|
||||
|
||||
### v2.3.0
|
||||
- clarified v2 positioning and coexistence story in docs
|
||||
- officially documents faster fallback defaults
|
||||
- recommends OCP v2 as the API bridge layer for Claude-powered tools
|
||||
|
||||
### v2.2.0
|
||||
- first-byte timeout
|
||||
- reduced default timeout for faster fallback
|
||||
|
||||
### v2.0.0
|
||||
- on-demand architecture
|
||||
- session management
|
||||
- full tool access
|
||||
- MCP + system prompt passthrough
|
||||
- concurrency control
|
||||
- coexistence with Claude Code interactive mode
|
||||
|
||||
## When to use OCP v2 vs Claude channel
|
||||
|
||||
Choose **OCP v2** when:
|
||||
- your app only supports OpenAI-compatible endpoints
|
||||
- you want routing / failover outside Claude
|
||||
- you want explicit health checks and local diagnostics
|
||||
- you want Claude available to multiple local tools through one endpoint
|
||||
|
||||
Choose **Claude channel** when:
|
||||
- you are primarily living inside Claude Code itself
|
||||
- you want Claude's native interactive workflow directly
|
||||
|
||||
Use **both together** when you want the best of both worlds.
|
||||
|
||||
---
|
||||
|
||||
If you already pay for Claude Pro or Max, OCP v2 turns that subscription into a practical local API bridge for the rest of your tooling stack.
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "openclaw-claude-proxy",
|
||||
"version": "2.4.0",
|
||||
"description": "OpenAI-compatible proxy for Claude CLI v2 — per-model circuit breaker, adaptive first-byte timeout, structured logging",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"openclaw-claude-proxy": "./server.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node server.mjs",
|
||||
"setup": "node setup.mjs"
|
||||
},
|
||||
"keywords": [
|
||||
"openclaw",
|
||||
"claude",
|
||||
"proxy",
|
||||
"openai",
|
||||
"anthropic"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/dtzp555-max/openclaw-claude-proxy"
|
||||
}
|
||||
}
|
||||
@@ -1,643 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* openclaw-claude-proxy v2.4.0 — OpenAI-compatible proxy for Claude CLI
|
||||
*
|
||||
* Translates OpenAI chat/completions requests into `claude -p` CLI calls,
|
||||
* letting you use your Claude Pro/Max subscription as an OpenClaw model provider.
|
||||
*
|
||||
* v2.4.0:
|
||||
* - Per-model circuit breaker: consecutive timeouts temporarily mark a model as degraded
|
||||
* - Adaptive first-byte timeout: scales by model tier + prompt size
|
||||
* - Structured JSON logging for key events (easier to parse/alert on)
|
||||
* - On-demand spawning (no pool), session management, full tool access
|
||||
*
|
||||
* Env vars:
|
||||
* CLAUDE_PROXY_PORT — listen port (default: 3456)
|
||||
* CLAUDE_BIN — path to claude binary (default: auto-detect)
|
||||
* CLAUDE_TIMEOUT — per-request timeout in ms (default: 120000)
|
||||
* CLAUDE_FIRST_BYTE_TIMEOUT — base first-byte timeout in ms (default: 45000)
|
||||
* CLAUDE_ALLOWED_TOOLS — comma-separated tools to allow (default: expanded set)
|
||||
* CLAUDE_SKIP_PERMISSIONS — "true" to bypass all permission checks (default: false)
|
||||
* CLAUDE_SYSTEM_PROMPT — system prompt appended to all requests
|
||||
* CLAUDE_MCP_CONFIG — path to MCP server config JSON file
|
||||
* CLAUDE_SESSION_TTL — session TTL in ms (default: 3600000 = 1h)
|
||||
* CLAUDE_MAX_CONCURRENT — max concurrent claude processes (default: 5)
|
||||
* CLAUDE_BREAKER_THRESHOLD — consecutive timeouts before circuit opens (default: 3)
|
||||
* CLAUDE_BREAKER_COOLDOWN — ms to wait before retrying after circuit opens (default: 60000)
|
||||
* PROXY_API_KEY — Bearer token for API auth (optional)
|
||||
*/
|
||||
import { createServer } from "node:http";
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFileSync, accessSync, constants } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const _pkg = JSON.parse(readFileSync(join(__dirname, "package.json"), "utf8"));
|
||||
|
||||
// ── Resolve claude binary ───────────────────────────────────────────────
|
||||
// Priority: CLAUDE_BIN env > well-known paths > which lookup
|
||||
// Fail-fast if not found — never start with an unresolvable binary.
|
||||
function resolveClaude() {
|
||||
if (process.env.CLAUDE_BIN) {
|
||||
try {
|
||||
accessSync(process.env.CLAUDE_BIN, constants.X_OK);
|
||||
return process.env.CLAUDE_BIN;
|
||||
} catch {
|
||||
console.error(`FATAL: CLAUDE_BIN="${process.env.CLAUDE_BIN}" is set but not executable.`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const candidates = [
|
||||
"/opt/homebrew/bin/claude",
|
||||
"/usr/local/bin/claude",
|
||||
"/usr/bin/claude",
|
||||
join(process.env.HOME || "", ".local/bin/claude"),
|
||||
];
|
||||
for (const p of candidates) {
|
||||
try { accessSync(p, constants.X_OK); console.warn(`[init] CLAUDE_BIN not set, resolved to ${p}`); return p; } catch {}
|
||||
}
|
||||
|
||||
try {
|
||||
const resolved = execFileSync("which", ["claude"], { encoding: "utf8", timeout: 5000 }).trim();
|
||||
if (resolved) { console.warn(`[init] CLAUDE_BIN not set, resolved via which: ${resolved}`); return resolved; }
|
||||
} catch {}
|
||||
|
||||
console.error(
|
||||
"FATAL: claude binary not found.\n" +
|
||||
" Set CLAUDE_BIN=/path/to/claude or ensure claude is in PATH.\n" +
|
||||
" Checked: " + candidates.join(", ")
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ── Configuration ───────────────────────────────────────────────────────
|
||||
const PORT = parseInt(process.env.CLAUDE_PROXY_PORT || "3456", 10);
|
||||
const CLAUDE = resolveClaude();
|
||||
const TIMEOUT = parseInt(process.env.CLAUDE_TIMEOUT || "120000", 10);
|
||||
const BASE_FIRST_BYTE_TIMEOUT = parseInt(process.env.CLAUDE_FIRST_BYTE_TIMEOUT || "45000", 10);
|
||||
const PROXY_API_KEY = process.env.PROXY_API_KEY || "";
|
||||
const SKIP_PERMISSIONS = process.env.CLAUDE_SKIP_PERMISSIONS === "true";
|
||||
const ALLOWED_TOOLS = (process.env.CLAUDE_ALLOWED_TOOLS ||
|
||||
"Bash,Read,Write,Edit,Glob,Grep,WebSearch,WebFetch,Agent"
|
||||
).split(",").map(s => s.trim()).filter(Boolean);
|
||||
const SYSTEM_PROMPT = process.env.CLAUDE_SYSTEM_PROMPT || "";
|
||||
const MCP_CONFIG = process.env.CLAUDE_MCP_CONFIG || "";
|
||||
const SESSION_TTL = parseInt(process.env.CLAUDE_SESSION_TTL || "3600000", 10);
|
||||
const MAX_CONCURRENT = parseInt(process.env.CLAUDE_MAX_CONCURRENT || "5", 10);
|
||||
const BREAKER_THRESHOLD = parseInt(process.env.CLAUDE_BREAKER_THRESHOLD || "3", 10);
|
||||
const BREAKER_COOLDOWN = parseInt(process.env.CLAUDE_BREAKER_COOLDOWN || "60000", 10);
|
||||
|
||||
const VERSION = _pkg.version;
|
||||
const START_TIME = Date.now();
|
||||
|
||||
// ── Structured logging helper ───────────────────────────────────────────
|
||||
function logEvent(level, event, data = {}) {
|
||||
const entry = { ts: new Date().toISOString(), level, event, ...data };
|
||||
if (level === "error" || level === "warn") {
|
||||
console.error(JSON.stringify(entry));
|
||||
} else {
|
||||
console.log(JSON.stringify(entry));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Per-model circuit breaker ───────────────────────────────────────────
|
||||
// Tracks consecutive timeouts per model. When threshold is reached, the
|
||||
// model is marked "open" (degraded) for BREAKER_COOLDOWN ms. During that
|
||||
// window, requests for this model fail fast with a clear error instead of
|
||||
// waiting for yet another timeout that would block the gateway.
|
||||
const breakers = new Map(); // cliModel → { failures, state, openedAt }
|
||||
|
||||
function getBreakerState(cliModel) {
|
||||
if (!breakers.has(cliModel)) {
|
||||
breakers.set(cliModel, { failures: 0, state: "closed", openedAt: 0 });
|
||||
}
|
||||
const b = breakers.get(cliModel);
|
||||
|
||||
// Auto-recover: if cooldown has elapsed, transition to half-open
|
||||
if (b.state === "open" && Date.now() - b.openedAt >= BREAKER_COOLDOWN) {
|
||||
b.state = "half-open";
|
||||
logEvent("info", "breaker_half_open", { model: cliModel, cooldownMs: BREAKER_COOLDOWN });
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
function breakerRecordSuccess(cliModel) {
|
||||
const b = getBreakerState(cliModel);
|
||||
if (b.failures > 0 || b.state !== "closed") {
|
||||
logEvent("info", "breaker_reset", { model: cliModel, previousFailures: b.failures, previousState: b.state });
|
||||
}
|
||||
b.failures = 0;
|
||||
b.state = "closed";
|
||||
b.openedAt = 0;
|
||||
}
|
||||
|
||||
function breakerRecordTimeout(cliModel) {
|
||||
const b = getBreakerState(cliModel);
|
||||
b.failures++;
|
||||
logEvent("warn", "breaker_failure", { model: cliModel, consecutiveFailures: b.failures, threshold: BREAKER_THRESHOLD });
|
||||
|
||||
if (b.failures >= BREAKER_THRESHOLD && b.state !== "open") {
|
||||
b.state = "open";
|
||||
b.openedAt = Date.now();
|
||||
logEvent("error", "breaker_open", { model: cliModel, failures: b.failures, cooldownMs: BREAKER_COOLDOWN });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Model mapping ───────────────────────────────────────────────────────
|
||||
// Maps request model IDs and aliases to canonical claude CLI model IDs.
|
||||
const MODEL_MAP = {
|
||||
"claude-opus-4-6": "claude-opus-4-6",
|
||||
"claude-sonnet-4-6": "claude-sonnet-4-6",
|
||||
"claude-haiku-4-5-20251001": "claude-haiku-4-5-20251001",
|
||||
"claude-opus-4": "claude-opus-4-6",
|
||||
"claude-haiku-4": "claude-haiku-4-5-20251001",
|
||||
"claude-haiku-4-5": "claude-haiku-4-5-20251001",
|
||||
"opus": "claude-opus-4-6",
|
||||
"sonnet": "claude-sonnet-4-6",
|
||||
"haiku": "claude-haiku-4-5-20251001",
|
||||
};
|
||||
|
||||
const MODELS = [
|
||||
{ id: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5" },
|
||||
];
|
||||
|
||||
// ── Session management ──────────────────────────────────────────────────
|
||||
// Maps conversation IDs (from caller) to Claude CLI session UUIDs.
|
||||
// Enables --resume for multi-turn conversations, reducing token waste.
|
||||
const sessions = new Map(); // conversationId → { uuid, messageCount, lastUsed, model }
|
||||
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [id, s] of sessions) {
|
||||
if (now - s.lastUsed > SESSION_TTL) {
|
||||
sessions.delete(id);
|
||||
console.log(`[session] expired ${id.slice(0, 12)}... (idle ${Math.round((now - s.lastUsed) / 60000)}m)`);
|
||||
}
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
// ── Stats & diagnostics ─────────────────────────────────────────────────
|
||||
const stats = {
|
||||
totalRequests: 0,
|
||||
activeRequests: 0,
|
||||
errors: 0,
|
||||
timeouts: 0,
|
||||
sessionHits: 0,
|
||||
sessionMisses: 0,
|
||||
oneOffRequests: 0,
|
||||
};
|
||||
const recentErrors = []; // last 20 errors
|
||||
|
||||
function trackError(msg) {
|
||||
stats.errors++;
|
||||
recentErrors.push({ time: new Date().toISOString(), message: String(msg).slice(0, 200) });
|
||||
if (recentErrors.length > 20) recentErrors.shift();
|
||||
}
|
||||
|
||||
// ── Auth health check ───────────────────────────────────────────────────
|
||||
let authStatus = { ok: null, lastCheck: 0, message: "" };
|
||||
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const env = { ...process.env };
|
||||
delete env.CLAUDECODE;
|
||||
delete env.ANTHROPIC_API_KEY;
|
||||
delete env.ANTHROPIC_BASE_URL;
|
||||
delete env.ANTHROPIC_AUTH_TOKEN;
|
||||
execFileSync(CLAUDE, ["auth", "status"], { encoding: "utf8", timeout: 10000, env });
|
||||
authStatus = { ok: true, lastCheck: Date.now(), message: "authenticated" };
|
||||
} catch (e) {
|
||||
const msg = (e.stderr || e.message || "").slice(0, 200);
|
||||
authStatus = { ok: false, lastCheck: Date.now(), message: msg };
|
||||
console.error(`[auth] check failed: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check auth on start and every 10 minutes
|
||||
checkAuth();
|
||||
setInterval(checkAuth, 600000);
|
||||
|
||||
// ── Build CLI arguments ─────────────────────────────────────────────────
|
||||
function buildCliArgs(cliModel, sessionInfo) {
|
||||
const args = ["-p", "--model", cliModel, "--output-format", "text"];
|
||||
|
||||
// Session handling
|
||||
if (sessionInfo?.resume) {
|
||||
args.push("--resume", sessionInfo.uuid);
|
||||
} else if (sessionInfo?.uuid) {
|
||||
args.push("--session-id", sessionInfo.uuid);
|
||||
} else {
|
||||
args.push("--no-session-persistence");
|
||||
}
|
||||
|
||||
// Permissions
|
||||
if (SKIP_PERMISSIONS) {
|
||||
args.push("--dangerously-skip-permissions");
|
||||
} else if (ALLOWED_TOOLS.length > 0) {
|
||||
args.push("--allowedTools", ...ALLOWED_TOOLS);
|
||||
}
|
||||
|
||||
// System prompt
|
||||
if (SYSTEM_PROMPT) {
|
||||
args.push("--append-system-prompt", SYSTEM_PROMPT);
|
||||
}
|
||||
|
||||
// MCP config
|
||||
if (MCP_CONFIG) {
|
||||
args.push("--mcp-config", MCP_CONFIG);
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
// ── Format messages to prompt text ──────────────────────────────────────
|
||||
function messagesToPrompt(messages) {
|
||||
return messages.map((m) => {
|
||||
const text = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
|
||||
if (m.role === "system") return `[System] ${text}`;
|
||||
if (m.role === "assistant") return `[Assistant] ${text}`;
|
||||
return text;
|
||||
}).join("\n\n");
|
||||
}
|
||||
|
||||
// Model tier multipliers for first-byte timeout.
|
||||
// Opus is much slower to produce first token, especially with large contexts.
|
||||
const MODEL_TIMEOUT_TIERS = {
|
||||
"opus": { base: 60000, perPromptChar: 0.00015 }, // 60s base + ~15s per 100k chars
|
||||
"sonnet": { base: 45000, perPromptChar: 0.00008 }, // 45s base + ~8s per 100k chars
|
||||
"haiku": { base: 30000, perPromptChar: 0.00005 }, // 30s base + ~5s per 100k chars
|
||||
};
|
||||
|
||||
function getModelTier(cliModel) {
|
||||
if (cliModel.includes("opus")) return "opus";
|
||||
if (cliModel.includes("haiku")) return "haiku";
|
||||
return "sonnet";
|
||||
}
|
||||
|
||||
function computeFirstByteTimeout(cliModel, promptLength) {
|
||||
const tier = MODEL_TIMEOUT_TIERS[getModelTier(cliModel)];
|
||||
const timeout = tier.base + Math.floor(promptLength * tier.perPromptChar);
|
||||
return Math.min(timeout, Math.max(TIMEOUT - 5000, 10000));
|
||||
}
|
||||
|
||||
// ── Call claude CLI ─────────────────────────────────────────────────────
|
||||
// On-demand spawning: each request spawns a fresh `claude -p` process.
|
||||
// No pool = no crash loops, no stale workers, no degraded states.
|
||||
// Stdin is written immediately so there's no 3s stdin timeout issue.
|
||||
function callClaude(model, messages, conversationId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (stats.activeRequests >= MAX_CONCURRENT) {
|
||||
return reject(new Error(`concurrency limit reached (${stats.activeRequests}/${MAX_CONCURRENT})`));
|
||||
}
|
||||
|
||||
const cliModel = MODEL_MAP[model] || model;
|
||||
|
||||
// Circuit breaker check: fail fast if model is in open state
|
||||
const breaker = getBreakerState(cliModel);
|
||||
if (breaker.state === "open") {
|
||||
const remainingMs = BREAKER_COOLDOWN - (Date.now() - breaker.openedAt);
|
||||
logEvent("warn", "breaker_rejected", { model: cliModel, remainingCooldownMs: remainingMs });
|
||||
return reject(new Error(`circuit breaker open for ${cliModel}: ${breaker.failures} consecutive timeouts, retry in ${Math.ceil(remainingMs / 1000)}s`));
|
||||
}
|
||||
|
||||
stats.activeRequests++;
|
||||
stats.totalRequests++;
|
||||
|
||||
let sessionInfo = null;
|
||||
let prompt;
|
||||
|
||||
// ── Session logic ──
|
||||
if (conversationId && sessions.has(conversationId)) {
|
||||
// Resume existing session: only send the latest user message
|
||||
const session = sessions.get(conversationId);
|
||||
session.lastUsed = Date.now();
|
||||
sessionInfo = { uuid: session.uuid, resume: true };
|
||||
stats.sessionHits++;
|
||||
|
||||
const lastUserMsg = [...messages].reverse().find((m) => m.role === "user");
|
||||
prompt = lastUserMsg
|
||||
? (typeof lastUserMsg.content === "string" ? lastUserMsg.content : JSON.stringify(lastUserMsg.content))
|
||||
: "";
|
||||
session.messageCount = messages.length;
|
||||
|
||||
console.log(`[session] resume conv=${conversationId.slice(0, 12)}... uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`);
|
||||
|
||||
} else if (conversationId) {
|
||||
// New session: send all messages, persist session for future --resume
|
||||
const uuid = randomUUID();
|
||||
sessions.set(conversationId, { uuid, messageCount: messages.length, lastUsed: Date.now(), model: cliModel });
|
||||
sessionInfo = { uuid, resume: false };
|
||||
stats.sessionMisses++;
|
||||
prompt = messagesToPrompt(messages);
|
||||
|
||||
console.log(`[session] new conv=${conversationId.slice(0, 12)}... uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`);
|
||||
|
||||
} else {
|
||||
// One-off request, no session
|
||||
stats.oneOffRequests++;
|
||||
prompt = messagesToPrompt(messages);
|
||||
}
|
||||
|
||||
const cliArgs = buildCliArgs(cliModel, sessionInfo);
|
||||
|
||||
const env = { ...process.env };
|
||||
delete env.CLAUDECODE;
|
||||
delete env.ANTHROPIC_API_KEY;
|
||||
delete env.ANTHROPIC_BASE_URL;
|
||||
delete env.ANTHROPIC_AUTH_TOKEN;
|
||||
|
||||
const proc = spawn(CLAUDE, cliArgs, { env, stdio: ["pipe", "pipe", "pipe"] });
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
const t0 = Date.now();
|
||||
const firstByteTimeoutMs = computeFirstByteTimeout(cliModel, prompt.length);
|
||||
let settled = false;
|
||||
let gotFirstByte = false;
|
||||
|
||||
function settle(err, result) {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(firstByteTimer);
|
||||
stats.activeRequests--;
|
||||
|
||||
if (err) {
|
||||
trackError(err.message || String(err));
|
||||
|
||||
// If session resume failed, remove session so next request starts fresh
|
||||
if (sessionInfo?.resume && conversationId) {
|
||||
console.warn(`[session] resume failed for ${conversationId.slice(0, 12)}..., removing stale session`);
|
||||
sessions.delete(conversationId);
|
||||
}
|
||||
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
|
||||
proc.stdout.on("data", (d) => {
|
||||
if (!gotFirstByte) {
|
||||
gotFirstByte = true;
|
||||
clearTimeout(firstByteTimer);
|
||||
console.log(`[claude] first-byte model=${cliModel} elapsed=${Date.now() - t0}ms`);
|
||||
}
|
||||
stdout += d;
|
||||
});
|
||||
proc.stderr.on("data", (d) => (stderr += d));
|
||||
|
||||
proc.on("close", (code, signal) => {
|
||||
const elapsed = Date.now() - t0;
|
||||
if (settled) {
|
||||
logEvent("warn", "late_close", { model: cliModel, code, signal: signal || "none", elapsed });
|
||||
return;
|
||||
}
|
||||
if (code !== 0) {
|
||||
logEvent("error", "claude_exit", { model: cliModel, code, signal: signal || "none", elapsed, stderr: stderr.slice(0, 300) });
|
||||
settle(new Error(stderr.slice(0, 300) || stdout.slice(0, 300) || `claude exit ${code}`));
|
||||
} else {
|
||||
breakerRecordSuccess(cliModel);
|
||||
logEvent("info", "claude_ok", { model: cliModel, chars: stdout.length, elapsed, session: conversationId ? conversationId.slice(0, 12) + "..." : "none" });
|
||||
settle(null, stdout.trim());
|
||||
}
|
||||
});
|
||||
|
||||
proc.on("error", (err) => {
|
||||
console.error(`[claude] spawn error: ${err.message}`);
|
||||
settle(err);
|
||||
});
|
||||
|
||||
// Write prompt to stdin immediately — no idle timeout issue
|
||||
proc.stdin.write(prompt);
|
||||
proc.stdin.end();
|
||||
|
||||
logEvent("info", "claude_spawned", { model: cliModel, promptChars: prompt.length, firstByteTimeout: firstByteTimeoutMs, tier: getModelTier(cliModel), session: conversationId ? conversationId.slice(0, 12) + "..." : "none" });
|
||||
|
||||
// First-byte timeout: abort early if Claude CLI produces no output
|
||||
const firstByteTimer = setTimeout(() => {
|
||||
if (!gotFirstByte && !settled) {
|
||||
stats.timeouts++;
|
||||
breakerRecordTimeout(cliModel);
|
||||
logEvent("error", "first_byte_timeout", { model: cliModel, timeoutMs: firstByteTimeoutMs, promptChars: prompt.length });
|
||||
try { proc.kill("SIGTERM"); } catch {}
|
||||
setTimeout(() => { try { proc.kill("SIGKILL"); } catch {} }, 5000);
|
||||
settle(new Error(`first-byte timeout after ${firstByteTimeoutMs}ms`));
|
||||
}
|
||||
}, firstByteTimeoutMs);
|
||||
|
||||
// Overall request timeout with graceful kill
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
stats.timeouts++;
|
||||
breakerRecordTimeout(cliModel);
|
||||
logEvent("error", "request_timeout", { model: cliModel, timeoutMs: TIMEOUT });
|
||||
try { proc.kill("SIGTERM"); } catch {}
|
||||
setTimeout(() => { try { proc.kill("SIGKILL"); } catch {} }, 5000);
|
||||
settle(new Error(`timeout after ${TIMEOUT}ms`));
|
||||
}, TIMEOUT);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Response helpers ────────────────────────────────────────────────────
|
||||
function jsonResponse(res, status, data) {
|
||||
if (res.headersSent || res.writableEnded || res.destroyed) return;
|
||||
res.writeHead(status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(data));
|
||||
}
|
||||
|
||||
function sendSSE(res, data) {
|
||||
res.write(`data: ${JSON.stringify(data)}\n\n`);
|
||||
}
|
||||
|
||||
function streamResponse(res, id, model, content) {
|
||||
if (res.headersSent || res.writableEnded || res.destroyed) return;
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
});
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
sendSSE(res, {
|
||||
id, object: "chat.completion.chunk", created, model,
|
||||
choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
|
||||
});
|
||||
for (let i = 0; i < content.length; i += 500) {
|
||||
sendSSE(res, {
|
||||
id, object: "chat.completion.chunk", created, model,
|
||||
choices: [{ index: 0, delta: { content: content.slice(i, i + 500) }, finish_reason: null }],
|
||||
});
|
||||
}
|
||||
sendSSE(res, {
|
||||
id, object: "chat.completion.chunk", created, model,
|
||||
choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
|
||||
});
|
||||
res.write("data: [DONE]\n\n");
|
||||
res.end();
|
||||
}
|
||||
|
||||
function completionResponse(res, id, model, content) {
|
||||
jsonResponse(res, 200, {
|
||||
id, object: "chat.completion",
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model,
|
||||
choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: "stop" }],
|
||||
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
|
||||
});
|
||||
}
|
||||
|
||||
// ── Handle chat completions ─────────────────────────────────────────────
|
||||
async function handleChatCompletions(req, res) {
|
||||
let body = "";
|
||||
for await (const chunk of req) body += chunk;
|
||||
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(body); } catch { return jsonResponse(res, 400, { error: "Invalid JSON" }); }
|
||||
|
||||
const messages = parsed.messages || parsed.input || [{ role: "user", content: parsed.prompt || "" }];
|
||||
const model = parsed.model || "claude-sonnet-4-6";
|
||||
const stream = parsed.stream;
|
||||
|
||||
// Session ID: from request body, header, or null (one-off)
|
||||
const conversationId = parsed.session_id || parsed.conversation_id || req.headers["x-session-id"] || req.headers["x-conversation-id"] || null;
|
||||
|
||||
if (!messages?.length) return jsonResponse(res, 400, { error: "messages required" });
|
||||
|
||||
try {
|
||||
const content = await callClaude(model, messages, conversationId);
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
|
||||
if (stream) {
|
||||
streamResponse(res, id, model, content);
|
||||
} else {
|
||||
completionResponse(res, id, model, content);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[proxy] error: ${err.message}`);
|
||||
if (res.headersSent || res.writableEnded || res.destroyed) {
|
||||
try { res.end(); } catch {}
|
||||
return;
|
||||
}
|
||||
jsonResponse(res, 500, { error: { message: err.message, type: "proxy_error" } });
|
||||
}
|
||||
}
|
||||
|
||||
// ── HTTP server ─────────────────────────────────────────────────────────
|
||||
const server = createServer(async (req, res) => {
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Session-Id, X-Conversation-Id");
|
||||
if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; }
|
||||
|
||||
// Bearer token auth (skip for /health and when PROXY_API_KEY is not set)
|
||||
if (PROXY_API_KEY && req.url !== "/health") {
|
||||
const auth = req.headers["authorization"] || "";
|
||||
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
||||
if (token !== PROXY_API_KEY) {
|
||||
return jsonResponse(res, 401, { error: { message: "Unauthorized: invalid or missing Bearer token", type: "auth_error" } });
|
||||
}
|
||||
}
|
||||
|
||||
// GET /v1/models
|
||||
if (req.url === "/v1/models" && req.method === "GET") {
|
||||
return jsonResponse(res, 200, {
|
||||
object: "list",
|
||||
data: MODELS.map((m) => ({
|
||||
id: m.id, object: "model", owned_by: "anthropic",
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
// POST /v1/chat/completions
|
||||
if (req.url === "/v1/chat/completions" && req.method === "POST") {
|
||||
return handleChatCompletions(req, res);
|
||||
}
|
||||
|
||||
// GET /health — comprehensive diagnostics
|
||||
if (req.url === "/health") {
|
||||
let binaryOk = false;
|
||||
try { accessSync(CLAUDE, constants.X_OK); binaryOk = true; } catch {}
|
||||
|
||||
const uptimeMs = Date.now() - START_TIME;
|
||||
const sessionList = [];
|
||||
for (const [id, s] of sessions) {
|
||||
sessionList.push({
|
||||
id: id.slice(0, 12) + "...",
|
||||
model: s.model,
|
||||
messages: s.messageCount,
|
||||
idleMs: Date.now() - s.lastUsed,
|
||||
});
|
||||
}
|
||||
|
||||
return jsonResponse(res, 200, {
|
||||
status: binaryOk && authStatus.ok !== false ? "ok" : "degraded",
|
||||
version: VERSION,
|
||||
architecture: "on-demand (v2)",
|
||||
uptime: uptimeMs,
|
||||
uptimeHuman: `${Math.floor(uptimeMs / 3600000)}h ${Math.floor((uptimeMs % 3600000) / 60000)}m`,
|
||||
claudeBinary: CLAUDE,
|
||||
claudeBinaryOk: binaryOk,
|
||||
auth: authStatus,
|
||||
config: {
|
||||
timeout: TIMEOUT,
|
||||
firstByteTimeout: BASE_FIRST_BYTE_TIMEOUT,
|
||||
maxConcurrent: MAX_CONCURRENT,
|
||||
sessionTTL: SESSION_TTL,
|
||||
allowedTools: SKIP_PERMISSIONS ? "all (skip-permissions)" : ALLOWED_TOOLS,
|
||||
systemPrompt: SYSTEM_PROMPT ? `${SYSTEM_PROMPT.slice(0, 50)}...` : "(none)",
|
||||
mcpConfig: MCP_CONFIG || "(none)",
|
||||
},
|
||||
stats,
|
||||
sessions: sessionList,
|
||||
recentErrors: recentErrors.slice(-5),
|
||||
});
|
||||
}
|
||||
|
||||
// DELETE /sessions — clear all sessions
|
||||
if (req.url === "/sessions" && req.method === "DELETE") {
|
||||
const count = sessions.size;
|
||||
sessions.clear();
|
||||
return jsonResponse(res, 200, { cleared: count });
|
||||
}
|
||||
|
||||
// GET /sessions — list active sessions
|
||||
if (req.url === "/sessions" && req.method === "GET") {
|
||||
const list = [];
|
||||
for (const [id, s] of sessions) {
|
||||
list.push({ id, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() });
|
||||
}
|
||||
return jsonResponse(res, 200, { sessions: list });
|
||||
}
|
||||
|
||||
// Catch-all POST
|
||||
if (req.method === "POST") {
|
||||
return handleChatCompletions(req, res);
|
||||
}
|
||||
|
||||
jsonResponse(res, 404, { error: "Not found. Endpoints: GET /v1/models, POST /v1/chat/completions, GET /health, GET|DELETE /sessions" });
|
||||
});
|
||||
|
||||
// ── Start ───────────────────────────────────────────────────────────────
|
||||
server.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`openclaw-claude-proxy v${VERSION} listening on http://0.0.0.0:${PORT}`);
|
||||
console.log(`Architecture: on-demand spawning (no pool)`);
|
||||
console.log(`Models: ${MODELS.map((m) => m.id).join(", ")}`);
|
||||
console.log(`Claude binary: ${CLAUDE}`);
|
||||
console.log(`Timeout: ${TIMEOUT}ms (base first-byte: ${BASE_FIRST_BYTE_TIMEOUT}ms, adaptive by model/prompt) | Max concurrent: ${MAX_CONCURRENT}`);
|
||||
console.log(`Tools: ${SKIP_PERMISSIONS ? "all (skip-permissions)" : ALLOWED_TOOLS.join(", ")}`);
|
||||
console.log(`Sessions: TTL=${SESSION_TTL / 1000}s`);
|
||||
if (SYSTEM_PROMPT) console.log(`System prompt: "${SYSTEM_PROMPT.slice(0, 80)}..."`);
|
||||
if (MCP_CONFIG) console.log(`MCP config: ${MCP_CONFIG}`);
|
||||
console.log(`Auth: ${PROXY_API_KEY ? "enabled (PROXY_API_KEY set)" : "disabled (no PROXY_API_KEY)"}`);
|
||||
console.log(`---`);
|
||||
console.log(`Coexistence: This proxy does NOT conflict with Claude Code interactive mode.`);
|
||||
console.log(` OCP uses: localhost:${PORT} (HTTP) → claude -p (per-request process)`);
|
||||
console.log(` CC uses: MCP protocol (in-process) → persistent session`);
|
||||
console.log(` Both can run simultaneously on the same machine.`);
|
||||
});
|
||||
Generated
-20
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"name": "openclaw-claude-proxy",
|
||||
"version": "3.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "openclaw-claude-proxy",
|
||||
"version": "3.4.0",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"ocp": "ocp",
|
||||
"openclaw-claude-proxy": "server.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "openclaw-claude-proxy",
|
||||
"version": "3.12.0",
|
||||
"name": "open-claude-proxy",
|
||||
"version": "3.16.2",
|
||||
"description": "OCP (Open Claude Proxy) — use your Claude Pro/Max subscription as an OpenAI-compatible API for any IDE. Works with Cline, OpenCode, Aider, Continue.dev, OpenClaw, and more.",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
@@ -9,7 +9,8 @@
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node server.mjs",
|
||||
"setup": "node setup.mjs"
|
||||
"setup": "node setup.mjs",
|
||||
"test": "node test-features.mjs"
|
||||
},
|
||||
"keywords": [
|
||||
"openclaw",
|
||||
@@ -20,7 +21,7 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=22.5"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* scripts/doctor.mjs — OCP health & upgrade-readiness check.
|
||||
*
|
||||
* Usage:
|
||||
* ocp doctor human-readable PASS/WARN/FAIL
|
||||
* ocp doctor --json machine-readable JSON for AI agents + ocp update
|
||||
* ocp doctor --check oauth fast path: only OAuth check
|
||||
*
|
||||
* Exit codes:
|
||||
* 0 all PASS or WARN-only
|
||||
* 1 any FAIL
|
||||
*/
|
||||
import { readFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
const SCHEMA_VERSION = "1";
|
||||
|
||||
function semverParts(v) {
|
||||
const m = String(v).replace(/^v/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
if (!m) return null;
|
||||
return { major: +m[1], minor: +m[2], patch: +m[3] };
|
||||
}
|
||||
|
||||
function semverCompare(a, b) {
|
||||
const A = semverParts(a), B = semverParts(b);
|
||||
if (!A || !B) return 0;
|
||||
if (A.major !== B.major) return A.major - B.major;
|
||||
if (A.minor !== B.minor) return A.minor - B.minor;
|
||||
return A.patch - B.patch;
|
||||
}
|
||||
|
||||
export async function runDoctor(opts = {}) {
|
||||
const checks = [];
|
||||
const push = (id, level, message, extra = {}) =>
|
||||
checks.push({ id, level, message, ...extra });
|
||||
|
||||
// --- fast path: --check oauth ---
|
||||
if (opts.checkOnly === "oauth") {
|
||||
return runOauthOnly(opts, checks, push);
|
||||
}
|
||||
|
||||
// --- version detection ---
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
let currentVersion = opts.mockVersion;
|
||||
if (!currentVersion) {
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(ocpDir, "package.json"), "utf8"));
|
||||
currentVersion = `v${pkg.version}`;
|
||||
} catch {
|
||||
currentVersion = "unknown";
|
||||
}
|
||||
}
|
||||
// Resolve latest from origin/main (cheap: `git show origin/main:package.json`).
|
||||
// Falls back to current_version when network/git unavailable, so kind = noop instead
|
||||
// of recommending a downgrade against a stale hardcoded value.
|
||||
let latestVersion = opts.mockLatest;
|
||||
if (!latestVersion) {
|
||||
try {
|
||||
const out = execSync(`git -C ${ocpDir} show origin/main:package.json 2>/dev/null`, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
const remotePkg = JSON.parse(out);
|
||||
latestVersion = `v${remotePkg.version}`;
|
||||
} catch {
|
||||
latestVersion = currentVersion;
|
||||
}
|
||||
}
|
||||
push("current_version", "PASS", `current=${currentVersion}`);
|
||||
|
||||
// --- from-version supported? ---
|
||||
const fromSupported = !!semverParts(currentVersion) && semverCompare(currentVersion, "v3.4.0") >= 0;
|
||||
push("from_version_supported", fromSupported ? "PASS" : "FAIL",
|
||||
fromSupported ? "≥ v3.4.0" : `${currentVersion} < v3.4.0; in-place upgrade not supported`);
|
||||
|
||||
// --- service health check (mockable) ---
|
||||
let healthOk = true, oauthOk = true;
|
||||
if (!opts.skipNetwork) {
|
||||
let health;
|
||||
if (opts.mockHealth !== undefined) {
|
||||
health = opts.mockHealth;
|
||||
} else {
|
||||
try {
|
||||
const port = process.env.CLAUDE_PROXY_PORT || "3478";
|
||||
const out = execSync(`curl -sf --max-time 3 http://127.0.0.1:${port}/health`, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
health = { status: 200, body: JSON.parse(out) };
|
||||
} catch (e) {
|
||||
health = { error: String(e.message || e) };
|
||||
}
|
||||
}
|
||||
if (health.error || health.status !== 200) {
|
||||
healthOk = false;
|
||||
push("service_running", "FAIL", `service unreachable: ${health.error || `status ${health.status}`}`);
|
||||
} else if (!health.body || typeof health.body !== "object") {
|
||||
healthOk = false;
|
||||
push("service_running", "FAIL", "service /health returned 200 but empty/non-JSON body");
|
||||
} else {
|
||||
push("service_running", "PASS", "service responding on /health");
|
||||
const authOk = health.body?.auth?.ok;
|
||||
if (!authOk) {
|
||||
oauthOk = false;
|
||||
push("oauth_ok", "FAIL", `auth.ok=false: ${health.body?.auth?.message || "unknown"}`);
|
||||
} else {
|
||||
push("oauth_ok", "PASS", "OAuth token valid");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- determine next_action.kind (priority: fresh_install > fix_service > fix_oauth > noop > update > upgrade) ---
|
||||
let kind;
|
||||
if (!fromSupported) {
|
||||
kind = "fresh_install";
|
||||
} else if (!opts.skipNetwork && !healthOk) {
|
||||
kind = "fix_service";
|
||||
} else if (!opts.skipNetwork && !oauthOk) {
|
||||
kind = "fix_oauth";
|
||||
} else {
|
||||
const cur = semverParts(currentVersion), lat = semverParts(latestVersion);
|
||||
if (!cur) {
|
||||
kind = "fresh_install";
|
||||
} else if (semverCompare(currentVersion, latestVersion) === 0) {
|
||||
kind = "noop";
|
||||
} else if (lat && cur.major === lat.major && cur.minor === lat.minor) {
|
||||
kind = "update";
|
||||
} else {
|
||||
kind = "upgrade";
|
||||
}
|
||||
}
|
||||
|
||||
// --- next_action shape ---
|
||||
let next_action;
|
||||
if (kind === "fresh_install") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: ["claude auth login (only if OAuth becomes invalid after reinstall)"],
|
||||
ai_executable: [
|
||||
`launchctl bootout gui/$(id -u)/ai.openclaw.proxy 2>/dev/null || true`,
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`mv ${join(homedir(), ".ocp")} ${join(homedir(), ".ocp.backup-")}$(date +%s) 2>/dev/null || true`,
|
||||
`rm -rf ${ocpDir}`,
|
||||
`git clone https://github.com/dtzp555-max/ocp ${ocpDir}`,
|
||||
`cd ${ocpDir} && npm install --no-audit --no-fund && node setup.mjs`,
|
||||
`${ocpDir}/ocp doctor`
|
||||
],
|
||||
verify: "ocp doctor expects PASS on all checks"
|
||||
};
|
||||
} else if (kind === "noop") {
|
||||
next_action = { kind, human_required: [], ai_executable: [], verify: "already at latest" };
|
||||
} else if (kind === "fix_oauth") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`cd "$(npm root -g)/@anthropic-ai/claude-code" && node install.cjs`,
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor`
|
||||
],
|
||||
verify: "ocp doctor expects oauth_ok=PASS",
|
||||
reference: "~/.cc-rules/memory/learnings/ocp_claude_native_binary_postinstall.md"
|
||||
};
|
||||
} else if (kind === "fix_service") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor`
|
||||
],
|
||||
verify: "ocp doctor expects service_running=PASS"
|
||||
};
|
||||
} else {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [`${ocpDir}/ocp update --yes`],
|
||||
verify: "ocp doctor expects PASS on all checks"
|
||||
};
|
||||
}
|
||||
|
||||
const fail_count = checks.filter(c => c.level === "FAIL").length;
|
||||
const warn_count = checks.filter(c => c.level === "WARN").length;
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
ready_to_upgrade: fail_count === 0,
|
||||
current_version: currentVersion,
|
||||
latest_version: latestVersion,
|
||||
from_version_supported: fromSupported,
|
||||
fail_count,
|
||||
warn_count,
|
||||
checks,
|
||||
next_action
|
||||
};
|
||||
}
|
||||
|
||||
function runOauthOnly(opts, checks, push) {
|
||||
let healthOk = true, oauthOk = true;
|
||||
let health;
|
||||
if (opts.mockHealth !== undefined) {
|
||||
health = opts.mockHealth;
|
||||
} else {
|
||||
try {
|
||||
const port = process.env.CLAUDE_PROXY_PORT || "3478";
|
||||
const out = execSync(`curl -sf --max-time 3 http://127.0.0.1:${port}/health`, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
health = { status: 200, body: JSON.parse(out) };
|
||||
} catch (e) {
|
||||
health = { error: String(e.message || e) };
|
||||
}
|
||||
}
|
||||
|
||||
if (health.error || health.status !== 200) {
|
||||
healthOk = false;
|
||||
push("oauth_ok", "FAIL", `service unreachable: ${health.error || `status ${health.status}`}`);
|
||||
} else if (!health.body || typeof health.body !== "object") {
|
||||
healthOk = false;
|
||||
push("oauth_ok", "FAIL", "service /health returned 200 but empty/non-JSON body");
|
||||
} else if (!health.body?.auth?.ok) {
|
||||
oauthOk = false;
|
||||
push("oauth_ok", "FAIL", `auth.ok=false: ${health.body?.auth?.message || "unknown"}`);
|
||||
} else {
|
||||
push("oauth_ok", "PASS", "OAuth token valid");
|
||||
}
|
||||
|
||||
const kind = !healthOk ? "fix_service" : !oauthOk ? "fix_oauth" : "noop";
|
||||
|
||||
let next_action;
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
if (kind === "noop") {
|
||||
next_action = { kind, human_required: [], ai_executable: [], verify: "OAuth healthy" };
|
||||
} else if (kind === "fix_oauth") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`cd "$(npm root -g)/@anthropic-ai/claude-code" && node install.cjs`,
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor --check oauth`
|
||||
],
|
||||
verify: "ocp doctor --check oauth expects PASS",
|
||||
reference: "~/.cc-rules/memory/learnings/ocp_claude_native_binary_postinstall.md"
|
||||
};
|
||||
} else {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor --check oauth`
|
||||
],
|
||||
verify: "ocp doctor --check oauth expects service_running=PASS"
|
||||
};
|
||||
}
|
||||
|
||||
const fail_count = checks.filter(c => c.level === "FAIL").length;
|
||||
// "skipped" = --check oauth fast path intentionally omits version detection.
|
||||
// AI agents should NOT semver-compare against current_version/latest_version when
|
||||
// either equals "skipped"; the full path provides those fields when needed.
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
ready_to_upgrade: fail_count === 0,
|
||||
current_version: opts.mockVersion || "skipped",
|
||||
latest_version: opts.mockLatest || "skipped",
|
||||
from_version_supported: true,
|
||||
fail_count,
|
||||
warn_count: 0,
|
||||
checks,
|
||||
next_action
|
||||
};
|
||||
}
|
||||
|
||||
// CLI entrypoint — use fileURLToPath + realpath to handle symlinked install paths
|
||||
// (e.g. /tmp/ → /private/tmp/ on macOS would otherwise miss the guard).
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { realpathSync } from "node:fs";
|
||||
function _isMain() {
|
||||
if (!process.argv[1]) return false;
|
||||
try {
|
||||
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
||||
} catch { return false; }
|
||||
}
|
||||
if (_isMain()) {
|
||||
const wantJson = process.argv.includes("--json");
|
||||
const checkIdx = process.argv.indexOf("--check");
|
||||
const checkOnly = checkIdx !== -1 ? process.argv[checkIdx + 1] : undefined;
|
||||
const result = await runDoctor({ checkOnly });
|
||||
if (wantJson) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(`OCP doctor — ${result.current_version} → ${result.latest_version}`);
|
||||
for (const c of result.checks) console.log(` [${c.level}] ${c.id}: ${c.message}`);
|
||||
console.log(`\nSummary: ${result.fail_count} FAIL, ${result.warn_count} WARN`);
|
||||
console.log(`Next action: ${result.next_action.kind}`);
|
||||
}
|
||||
process.exit(result.fail_count === 0 ? 0 : 1);
|
||||
}
|
||||
Executable
+132
@@ -0,0 +1,132 @@
|
||||
#!/bin/bash
|
||||
# One-shot field-evidence gatherer for OCP v3.12.0 SSE heartbeat.
|
||||
# Scheduled by ~/Library/LaunchAgents/dev.ocp.heartbeat-check.plist to fire
|
||||
# once at 2026-05-02 09:00 Australia/Brisbane. Gathers evidence from local
|
||||
# OCP logs + GitHub issue #47 + repo issue search, posts a summary comment
|
||||
# on #47, and exits. Does NOT open PRs or change code — the maintainer
|
||||
# decides after reading the summary.
|
||||
#
|
||||
# Dry-run: ./heartbeat-field-check.sh --dry-run (prints summary, skips post)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
REPO="dtzp555-max/ocp"
|
||||
SHIP_DATE="2026-04-25"
|
||||
# Baseline captured at script-install time so internal testing entries from
|
||||
# Phase 3 verification (~5 entries from 2026-04-25T00:00–00:48Z) don't get
|
||||
# counted as field evidence. Any heartbeat_active log entry with ts >= this
|
||||
# timestamp is treated as a real opt-in.
|
||||
BASELINE_TS="2026-04-25T01:00:00Z"
|
||||
PROXY_LOG="$HOME/ocp/logs/proxy.log"
|
||||
OUT_DIR="$HOME/ocp/logs"
|
||||
SELF_LOG="$OUT_DIR/heartbeat-field-check-$(date +%Y-%m-%d).log"
|
||||
DRY_RUN=0
|
||||
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1
|
||||
|
||||
mkdir -p "$OUT_DIR"
|
||||
|
||||
exec > >(tee -a "$SELF_LOG") 2>&1
|
||||
|
||||
echo "=== heartbeat field-evidence check: $(date -u +%Y-%m-%dT%H:%M:%SZ) (dry_run=$DRY_RUN) ==="
|
||||
|
||||
# ── signal 1: local proxy log ─────────────────────────────────────────────
|
||||
if [ -r "$PROXY_LOG" ]; then
|
||||
# Only count entries with ts >= BASELINE_TS (string sort works on RFC3339)
|
||||
HEARTBEAT_COUNT=$(grep '"event":"heartbeat_active"' "$PROXY_LOG" 2>/dev/null \
|
||||
| awk -v base="$BASELINE_TS" '
|
||||
match($0, /"ts":"[^"]+"/) {
|
||||
ts = substr($0, RSTART+6, RLENGTH-7);
|
||||
if (ts >= base) c++
|
||||
}
|
||||
END { print c+0 }')
|
||||
else
|
||||
HEARTBEAT_COUNT=0
|
||||
fi
|
||||
echo "signal 1 — heartbeat_active log entries since $BASELINE_TS: $HEARTBEAT_COUNT"
|
||||
|
||||
# ── signal 2: comments on #47 since ship ──────────────────────────────────
|
||||
NEW_47_JSON="/tmp/ocp-47-new-comments-$$.json"
|
||||
gh issue view 47 --repo "$REPO" --json comments \
|
||||
--jq '[.comments[] | select(.createdAt >= "'"$SHIP_DATE"'T00:00:00Z")]' \
|
||||
> "$NEW_47_JSON" 2>/dev/null || echo "[]" > "$NEW_47_JSON"
|
||||
NEW_COMMENTS=$(jq 'length' "$NEW_47_JSON")
|
||||
echo "signal 2 — new comments on #47 since $SHIP_DATE: $NEW_COMMENTS"
|
||||
|
||||
# Build a compact, human-readable excerpt for the summary body
|
||||
NEW_47_EXCERPT=""
|
||||
if [ "$NEW_COMMENTS" -gt 0 ]; then
|
||||
NEW_47_EXCERPT=$(jq -r '.[] | "- **@\(.author.login)** (\(.createdAt)): " + (.body | gsub("\r"; "") | split("\n")[0])[:180]' "$NEW_47_JSON")
|
||||
fi
|
||||
|
||||
# ── signal 3: other heartbeat-related issues since ship ──────────────────
|
||||
OTHER_ISSUES_JSON="/tmp/ocp-heartbeat-issues-$$.json"
|
||||
gh search issues "repo:$REPO heartbeat" --json number,title,state,createdAt --limit 30 \
|
||||
--jq '[.[] | select(.createdAt >= "'"$SHIP_DATE"'T00:00:00Z" and .number != 47 and .number != 48)]' \
|
||||
> "$OTHER_ISSUES_JSON" 2>/dev/null || echo "[]" > "$OTHER_ISSUES_JSON"
|
||||
OTHER_ISSUES=$(jq 'length' "$OTHER_ISSUES_JSON")
|
||||
echo "signal 3 — other heartbeat-related issues since ship: $OTHER_ISSUES"
|
||||
|
||||
OTHER_ISSUES_EXCERPT=""
|
||||
if [ "$OTHER_ISSUES" -gt 0 ]; then
|
||||
OTHER_ISSUES_EXCERPT=$(jq -r '.[] | "- #\(.number) [\(.state)] \(.title)"' "$OTHER_ISSUES_JSON")
|
||||
fi
|
||||
|
||||
# ── compose summary ──────────────────────────────────────────────────────
|
||||
BODY_FILE="/tmp/ocp-47-summary-$$.md"
|
||||
{
|
||||
echo "### Automated 7-day field-evidence check (v3.12.0)"
|
||||
echo
|
||||
echo "_Triggered by a local launchd scheduled task on the maintainer's rig at $(date -u +%Y-%m-%dT%H:%M:%SZ)._"
|
||||
echo
|
||||
echo "| Signal | Count |"
|
||||
echo "|---|---|"
|
||||
echo "| \`heartbeat_active\` log entries on prod rig (since baseline $BASELINE_TS) | $HEARTBEAT_COUNT |"
|
||||
echo "| New comments on #47 since $SHIP_DATE | $NEW_COMMENTS |"
|
||||
echo "| Other heartbeat-related issues filed since $SHIP_DATE | $OTHER_ISSUES |"
|
||||
echo
|
||||
if [ -n "$NEW_47_EXCERPT" ]; then
|
||||
echo "**New #47 comments (first line each):**"
|
||||
echo
|
||||
echo "$NEW_47_EXCERPT"
|
||||
echo
|
||||
fi
|
||||
if [ -n "$OTHER_ISSUES_EXCERPT" ]; then
|
||||
echo "**Other heartbeat-related issues:**"
|
||||
echo
|
||||
echo "$OTHER_ISSUES_EXCERPT"
|
||||
echo
|
||||
fi
|
||||
echo "**Decision guidance for maintainer (manual):**"
|
||||
echo
|
||||
echo "- If any of the above indicate a **crash report** on \`: keepalive\` comment frames → leave default at \`0\` and file a \`CLAUDE_HEARTBEAT_FORMAT=empty-delta\` follow-up issue (spec \`§D2\` fallback plan)."
|
||||
echo "- If there is at least one **opt-in confirmation** (a user reports \`CLAUDE_HEARTBEAT_INTERVAL\` fixed their timeout issue) and no crash reports → consider opening a PR for v3.13.0 flipping the default to \`30000\`, following the same ALIGNMENT + independent-reviewer + release-kit discipline as PR #49."
|
||||
echo "- If all three signals are zero → extend the soak window or close this follow-up as \"no field evidence.\""
|
||||
echo
|
||||
echo "This bot does not open PRs or change code. The maintainer reviews and acts."
|
||||
} > "$BODY_FILE"
|
||||
|
||||
echo "--- summary preview ---"
|
||||
cat "$BODY_FILE"
|
||||
echo "--- end preview ---"
|
||||
|
||||
# ── post (unless dry-run) ────────────────────────────────────────────────
|
||||
if [ "$DRY_RUN" -eq 1 ]; then
|
||||
echo "DRY RUN — skipping gh issue comment"
|
||||
else
|
||||
gh issue comment 47 --repo "$REPO" --body-file "$BODY_FILE" && echo "comment posted on #47"
|
||||
fi
|
||||
|
||||
# ── cleanup + self-disable so the plist doesn't linger loaded forever ────
|
||||
rm -f "$NEW_47_JSON" "$OTHER_ISSUES_JSON" "$BODY_FILE"
|
||||
|
||||
if [ "$DRY_RUN" -eq 0 ]; then
|
||||
# Unload + remove the plist so this never fires again
|
||||
PLIST="$HOME/Library/LaunchAgents/dev.ocp.heartbeat-check.plist"
|
||||
if [ -f "$PLIST" ]; then
|
||||
launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
|
||||
rm -f "$PLIST"
|
||||
echo "self-disabled: removed $PLIST"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "=== done ==="
|
||||
@@ -0,0 +1,86 @@
|
||||
// scripts/lib/plist-merge.mjs
|
||||
//
|
||||
// Preserves user-customised env vars when setup.mjs rewrites the unit file.
|
||||
//
|
||||
// Rule:
|
||||
// - keys present in NEW template → template value wins (template is source of truth)
|
||||
// - keys ONLY in EXISTING (not in template) → preserved verbatim
|
||||
//
|
||||
// No new dependencies — regex-based, plist <key>X</key><string>Y</string> shape
|
||||
// is stable enough for our hand-written templates in setup.mjs.
|
||||
|
||||
const PLIST_KV_RE = /<key>([^<]+)<\/key>\s*<string>([^<]*)<\/string>/g;
|
||||
|
||||
export function parsePlistEnv(plistContent) {
|
||||
if (!plistContent) return {};
|
||||
if (Buffer.isBuffer(plistContent)) plistContent = plistContent.toString("utf8");
|
||||
// Restrict to the EnvironmentVariables dict to avoid catching Label, etc.
|
||||
const envBlock = plistContent.match(/<key>EnvironmentVariables<\/key>\s*<dict>([\s\S]*?)<\/dict>/);
|
||||
if (!envBlock) return {};
|
||||
const out = {};
|
||||
let m;
|
||||
PLIST_KV_RE.lastIndex = 0;
|
||||
while ((m = PLIST_KV_RE.exec(envBlock[1])) !== null) {
|
||||
out[m[1]] = m[2];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mergePlistEnv(existing, template) {
|
||||
if (!existing) return template;
|
||||
const existingEnv = parsePlistEnv(existing);
|
||||
const templateEnv = parsePlistEnv(template);
|
||||
const KNOWN = new Set(Object.keys(templateEnv));
|
||||
|
||||
const preserved = {};
|
||||
for (const [k, v] of Object.entries(existingEnv)) {
|
||||
if (!KNOWN.has(k)) preserved[k] = v;
|
||||
}
|
||||
if (Object.keys(preserved).length === 0) return template;
|
||||
|
||||
const lines = Object.entries(preserved)
|
||||
.map(([k, v]) => ` <key>${k}</key>\n <string>${v}</string>`)
|
||||
.join("\n");
|
||||
|
||||
// Inject before the closing </dict> of EnvironmentVariables
|
||||
return template.replace(
|
||||
/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/,
|
||||
`$1\n${lines}$2`
|
||||
);
|
||||
}
|
||||
|
||||
const SYSTEMD_KV_RE = /^Environment=([^=]+)=(.*)$/gm;
|
||||
|
||||
export function parseSystemdEnv(serviceContent) {
|
||||
if (!serviceContent) return {};
|
||||
if (Buffer.isBuffer(serviceContent)) serviceContent = serviceContent.toString("utf8");
|
||||
const out = {};
|
||||
let m;
|
||||
SYSTEMD_KV_RE.lastIndex = 0;
|
||||
while ((m = SYSTEMD_KV_RE.exec(serviceContent)) !== null) {
|
||||
out[m[1]] = m[2];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mergeSystemdEnv(existing, template) {
|
||||
if (!existing) return template;
|
||||
const existingEnv = parseSystemdEnv(existing);
|
||||
const templateEnv = parseSystemdEnv(template);
|
||||
const KNOWN = new Set(Object.keys(templateEnv));
|
||||
|
||||
const preservedLines = Object.entries(existingEnv)
|
||||
.filter(([k]) => !KNOWN.has(k))
|
||||
.map(([k, v]) => `Environment=${k}=${v}`);
|
||||
if (preservedLines.length === 0) return template;
|
||||
|
||||
// Guard: if template has no Environment= anchor, cannot inject — return template as-is.
|
||||
// (In practice the OCP systemd template always has Environment= lines.)
|
||||
if (!/^Environment=/m.test(template)) return template;
|
||||
|
||||
// Inject after the last existing Environment= line in the template
|
||||
return template.replace(
|
||||
/(^Environment=[^\n]+\n)((?!Environment=).*$)/ms,
|
||||
`$1${preservedLines.join("\n")}\n$2`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { mkdirSync, writeFileSync, readFileSync, copyFileSync, existsSync, readdirSync, statSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function writeSnapshot({ homeDir, fromCommit, fromVersion, toVersion, extraFiles = [] }) {
|
||||
const ts = new Date().toISOString().replace(/\.\d+Z$/, "Z");
|
||||
const root = join(homeDir, ".ocp", `upgrade-snapshot-${ts}`);
|
||||
mkdirSync(root, { recursive: true });
|
||||
|
||||
// Standard manifest files
|
||||
writeFileSync(join(root, "from-commit.txt"), fromCommit + "\n");
|
||||
writeFileSync(join(root, "from-version.txt"), fromVersion + "\n");
|
||||
writeFileSync(join(root, "to-version.txt"), toVersion + "\n");
|
||||
|
||||
// Optional captures (best-effort, never fatal)
|
||||
const tryCopy = (src, dst) => {
|
||||
try {
|
||||
if (existsSync(src)) copyFileSync(src, dst);
|
||||
} catch (err) {
|
||||
console.error(`[snapshot] warn: could not copy ${src} (${err.code || err.message})`);
|
||||
}
|
||||
};
|
||||
tryCopy(join(homeDir, "Library", "LaunchAgents", "dev.ocp.proxy.plist"), join(root, "plist"));
|
||||
tryCopy(join(homeDir, ".config", "systemd", "user", "ocp-proxy.service"), join(root, "service"));
|
||||
tryCopy(join(homeDir, ".ocp", "ocp.db"), join(root, "db.bak"));
|
||||
tryCopy(join(homeDir, ".ocp", "admin-key"), join(root, "admin-key"));
|
||||
tryCopy(join(homeDir, ".openclaw", "openclaw.json"), join(root, "openclaw.json"));
|
||||
|
||||
for (const { src, name } of extraFiles) tryCopy(src, join(root, name));
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
export function readSnapshot(snapshotPath) {
|
||||
const read = (n) => {
|
||||
try { return readFileSync(join(snapshotPath, n), "utf8").trim(); } catch { return null; }
|
||||
};
|
||||
return {
|
||||
path: snapshotPath,
|
||||
fromCommit: read("from-commit.txt"),
|
||||
fromVersion: read("from-version.txt"),
|
||||
toVersion: read("to-version.txt")
|
||||
};
|
||||
}
|
||||
|
||||
export function listSnapshots(homeDir) {
|
||||
const root = join(homeDir, ".ocp");
|
||||
if (!existsSync(root)) return [];
|
||||
return readdirSync(root)
|
||||
.filter(name => name.startsWith("upgrade-snapshot-"))
|
||||
.map(name => ({ name, path: join(root, name), mtime: statSync(join(root, name)).mtimeMs }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Garbage-collect old upgrade snapshots.
|
||||
*
|
||||
* Retention rule (a snapshot is KEPT if any of these is true):
|
||||
* - It is among the last `keepCount` snapshots (sorted oldest→newest)
|
||||
* - Its timestamp is within `keepDays` of `now`
|
||||
* - It is the single most-recent snapshot (always-keep safety net)
|
||||
*
|
||||
* @param {string} homeDir - Root containing ~/.ocp/
|
||||
* @param {object} opts
|
||||
* @param {number} [opts.keepCount=5] - Minimum count to keep
|
||||
* @param {number} [opts.keepDays=30] - Keep snapshots newer than N days
|
||||
* @param {boolean} [opts.dryRun=false] - If true, report plan but don't delete
|
||||
* @param {Date} [opts.now=new Date()] - Override clock for testing
|
||||
* @returns {{kept: Array, removed: Array, dryRun: boolean}}
|
||||
*/
|
||||
export function gcSnapshots(homeDir, opts = {}) {
|
||||
const keepCount = opts.keepCount ?? 5;
|
||||
const keepDays = opts.keepDays ?? 30;
|
||||
const dryRun = !!opts.dryRun;
|
||||
const now = opts.now || new Date();
|
||||
|
||||
const all = listSnapshots(homeDir); // sorted oldest→newest
|
||||
if (all.length === 0) return { kept: [], removed: [], dryRun };
|
||||
if (all.length === 1) return { kept: all, removed: [], dryRun }; // always keep most recent
|
||||
|
||||
const cutoffMs = now.getTime() - keepDays * 24 * 60 * 60 * 1000;
|
||||
const lastN = new Set(all.slice(-keepCount).map(s => s.path));
|
||||
|
||||
const kept = [], removed = [];
|
||||
for (let i = 0; i < all.length; i++) {
|
||||
const s = all[i];
|
||||
const isMostRecent = i === all.length - 1;
|
||||
const isInLastN = lastN.has(s.path);
|
||||
const isWithinDays = parseSnapshotTimestamp(s.name) >= cutoffMs;
|
||||
if (isMostRecent || isInLastN || isWithinDays) {
|
||||
kept.push(s);
|
||||
} else {
|
||||
removed.push(s);
|
||||
}
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
for (const s of removed) {
|
||||
try {
|
||||
rmSync(s.path, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
console.error(`[snapshot] warn: could not remove ${s.path} (${err.code || err.message})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { kept, removed, dryRun };
|
||||
}
|
||||
|
||||
function parseSnapshotTimestamp(name) {
|
||||
// upgrade-snapshot-2026-05-11T08:30:00Z → epoch ms
|
||||
const m = name.match(/upgrade-snapshot-(.+)$/);
|
||||
if (!m) return 0;
|
||||
const t = Date.parse(m[1]);
|
||||
return Number.isFinite(t) ? t : 0;
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* scripts/upgrade.mjs — OCP unified upgrade dispatcher.
|
||||
*
|
||||
* Paths:
|
||||
* noop current == latest, exit 0
|
||||
* light same major.minor, patch bump only (existing fast path; delegated to bash)
|
||||
* full cross-minor (snapshot + setup.mjs + post-flight)
|
||||
* fresh_install from-version < v3.4.0 (--yes required for non-interactive)
|
||||
* rollback restore from snapshot
|
||||
*/
|
||||
import { runDoctor } from "./doctor.mjs";
|
||||
import { execSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { existsSync, copyFileSync } from "node:fs";
|
||||
import { writeSnapshot, listSnapshots, readSnapshot, gcSnapshots } from "./lib/snapshot.mjs";
|
||||
|
||||
export async function runUpgrade(opts = {}) {
|
||||
const dryRun = !!opts.dryRun;
|
||||
const yes = !!opts.yes;
|
||||
// yes is reserved for Bundle 3 (fresh-install / rollback interactive gate); not used in upgrade-path here.
|
||||
const plan = [];
|
||||
|
||||
// --- rollback path (no doctor needed; snapshot is authoritative) ---
|
||||
if (opts.rollback) {
|
||||
return await runRollback(opts);
|
||||
}
|
||||
|
||||
// --- doctor pre-flight ---
|
||||
const doctor = opts.mockDoctor || await runDoctor();
|
||||
if (!doctor.ready_to_upgrade && doctor.next_action.kind !== "fresh_install") {
|
||||
throw new Error(`doctor FAIL: ${doctor.next_action.kind} (run "ocp doctor" for details)`);
|
||||
}
|
||||
|
||||
const kind = doctor.next_action.kind;
|
||||
plan.push(`[doctor] from=${doctor.current_version} to=${doctor.latest_version} kind=${kind}`);
|
||||
|
||||
// --- noop ---
|
||||
if (kind === "noop") {
|
||||
plan.push(`[noop] already at latest (${doctor.latest_version})`);
|
||||
return { path: "noop", executed: true, changed: false, plan };
|
||||
}
|
||||
|
||||
// --- dry-run early exit ---
|
||||
if (dryRun) {
|
||||
plan.push(`[plan] would proceed with ${kind} path`);
|
||||
if (kind === "upgrade") {
|
||||
plan.push(`[plan] phase 1: snapshot to ~/.ocp/upgrade-snapshot-<ts>/`);
|
||||
plan.push(`[plan] phase 2: git checkout ${doctor.latest_version} && npm install`);
|
||||
plan.push(`[plan] phase 3: node setup.mjs`);
|
||||
plan.push(`[plan] phase 4: launchctl bootout/bootstrap`);
|
||||
plan.push(`[plan] phase 5: post-flight /health + /v1/models`);
|
||||
} else if (kind === "update") {
|
||||
plan.push(`[plan] light path: git pull + npm install + restart`);
|
||||
} else if (kind === "fresh_install") {
|
||||
plan.push(`[plan] fresh-install ai_executable[]:`);
|
||||
for (const cmd of doctor.next_action.ai_executable) plan.push(` - ${cmd}`);
|
||||
}
|
||||
return { path: kind, executed: false, plan };
|
||||
}
|
||||
|
||||
// --- non-dry-run paths ---
|
||||
if (kind === "update") {
|
||||
return { path: "update", executed: true, changed: true, plan: [...plan, "[light] delegated to bash cmd_update existing logic"] };
|
||||
}
|
||||
|
||||
if (kind === "upgrade") {
|
||||
return await runFullUpgrade({ doctor, opts });
|
||||
}
|
||||
|
||||
if (kind === "fresh_install") {
|
||||
return await runFreshInstall({ doctor, opts });
|
||||
}
|
||||
|
||||
throw new Error(`path ${kind} not yet implemented`);
|
||||
}
|
||||
|
||||
async function runFullUpgrade({ doctor, opts }) {
|
||||
const phases = [];
|
||||
let snapshotPath = null;
|
||||
const exec = (cmd, label) => {
|
||||
if (opts.mockExec) {
|
||||
phases.push({ name: label, cmd, status: "skipped-mock" });
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const out = execSync(cmd, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
phases.push({ name: label, cmd, status: "ok" });
|
||||
return out;
|
||||
} catch (err) {
|
||||
const detail = err.stderr?.toString().trim();
|
||||
phases.push({ name: label, cmd, status: "fail", stderr: detail });
|
||||
throw Object.assign(
|
||||
new Error(`phase ${label} failed: ${detail || err.message}`),
|
||||
{ phases, cmd }
|
||||
);
|
||||
}
|
||||
};
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
|
||||
try {
|
||||
// phase 1: pre-flight (doctor already passed; just record)
|
||||
phases.push({ name: "pre-flight", status: "ok", note: `kind=upgrade from=${doctor.current_version} to=${doctor.latest_version}` });
|
||||
|
||||
// phase 2: snapshot
|
||||
const fromCommit = opts.mockExec
|
||||
? "mock-commit"
|
||||
: execSync(`git -C ${ocpDir} rev-parse HEAD`).toString().trim();
|
||||
snapshotPath = opts.mockExec
|
||||
? "/tmp/mock-snapshot"
|
||||
: writeSnapshot({ homeDir: homedir(), fromCommit, fromVersion: doctor.current_version, toVersion: doctor.latest_version });
|
||||
phases.push({ name: "snapshot", path: snapshotPath, status: "ok" });
|
||||
|
||||
// phase 3: fetch + install
|
||||
exec(`git -C ${ocpDir} fetch --tags --quiet`, "fetch+install");
|
||||
exec(`git -C ${ocpDir} checkout ${doctor.latest_version}`, "fetch+install");
|
||||
exec(`npm --prefix ${ocpDir} install --no-audit --no-fund`, "fetch+install");
|
||||
|
||||
// phase 4: reconfigure
|
||||
exec(`node ${ocpDir}/setup.mjs`, "reconfigure");
|
||||
|
||||
// phase 5: restart (heads-up note printed before invoking)
|
||||
if (!opts.mockExec) {
|
||||
console.error(`[heads-up] restarting OCP service in 3s — expect ~5–10s blip on requests in flight.`);
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
}
|
||||
if (process.platform === "darwin") {
|
||||
exec(`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`, "restart");
|
||||
exec(`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`, "restart");
|
||||
} else {
|
||||
exec(`systemctl --user restart ocp-proxy.service`, "restart");
|
||||
}
|
||||
|
||||
// phase 6: post-flight (10s budget; skipped under mockExec)
|
||||
if (!opts.mockExec) {
|
||||
const port = process.env.CLAUDE_PROXY_PORT || "3478";
|
||||
let ok = false;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
try {
|
||||
const out = execSync(`curl -sf --max-time 2 http://127.0.0.1:${port}/health`).toString();
|
||||
const body = JSON.parse(out);
|
||||
if (body.auth?.ok === true) { ok = true; break; }
|
||||
} catch { /* retry */ }
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
}
|
||||
if (!ok) {
|
||||
phases.push({ name: "post-flight", status: "fail", message: "health did not return auth.ok=true within 10s" });
|
||||
throw new Error("post-flight failed");
|
||||
}
|
||||
execSync(`curl -sf --max-time 3 http://127.0.0.1:${port}/v1/models > /dev/null`);
|
||||
phases.push({ name: "post-flight", status: "ok" });
|
||||
} else {
|
||||
phases.push({ name: "post-flight", status: "skipped-mock" });
|
||||
}
|
||||
|
||||
// Auto-GC old snapshots after successful upgrade (best-effort, never throws).
|
||||
try {
|
||||
const gc = gcSnapshots(homedir(), { keepCount: 5, keepDays: 30 });
|
||||
if (gc.removed.length > 0) {
|
||||
console.error(`[gc] removed ${gc.removed.length} old snapshots; kept ${gc.kept.length}`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[gc] warn: snapshot GC failed: ${e.message}`);
|
||||
}
|
||||
|
||||
return { path: "upgrade", executed: true, changed: true, snapshotPath, phases };
|
||||
} catch (err) {
|
||||
if (snapshotPath && !err.snapshotPath) {
|
||||
Object.assign(err, {
|
||||
snapshotPath,
|
||||
phases,
|
||||
hint: "Working tree may be at new version. Run `ocp update --rollback` to restore from snapshot."
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function runFreshInstall({ doctor, opts }) {
|
||||
if (!opts.yes) {
|
||||
throw new Error("fresh_install requires --yes for non-interactive execution (or run interactively and answer y)");
|
||||
}
|
||||
const steps = [];
|
||||
for (const cmd of doctor.next_action.ai_executable) {
|
||||
if (opts.mockExec) {
|
||||
steps.push({ cmd, status: "skipped-mock" });
|
||||
} else {
|
||||
try {
|
||||
execSync(cmd, { stdio: "inherit" });
|
||||
steps.push({ cmd, status: "ok" });
|
||||
} catch (e) {
|
||||
const detail = e.stderr?.toString().trim() || e.message;
|
||||
steps.push({ cmd, status: "fail", error: String(detail) });
|
||||
throw Object.assign(new Error(`fresh_install step failed: ${cmd} — ${detail}`), { steps });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { path: "fresh_install", executed: true, changed: true, steps };
|
||||
}
|
||||
|
||||
async function runRollback(opts) {
|
||||
const homeDir = opts.homeDir || homedir();
|
||||
const snapshots = opts.mockSnapshots ?? listSnapshots(homeDir);
|
||||
|
||||
if (opts.gc) {
|
||||
const result = gcSnapshots(homeDir, { dryRun: opts.dryRun });
|
||||
return { path: opts.dryRun ? "rollback-gc-dry-run" : "rollback-gc", ...result };
|
||||
}
|
||||
|
||||
if (opts.list) {
|
||||
return { path: "rollback-list", snapshots };
|
||||
}
|
||||
if (snapshots.length === 0) {
|
||||
throw new Error("no upgrade snapshots found in ~/.ocp/upgrade-snapshot-*");
|
||||
}
|
||||
|
||||
const target = opts.snapshotPath
|
||||
? snapshots.find(s => s.path === opts.snapshotPath)
|
||||
: snapshots[snapshots.length - 1];
|
||||
if (!target) throw new Error(`snapshot not found: ${opts.snapshotPath} (must be inside ~/.ocp/upgrade-snapshot-*)`);
|
||||
|
||||
const meta = opts.mockSnapshotMeta ?? readSnapshot(target.path);
|
||||
if (!meta.fromCommit) throw new Error(`snapshot ${target.path} has no from-commit.txt`);
|
||||
|
||||
const phases = [];
|
||||
if (opts.dryRun) {
|
||||
return {
|
||||
path: "rollback-dry-run",
|
||||
executed: false,
|
||||
target: target.path,
|
||||
plan: [
|
||||
`git checkout ${meta.fromCommit}`,
|
||||
`cp ${target.path}/plist ~/Library/LaunchAgents/dev.ocp.proxy.plist`,
|
||||
`cp ${target.path}/db.bak ~/.ocp/ocp.db`,
|
||||
`launchctl bootout/bootstrap`,
|
||||
`ocp doctor`
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
if (!opts.yes) throw new Error("rollback requires --yes for non-interactive execution");
|
||||
|
||||
const exec = (cmd, label) => {
|
||||
if (opts.mockExec) {
|
||||
phases.push({ name: label, cmd, status: "skipped-mock" });
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
execSync(cmd, { stdio: ["pipe", "pipe", "pipe"] });
|
||||
phases.push({ name: label, cmd, status: "ok" });
|
||||
} catch (err) {
|
||||
const detail = err.stderr?.toString().trim();
|
||||
phases.push({ name: label, cmd, status: "fail", stderr: detail });
|
||||
throw Object.assign(
|
||||
new Error(`rollback phase ${label} failed: ${detail || err.message}`),
|
||||
{ phases, target: target.path }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
exec(`git -C ${ocpDir} checkout ${meta.fromCommit}`, "git-checkout");
|
||||
|
||||
if (!opts.mockExec) {
|
||||
const tryCopy = (src, dst) => {
|
||||
try {
|
||||
if (existsSync(src)) copyFileSync(src, dst);
|
||||
} catch (err) {
|
||||
console.error(`[rollback] warn: could not restore ${src} → ${dst} (${err.code || err.message})`);
|
||||
}
|
||||
};
|
||||
tryCopy(join(target.path, "plist"), join(homeDir, "Library", "LaunchAgents", "dev.ocp.proxy.plist"));
|
||||
tryCopy(join(target.path, "service"), join(homeDir, ".config", "systemd", "user", "ocp-proxy.service"));
|
||||
tryCopy(join(target.path, "db.bak"), join(homeDir, ".ocp", "ocp.db"));
|
||||
tryCopy(join(target.path, "admin-key"), join(homeDir, ".ocp", "admin-key"));
|
||||
phases.push({ name: "restore-files", status: "ok" });
|
||||
} else {
|
||||
phases.push({ name: "restore-files", status: "skipped-mock" });
|
||||
}
|
||||
|
||||
exec(`npm --prefix ${ocpDir} install --no-audit --no-fund`, "npm-install");
|
||||
|
||||
if (!opts.mockExec) {
|
||||
console.error(`[heads-up] restarting OCP service in 3s — expect ~5–10s blip on requests in flight.`);
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
}
|
||||
if (process.platform === "darwin") {
|
||||
exec(`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`, "restart");
|
||||
exec(`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`, "restart");
|
||||
} else {
|
||||
exec(`systemctl --user restart ocp-proxy.service`, "restart");
|
||||
}
|
||||
|
||||
return { path: "rollback", executed: true, changed: true, target: target.path, phases };
|
||||
}
|
||||
|
||||
// CLI entrypoint — use fileURLToPath + realpath to handle symlinked install paths.
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { realpathSync } from "node:fs";
|
||||
function _isMain() {
|
||||
if (!process.argv[1]) return false;
|
||||
try {
|
||||
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
||||
} catch { return false; }
|
||||
}
|
||||
if (_isMain()) {
|
||||
const args = process.argv.slice(2);
|
||||
const dryRun = args.includes("--dry-run");
|
||||
const yes = args.includes("--yes");
|
||||
const rollback = args.includes("--rollback");
|
||||
const list = args.includes("--list");
|
||||
const gc = args.includes("--gc");
|
||||
const targetIdx = args.indexOf("--target");
|
||||
const target = targetIdx !== -1 ? args[targetIdx + 1] : undefined;
|
||||
// First non-flag positional after --rollback is the snapshot path
|
||||
let snapshotPath;
|
||||
if (rollback) {
|
||||
const rb = args.indexOf("--rollback");
|
||||
const cand = args[rb + 1];
|
||||
if (cand && !cand.startsWith("--")) snapshotPath = cand;
|
||||
}
|
||||
try {
|
||||
const result = await runUpgrade({ dryRun, yes, rollback, list, gc, snapshotPath, target });
|
||||
if (result.plan) for (const line of result.plan) console.log(line);
|
||||
if (result.phases) for (const p of result.phases) console.log(`[${p.name}] ${p.status}${p.cmd ? `: ${p.cmd}` : ""}`);
|
||||
if (result.steps) for (const s of result.steps) console.log(` ${s.status === "ok" ? "✓" : s.status === "skipped-mock" ? "·" : "✗"} ${s.cmd}`);
|
||||
if (result.snapshots) {
|
||||
console.log(`Found ${result.snapshots.length} snapshots:`);
|
||||
for (const s of result.snapshots) console.log(` ${s.name}`);
|
||||
}
|
||||
if (result.removed && result.kept) {
|
||||
console.log(`Snapshots: kept ${result.kept.length}, ${result.dryRun ? "would remove" : "removed"} ${result.removed.length}`);
|
||||
for (const s of result.removed) console.log(` - ${s.name}`);
|
||||
}
|
||||
process.exit(0);
|
||||
} catch (e) {
|
||||
console.error(`✗ ${e.message}`);
|
||||
if (e.snapshotPath) console.error(` snapshot: ${e.snapshotPath}`);
|
||||
if (e.target) console.error(` target: ${e.target}`);
|
||||
if (e.hint) console.error(` hint: ${e.hint}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
+234
-58
@@ -30,19 +30,59 @@
|
||||
import { createServer } from "node:http";
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { randomUUID, timingSafeEqual } from "node:crypto";
|
||||
import { readFileSync, accessSync, existsSync, constants } from "node:fs";
|
||||
import { readFileSync, readdirSync, accessSync, existsSync, constants, chmodSync, statSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { validateKey, recordUsage, getUsageByKey, getUsageTimeline, getRecentUsage, createKey, listKeys, revokeKey, closeDb, checkQuota, updateKeyQuota, getKeyQuota, findKey, cacheHash, getCachedResponse, setCachedResponse, clearCache, getCacheStats } from "./keys.mjs";
|
||||
import { validateKey, recordUsage, getUsageByKey, getUsageTimeline, getRecentUsage, createKey, listKeys, revokeKey, closeDb, checkQuota, updateKeyQuota, getKeyQuota, findKey, cacheHash, getCachedResponse, setCachedResponse, clearCache, getCacheStats, hasCacheControl, singleflight, getInflightStats } from "./keys.mjs";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const _pkg = JSON.parse(readFileSync(join(__dirname, "package.json"), "utf8"));
|
||||
const modelsConfig = JSON.parse(readFileSync(join(__dirname, "models.json"), "utf8"));
|
||||
|
||||
// ── Resolve claude binary ───────────────────────────────────────────────
|
||||
// Priority: CLAUDE_BIN env > well-known paths > which lookup
|
||||
// Fail-fast if not found — never start with an unresolvable binary.
|
||||
// Priority: CLAUDE_BIN env > well-known paths > nvm/fnm/asdf user-local
|
||||
// installs > which lookup. Fail-fast if not found — never start with an
|
||||
// unresolvable binary.
|
||||
function _listVersionDirs(parent) {
|
||||
try { return readdirSync(parent); } catch { return []; }
|
||||
}
|
||||
function _collectNodeManagerCandidates(home) {
|
||||
if (!home) return [];
|
||||
const out = [];
|
||||
|
||||
// nvm: $HOME/.nvm/versions/node/<version>/bin/claude
|
||||
const nvmRoot = join(home, ".nvm/versions/node");
|
||||
for (const v of _listVersionDirs(nvmRoot)) {
|
||||
out.push(join(nvmRoot, v, "bin/claude"));
|
||||
}
|
||||
// nvm default alias: resolve $HOME/.nvm/aliases/default if it points to a version
|
||||
try {
|
||||
const aliasFile = join(home, ".nvm/aliases/default");
|
||||
const aliasVer = readFileSync(aliasFile, "utf8").trim();
|
||||
if (aliasVer) {
|
||||
const direct = join(nvmRoot, aliasVer, "bin/claude");
|
||||
if (!out.includes(direct)) out.unshift(direct);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// fnm: $HOME/.fnm/node-versions/<version>/installation/bin/claude
|
||||
const fnmRoot = join(home, ".fnm/node-versions");
|
||||
for (const v of _listVersionDirs(fnmRoot)) {
|
||||
out.push(join(fnmRoot, v, "installation/bin/claude"));
|
||||
}
|
||||
|
||||
// asdf: $HOME/.asdf/installs/nodejs/<version>/bin/claude
|
||||
const asdfRoot = join(home, ".asdf/installs/nodejs");
|
||||
for (const v of _listVersionDirs(asdfRoot)) {
|
||||
out.push(join(asdfRoot, v, "bin/claude"));
|
||||
}
|
||||
|
||||
// npm prefix-relocated: $HOME/.npm-global/bin/claude
|
||||
out.push(join(home, ".npm-global/bin/claude"));
|
||||
|
||||
return out;
|
||||
}
|
||||
function resolveClaude() {
|
||||
if (process.env.CLAUDE_BIN) {
|
||||
try {
|
||||
@@ -54,11 +94,13 @@ function resolveClaude() {
|
||||
}
|
||||
}
|
||||
|
||||
const home = process.env.HOME || "";
|
||||
const candidates = [
|
||||
"/opt/homebrew/bin/claude",
|
||||
"/usr/local/bin/claude",
|
||||
"/usr/bin/claude",
|
||||
join(process.env.HOME || "", ".local/bin/claude"),
|
||||
join(home, ".local/bin/claude"),
|
||||
..._collectNodeManagerCandidates(home),
|
||||
];
|
||||
for (const p of candidates) {
|
||||
try { accessSync(p, constants.X_OK); console.warn(`[init] CLAUDE_BIN not set, resolved to ${p}`); return p; } catch {}
|
||||
@@ -72,6 +114,8 @@ function resolveClaude() {
|
||||
console.error(
|
||||
"FATAL: claude binary not found.\n" +
|
||||
" Set CLAUDE_BIN=/path/to/claude or ensure claude is in PATH.\n" +
|
||||
" Hint: if you use nvm/fnm/asdf, set CLAUDE_BIN to the absolute path\n" +
|
||||
" shown by `which claude` in your interactive shell.\n" +
|
||||
" Checked: " + candidates.join(", ")
|
||||
);
|
||||
process.exit(1);
|
||||
@@ -123,6 +167,44 @@ function logEvent(level, event, data = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Startup file-mode reconciliation ───────────────────────────────────
|
||||
// Idempotently tightens OCP credential-bearing files to 700/600 so that
|
||||
// existing installs (created before this fix) are hardened on next restart.
|
||||
// Wrapped in try/catch — chmod failure must never crash startup.
|
||||
// Does NOT touch systemd units or launchd plists; those are managed by setup.mjs.
|
||||
function _tightenFileModesIfPossible() {
|
||||
const ocpDir = join(homedir(), ".ocp");
|
||||
const targets = [
|
||||
{ path: ocpDir, mode: 0o700, label: "~/.ocp (dir)" },
|
||||
{ path: join(ocpDir, "admin-key"), mode: 0o600, label: "~/.ocp/admin-key" },
|
||||
{ path: join(ocpDir, "ocp.db"), mode: 0o600, label: "~/.ocp/ocp.db" },
|
||||
];
|
||||
let tightened = 0;
|
||||
let alreadyOk = 0;
|
||||
for (const { path, mode, label } of targets) {
|
||||
try {
|
||||
const st = statSync(path);
|
||||
const current = st.mode & 0o777;
|
||||
if (current !== mode) {
|
||||
chmodSync(path, mode);
|
||||
tightened++;
|
||||
} else {
|
||||
alreadyOk++;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.code !== "ENOENT") {
|
||||
// File exists but chmod failed (e.g. EPERM) — log and move on
|
||||
logEvent("warn", "file_mode_tighten_failed", { path: label, error: e.message });
|
||||
}
|
||||
// ENOENT is fine — file doesn't exist yet
|
||||
}
|
||||
}
|
||||
if (tightened > 0) {
|
||||
logEvent("info", "file_modes_tightened", { tightened, alreadyOk });
|
||||
}
|
||||
}
|
||||
_tightenFileModesIfPossible();
|
||||
|
||||
// ── Circuit breaker (DISABLED) ──────────────────────────────────────────
|
||||
// Disabled: CLI proxy has its own retry logic, and the breaker was causing
|
||||
// cascading failures — once API got briefly slow, ALL agents lost connectivity
|
||||
@@ -158,25 +240,36 @@ const MODEL_MAP = Object.fromEntries([
|
||||
const MODELS = modelsConfig.models.map(m => ({ id: m.id, name: m.displayName }));
|
||||
|
||||
// ── Session management ──────────────────────────────────────────────────
|
||||
// Maps conversation IDs (from caller) to Claude CLI session UUIDs.
|
||||
// Maps namespaced session keys to Claude CLI session UUIDs.
|
||||
// Key format: "${keyName}|${conversationId}" — prevents cross-key collision
|
||||
// when two callers (different API keys or anon + authenticated) use the same
|
||||
// session_id string. Anonymous callers use "anon"; admin uses "admin".
|
||||
// Enables --resume for multi-turn conversations, reducing token waste.
|
||||
const sessions = new Map(); // conversationId → { uuid, messageCount, lastUsed, model }
|
||||
const sessions = new Map(); // `${keyName}|${conversationId}` → { uuid, messageCount, lastUsed, model }
|
||||
|
||||
// Build the namespaced key used for all sessions Map operations.
|
||||
// Returns null when conversationId is falsy (one-off requests bypass session tracking).
|
||||
function _sessionKey(conversationId, keyName) {
|
||||
return conversationId ? `${keyName || "anon"}|${conversationId}` : null;
|
||||
}
|
||||
|
||||
const sessionCleanupInterval = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [id, s] of sessions) {
|
||||
const idleMs = now - s.lastUsed;
|
||||
const ageMs = s.firstSeen ? now - s.firstSeen : null;
|
||||
// id is "${keyName}|${conversationId}"; strip prefix for log output
|
||||
const convIdShort = id.includes("|") ? id.slice(id.indexOf("|") + 1, id.indexOf("|") + 13) : id.slice(0, 12);
|
||||
if (idleMs > SESSION_TTL) {
|
||||
sessions.delete(id);
|
||||
console.log(`[session] expired ${id.slice(0, 12)}... (idle ${Math.round(idleMs / 60000)}m)`);
|
||||
logEvent("info", "session_expired", { conversationId: id.slice(0, 12) + "...", idleMs, ageMs });
|
||||
console.log(`[session] expired ${convIdShort}... (idle ${Math.round(idleMs / 60000)}m)`);
|
||||
logEvent("info", "session_expired", { conversationId: convIdShort + "...", idleMs, ageMs });
|
||||
} else if (ageMs !== null && ageMs > 4 * SESSION_TTL) {
|
||||
// #42 evidence-gathering: a session whose firstSeen is more than 4× TTL old
|
||||
// but whose lastUsed keeps getting bumped (never idle long enough to expire)
|
||||
// is the suspected bug. Log without action so the pattern can be confirmed
|
||||
// in /logs. Do NOT enforce an absolute age cap here speculatively.
|
||||
logEvent("warn", "session_long_lived", { conversationId: id.slice(0, 12) + "...", idleMs, ageMs });
|
||||
logEvent("warn", "session_long_lived", { conversationId: convIdShort + "...", idleMs, ageMs });
|
||||
}
|
||||
}
|
||||
}, 60000);
|
||||
@@ -383,7 +476,7 @@ function getModelTier(cliModel) {
|
||||
// ── Spawn claude CLI (shared setup) ─────────────────────────────────────
|
||||
// Resolves session logic, builds CLI args, spawns the process, and sets up
|
||||
// timeouts. Returns context object or throws synchronously.
|
||||
function spawnClaudeProcess(model, messages, conversationId) {
|
||||
function spawnClaudeProcess(model, messages, conversationId, keyName) {
|
||||
if (stats.activeRequests >= MAX_CONCURRENT) {
|
||||
throw new Error(`concurrency limit reached (${stats.activeRequests}/${MAX_CONCURRENT})`);
|
||||
}
|
||||
@@ -399,8 +492,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
let prompt;
|
||||
|
||||
// ── Session logic ──
|
||||
if (conversationId && sessions.has(conversationId)) {
|
||||
const session = sessions.get(conversationId);
|
||||
// sessionKey namespaces the Map key by keyName to prevent cross-caller collision
|
||||
// when two callers with different API keys share the same conversationId string.
|
||||
const sessionKey = _sessionKey(conversationId, keyName);
|
||||
if (sessionKey && sessions.has(sessionKey)) {
|
||||
const session = sessions.get(sessionKey);
|
||||
session.lastUsed = Date.now();
|
||||
sessionInfo = { uuid: session.uuid, resume: true };
|
||||
stats.sessionHits++;
|
||||
@@ -411,17 +507,17 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
: "";
|
||||
session.messageCount = messages.length;
|
||||
|
||||
console.log(`[session] resume conv=${conversationId.slice(0, 12)}... uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`);
|
||||
console.log(`[session] resume conv=${conversationId.slice(0, 12)}... key=${keyName || "anon"} uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`);
|
||||
|
||||
} else if (conversationId) {
|
||||
} else if (sessionKey) {
|
||||
const uuid = randomUUID();
|
||||
const now = Date.now();
|
||||
sessions.set(conversationId, { uuid, messageCount: messages.length, firstSeen: now, lastUsed: now, model: cliModel });
|
||||
sessions.set(sessionKey, { uuid, messageCount: messages.length, firstSeen: now, lastUsed: now, model: cliModel });
|
||||
sessionInfo = { uuid, resume: false };
|
||||
stats.sessionMisses++;
|
||||
prompt = messagesToPrompt(messages);
|
||||
|
||||
console.log(`[session] new conv=${conversationId.slice(0, 12)}... uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`);
|
||||
console.log(`[session] new conv=${conversationId.slice(0, 12)}... key=${keyName || "anon"} uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`);
|
||||
|
||||
} else {
|
||||
stats.oneOffRequests++;
|
||||
@@ -466,11 +562,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
proc.once("exit", cleanup);
|
||||
|
||||
function handleSessionFailure() {
|
||||
if (sessionInfo?.resume && conversationId) {
|
||||
if (sessionInfo?.resume && sessionKey) {
|
||||
console.warn(`[session] resume failed for ${conversationId.slice(0, 12)}..., removing stale session`);
|
||||
logEvent("warn", "session_failure", { mode: "resume", conversationId: conversationId.slice(0, 12) + "...", action: "deleted" });
|
||||
sessions.delete(conversationId);
|
||||
} else if (sessionInfo && !sessionInfo.resume && conversationId) {
|
||||
sessions.delete(sessionKey);
|
||||
} else if (sessionInfo && !sessionInfo.resume && sessionKey) {
|
||||
// #41 evidence-gathering: session-create failures currently leave a stale entry
|
||||
// in the sessions map. Log without action so the staleness pattern can be
|
||||
// confirmed in /logs before any code change. Do NOT delete here speculatively.
|
||||
@@ -513,11 +609,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
// On-demand spawning: each request spawns a fresh `claude -p` process.
|
||||
// No pool = no crash loops, no stale workers, no degraded states.
|
||||
// Stdin is written immediately so there's no 3s stdin timeout issue.
|
||||
function callClaude(model, messages, conversationId) {
|
||||
function callClaude(model, messages, conversationId, keyName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let ctx;
|
||||
try {
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId);
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId, keyName);
|
||||
} catch (err) {
|
||||
return reject(err);
|
||||
}
|
||||
@@ -590,13 +686,14 @@ function startHeartbeat(res, intervalMs, sessionId) {
|
||||
// ── Call claude CLI (real streaming) ─────────────────────────────────────
|
||||
// Pipes stdout from the claude process directly to SSE chunks as they arrive.
|
||||
// Each data chunk becomes a proper SSE event with delta content in real time.
|
||||
// TODO(cache-singleflight-stream): streaming-path singleflight is out of scope for v3.13.0; see spec D4 streaming caveat.
|
||||
function callClaudeStreaming(model, messages, conversationId, res, authInfo = {}) {
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
|
||||
let ctx;
|
||||
try {
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId);
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId, authInfo.keyName);
|
||||
} catch (err) {
|
||||
return jsonResponse(res, 500, { error: { message: err.message, type: "proxy_error" } });
|
||||
}
|
||||
@@ -1218,30 +1315,43 @@ async function handleChatCompletions(req, res) {
|
||||
|
||||
// Cache check (only when cache is enabled and no active conversation/session)
|
||||
if (CACHE_TTL > 0 && !conversationId) {
|
||||
const hash = cacheHash(model, messages, { temperature: parsed.temperature, max_tokens: parsed.max_tokens, top_p: parsed.top_p });
|
||||
req._cacheHash = hash; // store for later write-back
|
||||
try {
|
||||
const cached = getCachedResponse(hash, CACHE_TTL);
|
||||
if (cached) {
|
||||
logEvent("info", "cache_hit", { model, hash: hash.slice(0, 12), hits: cached.hits });
|
||||
if (stream) {
|
||||
// Simulate streaming for cached response
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" });
|
||||
sendSSE(res, { id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] });
|
||||
sendSSE(res, { id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { content: cached.response }, finish_reason: null }] });
|
||||
sendSSE(res, { id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });
|
||||
res.write("data: [DONE]\n\n");
|
||||
res.end();
|
||||
return;
|
||||
} else {
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
return completionResponse(res, id, model, cached.response);
|
||||
// D2: skip OCP cache entirely when messages carry cache_control annotations;
|
||||
// the client is requesting Anthropic-side prompt caching, not OCP-layer caching.
|
||||
if (hasCacheControl(messages)) {
|
||||
req._cacheHash = null;
|
||||
logEvent("info", "cache_skipped", { reason: "cache_control_present" });
|
||||
} else {
|
||||
// D1: include keyId in hash to isolate per-key cache pools (v2 format)
|
||||
const hash = cacheHash(model, messages, { keyId: req._authKeyId, temperature: parsed.temperature, max_tokens: parsed.max_tokens, top_p: parsed.top_p });
|
||||
req._cacheHash = hash; // store for later write-back
|
||||
try {
|
||||
const cached = getCachedResponse(hash, CACHE_TTL);
|
||||
if (cached) {
|
||||
logEvent("info", "cache_hit", { model, hash: hash.slice(0, 12), hits: cached.hits });
|
||||
if (stream) {
|
||||
// D3: replay cached content as chunked SSE stream (80 codepoints/chunk)
|
||||
const CACHE_REPLAY_CHUNK_SIZE = 80;
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" });
|
||||
sendSSE(res, { id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] });
|
||||
const codepoints = Array.from(cached.response);
|
||||
for (let i = 0; i < codepoints.length; i += CACHE_REPLAY_CHUNK_SIZE) {
|
||||
const chunk = codepoints.slice(i, i + CACHE_REPLAY_CHUNK_SIZE).join("");
|
||||
sendSSE(res, { id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }] });
|
||||
}
|
||||
sendSSE(res, { id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });
|
||||
res.write("data: [DONE]\n\n");
|
||||
res.end();
|
||||
return;
|
||||
} else {
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
return completionResponse(res, id, model, cached.response);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logEvent("error", "cache_check_failed", { error: e.message });
|
||||
}
|
||||
} catch (e) {
|
||||
logEvent("error", "cache_check_failed", { error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1252,14 +1362,45 @@ async function handleChatCompletions(req, res) {
|
||||
|
||||
const t0Usage = Date.now();
|
||||
const promptChars = messages.reduce((a, m) => a + (typeof m.content === "string" ? m.content.length : JSON.stringify(m.content).length), 0);
|
||||
|
||||
// Non-streaming path with stampede protection: wrap the upstream call in singleflight
|
||||
// when cache is enabled and a hash is present. Concurrent identical requests share
|
||||
// one upstream spawn; followers receive the same promise. Streaming-path dedup is
|
||||
// explicitly out of scope (see TODO comment above callClaudeStreaming).
|
||||
if (CACHE_TTL > 0 && req._cacheHash) {
|
||||
try {
|
||||
const content = await singleflight(req._cacheHash, async () => {
|
||||
// Re-check cache inside the singleflight: a follower that enters before the
|
||||
// leader finishes will wait on the shared promise (not reach here), but a
|
||||
// request that races in just after the previous singleflight cleared the map
|
||||
// will re-read the freshly-populated cache entry here rather than spawning.
|
||||
const recheck = getCachedResponse(req._cacheHash, CACHE_TTL);
|
||||
if (recheck) return recheck.response;
|
||||
const c = await callClaude(model, messages, conversationId, req._authKeyName);
|
||||
try { setCachedResponse(req._cacheHash, model, c); } catch (e) { logEvent("error", "cache_write_failed", { error: e.message }); }
|
||||
return c;
|
||||
});
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
completionResponse(res, id, model, content);
|
||||
try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: content.length, elapsedMs: Date.now() - t0Usage, success: true }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); }
|
||||
return;
|
||||
} catch (err) {
|
||||
try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: 0, elapsedMs: Date.now() - t0Usage, success: false }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); }
|
||||
console.error(`[proxy] error: ${err.message}`);
|
||||
if (res.headersSent || res.writableEnded || res.destroyed) {
|
||||
try { res.end(); } catch {}
|
||||
return;
|
||||
}
|
||||
const safeMessage = (err.message || "Internal error").replace(/\/[\w/.\-]+/g, "[path]");
|
||||
return jsonResponse(res, 500, { error: { message: safeMessage, type: "proxy_error" } });
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: cache disabled (CACHE_TTL=0) or no _cacheHash — original path untouched.
|
||||
try {
|
||||
const content = await callClaude(model, messages, conversationId);
|
||||
const content = await callClaude(model, messages, conversationId, req._authKeyName);
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
completionResponse(res, id, model, content);
|
||||
// Write to cache
|
||||
if (CACHE_TTL > 0 && req._cacheHash) {
|
||||
try { setCachedResponse(req._cacheHash, model, content); } catch (e) { logEvent("error", "cache_write_failed", { error: e.message }); }
|
||||
}
|
||||
try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: content.length, elapsedMs: Date.now() - t0Usage, success: true }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); }
|
||||
} catch (err) {
|
||||
try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: 0, elapsedMs: Date.now() - t0Usage, success: false }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); }
|
||||
@@ -1391,8 +1532,10 @@ const server = createServer(async (req, res) => {
|
||||
const uptimeMs = Date.now() - START_TIME;
|
||||
const sessionList = [];
|
||||
for (const [id, s] of sessions) {
|
||||
// id is "${keyName}|${conversationId}"; expose only the public-facing conversationId
|
||||
const convId = id.includes("|") ? id.slice(id.indexOf("|") + 1) : id;
|
||||
sessionList.push({
|
||||
id: id.slice(0, 12) + "...",
|
||||
id: convId.slice(0, 12) + "...",
|
||||
model: s.model,
|
||||
messages: s.messageCount,
|
||||
idleMs: Date.now() - s.lastUsed,
|
||||
@@ -1437,7 +1580,9 @@ const server = createServer(async (req, res) => {
|
||||
if (req.url === "/sessions" && req.method === "GET") {
|
||||
const list = [];
|
||||
for (const [id, s] of sessions) {
|
||||
list.push({ id, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() });
|
||||
// id is "${keyName}|${conversationId}"; expose only the public-facing conversationId
|
||||
const convId = id.includes("|") ? id.slice(id.indexOf("|") + 1) : id;
|
||||
list.push({ id: convId, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() });
|
||||
}
|
||||
return jsonResponse(res, 200, { sessions: list });
|
||||
}
|
||||
@@ -1527,21 +1672,52 @@ const server = createServer(async (req, res) => {
|
||||
}
|
||||
|
||||
if (req.url?.startsWith("/api/usage") && req.method === "GET") {
|
||||
if (!isAdmin) return jsonResponse(res, 403, { error: "Admin access required" });
|
||||
// Least-privilege scope rules (security audit follow-up):
|
||||
// - non-admin authenticated key → only own rows
|
||||
// - anonymous (PROXY_ANONYMOUS_KEY) → only "anonymous" rows; ?all=true ignored
|
||||
// - admin without ?all=true → only own ("admin") rows
|
||||
// - admin with ?all=true → full byKey/recent (legacy behavior); audited
|
||||
// Authenticated callers are required (anyone reaching here passed the auth gate above);
|
||||
// remote+no-auth requests would have been rejected before this point.
|
||||
const url = new URL(req.url, `http://${BIND_ADDRESS}:${PORT}`);
|
||||
const since = url.searchParams.get("since");
|
||||
const until = url.searchParams.get("until");
|
||||
const wantAll = url.searchParams.get("all") === "true";
|
||||
const callerName = req._authKeyName;
|
||||
|
||||
// Anonymous callers may never opt into all-keys view, even if they pass ?all=true.
|
||||
const isAnonCaller = callerName === "anonymous";
|
||||
const fullScope = isAdmin && wantAll && !isAnonCaller;
|
||||
|
||||
// scopeName === null when fullScope is true (no filter); otherwise the key_name to filter by.
|
||||
const scopeName = fullScope ? null : callerName;
|
||||
|
||||
if (fullScope) {
|
||||
logEvent("info", "admin_usage_full_scope", { caller: callerName, ip: req.socket.remoteAddress || null });
|
||||
}
|
||||
|
||||
const byKeyAll = getUsageByKey({ since, until });
|
||||
const recentAll = getRecentUsage(Math.min(parseInt(url.searchParams.get("limit") || "50", 10), 500));
|
||||
const timeline = getUsageTimeline({
|
||||
keyName: scopeName || undefined,
|
||||
hours: Math.min(parseInt(url.searchParams.get("hours") || "24", 10), 720),
|
||||
});
|
||||
|
||||
const byKey = scopeName ? byKeyAll.filter((row) => row.key_name === scopeName) : byKeyAll;
|
||||
const recent = scopeName ? recentAll.filter((row) => row.key_name === scopeName) : recentAll;
|
||||
|
||||
return jsonResponse(res, 200, {
|
||||
byKey: getUsageByKey({ since, until }),
|
||||
timeline: getUsageTimeline({ hours: Math.min(parseInt(url.searchParams.get("hours") || "24", 10), 720) }),
|
||||
recent: getRecentUsage(Math.min(parseInt(url.searchParams.get("limit") || "50", 10), 500)),
|
||||
byKey,
|
||||
timeline,
|
||||
recent,
|
||||
scope: { self: scopeName, all: fullScope },
|
||||
});
|
||||
}
|
||||
|
||||
// GET /cache/stats — cache statistics
|
||||
// GET /cache/stats — cache statistics (entries, hits, size, inflight singleflight count)
|
||||
if (pathname === "/cache/stats" && req.method === "GET") {
|
||||
if (!isAdmin) return jsonResponse(res, 403, { error: "Admin access required" });
|
||||
return jsonResponse(res, 200, getCacheStats());
|
||||
return jsonResponse(res, 200, { ...getCacheStats(), ...getInflightStats() });
|
||||
}
|
||||
|
||||
// DELETE /cache — clear cache
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* openclaw-claude-proxy setup
|
||||
* OCP (Open Claude Proxy) setup
|
||||
*
|
||||
* Automatically configures OpenClaw to use Claude CLI as a model provider.
|
||||
* Run: node setup.mjs [--port 3456] [--default-model opus|sonnet|haiku] [--dry-run]
|
||||
@@ -12,7 +12,8 @@
|
||||
* 4. Creates start.sh for easy launch
|
||||
* 5. Optionally starts the proxy
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync, chmodSync } from "node:fs";
|
||||
import { mergePlistEnv, mergeSystemdEnv } from "./scripts/lib/plist-merge.mjs";
|
||||
import { execSync } from "node:child_process";
|
||||
import { join, dirname } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
@@ -39,6 +40,29 @@ const PROVIDER_NAME = opt("provider-name", "claude-local");
|
||||
const BIND_ADDRESS = opt("bind", "127.0.0.1");
|
||||
const AUTH_MODE_CONFIG = opt("auth-mode", "none");
|
||||
|
||||
// ── Service-env injection: CLAUDE_BIN, OCP_ADMIN_KEY, PROXY_ANONYMOUS_KEY ──
|
||||
// These are read from the user's shell env at install time and written into
|
||||
// the service unit (plist / systemd) so the daemon picks them up on boot.
|
||||
|
||||
// CLAUDE_BIN — detect at install time; omit if not found (server.mjs fallback)
|
||||
let CLAUDE_BIN_INJECT = null;
|
||||
if (process.env.CLAUDE_BIN) {
|
||||
CLAUDE_BIN_INJECT = process.env.CLAUDE_BIN;
|
||||
} else {
|
||||
try {
|
||||
const detected = execSync("which claude 2>/dev/null", { encoding: "utf-8" }).trim();
|
||||
if (detected && existsSync(detected)) {
|
||||
CLAUDE_BIN_INJECT = detected;
|
||||
}
|
||||
} catch { /* which not available or claude not on PATH — omit */ }
|
||||
}
|
||||
|
||||
// OCP_ADMIN_KEY — omit entirely when empty/unset; don't write empty string
|
||||
const OCP_ADMIN_KEY_INJECT = process.env.OCP_ADMIN_KEY || null;
|
||||
|
||||
// PROXY_ANONYMOUS_KEY — same pattern
|
||||
const PROXY_ANON_KEY_INJECT = process.env.PROXY_ANONYMOUS_KEY || null;
|
||||
|
||||
// ── Models: derived from models.json (single source of truth) ──────────
|
||||
const modelsConfig = JSON.parse(readFileSync(join(__dirname, "models.json"), "utf-8"));
|
||||
|
||||
@@ -107,106 +131,112 @@ try {
|
||||
warn("Make sure you're logged in: claude login");
|
||||
}
|
||||
|
||||
// Check openclaw config
|
||||
if (!existsSync(CONFIG_PATH)) fail(`OpenClaw config not found at ${CONFIG_PATH}`);
|
||||
log(`OpenClaw config: ${CONFIG_PATH}`);
|
||||
// Check openclaw config (optional — OCP runs standalone without OpenClaw)
|
||||
const OPENCLAW_PRESENT = existsSync(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 ─────────────────────────────────────────
|
||||
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
|
||||
if (!config.models) config.models = {};
|
||||
if (!config.models.providers) config.models.providers = {};
|
||||
// Ensure models.providers exists
|
||||
if (!config.models) config.models = {};
|
||||
if (!config.models.providers) config.models.providers = {};
|
||||
|
||||
// Add/update claude-local provider
|
||||
config.models.providers[PROVIDER_NAME] = {
|
||||
baseUrl: `http://127.0.0.1:${PORT}/v1`,
|
||||
api: "openai-completions",
|
||||
authHeader: false,
|
||||
models: MODELS,
|
||||
};
|
||||
log(`Provider "${PROVIDER_NAME}" → http://127.0.0.1:${PORT}/v1`);
|
||||
// Add/update claude-local provider
|
||||
config.models.providers[PROVIDER_NAME] = {
|
||||
baseUrl: `http://127.0.0.1:${PORT}/v1`,
|
||||
api: "openai-completions",
|
||||
authHeader: false,
|
||||
models: MODELS,
|
||||
};
|
||||
log(`Provider "${PROVIDER_NAME}" → http://127.0.0.1:${PORT}/v1`);
|
||||
|
||||
// Ensure auth profile in config
|
||||
if (!config.auth) config.auth = {};
|
||||
if (!config.auth.profiles) config.auth.profiles = {};
|
||||
config.auth.profiles[`${PROVIDER_NAME}:default`] = {
|
||||
provider: PROVIDER_NAME,
|
||||
mode: "api_key",
|
||||
};
|
||||
log(`Auth profile "${PROVIDER_NAME}:default" registered`);
|
||||
// Ensure auth profile in config
|
||||
if (!config.auth) config.auth = {};
|
||||
if (!config.auth.profiles) config.auth.profiles = {};
|
||||
config.auth.profiles[`${PROVIDER_NAME}:default`] = {
|
||||
provider: PROVIDER_NAME,
|
||||
mode: "api_key",
|
||||
};
|
||||
log(`Auth profile "${PROVIDER_NAME}:default" registered`);
|
||||
|
||||
// Add models to agents.defaults.models
|
||||
if (!config.agents) config.agents = {};
|
||||
if (!config.agents.defaults) config.agents.defaults = {};
|
||||
if (!config.agents.defaults.models) config.agents.defaults.models = {};
|
||||
for (const [key, val] of Object.entries(MODEL_ALIASES)) {
|
||||
config.agents.defaults.models[key] = val;
|
||||
}
|
||||
log(`Model aliases added to agents.defaults.models`);
|
||||
|
||||
// Set idleTimeoutSeconds to 0 — critical for Claude tool-use.
|
||||
// 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,
|
||||
// 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.idleTimeoutSeconds === undefined ||
|
||||
config.agents.defaults.llm.idleTimeoutSeconds > 0) {
|
||||
config.agents.defaults.llm.idleTimeoutSeconds = 0;
|
||||
log(`Set agents.defaults.llm.idleTimeoutSeconds = 0 (prevents tool-call timeouts)`);
|
||||
} else {
|
||||
log(`idleTimeoutSeconds already configured: ${config.agents.defaults.llm.idleTimeoutSeconds}`);
|
||||
}
|
||||
|
||||
writeJSON(CONFIG_PATH, config);
|
||||
log(`Config saved`);
|
||||
|
||||
// ── Step 3: Patch auth-profiles.json ────────────────────────────────────
|
||||
console.log("\n🔑 Configuring auth profiles...\n");
|
||||
|
||||
// Find all agent auth-profiles.json files
|
||||
const agentsDir = join(OPENCLAW_DIR, "agents");
|
||||
const agentDirs = existsSync(agentsDir)
|
||||
? readdirSync(agentsDir).filter((d) => {
|
||||
const ap = join(agentsDir, d, "agent", "auth-profiles.json");
|
||||
return existsSync(ap);
|
||||
})
|
||||
: [];
|
||||
|
||||
import { readdirSync } from "node:fs";
|
||||
|
||||
for (const agentId of agentDirs) {
|
||||
const apPath = join(agentsDir, agentId, "agent", "auth-profiles.json");
|
||||
try {
|
||||
const ap = readJSON(apPath);
|
||||
if (!ap.profiles) ap.profiles = {};
|
||||
|
||||
// Add claude-local profile if missing
|
||||
if (!ap.profiles[`${PROVIDER_NAME}:default`]) {
|
||||
ap.profiles[`${PROVIDER_NAME}:default`] = {
|
||||
type: "api_key",
|
||||
provider: PROVIDER_NAME,
|
||||
key: "local-proxy-no-auth",
|
||||
};
|
||||
}
|
||||
|
||||
// Add to lastGood if missing
|
||||
if (!ap.lastGood) ap.lastGood = {};
|
||||
if (!ap.lastGood[PROVIDER_NAME]) {
|
||||
ap.lastGood[PROVIDER_NAME] = `${PROVIDER_NAME}:default`;
|
||||
}
|
||||
|
||||
writeJSON(apPath, ap);
|
||||
log(`Agent "${agentId}" auth profile updated`);
|
||||
} catch (e) {
|
||||
warn(`Skipped agent "${agentId}": ${e.message}`);
|
||||
// Add models to agents.defaults.models
|
||||
if (!config.agents) config.agents = {};
|
||||
if (!config.agents.defaults) config.agents.defaults = {};
|
||||
if (!config.agents.defaults.models) config.agents.defaults.models = {};
|
||||
for (const [key, val] of Object.entries(MODEL_ALIASES)) {
|
||||
config.agents.defaults.models[key] = val;
|
||||
}
|
||||
}
|
||||
log(`Model aliases added to agents.defaults.models`);
|
||||
|
||||
if (agentDirs.length === 0) {
|
||||
warn("No agent auth-profiles.json found — you may need to restart the gateway first");
|
||||
// Set idleTimeoutSeconds to 0 — critical for Claude tool-use.
|
||||
// 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,
|
||||
// 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.idleTimeoutSeconds === undefined ||
|
||||
config.agents.defaults.llm.idleTimeoutSeconds > 0) {
|
||||
config.agents.defaults.llm.idleTimeoutSeconds = 0;
|
||||
log(`Set agents.defaults.llm.idleTimeoutSeconds = 0 (prevents tool-call timeouts)`);
|
||||
} else {
|
||||
log(`idleTimeoutSeconds already configured: ${config.agents.defaults.llm.idleTimeoutSeconds}`);
|
||||
}
|
||||
|
||||
writeJSON(CONFIG_PATH, config);
|
||||
log(`Config saved`);
|
||||
|
||||
// ── Step 3: Patch auth-profiles.json ────────────────────────────────────
|
||||
console.log("\n🔑 Configuring auth profiles...\n");
|
||||
|
||||
// Find all agent auth-profiles.json files
|
||||
const agentsDir = join(OPENCLAW_DIR, "agents");
|
||||
const agentDirs = existsSync(agentsDir)
|
||||
? readdirSync(agentsDir).filter((d) => {
|
||||
const ap = join(agentsDir, d, "agent", "auth-profiles.json");
|
||||
return existsSync(ap);
|
||||
})
|
||||
: [];
|
||||
|
||||
for (const agentId of agentDirs) {
|
||||
const apPath = join(agentsDir, agentId, "agent", "auth-profiles.json");
|
||||
try {
|
||||
const ap = readJSON(apPath);
|
||||
if (!ap.profiles) ap.profiles = {};
|
||||
|
||||
// Add claude-local profile if missing
|
||||
if (!ap.profiles[`${PROVIDER_NAME}:default`]) {
|
||||
ap.profiles[`${PROVIDER_NAME}:default`] = {
|
||||
type: "api_key",
|
||||
provider: PROVIDER_NAME,
|
||||
key: "local-proxy-no-auth",
|
||||
};
|
||||
}
|
||||
|
||||
// Add to lastGood if missing
|
||||
if (!ap.lastGood) ap.lastGood = {};
|
||||
if (!ap.lastGood[PROVIDER_NAME]) {
|
||||
ap.lastGood[PROVIDER_NAME] = `${PROVIDER_NAME}:default`;
|
||||
}
|
||||
|
||||
writeJSON(apPath, ap);
|
||||
log(`Agent "${agentId}" auth profile updated`);
|
||||
} catch (e) {
|
||||
warn(`Skipped agent "${agentId}": ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (agentDirs.length === 0) {
|
||||
warn("No agent auth-profiles.json found — you may need to restart the gateway first");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Step 4: Create start.sh ─────────────────────────────────────────────
|
||||
@@ -217,7 +247,7 @@ const logDir = join(OPENCLAW_DIR, "logs");
|
||||
if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true });
|
||||
|
||||
const startSh = `#!/bin/bash
|
||||
# Start openclaw-claude-proxy if not already running
|
||||
# Start OCP (Open Claude Proxy) if not already running
|
||||
PORT=\${CLAUDE_PROXY_PORT:-${PORT}}
|
||||
if ! lsof -i :\$PORT -sTCP:LISTEN &>/dev/null; then
|
||||
unset CLAUDECODE
|
||||
@@ -238,40 +268,71 @@ if (!DRY_RUN) {
|
||||
log(`Launcher: ${startPath}`);
|
||||
|
||||
// ── Step 5: Summary ─────────────────────────────────────────────────────
|
||||
console.log(`
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ Setup complete! ║
|
||||
╠══════════════════════════════════════════════════════════════╣
|
||||
║ ║
|
||||
║ Provider: ${PROVIDER_NAME.padEnd(44)}║
|
||||
║ Port: ${String(PORT).padEnd(44)}║
|
||||
║ Models: ${`see models.json (${MODELS.length} available)`.padEnd(44)}║
|
||||
║ Default: ${DEFAULT_MODEL_ID.padEnd(44)}║
|
||||
║ ║
|
||||
║ Start proxy: ║
|
||||
║ bash ${startPath.replace(HOME, "~").padEnd(50)}║
|
||||
║ ║
|
||||
║ Or directly: ║
|
||||
║ node ${serverPath.replace(HOME, "~").padEnd(49)}║
|
||||
║ ║
|
||||
║ Set as default model in openclaw.json: ║
|
||||
║ agents.defaults.model.primary = ║
|
||||
║ "${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) {
|
||||
try {
|
||||
execSync(`bash "${startPath}"`, { stdio: "inherit" });
|
||||
} catch { /* ignore */ }
|
||||
const banner = [
|
||||
`╔══════════════════════════════════════════════════════════════╗`,
|
||||
`║ Setup complete! ║`,
|
||||
`╠══════════════════════════════════════════════════════════════╣`,
|
||||
`║ ║`,
|
||||
`║ Provider: ${PROVIDER_NAME.padEnd(44)}║`,
|
||||
`║ Port: ${String(PORT).padEnd(44)}║`,
|
||||
`║ Models: ${`see models.json (${MODELS.length} available)`.padEnd(44)}║`,
|
||||
`║ Default: ${DEFAULT_MODEL_ID.padEnd(44)}║`,
|
||||
`║ ║`,
|
||||
`║ Start proxy: ║`,
|
||||
`║ bash ${startPath.replace(HOME, "~").padEnd(50)}║`,
|
||||
`║ ║`,
|
||||
`║ Or directly: ║`,
|
||||
`║ node ${serverPath.replace(HOME, "~").padEnd(49)}║`,
|
||||
`║ ║`,
|
||||
];
|
||||
if (OPENCLAW_PRESENT) {
|
||||
banner.push(
|
||||
`║ Set as default model in openclaw.json: ║`,
|
||||
`║ agents.defaults.model.primary = ║`,
|
||||
`║ "${PROVIDER_NAME}/${DEFAULT_MODEL_ID}"${" ".repeat(Math.max(0, 30 - PROVIDER_NAME.length - DEFAULT_MODEL_ID.length))}║`,
|
||||
`║ ║`,
|
||||
`║ Then restart gateway: ║`,
|
||||
`║ openclaw gateway restart ║`,
|
||||
`║ ║`,
|
||||
);
|
||||
} else {
|
||||
banner.push(
|
||||
`║ OpenClaw not detected — running in standalone mode. ║`,
|
||||
`║ 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 ──────────────────────────────────
|
||||
|
||||
// Log service-env injection plan (shown in both dry-run and live mode)
|
||||
console.log("\n🔧 Service unit env vars to inject:\n");
|
||||
if (CLAUDE_BIN_INJECT) {
|
||||
log(`CLAUDE_BIN: ${CLAUDE_BIN_INJECT}`);
|
||||
} else {
|
||||
log(`CLAUDE_BIN: (not found — server.mjs will auto-detect at runtime)`);
|
||||
}
|
||||
if (OCP_ADMIN_KEY_INJECT) {
|
||||
log(`OCP_ADMIN_KEY: injected (length: ${OCP_ADMIN_KEY_INJECT.length})`);
|
||||
} else {
|
||||
log(`OCP_ADMIN_KEY: (unset — admin endpoints disabled)`);
|
||||
}
|
||||
if (PROXY_ANON_KEY_INJECT) {
|
||||
log(`PROXY_ANONYMOUS_KEY: injected (set)`);
|
||||
} else {
|
||||
log(`PROXY_ANONYMOUS_KEY: (unset — anonymous access disabled)`);
|
||||
}
|
||||
|
||||
if (DRY_RUN) {
|
||||
console.log("\n [dry-run] would write service unit with above env vars\n");
|
||||
}
|
||||
|
||||
if (!DRY_RUN) {
|
||||
console.log("\n🔄 Installing auto-start on login...\n");
|
||||
|
||||
@@ -344,7 +405,13 @@ if (!DRY_RUN) {
|
||||
<key>CLAUDE_BIND</key>
|
||||
<string>${BIND_ADDRESS}</string>
|
||||
<key>CLAUDE_AUTH_MODE</key>
|
||||
<string>${AUTH_MODE_CONFIG}</string>
|
||||
<string>${AUTH_MODE_CONFIG}</string>${CLAUDE_BIN_INJECT ? `
|
||||
<key>CLAUDE_BIN</key>
|
||||
<string>${CLAUDE_BIN_INJECT}</string>` : ""}${OCP_ADMIN_KEY_INJECT ? `
|
||||
<key>OCP_ADMIN_KEY</key>
|
||||
<string>${OCP_ADMIN_KEY_INJECT}</string>` : ""}${PROXY_ANON_KEY_INJECT ? `
|
||||
<key>PROXY_ANONYMOUS_KEY</key>
|
||||
<string>${PROXY_ANON_KEY_INJECT}</string>` : ""}
|
||||
</dict>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
@@ -358,8 +425,15 @@ if (!DRY_RUN) {
|
||||
</plist>
|
||||
`;
|
||||
|
||||
writeFileSync(plistPath, plistXml);
|
||||
log(`Plist written: ${plistPath}`);
|
||||
const existingPlist = existsSync(plistPath) ? readFileSync(plistPath, "utf8") : null;
|
||||
const finalPlistXml = mergePlistEnv(existingPlist, plistXml);
|
||||
writeFileSync(plistPath, finalPlistXml);
|
||||
chmodSync(plistPath, 0o600);
|
||||
if (existingPlist && finalPlistXml !== plistXml) {
|
||||
log(`Plist written: ${plistPath} (mode 600, preserved user env vars)`);
|
||||
} else {
|
||||
log(`Plist written: ${plistPath} (mode 600)`);
|
||||
}
|
||||
|
||||
// Bootout first (in case it was already loaded) then bootstrap
|
||||
try { execSync(`launchctl bootout gui/$(id -u) "${plistPath}" 2>/dev/null`); } catch { /* ignore */ }
|
||||
@@ -382,7 +456,7 @@ After=network.target
|
||||
ExecStart=${nodeBin} ${serverPath}
|
||||
Environment=CLAUDE_PROXY_PORT=${PORT}
|
||||
Environment=CLAUDE_BIND=${BIND_ADDRESS}
|
||||
Environment=CLAUDE_AUTH_MODE=${AUTH_MODE_CONFIG}
|
||||
Environment=CLAUDE_AUTH_MODE=${AUTH_MODE_CONFIG}${CLAUDE_BIN_INJECT ? `\nEnvironment=CLAUDE_BIN=${CLAUDE_BIN_INJECT}` : ""}${OCP_ADMIN_KEY_INJECT ? `\nEnvironment=OCP_ADMIN_KEY=${OCP_ADMIN_KEY_INJECT}` : ""}${PROXY_ANON_KEY_INJECT ? `\nEnvironment=PROXY_ANONYMOUS_KEY=${PROXY_ANON_KEY_INJECT}` : ""}
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
StandardOutput=append:${logPath}
|
||||
@@ -392,8 +466,15 @@ StandardError=append:${logPath}
|
||||
WantedBy=default.target
|
||||
`;
|
||||
|
||||
writeFileSync(servicePath, serviceUnit);
|
||||
log(`Service file written: ${servicePath}`);
|
||||
const existingService = existsSync(servicePath) ? readFileSync(servicePath, "utf8") : null;
|
||||
const finalServiceUnit = mergeSystemdEnv(existingService, serviceUnit);
|
||||
writeFileSync(servicePath, finalServiceUnit);
|
||||
chmodSync(servicePath, 0o600);
|
||||
if (existingService && finalServiceUnit !== serviceUnit) {
|
||||
log(`Service file written: ${servicePath} (mode 600, preserved user env vars)`);
|
||||
} else {
|
||||
log(`Service file written: ${servicePath} (mode 600)`);
|
||||
}
|
||||
|
||||
execSync(`systemctl --user daemon-reload`);
|
||||
execSync(`systemctl --user enable ocp-proxy`);
|
||||
@@ -405,4 +486,52 @@ WantedBy=default.target
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Start openclaw-claude-proxy if not already running
|
||||
PORT=${CLAUDE_PROXY_PORT:-3456}
|
||||
if ! lsof -i :$PORT -sTCP:LISTEN &>/dev/null; then
|
||||
unset CLAUDECODE
|
||||
nohup node "/Users/taodeng/.openclaw/projects/claude-proxy/server.mjs" \
|
||||
>> "/Users/taodeng/.openclaw/logs/claude-proxy.log" \
|
||||
2>> "/Users/taodeng/.openclaw/logs/claude-proxy.err.log" &
|
||||
echo "claude-proxy started on port $PORT (pid $!)"
|
||||
else
|
||||
echo "claude-proxy already running on port $PORT"
|
||||
fi
|
||||
+699
-1
@@ -3,7 +3,8 @@
|
||||
* Integration test for Quota + Cache features.
|
||||
* Tests database layer functions directly — no server needed.
|
||||
*/
|
||||
import { getDb, createKey, listKeys, validateKey, recordUsage, checkQuota, updateKeyQuota, getKeyQuota, findKey, cacheHash, getCachedResponse, setCachedResponse, clearCache, getCacheStats, closeDb } from "./keys.mjs";
|
||||
import { getDb, createKey, listKeys, validateKey, recordUsage, checkQuota, updateKeyQuota, getKeyQuota, findKey, cacheHash, getCachedResponse, setCachedResponse, clearCache, getCacheStats, closeDb, hasCacheControl, singleflight, getInflightStats } from "./keys.mjs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { strict as assert } from "node:assert";
|
||||
import { unlinkSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -253,6 +254,703 @@ test("clearCache with TTL only removes old entries", () => {
|
||||
clearCache();
|
||||
});
|
||||
|
||||
// ── PR-A: Per-key isolation (D1), cache_control bypass (D2), chunked replay (D3) ──
|
||||
console.log("\nPR-A Cache Upgrade:");
|
||||
|
||||
const msgsBase = [{ role: "user", content: "Shared prompt text" }];
|
||||
|
||||
test("D1: cacheHash with two distinct keyIds produces different hashes", () => {
|
||||
const h1 = cacheHash("sonnet", msgsBase, { keyId: "key-aaa" });
|
||||
const h2 = cacheHash("sonnet", msgsBase, { keyId: "key-bbb" });
|
||||
assert.notEqual(h1, h2);
|
||||
});
|
||||
|
||||
test("D1: cacheHash with keyId=undefined and keyId='anon' produce the same hash", () => {
|
||||
const hUndef = cacheHash("sonnet", msgsBase, { keyId: undefined });
|
||||
const hAnon = cacheHash("sonnet", msgsBase, { keyId: "anon" });
|
||||
assert.equal(hUndef, hAnon);
|
||||
});
|
||||
|
||||
test("D1: cacheHash with keyId=null and keyId='anon' produce the same hash", () => {
|
||||
const hNull = cacheHash("sonnet", msgsBase, { keyId: null });
|
||||
const hAnon = cacheHash("sonnet", msgsBase, { keyId: "anon" });
|
||||
assert.equal(hNull, hAnon);
|
||||
});
|
||||
|
||||
test("D1: v2 prefix — hash differs from a v1-style baseline (no prefix)", () => {
|
||||
// Reproduce a v1-style hash manually to confirm v2 differs
|
||||
const v1 = createHash("sha256")
|
||||
.update("sonnet")
|
||||
.update(msgsBase[0].role)
|
||||
.update(msgsBase[0].content)
|
||||
.digest("hex");
|
||||
const v2 = cacheHash("sonnet", msgsBase, { keyId: "anon" });
|
||||
assert.notEqual(v1, v2);
|
||||
});
|
||||
|
||||
test("D1: cacheHash is reproducible for same keyId (determinism)", () => {
|
||||
const h1 = cacheHash("sonnet", msgsBase, { keyId: "key-xyz" });
|
||||
const h2 = cacheHash("sonnet", msgsBase, { keyId: "key-xyz" });
|
||||
assert.equal(h1, h2);
|
||||
});
|
||||
|
||||
test("D2: hasCacheControl returns true for top-level cache_control on message", () => {
|
||||
const msgs = [{ role: "user", cache_control: { type: "ephemeral" }, content: "hello" }];
|
||||
assert.equal(hasCacheControl(msgs), true);
|
||||
});
|
||||
|
||||
test("D2: hasCacheControl returns true for nested cache_control in content array", () => {
|
||||
const msgs = [{ role: "user", content: [{ type: "text", text: "x", cache_control: { type: "ephemeral" } }] }];
|
||||
assert.equal(hasCacheControl(msgs), true);
|
||||
});
|
||||
|
||||
test("D2: hasCacheControl returns false for plain string content", () => {
|
||||
const msgs = [{ role: "user", content: "plain string" }];
|
||||
assert.equal(hasCacheControl(msgs), false);
|
||||
});
|
||||
|
||||
test("D2: hasCacheControl returns false for content array without cache_control", () => {
|
||||
const msgs = [{ role: "user", content: [{ type: "text", text: "x" }] }];
|
||||
assert.equal(hasCacheControl(msgs), false);
|
||||
});
|
||||
|
||||
test("D2: hasCacheControl handles null/empty input gracefully", () => {
|
||||
assert.equal(hasCacheControl(null), false);
|
||||
assert.equal(hasCacheControl([]), false);
|
||||
assert.equal(hasCacheControl([null, undefined]), false);
|
||||
});
|
||||
|
||||
// D3: chunked stream replay — verify the logic by simulating what server.mjs does
|
||||
test("D3: 160-char cached response produces 2 chunks at 80 codepoints/chunk", () => {
|
||||
const content = "a".repeat(160);
|
||||
const CACHE_REPLAY_CHUNK_SIZE = 80;
|
||||
const codepoints = Array.from(content);
|
||||
const chunks = [];
|
||||
for (let i = 0; i < codepoints.length; i += CACHE_REPLAY_CHUNK_SIZE) {
|
||||
chunks.push(codepoints.slice(i, i + CACHE_REPLAY_CHUNK_SIZE).join(""));
|
||||
}
|
||||
assert.equal(chunks.length, 2);
|
||||
assert.equal(chunks[0].length, 80);
|
||||
assert.equal(chunks[1].length, 80);
|
||||
});
|
||||
|
||||
test("D3: chunked replay uses Array.from — multibyte codepoints stay intact", () => {
|
||||
// Each Chinese character is 1 codepoint but 3 UTF-8 bytes
|
||||
const chinese = "你好世界".repeat(25); // 100 codepoints
|
||||
const CACHE_REPLAY_CHUNK_SIZE = 80;
|
||||
const codepoints = Array.from(chinese);
|
||||
const chunks = [];
|
||||
for (let i = 0; i < codepoints.length; i += CACHE_REPLAY_CHUNK_SIZE) {
|
||||
chunks.push(codepoints.slice(i, i + CACHE_REPLAY_CHUNK_SIZE).join(""));
|
||||
}
|
||||
assert.equal(chunks.length, 2);
|
||||
assert.equal(Array.from(chunks[0]).length, 80);
|
||||
assert.equal(Array.from(chunks[1]).length, 20);
|
||||
// Verify each character is a complete codepoint (no mojibake)
|
||||
for (const chunk of chunks) {
|
||||
for (const cp of Array.from(chunk)) {
|
||||
assert.equal(cp.length <= 2, true); // surrogate pairs are length 2, single chars length 1
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ── PR-B Singleflight tests (async) ──
|
||||
async function asyncTest(name, fn) {
|
||||
try {
|
||||
await fn();
|
||||
passed++;
|
||||
console.log(` ✓ ${name}`);
|
||||
} catch (e) {
|
||||
failed++;
|
||||
console.log(` ✗ ${name}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSingleflightTests() {
|
||||
console.log("\nPR-B Singleflight:");
|
||||
|
||||
// 1. Basic dedup: 10 concurrent calls with same hash execute fn only once.
|
||||
await asyncTest("basic dedup: 10 concurrent callers execute fn only once", async () => {
|
||||
let callCount = 0;
|
||||
const fn = () => new Promise(resolve => {
|
||||
callCount++;
|
||||
setTimeout(() => resolve("result-A"), 20);
|
||||
});
|
||||
const results = await Promise.all(Array.from({ length: 10 }, () => singleflight("sf-dedup-1", fn)));
|
||||
assert.equal(callCount, 1, `fn called ${callCount} times, expected 1`);
|
||||
assert.ok(results.every(r => r === "result-A"), "all 10 callers should receive the same return value");
|
||||
});
|
||||
|
||||
// 2. Failure fan-out: all followers reject when leader rejects.
|
||||
await asyncTest("failure fan-out: all followers reject with leader error", async () => {
|
||||
let callCount = 0;
|
||||
const fn = () => new Promise((_, reject) => {
|
||||
callCount++;
|
||||
setTimeout(() => reject(new Error("upstream-fail")), 20);
|
||||
});
|
||||
const promises = Array.from({ length: 10 }, () => singleflight("sf-fail-1", fn));
|
||||
const results = await Promise.allSettled(promises);
|
||||
assert.equal(callCount, 1, `fn called ${callCount} times, expected 1`);
|
||||
assert.ok(results.every(r => r.status === "rejected"), "all 10 should be rejected");
|
||||
assert.ok(results.every(r => r.reason?.message === "upstream-fail"), "all should share the same error message");
|
||||
});
|
||||
|
||||
// 3a. Map cleanup after success: inflight count returns to 0 after promise resolves.
|
||||
await asyncTest("map cleanup after success: inflight=0 after promise settles", async () => {
|
||||
const fn = () => new Promise(resolve => setTimeout(() => resolve("done"), 10));
|
||||
await singleflight("sf-cleanup-ok", fn);
|
||||
const stats = getInflightStats();
|
||||
assert.equal(stats.inflight, 0, `expected inflight=0 after settlement, got ${stats.inflight}`);
|
||||
});
|
||||
|
||||
// 3b. Map cleanup after failure: inflight count returns to 0 after promise rejects.
|
||||
await asyncTest("map cleanup after failure: inflight=0 after promise rejects", async () => {
|
||||
const fn = () => new Promise((_, reject) => setTimeout(() => reject(new Error("fail")), 10));
|
||||
try { await singleflight("sf-cleanup-fail", fn); } catch {}
|
||||
const stats = getInflightStats();
|
||||
assert.equal(stats.inflight, 0, `expected inflight=0 after rejection, got ${stats.inflight}`);
|
||||
});
|
||||
|
||||
// 4. Different hashes don't share: two parallel calls with distinct hashes both execute.
|
||||
await asyncTest("different hashes do not share a singleflight entry", async () => {
|
||||
let countA = 0;
|
||||
let countB = 0;
|
||||
const fnA = () => new Promise(resolve => { countA++; setTimeout(() => resolve("A"), 20); });
|
||||
const fnB = () => new Promise(resolve => { countB++; setTimeout(() => resolve("B"), 20); });
|
||||
const [rA, rB] = await Promise.all([singleflight("sf-hash-A", fnA), singleflight("sf-hash-B", fnB)]);
|
||||
assert.equal(countA, 1);
|
||||
assert.equal(countB, 1);
|
||||
assert.equal(rA, "A");
|
||||
assert.equal(rB, "B");
|
||||
});
|
||||
|
||||
// 5. getInflightStats shape: returns { inflight: number, requesters: number }.
|
||||
await asyncTest("getInflightStats returns correct shape", async () => {
|
||||
// Verify shape against a settled state (inflight=0 is still the right shape).
|
||||
const stats = getInflightStats();
|
||||
assert.equal(typeof stats.inflight, "number", "inflight should be a number");
|
||||
assert.equal(typeof stats.requesters, "number", "requesters should be a number");
|
||||
// Also verify live counts: start a pending fn, check inflight>0, then resolve.
|
||||
const { promise: blocker, resolve: resolveBlocker } = Promise.withResolvers();
|
||||
const fn = () => blocker;
|
||||
const p = singleflight("sf-stats-shape", fn);
|
||||
const liveStats = getInflightStats();
|
||||
assert.ok(liveStats.inflight >= 1, `expected inflight>=1, got ${liveStats.inflight}`);
|
||||
resolveBlocker("ok");
|
||||
await p;
|
||||
});
|
||||
|
||||
// 6. Sequential calls don't share: singleflight is for concurrent dedup only.
|
||||
await asyncTest("sequential calls with same hash each execute fn independently", async () => {
|
||||
let callCount = 0;
|
||||
const fn = () => new Promise(resolve => { callCount++; setTimeout(() => resolve(callCount), 10); });
|
||||
const r1 = await singleflight("sf-sequential", fn);
|
||||
const r2 = await singleflight("sf-sequential", fn);
|
||||
assert.equal(callCount, 2, `fn should have been called twice, got ${callCount}`);
|
||||
assert.equal(r1, 1);
|
||||
assert.equal(r2, 2);
|
||||
});
|
||||
}
|
||||
|
||||
await runSingleflightTests();
|
||||
|
||||
// ── Plist Env Merge Tests ──
|
||||
import { mergePlistEnv, mergeSystemdEnv } from "./scripts/lib/plist-merge.mjs";
|
||||
|
||||
console.log("\nPlist env merge:");
|
||||
|
||||
const SAMPLE_TEMPLATE_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>dev.ocp.proxy</string>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>CLAUDE_PROXY_PORT</key>
|
||||
<string>3478</string>
|
||||
<key>CLAUDE_BIND</key>
|
||||
<string>127.0.0.1</string>
|
||||
<key>CLAUDE_AUTH_MODE</key>
|
||||
<string>multi</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>`;
|
||||
|
||||
const SAMPLE_EXISTING_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>dev.ocp.proxy</string>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>CLAUDE_PROXY_PORT</key>
|
||||
<string>3456</string>
|
||||
<key>CLAUDE_BIND</key>
|
||||
<string>127.0.0.1</string>
|
||||
<key>CLAUDE_AUTH_MODE</key>
|
||||
<string>none</string>
|
||||
<key>CLAUDE_HEARTBEAT_INTERVAL</key>
|
||||
<string>2000</string>
|
||||
<key>CLAUDE_CACHE_TTL</key>
|
||||
<string>600</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>`;
|
||||
|
||||
test("mergePlistEnv preserves unknown user keys", () => {
|
||||
const merged = mergePlistEnv(SAMPLE_EXISTING_PLIST, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.match(merged, /<key>CLAUDE_HEARTBEAT_INTERVAL<\/key>\s*<string>2000<\/string>/);
|
||||
assert.match(merged, /<key>CLAUDE_CACHE_TTL<\/key>\s*<string>600<\/string>/);
|
||||
});
|
||||
|
||||
test("mergePlistEnv overrides known template keys", () => {
|
||||
const merged = mergePlistEnv(SAMPLE_EXISTING_PLIST, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.match(merged, /<key>CLAUDE_PROXY_PORT<\/key>\s*<string>3478<\/string>/);
|
||||
assert.match(merged, /<key>CLAUDE_AUTH_MODE<\/key>\s*<string>multi<\/string>/);
|
||||
});
|
||||
|
||||
test("mergePlistEnv first-install returns template unchanged when existing is null", () => {
|
||||
const merged = mergePlistEnv(null, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.equal(merged, SAMPLE_TEMPLATE_PLIST);
|
||||
});
|
||||
|
||||
test("mergePlistEnv first-install returns template unchanged when existing is empty", () => {
|
||||
const merged = mergePlistEnv("", SAMPLE_TEMPLATE_PLIST);
|
||||
assert.equal(merged, SAMPLE_TEMPLATE_PLIST);
|
||||
});
|
||||
|
||||
const SAMPLE_TEMPLATE_SYSTEMD = `[Unit]
|
||||
Description=OCP — Open Claude Proxy
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/node /home/u/ocp/server.mjs
|
||||
Environment=CLAUDE_PROXY_PORT=3478
|
||||
Environment=CLAUDE_BIND=127.0.0.1
|
||||
Environment=CLAUDE_AUTH_MODE=multi
|
||||
Restart=always
|
||||
`;
|
||||
|
||||
const SAMPLE_EXISTING_SYSTEMD = `[Unit]
|
||||
Description=OCP — Open Claude Proxy
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/node /home/u/ocp/server.mjs
|
||||
Environment=CLAUDE_PROXY_PORT=3456
|
||||
Environment=CLAUDE_BIND=127.0.0.1
|
||||
Environment=CLAUDE_AUTH_MODE=none
|
||||
Environment=CLAUDE_HEARTBEAT_INTERVAL=2000
|
||||
Environment=CLAUDE_CACHE_TTL=600
|
||||
Restart=always
|
||||
`;
|
||||
|
||||
test("mergeSystemdEnv preserves unknown user Environment lines", () => {
|
||||
const merged = mergeSystemdEnv(SAMPLE_EXISTING_SYSTEMD, SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.match(merged, /Environment=CLAUDE_HEARTBEAT_INTERVAL=2000/);
|
||||
assert.match(merged, /Environment=CLAUDE_CACHE_TTL=600/);
|
||||
});
|
||||
|
||||
test("mergeSystemdEnv overrides known template keys", () => {
|
||||
const merged = mergeSystemdEnv(SAMPLE_EXISTING_SYSTEMD, SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.match(merged, /Environment=CLAUDE_PROXY_PORT=3478/);
|
||||
assert.match(merged, /Environment=CLAUDE_AUTH_MODE=multi/);
|
||||
});
|
||||
|
||||
test("mergeSystemdEnv first-install returns template unchanged", () => {
|
||||
assert.equal(mergeSystemdEnv(null, SAMPLE_TEMPLATE_SYSTEMD), SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.equal(mergeSystemdEnv("", SAMPLE_TEMPLATE_SYSTEMD), SAMPLE_TEMPLATE_SYSTEMD);
|
||||
});
|
||||
|
||||
test("mergePlistEnv is idempotent", () => {
|
||||
const r1 = mergePlistEnv(SAMPLE_EXISTING_PLIST, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.equal(mergePlistEnv(r1, SAMPLE_TEMPLATE_PLIST), r1);
|
||||
});
|
||||
|
||||
test("mergeSystemdEnv is idempotent", () => {
|
||||
const r1 = mergeSystemdEnv(SAMPLE_EXISTING_SYSTEMD, SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.equal(mergeSystemdEnv(r1, SAMPLE_TEMPLATE_SYSTEMD), r1);
|
||||
});
|
||||
|
||||
// ── Doctor JSON Contract Tests ──
|
||||
import { runDoctor } from "./scripts/doctor.mjs";
|
||||
|
||||
console.log("\nDoctor:");
|
||||
|
||||
test("doctor --json shape: required top-level keys", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.10.0", mockLatest: "v3.14.0" });
|
||||
for (const k of ["schema_version", "ready_to_upgrade", "current_version", "latest_version",
|
||||
"from_version_supported", "fail_count", "warn_count", "checks", "next_action"]) {
|
||||
assert.ok(k in result, `missing key: ${k}`);
|
||||
}
|
||||
assert.equal(result.schema_version, "1");
|
||||
});
|
||||
|
||||
test("doctor detects from-version < v3.4.0 → fresh_install", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.2.0", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.from_version_supported, false);
|
||||
assert.equal(result.next_action.kind, "fresh_install");
|
||||
assert.ok(Array.isArray(result.next_action.ai_executable));
|
||||
assert.ok(result.next_action.ai_executable.length > 0);
|
||||
});
|
||||
|
||||
test("doctor next_action.kind enum is one of allowed values", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.10.0", mockLatest: "v3.14.0" });
|
||||
const ALLOWED = ["noop", "update", "upgrade", "fresh_install", "fix_oauth", "fix_service"];
|
||||
assert.ok(ALLOWED.includes(result.next_action.kind), `kind=${result.next_action.kind} not in enum`);
|
||||
});
|
||||
|
||||
test("doctor noop when current==latest", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.14.0", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.next_action.kind, "noop");
|
||||
assert.equal(result.ready_to_upgrade, true);
|
||||
});
|
||||
|
||||
test("doctor patch-bump same minor → update kind", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.14.0", mockLatest: "v3.14.1" });
|
||||
assert.equal(result.next_action.kind, "update");
|
||||
});
|
||||
|
||||
test("doctor cross-minor → upgrade kind", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.10.0", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.next_action.kind, "upgrade");
|
||||
});
|
||||
|
||||
test("doctor OAuth FAIL → fix_oauth kind", async () => {
|
||||
const result = await runDoctor({
|
||||
skipNetwork: false,
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { status: 200, body: { auth: { ok: false, message: "ENOEXEC" } } }
|
||||
});
|
||||
assert.equal(result.next_action.kind, "fix_oauth");
|
||||
assert.ok(result.next_action.ai_executable.some(c => c.includes("install.cjs")));
|
||||
});
|
||||
|
||||
test("doctor service down → fix_service kind", async () => {
|
||||
const result = await runDoctor({
|
||||
skipNetwork: false,
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { error: "ECONNREFUSED" }
|
||||
});
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
});
|
||||
|
||||
test("doctor unparseable version → fresh_install", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "garbage", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.from_version_supported, false);
|
||||
assert.equal(result.next_action.kind, "fresh_install");
|
||||
});
|
||||
|
||||
test("doctor empty health body → fix_service (not fix_oauth)", async () => {
|
||||
const result = await runDoctor({
|
||||
skipNetwork: false,
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { status: 200, body: null }
|
||||
});
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
});
|
||||
|
||||
test("doctor falls back to currentVersion when origin/main unreachable (no stale latest)", async () => {
|
||||
// Use a non-existent ocpDir so git command fails; without the fix this would still
|
||||
// hard-code v3.14.0 as latest and recommend a downgrade for a future v3.15.0+ user.
|
||||
const result = await runDoctor({
|
||||
skipNetwork: true,
|
||||
mockVersion: "v3.15.0",
|
||||
ocpDir: "/nonexistent-ocp-dir-for-test"
|
||||
});
|
||||
assert.equal(result.latest_version, "v3.15.0");
|
||||
assert.equal(result.next_action.kind, "noop");
|
||||
});
|
||||
|
||||
// ── Upgrade Tests ──
|
||||
import { runUpgrade } from "./scripts/upgrade.mjs";
|
||||
|
||||
console.log("\nUpgrade:");
|
||||
|
||||
test("upgrade --dry-run prints plan, no side effects", async () => {
|
||||
const result = await runUpgrade({
|
||||
dryRun: true,
|
||||
yes: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "upgrade" }, current_version: "v3.10.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.executed, false);
|
||||
assert.ok(result.plan.length > 0);
|
||||
assert.ok(result.plan.some(line => line.toLowerCase().includes("snapshot")));
|
||||
});
|
||||
|
||||
test("upgrade noop returns early when current==latest", async () => {
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "noop" }, current_version: "v3.14.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.path, "noop");
|
||||
assert.equal(result.executed, true);
|
||||
assert.equal(result.changed, false);
|
||||
});
|
||||
|
||||
test("upgrade aborts on doctor FAIL", async () => {
|
||||
await assert.rejects(async () => {
|
||||
await runUpgrade({
|
||||
yes: true,
|
||||
mockDoctor: { ready_to_upgrade: false, fail_count: 1, next_action: { kind: "fix_oauth" } }
|
||||
});
|
||||
}, /doctor FAIL/);
|
||||
});
|
||||
|
||||
test("upgrade full path executes 5 phases", async () => {
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
dryRun: false,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "upgrade" },
|
||||
current_version: "v3.10.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.path, "upgrade");
|
||||
// Plan asks for 6 phases by name; verify each appears as a phase entry
|
||||
const phaseNames = result.phases.map(p => p.name);
|
||||
for (const expected of ["pre-flight", "snapshot", "fetch+install", "reconfigure", "restart", "post-flight"]) {
|
||||
assert.ok(phaseNames.includes(expected), `missing phase: ${expected}; got ${phaseNames.join(",")}`);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Snapshot Tests ──
|
||||
import { writeSnapshot, readSnapshot, listSnapshots, gcSnapshots } from "./scripts/lib/snapshot.mjs";
|
||||
import { mkdtempSync, rmSync, mkdirSync as tMkdirSync, writeFileSync as testWriteFile, existsSync as testExistsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join as testJoin } from "node:path";
|
||||
|
||||
console.log("\nSnapshot:");
|
||||
|
||||
test("writeSnapshot creates dir + manifest files", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-snap-test-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
testWriteFile(testJoin(dotOcp, "ocp.db"), "fake-sqlite-bytes");
|
||||
|
||||
const path = writeSnapshot({
|
||||
homeDir: root,
|
||||
fromCommit: "abc1234",
|
||||
fromVersion: "v3.10.0",
|
||||
toVersion: "v3.14.0",
|
||||
extraFiles: []
|
||||
});
|
||||
const m = readSnapshot(path);
|
||||
assert.equal(m.fromCommit, "abc1234");
|
||||
assert.equal(m.fromVersion, "v3.10.0");
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("listSnapshots returns sorted by ISO timestamp", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-snap-list-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-05-01T10:00:00Z", "2026-05-02T10:00:00Z", "2026-05-03T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
const list = listSnapshots(root);
|
||||
assert.equal(list.length, 3);
|
||||
assert.ok(list[0].path.includes("2026-05-01"));
|
||||
assert.ok(list[2].path.includes("2026-05-03"));
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("upgrade error after snapshot carries snapshotPath + hint", async () => {
|
||||
// Use mockExec=true so no real commands are run.
|
||||
// Verify the success path returns a snapshotPath (Fix B regression guard).
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
dryRun: false,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "upgrade" },
|
||||
current_version: "v3.10.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.ok(result.snapshotPath, "successful upgrade returns snapshotPath");
|
||||
assert.equal(result.path, "upgrade");
|
||||
assert.equal(result.executed, true);
|
||||
});
|
||||
|
||||
test("upgrade fresh_install requires --yes for non-interactive", async () => {
|
||||
await assert.rejects(async () => {
|
||||
await runUpgrade({
|
||||
yes: false,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: false, from_version_supported: false,
|
||||
next_action: { kind: "fresh_install", ai_executable: ["echo would-rm-rf"] },
|
||||
current_version: "v3.2.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
}, /requires --yes/);
|
||||
});
|
||||
|
||||
test("upgrade fresh_install with --yes runs ai_executable", async () => {
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: false, from_version_supported: false,
|
||||
next_action: { kind: "fresh_install",
|
||||
ai_executable: ["echo step-1", "echo step-2", "echo step-3"] },
|
||||
current_version: "v3.2.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.path, "fresh_install");
|
||||
assert.equal(result.steps.length, 3);
|
||||
});
|
||||
|
||||
test("rollback --list returns snapshots", async () => {
|
||||
const result = await runUpgrade({
|
||||
rollback: true,
|
||||
list: true,
|
||||
mockSnapshots: [
|
||||
{ name: "upgrade-snapshot-2026-05-01T10:00:00Z", path: "/tmp/snap-1" },
|
||||
{ name: "upgrade-snapshot-2026-05-02T10:00:00Z", path: "/tmp/snap-2" }
|
||||
]
|
||||
});
|
||||
assert.equal(result.path, "rollback-list");
|
||||
assert.equal(result.snapshots.length, 2);
|
||||
});
|
||||
|
||||
test("rollback with no snapshots fails clearly", async () => {
|
||||
await assert.rejects(async () => {
|
||||
await runUpgrade({ rollback: true, dryRun: true, mockSnapshots: [] });
|
||||
}, /no upgrade snapshots/);
|
||||
});
|
||||
|
||||
test("rollback --dry-run produces a plan without mutation", async () => {
|
||||
const result = await runUpgrade({
|
||||
rollback: true,
|
||||
dryRun: true,
|
||||
mockSnapshots: [{ name: "upgrade-snapshot-2026-05-11T08:30:00Z", path: "/tmp/snap-x" }],
|
||||
mockSnapshotMeta: { fromCommit: "abc1234", fromVersion: "v3.10.0", toVersion: "v3.14.0", path: "/tmp/snap-x" }
|
||||
});
|
||||
assert.equal(result.path, "rollback-dry-run");
|
||||
assert.equal(result.executed, false);
|
||||
assert.ok(result.plan.length > 0);
|
||||
});
|
||||
|
||||
test("rollback latest snapshot restores files (mockExec)", async () => {
|
||||
const result = await runUpgrade({
|
||||
rollback: true,
|
||||
yes: true,
|
||||
mockExec: true,
|
||||
mockSnapshots: [{ name: "upgrade-snapshot-2026-05-11T08:30:00Z", path: "/tmp/snap-x" }],
|
||||
mockSnapshotMeta: { fromCommit: "abc1234", fromVersion: "v3.10.0", toVersion: "v3.14.0", path: "/tmp/snap-x" }
|
||||
});
|
||||
assert.equal(result.path, "rollback");
|
||||
assert.equal(result.executed, true);
|
||||
assert.ok(result.phases.some(p => p.name === "git-checkout"));
|
||||
});
|
||||
|
||||
test("gcSnapshots keeps last N regardless of age", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-test-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-04-01T10:00:00Z", "2026-04-15T10:00:00Z", "2026-04-30T10:00:00Z", "2026-05-01T10:00:00Z", "2026-05-10T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
const result = gcSnapshots(root, { keepCount: 3, keepDays: 0, now: new Date("2026-05-11T00:00:00Z") });
|
||||
assert.equal(result.kept.length, 3);
|
||||
assert.equal(result.removed.length, 2);
|
||||
assert.ok(result.kept[0].name.includes("2026-04-30"));
|
||||
assert.ok(result.kept[2].name.includes("2026-05-10"));
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("gcSnapshots keeps snapshots newer than keepDays regardless of count", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-days-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-04-01T10:00:00Z", "2026-04-15T10:00:00Z", "2026-04-30T10:00:00Z", "2026-05-01T10:00:00Z", "2026-05-10T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
// keepCount=1 but keepDays=15 means anything from after 2026-04-26 is kept too
|
||||
const result = gcSnapshots(root, { keepCount: 1, keepDays: 15, now: new Date("2026-05-11T00:00:00Z") });
|
||||
// Kept: 2026-04-30 (within 15 days), 2026-05-01 (within 15 days), 2026-05-10 (within 15 days)
|
||||
assert.ok(result.kept.length >= 3);
|
||||
// Removed: 2026-04-01, 2026-04-15
|
||||
assert.ok(result.removed.some(s => s.name.includes("2026-04-01")));
|
||||
});
|
||||
|
||||
test("gcSnapshots never deletes the most recent snapshot", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-recent-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
tMkdirSync(testJoin(dotOcp, "upgrade-snapshot-2026-01-01T10:00:00Z"));
|
||||
// Even with keepCount=0 and keepDays=0, the most recent must survive
|
||||
const result = gcSnapshots(root, { keepCount: 0, keepDays: 0, now: new Date("2026-05-11T00:00:00Z") });
|
||||
assert.equal(result.kept.length, 1);
|
||||
assert.equal(result.removed.length, 0);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("gcSnapshots --dry-run reports plan without deleting", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-dryrun-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-04-01T10:00:00Z", "2026-04-15T10:00:00Z", "2026-05-10T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
const result = gcSnapshots(root, { keepCount: 1, keepDays: 0, dryRun: true, now: new Date("2026-05-11T00:00:00Z") });
|
||||
assert.equal(result.dryRun, true);
|
||||
assert.equal(result.removed.length, 2);
|
||||
// Files still exist
|
||||
assert.ok(testExistsSync(testJoin(dotOcp, "upgrade-snapshot-2026-04-01T10:00:00Z")));
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// ── Doctor --check oauth fast path tests ──
|
||||
console.log("\nDoctor --check oauth:");
|
||||
|
||||
await asyncTest("doctor --check oauth runs only oauth check (skips version/from-version)", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { status: 200, body: { auth: { ok: true, message: "authenticated" } } }
|
||||
});
|
||||
// Should still produce a valid result object
|
||||
assert.equal(result.schema_version, "1");
|
||||
// checks[] should only contain oauth_ok (no current_version, no from_version_supported)
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "noop");
|
||||
});
|
||||
|
||||
await asyncTest("doctor --check oauth + OAuth FAIL → fix_oauth", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockHealth: { status: 200, body: { auth: { ok: false, message: "ENOEXEC" } } }
|
||||
});
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "fix_oauth");
|
||||
assert.equal(result.fail_count, 1);
|
||||
});
|
||||
|
||||
await asyncTest("doctor --check oauth + service down → fix_service", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockHealth: { error: "ECONNREFUSED" }
|
||||
});
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
assert.equal(result.fail_count, 1);
|
||||
});
|
||||
|
||||
await asyncTest("doctor --check oauth + 200 with null body → fix_service", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockHealth: { status: 200, body: null }
|
||||
});
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
assert.equal(result.fail_count, 1);
|
||||
});
|
||||
|
||||
// ── Cleanup ──
|
||||
closeDb();
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* openclaw-claude-proxy uninstaller
|
||||
* OCP (Open Claude Proxy) uninstaller
|
||||
*
|
||||
* Stops and removes the launchd (macOS) or systemd (Linux) auto-start entry.
|
||||
* Handles both legacy (ai.openclaw.proxy / openclaw-proxy) and current
|
||||
|
||||
Reference in New Issue
Block a user