rebellm-bridge 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 +223 -0
- package/README.md +115 -0
- package/dist/anthropic/map.d.ts +32 -0
- package/dist/anthropic/map.js +254 -0
- package/dist/anthropic/routes.d.ts +15 -0
- package/dist/anthropic/routes.js +140 -0
- package/dist/anthropic/sse.d.ts +24 -0
- package/dist/anthropic/sse.js +66 -0
- package/dist/anthropic/stop.d.ts +17 -0
- package/dist/anthropic/stop.js +51 -0
- package/dist/anthropic/types.d.ts +112 -0
- package/dist/anthropic/types.js +5 -0
- package/dist/cli.d.ts +57 -0
- package/dist/cli.js +200 -0
- package/dist/http.d.ts +14 -0
- package/dist/http.js +46 -0
- package/dist/launcher.d.ts +37 -0
- package/dist/launcher.js +253 -0
- package/dist/mcp.d.ts +17 -0
- package/dist/mcp.js +169 -0
- package/dist/openai.d.ts +54 -0
- package/dist/openai.js +265 -0
- package/dist/protocol.d.ts +99 -0
- package/dist/protocol.js +53 -0
- package/dist/server.d.ts +24 -0
- package/dist/server.js +70 -0
- package/dist/tab.d.ts +102 -0
- package/dist/tab.js +257 -0
- package/package.json +68 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"Commons Clause" License Condition v1.0
|
|
2
|
+
|
|
3
|
+
The Software is provided to you by the Licensor under the License, as defined
|
|
4
|
+
below, subject to the following condition.
|
|
5
|
+
|
|
6
|
+
Without limiting other conditions in the License, the grant of rights under the
|
|
7
|
+
License will not include, and the License does not grant to you, the right to
|
|
8
|
+
Sell the Software.
|
|
9
|
+
|
|
10
|
+
For purposes of the foregoing, "Sell" means practicing any or all of the rights
|
|
11
|
+
granted to you under the License to provide to third parties, for a fee or other
|
|
12
|
+
consideration (including without limitation fees for hosting or consulting/
|
|
13
|
+
support services related to the Software), a product or service whose value
|
|
14
|
+
derives, entirely or substantially, from the functionality of the Software. Any
|
|
15
|
+
license notice or attribution required by the License must also include this
|
|
16
|
+
Commons Clause License Condition notice.
|
|
17
|
+
|
|
18
|
+
Software: RebeLLM Bridge
|
|
19
|
+
License: Apache License, Version 2.0
|
|
20
|
+
Licensor: Byteleap Oy
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
Apache License
|
|
24
|
+
Version 2.0, January 2004
|
|
25
|
+
http://www.apache.org/licenses/
|
|
26
|
+
|
|
27
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
28
|
+
|
|
29
|
+
1. Definitions.
|
|
30
|
+
|
|
31
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
32
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
33
|
+
|
|
34
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
35
|
+
the copyright owner that is granting the License.
|
|
36
|
+
|
|
37
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
38
|
+
other entities that control, are controlled by, or are under common
|
|
39
|
+
control with that entity. For the purposes of this definition,
|
|
40
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
41
|
+
direction or management of such entity, whether by contract or
|
|
42
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
43
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
44
|
+
|
|
45
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
46
|
+
exercising permissions granted by this License.
|
|
47
|
+
|
|
48
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
49
|
+
including but not limited to software source code, documentation
|
|
50
|
+
source, and configuration files.
|
|
51
|
+
|
|
52
|
+
"Object" form shall mean any form resulting from mechanical
|
|
53
|
+
transformation or translation of a Source form, including but
|
|
54
|
+
not limited to compiled object code, generated documentation,
|
|
55
|
+
and conversions to other media types.
|
|
56
|
+
|
|
57
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
58
|
+
Object form, made available under the License, as indicated by a
|
|
59
|
+
copyright notice that is included in or attached to the work
|
|
60
|
+
(an example is provided in the Appendix below).
|
|
61
|
+
|
|
62
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
63
|
+
form, that is based on (or derived from) the Work and for which the
|
|
64
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
65
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
66
|
+
of this License, Derivative Works shall not include works that remain
|
|
67
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
68
|
+
the Work and Derivative Works thereof.
|
|
69
|
+
|
|
70
|
+
"Contribution" shall mean any work of authorship, including
|
|
71
|
+
the original version of the Work and any modifications or additions
|
|
72
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
73
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
74
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
75
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
76
|
+
means any form of electronic, verbal, or written communication sent
|
|
77
|
+
to the Licensor or its representatives, including but not limited to
|
|
78
|
+
communication on electronic mailing lists, source code control systems,
|
|
79
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
80
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
81
|
+
excluding communication that is conspicuously marked or otherwise
|
|
82
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
83
|
+
|
|
84
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
85
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
86
|
+
subsequently incorporated within the Work.
|
|
87
|
+
|
|
88
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
89
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
90
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
91
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
92
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
93
|
+
Work and such Derivative Works in Source or Object form.
|
|
94
|
+
|
|
95
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
96
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
97
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
98
|
+
(except as stated in this section) patent license to make, have made,
|
|
99
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
100
|
+
where such license applies only to those patent claims licensable
|
|
101
|
+
by such Contributor that are necessarily infringed by their
|
|
102
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
103
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
104
|
+
institute patent litigation against any entity (including a
|
|
105
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
106
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
107
|
+
or contributory patent infringement, then any patent licenses
|
|
108
|
+
granted to You under this License for that Work shall terminate
|
|
109
|
+
as of the date such litigation is filed.
|
|
110
|
+
|
|
111
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
112
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
113
|
+
modifications, and in Source or Object form, provided that You
|
|
114
|
+
meet the following conditions:
|
|
115
|
+
|
|
116
|
+
(a) You must give any other recipients of the Work or
|
|
117
|
+
Derivative Works a copy of this License; and
|
|
118
|
+
|
|
119
|
+
(b) You must cause any modified files to carry prominent notices
|
|
120
|
+
stating that You changed the files; and
|
|
121
|
+
|
|
122
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
123
|
+
that You distribute, all copyright, patent, trademark, and
|
|
124
|
+
attribution notices from the Source form of the Work,
|
|
125
|
+
excluding those notices that do not pertain to any part of
|
|
126
|
+
the Derivative Works; and
|
|
127
|
+
|
|
128
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
129
|
+
distribution, then any Derivative Works that You distribute must
|
|
130
|
+
include a readable copy of the attribution notices contained
|
|
131
|
+
within such NOTICE file, excluding those notices that do not
|
|
132
|
+
pertain to any part of the Derivative Works, in at least one
|
|
133
|
+
of the following places: within a NOTICE text file distributed
|
|
134
|
+
as part of the Derivative Works; within the Source form or
|
|
135
|
+
documentation, if provided along with the Derivative Works; or,
|
|
136
|
+
within a display generated by the Derivative Works, if and
|
|
137
|
+
wherever such third-party notices normally appear. The contents
|
|
138
|
+
of the NOTICE file are for informational purposes only and
|
|
139
|
+
do not modify the License. You may add Your own attribution
|
|
140
|
+
notices within Derivative Works that You distribute, alongside
|
|
141
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
142
|
+
that such additional attribution notices cannot be construed
|
|
143
|
+
as modifying the License.
|
|
144
|
+
|
|
145
|
+
You may add Your own copyright statement to Your modifications and
|
|
146
|
+
may provide additional or different license terms and conditions
|
|
147
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
148
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
149
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
150
|
+
the conditions stated in this License.
|
|
151
|
+
|
|
152
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
153
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
154
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
155
|
+
this License, without any additional terms or conditions.
|
|
156
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
157
|
+
the terms of any separate license agreement you may have executed
|
|
158
|
+
with Licensor regarding such Contributions.
|
|
159
|
+
|
|
160
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
161
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
162
|
+
except as required for reasonable and customary use in describing the
|
|
163
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
164
|
+
|
|
165
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
166
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
167
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
168
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
169
|
+
implied, including, without limitation, any warranties or conditions
|
|
170
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
171
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
172
|
+
appropriateness of using or redistributing the Work and assume any
|
|
173
|
+
risks associated with Your exercise of permissions under this License.
|
|
174
|
+
|
|
175
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
176
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
177
|
+
unless required by applicable law (such as deliberate and grossly
|
|
178
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
179
|
+
liable to You for damages, including any direct, indirect, special,
|
|
180
|
+
incidental, or consequential damages of any character arising as a
|
|
181
|
+
result of this License or out of the use or inability to use the
|
|
182
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
183
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
184
|
+
other commercial damages or losses), even if such Contributor
|
|
185
|
+
has been advised of the possibility of such damages.
|
|
186
|
+
|
|
187
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
188
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
189
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
190
|
+
or other liability obligations and/or rights consistent with this
|
|
191
|
+
License. However, in accepting such obligations, You may act only
|
|
192
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
193
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
194
|
+
defend, and hold each Contributor harmless for any liability
|
|
195
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
196
|
+
of your accepting any such warranty or additional liability.
|
|
197
|
+
|
|
198
|
+
END OF TERMS AND CONDITIONS
|
|
199
|
+
|
|
200
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
201
|
+
|
|
202
|
+
To apply the Apache License to your work, attach the following
|
|
203
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
204
|
+
replaced with your own identifying information. (Don't include
|
|
205
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
206
|
+
comment syntax for the file format. We also recommend that a
|
|
207
|
+
file or class name and description of purpose be included on the
|
|
208
|
+
same "printed page" as the copyright notice for easier
|
|
209
|
+
identification within third-party archives.
|
|
210
|
+
|
|
211
|
+
Copyright [yyyy] [name of copyright owner]
|
|
212
|
+
|
|
213
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
214
|
+
you may not use this file except in compliance with the License.
|
|
215
|
+
You may obtain a copy of the License at
|
|
216
|
+
|
|
217
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
218
|
+
|
|
219
|
+
Unless required by applicable law or agreed to in writing, software
|
|
220
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
221
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
222
|
+
See the License for the specific language governing permissions and
|
|
223
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# RebeLLM Bridge
|
|
2
|
+
|
|
3
|
+
Use the model running in your [RebeLLM](https://rebellm.ai) browser tab from the command
|
|
4
|
+
line, from any OpenAI or Anthropic client, and from Claude Code. The bridge is a small local
|
|
5
|
+
service: the tab connects to it and does the work; the bridge runs no model and holds no
|
|
6
|
+
keys.
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
Claude Code / curl / SDKs ──HTTP──▶ rebellm-bridge (127.0.0.1:7343) ◀──WebSocket── RebeLLM tab
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Getting started
|
|
13
|
+
|
|
14
|
+
Node 22+ and a RebeLLM tab.
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
npm install -g rebellm-bridge # or run it once with: npx rebellm-bridge
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
(From source: clone this repo, `npm install && npm run build && npm install -g .`.)
|
|
21
|
+
|
|
22
|
+
1. `rebellm-bridge` — the first start prints a token once and keeps it in
|
|
23
|
+
`~/.rebellm-bridge/token` (`cat` it to see it again, delete it for a new one).
|
|
24
|
+
2. In RebeLLM: Settings → Local bridge → paste the token, switch on, Save. The card reads
|
|
25
|
+
"Connected to 127.0.0.1:7343". The model must be loaded in that tab.
|
|
26
|
+
3. Check: `curl http://127.0.0.1:7343/health` → `{"tab":true,"state":"ready",...}`.
|
|
27
|
+
|
|
28
|
+
## Use it from the command line
|
|
29
|
+
|
|
30
|
+
OpenAI-style (streaming recommended — a local model can take minutes for the first token):
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
curl -N http://127.0.0.1:7343/v1/chat/completions -H 'Content-Type: application/json' \
|
|
34
|
+
-d '{"model":"rebellm","stream":true,"messages":[{"role":"user","content":"Capital of Finland, one word."}]}'
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Anthropic-style:
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
curl -N http://127.0.0.1:7343/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' \
|
|
41
|
+
-d '{"model":"rebellm","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"Capital of Finland, one word."}]}'
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Other routes: `GET /v1/models`, `GET /health`, `POST /v1/messages/count_tokens` (an
|
|
45
|
+
estimate, works without a tab). No API key is checked: the bridge listens on loopback only
|
|
46
|
+
and refuses requests from web pages (`Origin`) and foreign `Host` names. `model` is
|
|
47
|
+
ignored; the tab's model answers. `tools` are forwarded and come back as tool calls for your
|
|
48
|
+
client to run.
|
|
49
|
+
|
|
50
|
+
SDKs: OpenAI with `base_url="http://127.0.0.1:7343/v1"`, Anthropic with
|
|
51
|
+
`base_url="http://127.0.0.1:7343"`, any `api_key`.
|
|
52
|
+
|
|
53
|
+
## Claude Code
|
|
54
|
+
|
|
55
|
+
As Claude Code's model (its own config directory, your claude.ai login untouched):
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
rebellm-claude # interactive
|
|
59
|
+
rebellm-claude -p "What is 2 + 3?"
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
It reuses a running bridge or starts one, waits for the tab, sets the tab's context size
|
|
63
|
+
and a long request timeout, and passes every other argument to `claude`. Options:
|
|
64
|
+
`--claude <path>`, `--shared-config` (use your normal Claude Code config), `--port <n>`.
|
|
65
|
+
Claude Code's first request is ~11k tokens of system prompt and tools, so it needs a tab
|
|
66
|
+
with a 32k context and patience on a slow GPU.
|
|
67
|
+
|
|
68
|
+
As a tool inside your normal Claude Code (Claude keeps its own model, can ask yours):
|
|
69
|
+
|
|
70
|
+
```
|
|
71
|
+
claude mcp add rebellm -- rebellm-bridge --mcp
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Tools: `chat` (messages, optional `max_tokens`, `temperature`; streams progress) and
|
|
75
|
+
`status`. Raise `MCP_TOOL_TIMEOUT` if Claude Code gives up before a slow answer.
|
|
76
|
+
|
|
77
|
+
## Options
|
|
78
|
+
|
|
79
|
+
| Option | Default | Meaning |
|
|
80
|
+
| --------------- | ---------------------------- | -------------------------------------------------- |
|
|
81
|
+
| `--port <n>` | `7343` | one port for the tab (WebSocket) and HTTP |
|
|
82
|
+
| `--host <addr>` | `127.0.0.1` | anything else exposes your model; prints a warning |
|
|
83
|
+
| `--token <t>` | `REBELLM_BRIDGE_TOKEN`, file | the token the tab must present |
|
|
84
|
+
| `--wait <s>` | `120` | how long a request waits for a ready tab |
|
|
85
|
+
| `--mcp` | off | also serve MCP over stdio |
|
|
86
|
+
|
|
87
|
+
## Test it locally
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
npm run check # typecheck, lint, format, unit and end-to-end tests (fake tab)
|
|
91
|
+
npm run build && node dist/cli.js # then connect a real tab and curl as above
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The tests start bridges on free ports and drive them with a fake tab that speaks the
|
|
95
|
+
protocol; nothing needs a GPU.
|
|
96
|
+
|
|
97
|
+
## Protocol
|
|
98
|
+
|
|
99
|
+
The tab speaks protocol v1 to the bridge: JSON frames over one WebSocket — `hello` (token,
|
|
100
|
+
version, model, context) → `ok`/`error`; the bridge sends `chat`/`abort`, the tab answers
|
|
101
|
+
`queued`, `token`, `tool_call`, `done` (stop reason, usage) or `error`, plus `status` on
|
|
102
|
+
model state changes and `ping`/`pong`. Types and parser: `src/protocol.ts`; the RebeLLM app
|
|
103
|
+
owns the specification.
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
All changes go through the OpenSpec flow in `CLAUDE.md`; `npm install` enables the
|
|
108
|
+
pre-commit gate.
|
|
109
|
+
|
|
110
|
+
## Licence
|
|
111
|
+
|
|
112
|
+
Apache-2.0 with the Commons Clause (see `LICENSE`): free to use, change and share, for
|
|
113
|
+
anyone, companies included; not for sale — no selling the software or a hosting or support
|
|
114
|
+
service whose value comes substantially from it. Source-available, not open source in the
|
|
115
|
+
OSI sense. RebeLLM itself is a separate, proprietary product.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { StopReason as TabStop, ToolCall, Usage as TabUsage } from '../protocol.js';
|
|
2
|
+
import type { ChatInput } from '../tab.js';
|
|
3
|
+
import type { ApiError, ContentBlock, Message, StopReason, ToolUseBlock, Usage } from './types.js';
|
|
4
|
+
export declare const newId: () => string;
|
|
5
|
+
export type ParsedMessages = {
|
|
6
|
+
input: ChatInput;
|
|
7
|
+
stream: boolean;
|
|
8
|
+
stopSequences: string[];
|
|
9
|
+
} | {
|
|
10
|
+
error: string;
|
|
11
|
+
};
|
|
12
|
+
/** A Messages API request as the tab's `chat`; the error names the field that is wrong. */
|
|
13
|
+
export declare function toChatInput(body: unknown): ParsedMessages;
|
|
14
|
+
/** Rough prompt size without a tokenizer: `ceil(chars / 3.5)` over messages, calls and tools. */
|
|
15
|
+
export declare function estimateTokens(input: ChatInput): number;
|
|
16
|
+
/** The wording Claude Code reacts to by compacting the conversation. */
|
|
17
|
+
export declare const tooLong: (tokens: number, max: number) => string;
|
|
18
|
+
/** A failed chat as an API error; the tab's "prompt does not fit" becomes Claude Code's "too long". */
|
|
19
|
+
export declare function tabError(message: string): ApiError;
|
|
20
|
+
export declare function stopReason(stop: TabStop, calls: number): StopReason;
|
|
21
|
+
export declare const usage: (input: number, output: number) => Usage;
|
|
22
|
+
export declare const tabUsage: (u: TabUsage) => Usage;
|
|
23
|
+
export declare const toolUse: (c: ToolCall) => ToolUseBlock;
|
|
24
|
+
/** The content of an answer: its text (always, when there are no calls), then its tool calls. */
|
|
25
|
+
export declare const content: (text: string, calls: ToolUseBlock[]) => ContentBlock[];
|
|
26
|
+
export declare function message(meta: {
|
|
27
|
+
id: string;
|
|
28
|
+
model: string;
|
|
29
|
+
}, blocks: ContentBlock[], stop: {
|
|
30
|
+
reason: StopReason | null;
|
|
31
|
+
sequence: string | null;
|
|
32
|
+
}, u: Usage): Message;
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
3
|
+
const isStr = (v) => typeof v === 'string';
|
|
4
|
+
const absent = (v) => v === undefined || v === null;
|
|
5
|
+
export const newId = () => randomBytes(12).toString('hex');
|
|
6
|
+
/** A content block the tab cannot take, as text it can. */
|
|
7
|
+
const omitted = (type) => `[${type} omitted]`;
|
|
8
|
+
function blockText(b, at) {
|
|
9
|
+
if (!isObj(b) || !isStr(b.type))
|
|
10
|
+
return { error: `${at} must be a content block with a type` };
|
|
11
|
+
if (b.type !== 'text')
|
|
12
|
+
return omitted(b.type);
|
|
13
|
+
return isStr(b.text) ? b.text : { error: `${at}.text must be a string` };
|
|
14
|
+
}
|
|
15
|
+
function blocksText(blocks, path) {
|
|
16
|
+
const parts = [];
|
|
17
|
+
for (const [j, b] of blocks.entries()) {
|
|
18
|
+
const text = blockText(b, `${path}.${j}`);
|
|
19
|
+
if (!isStr(text))
|
|
20
|
+
return text;
|
|
21
|
+
parts.push(text);
|
|
22
|
+
}
|
|
23
|
+
return parts.join('\n\n');
|
|
24
|
+
}
|
|
25
|
+
function systemText(s) {
|
|
26
|
+
if (absent(s))
|
|
27
|
+
return '';
|
|
28
|
+
if (isStr(s))
|
|
29
|
+
return s;
|
|
30
|
+
if (!Array.isArray(s))
|
|
31
|
+
return { error: 'system must be a string or an array of text blocks' };
|
|
32
|
+
return blocksText(s, 'system');
|
|
33
|
+
}
|
|
34
|
+
function toolResult(b, path, names) {
|
|
35
|
+
if (!isStr(b.tool_use_id))
|
|
36
|
+
return { error: `${path}.tool_use_id must be a string` };
|
|
37
|
+
let text = '';
|
|
38
|
+
if (isStr(b.content))
|
|
39
|
+
text = b.content;
|
|
40
|
+
else if (Array.isArray(b.content))
|
|
41
|
+
text = blocksText(b.content, `${path}.content`);
|
|
42
|
+
else if (!absent(b.content))
|
|
43
|
+
return { error: `${path}.content must be a string or an array of blocks` };
|
|
44
|
+
if (!isStr(text))
|
|
45
|
+
return text;
|
|
46
|
+
const name = names.get(b.tool_use_id);
|
|
47
|
+
return { role: 'tool', content: b.is_error === true ? `Error: ${text}` : text, ...(name ? { name } : {}) };
|
|
48
|
+
}
|
|
49
|
+
/** One user message: text in order, each tool result its own `tool` message. */
|
|
50
|
+
function userMessages(content, path, names) {
|
|
51
|
+
const out = [];
|
|
52
|
+
let texts = null;
|
|
53
|
+
const flush = () => {
|
|
54
|
+
if (texts)
|
|
55
|
+
out.push({ role: 'user', content: texts.join('\n\n') });
|
|
56
|
+
texts = null;
|
|
57
|
+
};
|
|
58
|
+
for (const [j, b] of content.entries()) {
|
|
59
|
+
const at = `${path}.${j}`;
|
|
60
|
+
if (!isObj(b) || !isStr(b.type))
|
|
61
|
+
return { error: `${at} must be a content block with a type` };
|
|
62
|
+
if (b.type === 'tool_result') {
|
|
63
|
+
flush();
|
|
64
|
+
const m = toolResult(b, at, names);
|
|
65
|
+
if ('error' in m)
|
|
66
|
+
return m;
|
|
67
|
+
out.push(m);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const text = blockText(b, at);
|
|
71
|
+
if (!isStr(text))
|
|
72
|
+
return text;
|
|
73
|
+
(texts ??= []).push(text);
|
|
74
|
+
}
|
|
75
|
+
flush();
|
|
76
|
+
return out.length ? out : [{ role: 'user', content: '' }];
|
|
77
|
+
}
|
|
78
|
+
/** An assistant message: its text and tool calls; thinking and server-tool blocks are dropped. */
|
|
79
|
+
function assistantMessage(content, path, names) {
|
|
80
|
+
const texts = [];
|
|
81
|
+
const calls = [];
|
|
82
|
+
for (const [j, b] of content.entries()) {
|
|
83
|
+
const at = `${path}.${j}`;
|
|
84
|
+
if (!isObj(b) || !isStr(b.type))
|
|
85
|
+
return { error: `${at} must be a content block with a type` };
|
|
86
|
+
if (b.type === 'text') {
|
|
87
|
+
if (!isStr(b.text))
|
|
88
|
+
return { error: `${at}.text must be a string` };
|
|
89
|
+
if (b.text)
|
|
90
|
+
texts.push(b.text);
|
|
91
|
+
}
|
|
92
|
+
else if (b.type === 'tool_use') {
|
|
93
|
+
if (!isStr(b.id) || !isStr(b.name) || !(absent(b.input) || isObj(b.input)))
|
|
94
|
+
return { error: `${at} must be a tool_use block with an id, a name and an object input` };
|
|
95
|
+
names.set(b.id, b.name);
|
|
96
|
+
calls.push({ id: b.id, function: { name: b.name, arguments: isObj(b.input) ? b.input : {} } });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { role: 'assistant', content: texts.join('\n\n'), ...(calls.length ? { tool_calls: calls } : {}) };
|
|
100
|
+
}
|
|
101
|
+
function toolSchemas(tools) {
|
|
102
|
+
if (!Array.isArray(tools))
|
|
103
|
+
return { error: 'tools must be an array' };
|
|
104
|
+
const out = [];
|
|
105
|
+
for (const [i, t] of tools.entries()) {
|
|
106
|
+
if (!isObj(t))
|
|
107
|
+
return { error: `tools.${i} must be an object` };
|
|
108
|
+
// Server tools (web search, code execution, ...) run at Anthropic; the tab has none.
|
|
109
|
+
if (!absent(t.type) && t.type !== 'custom')
|
|
110
|
+
continue;
|
|
111
|
+
if (!isStr(t.name) || !t.name)
|
|
112
|
+
return { error: `tools.${i}.name must be a non-empty string` };
|
|
113
|
+
if (!absent(t.description) && !isStr(t.description))
|
|
114
|
+
return { error: `tools.${i}.description must be a string` };
|
|
115
|
+
if (!absent(t.input_schema) && !isObj(t.input_schema))
|
|
116
|
+
return { error: `tools.${i}.input_schema must be an object` };
|
|
117
|
+
out.push({
|
|
118
|
+
type: 'function',
|
|
119
|
+
function: {
|
|
120
|
+
name: t.name,
|
|
121
|
+
description: isStr(t.description) ? t.description : '',
|
|
122
|
+
parameters: isObj(t.input_schema) ? t.input_schema : { type: 'object', properties: {} },
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
/** A Messages API request as the tab's `chat`; the error names the field that is wrong. */
|
|
129
|
+
export function toChatInput(body) {
|
|
130
|
+
if (!isObj(body))
|
|
131
|
+
return { error: 'the body must be a JSON object' };
|
|
132
|
+
if (!Array.isArray(body.messages) || !body.messages.length)
|
|
133
|
+
return { error: 'messages must be a non-empty array' };
|
|
134
|
+
const messages = [];
|
|
135
|
+
const system = systemText(body.system);
|
|
136
|
+
if (!isStr(system))
|
|
137
|
+
return system;
|
|
138
|
+
if (system)
|
|
139
|
+
messages.push({ role: 'system', content: system });
|
|
140
|
+
// A tool result names its call only by id; the tab wants the tool's name.
|
|
141
|
+
const names = new Map();
|
|
142
|
+
for (const [i, m] of body.messages.entries()) {
|
|
143
|
+
const path = `messages.${i}`;
|
|
144
|
+
if (!isObj(m))
|
|
145
|
+
return { error: `${path} must be an object` };
|
|
146
|
+
if (m.role !== 'user' && m.role !== 'assistant' && m.role !== 'system')
|
|
147
|
+
return { error: `${path}.role must be "user", "assistant" or "system", not ${JSON.stringify(m.role)}` };
|
|
148
|
+
if (!isStr(m.content) && !Array.isArray(m.content))
|
|
149
|
+
return { error: `${path}.content must be a string or an array of content blocks` };
|
|
150
|
+
// Chat templates take a system message only at the start (Qwen's raises otherwise).
|
|
151
|
+
if (m.role === 'system') {
|
|
152
|
+
const text = isStr(m.content) ? m.content : blocksText(m.content, `${path}.content`);
|
|
153
|
+
if (!isStr(text))
|
|
154
|
+
return text;
|
|
155
|
+
messages.push({ role: 'user', content: text });
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (isStr(m.content)) {
|
|
159
|
+
messages.push({ role: m.role, content: m.content });
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const out = m.role === 'user'
|
|
163
|
+
? userMessages(m.content, `${path}.content`, names)
|
|
164
|
+
: assistantMessage(m.content, `${path}.content`, names);
|
|
165
|
+
if ('error' in out)
|
|
166
|
+
return out;
|
|
167
|
+
messages.push(...(Array.isArray(out) ? out : [out]));
|
|
168
|
+
}
|
|
169
|
+
const input = { messages };
|
|
170
|
+
const choice = body.tool_choice;
|
|
171
|
+
if (!absent(body.tools) && !(isObj(choice) && choice.type === 'none')) {
|
|
172
|
+
const tools = toolSchemas(body.tools);
|
|
173
|
+
if ('error' in tools)
|
|
174
|
+
return tools;
|
|
175
|
+
if (tools.length)
|
|
176
|
+
input.tools = tools;
|
|
177
|
+
}
|
|
178
|
+
if (!absent(body.max_tokens)) {
|
|
179
|
+
if (!Number.isInteger(body.max_tokens) || body.max_tokens < 1)
|
|
180
|
+
return { error: 'max_tokens must be a positive integer' };
|
|
181
|
+
input.maxTokens = body.max_tokens;
|
|
182
|
+
}
|
|
183
|
+
if (!absent(body.temperature)) {
|
|
184
|
+
const t = body.temperature;
|
|
185
|
+
if (typeof t !== 'number' || !Number.isFinite(t) || t < 0)
|
|
186
|
+
return { error: 'temperature must be a number of at least 0' };
|
|
187
|
+
input.temperature = t;
|
|
188
|
+
}
|
|
189
|
+
let stopSequences = [];
|
|
190
|
+
if (!absent(body.stop_sequences)) {
|
|
191
|
+
if (!Array.isArray(body.stop_sequences) || !body.stop_sequences.every(isStr))
|
|
192
|
+
return { error: 'stop_sequences must be an array of strings' };
|
|
193
|
+
stopSequences = body.stop_sequences.filter((s) => s.length > 0);
|
|
194
|
+
}
|
|
195
|
+
return { input, stream: body.stream === true, stopSequences };
|
|
196
|
+
}
|
|
197
|
+
/** Rough prompt size without a tokenizer: `ceil(chars / 3.5)` over messages, calls and tools. */
|
|
198
|
+
export function estimateTokens(input) {
|
|
199
|
+
let chars = 0;
|
|
200
|
+
for (const m of input.messages) {
|
|
201
|
+
chars += m.content.length + (m.name?.length ?? 0);
|
|
202
|
+
for (const c of m.tool_calls ?? [])
|
|
203
|
+
chars += c.function.name.length + JSON.stringify(c.function.arguments).length;
|
|
204
|
+
}
|
|
205
|
+
for (const { function: f } of input.tools ?? [])
|
|
206
|
+
chars += f.name.length + f.description.length + JSON.stringify(f.parameters).length;
|
|
207
|
+
return Math.ceil(chars / 3.5);
|
|
208
|
+
}
|
|
209
|
+
/** The wording Claude Code reacts to by compacting the conversation. */
|
|
210
|
+
export const tooLong = (tokens, max) => `prompt is too long: ${tokens} tokens > ${max} maximum`;
|
|
211
|
+
// The RebeLLM tab's wording when a prompt does not fit its context.
|
|
212
|
+
const TAB_TOO_LONG = /^The prompt needs (\d+) tokens; the tab's context holds (\d+)/;
|
|
213
|
+
/** A failed chat as an API error; the tab's "prompt does not fit" becomes Claude Code's "too long". */
|
|
214
|
+
export function tabError(message) {
|
|
215
|
+
const m = TAB_TOO_LONG.exec(message);
|
|
216
|
+
return m
|
|
217
|
+
? { type: 'invalid_request_error', message: tooLong(Number(m[1]), Number(m[2])) }
|
|
218
|
+
: { type: 'api_error', message };
|
|
219
|
+
}
|
|
220
|
+
export function stopReason(stop, calls) {
|
|
221
|
+
if (calls || stop === 'tool_call')
|
|
222
|
+
return 'tool_use';
|
|
223
|
+
return stop === 'length' ? 'max_tokens' : 'end_turn';
|
|
224
|
+
}
|
|
225
|
+
export const usage = (input, output) => ({
|
|
226
|
+
input_tokens: input,
|
|
227
|
+
output_tokens: output,
|
|
228
|
+
cache_creation_input_tokens: 0,
|
|
229
|
+
cache_read_input_tokens: 0,
|
|
230
|
+
});
|
|
231
|
+
export const tabUsage = (u) => usage(u.prompt, u.completion);
|
|
232
|
+
export const toolUse = (c) => ({
|
|
233
|
+
type: 'tool_use',
|
|
234
|
+
id: c.id ?? `toolu_${newId()}`,
|
|
235
|
+
name: c.function.name,
|
|
236
|
+
input: c.function.arguments,
|
|
237
|
+
});
|
|
238
|
+
/** The content of an answer: its text (always, when there are no calls), then its tool calls. */
|
|
239
|
+
export const content = (text, calls) => [
|
|
240
|
+
...(text || !calls.length ? [{ type: 'text', text }] : []),
|
|
241
|
+
...calls,
|
|
242
|
+
];
|
|
243
|
+
export function message(meta, blocks, stop, u) {
|
|
244
|
+
return {
|
|
245
|
+
id: meta.id,
|
|
246
|
+
type: 'message',
|
|
247
|
+
role: 'assistant',
|
|
248
|
+
model: meta.model,
|
|
249
|
+
content: blocks,
|
|
250
|
+
stop_reason: stop.reason,
|
|
251
|
+
stop_sequence: stop.sequence,
|
|
252
|
+
usage: u,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { type TabLink } from '../tab.js';
|
|
3
|
+
import type { ErrorType } from './types.js';
|
|
4
|
+
/** The Messages API sends a ping about this often; clients expect something within a minute. */
|
|
5
|
+
export declare const PING_MS = 10000;
|
|
6
|
+
export interface MessagesOptions {
|
|
7
|
+
/** How long a request waits for a tab with a ready model. */
|
|
8
|
+
waitMs: number;
|
|
9
|
+
pingMs?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Anthropic's error shape, the only one its SDKs (and Claude Code) read. */
|
|
12
|
+
export declare function sendApiError(res: ServerResponse, status: number, type: ErrorType, message: string): void;
|
|
13
|
+
export declare const isMessagesPath: (path: string) => boolean;
|
|
14
|
+
/** `POST /v1/messages` and `POST /v1/messages/count_tokens` for Anthropic clients such as Claude Code. */
|
|
15
|
+
export declare function messagesRoutes(tab: TabLink, o: MessagesOptions): (req: IncomingMessage, res: ServerResponse) => void;
|