@arhan-w/ibex 0.0.0-stage → 3.6.1
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 +21 -0
- package/README.md +306 -2
- package/npm-package/LICENSE +21 -0
- package/npm-package/README.md +178 -0
- package/npm-package/bin/goat.js +3 -0
- package/npm-package/bin/ibex.js +78 -0
- package/npm-package/package.json +58 -0
- package/npm-package/scripts/install-binary.js +168 -0
- package/package.json +69 -6
- package/src/agent.ts +695 -0
- package/src/agents/loader.ts +110 -0
- package/src/ambient.d.ts +2 -0
- package/src/code/extract.ts +292 -0
- package/src/code/find.ts +244 -0
- package/src/code/grammars.ts +88 -0
- package/src/code/indexer.ts +242 -0
- package/src/code/semantic.ts +253 -0
- package/src/code/slash.ts +88 -0
- package/src/code/tool.ts +40 -0
- package/src/collab/client.ts +141 -0
- package/src/collab/handlers.ts +141 -0
- package/src/collab/invite.ts +39 -0
- package/src/collab/relay.ts +106 -0
- package/src/collab/sync.ts +131 -0
- package/src/commands.tsx +943 -0
- package/src/computer.ts +629 -0
- package/src/config.ts +318 -0
- package/src/constants.ts +18 -0
- package/src/context.ts +73 -0
- package/src/data/providers.json +2342 -0
- package/src/diff.ts +50 -0
- package/src/doctor.ts +443 -0
- package/src/errors.ts +139 -0
- package/src/gflash.ts +170 -0
- package/src/hooks.ts +133 -0
- package/src/ide/assets.gen.ts +3 -0
- package/src/ide/index.html +844 -0
- package/src/ide/server.ts +506 -0
- package/src/ide/vendor/marked.umd.js +80 -0
- package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
- package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
- package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
- package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
- package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
- package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
- package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
- package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
- package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
- package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
- package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
- package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
- package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
- package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
- package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
- package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
- package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
- package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
- package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
- package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
- package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
- package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
- package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
- package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
- package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
- package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
- package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
- package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
- package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
- package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
- package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
- package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
- package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
- package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
- package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
- package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
- package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
- package/src/ide/vendor/vs/editor/editor.main.css +8 -0
- package/src/ide/vendor/vs/editor/editor.main.js +798 -0
- package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
- package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
- package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
- package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
- package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
- package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
- package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
- package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
- package/src/ide/vendor/vs/loader.js +11 -0
- package/src/index-shared.ts +117 -0
- package/src/index.ts +586 -0
- package/src/llm.ts +721 -0
- package/src/logger.ts +39 -0
- package/src/mcp/client.ts +121 -0
- package/src/mcp/types.ts +27 -0
- package/src/oauth.ts +205 -0
- package/src/onboarding.ts +140 -0
- package/src/palette.tsx +199 -0
- package/src/permissions.ts +123 -0
- package/src/plugins/loader.ts +120 -0
- package/src/plugins/marketplace.ts +252 -0
- package/src/plugins/sandbox.ts +303 -0
- package/src/plugins/tar.ts +241 -0
- package/src/pricing.ts +78 -0
- package/src/protocol/client.ts +102 -0
- package/src/protocol/rpc.ts +43 -0
- package/src/protocol/serve.ts +136 -0
- package/src/providers.ts +402 -0
- package/src/rate-limiter.ts +101 -0
- package/src/refs.ts +97 -0
- package/src/runtime.ts +144 -0
- package/src/session.ts +401 -0
- package/src/skills/loader.ts +136 -0
- package/src/statusline.ts +70 -0
- package/src/system-prompt.ts +28 -0
- package/src/tools.ts +1280 -0
- package/src/tui.tsx +1355 -0
- package/src/update.ts +236 -0
- package/src/vendor/flashServer.ts +2 -0
- package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
- package/src/virtual-list.tsx +125 -0
- package/src/window.ts +31 -0
- package/tsconfig.json +16 -0
package/src/llm.ts
ADDED
|
@@ -0,0 +1,721 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming chat clients for the four wire formats:
|
|
3
|
+
* openai POST /chat/completions (SSE)
|
|
4
|
+
* claude POST /messages (SSE, x-api-key or bearer)
|
|
5
|
+
* openai-responses POST /responses (SSE)
|
|
6
|
+
* gemini :streamGenerateContent (SSE; cloudcode-pa OAuth shape)
|
|
7
|
+
*
|
|
8
|
+
* All yield the same StreamEvent shape so the agent loop is model-agnostic.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { PROVIDER_RATE_LIMITS } from "./providers.ts";
|
|
12
|
+
import { GOATED_FLASH_ID } from "./gflash.ts";
|
|
13
|
+
import { TokenBucketRateLimiter, RateLimiterRegistry, type RateLimiterConfig } from "./rate-limiter.ts";
|
|
14
|
+
|
|
15
|
+
export interface ToolSpec {
|
|
16
|
+
name: string;
|
|
17
|
+
description: string;
|
|
18
|
+
parameters: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ToolCall {
|
|
22
|
+
id: string;
|
|
23
|
+
name: string;
|
|
24
|
+
arguments: Record<string, unknown>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Wire-agnostic multimodal content part. Image data is base64 (no prefix). */
|
|
28
|
+
export type ContentPart =
|
|
29
|
+
| { type: "text"; text: string }
|
|
30
|
+
| { type: "image"; data: string; mediaType: string };
|
|
31
|
+
|
|
32
|
+
export interface Message {
|
|
33
|
+
role: "system" | "user" | "assistant" | "tool";
|
|
34
|
+
content: string | ContentPart[];
|
|
35
|
+
toolCalls?: ToolCall[];
|
|
36
|
+
toolCallId?: string;
|
|
37
|
+
name?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function partsOf(content: string | ContentPart[]): ContentPart[] {
|
|
41
|
+
return typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Plain-text projection (for digests, size math, transcript display). */
|
|
45
|
+
export function textOf(content: string | ContentPart[]): string {
|
|
46
|
+
if (typeof content === "string") return content;
|
|
47
|
+
return content.map((p) => (p.type === "text" ? p.text : "[image]")).join("\n");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function hasImages(content: string | ContentPart[]): boolean {
|
|
51
|
+
return typeof content !== "string" && content.some((p) => p.type === "image");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Rough wire-cost length of a message: text length + ~1.5x base64 image payload. */
|
|
55
|
+
export function contentChars(content: string | ContentPart[]): number {
|
|
56
|
+
if (typeof content === "string") return content.length;
|
|
57
|
+
return content.reduce((s, p) => s + (p.type === "text" ? p.text.length : Math.ceil(p.data.length * 1.5)), 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Token estimate, much closer to reality than chars/4: prose ~4 chars/token,
|
|
62
|
+
* code ~3.2 (lots of punctuation), CJK ~1.5 (near 1 token per char). Images
|
|
63
|
+
* are ~1.5k tokens per 768px side regardless of bytes; we approximate with
|
|
64
|
+
* payload size. Only used for display/compaction heuristics, never billing.
|
|
65
|
+
*/
|
|
66
|
+
export function estimateTokens(content: string | ContentPart[]): number {
|
|
67
|
+
if (typeof content === "string") return textTokens(content);
|
|
68
|
+
return content.reduce(
|
|
69
|
+
(s, p) => s + (p.type === "text" ? textTokens(p.text) : Math.max(85, Math.round(p.data.length / 350))),
|
|
70
|
+
0,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function textTokens(t: string): number {
|
|
75
|
+
if (!t) return 0;
|
|
76
|
+
let cjk = 0;
|
|
77
|
+
// count CJK + Hangul + Kana codepoints; they cost ~1-1.5 tokens per char
|
|
78
|
+
for (let i = 0; i < t.length; i++) {
|
|
79
|
+
const c = t.charCodeAt(i);
|
|
80
|
+
if ((c >= 0x3040 && c <= 0x30ff) || (c >= 0x4e00 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af)) cjk++;
|
|
81
|
+
}
|
|
82
|
+
const rest = t.length - cjk;
|
|
83
|
+
// code-ish content densifies tokens: punctuation/indent ratio nudges the divisor down
|
|
84
|
+
const punct = (t.match(/[{}()\[\]<>=;:,.#*_|\\&^%$@"'`]/g) ?? []).length;
|
|
85
|
+
const divisor = punct / Math.max(rest, 1) > 0.08 ? 3.2 : 4.0;
|
|
86
|
+
return Math.ceil(cjk * 1.4 + rest / divisor);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface StreamEvent {
|
|
90
|
+
textDelta?: string;
|
|
91
|
+
thinkingDelta?: string;
|
|
92
|
+
toolCalls?: ToolCall[];
|
|
93
|
+
usage?: { prompt: number; completion: number; cacheRead?: number; cacheWrite?: number };
|
|
94
|
+
error?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export class LLMError extends Error {
|
|
98
|
+
/** HTTP status when the failure came from a response, else undefined. */
|
|
99
|
+
status?: number;
|
|
100
|
+
/** Seconds parsed from a retry-after header, when the server sent one. */
|
|
101
|
+
retryAfterSec?: number;
|
|
102
|
+
constructor(message: string, opts?: { status?: number; retryAfterSec?: number }) {
|
|
103
|
+
super(message);
|
|
104
|
+
this.name = "LLMError";
|
|
105
|
+
this.status = opts?.status;
|
|
106
|
+
this.retryAfterSec = opts?.retryAfterSec;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const RETRYABLE_STATUS = new Set([408, 409, 425, 429, 500, 502, 503, 504]);
|
|
111
|
+
const NETWORK_HINTS = ["fetch failed", "enotfound", "eai_again", "etimedout", "econnreset", "econnrefused", "socket hang up", "network", "timed out", "terminated"];
|
|
112
|
+
|
|
113
|
+
/** Transient enough to retry: 429/5xx, or a network-level failure. User aborts are never retryable. */
|
|
114
|
+
export function isRetryableLLMError(e: unknown): boolean {
|
|
115
|
+
if (!e || typeof e !== "object") return false;
|
|
116
|
+
const err = e as { name?: string; message?: string; status?: number };
|
|
117
|
+
if (err.name === "AbortError") return false;
|
|
118
|
+
if (typeof err.status === "number") return RETRYABLE_STATUS.has(err.status);
|
|
119
|
+
const msg = String(err.message ?? "").toLowerCase();
|
|
120
|
+
return NETWORK_HINTS.some((h) => msg.includes(h));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function retryAfterSeconds(res: Response): number | undefined {
|
|
124
|
+
const v = res.headers.get("retry-after");
|
|
125
|
+
if (!v) return undefined;
|
|
126
|
+
const secs = Number(v);
|
|
127
|
+
if (Number.isFinite(secs)) return Math.max(0, secs);
|
|
128
|
+
const date = Date.parse(v);
|
|
129
|
+
return Number.isNaN(date) ? undefined : Math.max(0, (date - Date.now()) / 1000);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface StreamOpts {
|
|
133
|
+
model: string;
|
|
134
|
+
maxTokens: number;
|
|
135
|
+
temperature?: number | null;
|
|
136
|
+
signal?: AbortSignal;
|
|
137
|
+
/** Anthropic prompt caching: cache system+tools (ephemeral). Ignored by other formats. */
|
|
138
|
+
cache?: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface ChatClient {
|
|
142
|
+
streamChat(messages: Message[], tools: ToolSpec[], opts: StreamOpts): AsyncGenerator<StreamEvent>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------- SSE plumbing ----------
|
|
146
|
+
|
|
147
|
+
/** Split an SSE response body into `data:` payload lines. Line-based and
|
|
148
|
+
* backpressure-safe: never buffers whole events past their newline, so a
|
|
149
|
+
* provider that streams slowly still delivers deltas immediately and a
|
|
150
|
+
* provider that closes early can never wedge the reader. */
|
|
151
|
+
async function* sseLines(response: Response): AsyncGenerator<string> {
|
|
152
|
+
const reader = response.body?.getReader();
|
|
153
|
+
if (!reader) return;
|
|
154
|
+
const decoder = new TextDecoder();
|
|
155
|
+
let buf = "";
|
|
156
|
+
try {
|
|
157
|
+
for (;;) {
|
|
158
|
+
const { done, value } = await reader.read();
|
|
159
|
+
if (done) break;
|
|
160
|
+
buf += decoder.decode(value, { stream: true });
|
|
161
|
+
let idx: number;
|
|
162
|
+
while ((idx = buf.indexOf("\n")) >= 0) {
|
|
163
|
+
const line = buf.slice(0, idx).replace(/\r$/, "");
|
|
164
|
+
buf = buf.slice(idx + 1);
|
|
165
|
+
if (line.startsWith("data:")) yield line.slice(5).trim();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
buf += decoder.decode();
|
|
169
|
+
if (buf.startsWith("data:")) yield buf.slice(5).trim();
|
|
170
|
+
} finally {
|
|
171
|
+
reader.releaseLock();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function postJson(
|
|
176
|
+
url: string, headers: Record<string, string>, body: unknown, signal?: AbortSignal,
|
|
177
|
+
): Promise<Response> {
|
|
178
|
+
let res: Response;
|
|
179
|
+
try {
|
|
180
|
+
res = await fetch(url, {
|
|
181
|
+
method: "POST",
|
|
182
|
+
headers: { "content-type": "application/json", ...headers },
|
|
183
|
+
body: JSON.stringify(body),
|
|
184
|
+
signal,
|
|
185
|
+
});
|
|
186
|
+
} catch (e: any) {
|
|
187
|
+
throw new LLMError(`${e?.name ?? "network"}: ${e?.message ?? e}`);
|
|
188
|
+
}
|
|
189
|
+
if (!res.ok) {
|
|
190
|
+
const text = await res.text().catch(() => "");
|
|
191
|
+
throw new LLMError(`HTTP ${res.status}: ${text.slice(0, 600)}`, {
|
|
192
|
+
status: res.status, retryAfterSec: retryAfterSeconds(res),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return res;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function safeParse(s: string): any {
|
|
199
|
+
try { return JSON.parse(s); } catch { return null; }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function finishToolCalls(partial: Map<number, { id: string; name: string; args: string }>): ToolCall[] {
|
|
203
|
+
const calls: ToolCall[] = [];
|
|
204
|
+
for (const [, p] of [...partial.entries()].sort((a, b) => a[0] - b[0])) {
|
|
205
|
+
if (!p.name) continue;
|
|
206
|
+
let args: Record<string, unknown> = {};
|
|
207
|
+
try { args = p.args ? JSON.parse(p.args) : {}; } catch { args = { _raw: p.args }; }
|
|
208
|
+
calls.push({ id: p.id || `call_${calls.length}`, name: p.name, arguments: args });
|
|
209
|
+
}
|
|
210
|
+
return calls;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---------- OpenAI chat completions ----------
|
|
214
|
+
|
|
215
|
+
export class OpenAIChatClient implements ChatClient {
|
|
216
|
+
constructor(
|
|
217
|
+
private baseUrl: string,
|
|
218
|
+
private apiKey?: string,
|
|
219
|
+
private extraHeaders?: Record<string, string>,
|
|
220
|
+
) {}
|
|
221
|
+
|
|
222
|
+
private headers(): Record<string, string> {
|
|
223
|
+
return { authorization: `Bearer ${this.apiKey ?? ""}`, ...(this.extraHeaders ?? {}) };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async *streamChat(messages: Message[], tools: ToolSpec[], opts: StreamOpts): AsyncGenerator<StreamEvent> {
|
|
227
|
+
const payload: any = {
|
|
228
|
+
model: opts.model,
|
|
229
|
+
max_tokens: opts.maxTokens,
|
|
230
|
+
stream: true,
|
|
231
|
+
stream_options: { include_usage: true },
|
|
232
|
+
messages: messages.flatMap((m): any[] => {
|
|
233
|
+
if (m.role === "system") return [{ role: "system", content: textOf(m.content) }];
|
|
234
|
+
if (m.role === "tool")
|
|
235
|
+
return [{ role: "tool", tool_call_id: m.toolCallId, content: textOf(m.content) }];
|
|
236
|
+
if (m.role === "assistant" && m.toolCalls?.length)
|
|
237
|
+
return [{
|
|
238
|
+
role: "assistant", content: textOf(m.content) || null,
|
|
239
|
+
tool_calls: m.toolCalls.map((tc) => ({
|
|
240
|
+
id: tc.id, type: "function",
|
|
241
|
+
function: { name: tc.name, arguments: JSON.stringify(tc.arguments) },
|
|
242
|
+
})),
|
|
243
|
+
}];
|
|
244
|
+
if (m.role === "user" && typeof m.content !== "string") {
|
|
245
|
+
return [{
|
|
246
|
+
role: "user",
|
|
247
|
+
content: m.content.map((p) => p.type === "text"
|
|
248
|
+
? { type: "text", text: p.text }
|
|
249
|
+
: { type: "image_url", image_url: { url: `data:${p.mediaType};base64,${p.data}` } }),
|
|
250
|
+
}];
|
|
251
|
+
}
|
|
252
|
+
return [{ role: m.role, content: m.content }];
|
|
253
|
+
}),
|
|
254
|
+
};
|
|
255
|
+
if (opts.temperature != null) payload.temperature = opts.temperature;
|
|
256
|
+
if (tools.length)
|
|
257
|
+
payload.tools = tools.map((t) => ({
|
|
258
|
+
type: "function",
|
|
259
|
+
function: { name: t.name, description: t.description, parameters: t.parameters },
|
|
260
|
+
}));
|
|
261
|
+
|
|
262
|
+
const res = await postJson(`${this.baseUrl}/chat/completions`, this.headers(), payload, opts.signal);
|
|
263
|
+
const partial = new Map<number, { id: string; name: string; args: string }>();
|
|
264
|
+
let emittedTools = false;
|
|
265
|
+
for await (const data of sseLines(res)) {
|
|
266
|
+
if (data === "[DONE]") break;
|
|
267
|
+
const obj = safeParse(data);
|
|
268
|
+
if (!obj) continue;
|
|
269
|
+
const choice = obj.choices?.[0];
|
|
270
|
+
const delta = choice?.delta;
|
|
271
|
+
if (delta?.content) yield { textDelta: delta.content };
|
|
272
|
+
for (const tc of delta?.tool_calls ?? []) {
|
|
273
|
+
const idx = tc.index ?? 0;
|
|
274
|
+
const cur = partial.get(idx) ?? { id: "", name: "", args: "" };
|
|
275
|
+
if (tc.id) cur.id = tc.id;
|
|
276
|
+
if (tc.function?.name) cur.name += tc.function.name;
|
|
277
|
+
if (tc.function?.arguments) cur.args += tc.function.arguments;
|
|
278
|
+
partial.set(idx, cur);
|
|
279
|
+
}
|
|
280
|
+
if (obj.usage)
|
|
281
|
+
yield { usage: { prompt: obj.usage.prompt_tokens ?? 0, completion: obj.usage.completion_tokens ?? 0 } };
|
|
282
|
+
if (choice?.finish_reason === "tool_calls" || choice?.finish_reason === "stop") {
|
|
283
|
+
if (partial.size && !emittedTools) {
|
|
284
|
+
emittedTools = true;
|
|
285
|
+
yield { toolCalls: finishToolCalls(partial) };
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (partial.size && !emittedTools) {
|
|
290
|
+
yield { toolCalls: finishToolCalls(partial) };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// ---------- Anthropic messages ----------
|
|
296
|
+
|
|
297
|
+
export class AnthropicClient implements ChatClient {
|
|
298
|
+
constructor(
|
|
299
|
+
private baseUrl: string,
|
|
300
|
+
private apiKey?: string,
|
|
301
|
+
private authToken?: string,
|
|
302
|
+
private extraHeaders?: Record<string, string>,
|
|
303
|
+
) {}
|
|
304
|
+
|
|
305
|
+
private headers(): Record<string, string> {
|
|
306
|
+
const base: Record<string, string> = { "anthropic-version": "2023-06-01" };
|
|
307
|
+
if (this.authToken) {
|
|
308
|
+
base.authorization = `Bearer ${this.authToken}`;
|
|
309
|
+
base["anthropic-beta"] = "oauth-2025-04-20";
|
|
310
|
+
} else {
|
|
311
|
+
base["x-api-key"] = this.apiKey ?? "";
|
|
312
|
+
}
|
|
313
|
+
return { ...base, ...(this.extraHeaders ?? {}) };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** System messages concatenate; consecutive tool results merge into ONE
|
|
317
|
+
* user turn (parallel tool calls); strict role alternation otherwise. */
|
|
318
|
+
static systemAndMessages(messages: Message[]): { system: string; msgs: any[] } {
|
|
319
|
+
let system = "";
|
|
320
|
+
const msgs: any[] = [];
|
|
321
|
+
for (const m of messages) {
|
|
322
|
+
if (m.role === "system") { system += (system ? "\n\n" : "") + textOf(m.content); continue; }
|
|
323
|
+
if (m.role === "tool") {
|
|
324
|
+
// tool_result content: text stays a string; multimodal blocks pass through
|
|
325
|
+
// (Anthropic renders images inside tool_result natively)
|
|
326
|
+
const block: any = { type: "tool_result", tool_use_id: m.toolCallId };
|
|
327
|
+
if (typeof m.content === "string") block.content = m.content;
|
|
328
|
+
else block.content = m.content.map((p) => p.type === "text"
|
|
329
|
+
? { type: "text", text: p.text }
|
|
330
|
+
: { type: "image", source: { type: "base64", media_type: p.mediaType, data: p.data } });
|
|
331
|
+
const last = msgs[msgs.length - 1];
|
|
332
|
+
if (last?.role === "user" && Array.isArray(last.content) &&
|
|
333
|
+
last.content.every((b: any) => b.type === "tool_result"))
|
|
334
|
+
last.content.push(block);
|
|
335
|
+
else msgs.push({ role: "user", content: [block] });
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
if (m.role === "assistant") {
|
|
339
|
+
const content: any[] = [];
|
|
340
|
+
if (m.content) content.push({ type: "text", text: textOf(m.content) });
|
|
341
|
+
for (const tc of m.toolCalls ?? [])
|
|
342
|
+
content.push({ type: "tool_use", id: tc.id, name: tc.name, input: tc.arguments });
|
|
343
|
+
if (content.length) msgs.push({ role: "assistant", content });
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (typeof m.content !== "string") {
|
|
347
|
+
msgs.push({
|
|
348
|
+
role: "user",
|
|
349
|
+
content: m.content.map((p) => p.type === "text"
|
|
350
|
+
? { type: "text", text: p.text }
|
|
351
|
+
: { type: "image", source: { type: "base64", media_type: p.mediaType, data: p.data } }),
|
|
352
|
+
});
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
msgs.push({ role: "user", content: m.content });
|
|
356
|
+
}
|
|
357
|
+
return { system, msgs };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Build the /messages request body. Static + pure so tests can assert
|
|
361
|
+
* the prompt-caching shape without a network. */
|
|
362
|
+
static buildPayload(system: string, msgs: any[], tools: ToolSpec[], opts: StreamOpts): any {
|
|
363
|
+
const payload: any = {
|
|
364
|
+
model: opts.model, max_tokens: opts.maxTokens, stream: true, messages: msgs,
|
|
365
|
+
};
|
|
366
|
+
if (system) {
|
|
367
|
+
payload.system = opts.cache
|
|
368
|
+
? [{ type: "text", text: system, cache_control: { type: "ephemeral" } }]
|
|
369
|
+
: system;
|
|
370
|
+
}
|
|
371
|
+
if (opts.temperature != null) payload.temperature = opts.temperature;
|
|
372
|
+
if (tools.length) {
|
|
373
|
+
const list: any[] = tools.map((t) => ({
|
|
374
|
+
name: t.name, description: t.description, input_schema: t.parameters,
|
|
375
|
+
}));
|
|
376
|
+
// cache_control on the LAST tool marks the whole tools block cacheable
|
|
377
|
+
if (opts.cache) list[list.length - 1].cache_control = { type: "ephemeral" };
|
|
378
|
+
payload.tools = list;
|
|
379
|
+
}
|
|
380
|
+
return payload;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async *streamChat(messages: Message[], tools: ToolSpec[], opts: StreamOpts): AsyncGenerator<StreamEvent> {
|
|
384
|
+
const { system, msgs } = AnthropicClient.systemAndMessages(messages);
|
|
385
|
+
const payload = AnthropicClient.buildPayload(system, msgs, tools, opts);
|
|
386
|
+
|
|
387
|
+
const res = await postJson(`${this.baseUrl}/messages`, this.headers(), payload, opts.signal);
|
|
388
|
+
const toolBuf = new Map<number, { id: string; name: string; json: string }>();
|
|
389
|
+
const cacheTok = { read: 0, write: 0 };
|
|
390
|
+
let blockType = "";
|
|
391
|
+
for await (const data of sseLines(res)) {
|
|
392
|
+
const obj = safeParse(data);
|
|
393
|
+
if (!obj) continue;
|
|
394
|
+
switch (obj.type) {
|
|
395
|
+
case "message_start": {
|
|
396
|
+
// cache token counts ride on message_start usage; merge them into the
|
|
397
|
+
// single authoritative usage event at message_delta (never double-yield)
|
|
398
|
+
const u = obj.message?.usage;
|
|
399
|
+
if (u) {
|
|
400
|
+
cacheTok.read = u.cache_read_input_tokens ?? 0;
|
|
401
|
+
cacheTok.write = u.cache_creation_input_tokens ?? 0;
|
|
402
|
+
}
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
case "content_block_start":
|
|
406
|
+
blockType = obj.content_block?.type ?? "";
|
|
407
|
+
if (blockType === "tool_use")
|
|
408
|
+
toolBuf.set(obj.index, { id: obj.content_block.id, name: obj.content_block.name, json: "" });
|
|
409
|
+
break;
|
|
410
|
+
case "content_block_delta": {
|
|
411
|
+
const d = obj.delta;
|
|
412
|
+
if (d?.type === "text_delta") yield { textDelta: d.text };
|
|
413
|
+
else if (d?.type === "thinking_delta") yield { thinkingDelta: d.thinking };
|
|
414
|
+
else if (d?.type === "input_json_delta" && toolBuf.has(obj.index))
|
|
415
|
+
toolBuf.get(obj.index)!.json += d.partial_json;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
case "message_delta":
|
|
419
|
+
if (obj.usage)
|
|
420
|
+
yield { usage: {
|
|
421
|
+
prompt: obj.usage.input_tokens ?? 0,
|
|
422
|
+
completion: obj.usage.output_tokens ?? 0,
|
|
423
|
+
...(cacheTok.read || cacheTok.write
|
|
424
|
+
? { cacheRead: cacheTok.read, cacheWrite: cacheTok.write }
|
|
425
|
+
: {}),
|
|
426
|
+
} };
|
|
427
|
+
break;
|
|
428
|
+
case "message_stop": {
|
|
429
|
+
if (toolBuf.size) {
|
|
430
|
+
const calls: ToolCall[] = [];
|
|
431
|
+
for (const [, t] of [...toolBuf.entries()].sort((a, b) => a[0] - b[0])) {
|
|
432
|
+
let args: Record<string, unknown> = {};
|
|
433
|
+
try { args = t.json ? JSON.parse(t.json) : {}; } catch { args = { _raw: t.json }; }
|
|
434
|
+
calls.push({ id: t.id, name: t.name, arguments: args });
|
|
435
|
+
}
|
|
436
|
+
yield { toolCalls: calls };
|
|
437
|
+
}
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
case "error":
|
|
441
|
+
yield { error: obj.error?.message ?? "anthropic stream error" };
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// ---------- OpenAI Responses ----------
|
|
449
|
+
|
|
450
|
+
export class OpenAIResponsesClient implements ChatClient {
|
|
451
|
+
constructor(
|
|
452
|
+
private baseUrl: string,
|
|
453
|
+
private apiKey?: string,
|
|
454
|
+
private authToken?: string,
|
|
455
|
+
private extraHeaders?: Record<string, string>,
|
|
456
|
+
) {}
|
|
457
|
+
|
|
458
|
+
private headers(): Record<string, string> {
|
|
459
|
+
const auth = this.authToken
|
|
460
|
+
? { authorization: `Bearer ${this.authToken}` }
|
|
461
|
+
: { authorization: `Bearer ${this.apiKey ?? ""}` };
|
|
462
|
+
return { ...auth, ...(this.extraHeaders ?? {}) };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async *streamChat(messages: Message[], tools: ToolSpec[], opts: StreamOpts): AsyncGenerator<StreamEvent> {
|
|
466
|
+
const input: any[] = [];
|
|
467
|
+
let instructions = "";
|
|
468
|
+
for (const m of messages) {
|
|
469
|
+
if (m.role === "system") { instructions += (instructions ? "\n\n" : "") + textOf(m.content); continue; }
|
|
470
|
+
if (m.role === "tool") {
|
|
471
|
+
input.push({ type: "function_call_output", call_id: m.toolCallId, output: textOf(m.content) });
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (m.role === "assistant" && m.toolCalls?.length) {
|
|
475
|
+
const t = textOf(m.content);
|
|
476
|
+
if (t) input.push({ role: "assistant", content: t });
|
|
477
|
+
for (const tc of m.toolCalls)
|
|
478
|
+
input.push({ type: "function_call", call_id: tc.id, name: tc.name, arguments: JSON.stringify(tc.arguments) });
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (m.role === "user" && typeof m.content !== "string") {
|
|
482
|
+
input.push({
|
|
483
|
+
role: "user",
|
|
484
|
+
content: m.content.map((p) => p.type === "text"
|
|
485
|
+
? { type: "input_text", text: p.text }
|
|
486
|
+
: { type: "input_image", image_url: `data:${p.mediaType};base64,${p.data}` }),
|
|
487
|
+
});
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
input.push({ role: m.role, content: m.content });
|
|
491
|
+
}
|
|
492
|
+
const payload: any = {
|
|
493
|
+
model: opts.model, input, stream: true, max_output_tokens: opts.maxTokens,
|
|
494
|
+
};
|
|
495
|
+
if (instructions) payload.instructions = instructions;
|
|
496
|
+
if (opts.temperature != null) payload.temperature = opts.temperature;
|
|
497
|
+
if (tools.length)
|
|
498
|
+
payload.tools = tools.map((t) => ({
|
|
499
|
+
type: "function", name: t.name, description: t.description,
|
|
500
|
+
parameters: t.parameters, strict: false,
|
|
501
|
+
}));
|
|
502
|
+
|
|
503
|
+
const res = await postJson(`${this.baseUrl}/responses`, this.headers(), payload, opts.signal);
|
|
504
|
+
const calls = new Map<string, { id: string; name: string; args: string }>();
|
|
505
|
+
for await (const data of sseLines(res)) {
|
|
506
|
+
const obj = safeParse(data);
|
|
507
|
+
if (!obj) continue;
|
|
508
|
+
const type = obj.type ?? "";
|
|
509
|
+
if (type === "response.output_text.delta") yield { textDelta: obj.delta };
|
|
510
|
+
else if (type === "response.reasoning_summary_text.delta") yield { thinkingDelta: obj.delta };
|
|
511
|
+
else if (type === "response.function_call_arguments.delta") {
|
|
512
|
+
const key = String(obj.item_id ?? obj.output_index ?? 0);
|
|
513
|
+
const cur = calls.get(key) ?? { id: obj.item_id ?? key, name: obj.name ?? "", args: "" };
|
|
514
|
+
cur.args += obj.delta ?? "";
|
|
515
|
+
if (obj.name) cur.name = obj.name;
|
|
516
|
+
calls.set(key, cur);
|
|
517
|
+
} else if (type === "response.completed" || type === "response.response.completed") {
|
|
518
|
+
const out = obj.response?.output ?? [];
|
|
519
|
+
const toolCalls: ToolCall[] = [];
|
|
520
|
+
for (const item of out) {
|
|
521
|
+
if (item.type === "function_call") {
|
|
522
|
+
let args: Record<string, unknown> = {};
|
|
523
|
+
try { args = item.arguments ? JSON.parse(item.arguments) : {}; } catch { args = { _raw: item.arguments }; }
|
|
524
|
+
toolCalls.push({ id: item.call_id ?? item.id, name: item.name, arguments: args });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (toolCalls.length) yield { toolCalls };
|
|
528
|
+
const u = obj.response?.usage;
|
|
529
|
+
if (u) yield { usage: { prompt: u.input_tokens ?? 0, completion: u.output_tokens ?? 0 } };
|
|
530
|
+
} else if (type === "response.failed" || type === "error") {
|
|
531
|
+
yield { error: obj.response?.error?.message ?? obj.error?.message ?? "responses stream error" };
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ---------- Gemini (API key + cloudcode-pa OAuth) ----------
|
|
538
|
+
|
|
539
|
+
export class GeminiClient implements ChatClient {
|
|
540
|
+
cloudcode = false;
|
|
541
|
+
private project: string | null = null;
|
|
542
|
+
|
|
543
|
+
constructor(
|
|
544
|
+
private baseUrl: string,
|
|
545
|
+
private apiKey?: string,
|
|
546
|
+
private authToken?: string,
|
|
547
|
+
private extraHeaders?: Record<string, string>,
|
|
548
|
+
) {
|
|
549
|
+
this.cloudcode = baseUrl.includes("cloudcode-pa");
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
private headers(): Record<string, string> {
|
|
553
|
+
const auth: Record<string, string> = this.authToken
|
|
554
|
+
? { authorization: `Bearer ${this.authToken}` }
|
|
555
|
+
: { "x-goog-api-key": this.apiKey ?? "" };
|
|
556
|
+
return { ...auth, ...(this.extraHeaders ?? {}) };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
private async resolveProject(): Promise<string> {
|
|
560
|
+
if (this.project !== null) return this.project;
|
|
561
|
+
try {
|
|
562
|
+
const res = await fetch(`${this.baseUrl}:loadCodeAssist`, {
|
|
563
|
+
method: "POST", headers: this.headers(),
|
|
564
|
+
body: JSON.stringify({ metadata: { pluginType: "gemini-vscode", ideType: "OTHER" } }),
|
|
565
|
+
});
|
|
566
|
+
const j: any = await res.json().catch(() => null);
|
|
567
|
+
this.project = j?.cloudaicompanionProject?.id ?? j?.currentTier?.project ?? null;
|
|
568
|
+
} catch {
|
|
569
|
+
this.project = null;
|
|
570
|
+
}
|
|
571
|
+
return this.project ?? "";
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
static contentsAndSystem(messages: Message[]): { contents: any[]; system: string } {
|
|
575
|
+
let system = "";
|
|
576
|
+
const contents: any[] = [];
|
|
577
|
+
for (const m of messages) {
|
|
578
|
+
if (m.role === "system") { system += (system ? "\n\n" : "") + textOf(m.content); continue; }
|
|
579
|
+
if (m.role === "tool") {
|
|
580
|
+
const part = { functionResponse: { name: m.name ?? "", response: { output: textOf(m.content) } } };
|
|
581
|
+
const last = contents[contents.length - 1];
|
|
582
|
+
if (last?.role === "user" && last.parts.every((p: any) => p.functionResponse)) last.parts.push(part);
|
|
583
|
+
else contents.push({ role: "user", parts: [part] });
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
if (m.role === "assistant") {
|
|
587
|
+
const parts: any[] = [];
|
|
588
|
+
const t = textOf(m.content);
|
|
589
|
+
if (t) parts.push({ text: t });
|
|
590
|
+
for (const tc of m.toolCalls ?? [])
|
|
591
|
+
parts.push({ functionCall: { name: tc.name, args: tc.arguments } });
|
|
592
|
+
if (parts.length) contents.push({ role: "model", parts });
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
if (typeof m.content !== "string") {
|
|
596
|
+
contents.push({
|
|
597
|
+
role: "user",
|
|
598
|
+
parts: m.content.map((p) => p.type === "text"
|
|
599
|
+
? { text: p.text }
|
|
600
|
+
: { inlineData: { mimeType: p.mediaType, data: p.data } }),
|
|
601
|
+
});
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
contents.push({ role: "user", parts: [{ text: m.content }] });
|
|
605
|
+
}
|
|
606
|
+
return { contents, system };
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async *streamChat(messages: Message[], tools: ToolSpec[], opts: StreamOpts): AsyncGenerator<StreamEvent> {
|
|
610
|
+
const { contents, system } = GeminiClient.contentsAndSystem(messages);
|
|
611
|
+
const body: any = {
|
|
612
|
+
contents,
|
|
613
|
+
generationConfig: { maxOutputTokens: opts.maxTokens },
|
|
614
|
+
};
|
|
615
|
+
if (opts.temperature != null) body.generationConfig.temperature = opts.temperature;
|
|
616
|
+
if (system) body.systemInstruction = { parts: [{ text: system }] };
|
|
617
|
+
if (tools.length)
|
|
618
|
+
body.tools = [{
|
|
619
|
+
functionDeclarations: tools.map((t) => ({
|
|
620
|
+
name: t.name, description: t.description, parameters: t.parameters,
|
|
621
|
+
})),
|
|
622
|
+
}];
|
|
623
|
+
|
|
624
|
+
let url: string;
|
|
625
|
+
let payload: any = body;
|
|
626
|
+
if (this.cloudcode) {
|
|
627
|
+
const project = await this.resolveProject();
|
|
628
|
+
payload = { model: opts.model, project, request: body };
|
|
629
|
+
url = `${this.baseUrl}:streamGenerateContent?alt=sse`;
|
|
630
|
+
} else {
|
|
631
|
+
url = `${this.baseUrl}/models/${opts.model}:streamGenerateContent?alt=sse&key=${this.apiKey ?? ""}`;
|
|
632
|
+
}
|
|
633
|
+
const res = await postJson(url, this.headers(), payload, opts.signal);
|
|
634
|
+
const calls: ToolCall[] = [];
|
|
635
|
+
for await (const data of sseLines(res)) {
|
|
636
|
+
const obj = safeParse(data);
|
|
637
|
+
if (!obj) continue;
|
|
638
|
+
const inner = obj.request?.response ? obj : { response: obj };
|
|
639
|
+
const resp = obj.response ?? obj;
|
|
640
|
+
for (const cand of resp.candidates ?? []) {
|
|
641
|
+
for (const part of cand.content?.parts ?? []) {
|
|
642
|
+
if (part.text) yield { textDelta: part.text };
|
|
643
|
+
if (part.functionCall)
|
|
644
|
+
calls.push({
|
|
645
|
+
id: `call_${calls.length}`, name: part.functionCall.name,
|
|
646
|
+
arguments: part.functionCall.args ?? {},
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
if (resp.usageMetadata)
|
|
651
|
+
yield { usage: {
|
|
652
|
+
prompt: resp.usageMetadata.promptTokenCount ?? 0,
|
|
653
|
+
completion: resp.usageMetadata.candidatesTokenCount ?? 0,
|
|
654
|
+
} };
|
|
655
|
+
if (obj.error) yield { error: obj.error.message ?? "gemini stream error" };
|
|
656
|
+
}
|
|
657
|
+
if (calls.length) yield { toolCalls: calls };
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// ---------- rate-limiting wrapper ----------
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Wraps a ChatClient with per-provider token-bucket rate limiting.
|
|
665
|
+
* Tokens are decremented on acquire (pre-request). No explicit release
|
|
666
|
+
* is needed after the request completes.
|
|
667
|
+
*/
|
|
668
|
+
export class RateLimitedChatClient implements ChatClient {
|
|
669
|
+
private readonly limiter: TokenBucketRateLimiter;
|
|
670
|
+
|
|
671
|
+
constructor(
|
|
672
|
+
private readonly inner: ChatClient,
|
|
673
|
+
private readonly providerId: string,
|
|
674
|
+
) {
|
|
675
|
+
const config = PROVIDER_RATE_LIMITS[providerId];
|
|
676
|
+
const registry = RateLimiterRegistry.get();
|
|
677
|
+
this.limiter = registry.register(providerId, config ?? {});
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async *streamChat(messages: Message[], tools: ToolSpec[], opts: StreamOpts): AsyncGenerator<StreamEvent> {
|
|
681
|
+
const result = this.limiter.tryAcquire();
|
|
682
|
+
if (!result.allowed) {
|
|
683
|
+
// Wait for a token to become available, then retry once
|
|
684
|
+
await new Promise((resolve) => setTimeout(resolve, result.waitMs));
|
|
685
|
+
const retry = this.limiter.tryAcquire();
|
|
686
|
+
if (!retry.allowed) {
|
|
687
|
+
yield { error: `Rate limit exceeded for ${this.providerId}. Retry after ${Math.round(retry.waitMs / 1000)}s` };
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
yield *this.inner.streamChat(messages, tools, opts);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// ---------- factory ----------
|
|
696
|
+
|
|
697
|
+
export function makeClient(
|
|
698
|
+
format: string, baseUrl: string,
|
|
699
|
+
opts: { apiKey?: string; authToken?: string; extraHeaders?: Record<string, string> },
|
|
700
|
+
providerId?: string,
|
|
701
|
+
): ChatClient {
|
|
702
|
+
const inner: ChatClient = (() => {
|
|
703
|
+
switch (format) {
|
|
704
|
+
case "claude":
|
|
705
|
+
return new AnthropicClient(baseUrl, opts.apiKey, opts.authToken, opts.extraHeaders);
|
|
706
|
+
case "openai-responses":
|
|
707
|
+
return new OpenAIResponsesClient(baseUrl, opts.apiKey, opts.authToken, opts.extraHeaders);
|
|
708
|
+
case "gemini":
|
|
709
|
+
case "gemini-oauth":
|
|
710
|
+
return new GeminiClient(baseUrl, opts.apiKey, opts.authToken, opts.extraHeaders);
|
|
711
|
+
default:
|
|
712
|
+
return new OpenAIChatClient(baseUrl, opts.apiKey ?? opts.authToken, opts.extraHeaders);
|
|
713
|
+
}
|
|
714
|
+
})();
|
|
715
|
+
|
|
716
|
+
// Wrap with rate limiting when a provider ID is known
|
|
717
|
+
if (providerId && providerId !== GOATED_FLASH_ID) {
|
|
718
|
+
return new RateLimitedChatClient(inner, providerId);
|
|
719
|
+
}
|
|
720
|
+
return inner;
|
|
721
|
+
}
|