omp packages

pi-provider-xhx1.0.1

Pi extension for 小浣熊 (SenseTime Raccoon) — OAuth login, live model catalog, OpenAI-compatible responses

flying_dragon Published 2 days ago MIT ~3.3K downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

pi-provider-xhx

小浣熊 (SenseTime Raccoon) as a first-class pi provider

OAuth login · live model catalog · token-by-token streaming

npm pi TypeScript Tests


A pi extension that connects pi to 小浣熊 — the xiaohuanxiong.com web/desktop gateway — as a first-class provider.

No local proxy process. The extension speaks the gateway's OpenAI-compatible Chat Completions surface directly, holds the OAuth credentials, refreshes them through pi's auth layer, and converts each non-streaming response into pi's assistant event stream.

Highlights

🔐 One-shot OAuth Browser loopback login — sign in once, nothing to copy
📡 Live catalog Models fetched from the gateway on every session start, with a built-in fallback list
🧠 Thinking levels pi's thinking levels mapped onto the gateway's raccoon_thinking levels
🖼️ Multimodal Text + image input via OpenAI content arrays
💰 Zero USD cost The gateway bills in points, not per-token USD
🛡️ Validated responses Business errors, malformed payloads, and filtered responses become explicit errors

Quick start

pi install npm:pi-provider-xhx
pi --provider xhx --model sn-glm-5-3-flash

Inside pi:

/login xhx
/model sn-glm-5-3-flash

Contents


Login

/login xhx runs a browser OAuth loopback flow. The extension binds a throwaway HTTP server on 127.0.0.1, opens the official authorize page, and the page redirects the browser straight back to that local server once you sign in:

https://xiaohuanxiong.com/code/authorize
  ?login_source=desktop
  &desktop_callback=loopback
  &appname=办公小浣熊客户端
  &state=<64 hex>
  &redirect=http://127.0.0.1:<port>/auth/callback

Sign in with WeChat, SMS, or password. The browser lands on a 「登录成功」 page, the extension verifies state, exchanges the one-time code at auth/v1/login_with_authorization_code, and stores the credentials in ~/.pi/agent/auth.json. Nothing to copy.

The authorize page validates the loopback pair strictly — the redirect must be http://127.0.0.1:<port>/auth/callback with a port in 1024..65535, and state must be exactly 64 lowercase hex characters. Anything else falls back to the office-raccoon://auth/callback scheme, which a browser cannot open.

💡 If the browser cannot reach the loopback (remote shell, firewall), the login waits XHX_LOGIN_TIMEOUT_MS (default 5 minutes) and then asks for the callback URL instead. Pasting only the code also works; the state check is skipped in that case.

Token lifetime

The access token is a JWT. The extension reads exp, schedules an early refresh, and never extends a short-lived credential beyond its actual JWT expiry. The refresh token is rotated when the upstream rotates it and kept when it does not.

⚠️ Do not run a second client (the Go proxy, the desktop app) against the same account: two processes refreshing one refresh token invalidate each other.


Models

The catalog is live: GET llm/v2/model_catalog on every session start, filtered to visible entries. Model ids are the upstream ids — the gateway does no aliasing.

A seven-model fallback list (the current live catalog) is registered at load time and restored whenever a catalog fetch fails, so the model list never goes empty mid-session.

Context window context_window from the catalog, else 128K
Max output max_tokens from the catalog (100K for most models), never a global cap

Output budget

The budget is the catalog's max_tokens (100K for most models). XHX_MAX_TOKENS overrides it in every mode, and when the platform rejects a value it names the accepted range in the 400 body (Range of max_tokens should be [1, N] / max_tokens参数非法:限制数值范围[1,N]); that range is parsed and the request is retried once inside it, so the real ceiling is discovered instead of guessed.

Thinking tokens are billed against max_tokens, so a budget that is too small comes back as finish_reason=length with an empty body, and a global ceiling silently truncates long answers. The budget therefore comes from the catalog (max_tokens, 100K for most models), with a 2048 floor for explicitly small requests. If a response still ends with length and an empty body while thinking is non-empty, the non-streaming path retries once at 8192 and then reports an actionable error instead of an empty message.

Measured on the live gateway over a fixed five-prompt set (short, long, reasoning, tool call, and a deliberately tiny 256-token budget): the old global 16384 cap answered 4/5, the catalog budget with the floor answered 5/5, and output tokens stayed within noise (2.5K-3.7K across repeats). Twelve requests at a 100K budget produced no risk-control block, so the old cap was not buying anything. | Input | text and images (OpenAI multimodal content arrays) | | Cost | zero — the gateway bills in points, not USD per token | | Thinking | raccoon_thinking, mapped from pi's thinking level (see below) |

Thinking levels

The catalog describes each model's thinking control under params.raccoon_thinking: the levels it accepts (level_1 … level_5, sometimes a subset) and whether off is allowed. The extension maps pi's thinking levels onto those values and sends the result as the raccoon_thinking request field:

pi level three-level model five-level model
off level_1 (or off when the model allows it) level_1 (or off)
minimal level_1 level_1
low level_1 level_2
medium level_3 level_3
high / xhigh / max level_5 level_5

