llm-session-proxy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.en.md ADDED
@@ -0,0 +1,466 @@
1
+ # llm-session-proxy
2
+
3
+ [![npm version](https://img.shields.io/npm/v/llm-session-proxy.svg)](https://www.npmjs.com/package/llm-session-proxy)
4
+ [![Publish to npm](https://github.com/alaahong/llm-session-proxy/actions/workflows/publish.yml/badge.svg)](https://github.com/alaahong/llm-session-proxy/actions/workflows/publish.yml)
5
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-1f6feb)](https://www.ianzhang.cn/llm-session-proxy/en/)
6
+
7
+ *English · [中文文档](README.md) · [Documentation site](https://www.ianzhang.cn/llm-session-proxy/en/)*
8
+
9
+ **A configurable local reverse proxy for LLM APIs.** Zero dependencies, runnable with `npx`.
10
+
11
+ It sits between your client and the upstream API, fills in the session headers your client cannot
12
+ send, injects arbitrary custom parameters, rewrites model aliases and request paths, then forwards
13
+ the request — including streamed SSE responses — untouched.
14
+
15
+ It was originally built for [OpenCode Go](https://opencode.ai/docs/go/), but nothing in it is tied
16
+ to that provider: swap `upstream` and `inject.headers` and it fronts any OpenAI- or
17
+ Anthropic-compatible endpoint.
18
+
19
+ ---
20
+
21
+ ## The problem it solves
22
+
23
+ OpenCode Go / Zen API expects a session identifier on every request:
24
+
25
+ ```
26
+ x-opencode-session : stable per conversation (used for prompt caching and routing)
27
+ ```
28
+
29
+ When a client omits it, the upstream rejects the call outright:
30
+
31
+ ```
32
+ 400 Request is missing x-opencode-session and cannot be routed efficiently
33
+ ```
34
+
35
+ Most clients cannot set custom request headers at all. This tool moves that job onto your machine:
36
+ point the client's base URL at the local proxy and let the proxy handle the rest.
37
+
38
+ ### Which clients need this
39
+
40
+ If your client already sends a session header, you do not need this tool (though it will not hurt):
41
+
42
+ | Client | Status | Needs this proxy? |
43
+ | --- | --- | --- |
44
+ | OpenCode | Native support | No |
45
+ | Claude Code | Upstream recognizes its native session header | No |
46
+ | Codex | Recognizes the header, but some versions/proxies drop it | Only if it gets dropped |
47
+ | ZCode / Pi / jcode / Kilo Code CLI | Fixed in recent versions | Upgrade first, use this for older builds |
48
+ | Trae / self-built agents / GUI clients | Cannot customize headers | **Yes** |
49
+
50
+ ---
51
+
52
+ ## Features
53
+
54
+ - **Automatic session IDs** — three-tier strategy: explicit client identifier → content fingerprint
55
+ (`system` + first user message) → one-off random. Stable within a conversation, so prompt caching
56
+ actually works.
57
+ - **Arbitrary header and body injection** — values are templates (`{{session.id}}`, `{{uuid}}`,
58
+ `{{env.HOME}}`, …).
59
+ - **Model alias rewriting** — prefix stripping (`proxy-glm` → `glm-5.3`) plus exact mapping, and the
60
+ two compose.
61
+ - **Request path rewriting** — map the `/v1` your client insists on to whatever path the upstream
62
+ actually serves.
63
+ - **Body parameter injection and removal** — add `temperature` or `metadata` to every request, or
64
+ strip fields the upstream rejects.
65
+ - **Zero-buffer SSE pass-through** — chunks are forwarded as they arrive; streams stay streams.
66
+ Upstream 4xx bodies are returned verbatim.
67
+ - **Zero dependencies** — Node built-ins only, so `npx` starts instantly.
68
+ - **Local status endpoint** — inspect session count, cache hit rate, and injected headers at runtime.
69
+
70
+ ---
71
+
72
+ ## Install and run
73
+
74
+ ```bash
75
+ # Try it without installing
76
+ npx llm-session-proxy
77
+
78
+ # Or install globally
79
+ npm install -g llm-session-proxy
80
+ llm-session-proxy
81
+ ```
82
+
83
+ Requires Node.js >= 18.
84
+
85
+ ---
86
+
87
+ ## Quick start
88
+
89
+ ### 1. OpenCode Go from a client that cannot set headers
90
+
91
+ Subscribe to OpenCode Go and grab an API key at [opencode.ai/auth](https://opencode.ai/auth), then:
92
+
93
+ ```bash
94
+ npx llm-session-proxy
95
+ ```
96
+
97
+ Configure a custom model in your client:
98
+
99
+ | Field | Value |
100
+ | --- | --- |
101
+ | Base URL | `http://127.0.0.1:9355/zen/go/v1` |
102
+ | Model ID | `proxy-` + the real model name, e.g. `proxy-glm-5.3-flash` |
103
+ | API Key | your OpenCode API key |
104
+
105
+ > **The `proxy-` prefix is not optional.** Clients like Trae route traffic by model ID. If you use a
106
+ > built-in preset name (such as `glm-5.3-flash`), the conversation is diverted to the client's own
107
+ > cloud channel, **bypassing this proxy entirely** — and then it still fails with a 400. The prefix
108
+ > forces traffic through the proxy, which strips it before forwarding upstream.
109
+
110
+ If your client can only be pointed at `http://127.0.0.1:9355/v1`, add a path rewrite:
111
+
112
+ ```bash
113
+ npx llm-session-proxy --path-rewrite "^/v1/=>/zen/go/v1/"
114
+ ```
115
+
116
+ ### 2. Any OpenAI-compatible upstream
117
+
118
+ ```bash
119
+ npx llm-session-proxy \
120
+ --upstream https://api.deepseek.com \
121
+ --port 8788 \
122
+ --inject "x-session-id={{session.id}}" \
123
+ --inject "x-trace-id={{uuid}}" \
124
+ --model-map fast=deepseek-chat \
125
+ --model-map smart=deepseek-reasoner \
126
+ --model-prefix ""
127
+ ```
128
+
129
+ Point the client at `http://127.0.0.1:8788/v1` and it can use short aliases like `fast` or `smart`.
130
+ Full version in [`examples/generic-openai.json`](examples/generic-openai.json).
131
+
132
+ ### 3. A config file (recommended for daily use)
133
+
134
+ ```bash
135
+ npx llm-session-proxy --init # writes an annotated sample config
136
+ npx llm-session-proxy -c llm-session-proxy.config.json
137
+ ```
138
+
139
+ The config file is JSON with comments (`//`, `/* */`) and trailing commas allowed:
140
+
141
+ ```jsonc
142
+ {
143
+ "listen": { "host": "127.0.0.1", "port": 9355 },
144
+ "upstream": { "host": "opencode.ai" },
145
+ "inject": {
146
+ "headers": {
147
+ "x-opencode-session": "{{session.id}}",
148
+ "x-opencode-request": "{{session.requestId}}"
149
+ }
150
+ },
151
+ "model": { "stripPrefixes": ["proxy-"] }
152
+ }
153
+ ```
154
+
155
+ Ready-made configs: [`examples/opencode-go.json`](examples/opencode-go.json),
156
+ [`examples/generic-openai.json`](examples/generic-openai.json),
157
+ [`examples/opencode-go-models.json`](examples/opencode-go-models.json).
158
+
159
+ ### How to fill in the client's base URL
160
+
161
+ | Client can only be set to | Startup flag |
162
+ | --- | --- |
163
+ | `http://127.0.0.1:9355/zen/go/v1` | nothing needed (passed through as-is) |
164
+ | `http://127.0.0.1:9355/v1` | `--path-rewrite "^/v1/=>/zen/go/v1/"` |
165
+ | `http://127.0.0.1:9355` (no path) | `--base-path /zen/go/v1` |
166
+
167
+ ---
168
+
169
+ ## OpenCode Go model reference
170
+
171
+ Upstream splits models across three endpoints. **What your client can speak matters more than the
172
+ model name**, because this proxy does not translate between protocols.
173
+
174
+ **① `/zen/go/v1/chat/completions` — OpenAI-compatible; what most clients use**
175
+
176
+ | Model | Client model ID | Upstream model ID |
177
+ | --- | --- | --- |
178
+ | GLM-5.3 | `proxy-glm` / `proxy-glm-5.3` | `glm-5.3` |
179
+ | GLM-5.3-Flash | `proxy-glm-flash` | `glm-5.3-flash` |
180
+ | GLM-5.2 / 5.1 | `proxy-glm-5.2` | `glm-5.2` |
181
+ | Kimi K3 | `proxy-kimi` | `kimi-k3` |
182
+ | Kimi K2.7 Code | `proxy-kimi-code` | `kimi-k2.7-code` |
183
+ | Kimi K2.6 | `proxy-kimi-k2.6` | `kimi-k2.6` |
184
+ | DeepSeek V4.1 Flash | `proxy-deepseek` | `deepseek-flash` |
185
+ | DeepSeek V4 Pro | `proxy-deepseek-pro` | `deepseek-v4-pro` |
186
+ | DeepSeek V4 Flash | `proxy-deepseek-v4-flash` | `deepseek-v4-flash` |
187
+ | DeepSeek V4 Flash Vision Exp | `proxy-deepseek-vision` | `deepseek-v4-flash-vision-exp` |
188
+ | LongCat-2.0 | `proxy-longcat` | `longcat-2.0` |
189
+ | MiMo-V2.5 / Pro | `proxy-mimo` | `mimo-v2.5` |
190
+ | Hy3 / Hy4 preview | `proxy-hy3` | `hy3` |
191
+
192
+ **② `/zen/go/v1/responses` — OpenAI Responses API; the client must speak that protocol**
193
+
194
+ | Model | Client model ID | Upstream model ID |
195
+ | --- | --- | --- |
196
+ | Grok 4.6 | `proxy-grok` | `grok-4.6` |
197
+ | GPT 5.6 Luna | `proxy-gpt-luna` | `gpt-5.6-luna` |
198
+ | Muse Spark 1.3 / 1.2 Contributor | `proxy-muse-1.3` | `muse-spark-1.3-contributor` |
199
+
200
+ **③ `/zen/go/v1/messages` — Anthropic Messages API; the client must send Anthropic-shaped bodies**
201
+
202
+ | Model | Client model ID | Upstream model ID |
203
+ | --- | --- | --- |
204
+ | MiniMax M3 / M2.7 / M2.5 | `proxy-minimax` | `minimax-m3` |
205
+ | Qwen3.8 Max | `proxy-qwen-max` | `qwen3.8-max` |
206
+ | Qwen3.8 Flash | `proxy-qwen-flash` | `qwen3.8-flash` |
207
+ | Qwen3.7 / 3.6 Plus | `proxy-qwen-plus` | `qwen3.6-plus` |
208
+
209
+ > This proxy performs **no protocol translation**. If your client sends OpenAI-shaped bodies,
210
+ > categories ② and ③ are unusable: the proxy fills headers, rewrites the model name, and reroutes
211
+ > the path, but it will not turn a Chat Completions body into a Messages body.
212
+ >
213
+ > Writing the real upstream ID directly (no alias, no prefix) also works — it is passed through.
214
+ > The model list changes over time; treat the
215
+ > [upstream docs](https://opencode.ai/docs/go/) as the source of truth.
216
+
217
+ ---
218
+
219
+ ## Configuration reference
220
+
221
+ Priority: **defaults < config file < environment variables < CLI flags**.
222
+
223
+ ### `listen`
224
+
225
+ | Field | Default | Description |
226
+ | --- | --- | --- |
227
+ | `host` | `127.0.0.1` | Bind address. Loopback only — do **not** use `0.0.0.0`, or anyone on your network can spend your quota |
228
+ | `port` | `9355` | Port |
229
+
230
+ ### `upstream`
231
+
232
+ | Field | Default | Description |
233
+ | --- | --- | --- |
234
+ | `protocol` | `https` | `https` or `http` |
235
+ | `host` | `opencode.ai` | May also be a full URL, which gets parsed automatically |
236
+ | `port` | `null` | `null` means the protocol default (443 / 80) |
237
+ | `basePath` | `""` | Prefix prepended to every forwarded path, e.g. `/zen/go/v1` |
238
+ | `rewriteHost` | `true` | Whether to rewrite the `Host` header |
239
+
240
+ ### `request`
241
+
242
+ | Field | Default | Description |
243
+ | --- | --- | --- |
244
+ | `bufferBody` | `true` | Must be `true` to rewrite the body (model name, parameter injection) |
245
+ | `maxBodyBytes` | `67108864` | Request body limit (64 MB); larger returns 413 |
246
+ | `timeoutMs` | `600000` | Upstream timeout |
247
+ | `pathRewrite` | `[]` | Rules as `{ "pattern": "regex", "replacement": "..." }` |
248
+ | `dropHeaders` | `[]` | Headers (lowercase) not forwarded upstream |
249
+ | `forwardClientSessionHeaders` | `true` | Forward the client's own session headers |
250
+
251
+ ### `session`
252
+
253
+ | Field | Default | Description |
254
+ | --- | --- | --- |
255
+ | `enabled` | `true` | Enable session ID injection |
256
+ | `headerNames` | `x-opencode-session`, 4 more | Tried in order to read the client's session ID |
257
+ | `bodyFields` | `session_id`, … | Tried in order on the request body (dot paths supported) |
258
+ | `contentHash.enabled` | `true` | Fall back to a content fingerprint |
259
+ | `contentHash.fields` | `["system", "system_instruction", "instructions"]` | Fields used for the fingerprint |
260
+ | `contentHash.includeFirstUserMessage` | `true` | Whether the first user message participates |
261
+ | `idPrefix` | `ses_` | Prefix for generated IDs |
262
+ | `idFormat` | `hex26` | `hex26` / `hex` / `uuid` / `base36` / `short` |
263
+ | `requestIdFormat` | `msg_{{session.count}}` | Request-id template |
264
+ | `maxSessions` | `512` | Session table cap; oldest evicted first |
265
+ | `ttlSeconds` | `0` | Expiry in seconds; `0` disables expiry |
266
+
267
+ ### `inject`
268
+
269
+ | Field | Default | Description |
270
+ | --- | --- | --- |
271
+ | `headers` | 4 `x-opencode-*` headers | Headers to inject; values are templates. Set to `null` to skip one |
272
+ | `body` | `{}` | Fields merged into the request body (dot paths and templates supported) |
273
+ | `removeBodyFields` | `[]` | Body field paths to delete |
274
+ | `overwrite` | `true` | `false` keeps the client's existing header/field |
275
+
276
+ ### `model`
277
+
278
+ | Field | Default | Description |
279
+ | --- | --- | --- |
280
+ | `enabled` | `true` | Enable model rewriting |
281
+ | `field` | `model` | Body field holding the model name |
282
+ | `stripPrefixes` | `["proxy-"]` | Prefixes to strip, first match wins |
283
+ | `map` | `{}` | Exact mapping. Looked up by original name first, then again after prefix stripping |
284
+ | `default` | `null` | Fallback model |
285
+
286
+ ### Response, UA and logging
287
+
288
+ | Field | Default | Description |
289
+ | --- | --- | --- |
290
+ | `userAgent` | `opencode/1.18.29 cli` | Injected UA |
291
+ | `userAgentMode` | `replace-generic` | `keep` preserves the client UA; `replace` always overrides; `replace-generic` only when missing or library-like |
292
+ | `response.stream` | `true` | Stream pass-through. `false` buffers everything (**breaks SSE**) |
293
+ | `log.level` | `info` | `silent` / `error` / `warn` / `info` / `debug` |
294
+ | `log.file` | `null` | Extra log file, rotated by size |
295
+
296
+ ---
297
+
298
+ ## Template variables
299
+
300
+ | Variable | Meaning |
301
+ | --- | --- |
302
+ | `{{session.id}}` | Session ID used for this request |
303
+ | `{{session.count}}` | Nth request within the session (1-based) |
304
+ | `{{session.requestId}}` | Rendered from `requestIdFormat`, e.g. `msg_3` |
305
+ | `{{session.source}}` | `header:*` / `body:*` / `content-hash` / `random` |
306
+ | `{{model}}` | Model name after rewriting |
307
+ | `{{path}}` / `{{method}}` | Original path / method |
308
+ | `{{header.x-foo}}` | Client header (lowercase) |
309
+ | `{{query.foo}}` | Query parameter |
310
+ | `{{env.HOME}}` | Environment variable |
311
+ | `{{uuid}}` | Fresh UUID per render |
312
+ | `{{random}}` / `{{randomHex:16}}` | Random hex, default 26 / 16 chars |
313
+ | `{{timestamp}}` / `{{timestampMs}}` | Seconds / milliseconds |
314
+
315
+ ---
316
+
317
+ ## CLI reference
318
+
319
+ | Flag | Description |
320
+ | --- | --- |
321
+ | `-c, --config <file>` | Read a config file |
322
+ | `-p, --port <n>` / `--host <addr>` | Listen port / address |
323
+ | `-u, --upstream <url>` | Upstream, e.g. `https://opencode.ai` or `host:port` |
324
+ | `--base-path <path>` | Forwarding path prefix |
325
+ | `--path-rewrite <a=>b>` | Path rewrite (regex), repeatable |
326
+ | `--inject <name=value>` | Inject a header, repeatable |
327
+ | `--body-inject <k=v>` | Inject a body field (dot paths), repeatable |
328
+ | `--model-prefix <prefix>` | Prefix to strip, repeatable |
329
+ | `--model-map <a=b>` | Exact model mapping, repeatable |
330
+ | `--session-header <name>` / `--session-field <path>` | Add a session source, repeatable |
331
+ | `--session-id-format <f>` / `--request-id-format <t>` | Session ID format / request-id template |
332
+ | `--no-session` / `--no-stream` | Disable session injection / disable streaming |
333
+ | `--timeout <ms>` / `--max-body <bytes>` | Upstream timeout / body limit |
334
+ | `--log-level <l>` / `--log-file <f>` | Log level / log file |
335
+ | `--init [file]` | Write a sample config |
336
+ | `--print-config` | Print the merged config and exit |
337
+
338
+ Environment variables mirror the config field names in uppercase: `PROXY_PORT`, `UPSTREAM_HOST`,
339
+ `UPSTREAM_PROTO`, `OPENCODE_UA`, `LOG_LEVEL`, `LOG_FILE`, `MODEL_ALIAS_PREFIX`, `INJECT_HEADERS`
340
+ (JSON), and so on.
341
+
342
+ ### Local status endpoints
343
+
344
+ ```bash
345
+ # Overview: session count, hit rate, injected headers, upstream
346
+ curl http://127.0.0.1:9355/__llm_session_proxy__/status
347
+
348
+ # Per-session detail
349
+ curl http://127.0.0.1:9355/__llm_session_proxy__/sessions
350
+ ```
351
+
352
+ Handy when debugging: if `sessions.active` stays at 0, requests never reached the proxy — usually
353
+ because the model ID is missing the `proxy-` prefix and the client intercepted it.
354
+
355
+ ---
356
+
357
+ ## How it works
358
+
359
+ ```
360
+ client ──▶ llm-session-proxy ──▶ upstream API
361
+
362
+ ├─ 1. read and parse the request body
363
+ ├─ 2. resolve the session: explicit > fingerprint > random
364
+ ├─ 3. rewrite path and model name
365
+ ├─ 4. inject headers and body parameters
366
+ └─ 5. forward, streaming SSE chunks back as they arrive
367
+ ```
368
+
369
+ The three-tier session resolution is what keeps IDs stable within a conversation:
370
+
371
+ 1. **Explicit** — the client already sent `x-opencode-session`, or the body carries `session_id`.
372
+ Reused verbatim; most accurate.
373
+ 2. **Content fingerprint** — SHA-256 over `system` plus the first user message. Later turns only
374
+ append messages, so the anchor stays stable and the ID is reused.
375
+ 3. **One-off random** — neither is available (e.g. a non-JSON body). A random ID is issued so the
376
+ upstream will not 400; these requests are not stored, keeping the session table from growing.
377
+
378
+ ---
379
+
380
+ ## Use as a library
381
+
382
+ ```js
383
+ import { startProxy, buildConfig, createProxyServer } from 'llm-session-proxy';
384
+
385
+ const proxy = await startProxy({
386
+ flags: {
387
+ listen: { port: 9355 },
388
+ upstream: { host: 'opencode.ai' },
389
+ inject: { headers: { 'x-opencode-session': '{{session.id}}' } },
390
+ },
391
+ });
392
+
393
+ console.log(`listening on ${proxy.url}`);
394
+ console.log(`active sessions: ${proxy.store.size}`);
395
+
396
+ await proxy.stop();
397
+ ```
398
+
399
+ You can also take just the parts you need: `createProxyServer` (own the lifecycle),
400
+ `SessionStore` (session table), `renderTemplate` (template engine), `buildConfig` (config merging).
401
+
402
+ ---
403
+
404
+ ## FAQ
405
+
406
+ **The client cannot connect, and the proxy logs nothing**
407
+
408
+ Check that the base URL points at the proxy and that the model ID carries the `proxy-` prefix. The
409
+ latter is by far the most common cause — clients like Trae divert traffic by model ID.
410
+
411
+ **Still a 400 about the missing session header**
412
+
413
+ Look at the `session=` field in the proxy log for that request. A value there means the proxy
414
+ injected it but the upstream did not see it — check whether `inject.headers` got overwritten by a
415
+ config file. No value means `session.enabled` is off.
416
+
417
+ **Long conversations get slower; prompt caching never hits**
418
+
419
+ The session ID is not stable. Check whether the client mutates `system` or the first user message
420
+ every turn (some clients inject timestamps or the current file path). Either switch to an explicit
421
+ session header, or narrow `contentHash.fields` to the most stable field.
422
+
423
+ **Will the injected headers confuse a different upstream?**
424
+
425
+ No. Headers the upstream does not recognize are harmless extras. For a clean request set
426
+ `inject.headers` to `{}` or keep only the ones you need.
427
+
428
+ **Port already in use**
429
+
430
+ On `EADDRINUSE`, pick another port (`--port 9356`) and update the client's base URL.
431
+
432
+ ---
433
+
434
+ ## Limitations
435
+
436
+ - **Loopback only (127.0.0.1).** The proxy forwards your API key; do not bind it to `0.0.0.0`.
437
+ - **`response.stream: false` breaks SSE.** Keep it `true` unless you genuinely need full buffering.
438
+ - **`bufferBody: false` disables body rewriting.** Model rewriting and parameter injection stop
439
+ working; only header injection and header-based session detection remain.
440
+ - The proxy only forwards and patches. It does not cache, meter usage, or modify responses.
441
+
442
+ ---
443
+
444
+ ## Releasing a new version
445
+
446
+ Publishing is handled by GitHub Actions ([`.github/workflows/publish.yml`](.github/workflows/publish.yml));
447
+ no local `npm login` required:
448
+
449
+ 1. Bump `version` in `package.json`
450
+ 2. Commit and push
451
+ 3. Tag and push the matching tag:
452
+
453
+ ```bash
454
+ git tag v0.1.1 && git push origin v0.1.1
455
+ ```
456
+
457
+ The workflow runs the full test suite, verifies the tag matches `package.json`, then publishes to
458
+ registry.npmjs.org using the `NPM_TOKEN` repository secret. It can also be triggered manually from
459
+ the Actions tab, optionally as a dry run.
460
+
461
+ > The secret must be an **Automation** token (npmjs.com → Access Tokens → Classic Token →
462
+ > Automation). A 2FA-protected Publish token will fail in CI with `EOTP`.
463
+
464
+ ## License
465
+
466
+ [Apache License 2.0](LICENSE) © 2026 alaahong