@foldrun/core 13.1.0 → 14.0.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/dist/src/model-supply.d.ts +1 -1
- package/dist/src/model-supply.js +25 -10
- package/dist/src/starter.js +3 -1
- package/dist/src/translator.d.ts +22 -2
- package/dist/src/translator.js +49 -8
- package/package.json +1 -1
- package/src/model-supply.ts +26 -11
- package/src/starter.ts +3 -1
- package/src/translator.ts +51 -9
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type WireFormat } from "./providers.ts";
|
|
2
|
-
export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "
|
|
2
|
+
export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "deepseek" | "moonshot";
|
|
3
3
|
export interface SupplyProvider {
|
|
4
4
|
name: SupplyProviderName;
|
|
5
5
|
/** The preset the step's provider block is built from (providers.ts). */
|
package/dist/src/model-supply.js
CHANGED
|
@@ -26,15 +26,6 @@ export const SUPPLY_PROVIDERS = {
|
|
|
26
26
|
{ method: "GET", path: "/v1/models" },
|
|
27
27
|
],
|
|
28
28
|
},
|
|
29
|
-
openrouter: {
|
|
30
|
-
name: "openrouter",
|
|
31
|
-
preset: "openrouter",
|
|
32
|
-
format: "anthropic",
|
|
33
|
-
host: "openrouter.ai",
|
|
34
|
-
auth: "bearer",
|
|
35
|
-
metered: ["/api/v1/messages"],
|
|
36
|
-
free: [{ method: "GET", path: "/api/v1/models" }],
|
|
37
|
-
},
|
|
38
29
|
openai: {
|
|
39
30
|
name: "openai",
|
|
40
31
|
preset: "openai",
|
|
@@ -53,6 +44,29 @@ export const SUPPLY_PROVIDERS = {
|
|
|
53
44
|
metered: ["/v1beta/openai/chat/completions"],
|
|
54
45
|
free: [{ method: "GET", path: "/v1beta/openai/models" }],
|
|
55
46
|
},
|
|
47
|
+
// DeepSeek and Moonshot (owner, 3 Nov 2026: directly, not through
|
|
48
|
+
// OpenRouter, whose price depends on which host it routes a call to).
|
|
49
|
+
// Both speak Anthropic's Messages API at /anthropic/v1/messages and report
|
|
50
|
+
// usage the same way; neither prices a provider-run tool we allow
|
|
51
|
+
// (DeepSeek's web search is a typed tool, refused like Anthropic's).
|
|
52
|
+
deepseek: {
|
|
53
|
+
name: "deepseek",
|
|
54
|
+
preset: "deepseek",
|
|
55
|
+
format: "anthropic",
|
|
56
|
+
host: "api.deepseek.com",
|
|
57
|
+
auth: "x-api-key",
|
|
58
|
+
metered: ["/anthropic/v1/messages"],
|
|
59
|
+
free: [],
|
|
60
|
+
},
|
|
61
|
+
moonshot: {
|
|
62
|
+
name: "moonshot",
|
|
63
|
+
preset: "moonshot",
|
|
64
|
+
format: "anthropic",
|
|
65
|
+
host: "api.moonshot.ai",
|
|
66
|
+
auth: "bearer",
|
|
67
|
+
metered: ["/anthropic/v1/messages"],
|
|
68
|
+
free: [],
|
|
69
|
+
},
|
|
56
70
|
};
|
|
57
71
|
export const SUPPLY_PROVIDER_NAMES = Object.keys(SUPPLY_PROVIDERS);
|
|
58
72
|
/** How each reads to a person: on a step's credential line, in Settings. */
|
|
@@ -60,7 +74,8 @@ export const SUPPLY_TITLES = {
|
|
|
60
74
|
anthropic: "Anthropic",
|
|
61
75
|
openai: "OpenAI",
|
|
62
76
|
gemini: "Google Gemini",
|
|
63
|
-
|
|
77
|
+
deepseek: "DeepSeek",
|
|
78
|
+
moonshot: "Moonshot Kimi",
|
|
64
79
|
};
|
|
65
80
|
export function isSupplyProvider(name) {
|
|
66
81
|
return typeof name === "string" && Object.hasOwn(SUPPLY_PROVIDERS, name);
|
package/dist/src/starter.js
CHANGED
|
@@ -42,7 +42,9 @@ foldrun_version: "0.1"
|
|
|
42
42
|
#
|
|
43
43
|
# Your own model key needs no block: Settings → Model provider, or
|
|
44
44
|
# \`foldrun account model set anthropic --key …\` (an API key, not a login).
|
|
45
|
-
#
|
|
45
|
+
# On foldrun's own platform you can run on foldrun's models instead, billed
|
|
46
|
+
# in credits: \`foldrun account model use foldrun --provider anthropic\`.
|
|
47
|
+
# A provider: block here or lower wins over either.
|
|
46
48
|
#
|
|
47
49
|
# provider:
|
|
48
50
|
# base_url: https://openrouter.ai/api
|
package/dist/src/translator.d.ts
CHANGED
|
@@ -91,6 +91,8 @@ export declare function toChatCompletions(req: Json, opts: {
|
|
|
91
91
|
cacheKey?: string;
|
|
92
92
|
/** Merged in last, so the file wins over the translation. */
|
|
93
93
|
params?: Record<string, unknown>;
|
|
94
|
+
/** What the provider attached to earlier tool calls, to send back. */
|
|
95
|
+
extras?: ToolCallExtras;
|
|
94
96
|
}, drop?: Dropped): Json;
|
|
95
97
|
/**
|
|
96
98
|
* An Anthropic Messages request as a Responses request. Pure.
|
|
@@ -109,7 +111,7 @@ export declare function toResponses(req: Json, opts: {
|
|
|
109
111
|
params?: Record<string, unknown>;
|
|
110
112
|
}, drop?: Dropped): Json;
|
|
111
113
|
/** A finished Chat Completion as an Anthropic message. Pure. */
|
|
112
|
-
export declare function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown): Json;
|
|
114
|
+
export declare function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown, extras?: ToolCallExtras): Json;
|
|
113
115
|
/**
|
|
114
116
|
* The streaming half: Chat-Completions chunks in, Anthropic SSE events out.
|
|
115
117
|
* A state machine because the two streams disagree about structure — one
|
|
@@ -117,6 +119,23 @@ export declare function fromChatCompletion(res: Json, requestedModel: string, st
|
|
|
117
119
|
* stops — and a tool call's arguments arrive as fragments that the other
|
|
118
120
|
* side wants as `input_json_delta`s inside one open block.
|
|
119
121
|
*/
|
|
122
|
+
/**
|
|
123
|
+
* What a provider attached to a tool call that must come back with it.
|
|
124
|
+
* Gemini 3 and later put a thought signature on each tool call
|
|
125
|
+
* (`extra_content.google.thought_signature`) and refuse the next turn when
|
|
126
|
+
* it is missing; Claude's transcript has nowhere to keep it, so the
|
|
127
|
+
* translator — one per step, or per host call — remembers it by the call's
|
|
128
|
+
* id and puts it back when that call is sent again. Bounded: a step that
|
|
129
|
+
* makes more calls than this forgets the oldest.
|
|
130
|
+
*/
|
|
131
|
+
export declare class ToolCallExtras {
|
|
132
|
+
private byId;
|
|
133
|
+
private readonly max;
|
|
134
|
+
constructor(max?: number);
|
|
135
|
+
keep(id: string, extra: unknown): void;
|
|
136
|
+
get(id: string): Json | undefined;
|
|
137
|
+
get size(): number;
|
|
138
|
+
}
|
|
120
139
|
export declare class StreamTranslator {
|
|
121
140
|
private started;
|
|
122
141
|
private nextIndex;
|
|
@@ -129,7 +148,8 @@ export declare class StreamTranslator {
|
|
|
129
148
|
private id;
|
|
130
149
|
private readonly model;
|
|
131
150
|
private readonly stops;
|
|
132
|
-
|
|
151
|
+
private readonly extras?;
|
|
152
|
+
constructor(model: string, stopSequences?: unknown, extras?: ToolCallExtras);
|
|
133
153
|
private event;
|
|
134
154
|
private start;
|
|
135
155
|
private closeText;
|
package/dist/src/translator.js
CHANGED
|
@@ -137,10 +137,12 @@ export function toChatCompletions(req, opts, drop = dropped()) {
|
|
|
137
137
|
const toolCalls = [];
|
|
138
138
|
for (const b of Array.isArray(content) ? content : []) {
|
|
139
139
|
if (b.type === "tool_use") {
|
|
140
|
+
const extra = opts.extras?.get(String(b.id));
|
|
140
141
|
toolCalls.push({
|
|
141
142
|
id: String(b.id),
|
|
142
143
|
type: "function",
|
|
143
144
|
function: { name: String(b.name), arguments: JSON.stringify(b.input ?? {}) },
|
|
145
|
+
...(extra ? { extra_content: extra } : {}),
|
|
144
146
|
});
|
|
145
147
|
}
|
|
146
148
|
else if (b.type === "thinking" || b.type === "redacted_thinking") {
|
|
@@ -474,7 +476,7 @@ function parseArgs(raw) {
|
|
|
474
476
|
}
|
|
475
477
|
}
|
|
476
478
|
/** A finished Chat Completion as an Anthropic message. Pure. */
|
|
477
|
-
export function fromChatCompletion(res, requestedModel, stopSequences) {
|
|
479
|
+
export function fromChatCompletion(res, requestedModel, stopSequences, extras) {
|
|
478
480
|
const choice = (res.choices ?? [])[0] ?? {};
|
|
479
481
|
const msg = choice.message ?? {};
|
|
480
482
|
const content = [];
|
|
@@ -483,9 +485,11 @@ export function fromChatCompletion(res, requestedModel, stopSequences) {
|
|
|
483
485
|
content.push({ type: "text", text });
|
|
484
486
|
for (const tc of (Array.isArray(msg.tool_calls) ? msg.tool_calls : [])) {
|
|
485
487
|
const fn = tc.function ?? {};
|
|
488
|
+
const id = String(tc.id ?? `call_${crypto.randomBytes(6).toString("hex")}`);
|
|
489
|
+
extras?.keep(id, tc.extra_content);
|
|
486
490
|
content.push({
|
|
487
491
|
type: "tool_use",
|
|
488
|
-
id
|
|
492
|
+
id,
|
|
489
493
|
name: String(fn.name ?? ""),
|
|
490
494
|
input: parseArgs(fn.arguments),
|
|
491
495
|
});
|
|
@@ -510,6 +514,37 @@ export function fromChatCompletion(res, requestedModel, stopSequences) {
|
|
|
510
514
|
* stops — and a tool call's arguments arrive as fragments that the other
|
|
511
515
|
* side wants as `input_json_delta`s inside one open block.
|
|
512
516
|
*/
|
|
517
|
+
/**
|
|
518
|
+
* What a provider attached to a tool call that must come back with it.
|
|
519
|
+
* Gemini 3 and later put a thought signature on each tool call
|
|
520
|
+
* (`extra_content.google.thought_signature`) and refuse the next turn when
|
|
521
|
+
* it is missing; Claude's transcript has nowhere to keep it, so the
|
|
522
|
+
* translator — one per step, or per host call — remembers it by the call's
|
|
523
|
+
* id and puts it back when that call is sent again. Bounded: a step that
|
|
524
|
+
* makes more calls than this forgets the oldest.
|
|
525
|
+
*/
|
|
526
|
+
export class ToolCallExtras {
|
|
527
|
+
byId = new Map();
|
|
528
|
+
max;
|
|
529
|
+
constructor(max = 5000) {
|
|
530
|
+
this.max = max;
|
|
531
|
+
}
|
|
532
|
+
keep(id, extra) {
|
|
533
|
+
if (!id || !extra || typeof extra !== "object" || Array.isArray(extra))
|
|
534
|
+
return;
|
|
535
|
+
const prev = this.byId.get(id);
|
|
536
|
+
this.byId.delete(id);
|
|
537
|
+
this.byId.set(id, prev ? { ...prev, ...extra } : extra);
|
|
538
|
+
while (this.byId.size > this.max)
|
|
539
|
+
this.byId.delete(this.byId.keys().next().value);
|
|
540
|
+
}
|
|
541
|
+
get(id) {
|
|
542
|
+
return this.byId.get(id);
|
|
543
|
+
}
|
|
544
|
+
get size() {
|
|
545
|
+
return this.byId.size;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
513
548
|
export class StreamTranslator {
|
|
514
549
|
started = false;
|
|
515
550
|
nextIndex = 0;
|
|
@@ -522,9 +557,11 @@ export class StreamTranslator {
|
|
|
522
557
|
id = `msg_${crypto.randomBytes(8).toString("hex")}`;
|
|
523
558
|
model;
|
|
524
559
|
stops;
|
|
525
|
-
|
|
560
|
+
extras;
|
|
561
|
+
constructor(model, stopSequences, extras) {
|
|
526
562
|
this.model = model;
|
|
527
563
|
this.stops = stopList(stopSequences);
|
|
564
|
+
this.extras = extras;
|
|
528
565
|
}
|
|
529
566
|
event(name, data) {
|
|
530
567
|
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
@@ -595,19 +632,20 @@ export class StreamTranslator {
|
|
|
595
632
|
// A new call: text stops here (a block is one thing), the tool
|
|
596
633
|
// block opens with the id and name the first fragment carries.
|
|
597
634
|
out.push(...this.closeText());
|
|
598
|
-
entry = { block: this.nextIndex++, argsSeen: false };
|
|
635
|
+
entry = { block: this.nextIndex++, argsSeen: false, id: String(tc.id ?? `call_${crypto.randomBytes(6).toString("hex")}`) };
|
|
599
636
|
this.tools.set(idx, entry);
|
|
600
637
|
out.push(this.event("content_block_start", {
|
|
601
638
|
type: "content_block_start",
|
|
602
639
|
index: entry.block,
|
|
603
640
|
content_block: {
|
|
604
641
|
type: "tool_use",
|
|
605
|
-
id:
|
|
642
|
+
id: entry.id,
|
|
606
643
|
name: String(fn.name ?? ""),
|
|
607
644
|
input: {},
|
|
608
645
|
},
|
|
609
646
|
}));
|
|
610
647
|
}
|
|
648
|
+
this.extras?.keep(entry.id, tc.extra_content);
|
|
611
649
|
const args = typeof fn.arguments === "string" ? fn.arguments : "";
|
|
612
650
|
if (args) {
|
|
613
651
|
entry.argsSeen = true;
|
|
@@ -875,6 +913,9 @@ export async function startTranslator(spec) {
|
|
|
875
913
|
const log = [];
|
|
876
914
|
const base = trimSlashes(spec.upstreamBase);
|
|
877
915
|
const label = spec.label ?? base;
|
|
916
|
+
// One per translator (a step, or one host call): what the provider put on
|
|
917
|
+
// tool calls that must come back with them (Gemini's thought signatures).
|
|
918
|
+
const extras = new ToolCallExtras();
|
|
878
919
|
const server = http.createServer(async (req, res) => {
|
|
879
920
|
const started = Date.now();
|
|
880
921
|
const send = (status, body, type = "application/json") => {
|
|
@@ -916,7 +957,7 @@ export async function startTranslator(spec) {
|
|
|
916
957
|
const responses = spec.wire === "responses";
|
|
917
958
|
const outbound = responses
|
|
918
959
|
? toResponses(body, { reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream }, drop)
|
|
919
|
-
: toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream }, drop);
|
|
960
|
+
: toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, extras }, drop);
|
|
920
961
|
for (const line of drop.lines())
|
|
921
962
|
if (!log.includes(line))
|
|
922
963
|
log.push(line);
|
|
@@ -978,10 +1019,10 @@ export async function startTranslator(spec) {
|
|
|
978
1019
|
return send(502, errorBody(502, `translator: ${label} answered with something that is not JSON`));
|
|
979
1020
|
}
|
|
980
1021
|
log.push(`POST ${label} → 200 (${Date.now() - started}ms, ${model})`);
|
|
981
|
-
return send(200, JSON.stringify(responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences)));
|
|
1022
|
+
return send(200, JSON.stringify(responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences, extras)));
|
|
982
1023
|
}
|
|
983
1024
|
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
|
|
984
|
-
const machine = responses ? new ResponsesStreamTranslator(model) : new StreamTranslator(model, body.stop_sequences);
|
|
1025
|
+
const machine = responses ? new ResponsesStreamTranslator(model) : new StreamTranslator(model, body.stop_sequences, extras);
|
|
985
1026
|
const reader = upstream.body?.getReader();
|
|
986
1027
|
if (!reader) {
|
|
987
1028
|
for (const e of machine.finishStream())
|
package/package.json
CHANGED
package/src/model-supply.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import { providerPreset, type WireFormat } from "./providers.ts";
|
|
17
17
|
|
|
18
|
-
export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "
|
|
18
|
+
export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "deepseek" | "moonshot";
|
|
19
19
|
|
|
20
20
|
export interface SupplyProvider {
|
|
21
21
|
name: SupplyProviderName;
|
|
@@ -48,15 +48,6 @@ export const SUPPLY_PROVIDERS: Record<SupplyProviderName, SupplyProvider> = {
|
|
|
48
48
|
{ method: "GET", path: "/v1/models" },
|
|
49
49
|
],
|
|
50
50
|
},
|
|
51
|
-
openrouter: {
|
|
52
|
-
name: "openrouter",
|
|
53
|
-
preset: "openrouter",
|
|
54
|
-
format: "anthropic",
|
|
55
|
-
host: "openrouter.ai",
|
|
56
|
-
auth: "bearer",
|
|
57
|
-
metered: ["/api/v1/messages"],
|
|
58
|
-
free: [{ method: "GET", path: "/api/v1/models" }],
|
|
59
|
-
},
|
|
60
51
|
openai: {
|
|
61
52
|
name: "openai",
|
|
62
53
|
preset: "openai",
|
|
@@ -75,6 +66,29 @@ export const SUPPLY_PROVIDERS: Record<SupplyProviderName, SupplyProvider> = {
|
|
|
75
66
|
metered: ["/v1beta/openai/chat/completions"],
|
|
76
67
|
free: [{ method: "GET", path: "/v1beta/openai/models" }],
|
|
77
68
|
},
|
|
69
|
+
// DeepSeek and Moonshot (owner, 3 Nov 2026: directly, not through
|
|
70
|
+
// OpenRouter, whose price depends on which host it routes a call to).
|
|
71
|
+
// Both speak Anthropic's Messages API at /anthropic/v1/messages and report
|
|
72
|
+
// usage the same way; neither prices a provider-run tool we allow
|
|
73
|
+
// (DeepSeek's web search is a typed tool, refused like Anthropic's).
|
|
74
|
+
deepseek: {
|
|
75
|
+
name: "deepseek",
|
|
76
|
+
preset: "deepseek",
|
|
77
|
+
format: "anthropic",
|
|
78
|
+
host: "api.deepseek.com",
|
|
79
|
+
auth: "x-api-key",
|
|
80
|
+
metered: ["/anthropic/v1/messages"],
|
|
81
|
+
free: [],
|
|
82
|
+
},
|
|
83
|
+
moonshot: {
|
|
84
|
+
name: "moonshot",
|
|
85
|
+
preset: "moonshot",
|
|
86
|
+
format: "anthropic",
|
|
87
|
+
host: "api.moonshot.ai",
|
|
88
|
+
auth: "bearer",
|
|
89
|
+
metered: ["/anthropic/v1/messages"],
|
|
90
|
+
free: [],
|
|
91
|
+
},
|
|
78
92
|
};
|
|
79
93
|
|
|
80
94
|
export const SUPPLY_PROVIDER_NAMES = Object.keys(SUPPLY_PROVIDERS) as SupplyProviderName[];
|
|
@@ -84,7 +98,8 @@ export const SUPPLY_TITLES: Record<SupplyProviderName, string> = {
|
|
|
84
98
|
anthropic: "Anthropic",
|
|
85
99
|
openai: "OpenAI",
|
|
86
100
|
gemini: "Google Gemini",
|
|
87
|
-
|
|
101
|
+
deepseek: "DeepSeek",
|
|
102
|
+
moonshot: "Moonshot Kimi",
|
|
88
103
|
};
|
|
89
104
|
|
|
90
105
|
export function isSupplyProvider(name: unknown): name is SupplyProviderName {
|
package/src/starter.ts
CHANGED
|
@@ -49,7 +49,9 @@ foldrun_version: "0.1"
|
|
|
49
49
|
#
|
|
50
50
|
# Your own model key needs no block: Settings → Model provider, or
|
|
51
51
|
# \`foldrun account model set anthropic --key …\` (an API key, not a login).
|
|
52
|
-
#
|
|
52
|
+
# On foldrun's own platform you can run on foldrun's models instead, billed
|
|
53
|
+
# in credits: \`foldrun account model use foldrun --provider anthropic\`.
|
|
54
|
+
# A provider: block here or lower wins over either.
|
|
53
55
|
#
|
|
54
56
|
# provider:
|
|
55
57
|
# base_url: https://openrouter.ai/api
|
package/src/translator.ts
CHANGED
|
@@ -200,6 +200,8 @@ export function toChatCompletions(
|
|
|
200
200
|
cacheKey?: string;
|
|
201
201
|
/** Merged in last, so the file wins over the translation. */
|
|
202
202
|
params?: Record<string, unknown>;
|
|
203
|
+
/** What the provider attached to earlier tool calls, to send back. */
|
|
204
|
+
extras?: ToolCallExtras;
|
|
203
205
|
},
|
|
204
206
|
drop: Dropped = dropped(),
|
|
205
207
|
): Json {
|
|
@@ -217,10 +219,12 @@ export function toChatCompletions(
|
|
|
217
219
|
const toolCalls: Json[] = [];
|
|
218
220
|
for (const b of Array.isArray(content) ? (content as Json[]) : []) {
|
|
219
221
|
if (b.type === "tool_use") {
|
|
222
|
+
const extra = opts.extras?.get(String(b.id));
|
|
220
223
|
toolCalls.push({
|
|
221
224
|
id: String(b.id),
|
|
222
225
|
type: "function",
|
|
223
226
|
function: { name: String(b.name), arguments: JSON.stringify(b.input ?? {}) },
|
|
227
|
+
...(extra ? { extra_content: extra } : {}),
|
|
224
228
|
});
|
|
225
229
|
} else if (b.type === "thinking" || b.type === "redacted_thinking") {
|
|
226
230
|
drop.add("thinking blocks in the transcript");
|
|
@@ -514,7 +518,7 @@ function parseArgs(raw: unknown): unknown {
|
|
|
514
518
|
}
|
|
515
519
|
|
|
516
520
|
/** A finished Chat Completion as an Anthropic message. Pure. */
|
|
517
|
-
export function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown): Json {
|
|
521
|
+
export function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown, extras?: ToolCallExtras): Json {
|
|
518
522
|
const choice = ((res.choices as Json[] | undefined) ?? [])[0] ?? {};
|
|
519
523
|
const msg = (choice.message as Json | undefined) ?? {};
|
|
520
524
|
const content: Json[] = [];
|
|
@@ -522,9 +526,11 @@ export function fromChatCompletion(res: Json, requestedModel: string, stopSequen
|
|
|
522
526
|
if (text) content.push({ type: "text", text });
|
|
523
527
|
for (const tc of (Array.isArray(msg.tool_calls) ? msg.tool_calls : []) as Json[]) {
|
|
524
528
|
const fn = (tc.function as Json | undefined) ?? {};
|
|
529
|
+
const id = String(tc.id ?? `call_${crypto.randomBytes(6).toString("hex")}`);
|
|
530
|
+
extras?.keep(id, tc.extra_content);
|
|
525
531
|
content.push({
|
|
526
532
|
type: "tool_use",
|
|
527
|
-
id
|
|
533
|
+
id,
|
|
528
534
|
name: String(fn.name ?? ""),
|
|
529
535
|
input: parseArgs(fn.arguments),
|
|
530
536
|
});
|
|
@@ -550,21 +556,53 @@ export function fromChatCompletion(res: Json, requestedModel: string, stopSequen
|
|
|
550
556
|
* stops — and a tool call's arguments arrive as fragments that the other
|
|
551
557
|
* side wants as `input_json_delta`s inside one open block.
|
|
552
558
|
*/
|
|
559
|
+
/**
|
|
560
|
+
* What a provider attached to a tool call that must come back with it.
|
|
561
|
+
* Gemini 3 and later put a thought signature on each tool call
|
|
562
|
+
* (`extra_content.google.thought_signature`) and refuse the next turn when
|
|
563
|
+
* it is missing; Claude's transcript has nowhere to keep it, so the
|
|
564
|
+
* translator — one per step, or per host call — remembers it by the call's
|
|
565
|
+
* id and puts it back when that call is sent again. Bounded: a step that
|
|
566
|
+
* makes more calls than this forgets the oldest.
|
|
567
|
+
*/
|
|
568
|
+
export class ToolCallExtras {
|
|
569
|
+
private byId = new Map<string, Json>();
|
|
570
|
+
private readonly max: number;
|
|
571
|
+
constructor(max = 5000) {
|
|
572
|
+
this.max = max;
|
|
573
|
+
}
|
|
574
|
+
keep(id: string, extra: unknown): void {
|
|
575
|
+
if (!id || !extra || typeof extra !== "object" || Array.isArray(extra)) return;
|
|
576
|
+
const prev = this.byId.get(id);
|
|
577
|
+
this.byId.delete(id);
|
|
578
|
+
this.byId.set(id, prev ? { ...prev, ...(extra as Json) } : (extra as Json));
|
|
579
|
+
while (this.byId.size > this.max) this.byId.delete(this.byId.keys().next().value as string);
|
|
580
|
+
}
|
|
581
|
+
get(id: string): Json | undefined {
|
|
582
|
+
return this.byId.get(id);
|
|
583
|
+
}
|
|
584
|
+
get size(): number {
|
|
585
|
+
return this.byId.size;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
553
589
|
export class StreamTranslator {
|
|
554
590
|
private started = false;
|
|
555
591
|
private nextIndex = 0;
|
|
556
592
|
private textIndex: number | null = null;
|
|
557
593
|
/** Chat-Completions tool index → Anthropic block index. */
|
|
558
|
-
private tools = new Map<number, { block: number; argsSeen: boolean }>();
|
|
594
|
+
private tools = new Map<number, { block: number; argsSeen: boolean; id: string }>();
|
|
559
595
|
/** The last choice's stop fields: finish_reason and any matched stop. */
|
|
560
596
|
private finish: Json = {};
|
|
561
597
|
private usage: { input: number; cached: number; output: number } | null = null;
|
|
562
598
|
private id = `msg_${crypto.randomBytes(8).toString("hex")}`;
|
|
563
599
|
private readonly model: string;
|
|
564
600
|
private readonly stops: string[];
|
|
565
|
-
|
|
601
|
+
private readonly extras?: ToolCallExtras;
|
|
602
|
+
constructor(model: string, stopSequences?: unknown, extras?: ToolCallExtras) {
|
|
566
603
|
this.model = model;
|
|
567
604
|
this.stops = stopList(stopSequences);
|
|
605
|
+
this.extras = extras;
|
|
568
606
|
}
|
|
569
607
|
|
|
570
608
|
private event(name: string, data: Json): string {
|
|
@@ -640,7 +678,7 @@ export class StreamTranslator {
|
|
|
640
678
|
// A new call: text stops here (a block is one thing), the tool
|
|
641
679
|
// block opens with the id and name the first fragment carries.
|
|
642
680
|
out.push(...this.closeText());
|
|
643
|
-
entry = { block: this.nextIndex++, argsSeen: false };
|
|
681
|
+
entry = { block: this.nextIndex++, argsSeen: false, id: String(tc.id ?? `call_${crypto.randomBytes(6).toString("hex")}`) };
|
|
644
682
|
this.tools.set(idx, entry);
|
|
645
683
|
out.push(
|
|
646
684
|
this.event("content_block_start", {
|
|
@@ -648,13 +686,14 @@ export class StreamTranslator {
|
|
|
648
686
|
index: entry.block,
|
|
649
687
|
content_block: {
|
|
650
688
|
type: "tool_use",
|
|
651
|
-
id:
|
|
689
|
+
id: entry.id,
|
|
652
690
|
name: String(fn.name ?? ""),
|
|
653
691
|
input: {},
|
|
654
692
|
},
|
|
655
693
|
}),
|
|
656
694
|
);
|
|
657
695
|
}
|
|
696
|
+
this.extras?.keep(entry.id, tc.extra_content);
|
|
658
697
|
const args = typeof fn.arguments === "string" ? fn.arguments : "";
|
|
659
698
|
if (args) {
|
|
660
699
|
entry.argsSeen = true;
|
|
@@ -929,6 +968,9 @@ export async function startTranslator(spec: TranslatorSpec): Promise<RunningTran
|
|
|
929
968
|
const log: string[] = [];
|
|
930
969
|
const base = trimSlashes(spec.upstreamBase);
|
|
931
970
|
const label = spec.label ?? base;
|
|
971
|
+
// One per translator (a step, or one host call): what the provider put on
|
|
972
|
+
// tool calls that must come back with them (Gemini's thought signatures).
|
|
973
|
+
const extras = new ToolCallExtras();
|
|
932
974
|
|
|
933
975
|
const server = http.createServer(async (req, res) => {
|
|
934
976
|
const started = Date.now();
|
|
@@ -972,7 +1014,7 @@ export async function startTranslator(spec: TranslatorSpec): Promise<RunningTran
|
|
|
972
1014
|
const responses = spec.wire === "responses";
|
|
973
1015
|
const outbound = responses
|
|
974
1016
|
? toResponses(body, { reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream }, drop)
|
|
975
|
-
: toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream }, drop);
|
|
1017
|
+
: toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, extras }, drop);
|
|
976
1018
|
for (const line of drop.lines()) if (!log.includes(line)) log.push(line);
|
|
977
1019
|
|
|
978
1020
|
let upstream: Response;
|
|
@@ -1035,11 +1077,11 @@ export async function startTranslator(spec: TranslatorSpec): Promise<RunningTran
|
|
|
1035
1077
|
return send(502, errorBody(502, `translator: ${label} answered with something that is not JSON`));
|
|
1036
1078
|
}
|
|
1037
1079
|
log.push(`POST ${label} → 200 (${Date.now() - started}ms, ${model})`);
|
|
1038
|
-
return send(200, JSON.stringify(responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences)));
|
|
1080
|
+
return send(200, JSON.stringify(responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences, extras)));
|
|
1039
1081
|
}
|
|
1040
1082
|
|
|
1041
1083
|
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
|
|
1042
|
-
const machine = responses ? new ResponsesStreamTranslator(model) : new StreamTranslator(model, body.stop_sequences);
|
|
1084
|
+
const machine = responses ? new ResponsesStreamTranslator(model) : new StreamTranslator(model, body.stop_sequences, extras);
|
|
1043
1085
|
const reader = upstream.body?.getReader();
|
|
1044
1086
|
if (!reader) {
|
|
1045
1087
|
for (const e of machine.finishStream()) res.write(e);
|