mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-31 19:42:15 +03:00
Compare commits
3 Commits
feat/orche
...
fix/v3850-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b574f0d14e | ||
|
|
31d3702a37 | ||
|
|
cb623b3cef |
40
.env.example
40
.env.example
@@ -1469,17 +1469,25 @@ CURSOR_USER_AGENT="Cursor/3.4"
|
||||
# FIRECRAWL_BASE_URL=https://api.firecrawl.dev
|
||||
# FIRECRAWL_TIMEOUT_MS=30000 # Per-request timeout (default: 30000 = 30s)
|
||||
|
||||
# ── Claude TLS sidecar (Chromium-fingerprinted client) ──
|
||||
# Used by: open-sse/services/claudeTlsClient.ts — wire-level timeout for
|
||||
# the bogdanfinn/tls-client koffi binding and the JS-side grace window
|
||||
# layered on top of it when the native library is wedged.
|
||||
# ── ChatGPT browser transport (Firefox-fingerprinted client) ──
|
||||
# Used by: open-sse/services/chatgptTlsClient.ts — native wreq-js request
|
||||
# timeout and the JS-side hard-deadline grace layered on top of it.
|
||||
# OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS=60000
|
||||
# OMNIROUTE_CHATGPT_TLS_GRACE_MS=10000
|
||||
# Max wait for the FIRST streamed byte before switching from direct streaming
|
||||
# to a buffered response, in milliseconds. Default 30000 (30s). The request's
|
||||
# hard deadline continues to apply while the buffered body is read.
|
||||
# OMNIROUTE_CHATGPT_STREAM_FIRST_BYTE_TIMEOUT_MS=30000
|
||||
|
||||
# ── Claude browser transport (Chromium-fingerprinted client) ──
|
||||
# Used by: open-sse/services/claudeTlsClient.ts — native wreq-js request
|
||||
# timeout and the JS-side hard-deadline grace layered on top of it.
|
||||
# OMNIROUTE_CLAUDE_TLS_TIMEOUT_MS=60000
|
||||
# OMNIROUTE_CLAUDE_TLS_GRACE_MS=10000
|
||||
|
||||
# ── Perplexity TLS sidecar (Firefox-fingerprinted client) ──
|
||||
# Used by: open-sse/services/perplexityTlsClient.ts — wire-level timeout for
|
||||
# the bogdanfinn/tls-client koffi binding and the JS-side grace window
|
||||
# layered on top of it when the native library is wedged.
|
||||
# ── Perplexity browser transport (Firefox-fingerprinted client) ──
|
||||
# Used by: open-sse/services/perplexityTlsClient.ts — native wreq-js request
|
||||
# timeout and the JS-side hard-deadline grace layered on top of it.
|
||||
# OMNIROUTE_PPLX_TLS_TIMEOUT_MS=30000
|
||||
# OMNIROUTE_PPLX_TLS_GRACE_MS=10000
|
||||
|
||||
@@ -1491,18 +1499,16 @@ CURSOR_USER_AGENT="Cursor/3.4"
|
||||
# meta-commentary. Set to 1/true/yes/on to restore the old behavior.
|
||||
# OMNIROUTE_PPLX_SEARCH_HINT=0
|
||||
|
||||
# ── Grok web TLS sidecar (Chrome-fingerprinted client) ──
|
||||
# Used by: open-sse/services/grokTlsClient.ts — wire-level timeout for the
|
||||
# bogdanfinn/tls-client koffi binding and the JS-side grace window layered on
|
||||
# top of it when the native library is wedged.
|
||||
# ── Grok web browser transport (Chrome-fingerprinted client) ──
|
||||
# Used by: open-sse/services/grokTlsClient.ts — native wreq-js request timeout
|
||||
# and the JS-side hard-deadline grace layered on top of it.
|
||||
# OMNIROUTE_GROK_TLS_TIMEOUT_MS=60000
|
||||
# OMNIROUTE_GROK_TLS_GRACE_MS=10000
|
||||
|
||||
# ── Notion web TLS sidecar (Chrome-fingerprinted client) ──
|
||||
# Used by: open-sse/services/notionTlsClient.ts — wire-level timeout for the
|
||||
# bogdanfinn/tls-client koffi binding and the JS-side grace window layered on
|
||||
# top of it when the native library is wedged. The notion-web executor raises
|
||||
# the wire timeout per-request to 180000 for long generations.
|
||||
# ── Notion web browser transport (Chrome-fingerprinted client) ──
|
||||
# Used by: open-sse/services/notionTlsClient.ts — native wreq-js request timeout
|
||||
# and the JS-side hard-deadline grace layered on top of it. The notion-web
|
||||
# executor raises the native timeout per-request to 180000 for long generations.
|
||||
# OMNIROUTE_NOTION_TLS_TIMEOUT_MS=30000
|
||||
# OMNIROUTE_NOTION_TLS_GRACE_MS=10000
|
||||
|
||||
|
||||
2
.github/workflows/electron-release.yml
vendored
2
.github/workflows/electron-release.yml
vendored
@@ -237,7 +237,7 @@ jobs:
|
||||
# optionals (@img/sharp-*, @img/sharp-libvips-*, @ngrok/ngrok-*,
|
||||
# fsevents) carry linux forks. Replace them with the forks this
|
||||
# leg's own `npm ci` resolved, then assert every bundled native
|
||||
# (koffi triplets, better-sqlite3 prebuilds, wreq-js, onnxruntime)
|
||||
# (better-sqlite3 prebuilds, wreq-js, onnxruntime)
|
||||
# can service this leg's platform/arch before packaging starts.
|
||||
run: |
|
||||
node scripts/build/standaloneBundle.mjs restore --archive web-bundle.tar.gz
|
||||
|
||||
16
Dockerfile
16
Dockerfile
@@ -103,25 +103,11 @@ RUN test -f package-lock.json \
|
||||
# node-gyp comes from npm's own bundled copy (deterministic, already in the image)
|
||||
# instead of `npx --yes`, which would install an arbitrary registry version
|
||||
# on-demand and run its lifecycle scripts (Sonar docker:S6505).
|
||||
#
|
||||
# tls-client-node (claude-web/grok-web/lmarena/perplexity-web TLS
|
||||
# impersonation) hits the same --ignore-scripts wall: its own postinstall.js
|
||||
# fetches a platform .so/.dylib/.dll from the bogdanfinn/tls-client GitHub
|
||||
# Releases API and is never invoked when npm ci skips lifecycle scripts. Unlike
|
||||
# better-sqlite3 above, that script never throws on failure — it only
|
||||
# `console.warn`s and exits 0 — so a rate-limited or offline build would
|
||||
# otherwise succeed silently with an empty bin/ and only fail at first request
|
||||
# in production (TlsClientUnavailableError, #7802). Run it explicitly here so
|
||||
# a broken/rate-limited fetch fails the BUILD loudly instead of shipping a
|
||||
# broken image.
|
||||
RUN --mount=type=cache,id=s/92ca8a61-c1ba-421f-a389-d48ac7258c2d-npm-cache,target=/root/.npm \
|
||||
npm ci --include=optional --no-audit --no-fund --legacy-peer-deps --ignore-scripts \
|
||||
&& (cd node_modules/better-sqlite3 \
|
||||
&& node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js rebuild) \
|
||||
&& node -e "require('better-sqlite3')(':memory:').close()" \
|
||||
&& node node_modules/tls-client-node/scripts/postinstall.js \
|
||||
&& (test -n "$(find node_modules/tls-client-node/bin -mindepth 1 -print -quit 2>/dev/null)" \
|
||||
|| (echo "tls-client-node native binary missing after postinstall — GitHub API fetch likely rate-limited or failed (#7802)" >&2 && exit 1))
|
||||
&& node -e "require('better-sqlite3')(':memory:').close()"
|
||||
|
||||
# Build with Turbopack (stable in Next 16, the repo default). The v3.8.27-era
|
||||
# TurbopackInternalError panic ("entered unreachable code: there must be a path to a
|
||||
|
||||
@@ -31,9 +31,9 @@ COPY scripts/dev/sync-env.mjs ./scripts/dev/sync-env.mjs
|
||||
# Fast Bun native package install
|
||||
RUN bun install --include=optional --quiet
|
||||
|
||||
# Fetch tls-client-node native binary if script exists
|
||||
RUN if [ -f "node_modules/tls-client-node/scripts/postinstall.js" ] && [ ! -d "node_modules/tls-client-node/bin" ]; then \
|
||||
bun node_modules/tls-client-node/scripts/postinstall.js || true; \
|
||||
# Compile native better-sqlite3 Node-API addon under Bun
|
||||
RUN if [ -d "node_modules/better-sqlite3" ]; then \
|
||||
(cd node_modules/better-sqlite3 && bunx node-gyp rebuild); \
|
||||
fi
|
||||
|
||||
# Smoke check native database driver used by Bun (bun:sqlite)
|
||||
|
||||
@@ -25,6 +25,31 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FO
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
|
||||
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
## wreq-js 3.0.0
|
||||
|
||||
OmniRoute distributes `wreq-js` and its seven platform-specific native addons from
|
||||
[`wreq-js@3.0.0`](https://www.npmjs.com/package/wreq-js/v/3.0.0).
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 will-work-for-meal
|
||||
Copyright (c) 2025 Oleksandr Herasymov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
||||
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
|
||||
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
## blackwell-systems/gcf-typescript
|
||||
|
||||
The generic-profile codec in
|
||||
|
||||
1
changelog.d/maintenance/11753-wreq-js-transport.md
Normal file
1
changelog.d/maintenance/11753-wreq-js-transport.md
Normal file
@@ -0,0 +1 @@
|
||||
- **chore(stealth):** replace the `tls-client-node` sidecar/temp-file transport used by the six web-cookie providers with the exactly pinned `wreq-js` 3.0.0 native transport, preserving streaming, proxy isolation, deadlines, EOF policies, binary responses, and cancellation while removing the obsolete downloader and native repair path ([#11753](https://github.com/diegosouzapw/OmniRoute/pull/11753)).
|
||||
@@ -74,12 +74,6 @@
|
||||
"justification": "CC-BY-4.0 applies to the caniuse browser-support data (a dataset, not code). The Creative Commons Attribution license requires attribution when distributing — OmniRoute does not distribute caniuse-lite data directly to end users; it is consumed by browserslist/PostCSS at build time to generate CSS compatibility info. This is a widely accepted pattern in the Node.js ecosystem (caniuse-lite is in millions of projects). Attribution is satisfied by keeping the package in node_modules with its original license file.",
|
||||
"risk": "low",
|
||||
"reviewAt": "v4.0.0"
|
||||
},
|
||||
"tls-client-node": {
|
||||
"license": "Custom: LICENSE (Apache-2.0 + Commons Clause)",
|
||||
"justification": "TODO: revisar — tls-client-node uses Apache-2.0 with a 'Commons Clause' addendum that restricts 'Selling' the software (i.e., offering it as a hosted/commercial service whose value derives substantially from tls-client-node). OmniRoute is an open-source proxy; however if deployed as a paid SaaS/hosting service, this restriction could apply. The package is used by grokTlsClient.ts for Grok TLS fingerprinting. RISK: medium — legal review recommended before commercial deployment. Alternatives: consider replacing with a native TLS fingerprinting approach or a truly permissive library.",
|
||||
"risk": "medium",
|
||||
"reviewAt": "v3.9.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +133,6 @@
|
||||
"sqlite-vec",
|
||||
"tailwind-merge",
|
||||
"tailwindcss",
|
||||
"tls-client-node",
|
||||
"tsup",
|
||||
"tsx",
|
||||
"turndown",
|
||||
|
||||
44
config/release/wreq-js-native-manifest.json
Normal file
44
config/release/wreq-js-native-manifest.json
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"package": "wreq-js",
|
||||
"version": "3.0.0",
|
||||
"source": "https://registry.npmjs.org/wreq-js/-/wreq-js-3.0.0.tgz",
|
||||
"npmIntegrity": "sha512-RZCoRSevVPpH4A4B4MxbFGo/pVPFveWd2gbe4ENKpPWlKXEYklZSDESOjBMmrIsmnkHh+nhM4PNJvG+NL7wBPA==",
|
||||
"license": "MIT",
|
||||
"nativeAddons": [
|
||||
{
|
||||
"path": "rust/wreq-js.darwin-arm64.node",
|
||||
"size": 7690880,
|
||||
"sha256": "c82eec39df691adb94f2cd09a8ff51335de8587cf132cd8b3ec797469a4b5002"
|
||||
},
|
||||
{
|
||||
"path": "rust/wreq-js.darwin-x64.node",
|
||||
"size": 8192028,
|
||||
"sha256": "073b8a8a4c26aedbce7c14eef3e5567918e62e8dbf4d28296b23f9d2beec2981"
|
||||
},
|
||||
{
|
||||
"path": "rust/wreq-js.linux-arm64-gnu.node",
|
||||
"size": 8520824,
|
||||
"sha256": "861d96a78caf7ce02c9ae8d37f1c59f5b0480e3142775c32917fcfe9b88524b0"
|
||||
},
|
||||
{
|
||||
"path": "rust/wreq-js.linux-arm64-musl.node",
|
||||
"size": 8735472,
|
||||
"sha256": "2409a3578c8c440df419b4d5abe3ac149bec48881611a6dc1571b95e6246552d"
|
||||
},
|
||||
{
|
||||
"path": "rust/wreq-js.linux-x64-gnu.node",
|
||||
"size": 9048992,
|
||||
"sha256": "55b40f4602c52111dfcdcc93db83f9d0de55d0ef7540348757709d58d05a9b64"
|
||||
},
|
||||
{
|
||||
"path": "rust/wreq-js.linux-x64-musl.node",
|
||||
"size": 8974880,
|
||||
"sha256": "bd52d15b1bb4704b11561a8aa95648a6c91150082b5af0e39dd1608b7db2d317"
|
||||
},
|
||||
{
|
||||
"path": "rust/wreq-js.win32-x64-msvc.node",
|
||||
"size": 7967232,
|
||||
"sha256": "7451a8701b82c946b03ba2be2f15257260a250b9e0ed9910611b22564fbec7a9"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -75,7 +75,7 @@ When you run `npm install -g omniroute`, you may see a wall of warnings like `np
|
||||
The warnings come from stale peer-dependency ranges in third-party packages OmniRoute doesn't control:
|
||||
|
||||
1. **`marked-terminal` wants `marked >=1 <16`, found `marked@18`** — works fine in practice; the upstream peer range is just stale.
|
||||
2. **`deprecated prebuild-install@7.1.3`** — the native-binary fetch helper. Only relevant later if a web-cookie provider reports a missing `tls-client-node` native binary (a separate issue, not caused by this warning).
|
||||
2. **`deprecated prebuild-install@7.1.3`** — a transitive native-binary helper used by another dependency. The pinned `wreq-js@3.0.0` package bundles its seven supported platform addons directly; this warning does not diagnose the web-cookie transport.
|
||||
|
||||
**No action needed** — the warnings cannot be fully silenced without forking upstream packages.
|
||||
|
||||
@@ -148,9 +148,10 @@ desktop app, for example:
|
||||
- `resources/app/.build/next/node_modules/playwright-<hash>/lib/…/agentParser.js` and
|
||||
`workerProcessEntry.js` — [Playwright](https://playwright.dev), the browser-automation
|
||||
library used for in-app provider login and browser-backed chat.
|
||||
- `resources/app/.build/next/node_modules/tls-client-node-<hash>/bin/tls-client-windows-64-<ver>.dll`
|
||||
— the native binary from `tls-client-node`, used for Cloudflare-tolerant HTTP on some web
|
||||
providers.
|
||||
- `resources/app/.build/next/node_modules/wreq-js-<hash>/rust/wreq-js.win32-x64-msvc.node`
|
||||
— the declared MIT-licensed native addon from pinned `wreq-js@3.0.0`, used for
|
||||
browser-fingerprinted HTTP on some web providers. Its expected SHA-256 is recorded in
|
||||
`config/release/wreq-js-native-manifest.json`.
|
||||
|
||||
**Why it fires:** the Windows installer is **not yet code-signed**, so an unsigned NSIS
|
||||
installer has zero reputation and behavioral heuristics run at maximum aggression. Combined
|
||||
|
||||
@@ -763,15 +763,18 @@ REQUEST_TIMEOUT_MS (global override)
|
||||
| `OMNIROUTE_PROVIDER_PROBE_TIMEOUT_MS` | `8000` | Timeout (ms) for the `validationRead` and `modelsProbe` presets in `src/shared/network/safeOutboundFetch.ts`. Raise for slow endpoints (Cerebras, Cloudflare AI, Groq) to prevent flapping between active/error in the dashboard. Falls back to 8000ms for invalid (<1000) or non-numeric values. |
|
||||
| `OMNIROUTE_RELAY_FETCH_TIMEOUT_MS` | `25000` | Relay-specific fetch timeout in `open-sse/utils/proxyFetch.ts` (#9158). A hung relay must fail before the client/agent timeout (~30s) so callers see a relay-specific failure instead of a generic upstream timeout. Capped at `29000` so it always fires first. |
|
||||
| `OMNIROUTE_RETRY_BACKOFF_MS` | `10` | Shared retry backoff for the direct/relay/proxy retry-once paths in `open-sse/utils/proxyFetch.ts` (#9158). `0` = retry immediately. |
|
||||
| `OMNIROUTE_CLAUDE_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`claudeTlsClient.ts`). |
|
||||
| `OMNIROUTE_CLAUDE_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
|
||||
| `OMNIROUTE_PPLX_TLS_TIMEOUT_MS` | `30000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`perplexityTlsClient.ts`). |
|
||||
| `OMNIROUTE_PPLX_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
|
||||
| `OMNIROUTE_CHATGPT_TLS_TIMEOUT_MS` | `60000` | Native wreq-js request timeout (`chatgptTlsClient.ts`). |
|
||||
| `OMNIROUTE_CHATGPT_TLS_GRACE_MS` | `10000` | JS-side hard-deadline grace added on top of the native timeout. |
|
||||
| `OMNIROUTE_CHATGPT_STREAM_FIRST_BYTE_TIMEOUT_MS` | `30000` (30s) | Max wait for the first streamed byte before ChatGPT switches to a buffered response; the hard request deadline remains active. |
|
||||
| `OMNIROUTE_CLAUDE_TLS_TIMEOUT_MS` | `60000` | Native wreq-js request timeout (`claudeTlsClient.ts`). |
|
||||
| `OMNIROUTE_CLAUDE_TLS_GRACE_MS` | `10000` | JS-side hard-deadline grace added on top of the native timeout. |
|
||||
| `OMNIROUTE_PPLX_TLS_TIMEOUT_MS` | `30000` | Native wreq-js request timeout (`perplexityTlsClient.ts`). |
|
||||
| `OMNIROUTE_PPLX_TLS_GRACE_MS` | `10000` | JS-side hard-deadline grace added on top of the native timeout. |
|
||||
| `OMNIROUTE_PPLX_SEARCH_HINT` | `0` (off) | Appends "You have built-in web search. Answer questions directly using search results." to the caller's system message (`perplexity-web/protocol.ts`). Off by default — Perplexity searches anyway, and the sentence leaks into replies as meta-commentary for coding clients. Set `1`/`true`/`yes`/`on` to restore. |
|
||||
| `OMNIROUTE_GROK_TLS_TIMEOUT_MS` | `60000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`grokTlsClient.ts`). |
|
||||
| `OMNIROUTE_GROK_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
|
||||
| `OMNIROUTE_NOTION_TLS_TIMEOUT_MS` | `30000` | Wire-level timeout for the bogdanfinn/tls-client koffi binding (`notionTlsClient.ts`); the `notion-web` executor raises it per-request to `180000` for long generations. |
|
||||
| `OMNIROUTE_NOTION_TLS_GRACE_MS` | `10000` | JS-side grace added on top of the wire timeout when the native binding is wedged. |
|
||||
| `OMNIROUTE_GROK_TLS_TIMEOUT_MS` | `60000` | Native wreq-js request timeout (`grokTlsClient.ts`). |
|
||||
| `OMNIROUTE_GROK_TLS_GRACE_MS` | `10000` | JS-side hard-deadline grace added on top of the native timeout. |
|
||||
| `OMNIROUTE_NOTION_TLS_TIMEOUT_MS` | `30000` | Native wreq-js request timeout (`notionTlsClient.ts`); `notion-web` raises it per request to `180000` for long generations. |
|
||||
| `OMNIROUTE_NOTION_TLS_GRACE_MS` | `10000` | JS-side hard-deadline grace added on top of the native timeout. |
|
||||
| `OMNIROUTE_BROWSER_POOL` | `on` | Shared Playwright browser pool for browser-backed web-cookie chat (`browserPool.ts`); set `off` to disable. |
|
||||
| `WEB_COOKIE_USE_BROWSER` | `0` | Opt a web-cookie chat request into the browser-backed path (`browserBackedChat.ts`); `1` to enable. |
|
||||
| `KIMI_WEB_BASE_URL` | `https://www.kimi.ai` | Base URL for the Kimi Web (international kimi.ai Connect-RPC) executor (`kimi-web.ts`); override only for mirror/proxy endpoints. |
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
title: "Stealth Guide"
|
||||
version: 3.8.40
|
||||
lastUpdated: 2026-06-28
|
||||
version: 3.8.50
|
||||
lastUpdated: 2026-08-26
|
||||
---
|
||||
|
||||
# Stealth Guide
|
||||
|
||||
> **Source of truth:** `open-sse/utils/tlsClient.ts`, `open-sse/services/{claudeCodeCCH,claudeCodeFingerprint,claudeCodeObfuscation,claudeCodeCompatible}.ts`, `open-sse/config/cliFingerprints.ts`, `src/mitm/`
|
||||
> **Last updated:** 2026-06-28 — v3.8.40
|
||||
> **Source of truth:** `open-sse/utils/tlsClient.ts`, `open-sse/services/{tlsClientBase,chatgptTlsClient,claudeTlsClient,perplexityTlsClient,grokTlsClient,notionTlsClient,lmarenaTlsClient,claudeCodeCCH,claudeCodeFingerprint,claudeCodeObfuscation,claudeCodeCompatible}.ts`, `open-sse/config/cliFingerprints.ts`, `src/mitm/`
|
||||
> **Last updated:** 2026-08-26 — v3.8.50
|
||||
> **Audience:** Engineers maintaining provider-specific stealth integrations.
|
||||
|
||||
OmniRoute integrates with providers whose edges actively fingerprint non-official clients (TLS JA3/JA4, header ordering, JSON body shape, integrity tokens). This page documents the stealth surfaces OmniRoute exposes and where they are implemented.
|
||||
@@ -29,6 +29,41 @@ Lazy-loaded `wreq-js` session that impersonates **Chrome 124 on macOS**. Used as
|
||||
- Timeout: `TLS_CLIENT_TIMEOUT_MS` (inherits from `FETCH_TIMEOUT_MS`, default 600000)
|
||||
- `wreq-js` Response is fetch-compatible (`headers`, `text()`, `json()`, `clone()`, `body`).
|
||||
|
||||
### Web-cookie provider transport — wreq-js 3.0.0
|
||||
|
||||
`open-sse/services/tlsClientBase.ts` is the shared transport for ChatGPT, Claude, Perplexity,
|
||||
Grok, Notion, and LMArena web sessions. Each thin provider wrapper selects a browser/OS profile;
|
||||
the base loads `wreq-js` lazily, reuses only transport-level connections keyed by
|
||||
profile + OS + resolved proxy, and gives every request an ephemeral cookie scope. It never shares a
|
||||
wreq session or cookie jar between accounts or requests.
|
||||
|
||||
| Provider | Profile | Emulated OS | Stream EOF policy |
|
||||
| ---------- | ------------- | ----------- | -------------------------------- |
|
||||
| ChatGPT | `firefox_148` | macOS | include `[DONE]` |
|
||||
| Claude | `chrome_146` | Linux | include `[DONE]` |
|
||||
| Perplexity | `firefox_148` | macOS | include `event: end_of_stream` |
|
||||
| Grok | `chrome_146` | Linux | exclude `[DONE]` |
|
||||
| Notion | `chrome_146` | Windows | include `[DONE]` |
|
||||
| LMArena | `chrome_146` | Windows | no sentinel; close on native EOF |
|
||||
|
||||
- Streaming uses the native response `ReadableStream` directly; no temp file or sidecar is created.
|
||||
- Up to 256 initial bytes are inspected before exposing a stream. SSE providers buffer non-SSE
|
||||
errors; Grok/LMArena map Cloudflare challenges to `403` and HTML interstitials to `502`.
|
||||
- The native request timeout remains wrapped by an absolute JS hard deadline. A hang invalidates
|
||||
and closes only the affected profile/OS/proxy transport before the next request recreates it.
|
||||
- Proxy resolution priority is per-call `proxyUrl` → request-scoped account/dashboard context →
|
||||
`HTTPS_PROXY`/`HTTP_PROXY`/`ALL_PROXY` (including lowercase variants). Resolution errors fail
|
||||
closed instead of leaking a direct connection. LMArena deliberately resolves against `arena.ai`.
|
||||
- `byteResponse` returns a content-typed `data:` URL without UTF-8 corruption.
|
||||
- Errors are `TlsClientUnavailableError` (package/addon unavailable) and `TlsClientHangError`
|
||||
(deadline exceeded).
|
||||
|
||||
The profiles are supported by the pinned package, but real WAF acceptance can change independently
|
||||
of local contract tests. Validate fingerprint changes against an explicitly authorized live account
|
||||
before claiming parity with an upstream browser.
|
||||
|
||||
---
|
||||
|
||||
## Claude Code Stealth Bundle
|
||||
|
||||
When `cliCompatMode` is on, OmniRoute reshapes outgoing Claude requests so they are indistinguishable from `claude-cli` traffic. Three modules collaborate:
|
||||
|
||||
@@ -132,9 +132,7 @@ const nextConfig = {
|
||||
// instead of keeping the old generation in control. Falls back to a
|
||||
// value that is unique per build run when git is absent (CI tarball).
|
||||
NEXT_PUBLIC_SW_BUILD_ID:
|
||||
process.env.OMNIROUTE_SW_BUILD_ID ||
|
||||
process.env.SOURCE_VERSION ||
|
||||
`${Date.now()}`,
|
||||
process.env.OMNIROUTE_SW_BUILD_ID || process.env.SOURCE_VERSION || `${Date.now()}`,
|
||||
},
|
||||
distDir,
|
||||
// Turbopack config: redirect native modules to stubs at build time
|
||||
@@ -307,9 +305,6 @@ const nextConfig = {
|
||||
"keytar",
|
||||
"wreq-js",
|
||||
"zod",
|
||||
"tls-client-node",
|
||||
"koffi",
|
||||
"tough-cookie",
|
||||
"@ngrok/ngrok",
|
||||
"@huggingface/transformers",
|
||||
// copilot-m365-web.ts imports 'ws' as a client-side WebSocket. When bundled,
|
||||
|
||||
@@ -939,8 +939,8 @@ export class GrokWebExecutor extends BaseExecutor {
|
||||
|
||||
// Fetch from Grok via TLS-impersonating client (#3180).
|
||||
// Grok sits behind Cloudflare Enterprise which rejects Node's native TLS
|
||||
// fingerprint even with valid sso+sso-rw cookies. We use tls-client-node
|
||||
// to send a Chrome-like handshake instead.
|
||||
// fingerprint even with valid sso+sso-rw cookies. The pinned wreq-js
|
||||
// transport sends a Chrome-like handshake instead.
|
||||
let tlsResult: TlsFetchResult;
|
||||
try {
|
||||
tlsResult = await tlsFetchGrok(GROK_CHAT_API, {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* LMArenaExecutor — Arena (formerly LMArena) web-session provider.
|
||||
*
|
||||
* Routes requests through arena.ai create-evaluation with session cookies.
|
||||
* Upstream sits behind Cloudflare; traffic goes through tls-client-node Chrome
|
||||
* impersonation (see services/lmarenaTlsClient.ts).
|
||||
* Upstream sits behind Cloudflare; traffic goes through wreq-js Chrome
|
||||
* impersonation with isolated ephemeral cookies (see services/lmarenaTlsClient.ts).
|
||||
*
|
||||
* Helpers: open-sse/executors/lmarena/{cookie,models,stream,response}.ts
|
||||
*/
|
||||
@@ -174,7 +174,6 @@ export class LMArenaExecutor extends BaseExecutor {
|
||||
body: JSON.stringify(transformedBody),
|
||||
signal: ctx.signal,
|
||||
stream: ctx.stream,
|
||||
streamEofSymbol: "__OMNIROUTE_LMARENA_EOF_NEVER__",
|
||||
});
|
||||
|
||||
const failed = mapFailedTlsResult({
|
||||
|
||||
@@ -6,9 +6,9 @@ export const LMARENA_API_BASE = "https://arena.ai";
|
||||
export const LMARENA_STREAM_URL = `${LMARENA_API_BASE}/nextjs-api/stream/create-evaluation`;
|
||||
/**
|
||||
* Current Chrome stable UA (header surface).
|
||||
* TLS JA3 profile is separate: tls-client-node tops out at chrome_146 — see
|
||||
* LMARENA_PROFILE in lmarenaTlsClient.ts. Headers track the live browser string;
|
||||
* fingerprint stays at the newest native profile we can actually impersonate.
|
||||
* TLS JA3/JA4 profile is separate: the provider-tested wreq-js profile is pinned
|
||||
* to chrome_146 in lmarenaTlsClient.ts while headers track the live browser string.
|
||||
* Treat that deliberate version skew as a WAF-sensitive compatibility surface.
|
||||
*/
|
||||
export const LMARENA_USER_AGENT =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36";
|
||||
|
||||
@@ -114,7 +114,7 @@ export function mapTlsUnavailable(
|
||||
return {
|
||||
response: errorResponse(
|
||||
502,
|
||||
`Arena TLS impersonation unavailable: ${error.message}. Install/repair tls-client-node native binary.`,
|
||||
`Arena TLS impersonation unavailable: ${error.message}. Verify the wreq-js 3.0.0 native addon.`,
|
||||
"upstream_error",
|
||||
"TLS_CLIENT_UNAVAILABLE"
|
||||
),
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
* chunk — safer than assuming unverified incremental-delta semantics.
|
||||
*
|
||||
* Auth: Cookie-based (token_v2 [+ optional space_id, notion_browser_id, user_id])
|
||||
* Method: Browser-TLS impersonation via tls-client-node (Chrome JA3). Plain
|
||||
* Method: Browser-TLS impersonation via pinned wreq-js (Chrome JA3/JA4). Plain
|
||||
* Node/undici fetch is rejected by Notion's edge with in-band
|
||||
* `temporarily-unavailable` (HTTP 200, empty assistant text) — curl/Schannel
|
||||
* and Chrome work with the same cookie + body. See services/notionTlsClient.ts.
|
||||
@@ -60,10 +60,7 @@ import {
|
||||
messagesForNotionTranscript,
|
||||
type NotionAgentOptions,
|
||||
} from "../services/notionTranscriptBuilder.ts";
|
||||
import {
|
||||
tlsFetchNotion,
|
||||
TlsClientUnavailableError,
|
||||
} from "../services/notionTlsClient.ts";
|
||||
import { tlsFetchNotion, TlsClientUnavailableError } from "../services/notionTlsClient.ts";
|
||||
|
||||
// Re-exported for unit tests that destructure `mod.<name>` on this module.
|
||||
export {
|
||||
@@ -225,7 +222,6 @@ function extractUserIdFromCookie(cookie: string): string {
|
||||
return extractNotionUserIdFromCookie(cookie);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Notion's undocumented inference API does not return token usage.
|
||||
* Emit a cheap char-based estimate so clients don't see a constant
|
||||
@@ -236,9 +232,7 @@ export function estimateNotionUsage(
|
||||
messages: NotionMessage[] | undefined,
|
||||
content: string
|
||||
): { prompt_tokens: number; completion_tokens: number; total_tokens: number; estimated: true } {
|
||||
const promptText = (messages || [])
|
||||
.map((m) => extractNotionMessageText(m?.content))
|
||||
.join("\n");
|
||||
const promptText = (messages || []).map((m) => extractNotionMessageText(m?.content)).join("\n");
|
||||
// ~4 chars/token (English-ish); at least 1 when there is any text.
|
||||
const prompt_tokens = promptText ? Math.max(1, Math.ceil(promptText.length / 4)) : 0;
|
||||
const completion_tokens = content ? Math.max(1, Math.ceil(content.length / 4)) : 0;
|
||||
@@ -393,9 +387,8 @@ function buildNotionExecuteHeaders(opts: {
|
||||
const isCustom = Boolean(opts.agent?.workflowId);
|
||||
// Browser uses /agent/<workflowId without dashes>?wfv=chat for custom agents.
|
||||
const agentPathId = (opts.agent?.workflowId || "").replace(/-/g, "");
|
||||
const referer = isCustom && agentPathId
|
||||
? `${BASE_URL}/agent/${agentPathId}?wfv=chat`
|
||||
: `${BASE_URL}/ai`;
|
||||
const referer =
|
||||
isCustom && agentPathId ? `${BASE_URL}/agent/${agentPathId}?wfv=chat` : `${BASE_URL}/ai`;
|
||||
const reqHeaders: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": USER_AGENT,
|
||||
@@ -453,11 +446,8 @@ export function resolveNotionAgentOptions(
|
||||
"agent_id",
|
||||
]) || "";
|
||||
const pageFromPs =
|
||||
readProviderSpecificString(ps, [
|
||||
"contextPageId",
|
||||
"context_page_id",
|
||||
"notionContextPageId",
|
||||
]) || "";
|
||||
readProviderSpecificString(ps, ["contextPageId", "context_page_id", "notionContextPageId"]) ||
|
||||
"";
|
||||
|
||||
const readCookie = (name: string): string => {
|
||||
const m = cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]+)`, "i"));
|
||||
@@ -477,10 +467,7 @@ export function resolveNotionAgentOptions(
|
||||
readCookie("agent_id")
|
||||
);
|
||||
const contextPageId =
|
||||
pageFromPs ||
|
||||
readCookie("context_page_id") ||
|
||||
readCookie("notion_context_page_id") ||
|
||||
"";
|
||||
pageFromPs || readCookie("context_page_id") || readCookie("notion_context_page_id") || "";
|
||||
|
||||
return {
|
||||
workflowId: workflowId || undefined,
|
||||
@@ -510,8 +497,7 @@ async function sendNotionInferenceRequest(opts: {
|
||||
body: JSON.stringify(reqBody),
|
||||
signal: signal ?? undefined,
|
||||
// Inference can take a while (tool-autoload + LLM first token).
|
||||
timeoutMs:
|
||||
Number.parseInt(process.env.OMNIROUTE_NOTION_TLS_TIMEOUT_MS || "", 10) || 180_000,
|
||||
timeoutMs: Number.parseInt(process.env.OMNIROUTE_NOTION_TLS_TIMEOUT_MS || "", 10) || 180_000,
|
||||
});
|
||||
status = tlsRes.status;
|
||||
rawText = tlsRes.text ?? "";
|
||||
@@ -634,8 +620,7 @@ export class NotionWebExecutor extends BaseExecutor {
|
||||
const inboundHeaders =
|
||||
(input.clientHeaders as Record<string, string> | null | undefined) ??
|
||||
((input as { headers?: Record<string, string> }).headers as
|
||||
| Record<string, string>
|
||||
| undefined);
|
||||
Record<string, string> | undefined);
|
||||
const clientThreadId = readClientThreadId(requestBody, inboundHeaders ?? undefined);
|
||||
// Namespace the thread cache PER CALLER (hash of the caller's cookie) AND by custom
|
||||
// agent, so (a) two users of the same Notion space never share a cached thread
|
||||
@@ -738,7 +723,10 @@ export class NotionWebExecutor extends BaseExecutor {
|
||||
|
||||
// One automatic retry for transient Notion faults — same threadId, never create again
|
||||
if (isFailedAttempt(attempt) && attempt.retryable) {
|
||||
const delayMs = process.env.NODE_ENV === "test" || process.env.VITEST ? 20 : 700 + Math.floor(Math.random() * 400);
|
||||
const delayMs =
|
||||
process.env.NODE_ENV === "test" || process.env.VITEST
|
||||
? 20
|
||||
: 700 + Math.floor(Math.random() * 400);
|
||||
await new Promise((r) => setTimeout(r, delayMs));
|
||||
attempt = await runOnce({ createThread: false, threadId });
|
||||
}
|
||||
|
||||
@@ -501,7 +501,7 @@ export class PerplexityWebExecutor extends BaseExecutor {
|
||||
if (isCloudflareChallenge(response.text)) {
|
||||
errMsg =
|
||||
"Cloudflare blocked the request — Perplexity's edge rejected this server's TLS fingerprint " +
|
||||
"(common on VPS/datacenter IPs). Ensure tls-client-node is installed with its native binary, " +
|
||||
"(common on VPS/datacenter IPs). Verify the wreq-js 3.0.0 native addon, " +
|
||||
"or route perplexity-web through a residential proxy.";
|
||||
log?.error?.("PPLX-WEB", "Cloudflare challenge detected — TLS bypass failed");
|
||||
} else {
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
/**
|
||||
* Regression tests for the proxy-leak fix in grokTlsClient.
|
||||
*
|
||||
* Bug context (#3180): tlsFetchGrok() built its native tls-client-node
|
||||
* requestOptions without a `proxyUrl` field, so every grok-web call
|
||||
* Bug context (#3180): tlsFetchGrok() built its native transport options
|
||||
* without a `proxyUrl` field, so every grok-web call
|
||||
* egressed with the bare host IP regardless of the dashboard proxy config
|
||||
* or HTTP_PROXY / HTTPS_PROXY env vars (the koffi-loaded Go binary does not
|
||||
* consult Go's `http.ProxyFromEnvironment`).
|
||||
* or HTTP_PROXY / HTTPS_PROXY env vars. Native browser transports require the
|
||||
* resolved proxy to be passed explicitly.
|
||||
*
|
||||
* These tests pin the resolution-order contract:
|
||||
* 1. Per-call `options.proxyUrl` wins.
|
||||
* 2. POSIX-standard HTTPS_PROXY / HTTP_PROXY / ALL_PROXY (and lowercase variants).
|
||||
* 3. Otherwise undefined (no proxy).
|
||||
* 2. Request-scoped dashboard/account proxy context.
|
||||
* 3. POSIX-standard HTTPS_PROXY / HTTP_PROXY / ALL_PROXY (and lowercase variants).
|
||||
* 4. Otherwise undefined (no proxy).
|
||||
*
|
||||
* They also pin that the resolved proxy is actually placed on the
|
||||
* requestOptions object handed to the native binding — the original bug
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Browser-TLS-impersonating HTTP client for claude.ai.
|
||||
*
|
||||
* Thin re-export over the shared `tlsClientBase.ts` factory
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (sidecar lifecycle,
|
||||
* streaming tail-file, proxy resolution, error classes, SSE detection) lives
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (wreq-js transport
|
||||
* pooling, direct streaming, proxy resolution, deadlines, SSE detection) lives
|
||||
* in the base module; this file supplies only Claude-specific config and
|
||||
* preserves the original public export surface.
|
||||
*/
|
||||
@@ -24,13 +24,13 @@ const HARD_TIMEOUT_GRACE_MS =
|
||||
export const tlsClientModule = createTlsClientModule({
|
||||
providerName: "Claude",
|
||||
tlsProfile: `chrome_${CLAUDE_TLS_BROWSER_MAJOR_VERSION}`,
|
||||
emulationOs: "linux",
|
||||
domain: "https://claude.ai",
|
||||
tempDirPrefix: "cgpt-stream-",
|
||||
tailFileVariant: "A",
|
||||
streamEofPolicy: "include",
|
||||
responseValidation: "sse",
|
||||
exportCloudflareCheck: false,
|
||||
exposeStreamingForTesting: true,
|
||||
// Claude waits indefinitely for the first SSE byte (original 2-arg waitForContent).
|
||||
// Claude allows the native/hard request deadline to bound a slow first SSE byte.
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
hardTimeoutGraceMs: HARD_TIMEOUT_GRACE_MS,
|
||||
firstByteTimeoutMs: Number.POSITIVE_INFINITY,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* 3. Waits for Turnstile challenge to appear
|
||||
* 4. Waits for challenge to be solved (with retry)
|
||||
* 5. Extracts cf_clearance cookie
|
||||
* 6. Returns fresh cookie for tls-client-node
|
||||
* 6. Returns a fresh cookie for the isolated wreq-js request
|
||||
*/
|
||||
|
||||
import type { Browser, Page } from "playwright";
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Browser-TLS-impersonating HTTP client for grok.com.
|
||||
*
|
||||
* Thin re-export over the shared `tlsClientBase.ts` factory
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (sidecar lifecycle,
|
||||
* streaming tail-file, proxy resolution, error classes, Cloudflare challenge
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (wreq-js transport
|
||||
* pooling, direct streaming, proxy resolution, deadlines, Cloudflare challenge
|
||||
* detection) lives in the base module; this file supplies only Grok-specific
|
||||
* config and preserves the original public export surface.
|
||||
*/
|
||||
@@ -22,9 +22,9 @@ const HARD_TIMEOUT_GRACE_MS =
|
||||
export const tlsClientModule = createTlsClientModule({
|
||||
providerName: "Grok",
|
||||
tlsProfile: "chrome_146",
|
||||
emulationOs: "linux",
|
||||
domain: "https://grok.com",
|
||||
tempDirPrefix: "grok-stream-",
|
||||
tailFileVariant: "B1",
|
||||
streamEofPolicy: "exclude",
|
||||
responseValidation: "cf",
|
||||
exportCloudflareCheck: true,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Browser-TLS-impersonating HTTP client for arena.ai.
|
||||
*
|
||||
* Thin re-export over the shared `tlsClientBase.ts` factory
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (sidecar lifecycle,
|
||||
* streaming tail-file, proxy resolution, error classes, Cloudflare challenge
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (wreq-js transport
|
||||
* pooling, direct streaming, proxy resolution, deadlines, Cloudflare challenge
|
||||
* detection) lives in the base module; this file supplies only LMArena-specific
|
||||
* config and preserves the original public export surface.
|
||||
*/
|
||||
@@ -20,11 +20,12 @@ const HARD_TIMEOUT_GRACE_MS = 10_000;
|
||||
export const tlsClientModule = createTlsClientModule({
|
||||
providerName: "LMArena",
|
||||
tlsProfile: "chrome_146",
|
||||
emulationOs: "windows",
|
||||
domain: "https://lmarena.ai",
|
||||
// LMArena's proxy resolution domain is hardcoded to arena.ai, not the config domain.
|
||||
proxyDomainOverride: "https://arena.ai",
|
||||
tempDirPrefix: "LMArena-stream-",
|
||||
tailFileVariant: "B2",
|
||||
streamEofPolicy: "none",
|
||||
streamEofSymbol: "",
|
||||
responseValidation: "cf",
|
||||
exportCloudflareCheck: true,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Browser-TLS-impersonating HTTP client for app.notion.com.
|
||||
*
|
||||
* Thin re-export over the shared `tlsClientBase.ts` factory
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (sidecar lifecycle,
|
||||
* streaming tail-file, proxy resolution, error classes, SSE detection,
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (wreq-js transport
|
||||
* pooling, direct streaming, proxy resolution, deadlines, SSE detection,
|
||||
* Cloudflare challenge detection) lives in the base module; this file supplies
|
||||
* only Notion-specific config and preserves the original public export surface.
|
||||
*/
|
||||
@@ -22,9 +22,9 @@ const HARD_TIMEOUT_GRACE_MS =
|
||||
export const tlsClientModule = createTlsClientModule({
|
||||
providerName: "Notion",
|
||||
tlsProfile: "chrome_146",
|
||||
emulationOs: "windows",
|
||||
domain: "https://app.notion.com",
|
||||
tempDirPrefix: "pplx-stream-",
|
||||
tailFileVariant: "A",
|
||||
streamEofPolicy: "include",
|
||||
responseValidation: "sse",
|
||||
exportCloudflareCheck: true,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Browser-TLS-impersonating HTTP client for www.perplexity.ai.
|
||||
*
|
||||
* Thin re-export over the shared `tlsClientBase.ts` factory
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (sidecar lifecycle,
|
||||
* streaming tail-file, proxy resolution, error classes, SSE detection,
|
||||
* (`createTlsClientModule`). All provider-agnostic logic (wreq-js transport
|
||||
* pooling, direct streaming, proxy resolution, deadlines, SSE detection,
|
||||
* Cloudflare challenge detection) lives in the base module; this file supplies
|
||||
* only Perplexity-specific config and preserves the original public export
|
||||
* surface.
|
||||
@@ -23,9 +23,9 @@ const HARD_TIMEOUT_GRACE_MS =
|
||||
export const tlsClientModule = createTlsClientModule({
|
||||
providerName: "Perplexity",
|
||||
tlsProfile: "firefox_148",
|
||||
emulationOs: "macos",
|
||||
domain: "https://www.perplexity.ai",
|
||||
tempDirPrefix: "pplx-stream-",
|
||||
tailFileVariant: "A",
|
||||
streamEofPolicy: "include",
|
||||
responseValidation: "sse",
|
||||
exportCloudflareCheck: true,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,23 +0,0 @@
|
||||
import { join } from "node:path";
|
||||
import { resolveDataDir } from "@/lib/dataPaths";
|
||||
|
||||
/**
|
||||
* Writable cache directory for tls-client-node's native binary.
|
||||
*
|
||||
* Without an explicit `downloadDir`, the library defaults to its own package
|
||||
* `node_modules/tls-client-node/bin`, which is root-owned on global installs
|
||||
* and fails with EACCES for normal users (#8579).
|
||||
*/
|
||||
export function resolveTlsClientDownloadDir(): string {
|
||||
return join(resolveDataDir(), "tls-client", "bin");
|
||||
}
|
||||
|
||||
export function buildNativeTlsClientOptions(): {
|
||||
runtimeMode: "native";
|
||||
downloadDir: string;
|
||||
} {
|
||||
return {
|
||||
runtimeMode: "native",
|
||||
downloadDir: resolveTlsClientDownloadDir(),
|
||||
};
|
||||
}
|
||||
177
package-lock.json
generated
177
package-lock.json
generated
@@ -165,8 +165,7 @@
|
||||
"keytar": "^7.9.0",
|
||||
"onnxruntime-node": "1.24.3",
|
||||
"sqlite-vec": "^0.1.9",
|
||||
"tls-client-node": "^0.2.0",
|
||||
"wreq-js": "^3.1.0"
|
||||
"wreq-js": "3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@adobe/css-tools": {
|
||||
@@ -13626,118 +13625,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@wreq-js/binding-darwin-arm64": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-darwin-arm64/-/binding-darwin-arm64-3.1.0.tgz",
|
||||
"integrity": "sha512-wa9xns8VngAc6rOv9f8AtLQVb0NttBtbJpxeTZBLyWY/6+q+HjVBfV/0VwoYO8xCL+U+VwYWHn2X80LvL2nvVg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wreq-js/binding-darwin-x64": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-darwin-x64/-/binding-darwin-x64-3.1.0.tgz",
|
||||
"integrity": "sha512-93y4x2XBlLRBUhCnCDeOUkH54eCut1RIrIOkWmWBDDBjM1VyLq2SxGEprWoEV2JMNaavTbrMM589MqwlqFA18w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wreq-js/binding-linux-arm64-gnu": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-3.1.0.tgz",
|
||||
"integrity": "sha512-98F2f95iMaFhfo6JuNXYpZRI8L0nK9h2/UOsaqN6CI7qUbAk/Cjf4FqYSIFs4FgC2Upe3Ju1ySxEXIWGXYPmeA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wreq-js/binding-linux-arm64-musl": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-linux-arm64-musl/-/binding-linux-arm64-musl-3.1.0.tgz",
|
||||
"integrity": "sha512-FSjTGsj+Q/+wFWtGT7NwX7pRfaHRpKtcCq5WxviPei1+hpEX43EFHMfx0/taw2kDdArQ381MhVyrBQmZ1r4p5w==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wreq-js/binding-linux-x64-gnu": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-linux-x64-gnu/-/binding-linux-x64-gnu-3.1.0.tgz",
|
||||
"integrity": "sha512-+vNDkG6DtW/BAdzxfqycspHIsKYfS1EC21FoXUpgCfvEA5UZDTGE7funimEh+/T9WZmrH6ce9sjaWA2U32SIPA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wreq-js/binding-linux-x64-musl": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-linux-x64-musl/-/binding-linux-x64-musl-3.1.0.tgz",
|
||||
"integrity": "sha512-PwS/8pNlyJZRxcUwYOAGhUQg3nx3/zWeOItGDlpnJFFNs7ooTRipVE25hLebZbCH0a5pydkprqQDy+KL5vMRWg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wreq-js/binding-win32-x64-msvc": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@wreq-js/binding-win32-x64-msvc/-/binding-win32-x64-msvc-3.1.0.tgz",
|
||||
"integrity": "sha512-rIhGDdsgtYdf9qSJvSU19Lu1yVa+6PTSjFE0SifUcimAP5cLJVysRyt8imxzv8c6+eGoEwqApvZ4SgBbED+3aQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@xmldom/xmldom": {
|
||||
"version": "0.9.10",
|
||||
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz",
|
||||
@@ -25448,17 +25335,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/koffi": {
|
||||
"version": "2.16.1",
|
||||
"resolved": "https://registry.npmjs.org/koffi/-/koffi-2.16.1.tgz",
|
||||
"integrity": "sha512-0Ie6CfD026dNfWSosDw9dPxPzO9Rlyo0N8m5r05S8YjytIpuilzMFDMY4IDy/8xQsTwpuVinhncD+S8n3bcYZQ==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"funding": {
|
||||
"url": "https://liberapay.com/Koromix"
|
||||
}
|
||||
},
|
||||
"node_modules/kuler": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
|
||||
@@ -25648,17 +25524,6 @@
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/libxmljs2/node_modules/brace-expansion": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
|
||||
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/libxmljs2/node_modules/cacache": {
|
||||
"version": "19.0.1",
|
||||
"resolved": "https://registry.npmjs.org/cacache/-/cacache-19.0.1.tgz",
|
||||
@@ -35722,7 +35587,7 @@
|
||||
"version": "7.0.27",
|
||||
"resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.27.tgz",
|
||||
"integrity": "sha512-I4FZcVFcqCRuT0ph6dCDpPuO4Xgzvh+spkcTr1gK7peIvxWauoloVO0vuy1FQnijT63ss6AsHB6+OIM4aXHbPg==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tldts-core": "^7.0.27"
|
||||
@@ -35735,28 +35600,9 @@
|
||||
"version": "7.0.27",
|
||||
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.27.tgz",
|
||||
"integrity": "sha512-YQ7uPjgWUibIK6DW5lrKujGwUKhLevU4hcGbP5O6TcIUb+oTjJYJVWPS4nZsIHrEEEG6myk/oqAJUEQmpZrHsg==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tls-client-node": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tls-client-node/-/tls-client-node-0.2.0.tgz",
|
||||
"integrity": "sha512-0PHJgaGPvMK9ly7xohviOoe8Oxos43IOIdsEhibgku4ce/3/YLhxJTPPKNQZII0PdcOjlfPweB9eRs13mWaWIg==",
|
||||
"hasInstallScript": true,
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"koffi": "^2.8.9",
|
||||
"tough-cookie": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fatihkabakk"
|
||||
}
|
||||
},
|
||||
"node_modules/to-regex-range": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||
@@ -35815,7 +35661,7 @@
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
|
||||
"integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",
|
||||
"devOptional": true,
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tldts": "^7.0.5"
|
||||
@@ -37730,9 +37576,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/wreq-js": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/wreq-js/-/wreq-js-3.1.0.tgz",
|
||||
"integrity": "sha512-c+DF8s0kiCwTzXFwCNjBYJZMkodk2OukamoielaPegXWctrDth5tB1w0mszX7nysIJU4zge5q0RZUfoOfqH+uQ==",
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wreq-js/-/wreq-js-3.0.0.tgz",
|
||||
"integrity": "sha512-RZCoRSevVPpH4A4B4MxbFGo/pVPFveWd2gbe4ENKpPWlKXEYklZSDESOjBMmrIsmnkHh+nhM4PNJvG+NL7wBPA==",
|
||||
"cpu": [
|
||||
"x64",
|
||||
"arm64"
|
||||
@@ -37746,15 +37592,6 @@
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@wreq-js/binding-darwin-arm64": "3.1.0",
|
||||
"@wreq-js/binding-darwin-x64": "3.1.0",
|
||||
"@wreq-js/binding-linux-arm64-gnu": "3.1.0",
|
||||
"@wreq-js/binding-linux-arm64-musl": "3.1.0",
|
||||
"@wreq-js/binding-linux-x64-gnu": "3.1.0",
|
||||
"@wreq-js/binding-linux-x64-musl": "3.1.0",
|
||||
"@wreq-js/binding-win32-x64-msvc": "3.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/write-file-atomic": {
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
"src/types/",
|
||||
".env.example",
|
||||
"scripts/build/postinstall.mjs",
|
||||
"scripts/build/fixTlsClientNodeBinary.mjs",
|
||||
"scripts/build/fixPlaywrightAndroid.mjs",
|
||||
"bin/cli/runtime/",
|
||||
"scripts/postinstall.mjs",
|
||||
@@ -38,6 +37,8 @@
|
||||
"scripts/build/backendOnlyPages.mjs",
|
||||
"scripts/build/build-tproxy-native.mjs",
|
||||
"scripts/build/native-binary-compat.mjs",
|
||||
"scripts/build/wreqJsNative.mjs",
|
||||
"config/release/wreq-js-native-manifest.json",
|
||||
"scripts/build/build-next-isolated.mjs",
|
||||
"scripts/build/runtime-env.mjs",
|
||||
"scripts/packs/optionalPackManifest.mjs",
|
||||
@@ -356,8 +357,7 @@
|
||||
"keytar": "^7.9.0",
|
||||
"onnxruntime-node": "1.24.3",
|
||||
"sqlite-vec": "^0.1.9",
|
||||
"tls-client-node": "^0.2.0",
|
||||
"wreq-js": "^3.1.0"
|
||||
"wreq-js": "3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.13.0",
|
||||
|
||||
@@ -12,12 +12,10 @@ allowBuilds:
|
||||
core-js: true
|
||||
esbuild: true
|
||||
keytar: true
|
||||
koffi: true
|
||||
libxmljs2: true
|
||||
onnxruntime-node: true
|
||||
protobufjs: true
|
||||
sharp: true
|
||||
tls-client-node: true
|
||||
unrs-resolver: true
|
||||
onlyBuiltDependencies:
|
||||
- "@parcel/watcher"
|
||||
@@ -26,11 +24,9 @@ onlyBuiltDependencies:
|
||||
- "core-js"
|
||||
- "esbuild"
|
||||
- "keytar"
|
||||
- "koffi"
|
||||
- "libxmljs2"
|
||||
- "onnxruntime-node"
|
||||
- "omniroute"
|
||||
- "protobufjs"
|
||||
- "sharp"
|
||||
- "tls-client-node"
|
||||
- "unrs-resolver"
|
||||
|
||||
@@ -6,13 +6,11 @@
|
||||
"core-js",
|
||||
"esbuild",
|
||||
"keytar",
|
||||
"koffi",
|
||||
"libxmljs2",
|
||||
"omniroute",
|
||||
"onnxruntime-node",
|
||||
"protobufjs",
|
||||
"sharp",
|
||||
"tls-client-node",
|
||||
"unrs-resolver"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* tls-client-node postinstall repair (#7802).
|
||||
*
|
||||
* tls-client-node's own postinstall.js fetches a platform-specific native
|
||||
* binary (.so/.dylib/.dll) from the bogdanfinn/tls-client GitHub Releases
|
||||
* API. That script is blocked by `npm ci --ignore-scripts` (the Dockerfile
|
||||
* builder stage runs with scripts disabled for supply-chain hygiene) and,
|
||||
* even when it does run, silently no-ops on a rate-limited/failed GitHub API
|
||||
* call instead of raising — so `node_modules/tls-client-node/bin/` can end
|
||||
* up empty with no visible signal until the first live request throws
|
||||
* TlsClientUnavailableError (claude-web/grok-web/lmarena/
|
||||
* perplexity-web all share this transport).
|
||||
*
|
||||
* This module:
|
||||
* 1. Copies an already-fetched root `bin/` into the standalone
|
||||
* `dist/node_modules/tls-client-node/bin/` bundle (same pattern as
|
||||
* fixWreqJsBinary), so the published npm package works even though its
|
||||
* own `files` allowlist never ships the binary.
|
||||
* 2. When the root `bin/` is empty (--ignore-scripts blocked it, or a
|
||||
* transient GitHub rate-limit ate the first attempt), retries the
|
||||
* module's own postinstall.js with exponential backoff instead of
|
||||
* giving up on the first failure.
|
||||
*
|
||||
* Best-effort throughout: a failure here never throws out of postinstall.mjs
|
||||
* — it only warns, matching the other fix*Binary() steps. The runtime layer
|
||||
* (perplexityTlsClient.ts and its 4 siblings) already surfaces a clear
|
||||
* TlsClientUnavailableError pointing at the missing binary, so an operator
|
||||
* who hits a still-empty bin/ after this repair gets an actionable message
|
||||
* rather than an opaque crash.
|
||||
*/
|
||||
|
||||
import { copyFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const DEFAULT_RETRY_DELAYS_MS = [1_000, 3_000, 8_000];
|
||||
|
||||
function hasAnyFile(dir) {
|
||||
if (!existsSync(dir)) return false;
|
||||
try {
|
||||
return readdirSync(dir).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function copyBinDir(sourceDir, destDir) {
|
||||
mkdirSync(destDir, { recursive: true });
|
||||
for (const file of readdirSync(sourceDir)) {
|
||||
copyFileSync(join(sourceDir, file), join(destDir, file));
|
||||
}
|
||||
}
|
||||
|
||||
async function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-run tls-client-node's own postinstall.js in-process, retrying with
|
||||
* backoff when the attempt leaves `bin/` empty (covers transient GitHub API
|
||||
* rate-limiting — the upstream script itself never throws on failure, it
|
||||
* only warns, so "still empty after running it" is the only failure signal
|
||||
* available).
|
||||
*/
|
||||
async function downloadWithRetry(rootTlsClientDir, retryDelaysMs, log) {
|
||||
const postinstallScript = join(rootTlsClientDir, "scripts", "postinstall.js");
|
||||
const binDir = join(rootTlsClientDir, "bin");
|
||||
if (!existsSync(postinstallScript)) return false;
|
||||
|
||||
for (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {
|
||||
if (attempt > 0) {
|
||||
log(
|
||||
` ⏳ tls-client-node native binary still missing — retrying download ` +
|
||||
`(attempt ${attempt + 1}/${retryDelaysMs.length + 1}) after rate-limit/backoff...`
|
||||
);
|
||||
await sleep(retryDelaysMs[attempt - 1]);
|
||||
}
|
||||
|
||||
try {
|
||||
const { execFileSync } = await import("node:child_process");
|
||||
execFileSync(process.execPath, [postinstallScript], {
|
||||
cwd: rootTlsClientDir,
|
||||
stdio: "pipe",
|
||||
timeout: 30_000,
|
||||
});
|
||||
} catch (err) {
|
||||
log(` ⚠️ tls-client-node postinstall attempt failed: ${err.message.split("\n")[0]}`);
|
||||
}
|
||||
|
||||
if (hasAnyFile(binDir)) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} opts
|
||||
* @param {string} opts.rootDir - repo root
|
||||
* @param {(msg: string) => void} [opts.log]
|
||||
* @param {number[]} [opts.retryDelaysMs] - override for tests (avoid real sleeps)
|
||||
*/
|
||||
export async function fixTlsClientNodeBinary({
|
||||
rootDir,
|
||||
log = (m) => console.log(m),
|
||||
retryDelaysMs = DEFAULT_RETRY_DELAYS_MS,
|
||||
} = {}) {
|
||||
const rootTlsClientDir = join(rootDir, "node_modules", "tls-client-node");
|
||||
const rootBinDir = join(rootTlsClientDir, "bin");
|
||||
const distTlsClientDir = join(rootDir, "dist", "node_modules", "tls-client-node");
|
||||
|
||||
if (!existsSync(rootTlsClientDir)) return;
|
||||
|
||||
if (!hasAnyFile(rootBinDir)) {
|
||||
log(
|
||||
"\n 🔧 tls-client-node native binary missing (blocked by --ignore-scripts or a " +
|
||||
"failed fetch) — attempting repair...\n"
|
||||
);
|
||||
const recovered = await downloadWithRetry(rootTlsClientDir, retryDelaysMs, log);
|
||||
if (!recovered) {
|
||||
console.warn(
|
||||
"\n ⚠️ Could not fetch tls-client-node's native binary " +
|
||||
"(GitHub API rate-limited or unreachable after retries)."
|
||||
);
|
||||
console.warn(
|
||||
" claude-web/grok-web/lmarena/perplexity-web will raise a clear " +
|
||||
"TlsClientUnavailableError on first use until this is resolved."
|
||||
);
|
||||
console.warn(
|
||||
` Manual fix: node ${join(rootTlsClientDir, "scripts", "postinstall.js")}\n`
|
||||
);
|
||||
return;
|
||||
}
|
||||
log(" ✅ tls-client-node native binary fetched successfully!\n");
|
||||
}
|
||||
|
||||
if (!existsSync(distTlsClientDir) || !hasAnyFile(rootBinDir)) return;
|
||||
|
||||
const distBinDir = join(distTlsClientDir, "bin");
|
||||
if (hasAnyFile(distBinDir)) return;
|
||||
|
||||
try {
|
||||
copyBinDir(rootBinDir, distBinDir);
|
||||
log(" ✅ tls-client-node native binary copied to standalone dist/node_modules.\n");
|
||||
} catch (err) {
|
||||
console.warn(` ⚠️ Could not copy tls-client-node binary into dist/: ${err.message}`);
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@
|
||||
* matrix leg. Everything except install-machine-forked optional packages is
|
||||
* platform-independent:
|
||||
*
|
||||
* - Bundled-for-all (verify only): koffi ships every triplet under
|
||||
* `build/koffi/<os>_<arch>`, better-sqlite3 v13 ships Node-API prebuilds for
|
||||
* 8 platforms, wreq-js ships `rust/wreq-js.<plat>-<arch>[-libc].node`, and
|
||||
* - Bundled-for-all (verify only): better-sqlite3 v13 ships Node-API prebuilds
|
||||
* for 8 platforms, wreq-js ships
|
||||
* `rust/wreq-js.<plat>-<arch>[-libc].node`, and
|
||||
* onnxruntime-node ships `bin/napi-v6/<os>/<arch>`.
|
||||
* - Install-machine-forked (hydrate): `@img/sharp-*`, `@img/sharp-libvips-*`,
|
||||
* `@ngrok/ngrok-*` and macOS-only `fsevents` resolve to whichever platform
|
||||
@@ -33,8 +33,7 @@ export const HYDRATED_ROOT_PACKAGES = ["fsevents"];
|
||||
export const BUNDLED_EXEMPTIONS = new Set(["onnxruntime-node:darwin-x64"]);
|
||||
|
||||
function platformTriple(platform, arch) {
|
||||
// koffi uses underscore triplets; better-sqlite3/wreq-js/onnx use dashes.
|
||||
return { koffi: `${platform}_${arch}`, dash: `${platform}-${arch}` };
|
||||
return { dash: `${platform}-${arch}` };
|
||||
}
|
||||
|
||||
function rmrf(target) {
|
||||
@@ -106,9 +105,6 @@ export function verifyBundledNatives({ nodeModulesDir, platform, arch }) {
|
||||
const errors = [];
|
||||
const triple = platformTriple(platform, arch);
|
||||
|
||||
const koffiDir = path.join(nodeModulesDir, "koffi", "build", "koffi", triple.koffi);
|
||||
if (!fs.existsSync(koffiDir)) errors.push(`koffi: missing bundled triplet ${triple.koffi}`);
|
||||
|
||||
const sqlitePrebuild = path.join(
|
||||
nodeModulesDir,
|
||||
"better-sqlite3",
|
||||
|
||||
@@ -94,6 +94,7 @@ export const PACK_ARTIFACT_ROOT_ALLOWED_EXACT_PATHS: string[] = [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"THIRD_PARTY_NOTICES.md",
|
||||
"config/release/wreq-js-native-manifest.json",
|
||||
"bin/aliasResolver.mjs",
|
||||
"bin/chatgpt-web-codex-mcp.mjs",
|
||||
// #7808: ESM loader hook split out of bin/aliasResolver.mjs to silence CodeQL
|
||||
@@ -136,12 +137,10 @@ export const PACK_ARTIFACT_ROOT_ALLOWED_EXACT_PATHS: string[] = [
|
||||
"scripts/build/build-next-isolated.mjs",
|
||||
"scripts/check/check-supported-node-runtime.ts",
|
||||
"scripts/build/native-binary-compat.mjs",
|
||||
"scripts/build/wreqJsNative.mjs",
|
||||
"scripts/build/postinstall.mjs",
|
||||
"scripts/build/postinstallSupport.mjs",
|
||||
"scripts/build/colocateOptionals.mjs",
|
||||
// #7802: imported by scripts/build/postinstall.mjs to repair tls-client-node's
|
||||
// native binary (claude-web/grok-web/lmarena/perplexity-web transport).
|
||||
"scripts/build/fixTlsClientNodeBinary.mjs",
|
||||
// #8859: imported by scripts/build/postinstall.mjs to repair playwright-core's
|
||||
// browser resolution on Termux/Android (no glibc, no bundled browsers).
|
||||
"scripts/build/fixPlaywrightAndroid.mjs",
|
||||
@@ -222,13 +221,14 @@ export const PACK_ARTIFACT_REQUIRED_PATHS: string[] = [
|
||||
// or the CLI fails to boot — list them REQUIRED so a regression is loud.
|
||||
"bin/aliasResolver.mjs",
|
||||
"bin/aliasResolverHook.mjs",
|
||||
"config/release/wreq-js-native-manifest.json",
|
||||
"package.json",
|
||||
"scripts/build/native-binary-compat.mjs",
|
||||
"scripts/build/postinstall.mjs",
|
||||
"scripts/build/postinstallSupport.mjs",
|
||||
"scripts/build/colocateOptionals.mjs",
|
||||
"scripts/build/fixTlsClientNodeBinary.mjs",
|
||||
"scripts/build/runtime-env.mjs",
|
||||
"scripts/build/wreqJsNative.mjs",
|
||||
// #10382: runtime imports of bin/cli/commands/packs.mjs (optional packs CLI) —
|
||||
// listed REQUIRED so their absence from the tarball fails loudly.
|
||||
"scripts/packs/optionalPackInstaller.mjs",
|
||||
|
||||
@@ -14,8 +14,7 @@
|
||||
*
|
||||
* Modules repaired:
|
||||
* - better-sqlite3 (SQLite bindings)
|
||||
* - wreq-js (TLS client for OAuth providers)
|
||||
* - tls-client-node (TLS client for claude-web/grok-web/lmarena/perplexity-web)
|
||||
* - wreq-js (TLS client for OAuth and web-cookie providers)
|
||||
* - sql.js (WASM SQLite fallback runtime)
|
||||
* - node-machine-id (local CLI machine-token server runtime)
|
||||
*
|
||||
@@ -26,15 +25,7 @@
|
||||
* Fixes: https://github.com/diegosouzapw/OmniRoute/issues/7802
|
||||
*/
|
||||
|
||||
import {
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -42,8 +33,8 @@ import { fileURLToPath } from "node:url";
|
||||
import { PUBLISHED_BUILD_ARCH, PUBLISHED_BUILD_PLATFORM } from "./native-binary-compat.mjs";
|
||||
import { hasStandaloneAppBundle, isTermux } from "./postinstallSupport.mjs";
|
||||
import { colocateLlmlinguaOptionals } from "./colocateOptionals.mjs";
|
||||
import { fixTlsClientNodeBinary } from "./fixTlsClientNodeBinary.mjs";
|
||||
import { fixPlaywrightAndroid } from "./fixPlaywrightAndroid.mjs";
|
||||
import { resolveWreqJsNativeBinaryName } from "./wreqJsNative.mjs";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
@@ -277,7 +268,7 @@ async function fixWreqJsBinary() {
|
||||
if (process.platform === "android" || isTermux()) {
|
||||
console.log(
|
||||
" [postinstall] wreq-js: skipped on Termux/Android " +
|
||||
"(libgcc not available — OAuth TLS fingerprinting will use the fallback path)"
|
||||
"(wreq-js 3.0.0 does not publish an Android native addon)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -289,7 +280,16 @@ async function fixWreqJsBinary() {
|
||||
return;
|
||||
}
|
||||
|
||||
const binaryName = `wreq-js.${process.platform}-${process.arch}.node`;
|
||||
const binaryName = resolveWreqJsNativeBinaryName({
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
});
|
||||
if (!binaryName) {
|
||||
console.warn(
|
||||
` ⚠️ wreq-js 3.0.0 has no native addon for ${process.platform}-${process.arch}.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
const appBinaryPath = join(appWreqDir, binaryName);
|
||||
const rootBinaryPath = join(rootWreqDir, binaryName);
|
||||
|
||||
@@ -318,27 +318,7 @@ async function fixWreqJsBinary() {
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 2: Copy entire rust/ directory from root (gets all platform binaries)
|
||||
if (existsSync(rootWreqDir)) {
|
||||
try {
|
||||
mkdirSync(appWreqDir, { recursive: true });
|
||||
const files = readdirSync(rootWreqDir);
|
||||
for (const file of files) {
|
||||
if (file.endsWith(".node")) {
|
||||
copyFileSync(join(rootWreqDir, file), join(appWreqDir, file));
|
||||
}
|
||||
}
|
||||
if (existsSync(appBinaryPath)) {
|
||||
process.dlopen({ exports: {} }, appBinaryPath);
|
||||
console.log(" ✅ wreq-js native module fixed (full copy) successfully!\n");
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(` ⚠️ wreq-js full copy failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 3: Rebuild wreq-js inside dist/
|
||||
// Strategy 2: Rebuild wreq-js inside dist/
|
||||
console.log(" 📥 Attempting npm rebuild wreq-js...");
|
||||
try {
|
||||
const { execSync } = await import("node:child_process");
|
||||
@@ -359,8 +339,10 @@ async function fixWreqJsBinary() {
|
||||
console.warn(
|
||||
`\n ⚠️ Could not fix wreq-js native module for ${process.platform}-${process.arch}.`
|
||||
);
|
||||
console.warn(" OAuth-based providers (Codex, Cursor, etc.) may not work.");
|
||||
console.warn(` Manual fix: cd ${join(ROOT, "dist")} && npm install wreq-js --no-save\n`);
|
||||
console.warn(" Browser-TLS OAuth and web-cookie providers may not work.");
|
||||
console.warn(
|
||||
` Manual fix: cd ${join(ROOT, "dist")} && npm install wreq-js@3.0.0 --save-exact\n`
|
||||
);
|
||||
}
|
||||
|
||||
async function ensureSwcHelpers() {
|
||||
@@ -470,7 +452,6 @@ async function ensureStandaloneRuntimePackages() {
|
||||
await verifyDevNativeModules();
|
||||
await fixBetterSqliteBinary();
|
||||
await fixWreqJsBinary();
|
||||
await fixTlsClientNodeBinary({ rootDir: ROOT });
|
||||
await fixPlaywrightAndroid({ rootDir: ROOT });
|
||||
await ensureSwcHelpers();
|
||||
await ensureStandaloneRuntimePackages();
|
||||
|
||||
37
scripts/build/wreqJsNative.mjs
Normal file
37
scripts/build/wreqJsNative.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
/** Exact native-addon layout published by wreq-js 3.0.0. */
|
||||
export const WREQ_JS_NATIVE_BINARY_NAMES = Object.freeze([
|
||||
"wreq-js.darwin-arm64.node",
|
||||
"wreq-js.darwin-x64.node",
|
||||
"wreq-js.linux-arm64-gnu.node",
|
||||
"wreq-js.linux-arm64-musl.node",
|
||||
"wreq-js.linux-x64-gnu.node",
|
||||
"wreq-js.linux-x64-musl.node",
|
||||
"wreq-js.win32-x64-msvc.node",
|
||||
]);
|
||||
|
||||
/** Detect the C library used by the current Linux runtime. */
|
||||
export function detectRuntimeLibc() {
|
||||
if (process.platform !== "linux") return undefined;
|
||||
try {
|
||||
const report = process.report?.getReport();
|
||||
return report?.header?.glibcVersionRuntime ? "gnu" : "musl";
|
||||
} catch {
|
||||
return "musl";
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve the exact addon filename that wreq-js 3.0.0 will load. */
|
||||
export function resolveWreqJsNativeBinaryName({ platform, arch, libc }) {
|
||||
if (platform === "darwin" && (arch === "arm64" || arch === "x64")) {
|
||||
return `wreq-js.darwin-${arch}.node`;
|
||||
}
|
||||
if (platform === "linux" && (arch === "arm64" || arch === "x64")) {
|
||||
const linuxLibc = libc ?? detectRuntimeLibc();
|
||||
if (linuxLibc !== "gnu" && linuxLibc !== "musl") return null;
|
||||
return `wreq-js.linux-${arch}-${linuxLibc}.node`;
|
||||
}
|
||||
if (platform === "win32" && arch === "x64") {
|
||||
return "wreq-js.win32-x64-msvc.node";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
"use client";
|
||||
/** Polls the 3 agent sources (allSettled), listens to the `requests` WS channel as a refetch trigger. */
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useLiveDashboard } from "@/hooks/useLiveDashboard";
|
||||
import type { CloudAgentTask } from "@/lib/cloudAgent/types";
|
||||
import type { A2ATask } from "@/lib/a2a/taskManager";
|
||||
import type { FleetSnapshot } from "@/lib/conductor/hubProxy";
|
||||
import { fromCloudAgent } from "../model/fromCloudAgent";
|
||||
import { fromA2A } from "../model/fromA2A";
|
||||
import { fromConductor } from "../model/fromConductor";
|
||||
import { mergeSnapshot } from "../model/mergeSnapshot";
|
||||
import type { OrchSnapshot, SourceStatus } from "../model/orchestrationTypes";
|
||||
|
||||
export const POLL_MS = 5_000;
|
||||
export const WS_REFETCH_DEBOUNCE_MS = 1_000;
|
||||
|
||||
interface Raw {
|
||||
cloudAgent: CloudAgentTask[];
|
||||
a2a: A2ATask[];
|
||||
conductor: FleetSnapshot;
|
||||
}
|
||||
const EMPTY_RAW: Raw = {
|
||||
cloudAgent: [],
|
||||
a2a: [],
|
||||
conductor: { offline: true, runners: [], tasks: [] },
|
||||
};
|
||||
|
||||
async function fetchJson<T>(url: string, signal: AbortSignal): Promise<T> {
|
||||
const res = await fetch(url, { signal, cache: "no-store" });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
/** Builds the 3-source status list from a `Promise.allSettled` triple. */
|
||||
function buildSourceStatuses(
|
||||
ca: PromiseSettledResult<{ data: CloudAgentTask[] }>,
|
||||
a2a: PromiseSettledResult<{ tasks: A2ATask[] }>,
|
||||
cond: PromiseSettledResult<FleetSnapshot>,
|
||||
nowIso: string
|
||||
): SourceStatus[] {
|
||||
const next: SourceStatus[] = [];
|
||||
if (ca.status === "fulfilled") next.push({ source: "cloud-agent", ok: true });
|
||||
else
|
||||
next.push({
|
||||
source: "cloud-agent",
|
||||
ok: false,
|
||||
error: String(ca.reason),
|
||||
staleSince: nowIso,
|
||||
});
|
||||
if (a2a.status === "fulfilled") next.push({ source: "a2a", ok: true });
|
||||
else next.push({ source: "a2a", ok: false, error: String(a2a.reason), staleSince: nowIso });
|
||||
if (cond.status === "fulfilled") {
|
||||
next.push({ source: "conductor", ok: true, offline: cond.value.offline });
|
||||
} else
|
||||
next.push({
|
||||
source: "conductor",
|
||||
ok: false,
|
||||
error: String(cond.reason),
|
||||
staleSince: nowIso,
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export function useOrchestrationSnapshot() {
|
||||
// `raw` and `polledAt` are React state (not refs) so the merge below reads them
|
||||
// during render like any other state — a ref read during render trips the
|
||||
// `react-hooks/refs` lint rule, and computing `Date.now()` inline in the memo
|
||||
// factory trips `react-hooks/purity`. Sampling `Date.now()` once per poll (inside
|
||||
// the effect, not during render) keeps `mergeSnapshot`'s staleness math correct
|
||||
// without either violation.
|
||||
const [raw, setRaw] = useState<Raw>(EMPTY_RAW);
|
||||
const [statuses, setStatuses] = useState<SourceStatus[]>([]);
|
||||
// Lazy initializer (not a literal 0) so the pre-first-poll render already has a
|
||||
// real timestamp — with `0` the very first `mergeSnapshot` call stamped
|
||||
// `generatedAt` as the 1970 epoch. Safe: with EMPTY_RAW there is nothing to
|
||||
// staleness-filter at mount, so seeding `Date.now()` here changes no behavior.
|
||||
const [polledAt, setPolledAt] = useState<number>(() => Date.now());
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [showCompleted, setShowCompleted] = useState(false);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// Populated by the mount effect below; lets `refetch()` (and the WS debounce
|
||||
// trigger) reach the same poll loop without hoisting it out of the effect —
|
||||
// hoisting to a top-level `useCallback` invoked from the effect body trips
|
||||
// `react-hooks/set-state-in-effect`.
|
||||
const pollRef = useRef<() => void>(() => {});
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
const poll = async () => {
|
||||
const [ca, a2a, cond] = await Promise.allSettled([
|
||||
fetchJson<{ data: CloudAgentTask[] }>("/api/v1/agents/tasks?limit=100", controller.signal),
|
||||
fetchJson<{ tasks: A2ATask[] }>("/api/a2a/tasks?limit=200", controller.signal),
|
||||
fetchJson<FleetSnapshot>("/api/conductor/fleet", controller.signal),
|
||||
]);
|
||||
if (controller.signal.aborted) return;
|
||||
const nowMs = Date.now();
|
||||
const nowIso = new Date(nowMs).toISOString();
|
||||
const next = buildSourceStatuses(ca, a2a, cond, nowIso);
|
||||
|
||||
// Failed sources keep the previously stored slice — only overwrite what
|
||||
// actually resolved this round ("last good data" contract from the brief).
|
||||
setRaw((prev) => ({
|
||||
cloudAgent: ca.status === "fulfilled" ? ca.value.data : prev.cloudAgent,
|
||||
a2a: a2a.status === "fulfilled" ? a2a.value.tasks : prev.a2a,
|
||||
conductor: cond.status === "fulfilled" ? cond.value : prev.conductor,
|
||||
}));
|
||||
setStatuses(next);
|
||||
setPolledAt(nowMs);
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
pollRef.current = () => void poll();
|
||||
void poll();
|
||||
const id = setInterval(() => void poll(), POLL_MS);
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
controller.abort();
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current);
|
||||
debounceRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const refetch = useCallback(() => {
|
||||
pollRef.current();
|
||||
}, []);
|
||||
|
||||
useLiveDashboard({
|
||||
channels: ["requests"],
|
||||
onEvent: (payload) => {
|
||||
if (payload.channel !== "requests") return;
|
||||
if (debounceRef.current) return; // debounce burst → one refetch
|
||||
debounceRef.current = setTimeout(() => {
|
||||
debounceRef.current = null;
|
||||
refetch();
|
||||
}, WS_REFETCH_DEBOUNCE_MS);
|
||||
},
|
||||
});
|
||||
|
||||
const snapshot: OrchSnapshot = useMemo(
|
||||
() =>
|
||||
mergeSnapshot(
|
||||
{
|
||||
cloudAgent: fromCloudAgent(raw.cloudAgent),
|
||||
a2a: fromA2A(raw.a2a),
|
||||
conductor: fromConductor(raw.conductor),
|
||||
},
|
||||
statuses,
|
||||
{ now: polledAt, showCompleted }
|
||||
),
|
||||
[raw, statuses, showCompleted, polledAt]
|
||||
);
|
||||
|
||||
return { snapshot, isLoading, showCompleted, setShowCompleted, refetch };
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/** A2A tasks → unified orchestration nodes. Pure. */
|
||||
import type { A2ATask } from "@/lib/a2a/taskManager";
|
||||
import type { OrchEdge, OrchNode, OrchState } from "./orchestrationTypes";
|
||||
|
||||
const STATE_MAP: Record<string, OrchState> = {
|
||||
submitted: "queued",
|
||||
working: "running",
|
||||
completed: "succeeded",
|
||||
failed: "failed",
|
||||
cancelled: "cancelled",
|
||||
};
|
||||
const TERMINAL: ReadonlySet<OrchState> = new Set(["succeeded", "failed", "cancelled"]);
|
||||
|
||||
function truncate(s: string, n = 60): string {
|
||||
return s.length > n ? `${s.slice(0, n - 1)}…` : s;
|
||||
}
|
||||
|
||||
export function fromA2A(tasks: A2ATask[]): { nodes: OrchNode[]; edges: OrchEdge[] } {
|
||||
if (tasks.length === 0) return { nodes: [], edges: [] };
|
||||
const nodes: OrchNode[] = [];
|
||||
const edges: OrchEdge[] = [];
|
||||
const counts: Partial<Record<OrchState, number>> = {};
|
||||
|
||||
for (const t of tasks) {
|
||||
const mapped = STATE_MAP[t.state];
|
||||
const state: OrchState = mapped ?? "failed";
|
||||
counts[state] = (counts[state] ?? 0) + 1;
|
||||
const id = `a2a:${t.id}`;
|
||||
const firstUser = t.input.messages.find((m) => m.role === "user")?.content ?? "";
|
||||
nodes.push({
|
||||
id,
|
||||
kind: "work",
|
||||
source: "a2a",
|
||||
state,
|
||||
label: t.skill,
|
||||
sublabel: mapped ? truncate(firstUser) : `unknown state: ${String(t.state)}`,
|
||||
startedAt: t.createdAt,
|
||||
updatedAt: t.updatedAt,
|
||||
endedAt: TERMINAL.has(state) ? t.updatedAt : undefined,
|
||||
raw: t,
|
||||
});
|
||||
edges.push({
|
||||
id: `e:source:a2a→${id}`,
|
||||
from: "source:a2a",
|
||||
to: id,
|
||||
kind: "owns",
|
||||
active: state === "running",
|
||||
});
|
||||
}
|
||||
|
||||
nodes.unshift({ id: "source:a2a", kind: "source", source: "a2a", label: "A2A", counts });
|
||||
return { nodes, edges };
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/** Cloud Agent tasks → unified orchestration nodes. Pure. */
|
||||
import type { CloudAgentTask } from "@/lib/cloudAgent/types";
|
||||
import type { OrchEdge, OrchNode, OrchState } from "./orchestrationTypes";
|
||||
|
||||
const STATE_MAP: Record<string, OrchState> = {
|
||||
queued: "queued",
|
||||
running: "running",
|
||||
awaiting_approval: "waiting_approval",
|
||||
completed: "succeeded",
|
||||
failed: "failed",
|
||||
cancelled: "cancelled",
|
||||
};
|
||||
|
||||
function truncate(s: string, n = 60): string {
|
||||
return s.length > n ? `${s.slice(0, n - 1)}…` : s;
|
||||
}
|
||||
|
||||
export function fromCloudAgent(tasks: CloudAgentTask[]): { nodes: OrchNode[]; edges: OrchEdge[] } {
|
||||
if (tasks.length === 0) return { nodes: [], edges: [] };
|
||||
const nodes: OrchNode[] = [];
|
||||
const edges: OrchEdge[] = [];
|
||||
const counts: Partial<Record<OrchState, number>> = {};
|
||||
|
||||
for (const t of tasks) {
|
||||
const mapped = STATE_MAP[t.status];
|
||||
const state: OrchState = mapped ?? "failed";
|
||||
counts[state] = (counts[state] ?? 0) + 1;
|
||||
const id = `cloud-agent:${t.id}`;
|
||||
const active = state === "running";
|
||||
nodes.push({
|
||||
id,
|
||||
kind: "work",
|
||||
source: "cloud-agent",
|
||||
state,
|
||||
label: truncate(t.prompt),
|
||||
sublabel: mapped ? t.providerId : `${t.providerId} — unknown status: ${String(t.status)}`,
|
||||
startedAt: t.createdAt,
|
||||
updatedAt: t.updatedAt,
|
||||
endedAt: t.completedAt,
|
||||
cost: t.result?.cost,
|
||||
raw: t,
|
||||
});
|
||||
edges.push({
|
||||
id: `e:source:cloud-agent→${id}`,
|
||||
from: "source:cloud-agent",
|
||||
to: id,
|
||||
kind: "owns",
|
||||
active,
|
||||
});
|
||||
|
||||
const last = t.activities[t.activities.length - 1];
|
||||
if (active && last) {
|
||||
const actId = `${id}:activity`;
|
||||
nodes.push({
|
||||
id: actId,
|
||||
kind: "activity",
|
||||
source: "cloud-agent",
|
||||
state,
|
||||
label: truncate(last.content),
|
||||
sublabel: last.type,
|
||||
updatedAt: last.timestamp,
|
||||
});
|
||||
edges.push({ id: `e:${id}→${actId}`, from: id, to: actId, kind: "owns", active: true });
|
||||
}
|
||||
}
|
||||
|
||||
nodes.unshift({
|
||||
id: "source:cloud-agent",
|
||||
kind: "source",
|
||||
source: "cloud-agent",
|
||||
label: "Cloud Agent",
|
||||
counts,
|
||||
});
|
||||
return { nodes, edges };
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
/** Conductor fleet snapshot → unified orchestration nodes. Pure. */
|
||||
import type { FleetRunner, FleetSnapshot, FleetTask } from "@/lib/conductor/hubProxy";
|
||||
import type { OrchEdge, OrchNode, OrchState } from "./orchestrationTypes";
|
||||
|
||||
const TERMINAL: ReadonlySet<OrchState> = new Set(["succeeded", "failed", "cancelled"]);
|
||||
|
||||
function mapHubStatus(status: string): OrchState | null {
|
||||
const s = status.toLowerCase();
|
||||
if (s === "queued" || s === "pending") return "queued";
|
||||
if (s === "running" || s === "working" || s === "scheduled") return "running";
|
||||
if (s === "done" || s === "completed" || s === "succeeded") return "succeeded";
|
||||
if (s === "failed" || s === "error") return "failed";
|
||||
if (s === "cancelled" || s === "canceled") return "cancelled";
|
||||
return null;
|
||||
}
|
||||
|
||||
function taskNode(t: FleetTask, kind: "work" | "activity"): OrchNode {
|
||||
const mapped = mapHubStatus(t.status);
|
||||
const state: OrchState = mapped ?? "failed";
|
||||
return {
|
||||
id: `conductor:task:${t.id}`,
|
||||
kind,
|
||||
source: "conductor",
|
||||
state,
|
||||
label: t.summary ?? t.id,
|
||||
sublabel: mapped ? (t.repo ?? t.mode) : `unknown status: ${t.status}`,
|
||||
updatedAt: t.updated_at ?? undefined,
|
||||
// FleetTask has no dedicated completion timestamp — updated_at is the closest
|
||||
// proxy, same pattern as fromA2A.ts (A2ATask has no completedAt either).
|
||||
endedAt: TERMINAL.has(state) ? (t.updated_at ?? undefined) : undefined,
|
||||
raw: t,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tasks whose runner actually exists in `snap.runners` AND is currently "running" — those
|
||||
* get "absorbed" into that runner's ActivityNode instead of getting their own work node.
|
||||
* A running task pointing at a runner id that has since deregistered falls through to the
|
||||
* normal work-node loop instead of being silently skipped as "already an activity".
|
||||
*/
|
||||
function computeActiveByRunner(snap: FleetSnapshot): Map<string, FleetTask> {
|
||||
const runnerIds = new Set(snap.runners.map((r) => r.id));
|
||||
const activeByRunner = new Map<string, FleetTask>();
|
||||
for (const t of snap.tasks) {
|
||||
if (t.runner && runnerIds.has(t.runner) && mapHubStatus(t.status) === "running") {
|
||||
activeByRunner.set(t.runner, t);
|
||||
}
|
||||
}
|
||||
return activeByRunner;
|
||||
}
|
||||
|
||||
function runnerState(r: FleetRunner, activeTask: FleetTask | undefined): OrchState {
|
||||
if (!r.online) return "failed";
|
||||
if (r.draining) return "cancelled";
|
||||
return activeTask ? "running" : "queued";
|
||||
}
|
||||
|
||||
/** One work node per runner, plus an activity node for its currently-active task. */
|
||||
function runnerWorkNodes(
|
||||
snap: FleetSnapshot,
|
||||
activeByRunner: Map<string, FleetTask>,
|
||||
bump: (s: OrchState) => void
|
||||
): { nodes: OrchNode[]; edges: OrchEdge[] } {
|
||||
const nodes: OrchNode[] = [];
|
||||
const edges: OrchEdge[] = [];
|
||||
for (const r of snap.runners) {
|
||||
const id = `conductor:runner:${r.id}`;
|
||||
const activeTask = activeByRunner.get(r.id);
|
||||
const state = runnerState(r, activeTask);
|
||||
bump(state);
|
||||
nodes.push({
|
||||
id,
|
||||
kind: "work",
|
||||
source: "conductor",
|
||||
state,
|
||||
label: r.name,
|
||||
sublabel: r.clis.join(", "),
|
||||
raw: r,
|
||||
});
|
||||
edges.push({
|
||||
id: `e:source:conductor→${id}`,
|
||||
from: "source:conductor",
|
||||
to: id,
|
||||
kind: "owns",
|
||||
active: state === "running",
|
||||
});
|
||||
if (activeTask) {
|
||||
nodes.push(taskNode(activeTask, "activity"));
|
||||
edges.push({
|
||||
id: `e:${id}→conductor:task:${activeTask.id}`,
|
||||
from: id,
|
||||
to: `conductor:task:${activeTask.id}`,
|
||||
kind: "owns",
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { nodes, edges };
|
||||
}
|
||||
|
||||
/** Work nodes for tasks not already absorbed as a runner's activity node. */
|
||||
function remainingTaskWorkNodes(
|
||||
snap: FleetSnapshot,
|
||||
activeByRunner: Map<string, FleetTask>,
|
||||
bump: (s: OrchState) => void
|
||||
): { nodes: OrchNode[]; edges: OrchEdge[] } {
|
||||
const nodes: OrchNode[] = [];
|
||||
const edges: OrchEdge[] = [];
|
||||
for (const t of snap.tasks) {
|
||||
if (t.runner && activeByRunner.get(t.runner)?.id === t.id) continue; // already an activity
|
||||
const node = taskNode(t, "work");
|
||||
bump(node.state as OrchState);
|
||||
nodes.push(node);
|
||||
edges.push({
|
||||
id: `e:source:conductor→${node.id}`,
|
||||
from: "source:conductor",
|
||||
to: node.id,
|
||||
kind: "owns",
|
||||
active: node.state === "running",
|
||||
});
|
||||
}
|
||||
return { nodes, edges };
|
||||
}
|
||||
|
||||
export function fromConductor(snap: FleetSnapshot): { nodes: OrchNode[]; edges: OrchEdge[] } {
|
||||
if (snap.offline || (snap.runners.length === 0 && snap.tasks.length === 0)) {
|
||||
return { nodes: [], edges: [] };
|
||||
}
|
||||
const counts: Partial<Record<OrchState, number>> = {};
|
||||
const bump = (s: OrchState) => {
|
||||
counts[s] = (counts[s] ?? 0) + 1;
|
||||
};
|
||||
|
||||
const activeByRunner = computeActiveByRunner(snap);
|
||||
const runners = runnerWorkNodes(snap, activeByRunner, bump);
|
||||
const tasks = remainingTaskWorkNodes(snap, activeByRunner, bump);
|
||||
const nodes = [...runners.nodes, ...tasks.nodes];
|
||||
const edges = [...runners.edges, ...tasks.edges];
|
||||
|
||||
nodes.unshift({
|
||||
id: "source:conductor",
|
||||
kind: "source",
|
||||
source: "conductor",
|
||||
label: "Conductor",
|
||||
counts,
|
||||
});
|
||||
return { nodes, edges };
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
/** Merge the three source mappers into one snapshot: root, dedupe, staleness filter, cap. Pure. */
|
||||
import {
|
||||
MAX_WORK_NODES,
|
||||
STALE_COMPLETED_MS,
|
||||
type OrchEdge,
|
||||
type OrchNode,
|
||||
type OrchSnapshot,
|
||||
type OrchSource,
|
||||
type OrchState,
|
||||
type SourceStatus,
|
||||
} from "./orchestrationTypes";
|
||||
|
||||
const TERMINAL: ReadonlySet<OrchState> = new Set(["succeeded", "failed", "cancelled"]);
|
||||
|
||||
export interface MergeOptions {
|
||||
now: number;
|
||||
showCompleted?: boolean;
|
||||
}
|
||||
|
||||
interface Part {
|
||||
nodes: OrchNode[];
|
||||
edges: OrchEdge[];
|
||||
}
|
||||
|
||||
interface NodesAndEdges {
|
||||
nodes: OrchNode[];
|
||||
edges: OrchEdge[];
|
||||
}
|
||||
|
||||
function conductorMirrorId(node: OrchNode): string | null {
|
||||
const raw = node.raw as { metadata?: { conductor?: { task_id?: unknown } } } | undefined;
|
||||
const id = raw?.metadata?.conductor?.task_id;
|
||||
return typeof id === "string" ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* (2) Conductor↔A2A dedupe — key verified in src/lib/conductor/bridge.ts::ensureMirrored.
|
||||
* Mutates `dropped` in place; returns the (possibly patched) nodes/edges.
|
||||
*/
|
||||
function dedupeConductorMirrors(
|
||||
nodes: OrchNode[],
|
||||
edges: OrchEdge[],
|
||||
dropped: Set<string>
|
||||
): NodesAndEdges {
|
||||
const conductorTaskIds = new Set(
|
||||
nodes
|
||||
.filter((n) => n.source === "conductor" && n.id.startsWith("conductor:task:"))
|
||||
.map((n) => n.id.slice("conductor:task:".length))
|
||||
);
|
||||
const nextNodes = [...nodes];
|
||||
const nextEdges = [...edges];
|
||||
for (const n of nextNodes) {
|
||||
if (n.source !== "a2a" || n.kind !== "work") continue;
|
||||
const mirror = conductorMirrorId(n);
|
||||
if (mirror && conductorTaskIds.has(mirror)) {
|
||||
dropped.add(n.id);
|
||||
const cIndex = nextNodes.findIndex((c) => c.id === `conductor:task:${mirror}`);
|
||||
if (cIndex !== -1) {
|
||||
// Copy rather than mutate — the original object is still referenced by
|
||||
// parts.conductor.nodes, and this function's contract is Pure.
|
||||
const cNode: OrchNode = { ...nextNodes[cIndex], mirrorOf: n.id };
|
||||
nextNodes[cIndex] = cNode;
|
||||
nextEdges.push({
|
||||
id: `e:mirror:${cNode.id}`,
|
||||
from: cNode.id,
|
||||
to: "source:a2a",
|
||||
kind: "mirror",
|
||||
active: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return { nodes: nextNodes, edges: nextEdges };
|
||||
}
|
||||
|
||||
/** (3) staleness filter — adds stale terminal work/activity node ids to `dropped`. */
|
||||
function markStaleCompleted(nodes: OrchNode[], now: number, dropped: Set<string>): void {
|
||||
for (const n of nodes) {
|
||||
if (n.kind !== "work" && n.kind !== "activity") continue;
|
||||
if (
|
||||
n.state &&
|
||||
TERMINAL.has(n.state) &&
|
||||
n.endedAt &&
|
||||
now - Date.parse(n.endedAt) > STALE_COMPLETED_MS
|
||||
) {
|
||||
dropped.add(n.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One source's overflow placeholder node, or null when it fits under `budgetPer`. */
|
||||
function overflowNodeForSource(
|
||||
source: OrchSource,
|
||||
list: OrchNode[],
|
||||
budgetPer: number,
|
||||
dropped: Set<string>
|
||||
): OrchNode | null {
|
||||
if (list.length <= budgetPer) return null;
|
||||
list.sort((a, b) => Date.parse(b.updatedAt ?? "0") - Date.parse(a.updatedAt ?? "0"));
|
||||
const excess = list.slice(budgetPer);
|
||||
const counts: Partial<Record<OrchState, number>> = {};
|
||||
for (const n of excess) {
|
||||
dropped.add(n.id);
|
||||
if (n.state) counts[n.state] = (counts[n.state] ?? 0) + 1;
|
||||
}
|
||||
return {
|
||||
id: `overflow:${source}`,
|
||||
kind: "overflow",
|
||||
source,
|
||||
label: `+${excess.length} more`,
|
||||
counts,
|
||||
// Additive: lets overviewProjection fold true per-state totals into its
|
||||
// counters even though these nodes no longer render on the canvas
|
||||
// (operator ruling — spec governs, counters must show TRUE totals).
|
||||
droppedByState: counts,
|
||||
};
|
||||
}
|
||||
|
||||
/** (4) cap with per-source overflow, newest kept. */
|
||||
function capWorkNodesWithOverflow(
|
||||
nodes: OrchNode[],
|
||||
edges: OrchEdge[],
|
||||
dropped: Set<string>
|
||||
): NodesAndEdges {
|
||||
const works = nodes.filter((n) => n.kind === "work");
|
||||
if (works.length <= MAX_WORK_NODES) return { nodes, edges };
|
||||
|
||||
const bySource = new Map<OrchSource, OrchNode[]>();
|
||||
for (const w of works) {
|
||||
const list = bySource.get(w.source as OrchSource) ?? [];
|
||||
list.push(w);
|
||||
bySource.set(w.source as OrchSource, list);
|
||||
}
|
||||
const budgetPer = Math.max(1, Math.floor(MAX_WORK_NODES / bySource.size));
|
||||
const overflowNodes: OrchNode[] = [];
|
||||
for (const [source, list] of bySource) {
|
||||
const overflow = overflowNodeForSource(source, list, budgetPer, dropped);
|
||||
if (overflow) overflowNodes.push(overflow);
|
||||
}
|
||||
|
||||
const nextNodes = nodes.filter((n) => !dropped.has(n.id)).concat(overflowNodes);
|
||||
const nextEdges = edges.filter((e) => !dropped.has(e.from) && !dropped.has(e.to));
|
||||
for (const o of overflowNodes) {
|
||||
nextEdges.push({
|
||||
id: `e:source:${o.source}→${o.id}`,
|
||||
from: `source:${o.source}`,
|
||||
to: o.id,
|
||||
kind: "owns",
|
||||
active: false,
|
||||
});
|
||||
}
|
||||
return { nodes: nextNodes, edges: nextEdges };
|
||||
}
|
||||
|
||||
/**
|
||||
* (1) root — link every present SourceNode, plus failed sources so the UI can show them
|
||||
* stale. Returns nodes with the root prepended.
|
||||
*/
|
||||
function buildRootAndSourceEdges(
|
||||
nodes: OrchNode[],
|
||||
edges: OrchEdge[],
|
||||
sources: SourceStatus[]
|
||||
): NodesAndEdges {
|
||||
const root: OrchNode = { id: "orchestrator", kind: "orchestrator", label: "OmniRoute" };
|
||||
const nextNodes = [...nodes];
|
||||
const nextEdges = [...edges];
|
||||
const sourceIds = new Set(nextNodes.filter((n) => n.kind === "source").map((n) => n.id));
|
||||
for (const s of sources) {
|
||||
// `!s.ok` covers hard failures; `s.offline` also materializes a placeholder
|
||||
// for a source that reported ok:true but offline:true (e.g. Conductor with
|
||||
// no hub configured) — otherwise that source never gets a SourceNode at all
|
||||
// and its "offline" sublabel can never render.
|
||||
if ((!s.ok || s.offline) && !sourceIds.has(`source:${s.source}`) && s.source !== "routing") {
|
||||
nextNodes.push({
|
||||
id: `source:${s.source}`,
|
||||
kind: "source",
|
||||
source: s.source,
|
||||
label: s.source,
|
||||
sublabel: s.offline ? "offline" : "error",
|
||||
});
|
||||
sourceIds.add(`source:${s.source}`);
|
||||
}
|
||||
}
|
||||
for (const id of sourceIds) {
|
||||
nextEdges.push({
|
||||
id: `e:orchestrator→${id}`,
|
||||
from: "orchestrator",
|
||||
to: id,
|
||||
kind: "owns",
|
||||
active: false,
|
||||
});
|
||||
}
|
||||
return { nodes: [root, ...nextNodes], edges: nextEdges };
|
||||
}
|
||||
|
||||
export function mergeSnapshot(
|
||||
parts: { cloudAgent: Part; a2a: Part; conductor: Part },
|
||||
sources: SourceStatus[],
|
||||
opts: MergeOptions
|
||||
): OrchSnapshot {
|
||||
let nodes: OrchNode[] = [...parts.cloudAgent.nodes, ...parts.a2a.nodes, ...parts.conductor.nodes];
|
||||
let edges: OrchEdge[] = [...parts.cloudAgent.edges, ...parts.a2a.edges, ...parts.conductor.edges];
|
||||
|
||||
const dropped = new Set<string>();
|
||||
({ nodes, edges } = dedupeConductorMirrors(nodes, edges, dropped));
|
||||
|
||||
if (!opts.showCompleted) {
|
||||
markStaleCompleted(nodes, opts.now, dropped);
|
||||
}
|
||||
nodes = nodes.filter((n) => !dropped.has(n.id));
|
||||
edges = edges.filter((e) => !dropped.has(e.from) && !dropped.has(e.to));
|
||||
|
||||
({ nodes, edges } = capWorkNodesWithOverflow(nodes, edges, dropped));
|
||||
({ nodes, edges } = buildRootAndSourceEdges(nodes, edges, sources));
|
||||
|
||||
return { nodes, edges, sources, generatedAt: new Date(opts.now).toISOString() };
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
/** OrchSnapshot → @xyflow nodes/edges with a deterministic shallow 3-layer layout. Pure. */
|
||||
import type { Edge, Node } from "@xyflow/react";
|
||||
import { edgeStyle } from "@/shared/components/flow/edgeStyles";
|
||||
import type { OrchNodeKind, OrchSnapshot } from "./orchestrationTypes";
|
||||
|
||||
const LAYER_Y: Record<OrchNodeKind, number> = {
|
||||
orchestrator: 0,
|
||||
source: 150,
|
||||
work: 320,
|
||||
overflow: 320,
|
||||
activity: 470,
|
||||
};
|
||||
const X_GAP = 260;
|
||||
|
||||
export function orchestrationToFlow(snap: OrchSnapshot): {
|
||||
nodes: Node[];
|
||||
edges: Edge[];
|
||||
fitKey: string;
|
||||
} {
|
||||
const byLayer = new Map<number, string[]>();
|
||||
for (const n of [...snap.nodes].sort((a, b) => a.id.localeCompare(b.id))) {
|
||||
const y = LAYER_Y[n.kind];
|
||||
const ids = byLayer.get(y) ?? [];
|
||||
ids.push(n.id);
|
||||
byLayer.set(y, ids);
|
||||
}
|
||||
const pos = new Map<string, { x: number; y: number }>();
|
||||
for (const [y, ids] of byLayer) {
|
||||
const width = (ids.length - 1) * X_GAP;
|
||||
ids.forEach((id, i) => pos.set(id, { x: i * X_GAP - width / 2, y }));
|
||||
}
|
||||
|
||||
const stateOf = new Map(snap.nodes.map((n) => [n.id, n.state]));
|
||||
const nodes: Node[] = snap.nodes.map((n) => ({
|
||||
id: n.id,
|
||||
type: n.kind,
|
||||
position: pos.get(n.id)!,
|
||||
data: n as unknown as Record<string, unknown>,
|
||||
}));
|
||||
const edges: Edge[] = snap.edges.map((e) => {
|
||||
const target = stateOf.get(e.to);
|
||||
const style = edgeStyle(e.active, false, target === "failed", target === "succeeded");
|
||||
return {
|
||||
id: e.id,
|
||||
source: e.from,
|
||||
target: e.to,
|
||||
animated: e.active,
|
||||
style: e.kind === "mirror" ? { ...style, strokeDasharray: "6 4" } : style,
|
||||
};
|
||||
});
|
||||
|
||||
const fitKey = snap.nodes
|
||||
.filter((n) => n.kind === "work")
|
||||
.map((n) => n.id)
|
||||
.sort()
|
||||
.join("|");
|
||||
return { nodes, edges, fitKey };
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/**
|
||||
* Pure domain vocabulary for the Orchestration Canvas — no React, no side effects.
|
||||
* Spec: _tasks/superpowers/specs/2026-08-30-orchestration-canvas-design.md
|
||||
*/
|
||||
import { STATUS_HEX } from "@/shared/constants/statusColors";
|
||||
|
||||
export type OrchState =
|
||||
"queued" | "running" | "waiting_approval" | "succeeded" | "failed" | "cancelled";
|
||||
export type OrchSource = "cloud-agent" | "a2a" | "conductor" | "routing";
|
||||
export type OrchNodeKind = "orchestrator" | "source" | "work" | "activity" | "overflow";
|
||||
|
||||
export interface OrchNode {
|
||||
id: string; // `${source}:${sourceId}` for work nodes
|
||||
kind: OrchNodeKind;
|
||||
source?: OrchSource;
|
||||
state?: OrchState;
|
||||
label: string;
|
||||
sublabel?: string;
|
||||
startedAt?: string;
|
||||
updatedAt?: string;
|
||||
endedAt?: string;
|
||||
cost?: number;
|
||||
counts?: Partial<Record<OrchState, number>>;
|
||||
// Overflow nodes only: per-state counts of the work nodes folded into this
|
||||
// overflow node when the MAX_WORK_NODES cap engages. overviewProjection folds
|
||||
// this into its `counts` totals (never into `columns`) so operators still see
|
||||
// TRUE totals even when the canvas caps the rendered node count.
|
||||
droppedByState?: Partial<Record<OrchState, number>>;
|
||||
mirrorOf?: string;
|
||||
raw?: unknown;
|
||||
}
|
||||
|
||||
export interface OrchEdge {
|
||||
id: string;
|
||||
from: string;
|
||||
to: string;
|
||||
kind: "owns" | "mirror";
|
||||
active: boolean; // true while the target work is `running`
|
||||
}
|
||||
|
||||
export interface SourceStatus {
|
||||
source: OrchSource;
|
||||
ok: boolean;
|
||||
offline?: boolean;
|
||||
error?: string;
|
||||
staleSince?: string;
|
||||
}
|
||||
|
||||
export interface OrchSnapshot {
|
||||
nodes: OrchNode[];
|
||||
edges: OrchEdge[];
|
||||
sources: SourceStatus[];
|
||||
generatedAt: string;
|
||||
}
|
||||
|
||||
export const ORCH_STATES = [
|
||||
"queued",
|
||||
"running",
|
||||
"waiting_approval",
|
||||
"succeeded",
|
||||
"failed",
|
||||
"cancelled",
|
||||
] as const satisfies readonly OrchState[];
|
||||
|
||||
const STATE_HEX: Record<OrchState, string> = {
|
||||
queued: STATUS_HEX.muted,
|
||||
running: STATUS_HEX.warning,
|
||||
waiting_approval: STATUS_HEX.approval,
|
||||
succeeded: STATUS_HEX.success,
|
||||
failed: STATUS_HEX.error,
|
||||
cancelled: STATUS_HEX.muted,
|
||||
};
|
||||
|
||||
export function orchStateColor(state: OrchState): string {
|
||||
return STATE_HEX[state];
|
||||
}
|
||||
|
||||
export const STALE_COMPLETED_MS = 600_000; // completed >10 min ago drop out of the live view
|
||||
export const MAX_WORK_NODES = 40; // beyond this, per-source overflow nodes take over
|
||||
@@ -1,50 +0,0 @@
|
||||
/** OrchSnapshot → overview counters + kanban columns. Pure. */
|
||||
import {
|
||||
ORCH_STATES,
|
||||
type OrchNode,
|
||||
type OrchSnapshot,
|
||||
type OrchState,
|
||||
} from "./orchestrationTypes";
|
||||
|
||||
export interface OverviewData {
|
||||
counts: Record<OrchState, number>;
|
||||
columns: {
|
||||
queued: OrchNode[];
|
||||
running: OrchNode[];
|
||||
waiting_approval: OrchNode[];
|
||||
done: OrchNode[];
|
||||
};
|
||||
}
|
||||
|
||||
export function overviewProjection(snap: OrchSnapshot, comboActive: number): OverviewData {
|
||||
const counts = Object.fromEntries(ORCH_STATES.map((s) => [s, 0])) as Record<OrchState, number>;
|
||||
const columns: OverviewData["columns"] = {
|
||||
queued: [],
|
||||
running: [],
|
||||
waiting_approval: [],
|
||||
done: [],
|
||||
};
|
||||
|
||||
for (const n of snap.nodes) {
|
||||
// Overflow nodes (MAX_WORK_NODES cap) fold their dropped work nodes' true
|
||||
// per-state counts into `counts` only — never into `columns`, since those
|
||||
// nodes are not rendered on the canvas. Counters must show TRUE totals
|
||||
// even when the canvas caps the rendered node count (operator ruling).
|
||||
if (n.kind === "overflow" && n.droppedByState) {
|
||||
for (const s of ORCH_STATES) {
|
||||
counts[s] += n.droppedByState[s] ?? 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (n.kind !== "work" || !n.state) continue;
|
||||
counts[n.state] += 1;
|
||||
if (n.state === "queued" || n.state === "running" || n.state === "waiting_approval") {
|
||||
columns[n.state].push(n);
|
||||
} else {
|
||||
columns.done.push(n);
|
||||
}
|
||||
}
|
||||
columns.done.sort((a, b) => Date.parse(b.updatedAt ?? "0") - Date.parse(a.updatedAt ?? "0"));
|
||||
counts.running += comboActive;
|
||||
return { counts, columns };
|
||||
}
|
||||
@@ -287,7 +287,7 @@ export async function validateGrokWebProvider({ apiKey, providerSpecificData = {
|
||||
errorDetail = (response.text || "").slice(0, 240);
|
||||
} catch {}
|
||||
|
||||
// Detect Cloudflare challenge pages even with a 200 status from tls-client-node
|
||||
// Detect Cloudflare challenge pages even when the browser transport reports status 200.
|
||||
if (isCloudflareChallenge(errorDetail)) {
|
||||
return {
|
||||
valid: false,
|
||||
@@ -455,7 +455,7 @@ export async function validatePerplexityWebProvider({ apiKey, providerSpecificDa
|
||||
valid: false,
|
||||
error:
|
||||
"Cloudflare is blocking connections from this server's IP (TLS fingerprint rejected). " +
|
||||
"The session cookie may still be valid — install tls-client-node's native binary or route " +
|
||||
"The session cookie may still be valid — verify the wreq-js 3.0.0 native addon or route " +
|
||||
"perplexity-web through a residential proxy.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,6 +14,4 @@ export const STATUS_HEX = {
|
||||
warning: "#f59e0b",
|
||||
error: "#ef4444",
|
||||
muted: "#6b7280",
|
||||
/** Human-approval gate (waiting_approval) — violet, matching the industry de-facto palette. */
|
||||
approval: "#8b5cf6",
|
||||
} as const;
|
||||
|
||||
@@ -205,17 +205,17 @@ test("classifyLicense: exception does not apply to different package", () => {
|
||||
assert.equal(result.status, "denied", "exception must be per-package, not per-license");
|
||||
});
|
||||
|
||||
test("classifyLicense: exception with risk=medium still returns 'exception' (not denied)", () => {
|
||||
test("classifyLicense: a medium-risk custom exception still returns 'exception'", () => {
|
||||
const allowlist = makeAllowlist({
|
||||
exceptions: {
|
||||
"tls-client-node": {
|
||||
license: "Custom: LICENSE",
|
||||
justification: "Commons Clause + Apache-2.0. TODO: revisar.",
|
||||
"custom-runtime": {
|
||||
license: "Custom: reviewed terms",
|
||||
justification: "Reviewed custom runtime terms.",
|
||||
risk: "medium",
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = classifyLicense("tls-client-node@0.2.0", "Custom: LICENSE", allowlist);
|
||||
const result = classifyLicense("custom-runtime@1.0.0", "Custom: reviewed terms", allowlist);
|
||||
assert.equal(result.status, "exception");
|
||||
});
|
||||
|
||||
@@ -285,13 +285,6 @@ test("loadAllowlist: exceptions entries have required fields", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("loadAllowlist: tls-client-node exception has risk=medium (Commons Clause)", () => {
|
||||
const allowlist = loadAllowlist();
|
||||
const exc = allowlist.exceptions["tls-client-node"] as any;
|
||||
assert.ok(exc, "tls-client-node exception must be registered");
|
||||
assert.equal(exc.risk, "medium", "tls-client-node is a medium-risk exception (Commons Clause)");
|
||||
});
|
||||
|
||||
test("loadAllowlist: LGPL packages have registered exceptions", () => {
|
||||
const allowlist = loadAllowlist();
|
||||
const lgplPkgs = ["@img/sharp-libvips-linux-x64", "@img/sharp-libvips-linuxmusl-x64"];
|
||||
@@ -326,12 +319,6 @@ test("integration: classifyLicense passes MIT packages against real allowlist",
|
||||
assert.equal(result.status, "allowed");
|
||||
});
|
||||
|
||||
test("integration: classifyLicense passes tls-client-node as exception against real allowlist", () => {
|
||||
const allowlist = loadAllowlist();
|
||||
const result = classifyLicense("tls-client-node@0.2.0", "Custom: LICENSE", allowlist);
|
||||
assert.equal(result.status, "exception");
|
||||
});
|
||||
|
||||
test("integration: classifyLicense denies GPL-3.0 against real allowlist", () => {
|
||||
const allowlist = loadAllowlist();
|
||||
const result = classifyLicense("hypothetical-gpl@1.0.0", "GPL-3.0", allowlist);
|
||||
|
||||
@@ -266,7 +266,6 @@ test("verifyBundledNatives asserts serviceability and honors the onnx darwin-x64
|
||||
const root = tmpDir("s8-natives-");
|
||||
try {
|
||||
const nm = path.join(root, "node_modules");
|
||||
writeNative(nm, "koffi/build/koffi/linux_x64/koffi.node", "elf");
|
||||
writeNative(nm, "better-sqlite3/prebuilds/linux-x64.node", "napi");
|
||||
writeNative(nm, "wreq-js/rust/wreq-js.linux-x64-gnu.node", "rust");
|
||||
writeNative(nm, "onnxruntime-node/bin/napi-v6/linux/x64/libonnxruntime.so", "ort");
|
||||
@@ -278,18 +277,18 @@ test("verifyBundledNatives asserts serviceability and honors the onnx darwin-x64
|
||||
`expected serviceable: ${(good as { errors?: string[] }).errors?.join("; ")}`
|
||||
);
|
||||
|
||||
const missingKoffi = verifyBundledNatives({
|
||||
const missingPlatformNatives = verifyBundledNatives({
|
||||
nodeModulesDir: nm,
|
||||
platform: "darwin",
|
||||
arch: "arm64",
|
||||
});
|
||||
assert.equal(missingKoffi.ok, false);
|
||||
assert.ok((missingKoffi as { errors: string[] }).errors.some((e) => e.startsWith("koffi:")));
|
||||
|
||||
assert.equal(missingPlatformNatives.ok, false);
|
||||
assert.ok(
|
||||
(missingPlatformNatives as { errors: string[] }).errors.some((e) => e.startsWith("wreq-js:"))
|
||||
);
|
||||
// darwin-x64 has no onnxruntime-node prebuild at all — the exemption must keep it green
|
||||
// as long as the other bundled natives service that triple.
|
||||
const nm2 = path.join(root, "node_modules2");
|
||||
writeNative(nm2, "koffi/build/koffi/darwin_x64/koffi.node", "macho");
|
||||
writeNative(nm2, "better-sqlite3/prebuilds/darwin-x64.node", "napi");
|
||||
writeNative(nm2, "wreq-js/rust/wreq-js.darwin-x64.node", "rust");
|
||||
const exempted = verifyBundledNatives({ nodeModulesDir: nm2, platform: "darwin", arch: "x64" });
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
|
||||
import { tlsFetchStreaming } from "../../open-sse/services/claudeTlsClient.ts";
|
||||
@@ -15,19 +14,17 @@ const SSE_BODY = [
|
||||
|
||||
test("Claude Web keeps waiting when the first Opus SSE event takes longer than five seconds", async () => {
|
||||
const client = {
|
||||
request: async (_url: string, options: Record<string, unknown>) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, SLOW_FIRST_BYTE_MS));
|
||||
await writeFile(String(options.streamOutputPath), SSE_BODY);
|
||||
return {
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "",
|
||||
cookies: {},
|
||||
text: async () => "",
|
||||
json: async () => ({}),
|
||||
bytes: async () => new Uint8Array(),
|
||||
};
|
||||
},
|
||||
request: async () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
await new Promise((resolve) => setTimeout(resolve, SLOW_FIRST_BYTE_MS));
|
||||
controller.enqueue(new TextEncoder().encode(SSE_BODY));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "text/event-stream" } }
|
||||
),
|
||||
};
|
||||
|
||||
const result = await tlsFetchStreaming(
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, existsSync, readdirSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { fixTlsClientNodeBinary } from "../../scripts/build/fixTlsClientNodeBinary.mjs";
|
||||
|
||||
function makeRoot() {
|
||||
return mkdtempSync(join(tmpdir(), "fix-tls-client-node-binary-7802-"));
|
||||
}
|
||||
|
||||
function collectLogs() {
|
||||
const logs: string[] = [];
|
||||
return { logs, log: (m: string) => logs.push(m) };
|
||||
}
|
||||
|
||||
test("no-ops when node_modules/tls-client-node is absent (module not installed)", async () => {
|
||||
const rootDir = makeRoot();
|
||||
try {
|
||||
const { logs, log } = collectLogs();
|
||||
await fixTlsClientNodeBinary({ rootDir, log });
|
||||
assert.deepEqual(logs, []);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
test("copies an already-populated root bin/ into the standalone dist bundle (#7802 item 2)", async () => {
|
||||
const rootDir = makeRoot();
|
||||
try {
|
||||
const rootBin = join(rootDir, "node_modules", "tls-client-node", "bin");
|
||||
mkdirSync(rootBin, { recursive: true });
|
||||
writeFileSync(join(rootBin, "tls-client-linux-ubuntu-amd64-1.0.0.so"), "fake-binary");
|
||||
|
||||
const distTlsClientDir = join(rootDir, "dist", "node_modules", "tls-client-node");
|
||||
mkdirSync(distTlsClientDir, { recursive: true });
|
||||
|
||||
const { log } = collectLogs();
|
||||
await fixTlsClientNodeBinary({ rootDir, log });
|
||||
|
||||
const distBin = join(distTlsClientDir, "bin");
|
||||
assert.ok(existsSync(distBin), "dist bin/ should have been created");
|
||||
assert.deepEqual(readdirSync(distBin), ["tls-client-linux-ubuntu-amd64-1.0.0.so"]);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
test("retries the download when root bin/ is empty, and stops once a file appears (#7802 item 3)", async () => {
|
||||
const rootDir = makeRoot();
|
||||
try {
|
||||
const tlsClientDir = join(rootDir, "node_modules", "tls-client-node");
|
||||
const rootBin = join(tlsClientDir, "bin");
|
||||
mkdirSync(rootBin, { recursive: true });
|
||||
|
||||
const scriptsDir = join(tlsClientDir, "scripts");
|
||||
mkdirSync(scriptsDir, { recursive: true });
|
||||
// A postinstall.js stand-in that drops a file into bin/ on its 2nd invocation —
|
||||
// simulating a first attempt eaten by a GitHub rate-limit and a 2nd that recovers.
|
||||
writeFileSync(
|
||||
join(scriptsDir, "postinstall.js"),
|
||||
`const fs = require("fs");
|
||||
const path = require("path");
|
||||
const marker = path.join(__dirname, "..", ".attempts");
|
||||
const attempts = fs.existsSync(marker) ? Number(fs.readFileSync(marker, "utf8")) : 0;
|
||||
fs.writeFileSync(marker, String(attempts + 1));
|
||||
if (attempts + 1 >= 2) {
|
||||
fs.writeFileSync(path.join(__dirname, "..", "bin", "tls-client-linux-ubuntu-amd64-1.0.0.so"), "ok");
|
||||
}`
|
||||
);
|
||||
|
||||
const { logs, log } = collectLogs();
|
||||
await fixTlsClientNodeBinary({ rootDir, log, retryDelaysMs: [1, 1, 1] });
|
||||
|
||||
assert.ok(existsSync(join(rootBin, "tls-client-linux-ubuntu-amd64-1.0.0.so")));
|
||||
assert.ok(
|
||||
logs.some((m) => m.includes("fetched successfully")),
|
||||
"expected a success log once the retry recovered"
|
||||
);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
test("warns without throwing when every retry leaves bin/ empty (still rate-limited)", async () => {
|
||||
const rootDir = makeRoot();
|
||||
try {
|
||||
const tlsClientDir = join(rootDir, "node_modules", "tls-client-node");
|
||||
mkdirSync(join(tlsClientDir, "bin"), { recursive: true });
|
||||
const scriptsDir = join(tlsClientDir, "scripts");
|
||||
mkdirSync(scriptsDir, { recursive: true });
|
||||
// A postinstall.js stand-in that always fails to produce a binary (persistent rate-limit).
|
||||
writeFileSync(join(scriptsDir, "postinstall.js"), `process.exitCode = 0;`);
|
||||
|
||||
const originalWarn = console.warn;
|
||||
const warnings: string[] = [];
|
||||
console.warn = (m: string) => warnings.push(m);
|
||||
try {
|
||||
const { log } = collectLogs();
|
||||
await assert.doesNotReject(fixTlsClientNodeBinary({ rootDir, log, retryDelaysMs: [1, 1] }));
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
|
||||
assert.ok(
|
||||
warnings.some((m) => m.includes("Could not fetch tls-client-node")),
|
||||
"expected a clear warning pointing at the manual fix, not a silent no-op"
|
||||
);
|
||||
} finally {
|
||||
rmSync(rootDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
@@ -253,6 +253,7 @@ test("findMissingArtifactPaths flags missing root runtime files in the tarball",
|
||||
"bin/mcp-server.mjs",
|
||||
"bin/mcpStdioConsoleGuard.mjs",
|
||||
"bin/nodeRuntimeSupport.mjs",
|
||||
"config/release/wreq-js-native-manifest.json",
|
||||
"dist/head-response-guard.cjs",
|
||||
"dist/http-method-guard.cjs",
|
||||
"dist/main-server-timeouts.mjs",
|
||||
@@ -267,9 +268,9 @@ test("findMissingArtifactPaths flags missing root runtime files in the tarball",
|
||||
"dist/tls-options.mjs",
|
||||
"dist/webdav-handler.mjs",
|
||||
"scripts/build/colocateOptionals.mjs",
|
||||
"scripts/build/fixTlsClientNodeBinary.mjs",
|
||||
"scripts/build/native-binary-compat.mjs",
|
||||
"scripts/build/runtime-env.mjs",
|
||||
"scripts/build/wreqJsNative.mjs",
|
||||
"scripts/packs/optionalPackInstaller.mjs",
|
||||
"scripts/packs/optionalPackManifest.mjs",
|
||||
"src/shared/utils/nodeRuntimeSupport.ts",
|
||||
|
||||
@@ -1,25 +1,16 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
|
||||
// Issue #7134 — claude-web reported "Claude Web API error (400) with no
|
||||
// response body" even when Claude's upstream DID send a real JSON error body.
|
||||
//
|
||||
// Root cause: tlsFetchStreaming() streams the upstream response to a temp
|
||||
// file via tls-client-node's `streamOutputPath` mode. For a non-SSE,
|
||||
// non-2xx response, the native binding resolves with an EMPTY in-memory
|
||||
// `body` field (it only populates `body` for its non-streaming mode) even
|
||||
// though the real error bytes were already written to the temp file and
|
||||
// even peeked (`looksLikeSse`) to decide the response wasn't SSE. The old
|
||||
// code read the empty `r.body` instead of the file it just peeked, throwing
|
||||
// away the real upstream error detail.
|
||||
// The browser transport must peek a requested stream to distinguish SSE from
|
||||
// an upstream JSON error. Once it decides the response is not SSE, it must
|
||||
// buffer the same native body stream without discarding the bytes it peeked.
|
||||
//
|
||||
// This test injects a fake `client` (matching the `{ request }` shape
|
||||
// tlsFetchStreaming already accepts for DI) that reproduces the exact
|
||||
// tls-client-node contract under `streamOutputPath`: write bytes to the file,
|
||||
// resolve with an empty `body`. No `--experimental-test-module-mocks` flag
|
||||
// needed — this exercises the real, unmodified `tlsFetchStreaming` via
|
||||
// dependency injection instead of module-mocking `tls-client-node`.
|
||||
// tlsFetchStreaming accepts for DI). No experimental module mocks are needed:
|
||||
// the test exercises the production wreq response-stream path directly.
|
||||
|
||||
const { tlsFetchStreaming } = await import("../../open-sse/services/claudeTlsClient.ts");
|
||||
|
||||
@@ -33,21 +24,16 @@ const REAL_CLAUDE_ERROR_BODY = JSON.stringify({
|
||||
|
||||
function makeFakeClient(status: number, bodyOnFile: string) {
|
||||
return {
|
||||
request: async (_url: string, opts: Record<string, unknown>) => {
|
||||
const streamOutputPath = opts.streamOutputPath as string;
|
||||
await writeFile(streamOutputPath, bodyOnFile);
|
||||
return {
|
||||
status,
|
||||
headers: {},
|
||||
// tls-client-node does not populate `body` for streamed requests —
|
||||
// this is the exact defect condition.
|
||||
body: "",
|
||||
cookies: {},
|
||||
text: async () => "",
|
||||
json: async () => ({}),
|
||||
bytes: async () => new Uint8Array(),
|
||||
};
|
||||
},
|
||||
request: async () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(bodyOnFile));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ status }
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -73,19 +59,11 @@ test("issue #7134: tlsFetchStreaming surfaces the real error body for a non-SSE
|
||||
|
||||
test("issue #7134: tlsFetchStreaming still uses r.body when the native client DOES populate it", async () => {
|
||||
const client = {
|
||||
request: async (_url: string, opts: Record<string, unknown>) => {
|
||||
const streamOutputPath = opts.streamOutputPath as string;
|
||||
await writeFile(streamOutputPath, "{}");
|
||||
return {
|
||||
status: 403,
|
||||
headers: {},
|
||||
body: "populated body from native client",
|
||||
cookies: {},
|
||||
text: async () => "",
|
||||
json: async () => ({}),
|
||||
bytes: async () => new Uint8Array(),
|
||||
};
|
||||
},
|
||||
request: async () => ({
|
||||
status: 403,
|
||||
headers: {},
|
||||
body: "populated body from native client",
|
||||
}),
|
||||
};
|
||||
|
||||
const result = await tlsFetchStreaming(
|
||||
|
||||
@@ -2354,7 +2354,7 @@ test("claude-web validator: 500 → Claude.ai unavailable", async () => {
|
||||
test("claude-web validator: TLS client unavailable → clear error", async () => {
|
||||
const { TlsClientUnavailableError } = await import("../../open-sse/services/claudeTlsClient.ts");
|
||||
__setClaudeTlsFetchOverride(async () => {
|
||||
throw new TlsClientUnavailableError("tls-client-node not installed");
|
||||
throw new TlsClientUnavailableError("wreq-js 3.0.0 native addon unavailable");
|
||||
});
|
||||
|
||||
const result = await validateProviderApiKey({
|
||||
@@ -2363,7 +2363,7 @@ test("claude-web validator: TLS client unavailable → clear error", async () =>
|
||||
});
|
||||
|
||||
assert.equal(result.valid, false);
|
||||
assert.match(result.error || "", /tls-client-node not installed/i);
|
||||
assert.match(result.error || "", /wreq-js 3\.0\.0 native addon unavailable/i);
|
||||
__setClaudeTlsFetchOverride(null);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { test, afterEach } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = join(__dirname, "..", "..");
|
||||
|
||||
const TLS_CLIENT_WRAPPERS = [
|
||||
"open-sse/services/claudeTlsClient.ts",
|
||||
"open-sse/services/grokTlsClient.ts",
|
||||
"open-sse/services/perplexityTlsClient.ts",
|
||||
"open-sse/services/lmarenaTlsClient.ts",
|
||||
"open-sse/services/notionTlsClient.ts",
|
||||
] as const;
|
||||
|
||||
const originalDataDir = process.env.DATA_DIR;
|
||||
|
||||
afterEach(() => {
|
||||
if (originalDataDir === undefined) {
|
||||
delete process.env.DATA_DIR;
|
||||
} else {
|
||||
process.env.DATA_DIR = originalDataDir;
|
||||
}
|
||||
});
|
||||
|
||||
test("resolveTlsClientDownloadDir caches native binary under DATA_DIR/tls-client/bin (#8579)", async () => {
|
||||
const dataDir = mkdtempSync(join(tmpdir(), "omniroute-tls-client-8579-"));
|
||||
process.env.DATA_DIR = dataDir;
|
||||
|
||||
const { resolveTlsClientDownloadDir } =
|
||||
await import("../../open-sse/services/tlsClientDownloadDir.ts");
|
||||
|
||||
assert.equal(resolveTlsClientDownloadDir(), join(dataDir, "tls-client", "bin"));
|
||||
});
|
||||
|
||||
test("buildNativeTlsClientOptions passes downloadDir to tls-client-node (#8579)", async () => {
|
||||
const dataDir = mkdtempSync(join(tmpdir(), "omniroute-tls-client-opts-8579-"));
|
||||
process.env.DATA_DIR = dataDir;
|
||||
|
||||
const { buildNativeTlsClientOptions } =
|
||||
await import("../../open-sse/services/tlsClientDownloadDir.ts");
|
||||
|
||||
const options = buildNativeTlsClientOptions();
|
||||
|
||||
assert.equal(options.runtimeMode, "native");
|
||||
assert.equal(options.downloadDir, join(dataDir, "tls-client", "bin"));
|
||||
});
|
||||
|
||||
test("all remaining web-provider tls clients wire downloadDir through buildNativeTlsClientOptions (#8579)", () => {
|
||||
const base = readFileSync(join(ROOT, "open-sse/services/tlsClientBase.ts"), "utf8");
|
||||
assert.match(
|
||||
base,
|
||||
/buildNativeTlsClientOptions\(\)/,
|
||||
"tlsClientBase.ts must pass buildNativeTlsClientOptions() to TLSClient"
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
base,
|
||||
/new TLSClient\(\{\s*runtimeMode:\s*"native"\s*\}\)/,
|
||||
"tlsClientBase.ts must not construct TLSClient without downloadDir"
|
||||
);
|
||||
|
||||
for (const relPath of TLS_CLIENT_WRAPPERS) {
|
||||
const source = readFileSync(join(ROOT, relPath), "utf8");
|
||||
assert.match(
|
||||
source,
|
||||
/createTlsClientModule\(/,
|
||||
`${relPath} must go through createTlsClientModule so downloadDir is inherited`
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/new TLSClient\(\{\s*runtimeMode:\s*"native"\s*\}\)/,
|
||||
`${relPath} must not construct TLSClient without downloadDir`
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = join(__dirname, "..", "..");
|
||||
|
||||
test("Dockerfile's --ignore-scripts npm ci is compensated for tls-client-node's native binary, same as it is for wreq-js and better-sqlite3 (#7802)", () => {
|
||||
const dockerfile = readFileSync(join(ROOT, "Dockerfile"), "utf8");
|
||||
const postinstall = readFileSync(join(ROOT, "scripts/build/postinstall.mjs"), "utf8");
|
||||
|
||||
assert.match(
|
||||
dockerfile,
|
||||
// Flag-order tolerant on purpose: the assertion is about the --ignore-scripts
|
||||
// PRECONDITION, not the exact flag list. #9185 inserted --include=optional
|
||||
// (LLMLingua optional deps) and broke the literal pin without touching intent.
|
||||
/npm ci(?: --[\w-]+(?:=[\w-]+)?)* --ignore-scripts/,
|
||||
"expected the builder stage to install with --ignore-scripts (precondition of #7802)"
|
||||
);
|
||||
|
||||
assert.match(
|
||||
dockerfile,
|
||||
/better-sqlite3[\s\S]*node-gyp\.js rebuild/,
|
||||
"expected an explicit better-sqlite3 rebuild step after --ignore-scripts"
|
||||
);
|
||||
|
||||
assert.match(
|
||||
postinstall,
|
||||
/fixWreqJsBinary/,
|
||||
"expected postinstall.mjs to repair wreq-js's native binary"
|
||||
);
|
||||
|
||||
const dockerfileHandlesIt = /tls-client-node[\s\S]{0,200}(postinstall|rebuild|download)/i.test(
|
||||
dockerfile
|
||||
);
|
||||
const postinstallHandlesIt = /tls-client-node/i.test(postinstall);
|
||||
|
||||
assert.ok(
|
||||
dockerfileHandlesIt || postinstallHandlesIt,
|
||||
"tls-client-node has no --ignore-scripts compensation in Dockerfile or " +
|
||||
"scripts/build/postinstall.mjs (unlike better-sqlite3 and wreq-js) — " +
|
||||
"node_modules/tls-client-node/bin/ is never populated in the official " +
|
||||
"Docker image, so claude-web/grok-web/lmarena/perplexity-web " +
|
||||
"all fail with TlsClientUnavailableError at first request (#7802)"
|
||||
);
|
||||
});
|
||||
1078
tests/unit/tls-client-wreq-migration.test.ts
Normal file
1078
tests/unit/tls-client-wreq-migration.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
54
tests/unit/tls-client-wreq-residue.test.ts
Normal file
54
tests/unit/tls-client-wreq-residue.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
||||
|
||||
test("the distributable is pinned to wreq-js 3.0.0 with no tls-client-node or orphaned koffi residue", () => {
|
||||
const packageJson = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as {
|
||||
files: string[];
|
||||
optionalDependencies: Record<string, string>;
|
||||
};
|
||||
assert.equal(packageJson.optionalDependencies["wreq-js"], "3.0.0");
|
||||
assert.equal(packageJson.optionalDependencies["tls-client-node"], undefined);
|
||||
assert.equal(packageJson.files.includes("scripts/build/fixTlsClientNodeBinary.mjs"), false);
|
||||
|
||||
for (const relativePath of [
|
||||
"package-lock.json",
|
||||
"next.config.mjs",
|
||||
"Dockerfile",
|
||||
"Dockerfile.bun",
|
||||
"pnpm.json",
|
||||
"pnpm-workspace.yaml",
|
||||
"config/quality/dependency-allowlist.json",
|
||||
"config/quality/.license-allowlist.json",
|
||||
"scripts/build/postinstall.mjs",
|
||||
"scripts/build/pack-artifact-policy.ts",
|
||||
]) {
|
||||
const source = readFileSync(join(ROOT, relativePath), "utf8");
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/tls-client-node/i,
|
||||
`${relativePath} still references tls-client-node`
|
||||
);
|
||||
assert.doesNotMatch(source, /\bkoffi\b/i, `${relativePath} still references orphaned koffi`);
|
||||
}
|
||||
|
||||
assert.equal(existsSync(join(ROOT, "open-sse/services/tlsClientDownloadDir.ts")), false);
|
||||
assert.equal(existsSync(join(ROOT, "scripts/build/fixTlsClientNodeBinary.mjs")), false);
|
||||
|
||||
for (const relativePath of [
|
||||
".env.example",
|
||||
"docs/reference/ENVIRONMENT.md",
|
||||
"docs/security/STEALTH_GUIDE.md",
|
||||
]) {
|
||||
const source = readFileSync(join(ROOT, relativePath), "utf8");
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/OMNIROUTE_TLS_PROXY_URL/,
|
||||
`${relativePath} still documents the removed sidecar override`
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// #5591 regression guard: every chrome_* TLS impersonation profile referenced in
|
||||
// #5591 regression guard: every TLS impersonation profile referenced in
|
||||
// the source must be a real wreq-js BrowserProfile. PR #5237 set them to
|
||||
// "chrome_149", which does not exist in wreq-js 2.3.1 (the union tops out at
|
||||
// chrome_147) — the native layer then produced a degenerate fingerprint and the
|
||||
@@ -19,15 +19,24 @@ function supportedProfiles() {
|
||||
path.join(ROOT, "node_modules", "wreq-js", "dist", "wreq-js.d.ts"),
|
||||
"utf8"
|
||||
);
|
||||
return new Set([...dts.matchAll(/chrome_(\d+)/g)].map((m) => `chrome_${m[1]}`));
|
||||
const union = dts.match(/type BrowserProfile = ([^;]+);/)?.[1] ?? "";
|
||||
return new Set([...union.matchAll(/'([^']+)'/g)].map((match) => match[1]));
|
||||
}
|
||||
|
||||
// Source files that hand a `browser`/PROFILE value to wreq-js.
|
||||
const PROVIDER_PROFILES = {
|
||||
"open-sse/services/chatgptTlsClient.ts": ["firefox_148", "macos"],
|
||||
"open-sse/services/claudeTlsClient.ts": ["chrome_146", "linux"],
|
||||
"open-sse/services/perplexityTlsClient.ts": ["firefox_148", "macos"],
|
||||
"open-sse/services/grokTlsClient.ts": ["chrome_146", "linux"],
|
||||
"open-sse/services/notionTlsClient.ts": ["chrome_146", "windows"],
|
||||
"open-sse/services/lmarenaTlsClient.ts": ["chrome_146", "windows"],
|
||||
};
|
||||
|
||||
// Other source files that hand a browser profile directly to wreq-js.
|
||||
const SOURCES = [
|
||||
"src/app/api/internal/codex-responses-ws/route.ts",
|
||||
"scripts/dev/responses-ws-proxy.mjs",
|
||||
"open-sse/services/grokTlsClient.ts",
|
||||
"open-sse/services/claudeTlsClient.ts",
|
||||
...Object.keys(PROVIDER_PROFILES),
|
||||
];
|
||||
|
||||
// Strip comments before scanning — explanatory comments may name the bad
|
||||
@@ -36,16 +45,16 @@ function stripComments(line) {
|
||||
return line.replace(/\/\*.*?\*\//g, "").replace(/\/\/.*$/, "");
|
||||
}
|
||||
|
||||
test("#5591 all configured chrome_* TLS profiles exist in wreq-js", () => {
|
||||
test("#5591 all configured browser TLS profiles exist in pinned wreq-js", () => {
|
||||
const supported = supportedProfiles();
|
||||
assert.ok(supported.size > 0, "expected to parse chrome_* profiles from wreq-js d.ts");
|
||||
assert.ok(supported.size > 0, "expected to parse BrowserProfile from wreq-js d.ts");
|
||||
|
||||
for (const rel of SOURCES) {
|
||||
const lines = fs.readFileSync(path.join(ROOT, rel), "utf8").split("\n");
|
||||
lines.forEach((line, i) => {
|
||||
const code = stripComments(line);
|
||||
for (const m of code.matchAll(/chrome_(\d+)/g)) {
|
||||
const profile = `chrome_${m[1]}`;
|
||||
for (const m of code.matchAll(/\b(?:chrome|firefox|edge|opera|safari|okhttp)_[\w.]+/g)) {
|
||||
const profile = m[0];
|
||||
assert.ok(
|
||||
supported.has(profile),
|
||||
`${rel}:${i + 1} uses ${profile} which is NOT a wreq-js BrowserProfile ` +
|
||||
@@ -54,4 +63,16 @@ test("#5591 all configured chrome_* TLS profiles exist in wreq-js", () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const [rel, [profile, os]] of Object.entries(PROVIDER_PROFILES)) {
|
||||
const source = fs.readFileSync(path.join(ROOT, rel), "utf8");
|
||||
assert.ok(supported.has(profile), `${rel} expected unsupported ${profile}`);
|
||||
if (rel.endsWith("claudeTlsClient.ts")) {
|
||||
assert.match(source, /CLAUDE_TLS_BROWSER_MAJOR_VERSION = "146"/);
|
||||
assert.match(source, /tlsProfile: `chrome_\$\{CLAUDE_TLS_BROWSER_MAJOR_VERSION\}`/);
|
||||
} else {
|
||||
assert.match(source, new RegExp(`tlsProfile: ["']${profile}["']`));
|
||||
}
|
||||
assert.match(source, new RegExp(`emulationOs: ["']${os}["']`));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -19,9 +19,9 @@ const { default: AddApiKeyModal } =
|
||||
await import("../../../src/app/(dashboard)/dashboard/providers/[id]/components/modals/AddApiKeyModal");
|
||||
|
||||
const TLS_EACCES_ERROR =
|
||||
"TLS impersonation client failed to start: EACCES: permission denied, mkdir " +
|
||||
"'/usr/lib/node_modules/omniroute/dist/node_modules/tls-client-node/bin'. " +
|
||||
"Verify tls-client-node is installed and its native binary downloaded. " +
|
||||
"TLS impersonation client failed to start: EACCES: permission denied, open " +
|
||||
"'/usr/lib/node_modules/omniroute/dist/node_modules/wreq-js/rust'. " +
|
||||
"Verify wreq-js 3.0.0 and its platform addon are installed. " +
|
||||
"(claude-web requires this — without it, Cloudflare blocks every request)";
|
||||
|
||||
const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
|
||||
|
||||
@@ -1,372 +0,0 @@
|
||||
/**
|
||||
* tests/unit/ui/orchestrationModel.test.ts
|
||||
* Run: node --import tsx/esm --test tests/unit/ui/orchestrationModel.test.ts
|
||||
*/
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
ORCH_STATES,
|
||||
orchStateColor,
|
||||
} from "../../../src/app/(dashboard)/dashboard/orchestration/model/orchestrationTypes.ts";
|
||||
import { STATUS_HEX } from "../../../src/shared/constants/statusColors.ts";
|
||||
import { fromCloudAgent } from "../../../src/app/(dashboard)/dashboard/orchestration/model/fromCloudAgent.ts";
|
||||
import type { CloudAgentTask } from "../../../src/lib/cloudAgent/types.ts";
|
||||
import { fromA2A } from "../../../src/app/(dashboard)/dashboard/orchestration/model/fromA2A.ts";
|
||||
import type { A2ATask } from "../../../src/lib/a2a/taskManager.ts";
|
||||
import { fromConductor } from "../../../src/app/(dashboard)/dashboard/orchestration/model/fromConductor.ts";
|
||||
import type { FleetSnapshot } from "../../../src/lib/conductor/hubProxy.ts";
|
||||
import { mergeSnapshot } from "../../../src/app/(dashboard)/dashboard/orchestration/model/mergeSnapshot.ts";
|
||||
import {
|
||||
STALE_COMPLETED_MS,
|
||||
MAX_WORK_NODES,
|
||||
} from "../../../src/app/(dashboard)/dashboard/orchestration/model/orchestrationTypes.ts";
|
||||
|
||||
describe("orchestrationTypes", () => {
|
||||
it("covers all six states with a color each", () => {
|
||||
assert.equal(ORCH_STATES.length, 6);
|
||||
for (const s of ORCH_STATES) {
|
||||
assert.match(orchStateColor(s), /^#[0-9a-f]{6}$/i, s);
|
||||
}
|
||||
});
|
||||
it("waiting_approval maps to the new STATUS_HEX.approval violet", () => {
|
||||
assert.equal(orchStateColor("waiting_approval"), STATUS_HEX.approval);
|
||||
assert.equal(STATUS_HEX.approval, "#8b5cf6");
|
||||
});
|
||||
it("running maps to warning, succeeded to success, failed to error", () => {
|
||||
assert.equal(orchStateColor("running"), STATUS_HEX.warning);
|
||||
assert.equal(orchStateColor("succeeded"), STATUS_HEX.success);
|
||||
assert.equal(orchStateColor("failed"), STATUS_HEX.error);
|
||||
});
|
||||
});
|
||||
|
||||
function caTask(over: Partial<CloudAgentTask>): CloudAgentTask {
|
||||
return {
|
||||
id: "t1",
|
||||
providerId: "devin",
|
||||
status: "running",
|
||||
prompt: "Fix the flaky test in CI",
|
||||
source: { repoName: "acme/app", repoUrl: "https://github.com/acme/app" },
|
||||
options: {},
|
||||
activities: [],
|
||||
createdAt: "2026-08-30T10:00:00Z",
|
||||
updatedAt: "2026-08-30T10:05:00Z",
|
||||
...over,
|
||||
} as CloudAgentTask;
|
||||
}
|
||||
|
||||
describe("fromCloudAgent", () => {
|
||||
it("maps every status to the unified OrchState", () => {
|
||||
const cases: Array<[CloudAgentTask["status"], string]> = [
|
||||
["queued", "queued"],
|
||||
["running", "running"],
|
||||
["awaiting_approval", "waiting_approval"],
|
||||
["completed", "succeeded"],
|
||||
["failed", "failed"],
|
||||
["cancelled", "cancelled"],
|
||||
];
|
||||
for (const [input, expected] of cases) {
|
||||
const { nodes } = fromCloudAgent([caTask({ status: input })]);
|
||||
const work = nodes.find((n) => n.kind === "work");
|
||||
assert.equal(work?.state, expected, input);
|
||||
}
|
||||
});
|
||||
it("unknown status becomes failed with the raw value in sublabel", () => {
|
||||
const { nodes } = fromCloudAgent([caTask({ status: "exploded" as CloudAgentTask["status"] })]);
|
||||
const work = nodes.find((n) => n.kind === "work");
|
||||
assert.equal(work?.state, "failed");
|
||||
assert.match(work?.sublabel ?? "", /exploded/);
|
||||
});
|
||||
it("running task with activities gets one ActivityNode; completed does not", () => {
|
||||
const running = caTask({
|
||||
activities: [
|
||||
{ id: "a1", type: "command", content: "npm test", timestamp: "2026-08-30T10:04:00Z" },
|
||||
],
|
||||
});
|
||||
const done = caTask({ id: "t2", status: "completed", activities: running.activities });
|
||||
const { nodes, edges } = fromCloudAgent([running, done]);
|
||||
const acts = nodes.filter((n) => n.kind === "activity");
|
||||
assert.equal(acts.length, 1);
|
||||
assert.equal(acts[0].id, "cloud-agent:t1:activity");
|
||||
assert.ok(
|
||||
edges.some(
|
||||
(e) => e.from === "cloud-agent:t1" && e.to === "cloud-agent:t1:activity" && e.active
|
||||
)
|
||||
);
|
||||
});
|
||||
it("emits a SourceNode with per-state counts and owns-edges from it", () => {
|
||||
const { nodes, edges } = fromCloudAgent([caTask({}), caTask({ id: "t2", status: "failed" })]);
|
||||
const src = nodes.find((n) => n.id === "source:cloud-agent");
|
||||
assert.equal(src?.counts?.running, 1);
|
||||
assert.equal(src?.counts?.failed, 1);
|
||||
assert.ok(
|
||||
edges.some(
|
||||
(e) => e.from === "source:cloud-agent" && e.to === "cloud-agent:t1" && e.kind === "owns"
|
||||
)
|
||||
);
|
||||
});
|
||||
it("empty input emits nothing", () => {
|
||||
const out = fromCloudAgent([]);
|
||||
assert.equal(out.nodes.length, 0);
|
||||
assert.equal(out.edges.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
function a2aTask(over: Partial<A2ATask>): A2ATask {
|
||||
return {
|
||||
id: "a1",
|
||||
skill: "smart-routing",
|
||||
state: "working",
|
||||
input: { skill: "smart-routing", messages: [{ role: "user", content: "route this well" }] },
|
||||
artifacts: [],
|
||||
events: [{ timestamp: "2026-08-30T10:00:00Z", state: "submitted" }],
|
||||
metadata: {},
|
||||
createdAt: "2026-08-30T10:00:00Z",
|
||||
updatedAt: "2026-08-30T10:01:00Z",
|
||||
expiresAt: "2026-08-30T10:05:00Z",
|
||||
...over,
|
||||
} as A2ATask;
|
||||
}
|
||||
|
||||
describe("fromA2A", () => {
|
||||
it("maps the five A2A states", () => {
|
||||
const cases: Array<[A2ATask["state"], string]> = [
|
||||
["submitted", "queued"],
|
||||
["working", "running"],
|
||||
["completed", "succeeded"],
|
||||
["failed", "failed"],
|
||||
["cancelled", "cancelled"],
|
||||
];
|
||||
for (const [input, expected] of cases) {
|
||||
const { nodes } = fromA2A([a2aTask({ state: input })]);
|
||||
assert.equal(nodes.find((n) => n.kind === "work")?.state, expected, input);
|
||||
}
|
||||
});
|
||||
it("work node id is a2a:<id>, label is the skill", () => {
|
||||
const { nodes } = fromA2A([a2aTask({})]);
|
||||
const w = nodes.find((n) => n.kind === "work");
|
||||
assert.equal(w?.id, "a2a:a1");
|
||||
assert.equal(w?.label, "smart-routing");
|
||||
});
|
||||
it("empty input emits nothing", () => {
|
||||
assert.equal(fromA2A([]).nodes.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
const baseSnap: FleetSnapshot = {
|
||||
offline: false,
|
||||
runners: [{ id: "r1", name: "runner-one", clis: ["claude"], online: true, draining: false }],
|
||||
tasks: [
|
||||
{
|
||||
id: "ct1",
|
||||
status: "running",
|
||||
mode: "auto",
|
||||
repo: "acme/app",
|
||||
runner: "r1",
|
||||
summary: "Refactor auth",
|
||||
branch: null,
|
||||
error: null,
|
||||
updated_at: "2026-08-30T10:00:00Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("fromConductor", () => {
|
||||
it("online runner with a running task → running WorkNode + ActivityNode for the task", () => {
|
||||
const { nodes, edges } = fromConductor(baseSnap);
|
||||
const runner = nodes.find((n) => n.id === "conductor:runner:r1");
|
||||
assert.equal(runner?.state, "running");
|
||||
const act = nodes.find((n) => n.id === "conductor:task:ct1");
|
||||
assert.equal(act?.kind, "activity");
|
||||
assert.ok(edges.some((e) => e.from === "conductor:runner:r1" && e.to === "conductor:task:ct1"));
|
||||
});
|
||||
it("queued task without runner hangs directly under the source as a work node", () => {
|
||||
const snap: FleetSnapshot = {
|
||||
...baseSnap,
|
||||
runners: [],
|
||||
tasks: [{ ...baseSnap.tasks[0], id: "ct2", status: "queued", runner: null }],
|
||||
};
|
||||
const { nodes, edges } = fromConductor(snap);
|
||||
const w = nodes.find((n) => n.id === "conductor:task:ct2");
|
||||
assert.equal(w?.kind, "work");
|
||||
assert.equal(w?.state, "queued");
|
||||
assert.ok(edges.some((e) => e.from === "source:conductor" && e.to === "conductor:task:ct2"));
|
||||
});
|
||||
it("offline snapshot emits only nothing (hook marks the source offline separately)", () => {
|
||||
const out = fromConductor({ offline: true, runners: [], tasks: [] });
|
||||
assert.equal(out.nodes.length, 0);
|
||||
});
|
||||
it("unknown hub status maps to failed with the raw value in sublabel", () => {
|
||||
const snap: FleetSnapshot = {
|
||||
...baseSnap,
|
||||
runners: [],
|
||||
tasks: [{ ...baseSnap.tasks[0], id: "ct3", status: "vaporized", runner: null }],
|
||||
};
|
||||
const w = fromConductor(snap).nodes.find((n) => n.id === "conductor:task:ct3");
|
||||
assert.equal(w?.state, "failed");
|
||||
assert.match(w?.sublabel ?? "", /vaporized/);
|
||||
});
|
||||
it("running task whose runner is not present in snap.runners is emitted as a work node, not swallowed", () => {
|
||||
const snap: FleetSnapshot = {
|
||||
offline: false,
|
||||
runners: [],
|
||||
tasks: [
|
||||
{
|
||||
...baseSnap.tasks[0],
|
||||
id: "ct-orphan",
|
||||
status: "running",
|
||||
runner: "ghost-runner",
|
||||
},
|
||||
],
|
||||
};
|
||||
const { nodes, edges } = fromConductor(snap);
|
||||
const w = nodes.find((n) => n.id === "conductor:task:ct-orphan");
|
||||
assert.equal(w?.kind, "work");
|
||||
assert.equal(w?.state, "running");
|
||||
assert.ok(
|
||||
edges.some((e) => e.from === "source:conductor" && e.to === "conductor:task:ct-orphan")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const OK_SOURCES = [
|
||||
{ source: "cloud-agent" as const, ok: true },
|
||||
{ source: "a2a" as const, ok: true },
|
||||
{ source: "conductor" as const, ok: true },
|
||||
];
|
||||
const NOW = Date.parse("2026-08-30T12:00:00Z");
|
||||
const empty = { nodes: [], edges: [] };
|
||||
|
||||
describe("mergeSnapshot", () => {
|
||||
it("adds the orchestrator root and root→source edges", () => {
|
||||
const snap = mergeSnapshot(
|
||||
{ cloudAgent: fromCloudAgent([caTask({})]), a2a: empty, conductor: empty },
|
||||
OK_SOURCES,
|
||||
{ now: NOW }
|
||||
);
|
||||
assert.ok(snap.nodes.some((n) => n.id === "orchestrator"));
|
||||
assert.ok(snap.edges.some((e) => e.from === "orchestrator" && e.to === "source:cloud-agent"));
|
||||
});
|
||||
it("dedupes a Conductor-mirrored A2A task into one node with a mirror edge", () => {
|
||||
const a2a = fromA2A([
|
||||
a2aTask({ id: "am1", skill: "conductor", metadata: { conductor: { task_id: "ct1" } } }),
|
||||
]);
|
||||
const conductor = fromConductor(baseSnap); // contains conductor:task:ct1 as activity of r1
|
||||
const snap = mergeSnapshot({ cloudAgent: empty, a2a, conductor }, OK_SOURCES, { now: NOW });
|
||||
assert.ok(
|
||||
!snap.nodes.some((n) => n.id === "a2a:am1"),
|
||||
"mirrored A2A work node must be dropped"
|
||||
);
|
||||
const mirrorEdge = snap.edges.find((e) => e.kind === "mirror");
|
||||
assert.equal(mirrorEdge?.to, "source:a2a");
|
||||
});
|
||||
it("drops terminal work older than STALE_COMPLETED_MS unless showCompleted", () => {
|
||||
const old = caTask({
|
||||
id: "old",
|
||||
status: "completed",
|
||||
completedAt: new Date(NOW - STALE_COMPLETED_MS - 1000).toISOString(),
|
||||
});
|
||||
const parts = { cloudAgent: fromCloudAgent([old]), a2a: empty, conductor: empty };
|
||||
assert.ok(
|
||||
!mergeSnapshot(parts, OK_SOURCES, { now: NOW }).nodes.some((n) => n.id === "cloud-agent:old")
|
||||
);
|
||||
assert.ok(
|
||||
mergeSnapshot(parts, OK_SOURCES, { now: NOW, showCompleted: true }).nodes.some(
|
||||
(n) => n.id === "cloud-agent:old"
|
||||
)
|
||||
);
|
||||
});
|
||||
it("caps work nodes at MAX_WORK_NODES with a per-source overflow node", () => {
|
||||
const many = Array.from({ length: MAX_WORK_NODES + 10 }, (_, i) =>
|
||||
caTask({ id: `m${i}`, updatedAt: new Date(NOW - i * 1000).toISOString() })
|
||||
);
|
||||
const snap = mergeSnapshot(
|
||||
{ cloudAgent: fromCloudAgent(many), a2a: empty, conductor: empty },
|
||||
OK_SOURCES,
|
||||
{ now: NOW }
|
||||
);
|
||||
const works = snap.nodes.filter((n) => n.kind === "work");
|
||||
assert.ok(works.length <= MAX_WORK_NODES, `got ${works.length}`);
|
||||
const overflow = snap.nodes.find((n) => n.id === "overflow:cloud-agent");
|
||||
assert.ok(overflow, "overflow node expected");
|
||||
});
|
||||
it("keeps SourceStatus[] verbatim on the snapshot", () => {
|
||||
const src = [{ source: "conductor" as const, ok: false, offline: true }];
|
||||
const snap = mergeSnapshot({ cloudAgent: empty, a2a: empty, conductor: empty }, src, {
|
||||
now: NOW,
|
||||
});
|
||||
assert.deepEqual(snap.sources, src);
|
||||
});
|
||||
it("does not mutate input node objects when deduping (honors the Pure contract)", () => {
|
||||
const a2a = fromA2A([
|
||||
a2aTask({ id: "am2", skill: "conductor", metadata: { conductor: { task_id: "ct1" } } }),
|
||||
]);
|
||||
const conductor = fromConductor(baseSnap); // contains conductor:task:ct1 as activity of r1
|
||||
const originalNode = conductor.nodes.find((n) => n.id === "conductor:task:ct1");
|
||||
assert.ok(originalNode, "conductor:task:ct1 must exist in the source part");
|
||||
const snap = mergeSnapshot({ cloudAgent: empty, a2a, conductor }, OK_SOURCES, { now: NOW });
|
||||
assert.equal(
|
||||
"mirrorOf" in (originalNode as object),
|
||||
false,
|
||||
"the original conductor input node must not be mutated"
|
||||
);
|
||||
const mergedNode = snap.nodes.find((n) => n.id === "conductor:task:ct1");
|
||||
assert.equal(mergedNode?.mirrorOf, "a2a:am2");
|
||||
});
|
||||
it("materializes an offline placeholder source node for a source reporting offline:true even when ok:true", () => {
|
||||
const src = [{ source: "conductor" as const, ok: true, offline: true }];
|
||||
const snap = mergeSnapshot({ cloudAgent: empty, a2a: empty, conductor: empty }, src, {
|
||||
now: NOW,
|
||||
});
|
||||
const node = snap.nodes.find((n) => n.id === "source:conductor");
|
||||
assert.ok(node, "offline placeholder source:conductor node expected");
|
||||
assert.equal(node?.sublabel, "offline");
|
||||
assert.ok(
|
||||
snap.edges.some(
|
||||
(e) => e.from === "orchestrator" && e.to === "source:conductor" && e.kind === "owns"
|
||||
)
|
||||
);
|
||||
});
|
||||
it("overflow node carries droppedByState with the per-state counts of dropped work nodes", () => {
|
||||
const many = Array.from({ length: MAX_WORK_NODES + 5 }, (_, i) =>
|
||||
caTask({
|
||||
id: `ov${i}`,
|
||||
status: i < MAX_WORK_NODES ? "running" : "failed",
|
||||
updatedAt: new Date(NOW - i * 1000).toISOString(),
|
||||
})
|
||||
);
|
||||
const snap = mergeSnapshot(
|
||||
{ cloudAgent: fromCloudAgent(many), a2a: empty, conductor: empty },
|
||||
OK_SOURCES,
|
||||
{ now: NOW }
|
||||
);
|
||||
const overflow = snap.nodes.find((n) => n.id === "overflow:cloud-agent");
|
||||
assert.ok(overflow, "overflow node expected");
|
||||
assert.deepEqual(overflow?.droppedByState, { failed: 5 });
|
||||
});
|
||||
it("drops a stale terminal Conductor task older than STALE_COMPLETED_MS unless showCompleted", () => {
|
||||
const staleSnap: FleetSnapshot = {
|
||||
...baseSnap,
|
||||
runners: [],
|
||||
tasks: [
|
||||
{
|
||||
...baseSnap.tasks[0],
|
||||
id: "ctOld",
|
||||
status: "completed",
|
||||
runner: null,
|
||||
updated_at: new Date(NOW - STALE_COMPLETED_MS - 1000).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
const parts = { cloudAgent: empty, a2a: empty, conductor: fromConductor(staleSnap) };
|
||||
assert.ok(
|
||||
!mergeSnapshot(parts, OK_SOURCES, { now: NOW }).nodes.some(
|
||||
(n) => n.id === "conductor:task:ctOld"
|
||||
)
|
||||
);
|
||||
assert.ok(
|
||||
mergeSnapshot(parts, OK_SOURCES, { now: NOW, showCompleted: true }).nodes.some(
|
||||
(n) => n.id === "conductor:task:ctOld"
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
/** Run: node --import tsx/esm --test tests/unit/ui/orchestrationToFlow.test.ts */
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { orchestrationToFlow } from "../../../src/app/(dashboard)/dashboard/orchestration/model/orchestrationToFlow.ts";
|
||||
import type { OrchSnapshot } from "../../../src/app/(dashboard)/dashboard/orchestration/model/orchestrationTypes.ts";
|
||||
|
||||
const snap: OrchSnapshot = {
|
||||
nodes: [
|
||||
{ id: "orchestrator", kind: "orchestrator", label: "OmniRoute" },
|
||||
{ id: "source:a2a", kind: "source", source: "a2a", label: "A2A" },
|
||||
{ id: "a2a:t1", kind: "work", source: "a2a", state: "running", label: "smart-routing" },
|
||||
{ id: "a2a:t2", kind: "work", source: "a2a", state: "failed", label: "cost-analysis" },
|
||||
],
|
||||
edges: [
|
||||
{ id: "e1", from: "orchestrator", to: "source:a2a", kind: "owns", active: false },
|
||||
{ id: "e2", from: "source:a2a", to: "a2a:t1", kind: "owns", active: true },
|
||||
{ id: "e3", from: "source:a2a", to: "a2a:t2", kind: "owns", active: false },
|
||||
],
|
||||
sources: [],
|
||||
generatedAt: "2026-08-30T12:00:00Z",
|
||||
};
|
||||
|
||||
describe("orchestrationToFlow", () => {
|
||||
it("puts each kind on its own Y layer and is deterministic", () => {
|
||||
const a = orchestrationToFlow(snap);
|
||||
const b = orchestrationToFlow(snap);
|
||||
assert.deepEqual(
|
||||
a.nodes.map((n) => n.position),
|
||||
b.nodes.map((n) => n.position)
|
||||
);
|
||||
const ys = new Map(a.nodes.map((n) => [n.id, n.position.y]));
|
||||
assert.equal(ys.get("orchestrator"), 0);
|
||||
assert.equal(ys.get("source:a2a"), 150);
|
||||
assert.equal(ys.get("a2a:t1"), 320);
|
||||
});
|
||||
it("active edge is animated; edge to failed work is red", () => {
|
||||
const { edges } = orchestrationToFlow(snap);
|
||||
assert.equal(edges.find((e) => e.id === "e2")?.animated, true);
|
||||
const failedEdge = edges.find((e) => e.id === "e3");
|
||||
assert.equal((failedEdge?.style as { stroke?: string })?.stroke, "#ef4444");
|
||||
});
|
||||
it("fitKey only tracks the set of work ids", () => {
|
||||
const k1 = orchestrationToFlow(snap).fitKey;
|
||||
const stateChanged = {
|
||||
...snap,
|
||||
nodes: snap.nodes.map((n) => (n.id === "a2a:t1" ? { ...n, state: "succeeded" as const } : n)),
|
||||
};
|
||||
assert.equal(orchestrationToFlow(stateChanged).fitKey, k1);
|
||||
const nodeRemoved = {
|
||||
...snap,
|
||||
nodes: snap.nodes.filter((n) => n.id !== "a2a:t2"),
|
||||
edges: snap.edges.filter((e) => e.to !== "a2a:t2"),
|
||||
};
|
||||
assert.notEqual(orchestrationToFlow(nodeRemoved).fitKey, k1);
|
||||
});
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
/** Run: node --import tsx/esm --test tests/unit/ui/overviewProjection.test.ts */
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { overviewProjection } from "../../../src/app/(dashboard)/dashboard/orchestration/model/overviewProjection.ts";
|
||||
import type { OrchSnapshot } from "../../../src/app/(dashboard)/dashboard/orchestration/model/orchestrationTypes.ts";
|
||||
|
||||
const snap: OrchSnapshot = {
|
||||
nodes: [
|
||||
{ id: "orchestrator", kind: "orchestrator", label: "OmniRoute" },
|
||||
{ id: "cloud-agent:1", kind: "work", source: "cloud-agent", state: "running", label: "a" },
|
||||
{
|
||||
id: "cloud-agent:2",
|
||||
kind: "work",
|
||||
source: "cloud-agent",
|
||||
state: "waiting_approval",
|
||||
label: "b",
|
||||
},
|
||||
{
|
||||
id: "a2a:3",
|
||||
kind: "work",
|
||||
source: "a2a",
|
||||
state: "failed",
|
||||
label: "c",
|
||||
updatedAt: "2026-08-30T11:00:00Z",
|
||||
},
|
||||
{ id: "a2a:3:activity", kind: "activity", source: "a2a", state: "running", label: "noise" },
|
||||
],
|
||||
edges: [],
|
||||
sources: [],
|
||||
generatedAt: "2026-08-30T12:00:00Z",
|
||||
};
|
||||
|
||||
describe("overviewProjection", () => {
|
||||
it("counts only work nodes and adds comboActive to running", () => {
|
||||
const { counts } = overviewProjection(snap, 4);
|
||||
assert.equal(counts.running, 1 + 4);
|
||||
assert.equal(counts.waiting_approval, 1);
|
||||
assert.equal(counts.failed, 1);
|
||||
assert.equal(counts.queued, 0);
|
||||
});
|
||||
it("folds terminals into the done column", () => {
|
||||
const { columns } = overviewProjection(snap, 0);
|
||||
assert.equal(columns.done.length, 1);
|
||||
assert.equal(columns.done[0].id, "a2a:3");
|
||||
assert.equal(columns.running.length, 1);
|
||||
});
|
||||
it("folds an overflow node's droppedByState into counts but not into columns", () => {
|
||||
const snapWithOverflow: OrchSnapshot = {
|
||||
...snap,
|
||||
nodes: [
|
||||
...snap.nodes,
|
||||
{
|
||||
id: "overflow:cloud-agent",
|
||||
kind: "overflow",
|
||||
source: "cloud-agent",
|
||||
label: "+7 more",
|
||||
droppedByState: { running: 5, failed: 2 },
|
||||
},
|
||||
],
|
||||
};
|
||||
const { counts, columns } = overviewProjection(snapWithOverflow, 0);
|
||||
assert.equal(counts.running, 1 + 5);
|
||||
assert.equal(counts.failed, 1 + 2);
|
||||
assert.equal(columns.running.length, 1);
|
||||
assert.equal(columns.done.length, 1);
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import React, { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
// Capture the onEvent handler the hook registers on the requests channel.
|
||||
let capturedOnEvent: ((p: { channel: string }) => void) | null = null;
|
||||
vi.mock("@/hooks/useLiveDashboard", () => ({
|
||||
useLiveDashboard: (opts: { onEvent?: (p: { channel: string }) => void }) => {
|
||||
capturedOnEvent = opts.onEvent ?? null;
|
||||
return { connection: { isConnected: true }, events: [] };
|
||||
},
|
||||
}));
|
||||
|
||||
import { useOrchestrationSnapshot } from "@/app/(dashboard)/dashboard/orchestration/hooks/useOrchestrationSnapshot";
|
||||
|
||||
function HookProbe({
|
||||
onRender,
|
||||
}: {
|
||||
onRender: (v: ReturnType<typeof useOrchestrationSnapshot>) => void;
|
||||
}) {
|
||||
onRender(useOrchestrationSnapshot());
|
||||
return null;
|
||||
}
|
||||
|
||||
const okJson = (body: unknown) =>
|
||||
Promise.resolve({ ok: true, json: () => Promise.resolve(body) } as Response);
|
||||
|
||||
describe("useOrchestrationSnapshot", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("polls the three endpoints and builds a snapshot; a failed source keeps the last good data", async () => {
|
||||
let latest: ReturnType<typeof useOrchestrationSnapshot> | null = null;
|
||||
const task = {
|
||||
id: "t1",
|
||||
providerId: "devin",
|
||||
status: "running",
|
||||
prompt: "p",
|
||||
source: { repoName: "r", repoUrl: "https://x" },
|
||||
options: {},
|
||||
activities: [],
|
||||
createdAt: "2026-08-30T10:00:00Z",
|
||||
updatedAt: "2026-08-30T10:00:00Z",
|
||||
};
|
||||
const fetchMock = vi.fn((url: string) => {
|
||||
if (url.startsWith("/api/v1/agents/tasks")) return okJson({ data: [task] });
|
||||
if (url.startsWith("/api/a2a/tasks"))
|
||||
return okJson({ tasks: [], total: 0, limit: 200, offset: 0 });
|
||||
return okJson({ offline: false, runners: [], tasks: [] });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<HookProbe
|
||||
onRender={(v) => {
|
||||
latest = v;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
});
|
||||
expect(latest!.snapshot.nodes.some((n) => n.id === "cloud-agent:t1")).toBe(true);
|
||||
|
||||
// Second tick: cloud agent fails — node must survive from the last good photo, source marked stale.
|
||||
fetchMock.mockImplementation((url: string) => {
|
||||
if (url.startsWith("/api/v1/agents/tasks")) return Promise.reject(new Error("boom"));
|
||||
if (url.startsWith("/api/a2a/tasks"))
|
||||
return okJson({ tasks: [], total: 0, limit: 200, offset: 0 });
|
||||
return okJson({ offline: false, runners: [], tasks: [] });
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(5_100);
|
||||
});
|
||||
expect(latest!.snapshot.nodes.some((n) => n.id === "cloud-agent:t1")).toBe(true);
|
||||
const st = latest!.snapshot.sources.find((s) => s.source === "cloud-agent");
|
||||
expect(st?.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("a requests-channel WS event triggers a debounced immediate refetch", async () => {
|
||||
const fetchMock = vi.fn((url: string) => {
|
||||
if (url.startsWith("/api/v1/agents/tasks")) return okJson({ data: [] });
|
||||
if (url.startsWith("/api/a2a/tasks"))
|
||||
return okJson({ tasks: [], total: 0, limit: 200, offset: 0 });
|
||||
return okJson({ offline: false, runners: [], tasks: [] });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await act(async () => {
|
||||
root.render(<HookProbe onRender={() => {}} />);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
});
|
||||
const callsAfterMount = fetchMock.mock.calls.length;
|
||||
|
||||
act(() => {
|
||||
capturedOnEvent?.({ channel: "requests" });
|
||||
capturedOnEvent?.({ channel: "requests" });
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(1_100);
|
||||
});
|
||||
// Two burst events → exactly ONE extra round of 3 fetches (debounce), not two.
|
||||
expect(fetchMock.mock.calls.length).toBe(callsAfterMount + 3);
|
||||
});
|
||||
});
|
||||
64
tests/unit/wreq-native-manifest.test.ts
Normal file
64
tests/unit/wreq-native-manifest.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const MANIFEST_PATH = join(ROOT, "config/release/wreq-js-native-manifest.json");
|
||||
|
||||
interface NativeEntry {
|
||||
path: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
interface NativeManifest {
|
||||
package: string;
|
||||
version: string;
|
||||
npmIntegrity: string;
|
||||
license: string;
|
||||
nativeAddons: NativeEntry[];
|
||||
}
|
||||
|
||||
test("wreq-js 3.0.0 has an exact seven-platform native hash manifest and notice", () => {
|
||||
assert.equal(existsSync(MANIFEST_PATH), true, "native manifest must be committed");
|
||||
const manifest = JSON.parse(readFileSync(MANIFEST_PATH, "utf8")) as NativeManifest;
|
||||
assert.equal(manifest.package, "wreq-js");
|
||||
assert.equal(manifest.version, "3.0.0");
|
||||
assert.equal(
|
||||
manifest.npmIntegrity,
|
||||
"sha512-RZCoRSevVPpH4A4B4MxbFGo/pVPFveWd2gbe4ENKpPWlKXEYklZSDESOjBMmrIsmnkHh+nhM4PNJvG+NL7wBPA=="
|
||||
);
|
||||
assert.equal(manifest.license, "MIT");
|
||||
assert.equal(manifest.nativeAddons.length, 7);
|
||||
assert.deepEqual(manifest.nativeAddons.map((entry) => entry.path).sort(), [
|
||||
"rust/wreq-js.darwin-arm64.node",
|
||||
"rust/wreq-js.darwin-x64.node",
|
||||
"rust/wreq-js.linux-arm64-gnu.node",
|
||||
"rust/wreq-js.linux-arm64-musl.node",
|
||||
"rust/wreq-js.linux-x64-gnu.node",
|
||||
"rust/wreq-js.linux-x64-musl.node",
|
||||
"rust/wreq-js.win32-x64-msvc.node",
|
||||
]);
|
||||
|
||||
const packageRoot = join(ROOT, "node_modules/wreq-js");
|
||||
const installedPackage = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")) as {
|
||||
version: string;
|
||||
};
|
||||
assert.equal(installedPackage.version, manifest.version);
|
||||
for (const entry of manifest.nativeAddons) {
|
||||
const bytes = readFileSync(join(packageRoot, entry.path));
|
||||
assert.equal(bytes.byteLength, entry.size, `${entry.path}: byte size`);
|
||||
assert.equal(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
entry.sha256,
|
||||
`${entry.path}: sha256`
|
||||
);
|
||||
}
|
||||
|
||||
const notices = readFileSync(join(ROOT, "THIRD_PARTY_NOTICES.md"), "utf8");
|
||||
assert.match(notices, /^## wreq-js 3\.0\.0$/m);
|
||||
assert.match(notices, /Copyright \(c\) 2025 will-work-for-meal/);
|
||||
assert.match(notices, /Copyright \(c\) 2025 Oleksandr Herasymov/);
|
||||
});
|
||||
49
tests/unit/wreq-postinstall-native.test.ts
Normal file
49
tests/unit/wreq-postinstall-native.test.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
WREQ_JS_NATIVE_BINARY_NAMES,
|
||||
resolveWreqJsNativeBinaryName,
|
||||
} from "../../scripts/build/wreqJsNative.mjs";
|
||||
|
||||
test("wreq-js 3.0.0 resolver covers every shipped native addon name", () => {
|
||||
assert.deepEqual([...WREQ_JS_NATIVE_BINARY_NAMES].sort(), [
|
||||
"wreq-js.darwin-arm64.node",
|
||||
"wreq-js.darwin-x64.node",
|
||||
"wreq-js.linux-arm64-gnu.node",
|
||||
"wreq-js.linux-arm64-musl.node",
|
||||
"wreq-js.linux-x64-gnu.node",
|
||||
"wreq-js.linux-x64-musl.node",
|
||||
"wreq-js.win32-x64-msvc.node",
|
||||
]);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "darwin", arch: "arm64" }),
|
||||
"wreq-js.darwin-arm64.node"
|
||||
);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "darwin", arch: "x64" }),
|
||||
"wreq-js.darwin-x64.node"
|
||||
);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "linux", arch: "arm64", libc: "gnu" }),
|
||||
"wreq-js.linux-arm64-gnu.node"
|
||||
);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "linux", arch: "arm64", libc: "musl" }),
|
||||
"wreq-js.linux-arm64-musl.node"
|
||||
);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "linux", arch: "x64", libc: "gnu" }),
|
||||
"wreq-js.linux-x64-gnu.node"
|
||||
);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "linux", arch: "x64", libc: "musl" }),
|
||||
"wreq-js.linux-x64-musl.node"
|
||||
);
|
||||
assert.equal(
|
||||
resolveWreqJsNativeBinaryName({ platform: "win32", arch: "x64" }),
|
||||
"wreq-js.win32-x64-msvc.node"
|
||||
);
|
||||
assert.equal(resolveWreqJsNativeBinaryName({ platform: "win32", arch: "arm64" }), null);
|
||||
assert.equal(resolveWreqJsNativeBinaryName({ platform: "android", arch: "arm64" }), null);
|
||||
});
|
||||
Reference in New Issue
Block a user