Pick a level with /thinking, --thinking <level>, or the model's thinking selector. The gateway always reasons for models that cannot disable it, so off means "the lowest level" there. Reasoning arrives as message.reasoning_content and is rendered as thinking blocks.


Commands

Command What it does
/xhx provider, origin, chat/catalog endpoints, auth source, token tail, model count, points balance
/xhx-balance points/v1/balance
/xhx-checkin triggers the daily grant, then reports the outcome from the points/v1/bills ledger
/xhx-bind binds this machine as a trusted device (auth/v1/devices_current_bind)
/xhx-models lists the registered models

Environment

Variable Meaning
XHX_ACCESS_TOKEN use a token directly instead of /login; also the fallback when no credential is stored
XHX_ORIGIN point the extension at a mirror or a local mock (default https://xiaohuanxiong.com)
XHX_LOGIN_TIMEOUT_MS how long the loopback login waits for the browser before offering a paste (default 300000)
XHX_MAX_TOKENS explicit output budget; wins over the catalog value in every mode. If the platform refuses it, the accepted range is read from the 400 body and the request is retried once inside it
XHX_MIN_INTERVAL_MS minimum spacing between requests (default 400; 0 disables)
XHX_ORG_CODE value for the X-Org-Code header the official client sends (default empty)

Official-client identity

Every request carries the identity headers the official desktop client sends:

x-client-name:     @raccoon/office-desktop
x-client-platform: desktop-windows-x64
x-client-version:  v1.1.0
x-client-channel:  official

The gateway's risk control separates official traffic from everything else by these headers; a browser user agent alone is not enough. /xhx-bind additionally registers this machine as a trusted device through auth/v1/devices_current_bind, which is what the daily points grant is

The client_device_id is the session's device identity: it is generated once per account, stored in ~/.pi/agent/xhx-device.json, and reused for both the bind and the heartbeat. Changing it mid-session makes the gateway answer device_session_mismatch and mark the device suspicious; the heartbeat detects device_bind_required and re-binds with the stored id to recover. A heartbeat runs on every session start so the device stays marked online. tied to — an unbound account never receives it. The client device id is generated once per account and reused, because claiming a new device on every call is exactly the pattern the risk control watches for. State lives in ~/.pi/agent/xhx-device.json. | XHX_TIMEOUT_MS | how long one chat request may take before it is aborted with a clear message (default 600000) |

XHX_ACCESS_TOKEN is enough to start using the provider without the login flow:

XHX_ACCESS_TOKEN=eyJhbGci… pi --provider xhx --model sn-glm-5-3-flash

Grab it from the browser: log in at xiaohuanxiong.com, open DevTools → Network, copy the Authorization: Bearer eyJ… value from any request. The desktop client keeps the same pair in ~/.box-agent/config/auth.json.


Endpoints

Purpose Request
Authorize page GET {origin}/code/authorize?login_source=desktop&appname=…&state=…
Code exchange POST {origin}/api/web/auth/v1/login_with_authorization_code
Token refresh POST {origin}/api/web/auth/v1/refresh
Model catalog GET {origin}/api/web/llm/v2/model_catalog
Chat (streaming) POST {origin}/api/web/llm/v2/chat/completions with stream: true
Chat (fallback) POST {origin}/api/web/llm/v1/chat/completions (non-streaming)
Balance GET {origin}/api/web/points/v1/balance
Entitlement GET {origin}/api/web/auth/v1/entitlement_info
Daily grant GET {origin}/api/web/office/v3/setting_info

Why v2 streaming with a v1 fallback

/llm/v2/chat/completions with stream: true answers real SSE frames, so text, thinking and tool calls reach pi as they are generated. Measured against the live gateway with a real account: first token at 3.5 s, full answer at 5.0 s, 22 incremental chunks.

v2 also sits behind a risk control that can answer 429 with code 200108 and block model calls for the account. /llm/v1/chat/completions serves the same OpenAI shape without that gate, but its own streaming path is broken upstream — it answers invalid upstream stream response inside an SSE frame. So v1 is used non-streaming as the safety net: if the streaming attempt is refused before any content arrives, the same request is retried once against v1 and the full answer is synthesized into pi's event stream.

A refusal is remembered — 10 minutes for a protocol failure, 30 minutes for a risk-control block — so later turns skip the failing path instead of paying a failed round trip every time. A stream that dies after content has started surfaces as an error rather than silently restarting.

Wire compatibility

Model configs record the classic Chat Completions compatibility flags in src/compat.ts: no store, no developer role, no reasoning_effort, max_tokens instead of max_completion_tokens, and no stream_options. The active adapter emits that request shape directly.

The non-streaming response is validated before any content event is emitted. HTTP errors, business-error envelopes returned with HTTP 200, missing choices, malformed content/tool calls, and unknown or filtered finish_reason values become explicit pi error events. Tool argument errors are preserved for tool validation, and usage separates uncached input, cache reads/writes, output, and reasoning tokens.


Development

npm install
npm run typecheck
npm test          # 94 tests against a mock gateway
npm run build     # esbuild -> dist/index.js

test/mock-upstream.ts implements the gateway's endpoints with the documented response shapes: the {code,message,data} envelope, the categories[].models[] catalog, SSE and non-streaming completions carrying reasoning_content, tool calls and usage, the device bind/heartbeat endpoints, and the platform's max_tokens range rejection.

bench/budget-bench.mjs runs a fixed five-prompt set against the live gateway and reports answer completeness plus token cost; it is a development tool and is not part of the package.

To drive a real pi process against it:

node test/manual/serve-mock.ts 18080          # prints {origin, token}
XHX_ORIGIN=http://127.0.0.1:18080 XHX_ACCESS_TOKEN=<token> \
  pi -e . -p "hello" --provider xhx --model sn-glm-5-3-flash

Verification

What the current test suite and earlier end-to-end runs cover:

  • 82 tests against the mock gateway — OAuth (loopback, foreign-state recovery, cancellation, expired codes, paste fallback, short-lived JWTs), refresh rotation/rejection, catalog parsing and limits, model mapping, SSE streaming (incremental text and thinking deltas, tool calls split across chunks, keep-alive and unparseable frames, first-token latency, mid-stream death), the v1 non-streaming fallback and its remembered verdict, response validation (malformed arguments/responses, HTTP 200 business errors, content filtering, 401, abort, timeout, empty responses), concurrent throttling, request options, system/tool transcript folding, image input, account endpoints, and provider registration.
  • A real pi process against the mock gateway — text reply, tool-call round trip (pi executed read and sent the result back), thinking blocks, and the session-start catalog refresh.
  • The live gateway with a real account — /login xhx completed through the loopback redirect and stored an IAM JWT; a chat answered 1+1等于2。; a tool-call round trip read a file and returned its contents; /xhx-models listed the seven live catalog models with their upstream descriptions; points/v1/balance returned the account's points.
  • The live gateway, streaming, with a real account — llm/v2/chat/completions with stream: true answered SSE; through the built extension the first token arrived at 3.5 s and the full answer at 5.0 s across 22 deltas. llm/v1/chat/completions with stream: true answers {"status":{"code":9,"message":"invalid upstream stream response"}}, which is why v1 is only used non-streaming.
  • The live host without credentials — llm/v2/model_catalog answers 401, /code/authorize answers 307, auth/v1/refresh answers code=100002 for a malformed token, and a chat with a bogus token surfaces 401 authorization_verify_error.
  • The published tarball — pi -e npm:pi-provider-xhx --list-models registers the provider.

Limitations

  • The gateway's "upload a file" entry point (upload to the Raccoon side, then reference it) is not implemented; images go inline as data: URLs.
  • Image input is declared for every catalog model. Models that do not accept images answer with an upstream error rather than being hidden from the picker.
  • Thinking is requested through the catalog's raccoon_thinking levels; vendor-specific reasoning_effort, thinking, and enable_thinking fields are not sent.
  • Upstream model behaviour, quotas, and risk controls can change without notice.

Troubleshooting

401 authorization_verify_error

The access token is expired or was invalidated by another client refreshing the same account. Run /login xhx again.

A pasted callback URL says the state does not match

The callback URL came from an earlier login attempt. Start the login again and paste the URL from that attempt.

The model list is the seven-model fallback

The catalog fetch failed. /xhx shows the origin and auth source; a 401 there means the token is dead, a timeout means the network.

The gateway returns an empty response or a business error

Empty choices, malformed JSON, and non-zero business codes are surfaced as errors rather than a successful empty answer. The error text includes the upstream detail; /xhx can separately check whether the token and account endpoints still work.

fetch failed

The connection died before the response completed. The error text now carries the real cause after <- (UND_ERR_SOCKET, ECONNRESET, ETIMEDOUT, …).

The usual cause is a local proxy that closes idle connections: a non-streaming request sends nothing while the model thinks, so a long reasoning turn looks idle. xaiproxy-bridge used to cut such connections at 120 s; it now honours PI_PROXY_IDLE_TIMEOUT (default 600 s). Raise it, or lower the thinking level for that model.

429 with code 200108

The gateway has flagged the account for abnormal usage and blocked model calls. It does not clear on its own in a reasonable time. Open the 小浣熊 app, click the avatar in the bottom-left, choose 「问题反馈」 and ask them to lift the restriction, or sign in with another account.

The extension sends what the official client sends: the same header set (Authorization, Content-Type, X-Org-Code, X-Raccoon-Language), a browser user agent, verbose: true, a 16K output reservation instead of the catalog's 100K, and at least 400 ms between requests. What it cannot hide is the workload: a long agent session sends far more tokens than a human chatting in the web app, and pi's system prompt is not the office assistant's. A consumer account can still be flagged.


Credits

The protocol — endpoints, envelope shapes, catalog parsing rules, and the OAuth callback scheme — was reverse-engineered by haoxinyu1/xiaohuanxiong2api, a Go proxy for the same gateway. This extension is an independent TypeScript implementation of that surface that runs inside pi instead of in front of it.

Not affiliated with SenseTime. Use your own account.